Exemplo n.º 1
0
static void check1d(const char* name, IntList x) {
  if (x.size() != 1) {
    std::ostringstream ss;
    ss << "max_pool1d() argument '" << name << "' should contain one int (got "
       << x.size() << ")";
    throw std::runtime_error(ss.str());
  }
}
Exemplo n.º 2
0
static std::vector<int64_t> defaultStrides(IntList sizes) {
  std::vector<int64_t> strides(sizes.size());
  int64_t stride = 1;
  for(size_t i = sizes.size(); i > 0; --i) {
    strides[i-1] = stride;
    stride *= sizes[i-1];
  }
  return strides;
}
Exemplo n.º 3
0
bool should_expand(const IntList &from_size, const IntList &to_size) {
  if(from_size.size() > to_size.size()) {
    return false;
  }
  for (auto from_dim_it = from_size.rbegin(); from_dim_it != from_size.rend(); ++from_dim_it) {
    for (auto to_dim_it = to_size.rbegin(); to_dim_it != to_size.rend(); ++to_dim_it) {
      if (*from_dim_it != 1 && *from_dim_it != *to_dim_it) {
        return false;
      }
    }
  }
  return true;
}
Exemplo n.º 4
0
void DefaultHttpHeader::set(const std::string& name, const IntList& values) {
    StringList list;
    for (size_t i = 0; i < values.size(); ++i) {
        list.push_back(Integer::toString(values[i]));
    }
    set(name, list);
}
Exemplo n.º 5
0
void checkSize(CheckedFrom c, const TensorGeometryArg& t, IntList sizes) {
  checkDim(c, t, sizes.size());
  if (!t->sizes().equals(sizes)) {
    std::ostringstream oss;
    oss << "Expected tensor of size " << sizes << ", but got tensor of size "
        << t->sizes() << " for " << t
        << " (while checking arguments for " << c << ")";
    throw std::runtime_error(oss.str());
  }
}
Exemplo n.º 6
0
  bool getVersion_(const String& version, MyriMatchVersion& myrimatch_version_i) const
  {
    // we expect three components
    IntList nums = ListUtils::create<Int>(ListUtils::create<String>(version, '.'));
    if (nums.size() != 3) return false;

    myrimatch_version_i.myrimatch_major = nums[0];
    myrimatch_version_i.myrimatch_minor = nums[1];
    myrimatch_version_i.myrimatch_patch = nums[2];
    return true;
  }
Exemplo n.º 7
0
static int64_t computeStorageSize(IntList sizes, IntList strides) {
  // size of the underlying storage is 1 bigger than the offset
  // of the last element according to stride
  int64_t size = 1;
  for(size_t i = 0; i < sizes.size(); i++) {
    if(sizes[i] == 0) {
      return 0;
    }
    size += strides[i]*(sizes[i]-1);
  }
  return size;
}
Exemplo n.º 8
0
std::vector<int64_t> conv_output_size(
    IntList input_size, IntList weight_size,
    IntList padding, IntList stride, IntList dilation)
{
  auto dim = input_size.size();
  std::vector<int64_t> output_size(dim);
  output_size[0] = input_size[input_batch_size_dim];
  output_size[1] = weight_size[weight_output_channels_dim];
  for (size_t d = 2; d < dim; ++d) {
    auto kernel = dilation[d - 2] * (weight_size[d] - 1) + 1;
    output_size[d] = (input_size[d] + (2 * padding[d - 2])
                        - kernel) / stride[d - 2] + 1;
  }
  return output_size;
}
Exemplo n.º 9
0
double
check_multiple( double * tgt, double * src, int & ind, IntList & nb, SeedList & seeds, double & tolerance, int & nx, int & ny ) {
    if ( nb.size() == 1 ) return nb.front();
    if ( nb.size() <  1 ) return 0.0; // dumb protection

    double diff, maxdiff = 0.0, res = 0.0;
    int i;
    IntList::iterator  it;
    SeedList::iterator sit;
    PointXY ptsit, pt = pointFromIndex( ind, nx );
    double distx, dist = FLT_MAX;

    /* maxdiff */
    for ( it = nb.begin(); it != nb.end(); it++ ) {
        if ( !get_seed( seeds, *it, sit ) ) continue;
        diff = fabs( src[ ind ] - src[ (*sit).index ] );
        if ( diff > maxdiff ) {
            maxdiff = diff;
            /* assign result to the steepest until and if it not assigned to closest over the tolerance */
            if ( dist == FLT_MAX )
                res = *it;
        }
        /* we assign to the closest centre which is above tolerance, if none than to maxdiff */
        if ( diff >= tolerance ) {
            ptsit = pointFromIndex( (*sit).index, nx );
            distx = distanceXY( pt, ptsit);
            if ( distx < dist ) {
                dist =  distx;
                res = * it;
            }
        }

    }
    /* assign all that need assignment to res, which has maxdiff */
    for ( it = nb.begin(); it != nb.end(); it++ ) {
        if ( *it == res ) continue;
        if ( !get_seed( seeds, *it, sit ) ) continue;
        if ( fabs( src[ ind ] - src[ (*sit).index ] ) >= tolerance ) continue;
        for ( i = 0; i < nx * ny; i++ )
            if ( tgt[ i ] == *it )
                tgt[ i ] = res;
        seeds.erase( sit );
    }
    return res;
}
Exemplo n.º 10
0
static bool compare(const IntList& flist, const std::list<int>& l)
{
    if (flist.size() == l.size())
    {
        IntList::ConstElementHandler h(flist.first());
        std::list<int>::const_iterator it = l.begin();

        bool equals = true;
        while (h.is_valid() && equals)
        {
            equals = *h == *it;
            ++h;
            ++it;
        }
        return equals;
    }
    else
    {
        return false;
    }
}
static PyObject * THPVariable_stride(PyObject* self, PyObject* args, PyObject* kwargs)
{
  HANDLE_TH_ERRORS
  static PythonArgParser parser({
    "stride(int64_t dim)",
    "stride()",
  });
  auto& self_ = reinterpret_cast<THPVariable*>(self)->cdata;
  ParsedArgs<3> parsed_args;
  auto r = parser.parse(args, kwargs, parsed_args);
  if (r.idx == 0) {
    return wrap(self_.stride(r.toInt64(0)));
  } else if (r.idx == 1) {
    // yes, this is called strides in ATen.
    IntList strides = self_.strides();
    // we can't do the normal wrapping here because IntList maps to both
    // torch.Size and tuple in python
    return THPUtils_packInt64Array(strides.size(), strides.data());
  }
  Py_RETURN_NONE;
  END_HANDLE_TH_ERRORS
}
Exemplo n.º 12
0
 int *flattenIVecList(int t, int vecDim, IntVecList* pintVecList)
 {
     int szvec = 0;
     int *array = NULL;
     // walk through the vector list and check few things then send the packed version
     int *p = NULL;
     if (NULL == pintVecList)
       return 0;
     for(int i=0; i<(int)pintVecList->size(); i++)
     {
         if(szvec == 0) {
             szvec = (int)((*pintVecList)[i]->size());
             p = array = new int[szvec * pintVecList->size()]; // we assume all vectors are the same size
         }
         else if(szvec != (*pintVecList)[i]->size()) {
             yyerror("Vector list has inconsistent vectors\n");
             continue;
         }
         IntList* pfl = (*pintVecList)[i];
         if (NULL!=pfl)
         {
         for(int j=0; j<(int)pfl->size(); j++)
             *p++ = (*pfl)[j];
         delete pfl;
           pfl = NULL;
         }
     }
     if(vecDim < 0)
         vecDim = (int)pintVecList->size();
     // we do the test here in any case : the previous loop needed to do some "delete" anyways
     if((szvec != vecDim) || (t != pintVecList->size()))
     {
         yyerror("Vector dimension in value assignment don't match the type\n");
         delete array;
         return NULL;
     }
     return array;
 }
Exemplo n.º 13
0
static void recursive_store(char* data, IntList sizes, IntList strides, int64_t dim,
                            ScalarType scalarType, int elementSize, PyObject* obj) {
  int64_t ndim = sizes.size();
  if (dim == ndim) {
    torch::utils::store_scalar(data, scalarType, obj);
    return;
  }

  auto n = sizes[dim];
  auto seq = THPObjectPtr(PySequence_Fast(obj, "not a sequence"));
  if (!seq) throw python_error();
  auto seq_size = PySequence_Fast_GET_SIZE(seq.get());
  if (seq_size != n) {
    throw ValueError("expected sequence of length %lld at dim %lld (got %lld)",
      (long long)n, (long long)dim, (long long)seq_size);
  }

  PyObject** items = PySequence_Fast_ITEMS(seq.get());
  for (int64_t i = 0; i < n; i++) {
    recursive_store(data, sizes, strides, dim + 1, scalarType, elementSize, items[i]);
    data += strides[dim] * elementSize;
  }
}
Exemplo n.º 14
0
// Given a list of lists of possible cage values:
//     [[1,2,3], [3,4,5]]
// Recursively generates tuples of combinations from each of the lists as
// follows:
//   [1,3]
//   [1,4]
//   [1,5]
//   [2,3]
//   [2,4]
// ... etc
// Each of these is checked against the target sum, and pushed into a result
// vector if they match.
// Note: The algorithm assumes that the list of possibles/candidates are
// ordered. This allows it to bail out early if it detects there's no point
// going further.
static void subsetSum(const std::vector<IntList> &possible_lists,
                      const std::size_t p_size, IntList &tuple,
                      unsigned tuple_sum, std::vector<IntList> &subsets,
                      const unsigned target_sum, unsigned list_idx) {
  for (unsigned p = list_idx; p < p_size; ++p) {
    for (auto &poss : possible_lists[p]) {
      // Optimization for small target sums: if the candidate is bigger than
      // the target itself then it can't be valid, neither can any candidate
      // after it (ordered).
      if (target_sum < static_cast<unsigned>(poss)) {
        break;
      }

      // Can't repeat a value inside a cage
      if (std::find(tuple.begin(), tuple.end(), poss) != tuple.end()) {
        continue;
      }

      // Pre-calculate the new tuple values to avoid spurious
      // insertions/deletions to the vector.
      const auto new_tuple_sum = tuple_sum + poss;
      const auto new_tuple_size = tuple.size() + 1;

      // If we've added too much then we can bail out (ordered).
      if (new_tuple_sum > target_sum) {
        break;
      }

      // If there are fewer spots left in the tuple than there are options for
      // the sum to reach the target, bail.
      // TODO: This could be more sophisticated (can't have more than one 1, so
      // it's more like the N-1 sum that it should be greater than.
      if ((p_size - new_tuple_size) > (target_sum - new_tuple_sum)) {
        break;
      }

      if (new_tuple_size == p_size) {
        // If we've reached our target size then we can stop searching other
        // possiblities from this list (ordered).
        if (new_tuple_sum == target_sum) {
          tuple.push_back(poss);
          subsets.push_back(tuple);
          tuple.pop_back();
          break;
        }

        // Else, move on to the next candidate in the list.
        continue;
      }

      tuple_sum += poss;
      tuple.push_back(poss);

      subsetSum(possible_lists, p_size, tuple, tuple_sum, subsets, target_sum,
                p + 1);

      tuple.pop_back();
      tuple_sum -= poss;
    }
  }
}
Exemplo n.º 15
0
  TEST_EQUAL(sv[2], " maybe")

  std::vector<double> dv = ListUtils::create<double>("1.2,3.5");
  TEST_EQUAL(dv.size(), 2)
  ABORT_IF(dv.size() != 2)
  TEST_EQUAL(dv[0], 1.2)
  TEST_EQUAL(dv[1], 3.5)

  std::vector<Int> iv = ListUtils::create<Int>("1,5");
  TEST_EQUAL(iv.size(),2)
  ABORT_IF(iv.size() != 2)
  TEST_EQUAL(iv[0], 1)
  TEST_EQUAL(iv[1], 5)

  IntList iv2 = ListUtils::create<Int>("2");
  TEST_EQUAL(iv2.size(),1)
  TEST_EQUAL(iv2[0],2)

  IntList iv3 = ListUtils::create<Int>("");
  TEST_EQUAL(iv3.size(),0)

  StringList sl1 = ListUtils::create<String>("test string,string2,last string");
  TEST_EQUAL(sl1.size(),3)
  ABORT_IF(sl1.size() != 3)
  TEST_EQUAL(sl1[0], "test string")
  TEST_EQUAL(sl1[1], "string2")
  TEST_EQUAL(sl1[2], "last string")

  StringList list = ListUtils::create<String>("yes,no");
  TEST_EQUAL(list.size(),2)
  ABORT_IF(list.size() != 2)
Exemplo n.º 16
0
	TEST_EQUAL(list[0],"a")
	TEST_EQUAL(list[1],"bb")
	TEST_EQUAL(list[2],"ccc")

	TEST_EQUAL(p2.getValue("stringlist2").valueType(), DataValue::STRING_LIST)
	list = p2.getValue("stringlist2");
	TEST_EQUAL(list.size(),0)

	TEST_EQUAL(p2.getValue("stringlist").valueType(), DataValue::STRING_LIST)
	list = p2.getValue("stringlist3");
	TEST_EQUAL(list.size(),1)
	TEST_EQUAL(list[0],"1")

	TEST_EQUAL(p2.getValue("intlist").valueType(), DataValue::INT_LIST)
	IntList intlist = p2.getValue("intlist");
	TEST_EQUAL(intlist.size(),3);
	TEST_EQUAL(intlist[0], 1)
	TEST_EQUAL(intlist[1], 22)
	TEST_EQUAL(intlist[2], 333)

	TEST_EQUAL(p2.getValue("intlist2").valueType(),DataValue::INT_LIST)
	intlist = p2.getValue("intlist2");
	TEST_EQUAL(intlist.size(),0)

	TEST_EQUAL(p2.getValue("intlist3").valueType(),DataValue::INT_LIST)
	intlist = p2.getValue("intlist3");
	TEST_EQUAL(intlist.size(),1)
	TEST_EQUAL(intlist[0],1)

	TEST_EQUAL(p2.getValue("doublelist").valueType(), DataValue::DOUBLE_LIST)
	DoubleList doublelist = p2.getValue("doublelist");
Exemplo n.º 17
0
/*----------------------------------------------------------------------- */
SEXP
watershed (SEXP x, SEXP _tolerance, SEXP _ext) {
    SEXP res;
    int im, i, j, nx, ny, nz, ext, nprotect = 0;
    double tolerance;

    nx = INTEGER ( GET_DIM(x) )[0];
    ny = INTEGER ( GET_DIM(x) )[1];
    nz = getNumberOfFrames(x,0);
    tolerance = REAL( _tolerance )[0];
    ext = INTEGER( _ext )[0];

    PROTECT ( res = Rf_duplicate(x) );
    nprotect++;
  
    int * index = new int[ nx * ny ];

    for ( im = 0; im < nz; im++ ) {

        double * src = &( REAL(x)[ im * nx * ny ] );
        double * tgt = &( REAL(res)[ im * nx * ny ] );

        /* generate pixel index and negate the image -- filling wells */
        for ( i = 0; i < nx * ny; i++ ) {
	  tgt[ i ] = -src[ i ];
	  index[ i ] = i;
        }
        /* from R includes R_ext/Utils.h */
        /* will resort tgt as well */
        rsort_with_index( tgt, index, nx * ny );
        /* reassign tgt as it was reset above but keep new index */
        for ( i = 0; i < nx * ny; i++ )
            tgt[ i ] = -src[ i ];

        SeedList seeds;  /* indexes of all seed starting points, i.e. lowest values */

        IntList  equals; /* queue of all pixels on the same gray level */
        IntList  nb;     /* seed values of assigned neighbours */
        int ind, indxy, nbseed, x, y, topseed = 0;
        IntList::iterator it;
        TheSeed newseed;
        PointXY pt;
        bool isin;
        /* loop through the sorted index */
        for ( i = 0; i < nx * ny && src[ index[i] ] > BG; ) {
            /* pool a queue of equally lowest values */
            ind = index[ i ];
            equals.push_back( ind );
            for ( i = i + 1; i < nx * ny; ) {
                if ( src[ index[i] ] != src[ ind ] ) break;
                equals.push_back( index[i] );
                i++;
            }
            while ( !equals.empty() ) {
                /* first check through all the pixels if we can assign them to
                 * existing objects, count checked and reset counter on each assigned
                 * -- exit when counter equals queue length */
                for ( j = 0; j < (int) equals.size(); ) {
		  if ((j%1000)==0) R_CheckUserInterrupt();
                    ind = equals.front();
                    equals.pop_front();
                    /* check neighbours:
                     * - if exists one, assign
                     * - if two or more check what should be combined and assign to the steepest
                     * - if none, push back */
                    /* reset j to 0 every time we assign another pixel to restart the loop */
                    nb.clear();
                    pt = pointFromIndex( ind, nx );
                    /* determine which neighbour we have, push them to nb */
                    for ( x = pt.x - ext; x <= pt.x + ext; x++ )
                        for ( y = pt.y - ext; y <= pt.y + ext; y++ ) {
                            if ( x < 0 || y < 0 || x >= nx || y >= ny || (x == pt.x && y == pt.y) ) continue;
                            indxy = x + y * nx;
                            nbseed = (int) tgt[ indxy ];
                            if ( nbseed < 1 ) continue;
                            isin = false;
                            for ( it = nb.begin(); it != nb.end() && !isin; it++ )
                                if ( nbseed == *it ) isin = true;
                            if ( !isin ) nb.push_back( nbseed );
                        }
                    if ( nb.size() == 0 ) {
                        /* push the pixel back and continue with the next one */
                        equals.push_back( ind );
                        j++;
                        continue;
                    }
                    tgt[ ind ] = check_multiple(tgt, src, ind, nb, seeds, tolerance, nx, ny );
                    /* we assigned the pixel, reset j to restart neighbours detection */
                    j = 0;
                }
                /* now we have assigned all that we could */
                if ( !equals.empty() ) {
                    /* create a new seed for one pixel only and go back to assigning neighbours */
                    topseed++;
                    newseed.index = equals.front();
                    newseed.seed = topseed;
                    equals.pop_front();
                    tgt[ newseed.index ] = topseed;
                    seeds.push_back( newseed );
                }
            } // assigning equals
        } // sorted index

        /* now we need to reassign indexes while some seeds could be removed */
        double * finseed = new double[ topseed ];
        for ( i = 0; i < topseed; i++ )
            finseed[ i ] = 0;
        i = 0;
        while ( !seeds.empty() ) {
            newseed = seeds.front();
            seeds.pop_front();
            finseed[ newseed.seed - 1 ] = i + 1;
            i++;
        }
        for ( i = 0; i < nx * ny; i++ ) {
            j = (int) tgt[ i ];
            if ( 0 < j && j <= topseed )
                tgt[ i ] = finseed[ j - 1 ];
        }
        delete[] finseed;

    } // loop through images

    delete[] index;

    UNPROTECT (nprotect);
    return res;
}