示例#1
0
static PyObject *
curve(struct PyLibPlot *self, PyObject *args)
{
	PyObject *ox, *oy;
	PyObject *x, *y;
	npy_intp i, n;

	if ( !PyArg_ParseTuple( args, "OO", &ox, &oy ) )
		return NULL;

	x = PyArray_ContiguousFromAny( ox, NPY_DOUBLE, 1, 1 );
	y = PyArray_ContiguousFromAny( oy, NPY_DOUBLE, 1, 1 );

	if ( x == NULL || y == NULL )
		goto quit;

	n = BGL_MIN( PyArray_SIZE(x), PyArray_SIZE(y) );
	if ( n <= 0 )
		goto quit;

	pl_fmove_r( self->pl, BGL_DArray1(x,0), BGL_DArray1(y,0) );
	for ( i = 1; i < n; i++ )
		pl_fcont_r( self->pl, BGL_DArray1(x,i), BGL_DArray1(y,i) );
	pl_endpath_r( self->pl );

quit:
	Py_XDECREF(x);
	Py_XDECREF(y);
    Py_RETURN_NONE;
}
示例#2
0
static PyObject *
symbols(struct PyLibPlot *self, PyObject *args)
{
	PyObject *ox, *oy;
	PyObject *x, *y;
	double d0;
	int i0;
    npy_intp i, n;

	if ( !PyArg_ParseTuple( args, "OOid", &ox, &oy, &i0, &d0 ) )
		return NULL;

	x = PyArray_ContiguousFromAny( ox, NPY_DOUBLE, 1, 1 );
	y = PyArray_ContiguousFromAny( oy, NPY_DOUBLE, 1, 1 );

	if ( x == NULL || y == NULL )
		goto quit;

	n = BGL_MIN( PyArray_SIZE(x), PyArray_SIZE(y) );

	_symbol_begin( self->pl, i0, d0 );

	for ( i = 0; i < n; i++ )
		_symbol_draw( self->pl, BGL_DArray1(x,i), BGL_DArray1(y,i), i0, d0 );

	_symbol_end( self->pl, i0, d0 );

quit:
	Py_XDECREF(x);
	Py_XDECREF(y);
    Py_RETURN_NONE;
}
示例#3
0
文件: main.cpp 项目: banados/lsd
static PyObject *Py_table_join(PyObject *self, PyObject *args)
{
	PyObject *ret = NULL;

	PyObject *id1 = NULL, *id2 = NULL, *m1 = NULL, *m2 = NULL;
	const char *join_type = NULL;

	try
	{
		PyObject *id1_, *id2_, *m1_, *m2_;
		if (! PyArg_ParseTuple(args, "OOOOs", &id1_, &id2_, &m1_, &m2_, &join_type))	throw E(PyExc_Exception, "Wrong number or type of args");

		if ((id1 = PyArray_ContiguousFromAny(id1_, PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "id1 is not a 1D uint64 NumPy array");
		if ((id2 = PyArray_ContiguousFromAny(id2_, PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "Could not cast the value of id2 to 1D NumPy array");
		if ((m1  = PyArray_ContiguousFromAny(m1_,  PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "Could not cast the value of m1 to 1D NumPy array");
		if ((m2  = PyArray_ContiguousFromAny(m2_,  PyArray_UINT64, 1, 1)) == NULL)	throw E(PyExc_Exception, "Could not cast the value of m2 to 1D NumPy array");

		if (PyArray_DIM(m1, 0) != PyArray_DIM(m2, 0))  throw E(PyExc_Exception, "The sizes of len(m1) and len(m2) must be the same");

		#define DATAPTR(type, obj) ((type*)PyArray_DATA(obj))
		PyOutput o;
		table_join(
			o,
			DATAPTR(uint64_t, id1), PyArray_Size(id1),
			DATAPTR(uint64_t, id2), PyArray_Size(id2),
			DATAPTR(uint64_t, m1), DATAPTR(uint64_t, m2), PyArray_Size(m2),
			join_type
		);
		#undef DATAPTR
		o.resize(o.size);

		ret = PyTuple_New(4);
		// because PyTuple will take ownership (and PyOutput will do a DECREF on destruction).
		Py_INCREF(o.o_idx1);
		Py_INCREF(o.o_idx2);
		Py_INCREF(o.o_idxLink);
		Py_INCREF(o.o_isnull);
		PyTuple_SetItem(ret, 0, (PyObject *)o.o_idx1);
		PyTuple_SetItem(ret, 1, (PyObject *)o.o_idx2);
		PyTuple_SetItem(ret, 2, (PyObject *)o.o_idxLink);
		PyTuple_SetItem(ret, 3, (PyObject *)o.o_isnull);
	}
	catch(const E& e)
	{
		ret = NULL;
	}

	Py_XDECREF(id1);
	Py_XDECREF(id2);
	Py_XDECREF(m1);
	Py_XDECREF(m2);

	return ret;
}
示例#4
0
static PyObject *
clipped_colored_symbols(struct PyLibPlot *self, PyObject *args)
{
	PyObject *ox, *oy, *oc;
	PyObject *x, *y, *c;
	double xmin, xmax, ymin, ymax;
	double d0;
	int i0;
    npy_intp i, n;
	double px, py;
	int r, g, b;

	if ( !PyArg_ParseTuple( args, "OOOiddddd", &ox, &oy, &oc,
			&i0, &d0, &xmin, &xmax, &ymin, &ymax ) )
		return NULL;

	x = PyArray_ContiguousFromAny( ox, NPY_DOUBLE, 1, 1 );
	y = PyArray_ContiguousFromAny( oy, NPY_DOUBLE, 1, 1 );
	c = PyArray_ContiguousFromAny( oc, NPY_DOUBLE, 2, 2 );

	if ( x == NULL || y == NULL || c == NULL )
		goto quit;

	n = BGL_MIN( PyArray_SIZE(x), PyArray_SIZE(y) );
	n = BGL_MIN( n, PyArray_SIZE(c) );
	
	_symbol_begin( self->pl, i0, d0 );

	for ( i = 0; i < n; i++ )
	{
		px = BGL_DArray1(x,i);
		py = BGL_DArray1(y,i);

		if ( px >= xmin && px <= xmax &&
		     py >= ymin && py <= ymax ) {
			r = (int) floor( BGL_DArray2(c,i,0)*65535 );
			g = (int) floor( BGL_DArray2(c,i,1)*65535 );
			b = (int) floor( BGL_DArray2(c,i,2)*65535 );
			pl_fillcolor_r( self->pl, r, g, b );
			pl_pencolor_r(  self->pl, r, g, b );
		  
			_symbol_draw( self->pl, px, py, i0, d0 );
		}
	}

	_symbol_end( self->pl, i0, d0 );

quit:
	Py_XDECREF(x);
	Py_XDECREF(y);
	Py_XDECREF(c);
    Py_RETURN_NONE;
}
示例#5
0
static PyObject *
biggles_contour_segments( PyObject *self, PyObject *args )
{
	PyObject *ox, *oy, *oz, *list, *ref;
	PyObject *x, *y, *z;
	double z0;
	double segs[BGL_MAX_SEGS][4];
	int i, j, k, ns;

	list = NULL;

	if ( !PyArg_ParseTuple(args, "OOOd", &ox, &oy, &oz, &z0) )
		return NULL;

	x = PyArray_ContiguousFromAny( ox, NPY_DOUBLE, 1, 1 );
	y = PyArray_ContiguousFromAny( oy, NPY_DOUBLE, 1, 1 );
	z = PyArray_ContiguousFromAny( oz, NPY_DOUBLE, 2, 2 );

	if ( x == NULL || y == NULL || z == NULL )
		goto quit;

    if ( PyArray_DIM(z,0) != PyArray_DIM(x,0)
             || PyArray_DIM(z,1) != PyArray_DIM(y,0) ) {
        PyErr_SetString( PyExc_ValueError,
                         "array dimensions are not compatible" );
        goto quit;
	}

	list = PyList_New( 0 );
	if ( list == NULL )
		goto quit;

	for ( i = 0; i < PyArray_DIM(z,0)-1; i++ )
        for ( j = 0; j < PyArray_DIM(z,1)-1; j++ )
        {
            ns = _pixel_interpolate( x, y, z, z0, i, j, segs );
            for ( k = 0; k < ns; k++ )
            {
                ref = Py_BuildValue( "((dd)(dd))",
                                     segs[k][0], segs[k][1],
                                     segs[k][2], segs[k][3] );
                PyList_Append( list, ref );
                Py_DECREF(ref); /* ??? */
            }
        }

quit:
	Py_XDECREF(x);
	Py_XDECREF(y);
	Py_XDECREF(z);
	return list;
}
示例#6
0
static PyObject *
biggles_hammer_geodesic_fill( PyObject *self, PyObject *args )
{
	PyObject *ol, *ob, *ref;
	PyObject *l, *b, *l2, *b2;
    int div;
	npy_intp i, n, dims[1];

	ref = NULL;

	if ( !PyArg_ParseTuple(args, "OOi", &ol, &ob, &div) )
		return NULL;

	l = PyArray_ContiguousFromAny( ol, NPY_DOUBLE, 1, 1 );
	b = PyArray_ContiguousFromAny( ob, NPY_DOUBLE, 1, 1 );

	if ( l == NULL || b == NULL )
	{	
		Py_XDECREF(l);
		Py_XDECREF(b);
		return NULL;
	}

	n = PyArray_SIZE(l);
	dims[0] = (n-1)*div + 1;

	l2 = PyArray_ZEROS( 1, dims, NPY_DOUBLE, 0);
	b2 = PyArray_ZEROS( 1, dims, NPY_DOUBLE, 0);

	if ( l2 == NULL || b2 == NULL )
		goto quit;

	for ( i = 0; i < n-1; i++ ) {
		_lb_geodesic( div,
			BGL_DArray1(l,i), BGL_DArray1(b,i),
			BGL_DArray1(l,i+1), BGL_DArray1(b,i+1),
            BGL_DArray1_ptr(l2, i*div),
            BGL_DArray1_ptr(b2, i*div));
    }

	ref = Py_BuildValue( "OO", l2, b2 );
quit:
	Py_DECREF(l);
	Py_DECREF(b);
	Py_XDECREF(l2);
	Py_XDECREF(b2);
	return ref;
}
static int
PyDistLookup_init(
    PyDistLookup* self,
    PyObject* args,
    /*@unused@*/ PyObject* kwds) {

  PyObject* py_array_obj = NULL;
  PyArrayObject* array_obj = NULL;

  if (!PyArg_ParseTuple(args, "O(dd)(dd)(dd):DistortionLookupTable.__init__",
                        &py_array_obj,
                        &(self->x.crpix[0]), &(self->x.crpix[1]),
                        &(self->x.crval[0]), &(self->x.crval[1]),
                        &(self->x.cdelt[0]), &(self->x.cdelt[1]))) {
    return -1;
  }

  array_obj = (PyArrayObject*)PyArray_ContiguousFromAny(py_array_obj, NPY_FLOAT32, 2, 2);
  if (array_obj == NULL) {
    return -1;
  }

  self->py_data = array_obj;
  self->x.naxis[0] = (unsigned int)PyArray_DIM(array_obj, 1);
  self->x.naxis[1] = (unsigned int)PyArray_DIM(array_obj, 0);
  self->x.data = (float *)PyArray_DATA(array_obj);

  return 0;
}
static int
PyDistLookup_set_data(
    PyDistLookup* self,
    PyObject* value,
    /*@unused@*/ void* closure) {

  PyArrayObject* value_array = NULL;

  if (value == NULL) {
    Py_XDECREF(self->py_data);
    self->py_data = NULL;
    self->x.data = NULL;
    return 0;
  }

  value_array = (PyArrayObject*)PyArray_ContiguousFromAny(value, NPY_FLOAT32, 2, 2);

  if (value_array == NULL) {
    return -1;
  }

  Py_XDECREF(self->py_data);

  self->py_data = value_array;
  self->x.naxis[0] = (unsigned int)PyArray_DIM(value_array, 1);
  self->x.naxis[1] = (unsigned int)PyArray_DIM(value_array, 0);
  self->x.data = (float *)PyArray_DATA(value_array);

  return 0;
}
示例#9
0
int BuildRealArray(int size,PyObject *input,double *array) {

  int i,result = -1;
  PyArrayObject *array_py = NULL;

  Py_INCREF(input);

  if ((array_py = (PyArrayObject *)
       PyArray_ContiguousFromAny(input,PyArray_DOUBLE,1,1)) == NULL)
    goto cleanup;

  if (PyArray_DIM(array_py,0) < size) {
    PyErr_SetString(PyExc_ValueError,"array shorter than expected");
    goto cleanup;
  }

  for (i = 0; i < size; i++)
    array[i] = ((double *) PyArray_DATA(array_py))[i];

  result = 0;

 cleanup:
  Py_XDECREF(input   );
  Py_XDECREF(array_py);

  return result;

}
示例#10
0
static int
convert_matrix(
    /*@null@*/ PyObject* pyobj,
    PyArrayObject** array,
    double** data,
    unsigned int* order) {

  if (pyobj == Py_None) {
    *array = NULL;
    *data = NULL;
    *order = 0;
    return 0;
  }

  *array = (PyArrayObject*)PyArray_ContiguousFromAny(
      pyobj, PyArray_DOUBLE, 2, 2);
  if (*array == NULL) {
    return -1;
  }

  if (PyArray_DIM(*array, 0) != PyArray_DIM(*array, 1)) {
    PyErr_SetString(PyExc_ValueError,
                    "Matrix must be square.");
    return -1;
  }

  *data = (double*)PyArray_DATA(*array);
  *order = (unsigned int)PyArray_DIM(*array, 0) - 1;

  return 0;
}
示例#11
0
static PyObject *
biggles_hammer_call_vec( PyObject *self, PyObject *args )
{
	PyObject *ol, *ob, *ret;
	PyObject *l, *b, *u, *v;
	double l0, b0, rot;
	double ll, bb;
	npy_intp i, n;

	ret = NULL;

	if ( !PyArg_ParseTuple(args, "OOddd", &ol, &ob, &l0, &b0, &rot) )
		return NULL;

    // 1-d C contiguous
	l = PyArray_ContiguousFromAny( ol, NPY_DOUBLE, 1, 1 );
	b = PyArray_ContiguousFromAny( ob, NPY_DOUBLE, 1, 1 );

	if ( l == NULL || b == NULL )
		goto quit0;

	n = BGL_MIN( PyArray_SIZE(l), PyArray_SIZE(b) );

    u = PyArray_ZEROS(1, &n, NPY_DOUBLE, 0);
    v = PyArray_ZEROS(1, &n, NPY_DOUBLE, 0);

	if ( u == NULL || v == NULL )
		goto quit1;

	for ( i = 0; i < n; i++ )
	{
		_lb_input( BGL_DArray1(l,i), BGL_DArray1(b,i),
			l0, b0, rot, &ll, &bb );
		_lb2uv( ll, bb, BGL_DArray1_ptr(u,i), BGL_DArray1_ptr(v,i) );
	}

	ret = Py_BuildValue( "OO", u, v );

quit1:
	Py_XDECREF(u);
	Py_XDECREF(v);
quit0:
	Py_XDECREF(l);
	Py_XDECREF(b);
	return ret;
}
示例#12
0
static PyObject *
clipped_symbols(struct PyLibPlot *self, PyObject *args)
{
	PyObject *ox, *oy;
	PyObject *x, *y;
	double xmin, xmax, ymin, ymax;
	double d0;
	int i0;
    npy_intp i, n;
	double px, py;

	if ( !PyArg_ParseTuple( args, "OOiddddd", &ox, &oy,
			&i0, &d0, &xmin, &xmax, &ymin, &ymax ) )
		return NULL;

	x = PyArray_ContiguousFromAny( ox, NPY_DOUBLE, 1, 1 );
	y = PyArray_ContiguousFromAny( oy, NPY_DOUBLE, 1, 1 );

	if ( x == NULL || y == NULL )
		goto quit;

	n = BGL_MIN( PyArray_SIZE(x), PyArray_SIZE(y) );

	_symbol_begin( self->pl, i0, d0 );

	for ( i = 0; i < n; i++ )
	{
		px = BGL_DArray1(x,i);
		py = BGL_DArray1(y,i);

		if ( px >= xmin && px <= xmax &&
		     py >= ymin && py <= ymax )
			_symbol_draw( self->pl, px, py, i0, d0 );
	}

	_symbol_end( self->pl, i0, d0 );

quit:
	Py_XDECREF(x);
	Py_XDECREF(y);
    Py_RETURN_NONE;
}
示例#13
0
static PyArrayObject *
_get_transform_mesh(PyObject *py_affine, npy_intp *dims)
{
    /* TODO: Could we get away with float, rather than double, arrays here? */

    /* Given a non-affine transform object, create a mesh that maps
    every pixel in the output image to the input image.  This is used
    as a lookup table during the actual resampling. */

    PyObject *py_inverse = NULL;
    npy_intp out_dims[3];

    out_dims[0] = dims[0] * dims[1];
    out_dims[1] = 2;

    py_inverse = PyObject_CallMethod(
        py_affine, (char *)"inverted", (char *)"", NULL);
    if (py_inverse == NULL) {
        return NULL;
    }

    numpy::array_view<double, 2> input_mesh(out_dims);
    double *p = (double *)input_mesh.data();

    for (npy_intp y = 0; y < dims[0]; ++y) {
        for (npy_intp x = 0; x < dims[1]; ++x) {
            *p++ = (double)x;
            *p++ = (double)y;
        }
    }

    PyObject *output_mesh =
        PyObject_CallMethod(
            py_inverse, (char *)"transform", (char *)"O",
            (char *)input_mesh.pyobj(), NULL);

    Py_DECREF(py_inverse);

    if (output_mesh == NULL) {
        return NULL;
    }

    PyArrayObject *output_mesh_array =
        (PyArrayObject *)PyArray_ContiguousFromAny(
            output_mesh, NPY_DOUBLE, 2, 2);

    Py_DECREF(output_mesh);

    if (output_mesh_array == NULL) {
        return NULL;
    }

    return output_mesh_array;
}
示例#14
0
文件: acf_ext.c 项目: pearu/iocbio
static PyObject *py_acf_maximum_point(PyObject *self, PyObject *args)
{
  int n, rows;
  PyObject* f_py = NULL;
  PyObject* f1_py = NULL;
  ACFInterpolationMethod mth = ACFUnspecified;
  double r;
  double *f = NULL;
  int start_j = 0;
  if (!PyArg_ParseTuple(args, "Oii", &f1_py, &start_j, &mth))
    return NULL;
  switch (mth)
    {
    case ACFInterpolationConstant: ;
    case ACFInterpolationLinear: ;
    case ACFInterpolationCatmullRom: 
    case ACFInterpolationConstantWithSizeReduction: ;
    case ACFInterpolationLinearWithSizeReduction: ;
    case ACFInterpolationCatmullRomWithSizeReduction: ;
      break;
    default:
      PyErr_SetString(PyExc_TypeError,"third argument must be 0, 1, or 2");
      return NULL;
    }
  f_py = PyArray_ContiguousFromAny(f1_py, PyArray_DOUBLE, 1, 2);
  if (f_py==NULL)
    return NULL;
  if (PyArray_NDIM(f_py)==2)
    {
      n = PyArray_DIMS(f_py)[0];
      rows = PyArray_DIMS(f_py)[1];
      if (rows<=0)
	{
	  PyErr_SetString(PyExc_TypeError,"first argument is empty");
	  return NULL;	  
	}
    }
  else
    {
      n = PyArray_DIMS(f_py)[0];
      rows = 1;
    }
  assert(rows>0);
  f = (double*)PyArray_DATA(f_py);
  r = acf_maximum_point(f, n, rows, start_j, mth);
  if (f1_py != f_py)
    {
      Py_DECREF(f_py);
    }
  return Py_BuildValue("d",r);
}
示例#15
0
static PyObject *
clipped_curve(struct PyLibPlot *self, PyObject *args)
{
	PyObject *ox, *oy;
	PyObject *x, *y;
	double xmin, xmax, ymin, ymax;
	npy_intp i, n;

	if ( !PyArg_ParseTuple( args, "OOdddd", &ox, &oy,
			&xmin, &xmax, &ymin, &ymax ) )
		return NULL;

	x = PyArray_ContiguousFromAny( ox, NPY_DOUBLE, 1, 1 );
	y = PyArray_ContiguousFromAny( oy, NPY_DOUBLE, 1, 1 );

	if ( x == NULL || y == NULL )
		goto quit;

	n = BGL_MIN( PyArray_SIZE(x), PyArray_SIZE(y) );
	if ( n <= 0 )
		goto quit;

	for ( i = 0; i < n-1; i++ )
	{
		clipped_pl_fline_r( self->pl,
			xmin, xmax, ymin, ymax,
			BGL_DArray1(x,i), BGL_DArray1(y,i),
			BGL_DArray1(x,i+1), BGL_DArray1(y,i+1) );
	}
	pl_endpath_r( self->pl );

quit:
	Py_XDECREF(x);
	Py_XDECREF(y);
    Py_RETURN_NONE;
}
示例#16
0
static PyObject *dofilt_wrap(PyObject *self, PyObject *args)
{
    int n;
    npy_intp dim[1];
    PyObject *ao, *fo;
    PyArrayObject *a, *r;
    FILTER *handle;
    IIRSPEC *filter;

    if (!PyArg_ParseTuple(args, "OO:dofilt", &ao, &fo)) {
	return NULL;
    }

    if (!PyCObject_Check(fo)) {
	PyErr_SetString(PyExc_TypeError, "second argument must be a filter object");
	return NULL;
    }
    handle = (FILTER *)PyCObject_AsVoidPtr(fo);

    a = (PyArrayObject *)PyArray_ContiguousFromAny(ao, NPY_DOUBLE, 1, 1);
    if (a == NULL) {
	return NULL;
    }
    n = PyArray_DIM(a, 0);

    dim[0] = n;
    r = (PyArrayObject *)PyArray_SimpleNew(1, dim, NPY_DOUBLE);
    if (r == NULL) {
	Py_DECREF(a);
	return NULL;
    }

    if (handle->type == FILTER_TYPE_IIR) {
	filter = (IIRSPEC *)&handle->iirspec;
	if (bdiir((double *)PyArray_DATA(a), (double *)PyArray_DATA(r), n, filter) < 0) {
	    PyErr_SetString(PyExc_RuntimeError, "bdiir() failed");  // because it allocates memory,
	    Py_DECREF(a);                                           // which it shouldn't
	    Py_DECREF(r);
	    return NULL;
	}
    } else {
	FFTfilter((double *)PyArray_DATA(a), (double *)PyArray_DATA(r), handle->gain, n);
    }

    Py_DECREF(a);
    return PyArray_Return(r);
}
示例#17
0
static PyObject *
color_density_plot(struct PyLibPlot *self, PyObject *args)
{
	PyObject *ogrid;
	PyObject *grid;
	double xmin, xmax, ymin, ymax;
	
	double px, py, dx, dy;
	npy_intp xi, yi, xn, yn;
	int    r, g, b;

	if ( !PyArg_ParseTuple( args, "Odddd", &ogrid,
				&xmin, &xmax, &ymin, &ymax ) )
		return NULL;

	grid = PyArray_ContiguousFromAny( ogrid, NPY_DOUBLE, 3, 3 );

	if ( grid == NULL )
		goto quit;

	if ( PyArray_NDIM(grid) != 3) {
		printf("Expect a NxMx3 array for color densgrid");
		goto quit;
	}
	
	xn = PyArray_DIM(grid, 0);
	yn = PyArray_DIM(grid, 1);
	dx = (xmax - xmin) / xn;
	dy = (ymax - ymin) / yn;
	
	for   ( xi=0, px=xmin; xi < xn; xi++, px+=dx ) {
	  for ( yi=0, py=ymin; yi < yn; yi++, py+=dy ) {
	    r = (int) floor( BGL_DArray3(grid,xi,yi,0)*65535 );
	    g = (int) floor( BGL_DArray3(grid,xi,yi,1)*65535 );
	    b = (int) floor( BGL_DArray3(grid,xi,yi,2)*65535 );
	    pl_filltype_r ( self->pl, 1.0 );
	    pl_fillcolor_r( self->pl, r, g, b );
	    pl_pencolor_r ( self->pl, r, g, b );

	    pl_fbox_r( self->pl, px, py, px+dx, py+dy );
	  }
	}

quit:
	Py_XDECREF(grid);
    Py_RETURN_NONE;
}
示例#18
0
文件: pyutil.c 项目: rajul/astropy
int
set_double_array(
    const char* propname,
    PyObject* value,
    int ndims,
    const npy_intp* dims,
    double* dest) {

  PyArrayObject* value_array = NULL;
  npy_int        i           = 0;
  char           shape_str[SHAPE_STR_LEN];

  if (check_delete(propname, value)) {
    return -1;
  }

  value_array = (PyArrayObject*)PyArray_ContiguousFromAny(value, PyArray_DOUBLE,
                                                          ndims, ndims);
  if (value_array == NULL) {
    return -1;
  }

  if (dims != NULL) {
    for (i = 0; i < ndims; ++i) {
      if (PyArray_DIM(value_array, i) != dims[i]) {
        shape_to_string(ndims, dims, shape_str);
        PyErr_Format(
            PyExc_ValueError,
            "'%s' array is the wrong shape, must be %s",
            propname, shape_str);
        Py_DECREF(value_array);
        return -1;
      }
    }
  }

  copy_array_to_c_double(value_array, dest);

  Py_DECREF(value_array);

  return 0;
}
示例#19
0
ValVector numpyToValVector(PyObject* obj)
{
  PyArrayObject *arrayobj = (PyArrayObject*)
    PyArray_ContiguousFromAny(obj, NPY_DOUBLE, 1, 1);
  if(arrayobj == NULL)
    {
      throw "Cannot covert item to 1D numpy array";
    }

  const double* data = (double*)PyArray_DATA(arrayobj);
  unsigned dim = PyArray_DIMS(arrayobj)[0];

  ValVector out;
  out.reserve(dim);
  for(unsigned i=0; i<dim; ++i)
    out.push_back(data[i]);

  Py_DECREF((PyObject*)arrayobj);

  return out;
}
示例#20
0
static PyObject*
pydat_cell(HDSObject *self, PyObject *args)
{
    PyObject *pobj1, *osub;
    if(!PyArg_ParseTuple(args, "O:pydat_cell", &osub))
        return NULL;

    // Recover C-pointer passed via Python
    HDSLoc* loc1 = HDS_retrieve_locator(self);

    // Attempt to convert the input to something useable
    PyArrayObject *sub = (PyArrayObject *) PyArray_ContiguousFromAny(osub, NPY_INT, 1, 1);
    if(!sub) return NULL;

    // Convert Python-like --> Fortran-like
    int ndim = PyArray_SIZE(sub);
    int i, rdim[ndim];
    int *sdata = (int*)PyArray_DATA(sub);
    for(i=0; i<ndim; i++) rdim[i] = sdata[ndim-i-1]+1;

    HDSLoc* loc2 = NULL;
    int status = SAI__OK;
    errBegin(&status);
    // Finally run the routine
    datCell(loc1, ndim, rdim, &loc2, &status);
    if(status != SAI__OK) goto fail;

    // PyCObject to pass pointer along to other wrappers
    Py_DECREF(sub);
    return HDS_create_object(loc2);

fail:
    raiseHDSException(&status);
    Py_XDECREF(sub);
    return NULL;
};
static PyObject *
cpmaximum(PyObject *self, PyObject *args)
{
     PyObject *image     = NULL; /* the image ndarray */
     PyObject *cimage    = NULL; /* a contiguous version of the array */
     PyObject *structure = NULL; /* the structure ndarray */
     PyObject *cstructure= NULL; /* a contiguous version of the structure */
     PyObject *im_shape  = NULL; /* the image shape sequence */
     PyObject *str_shape = NULL; /* the structure shape sequence */
     PyObject *offset    = NULL; /* 2-tuple giving the x and y offset of the origin of the structuring element */
     long     height     = 0;    /* the image height */
     long     width      = 0;    /* the image width */
     long     strheight  = 0;    /* the structuring element height */
     long     strwidth   = 0;    /* the structuring element width */
     PyObject *output    = NULL; /* the output ndarray */
     double   *imdata    = NULL; /* the image data */
     char     *strdata   = NULL; /* the structure data (really boolean) */
     double   *out_data  = NULL; /* the output data */
     const char *error   = NULL;
     PyObject **shapes[] = { &im_shape, &im_shape, &str_shape, &str_shape };
     long     *slots[]   = { &width, &height, &strwidth, &strheight };
     int      indices[]  = { 0,1,0,1 };
     int      i          = 0;
     int      j          = 0;
     int      k          = 0;
     int      l          = 0;
     npy_intp dims[2];
     long     xoff       = 0;
     long     yoff       = 0;

     image = PySequence_GetItem(args,0);
     if (! image) {
          error = "Failed to get image from arguments";
          goto exit;
     }
     cimage = PyArray_ContiguousFromAny(image, NPY_DOUBLE,2,2);
     if (! cimage) {
          error = "Failed to make a contiguous array from first argument";
          goto exit;
     }
     structure = PySequence_GetItem(args,1);
     if (! structure) {
          error = "Failed to get structuring element from arguments";
          goto exit;
     }
     cstructure = PyArray_ContiguousFromAny(structure, NPY_BOOL,2,2);
     if (! cstructure) {
          error = "Failed to make a contiguous array from second argument";
          goto exit;
     }
     im_shape = PyObject_GetAttrString(cimage,"shape");
     if (! im_shape) {
          error = "Failed to get image.shape";
          goto exit;
     }
     if (! PyTuple_Check(im_shape)) {
          error = "image.shape not a tuple";
          goto exit;
     }
     if (PyTuple_Size(im_shape) != 2) {
          error = "image is not 2D";
          goto exit;
     }

     str_shape = PyObject_GetAttrString(cstructure,"shape");
     if (! str_shape) {
          error = "Failed to get structure.shape";
          goto exit;
     }
     if (! PyTuple_Check(str_shape)) {
          error = "structure.shape not a tuple";
          goto exit;
     }
     if (PyTuple_Size(str_shape) != 2) {
          error = "structure is not 2D";
          goto exit;
     }
     for (i=0;i<4;i++) {
          PyObject *obDim = PyTuple_GetItem(*shapes[i],indices[i]);
          *(slots[i]) = PyInt_AsLong(obDim);
          if (PyErr_Occurred()) {
               error = "Array shape is not a tuple of integers";
               goto exit;
          }
     }
     imdata = (double *)PyArray_DATA(cimage);
     if (! imdata) {
          error = "Failed to get image data";
          goto exit;
     }
     strdata = (char *)PyArray_DATA(cstructure);
     if (! strdata) {
          error = "Failed to get structure data";
          goto exit;
     }
     offset = PySequence_GetItem(args,2);
     if (! offset) {
          error = "Failed to get offset into structure from args";
          goto exit;
     }
     if (! PyTuple_Check(offset)) {
          error = "offset is not a tuple";
          goto exit;
     } else {
          PyObject *temp = PyTuple_GetItem(offset,0);
          if (! temp) {
               error = "Failed to get x offset from tuple";
               goto exit;
          }
          xoff = PyInt_AsLong(temp);
          if (PyErr_Occurred()) {
               error = "Offset X is not an integer";
               goto exit;
          }
          temp = PyTuple_GetItem(offset,1);
          if (! temp) {
               error = "Failed to get y offset from tuple";
               goto exit;
          }
          yoff = PyInt_AsLong(temp);
          if (PyErr_Occurred()) {
               error = "Offset Y is not an integer";
               goto exit;
          }
     }
     
     dims[0] = width;
     dims[1] = height;
     output = PyArray_SimpleNew(2, dims, NPY_DOUBLE);
     if (! output) {
          error = "Failed to create output array";
          goto exit;
     }
     out_data = (double *)PyArray_DATA(output);
     memcpy(out_data,imdata,height*width*sizeof(double));

     for (j=0;j<height;j++) {
          for (i=0;i<width;i++,imdata++) {
               char *strptr = strdata;
               double value = - 1000000; /* was INFINITY but Unix doesn't like */
               if (i-xoff < 0 ||
                   j-yoff < 0 ||
                   i+strwidth-xoff >= width ||
                   j+strheight-yoff >= height) {
                    /* A corner case (literally) - check limit as we go */
                    for (l=-yoff;l<strheight-yoff;l++) {
                         double *imdata_ptr = imdata + l*width-xoff;
                         for (k=-xoff;k<strwidth-xoff;k++,imdata_ptr++) {
                              double data;
                              if (! *strptr++) continue;
                              if (i+k < 0) continue;
                              if (i+k >= width) continue;
                              if (j+l < 0) continue;
                              if (j+l >= width) continue;
                              data = *imdata_ptr;
                              if (data > value)
                                   value = data;
                         }
                    }
               } else {
                    /* Don't worry about corners and go faster */
                    for (l=-yoff;l<strheight-yoff;l++) {
                         double *imdata_ptr = imdata + l*width-xoff;
                         for (k=-xoff;k<strwidth-xoff;k++,imdata_ptr++) {
                              double data;
                              if (! *strptr++) continue;
                              data = *imdata_ptr;
                              if (data > value)
                                   value = data;
                         }
                    }
               }
               *out_data++ = value;
          }
     }
     

  exit:
     if (image) {
          Py_DECREF(image);
     }
     if (cimage) {
          Py_DECREF(cimage);
     }
     if (structure) {
          Py_DECREF(structure);
     }
     if (cstructure) {
          Py_DECREF(cstructure);
     }
     if (im_shape) {
          Py_DECREF(im_shape);
     }
     if (str_shape) {
          Py_DECREF(str_shape);
     }
     if (offset) {
          Py_DECREF(offset);
     }

     if (error) {
          if (output) {
               Py_DECREF(output);
          }
          output = PyString_FromString(error);
          if (! output) {
               Py_RETURN_NONE;
          }
     }
     return output;
}
示例#22
0
static int
PySip_init(
    PySip* self,
    PyObject* args,
    /*@unused@*/ PyObject* kwds) {

  PyObject*      py_a     = NULL;
  PyObject*      py_b     = NULL;
  PyObject*      py_ap    = NULL;
  PyObject*      py_bp    = NULL;
  PyObject*      py_crpix = NULL;
  PyArrayObject* a        = NULL;
  PyArrayObject* b        = NULL;
  PyArrayObject* ap       = NULL;
  PyArrayObject* bp       = NULL;
  PyArrayObject* crpix    = NULL;
  double*        a_data   = NULL;
  double*        b_data   = NULL;
  double*        ap_data  = NULL;
  double*        bp_data  = NULL;
  unsigned int   a_order  = 0;
  unsigned int   b_order  = 0;
  unsigned int   ap_order = 0;
  unsigned int   bp_order = 0;
  int            status   = -1;

  if (!PyArg_ParseTuple(args, "OOOOO:Sip.__init__",
                        &py_a, &py_b, &py_ap, &py_bp, &py_crpix)) {
    return -1;
  }

  if (convert_matrix(py_a, &a, &a_data, &a_order) ||
      convert_matrix(py_b, &b, &b_data, &b_order) ||
      convert_matrix(py_ap, &ap, &ap_data, &ap_order) ||
      convert_matrix(py_bp, &bp, &bp_data, &bp_order)) {
    goto exit;
  }

  crpix = (PyArrayObject*)PyArray_ContiguousFromAny(py_crpix, PyArray_DOUBLE,
                                                    1, 1);
  if (crpix == NULL) {
    goto exit;
  }

  if (PyArray_DIM(crpix, 0) != 2) {
    PyErr_SetString(PyExc_ValueError, "CRPIX wrong length");
    goto exit;
  }

  status = sip_init(&self->x,
                    a_order, a_data,
                    b_order, b_data,
                    ap_order, ap_data,
                    bp_order, bp_data,
                    PyArray_DATA(crpix));

 exit:
  Py_XDECREF(a);
  Py_XDECREF(b);
  Py_XDECREF(ap);
  Py_XDECREF(bp);
  Py_XDECREF(crpix);

  if (status == 0) {
    return 0;
  } else if (status == -1) {
    /* Exception already set */
    return -1;
  } else {
    wcserr_to_python_exc(self->x.err);
    return -1;
  }
}
示例#23
0
DimensionDictionary::DimensionDictionary(PyObject * dim_dict)
{
  // Check that dim_dict is a dictionary
  if (!PyDict_Check(dim_dict))
  {
    PyErr_SetString(PyExc_TypeError,
                    "'dim_dict' element is not a dictionary");
    throw PythonException();
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "dim_dict = " << PyString_AsString(PyObject_Str(dim_dict))
            << std::endl;
#endif

  ////////////////////////////////
  // Get the 'dist_type' attribute
  ////////////////////////////////
  PyObject * distTypeObj = PyDict_GetItemString(dim_dict, "dist_type");
  if (distTypeObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' has no 'dist_type' key");
    throw PythonException();
  }
  if (!PyString_Check(distTypeObj))
  {
    PyErr_SetString(PyExc_TypeError,
                    "'dist_type' is not a string");
    throw PythonException();
  }
  char * distTypeStr = PyString_AsString(distTypeObj);
  if (strcmp(distTypeStr, "b") == 0)
    dist_type = BLOCK;
  else if (strcmp(distTypeStr, "c") == 0)
    dist_type = CYCLIC;
  else if (strcmp(distTypeStr, "u") == 0)
    dist_type = UNSTRUCTURED;
  else
  {
    PyErr_Format(PyExc_ValueError,
                 "'dist_type' value '%s' is unrecognized",
                 distTypeStr);
    throw PythonException();
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  dist_type = '" << distTypeStr << "'" << std::endl;
#endif

  ///////////////////////////
  // Get the 'size' attribute
  ///////////////////////////
  PyObject * sizeObj = PyDict_GetItemString(dim_dict, "size");
  if (sizeObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' required key 'size' not present");
    throw PythonException();
  }
  if (!PyInt_Check(sizeObj))
  {
    PyErr_Format(PyExc_TypeError, "'size' is not an int");
    throw PythonException();
  }
  size = PyInt_AsLong(sizeObj);
  if (size < 0)
  {
    PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'size' = %d is less "
                 "than zero", size);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  size = " << size << std::endl;
#endif

  /////////////////////////////////////
  // Get the 'proc_grid_size' attribute
  /////////////////////////////////////
  PyObject * commDimObj = PyDict_GetItemString(dim_dict, "proc_grid_size");
  if (commDimObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' required key 'proc_grid_size' not present");
    throw PythonException();
  }
  if (!PyInt_Check(commDimObj))
  {
    PyErr_Format(PyExc_TypeError,
                 "'proc_grid_size' is not an int");
    throw PythonException();
  }
  proc_grid_size = PyInt_AsLong(commDimObj);
  if (proc_grid_size < 1)
  {
    PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'proc_grid_size' = "
                 "%d is less than one", proc_grid_size);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  proc_grid_size = " << proc_grid_size << std::endl;
#endif

  /////////////////////////////////////
  // Get the 'proc_grid_rank' attribute
  /////////////////////////////////////
  PyObject * commRankObj = PyDict_GetItemString(dim_dict, "proc_grid_rank");
  if (commRankObj == NULL)
  {
    PyErr_SetString(PyExc_KeyError,
                    "'dim_dict' required key 'proc_grid_rank' not present");
    throw PythonException();
  }
  if (!PyInt_Check(commRankObj))
  {
    PyErr_Format(PyExc_TypeError,
                 "'proc_grid_rank' is not an int");
    throw PythonException();
  }
  proc_grid_rank = PyInt_AsLong(commRankObj);
  if ((proc_grid_rank < 0) || (proc_grid_rank >= proc_grid_size))
  {
    PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'proc_grid_rank' = "
                 "%d is out of range [0, %d)", proc_grid_rank, proc_grid_size);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  proc_grid_rank = " << proc_grid_rank << std::endl;
#endif

  ////////////////////////////
  // Get the 'start' attribute
  ////////////////////////////
  PyObject * startObj = PyDict_GetItemString(dim_dict, "start");
  if (startObj == NULL)
  {
    if ((dist_type == BLOCK) || (dist_type == CYCLIC))
    {
      PyErr_SetString(PyExc_KeyError,
                      "'dim_dict' is of type BLOCK or CYCLIC but has no "
                      "'start' key");
      throw PythonException();
    }
    else
    {
      start = -1;
    }
  }
  else
  {
    if (!PyInt_Check(startObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'start' is not an int");
      throw PythonException();
    }
    start = PyInt_AsLong(startObj);
    if ((start < 0) || (start > size))
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'start' = "
                   "%d is out of range [0, %d]", start, size);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  start = " << start << std::endl;
#endif

  ///////////////////////////
  // Get the 'stop' attribute
  ///////////////////////////
  PyObject * stopObj = PyDict_GetItemString(dim_dict, "stop");
  if (stopObj == NULL)
  {
    if (dist_type == BLOCK)
    {
      PyErr_SetString(PyExc_KeyError,
                      "'dim_dict' is of type BLOCK but has no 'stop' key");
      throw PythonException();
    }
    else
    {
      stop = -1;
    }
  }
  else
  {
    if (!PyInt_Check(stopObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'stop' for axis %d is not an int");
      throw PythonException();
    }
    stop = PyInt_AsLong(stopObj);
    if ((stop < 0) || (stop > size))
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'stop' = "
                   "%d is out of range [0, %d]", stop, size);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  stop = " << stop << std::endl;
#endif

  /////////////////////////////////
  // Get the 'block_size' attribute
  /////////////////////////////////
  PyObject * blockSizeObj = PyDict_GetItemString(dim_dict, "block_size");
  if (blockSizeObj == NULL)
  {
    block_size = 1;
  }
  else
  {
    if (!PyInt_Check(blockSizeObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'block_size' is not an int");
      throw PythonException();
    }
    block_size = PyInt_AsLong(stopObj);
    if (block_size < 1)
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'block_size' = "
                   "%d is less than one", block_size);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  block_size = " << block_size << std::endl;
#endif

  //////////////////////////////
  // Get the 'padding' attribute
  //////////////////////////////
  PyObject * paddingObj = PyDict_GetItemString(dim_dict, "padding");
  if (paddingObj == NULL)
  {
    padding[0] = 0;
    padding[1] = 0;
  }
  else
  {
    if (!PySequence_Check(paddingObj))
    {
      PyErr_SetString(PyExc_ValueError, "'padding' attribute must be a "
                      "sequence of two integers");
      throw PythonException();
    }
    if (PySequence_Size(paddingObj) != 2)
    {
      PyErr_SetString(PyExc_ValueError, "'padding' attribute must be a "
                      "sequence of two integers");
      throw PythonException();
    }
    PyObject * padObj = PySequence_GetItem(padObj, 0);
    if (!PyInt_Check(padObj))
    {
      PyErr_SetString(PyExc_TypeError, "Lower 'padding' object is not an "
                      "integer");
      throw PythonException();
    }
    padding[0] = PyInt_AsLong(padObj);
    if (padding[0] < 0)
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'padding'[0] = "
                   "%d is less than zero", padding[0]);
    }
    padObj = PySequence_GetItem(padObj, 1);
    if (!PyInt_Check(padObj))
    {
      PyErr_SetString(PyExc_TypeError, "Upper 'padding' object is not an "
                      "integer");
      throw PythonException();
    }
    padding[1] = PyInt_AsLong(padObj);
    if (padding[1] < 0)
    {
      PyErr_Format(PyExc_ValueError, "'dim_dict' attribute 'padding'[1] = "
                   "%d is less than zero", padding[1]);
    }
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  padding = " << padding << std::endl;
#endif

  ///////////////////////////////
  // Get the 'periodic' attribute
  ///////////////////////////////
  PyObject * periodicObj = PyDict_GetItemString(dim_dict, "periodic");
  if (periodicObj == NULL)
  {
    periodic = false;
  }
  else
  {
    if (!PyBool_Check(periodicObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'periodic' is not a bool");
      throw PythonException();
    }
    if (periodicObj == Py_True) periodic = true;
    else                        periodic = false;
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  periodic = " << (periodic ? "true" : "false") << std::endl;
#endif

  /////////////////////////////////
  // Get the 'one_to_one' attribute
  /////////////////////////////////
  PyObject * oneToOneObj = PyDict_GetItemString(dim_dict, "one_to_one");
  if (oneToOneObj == NULL)
  {
    one_to_one = false;
  }
  else
  {
    if (!PyBool_Check(oneToOneObj))
    {
      PyErr_SetString(PyExc_TypeError,
                      "'one_to_one' is not a bool");
      throw PythonException();
    }
    if (oneToOneObj == Py_True) one_to_one = true;
    else                        one_to_one = false;
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  one_to_one = " << (one_to_one ? "true" : "false")
            << std::endl;
#endif

  //////////////////////////////
  // Get the 'indices' attribute
  //////////////////////////////
  PyObject * indicesObj = PyDict_GetItemString(dim_dict, "indices");
  if (indicesObj == NULL)
  {
    if (dist_type == UNSTRUCTURED)
    {
      PyErr_SetString(PyExc_KeyError, "'dim_dict' with type UNSTRUCTURED "
                      "requires 'indices' key");
      throw PythonException();
    }
  }
  else
  {
    PyObject * indicesArray =
      PyArray_ContiguousFromAny(indicesObj, NPY_INT, 1, 1);
    if (indicesArray == NULL)
    {
      PyErr_SetString(PyExc_ValueError, "'dim_dict' attribute 'indices' "
                      "specified illegally");
      throw PythonException();
    }
    npy_intp numIndices = PyArray_Size(indicesArray);
    indices.resize(numIndices);
    int * source = (int*) PyArray_DATA((PyArrayObject*)indicesArray);
    for (IndicesType::size_type i = 0; i < numIndices; ++i)
      indices[i] = *(source++);
    Py_DECREF(indicesArray);
  }
#ifdef PYTRILINOS_DAP_VERBOSE
  std::cout << "  indices = " << indices() << std::endl;
#endif
}
示例#24
0
/*
 * arr_bincount is registered as bincount.
 *
 * bincount accepts one, two or three arguments. The first is an array of
 * non-negative integers The second, if present, is an array of weights,
 * which must be promotable to double. Call these arguments list and
 * weight. Both must be one-dimensional with len(weight) == len(list). If
 * weight is not present then bincount(list)[i] is the number of occurrences
 * of i in list.  If weight is present then bincount(self,list, weight)[i]
 * is the sum of all weight[j] where list [j] == i.  Self is not used.
 * The third argument, if present, is a minimum length desired for the
 * output array.
 */
NPY_NO_EXPORT PyObject *
arr_bincount(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds)
{
    PyArray_Descr *type;
    PyObject *list = NULL, *weight=Py_None, *mlength=Py_None;
    PyArrayObject *lst=NULL, *ans=NULL, *wts=NULL;
    npy_intp *numbers, *ians, len , mx, mn, ans_size, minlength;
    npy_intp i;
    double *weights , *dans;
    static char *kwlist[] = {"list", "weights", "minlength", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO",
                kwlist, &list, &weight, &mlength)) {
            goto fail;
    }

    lst = (PyArrayObject *)PyArray_ContiguousFromAny(list, NPY_INTP, 1, 1);
    if (lst == NULL) {
        goto fail;
    }
    len = PyArray_SIZE(lst);
    type = PyArray_DescrFromType(NPY_INTP);

    if (mlength == Py_None) {
        minlength = 0;
    }
    else {
        minlength = PyArray_PyIntAsIntp(mlength);
        if (minlength <= 0) {
            if (!PyErr_Occurred()) {
                PyErr_SetString(PyExc_ValueError,
                                "minlength must be positive");
            }
            goto fail;
        }
    }

    /* handle empty list */
    if (len == 0) {
        if (!(ans = (PyArrayObject *)PyArray_Zeros(1, &minlength, type, 0))){
            goto fail;
        }
        Py_DECREF(lst);
        return (PyObject *)ans;
    }

    numbers = (npy_intp *) PyArray_DATA(lst);
    minmax(numbers, len, &mn, &mx);
    if (mn < 0) {
        PyErr_SetString(PyExc_ValueError,
                "The first argument of bincount must be non-negative");
        goto fail;
    }
    ans_size = mx + 1;
    if (mlength != Py_None) {
        if (ans_size < minlength) {
            ans_size = minlength;
        }
    }
    if (weight == Py_None) {
        ans = (PyArrayObject *)PyArray_Zeros(1, &ans_size, type, 0);
        if (ans == NULL) {
            goto fail;
        }
        ians = (npy_intp *)(PyArray_DATA(ans));
        NPY_BEGIN_ALLOW_THREADS;
        for (i = 0; i < len; i++)
            ians[numbers[i]] += 1;
        NPY_END_ALLOW_THREADS;
        Py_DECREF(lst);
    }
    else {
        wts = (PyArrayObject *)PyArray_ContiguousFromAny(
                                                weight, NPY_DOUBLE, 1, 1);
        if (wts == NULL) {
            goto fail;
        }
        weights = (double *)PyArray_DATA (wts);
        if (PyArray_SIZE(wts) != len) {
            PyErr_SetString(PyExc_ValueError,
                    "The weights and list don't have the same length.");
            goto fail;
        }
        type = PyArray_DescrFromType(NPY_DOUBLE);
        ans = (PyArrayObject *)PyArray_Zeros(1, &ans_size, type, 0);
        if (ans == NULL) {
            goto fail;
        }
        dans = (double *)PyArray_DATA(ans);
        NPY_BEGIN_ALLOW_THREADS;
        for (i = 0; i < len; i++) {
            dans[numbers[i]] += weights[i];
        }
        NPY_END_ALLOW_THREADS;
        Py_DECREF(lst);
        Py_DECREF(wts);
    }
    return (PyObject *)ans;

fail:
    Py_XDECREF(lst);
    Py_XDECREF(wts);
    Py_XDECREF(ans);
    return NULL;
}
示例#25
0
NPY_NO_EXPORT PyObject *
arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
{

    PyObject *fp, *xp, *x;
    PyObject *left = NULL, *right = NULL;
    PyArrayObject *afp = NULL, *axp = NULL, *ax = NULL, *af = NULL;
    npy_intp i, lenx, lenxp;
    npy_double lval, rval;
    const npy_double *dy, *dx, *dz;
    npy_double *dres, *slopes = NULL;

    static char *kwlist[] = {"x", "xp", "fp", "left", "right", NULL};

    NPY_BEGIN_THREADS_DEF;

    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OO", kwlist,
                                     &x, &xp, &fp, &left, &right)) {
        return NULL;
    }

    afp = (PyArrayObject *)PyArray_ContiguousFromAny(fp, NPY_DOUBLE, 1, 1);
    if (afp == NULL) {
        return NULL;
    }
    axp = (PyArrayObject *)PyArray_ContiguousFromAny(xp, NPY_DOUBLE, 1, 1);
    if (axp == NULL) {
        goto fail;
    }
    ax = (PyArrayObject *)PyArray_ContiguousFromAny(x, NPY_DOUBLE, 1, 0);
    if (ax == NULL) {
        goto fail;
    }
    lenxp = PyArray_SIZE(axp);
    if (lenxp == 0) {
        PyErr_SetString(PyExc_ValueError,
                "array of sample points is empty");
        goto fail;
    }
    if (PyArray_SIZE(afp) != lenxp) {
        PyErr_SetString(PyExc_ValueError,
                "fp and xp are not of the same length.");
        goto fail;
    }

    af = (PyArrayObject *)PyArray_SimpleNew(PyArray_NDIM(ax),
                                            PyArray_DIMS(ax), NPY_DOUBLE);
    if (af == NULL) {
        goto fail;
    }
    lenx = PyArray_SIZE(ax);

    dy = (const npy_double *)PyArray_DATA(afp);
    dx = (const npy_double *)PyArray_DATA(axp);
    dz = (const npy_double *)PyArray_DATA(ax);
    dres = (npy_double *)PyArray_DATA(af);
    /* Get left and right fill values. */
    if ((left == NULL) || (left == Py_None)) {
        lval = dy[0];
    }
    else {
        lval = PyFloat_AsDouble(left);
        if ((lval == -1) && PyErr_Occurred()) {
            goto fail;
        }
    }
    if ((right == NULL) || (right == Py_None)) {
        rval = dy[lenxp - 1];
    }
    else {
        rval = PyFloat_AsDouble(right);
        if ((rval == -1) && PyErr_Occurred()) {
            goto fail;
        }
    }

    /* binary_search_with_guess needs at least a 3 item long array */
    if (lenxp == 1) {
        const npy_double xp_val = dx[0];
        const npy_double fp_val = dy[0];

        NPY_BEGIN_THREADS_THRESHOLDED(lenx);
        for (i = 0; i < lenx; ++i) {
            const npy_double x_val = dz[i];
            dres[i] = (x_val < xp_val) ? lval :
                                         ((x_val > xp_val) ? rval : fp_val);
        }
        NPY_END_THREADS;
    }
    else {
        npy_intp j = 0;

        /* only pre-calculate slopes if there are relatively few of them. */
        if (lenxp <= lenx) {
            slopes = PyArray_malloc((lenxp - 1) * sizeof(npy_double));
            if (slopes == NULL) {
                goto fail;
            }
        }

        NPY_BEGIN_THREADS;

        if (slopes != NULL) {
            for (i = 0; i < lenxp - 1; ++i) {
                slopes[i] = (dy[i+1] - dy[i]) / (dx[i+1] - dx[i]);
            }
        }

        for (i = 0; i < lenx; ++i) {
            const npy_double x_val = dz[i];

            if (npy_isnan(x_val)) {
                dres[i] = x_val;
                continue;
            }

            j = binary_search_with_guess(x_val, dx, lenxp, j);
            if (j == -1) {
                dres[i] = lval;
            }
            else if (j == lenxp) {
                dres[i] = rval;
            }
            else if (j == lenxp - 1) {
                dres[i] = dy[j];
            }
            else {
                const npy_double slope = (slopes != NULL) ? slopes[j] :
                                         (dy[j+1] - dy[j]) / (dx[j+1] - dx[j]);
                dres[i] = slope*(x_val - dx[j]) + dy[j];
            }
        }

        NPY_END_THREADS;
    }

    PyArray_free(slopes);
    Py_DECREF(afp);
    Py_DECREF(axp);
    Py_DECREF(ax);
    return (PyObject *)af;

fail:
    Py_XDECREF(afp);
    Py_XDECREF(axp);
    Py_XDECREF(ax);
    Py_XDECREF(af);
    return NULL;
}
示例#26
0
文件: astropy_wcs.c 项目: phn/astropy
/*@null@*/ static PyObject*
Wcs_all_pix2world(
    Wcs* self,
    PyObject* args,
    PyObject* kwds) {

    int            naxis      = 2;
    PyObject*      pixcrd_obj = NULL;
    int            origin     = 1;
    PyArrayObject* pixcrd     = NULL;
    PyArrayObject* world      = NULL;
    int            status     = -1;
    const char*    keywords[] = {
        "pixcrd", "origin", NULL
    };

    if (!PyArg_ParseTupleAndKeywords(
                args, kwds, "Oi:all_pix2world", (char **)keywords,
                &pixcrd_obj, &origin)) {
        return NULL;
    }

    naxis = self->x.wcs->naxis;

    pixcrd = (PyArrayObject*)PyArray_ContiguousFromAny(pixcrd_obj, PyArray_DOUBLE, 2, 2);
    if (pixcrd == NULL) {
        return NULL;
    }

    if (PyArray_DIM(pixcrd, 1) < naxis) {
        PyErr_Format(
            PyExc_RuntimeError,
            "Input array must be 2-dimensional, where the second dimension >= %d",
            naxis);
        goto exit;
    }

    world = (PyArrayObject*)PyArray_SimpleNew(2, PyArray_DIMS(pixcrd), PyArray_DOUBLE);
    if (world == NULL) {
        goto exit;
    }

    /* Make the call */
    Py_BEGIN_ALLOW_THREADS
    preoffset_array(pixcrd, origin);
    wcsprm_python2c(self->x.wcs);
    status = pipeline_all_pixel2world(&self->x,
                                      (unsigned int)PyArray_DIM(pixcrd, 0),
                                      (unsigned int)PyArray_DIM(pixcrd, 1),
                                      (double*)PyArray_DATA(pixcrd),
                                      (double*)PyArray_DATA(world));
    wcsprm_c2python(self->x.wcs);
    unoffset_array(pixcrd, origin);
    Py_END_ALLOW_THREADS
    /* unoffset_array(world, origin); */

exit:
    Py_XDECREF(pixcrd);

    if (status == 0 || status == 8) {
        return (PyObject*)world;
    } else if (status == -1) {
        PyErr_SetString(
            PyExc_ValueError,
            "Wrong number of dimensions in input array.  Expected 2.");
        return NULL;
    } else {
        Py_DECREF(world);
        if (status == -1) {
            /* exception already set */
            return NULL;
        } else {
            wcserr_to_python_exc(self->x.err);
            return NULL;
        }
    }
}
示例#27
0
文件: astropy_wcs.c 项目: phn/astropy
/*@null@*/ static PyObject*
Wcs_det2im(
    Wcs* self,
    PyObject* args,
    PyObject* kwds) {

    PyObject*      detcrd_obj = NULL;
    int            origin     = 1;
    PyArrayObject* detcrd     = NULL;
    PyArrayObject* imcrd     = NULL;
    int            status     = -1;
    const char*    keywords[] = {
        "detcrd", "origin", NULL
    };

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oi:det2im", (char **)keywords,
                                     &detcrd_obj, &origin)) {
        return NULL;
    }

    if (self->x.det2im[0] == NULL && self->x.det2im[1] == NULL) {
        Py_INCREF(detcrd_obj);
        return detcrd_obj;
    }

    detcrd = (PyArrayObject*)PyArray_ContiguousFromAny(detcrd_obj, PyArray_DOUBLE, 2, 2);
    if (detcrd == NULL) {
        return NULL;
    }

    if (PyArray_DIM(detcrd, 1) != NAXES) {
        PyErr_SetString(PyExc_ValueError, "Pixel array must be an Nx2 array");
        goto exit;
    }

    imcrd = (PyArrayObject*)PyArray_SimpleNew(2, PyArray_DIMS(detcrd), PyArray_DOUBLE);
    if (imcrd == NULL) {
        status = 2;
        goto exit;
    }

    Py_BEGIN_ALLOW_THREADS
    preoffset_array(detcrd, origin);
    status = p4_pix2foc(2, (void *)self->x.det2im,
                        (unsigned int)PyArray_DIM(detcrd, 0),
                        (double*)PyArray_DATA(detcrd),
                        (double*)PyArray_DATA(imcrd));
    unoffset_array(detcrd, origin);
    unoffset_array(imcrd, origin);
    Py_END_ALLOW_THREADS

exit:

    Py_XDECREF(detcrd);

    if (status == 0) {
        return (PyObject*)imcrd;
    } else {
        Py_XDECREF(imcrd);
        if (status == -1) {
            /* Exception already set */
            return NULL;
        } else {
            PyErr_SetString(PyExc_MemoryError, "NULL pointer passed");
            return NULL;
        }
    }
}
示例#28
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;
}
示例#29
0
static PyObject *
  PyACME_apply_weights(PyObject *self,PyObject *args)
{
  PyObject *row_obj,*col_obj,*S_obj,*fracb_obj,*data_obj;
  PyArrayObject *row=NULL,*col=NULL,*S=NULL,*fracb=NULL,*dest_field=NULL,*data=NULL;
  double *S_vals,*fracb_vals;
  int *row_vals,*col_vals;
  char type;
  void *data_vals;
  double *out;

  if (!PyArg_ParseTuple(args,"OOOOO",&data_obj,&S_obj,&row_obj,&col_obj,&fracb_obj))
    return NULL;

    S =(PyArrayObject *) PyArray_ContiguousFromAny(S_obj,NPY_FLOAT64,1,1);
    col =(PyArrayObject *) PyArray_ContiguousFromAny(col_obj,NPY_INT32,1,1);
    row =(PyArrayObject *) PyArray_ContiguousFromAny(row_obj,NPY_INT32,1,1);
    data =(PyArrayObject *) PyArray_ContiguousFromAny(data_obj,NPY_NOTYPE,1,0);
    fracb =(PyArrayObject *) PyArray_ContiguousFromAny(fracb_obj,NPY_FLOAT64,1,1);

    type = data->descr->type;
    int nindep=1;
    int i,j;
    for (i=0;i<data->nd-1;i++) {
      nindep*=data->dimensions[i];
    }
    /* Construct dest array */
    int n1 = data->dimensions[data->nd-1];
    int n2 = fracb->dimensions[0];
    npy_intp newdims[2];
    newdims[0]=nindep;
    newdims[1] = n2;
    out=malloc(newdims[0]*newdims[1]*sizeof(double));
    #pragma omp parallel for
    for (j=0;j<newdims[0]*newdims[1];j++) {
      out[j]=0;
    }

    dest_field = PyArray_SimpleNew(2,newdims,NPY_DOUBLE);

    S_vals = (double *)S->data;
    row_vals = (int *) row->data;
    col_vals = (int *) col->data;
    data_vals = (void *) data->data;
    fracb_vals = (double *) fracb->data;
    #pragma omp parallel for private(j)
    for (i=0;i<nindep;i++) {
      if (type=='d') {
        for (j=0;j<S->dimensions[0];j++) {
          out[i*n2+row_vals[j]] = out[i*n2+row_vals[j]] + S_vals[j]*((double *)data_vals)[i*n1+col_vals[j]];
        }
      }
      else if (type=='f') {
        for (j=0;j<S->dimensions[0];j++) {
          out[i*n2+row_vals[j]] = out[i*n2+row_vals[j]] + S_vals[j]*((float *)data_vals)[i*n1+col_vals[j]];
        }
      }
      else if (type=='i') {
        for (j=0;j<S->dimensions[0];j++) {
          out[i*n2+row_vals[j]] = out[i*n2+row_vals[j]] + S_vals[j]*((int *)data_vals)[i*n1+col_vals[j]];
        }
      }
      else if (type=='l') {
        for (j=0;j<S->dimensions[0];j++) {
          out[i*n2+row_vals[j]] = out[i*n2+row_vals[j]] + S_vals[j]*((long *)data_vals)[i*n1+col_vals[j]];
        }
      }
      else {
        fprintf(stderr,"unsupported type: %c\n" , type);
      }
      for (j=0;j<n2;j++) {
        if (fracb_vals[j]>0.) out[i*n2+j]=out[i*n2+j]/fracb_vals[j];
      }
    }
    dest_field->data=out;
  return Py_BuildValue("N",dest_field);
}
示例#30
0
文件: astropy_wcs.c 项目: phn/astropy
/*@null@*/ static PyObject*
Wcs_pix2foc(
    Wcs* self,
    PyObject* args,
    PyObject* kwds) {

    PyObject*      pixcrd_obj = NULL;
    int            origin     = 1;
    PyArrayObject* pixcrd     = NULL;
    PyArrayObject* foccrd     = NULL;
    int            status     = -1;
    const char*    keywords[] = {
        "pixcrd", "origin", NULL
    };

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oi:pix2foc", (char **)keywords,
                                     &pixcrd_obj, &origin)) {
        return NULL;
    }

    pixcrd = (PyArrayObject*)PyArray_ContiguousFromAny(pixcrd_obj, PyArray_DOUBLE, 2, 2);
    if (pixcrd == NULL) {
        return NULL;
    }

    if (PyArray_DIM(pixcrd, 1) != NAXES) {
        PyErr_SetString(PyExc_ValueError, "Pixel array must be an Nx2 array");
        goto _exit;
    }

    foccrd = (PyArrayObject*)PyArray_SimpleNew(2, PyArray_DIMS(pixcrd), PyArray_DOUBLE);
    if (foccrd == NULL) {
        goto _exit;
    }

    Py_BEGIN_ALLOW_THREADS
    preoffset_array(pixcrd, origin);
    status = pipeline_pix2foc(&self->x,
                              (unsigned int)PyArray_DIM(pixcrd, 0),
                              (unsigned int)PyArray_DIM(pixcrd, 1),
                              (double*)PyArray_DATA(pixcrd),
                              (double*)PyArray_DATA(foccrd));
    unoffset_array(pixcrd, origin);
    unoffset_array(foccrd, origin);
    Py_END_ALLOW_THREADS

_exit:

    Py_XDECREF(pixcrd);

    if (status == 0) {
        return (PyObject*)foccrd;
    } else {
        Py_XDECREF(foccrd);
        if (status == -1) {
            /* Exception already set */
            return NULL;
        } else {
            wcserr_to_python_exc(self->x.err);
            return NULL;
        }
    }
}