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; }
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 *inverse_subtraction_inplace(PyObject *self, PyObject *args) { PyObject* a = NULL; PyObject* b = NULL; npy_intp sz = 0, i; npy_complex64* tmp_sp = NULL; npy_complex64* a_data_sp = NULL; npy_float32* b_data_sp = NULL; npy_complex128* tmp_dp = NULL; npy_complex128* a_data_dp = NULL; npy_float64* b_data_dp = NULL; double c; if (!PyArg_ParseTuple(args, "OOd", &a, &b, &c)) return NULL; if (!(PyArray_Check(a) && PyArray_Check(b))) { PyErr_SetString(PyExc_TypeError,"arguments must be array objects"); return NULL; } sz = PyArray_SIZE(a); if (sz != PyArray_SIZE(b)) { PyErr_SetString(PyExc_TypeError,"argument sizes must be equal"); return NULL; } if ((PyArray_TYPE(a) == PyArray_COMPLEX64) && (PyArray_TYPE(b) == PyArray_FLOAT32)) { a_data_sp = (npy_complex64*)PyArray_DATA(a); b_data_sp = (npy_float32*)PyArray_DATA(b); for (i=0; i<sz; ++i) { tmp_sp = a_data_sp + i; tmp_sp->real = b_data_sp[i] - tmp_sp->real * c; } } else if ((PyArray_TYPE(a) == PyArray_COMPLEX128) && (PyArray_TYPE(b) == PyArray_FLOAT64)) { a_data_dp = (npy_complex128*)PyArray_DATA(a); b_data_dp = (npy_float64*)PyArray_DATA(b); for (i=0; i<sz; ++i) { tmp_dp = a_data_dp + i; tmp_dp->real = b_data_dp[i] - tmp_dp->real * c; } } else { PyErr_SetString(PyExc_TypeError,"argument types must be complex64 and float32"); return NULL; } return Py_BuildValue(""); }
// ======================================================================== // class vec<double> // // constructor from a python array vec<double>::vec(array& boost_array) { // get array info PyArrayObject* py_array_p=reinterpret_cast<PyArrayObject*>(boost_array.ptr()); npy_intp* dims_ptr = PyArray_DIMS(py_array_p); int length = dims_ptr[0]; // check array info PYCPPAD_ASSERT( PyArray_NDIM(py_array_p) == 1 , "array is not a vector" ); PYCPPAD_ASSERT( length >= 0 , "array length is <= zero" ); // set private data length_ = static_cast<size_t>( length ); if( PyArray_TYPE(py_array_p) == NPY_DOUBLE ) { pointer_ = static_cast<double*>( PyArray_DATA(py_array_p) ); allocated_ = false; } else if( PyArray_TYPE(py_array_p) == NPY_INT ) { pointer_ = CPPAD_TRACK_NEW_VEC(length, pointer_); int* data = static_cast<int*>( PyArray_DATA(py_array_p) ); for(size_t i = 0; i < length_; i++) pointer_[i] = static_cast<double>( data[i] ); allocated_ = true; } else if( PyArray_TYPE(py_array_p) == NPY_LONG ) { pointer_ = CPPAD_TRACK_NEW_VEC(length, pointer_); long* data = static_cast<long*>( PyArray_DATA(py_array_p) ); for(size_t i = 0; i < length_; i++) pointer_[i] = static_cast<double>( data[i] ); allocated_ = true; } else PYCPPAD_ASSERT( 0, "expected an array with int or float elements" ); return; }
vec<Scalar>::vec(array& boost_array) { // get array info PyArrayObject* py_array_p=reinterpret_cast<PyArrayObject*>(boost_array.ptr()); npy_intp* dims_ptr = PyArray_DIMS(py_array_p); int length = dims_ptr[0]; // check array info PYCPPAD_ASSERT( PyArray_NDIM(py_array_p) == 1 , "array is not a vector" ); PYCPPAD_ASSERT( PyArray_TYPE(py_array_p) == NPY_OBJECT , "expected array elements of type object" ); PYCPPAD_ASSERT( length >= 0 , "array length is <= zero" ); // pointer to object object *obj_ptr = static_cast<object*>( PyArray_DATA(py_array_p) ); // set private data length_ = static_cast<size_t>(length); pointer_ = 0; handle_ = CPPAD_TRACK_NEW_VEC(length_, handle_); for(size_t i = 0; i < length_; i++) handle_[i] = & extract<Scalar&>(obj_ptr[i])(); return; }
static PyObject * Py_gstrf(PyObject *self, PyObject *args, PyObject *keywds) { /* default value for SuperLU parameters*/ int N, nnz; PyArrayObject *rowind, *colptr, *nzvals; SuperMatrix A; PyObject *result; PyObject *option_dict = NULL; int type; int ilu = 0; static char *kwlist[] = {"N","nnz","nzvals","colind","rowptr", "options", "ilu", NULL}; int res = PyArg_ParseTupleAndKeywords( args, keywds, "iiO!O!O!|Oi", kwlist, &N, &nnz, &PyArray_Type, &nzvals, &PyArray_Type, &rowind, &PyArray_Type, &colptr, &option_dict, &ilu); if (!res) return NULL; if (!_CHECK_INTEGER(colptr) || !_CHECK_INTEGER(rowind)) { PyErr_SetString(PyExc_TypeError, "rowind and colptr must be of type cint"); return NULL; } type = PyArray_TYPE(nzvals); if (!CHECK_SLU_TYPE(type)) { PyErr_SetString(PyExc_TypeError, "nzvals is not of a type supported by SuperLU"); return NULL; } if (NCFormat_from_spMatrix(&A, N, N, nnz, nzvals, rowind, colptr, type)) { goto fail; } result = newSciPyLUObject(&A, option_dict, type, ilu); if (result == NULL) { goto fail; } /* arrays of input matrix will not be freed */ Destroy_SuperMatrix_Store(&A); return result; fail: /* arrays of input matrix will not be freed */ Destroy_SuperMatrix_Store(&A); return NULL; }
static double* check_double_image(PyObject* image, size_t *nrows, size_t *ncols) { double* ptr=NULL; npy_intp *dims=NULL; if (!PyArray_Check(image)) { PyErr_SetString(PyExc_ValueError, "image must be a 2D numpy array of type 64-bit float"); return NULL; } if (2 != PyArray_NDIM((PyArrayObject*)image)) { PyErr_Format(PyExc_ValueError, "image must be a 2D numpy array of type 64-bit float"); return NULL; } if (NPY_DOUBLE != PyArray_TYPE((PyArrayObject*)image)) { PyErr_Format(PyExc_ValueError, "image must be a 2D numpy array of type 64-bit float"); return NULL; } ptr = PyArray_DATA((PyArrayObject*)image); dims = PyArray_DIMS((PyArrayObject*)image); *nrows = dims[0]; *ncols = dims[1]; return ptr; }
static int check_object(PyObject *ob, int t, char *obname, char *tname, char *funname) { if (!PyArray_Check(ob)) { PyErr_Format(LapackError, "Expected an array for parameter %s in lapack_lite.%s", obname, funname); return 0; } else if (!PyArray_IS_C_CONTIGUOUS((PyArrayObject *)ob)) { PyErr_Format(LapackError, "Parameter %s is not contiguous in lapack_lite.%s", obname, funname); return 0; } else if (!(PyArray_TYPE((PyArrayObject *)ob) == t)) { PyErr_Format(LapackError, "Parameter %s is not of type %s in lapack_lite.%s", obname, tname, funname); return 0; } else if (PyArray_ISBYTESWAPPED((PyArrayObject *)ob)) { PyErr_Format(LapackError, "Parameter %s has non-native byte order in lapack_lite.%s", obname, funname); return 0; } else { return 1; } }
static PyObject* gse_checksum(PyObject *dummy, PyObject *args) { int checksum, length, i; PyObject *array = NULL; PyArrayObject *carray = NULL; int *data; if (!PyArg_ParseTuple(args, "O", &array )) { PyErr_SetString(GSEError, "usage checksum(array)" ); return NULL; } if (!PyArray_Check(array)) { PyErr_SetString(GSEError, "Data must be given as NumPy array." ); return NULL; } if (PyArray_TYPE(array) != NPY_INT32) { PyErr_SetString(GSEError, "Data must be 32-bit integers."); return NULL; } carray = PyArray_GETCONTIGUOUS((PyArrayObject*)array); length = PyArray_SIZE(carray); data = (int*)PyArray_DATA(carray); checksum = 0; for (i=0; i<length; i++) { checksum += data[i] % MODULUS; checksum %= MODULUS; } return Py_BuildValue("i", abs(checksum)); }
/* setData */ PyObject * Image_setData(PyObject *obj, PyObject *args, PyObject *kwargs) { ImageObject *self = (ImageObject*) obj; PyArrayObject * arr = NULL; if (self != NULL && PyArg_ParseTuple(args, "O", &arr)) { try { ImageGeneric & image = Image_Value(self); DataType dt = npyType2Datatype(PyArray_TYPE(arr)); int nd = PyArray_NDIM(arr); //Setup of image image.setDatatype(dt); ArrayDim adim; adim.ndim = (nd == 4 ) ? PyArray_DIM(arr, 0) : 1; adim.zdim = (nd > 2 ) ? PyArray_DIM(arr, nd - 3) : 1; adim.ydim = PyArray_DIM(arr, nd - 2); adim.xdim = PyArray_DIM(arr, nd - 1); MULTIDIM_ARRAY_GENERIC(image).resize(adim, false); void *mymem = image().getArrayPointer(); void * data = PyArray_DATA(arr); memcpy(mymem, data, adim.nzyxdim * gettypesize(dt)); Py_RETURN_NONE; } catch (XmippError &xe) { PyErr_SetString(PyXmippError, xe.msg.c_str()); } } return NULL; }//function Image_setData
static PyObject* PyTesseract_set_image(PyTesseract *self, PyObject *array) { if (!PyArray_Check(array)) { PyErr_SetString(PyExc_TypeError, "Image must be a NumPy array"); return NULL; } PyArrayObject *np_array = (PyArrayObject *)array; npy_intp *shape = PyArray_DIMS(np_array); int dimension_count = PyArray_NDIM(np_array); int channels = 0; switch (dimension_count) { case 2: channels = 1; break; case 3: channels = (int)shape[2]; break; default: PyErr_SetString(PyExc_TypeError, "Invalid array format"); return NULL; } int bytes_per_channel = 0; switch (PyArray_TYPE(np_array)) { case NPY_BYTE: case NPY_UBYTE: bytes_per_channel = 1; break; case NPY_SHORT: case NPY_USHORT: bytes_per_channel = 2; break; case NPY_FLOAT: bytes_per_channel = 4; break; case NPY_DOUBLE: bytes_per_channel = 8; break; default: PyErr_SetString(PyExc_TypeError, "Invalid array format"); return NULL; } int rows = (int)shape[0]; int cols = (int)shape[1]; Py_INCREF(array); self->image = array; int bytes_per_pixel = bytes_per_channel * channels; self->tess->SetImage((unsigned char *)PyArray_BYTES(np_array), cols, rows, bytes_per_pixel, bytes_per_pixel * cols); PyTesseract_invalidate_iterators(self); if (self->page) { delete self->page; self->page = NULL; } Py_INCREF(Py_None); return Py_None; }
static PyObject *poisson_hist_factor_estimate(PyObject *self, PyObject *args) { PyObject* a = NULL; PyObject* b = NULL; npy_intp sz = 0, i; npy_float32 tmp; npy_float32* a_data = NULL; npy_float32* b_data = NULL; double c; double unstable = 0.0, stable = 0.0; if (!PyArg_ParseTuple(args, "OOd", &a, &b, &c)) return NULL; if (c<0 || c>0.5) { PyErr_SetString(PyExc_TypeError,"third argument must be non-negative and less than 0.5"); return NULL; } if (!(PyArray_Check(a) && PyArray_Check(b))) { PyErr_SetString(PyExc_TypeError,"first two arguments must be array objects"); return NULL; } sz = PyArray_SIZE(a); if (sz != PyArray_SIZE(b)) { PyErr_SetString(PyExc_TypeError,"array argument sizes must be equal"); return NULL; } if (! ((PyArray_TYPE(a) == PyArray_FLOAT32) && (PyArray_TYPE(b) == PyArray_FLOAT32))) { PyErr_SetString(PyExc_TypeError,"array argument types must be float32"); return NULL; } a_data = (npy_float32*)PyArray_DATA(a); b_data = (npy_float32*)PyArray_DATA(b); for (i=0; i<sz; ++i) { tmp = a_data[i]; if (((tmp>-c) && (tmp<c)) || ((tmp<1.0+c) && (tmp>1.0-c))) stable += tmp * b_data[i]; else { unstable += tmp * b_data[i]; } } return Py_BuildValue("dd",stable, unstable); }
td_tag_t td_py_get_eltype(void *v) { if (PyArray_Check( (PyObject *) v)){ PyArrayObject *arr = (PyArrayObject *)v; return numpy_type_to_td(PyArray_TYPE(v)); } return TD_UNKNOWN; }
static PyObject* write_coords(PyObject* self, PyObject* args) { oskar_MeasurementSet* h = 0; PyObject *capsule = 0; PyObject *obj[] = {0, 0, 0}; PyArrayObject *uu = 0, *vv = 0, *ww = 0; int start_row = 0, num_baselines = 0; double exposure_sec = 0.0, interval_sec = 0.0, time_stamp = 0.0; if (!PyArg_ParseTuple(args, "OiiOOOddd", &capsule, &start_row, &num_baselines, &obj[0], &obj[1], &obj[2], &exposure_sec, &interval_sec, &time_stamp)) return 0; if (!(h = (oskar_MeasurementSet*) get_handle(capsule, name))) return 0; /* Make sure input objects are arrays. Convert if required. */ uu = (PyArrayObject*) PyArray_FROM_OF(obj[0], NPY_ARRAY_IN_ARRAY); vv = (PyArrayObject*) PyArray_FROM_OF(obj[1], NPY_ARRAY_IN_ARRAY); ww = (PyArrayObject*) PyArray_FROM_OF(obj[2], NPY_ARRAY_IN_ARRAY); if (!uu || !vv || !ww) goto fail; /* Check dimensions. */ if (num_baselines != (int) PyArray_SIZE(uu) || num_baselines != (int) PyArray_SIZE(vv) || num_baselines != (int) PyArray_SIZE(ww)) { PyErr_SetString(PyExc_RuntimeError, "Input data dimension mismatch."); goto fail; } /* Write the coordinates. */ Py_BEGIN_ALLOW_THREADS if (PyArray_TYPE(uu) == NPY_DOUBLE) oskar_ms_write_coords_d(h, start_row, num_baselines, (const double*)PyArray_DATA(uu), (const double*)PyArray_DATA(vv), (const double*)PyArray_DATA(ww), exposure_sec, interval_sec, time_stamp); else oskar_ms_write_coords_f(h, start_row, num_baselines, (const float*)PyArray_DATA(uu), (const float*)PyArray_DATA(vv), (const float*)PyArray_DATA(ww), exposure_sec, interval_sec, time_stamp); Py_END_ALLOW_THREADS Py_XDECREF(uu); Py_XDECREF(vv); Py_XDECREF(ww); return Py_BuildValue(""); fail: Py_XDECREF(uu); Py_XDECREF(vv); Py_XDECREF(ww); return 0; }
static void to_td_val(td_val_t *out, PyObject *pVal) { PyObject *pStr; td_array_t *arr; PyArrayObject *pArr; td_tag_t tag = py_type_to_td(pVal); switch (tag) { case TD_INT32: out->tag = TD_INT32; if (PyInt_Check(pVal)) out->int32_val = PyInt_AS_LONG(pVal); else out->int32_val = PyLong_AsLong(pVal); break; case TD_UINT32: out->tag = TD_UINT32; out->uint32_val = PyLong_AsUnsignedLong(pVal); break; case TD_INT64: out->tag = TD_INT64; out->int64_val = PyLong_AsLongLong(pVal); break; case TD_UINT64: out->tag = TD_UINT64; out->uint64_val = PyLong_AsUnsignedLongLong(pVal); break; case TD_DOUBLE: out->tag = TD_DOUBLE; out->double_val = PyFloat_AsDouble(pVal); break; case TD_UTF8: pStr = pVal; if (PyUnicode_Check(pStr)) pStr = PyUnicode_AsUTF8String(pStr); size_t len = PyString_Size(pStr); char* data = malloc((len+1)*sizeof(char)); strcpy(PyString_AsString(pStr), data); td_string_t *obj = malloc(sizeof(td_string_t)); obj->length = len; obj->data = (void*) data; out->tag = TD_UTF8; out->object = (void*) obj; break; case TD_ARRAY: arr = (td_array_t *)malloc(sizeof(td_array_t)); pArr = (PyArrayObject *) pVal; arr->data = PyArray_DATA(pArr); arr->length = PyArray_SIZE(pArr); arr->eltype = numpy_type_to_td(PyArray_TYPE(pArr)); arr->ndims = PyArray_NDIM(pArr); break; default: out->tag = TD_OBJECT; out->owner = td_env_python(NULL, NULL); out->object = pVal; } }
static PyObject* write_vis(PyObject* self, PyObject* args) { oskar_MeasurementSet* h = 0; PyObject *capsule = 0; PyObject *obj = 0; PyArrayObject *vis = 0; int start_row = 0, start_channel = 0; int num_channels = 0, num_baselines = 0, num_pols = 0; if (!PyArg_ParseTuple(args, "OiiiiO", &capsule, &start_row, &start_channel, &num_channels, &num_baselines, &obj)) return 0; if (!(h = get_handle(capsule))) return 0; /* Make sure input objects are arrays. Convert if required. */ vis = (PyArrayObject*) PyArray_FROM_OF(obj, NPY_ARRAY_IN_ARRAY); if (!vis) goto fail; /* Get precision of complex visibility data. */ if (!PyArray_ISCOMPLEX(vis)) { PyErr_SetString(PyExc_RuntimeError, "Input visibility data must be complex."); goto fail; } /* Check dimensions. */ num_pols = oskar_ms_num_pols(h); if (num_baselines * num_channels * num_pols != (int) PyArray_SIZE(vis)) { PyErr_SetString(PyExc_RuntimeError, "Input data dimension mismatch."); goto fail; } /* Allow threads. */ Py_BEGIN_ALLOW_THREADS /* Write the visibilities. */ if (PyArray_TYPE(vis) == NPY_DOUBLE) oskar_ms_write_vis_d(h, start_row, start_channel, num_channels, num_baselines, (const double*)PyArray_DATA(vis)); else oskar_ms_write_vis_f(h, start_row, start_channel, num_channels, num_baselines, (const float*)PyArray_DATA(vis)); /* Disallow threads. */ Py_END_ALLOW_THREADS Py_XDECREF(vis); return Py_BuildValue(""); fail: Py_XDECREF(vis); return 0; }
/* Fetch vector data from an iterator (view or copy) */ void _fff_vector_sync_with_PyArrayIter(fff_vector* y, const PyArrayIterObject* it, npy_intp axis) { if (y->owner) { PyArrayObject* ao = (PyArrayObject*) it->ao; COPY_BUFFER(y, PyArray_ITER_DATA(it), PyArray_STRIDE(ao, axis), PyArray_TYPE(ao), PyArray_ITEMSIZE(ao)); } else y->data = (double*) PyArray_ITER_DATA(it); return; }
fff_array* fff_array_fromPyArray(const PyArrayObject* x) { fff_array* y; fff_datatype datatype; unsigned int nbytes; size_t dimX = 1, dimY = 1, dimZ = 1, dimT = 1; size_t offX = 0, offY = 0, offZ = 0, offT = 0; size_t ndims = (size_t)PyArray_NDIM(x); /* Check that the input array has less than four dimensions */ if (ndims > 4) { FFF_ERROR("Input array has more than four dimensions", EINVAL); return NULL; } /* Check that the input array is aligned */ if (! PyArray_ISALIGNED(x)) { FFF_ERROR("Input array is not aligned", EINVAL); return NULL; } /* Match the data type */ datatype = fff_datatype_fromNumPy(PyArray_TYPE(x)); if (datatype == FFF_UNKNOWN_TYPE) { FFF_ERROR("Unrecognized data type", EINVAL); return NULL; } /* Dimensions and offsets */ nbytes = fff_nbytes(datatype); dimX = PyArray_DIM(x, 0); offX = PyArray_STRIDE(x, 0)/nbytes; if (ndims > 1) { dimY = PyArray_DIM(x, 1); offY = PyArray_STRIDE(x, 1)/nbytes; if (ndims > 2) { dimZ = PyArray_DIM(x, 2); offZ = PyArray_STRIDE(x, 2)/nbytes; if (ndims > 3) { dimT = PyArray_DIM(x, 3); offT = PyArray_STRIDE(x, 3)/nbytes; } } } /* Create array (not owner) */ y = (fff_array*)malloc(sizeof(fff_array)); *y = fff_array_view(datatype, (void*) PyArray_DATA(x), dimX, dimY, dimZ, dimT, offX, offY, offZ, offT); return y; }
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; }
MPI_Datatype type_map(PyArrayObject *x, int *count) { /* Return the MPI Datatype corresponding to the Python data type as follows TYPE py_type mpi_type bytes symbol ---------------------------------------- INT 4 6 4 'i' LONG 5 8 8 'l' FLOAT 6 10 4 'f' DOUBLE 12 11 8 'd' Also return the total number of elements in the array The Python datatype COMPLEX ('F') and COMPLEX_DOUBLE ('D') is treated as a special case to the absence of an MPI_COMPLEX datatype: Complex arrays are mapped to float or double arrays with real and imaginary parts alternating and count is updated. */ int py_type; MPI_Datatype mpi_type; *count = length(x); py_type = PyArray_TYPE(x); if (py_type == NPY_DOUBLE) mpi_type = MPI_DOUBLE; else if (py_type == NPY_INT) mpi_type = MPI_INT; else if (py_type == NPY_CDOUBLE) { mpi_type = MPI_DOUBLE; (*count) *= 2; } else if (py_type == NPY_FLOAT) mpi_type = MPI_FLOAT; else if (py_type == NPY_LONG) mpi_type = MPI_LONG; else if (py_type == NPY_CFLOAT) { mpi_type = MPI_FLOAT; (*count) *= 2; } else { /* FIXME: Should let caller decide about setting Python exception */ PyErr_Format(PyExc_ValueError, "Array must be of type int or float. I got py_type == %d", py_type); /* FIXME: consider MPI_DATATYPE_NULL */ return (MPI_Datatype) NULL; } //printf("Types: py_type=%d, mpi_type=%d\n", py_type, (int) mpi_type); return mpi_type; }
static double* coerce_ndarray_double(PyArrayObject *in, PyArrayObject **out) { int pcm_type = PyArray_TYPE(in); if (pcm_type==NPY_DOUBLE) return ((double *) PyArray_DATA(in)); else if (PyArray_CanCastSafely(pcm_type, NPY_DOUBLE)) { *out = (PyArrayObject*)PyArray_Cast(in, NPY_DOUBLE); return ((double *) PyArray_DATA(*out)); } else return NULL; }
/* 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; }
static PyObject *zero_if_zero_inplace(PyObject *self, PyObject *args) { PyObject* a = NULL; PyObject* b = NULL; npy_intp sz = 0, i; npy_complex64* tmp = NULL; npy_complex64* a_data = NULL; npy_float32* b_data = NULL; if (!PyArg_ParseTuple(args, "OO", &a, &b)) return NULL; if (!(PyArray_Check(a) && PyArray_Check(b))) { PyErr_SetString(PyExc_TypeError,"arguments must be array objects"); return NULL; } sz = PyArray_SIZE(a); if (sz != PyArray_SIZE(b)) { PyErr_SetString(PyExc_TypeError,"argument sizes must be equal"); return NULL; } if (! ((PyArray_TYPE(a) == PyArray_COMPLEX64) && (PyArray_TYPE(b) == PyArray_FLOAT32))) { PyErr_SetString(PyExc_TypeError,"argument types must be complex64 and float32"); return NULL; } a_data = (npy_complex64*)PyArray_DATA(a); b_data = (npy_float32*)PyArray_DATA(b); for (i=0; i<sz; ++i) { if (b_data[i]==0) { tmp = a_data + i; tmp->real = tmp->imag = 0.0; } } return Py_BuildValue(""); }
fvec_t * PyAubio_ArrayToCFvec (PyObject *input) { PyObject *array; fvec_t *vec; if (input == NULL) { PyErr_SetString (PyExc_ValueError, "input array is not a python object"); goto fail; } // parsing input object into a Py_fvec if (PyArray_Check(input)) { // we got an array, convert it to an fvec if (PyArray_NDIM (input) == 0) { PyErr_SetString (PyExc_ValueError, "input array is a scalar"); goto fail; } else if (PyArray_NDIM (input) > 1) { PyErr_SetString (PyExc_ValueError, "input array has more than one dimensions"); goto fail; } if (!PyArray_ISFLOAT (input)) { PyErr_SetString (PyExc_ValueError, "input array should be float"); goto fail; } else if (PyArray_TYPE (input) != AUBIO_NPY_SMPL) { PyErr_SetString (PyExc_ValueError, "input array should be float32"); goto fail; } else { // input data type is float32, nothing else to do array = input; } // vec = new_fvec (vec->length); // no need to really allocate fvec, just its struct member vec = (fvec_t *)malloc(sizeof(fvec_t)); vec->length = PyArray_SIZE (array); vec->data = (smpl_t *) PyArray_GETPTR1 (array, 0); } else if (PyObject_TypeCheck (input, &PyList_Type)) { PyErr_SetString (PyExc_ValueError, "does not convert from list yet"); return NULL; } else { PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input"); return NULL; } return vec; fail: return NULL; }
int not_doublevector(PyArrayObject *vec) { if (PyArray_TYPE(vec) != NPY_DOUBLE) { PyErr_SetString(PyExc_ValueError, "Vector is not a float or double vector."); return 1; } if (PyArray_NDIM(vec) != 1) { PyErr_Format(PyExc_ValueError, "Vector is not a 1 dimensional vector (%d).", PyArray_NDIM(vec)); return 1; } return 0; }
static PyObject *_eclipse(PyObject *self, PyObject *args) { int nthreads; double d, p, kap0, kap1, fp, alpha_t, alpha_o; PyArrayObject *ds, *flux; npy_intp i, dims[1]; if(!PyArg_ParseTuple(args, "Oddi", &ds, &p, &fp, &nthreads)) return NULL; //parses function input dims[0] = PyArray_DIMS(ds)[0]; flux = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_TYPE(ds)); //creates numpy array to store return flux values double *f_array = PyArray_DATA(flux); double *d_array = PyArray_DATA(ds); if(fabs(p - 0.5) < 1.e-3) p = 0.5; #if defined (_OPENMP) omp_set_num_threads(nthreads); #endif #if defined (_OPENMP) #pragma omp parallel for private(d, kap1, kap0) #endif for(i=0; i<dims[0]; i++) { d = d_array[i]; // separation of centers if(d >= 1. + p) { f_array[i] = 1. + fp; //planet fully visible } else if(d < 1. - p) { f_array[i] = 1.; //planet fully occulted } else //planet is crossing the limb { kap1=acos(fmin((1. - p*p + d*d)/2./d, 1.)); kap0=acos(fmin((p*p + d*d - 1.)/2./p/d, 1.)); alpha_t = (p*p*kap0 + kap1 - 0.5*sqrt(fmax(4.*d*d \ - pow(1. + d*d - p*p, 2.), 0.)))/M_PI; //transit depth alpha_o = alpha_t/p/p; //fraction of planet disk that is eclipsed by the star f_array[i] = 1. + fp*(1. - alpha_o); //planet partially occulted } } return PyArray_Return((PyArrayObject *)flux); }
int PyUFunc_PipelinedFunction(PyUFuncObject *ufunc, PyArrayObject **args, size_t start, size_t end) { int retval = 0; int i, nin = ufunc->nin, nout = ufunc->nout; int nop = nin + nout; PyArray_Descr *dtypes[NPY_MAXARGS]; PyArrayObject *op[NPY_MAXARGS]; NPY_ORDER order = NPY_KEEPORDER; NPY_CASTING casting = NPY_DEFAULT_ASSIGN_CASTING; int trivial_loop_ok = 1; for (i = 0; i < NPY_MAXARGS; ++i) { op[i] = NULL; dtypes[i] = NULL; } retval = ufunc->type_resolver(ufunc, casting, args, NULL, dtypes); if (retval < 0) { goto fail; } for(i = 0; i < nop; ++i) { size_t size = PyArray_SIZE(args[i]); if (size > 1) { npy_intp elements[1] = { end - start }; Py_XINCREF(PyArray_DESCR(args[i])); op[i] = (PyArrayObject*) PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(args[i]), 1, elements, NULL, PyArray_ElementPointer(args[i], start), NPY_ARRAY_CARRAY | !NPY_ARRAY_OWNDATA, NULL); } else { Py_XINCREF(args[i]); op[i] = args[i]; } if (PyArray_TYPE(args[i]) != dtypes[i]->type_num) { assert(i < nin); // Casting makes no sense for output arrays, only for input arrays. If we have to cast the output array something went wrong PyArrayObject *converted = (PyArrayObject*) PyArray_CastToType(op[i], dtypes[i], 0); Py_XDECREF(op[i]); op[i] = converted; } } retval = execute_legacy_ufunc_loop(ufunc, trivial_loop_ok, op, dtypes, order); for(i = 0; i < nop; ++i) { Py_XDECREF(op[i]); } fail: return retval; }
fff_vector* fff_vector_fromPyArray(const PyArrayObject* x) { fff_vector* y; int ok; npy_intp axis = _PyArray_main_axis(x, &ok); if (!ok) { FFF_ERROR("Input array is not a vector", EINVAL); return NULL; } y = _fff_vector_new_from_buffer(PyArray_DATA(x), PyArray_DIM(x, axis), PyArray_STRIDE(x, axis), PyArray_TYPE(x), PyArray_ITEMSIZE(x)); return y; }
int good_array(PyObject* o, int typenum) { if (!PyArray_Check(o)) { PyErr_SetString(PyExc_ValueError, "not a NumPy array" ); return 0; } if (PyArray_TYPE((PyArrayObject*)o) != typenum) { PyErr_SetString(PyExc_ValueError, "array of unexpected type"); return 0; } if (!PyArray_ISCARRAY((PyArrayObject*)o)) { PyErr_SetString(PyExc_ValueError, "array is not contiguous or not well behaved"); return 0; } return 1; }
PyObject *punwrap3D_Unwrap3D(PyObject *self, PyObject *args) { PyObject *op; PyArrayObject *phsArray, *retArray; float *wr_phs, *uw_phs; npy_intp *dims; int typenum_phs, ndim; PyArray_Descr *dtype_phs; if(!PyArg_ParseTuple(args, "O", &op)) { PyErr_SetString(PyExc_Exception, "Unwrap3D: Couldn't parse any args"); return NULL; } if(op==NULL) { PyErr_SetString(PyExc_Exception, "Unwrap3D: Arguments not read correctly"); return NULL; } typenum_phs = PyArray_TYPE(op); ndim = PyArray_NDIM(op); dims = PyArray_DIMS(op); if(typenum_phs != PyArray_FLOAT) { PyErr_SetString(PyExc_Exception, "Unwrap3D: I can only handle single-precision floating point numbers"); return NULL; } if(ndim < 3) { PyErr_SetString(PyExc_Exception, "Unwrap3D: I can only unwrap 3D arrays"); return NULL; } dtype_phs = PyArray_DescrFromType(typenum_phs); /* increasing reference here */ phsArray = (PyArrayObject *)PyArray_FROM_OTF(op, typenum_phs, 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); unwrap_phs(wr_phs, uw_phs, (int) dims[0], (int) dims[1], (int) dims[2]); Py_DECREF(phsArray); return PyArray_Return(retArray); }