PyObject *computeTimeLagCov(PyArrayObject *i_data, int timeLag) { /* Output matrix: | * * * * * | | 0 * * * * | | 0 0 * * * | | 0 0 0 * * | | 0 0 0 0 * | */ int i, j, k, mCov, nCov, nData, mData; npy_intp dimCov[2]; double *rowCov, *colData1, *colData2, *colMean1, *colMean2; ticaC_numpyArrayDim dimData = NULL; PyObject *o_cov = NULL; PyArrayObject *cov = NULL; PyArrayObject *colMeanArray = NULL; dimData = PyArray_DIMS(i_data); dimCov[0] = dimData[1]; dimCov[1] = dimData[1]; mCov = dimCov[0]; nCov = dimCov[1]; nData = dimData[0]; mData = dimData[1]; o_cov = PyArray_SimpleNew(TICA_ARRAY_DIMENSION, dimCov, NPY_DOUBLE); cov = (PyArrayObject*)PyArray_FROM_OTF(o_cov, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (NULL == o_cov) { return NULL; } for (i = 0; i < mCov; i++) { rowCov = (double*)PyArray_GETPTR2(cov, i, i); for (j = i; j < nCov; j++, rowCov++) { colData1 = (double*)PyArray_GETPTR2(i_data, TICA_FIRST_ROW, i); colData2 = (double*)PyArray_GETPTR2(i_data, TICA_FIRST_ROW, j); colData2 += mData * timeLag; for (k = 0; k < nData - timeLag; k++, colData1 += mData, colData2 += mData) { *rowCov += (*colData1) * (*colData2); } } } o_cov = (PyObject*)cov; Py_INCREF(cov); return o_cov; }
static PyObject* calculate(const char sequence[], int s, PyObject* matrix, npy_intp m) { npy_intp n = s - m + 1; npy_intp i, j; char c; double score; int ok; PyObject* result; PyArrayObject* array; float* p; npy_intp shape = (npy_intp)n; float nan = 0.0; nan /= nan; if ((int)shape!=n) { PyErr_SetString(PyExc_ValueError, "integer overflow"); return NULL; } result = PyArray_SimpleNew(1, &shape, NPY_FLOAT32); if (!result) { PyErr_SetString(PyExc_MemoryError, "failed to create output data"); return NULL; } p = PyArray_DATA((PyArrayObject*)result); array = (PyArrayObject*)matrix; for (i = 0; i < n; i++) { score = 0.0; ok = 1; for (j = 0; j < m; j++) { c = sequence[i+j]; switch (c) { case 'A': case 'a': score += *((double*)PyArray_GETPTR2(array, j, 0)); break; case 'C': case 'c': score += *((double*)PyArray_GETPTR2(array, j, 1)); break; case 'G': case 'g': score += *((double*)PyArray_GETPTR2(array, j, 2)); break; case 'T': case 't': score += *((double*)PyArray_GETPTR2(array, j, 3)); break; default: ok = 0; } } if (ok) *p = (float)score; else *p = nan; p++; } return result; }
/*==========================================================================*/ PyObject *calculate(PyObject *self, PyObject *args) { long i, j; KD kd; int nReps=0, bPeriodic=0, bEwald=0; float fSoft; int nPos; PyObject *kdobj, *acc, *pot, *pos; PARTICLE *testParticles; PyArg_ParseTuple(args, "OOOOdi", &kdobj, &pos, &acc, &pot, &fSoft, &nPos); kd = PyCObject_AsVoidPtr(kdobj); if (kd == NULL) return NULL; testParticles = (PARTICLE *)malloc(nPos*sizeof(PARTICLE)); assert(testParticles != NULL); for (i=0; i< nPos; i++) { for (j=0; j < 3; j++) { testParticles[i].r[j] = (float)*((double *)PyArray_GETPTR2(pos, i, j)); testParticles[i].a[j] = 0; } testParticles[i].fMass = 0; testParticles[i].fPot = 0; testParticles[i].fSoft = fSoft; testParticles[i].iOrder = i; } Py_BEGIN_ALLOW_THREADS kdGravWalk(kd, nReps, bPeriodic && bEwald, testParticles, nPos); Py_END_ALLOW_THREADS for (i=0; i < nPos; i++) { PyArray_SETITEM(pot, PyArray_GETPTR1(pot,i), PyFloat_FromDouble(testParticles[i].fPot)); for (j=0; j < 3; j++) { PyArray_SETITEM(acc, PyArray_GETPTR2(acc, i, j), PyFloat_FromDouble(testParticles[i].a[j])); } } Py_DECREF(kd); /* Py_DECREF(pos); Py_DECREF(pot); Py_DECREF(acc); */ Py_INCREF(Py_None); return Py_None; }
static PyObject * find_all_nearest_pois(PyObject *self, PyObject *args) { double radius; int varind, num, gno, impno; if (!PyArg_ParseTuple(args, "diiii", &radius, &num, &varind, &gno, &impno)) return NULL; std::shared_ptr<MTC::accessibility::Accessibility> sa = sas[gno]; std::vector<std::vector<float> > nodes = sa->findAllNearestPOIs(radius, num, varind, impno); npy_intp dims[2]; dims[0] = nodes.size(); dims[1] = num; PyArrayObject *returnobj = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT); for(int i = 0 ; i < dims[0] ; i++) { for(int j = 0 ; j < dims[1] ; j++) { *(npy_float *) PyArray_GETPTR2(returnobj, i, j) = (npy_float) nodes[i][j]; } } return PyArray_Return(returnobj); }
void create_flat_labels( PyArrayObject * label_matrix, int ** flat_labels, int ** label_lengths ) { npy_int rows = PyArray_DIMS( label_matrix )[0]; npy_int cols = PyArray_DIMS( label_matrix )[1]; *flat_labels = (int *) calloc( rows * cols, sizeof(int) ); if ( NULL == (*flat_labels) ) return; *label_lengths = (int *) calloc( rows, sizeof(int) ); if ( NULL == (*label_lengths) ) { free( *flat_labels ); *flat_labels = NULL; return; } npy_int label_index = 0; for( npy_int row_idx = 0; row_idx < rows; ++row_idx ) { npy_int label_length = 0; for( npy_int col_idx = 0; col_idx < cols; ++col_idx ) { npy_int label = *( (npy_int *) PyArray_GETPTR2( label_matrix, row_idx, col_idx ) ); if ( label >= 0 ) // negative values are assumed to be padding { (*flat_labels)[ label_index++ ] = label; ++label_length; } } (*label_lengths)[ row_idx ] = label_length; } }
/** * Init from a given set of y-values * */ int dtnode :: y_init(PyArrayObject* yinit, int ti) { vector<node*> multi = get_multinodes(); // Make sure dimensionality is correct if(multi.size() != PyArray_DIM(yinit,1)) { // ERROR PyErr_SetString(PyExc_RuntimeError, "q-init dimensionality mismatch - wrong # q-values"); return BAD; } for(uint mi = 0; mi < multi.size(); mi++) { multinode* mu = dynamic_cast<multinode*>(ichildren[mi]); int yval = *((int*)PyArray_GETPTR2(yinit,ti,mi)); //printf("initing w/ yval =%d\n",yval); // Make sure y-value in valid range [0,Q-1] if(yval < 0 || yval >= (*mu).num_variants()) { // ERROR PyErr_SetString(PyExc_RuntimeError, "Out-of-range value in q-init"); return BAD; } else (*(mu)).set_y(yval); } return OK; }
/* return the offchip (ovd, length) NumPy array with shape (offcount,2) */ static PyObject* pm_get_offchip(PyObject *self, PyObject *args) { PyArrayObject *py_offchip; npy_intp shape[2]; int i; long long *tmp; if (!loaded(0)) { PyErr_Format(PyExc_ValueError, "pm not Loaded!"); return NULL; } shape[0] = offcount; shape[1] = 2; if (!PyArg_ParseTuple(args,"")) return NULL; py_offchip = (PyArrayObject *) PyArray_SimpleNew(2,shape,NPY_LONGLONG); if (!py_offchip) goto err_alloc; for (i = 0; i < offcount; i++) { tmp = (long long *) PyArray_GETPTR2(py_offchip, i, 0); if(!tmp) goto err; *tmp = (long long) offchip[i].ovd; tmp = (long long *) PyArray_GETPTR2(py_offchip, i, 1); if(!tmp) goto err; *tmp = (long long) offchip[i].plen; } free(offchip); return (PyObject *) py_offchip; err: PyArray_free(py_offchip); err_alloc: PyErr_Format(PyExc_ValueError, "pm_get_preemption Error"); cleanup(); return NULL; }
PyObject *addMatrixPiecewise(PyObject *matrix, PyObject *matrix2) { int i, j, mCov, nCov; int dimCov[2]; double *matrixData1, *matrixData2; double *outMatrixDat; ticaC_numpyArrayDim dimData = NULL; PyObject *outMatrix = NULL; PyArrayObject *outMatrixArray = NULL, *matrixArray, *matrixArray2; matrixArray = (PyArrayObject*)PyArray_FROM_OTF(matrix, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); matrixArray2 = (PyArrayObject*)PyArray_FROM_OTF(matrix2, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); dimData = PyArray_DIMS(matrixArray); dimCov[0] = dimData[1]; dimCov[1] = dimData[1]; mCov = dimCov[0]; nCov = dimCov[1]; outMatrix = PyArray_SimpleNew(TICA_ARRAY_DIMENSION, dimCov, NPY_DOUBLE); outMatrixArray = (PyArrayObject*)PyArray_FROM_OTF(outMatrix, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (NULL == outMatrix) { return NULL; } for (i = 0; i < mCov; i++) { for (j = 0; j < nCov; j++) { outMatrixDat = (double*)PyArray_GETPTR2(outMatrixArray, i, j); matrixData1 = (double*)PyArray_GETPTR2(matrixArray, i, j); matrixData2 = (double*)PyArray_GETPTR2(matrixArray2, i, j); *outMatrixDat = *matrixData1 + *matrixData2; } } outMatrix = (PyObject*)outMatrixArray; Py_INCREF(outMatrixArray); return outMatrix; }
PyObject *matrixMulti(PyArrayObject *i_data, double tmp) { int i, j, mCov, nCov; npy_intp dimCov[2]; double *rowCov; ticaC_numpyArrayDim dimData = NULL; PyObject *o_cov = NULL; PyArrayObject *cov = NULL; double *tmp2; dimData = PyArray_DIMS(i_data); dimCov[0] = dimData[1]; dimCov[1] = dimData[1]; mCov = dimCov[0]; nCov = dimCov[1]; o_cov = PyArray_SimpleNew(TICA_ARRAY_DIMENSION, dimCov, NPY_DOUBLE); cov = (PyArrayObject*)PyArray_FROM_OTF(o_cov, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (NULL == o_cov) { return NULL; } for (i = 0; i < mCov; i++) { //rowCov = (double*)PyArray_GETPTR2(cov, i, i); for (j = i; j < nCov; j++) { tmp2 = (double*)PyArray_GETPTR2(i_data, i, j); rowCov = (double*)PyArray_GETPTR2(cov, i, j); //tmp2 = *rowCov; *rowCov = *tmp2 * tmp; } } o_cov = (PyObject*)cov; Py_INCREF(cov); return o_cov; }
// get index into counts for given row of obs int cptindex(PyArrayObject *obs, int row, int *offsets, int num_parents) { register int i,ind=0; for (i=0; i<num_parents; i++) { ind += *((int*)PyArray_GETPTR2(obs, row, i+1)) * offsets[i]; } return ind; }
PyObject *computeFullMatrix(PyArrayObject *matrix) { int i, j, mCov, nCov; npy_intp dimCov[2]; double *colData1; double *rowCov, *rowCov2; ticaC_numpyArrayDim dimData = NULL; PyObject *o_cov = NULL; PyArrayObject *cov = NULL; dimData = PyArray_DIMS(matrix); dimCov[0] = dimData[1]; dimCov[1] = dimData[1]; mCov = dimCov[0]; nCov = dimCov[1]; o_cov = PyArray_SimpleNew(TICA_ARRAY_DIMENSION, dimCov, NPY_DOUBLE); cov = (PyArrayObject*)PyArray_FROM_OTF(o_cov, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (NULL == o_cov) { return NULL; } for (i = 0; i < mCov; i++) { for (j = i; j < nCov; j++) { rowCov = (double*)PyArray_GETPTR2(cov, j, i); rowCov2 = (double*)PyArray_GETPTR2(cov, i, j); colData1 = (double*)PyArray_GETPTR2(matrix, i, j); *rowCov = *colData1; *rowCov2 = *colData1; } } o_cov = (PyObject*)cov; Py_INCREF(cov); return o_cov; }
/* Adds two (complex) matrices, overwritting the first one. */ static PyObject * accum (PyObject *self, PyObject *args) { int i, j; PyArrayObject *m0, *m1; complex double *p0, *p1; if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &m0, &PyArray_Type, &m1)) return NULL; if (m0->dimensions[0] < m1->dimensions[0] || m0->dimensions[1] < m1->dimensions[1]) { PyErr_SetString(PyExc_ValueError, "accum: m0 must be able to accomodate m1"); return NULL; } if (m0->nd != 2 || m1->nd != 2) { PyErr_SetString(PyExc_ValueError, "accum: the arrays must have dimension 2."); return NULL; } for (i = 0; i < m0->dimensions[0]; i++) { /* We make use here of the fact that the matrices come from a mp expansion where m <= l. */ for (j = 0; j <= i; j++) { p0 = (complex double *) PyArray_GETPTR2 (m0, i, j); p1 = (complex double *) PyArray_GETPTR2 (m1, i, j); *p0 += *p1; } } Py_RETURN_NONE; }
//initialization of BallTree object // argument is a single array of size [D,N] static int BallTree_init(BallTreeObject *self, PyObject *args, PyObject *kwds){ //we use goto statements : all variables should be declared up front PyObject *arg=NULL; PyObject *arr=NULL; long int leaf_size=20; static char *kwlist[] = {"x", "leafsize", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|l", kwlist, &arg,&leaf_size) ) goto fail; if(leaf_size <= 0){ PyErr_SetString(PyExc_ValueError, "BallTree : leaf size must be greater than zero"); goto fail; } //view this object as an array of doubles, arr = PyArray_FROM_OTF(arg,NPY_DOUBLE,0); if(arr==NULL) goto fail; //check that it is 2D if( PyArray_NDIM(arr) != 2) goto fail; if(self != NULL){ //create the list of points self->size = PyArray_DIMS(arr)[0]; self->dim = PyArray_DIMS(arr)[1]; int inc = PyArray_STRIDES(arr)[1]/PyArray_DESCR(arr)->elsize; self->Points = new std::vector<BallTree_Point*>(self->size); for(int i=0;i<self->size;i++) self->Points->at(i) = new BallTree_Point(arr, (double*)PyArray_GETPTR2(arr,i,0), inc, PyArray_DIM(arr,1)); self->tree = new BallTree<BallTree_Point>(*(self->Points), leaf_size); } self->data = arr; //Py_DECREF(arr); return 0; fail: Py_XDECREF(arr); return -1; }
static PyObject * gicdat_vpdistM(PyObject *self, PyObject *args) { PyObject *strains; PyArrayObject *distances; int i, j; long n, rshape[2]; float cost, d; if (!PyArg_ParseTuple(args, "Of", &strains, &cost)) return NULL; n = (long)PySequence_Length(strains); rshape[0] = n; rshape[1] = n; distances = PyArray_ZEROS(2, rshape, NPY_FLOAT64, 0); Py_INCREF(distances); for (i=0;i<n-1;i++) { for (j=i+1;j<n;j++) { d = victorDist(PySequence_GetItem(strains, i), PySequence_GetItem(strains, j), cost); *(double *)PyArray_GETPTR2(distances, i, j) = d; *(double *)PyArray_GETPTR2(distances, j, i) = d; } } return distances; }
/*==========================================================================*/ PyObject *treeinit(PyObject *self, PyObject *args) { int nBucket, nbodies, nTreeBitsLo=14, nTreebitsHi=18; int i, j; KD kd = (KD)malloc(sizeof(struct kdContext)); PyObject *pos; // Nx3 Numpy array of positions PyObject *mass; // Nx1 Numpy array of masses double dTheta=0.7 * 2.0/sqrt(3.0); float fPeriod[3], fTemp, fSoft; for (i=0; i<3; i++) fPeriod[i] = 1.0; if (!PyArg_ParseTuple(args, "OOiif", &pos, &mass, &nBucket, &nbodies, &fSoft)) return NULL; /*nbodies = PyArray_DIM(mass, 0);*/ kdInitialize(kd, nbodies, nBucket, dTheta, nTreeBitsLo, nTreebitsHi, fPeriod); /* ** Allocate particles. */ kd->pStorePRIVATE = (PARTICLE *)malloc(nbodies*kd->iParticleSize); assert(kd->pStorePRIVATE != NULL); Py_BEGIN_ALLOW_THREADS for (i=0; i < nbodies; i++) { for (j=0; j < 3; j++) { fTemp = (float)*((double *)PyArray_GETPTR2(pos, i, j)); kd->pStorePRIVATE[i].r[j] = fTemp; kd->pStorePRIVATE[i].a[j] = 0; } fTemp = (float)*((double *)PyArray_GETPTR1(mass, i)); kd->pStorePRIVATE[i].fMass = fTemp; kd->pStorePRIVATE[i].fPot = 0; kd->pStorePRIVATE[i].fSoft = fSoft; } kdTreeBuild(kd, nBucket); Py_END_ALLOW_THREADS return PyCObject_FromVoidPtr((void *)kd, NULL); }
static PyObject *mandelbrot(PyObject *self, PyObject *args) { PyArrayObject *result; PyArrayObject *x_coords; PyArrayObject *y_coords; unsigned int size; int x,y; if(!PyArg_ParseTuple(args, "O!(O!O!)I", &PyArray_Type, &result, &PyArray_Type, &x_coords, &PyArray_Type, &y_coords, &size)) return NULL; #pragma omp parallel for private(y) for(x = 0; x < size; x++) { for(y = 0; y < size; y++) { *(char *)(PyArray_GETPTR2(result, y, x)) = solve(*(float *)(PyArray_GETPTR1(x_coords, x)), *(float *)(PyArray_GETPTR1(y_coords, y))); } } return Py_BuildValue("i",1); }
/** * Returns a V3D object from the Python object given * to the converter * @returns A newly constructed V3D object converted * from the PyObject. */ Kernel::Matrix<double> PyObjectToMatrix::operator()() { if (m_alreadyMatrix) { return extract<Kernel::Matrix<double>>(m_obj)(); } PyArrayObject *ndarray = (PyArrayObject *)PyArray_View( (PyArrayObject *)m_obj.ptr(), PyArray_DescrFromType(NPY_DOUBLE), &PyArray_Type); const auto shape = PyArray_DIMS(ndarray); npy_intp nx(shape[0]), ny(shape[1]); Kernel::Matrix<double> matrix(nx, ny); for (npy_intp i = 0; i < nx; i++) { auto row = matrix[i]; for (npy_intp j = 0; j < ny; j++) { row[j] = *((double *)PyArray_GETPTR2(ndarray, i, j)); } } return matrix; }
static PyObject* spherematch_kdtree_build(PyObject* self, PyObject* args) { int N, D; int i,j; int Nleaf, treeoptions, treetype; kdtree_t* kd; double* data; PyArrayObject* x; if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &x)) return NULL; if (PyArray_NDIM(x) != 2) { PyErr_SetString(PyExc_ValueError, "array must be two-dimensional"); return NULL; } if (PyArray_TYPE(x) != PyArray_DOUBLE) { PyErr_SetString(PyExc_ValueError, "array must contain doubles"); return NULL; } N = (int)PyArray_DIM(x, 0); D = (int)PyArray_DIM(x, 1); if (D > 10) { PyErr_SetString(PyExc_ValueError, "maximum dimensionality is 10: maybe you need to transpose your array?"); return NULL; } data = malloc(N * D * sizeof(double)); for (i=0; i<N; i++) { for (j=0; j<D; j++) { double* pd = PyArray_GETPTR2(x, i, j); data[i*D + j] = *pd; } } Nleaf = 16; treetype = KDTT_DOUBLE; //treeoptions = KD_BUILD_SPLIT; treeoptions = KD_BUILD_BBOX; kd = kdtree_build(NULL, data, N, D, Nleaf, treetype, treeoptions); return Py_BuildValue("k", kd); }
static PyObject * gicdat_vpdistS(PyObject *self, PyObject *args) { PyObject *itrains, *jtrains; PyArrayObject *distances; int i, j; long rshape[2]; float cost, d; if (!PyArg_ParseTuple(args, "OOf", &itrains, &jtrains, &cost)) return NULL; rshape[0] = (long)PySequence_Length(itrains); rshape[1] = (long)PySequence_Length(jtrains); distances = PyArray_ZEROS(2, rshape, NPY_FLOAT64, 0); Py_INCREF(distances); for (i=0;i<rshape[0];i++) { for (j=0;j<rshape[1];j++) { d = victorDist(PySequence_GetItem(itrains, i), PySequence_GetItem(jtrains, j), cost); *(double *)PyArray_GETPTR2(distances, i, j) = d; } } return distances; }
static PyObject * cKeo_linear_interpolate(PyObject *self, PyObject *args){ PyObject *keo_arr, *data_list; int strip_width,max_gap; npy_intp keo_arr_dims[2], data_list_dims[1]; int keo_arr_num_dim, data_list_num_dim; long int x,y,k; int start_pix, end_pix, offset; double gradient; //parse the arguments passed to the function by Python - no increase in ref count if(!PyArg_ParseTuple(args, "OOii", &keo_arr, &data_list, &strip_width, &max_gap)){ //no increase to the object's reference count PyErr_SetString(PyExc_ValueError,"Invalid parameters"); return NULL; } //check that we have been passed array objects if (!PyArray_Check(keo_arr)){ PyErr_SetString(PyExc_TypeError,"Invalid type for keo_arr argument. Expecting Numpy array."); return NULL; } if (!PyArray_Check(data_list)){ PyErr_SetString(PyExc_TypeError,"Invalid type for data_list argument. Expecting Numpy array."); return NULL; } //check that keo_arr is two dimensional keo_arr_num_dim = PyArray_NDIM(keo_arr); if (keo_arr_num_dim != 2){ PyErr_SetString(PyExc_ValueError,"Keogram array must be two dimensional"); return NULL; } //check that data_list is 1D data_list_num_dim = PyArray_NDIM(data_list); if (data_list_num_dim != 1){ PyErr_SetString(PyExc_ValueError,"Data list array must be one dimensional"); return NULL; } //check that both are well behaved if (! PyArray_ISBEHAVED(keo_arr)){ PyErr_SetString(PyExc_ValueError,"Keogram array must be well behaved"); return NULL; } if (! PyArray_ISBEHAVED(data_list)){ PyErr_SetString(PyExc_ValueError,"Data list array must be well behaved"); return NULL; } //get the dimensions of the keogram and data_list keo_arr_dims[0] = PyArray_DIM(keo_arr, 0); keo_arr_dims[1] = PyArray_DIM(keo_arr, 1); data_list_dims[0] = PyArray_DIM(data_list, 0); //do the interpolation for(k=0;k<data_list_dims[0]-1;k++){ start_pix = *((int*)PyArray_GETPTR1(data_list,(int)k))+(strip_width/2); end_pix = *((int*)PyArray_GETPTR1(data_list,((int)k)+1))-(strip_width/2); //check that any interpolation is actually needed if (start_pix == end_pix){ continue; } //check for missing data entries if (end_pix-start_pix > max_gap){ continue; //don't interpolate over large gaps in the data. } for (y=0;y<keo_arr_dims[1];y++){ offset = keo_arr_dims[1]*y; //gradient = (keo_data[(end_pix*y_stride)+(y*x_stride)] - keo_data[(start_pix*y_stride)+(y*x_stride)])/(double)(end_pix-start_pix); gradient = (*((int*)PyArray_GETPTR2(keo_arr,end_pix,y))-*((int*)PyArray_GETPTR2(keo_arr,start_pix,y)))/(double)(end_pix-start_pix); for(x=start_pix+1;x<end_pix;x++){ //keo_data[(x*y_stride)+(y*x_stride)] = keo_data[(start_pix*y_stride)+(y*x_stride)] + (x-start_pix)*gradient; *((int*)PyArray_GETPTR2(keo_arr,x,y)) = *((int*)PyArray_GETPTR2(keo_arr,start_pix,y))+ (x-start_pix)*gradient; } } } Py_RETURN_NONE; }
PyObject *computeColMeans( PyObject *i_funGetData , PyObject *i_funHasMoreData , double *i_chunkSize ) { int i, j, nRow, nCol; int numRow = 0; double *col, *sumCol; double factor = 0; int whileIter = 0; int colMeansDim[2]; void *ptrBuffer; ticaC_numpyArrayDim dimChunk = NULL; PyObject *o_colMeans = NULL; PyArrayObject *dataChunk = NULL; //PyArrayObject *colMeans = NULL; double *colMeans; while (call_funHasMoreData( i_funHasMoreData )) { whileIter++; //free(dataChunk); dataChunk = call_funGetData( i_funGetData, *i_chunkSize ); //return (PyObject*)dataChunk; dimChunk = PyArray_DIMS( dataChunk ); numRow += dimChunk[0]; nRow = dimChunk[0]; nCol = dimChunk[1]; if (1 == whileIter) { colMeansDim[0] = 1; colMeansDim[1] = dimChunk[1]; /*o_colMeans initialized as row vector*/ //colMeans = (PyArrayObject*)PyArray_FROM_OTF( o_colMeans, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY ); colMeans = (double *)malloc( sizeof( double ) * colMeansDim[0] * colMeansDim[1] ); memset( colMeans, 0, sizeof( double ) * colMeansDim[0] * colMeansDim[1] ); //for (i = 0; i < nCol; i++) //{ // sumCol = (double*)PyArray_GETPTR2( colMeans, TICA_FIRST_ROW, i ); // *sumCol = 0; //} } for (i = 0; i < nCol; i++) { col = (double*)PyArray_GETPTR2( dataChunk, TICA_FIRST_ROW, i ); //sumCol = (double*)PyArray_GETPTR2( colMeans, TICA_FIRST_ROW, i ); sumCol = (double*)TICA_GET_POINTER2D( colMeans, i, TICA_FIRST_COL, colMeansDim ); for (j = 0; j < nRow; j++, col += nCol) { *sumCol += *col; } //PyArray_free(sumCol); //PyArray_free( col ); //free(col); //free(sumCol); } //PyArray_free( col ); //PyArray_free( sumCol ); } factor = 1.0 / (double)numRow; for (i = 0; i < colMeansDim[1]; i++) { sumCol = (double*)TICA_GET_POINTER2D( colMeans, i, TICA_FIRST_COL, colMeansDim ); *sumCol *= factor; } o_colMeans = PyArray_SimpleNew( TICA_ARRAY_DIMENSION, colMeansDim, NPY_DOUBLE ); if (NULL == o_colMeans) { return NULL; } ptrBuffer = PyArray_DATA( (PyArrayObject*)o_colMeans ); memcpy( ptrBuffer, colMeans, sizeof( double ) * colMeansDim[0] * colMeansDim[1] ); free(colMeans); //o_colMeans = (PyObject*)colMeans; Py_INCREF( o_colMeans ); return o_colMeans; }
//Wrapper for Brute-Force neighbor search static PyObject* BallTree_knn_brute(PyObject *self, PyObject *args, PyObject *kwds){ long int k = 1; std::vector<BallTree_Point*> Points; PyObject *arg1 = NULL; PyObject *arg2 = NULL; PyObject *arr1 = NULL; PyObject *arr2 = NULL; PyObject *nbrs = NULL; long int* nbrs_data; PyArrayIterObject *arr2_iter = NULL; PyArrayIterObject *nbrs_iter = NULL; static char *kwlist[] = {"x", "pt", "k", NULL}; npy_intp* dim; int nd, pt_size, pt_inc; long int N; long int D; //parse arguments. If k is not provided, the default is 1 if(!PyArg_ParseTupleAndKeywords(args,kwds,"OO|l",kwlist, &arg1,&arg2,&k)) goto fail; //First array should be a 2D array of doubles arr1 = PyArray_FROM_OTF(arg1,NPY_DOUBLE,0); if(arr1==NULL) goto fail; if( PyArray_NDIM(arr1) != 2){ PyErr_SetString(PyExc_ValueError, "x must be two dimensions"); goto fail; } //Second array should be a 1D array of doubles arr2 = PyArray_FROM_OTF(arg2,NPY_DOUBLE,0); if(arr2==NULL) goto fail; nd = PyArray_NDIM(arr2); if(nd == 0){ PyErr_SetString(PyExc_ValueError, "pt cannot be zero-sized array"); goto fail; } pt_size = PyArray_DIM(arr2,nd-1); //Check that dimensions match N = PyArray_DIMS(arr1)[0]; D = PyArray_DIMS(arr1)[1]; if( pt_size != D ){ PyErr_SetString(PyExc_ValueError, "pt must be same dimension as x"); goto fail; } //check the value of k if(k<1){ PyErr_SetString(PyExc_ValueError, "k must be a positive integer"); goto fail; } if(k>N){ PyErr_SetString(PyExc_ValueError, "k must be less than the number of points"); goto fail; } //create a neighbors array and distance array dim = new npy_intp[nd]; for(int i=0; i<nd-1;i++) dim[i] = PyArray_DIM(arr2,i); dim[nd-1] = k; nbrs = (PyObject*)PyArray_SimpleNew(nd,dim,PyArray_LONG); delete[] dim; if(nbrs==NULL) goto fail; //create iterators to cycle through points nd-=1; arr2_iter = (PyArrayIterObject*)PyArray_IterAllButAxis(arr2,&nd); nbrs_iter = (PyArrayIterObject*)PyArray_IterAllButAxis(nbrs,&nd); nd+=1; if( arr2_iter==NULL || nbrs_iter==NULL || (arr2_iter->size != nbrs_iter->size) ){ PyErr_SetString(PyExc_ValueError, "failure constructing iterators"); goto fail; } pt_inc = PyArray_STRIDES(arr2)[nd-1] / PyArray_DESCR(arr2)->elsize; if(PyArray_STRIDES(nbrs)[nd-1] != PyArray_DESCR(nbrs)->elsize ){ PyErr_SetString(PyExc_ValueError, "nbrs not allocated as a C-array"); goto fail; } //create the list of points pt_inc = PyArray_STRIDES(arr1)[1]/PyArray_DESCR(arr1)->elsize; Points.resize(N); for(int i=0;i<N;i++) Points[i] = new BallTree_Point(arr1, (double*)PyArray_GETPTR2(arr1,i,0), pt_inc, PyArray_DIM(arr1,1)); //iterate through points and determine neighbors //warning: if nbrs is not a C-array, or if we're not iterating // over the last dimension, this may cause a seg fault. while(arr2_iter->index < arr2_iter->size){ BallTree_Point Query_Point(arr2, (double*)PyArray_ITER_DATA(arr2_iter), pt_inc,pt_size); nbrs_data = (long int*)(PyArray_ITER_DATA(nbrs_iter)); BruteForceNeighbors(Points, Query_Point, k, nbrs_data ); PyArray_ITER_NEXT(arr2_iter); PyArray_ITER_NEXT(nbrs_iter); } for(int i=0;i<N;i++) delete Points[i]; //if only one neighbor is requested, then resize the neighbors array if(k==1){ PyArray_Dims dims; dims.ptr = PyArray_DIMS(arr2); dims.len = PyArray_NDIM(arr2)-1; //PyArray_Resize returns None - this needs to be picked // up and dereferenced. PyObject *NoneObj = PyArray_Resize( (PyArrayObject*)nbrs, &dims, 0, NPY_ANYORDER ); if (NoneObj == NULL){ goto fail; } Py_DECREF(NoneObj); } return nbrs; fail: Py_XDECREF(arr1); Py_XDECREF(arr2); Py_XDECREF(nbrs); Py_XDECREF(arr2_iter); Py_XDECREF(nbrs_iter); return NULL; }
PyObject* radonShiftCorrelate(PyObject *self, PyObject *args) { /* ** Inputs: ** (1) 2D numpy array of first Radon transform (using doubles) ** (2) 2D numpy array of second Radon transform (using doubles) ** (3) interger of search radius (in pixels) ** Modifies: ** nothing ** Outputs: ** 1D numpy array containing correlation values of angle (y-axis) and shift (x-axis) */ Py_Initialize(); /* Simple test loop */ /*struct item *headtwo = NULL; int rad; for(rad=0; rad<8; rad++) { struct item *headtwo = NULL; headtwo = getAnglesList(rad, headtwo); fprintf(stderr, "radius %d, num angles %d\n", rad, list_length(headtwo)); //if (rad < 3) print_list(headtwo); delete_list(headtwo); } fprintf(stderr, "Finish test radii\n");*/ /* End simple test loop */ /* Parse tuples separately since args will differ between C fcns */ int radius; PyArrayObject *radonone, *radontwo; //fprintf(stderr, "Start variable read\n"); if (!PyArg_ParseTuple(args, "OOi", &radonone, &radontwo, &radius)) return NULL; if (radonone == NULL) return NULL; if (radontwo == NULL) return NULL; /* Create list of angles to check, number of angles is based on radius */ struct item *head = NULL; head = getAnglesList(radius, head); int numangles = list_length(head); //fprintf(stderr, "Finish get angles, radius %d, num angles %d\n", radius, list_length(head)); /* dimensions error checking */ if (radonone->dimensions[0] != radontwo->dimensions[0] || radonone->dimensions[1] != radontwo->dimensions[1]) { fprintf(stderr, "\n%s: Radon arrays are of different dimensions (%d,%d) vs. (%d,%d)\n\n", __FILE__, radonone->dimensions[0], radonone->dimensions[1], radontwo->dimensions[0], radontwo->dimensions[1]); return NULL; } /* Get the dimensions of the input */ int numrows = radonone->dimensions[0]; int numcols = radonone->dimensions[1]; //fprintf(stderr, "Dimensions: %d rows by %d cols\n", numrows, numcols); if (2*radius > numcols) { fprintf(stderr, "\n%s: Shift diameter %d is larger than Radon array dimensions (%d,%d))\n\n", __FILE__, radius*2, radontwo->dimensions[0], radontwo->dimensions[1]); return NULL; } /* double test; test = *((double *)PyArray_GETPTR2(radonone, 0, 0)); fprintf(stderr, "Array 1 test value at (0,0) = %.3f\n", test); test = *((double *)PyArray_GETPTR2(radontwo, 0, 0)); fprintf(stderr, "Array 2 test value at (0,0) = %.3f\n", test); */ /* Determine the dimensions for the output */ npy_intp outdims[2] = {numrows, numangles}; /* Make a new double matrix of desired dimensions */ //fprintf(stderr, "Creating output array of dimensions %d and %d\n", numrows, numangles); import_array(); // this is required to use PyArray_New() and PyArray_SimpleNew() PyArrayObject *output; //output = (PyArrayObject *) PyArray_New(&PyArray_Type, 2, outdims, NPY_DOUBLE, NULL, NULL, 0, 0, NULL); output = (PyArrayObject *) PyArray_SimpleNew(2, outdims, NPY_DOUBLE); //fprintf(stderr, "Finish create output array\n"); /* Do the calculation. */ int row; #pragma omp parallel for for (row=0; row<numrows; row++) { struct item *current; int anglecol=0; for(current=head; current!=NULL; current=current->next) { /* calculation of cross correlation */ double rawshift = radius*sin(current->angle); int shift; if (rawshift > 0) { shift = (int) (radius*sin(current->angle) + 0.5); } else { shift = (int) (radius*sin(current->angle) - 0.5); } //fprintf(stderr, "raw = %.3f; shift = %d\n", rawshift, shift); int i,j,ishift,jshift; double onevalue, twovalue; double outputsum = 0.0; //fprintf(stderr, "Position %d, %d\n", row, anglecol); for (i=0; i<numrows; i++) { for (j=0; j<numcols; j++) { ishift = i+row; if (ishift >= numrows) ishift -= numrows; // wrap overflow values if (ishift < 0) ishift += numrows; // wrap negative values jshift = j+shift; if (jshift >= numcols) jshift -= numcols; // wrap overflow values if (jshift < 0) jshift += numcols; // wrap negative values //fprintf(stderr, "%d, %d <-", ishift, jshift); onevalue = *((double *)PyArray_GETPTR2(radonone, ishift, jshift)); //fprintf(stderr, "-> %d, %d\n", i, j); twovalue = *((double *)PyArray_GETPTR2(radontwo, i, j)); outputsum += onevalue * twovalue; }} outputsum /= (numrows*numcols); *(double *) PyArray_GETPTR2(output, row, anglecol) = outputsum; /* interation variables */ anglecol++; } } /* clean up any memory leaks */ delete_list(head); return PyArray_Return(output); }
PyObject* PackOut( IData *GS, double *ICs, int state, double *stats, double hlast, int idid ) { int i, j; int numEvents = 0; /* Python objects to be returned at end of integration */ PyObject *OutObj = NULL; /* Overall PyTuple output object */ PyObject *TimeOut = NULL; /* Trajectory times */ PyObject *PointsOut = NULL; /* Trajectory points */ PyObject *StatsOut = NULL; /* */ PyObject *EventPointsOutTuple = NULL; PyObject *EventTimesOutTuple = NULL; PyObject *AuxOut = NULL; assert(GS); if( state == FAILURE ) { Py_INCREF(Py_None); return Py_None; } _init_numpy(); EventPointsOutTuple = PyTuple_New(GS->nEvents); assert(EventPointsOutTuple); EventTimesOutTuple = PyTuple_New(GS->nEvents); assert(EventTimesOutTuple); /* Copy out points */ npy_intp p_dims[2] = {GS->phaseDim, GS->pointsIdx}; PointsOut = PyArray_SimpleNew(2, p_dims, NPY_DOUBLE); assert(PointsOut); /* WARNING -- modified the order of the dimensions here! */ for(i = 0; i < GS->pointsIdx; i++) { for(j = 0; j < GS->phaseDim; j++) { *((double *) PyArray_GETPTR2((PyArrayObject *)PointsOut, j, i)) = GS->gPoints[i][j]; } } /* Copy out times */ npy_intp t_dims[1] = {GS->timeIdx}; TimeOut = PyArray_SimpleNew(1, t_dims, NPY_DOUBLE); assert(TimeOut); for( i = 0; i < GS->timeIdx; i++ ) { *((double *) PyArray_GETPTR1((PyArrayObject *)TimeOut, i)) = GS->gTimeV[i]; } /* Copy out auxilliary points */ npy_intp au_dims[2] = {GS->nAuxVars, GS->pointsIdx}; if( GS->nAuxVars > 0 && GS->calcAux == 1 ) { /* WARNING: The order of the dimensions is switched here! */ AuxOut = PyArray_SimpleNew(2, au_dims, NPY_DOUBLE); assert(AuxOut); for( i = 0; i < GS->pointsIdx; i++ ) { for( j = 0; j < GS->nAuxVars; j++ ) { *((double *) PyArray_GETPTR2((PyArrayObject *)AuxOut, j, i)) = GS->gAuxPoints[i][j]; } } } /* Allocate and copy out integration stats */ /* Number of stats different between Radau, Dopri */ npy_intp s_dims[1] = {7}; StatsOut = PyArray_SimpleNewFromData(1, s_dims, NPY_DOUBLE, stats); assert(StatsOut); /* Setup the tuple for the event points and times (separate from trajectory). Must remember to keep the reference count for Py_None up to date*/ for( i = 0; i < GS->nEvents; i++ ) { PyTuple_SetItem(EventPointsOutTuple, i, Py_None); Py_INCREF(Py_None); PyTuple_SetItem(EventTimesOutTuple, i, Py_None); Py_INCREF(Py_None); } /* Count the number of events for which something was caught */ numEvents = 0; for( i = 0; i < GS->haveActive; i++ ) { if( GS->gCheckableEventCounts[i] > 0 ) { numEvents++; } } /* Only allocate memory for events if something was caught */ if( numEvents > 0 ) { /* Lower reference count for Py_None from INCREFs in initialization of OutTuples above. Decrease by 2*numevents) */ for( i = 0; i < numEvents; i++ ) { Py_DECREF(Py_None); Py_DECREF(Py_None); } for( i = 0; i < GS->haveActive; i++ ) { if( GS->gCheckableEventCounts[i] > 0 ) { int k, l; /* Get the number of points caught for this event, and which one (in list of all active and nonactive events) it is */ int EvtCt = GS->gCheckableEventCounts[i], EvtIdx = GS->gCheckableEvents[i]; npy_intp et_dims[1] = {EvtCt}; npy_intp ep_dims[2] = {GS->phaseDim, EvtCt}; /* Copy the event times, points into a python array */ PyObject *e_times = PyArray_SimpleNewFromData(1, et_dims, NPY_DOUBLE, GS->gEventTimes[i]); assert(e_times); PyObject *e_points = PyArray_SimpleNew(2, ep_dims, NPY_DOUBLE); assert(e_points); for( k = 0; k < EvtCt; k++ ) { for( l = 0; l < GS->phaseDim; l++ ) { *((double *) PyArray_GETPTR2((PyArrayObject *)e_points, l, k)) = GS->gEventPoints[i][l][k]; } } /* The returned python tuple has slots for all events, not just active ones, which is why we insert into the tuple at position EvtIdx */ PyTuple_SetItem(EventPointsOutTuple, EvtIdx, e_points); PyTuple_SetItem(EventTimesOutTuple, EvtIdx, e_times); } } } /* Pack points, times, stats, events, etc. into a 7 tuple */ OutObj = PyTuple_New(8); assert(OutObj); PyTuple_SetItem(OutObj, 0, (PyObject *)TimeOut); PyTuple_SetItem(OutObj, 1, (PyObject *)PointsOut); if( GS->nAuxVars > 0 && GS->calcAux == 1) { PyTuple_SetItem(OutObj, 2, (PyObject *)AuxOut); } else { PyTuple_SetItem(OutObj, 2, Py_None); Py_INCREF(Py_None); } PyTuple_SetItem(OutObj, 3, (PyObject *)StatsOut); PyTuple_SetItem(OutObj, 4, PyFloat_FromDouble(hlast)); PyTuple_SetItem(OutObj, 5, PyFloat_FromDouble((double)idid)); PyTuple_SetItem(OutObj, 6, EventTimesOutTuple); PyTuple_SetItem(OutObj, 7, EventPointsOutTuple); return OutObj; }
static PyObject * _fasttrips_find_pathset(PyObject *self, PyObject *args) { PyArrayObject *pyo; fasttrips::PathSpecification path_spec; int hyperpath_i, outbound_i, trace_i; char *user_class, *purpose, *access_mode, *transit_mode, *egress_mode; if (!PyArg_ParseTuple(args, "iiiisssssiiidi", &path_spec.iteration_, &path_spec.passenger_id_, &path_spec.path_id_, &hyperpath_i, &user_class, &purpose, &access_mode, &transit_mode, &egress_mode, &path_spec.origin_taz_id_, &path_spec.destination_taz_id_, &outbound_i, &path_spec.preferred_time_, &trace_i)) { return NULL; } path_spec.hyperpath_ = (hyperpath_i != 0); path_spec.outbound_ = (outbound_i != 0); path_spec.trace_ = (trace_i != 0); path_spec.user_class_ = user_class; path_spec.purpose_ = purpose; path_spec.access_mode_ = access_mode; path_spec.transit_mode_= transit_mode; path_spec.egress_mode_ = egress_mode; fasttrips::PathSet pathset; fasttrips::PerformanceInfo perf_info = { 0, 0, 0, 0, 0, 0}; pathfinder.findPathSet(path_spec, pathset, perf_info); // count links int num_links = 0; for (fasttrips::PathSet::const_iterator psi=pathset.begin(); psi != pathset.end(); ++psi) { num_links += (int)psi->first.size(); } // package for returning. We'll separate ints and doubles. npy_intp dims_int[2]; dims_int[0] = num_links; dims_int[1] = 7; // path_num, stop_id, deparr_mode_, trip_id_, stop_succpred_, seq_, seq_succpred_ PyArrayObject *ret_int = (PyArrayObject *)PyArray_SimpleNew(2, dims_int, NPY_INT32); npy_intp dims_double[2]; dims_double[0] = num_links; dims_double[1] = 5; // label_, deparr_time_, link_time_, cost_, arrdep_time_ PyArrayObject *ret_double = (PyArrayObject *)PyArray_SimpleNew(2, dims_double, NPY_DOUBLE); // costs and probability npy_intp dims_paths[2]; dims_paths[0] = pathset.size(); dims_paths[1] = 2; PyArrayObject *ret_paths = (PyArrayObject*)PyArray_SimpleNew(2, dims_paths, NPY_DOUBLE); int ind = 0; int path_num = 0; for (fasttrips::PathSet::const_iterator psi=pathset.begin(); psi != pathset.end(); ++psi) { const fasttrips::Path& path = psi->first; *(npy_double*)PyArray_GETPTR2(ret_paths, path_num, 0) = path.cost(); *(npy_double*)PyArray_GETPTR2(ret_paths, path_num, 1) = psi->second.probability_; for (int link_num = 0; link_num < path.size(); ++link_num) { *(npy_int32*)PyArray_GETPTR2(ret_int, ind, 0) = path_num; *(npy_int32*)PyArray_GETPTR2(ret_int, ind, 1) = path[link_num].first; *(npy_int32*)PyArray_GETPTR2(ret_int, ind, 2) = path[link_num].second.deparr_mode_; *(npy_int32*)PyArray_GETPTR2(ret_int, ind, 3) = path[link_num].second.trip_id_; *(npy_int32*)PyArray_GETPTR2(ret_int, ind, 4) = path[link_num].second.stop_succpred_; *(npy_int32*)PyArray_GETPTR2(ret_int, ind, 5) = path[link_num].second.seq_; *(npy_int32*)PyArray_GETPTR2(ret_int, ind, 6) = path[link_num].second.seq_succpred_; *(npy_double*)PyArray_GETPTR2(ret_double, ind, 0) = 0.0; // TODO: label *(npy_double*)PyArray_GETPTR2(ret_double, ind, 1) = path[link_num].second.deparr_time_; *(npy_double*)PyArray_GETPTR2(ret_double, ind, 2) = path[link_num].second.link_time_; *(npy_double*)PyArray_GETPTR2(ret_double, ind, 3) = path[link_num].second.cost_; *(npy_double*)PyArray_GETPTR2(ret_double, ind, 4) = path[link_num].second.arrdep_time_; ind += 1; } path_num += 1; } PyObject *returnobj = Py_BuildValue("(OOOiiiillll)",ret_int,ret_double,ret_paths, pathfinder.processNumber(), perf_info.label_iterations_, perf_info.num_labeled_stops_, perf_info.max_process_count_, perf_info.milliseconds_labeling_, perf_info.milliseconds_enumerating_, perf_info.workingset_bytes_, perf_info.privateusage_bytes_); return returnobj; }
static PyObject * uberseg_direct(PyObject* self, PyObject* args) { int dmin=0,d=0,x=0,y=0,k=0,imin=0; PyObject* seg = NULL; PyObject* weight = NULL; int Nx; int Ny; int object_number; PyObject* obj_inds_x = NULL; PyObject* obj_inds_y = NULL; int Ninds; int *ptrx,*ptry,*ptrs; float *ptrw; int dx; if (!PyArg_ParseTuple(args, (char*)"OOiiiOOi", &seg, &weight, &Nx, &Ny, &object_number, &obj_inds_x, &obj_inds_y, &Ninds)) { return NULL; } for(x=0;x<Nx;++x) { for(y=0;y<Ny;++y) { //shortcuts ptrs = (int*)PyArray_GETPTR2(seg,x,y); if(*ptrs == object_number) continue; if(*ptrs > 0 && *ptrs != object_number) { ptrw = (float*)PyArray_GETPTR2(weight,x,y); *ptrw = 0.0; continue; } //must do direct search imin = -1; for(k=0;k<Ninds;++k) { ptrx = (int*)PyArray_GETPTR1(obj_inds_x,k); ptry = (int*)PyArray_GETPTR1(obj_inds_y,k); dx = x-(*ptrx); d = dx*dx; dx = y-(*ptry); d += dx*dx; if(d < dmin || imin == -1) { dmin = d; imin = k; } } if(imin == -1) { continue; } ptrx = (int*)PyArray_GETPTR1(obj_inds_x,imin); ptry = (int*)PyArray_GETPTR1(obj_inds_y,imin); ptrs = (int*)PyArray_GETPTR2(seg,*ptrx,*ptry); if(*ptrs != object_number) { ptrw = (float*)PyArray_GETPTR2(weight,x,y); *ptrw = 0.0; } } } Py_INCREF(Py_None); return Py_None; }
static PyObject * uberseg_tree(PyObject* self, PyObject* args) { int x=0,y=0,k=0,segmin=0; float dmin=0,r=0,dx=0,d=0; float pos[2],fac=0; PyObject* seg = NULL; PyObject* weight = NULL; int Nx; int Ny; int object_number; PyObject* obj_inds_x = NULL; PyObject* obj_inds_y = NULL; int Ninds; int *ptrx,*ptry,*ptrs; float *ptrw; struct mytype *obj = NULL; struct fast3tree *tree = NULL; struct fast3tree_results *res = NULL; if (!PyArg_ParseTuple(args, (char*)"OOiiiOOi", &seg, &weight, &Nx, &Ny, &object_number, &obj_inds_x, &obj_inds_y, &Ninds)) { return NULL; } obj = (struct mytype *)malloc(sizeof(struct mytype)*Ninds); if(obj == NULL) exit(1); for(k=0;k<Ninds;++k) { ptrx = (int*)PyArray_GETPTR1(obj_inds_x,k); ptry = (int*)PyArray_GETPTR1(obj_inds_y,k); ptrs = (int*)PyArray_GETPTR2(seg,*ptrx,*ptry); obj[k].idx = k; obj[k].seg = *ptrs; obj[k].pos[0] = (float)(*ptrx); obj[k].pos[1] = (float)(*ptry); } tree = fast3tree_init(Ninds,obj); if(tree == NULL) exit(1); res = fast3tree_results_init(); if(res == NULL) exit(1); float maxr = 1.1*sqrt(Nx*Nx+Ny*Ny); for(x=0;x<Nx;++x) { for(y=0;y<Ny;++y) { //shortcuts ptrs = (int*)PyArray_GETPTR2(seg,x,y); if(*ptrs == object_number) continue; if(*ptrs > 0 && *ptrs != object_number) { ptrw = (float*)PyArray_GETPTR2(weight,x,y); *ptrw = 0.0; continue; } //must do search pos[0] = (float)x; pos[1] = (float)y; r = fast3tree_find_next_closest_distance(tree,res,pos); fac = 1.0/1.1; do { fac *= 1.1; fast3tree_results_clear(res); fast3tree_find_sphere(tree,res,pos,r*fac); } while(res->num_points == 0 && r*fac <= maxr); segmin = -1; for(k=0;k<res->num_points;++k) { dx = res->points[k]->pos[0]-x; d = dx*dx; dx = res->points[k]->pos[1]-y; d += dx*dx; if(segmin == -1 || d < dmin) { segmin = res->points[k]->seg; dmin = d; } } if(segmin == -1) { continue; } if(segmin != object_number) { ptrw = (float*)PyArray_GETPTR2(weight,x,y); *ptrw = 0.0; } } } free(obj); fast3tree_free(&tree); fast3tree_results_free(res); Py_INCREF(Py_None); return Py_None; }
static PyObject * shift(PyObject * self, PyObject * args, PyObject * kwds) { PyArrayObject * pos, * arowvectors, *abox, *amin, *amax; static char * kwlist[] = {"POS", "ROWVECTORS", "BOX", "MIN", "MAX", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!O!O!O!", kwlist, &PyArray_Type, &pos, &PyArray_Type, &arowvectors, &PyArray_Type, &abox, &PyArray_Type, &amin, &PyArray_Type, &amax)) return NULL; int D = PyArray_DIMS(pos)[1]; npy_intp length = PyArray_DIMS(pos)[0]; int i,j; npy_intp p; amin = (PyArrayObject *) PyArray_Cast(amin, NPY_INT); amax = (PyArrayObject *) PyArray_Cast(amax, NPY_INT); abox = (PyArrayObject *) PyArray_Cast(abox, NPY_FLOAT); arowvectors = (PyArrayObject *) PyArray_Cast(arowvectors, NPY_FLOAT); int min[3] = {0}, max[3] = {0}; float box[3]; float rowvectors[3][3]; for(i = 0; i < D; i++) { min[i] = *((int*)PyArray_GETPTR1(amin, i)); max[i] = *((int*)PyArray_GETPTR1(amax, i)); box[i] = *((float*)PyArray_GETPTR1(abox, i)); for(j = 0; j < D; j++) { rowvectors[i][j] = *((float*)PyArray_GETPTR2(arowvectors, i, j)); } } #if 0 printf("box = %f %f %f\n", box[0], box[1], box[2]); printf("min = %d %d %d\n", min[0], min[1], min[2]); printf("max = %d %d %d\n", max[0], max[1], max[2]); printf("rowvectors = %f %f %f\n", rowvectors[0][0], rowvectors[0][1], rowvectors[0][2]); printf("rowvectors = %f %f %f\n", rowvectors[1][0], rowvectors[1][1], rowvectors[1][2]); printf("rowvectors = %f %f %f\n", rowvectors[2][0], rowvectors[2][1], rowvectors[2][2]); printf("D = %d\n", D); #endif int I[3] = {0,0,0}; int failed_count = 0; #pragma omp parallel for private(I) reduction(+: failed_count) for(p = 0; p < length; p++) { int i; float * ppos[3]; float shifted[3]; float original[3]; for(i = 0; i < D; i++) { ppos[i] = (float *) PyArray_GETPTR2(pos, p, i); original[i] = *(ppos[i]); } tryshift(original, shifted, rowvectors, I, D); if(!inbox(shifted, box, D)) { int newI[3]; for(newI[0] = min[0]; newI[0] <= max[0]; newI[0]++) for(newI[1] = min[1]; newI[1] <= max[1]; newI[1]++) for(newI[2] = min[2]; newI[2] <= max[2]; newI[2]++) { tryshift(original, shifted, rowvectors, newI, D); if(inbox(shifted, box, D)) { for(i = 0; i < D; i++) { I[i] = newI[i]; } goto out_of_here; } } out_of_here:; } if(!inbox(shifted, box, D)) { printf("%f %f %f to ", original[0], original[1], original[2]); printf("%f %f %f faild\n", shifted[0], shifted[1], shifted[2]); for(i = 0; i < D; i++) { shifted[i] = original[i]; } failed_count++; } for(i = 0; i < D; i++) { *(ppos[i]) = shifted[i]; } } #if 0 printf("failed = %d\n", failed_count); #endif Py_DECREF(abox); Py_DECREF(amax); Py_DECREF(amin); Py_DECREF(arowvectors); Py_RETURN_NONE; }
Py::Object _path_module::point_in_path_collection(const Py::Tuple& args) { args.verify_length(9); //segments, trans, clipbox, colors, linewidths, antialiaseds double x = Py::Float(args[0]); double y = Py::Float(args[1]); double radius = Py::Float(args[2]); agg::trans_affine master_transform = py_to_agg_transformation_matrix(args[3].ptr()); Py::SeqBase<Py::Object> paths = args[4]; Py::SeqBase<Py::Object> transforms_obj = args[5]; Py::SeqBase<Py::Object> offsets_obj = args[6]; agg::trans_affine offset_trans = py_to_agg_transformation_matrix(args[7].ptr()); bool filled = Py::Boolean(args[8]); PyArrayObject* offsets = (PyArrayObject*)PyArray_FromObject( offsets_obj.ptr(), PyArray_DOUBLE, 0, 2); if (!offsets || (PyArray_NDIM(offsets) == 2 && PyArray_DIM(offsets, 1) != 2) || (PyArray_NDIM(offsets) == 1 && PyArray_DIM(offsets, 0) != 0)) { Py_XDECREF(offsets); throw Py::ValueError("Offsets array must be Nx2"); } size_t Npaths = paths.length(); size_t Noffsets = offsets->dimensions[0]; size_t N = std::max(Npaths, Noffsets); size_t Ntransforms = std::min(transforms_obj.length(), N); size_t i; // Convert all of the transforms up front typedef std::vector<agg::trans_affine> transforms_t; transforms_t transforms; transforms.reserve(Ntransforms); for (i = 0; i < Ntransforms; ++i) { agg::trans_affine trans = py_to_agg_transformation_matrix (transforms_obj[i].ptr(), false); trans *= master_transform; transforms.push_back(trans); } Py::List result; agg::trans_affine trans; for (i = 0; i < N; ++i) { PathIterator path(paths[i % Npaths]); if (Ntransforms) { trans = transforms[i % Ntransforms]; } else { trans = master_transform; } if (Noffsets) { double xo = *(double*)PyArray_GETPTR2(offsets, i % Noffsets, 0); double yo = *(double*)PyArray_GETPTR2(offsets, i % Noffsets, 1); offset_trans.transform(&xo, &yo); trans *= agg::trans_affine_translation(xo, yo); } if (filled) { if (::point_in_path(x, y, path, trans)) result.append(Py::Int((int)i)); } else { if (::point_on_path(x, y, radius, path, trans)) result.append(Py::Int((int)i)); } } return result; }
Py::Object _path_module::get_path_collection_extents(const Py::Tuple& args) { args.verify_length(5); //segments, trans, clipbox, colors, linewidths, antialiaseds agg::trans_affine master_transform = py_to_agg_transformation_matrix(args[0].ptr()); Py::SeqBase<Py::Object> paths = args[1]; Py::SeqBase<Py::Object> transforms_obj = args[2]; Py::Object offsets_obj = args[3]; agg::trans_affine offset_trans = py_to_agg_transformation_matrix(args[4].ptr(), false); PyArrayObject* offsets = NULL; double x0, y0, x1, y1, xm, ym; try { offsets = (PyArrayObject*)PyArray_FromObject( offsets_obj.ptr(), PyArray_DOUBLE, 0, 2); if (!offsets || (PyArray_NDIM(offsets) == 2 && PyArray_DIM(offsets, 1) != 2) || (PyArray_NDIM(offsets) == 1 && PyArray_DIM(offsets, 0) != 0)) { throw Py::ValueError("Offsets array must be Nx2"); } size_t Npaths = paths.length(); size_t Noffsets = offsets->dimensions[0]; size_t N = std::max(Npaths, Noffsets); size_t Ntransforms = std::min(transforms_obj.length(), N); size_t i; // Convert all of the transforms up front typedef std::vector<agg::trans_affine> transforms_t; transforms_t transforms; transforms.reserve(Ntransforms); for (i = 0; i < Ntransforms; ++i) { agg::trans_affine trans = py_to_agg_transformation_matrix (transforms_obj[i].ptr(), false); trans *= master_transform; transforms.push_back(trans); } // The offset each of those and collect the mins/maxs x0 = std::numeric_limits<double>::infinity(); y0 = std::numeric_limits<double>::infinity(); x1 = -std::numeric_limits<double>::infinity(); y1 = -std::numeric_limits<double>::infinity(); xm = std::numeric_limits<double>::infinity(); ym = std::numeric_limits<double>::infinity(); agg::trans_affine trans; for (i = 0; i < N; ++i) { PathIterator path(paths[i % Npaths]); if (Ntransforms) { trans = transforms[i % Ntransforms]; } else { trans = master_transform; } if (Noffsets) { double xo = *(double*)PyArray_GETPTR2(offsets, i % Noffsets, 0); double yo = *(double*)PyArray_GETPTR2(offsets, i % Noffsets, 1); offset_trans.transform(&xo, &yo); trans *= agg::trans_affine_translation(xo, yo); } ::get_path_extents(path, trans, &x0, &y0, &x1, &y1, &xm, &ym); } } catch (...) { Py_XDECREF(offsets); throw; } Py_XDECREF(offsets); Py::Tuple result(4); result[0] = Py::Float(x0); result[1] = Py::Float(y0); result[2] = Py::Float(x1); result[3] = Py::Float(y1); return result; }