Example #1
0
static PyObject *
dotblas_restoredot(PyObject *dummy, PyObject *args)
{
    PyArray_Descr *descr;

    if (!PyArg_ParseTuple(args, "")) return NULL;

    if (altered) {
        descr = PyArray_DescrFromType(PyArray_FLOAT);
        descr->f->dotfunc = oldFunctions[PyArray_FLOAT];
        oldFunctions[PyArray_FLOAT] = NULL;
        Py_XDECREF(descr);

        descr = PyArray_DescrFromType(PyArray_DOUBLE);
        descr->f->dotfunc = oldFunctions[PyArray_DOUBLE];
        oldFunctions[PyArray_DOUBLE] = NULL;
        Py_XDECREF(descr);

        descr = PyArray_DescrFromType(PyArray_CFLOAT);
        descr->f->dotfunc = oldFunctions[PyArray_CFLOAT];
        oldFunctions[PyArray_CFLOAT] = NULL;
        Py_XDECREF(descr);

        descr = PyArray_DescrFromType(PyArray_CDOUBLE);
        descr->f->dotfunc = oldFunctions[PyArray_CDOUBLE];
        oldFunctions[PyArray_CDOUBLE] = NULL;
        Py_XDECREF(descr);

        altered = FALSE;
    }

    Py_INCREF(Py_None);
    return Py_None;
}
Example #2
0
static PyObject *
dotblas_alterdot(PyObject *dummy, PyObject *args)
{
    PyArray_Descr *descr;

    if (!PyArg_ParseTuple(args, "")) return NULL;

    /* Replace the dot functions to the ones using blas */

    if (!altered) {
        descr = PyArray_DescrFromType(PyArray_FLOAT);
        oldFunctions[PyArray_FLOAT] = descr->f->dotfunc;
        descr->f->dotfunc = (PyArray_DotFunc *)FLOAT_dot;

        descr = PyArray_DescrFromType(PyArray_DOUBLE);
        oldFunctions[PyArray_DOUBLE] = descr->f->dotfunc;
        descr->f->dotfunc = (PyArray_DotFunc *)DOUBLE_dot;

        descr = PyArray_DescrFromType(PyArray_CFLOAT);
        oldFunctions[PyArray_CFLOAT] = descr->f->dotfunc;
        descr->f->dotfunc = (PyArray_DotFunc *)CFLOAT_dot;

        descr = PyArray_DescrFromType(PyArray_CDOUBLE);
        oldFunctions[PyArray_CDOUBLE] = descr->f->dotfunc;
        descr->f->dotfunc = (PyArray_DotFunc *)CDOUBLE_dot;

        altered = TRUE;
    }

    Py_INCREF(Py_None);
    return Py_None;
}
Example #3
0
static PyObject*
logical_or_popcount_neon_512_wrap(PyObject* self, PyObject* args)
{
  // get numpy.array([], numpy.uint8)
  PyArrayObject *image_pyobj, *mask_pyobj;
  char *image, *mask;
  PyArray_Descr *descr1, *descr2;
  npy_intp dims1[3], dims2[3];
  int pixels;

  if (!PyArg_ParseTuple(args, "O!O!i", 
              &PyArray_Type, &image_pyobj, 
              &PyArray_Type, &mask_pyobj,
              &pixels)){
      return NULL;
  }

  descr1 = PyArray_DescrFromType(NPY_UINT8);
  descr2 = PyArray_DescrFromType(NPY_UINT8);

  if (PyArray_AsCArray((PyObject **) &image_pyobj, (void *)&image, dims1, 1, descr1) < 0 ||
          PyArray_AsCArray((PyObject **) &mask_pyobj, (void *)&mask, dims2, 1, descr2) < 0) {
      PyErr_SetString(PyExc_TypeError, "error converting to c array");
      return NULL;
  }
  
  uint32_t popcnt = logical_or_popcount_neon_512(image, mask, pixels);

  PyArray_Free((PyObject *) image_pyobj, (void *) image);
  PyArray_Free((PyObject *) mask_pyobj, (void *) mask);

  return Py_BuildValue("i", popcnt);
}
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;
}
Example #5
0
PyObject *
fftpack_rfftb(PyObject *NPY_UNUSED(self), PyObject *args)
{
    PyObject *op1, *op2;
    PyArrayObject *data, *ret;
    PyArray_Descr *descr;
    double *wsave, *dptr, *rptr;
    npy_intp nsave;
    int npts, nrepeats, i;

    if(!PyArg_ParseTuple(args, "OO", &op1, &op2)) {
        return NULL;
    }
    data = (PyArrayObject *)PyArray_ContiguousFromObject(op1,
            NPY_CDOUBLE, 1, 0);
    if (data == NULL) {
        return NULL;
    }
    npts = PyArray_DIM(data, PyArray_NDIM(data) - 1);
    ret = (PyArrayObject *)PyArray_Zeros(PyArray_NDIM(data), PyArray_DIMS(data),
            PyArray_DescrFromType(NPY_DOUBLE), 0);

    descr = PyArray_DescrFromType(NPY_DOUBLE);
    if (PyArray_AsCArray(&op2, (void *)&wsave, &nsave, 1, descr) == -1) {
        goto fail;
    }
    if (data == NULL || ret == NULL) {
        goto fail;
    }
    if (nsave != npts*2 + 15) {
        PyErr_SetString(ErrorObject, "invalid work array for fft size");
        goto fail;
    }

    nrepeats = PyArray_SIZE(ret)/npts;
    rptr = (double *)PyArray_DATA(ret);
    dptr = (double *)PyArray_DATA(data);

    NPY_SIGINT_ON;
    for (i = 0; i < nrepeats; i++) {
        memcpy((char *)(rptr + 1), (dptr + 2), (npts - 1)*sizeof(double));
        rptr[0] = dptr[0];
        rfftb(npts, rptr, wsave);
        rptr += npts;
        dptr += npts*2;
    }
    NPY_SIGINT_OFF;
    PyArray_Free(op2, (char *)wsave);
    Py_DECREF(data);
    return (PyObject *)ret;

fail:
    PyArray_Free(op2, (char *)wsave);
    Py_XDECREF(data);
    Py_XDECREF(ret);
    return NULL;
}
Example #6
0
static int QUATERNION_setitem(PyObject *op, char *ov, PyArrayObject *ap)
{
    quaternion q;

    if (PyArray_IsScalar(op, Quaternion)) {
        q = ((PyQuaternionScalarObject *)op)->obval;
    }
    else {
        q.w = PyFloat_AsDouble(PyTuple_GetItem(op, 0));
        q.x = PyFloat_AsDouble(PyTuple_GetItem(op, 1));
        q.y = PyFloat_AsDouble(PyTuple_GetItem(op, 2));
        q.z = PyFloat_AsDouble(PyTuple_GetItem(op, 3));
    }
    if (PyErr_Occurred()) {
        if (PySequence_Check(op)) {
            PyErr_Clear();
            PyErr_SetString(PyExc_ValueError,
                    "setting an array element with a sequence.");
        }
        return -1;
    }
    if (ap == NULL || PyArray_ISBEHAVED(ap))
        *((quaternion *)ov)=q;
    else {
        PyArray_Descr *descr;
        descr = PyArray_DescrFromType(NPY_DOUBLE);
        descr->f->copyswap(ov, &q.w, !PyArray_ISNOTSWAPPED(ap), NULL);
        descr->f->copyswap(ov+8, &q.x, !PyArray_ISNOTSWAPPED(ap), NULL);
        descr->f->copyswap(ov+16, &q.y, !PyArray_ISNOTSWAPPED(ap), NULL);
        descr->f->copyswap(ov+24, &q.z, !PyArray_ISNOTSWAPPED(ap), NULL);
        Py_DECREF(descr);
    }

    return 0;
}
Example #7
0
static PyObject *
QUATERNION_getitem(char *ip, PyArrayObject *ap)
{
    quaternion q;
    PyObject *tuple;

    if ((ap == NULL) || PyArray_ISBEHAVED_RO(ap)) {
        q = *((quaternion *)ip);
    }
    else {
        PyArray_Descr *descr;
        descr = PyArray_DescrFromType(NPY_DOUBLE);
        descr->f->copyswap(&q.w, ip, !PyArray_ISNOTSWAPPED(ap), NULL);
        descr->f->copyswap(&q.x, ip+8, !PyArray_ISNOTSWAPPED(ap), NULL);
        descr->f->copyswap(&q.y, ip+16, !PyArray_ISNOTSWAPPED(ap), NULL);
        descr->f->copyswap(&q.z, ip+24, !PyArray_ISNOTSWAPPED(ap), NULL);
        Py_DECREF(descr);
    }

    tuple = PyTuple_New(4);
    PyTuple_SET_ITEM(tuple, 0, PyFloat_FromDouble(q.w));
    PyTuple_SET_ITEM(tuple, 1, PyFloat_FromDouble(q.x));
    PyTuple_SET_ITEM(tuple, 2, PyFloat_FromDouble(q.y));
    PyTuple_SET_ITEM(tuple, 3, PyFloat_FromDouble(q.z));

    return tuple;
}
Example #8
0
PyArrayObject *func_PyArray_NewFromDescr(int datatype, const int ndims,
                                         Py_intptr_t *dims) {
  return reinterpret_cast<PyArrayObject *>(PyArray_NewFromDescr(
      &PyArray_Type, PyArray_DescrFromType(datatype), ndims, // rank
      dims, // Length in each dimension
      nullptr, NULL, 0, nullptr));
}
static PyObject *Py_longdouble2string(PyObject *self, PyObject *args) {
    PyObject *longdouble_obj = NULL;
    long double _longdouble;
    char _string[STRINGLEN];
    long ndigit = 0;

    if (!PyArg_ParseTuple(args,
			  (char*)"Ol",
			  &longdouble_obj,
			  &ndigit)) {
	fprintf(stderr,"Failed to parse longdouble object.\n");
	return NULL;
    }

    // raise an exception if this isn't a scalar...
    if (!PyArray_CheckScalar(longdouble_obj)) {
	PyErr_SetString(LongDoubleError,"Input long double must be a scalar.");
	return NULL;
    }

    // cast to long double
    PyArray_CastScalarToCtype(longdouble_obj, &_longdouble, PyArray_DescrFromType(NPY_LONGDOUBLE));

    // do the conversion
    if (longdouble2string(_longdouble, _string, ndigit) < 0) {
	PyErr_SetString(LongDoubleError,"Error with conversion.");
	return NULL;
    }

    return PyString_FromString(_string);
}
Example #10
0
/*@null@*/ static INLINE PyObject*
_PyArrayProxy_New(
    /*@shared@*/ PyObject* self,
    int nd,
    const npy_intp* dims,
    int typenum,
    const void* data,
    const int flags) {

  PyArray_Descr* type_descr = NULL;
  PyObject*      result     = NULL;

  type_descr = (PyArray_Descr*)PyArray_DescrFromType(typenum);
  if (type_descr == NULL) {
    return NULL;
  }

  result = (PyObject*)PyArray_NewFromDescr(
      &PyArray_Type,
      type_descr,
      nd, (npy_intp*)dims,
      NULL,
      (void*)data,
      NPY_C_CONTIGUOUS | flags,
      NULL);

  if (result == NULL) {
    return NULL;
  }
  Py_INCREF(self);
  PyArray_BASE(result) = (PyObject*)self;
  return result;
}
// Static helper functions
// =============================================================================
double * Epetra_NumPySerialSymDenseMatrix::getArray(PyObject * pyObject)
{
  // If tmp_array is NULL, build a PyArrayObject from the pyObject
  if (!tmp_array)
  {
    // If pyObject is an int, then emulate an int-int constructor
    if (PyInt_Check(pyObject))
    {
      int numRows = (int) PyInt_AsLong(pyObject);
      npy_intp dimensions[ ] = {numRows, numRows};
      tmp_array = (PyArrayObject *)
	PyArray_SimpleNew(2,dimensions,NPY_DOUBLE);
    }
    // If pyObject is not a bool nor an int, try to build a
    // contiguous 2D PyArrayObject from the pyObject
    else
    {
      // This function returns a borrowed ptr: no DECREF
      PyArray_Descr * dtype = 
	PyArray_DescrFromType(NPY_DOUBLE);
      tmp_array = (PyArrayObject *) PyArray_FromAny(pyObject, dtype, 2, 2,
						    NPY_ARRAY_FARRAY, NULL);
    }
  }
  // If no array has been correctly constructed, clean up and throw a
  // PythonException
  if (!tmp_array)
  {
    cleanup();
    throw PythonException();
  }

  return (double*)(PyArray_DATA(tmp_array));
}
// =============================================================================
void Epetra_NumPySerialSymDenseMatrix::setArray(bool copy)
{
  if (tmp_array)
  {
    array     = tmp_array;
    tmp_array = NULL;
  }
  else
  {
    npy_intp dimensions[ ] = { M(), N() };
    double * data = NULL;
    if (!copy) data = Epetra_SerialSymDenseMatrix::A();
    // This NumPy function returns a borrowed pointer: no DECREF
    PyArray_Descr * dtype  = PyArray_DescrFromType(NPY_DOUBLE);
    array = (PyArrayObject*)
      PyArray_NewFromDescr(&PyArray_Type,dtype,2,dimensions,NULL,(void*)data,
			   NPY_ARRAY_FARRAY,NULL);
    if (!array)
    {
      cleanup();
      throw PythonException();
    }
    if (copy)
    {
      double * oldData = Epetra_SerialSymDenseMatrix::A();
      double * newData = (double*) PyArray_DATA(array);
      int      size    = dimensions[0] * dimensions[1];
      for (int i=0; i<size; ++i) newData[i] = oldData[i];
    }
  }
}
Example #13
0
 static void* convertible(PyObject* ptr)
 {
     if (!PyArray_Check(ptr))
     {
         return NULL;
     }
     
     PyObject* retval(PyArray_CastToType(
                          reinterpret_cast<PyArrayObject*>(ptr),
                          PyArray_DescrFromType(
                              peer::util::get_numpy_typecode<
                                  native_type::value_type >::value ), 0) );
     if (!retval)
     {
         return NULL;
     }
     
     if (PyObject_Size(retval) != 3)
     {
         boost::python::decref(retval);
         return NULL;
     }
     
     return retval;
 }
Example #14
0
static void register_cast_function(int sourceType, int destType, PyArray_VectorUnaryFunc *castfunc)
{
    PyArray_Descr *descr = PyArray_DescrFromType(sourceType);
    PyArray_RegisterCastFunc(descr, destType, castfunc);
    PyArray_RegisterCanCast(descr, destType, NPY_NOSCALAR);
    Py_DECREF(descr);
}
Example #15
0
PyObject *
multifab_as_numpy (PyObject * self, PyObject * args)
{
  int ndim;
  long cptr;
  double *ptr;

  PyObject *arr = NULL;
  npy_intp dims[4];
  int idims[4];

  if (!PyArg_ParseTuple (args, "li", &cptr, &nbox))
    return NULL;

  multifab_as_numpy_f((void *) cptr, nbox, idims, &ptr);
  dims[0] = idims[0];
  dims[1] = idims[1];
  dims[2] = idims[2];
  dims[3] = idims[3];
  dims[ndim] = nc;

  arr = PyArray_NewFromDescr(&PyArray_Type,
                             PyArray_DescrFromType(NPY_DOUBLE), ndim+1, dims, NULL,
                             ptr, NPY_FORTRAN|NPY_WRITEABLE, NULL);

  Py_INCREF(arr);
  return arr;
}
Example #16
0
static PyObject*
IkaMatcher2_encode_wrap(PyObject* self, PyObject* args)
{
  // get numpy.array([], numpy.uint8)
  PyArrayObject *dest_pyobj, *src_pyobj;
  char *dest, *src;
  PyArray_Descr *descr;
  npy_intp dims[1];
  int pixels;
  int nd = 1; //number_of_dimensions

  if (!PyArg_ParseTuple(args, "O!O!i", 
              &PyArray_Type, &dest_pyobj, 
              &PyArray_Type, &src_pyobj,
              &pixels)){
      return NULL;
  }

  descr = PyArray_DescrFromType(NPY_UINT8);

  if (PyArray_AsCArray((PyObject **) &dest_pyobj, (void *)&dest, dims, nd, descr) < 0 ||
          PyArray_AsCArray((PyObject **) &src_pyobj, (void *)&src, dims, nd, descr) < 0) {
      PyErr_SetString(PyExc_TypeError, "error converting to c array");
      return NULL;
  }
  
  IkaMatcher2_encode(dest, src, pixels);

  return PyArray_Return(dest_pyobj);
}
Example #17
0
void Tomography::appendSinogram(PyObject *sinogram, PyObject *angles)
{
	hlp::python::Ref sinogramTmp =
		PyArray_FromAny(sinogram, PyArray_DescrFromType(NPY_FLOAT), 2, 2, NPY_ARRAY_ALIGNED | NPY_ARRAY_FORCECAST, nullptr);
	hlp::python::Ref anglesTmp = PyArray_FromAny(angles, PyArray_DescrFromType(NPY_FLOAT), 1, 1, NPY_ARRAY_ALIGNED | NPY_ARRAY_FORCECAST, nullptr);
	PyArrayObject *sinogramPy = (PyArrayObject *)sinogramTmp.ptr;
	PyArrayObject *anglesPy = (PyArrayObject *)anglesTmp.ptr;

	const float *sinogramData = reinterpret_cast<float *>(PyArray_DATA(sinogramPy));
	const float *anglesData = reinterpret_cast<float *>(PyArray_DATA(anglesPy));

	ndim::pointer<const float, 2> sinogramPtr(sinogramData, ndim::getShape<2>(sinogramPy), ndim::getStrides<2>(sinogramPy));
	ndim::pointer<const float, 1> anglesPtr(anglesData, ndim::getShape<1>(anglesPy), ndim::getStrides<1>(anglesPy));

	tomo::Tomography::appendSinogram(sinogramPtr, anglesPtr);
}
Example #18
0
static void
QUATERNION_copyswap(quaternion *dst, quaternion *src,
        int swap, void *NPY_UNUSED(arr))
{
    PyArray_Descr *descr;
    descr = PyArray_DescrFromType(NPY_DOUBLE);
    descr->f->copyswapn(dst, sizeof(double), src, sizeof(double), 4, swap, NULL);
    Py_DECREF(descr);
}
Example #19
0
hlp::python::Ref ndimToNumpy(ndim::pointer<const float, 2> data) {
	hlp::python::Gil gil;
	hlp::unused(gil);

	hlp::python::Ref containerRef = ndim::makePyArrayRef(data, gil);

	hlp::python::Ref result = PyArray_FromAny(containerRef.ptr, PyArray_DescrFromType(NPY_FLOAT), 2, 2, NPY_ARRAY_ENSURECOPY, nullptr);

	return result;
}
Example #20
0
static PyArray_Descr *
_descr_from_subtype(PyObject *type)
{
    PyObject *mro;
    mro = ((PyTypeObject *)type)->tp_mro;
    if (PyTuple_GET_SIZE(mro) < 2) {
        return PyArray_DescrFromType(PyArray_OBJECT);
    }
    return PyArray_DescrFromTypeObject(PyTuple_GET_ITEM(mro, 1));
}
Example #21
0
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);
    
}
Example #22
0
void Tomography::setReconstruction(PyObject *reconstruction)
{
	hlp::python::Ref reconstructionTmp =
		PyArray_FromAny(reconstruction, PyArray_DescrFromType(NPY_FLOAT), 2, 2, NPY_ARRAY_ALIGNED | NPY_ARRAY_FORCECAST, nullptr);
	PyArrayObject *reconstructionPy = (PyArrayObject *)reconstructionTmp.ptr;

	const float *reconstructionData = reinterpret_cast<float *>(PyArray_DATA(reconstructionPy));

	ndim::pointer<const float, 2> reconstructionPtr(reconstructionData, ndim::getShape<2>(reconstructionPy), ndim::getStrides<2>(reconstructionPy));

	tomo::Tomography::setReconstruction(reconstructionPtr);
}
Example #23
0
NPY_NO_EXPORT PyArray_Descr *
_array_find_python_scalar_type(PyObject *op)
{
    if (PyFloat_Check(op)) {
        return PyArray_DescrFromType(NPY_DOUBLE);
    }
    else if (PyComplex_Check(op)) {
        return PyArray_DescrFromType(NPY_CDOUBLE);
    }
    else if (PyInt_Check(op)) {
        /* bools are a subclass of int */
        if (PyBool_Check(op)) {
            return PyArray_DescrFromType(NPY_BOOL);
        }
        else {
            return  PyArray_DescrFromType(NPY_LONG);
        }
    }
    else if (PyLong_Check(op)) {
        /* if integer can fit into a longlong then return that*/
        if ((PyLong_AsLongLong(op) == -1) && PyErr_Occurred()) {
            PyErr_Clear();
            return PyArray_DescrFromType(NPY_OBJECT);
        }
        return PyArray_DescrFromType(NPY_LONGLONG);
    }
    return NULL;
}
Example #24
0
void Tomography::setOpenBeam(PyObject *openBeam)
{
	hlp::python::Ref openBeamTmp =
		PyArray_FromAny(openBeam, PyArray_DescrFromType(NPY_FLOAT), 1, 1, NPY_ARRAY_ALIGNED | NPY_ARRAY_FORCECAST, nullptr);

	PyArrayObject *openBeamPy = (PyArrayObject *)openBeamTmp.ptr;

	const float *openBeamData = reinterpret_cast<float *>(PyArray_DATA(openBeamPy));

	ndim::pointer<const float, 1> openBeamPtr(openBeamData, ndim::getShape<1>(openBeamPy), ndim::getStrides<1>(openBeamPy));

	tomo::Tomography::setOpenBeam(openBeamPtr);
}
Example #25
0
PyObject * wrap_double_array(double* d, int len) {
  init_numpy();
  PyArray_Descr *type = PyArray_DescrFromType(NPY_DOUBLE);
  npy_intp dim[1] = {len};
  npy_intp strides[1] = {sizeof(double)};
  PyObject* arr = PyArray_NewFromDescr( &PyArray_Type, type,
					1, dim, strides,
					d,
					NPY_CONTIGUOUS | NPY_WRITEABLE,
					NULL /*PyObject *obj*/ ); 
  PyArray_BASE(arr) = make_deallocator_for(d, 0);
  return arr;
}
Example #26
0
PyObject * wrapDMat(DMat d) {
  init_numpy();
  PyArray_Descr *type = PyArray_DescrFromType(NPY_DOUBLE);
  npy_intp dim[2] = {d->rows, d->cols};
  npy_intp strides[2] = {d->cols*sizeof(double), sizeof(double)};
  PyObject* arr = PyArray_NewFromDescr( &PyArray_Type, type,
					2, dim, strides,
					d->value[0],
					NPY_CONTIGUOUS | NPY_WRITEABLE,
					NULL /*PyObject *obj*/ ); 
  PyArray_BASE(arr) = make_deallocator_for(d->value, 1);
  return arr;
}
Example #27
0
static void
QUATERNION_copyswapn(quaternion *dst, npy_intp dstride,
        quaternion *src, npy_intp sstride,
        npy_intp n, int swap, void *NPY_UNUSED(arr))
{
    PyArray_Descr *descr;
    descr = PyArray_DescrFromType(NPY_DOUBLE);
    descr->f->copyswapn(&dst->w, dstride, &src->w, sstride, n, swap, NULL);
    descr->f->copyswapn(&dst->x, dstride, &src->x, sstride, n, swap, NULL);
    descr->f->copyswapn(&dst->y, dstride, &src->y, sstride, n, swap, NULL);
    descr->f->copyswapn(&dst->z, dstride, &src->z, sstride, n, swap, NULL);
    Py_DECREF(descr);    
}
Example #28
0
PyObject *cloneToNDArray(const ContainerType &cdata) {
  npy_intp dims[1] = {cdata.size()};
  int datatype = NDArrayTypeIndex<typename ContainerType::value_type>::typenum;
  PyObject *nparray =
      PyArray_NewFromDescr(&PyArray_Type, PyArray_DescrFromType(datatype),
                           1,    // rank 1
                           dims, // Length in each dimension
                           NULL, NULL, 0, NULL);

  void *arrayData = PyArray_DATA(nparray);
  const void *data = cdata.data();
  std::memcpy(arrayData, data, PyArray_ITEMSIZE(nparray) * dims[0]);
  return (PyObject *)nparray;
}
Example #29
0
static PyObject* spherematch_kdtree_get_data(PyObject* self, PyObject* args) {
  PyArrayObject* pyX;
  double* X;
  PyObject* rtn;
  npy_intp dims[2];
  long i;
  kdtree_t* kd;
  int k, D, N;
  //npy_int* I;
  npy_uint32* I;
  PyObject* pyO;
  PyObject* pyI;
  // this is the type returned by kdtree_rangesearch
  PyArray_Descr* dtype = PyArray_DescrFromType(NPY_UINT32);
  int req = NPY_C_CONTIGUOUS | NPY_ALIGNED | NPY_NOTSWAPPED | NPY_ELEMENTSTRIDES;

  if (!PyArg_ParseTuple(args, "lO", &i, &pyO)) {
    PyErr_SetString(PyExc_ValueError, "need two args: kdtree identifier (int), index array (numpy array of ints)");
    return NULL;
  }
  // Nasty!
  kd = (kdtree_t*)i;
  D = kd->ndim;

  Py_INCREF(dtype);
  pyI = PyArray_FromAny(pyO, dtype, 1, 1, req, NULL);
  if (!pyI) {
    PyErr_SetString(PyExc_ValueError, "Failed to convert index array to np array of int");
    Py_XDECREF(dtype);
    return NULL;
  }
  N = (int)PyArray_DIM(pyI, 0);

  dims[0] = N;
  dims[1] = D;

  pyX = (PyArrayObject*)PyArray_SimpleNew(2, dims, NPY_DOUBLE);
  X = PyArray_DATA(pyX);
  I = PyArray_DATA(pyI);

  for (k=0; k<N; k++) {
    kdtree_copy_data_double(kd, I[k], 1, X);
    X += D;
  }
  Py_DECREF(pyI);
  Py_DECREF(dtype);
  rtn = Py_BuildValue("O", pyX);
  Py_DECREF(pyX);
  return rtn;
}
Example #30
0
static int register_ldouble_to_qdouble_cast(int npy_registered_quadnum)
{
    PyArray_Descr* from_descr = PyArray_DescrFromType(NPY_LONGDOUBLE);
    int safe = 1;

    if (PyArray_RegisterCastFunc(from_descr, npy_registered_quadnum, npycast_ldouble_to_quad) < 0) {
        return -1;
    }
    if (safe && PyArray_RegisterCanCast(from_descr, npy_registered_quadnum, NPY_NOSCALAR) < 0) {
        return -1;
    }

    return 0;
}