void allstats_short(PyObject *inputarray, stats *result) { PyObject *iter; npy_short *ptr; iter = PyArray_IterNew(inputarray); while (PyArray_ITER_NOTDONE(iter)) { ptr = (npy_short *)PyArray_ITER_DATA(iter); updateStats(result, (double) (*ptr)); PyArray_ITER_NEXT(iter); } Py_XDECREF(iter); }
static void _cubic_spline_transform(PyArrayObject* res, int axis, double* work) { PyArrayIterObject* iter; unsigned int dim, stride; /* Instantiate iterator and views */ iter = (PyArrayIterObject*)PyArray_IterAllButAxis((PyObject*)res, &axis); dim = PyArray_DIM((PyArrayObject*)iter->ao, axis); stride = PyArray_STRIDE((PyArrayObject*)iter->ao, axis)/sizeof(double); /* Apply the cubic spline transform along given axis */ while(iter->index < iter->size) { _copy_double_buffer(work, PyArray_ITER_DATA(iter), dim, stride); _cubic_spline_transform1d(PyArray_ITER_DATA(iter), work, dim, stride, 1); PyArray_ITER_NEXT(iter); } /* Free local structures */ Py_DECREF(iter); return; }
/* Create an fff_vector from a PyArrayIter object */ fff_vector* _fff_vector_new_from_PyArrayIter(const PyArrayIterObject* it, npy_intp axis) { fff_vector* y; char* data = PyArray_ITER_DATA(it); PyArrayObject* ao = (PyArrayObject*) it->ao; npy_intp dim = PyArray_DIM(ao, axis); npy_intp stride = PyArray_STRIDE(ao, axis); int type = PyArray_TYPE(ao); int itemsize = PyArray_ITEMSIZE(ao); y = _fff_vector_new_from_buffer(data, dim, stride, type, itemsize); return y; }
/* Resample a 3d image submitted to an affine transformation. Tvox is the voxel transformation from the image to the destination grid. */ void cubic_spline_resample3d(PyArrayObject* im_resampled, const PyArrayObject* im, const double* Tvox, int cast_integer, int mode_x, int mode_y, int mode_z) { double i1; PyObject* py_i1; PyArrayObject* im_spline_coeff; PyArrayIterObject* imIter = (PyArrayIterObject*)PyArray_IterNew((PyObject*)im_resampled); unsigned int x, y, z; unsigned dimX = PyArray_DIM(im, 0); unsigned dimY = PyArray_DIM(im, 1); unsigned dimZ = PyArray_DIM(im, 2); npy_intp dims[3] = {dimX, dimY, dimZ}; double Tx, Ty, Tz; /* Compute the spline coefficient image */ im_spline_coeff = (PyArrayObject*)PyArray_SimpleNew(3, dims, NPY_DOUBLE); cubic_spline_transform(im_spline_coeff, im); /* Force iterator coordinates to be updated */ UPDATE_ITERATOR_COORDS(imIter); /* Resampling loop */ while(imIter->index < imIter->size) { x = imIter->coordinates[0]; y = imIter->coordinates[1]; z = imIter->coordinates[2]; _apply_affine_transform(&Tx, &Ty, &Tz, Tvox, x, y, z); i1 = cubic_spline_sample3d(Tx, Ty, Tz, im_spline_coeff, mode_x, mode_y, mode_z); if (cast_integer) i1 = ROUND(i1); /* Copy interpolated value into numpy array */ py_i1 = PyFloat_FromDouble(i1); PyArray_SETITEM(im_resampled, PyArray_ITER_DATA(imIter), py_i1); Py_DECREF(py_i1); /* Increment iterator */ PyArray_ITER_NEXT(imIter); } /* Free memory */ Py_DECREF(imIter); Py_DECREF(im_spline_coeff); return; }
PyArrayObject* make_edges(const PyArrayObject* idx, int ngb_size) { int* ngb = _select_neighborhood_system(ngb_size); PyArrayIterObject* iter = (PyArrayIterObject*)PyArray_IterNew((PyObject*)idx); int* buf_ngb; npy_intp xi, yi, zi, xj, yj, zj; npy_intp u2 = idx->dimensions[2]; npy_intp u1 = idx->dimensions[1]*u2; npy_intp u0 = idx->dimensions[0]*u1; npy_intp mask_size = 0, n_edges = 0; npy_intp idx_i; npy_intp *buf_idx; npy_intp *edges_data, *buf_edges; npy_intp ngb_idx; npy_intp pos; PyArrayObject* edges; npy_intp dim[2] = {0, 2}; /* First loop over the input array to determine the mask size */ while(iter->index < iter->size) { buf_idx = (npy_intp*)PyArray_ITER_DATA(iter); if (*buf_idx >= 0) mask_size ++; PyArray_ITER_NEXT(iter); } /* Allocate the array of edges using an upper bound of the required memory space */ edges_data = (npy_intp*)malloc(2 * ngb_size * mask_size * sizeof(npy_intp)); /* Second loop over the input array */ PyArray_ITER_RESET(iter); iter->contiguous = 0; /* To force coordinates to be updated */ buf_edges = edges_data; while(iter->index < iter->size) { xi = iter->coordinates[0]; yi = iter->coordinates[1]; zi = iter->coordinates[2]; buf_idx = (npy_intp*)PyArray_ITER_DATA(iter); idx_i = *buf_idx; /* Loop over neighbors if current point is within the mask */ if (idx_i >= 0) { buf_ngb = ngb; for (ngb_idx=0; ngb_idx<ngb_size; ngb_idx++) { /* Get neighbor coordinates */ xj = xi + *buf_ngb; buf_ngb++; yj = yi + *buf_ngb; buf_ngb++; zj = zi + *buf_ngb; buf_ngb++; pos = xj*u1 + yj*u2 + zj; /* Store edge if neighbor is within the mask */ if ((pos < 0) || (pos >= u0)) continue; buf_idx = (npy_intp*)idx->data + pos; if (*buf_idx < 0) continue; buf_edges[0] = idx_i; buf_edges[1] = *buf_idx; n_edges ++; buf_edges += 2; } } /* Increment iterator */ PyArray_ITER_NEXT(iter); } /* Reallocate edges array to account for connections suppressed due to masking */ edges_data = realloc((void *)edges_data, 2 * n_edges * sizeof(npy_intp)); dim[0] = n_edges; edges = (PyArrayObject*) PyArray_SimpleNewFromData(2, dim, NPY_INTP, (void*)edges_data); /* Transfer ownership to python (to avoid memory leaks!) */ edges->flags = (edges->flags) | NPY_OWNDATA; /* Free memory */ Py_XDECREF(iter); return edges; }
void ve_step(PyArrayObject* ppm, const PyArrayObject* ref, const PyArrayObject* XYZ, const PyArrayObject* U, int ngb_size, double beta) { npy_intp k, x, y, z, pos; double *p, *buf, *ppm_data; double psum, tmp; PyArrayIterObject* iter; int axis = 1; npy_intp K = ppm->dimensions[3]; npy_intp u2 = ppm->dimensions[2]*K; npy_intp u1 = ppm->dimensions[1]*u2; const double* ref_data = (double*)ref->data; const double* U_data = (double*)U->data; npy_intp* xyz; int* ngb; /* Neighborhood system */ ngb = _select_neighborhood_system(ngb_size); /* Pointer to the data array */ ppm_data = (double*)ppm->data; /* Allocate auxiliary vectors */ p = (double*)calloc(K, sizeof(double)); /* Loop over points */ iter = (PyArrayIterObject*)PyArray_IterAllButAxis((PyObject*)XYZ, &axis); while(iter->index < iter->size) { /* Integrate the energy over the neighborhood */ xyz = PyArray_ITER_DATA(iter); x = xyz[0]; y = xyz[1]; z = xyz[2]; _ngb_integrate(p, ppm, x, y, z, U_data, (const int*)ngb, ngb_size); /* Apply exponential transform, multiply with reference and compute normalization constant */ psum = 0.0; for (k=0, pos=(iter->index)*K, buf=p; k<K; k++, pos++, buf++) { tmp = exp(-2 * beta * (*buf)) * ref_data[pos]; psum += tmp; *buf = tmp; } /* Normalize to unitary sum */ pos = x*u1 + y*u2 + z*K; if (psum > TINY) for (k=0, buf=p; k<K; k++, pos++, buf++) ppm_data[pos] = *buf/psum; else for (k=0, buf=p; k<K; k++, pos++, buf++) ppm_data[pos] = (*buf+TINY/(double)K)/(psum+TINY); /* Update iterator */ PyArray_ITER_NEXT(iter); } /* Free memory */ free(p); Py_XDECREF(iter); return; }
//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; }
//query the ball tree. Arguments are the array of search points // and the radius around each point to search static PyObject * BallTree_queryball(BallTreeObject *self, PyObject *args, PyObject *kwds){ //we use goto statements : all variables should be declared up front int count_only = 0; double r; PyObject *arg = NULL; PyObject *arr = NULL; PyObject *nbrs = NULL; PyArrayIterObject* arr_iter = NULL; PyArrayIterObject* nbrs_iter = NULL; int nd, pt_size, pt_inc; static char *kwlist[] = {"x", "r", "count_only", NULL}; //parse arguments. If kmax is not provided, the default is 20 if(!PyArg_ParseTupleAndKeywords(args,kwds,"Od|i", kwlist,&arg,&r,&count_only)){ goto fail; } //check value of r if(r < 0){ PyErr_SetString(PyExc_ValueError, "r must not be negative"); goto fail; } //get the array object from the first argument arr = PyArray_FROM_OTF(arg,NPY_DOUBLE,NPY_ALIGNED); //check that the array was properly constructed if(arr==NULL){ PyErr_SetString(PyExc_ValueError, "pt must be convertable to array"); goto fail; } nd = PyArray_NDIM(arr); if(nd == 0){ PyErr_SetString(PyExc_ValueError, "pt cannot be zero-sized array"); goto fail; } pt_size = PyArray_DIM(arr,nd-1); if( pt_size != self->tree->PointSize() ){ PyErr_SetString(PyExc_ValueError, "points are incorrect dimension"); goto fail; } // Case 1: return arrays of all neighbors for each point // if(!count_only){ //create a neighbors array. This is an array of python objects. // each of which will be a numpy array of neighbors nbrs = (PyObject*)PyArray_SimpleNew(nd-1,PyArray_DIMS(arr), PyArray_OBJECT); if(nbrs==NULL){ goto fail; } //create iterators to cycle through points --nd; arr_iter = (PyArrayIterObject*)PyArray_IterAllButAxis(arr,&nd); nbrs_iter = (PyArrayIterObject*)PyArray_IterNew(nbrs); ++nd; if( arr_iter==NULL || nbrs_iter==NULL || (arr_iter->size != nbrs_iter->size)){ PyErr_SetString(PyExc_ValueError, "unable to construct iterator"); goto fail; } pt_inc = PyArray_STRIDES(arr)[nd-1] / PyArray_DESCR(arr)->elsize; if(PyArray_NDIM(nbrs)==0){ BallTree_Point pt(arr, (double*)PyArray_ITER_DATA(arr_iter), pt_inc,pt_size); std::vector<long int> nbrs_vec; self->tree->query_ball(pt,r,nbrs_vec); npy_intp N_nbrs = nbrs_vec.size(); PyObject* nbrs_obj = PyArray_SimpleNew(1, &N_nbrs, PyArray_LONG); long int* data = (long int*)PyArray_DATA(nbrs_obj); for(int i=0; i<N_nbrs; i++) data[i] = nbrs_vec[i]; PyObject* tmp = nbrs; nbrs = nbrs_obj; Py_DECREF(tmp); }else{ while(arr_iter->index < arr_iter->size){ BallTree_Point pt(arr, (double*)PyArray_ITER_DATA(arr_iter), pt_inc,pt_size); std::vector<long int> nbrs_vec; self->tree->query_ball(pt,r,nbrs_vec); npy_intp N_nbrs = nbrs_vec.size(); PyObject* nbrs_obj = PyArray_SimpleNew(1, &N_nbrs, PyArray_LONG); long int* data = (long int*)PyArray_DATA(nbrs_obj); for(int i=0; i<N_nbrs; i++) data[i] = nbrs_vec[i]; PyObject** nbrs_data = (PyObject**)PyArray_ITER_DATA(nbrs_iter); PyObject* tmp = nbrs_data[0]; nbrs_data[0] = nbrs_obj; Py_XDECREF(tmp); PyArray_ITER_NEXT(arr_iter); PyArray_ITER_NEXT(nbrs_iter); } } } // Case 2 : return number of neighbors for each point else{ //create an array to keep track of the count nbrs = (PyObject*)PyArray_SimpleNew(nd-1,PyArray_DIMS(arr), PyArray_LONG); if(nbrs==NULL){ goto fail; } //create iterators to cycle through points --nd; arr_iter = (PyArrayIterObject*)PyArray_IterAllButAxis(arr,&nd); nbrs_iter = (PyArrayIterObject*)PyArray_IterNew(nbrs); ++nd; if( arr_iter==NULL || nbrs_iter==NULL || (arr_iter->size != nbrs_iter->size)){ PyErr_SetString(PyExc_ValueError, "unable to construct iterator"); goto fail; } //go through points and call BallTree::query_ball to count neighbors pt_inc = PyArray_STRIDES(arr)[nd-1] / PyArray_DESCR(arr)->elsize; while(arr_iter->index < arr_iter->size){ BallTree_Point pt(arr, (double*)PyArray_ITER_DATA(arr_iter), pt_inc,pt_size); long int* nbrs_count = (long int*)PyArray_ITER_DATA(nbrs_iter); *nbrs_count = self->tree->query_ball(pt,r); PyArray_ITER_NEXT(arr_iter); PyArray_ITER_NEXT(nbrs_iter); } } Py_DECREF(nbrs_iter); Py_DECREF(arr_iter); Py_DECREF(arr); return nbrs; fail: Py_XDECREF(nbrs_iter); Py_XDECREF(arr_iter); Py_XDECREF(arr); Py_XDECREF(nbrs); return NULL; }
//query the ball tree. Arguments are the array of search points // and the number of nearest neighbors, k (optional) static PyObject * BallTree_query(BallTreeObject *self, PyObject *args, PyObject *kwds){ //we use goto statements : all variables should be declared up front int return_distance = 1; long int k = 1; PyObject *arg = NULL; PyObject *arr = NULL; PyObject *nbrs = NULL; PyObject *dist = NULL; PyArrayIterObject *arr_iter = NULL; PyArrayIterObject *nbrs_iter = NULL; PyArrayIterObject *dist_iter = NULL; long int* nbrs_data; double* dist_data; static char *kwlist[] = {"x", "k", "return_distance", NULL}; int nd, pt_size, pt_inc; npy_intp* dim; //parse arguments. If k is not provided, the default is 1 if(!PyArg_ParseTupleAndKeywords(args,kwds,"O|li",kwlist, &arg,&k,&return_distance)){ goto fail; } //check value of k if(k < 1){ PyErr_SetString(PyExc_ValueError, "k must be positive"); goto fail; } if(k > self->size){ PyErr_SetString(PyExc_ValueError, "k must not be greater than number of points"); goto fail; } //get the array object from the first argument arr = PyArray_FROM_OTF(arg,NPY_DOUBLE,NPY_ALIGNED); //check that the array was properly constructed if(arr==NULL){ PyErr_SetString(PyExc_ValueError, "pt must be convertable to array"); goto fail; } nd = PyArray_NDIM(arr); if(nd == 0){ PyErr_SetString(PyExc_ValueError, "pt cannot be zero-sized array"); goto fail; } pt_size = PyArray_DIM(arr,nd-1); if( pt_size != self->tree->PointSize() ){ PyErr_SetString(PyExc_ValueError, "points are incorrect dimension"); 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(arr,i); dim[nd-1] = k; nbrs = (PyObject*)PyArray_SimpleNew(nd,dim,PyArray_LONG); if(return_distance) dist = (PyObject*)PyArray_SimpleNew(nd,dim,PyArray_DOUBLE); delete[] dim; if(nbrs==NULL) goto fail; //create iterators to cycle through points nd-=1; arr_iter = (PyArrayIterObject*)PyArray_IterAllButAxis(arr,&nd); nbrs_iter = (PyArrayIterObject*)PyArray_IterAllButAxis(nbrs,&nd); if(return_distance) dist_iter = (PyArrayIterObject*)PyArray_IterAllButAxis(dist,&nd); nd+=1; if( arr_iter==NULL || nbrs_iter==NULL || (arr_iter->size != nbrs_iter->size) || (return_distance && (dist_iter==NULL || (arr_iter->size != dist_iter->size))) ){ PyErr_SetString(PyExc_ValueError, "failure constructing iterators"); goto fail; } pt_inc = PyArray_STRIDES(arr)[nd-1] / PyArray_DESCR(arr)->elsize; if( (PyArray_STRIDES(nbrs)[nd-1] != PyArray_DESCR(nbrs)->elsize ) || (return_distance && (PyArray_STRIDES(dist)[nd-1] != PyArray_DESCR(dist)->elsize )) ){ PyErr_SetString(PyExc_ValueError, "nbrs & dist not allocated as a C-array"); goto fail; } //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. if(return_distance){ while(arr_iter->index < arr_iter->size){ BallTree_Point pt(arr, (double*)PyArray_ITER_DATA(arr_iter), pt_inc,pt_size); nbrs_data = (long int*)(PyArray_ITER_DATA(nbrs_iter)); dist_data = (double*)(PyArray_ITER_DATA(dist_iter)); self->tree->query(pt,k,nbrs_data,dist_data); PyArray_ITER_NEXT(arr_iter); PyArray_ITER_NEXT(nbrs_iter); PyArray_ITER_NEXT(dist_iter); } }else{ while(arr_iter->index < arr_iter->size){ BallTree_Point pt(arr, (double*)PyArray_ITER_DATA(arr_iter), pt_inc,pt_size); nbrs_data = (long int*)(PyArray_ITER_DATA(nbrs_iter)); self->tree->query(pt,k,nbrs_data); PyArray_ITER_NEXT(arr_iter); PyArray_ITER_NEXT(nbrs_iter); } } //if only one neighbor is requested, then resize the neighbors array if(k==1){ PyArray_Dims dims; dims.ptr = PyArray_DIMS(arr); dims.len = PyArray_NDIM(arr)-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); if(return_distance){ NoneObj = PyArray_Resize( (PyArrayObject*)dist, &dims, 0, NPY_ANYORDER ); if (NoneObj == NULL){ goto fail; } Py_DECREF(NoneObj); } } if(return_distance){ Py_DECREF(arr_iter); Py_DECREF(nbrs_iter); Py_DECREF(dist_iter); Py_DECREF(arr); arr = Py_BuildValue("(OO)",dist,nbrs); Py_DECREF(nbrs); Py_DECREF(dist); return arr; }else{ Py_DECREF(arr_iter); Py_DECREF(nbrs_iter); Py_DECREF(arr); return nbrs; } fail: Py_XDECREF(arr); Py_XDECREF(nbrs); Py_XDECREF(dist); Py_XDECREF(arr_iter); Py_XDECREF(nbrs_iter); Py_XDECREF(dist_iter); return NULL; }
void joint_histogram(double* H, unsigned int clampI, unsigned int clampJ, PyArrayIterObject* iterI, const PyArrayObject* imJ_padded, const double* Tvox, int affine, int interp) { const signed short* J=(signed short*)imJ_padded->data; size_t dimJX=imJ_padded->dimensions[0]-2; size_t dimJY=imJ_padded->dimensions[1]-2; size_t dimJZ=imJ_padded->dimensions[2]-2; signed short Jnn[8]; double W[8]; signed short *bufI, *bufJnn; double *bufW; signed short i, j; size_t off; size_t u2 = imJ_padded->dimensions[2]; size_t u3 = u2+1; size_t u4 = imJ_padded->dimensions[1]*u2; size_t u5 = u4+1; size_t u6 = u4+u2; size_t u7 = u6+1; double wx, wy, wz, wxwy, wxwz, wywz; double W0, W2, W3, W4; size_t x, y, z; int nn, nx, ny, nz; double Tx, Ty, Tz; double *bufTvox = (double*)Tvox; void (*interpolate)(unsigned int, double*, unsigned int, const signed short*, const double*, int, void*); void* interp_params = NULL; rk_state rng; /* Reset the source image iterator */ PyArray_ITER_RESET(iterI); /* Make sure the iterator the iterator will update coordinate values */ UPDATE_ITERATOR_COORDS(iterI); /* Set interpolation method */ if (interp==0) interpolate = &_pv_interpolation; else if (interp>0) interpolate = &_tri_interpolation; else { /* interp < 0 */ interpolate = &_rand_interpolation; rk_seed(-interp, &rng); interp_params = (void*)(&rng); } /* Re-initialize joint histogram */ memset((void*)H, 0, clampI*clampJ*sizeof(double)); /* Looop over source voxels */ while(iterI->index < iterI->size) { /* Source voxel intensity */ bufI = (signed short*)PyArray_ITER_DATA(iterI); i = bufI[0]; /* Compute the transformed grid coordinates of current voxel */ if (affine) { /* Get voxel coordinates and apply transformation on-the-fly*/ x = iterI->coordinates[0]; y = iterI->coordinates[1]; z = iterI->coordinates[2]; _affine_transform(&Tx, &Ty, &Tz, Tvox, x, y, z); } else /* Use precomputed transformed coordinates */ bufTvox = _precomputed_transform(&Tx, &Ty, &Tz, (const double*)bufTvox); /* Test whether the current voxel is below the intensity threshold, or the transformed point is completly outside the reference grid */ if ((i>=0) && (Tx>-1) && (Tx<dimJX) && (Ty>-1) && (Ty<dimJY) && (Tz>-1) && (Tz<dimJZ)) { /* Nearest neighbor (floor coordinates in the padded image, hence +1). Notice that using the floor function doubles excetution time. FIXME: see if we can replace this with assembler instructions. */ nx = FLOOR(Tx) + 1; ny = FLOOR(Ty) + 1; nz = FLOOR(Tz) + 1; /* The convention for neighbor indexing is as follows: * * Floor slice Ceil slice * * 2----6 3----7 y * | | | | ^ * | | | | | * 0----4 1----5 ---> x */ /*** Trilinear interpolation weights. Note: wx = nnx + 1 - Tx, where nnx is the location in the NON-PADDED grid */ wx = nx - Tx; wy = ny - Ty; wz = nz - Tz; wxwy = wx*wy; wxwz = wx*wz; wywz = wy*wz; /*** Prepare buffers */ bufJnn = Jnn; bufW = W; /*** Initialize neighbor list */ off = nx*u4 + ny*u2 + nz; nn = 0; /*** Neighbor 0: (0,0,0) */ W0 = wxwy*wz; APPEND_NEIGHBOR(off, W0); /*** Neighbor 1: (0,0,1) */ APPEND_NEIGHBOR(off+1, wxwy-W0); /*** Neighbor 2: (0,1,0) */ W2 = wxwz-W0; APPEND_NEIGHBOR(off+u2, W2); /*** Neightbor 3: (0,1,1) */ W3 = wx-wxwy-W2; APPEND_NEIGHBOR(off+u3, W3); /*** Neighbor 4: (1,0,0) */ W4 = wywz-W0; APPEND_NEIGHBOR(off+u4, W4); /*** Neighbor 5: (1,0,1) */ APPEND_NEIGHBOR(off+u5, wy-wxwy-W4); /*** Neighbor 6: (1,1,0) */ APPEND_NEIGHBOR(off+u6, wz-wxwz-W4); /*** Neighbor 7: (1,1,1) */ APPEND_NEIGHBOR(off+u7, 1-W3-wy-wz+wywz); /* Update the joint histogram using the desired interpolation technique */ interpolate(i, H, clampJ, Jnn, W, nn, interp_params); } /* End of IF TRANSFORMS INSIDE */ /* Update source index */ PyArray_ITER_NEXT(iterI); } /* End of loop over voxels */ return; }
static PyObject* PyUnits_convert( PyUnits* self, PyObject* args, PyObject* kwds) { int status = 1; PyObject* input = NULL; PyArrayObject* input_arr = NULL; PyArrayObject* output_arr = NULL; PyObject* input_iter = NULL; PyObject* output_iter = NULL; double input_val; double output_val; if (!PyArg_ParseTuple(args, "O:UnitConverter.convert", &input)) { goto exit; } input_arr = (PyArrayObject*)PyArray_FromObject( input, NPY_DOUBLE, 0, NPY_MAXDIMS); if (input_arr == NULL) { goto exit; } output_arr = (PyArrayObject*)PyArray_SimpleNew( PyArray_NDIM(input_arr), PyArray_DIMS(input_arr), PyArray_DOUBLE); if (output_arr == NULL) { goto exit; } input_iter = PyArray_IterNew((PyObject*)input_arr); if (input_iter == NULL) { goto exit; } output_iter = PyArray_IterNew((PyObject*)output_arr); if (output_iter == NULL) { goto exit; } if (self->power != 1.0) { while (PyArray_ITER_NOTDONE(input_iter)) { input_val = *(double *)PyArray_ITER_DATA(input_iter); output_val = pow(self->scale*input_val + self->offset, self->power); if (errno) { PyErr_SetFromErrno(PyExc_ValueError); goto exit; } *(double *)PyArray_ITER_DATA(output_iter) = output_val; PyArray_ITER_NEXT(input_iter); PyArray_ITER_NEXT(output_iter); } } else { while (PyArray_ITER_NOTDONE(input_iter)) { input_val = *(double *)PyArray_ITER_DATA(input_iter); output_val = self->scale*input_val + self->offset; *(double *)PyArray_ITER_DATA(output_iter) = output_val; PyArray_ITER_NEXT(input_iter); PyArray_ITER_NEXT(output_iter); } } status = 0; exit: Py_XDECREF((PyObject*)input_arr); Py_XDECREF(input_iter); Py_XDECREF(output_iter); if (status) { Py_XDECREF((PyObject*)output_arr); return NULL; } return (PyObject*)output_arr; }
int joint_histogram(PyArrayObject* JH, unsigned int clampI, unsigned int clampJ, PyArrayIterObject* iterI, const PyArrayObject* imJ_padded, const PyArrayObject* Tvox, long interp) { const signed short* J=(signed short*)imJ_padded->data; size_t dimJX=imJ_padded->dimensions[0]-2; size_t dimJY=imJ_padded->dimensions[1]-2; size_t dimJZ=imJ_padded->dimensions[2]-2; signed short Jnn[8]; double W[8]; signed short *bufI, *bufJnn; double *bufW; signed short i, j; size_t off; size_t u2 = imJ_padded->dimensions[2]; size_t u3 = u2+1; size_t u4 = imJ_padded->dimensions[1]*u2; size_t u5 = u4+1; size_t u6 = u4+u2; size_t u7 = u6+1; double wx, wy, wz, wxwy, wxwz, wywz; double W0, W2, W3, W4; int nn, nx, ny, nz; double *H = (double*)PyArray_DATA(JH); double Tx, Ty, Tz; double *tvox = (double*)PyArray_DATA(Tvox); void (*interpolate)(unsigned int, double*, unsigned int, const signed short*, const double*, int, void*); void* interp_params = NULL; prng_state rng; /* Check assumptions regarding input arrays. If it fails, the function will return -1 without doing anything else. iterI : assumed to iterate over a signed short encoded, possibly non-contiguous array. imJ_padded : assumed C-contiguous (last index varies faster) & signed short encoded. H : assumed C-contiguous. Tvox : assumed C-contiguous: either a 3x4=12-sized array (or bigger) for an affine transformation or a 3xN array for a pre-computed transformation, with N equal to the size of the array corresponding to iterI (no checking done) */ if (PyArray_TYPE(iterI->ao) != NPY_SHORT) { fprintf(stderr, "Invalid type for the array iterator\n"); return -1; } if ( (!PyArray_ISCONTIGUOUS(imJ_padded)) || (!PyArray_ISCONTIGUOUS(JH)) || (!PyArray_ISCONTIGUOUS(Tvox)) ) { fprintf(stderr, "Some non-contiguous arrays\n"); return -1; } /* Reset the source image iterator */ PyArray_ITER_RESET(iterI); /* Set interpolation method */ if (interp==0) interpolate = &_pv_interpolation; else if (interp>0) interpolate = &_tri_interpolation; else { /* interp < 0 */ interpolate = &_rand_interpolation; prng_seed(-interp, &rng); interp_params = (void*)(&rng); } /* Re-initialize joint histogram */ memset((void*)H, 0, clampI*clampJ*sizeof(double)); /* Looop over source voxels */ while(iterI->index < iterI->size) { /* Source voxel intensity */ bufI = (signed short*)PyArray_ITER_DATA(iterI); i = bufI[0]; /* Compute the transformed grid coordinates of current voxel */ Tx = *tvox; tvox++; Ty = *tvox; tvox++; Tz = *tvox; tvox++; /* Test whether the current voxel is below the intensity threshold, or the transformed point is completly outside the reference grid */ if ((i>=0) && (Tx>-1) && (Tx<dimJX) && (Ty>-1) && (Ty<dimJY) && (Tz>-1) && (Tz<dimJZ)) { /* Nearest neighbor (floor coordinates in the padded image, hence +1). Notice that using the floor function doubles excetution time. FIXME: see if we can replace this with assembler instructions. */ nx = FLOOR(Tx) + 1; ny = FLOOR(Ty) + 1; nz = FLOOR(Tz) + 1; /* The convention for neighbor indexing is as follows: * * Floor slice Ceil slice * * 2----6 3----7 y * | | | | ^ * | | | | | * 0----4 1----5 ---> x */ /*** Trilinear interpolation weights. Note: wx = nnx + 1 - Tx, where nnx is the location in the NON-PADDED grid */ wx = nx - Tx; wy = ny - Ty; wz = nz - Tz; wxwy = wx*wy; wxwz = wx*wz; wywz = wy*wz; /*** Prepare buffers */ bufJnn = Jnn; bufW = W; /*** Initialize neighbor list */ off = nx*u4 + ny*u2 + nz; nn = 0; /*** Neighbor 0: (0,0,0) */ W0 = wxwy*wz; APPEND_NEIGHBOR(off, W0); /*** Neighbor 1: (0,0,1) */ APPEND_NEIGHBOR(off+1, wxwy-W0); /*** Neighbor 2: (0,1,0) */ W2 = wxwz-W0; APPEND_NEIGHBOR(off+u2, W2); /*** Neightbor 3: (0,1,1) */ W3 = wx-wxwy-W2; APPEND_NEIGHBOR(off+u3, W3); /*** Neighbor 4: (1,0,0) */ W4 = wywz-W0; APPEND_NEIGHBOR(off+u4, W4); /*** Neighbor 5: (1,0,1) */ APPEND_NEIGHBOR(off+u5, wy-wxwy-W4); /*** Neighbor 6: (1,1,0) */ APPEND_NEIGHBOR(off+u6, wz-wxwz-W4); /*** Neighbor 7: (1,1,1) */ APPEND_NEIGHBOR(off+u7, 1-W3-wy-wz+wywz); /* Update the joint histogram using the desired interpolation technique */ interpolate(i, H, clampJ, Jnn, W, nn, interp_params); } /* End of IF TRANSFORMS INSIDE */ /* Update source index */ PyArray_ITER_NEXT(iterI); } /* End of loop over voxels */ return 0; }