static PyObject *build_array(const std::pair<Iterator, Iterator> &range) {
   size_t sz = (npy_intp)std::distance(range.first, range.second);
   npy_intp fdims[] = {(npy_intp)sz};
   PyObject *array = (PyObject*)PyArray_SimpleNew(1, fdims, NPY_OBJECT);
   try {
     size_t i = 0;
     for (Iterator it = range.first; it != range.second; it++, i++) {
       PyObject **ref = (PyObject **)PyArray_GETPTR1((PyArrayObject*)array, i);
       PyObject *newobj = as_python_string(*it);
       Py_XDECREF(*ref);
       *ref = newobj;
     }
   }
   catch (...) {
     size_t i = 0;
     for (i = 0; i < sz; i++) {
       PyObject **ref = (PyObject **)PyArray_GETPTR1((PyArrayObject*)array, i);
       Py_XDECREF(*ref);
       *ref = Py_None;
       Py_XINCREF(*ref);
     }
     Py_XDECREF(array);
     array = NULL;
     std::rethrow_exception(std::current_exception());
   }
   return array;
 }
Example #2
0
/**
 * Update all branch counts associated with a given leaf
 */
void dtnode :: modify_count(double val, int leaf)
{
  // Is this leaf under one of our interior children?
  for(uint i = 0; i < ichildren.size(); i++)
    {
      if(leaf <= maxind[i])
        {
          // Update edge and sum
          (*((double*)PyArray_GETPTR1(this->edges,i))) += val;
          edgesum += val;
          // Recursively update child cts
          (*(ichildren[i])).modify_count(val,leaf);
          return;
        }
    }

  // No, this leaf must be one of our leaves
  
  // Get leaf edge index
  int ei = ichildren.size() + (leaf - leafstart);
  // Update edge and sum
  (*((double*)PyArray_GETPTR1(edges,ei))) += val;
  edgesum += val;
  return;  
}
Example #3
0
PyObject* marching_cubes_func(PyObject* lower, PyObject* upper,
    int numx, int numy, int numz, PyObject* f, double isovalue)
{
    std::vector<double> vertices;
    std::vector<size_t> polygons;
    
    // Copy the lower and upper coordinates to a C array.
    double lower_[3];
    double upper_[3];
    for(int i=0; i<3; ++i)
    {
        PyObject* l = PySequence_GetItem(lower, i);
        if(l == NULL)
            throw std::runtime_error("error");
        PyObject* u = PySequence_GetItem(upper, i);
        if(u == NULL)
        {
            Py_DECREF(l);
            throw std::runtime_error("error");
        }
        
        lower_[i] = PyFloat_AsDouble(l);
        upper_[i] = PyFloat_AsDouble(u);
        
        Py_DECREF(l);
        Py_DECREF(u);
        if(lower_[i]==-1.0 || upper_[i]==-1.0)
        {
            if(PyErr_Occurred())
                throw std::runtime_error("error");
        }
    }
    
    // Marching cubes.
    mc::marching_cubes<double>(lower_, upper_, numx, numy, numz, PythonToCFunc(f), isovalue, vertices, polygons);
    
    // Copy the result to two Python ndarrays.
    npy_intp size_vertices = vertices.size();
    npy_intp size_polygons = polygons.size();
    PyArrayObject* verticesarr = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, &size_vertices, PyArray_DOUBLE));
    PyArrayObject* polygonsarr = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, &size_polygons, PyArray_ULONG));
    
    std::vector<double>::const_iterator it = vertices.begin();
    for(int i=0; it!=vertices.end(); ++i, ++it)
        *reinterpret_cast<double*>(PyArray_GETPTR1(verticesarr, i)) = *it;
    std::vector<size_t>::const_iterator it2 = polygons.begin();
    for(int i=0; it2!=polygons.end(); ++i, ++it2)
        *reinterpret_cast<unsigned long*>(PyArray_GETPTR1(polygonsarr, i)) = *it2;
    
    PyObject* res = Py_BuildValue("(O,O)", verticesarr, polygonsarr);
    Py_XDECREF(verticesarr);
    Py_XDECREF(polygonsarr);
    return res;
}
Example #4
0
int
PyAubio_PyCvecToCCvec (PyObject *input, cvec_t *i) {
    if (PyObject_TypeCheck (input, &Py_cvecType)) {
        Py_cvec * in = (Py_cvec *)input;
        i->norm = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)(in->norm), 0);
        i->phas = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)(in->phas), 0);
        i->length = ((Py_cvec*)input)->length;
        return 1;
    } else {
        PyErr_SetString (PyExc_ValueError, "input array should be aubio.cvec");
        return 0;
    }
}
int APPLY_SPECIFIC(doublecop)(PyArrayObject *x,
                              PyArrayObject **out) {
  Py_XDECREF(*out);
  *out = (PyArrayObject *)PyArray_NewLikeArray(
                           inp, NPY_ANYORDER, NULL, 0);
  if (*out == NULL)
    return -1;

  for (npy_intp i = 0; i < PyArray_DIM(x, 0); i++) {
    *(DTYPE_OUTPUT_0 *)PyArray_GETPTR1(*out, i) =
      (*(DTYPE_INPUT_0 *)PyArray_GETPTR1(x, i)) * 2;
  }
  return 0;
}
PyObject* getAngles(PyObject *self, PyObject *args) {
/*
** Inputs:
** 	interger of search radius (in pixels)
** Modifies:
** 	nothing
** Outputs:
** 	1D numpy array containing correlation values of angle (x-axis)
*/
	Py_Initialize();
	int radius;
	if (!PyArg_ParseTuple(args, "i", &radius))
		return NULL;

	struct item *head = NULL;
	head = getAnglesList(radius, head);
	int numangles = list_length(head);

	npy_intp outdims[1] = {numangles};

	import_array(); // this is required to use PyArray_New() and PyArray_SimpleNew()
	PyArrayObject *output;
	output = (PyArrayObject *) PyArray_SimpleNew(1, outdims, NPY_DOUBLE);

	struct item *current;
	int i=0;
	for(current=head; current!=NULL; current=current->next) {
		*(double *) PyArray_GETPTR1(output, i) = current->angle;
		i++;
	}
	delete_list(head);

	return PyArray_Return(output);
}
Example #7
0
void _pylm_callback(PyObject *func, double *p, double *hx, int m, int n, int  jacobian) {
    int i;
	PyObject *args		= NULL;
    PyObject *result	= NULL;
	
	// marshall parameters from c -> python
	// construct numpy arrays from c 
	
	npy_intp dims_m[1] = {m};
	npy_intp dims_n[1] = {n};
	
    PyObject *estimate = PyArray_SimpleNewFromData(1, dims_m, PyArray_DOUBLE, p);
    PyObject *measurement = PyArray_SimpleNewFromData(1, dims_n , PyArray_DOUBLE, hx);
	
    args = Py_BuildValue("(OO)", estimate, measurement);
    if (!args) {
        goto cleanup;
    }

    // call func
    result = PyObject_CallObject(func, args);
    if (result == NULL) {
        PyErr_Print();
        goto cleanup;
    }
		
	if(!PyArray_Check(result)){
		PyErr_SetString(PyExc_TypeError, 
						"Return value from callback "
						"should be of numpy array type");
		goto cleanup;		
	}	

    // marshall results from python -> c
    
	npy_intp result_size = PyArray_DIM(result, 0);
	
	if ((!jacobian && (result_size == n)) ||
        (jacobian &&  (result_size == m*n))) {

        for (i = 0; i < result_size; i++) {
            double *j = PyArray_GETPTR1(result, i);
			hx[i] = *j;
		}
		
    } else {
        PyErr_SetString(PyExc_TypeError, 
						"Return value from callback "
                        "should be same size as measurement");
    }

 cleanup:
    
    Py_XDECREF(args);
    Py_XDECREF(estimate);
    Py_XDECREF(measurement);
    Py_XDECREF(result);
    return;
}
 inline string_array_output_iterator &operator++() {
   PyObject *s = as_python_string(output);
   PyObject **ref = (PyObject **)PyArray_GETPTR1((PyArrayObject*)array, i);
   Py_XDECREF(*ref);
   *ref = s;
   i++;
   return *this;
 }
Example #9
0
/* Checks if two boxes are near-neighbours by looking at their integer
   coordinates. */
static PyObject *
are_near_neighbours (PyObject *self, PyObject *args)
{
  PyArrayObject *c0, *c1;
  int i, *p0, *p1;

  if (!PyArg_ParseTuple(args, "O!O!", 
			&PyArray_Type, &c0,
			&PyArray_Type, &c1))
    return NULL;

  if (c0->nd != 1) {
     PyErr_SetString(PyExc_ValueError, 
		     "c0 must have dimension 1.");
     return NULL;
  }

  if (c1->nd != 1) {
     PyErr_SetString(PyExc_ValueError, 
		     "c1 must have dimension 1.");
     return NULL;
  }

  if (c0->dimensions[0] != 3) {
     PyErr_SetString(PyExc_ValueError, 
		     "c0 must have shape (3,).");
     return NULL;
  }

  if (c1->dimensions[0] != 3) {
     PyErr_SetString(PyExc_ValueError, 
		     "c1 must have shape (3,).");
     return NULL;
  }


  for (i = 0; i < 3; i++) {
    p0 = (int *) PyArray_GETPTR1 (c0, i);
    p1 = (int *) PyArray_GETPTR1 (c1, i);
    
    if (*p0 - *p1 > 1 || *p1 - *p0 > 1) Py_RETURN_FALSE;
  }

  Py_RETURN_TRUE;
}
Example #10
0
/**
 * Calculate the log of the (uncollapsed) P(w|z) expression
 * (used for the y-sampling step)
 */
double dtnode :: calc_logpwz()
{ 
  // Calculate for this node
  double logpwz = lgamma(orig_edgesum) - lgamma(edgesum);
  for(uint ei = 0; ei < PyArray_DIM(edges,0); ei++)
    {
      logpwz += lgamma(*((double*)PyArray_GETPTR1(edges,ei))) -
        lgamma(*((double*)PyArray_GETPTR1(orig_edges,ei)));
    }
  // Calculate for all interior children
  for(uint i = 0; i < ichildren.size(); i++)
    {
      
      dtnode* child = dynamic_cast<dtnode*>(this->ichildren[i]);
      logpwz += (*child).calc_logpwz();
    }
  return logpwz;
}
Example #11
0
// get index into counts for the given row
int
cptindex1(PyArrayObject *row, int *offsets, int num_parents) {
    register int i,ind=0;

    for (i=0; i<num_parents; i++) {
        ind += *((int*)PyArray_GETPTR1(row, i+1)) * offsets[i];    
    }

    return ind;
}
Example #12
0
File: cKeo.c Project: paalge/paskil
static inline int findIndex(PyObject *arr, int value, int size){
    //returns index of first occurrence of value in 1D array object, -1 if not
    //found
    int i;
    for (i=0;i<size;i++){
        if (*((int*)PyArray_GETPTR1(arr,i)) == value){
            return i;
        }
    }
    return -1;
}
Example #13
0
// calculate the loglikelihood of data
double
_loglikelihood(CPT *cpt, PyArrayObject *lnfac) {
    register int j,k;
    double score = 0.0;

    // score is calculated as follows: 
    //    1) add log((ri-1)!) 
    //    2) subtract log((Nij + ri -1)!)
    //    3) add sum of log(Nijk!)
   
    score += cpt->qi * *((double*)PyArray_GETPTR1(lnfac, cpt->ri - 1));
    for (j=0; j<cpt->qi; j++) {
        score -= *((double*)PyArray_GETPTR1(lnfac, cpt->counts[j][0] + cpt->ri - 1));
        for (k=0; k<cpt->ri; k++) {
            score += *((double*)PyArray_GETPTR1(lnfac, cpt->counts[j][k+1]));
        }
    }
    
    return score;
}
Example #14
0
static PyObject *PyLWPR_G_n_pruned(PyLWPR *self, void *closure) {
   int i;
   PyArrayObject *matout;
   npy_intp len = self->model.nOut;
   
   matout = (PyArrayObject *) PyArray_SimpleNew(1, &len, NPY_INT);

   for (i=0;i<len;i++) {
      *((int *) PyArray_GETPTR1(matout, i)) = self->model.sub[i].n_pruned;
   }
   return PyArray_Return(matout);
}
Example #15
0
/*==========================================================================*/
PyObject *calculate(PyObject *self, PyObject *args)
{
    long i, j;

    KD kd;
    int nReps=0, bPeriodic=0, bEwald=0;
    float fSoft;
    int nPos;
    PyObject *kdobj, *acc, *pot, *pos;
    PARTICLE *testParticles;
  
    PyArg_ParseTuple(args, "OOOOdi", &kdobj, &pos, &acc, &pot, &fSoft, &nPos);
    kd  = PyCObject_AsVoidPtr(kdobj);
    if (kd == NULL) return NULL;
    
    testParticles = (PARTICLE *)malloc(nPos*sizeof(PARTICLE));
    assert(testParticles != NULL);
    for (i=0; i< nPos; i++) {
	for (j=0; j < 3; j++) {
	    testParticles[i].r[j] = 
		(float)*((double *)PyArray_GETPTR2(pos, i, j));
	    testParticles[i].a[j] = 0;
	    }
	    testParticles[i].fMass = 0;
	    testParticles[i].fPot = 0;
	    testParticles[i].fSoft = fSoft;
	    testParticles[i].iOrder = i;
	}
    Py_BEGIN_ALLOW_THREADS

	kdGravWalk(kd, nReps, bPeriodic && bEwald, testParticles, nPos);

    Py_END_ALLOW_THREADS
    
    for (i=0; i < nPos; i++) {
	PyArray_SETITEM(pot, PyArray_GETPTR1(pot,i), PyFloat_FromDouble(testParticles[i].fPot));
	for (j=0; j < 3; j++) {
	    PyArray_SETITEM(acc, PyArray_GETPTR2(acc, i, j), 
			    PyFloat_FromDouble(testParticles[i].a[j]));
	    }
	}


    Py_DECREF(kd);
    /*
    Py_DECREF(pos);
    Py_DECREF(pot);
    Py_DECREF(acc);
    */
    Py_INCREF(Py_None);
    return Py_None;
}
Example #16
0
/**
 * Do a report on multinodes
 */
void dtnode :: report()
{
  vector<node*> multi = get_multinodes();
  for(uint mi = 0; mi < multi.size(); mi++)
    {
      multinode* mu = dynamic_cast<multinode*>(ichildren[mi]);

      double e = *((double*)PyArray_GETPTR1(edges,mi));
      printf("Edge = %f\n",e);
      printf("Multinode %d, y = %d (of %d variants)\n",
             mi,(*mu).get_y(),(*mu).num_variants());
    }
}
Example #17
0
fvec_t *
PyAubio_ArrayToCFvec (PyObject *input) {
  PyObject *array;
  fvec_t *vec;
  if (input == NULL) {
    PyErr_SetString (PyExc_ValueError, "input array is not a python object");
    goto fail;
  }
  // parsing input object into a Py_fvec
  if (PyArray_Check(input)) {

    // we got an array, convert it to an fvec 
    if (PyArray_NDIM (input) == 0) {
      PyErr_SetString (PyExc_ValueError, "input array is a scalar");
      goto fail;
    } else if (PyArray_NDIM (input) > 1) {
      PyErr_SetString (PyExc_ValueError,
          "input array has more than one dimensions");
      goto fail;
    }

    if (!PyArray_ISFLOAT (input)) {
      PyErr_SetString (PyExc_ValueError, "input array should be float");
      goto fail;
    } else if (PyArray_TYPE (input) != AUBIO_NPY_SMPL) {
      PyErr_SetString (PyExc_ValueError, "input array should be float32");
      goto fail;
    } else {
      // input data type is float32, nothing else to do
      array = input;
    }

    // vec = new_fvec (vec->length);
    // no need to really allocate fvec, just its struct member 
    vec = (fvec_t *)malloc(sizeof(fvec_t));
    vec->length = PyArray_SIZE (array);
    vec->data = (smpl_t *) PyArray_GETPTR1 (array, 0);

  } else if (PyObject_TypeCheck (input, &PyList_Type)) {
    PyErr_SetString (PyExc_ValueError, "does not convert from list yet");
    return NULL;
  } else {
    PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input");
    return NULL;
  }

  return vec;

fail:
  return NULL;
}
Example #18
0
PyObject* marching_cubes(PyArrayObject* arr, double isovalue)
{
    if(PyArray_NDIM(arr) != 3)
        throw std::runtime_error("Only three-dimensional arrays are supported.");
    
    // Prepare data.
    npy_intp* shape = PyArray_DIMS(arr);
    long lower[3] = {0,0,0};
    long upper[3] = {shape[0]-1, shape[1]-1, shape[2]-1};
    long numx = upper[0] - lower[0] + 1;
    long numy = upper[1] - lower[1] + 1;
    long numz = upper[2] - lower[2] + 1;
    std::vector<double> vertices;
    std::vector<size_t> polygons;
    
    // Marching cubes.
    mc::marching_cubes<long>(lower, upper, numx, numy, numz, PyArrayToCFunc(arr), isovalue,
                        vertices, polygons);
    
    // Copy the result to two Python ndarrays.
    npy_intp size_vertices = vertices.size();
    npy_intp size_polygons = polygons.size();
    PyArrayObject* verticesarr = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, &size_vertices, PyArray_DOUBLE));
    PyArrayObject* polygonsarr = reinterpret_cast<PyArrayObject*>(PyArray_SimpleNew(1, &size_polygons, PyArray_ULONG));
    
    std::vector<double>::const_iterator it = vertices.begin();
    for(int i=0; it!=vertices.end(); ++i, ++it)
        *reinterpret_cast<double*>(PyArray_GETPTR1(verticesarr, i)) = *it;
    std::vector<size_t>::const_iterator it2 = polygons.begin();
    for(int i=0; it2!=polygons.end(); ++i, ++it2)
        *reinterpret_cast<unsigned long*>(PyArray_GETPTR1(polygonsarr, i)) = *it2;
    
    PyObject* res = Py_BuildValue("(O,O)", verticesarr, polygonsarr);
    Py_XDECREF(verticesarr);
    Py_XDECREF(polygonsarr);
    
    return res;
}
Example #19
0
PyObject *
replace_data(PyObject *self, PyObject *args) {
    int pycpt; 
    PyArrayObject *oldrow, *newrow;
    
    if (!PyArg_ParseTuple(args, "iO!O!", &pycpt, &PyArray_Type, &oldrow, &PyArray_Type, &newrow)) {
        return NULL;
    }
    
    CPT *cpt = (CPT*) pycpt;
    int old_index = cptindex1(oldrow, cpt->offsets, cpt->num_parents);   
    int new_index = cptindex1(newrow, cpt->offsets, cpt->num_parents);
    int oldval = *((int*)PyArray_GETPTR1(oldrow, 0));
    int newval = *((int*)PyArray_GETPTR1(newrow, 0));

    cpt->counts[old_index][0]--;
    cpt->counts[new_index][0]++;
    
    cpt->counts[old_index][oldval+1]--;
    cpt->counts[new_index][newval+1]++;

    Py_RETURN_NONE;
}
Example #20
0
/**
 * Calculate topic-word term of Gibbs sampling eqn
 */
double dtnode :: calc_wordterm(double val, int leaf)
{
  // Is this leaf under one of our interior children?
  double newval;
  for(uint i = 0; i < ichildren.size(); i++)
    {
      if(leaf <= maxind[i])
        {
          // Update value
          newval = ((*((double*)PyArray_GETPTR1(this->edges,i)))
                    / this->edgesum);
          // Recurisively mult value by child
          return (*(this->ichildren[i])).calc_wordterm(newval*val,leaf);
        }
    }

  // No, this leaf must be one of our leaves
  
  // Get leaf edge index
  int ei = ichildren.size() + (leaf - this->leafstart);
  // Update value
  newval = (*((double*)PyArray_GETPTR1(this->edges,ei))) / this->edgesum;
  return (val * newval);
}
 static PyObject *build_array(const Container &container) {
   size_t sz = (size_t)container.size();
   npy_intp fdims[] = {(npy_intp)sz};
   PyObject *array = (PyObject*)PyArray_SimpleNew(1, fdims, NPY_OBJECT);
   try {
     for (size_t i = 0; i < container.size(); i++) {
       PyObject **ref = (PyObject **)PyArray_GETPTR1((PyArrayObject*)array, i);
       PyObject *newobj = as_python_string(container[i]);
       Py_XDECREF(*ref);
       *ref = newobj;
     }
   }
   catch (...) {
     for (size_t i = 0; i < sz; i++) {
       PyObject **ref = (PyObject **)PyArray_GETPTR1((PyArrayObject*)array, i);
       Py_XDECREF(*ref);
       *ref = Py_None;
       Py_XINCREF(*ref);
     }
     Py_XDECREF(array);
     std::rethrow_exception(std::current_exception());
   }
   return array;
 }
Example #22
0
void create_contiguous_input_lengths( PyArrayObject * input_lengths_arr,
    int ** input_lengths )
{
    npy_int num_elements = PyArray_DIMS( input_lengths_arr )[0];

    *input_lengths = (int *) calloc( num_elements, sizeof(int) );

    if ( NULL == (*input_lengths) )
        return;

    for( npy_int elem_idx = 0; elem_idx < num_elements; ++elem_idx )
    {
        (*input_lengths)[elem_idx] = *( (npy_int *) PyArray_GETPTR1( input_lengths_arr, elem_idx ) );
    }
}
Example #23
0
int PyAsap_SetIntFromArray(set<int> &to, PyObject *from)
{
  to.clear();
  PyArrayObject *array = (PyArrayObject *) PyArray_ContiguousFromObject(from, NPY_INT, 1, 1);
  if (array == NULL)
    {
      PyErr_SetString(PyExc_TypeError,
		      "Not compatible with 1D array of integers."); 
      return -1;
    };
  for (int i = 0; i < PyArray_DIM(array, 0); i++)
    to.insert(*((int *)PyArray_GETPTR1(array, i)));
  CHECKREF(array);
  Py_DECREF(array);
  return 0;
}
Example #24
0
/*==========================================================================*/
PyObject *treeinit(PyObject *self, PyObject *args)
{
    int nBucket, nbodies, nTreeBitsLo=14, nTreebitsHi=18;
    int i, j;
    KD kd = (KD)malloc(sizeof(struct kdContext));

    PyObject *pos;  // Nx3 Numpy array of positions
    PyObject *mass; // Nx1 Numpy array of masses
    double dTheta=0.7 * 2.0/sqrt(3.0);
    float fPeriod[3], fTemp, fSoft;
    for (i=0; i<3; i++) fPeriod[i] = 1.0;

    if (!PyArg_ParseTuple(args, "OOiif", &pos, &mass, &nBucket, &nbodies, &fSoft))
        return NULL;

    /*nbodies = PyArray_DIM(mass, 0);*/
    kdInitialize(kd, nbodies, nBucket, dTheta, nTreeBitsLo, nTreebitsHi, fPeriod);
    /*
    ** Allocate particles.
    */
    
    kd->pStorePRIVATE = (PARTICLE *)malloc(nbodies*kd->iParticleSize);
    assert(kd->pStorePRIVATE != NULL);

    Py_BEGIN_ALLOW_THREADS

    for (i=0; i < nbodies; i++)
    {
	for (j=0; j < 3; j++) {
	    fTemp = (float)*((double *)PyArray_GETPTR2(pos, i, j));
	    kd->pStorePRIVATE[i].r[j] = fTemp;
	    kd->pStorePRIVATE[i].a[j] = 0;
	    }
	fTemp = (float)*((double *)PyArray_GETPTR1(mass, i));
        kd->pStorePRIVATE[i].fMass = fTemp;
        kd->pStorePRIVATE[i].fPot = 0;
        kd->pStorePRIVATE[i].fSoft = fSoft;
    }

    kdTreeBuild(kd, nBucket);


    Py_END_ALLOW_THREADS

    return PyCObject_FromVoidPtr((void *)kd, NULL);
}
static PyObject *mandelbrot(PyObject *self, PyObject *args) {
	PyArrayObject *result;
	PyArrayObject *x_coords;
	PyArrayObject *y_coords;
	unsigned int size;
	int x,y;
	if(!PyArg_ParseTuple(args, "O!(O!O!)I", &PyArray_Type, &result, &PyArray_Type, &x_coords, &PyArray_Type, &y_coords, &size))
		return NULL;

#pragma omp parallel for private(y)
	for(x = 0; x < size; x++) {
		for(y = 0; y < size; y++) {
			*(char *)(PyArray_GETPTR2(result, y, x)) = solve(*(float *)(PyArray_GETPTR1(x_coords, x)), *(float *)(PyArray_GETPTR1(y_coords, y)));
		}
	}
	return Py_BuildValue("i",1);
}
Example #26
0
int APPLY_SPECIFIC(conv_desc)(PyArrayObject *filt_shp,
                              cudnnConvolutionDescriptor_t *desc) {
  cudnnStatus_t err;
  int pad[3] = {PAD_0, PAD_1, PAD_2};
  int strides[3] = {SUB_0, SUB_1, SUB_2};
  int upscale[3] = {1, 1, 1};

#if BORDER_MODE == 0
  pad[0] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 2) - 1;
  pad[1] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 3) - 1;
#if NB_DIMS > 2
  pad[2] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 4) - 1;
#endif
#elif BORDER_MODE == 2
  pad[0] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 2) / 2;
  pad[1] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 3) / 2;
#if NB_DIMS > 2
  pad[2] = *(npy_int64 *)PyArray_GETPTR1(filt_shp, 4) / 2;
#endif
#endif

  if (PyArray_DIM(filt_shp, 0) - 2 != NB_DIMS) {
    PyErr_Format(PyExc_ValueError, "Filter shape has too many dimensions: "
                 "expected %d, got %lld.", NB_DIMS,
                 (long long)PyArray_DIM(filt_shp, 0));
    return -1;
  }

  err = cudnnCreateConvolutionDescriptor(desc);
  if (err != CUDNN_STATUS_SUCCESS) {
    PyErr_Format(PyExc_MemoryError, "could not allocate convolution "
                 "descriptor: %s", cudnnGetErrorString(err));
    return -1;
  }

  err = cudnnSetConvolutionNdDescriptor(*desc, NB_DIMS, pad, strides,
                                        upscale, CONV_MODE, PRECISION);
  return 0;
}
Example #27
0
static PyObject *PyCMOR_axis(PyObject * self, PyObject * args)
{
    signal(signal_to_catch, signal_handler);
    int ierr, axis_id, n = 0;
    char *name;
    char *units;
    char *interval;
    int length;
    char type;
    void *coord_vals;
    void *cell_bounds;
    int cell_bounds_ndim;
    char *tmpstr = NULL;
    PyObject *coords_obj, *bounds_obj;
    PyArrayObject *coords = NULL, *bounds = NULL;

/************************************************************************/
/*         HUGE assumtion here is that the data is contiguous!          */
/************************************************************************/

    if (!PyArg_ParseTuple
        (args, "ssiOcOis", &name, &units, &length, &coords_obj, &type,
         &bounds_obj, &cell_bounds_ndim, &interval))
        return NULL;

    if (coords_obj == Py_None) {
        coord_vals = NULL;
    } else {
        coords =
          (PyArrayObject *) PyArray_ContiguousFromObject(coords_obj,
                                                         NPY_NOTYPE, 1, 0);

        if (PyArray_NDIM(coords) != 1) {
            printf("ok we need to pass contiguous flattened arrays only!\n");
            return NULL;
        }

        if (type != 'c') {
            coord_vals = (void *)PyArray_DATA(coords);
            n = cell_bounds_ndim;
        } else {
            tmpstr =
              (char *)malloc(sizeof(char) * length * (cell_bounds_ndim + 1));
            for (ierr = 0; ierr < length; ierr++) {
                coord_vals = (void *)PyArray_GETPTR1(coords, ierr);
                strncpy(&tmpstr[ierr * (cell_bounds_ndim + 1)],
                        coord_vals, cell_bounds_ndim);
                tmpstr[ierr * (cell_bounds_ndim + 1) + cell_bounds_ndim] = '\0';
            }
            coord_vals = &tmpstr[0];
            n = cell_bounds_ndim + 1;
            for (ierr = 0; ierr < length; ierr++) {
            }
        }
    }

    if (bounds_obj == Py_None) {
        cell_bounds = NULL;
    } else {
        bounds =
          (PyArrayObject *) PyArray_ContiguousFromObject(bounds_obj,
                                                         NPY_NOTYPE, 1, 0);
        if (PyArray_NDIM(bounds) != 1) {
            printf("ok we need to pass contiguous flattened arrays only!\n");
            return NULL;
        }
        cell_bounds = (void *)PyArray_DATA(bounds);
    }

    ierr =
      cmor_axis(&axis_id, name, units, length, coord_vals, type,
                cell_bounds, n, interval);

    if (coords != NULL) {
        Py_DECREF(coords);
    }
    if (bounds != NULL) {
        Py_DECREF(bounds);
    }

    if (type == 'c') {
        free(tmpstr);
    }

    if (ierr != 0 || raise_exception) {
        raise_exception = 0;
        PyErr_Format(CMORError, exception_message, "axis");
        return NULL;
    }

    return (Py_BuildValue("i", axis_id));
}
Example #28
0
static PyObject * uberseg_direct(PyObject* self, PyObject* args) {
  int dmin=0,d=0,x=0,y=0,k=0,imin=0; 

  PyObject* seg = NULL;
  PyObject* weight = NULL;
  int Nx;
  int Ny;
  int object_number;
  PyObject* obj_inds_x = NULL;
  PyObject* obj_inds_y = NULL;
  int Ninds;
  int *ptrx,*ptry,*ptrs;
  float *ptrw;
  int dx;
  
  if (!PyArg_ParseTuple(args, (char*)"OOiiiOOi", &seg, &weight, &Nx, &Ny, &object_number, &obj_inds_x, &obj_inds_y, &Ninds)) {
    return NULL;
  }
  
  for(x=0;x<Nx;++x) {
    for(y=0;y<Ny;++y) {

      //shortcuts
      ptrs = (int*)PyArray_GETPTR2(seg,x,y);
      if(*ptrs == object_number)
	continue;
      
      if(*ptrs > 0 && *ptrs != object_number) {
	ptrw = (float*)PyArray_GETPTR2(weight,x,y);
	*ptrw = 0.0;
	continue;
      }

      //must do direct search
      imin = -1;
      for(k=0;k<Ninds;++k) {
	ptrx = (int*)PyArray_GETPTR1(obj_inds_x,k);
	ptry = (int*)PyArray_GETPTR1(obj_inds_y,k);
	dx = x-(*ptrx);
	d = dx*dx;
	dx = y-(*ptry);
	d += dx*dx;
	if(d < dmin || imin == -1) {
	  dmin = d;
	  imin = k;
	}
      }

      if(imin == -1) {
	continue;
      }
      
      ptrx = (int*)PyArray_GETPTR1(obj_inds_x,imin);
      ptry = (int*)PyArray_GETPTR1(obj_inds_y,imin);
      ptrs = (int*)PyArray_GETPTR2(seg,*ptrx,*ptry);

      if(*ptrs != object_number) {
	ptrw = (float*)PyArray_GETPTR2(weight,x,y);
	*ptrw = 0.0;
      }
    }
  }
  
  Py_INCREF(Py_None);
  return Py_None;
}
Example #29
0
PyObject* PackOut( IData *GS, double *ICs,
		    int state, double *stats, double hlast, int idid ) {
  int i, j;
  int numEvents = 0;

  /* Python objects to be returned at end of integration */
  PyObject *OutObj = NULL; /* Overall PyTuple output object */ 
  PyObject *TimeOut = NULL; /* Trajectory times */
  PyObject *PointsOut = NULL; /* Trajectory points */
  PyObject *StatsOut = NULL; /* */

  PyObject *EventPointsOutTuple = NULL;
  PyObject *EventTimesOutTuple = NULL;

  PyObject *AuxOut = NULL;

  assert(GS);

  if( state == FAILURE ) {
    Py_INCREF(Py_None);
    return Py_None;
  }
  
  _init_numpy();

  EventPointsOutTuple = PyTuple_New(GS->nEvents);
  assert(EventPointsOutTuple);
  EventTimesOutTuple = PyTuple_New(GS->nEvents); 
  assert(EventTimesOutTuple);

  
  /* Copy out points */
  npy_intp p_dims[2] = {GS->phaseDim, GS->pointsIdx};
  PointsOut = PyArray_SimpleNew(2, p_dims, NPY_DOUBLE);
  assert(PointsOut);
  /* WARNING -- modified the order of the dimensions here! */
  for(i = 0; i < GS->pointsIdx; i++) {
    for(j = 0; j < GS->phaseDim; j++) {
      *((double *) PyArray_GETPTR2((PyArrayObject *)PointsOut, j, i)) = GS->gPoints[i][j];
    }
  }
  
  /* Copy out times */
  npy_intp t_dims[1] = {GS->timeIdx};
  TimeOut = PyArray_SimpleNew(1, t_dims, NPY_DOUBLE);
  assert(TimeOut);
  for( i = 0; i < GS->timeIdx; i++ ) {
      *((double *) PyArray_GETPTR1((PyArrayObject *)TimeOut, i)) = GS->gTimeV[i];
  }

  /* Copy out auxilliary points */
  npy_intp au_dims[2] = {GS->nAuxVars, GS->pointsIdx};
  if( GS->nAuxVars > 0 && GS->calcAux == 1 ) {
    /* WARNING: The order of the dimensions 
       is switched here! */
    AuxOut = PyArray_SimpleNew(2, au_dims, NPY_DOUBLE);
    assert(AuxOut);
    for( i = 0; i < GS->pointsIdx; i++ ) {
      for( j = 0; j < GS->nAuxVars; j++ ) {
	*((double *) PyArray_GETPTR2((PyArrayObject *)AuxOut, j, i)) = GS->gAuxPoints[i][j];
      }
    }
  }
  
  /* Allocate and copy out integration stats */
  /* Number of stats different between Radau, Dopri */
  npy_intp s_dims[1] = {7};
  StatsOut = PyArray_SimpleNewFromData(1, s_dims, NPY_DOUBLE, stats);
  assert(StatsOut);

  /* Setup the tuple for the event points and times (separate from trajectory).
     Must remember to keep the reference count for Py_None up to date*/
  for( i = 0; i < GS->nEvents; i++ ) {
    PyTuple_SetItem(EventPointsOutTuple, i, Py_None);
    Py_INCREF(Py_None);
    PyTuple_SetItem(EventTimesOutTuple, i, Py_None);
    Py_INCREF(Py_None);
  }
  
  /* Count the number of events for which something was caught */
  numEvents = 0;
  for( i = 0; i < GS->haveActive; i++ ) {
    if( GS->gCheckableEventCounts[i] > 0 ) {
      numEvents++;
    }
  }
  /* Only allocate memory for events if something was caught */
  if( numEvents > 0 ) {
    /* Lower reference count for Py_None from INCREFs in initialization of
       OutTuples above. Decrease by 2*numevents) */
    for( i = 0; i < numEvents; i++ ) {
      Py_DECREF(Py_None);
      Py_DECREF(Py_None);
    }

    for( i = 0; i < GS->haveActive; i++ ) {
      if( GS->gCheckableEventCounts[i] > 0 ) {
	int k, l;
	/* Get the number of points caught for this event, and which one (in list
	   of all active and nonactive events) it is */
	int EvtCt = GS->gCheckableEventCounts[i], EvtIdx = GS->gCheckableEvents[i];
    npy_intp et_dims[1] = {EvtCt};
    npy_intp ep_dims[2] = {GS->phaseDim, EvtCt};
	
	/* Copy the event times, points into a python array */
	PyObject *e_times = PyArray_SimpleNewFromData(1, et_dims, NPY_DOUBLE, GS->gEventTimes[i]);
	assert(e_times);
	PyObject *e_points = PyArray_SimpleNew(2, ep_dims, NPY_DOUBLE);
	assert(e_points);
	for( k = 0; k < EvtCt; k++ ) {
	  for( l = 0; l < GS->phaseDim; l++ ) {
          *((double *) PyArray_GETPTR2((PyArrayObject *)e_points, l, k)) = GS->gEventPoints[i][l][k];
	  }
	}
	/* The returned python tuple has slots for all events, not just active
	   ones, which is why we insert into the tuple at position EvtIdx */
	PyTuple_SetItem(EventPointsOutTuple, EvtIdx, e_points);
	PyTuple_SetItem(EventTimesOutTuple, EvtIdx, e_times);
      }
    }
  }

  /* Pack points, times, stats, events, etc. into a 7 tuple */
  OutObj = PyTuple_New(8);
  assert(OutObj);

  PyTuple_SetItem(OutObj, 0, (PyObject *)TimeOut);

  PyTuple_SetItem(OutObj, 1, (PyObject *)PointsOut);

  if( GS->nAuxVars > 0 && GS->calcAux == 1) {
    PyTuple_SetItem(OutObj, 2, (PyObject *)AuxOut);
  }
  else {
    PyTuple_SetItem(OutObj, 2, Py_None);
    Py_INCREF(Py_None);
  }

  PyTuple_SetItem(OutObj, 3, (PyObject *)StatsOut);

  PyTuple_SetItem(OutObj, 4, PyFloat_FromDouble(hlast));

  PyTuple_SetItem(OutObj, 5, PyFloat_FromDouble((double)idid));

  PyTuple_SetItem(OutObj, 6, EventTimesOutTuple);

  PyTuple_SetItem(OutObj, 7, EventPointsOutTuple);


  return OutObj;
}
Example #30
0
static PyObject * uberseg_tree(PyObject* self, PyObject* args) {
  int x=0,y=0,k=0,segmin=0;
  float dmin=0,r=0,dx=0,d=0;
  float pos[2],fac=0;

  PyObject* seg = NULL;
  PyObject* weight = NULL;
  int Nx;
  int Ny;
  int object_number;
  PyObject* obj_inds_x = NULL;
  PyObject* obj_inds_y = NULL;
  int Ninds;
  int *ptrx,*ptry,*ptrs;
  float *ptrw;
  
  struct mytype *obj = NULL;
  struct fast3tree *tree = NULL;
  struct fast3tree_results *res = NULL;
  
  if (!PyArg_ParseTuple(args, (char*)"OOiiiOOi", &seg, &weight, &Nx, &Ny, &object_number, &obj_inds_x, &obj_inds_y, &Ninds)) {
    return NULL;
  }

  obj = (struct mytype *)malloc(sizeof(struct mytype)*Ninds);
  if(obj == NULL) exit(1);
  
  for(k=0;k<Ninds;++k) {
    ptrx = (int*)PyArray_GETPTR1(obj_inds_x,k);
    ptry = (int*)PyArray_GETPTR1(obj_inds_y,k);
    ptrs = (int*)PyArray_GETPTR2(seg,*ptrx,*ptry);
    obj[k].idx = k;
    obj[k].seg = *ptrs;
    obj[k].pos[0] = (float)(*ptrx);
    obj[k].pos[1] = (float)(*ptry);
  }
  
  tree = fast3tree_init(Ninds,obj);
  if(tree == NULL) exit(1);

  res = fast3tree_results_init();    
  if(res == NULL) exit(1);

  float maxr = 1.1*sqrt(Nx*Nx+Ny*Ny);
    
  for(x=0;x<Nx;++x) {
    for(y=0;y<Ny;++y) {
      
      //shortcuts
      ptrs = (int*)PyArray_GETPTR2(seg,x,y);
      if(*ptrs == object_number)
	continue;
      
      if(*ptrs > 0 && *ptrs != object_number) {
	ptrw = (float*)PyArray_GETPTR2(weight,x,y);
	*ptrw = 0.0;
	continue;
      }
      
      //must do search
      pos[0] = (float)x;
      pos[1] = (float)y;
      r = fast3tree_find_next_closest_distance(tree,res,pos);
      fac = 1.0/1.1;
      do {
	fac *= 1.1;
	fast3tree_results_clear(res);
	fast3tree_find_sphere(tree,res,pos,r*fac);
      } while(res->num_points == 0 && r*fac <= maxr);
      
      segmin = -1;
      for(k=0;k<res->num_points;++k) {
	dx = res->points[k]->pos[0]-x;
	d = dx*dx;
	dx = res->points[k]->pos[1]-y;
	d += dx*dx;
	if(segmin == -1 || d < dmin) {
	  segmin = res->points[k]->seg;
	  dmin = d;
	}
      }
      
      if(segmin == -1) {
	continue;
      }
      
      if(segmin != object_number) {
	ptrw = (float*)PyArray_GETPTR2(weight,x,y);
	*ptrw = 0.0;
      }
    }
  }

  free(obj);
  fast3tree_free(&tree);
  fast3tree_results_free(res);
 
  
  Py_INCREF(Py_None);
  return Py_None;
}