// the data should be FLOAT32 and should be ensured in the wrapper static PyObject *interp3(PyObject *self, PyObject *args) { PyArrayObject *volume, *result, *C, *R, *S; float *pr, *pc, *ps; float *pvol, *pvc; int xdim, ydim, zdim; // We expect 4 arguments of the PyArray_Type if(!PyArg_ParseTuple(args, "O!O!O!O!", &PyArray_Type, &volume, &PyArray_Type, &R, &PyArray_Type, &C, &PyArray_Type, &S)) return NULL; if ( NULL == volume ) return NULL; if ( NULL == C ) return NULL; if ( NULL == R ) return NULL; if ( NULL == S ) return NULL; // result matrix is the same size as C and is float result = (PyArrayObject*) PyArray_ZEROS(PyArray_NDIM(C), C->dimensions, NPY_FLOAT, 0); // This is for reference counting ( I think ) PyArray_FLAGS(result) |= NPY_OWNDATA; // massive use of iterators to progress through the data PyArrayIterObject *itr_v, *itr_r, *itr_c, *itr_s; itr_v = (PyArrayIterObject *) PyArray_IterNew(result); itr_r = (PyArrayIterObject *) PyArray_IterNew(R); itr_c = (PyArrayIterObject *) PyArray_IterNew(C); itr_s = (PyArrayIterObject *) PyArray_IterNew(S); pvol = (float *)PyArray_DATA(volume); xdim = PyArray_DIM(volume, 0); ydim = PyArray_DIM(volume, 1); zdim = PyArray_DIM(volume, 2); //printf("%f\n", pvol[4*20*30 + 11*30 + 15]); while(PyArray_ITER_NOTDONE(itr_v)) { pvc = (float *) PyArray_ITER_DATA(itr_v); pr = (float *) PyArray_ITER_DATA(itr_r); pc = (float *) PyArray_ITER_DATA(itr_c); ps = (float *) PyArray_ITER_DATA(itr_s); // The order is weird because the tricubic code below is // for Fortran ordering. Note that the xdim changes fast in // the code, whereas the rightmost dim should change fast // in C multidimensional arrays. *pvc = TriCubic(*ps, *pc, *pr, pvol, zdim, ydim, xdim); PyArray_ITER_NEXT(itr_v); PyArray_ITER_NEXT(itr_r); PyArray_ITER_NEXT(itr_c); PyArray_ITER_NEXT(itr_s); } return result; }
/* wrapped cosine function */ static PyObject* cos_func_np(PyObject* self, PyObject* args) { PyArrayObject *in_array; PyObject *out_array; PyArrayIterObject *in_iter; PyArrayIterObject *out_iter; /* parse single numpy array argument */ if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &in_array)) return NULL; /* construct the output array, like the input array */ out_array = PyArray_NewLikeArray(in_array, NPY_ANYORDER, NULL, 0); if (out_array == NULL) return NULL; /* create the iterators */ /* TODO: this iterator API is deprecated since 1.6 * replace in favour of the new NpyIter API */ in_iter = (PyArrayIterObject *)PyArray_IterNew((PyObject*)in_array); out_iter = (PyArrayIterObject *)PyArray_IterNew(out_array); if (in_iter == NULL || out_iter == NULL) goto fail; /* iterate over the arrays */ while (in_iter->index < in_iter->size && out_iter->index < out_iter->size) { /* get the datapointers */ double * in_dataptr = (double *)in_iter->dataptr; double * out_dataptr = (double *)out_iter->dataptr; /* cosine of input into output */ *out_dataptr = cos(*in_dataptr); /* update the iterator */ PyArray_ITER_NEXT(in_iter); PyArray_ITER_NEXT(out_iter); } /* clean up and return the result */ Py_DECREF(in_iter); Py_DECREF(out_iter); Py_INCREF(out_array); return out_array; /* in case bad things happen */ fail: Py_XDECREF(out_array); Py_XDECREF(in_iter); Py_XDECREF(out_iter); return NULL; }
void local_histogram(double* H, unsigned int clamp, PyArrayIterObject* iter, const unsigned int* size) { PyArrayObject *block, *im = iter->ao; PyArrayIterObject* block_iter; unsigned int i, left, right, center, halfsize, dim, offset=0; npy_intp block_dims[3]; UPDATE_ITERATOR_COORDS(iter); /* Compute block corners */ for (i=0; i<3; i++) { center = iter->coordinates[i]; halfsize = size[i]/2; dim = PyArray_DIM(im, i); /* Left handside corner */ if (center<halfsize) left = 0; else left = center-halfsize; /* Right handside corner (plus one)*/ right = center+halfsize+1; if (right>dim) right = dim; /* Block properties */ offset += left*PyArray_STRIDE(im, i); block_dims[i] = right-left; } /* Create the block as a vew and the block iterator */ block = (PyArrayObject*)PyArray_New(&PyArray_Type, 3, block_dims, PyArray_TYPE(im), PyArray_STRIDES(im), (void*)(PyArray_DATA(im)+offset), PyArray_ITEMSIZE(im), NPY_BEHAVED, NULL); block_iter = (PyArrayIterObject*)PyArray_IterNew((PyObject*)block); /* Compute block histogram */ histogram(H, clamp, block_iter); /* Free memory */ Py_XDECREF(block_iter); Py_XDECREF(block); return; }
void allstats_ubyte(PyObject *inputarray, stats *result) { PyObject *iter; npy_ubyte *ptr; iter = PyArray_IterNew(inputarray); while (PyArray_ITER_NOTDONE(iter)) { ptr = (npy_ubyte *)PyArray_ITER_DATA(iter); updateStats(result, (double) (*ptr)); PyArray_ITER_NEXT(iter); } Py_XDECREF(iter); }
/* 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; }
/* Array evaluates as "TRUE" if any of the elements are non-zero*/ static int array_any_nonzero(PyArrayObject *arr) { npy_intp counter; PyArrayIterObject *it; npy_bool anyTRUE = NPY_FALSE; it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr); if (it == NULL) { return anyTRUE; } counter = it->size; while (counter--) { if (PyArray_DESCR(arr)->f->nonzero(it->dataptr, arr)) { anyTRUE = NPY_TRUE; break; } PyArray_ITER_NEXT(it); } Py_DECREF(it); return anyTRUE; }
static PyObject* test_neighborhood_iterator_oob(PyObject* NPY_UNUSED(self), PyObject* args) { PyObject *x, *out, *b1, *b2; PyArrayObject *ax; PyArrayIterObject *itx; int i, typenum, mode1, mode2, st; npy_intp bounds[NPY_MAXDIMS*2]; PyArrayNeighborhoodIterObject *niterx1, *niterx2; if (!PyArg_ParseTuple(args, "OOiOi", &x, &b1, &mode1, &b2, &mode2)) { return NULL; } if (!PySequence_Check(b1) || !PySequence_Check(b2)) { return NULL; } typenum = PyArray_ObjectType(x, 0); ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10); if (ax == NULL) { return NULL; } if (PySequence_Size(b1) != 2 * PyArray_NDIM(ax)) { PyErr_SetString(PyExc_ValueError, "bounds sequence 1 size not compatible with x input"); goto clean_ax; } if (PySequence_Size(b2) != 2 * PyArray_NDIM(ax)) { PyErr_SetString(PyExc_ValueError, "bounds sequence 2 size not compatible with x input"); goto clean_ax; } out = PyList_New(0); if (out == NULL) { goto clean_ax; } itx = (PyArrayIterObject*)PyArray_IterNew(x); if (itx == NULL) { goto clean_out; } /* Compute boundaries for the neighborhood iterator */ for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) { PyObject* bound; bound = PySequence_GetItem(b1, i); if (bounds == NULL) { goto clean_itx; } if (!PyInt_Check(bound)) { PyErr_SetString(PyExc_ValueError, "bound not long"); Py_DECREF(bound); goto clean_itx; } bounds[i] = PyInt_AsLong(bound); Py_DECREF(bound); } /* Create the neighborhood iterator */ niterx1 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew( (PyArrayIterObject*)itx, bounds, mode1, NULL); if (niterx1 == NULL) { goto clean_out; } for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) { PyObject* bound; bound = PySequence_GetItem(b2, i); if (bounds == NULL) { goto clean_itx; } if (!PyInt_Check(bound)) { PyErr_SetString(PyExc_ValueError, "bound not long"); Py_DECREF(bound); goto clean_itx; } bounds[i] = PyInt_AsLong(bound); Py_DECREF(bound); } niterx2 = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew( (PyArrayIterObject*)niterx1, bounds, mode2, NULL); if (niterx1 == NULL) { goto clean_niterx1; } switch (typenum) { case NPY_DOUBLE: st = copy_double_double(niterx1, niterx2, bounds, &out); break; default: PyErr_SetString(PyExc_ValueError, "Type not supported"); goto clean_niterx2; } if (st) { goto clean_niterx2; } Py_DECREF(niterx2); Py_DECREF(niterx1); Py_DECREF(itx); Py_DECREF(ax); return out; clean_niterx2: Py_DECREF(niterx2); clean_niterx1: Py_DECREF(niterx1); clean_itx: Py_DECREF(itx); clean_out: Py_DECREF(out); clean_ax: Py_DECREF(ax); return NULL; }
static PyObject* test_neighborhood_iterator(PyObject* NPY_UNUSED(self), PyObject* args) { PyObject *x, *fill, *out, *b; PyArrayObject *ax, *afill; PyArrayIterObject *itx; int i, typenum, mode, st; npy_intp bounds[NPY_MAXDIMS*2]; PyArrayNeighborhoodIterObject *niterx; if (!PyArg_ParseTuple(args, "OOOi", &x, &b, &fill, &mode)) { return NULL; } if (!PySequence_Check(b)) { return NULL; } typenum = PyArray_ObjectType(x, 0); typenum = PyArray_ObjectType(fill, typenum); ax = (PyArrayObject*)PyArray_FromObject(x, typenum, 1, 10); if (ax == NULL) { return NULL; } if (PySequence_Size(b) != 2 * PyArray_NDIM(ax)) { PyErr_SetString(PyExc_ValueError, "bounds sequence size not compatible with x input"); goto clean_ax; } out = PyList_New(0); if (out == NULL) { goto clean_ax; } itx = (PyArrayIterObject*)PyArray_IterNew(x); if (itx == NULL) { goto clean_out; } /* Compute boundaries for the neighborhood iterator */ for (i = 0; i < 2 * PyArray_NDIM(ax); ++i) { PyObject* bound; bound = PySequence_GetItem(b, i); if (bounds == NULL) { goto clean_itx; } if (!PyInt_Check(bound)) { PyErr_SetString(PyExc_ValueError, "bound not long"); Py_DECREF(bound); goto clean_itx; } bounds[i] = PyInt_AsLong(bound); Py_DECREF(bound); } /* Create the neighborhood iterator */ afill = NULL; if (mode == NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING) { afill = (PyArrayObject *)PyArray_FromObject(fill, typenum, 0, 0); if (afill == NULL) { goto clean_itx; } } niterx = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew( (PyArrayIterObject*)itx, bounds, mode, afill); if (niterx == NULL) { goto clean_afill; } switch (typenum) { case NPY_OBJECT: st = copy_object(itx, niterx, bounds, &out); break; case NPY_INT: st = copy_int(itx, niterx, bounds, &out); break; case NPY_DOUBLE: st = copy_double(itx, niterx, bounds, &out); break; default: PyErr_SetString(PyExc_ValueError, "Type not supported"); goto clean_niterx; } if (st) { goto clean_niterx; } Py_DECREF(niterx); Py_XDECREF(afill); Py_DECREF(itx); Py_DECREF(ax); return out; clean_niterx: Py_DECREF(niterx); clean_afill: Py_XDECREF(afill); clean_itx: Py_DECREF(itx); clean_out: Py_DECREF(out); clean_ax: Py_DECREF(ax); return NULL; }
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; }
//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; }
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; }
PyObject *func_PyArray_IterNew(PyArrayObject *arr) { return PyArray_IterNew(reinterpret_cast<PyObject *>(arr)); }
static PyObject *AscanfCall( ascanf_Function *af, PyObject *arglist, long repeats, int asarray, int deref, PAO_Options *opts, char *caller ) { int fargs= 0, aargc= 0, volatile_args= 0; double result= 0, *aresult=NULL; static double *AARGS= NULL; static char *ATYPE= NULL; static ascanf_Function *LAF= NULL; static size_t LAFN= 0; double *aargs= NULL; char *atype= NULL; ascanf_Function *laf= NULL, *af_array= NULL; size_t lafN= 0; PyObject *ret= NULL; static ascanf_Function *nDindex= NULL; int aV = ascanf_verbose; if( arglist ){ if( PyList_Check(arglist) ){ if( !(arglist= PyList_AsTuple(arglist)) ){ PyErr_SetString( XG_PythonError, "unexpected failure converting argument list to tuple" ); // PyErr_SetString( PyExc_RuntimeError, "unexpected failure converting argument list to tuple" ); return(NULL); } } if( !PyTuple_Check(arglist) ){ PyErr_SetString( XG_PythonError, // PyExc_SyntaxError, "arguments to the ascanf method should be passed as a tuple or list\n" " NB: a 1-element tuple is specified as (value , ) !!\n" ); return(NULL); } aargc= PyTuple_Size(arglist); } else{ aargc= 0; } if( !af ){ goto PAC_ESCAPE; } if( af->type!= _ascanf_procedure && af->Nargs> 0 ){ /* procedures can have as many arguments as MaxArguments, which is probably too much to allocate here. \ However, we know how many arguments a function can get (if all's well...), and we can assure that \ it will have space for those arguments \ 20061015: unless it also has MaxArguments, i.e. Nargs<0 ... */ fargs= af->Nargs; } { long n= (aargc+fargs+1)*2; if( opts->call_reentrant ){ lafN= n; aargs= (double*) calloc( lafN, sizeof(double) ); atype= (char*) calloc( lafN, sizeof(char) ); if( !aargs || !atype || !(laf= (ascanf_Function*) calloc( lafN, sizeof(ascanf_Function) )) ){ PyErr_NoMemory(); return(NULL); } } else{ if( !LAF ){ LAFN= n; AARGS= (double*) calloc( LAFN, sizeof(double) ); ATYPE= (char*) calloc( LAFN, sizeof(char) ); if( !AARGS || !ATYPE || !(LAF= (ascanf_Function*) calloc( LAFN, sizeof(ascanf_Function) )) ){ PyErr_NoMemory(); return(NULL); } } else if( n> LAFN ){ AARGS= (double*) realloc( AARGS, n * sizeof(double) ); ATYPE= (char*) realloc( ATYPE, n * sizeof(char) ); if( !AARGS || !ATYPE || !(LAF= (ascanf_Function*) realloc( LAF, n * sizeof(ascanf_Function) )) ){ PyErr_NoMemory(); return(NULL); } else{ for( ; LAFN< n; LAFN++ ){ AARGS[LAFN]= 0; memset( &LAF[LAFN], 0, sizeof(ascanf_Function) ); } } LAFN= n; } aargs= AARGS; atype= ATYPE; laf= LAF; lafN= LAFN; } } { int a= 0, i; if( opts->verbose > 1 ){ ascanf_verbose = 1; } if( af->type== _ascanf_array ){ if( !nDindex ){ nDindex= Py_getNamedAscanfVariable("nDindex"); } if( nDindex ){ af_array= af; aargs[a]= (af->own_address)? af->own_address : take_ascanf_address(af); af= nDindex; a+= 1; } } for( i= 0; i< aargc; i++, a++ ){ PyObject *arg= PyTuple_GetItem(arglist, i); ascanf_Function *aaf; if( PyFloat_Check(arg) ){ aargs[a]= PyFloat_AsDouble(arg); atype[a]= 1; } #ifdef USE_COBJ else if( PyCObject_Check(arg) ){ if( (aaf= PyCObject_AsVoidPtr(arg)) && (PyCObject_GetDesc(arg)== aaf->function) ){ aargs[a]= (aaf->own_address)? aaf->own_address : take_ascanf_address(aaf); atype[a]= 2; } else{ PyErr_SetString( XG_PythonError, "unsupported PyCObject type does not contain ascanf pointer" ); // PyErr_SetString( PyExc_TypeError, "unsupported PyCObject type does not contain ascanf pointer" ); goto PAC_ESCAPE; } } #else else if( PyAscanfObject_Check(arg) ){ if( (aaf= PyAscanfObject_AsAscanfFunction(arg)) ){ aargs[a]= (aaf->own_address)? aaf->own_address : take_ascanf_address(aaf); atype[a]= 2; } else{ PyErr_SetString( XG_PythonError, "invalid PyAscanfObject type does not contain ascanf pointer" ); // PyErr_SetString( PyExc_TypeError, "invalid PyAscanfObject type does not contain ascanf pointer" ); goto PAC_ESCAPE; } } #endif else if( PyInt_Check(arg) || PyLong_Check(arg) ){ aargs[a]= PyInt_AsLong(arg); atype[a]= 3; } else if( PyBytes_Check(arg) #ifdef IS_PY3K || PyUnicode_Check(arg) #endif ){ static char *AFname= "AscanfCall-Static-StringPointer"; ascanf_Function *saf= &laf[a]; memset( saf, 0, sizeof(ascanf_Function) ); saf->type= _ascanf_variable; saf->function= ascanf_Variable; if( !(saf->name= PyObject_Name(arg)) ){ saf->name= XGstrdup(AFname); } saf->is_address= saf->take_address= True; saf->is_usage= saf->take_usage= True; saf->internal= True; #ifdef IS_PY3K if( PyUnicode_Check(arg) ){ PyObject *bytes = NULL; char *str = NULL; PYUNIC_TOSTRING( arg, bytes, str ); if( !str ){ if( bytes ){ Py_XDECREF(bytes); } goto PAC_ESCAPE; } saf->usage= parse_codes( XGstrdup(str) ); Py_XDECREF(bytes); } else #endif { saf->usage= parse_codes( XGstrdup( PyBytes_AsString(arg) ) ); } aargs[a]= take_ascanf_address(saf); atype[a]= 4; if( i && af_array ){ volatile_args+= 1; } } else if( PyArray_Check(arg) || PyTuple_Check(arg) || PyList_Check(arg) ){ static char *AFname= "AscanfCall-Static-ArrayPointer"; ascanf_Function *saf= &laf[a]; PyArrayObject *parray; atype[a]= 6; if( PyList_Check(arg) ){ if( !(arg= PyList_AsTuple(arg)) ){ PyErr_SetString( XG_PythonError, "unexpected failure converting argument to tuple" ); // PyErr_SetString( PyExc_RuntimeError, "unexpected failure converting argument to tuple" ); goto PAC_ESCAPE; /* return(NULL); */ } else{ atype[a]= 5; } } memset( saf, 0, sizeof(ascanf_Function) ); saf->type= _ascanf_array; saf->function= ascanf_Variable; if( !(saf->name= PyObject_Name(arg)) ){ saf->name= XGstrdup(AFname); } saf->is_address= saf->take_address= True; saf->internal= True; if( a ){ saf->car= &laf[a-1]; } else{ saf->car= &laf[lafN-1]; } if( PyTuple_Check(arg) ){ saf->N= PyTuple_Size(arg); parray= NULL; } else{ saf->N= PyArray_Size(arg); parray= (PyArrayObject*) arg; atype[a]= 7; } if( (saf->array= (double*) malloc( saf->N * sizeof(double) )) ){ int j; if( parray ){ PyArrayObject* xd= NULL; double *PyArrayBuf= NULL; PyArrayIterObject *it; if( (xd = (PyArrayObject*) PyArray_ContiguousFromObject( (PyObject*) arg, PyArray_DOUBLE, 0, 0 )) ){ PyArrayBuf= (double*)PyArray_DATA(xd); /* size would be N*sizeof(double) */ } else{ it= (PyArrayIterObject*) PyArray_IterNew(arg); } if( PyArrayBuf ){ // for( j= 0; j< saf->N; j++ ){ // /* 20061016: indices used to be i?!?! */ // saf->array[j]= PyArrayBuf[j]; // } if( saf->array != PyArrayBuf ){ memcpy( saf->array, PyArrayBuf, saf->N * sizeof(double) ); } } else{ for( j= 0; j< saf->N; j++ ){ saf->array[j]= PyFloat_AsDouble( PyArray_DESCR(parray)->f->getitem( it->dataptr, arg) ); PyArray_ITER_NEXT(it); } } if( xd ){ Py_XDECREF(xd); } else{ Py_DECREF(it); } } else{ for( j= 0; j< saf->N; j++ ){ saf->array[j]= PyFloat_AsDouble( PyTuple_GetItem(arg,j) ); } } aargs[a]= take_ascanf_address(saf); if( i && af_array ){ volatile_args+= 1; } } else{ PyErr_NoMemory(); goto PAC_ESCAPE; } } #if 0 else{ PyErr_SetString( XG_PythonError, "arguments should be scalars, strings, arrays or ascanf pointers" ); // PyErr_SetString( PyExc_SyntaxError, "arguments should be scalars, strings, arrays or ascanf pointers" ); goto PAC_ESCAPE; } #else else{ static char *AFname= "AscanfCall-Static-PyObject"; ascanf_Function *saf= &laf[a]; memset( saf, 0, sizeof(ascanf_Function) ); saf->function= ascanf_Variable; saf->internal= True; saf= make_ascanf_python_object( saf, arg, "AscanfCall" ); if( !saf->name ){ if( saf->PyObject_Name ){ saf->name= XGstrdup(saf->PyObject_Name); } else{ saf->name= XGstrdup(AFname); } } aargs[a]= take_ascanf_address(saf); atype[a]= 4; if( i && af_array ){ volatile_args+= 1; } } #endif } if( a> aargc ){ aargc= a; } }
static PyObject *frputvect(PyObject *self, PyObject *args, PyObject *keywds) { FrFile *oFile; FrameH *frame; FrProcData *proc; FrAdcData *adc; FrSimData *sim; FrVect *vect; int verbose=0, nData, nBits, type, subType, arrayType; double dx, sampleRate, start; char blank[] = ""; char *filename=NULL, *history=NULL; char channel[MAX_STR_LEN], x_unit[MAX_STR_LEN], y_unit[MAX_STR_LEN], kind[MAX_STR_LEN]; PyObject *temp; char msg[MAX_STR_LEN]; PyObject *channellist, *channellist_iter, *framedict, *array; PyArrayIterObject *arrayIter; PyArray_Descr *temp_descr; static char *kwlist[] = {"filename", "channellist", "history", "verbose", NULL}; /*--------------- unpack arguments --------------------*/ verbose = 0; /* The | in the format string indicates the next arguments are optional. They are simply not assigned anything. */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "sO|si", kwlist, &filename, &channellist, &history, &verbose)) { Py_RETURN_NONE; } FrLibSetLvl(verbose); if (history == NULL) { history = blank; } /*-------- create frames, create vectors, and fill them. ------*/ // Channel-list must be any type of sequence if (!PySequence_Check(channellist)) { PyErr_SetNone(PyExc_TypeError); return NULL; } // Get channel name from first dictionary framedict = PySequence_GetItem(channellist, (Py_ssize_t)0); if (framedict == NULL) { PyErr_SetString(PyExc_ValueError, "channellist is empty!"); return NULL; } PyDict_ExtractString(channel, framedict, "name"); Py_XDECREF(framedict); if (PyErr_Occurred()) {return NULL;} if (verbose > 0) { printf("Creating frame %s...\n", channel); } frame = FrameNew(channel); if (frame == NULL) { snprintf(msg, MAX_STR_LEN, "FrameNew failed (%s)", FrErrorGetHistory()); PyErr_SetString(PyExc_FrError, msg); return NULL; } if (verbose > 0) { printf("Now iterating...\n"); } // Iterators allow one to deal with non-contiguous arrays channellist_iter = PyObject_GetIter(channellist); arrayIter = NULL; while ((framedict = PyIter_Next(channellist_iter))) { if (verbose > 0) { printf("In loop...\n"); } // Extract quantities from dict -- all borrowed references PyDict_ExtractString(channel, framedict, "name"); CHECK_ERROR; start = PyDict_ExtractDouble(framedict, "start"); CHECK_ERROR; dx = PyDict_ExtractDouble(framedict, "dx"); CHECK_ERROR; array = PyDict_GetItemString(framedict, "data"); if (!PyArray_Check(array)) { snprintf(msg, MAX_STR_LEN, "data is not an array"); PyErr_SetString(PyExc_TypeError, msg); } CHECK_ERROR; nData = PyArray_SIZE(array); nBits = PyArray_ITEMSIZE(array)*8; arrayType = PyArray_TYPE(array); // kind, x_unit, y_unit, type, and subType have default values temp = PyDict_GetItemString(framedict, "kind"); if (temp != NULL) {strncpy(kind, PyString_AsString(temp), MAX_STR_LEN);} else {snprintf(kind, MAX_STR_LEN, "PROC");} temp = PyDict_GetItemString(framedict, "x_unit"); if (temp != NULL) {strncpy(x_unit, PyString_AsString(temp), MAX_STR_LEN);} else {strncpy(x_unit, blank, MAX_STR_LEN);} temp = PyDict_GetItemString(framedict, "y_unit"); if (temp != NULL) {strncpy(y_unit, PyString_AsString(temp), MAX_STR_LEN);} else {strncpy(y_unit, blank, MAX_STR_LEN);} temp = PyDict_GetItemString(framedict, "type"); if (temp != NULL) {type = (int)PyInt_AsLong(temp);} else {type = 1;} temp = PyDict_GetItemString(framedict, "subType"); if (temp != NULL) {subType = (int)PyInt_AsLong(temp);} else {subType = 0;} // check for errors CHECK_ERROR; if (dx <= 0 || array == NULL || nData==0) { temp = PyObject_Str(framedict); snprintf(msg, MAX_STR_LEN, "Input dictionary contents: %s", PyString_AsString(temp)); Py_XDECREF(temp); FrameFree(frame); Py_XDECREF(framedict); Py_XDECREF(channellist_iter); PyErr_SetString(PyExc_ValueError, msg); return NULL; } if (verbose > 0) { printf("type = %d, subType = %d, start = %f, dx = %f\n", type, subType, start, dx); } sampleRate = 1./dx; if (verbose > 0) { printf("Now copying data to vector...\n"); } // Create empty vector (-typecode ==> empty) with metadata, // then copy data to vector vect = NULL; arrayIter = (PyArrayIterObject *)PyArray_IterNew(array); if(arrayType == NPY_INT16) { vect = FrVectNew1D(channel,-FR_VECT_2S,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataS[arrayIter->index] = *((npy_int16 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_INT32) { vect = FrVectNew1D(channel,-FR_VECT_4S,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataI[arrayIter->index] = *((npy_int32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_INT64) { vect = FrVectNew1D(channel,-FR_VECT_8S,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataL[arrayIter->index] = *((npy_int64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT8) { vect = FrVectNew1D(channel,-FR_VECT_1U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataU[arrayIter->index] = *((npy_uint8 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT16) { vect = FrVectNew1D(channel,-FR_VECT_2U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataUS[arrayIter->index] = *((npy_uint16 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT32) { vect = FrVectNew1D(channel,-FR_VECT_4U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataUI[arrayIter->index] = *((npy_uint32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_UINT64) { vect = FrVectNew1D(channel,-FR_VECT_8U,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataUL[arrayIter->index] = *((npy_uint64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_FLOAT32) { vect = FrVectNew1D(channel,-FR_VECT_4R,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataF[arrayIter->index] = *((npy_float32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} else if(arrayType == NPY_FLOAT64) { vect = FrVectNew1D(channel,-FR_VECT_8R,nData,dx,x_unit,y_unit); while (arrayIter->index < arrayIter->size) { vect->dataD[arrayIter->index] = *((npy_float64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);}} /* FrVects don't have complex pointers. Numpy stores complex numbers in the same way, but we have to trick it into giving us a (real) float pointer. */ else if(arrayType == NPY_COMPLEX64) { vect = FrVectNew1D(channel,-FR_VECT_8C,nData,dx,x_unit,y_unit); temp_descr = PyArray_DescrFromType(NPY_FLOAT32); temp = PyArray_View((PyArrayObject *)array, temp_descr, NULL); Py_XDECREF(temp_descr); Py_XDECREF(arrayIter); arrayIter = (PyArrayIterObject *)PyArray_IterNew(temp); while (arrayIter->index < arrayIter->size) { vect->dataF[arrayIter->index] = *((npy_float32 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);} Py_XDECREF(temp);} else if(arrayType == NPY_COMPLEX128) { vect = FrVectNew1D(channel,-FR_VECT_16C,nData,dx,x_unit,y_unit); temp_descr = PyArray_DescrFromType(NPY_FLOAT64); temp = PyArray_View((PyArrayObject *)array, temp_descr, NULL); Py_XDECREF(temp_descr); Py_XDECREF(arrayIter); arrayIter = (PyArrayIterObject *)PyArray_IterNew(temp); while (arrayIter->index < arrayIter->size) { vect->dataD[arrayIter->index] = *((npy_float64 *)arrayIter->dataptr); PyArray_ITER_NEXT(arrayIter);} Py_XDECREF(temp);} else PyErr_SetString(PyExc_TypeError, msg); if (PyErr_Occurred()) { if (vect != NULL) FrVectFree(vect); FrameFree(frame); Py_XDECREF(framedict); Py_XDECREF(channellist_iter); Py_XDECREF(arrayIter); return NULL; } if (verbose > 0) { printf("Done copying...\n"); FrameDump(frame, stdout, 6); } // Add Fr*Data to frame and attach vector to Fr*Data if (strncmp(kind, "PROC", MAX_STR_LEN)==0) { proc = FrProcDataNew(frame, channel, sampleRate, 1, nBits); FrVectFree(proc->data); proc->data = vect; proc->type = type; proc->subType = subType; frame->GTimeS = (npy_uint32)start; frame->GTimeN = (npy_uint32)((start-(frame->GTimeS))*1e9); if (type==1) { // time series proc->tRange = nData*dx; frame->dt = nData*dx; } else if (type==2) { // frequency series proc->fRange = nData*dx; } } else if (strncmp(kind, "ADC", MAX_STR_LEN)==0) { adc = FrAdcDataNew(frame, channel, sampleRate, 1, nBits); FrVectFree(adc->data); adc->data = vect; frame->dt = nData*dx; frame->GTimeS = (npy_uint32)start; frame->GTimeN = (npy_uint32)((start-(frame->GTimeS))*1e9); } else {// Already tested that kind is one of these strings above sim = FrSimDataNew(frame, channel, sampleRate, 1, nBits); FrVectFree(sim->data); sim->data = vect; frame->dt = nData*dx; frame->GTimeS = (npy_uint32)start; frame->GTimeN = (npy_uint32)((start-(frame->GTimeS))*1e9); } if (verbose > 0) { printf("Attached vect to frame.\n"); } // Clean up (all python objects in loop should be borrowed references) Py_XDECREF(framedict); Py_XDECREF(arrayIter); } // end iteration over channellist Py_XDECREF(channellist_iter); // At this point, there should be no Python references left! /*------------- Write file -----------------------------*/ oFile = FrFileONewH(filename, 1, history); // 1 ==> gzip contents if (oFile == NULL) { snprintf(msg, MAX_STR_LEN, "%s\n", FrErrorGetHistory()); PyErr_SetString(PyExc_FrError, msg); FrFileOEnd(oFile); return NULL; } if (FrameWrite(frame, oFile) != FR_OK) { snprintf(msg, MAX_STR_LEN, "%s\n", FrErrorGetHistory()); PyErr_SetString(PyExc_FrError, msg); FrFileOEnd(oFile); return NULL; } /* The FrFile owns data and vector memory. Do not free them separately. */ FrFileOEnd(oFile); FrameFree(frame); Py_RETURN_NONE; };