// create a new NDF (simple) structure static PyObject* pyndf_new(NDF *self, PyObject *args) { // use ultracam defaults const char *ftype = "_REAL"; int ndim; PyObject* lb; PyObject* ub; if(!PyArg_ParseTuple(args, "siOO:pyndf_new", &ftype, &ndim, &lb, &ub)) return NULL; if(ndim < 0 || ndim > 7) return NULL; // TODO: check for ftype here int status = SAI__OK; PyArrayObject* lower = (PyArrayObject*) PyArray_FROM_OTF(lb, NPY_UINT, NPY_IN_ARRAY | NPY_FORCECAST); PyArrayObject* upper = (PyArrayObject*) PyArray_FROM_OTF(ub, NPY_UINT, NPY_IN_ARRAY | NPY_FORCECAST); if (!lower || !upper) return NULL; if(PyArray_SIZE(lower) != ndim || PyArray_SIZE(upper) != ndim) return NULL; errBegin(&status); ndfNew(ftype,ndim,(int*)PyArray_DATA(lower),(int*)PyArray_DATA(upper),&self->_place,&self->_ndfid,&status); // placeholder annulled by this routine Py_DECREF(lower); Py_DECREF(upper); if (raiseNDFException(&status)) return NULL; Py_RETURN_NONE; }
static PyObject * averageDirectionIndexed(PyObject *dummy, PyObject *args) { PyObject *arg1=NULL, *arg2=NULL; PyObject *arr1=NULL, *arr2=NULL; int *ind; float *vec, tol; if (!PyArg_ParseTuple(args, "OOf", &arg1, &arg2, &tol)) return NULL; arr1 = PyArray_FROM_OTF(arg1, NPY_FLOAT, NPY_INOUT_ARRAY); if (arr1 == NULL) return NULL; arr2 = PyArray_FROM_OTF(arg2, NPY_INT, NPY_INOUT_ARRAY); if (arr2 == NULL) goto fail; npy_intp * dims; int nvec,ndim; dims = PyArray_DIMS(arg1); ndim = dims[1]; dims = PyArray_DIMS(arg2); nvec = dims[0]; vec = (float *)PyArray_DATA(arr1); ind = (int *)PyArray_DATA(arr2); average_direction_indexed(vec,ndim,ind,nvec,tol); /* Clean up and return */ Py_DECREF(arr1); Py_DECREF(arr2); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(arr1); Py_XDECREF(arr2); return NULL; }
//http://www.tutorialspoint.com/python/python_further_extensions.htm //https://docs.python.org/2/extending/extending.html //http://dan.iel.fm/posts/python-c-extensions/ static PyObject* pyspectro_HelloWorld(PyObject* self, PyObject* args) { printf("compiled on %s %s\n", __DATE__, __TIME__); printf("Then Ben said something"); PyObject *doublearr_obj, *intarr_obj; if(PyArg_ParseTuple(args, "OO", &doublearr_obj, &intarr_obj) == 0) { printf("error!\n"); return NULL; } PyObject* doublearr = PyArray_FROM_OTF(doublearr_obj, NPY_DOUBLE, NPY_OUT_ARRAY); PyObject* intarr = PyArray_FROM_OTF(intarr_obj, NPY_UINT8, NPY_OUT_ARRAY); if(!doublearr || !intarr) { Py_XDECREF(doublearr); Py_XDECREF(intarr); return NULL; } int dN = (int)PyArray_DIM(doublearr, 0); int iN = (int)PyArray_DIM(intarr, 0); double* c_doublearr = (double*)PyArray_DATA(doublearr); unsigned char* c_intarr = (unsigned char*)PyArray_DATA(intarr); if(c_intarr[0] == 1) { PyErr_SetString(PyExc_IOError, "hello"); return NULL; } for(int i = 0; i < dN; i++) c_doublearr[i] = dN - i; for(int i = 0; i < iN; i++) c_intarr[i] = dN - i; Py_DECREF(doublearr); Py_DECREF(intarr); Py_RETURN_NONE; }
static PyObject* dtw_extension(PyObject *dummy, PyObject *args) { PyObject *arg1 = NULL; PyObject *arr1 = NULL; PyObject *arg2 = NULL; PyObject *arr2 = NULL; if (!PyArg_ParseTuple(args, "OO", &arg1, &arg2)) { return NULL; } arr1 = PyArray_FROM_OTF(arg1, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (arr1 == NULL) { return NULL; } arr2 = PyArray_FROM_OTF(arg2, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (arr2 == NULL) { return NULL; } // Number of dimensions int nd1 = PyArray_NDIM((PyArrayObject*)arr1); int arr_type1 = PyArray_TYPE((PyArrayObject*)arr1); npy_intp *dims1 = PyArray_DIMS((PyArrayObject*)arr1); int nd2 = PyArray_NDIM((PyArrayObject*)arr2); int arr_type2 = PyArray_TYPE((PyArrayObject*)arr2); npy_intp *dims2 = PyArray_DIMS((PyArrayObject*)arr2); int r = 0; npy_double **input1 = NULL; r = PyArray_AsCArray((PyObject**)&arr1, (void**)&input1, dims1, nd1, PyArray_DescrFromType(arr_type1)); if (r < 0) { PyErr_SetString(PyExc_RuntimeError, "Could not convert input to C array"); return NULL; } npy_double **input2 = NULL; r = PyArray_AsCArray((PyObject**)&arr2, (void**)&input2, dims2, nd2, PyArray_DescrFromType(arr_type2)); if (r < 0) { PyErr_SetString(PyExc_RuntimeError, "Could not convert input to C array"); return NULL; } // DTW matrix_t mat_a = { input1, dims1[0], dims1[1] }; matrix_t mat_b = { input2, dims2[0], dims2[1] }; double dist = dtw_distance(&mat_a, &mat_b); PyObject *value = PyFloat_FromDouble(dist); if (value == NULL) { PyErr_SetString(PyExc_RuntimeError, "Could not convert double to object"); return NULL; } Py_DECREF(arr1); Py_DECREF(arr2); PyArray_Free(arr1, (void*)input1); PyArray_Free(arr2, (void*)input2); return value; }
static PyObject* evaluate_baseline_uvw_ha_dec(PyObject* self, PyObject* args) { /* Read input arguments */ PyObject *x_ecef_o=NULL, *y_ecef_o=NULL, *z_ecef_o=NULL; double ha, dec; if (!PyArg_ParseTuple(args, "O!O!O!dd", &PyArray_Type, &x_ecef_o, &PyArray_Type, &y_ecef_o, &PyArray_Type, &z_ecef_o, &ha, &dec)) return NULL; /* Convert Python objects to array of specified built-in data-type.*/ int typenum = NPY_DOUBLE; int requirements = NPY_ARRAY_IN_ARRAY; PyObject *x_ecef_=NULL, *y_ecef_=NULL, *z_ecef_=NULL; x_ecef_ = PyArray_FROM_OTF(x_ecef_o, typenum, requirements); if (!x_ecef_) goto fail; y_ecef_ = PyArray_FROM_OTF(y_ecef_o, typenum, requirements); if (!y_ecef_) goto fail; z_ecef_ = PyArray_FROM_OTF(z_ecef_o, typenum, requirements); if (!z_ecef_) goto fail; /* Extract dimensions and pointers. */ /* TODO(BM) Require input arrays be 1D, and check dimension consistency. * int nd = PyArray_NDIM(x_ecef_); */ npy_intp* dims = PyArray_DIMS((PyArrayObject*)x_ecef_); double* x_ecef = (double*)PyArray_DATA((PyArrayObject*)x_ecef_); double* y_ecef = (double*)PyArray_DATA((PyArrayObject*)y_ecef_); double* z_ecef = (double*)PyArray_DATA((PyArrayObject*)z_ecef_); /* Create New arrays for baseline coordinates. */ int n = dims[0]; npy_intp nb = (n * (n - 1)) / 2; PyObject* uu_ = PyArray_SimpleNew(1, &nb, NPY_DOUBLE); PyObject* vv_ = PyArray_SimpleNew(1, &nb, NPY_DOUBLE); PyObject* ww_ = PyArray_SimpleNew(1, &nb, NPY_DOUBLE); double* uu = (double*)PyArray_DATA((PyArrayObject*)uu_); double* vv = (double*)PyArray_DATA((PyArrayObject*)vv_); double* ww = (double*)PyArray_DATA((PyArrayObject*)ww_); /* Call function to evaluate baseline uvw */ uvwsim_evaluate_baseline_uvw_ha_dec(uu, vv, ww, n, x_ecef, y_ecef, z_ecef, ha, dec); /* Decrement references to local array objects. */ Py_DECREF(x_ecef_); Py_DECREF(y_ecef_); Py_DECREF(z_ecef_); /* Return baseline coordinates. */ return Py_BuildValue("NNN", uu_, vv_, ww_); fail: Py_XDECREF(x_ecef_); Py_XDECREF(y_ecef_); Py_XDECREF(z_ecef_); return NULL; }
static PyObject* evaluate_station_uvw(PyObject* self, PyObject* args) { /* Read input arguments */ PyObject *x_ecef_o=NULL, *y_ecef_o=NULL, *z_ecef_o=NULL; double ra0, dec0, mjd; if (!PyArg_ParseTuple(args, "O!O!O!ddd", &PyArray_Type, &x_ecef_o, &PyArray_Type, &y_ecef_o, &PyArray_Type, &z_ecef_o, &ra0, &dec0, &mjd)) return NULL; /* Convert Python objects to array of specified built-in data-type.*/ int typenum = NPY_DOUBLE; int requirements = NPY_ARRAY_IN_ARRAY; PyObject *x_ecef_=NULL, *y_ecef_=NULL, *z_ecef_=NULL; x_ecef_ = PyArray_FROM_OTF(x_ecef_o, typenum, requirements); if (!x_ecef_) goto fail; y_ecef_ = PyArray_FROM_OTF(y_ecef_o, typenum, requirements); if (!y_ecef_) goto fail; z_ecef_ = PyArray_FROM_OTF(z_ecef_o, typenum, requirements); if (!z_ecef_) goto fail; /* Extract dimensions and pointers. */ /* TODO Require input arrays be 1D, and check dimension consistency. * int nd = PyArray_NDIM(x_ecef_); */ npy_intp* dims = PyArray_DIMS((PyArrayObject*)x_ecef_); double* x_ecef = (double*)PyArray_DATA((PyArrayObject*)x_ecef_); double* y_ecef = (double*)PyArray_DATA((PyArrayObject*)y_ecef_); double* z_ecef = (double*)PyArray_DATA((PyArrayObject*)z_ecef_); /* Create New arrays for station coordinates. */ npy_intp n = dims[0]; PyObject* u_ = PyArray_SimpleNew(1, &n, NPY_DOUBLE); PyObject* v_ = PyArray_SimpleNew(1, &n, NPY_DOUBLE); PyObject* w_ = PyArray_SimpleNew(1, &n, NPY_DOUBLE); double* u = (double*)PyArray_DATA((PyArrayObject*)u_); double* v = (double*)PyArray_DATA((PyArrayObject*)v_); double* w = (double*)PyArray_DATA((PyArrayObject*)w_); /* Call function to evaluate station uvw */ uvwsim_evaluate_station_uvw(u, v, w, n, x_ecef, y_ecef, z_ecef, ra0, dec0, mjd); /* Decrement references to local array objects. */ Py_DECREF(x_ecef_); Py_DECREF(y_ecef_); Py_DECREF(z_ecef_); /* Return station uvw coordinates. */ return Py_BuildValue("NNN", u_, v_, w_); fail: Py_XDECREF(x_ecef_); Py_XDECREF(y_ecef_); Py_XDECREF(z_ecef_); return NULL; }
PyObject *punwrap2D_Unwrap2D(PyObject *self, PyObject *args) { PyObject *op1, *op2; PyArrayObject *phsArray, *mskArray, *retArray; float *wr_phs, *uw_phs; BYTE *bmask; int typenum_phs, typenum_msk, ndim; npy_intp *dims; PyArray_Descr *dtype_phs; if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) { PyErr_SetString(PyExc_Exception,"Unwrap2D: Couldn't parse the arguments"); return NULL; } if(op1==NULL || op2==NULL) { PyErr_SetString(PyExc_Exception,"Unwrap2D: Arguments not read correctly"); return NULL; } typenum_phs = PyArray_TYPE(op1); typenum_msk = PyArray_TYPE(op2); ndim = PyArray_NDIM(op1); dims = PyArray_DIMS(op2); /* This stuff is technically enforced in punwrap/__init__.py */ if(typenum_phs != PyArray_FLOAT) { PyErr_SetString(PyExc_Exception, "Unwrap2D: I can only handle single-precision floating point numbers"); return NULL; } if(typenum_msk != PyArray_UBYTE) { PyErr_SetString(PyExc_Exception, "Unwrap2D: The mask should be type uint8"); return NULL; } if(ndim != 2) { PyErr_SetString(PyExc_Exception, "Unwrap2D: I can only unwrap 2D arrays"); return NULL; } dtype_phs = PyArray_DescrFromType(typenum_phs); /* increasing references here */ phsArray = (PyArrayObject *)PyArray_FROM_OTF(op1, typenum_phs, NPY_IN_ARRAY); mskArray = (PyArrayObject *)PyArray_FROM_OTF(op2, typenum_msk, NPY_IN_ARRAY); /* create a new, empty ndarray with floats */ retArray = (PyArrayObject *)PyArray_SimpleNewFromDescr(ndim, dims, dtype_phs); wr_phs = (float *)PyArray_DATA(phsArray); uw_phs = (float *)PyArray_DATA(retArray); bmask = (BYTE *)PyArray_DATA(mskArray); phase_unwrap_2D(wr_phs, uw_phs, bmask, (int) dims[0], (int) dims[1]); Py_DECREF(phsArray); Py_DECREF(mskArray); return PyArray_Return(retArray); }
static PyObject *hc_cut(PyObject *self, PyObject *args, PyObject *keywds) { /* Inputs */ PyObject *ia = NULL; PyObject *ia_a = NULL; PyObject *ib = NULL; PyObject *ib_a = NULL; PyObject *height = NULL; PyObject *height_a = NULL; double t; npy_intp n; long *ia_c; long *ib_c; double *height_c; PyObject *cmap = NULL; npy_intp cmap_dims[1]; long *cmap_c; static char *kwlist[] = {"ia", "ib", "height", "t", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "OOOd", kwlist, &ia, &ib, &height, &t)) return NULL; ia_a = PyArray_FROM_OTF(ia, NPY_LONG, NPY_IN_ARRAY); if (ia_a == NULL) return NULL; ib_a = PyArray_FROM_OTF(ib, NPY_LONG, NPY_IN_ARRAY); if (ib_a == NULL) return NULL; height_a = PyArray_FROM_OTF(height, NPY_DOUBLE, NPY_IN_ARRAY); if (height_a == NULL) return NULL; n = PyArray_DIM(height_a, 0); ia_c = (long *) PyArray_DATA(ia_a); ib_c = (long *) PyArray_DATA(ib_a); height_c = (double *) PyArray_DATA(height_a); cmap_dims[0] = n; cmap = PyArray_SimpleNew(1, cmap_dims, NPY_LONG); cmap_c = (long *) PyArray_DATA(cmap); cutree((long) n, ia_c, ib_c, height_c, t, cmap_c); Py_DECREF(ia_a); Py_DECREF(ib_a); Py_DECREF(height_a); return Py_BuildValue("N", cmap); }
static PyObject *chi2_chi2(PyObject *self, PyObject *args) { double m, b; PyObject *x_obj, *y_obj, *yerr_obj; /* Parse the input tuple */ if (!PyArg_ParseTuple(args, "ddOOO", &m, &b, &x_obj, &y_obj, &yerr_obj)) return NULL; /* Interpret the input objects as numpy arrays. */ PyObject *x_array = PyArray_FROM_OTF(x_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *y_array = PyArray_FROM_OTF(y_obj, NPY_DOUBLE, NPY_IN_ARRAY); PyObject *yerr_array = PyArray_FROM_OTF(yerr_obj, NPY_DOUBLE, NPY_IN_ARRAY); /* If that didn't work, throw an exception. */ if (x_array == NULL || y_array == NULL || yerr_array == NULL) { Py_XDECREF(x_array); Py_XDECREF(y_array); Py_XDECREF(yerr_array); return NULL; } /* How many data points are there? */ int N = (int)PyArray_DIM(x_array, 0); /* Get pointers to the data as C-types. */ double *x = (double*)PyArray_DATA(x_array); double *y = (double*)PyArray_DATA(y_array); double *yerr = (double*)PyArray_DATA(yerr_array); /* Call the external C function to compute the chi-squared. */ double value = chi2(m, b, x, y, yerr, N); /* Clean up. */ Py_DECREF(x_array); Py_DECREF(y_array); Py_DECREF(yerr_array); if (value < 0.0) { PyErr_SetString(PyExc_RuntimeError, "Chi-squared returned an impossible value."); return NULL; } /* Build the output tuple */ PyObject *ret = Py_BuildValue("d", value); return ret; }
static PyObject * tofile_iint32(PyObject *dummy, PyObject *args) { PyObject *arg1=NULL, *arg2=NULL, *arg3=NULL; PyObject *arr1=NULL, *arr2=NULL; FILE *fp; char *fmt; /* single element format */ if (!PyArg_ParseTuple(args, "OOOs", &arg1, &arg2, &arg3, &fmt)) return NULL; arr1 = PyArray_FROM_OTF(arg1, NPY_INT, NPY_IN_ARRAY); if (arr1 == NULL) return NULL; arr2 = PyArray_FROM_OTF(arg2, NPY_INT, NPY_IN_ARRAY); if (arr2 == NULL) goto fail; fp = PyFile_AsFile(arg3); if (!fp) goto fail; int *val; val = (int *)PyArray_DATA(arr2); npy_intp * dims; dims = PyArray_DIMS(arg2); int nr,nc; nr = dims[0]; nc = dims[1]; int *ind; ind = (int *)PyArray_DATA(arr1); dims = PyArray_DIMS(arg1); if (dims[0] != nr) goto fail; int i,j; for (i=0; i<nr; i++) { fprintf(fp,"%i ",*(ind++)); for (j=0; j<nc; j++) { fprintf(fp,fmt,*(val++)); } fprintf(fp,"\n"); } /* Clean up and return */ Py_DECREF(arr1); Py_DECREF(arr2); Py_INCREF(Py_None); return Py_None; fail: Py_XDECREF(arr1); Py_XDECREF(arr2); return NULL; }
static PyObject* Py_convert_shape( PyObject* self, PyObject* args) { PyObject* landmarks_obj; int format; if (!PyArg_ParseTuple(args, "Oi:convert_shape", &landmarks_obj, &format)) return NULL; PyArrayObject* landmarks_array = (PyArrayObject*) PyArray_FROM_OTF(landmarks_obj, NPY_FLOAT, NPY_ARRAY_IN_ARRAY); if (landmarks_array == NULL) { PyErr_SetString(PyExc_TypeError, landmark_error); return NULL; } if (PyArray_NDIM(landmarks_array) != 2) { PyErr_SetString(PyExc_TypeError, landmark_dim_error); return NULL; } PyObject* retArray = PyArray_Copy(landmarks_array); Py_DECREF(landmarks_array); float* landmarks = (float*)PyArray_DATA((PyArrayObject*)retArray); stasm_convert_shape(landmarks, format); return retArray; }
static PyObject* pyspectro_readavsspectrum(PyObject* self, PyObject* args) { PyObject *spectrum_obj; unsigned int timeout; long hDevice; if(PyArg_ParseTuple(args, "Oil", &spectrum_obj, &timeout, &hDevice) == 0) return NULL; PyObject* spectrum = PyArray_FROM_OTF(spectrum_obj, NPY_DOUBLE, NPY_OUT_ARRAY); if(!spectrum) { Py_XDECREF(spectrum); return NULL; } //int N = (int)PyArray_DIM(spectrum, 0); double* c_spectrum = (double*)PyArray_DATA(spectrum); int err; unsigned int timestamp = 0; if((err = fReadAVSSpectrum(hDevice, c_spectrum, ×tamp, timeout)) != 0) { Py_DECREF(spectrum); char line[512]; snprintf(line, sizeof(line), "ReadAVSSpectrum(): %d\n", err); PyErr_SetString(PyExc_IOError, line); return NULL; } Py_DECREF(spectrum); return Py_BuildValue("i", timestamp); }
static PyObject *wrap_logicle_scale(PyObject *self, PyObject *args) { double t, w, m, a; PyObject *x; // parse the input args tuple if (!PyArg_ParseTuple(args, "ddddO", &t, &w, &m, &a, &x)) { return NULL; } // read the numpy array PyObject *x_array = PyArray_FROM_OTF(x, NPY_DOUBLE, NPY_IN_ARRAY); // throw exception if the array doesn't exist if (x_array == NULL) { Py_XDECREF(x_array); return NULL; } // get length of input array int n = (int)PyArray_DIM(x_array, 0); // get pointers to the data as C-type double *xc = (double*)PyArray_DATA(x_array); // now we can call our function! logicle_scale(t, w, m, a, xc, n); return x_array; }
/* * Returns image data from a PyObject representing a numpy array. * * In: array_obj - Numpy array with image data * Out: width - Image width * Out: height - Image height * * Returns: char* pointing to the array data; * NULL if array is invalid */ const char* PyArray_to_image( PyObject* array_obj, int* width, int* height) { PyArrayObject* img_array = (PyArrayObject*) PyArray_FROM_OTF(array_obj, NPY_UINT8, NPY_ARRAY_IN_ARRAY); if (img_array == NULL) { PyErr_SetString(PyExc_TypeError, imarray_error); return NULL; } if (PyArray_NDIM(img_array) != 2) { PyErr_SetString(PyExc_TypeError, imarray_dim_error); return NULL; } *height = (int)PyArray_DIM(img_array, 0); *width = (int)PyArray_DIM(img_array, 1); const char* img_data = PyArray_BYTES(img_array); Py_DECREF(img_array); return img_data; }
// this copies a block of memory from a numpy array to a memory address static PyObject* pymappedndf_numpytondf(NDFMapped *self, PyObject *args) { PyObject *npy, *ptrobj; PyArrayObject *npyarray; npy_intp el; size_t bytes; if(!PyArg_ParseTuple(args, "O:pyndfmapped_numpytondf",&npy)) return NULL; void *ptr = self->_pntr; el = self->nelem; if (el <= 0 || ptr == NULL) { PyErr_SetString( PyExc_ValueError, "ndf.mapped object does not have mapped pointer or element count"); return NULL; } int npytype = ndftype2numpy( self->type, &bytes ); if (npytype == 0) return NULL; npyarray = (PyArrayObject*) PyArray_FROM_OTF(npy, npytype, NPY_IN_ARRAY | NPY_FORCECAST); if (!npyarray) return NULL; /* Verify the number of elements */ if ( PyArray_Size(npyarray) != el ) { PyErr_Format( PyExc_ValueError, "Number of elements in numpy array (%zu) differs from number of elements mapped (%zu)", (size_t)PyArray_Size(npyarray), (size_t)el ); Py_DECREF(npyarray); return NULL; } memcpy(ptr,PyArray_DATA(npyarray),el*bytes); Py_DECREF(npyarray); Py_RETURN_NONE; }
static PyObject * omp_dbscan_wrapper(PyObject *self, PyObject *args, PyObject *kwargs) { const char *kw[] = {"samples", "min_samples", "eps", "threads", 0}; const char *fmt = "O|ldl"; PyObject *samples_src = 0; // this will have a borrowed reference PyArrayObject *samples_np = 0; PyArrayObject *clusters_np = 0; long int min_samples = 5; double eps = 0.5; long int threads = 1; if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, const_cast<char**>(kw), // yuk! &samples_src, &min_samples, &eps, &threads)) { return NULL; } int type = NPY_CFLOAT; // this is due to the type used by the dbscan code int requirements = NPY_ARRAY_IN_ARRAY|NPY_ARRAY_FORCECAST; samples_np = (PyArrayObject*)PyArray_FROM_OTF(samples_src, type, requirements); if (!samples_np) { return PyErr_NoMemory(); } if (2 != PyArray_NDIM(samples_np)) { PyErr_SetString(PyExc_ValueError, "omp_dbscan expects a 2 dimensional sample array"); Py_XDECREF(samples_np); return NULL; } float *data = (float *)PyArray_DATA(samples_np); npy_intp outer_dim = PyArray_DIMS(samples_np)[0]; npy_intp inner_dim = PyArray_DIMS(samples_np)[1]; clusters_np = (PyArrayObject*)PyArray_EMPTY(1, &outer_dim, NPY_INTP, 0); npy_intp *data_out = (npy_intp*)PyArray_DATA(clusters_np); dbsa::ClusteringAlgo dbs; dbs.set_dbscan_params(eps, min_samples); Py_BEGIN_ALLOW_THREADS long int old_threads = omp_get_num_threads(); omp_set_num_threads(threads); dbsa::set_samples_from_buffer(dbs, data, outer_dim, inner_dim); dbs.build_kdtree(); run_dbscan_algo_uf(dbs); dbsa::pack_results(dbs, data_out); omp_set_num_threads(old_threads); Py_END_ALLOW_THREADS Py_XDECREF(samples_np); return (PyObject*)clusters_np; }
static PyObject *web_calc_substellar(PyObject *self, PyObject *args) { double phase; PyObject *c_obj; /* Parse the input tuple */ if (!PyArg_ParseTuple(args, "dO", &phase,&c_obj)) return NULL; PyObject *c_array = PyArray_FROM_OTF(c_obj, NPY_DOUBLE, NPY_IN_ARRAY); /* If that didn't work, throw an exception. */ if (c_array == NULL) { Py_XDECREF(c_array); return NULL; } double *c = (double*)PyArray_DATA(c_array); /* Call the external C function to compute the area. */ double *output = calc_substellar(phase,c); PyObject *ret = Py_BuildValue("[d,d]",output[0],output[1]); Py_DECREF(c_array); return ret; }
// create a new NDF extension static PyObject* pyndf_xnew(NDF *self, PyObject *args) { int ndim = 0; const char *xname, *type; PyObject *dim; if(!PyArg_ParseTuple(args, "ss|iO:pyndf_xnew", &xname, &type, &ndim, &dim)) return NULL; int status = SAI__OK; HDSLoc *loc = NULL; // perform checks if we're not making an extension header if(ndim != 0) { // check for HDS types if (!checkHDStype(type)) return NULL; // need dims if it's not an ext if(ndim < 1 || dim == NULL) return NULL; PyArrayObject *npydim = (PyArrayObject*) PyArray_FROM_OTF(dim,NPY_INT,NPY_IN_ARRAY|NPY_FORCECAST); if (PyArray_SIZE(npydim) != ndim) return NULL; errBegin(&status); ndfXnew(self->_ndfid,xname,type,ndim,(int*)PyArray_DATA(npydim),&loc,&status); Py_DECREF(npydim); } else { // making an ext/struct errBegin(&status); ndfXnew(self->_ndfid,xname,type,0,0,&loc,&status); } if (raiseNDFException(&status)) return NULL; PyObject* pobj = NpyCapsule_FromVoidPtr(loc, PyDelLoc); return Py_BuildValue("O",pobj); }
//takes a numpy array of doubles of size pixelNum static PyObject* pyspectro_getlambda(PyObject* self, PyObject* args) { PyObject *lambda_obj; long hDevice; if(PyArg_ParseTuple(args, "Ol", &lambda_obj, &hDevice) == 0){ return NULL; } PyObject* lambda = PyArray_FROM_OTF(lambda_obj, NPY_DOUBLE, NPY_OUT_ARRAY); if(!lambda) { Py_XDECREF(lambda); return NULL; } double* c_lambda = (double*)PyArray_DATA(lambda); int err; if((err = fGetLambda(hDevice, c_lambda)) != 0) { Py_DECREF(lambda); char line[512]; snprintf(line, sizeof(line), "GetLambda(): %d\n", err); PyErr_SetString(PyExc_IOError, line); return NULL; } //int N = (int)PyArray_DIM(lambda, 0); //for(int i = 0; i < N; i++) // c_lambda[i] = 532.0; Py_DECREF(lambda); Py_RETURN_NONE; }
// make a new primitive static PyObject* pydat_new(HDSObject *self, PyObject *args) { PyObject *dimobj; const char *type, *name; int ndim; if(!PyArg_ParseTuple(args, "ssiO:pydat_new", &name, &type, &ndim, &dimobj)) return NULL; HDSLoc* loc = HDS_retrieve_locator(self); if(!checkHDStype(type)) return NULL; int status = SAI__OK; errBegin(&status); if (ndim > 0) { PyArrayObject *npydim = (PyArrayObject*) PyArray_FROM_OTF(dimobj,NPY_INT,NPY_IN_ARRAY|NPY_FORCECAST); hdsdim *dims = (hdsdim*)PyArray_DATA(npydim); datNew(loc,name,type,ndim,dims,&status); Py_DECREF(npydim); } else { datNew(loc,name,type,0,0,&status); } if (raiseHDSException(&status)) return NULL; Py_RETURN_NONE; }
static PyObject* MaximumEntropyMethod (PyObject* self, PyObject *arg, PyObject *keywords) { // Declaring initial variables double TimeStep; int NumberOfCoefficients = 100; //Default value for number of coeficients double AngularFrequency; // Interface with Python PyObject *velocity_obj, *frequency_obj; static char *kwlist[] = {"frequency", "velocity", "time_step", "coefficients", NULL}; if (!PyArg_ParseTupleAndKeywords(arg, keywords, "OOd|i", kwlist, &frequency_obj, &velocity_obj, &TimeStep, &NumberOfCoefficients)) return NULL; PyObject *velocity_array = PyArray_FROM_OTF(velocity_obj, NPY_CDOUBLE, NPY_IN_ARRAY); PyObject *frequency_array = PyArray_FROM_OTF(frequency_obj, NPY_DOUBLE, NPY_IN_ARRAY); if (velocity_array == NULL || frequency_array == NULL ) { Py_XDECREF(velocity_array); Py_XDECREF(frequency_array); return NULL; } double _Complex *Velocity = (double _Complex*)PyArray_DATA(velocity_array); double *Frequency = (double*)PyArray_DATA(frequency_array); int NumberOfData = (int)PyArray_DIM(velocity_array, 0); int NumberOfFrequencies = (int)PyArray_DIM(frequency_array, 0); //Create new numpy array for storing result PyArrayObject *PowerSpectrum_object; int dims[1]={NumberOfFrequencies}; PowerSpectrum_object = (PyArrayObject *) PyArray_FromDims(1,dims,NPY_FLOAT); float *PowerSpectrum = (float*)PyArray_DATA(PowerSpectrum_object); //Declare internal variables float coefficients[NumberOfCoefficients]; // Maximum Entropy Method Algorithm double MeanSquareDiscrepancy = GetCoefficients((double *)Velocity, NumberOfData, NumberOfCoefficients, coefficients); # pragma omp parallel for default(shared) private(AngularFrequency) for (int i=0;i<NumberOfFrequencies;i++) { AngularFrequency = Frequency[i]*2.0*M_PI; PowerSpectrum[i] = FrequencyEvaluation(AngularFrequency*TimeStep/2.0, coefficients, NumberOfCoefficients, MeanSquareDiscrepancy); } //Returning Python array return(PyArray_Return(PowerSpectrum_object)); }
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; }
void init() { if (attr != NULL) { arr = (PyArrayObject*)PyArray_FROM_OTF(attr, atype<T>(), NPY_ARRAY_IN_ARRAY); if (arr != NULL) { ptr_start = ptr = (T*)PyArray_DATA(arr); } } }
static PyObject* Add(PyObject* self, PyObject* args) { PyObject *arg1=NULL, *arg2=NULL; PyObject *npy_a=NULL, *npy_b=NULL, *npy_c=NULL; if(!PyArg_ParseTuple(args, "OO", &arg1, &arg2)) return NULL; if (arg1 == NULL) printf("arg1 NULL\n"); // convert to contiguous arrays npy_a = PyArray_FROM_OTF(arg1, NPY_FLOAT, NPY_IN_FARRAY); if (npy_a == NULL) goto fail; npy_b = PyArray_FROM_OTF(arg2, NPY_FLOAT, NPY_IN_FARRAY); if (npy_b == NULL) goto fail; npy_c = PyArray_FROM_OTF(npy_b, NPY_FLOAT, NPY_INOUT_FARRAY); if (npy_c == NULL) goto fail; matrix a, b, c; a = mat_from_pyarray(npy_a); b = mat_from_pyarray(npy_b); c = mat_from_pyarray(npy_c); int a_size = PyArray_SIZE(npy_a); int i; for(i=0;i<a_size;i++) c.mat[i] = a.mat[i] + b.mat[i]; Py_DECREF(npy_a); Py_DECREF(npy_b); Py_INCREF(Py_None); return npy_c; fail: fprintf(stderr,"failed to allocate numpy arrays\n"); return NULL; }
static PyObject * nodalSum(PyObject *dummy, PyObject *args) { PyObject *arg1=NULL, *arg2=NULL, *ret=NULL; PyObject *arr1=NULL, *arr2=NULL; float *val,*out; int *elems; int avg, all, max; if (!PyArg_ParseTuple(args, "OOiii", &arg1, &arg2, &max, &avg, &all)) return NULL; arr1 = PyArray_FROM_OTF(arg1, NPY_FLOAT, NPY_IN_ARRAY); if (arr1 == NULL) return NULL; arr2 = PyArray_FROM_OTF(arg2, NPY_INT, NPY_IN_ARRAY); if (arr2 == NULL) goto fail; npy_intp * dim; int nelems,nplex,nval; dim = PyArray_DIMS(arg1); nelems = dim[0]; nplex = dim[1]; nval = dim[2]; val = (float *)PyArray_DATA(arr1); elems = (int *)PyArray_DATA(arr2); /* create return array */ if (all) ret = PyArray_SimpleNew(3,dim, NPY_FLOAT); else { dim[0] = max+1; dim[1] = nval; ret = PyArray_SimpleNew(2,dim, NPY_FLOAT); } out = (float *)PyArray_DATA(ret); /* compute */ nodal_sum(val,elems,out,nelems,nplex,nval,max,avg,all); /* Clean up and return */ Py_DECREF(arr1); Py_DECREF(arr2); return ret; fail: Py_XDECREF(arr1); Py_XDECREF(arr2); 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; }
static int PyConverter_ComplexArrayCopy( PyObject *object, PyObject **address) { *address = PyArray_FROM_OTF(object, NPY_COMPLEX128, NPY_ARRAY_ENSURECOPY|NPY_ARRAY_IN_ARRAY); if (*address == NULL) return NPY_FAIL; return NPY_SUCCEED; }
static PyObject *hc_linkage(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *dist = NULL; PyObject *dist_a = NULL; double *dist_c; int method; int n; PyObject *ia = NULL; PyObject *ib = NULL; PyObject *height = NULL; PyObject *iorder = NULL; npy_intp ia_dims[1]; npy_intp ib_dims[1]; npy_intp height_dims[1]; npy_intp iorder_dims[1]; long *ia_c, *ib_c; long *iorder_c; double *height_c; static char *kwlist[] = {"n", "dist", "method", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "iOi", kwlist, &n, &dist, &method)) return NULL; dist_a = PyArray_FROM_OTF(dist, NPY_DOUBLE, NPY_IN_ARRAY); if (dist_a == NULL) return NULL; dist_c = (double *) PyArray_DATA(dist_a); ia_dims[0] = n; ia = PyArray_SimpleNew(1, ia_dims, NPY_LONG); ia_c = (long *) PyArray_DATA(ia); ib_dims[0] = n; ib = PyArray_SimpleNew(1, ib_dims, NPY_LONG); ib_c = (long *) PyArray_DATA(ib); iorder_dims[0] = n; iorder = PyArray_SimpleNew(1, iorder_dims, NPY_LONG); iorder_c = (long *) PyArray_DATA(iorder); height_dims[0] = n; height = PyArray_SimpleNew(1, height_dims, NPY_DOUBLE); height_c = (double *) PyArray_DATA(height); hclust((long) n, method, dist_c, ia_c, ib_c, iorder_c, height_c); Py_DECREF(dist_a); return Py_BuildValue("(N, N, N, N)", ia, ib, iorder, height); }
PyObject *computeCov(PyObject *i_funGetData , PyObject *i_funHasMoreData , PyObject *i_colMeans , double i_chunkSize , double dimData) { PyObject *o_covMat = NULL, *chunkCovMat = NULL; PyArrayObject *chunk = NULL; PyArrayObject *covArr = NULL; //PyArrayObject *retval = NULL; //bool moreData; double tmp; int whileIter = 0; while (call_funHasMoreData(i_funHasMoreData)) { whileIter++; if (1 == whileIter) { chunk = call_funGetData(i_funGetData, i_chunkSize); o_covMat = computeChunkCov(chunk, i_colMeans); } if (1 != whileIter) { chunk = call_funGetData(i_funGetData, i_chunkSize); chunkCovMat = computeChunkCov(chunk, i_colMeans); o_covMat = addMatrixPiecewise(o_covMat, chunkCovMat); } } covArr = (PyArrayObject*)PyArray_FROM_OTF(o_covMat, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); tmp = 1.0 / (dimData - 1.0); o_covMat = matrixMulti(covArr, tmp); covArr = (PyArrayObject*)PyArray_FROM_OTF(o_covMat, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); o_covMat = computeFullMatrix(covArr); //o_covMat = tmp * covArr; return o_covMat; //Py_BuildValue("O", o_covMat); }
static PyObject * pivoting(PyObject *self, PyObject *args) { int csz; PyObject *a0 = NULL, *b0 = NULL, *a = NULL, *b = NULL; if (!PyArg_ParseTuple(args, "OOi", &a0, &b0, &csz)) return NULL; a = PyArray_FROM_OTF(a0,NPY_DOUBLE,NPY_INOUT_ARRAY); b = PyArray_FROM_OTF(b0,NPY_DOUBLE,NPY_INOUT_ARRAY); // Check the validity of input values: int ndim_a = PyArray_NDIM(a), ndim_b = PyArray_NDIM(b); npy_intp *dims_a = PyArray_DIMS(a), *dims_b = PyArray_DIMS(b); int nrow_a = dims_a[0], ncol_a = dims_a[1], nrow_b = dims_b[0], ncol_b = 1; #ifdef CHK_INPUTS if (a == NULL || b == NULL) return NULL; if (ndim_a != 2){ PyErr_SetString(PyExc_ValueError,"The dimension of a should be 2."); return NULL; } if (ndim_b != 1){ PyErr_SetString(PyExc_ValueError,"The dimension of b should be 1."); return NULL; } if (nrow_a != nrow_b){ PyErr_SetString(PyExc_ValueError,"a and b should have the same rows"); return NULL; } #endif double *A = (double *)PyArray_DATA(a); double *B = (double *)PyArray_DATA(b); cpivoting(A, nrow_a, ncol_a, B, nrow_b, ncol_b, csz); Py_DECREF(a); Py_DECREF(b); Py_INCREF(Py_None); return Py_None; }