Exemplo n.º 1
0
PyObject *
convertToNumPyArray(const Domi::MDArrayView< T > & mdArrayView)
{
  // Get the number of dimensions and initialize the dimensions and
  // strides arrays
  int numDims = mdArrayView.numDims();
  Teuchos::Array< npy_intp > dims(numDims);
  Teuchos::Array< npy_intp > strides(numDims);
  int typecode = NumPy_TypeCode< T >();

  // Set the dimensions and strides
  for (int axis = 0; axis < numDims; ++axis)
  {
    dims[   axis] = mdArrayView.dimension(axis);
    strides[axis] = mdArrayView.strides()[axis];
  }
  
  // Get the data pointer and flags, based on data layout
  void * data = (void*) mdArrayView.getRawPtr();
  int flags = (mdArrayView.layout() == Domi::C_ORDER) ? NPY_ARRAY_CARRAY :
    NPY_ARRAY_FARRAY;

  // Return the result
  return PyArray_New(&PyArray_Type,
                     numDims,
                     dims.getRawPtr(),
                     typecode,
                     strides.getRawPtr(),
                     data,
                     0,
                     flags,
                     NULL);
}
Exemplo n.º 2
0
static PyArrayObject *mx2numeric(const mxArray *pArray)
{
  //current function returns PyArrayObject in c order currently
  mwSize nd;
  npy_intp  pydims[NPY_MAXDIMS];
  PyArrayObject *lRetval = NULL,*t=NULL;
  const double *lPR;
  const double *lPI;
  pyassert(PyArray_API,
           "Unable to perform this function without NumPy installed");

  nd = mxGetNumberOfDimensions(pArray);
  {
    const mwSize *dims;
    dims = mxGetDimensions(pArray);
    for (mwSize i=0; i != nd; i++){
        pydims[i] = static_cast<npy_intp>(dims[i]);
    }
  }
 //this function creates a fortran array
  t = (PyArrayObject *)
    PyArray_New(&PyArray_Type,static_cast<npy_intp>(nd), pydims,
                mxIsComplex(pArray) ? PyArray_CDOUBLE : PyArray_DOUBLE,
                NULL, // strides
                NULL, // data
                0,    //(ignored itemsize),
                NPY_F_CONTIGUOUS, 
                NULL); //  obj
  if (t == NULL) return NULL;
  
  lPR  = mxGetPr(pArray);
  if (mxIsComplex(pArray)) {
    double *lDst = (double *)PyArray_DATA(t);
    // AWMS unsigned int almost certainly can overflow on some platforms!
    npy_intp numberOfElements = PyArray_SIZE(t);
    lPI = mxGetPi(pArray);
    for (mwIndex i = 0; i != numberOfElements; i++) {
      *lDst++ = *lPR++;
      *lDst++ = *lPI++;
    }
  }
  else {
    double *lDst = (double *)PyArray_DATA(t);
    npy_intp numberOfElements = PyArray_SIZE(t);
    for (mwIndex i = 0; i != numberOfElements; i++) {
      *lDst++ = *lPR++;
    }
  }
  
  lRetval = (PyArrayObject *)PyArray_FromArray(t,NULL,NPY_C_CONTIGUOUS|NPY_ALIGNED|NPY_WRITEABLE);
  Py_DECREF(t);
  
  return lRetval;
  error_return:
  return NULL;
}
Exemplo n.º 3
0
static PyObject *
fortran_getattr(PyFortranObject *fp, char *name) {
    int i,j,k,flag;
    if (fp->dict != NULL) {
        PyObject *v = PyDict_GetItemString(fp->dict, name);
        if (v != NULL) {
            Py_INCREF(v);
            return v;
        }
    }
    for (i=0,j=1;i<fp->len && (j=strcmp(name,fp->defs[i].name));i++);
    if (j==0)
        if (fp->defs[i].rank!=-1) {                   /* F90 allocatable array */
            if (fp->defs[i].func==NULL) return NULL;
            for(k=0;k<fp->defs[i].rank;++k)
                fp->defs[i].dims.d[k]=-1;
            save_def = &fp->defs[i];
            (*(fp->defs[i].func))(&fp->defs[i].rank,fp->defs[i].dims.d,set_data,&flag);
            if (flag==2)
                k = fp->defs[i].rank + 1;
            else
                k = fp->defs[i].rank;
            if (fp->defs[i].data !=NULL) {              /* array is allocated */
                PyObject *v = PyArray_New(&PyArray_Type, k, fp->defs[i].dims.d,
                                          fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_FARRAY,
                                          NULL);
                if (v==NULL) return NULL;
                /* Py_INCREF(v); */
                return v;
            } else {                                    /* array is not allocated */
                Py_INCREF(Py_None);
                return Py_None;
            }
        }
    if (strcmp(name,"__dict__")==0) {
        Py_INCREF(fp->dict);
        return fp->dict;
    }
    if (strcmp(name,"__doc__")==0) {
        PyObject *s = PyString_FromString("");
        for (i=0;i<fp->len;i++)
            PyString_ConcatAndDel(&s,fortran_doc(fp->defs[i]));
        if (PyDict_SetItemString(fp->dict, name, s))
            return NULL;
        return s;
    }
    if ((strcmp(name,"_cpointer")==0) && (fp->len==1)) {
        PyObject *cobj = PyCObject_FromVoidPtr((void *)(fp->defs[0].data),NULL);
        if (PyDict_SetItemString(fp->dict, name, cobj))
            return NULL;
        return cobj;
    }
    return Py_FindMethod(fortran_methods, (PyObject *)fp, name);
}
Exemplo n.º 4
0
Arquivo: fffpy.c Projeto: FNNDSC/nipy
/* 
   Copy a buffer using numpy. 

   Copy buffer x into y assuming that y is contiguous. 
*/ 
void fff_vector_fetch_using_NumPy(fff_vector* y, const char* x, npy_intp stride, int type, int itemsize) 
{
  npy_intp dim[1] = {(npy_intp)y->size}; 
  npy_intp strides[1] = {stride};   
  PyArrayObject* X = (PyArrayObject*) PyArray_New(&PyArray_Type, 1, dim, type, strides, 
						  (void*)x, itemsize, NPY_BEHAVED, NULL); 
  PyArrayObject* Y = (PyArrayObject*) PyArray_SimpleNewFromData(1, dim, NPY_DOUBLE, (void*)y->data);
  PyArray_CastTo(Y, X); 
  Py_XDECREF(Y);
  Py_XDECREF(X);
  return; 
}
Exemplo n.º 5
0
PyObject *
PyFortranObject_New(FortranDataDef* defs, f2py_void_func init) {
    int i;
    PyFortranObject *fp = NULL;
    PyObject *v = NULL;
    if (init!=NULL)                           /* Initialize F90 module objects */
        (*(init))();
    if ((fp = PyObject_New(PyFortranObject, &PyFortran_Type))==NULL) return NULL;
    if ((fp->dict = PyDict_New())==NULL) return NULL;
    fp->len = 0;
    while (defs[fp->len].name != NULL) fp->len++;
    if (fp->len == 0) goto fail;
    fp->defs = defs;
    for (i=0;i<fp->len;i++)
        if (fp->defs[i].rank == -1) {                      /* Is Fortran routine */
            v = PyFortranObject_NewAsAttr(&(fp->defs[i]));
            if (v==NULL) return NULL;
            PyDict_SetItemString(fp->dict,fp->defs[i].name,v);
        } else
            if ((fp->defs[i].data)!=NULL) { /* Is Fortran variable or array (not allocatable) */
                if (fp->defs[i].type == NPY_STRING) {
                    int n = fp->defs[i].rank-1;
                    v = PyArray_New(&PyArray_Type, n, fp->defs[i].dims.d,
                                    NPY_STRING, NULL, fp->defs[i].data, fp->defs[i].dims.d[n],
                                    NPY_FARRAY, NULL);
                }
                else {
                    v = PyArray_New(&PyArray_Type, fp->defs[i].rank, fp->defs[i].dims.d,
                                    fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_FARRAY,
                                    NULL);
                }
                if (v==NULL) return NULL;
                PyDict_SetItemString(fp->dict,fp->defs[i].name,v);
            }
    Py_XDECREF(v);
    return (PyObject *)fp;
 fail:
    Py_XDECREF(v);
    return NULL;
}
Exemplo n.º 6
0
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; 
}		     
Exemplo n.º 7
0
PyObjectHandle LuaToPythonConverter::convertTensor(lua_State* L,
                                                   thpp::Tensor<T>& tensor,
                                                   int numpyType) {
  npy_intp zero = 0;
  int ndims;
  std::unique_ptr<npy_intp[]> dims;
  npy_intp* dimsPtr;
  std::unique_ptr<npy_intp[]> strides;

  // Numpy and Torch disagree on empty tensors. In Torch, an empty tensor
  // is a tensor with zero dimensions. In Numpy, a tensor with zero dimensions
  // is a scalar (with one element). So we'll convert an empty Torch tensor
  // to a 1d Numpy tensor of shape [0]. Also see pushTensor in PythonToLua.cpp.
  if (tensor.ndims() != 0) {
    ndims = tensor.ndims();
    auto tsizes = tensor.sizes();
    DCHECK_EQ(tsizes.size(), ndims);

    dims.reset(new npy_intp[ndims]);
    dimsPtr = dims.get();
    std::copy(tsizes.begin(), tsizes.end(), dims.get());

    if (!tensor.isContiguous()) {
      auto tstrides = tensor.strides();
      DCHECK_EQ(tstrides.size(), ndims);

      strides.reset(new npy_intp[ndims]);

      // Numpy strides use bytes; Torch strides use element counts.
      for (int i = 0; i < ndims; ++i) {
        strides[i] = tstrides[i] * sizeof(T);
      }
    }
  } else {
    ndims = 1;
    dimsPtr = &zero;
  }

  PyObjectHandle obj(PyArray_New(
      &PyArray_Type, ndims, dimsPtr, numpyType,
      strides.get(), tensor.data(), 0,
      NPY_ARRAY_ALIGNED, nullptr));
  checkPythonError(obj, L, "create numpy.ndarray of type {}", numpyType);

  // Create a PythonStorage object to hold the reference count.
  // PyArray_SetBaseObject steals the reference to the base object.
  int r = PyArray_SetBaseObject(reinterpret_cast<PyArrayObject*>(obj.get()),
                                PythonStorage<T>::allocate(
                                    L, tensor.storage()).release());
  checkPythonError(r != -1, L, "SetBaseObject on numpy.ndarray");
  return obj;
}
Exemplo n.º 8
0
PyObject* PyArray_FromMatrixXd(const MatrixXd& mat) {
	// matrix dimensionality
	npy_intp dims[2];
	dims[0] = mat.rows();
	dims[1] = mat.cols();

	// allocate PyArray
	#ifdef EIGEN_DEFAULT_TO_ROW_MAJOR
	PyObject* array = PyArray_New(&PyArray_Type, 2, dims, NPY_DOUBLE, 0, 0, sizeof(double), NPY_C_CONTIGUOUS, 0);
	#else
	PyObject* array = PyArray_New(&PyArray_Type, 2, dims, NPY_DOUBLE, 0, 0, sizeof(double), NPY_F_CONTIGUOUS, 0);
	#endif

	// copy data
	const double* data = mat.data();
	double* dataCopy = reinterpret_cast<double*>(PyArray_DATA(array));

	for(int i = 0; i < mat.size(); ++i)
		dataCopy[i] = data[i];

	return array;
}
Exemplo n.º 9
0
static PyObject *pixbuf_get_pixels_array(PyObject *self, PyObject *args)
{
    /* 1) read in Python pixbuf, get the underlying gdk_pixbuf */
    PyGObject *py_pixbuf;
    GdkPixbuf *gdk_pixbuf;
    PyArrayObject *array;
    npy_intp dims[3] = { 0, 0, 3 };
    npy_intp strides[3];

    if (!PyArg_ParseTuple(args, "O!:pixbuf_get_pixels_array", &PyGdkPixbuf_Type, &py_pixbuf))
        return NULL;

    gdk_pixbuf = GDK_PIXBUF(py_pixbuf->obj);

    /* 2) same as pygtk/gtk/gdk.c _wrap_gdk_pixbuf_get_pixels_array()
     * with 'self' changed to py_pixbuf
     */

    dims[0] = gdk_pixbuf_get_height(gdk_pixbuf);
    dims[1] = gdk_pixbuf_get_width(gdk_pixbuf);
    if (gdk_pixbuf_get_has_alpha(gdk_pixbuf))
        dims[2] = 4;

    strides[0] = gdk_pixbuf_get_rowstride(gdk_pixbuf);
    strides[1] = dims[2];
    strides[2] = 1;

    array = (PyArrayObject*)
        PyArray_New(&PyArray_Type, 3, dims, NPY_UBYTE, strides,
                    (void*)gdk_pixbuf_get_pixels(gdk_pixbuf), 1,
                    NPY_ARRAY_WRITEABLE, NULL);

    if (array == NULL)
        return NULL;

    /* the array holds a ref to the pixbuf pixels through this wrapper*/
    Py_INCREF(py_pixbuf);
#if NPY_API_VERSION >= 0x00000007
    if (PyArray_SetBaseObject(array, (PyObject *)py_pixbuf) == -1) {
        Py_DECREF(py_pixbuf);
        Py_DECREF(array);
        return NULL;
    }
#else
    PyArray_BASE(array) = (PyObject *) py_pixbuf;
#endif
    return PyArray_Return(array);
}
Exemplo n.º 10
0
PyObject* GeneralSwarm_AddParticlesFromCoordArray( void* swarm, Index count, Index dim, double* array )
{
    GeneralSwarm* self  = (GeneralSwarm*)swarm;
    unsigned* cellArray = Memory_Alloc_Array( unsigned, count, "GeneralSwarm_AddParticlesFromCoordArray_CellArray" );
    GlobalParticle localParticle;
    GlobalParticle* particle = &localParticle;
    int cellLocalCount  = self->cellLocalCount;
    int oldParticleCount = self->particleLocalCount;
    int ii;
    int totsLocalParticles=0;
    
    // find which particles are local. we do this to avoid swarm reallocs.
    for (ii=0; ii<count; ii++) {
        memcpy(&(particle->coord), array + dim*ii, dim*sizeof(double));
        cellArray[ii] = CellLayout_CellOf( self->cellLayout, particle );
        if( cellArray[ii] < cellLocalCount )
            totsLocalParticles++;

    }
    // alloc particle local index array (to be returned)
    int* partLocalIndex = Memory_Alloc_Array( int, count, "GeneralSwarm_AddParticlesFromCoordArray_CellArray" );
    // ok, lets add them to the swarm, now that we know how many are required
    self->particleLocalCount += totsLocalParticles;
    Swarm_Realloc( self );
    int newPartIndex = oldParticleCount;
    for (ii=0; ii<count; ii++) {
        if( cellArray[ii] < cellLocalCount ){
            particle = (GlobalParticle*)Swarm_ParticleAt( self, newPartIndex );
            memcpy(&(particle->coord), array + dim*ii, dim*sizeof(double));
            Swarm_AddParticleToCell( swarm, cellArray[ii], newPartIndex );
            partLocalIndex[ii] = newPartIndex;
            newPartIndex++;
        } else {
            partLocalIndex[ii] = -1;
        }
    }
 
    /* create numpy array to return */
    npy_intp dims[1] = { count };
    PyObject* pyobj = PyArray_New(&PyArray_Type, 1, dims, NPY_INT, NULL, (void*)partLocalIndex, sizeof(int), 0, NULL);
    /* enable the owndata flag.. this tells numpy to dealloc the data when it is finished with it */
#if NPY_API_VERSION < 0x00000007
    (((PyArrayObject*)pyobj)->flags) = NPY_ARRAY_OWNDATA;
#else
    PyArray_ENABLEFLAGS((PyArrayObject*)pyobj, NPY_ARRAY_OWNDATA);
#endif
    return pyobj;
}
Exemplo n.º 11
0
static PyObject *
get_times_for_entity (NsLibrary *lib,
                      uint32     file_id,
                      uint32     entity_id,
                      uint32     index,
                      uint32     length)
{
    PyObject  *array;
    ns_RESULT  res;
    npy_intp   dims[1];
    double    *data;
    int        i;

    res = ns_OK;
    dims[0] = length;

    array = PyArray_New (&PyArray_Type,
                         1,
                         dims,
                         NPY_DOUBLE,
                         NULL,
                         NULL /* data */,
                         0 /* itemsize */,
                         NPY_CARRAY,
                         NULL);

    data = (double *) PyArray_DATA (array);

    for (i = 0; i < length; i++)
    {
        res = lib->GetTimeByIndex (file_id,
                                   entity_id,
                                   index + i,
                                   (data + i));
        if (res != ns_OK)
            break;
    }

    if (check_result_is_error (res, lib))
    {
        Py_DECREF (array);
        return NULL;
    }

    return array;
}
Exemplo n.º 12
0
static PyObject* py_as_nparray(PyObject *self, PyObject *args)
{
  // Suppose you have data in C code and want to pass to Python as an array
  const int np=10;
  Particle* const p= calloc(sizeof(Particle), np);

  for(int i=0; i<np; ++i) {
    p[i].x[0]= (float) i + 1;
  }
  // This memory is assumed to be freed by the C code
  // (Memory leak in this example)

  const int nd=2;
  const int ncol= 3;
  npy_intp dims[]= {np, ncol};
  npy_intp strides[]= {sizeof(Particle), sizeof(float)};

  return PyArray_New(&PyArray_Type, nd, dims, NPY_FLOAT, strides,
		     p->x, 0, 0, 0);
}
Exemplo n.º 13
0
void Invocation::insertArgument(const std::string& name,
                                boost::uint8_t* data,
                                boost::uint32_t data_len,
                                boost::uint32_t data_stride,
                                dimension::Interpretation dataType,
                                boost::uint32_t numBytes)
{
    npy_intp mydims = data_len;
    int nd = 1;
    npy_intp* dims = &mydims;
    npy_intp stride = data_stride;
    npy_intp* strides = &stride;
    int flags = NPY_CARRAY; // NPY_BEHAVED

    const int pyDataType = getPythonDataType(dataType, numBytes);

    PyObject* pyArray = PyArray_New(&PyArray_Type, nd, dims, pyDataType, strides, data, 0, flags, NULL);

    m_pyInputArrays.push_back(pyArray);

    PyDict_SetItemString(m_varsIn, name.c_str(), pyArray);

    return;
}
Exemplo n.º 14
0
extern
PyArrayObject* array_from_pyobj(const int type_num,
                                npy_intp *dims,
                                const int rank,
                                const int intent,
                                PyObject *obj) {
    /* Note about reference counting
       -----------------------------
       If the caller returns the array to Python, it must be done with
       Py_BuildValue("N",arr).
       Otherwise, if obj!=arr then the caller must call Py_DECREF(arr).

       Note on intent(cache,out,..)
       ---------------------
       Don't expect correct data when returning intent(cache) array.

    */
    char mess[200];
    PyArrayObject *arr = NULL;
    PyArray_Descr *descr;
    char typechar;
    int elsize;

    if ((intent & F2PY_INTENT_HIDE)
        || ((intent & F2PY_INTENT_CACHE) && (obj==Py_None))
        || ((intent & F2PY_OPTIONAL) && (obj==Py_None))
        ) {
        /* intent(cache), optional, intent(hide) */
        if (count_nonpos(rank,dims)) {
            int i;
            strcpy(mess, "failed to create intent(cache|hide)|optional array"
                   "-- must have defined dimensions but got (");
            for(i=0;i<rank;++i)
                sprintf(mess+strlen(mess),"%" NPY_INTP_FMT ",",dims[i]);
            strcat(mess, ")");
            PyErr_SetString(PyExc_ValueError,mess);
            return NULL;
        }
        arr = (PyArrayObject *)
            PyArray_New(&PyArray_Type, rank, dims, type_num,
                        NULL,NULL,0,
                        !(intent&F2PY_INTENT_C),
                        NULL);
        if (arr==NULL) return NULL;
        if (!(intent & F2PY_INTENT_CACHE))
            PyArray_FILLWBYTE(arr, 0);
        return arr;
    }

    descr = PyArray_DescrFromType(type_num);
    elsize = descr->elsize;
    typechar = descr->type;
    Py_DECREF(descr);
    if (PyArray_Check(obj)) {
        arr = (PyArrayObject *)obj;

        if (intent & F2PY_INTENT_CACHE) {
            /* intent(cache) */
            if (PyArray_ISONESEGMENT(arr)
                && PyArray_ITEMSIZE(arr)>=elsize) {
                if (check_and_fix_dimensions(arr,rank,dims)) {
                    return NULL; /*XXX: set exception */
                }
                if (intent & F2PY_INTENT_OUT)
                    Py_INCREF(arr);
                return arr;
            }
            strcpy(mess, "failed to initialize intent(cache) array");
            if (!PyArray_ISONESEGMENT(arr))
                strcat(mess, " -- input must be in one segment");
            if (PyArray_ITEMSIZE(arr)<elsize)
                sprintf(mess+strlen(mess),
                        " -- expected at least elsize=%d but got %" NPY_INTP_FMT,
                        elsize,
                        (npy_intp)PyArray_ITEMSIZE(arr)
                        );
            PyErr_SetString(PyExc_ValueError,mess);
            return NULL;
        }

        /* here we have always intent(in) or intent(inout) or intent(inplace) */

        if (check_and_fix_dimensions(arr,rank,dims)) {
            return NULL; /*XXX: set exception */
        }
	/*
	printf("intent alignement=%d\n", F2PY_GET_ALIGNMENT(intent));
	printf("alignement check=%d\n", F2PY_CHECK_ALIGNMENT(arr, intent));
	int i;
	for (i=1;i<=16;i++)
	  printf("i=%d isaligned=%d\n", i, ARRAY_ISALIGNED(arr, i));
	*/
        if ((! (intent & F2PY_INTENT_COPY))
            && PyArray_ITEMSIZE(arr)==elsize
            && ARRAY_ISCOMPATIBLE(arr,type_num)
	    && F2PY_CHECK_ALIGNMENT(arr, intent)
            ) {
            if ((intent & F2PY_INTENT_C)?PyArray_ISCARRAY(arr):PyArray_ISFARRAY(arr)) {
                if ((intent & F2PY_INTENT_OUT)) {
                    Py_INCREF(arr);
                }
                /* Returning input array */
                return arr;
            }
        }

        if (intent & F2PY_INTENT_INOUT) {
            strcpy(mess, "failed to initialize intent(inout) array");
            if ((intent & F2PY_INTENT_C) && !PyArray_ISCARRAY(arr))
                strcat(mess, " -- input not contiguous");
            if (!(intent & F2PY_INTENT_C) && !PyArray_ISFARRAY(arr))
                strcat(mess, " -- input not fortran contiguous");
            if (PyArray_ITEMSIZE(arr)!=elsize)
                sprintf(mess+strlen(mess),
                        " -- expected elsize=%d but got %" NPY_INTP_FMT,
                        elsize,
                        (npy_intp)PyArray_ITEMSIZE(arr)
                        );
            if (!(ARRAY_ISCOMPATIBLE(arr,type_num)))
                sprintf(mess+strlen(mess)," -- input '%c' not compatible to '%c'",
                        PyArray_DESCR(arr)->type,typechar);
	    if (!(F2PY_CHECK_ALIGNMENT(arr, intent)))
	      sprintf(mess+strlen(mess)," -- input not %d-aligned", F2PY_GET_ALIGNMENT(intent));
            PyErr_SetString(PyExc_ValueError,mess);
            return NULL;
        }

        /* here we have always intent(in) or intent(inplace) */

        {
            PyArrayObject *retarr = (PyArrayObject *) \
                PyArray_New(&PyArray_Type, PyArray_NDIM(arr), PyArray_DIMS(arr), type_num,
                            NULL,NULL,0,
                            !(intent&F2PY_INTENT_C),
                            NULL);
            if (retarr==NULL)
                return NULL;
            F2PY_REPORT_ON_ARRAY_COPY_FROMARR;
            if (PyArray_CopyInto(retarr, arr)) {
                Py_DECREF(retarr);
                return NULL;
            }
            if (intent & F2PY_INTENT_INPLACE) {
                if (swap_arrays(arr,retarr))
                    return NULL; /* XXX: set exception */
                Py_XDECREF(retarr);
                if (intent & F2PY_INTENT_OUT)
                    Py_INCREF(arr);
            } else {
                arr = retarr;
            }
        }
        return arr;
    }

    if ((intent & F2PY_INTENT_INOUT) ||
            (intent & F2PY_INTENT_INPLACE) ||
            (intent & F2PY_INTENT_CACHE)) {
        PyErr_SetString(PyExc_TypeError,
                        "failed to initialize intent(inout|inplace|cache) "
                        "array, input not an array");
        return NULL;
    }

    {
        F2PY_REPORT_ON_ARRAY_COPY_FROMANY;
        arr = (PyArrayObject *) \
            PyArray_FromAny(obj,PyArray_DescrFromType(type_num), 0,0,
                            ((intent & F2PY_INTENT_C)?NPY_ARRAY_CARRAY:NPY_ARRAY_FARRAY) \
                            | NPY_ARRAY_FORCECAST, NULL);
        if (arr==NULL)
            return NULL;
        if (check_and_fix_dimensions(arr,rank,dims))
            return NULL; /*XXX: set exception */
        return arr;
    }

}
Exemplo n.º 15
0
static PyObject*
run(PyObject *self, PyObject *args, PyObject *kwargs)
{

  /* get the number of arguments */
  Py_ssize_t argc = PyTuple_Size(args);
  if(argc != 3)
  {
    std::cout << "Not the right number of arguments" << std::endl;
    Py_INCREF(Py_None);
    return Py_None;
  }

  /* get the first argument (kwargs) */
  PyObject *dxObj = PyTuple_GetItem(args, 0); 
  PyObject *dyObj = PyTuple_GetItem(args, 1); 
  PyObject *fmObj = PyTuple_GetItem(args, 2); 
  assert(PyArray_Check(dxObj));
  assert(PyArray_Check(dyObj));

  // Found variable, now copy it into the C/OCL data structure
  PyArrayObject * dxArray = (PyArrayObject*)dxObj;
  PyArrayObject * dyArray = (PyArrayObject*)dyObj;

  npy_intp * dims = PyArray_DIMS(dxArray);
  npy_intp out_dims[3];
  out_dims[0] = dims[0];
  out_dims[1] = dims[1];
  out_dims[2] = 3;

  double * dxData = (double *)dxArray->data;
  double * dyData = (double *)dyArray->data;
  unsigned char * out_data = (unsigned char *) calloc(out_dims[0] * out_dims[1] * out_dims[2], sizeof(unsigned char));

  double flowmax = 0.0;

  double input_fm;
  PyArray_ScalarAsCtype(fmObj, &input_fm);

  if(input_fm <= 0)
  {

    for(int i = 0 ; i < out_dims[0] ; i++)
    {
      for(int j = 0 ; j < out_dims[1] ; j++)
      {
        double fx = dxData[j + i * out_dims[1]];
        double fy = dyData[j + i * out_dims[1]];
        double mag = sqrt(fx * fx + fy * fy);
        if(mag > flowmax) flowmax = mag;
      }
    }
  }
  else
  {
    flowmax = input_fm;
  }


  for(int i = 0 ; i < out_dims[0] ; i++)
  {
    for(int j = 0 ; j < out_dims[1] ; j++)
    {
      double fx = dxData[j + i * out_dims[1]];
      double fy = dyData[j + i * out_dims[1]];
      computeColor(fx / flowmax, fy / flowmax , &out_data[j * 3 + i * out_dims[1] * 3]);
    }
  }

  PyObject * retArray = PyArray_New(&PyArray_Type, 3, out_dims, NPY_UINT8, NULL, out_data, 0, NPY_C_CONTIGUOUS, NULL);

  return retArray;

}
Exemplo n.º 16
0
static PyObject *
data_array_by_name(particles_t *self, char *key)
{
  int data_type;
  BOOL ex;
  int ierror = ERROR_NONE;

  void *array;

  PyObject *r;

  npy_intp dims[3];
#ifndef SEP_XYZ
  npy_intp strides[3];
#endif

  char errstr[100];

#ifdef DEBUG
  printf("[data_array_by_name] self = %p, key = %p\n", self, key);
  printf("[data_array_by_name] self->f90obj = %p, self->f90data = %p\n",
	 self->f90obj, self->f90data);
  printf("[data_array_by_name] key = %s\n", key);
#endif

  ex = f_data_exists(self->f90data, key, &data_type);

#ifdef DEBUG
  printf("[data_array_by_name] ex = %i\n", ex);
#endif

  r  = NULL;

  if (ex) {

    switch (data_type) {

    case TYPE_REAL:
      real_ptr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

      dims[0] = data_get_len(self->f90data);
#ifdef DEBUG
      printf("[data_array_by_name] TYPE_REAL, dim = %i\n", dims[0]);
#endif
      r  = PyArray_New(&PyArray_Type, 1, dims, NPY_DOUBLE, NULL, array, 0,
		       NPY_FARRAY, NULL);
      break;

    case TYPE_INTEGER:
      integer_ptr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

      dims[0] = data_get_len(self->f90data);
#ifdef DEBUG
      printf("[data_array_by_name] TYPE_INTEGER, dim = %i\n", dims[0]);
#endif
      r  = PyArray_New(&PyArray_Type, 1, dims, NPY_INT, NULL, array, 0,
		       NPY_FARRAY, NULL);
      break;

    case TYPE_REAL3:
      realx_ptr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

      dims[0]     = data_get_len(self->f90data);
      dims[1]     = 3;
      strides[0]  = 3*NPY_SIZEOF_DOUBLE;
      strides[1]  = NPY_SIZEOF_DOUBLE;
#ifdef DEBUG
      printf("[data_array_by_name] TYPE_REAL3, dim = %i %i, strides = %i %i\n",
	     dims[0], dims[1], strides[0], strides[1]);
#endif
      r  = PyArray_New(&PyArray_Type, 2, dims, NPY_DOUBLE, strides, array, 0,
		       NPY_BEHAVED, NULL);
      break;

    case TYPE_REAL3x3:
#ifdef DEBUG
      printf("[data_array_by_name] Type is REAL3x3\n");
#endif
      realxxx_ptr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

      dims[0] = data_get_len(self->f90data);
      dims[1] = 3;
      dims[2] = 3;
#ifdef DEBUG
      printf("[data_array_by_name] TYPE_REAL3x3, dim = %i %i %i\n", dims[0],
	     dims[1], dims[2]);
#endif
      r  = PyArray_New(&PyArray_Type, 3, dims, NPY_DOUBLE, NULL, array, 0,
		       NPY_FARRAY, NULL);
      break;

    case TYPE_REAL_ATTR:
      real_attr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

#ifdef DEBUG
      printf("[data_array_by_name] TYPE_REAL_ATTR\n");
#endif
      r  = PyFloat_FromDouble(*((double*) array));
      break;

    case TYPE_REAL3_ATTR:
      real3_attr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

      dims[0] = 3;
#ifdef DEBUG
      printf("[data_array_by_name] TYPE_REAL3_ATTR, dim = %i\n", dims[0]);
#endif
      r  = PyArray_New(&PyArray_Type, 1, dims, NPY_DOUBLE, NULL, array, 0,
		       NPY_FARRAY, NULL);
      break;

    case TYPE_REAL3x3_ATTR:
      real3x3_attr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

      dims[0] = 3;
      dims[1] = 3;
#ifdef DEBUG
      printf("[data_array_by_name] TYPE_REAL3_ATTR, dim = %i %i\n", dims[0],
	     dims[1]);
#endif
      r  = PyArray_New(&PyArray_Type, 2, dims, NPY_DOUBLE, NULL, array, 0,
		       NPY_FARRAY, NULL);
      break;

    case TYPE_INTEGER_ATTR:
      integer_attr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

#ifdef DEBUG
      printf("[data_array_by_name] TYPE_INTEGER_ATTR\n");
#endif
      r  = PyInt_FromLong(*((int*) array));
      break;

    case TYPE_INTEGER3_ATTR:
      integer3_attr_by_name(self->f90data, key, &array, &ierror);
      if (error_to_py(ierror))
        return NULL;

      dims[0] = 3;
#ifdef DEBUG
      printf("[data_array_by_name] TYPE_INTEGER3_ATTR, dim = %i\n", dims[0]);
#endif
      r  = PyArray_New(&PyArray_Type, 1, dims, NPY_INT, NULL, array, 0,
                       NPY_FARRAY, NULL);
      break;

    default:

      sprintf(errstr, "InternalError: Unknown type returned for field or "
	      "attribute '%s'.", PyString_AS_STRING(key));
      PyErr_SetString(PyExc_KeyError, errstr);
      r  = NULL;

    }

  }

  return r;
}
Exemplo n.º 17
0
/*NUMPY_API
 * ArgMax
 */
NPY_NO_EXPORT PyObject *
PyArray_ArgMax(PyArrayObject *op, int axis, PyArrayObject *out)
{
    PyArrayObject *ap = NULL, *rp = NULL;
    PyArray_ArgFunc* arg_func;
    char *ip;
    npy_intp *rptr;
    npy_intp i, n, m;
    int elsize;
    NPY_BEGIN_THREADS_DEF;

    if ((ap = (PyArrayObject *)PyArray_CheckAxis(op, &axis, 0)) == NULL) {
        return NULL;
    }
    /*
     * We need to permute the array so that axis is placed at the end.
     * And all other dimensions are shifted left.
     */
    if (axis != PyArray_NDIM(ap)-1) {
        PyArray_Dims newaxes;
        npy_intp dims[NPY_MAXDIMS];
        int j;

        newaxes.ptr = dims;
        newaxes.len = PyArray_NDIM(ap);
        for (j = 0; j < axis; j++) {
            dims[j] = j;
        }
        for (j = axis; j < PyArray_NDIM(ap) - 1; j++) {
            dims[j] = j + 1;
        }
        dims[PyArray_NDIM(ap) - 1] = axis;
        op = (PyArrayObject *)PyArray_Transpose(ap, &newaxes);
        Py_DECREF(ap);
        if (op == NULL) {
            return NULL;
        }
    }
    else {
        op = ap;
    }

    /* Will get native-byte order contiguous copy. */
    ap = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)op,
                                  PyArray_DESCR(op)->type_num, 1, 0);
    Py_DECREF(op);
    if (ap == NULL) {
        return NULL;
    }
    arg_func = PyArray_DESCR(ap)->f->argmax;
    if (arg_func == NULL) {
        PyErr_SetString(PyExc_TypeError,
                "data type not ordered");
        goto fail;
    }
    elsize = PyArray_DESCR(ap)->elsize;
    m = PyArray_DIMS(ap)[PyArray_NDIM(ap)-1];
    if (m == 0) {
        PyErr_SetString(PyExc_ValueError,
                "attempt to get argmax of an empty sequence");
        goto fail;
    }

    if (!out) {
        rp = (PyArrayObject *)PyArray_New(Py_TYPE(ap), PyArray_NDIM(ap)-1,
                                          PyArray_DIMS(ap), NPY_INTP,
                                          NULL, NULL, 0, 0,
                                          (PyObject *)ap);
        if (rp == NULL) {
            goto fail;
        }
    }
    else {
        if ((PyArray_NDIM(out) != PyArray_NDIM(ap) - 1) ||
                !PyArray_CompareLists(PyArray_DIMS(out), PyArray_DIMS(ap),
                                      PyArray_NDIM(out))) {
            PyErr_SetString(PyExc_ValueError,
                    "output array does not match result of np.argmax.");
            goto fail;
        }
        rp = (PyArrayObject *)PyArray_FromArray(out,
                              PyArray_DescrFromType(NPY_INTP),
                              NPY_ARRAY_CARRAY | NPY_ARRAY_UPDATEIFCOPY);
        if (rp == NULL) {
            goto fail;
        }
    }

    NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ap));
    n = PyArray_SIZE(ap)/m;
    rptr = (npy_intp *)PyArray_DATA(rp);
    for (ip = PyArray_DATA(ap), i = 0; i < n; i++, ip += elsize*m) {
        arg_func(ip, m, rptr, ap);
        rptr += 1;
    }
    NPY_END_THREADS_DESCR(PyArray_DESCR(ap));

    Py_DECREF(ap);
    /* Trigger the UPDATEIFCOPY if necessary */
    if (out != NULL && out != rp) {
        Py_DECREF(rp);
        rp = out;
        Py_INCREF(rp);
    }
    return (PyObject *)rp;

 fail:
    Py_DECREF(ap);
    Py_XDECREF(rp);
    return NULL;
}
Exemplo n.º 18
0
/*NUMPY_API
 * ArgMax
 */
NPY_NO_EXPORT PyObject *
PyArray_ArgMax(PyArrayObject *op, int axis, PyArrayObject *out)
{
    PyArrayObject *ap = NULL, *rp = NULL;
    PyArray_ArgFunc* arg_func;
    char *ip;
    intp *rptr;
    intp i, n, m;
    int elsize;
    int copyret = 0;
    NPY_BEGIN_THREADS_DEF;

    if ((ap=(PyAO *)_check_axis(op, &axis, 0)) == NULL) {
        return NULL;
    }
    /*
     * We need to permute the array so that axis is placed at the end.
     * And all other dimensions are shifted left.
     */
    if (axis != ap->nd-1) {
        PyArray_Dims newaxes;
        intp dims[MAX_DIMS];
        int i;

        newaxes.ptr = dims;
        newaxes.len = ap->nd;
        for (i = 0; i < axis; i++) dims[i] = i;
        for (i = axis; i < ap->nd - 1; i++) dims[i] = i + 1;
        dims[ap->nd - 1] = axis;
        op = (PyAO *)PyArray_Transpose(ap, &newaxes);
        Py_DECREF(ap);
        if (op == NULL) {
            return NULL;
        }
    }
    else {
        op = ap;
    }

    /* Will get native-byte order contiguous copy. */
    ap = (PyArrayObject *)
        PyArray_ContiguousFromAny((PyObject *)op,
                                  op->descr->type_num, 1, 0);
    Py_DECREF(op);
    if (ap == NULL) {
        return NULL;
    }
    arg_func = ap->descr->f->argmax;
    if (arg_func == NULL) {
        PyErr_SetString(PyExc_TypeError, "data type not ordered");
        goto fail;
    }
    elsize = ap->descr->elsize;
    m = ap->dimensions[ap->nd-1];
    if (m == 0) {
        PyErr_SetString(PyExc_ValueError,
                        "attempt to get argmax/argmin "\
                        "of an empty sequence");
        goto fail;
    }

    if (!out) {
        rp = (PyArrayObject *)PyArray_New(ap->ob_type, ap->nd-1,
                                          ap->dimensions, PyArray_INTP,
                                          NULL, NULL, 0, 0,
                                          (PyObject *)ap);
        if (rp == NULL) {
            goto fail;
        }
    }
    else {
        if (PyArray_SIZE(out) !=
                PyArray_MultiplyList(ap->dimensions, ap->nd - 1)) {
            PyErr_SetString(PyExc_TypeError,
                            "invalid shape for output array.");
        }
        rp = (PyArrayObject *)\
            PyArray_FromArray(out,
                              PyArray_DescrFromType(PyArray_INTP),
                              NPY_CARRAY | NPY_UPDATEIFCOPY);
        if (rp == NULL) {
            goto fail;
        }
        if (rp != out) {
            copyret = 1;
        }
    }

    NPY_BEGIN_THREADS_DESCR(ap->descr);
    n = PyArray_SIZE(ap)/m;
    rptr = (intp *)rp->data;
    for (ip = ap->data, i = 0; i < n; i++, ip += elsize*m) {
        arg_func(ip, m, rptr, ap);
        rptr += 1;
    }
    NPY_END_THREADS_DESCR(ap->descr);

    Py_DECREF(ap);
    if (copyret) {
        PyArrayObject *obj;
        obj = (PyArrayObject *)rp->base;
        Py_INCREF(obj);
        Py_DECREF(rp);
        rp = obj;
    }
    return (PyObject *)rp;

 fail:
    Py_DECREF(ap);
    Py_XDECREF(rp);
    return NULL;
}
Exemplo n.º 19
0
static PyObject *
do_get_analog_data (PyObject *self, PyObject *args, PyObject *kwds)
{
    NsLibrary      *lib;
    PyObject       *cobj;
    PyObject       *iobj, *id_obj, *idx_obj, *sz_obj;
    PyObject       *res_obj;
    PyObject       *array;
    PyObject       *times;
    uint32          file_id;
    uint32          entity_id;
    uint32          index;
    uint32          count;
    uint32          cont_count;
    ns_RESULT       res;
    void           *buffer;
    npy_intp        dims[1];

    if (!PyArg_ParseTuple (args, "OOOOO", &cobj, &iobj, &id_obj, &idx_obj, &sz_obj))
    {
        PyErr_SetString (PyExc_StandardError, "Could not parse arguments");
        return NULL;
    }

    if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) ||
            !PyInt_Check (id_obj) || !PyInt_Check (idx_obj) ||
            !PyInt_Check (sz_obj))
    {
        PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)");
        return NULL;
    }

    lib = PyCObject_AsVoidPtr (cobj);
    file_id = (uint32) PyInt_AsUnsignedLongMask (iobj);
    entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj);
    index = (uint32) PyInt_AsUnsignedLongMask (idx_obj);
    count = (uint32)  PyInt_AsUnsignedLongMask (sz_obj);

    /* ** */
    dims[0] = count; //sample count

    array = PyArray_New (&PyArray_Type,
                         1,
                         dims,
                         NPY_DOUBLE,
                         NULL,
                         NULL /* data */,
                         0 /* itemsize */,
                         NPY_CARRAY,
                         NULL);

    buffer = PyArray_DATA (array);

    res = lib->GetAnalogData (file_id,
                              entity_id,
                              index,
                              count,
                              &cont_count,
                              buffer);

    if (check_result_is_error (res, lib))
    {
        Py_DECREF (array);
        return NULL;
    }

    times = get_times_for_entity (lib,
                                  file_id,
                                  entity_id,
                                  index,
                                  count);

    if (times == NULL)
    {
        Py_DECREF (array);
        return NULL;
    }

    res_obj = PyTuple_New (3);
    PyTuple_SetItem (res_obj, 0, array);
    PyTuple_SetItem (res_obj, 1, times);
    PyTuple_SetItem (res_obj, 2, PyInt_FromLong (cont_count));

    return res_obj;
}
Exemplo n.º 20
0
static PyObject *
dotblas_matrixproduct(PyObject *dummy, PyObject *args)
{
    PyObject *op1, *op2;
    PyArrayObject *ap1=NULL, *ap2=NULL, *ret=NULL;
    int j, l, lda, ldb, ldc;
    int typenum, nd;
    intp ap1stride=0;
    intp dimensions[MAX_DIMS];
    intp numbytes;
    static const float oneF[2] = {1.0, 0.0};
    static const float zeroF[2] = {0.0, 0.0};
    static const double oneD[2] = {1.0, 0.0};
    static const double zeroD[2] = {0.0, 0.0};
    double prior1, prior2;
    PyTypeObject *subtype;
    PyArray_Descr *dtype;
    MatrixShape ap1shape, ap2shape;

    if (!PyArg_ParseTuple(args, "OO", &op1, &op2)) return NULL;

    /*
     * "Matrix product" using the BLAS.
     * Only works for float double and complex types.
     */

    typenum = PyArray_ObjectType(op1, 0);
    typenum = PyArray_ObjectType(op2, typenum);

    /* This function doesn't handle other types */
    if ((typenum != PyArray_DOUBLE && typenum != PyArray_CDOUBLE &&
            typenum != PyArray_FLOAT && typenum != PyArray_CFLOAT)) {
        return PyArray_Return((PyArrayObject *)PyArray_MatrixProduct(op1, op2));
    }

    dtype = PyArray_DescrFromType(typenum);
    ap1 = (PyArrayObject *)PyArray_FromAny(op1, dtype, 0, 0, ALIGNED, NULL);
    if (ap1 == NULL) return NULL;
    Py_INCREF(dtype);
    ap2 = (PyArrayObject *)PyArray_FromAny(op2, dtype, 0, 0, ALIGNED, NULL);
    if (ap2 == NULL) goto fail;


    if ((ap1->nd > 2) || (ap2->nd > 2)) {
        /* This function doesn't handle dimensions greater than 2
           (or negative striding)  -- other
           than to ensure the dot function is altered
        */
        if (!altered) {
            /* need to alter dot product */
            PyObject *tmp1, *tmp2;
            tmp1 = PyTuple_New(0);
            tmp2 = dotblas_alterdot(NULL, tmp1);
            Py_DECREF(tmp1);
            Py_DECREF(tmp2);
        }
        ret = (PyArrayObject *)PyArray_MatrixProduct((PyObject *)ap1,
                (PyObject *)ap2);
        Py_DECREF(ap1);
        Py_DECREF(ap2);
        return PyArray_Return(ret);
    }

    if (_bad_strides(ap1)) {
        op1 = PyArray_NewCopy(ap1, PyArray_ANYORDER);
        Py_DECREF(ap1);
        ap1 = (PyArrayObject *)op1;
        if (ap1 == NULL) goto fail;
    }
    if (_bad_strides(ap2)) {
        op2 = PyArray_NewCopy(ap2, PyArray_ANYORDER);
        Py_DECREF(ap2);
        ap2 = (PyArrayObject *)op2;
        if (ap2 == NULL) goto fail;
    }
    ap1shape = _select_matrix_shape(ap1);
    ap2shape = _select_matrix_shape(ap2);

    if (ap1shape == _scalar || ap2shape == _scalar) {
        PyArrayObject *oap1, *oap2;
        oap1 = ap1;
        oap2 = ap2;
        /* One of ap1 or ap2 is a scalar */
        if (ap1shape == _scalar) { 		/* Make ap2 the scalar */
            PyArrayObject *t = ap1;
            ap1 = ap2;
            ap2 = t;
            ap1shape = ap2shape;
            ap2shape = _scalar;
        }

        if (ap1shape == _row) ap1stride = ap1->strides[1];
        else if (ap1->nd > 0) ap1stride = ap1->strides[0];

        if (ap1->nd == 0 || ap2->nd == 0) {
            intp *thisdims;
            if (ap1->nd == 0) {
                nd = ap2->nd;
                thisdims = ap2->dimensions;
            }
            else {
                nd = ap1->nd;
                thisdims = ap1->dimensions;
            }
            l = 1;
            for (j=0; j<nd; j++) {
                dimensions[j] = thisdims[j];
                l *= dimensions[j];
            }
        }
        else {
            l = oap1->dimensions[oap1->nd-1];

            if (oap2->dimensions[0] != l) {
                PyErr_SetString(PyExc_ValueError, "matrices are not aligned");
                goto fail;
            }
            nd = ap1->nd + ap2->nd - 2;
            /* nd = 0 or 1 or 2 */
            /* If nd == 0 do nothing ... */
            if (nd == 1) {
                /* Either ap1->nd is 1 dim or ap2->nd is 1 dim
                   and the other is 2-dim */
                dimensions[0] = (oap1->nd == 2) ? oap1->dimensions[0] : oap2->dimensions[1];
                l = dimensions[0];
                /* Fix it so that dot(shape=(N,1), shape=(1,))
                   and dot(shape=(1,), shape=(1,N)) both return
                   an (N,) array (but use the fast scalar code)
                */
            }
            else if (nd == 2) {
                dimensions[0] = oap1->dimensions[0];
                dimensions[1] = oap2->dimensions[1];
                /* We need to make sure that dot(shape=(1,1), shape=(1,N))
                   and dot(shape=(N,1),shape=(1,1)) uses
                   scalar multiplication appropriately
                */
                if (ap1shape == _row) l = dimensions[1];
                else l = dimensions[0];
            }
        }
    }
    else { /* (ap1->nd <= 2 && ap2->nd <= 2) */
        /*  Both ap1 and ap2 are vectors or matrices */
        l = ap1->dimensions[ap1->nd-1];

        if (ap2->dimensions[0] != l) {
            PyErr_SetString(PyExc_ValueError, "matrices are not aligned");
            goto fail;
        }
        nd = ap1->nd+ap2->nd-2;

        if (nd == 1)
            dimensions[0] = (ap1->nd == 2) ? ap1->dimensions[0] : ap2->dimensions[1];
        else if (nd == 2) {
            dimensions[0] = ap1->dimensions[0];
            dimensions[1] = ap2->dimensions[1];
        }
    }

    /* Choose which subtype to return */
    if (ap1->ob_type != ap2->ob_type) {
        prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0);
        prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0);
        subtype = (prior2 > prior1 ? ap2->ob_type : ap1->ob_type);
    }
    else {
        prior1 = prior2 = 0.0;
        subtype = ap1->ob_type;
    }

    ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions,
                                       typenum, NULL, NULL, 0, 0,
                                       (PyObject *)
                                       (prior2 > prior1 ? ap2 : ap1));

    if (ret == NULL) goto fail;
    numbytes = PyArray_NBYTES(ret);
    memset(ret->data, 0, numbytes);
    if (numbytes==0 || l == 0) {
        Py_DECREF(ap1);
        Py_DECREF(ap2);
        return PyArray_Return(ret);
    }


    if (ap2shape == _scalar) {
        /* Multiplication by a scalar -- Level 1 BLAS */
        /* if ap1shape is a matrix and we are not contiguous, then we can't
           just blast through the entire array using a single
           striding factor */
        NPY_BEGIN_ALLOW_THREADS

        if (typenum == PyArray_DOUBLE) {
            if (l == 1) {
                *((double *)ret->data) = *((double *)ap2->data) * \
                                         *((double *)ap1->data);
            }
            else if (ap1shape != _matrix) {
                cblas_daxpy(l, *((double *)ap2->data), (double *)ap1->data,
                            ap1stride/sizeof(double), (double *)ret->data, 1);
            }
            else {
                int maxind, oind, i, a1s, rets;
                char *ptr, *rptr;
                double val;
                maxind = (ap1->dimensions[0] >= ap1->dimensions[1] ? 0 : 1);
                oind = 1-maxind;
                ptr = ap1->data;
                rptr = ret->data;
                l = ap1->dimensions[maxind];
                val = *((double *)ap2->data);
                a1s = ap1->strides[maxind] / sizeof(double);
                rets = ret->strides[maxind] / sizeof(double);
                for (i=0; i < ap1->dimensions[oind]; i++) {
                    cblas_daxpy(l, val, (double *)ptr, a1s,
                                (double *)rptr, rets);
                    ptr += ap1->strides[oind];
                    rptr += ret->strides[oind];
                }
            }
        }
        else if (typenum == PyArray_CDOUBLE) {
            if (l == 1) {
                cdouble *ptr1, *ptr2, *res;
                ptr1 = (cdouble *)ap2->data;
                ptr2 = (cdouble *)ap1->data;
                res = (cdouble *)ret->data;
                res->real = ptr1->real * ptr2->real - ptr1->imag * ptr2->imag;
                res->imag = ptr1->real * ptr2->imag + ptr1->imag * ptr2->real;
            }
            else if (ap1shape != _matrix) {
                cblas_zaxpy(l, (double *)ap2->data, (double *)ap1->data,
                            ap1stride/sizeof(cdouble), (double *)ret->data, 1);
            }
            else {
                int maxind, oind, i, a1s, rets;
                char *ptr, *rptr;
                double *pval;
                maxind = (ap1->dimensions[0] >= ap1->dimensions[1] ? 0 : 1);
                oind = 1-maxind;
                ptr = ap1->data;
                rptr = ret->data;
                l = ap1->dimensions[maxind];
                pval = (double *)ap2->data;
                a1s = ap1->strides[maxind] / sizeof(cdouble);
                rets = ret->strides[maxind] / sizeof(cdouble);
                for (i=0; i < ap1->dimensions[oind]; i++) {
                    cblas_zaxpy(l, pval, (double *)ptr, a1s,
                                (double *)rptr, rets);
                    ptr += ap1->strides[oind];
                    rptr += ret->strides[oind];
                }
            }
        }
        else if (typenum == PyArray_FLOAT) {
            if (l == 1) {
                *((float *)ret->data) = *((float *)ap2->data) * \
                                        *((float *)ap1->data);
            }
            else if (ap1shape != _matrix) {
                cblas_saxpy(l, *((float *)ap2->data), (float *)ap1->data,
                            ap1stride/sizeof(float), (float *)ret->data, 1);
            }
            else {
                int maxind, oind, i, a1s, rets;
                char *ptr, *rptr;
                float val;
                maxind = (ap1->dimensions[0] >= ap1->dimensions[1] ? 0 : 1);
                oind = 1-maxind;
                ptr = ap1->data;
                rptr = ret->data;
                l = ap1->dimensions[maxind];
                val = *((float *)ap2->data);
                a1s = ap1->strides[maxind] / sizeof(float);
                rets = ret->strides[maxind] / sizeof(float);
                for (i=0; i < ap1->dimensions[oind]; i++) {
                    cblas_saxpy(l, val, (float *)ptr, a1s,
                                (float *)rptr, rets);
                    ptr += ap1->strides[oind];
                    rptr += ret->strides[oind];
                }
            }
        }
        else if (typenum == PyArray_CFLOAT) {
            if (l == 1) {
                cfloat *ptr1, *ptr2, *res;
                ptr1 = (cfloat *)ap2->data;
                ptr2 = (cfloat *)ap1->data;
                res = (cfloat *)ret->data;
                res->real = ptr1->real * ptr2->real - ptr1->imag * ptr2->imag;
                res->imag = ptr1->real * ptr2->imag + ptr1->imag * ptr2->real;
            }
            else if (ap1shape != _matrix) {
                cblas_caxpy(l, (float *)ap2->data, (float *)ap1->data,
                            ap1stride/sizeof(cfloat), (float *)ret->data, 1);
            }
            else {
                int maxind, oind, i, a1s, rets;
                char *ptr, *rptr;
                float *pval;
                maxind = (ap1->dimensions[0] >= ap1->dimensions[1] ? 0 : 1);
                oind = 1-maxind;
                ptr = ap1->data;
                rptr = ret->data;
                l = ap1->dimensions[maxind];
                pval = (float *)ap2->data;
                a1s = ap1->strides[maxind] / sizeof(cfloat);
                rets = ret->strides[maxind] / sizeof(cfloat);
                for (i=0; i < ap1->dimensions[oind]; i++) {
                    cblas_caxpy(l, pval, (float *)ptr, a1s,
                                (float *)rptr, rets);
                    ptr += ap1->strides[oind];
                    rptr += ret->strides[oind];
                }
            }
        }
        NPY_END_ALLOW_THREADS
    }
Exemplo n.º 21
0
static PyObject *
potential_energy_and_forces(potential_t *self, PyObject *args, PyObject *kwargs)
{
  static char *kwlist[] = {
    "particles",
    "neighbors",
    "epot_per_at",
    "epot_per_bond",
    "f_per_bond",
    "wpot_per_at",
    "wpot_per_bond",
    NULL
  };

  npy_intp dims[3];
  npy_intp strides[3];

  particles_t *a;
  neighbors_t *n;
  PyObject *return_epot_per_at = NULL;
  PyObject *return_epot_per_bond = NULL;
  PyObject *return_f_per_bond = NULL;
  PyObject *return_wpot_per_at = NULL;
  PyObject *return_wpot_per_bond = NULL;

  int ierror = ERROR_NONE;

  double epot;
  PyObject *f;
  PyObject *wpot;
  PyObject *epot_per_at = NULL;
  PyObject *epot_per_bond = NULL;
  PyObject *f_per_bond = NULL;
  PyObject *wpot_per_at = NULL;
  PyObject *wpot_per_bond = NULL;

  double *epot_per_at_ptr = NULL;
  double *epot_per_bond_ptr = NULL;
  double *f_per_bond_ptr = NULL;
  double *wpot_per_at_ptr = NULL;
  double *wpot_per_bond_ptr = NULL;

  PyObject *r;

  int i;

  /* --- */

#ifdef DEBUG
  printf("[potential_energy_and_forces] self = %p\n", self);
#endif

  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O!|O!O!O!O!O!", kwlist,
				   &particles_type, &a, &neighbors_type, &n,
				   &PyBool_Type, &return_epot_per_at, 
				   &PyBool_Type, &return_epot_per_bond, 
				   &PyBool_Type, &return_f_per_bond,
 				   &PyBool_Type, &return_wpot_per_at, 
				   &PyBool_Type, &return_wpot_per_bond))
    return NULL;

  epot = 0.0;

  dims[0] = data_get_len(a->f90data);
  dims[1] = 3;
  strides[0] = dims[1]*NPY_SIZEOF_DOUBLE;
  strides[1] = NPY_SIZEOF_DOUBLE;
  f = (PyObject*) PyArray_New(&PyArray_Type, 2, dims, NPY_DOUBLE, strides,
                              NULL, 0, NPY_FARRAY, NULL);
  memset(PyArray_DATA(f), 0, dims[0]*dims[1]*NPY_SIZEOF_DOUBLE);

  dims[0] = 3;
  dims[1] = 3;
  wpot = PyArray_ZEROS(2, dims, NPY_DOUBLE, 1);

  if (return_epot_per_at) {

    if (return_epot_per_at == Py_True) {
      dims[0] = data_get_len(a->f90data);
      epot_per_at = PyArray_ZEROS(1, dims, NPY_DOUBLE, 1);
      epot_per_at_ptr = PyArray_DATA(epot_per_at);
    } else {
      epot_per_at  = Py_None;
      Py_INCREF(Py_None);
    }

  }

  if (return_epot_per_bond) {

    if (return_epot_per_bond == Py_True) {
      dims[0] = get_neighbors_size(n, a);
      epot_per_bond = PyArray_ZEROS(1, dims, NPY_DOUBLE, 1);
      epot_per_bond_ptr = PyArray_DATA(epot_per_bond);
    } else {
      epot_per_bond = Py_None;
      Py_INCREF(Py_None);
    }

  }

  if (return_f_per_bond) {
    
    if (return_f_per_bond == Py_True) {
      dims[0] = get_neighbors_size(n, a);
      dims[1] = 3;
      strides[0] = dims[1]*NPY_SIZEOF_DOUBLE;
      strides[1] = NPY_SIZEOF_DOUBLE;
      f_per_bond = (PyObject*) PyArray_New(&PyArray_Type, 2, dims,
                                           NPY_DOUBLE, strides, NULL, 0,
                                           NPY_FARRAY, NULL);
      f_per_bond_ptr = PyArray_DATA(f_per_bond);
      memset(f_per_bond_ptr, 0, dims[0]*dims[1]*NPY_SIZEOF_DOUBLE);
    } else {
      f_per_bond  = Py_None;
      Py_INCREF(Py_None);
    }

  }

  if (return_wpot_per_at) {

    if (return_wpot_per_at == Py_True) {
      dims[0]            = data_get_len(a->f90data);
      dims[1]            = 3;
      dims[2]            = 3;
      strides[0]         = dims[1]*dims[2]*NPY_SIZEOF_DOUBLE;
      strides[1]         = dims[2]*NPY_SIZEOF_DOUBLE;
      strides[2]         = NPY_SIZEOF_DOUBLE;
      wpot_per_at      = (PyObject*) PyArray_New(&PyArray_Type, 3, dims,
						 NPY_DOUBLE, strides, NULL, 0,
						 NPY_FARRAY, NULL);
      wpot_per_at_ptr  = PyArray_DATA(wpot_per_at);
      memset(wpot_per_at_ptr, 0, dims[0]*dims[1]*dims[2]*NPY_SIZEOF_DOUBLE);
    } else {
      wpot_per_at  = Py_None;
      Py_INCREF(Py_None);
    }

  }

  if (return_wpot_per_bond) {

    if (return_wpot_per_bond == Py_True) {
      dims[0]            = get_neighbors_size(n, a);
      dims[1]            = 3;
      dims[2]            = 3;
      strides[0]         = dims[1]*dims[2]*NPY_SIZEOF_DOUBLE;
      strides[1]         = dims[2]*NPY_SIZEOF_DOUBLE;
      strides[2]         = NPY_SIZEOF_DOUBLE;
      wpot_per_bond      = (PyObject*) PyArray_New(&PyArray_Type, 3, dims,
						   NPY_DOUBLE, strides, NULL, 
						   0, NPY_FARRAY, NULL);
      wpot_per_bond_ptr  = PyArray_DATA(wpot_per_bond);
      memset(wpot_per_bond_ptr, 0, dims[0]*dims[1]*dims[2]*NPY_SIZEOF_DOUBLE);
    } else {
      wpot_per_bond  = Py_None;
      Py_INCREF(Py_None);
    }

  }

#ifdef DEBUG
  printf("[potential_energy_and_forces] self->f90class->name = %s\n",
	 self->f90class->name);
  printf("[potential_energy_and_forces] self->f90obj = %p\n",
	 self->f90obj);
  printf("[potential_energy_and_forces] a->f90obj = %p\n",
	 a->f90obj);
  printf("[potential_energy_and_forces] n->f90obj = %p\n",
	 n->f90obj);
  printf("[potential_energy_and_forces] self->f90class->energy_and_forces = %p\n",
	 self->f90class->energy_and_forces);
#endif

  self->f90class->energy_and_forces(self->f90obj, a->f90obj, n->f90obj,
				    &epot, PyArray_DATA(f), PyArray_DATA(wpot),
				    epot_per_at_ptr, epot_per_bond_ptr,
				    f_per_bond_ptr, wpot_per_at_ptr,
				    wpot_per_bond_ptr,
				    &ierror);

  /*
   * Now we need to reorder the per-bond properties such that some Python
   * script can actually make sense out of the data.
   */

  if (epot_per_bond_ptr) {
    dims[0] = get_number_of_all_neighbors(n, a);
    PyObject *tmp = PyArray_ZEROS(1, dims, NPY_DOUBLE, 1);

    f_pack_per_bond_scalar(n->f90obj, epot_per_bond_ptr, PyArray_DATA(tmp));

    Py_DECREF(epot_per_bond);
    epot_per_bond = tmp;
  }

  if (wpot_per_bond_ptr) {
    dims[0] = get_number_of_all_neighbors(n, a);
    dims[1] = 3;
    dims[2] = 3;
    PyObject *tmp = PyArray_ZEROS(3, dims, NPY_DOUBLE, 0);

    f_pack_per_bond_3x3(n->f90obj, wpot_per_bond_ptr, PyArray_DATA(tmp));

    Py_DECREF(wpot_per_bond);
    wpot_per_bond = tmp;
  }

#ifdef DEBUG
  printf("[potential_energy_and_forces] epot = %f\n", epot);
#endif

  if (error_to_py(ierror))
    return NULL;

  /* --- Compose return tuple --- */

  i = 3;
  if (epot_per_at)    i++;
  if (epot_per_bond)  i++;
  if (f_per_bond)     i++;
  if (wpot_per_at)    i++;
  if (wpot_per_bond)  i++;

  r  = PyTuple_New(i);
  if (!r)
    return NULL;

  PyTuple_SET_ITEM(r, 0, PyFloat_FromDouble(epot));
  PyTuple_SET_ITEM(r, 1, f);
  PyTuple_SET_ITEM(r, 2, wpot);

  i = 2;
  if (epot_per_at) {
    i++;
    PyTuple_SET_ITEM(r, i, epot_per_at);
  }
  if (epot_per_bond) {
    i++;
    PyTuple_SET_ITEM(r, i, epot_per_bond);
  }
  if (f_per_bond) {
    i++;
    PyTuple_SET_ITEM(r, i, f_per_bond);
  }
  if (wpot_per_at) {
    i++;
    PyTuple_SET_ITEM(r, i, wpot_per_at);
  }
  if (wpot_per_bond) {
    i++;
    PyTuple_SET_ITEM(r, i, wpot_per_bond);
  }

#ifdef DEBUG
  printf("{potential_energy_and_forces}\n");
#endif

  return r;
}
Exemplo n.º 22
0
static PyObject *
fortran_getattr(PyFortranObject *fp, char *name) {
    int i,j,k,flag;
    if (fp->dict != NULL) {
        PyObject *v = PyDict_GetItemString(fp->dict, name);
        if (v != NULL) {
            Py_INCREF(v);
            return v;
        }
    }
    for (i=0,j=1;i<fp->len && (j=strcmp(name,fp->defs[i].name));i++);
    if (j==0)
        if (fp->defs[i].rank!=-1) {                   /* F90 allocatable array */
            if (fp->defs[i].func==NULL) return NULL;
            for(k=0;k<fp->defs[i].rank;++k)
                fp->defs[i].dims.d[k]=-1;
            save_def = &fp->defs[i];
            (*(fp->defs[i].func))(&fp->defs[i].rank,fp->defs[i].dims.d,set_data,&flag);
            if (flag==2)
                k = fp->defs[i].rank + 1;
            else
                k = fp->defs[i].rank;
            if (fp->defs[i].data !=NULL) {              /* array is allocated */
                PyObject *v = PyArray_New(&PyArray_Type, k, fp->defs[i].dims.d,
                                          fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_FARRAY,
                                          NULL);
                if (v==NULL) return NULL;
                /* Py_INCREF(v); */
                return v;
            } else {                                    /* array is not allocated */
                Py_INCREF(Py_None);
                return Py_None;
            }
        }
    if (strcmp(name,"__dict__")==0) {
        Py_INCREF(fp->dict);
        return fp->dict;
    }
    if (strcmp(name,"__doc__")==0) {
#if PY_VERSION_HEX >= 0x03000000
        PyObject *s = PyUnicode_FromString(""), *s2, *s3;
        for (i=0;i<fp->len;i++) {
            s2 = fortran_doc(fp->defs[i]);
            s3 = PyUnicode_Concat(s, s2);
            Py_DECREF(s2);
            Py_DECREF(s);
            s = s3;
        }
#else
        PyObject *s = PyString_FromString("");
        for (i=0;i<fp->len;i++)
            PyString_ConcatAndDel(&s,fortran_doc(fp->defs[i]));
#endif
        if (PyDict_SetItemString(fp->dict, name, s))
            return NULL;
        return s;
    }
    if ((strcmp(name,"_cpointer")==0) && (fp->len==1)) {
        PyObject *cobj = F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data),NULL);
        if (PyDict_SetItemString(fp->dict, name, cobj))
            return NULL;
        return cobj;
    }
#if PY_VERSION_HEX >= 0x03000000
    if (1) {
        PyObject *str, *ret;
        str = PyUnicode_FromString(name);
        ret = PyObject_GenericGetAttr((PyObject *)fp, str);
        Py_DECREF(str);
        return ret;
    }
#else
    return Py_FindMethod(fortran_methods, (PyObject *)fp, name);
#endif
}
Exemplo n.º 23
0
/*
 * digitize(x, bins, right=False) returns an array of integers the same length
 * as x. The values i returned are such that bins[i - 1] <= x < bins[i] if
 * bins is monotonically increasing, or bins[i - 1] > x >= bins[i] if bins
 * is monotonically decreasing.  Beyond the bounds of bins, returns either
 * i = 0 or i = len(bins) as appropriate. If right == True the comparison
 * is bins [i - 1] < x <= bins[i] or bins [i - 1] >= x > bins[i]
 */
NPY_NO_EXPORT PyObject *
arr_digitize(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds)
{
    PyObject *obj_x = NULL;
    PyObject *obj_bins = NULL;
    PyArrayObject *arr_x = NULL;
    PyArrayObject *arr_bins = NULL;
    PyObject *ret = NULL;
    npy_intp len_bins;
    int monotonic, right = 0;
    NPY_BEGIN_THREADS_DEF

    static char *kwlist[] = {"x", "bins", "right", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
                                     &obj_x, &obj_bins, &right)) {
        goto fail;
    }

    /* PyArray_SearchSorted will make `x` contiguous even if we don't */
    arr_x = (PyArrayObject *)PyArray_FROMANY(obj_x, NPY_DOUBLE, 0, 0,
                                             NPY_ARRAY_CARRAY_RO);
    if (arr_x == NULL) {
        goto fail;
    }

    /* TODO: `bins` could be strided, needs change to check_array_monotonic */
    arr_bins = (PyArrayObject *)PyArray_FROMANY(obj_bins, NPY_DOUBLE, 1, 1,
                                               NPY_ARRAY_CARRAY_RO);
    if (arr_bins == NULL) {
        goto fail;
    }

    len_bins = PyArray_SIZE(arr_bins);
    if (len_bins == 0) {
        PyErr_SetString(PyExc_ValueError, "bins must have non-zero length");
        goto fail;
    }

    NPY_BEGIN_THREADS_THRESHOLDED(len_bins)
    monotonic = check_array_monotonic((const double *)PyArray_DATA(arr_bins),
                                      len_bins);
    NPY_END_THREADS

    if (monotonic == 0) {
        PyErr_SetString(PyExc_ValueError,
                        "bins must be monotonically increasing or decreasing");
        goto fail;
    }

    /* PyArray_SearchSorted needs an increasing array */
    if (monotonic == - 1) {
        PyArrayObject *arr_tmp = NULL;
        npy_intp shape = PyArray_DIM(arr_bins, 0);
        npy_intp stride = -PyArray_STRIDE(arr_bins, 0);
        void *data = (void *)(PyArray_BYTES(arr_bins) - stride * (shape - 1));

        arr_tmp = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &shape,
                                               NPY_DOUBLE, &stride, data, 0,
                                               PyArray_FLAGS(arr_bins), NULL);
        if (!arr_tmp) {
            goto fail;
        }

        if (PyArray_SetBaseObject(arr_tmp, (PyObject *)arr_bins) < 0) {

            Py_DECREF(arr_tmp);
            goto fail;
        }
        arr_bins = arr_tmp;
    }

    ret = PyArray_SearchSorted(arr_bins, (PyObject *)arr_x,
                               right ? NPY_SEARCHLEFT : NPY_SEARCHRIGHT, NULL);
    if (!ret) {
        goto fail;
    }

    /* If bins is decreasing, ret has bins from end, not start */
    if (monotonic == -1) {
        npy_intp *ret_data =
                        (npy_intp *)PyArray_DATA((PyArrayObject *)ret);
        npy_intp len_ret = PyArray_SIZE((PyArrayObject *)ret);

        NPY_BEGIN_THREADS_THRESHOLDED(len_ret)
        while (len_ret--) {
            *ret_data = len_bins - *ret_data;
            ret_data++;
        }
        NPY_END_THREADS
    }
Exemplo n.º 24
0
/* unravel_index implementation - see add_newdocs.py */
NPY_NO_EXPORT PyObject *
arr_unravel_index(PyObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *indices0 = NULL, *ret_tuple = NULL;
    PyArrayObject *ret_arr = NULL;
    PyArrayObject *indices = NULL;
    PyArray_Descr *dtype = NULL;
    PyArray_Dims dimensions={0,0};
    NPY_ORDER order = NPY_CORDER;
    npy_intp unravel_size;

    NpyIter *iter = NULL;
    int i, ret_ndim;
    npy_intp ret_dims[NPY_MAXDIMS], ret_strides[NPY_MAXDIMS];

    char *kwlist[] = {"indices", "dims", "order", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|O&:unravel_index",
                    kwlist,
                    &indices0,
                    PyArray_IntpConverter, &dimensions,
                    PyArray_OrderConverter, &order)) {
        goto fail;
    }

    if (dimensions.len == 0) {
        PyErr_SetString(PyExc_ValueError,
                "dims must have at least one value");
        goto fail;
    }

    unravel_size = PyArray_MultiplyList(dimensions.ptr, dimensions.len);

    if (!PyArray_Check(indices0)) {
        indices = (PyArrayObject*)PyArray_FromAny(indices0,
                                                    NULL, 0, 0, 0, NULL);
        if (indices == NULL) {
            goto fail;
        }
    }
    else {
        indices = (PyArrayObject *)indices0;
        Py_INCREF(indices);
    }

    dtype = PyArray_DescrFromType(NPY_INTP);
    if (dtype == NULL) {
        goto fail;
    }

    iter = NpyIter_New(indices, NPY_ITER_READONLY|
                                NPY_ITER_ALIGNED|
                                NPY_ITER_BUFFERED|
                                NPY_ITER_ZEROSIZE_OK|
                                NPY_ITER_DONT_NEGATE_STRIDES|
                                NPY_ITER_MULTI_INDEX,
                                NPY_KEEPORDER, NPY_SAME_KIND_CASTING,
                                dtype);
    if (iter == NULL) {
        goto fail;
    }

    /*
     * Create the return array with a layout compatible with the indices
     * and with a dimension added to the end for the multi-index
     */
    ret_ndim = PyArray_NDIM(indices) + 1;
    if (NpyIter_GetShape(iter, ret_dims) != NPY_SUCCEED) {
        goto fail;
    }
    ret_dims[ret_ndim-1] = dimensions.len;
    if (NpyIter_CreateCompatibleStrides(iter,
                dimensions.len*sizeof(npy_intp), ret_strides) != NPY_SUCCEED) {
        goto fail;
    }
    ret_strides[ret_ndim-1] = sizeof(npy_intp);

    /* Remove the multi-index and inner loop */
    if (NpyIter_RemoveMultiIndex(iter) != NPY_SUCCEED) {
        goto fail;
    }
    if (NpyIter_EnableExternalLoop(iter) != NPY_SUCCEED) {
        goto fail;
    }

    ret_arr = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype,
                            ret_ndim, ret_dims, ret_strides, NULL, 0, NULL);
    dtype = NULL;
    if (ret_arr == NULL) {
        goto fail;
    }

    if (order == NPY_CORDER) {
        if (NpyIter_GetIterSize(iter) != 0) {
            NpyIter_IterNextFunc *iternext;
            char **dataptr;
            npy_intp *strides;
            npy_intp *countptr, count;
            npy_intp *coordsptr = (npy_intp *)PyArray_DATA(ret_arr);

            iternext = NpyIter_GetIterNext(iter, NULL);
            if (iternext == NULL) {
                goto fail;
            }
            dataptr = NpyIter_GetDataPtrArray(iter);
            strides = NpyIter_GetInnerStrideArray(iter);
            countptr = NpyIter_GetInnerLoopSizePtr(iter);

            do {
                count = *countptr;
                if (unravel_index_loop_corder(dimensions.len, dimensions.ptr,
                            unravel_size, count, *dataptr, *strides,
                            coordsptr) != NPY_SUCCEED) {
                    goto fail;
                }
                coordsptr += count*dimensions.len;
            } while(iternext(iter));
        }
    }
    else if (order == NPY_FORTRANORDER) {
        if (NpyIter_GetIterSize(iter) != 0) {
            NpyIter_IterNextFunc *iternext;
            char **dataptr;
            npy_intp *strides;
            npy_intp *countptr, count;
            npy_intp *coordsptr = (npy_intp *)PyArray_DATA(ret_arr);

            iternext = NpyIter_GetIterNext(iter, NULL);
            if (iternext == NULL) {
                goto fail;
            }
            dataptr = NpyIter_GetDataPtrArray(iter);
            strides = NpyIter_GetInnerStrideArray(iter);
            countptr = NpyIter_GetInnerLoopSizePtr(iter);

            do {
                count = *countptr;
                if (unravel_index_loop_forder(dimensions.len, dimensions.ptr,
                            unravel_size, count, *dataptr, *strides,
                            coordsptr) != NPY_SUCCEED) {
                    goto fail;
                }
                coordsptr += count*dimensions.len;
            } while(iternext(iter));
        }
    }
    else {
        PyErr_SetString(PyExc_ValueError,
                        "only 'C' or 'F' order is permitted");
        goto fail;
    }

    /* Now make a tuple of views, one per index */
    ret_tuple = PyTuple_New(dimensions.len);
    if (ret_tuple == NULL) {
        goto fail;
    }
    for (i = 0; i < dimensions.len; ++i) {
        PyArrayObject *view;

        view = (PyArrayObject *)PyArray_New(&PyArray_Type, ret_ndim-1,
                                ret_dims, NPY_INTP,
                                ret_strides,
                                PyArray_BYTES(ret_arr) + i*sizeof(npy_intp),
                                0, NPY_ARRAY_WRITEABLE, NULL);
        if (view == NULL) {
            goto fail;
        }
        Py_INCREF(ret_arr);
        if (PyArray_SetBaseObject(view, (PyObject *)ret_arr) < 0) {
            Py_DECREF(view);
            goto fail;
        }
        PyTuple_SET_ITEM(ret_tuple, i, PyArray_Return(view));
    }

    Py_DECREF(ret_arr);
    Py_XDECREF(indices);
    PyDimMem_FREE(dimensions.ptr);
    NpyIter_Deallocate(iter);

    return ret_tuple;

fail:
    Py_XDECREF(ret_tuple);
    Py_XDECREF(ret_arr);
    Py_XDECREF(dtype);
    Py_XDECREF(indices);
    PyDimMem_FREE(dimensions.ptr);
    NpyIter_Deallocate(iter);
    return NULL;
}
Exemplo n.º 25
0
static PyObject *
do_get_segment_data (PyObject *self, PyObject *args, PyObject *kwds)
{
    NsLibrary      *lib;
    PyObject       *cobj;
    PyObject       *iobj, *id_obj, *idx_obj, *sz_obj, *src_obj;
    PyObject       *res_obj;
    PyObject       *array;
    uint32          file_id;
    uint32          entity_id;
    uint32          index;
    uint32          count;
    uint32          sources;
    uint32          sample_count;
    uint32          uint_id;
    uint32          buffer_size;
    ns_RESULT       res;
    double         *buffer;
    npy_intp        dims[2];
    double          time_stamp;

    if (!PyArg_ParseTuple (args, "OOOOOO", &cobj, &iobj, &id_obj, &idx_obj, &src_obj, &sz_obj))
    {
        PyErr_SetString (PyExc_StandardError, "Could not parse arguments");
        return NULL;
    }

    if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) ||
            !PyInt_Check (id_obj) || !PyInt_Check (idx_obj) ||
            !PyInt_Check (sz_obj) || !PyInt_Check (src_obj))
    {
        PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)");
        return NULL;
    }

    lib = PyCObject_AsVoidPtr (cobj);
    file_id = (uint32) PyInt_AsUnsignedLongMask (iobj);
    entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj);
    index = (uint32) PyInt_AsUnsignedLongMask (idx_obj);
    count = (uint32)  PyInt_AsUnsignedLongMask (sz_obj);
    sources = (uint32)  PyInt_AsUnsignedLongMask (src_obj);

    /* ** */
    dims[0] = sources; //source count
    dims[1] = count; //sample count

    array = PyArray_New (&PyArray_Type,
                         2,
                         dims,
                         NPY_DOUBLE,
                         NULL,
                         NULL /* data */,
                         0 /* itemsize */,
                         0,
                         NULL);

    buffer = (double *) PyArray_DATA (array);
    buffer_size = (uint32) PyArray_NBYTES (array);

    res = lib->GetSegmentData (file_id,
                               entity_id,
                               index,
                               &time_stamp,
                               buffer,
                               buffer_size,
                               &sample_count,
                               &uint_id);

    if (check_result_is_error (res, lib))
    {
        Py_DECREF (array);
        return NULL;
    }

    res_obj = PyTuple_New (4);
    PyTuple_SetItem (res_obj, 0, array);
    PyTuple_SetItem (res_obj, 1, PyFloat_FromDouble (time_stamp));
    PyTuple_SetItem (res_obj, 2, PyInt_FromLong (sample_count));
    PyTuple_SetItem (res_obj, 3, PyInt_FromLong (uint_id));

    return res_obj;
}
Exemplo n.º 26
0
static PyObject *
do_get_neural_data (PyObject *self, PyObject *args, PyObject *kwds)
{
    NsLibrary      *lib;
    PyObject       *cobj;
    PyObject       *iobj, *id_obj, *idx_obj, *sz_obj;
    PyObject       *array;
    uint32          file_id;
    uint32          entity_id;
    uint32          index;
    uint32          index_count;
    ns_RESULT       res;
    void           *buffer;
    npy_intp        dims[1];

    if (!PyArg_ParseTuple (args, "OOOOO", &cobj, &iobj, &id_obj, &idx_obj, &sz_obj))
    {
        PyErr_SetString (PyExc_StandardError, "Could not parse arguments");
        return NULL;
    }

    if (!PyCObject_Check (cobj) || !PyInt_Check (iobj) ||
            !PyInt_Check (id_obj) || !PyInt_Check (idx_obj) ||
            !PyInt_Check (sz_obj))
    {
        PyErr_SetString (PyExc_TypeError, "Wrong argument type(s)");
        return NULL;
    }

    lib = PyCObject_AsVoidPtr (cobj);
    file_id = (uint32) PyInt_AsUnsignedLongMask (iobj);
    entity_id = (uint32) PyInt_AsUnsignedLongMask (id_obj);
    index = (uint32) PyInt_AsUnsignedLongMask (idx_obj);
    index_count = (uint32)  PyInt_AsUnsignedLongMask (sz_obj);

    /* ** */
    dims[0] = index_count;
    array = PyArray_New (&PyArray_Type,
                         1,
                         dims,
                         NPY_DOUBLE,
                         NULL,
                         NULL /* data */,
                         0 /* itemsize */,
                         NPY_CARRAY,
                         NULL);

    buffer = PyArray_DATA (array);

    res = lib->GetNeuralData (file_id,
                              entity_id,
                              index,
                              index_count,
                              buffer);

    if (check_result_is_error (res, lib))
    {
        Py_DECREF (array);
        return NULL;
    }

    return array;
}
Exemplo n.º 27
0
static PyObject * enz_vnmpocnp(PyObject *self, PyObject *args,
			       PyObject *keywds)
{
	static char *kwlist[] = { "r",		 "f",		"n",	       "m",	"L_max",
				  "bessel_name", "ncpus",	"verb",	       NULL };
	long syscpus = sysconf(_SC_NPROCESSORS_ONLN);

	PyObject *r_o, *f_o, *n_o, *m_o;
	PyObject *r = NULL;
	PyObject *f = NULL;
	PyObject *n = NULL;
	PyObject *m = NULL;
	const char *error = NULL;
	npy_intp r_n, f_n, beta_n;

	PyObject *vnm = NULL;
	npy_intp vnm_dims[3];

	double *datar = NULL;
	complex double *dataf = NULL;
	int *datan = NULL;
	int *datam = NULL;
	complex double *datap = NULL;

	int kL_max = 35;
	int kncpus = -1;
	int kverb = 0;
	char *kbessel_name = "jn";
	int ret;

	if (syscpus <= 0)
		syscpus = 1;

	if (!PyArg_ParseTupleAndKeywords(args, keywds, "O!O!O!O!|isii",
					 kwlist,
					 &PyArray_Type, &r_o,
					 &PyArray_Type, &f_o,
					 &PyArray_Type, &n_o,
					 &PyArray_Type, &m_o,
					 &kL_max, &kbessel_name, &kncpus, &kverb)) {
		PyErr_SetString(PyExc_SyntaxError, "failed to parse args");
		return NULL;
	}

	r = PyArray_FROM_OTF(r_o, NPY_FLOAT64, NPY_ARRAY_IN_ARRAY);
	f = PyArray_FROM_OTF(f_o, NPY_COMPLEX128, NPY_ARRAY_IN_ARRAY);
	n = PyArray_FROM_OTF(n_o, NPY_INT64, NPY_ARRAY_IN_ARRAY);
	m = PyArray_FROM_OTF(m_o, NPY_INT64, NPY_ARRAY_IN_ARRAY);

	if (!r) {
		PyErr_SetString(PyExc_ValueError, "cannot convert r to PyArray");
		return NULL;
	}
	if (!f) {
		PyErr_SetString(PyExc_ValueError, "cannot convert f to PyArray");
		return NULL;
	}
	if (!n) {
		PyErr_SetString(PyExc_ValueError, "cannot convert n to PyArray");
		return NULL;
	}
	if (!m) {
		PyErr_SetString(PyExc_ValueError, "cannot convert m to PyArray");
		return NULL;
	}

	if (!r || not_vect(r) || PyArray_TYPE((PyArrayObject*)r) != NPY_FLOAT64) {
		error = "r is not a vector of doubles";
		goto exit_decrement;
	}
	r_n = PyArray_DIM((PyArrayObject*)r, 0);

	if (!f || not_vect(f) ||
	    PyArray_TYPE((PyArrayObject*)f) != NPY_COMPLEX128) {
		error = "f is not a vector of complex numbers";
		goto exit_decrement;
	}
	f_n = PyArray_DIM((PyArrayObject*)f, 0);

	if (!n || not_vect(n) || PyArray_TYPE((PyArrayObject*)n) != NPY_INT64) {
		error = "n is not a vector of integers";
		goto exit_decrement;
	}
	if (!m || not_vect(m) || PyArray_TYPE((PyArrayObject*)m) != NPY_INT64) {
		error = "m is not a vector of integers";
		goto exit_decrement;
	}
	if (PyArray_DIM((PyArrayObject*)n, 0) !=
	    PyArray_DIM((PyArrayObject*)m, 0)) {
		error = "n and m must have the same length";
		goto exit_decrement;
	}
	beta_n = PyArray_DIM((PyArrayObject*)n, 0);

	vnm_dims[0] = r_n;
	vnm_dims[1] = f_n;
	vnm_dims[2] = beta_n;

	vnm = PyArray_New(&PyArray_Type, 3, vnm_dims, NPY_COMPLEX128, NULL, NULL,
			  0, NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_ALIGNED, NULL);

	if (!vnm) {
		error = "cannot create vnm";
		goto exit_decrement;
	}

	PyArray_CLEARFLAGS((PyArrayObject*)vnm, NPY_ARRAY_C_CONTIGUOUS);

	assert(PyArray_Size(vnm) == (r_n * f_n * beta_n));
	assert(PyArray_NBYTES(vnm) == (r_n * f_n * beta_n * sizeof(double complex)));
	datap = PyArray_DATA((PyArrayObject*)vnm);

	if (kncpus < 0)
		kncpus = beta_n < syscpus ? beta_n : syscpus;
	else
		kncpus = kncpus > syscpus ? syscpus : kncpus;

	if ((r_n * f_n * beta_n) != 0) {
		datar = PyArray_DATA((PyArrayObject*)r);
		dataf = PyArray_DATA((PyArrayObject*)f);
		datan = PyArray_DATA((PyArrayObject*)n);
		datam = PyArray_DATA((PyArrayObject*)m);
		Py_BEGIN_ALLOW_THREADS
			ret = vnmpocnp(r_n, datar,
				       f_n, dataf,
				       beta_n,
				       datan, datam,
				       kL_max, kbessel_name,
				       kncpus,
				       kverb, datap, &error);
		Py_END_ALLOW_THREADS
		if (ret) {
			Py_XDECREF(vnm);
			goto exit_decrement;
		}
	}