コード例 #1
0
ファイル: akima.c プロジェクト: metocean/tcrm
static PyObject *
py_interpolate(
    PyObject *obj,
    PyObject *args,
    PyObject *kwds)
{
    PyArrayObject *xdata = NULL;
    PyArrayObject *data = NULL;
    PyArrayObject *xout = NULL;
    PyArrayObject *out = NULL;
    PyArrayObject *oout = NULL;
    PyArrayIterObject *dit = NULL;
    PyArrayIterObject *oit = NULL;
    npy_intp dstride, ostride, xdstride, xostride, size, outsize;
    Py_ssize_t newshape[NPY_MAXDIMS];
    int axis = NPY_MAXDIMS;
    int i, ndim, error;
    double *buffer = NULL;

    static char *kwlist[] = {"x", "y", "x_new", "axis", "out", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&O&|O&O&", kwlist,
                                     PyConverter_AnyDoubleArray, &xdata,
                                     PyConverter_AnyDoubleArray, &data,
                                     PyConverter_AnyDoubleArray, &xout,
                                     PyArray_AxisConverter, &axis,
                                     PyOutputConverter_AnyDoubleArrayOrNone, &oout))
        goto _fail;

    /* check axis */
    ndim = PyArray_NDIM(data);
    if ((axis == NPY_MAXDIMS) || (axis == -1)) {
        axis = ndim - 1;
    } else if ((axis < 0) || (axis > NPY_MAXDIMS)) {
        PyErr_Format(PyExc_ValueError, "invalid axis");
        goto _fail;
    }

    if ((PyArray_NDIM(xdata) != 1) || (PyArray_NDIM(xout) != 1)) {
        PyErr_Format(PyExc_ValueError,
                     "x-arrays must be one dimensional");
        goto _fail;
    }

    size = PyArray_DIM(data, axis);
    outsize = PyArray_DIM(xout, 0);

    if (size < 3) {
        PyErr_Format(PyExc_ValueError, "size along axis is too small");
        goto _fail;
    }

    if (size != PyArray_DIM(xdata, 0)) {
        PyErr_Format(PyExc_ValueError,
                     "size of x-array must match data shape at axis");
        goto _fail;
    }

    for (i = 0; i < ndim; i++) {
        newshape[i] = (i == axis) ? outsize : PyArray_DIM(data, i);
    }

    if (oout == NULL) {
        /* create a new output array */
        out = (PyArrayObject*)PyArray_SimpleNew(ndim, newshape, NPY_DOUBLE);
        if (out == NULL) {
            PyErr_Format(PyExc_ValueError, "failed to allocate output array");
            goto _fail;
        }
    } else if (ndim != PyArray_NDIM(oout)) {
        PyErr_Format(PyExc_ValueError,
                     "output and data array dimension mismatch");
        goto _fail;
    } else {
        for (i = 0; i < ndim; i++) {
            if (newshape[i] != PyArray_DIM(oout, i)) {
                PyErr_Format(PyExc_ValueError, "wrong output shape");
                goto _fail;
            }
        }
        out = oout;
    }

    /* iterate over all but specified axis */
    dit = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)data, &axis);
    oit = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)out, &axis);
    dstride = PyArray_STRIDE(data, axis);
    ostride = PyArray_STRIDE(out, axis);
    xdstride = PyArray_STRIDE(xdata, 0);
    xostride = PyArray_STRIDE(xout, 0);

    buffer = (double *)PyMem_Malloc((size * 4 + 4) * sizeof(double));
    if (buffer == NULL) {
        PyErr_Format(PyExc_ValueError, "failed to allocate output buffer");
        goto _fail;
    }

    while (dit->index < dit->size) {
        error = interpolate(
                    size,
                    PyArray_DATA(xdata), xdstride,
                    dit->dataptr, dstride,
                    outsize,
                    PyArray_DATA(xout), xostride,
                    oit->dataptr, ostride,
                    buffer);

        if (error != 0) {
            PyErr_Format(PyExc_ValueError, "interpolate() failed");
            goto _fail;
        }

        PyArray_ITER_NEXT(oit);
        PyArray_ITER_NEXT(dit);
    }

    PyMem_Free(buffer);
    Py_DECREF(oit);
    Py_DECREF(dit);
    Py_DECREF(data);
    Py_DECREF(xout);
    Py_DECREF(xdata);

    /* Return output vector if not provided as argument */
    if (oout == NULL) {
        return PyArray_Return(out);
    } else {
        Py_INCREF(Py_None);
        return Py_None;
    }

_fail:
    Py_XDECREF(xdata);
    Py_XDECREF(xout);
    Py_XDECREF(data);
    Py_XDECREF(oit);
    Py_XDECREF(dit);
    if (buffer != NULL)
        PyMem_Free(buffer);
    if (oout == NULL)
        Py_XDECREF(out);
    else
        Py_XDECREF(oout);
    return NULL;
}
コード例 #2
0
ファイル: calcGrid.c プロジェクト: boywert/SussexBigRun2013
PyObject* _calcGrid(PyObject *self, PyObject *args) {
	PyArrayObject *pos, *hsml, *mass, *rho, *value, *pyGrid;
	int npart, nx, ny, nz, cells;
	int dims[3];
	double bx, by, bz, cx, cy, cz;
	double *data_pos, *data_hsml, *data_mass, *data_rho, *data_value;
	double *grid;
	int part;
	double px, py, pz, h, h2, m, r, v, cpx, cpy, cpz, r2;
	int x, y, z0, z1;
	int xmin, xmax, ymin, ymax, zmin, zmax, zmid;
	double cellsizex, cellsizey, cellsizez;
	time_t start;
	
	start = clock();

	if (!PyArg_ParseTuple( args, "O!O!O!O!O!iiidddddd:calcGrid( pos, hsml, mass, rho, value, nx, ny, nz, boxx, boxy, boxz, centerx, centery, centerz )", &PyArray_Type, &pos, &PyArray_Type, &hsml, &PyArray_Type, &mass, &PyArray_Type, &rho, &PyArray_Type, &value, &nx, &ny, &nz, &bx, &by, &bz, &cx, &cy, &cz )) {
		return 0;
	}

	if (pos->nd != 2 || pos->dimensions[1] != 3 || pos->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "pos has to be of dimensions [n,3] and type double" );
		return 0;
	}

	if (hsml->nd != 1 || hsml->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "hsml has to be of dimension [n] and type double" );
		return 0;
	}

	if (mass->nd != 1 || mass->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "mass has to be of dimension [n] and type double" );
		return 0;
	}

	if (rho->nd != 1 || rho->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "rho has to be of dimension [n] and type double" );
		return 0;
	}

	if (value->nd != 1 || value->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "value has to be of dimension [n] and type double" );
		return 0;
	}

	npart = pos->dimensions[0];
	if (npart != hsml->dimensions[0] || npart != mass->dimensions[0]  || npart != rho->dimensions[0] || npart != value->dimensions[0]) {
		PyErr_SetString( PyExc_ValueError, "pos, hsml, rho and value have to have the same size in the first dimension" );
		return 0;
	}

	dims[0] = nx;
	dims[1] = ny;
	dims[2] = nz;
	pyGrid = (PyArrayObject *)PyArray_FromDims( 3, dims, PyArray_DOUBLE );
	grid = (double*)pyGrid->data;
	cells = nx*ny*nz;
	memset( grid, 0, cells*sizeof(double) );

	cellsizex = bx / nx;
	cellsizey = by / ny;
	cellsizez = bz / nz;

	data_pos = (double*)pos->data;
	data_hsml = (double*)hsml->data;
	data_mass = (double*)mass->data;
	data_rho = (double*)rho->data;
	data_value = (double*)value->data;

	for (part=0; part<npart; part++) {
		px = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		py = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		pz = *data_pos;
		data_pos = (double*)((char*)data_pos - 2*pos->strides[1] + pos->strides[0]);
		
		h = *data_hsml;
		data_hsml = (double*)((char*)data_hsml + hsml->strides[0]);
		h2 = h*h;

		m = *data_mass;
		data_mass = (double*)((char*)data_mass + mass->strides[0]);

		r = *data_rho;
		data_rho = (double*)((char*)data_rho + rho->strides[0]);

		v = *data_value;
		data_value = (double*)((char*)data_value + value->strides[0]);

		xmin = max( floor( (px - h - cx + 0.5*bx) / cellsizex ), 0 );
		xmax = min( ceil( (px + h - cx + 0.5*bx) / cellsizex ), nx-1 );
		ymin = max( floor( (py - h - cy + 0.5*by) / cellsizey ), 0 );
		ymax = min( ceil( (py + h - cy + 0.5*by) / cellsizey ), ny-1 );
		zmin = max( floor( (pz - h - cz + 0.5*bz) / cellsizez ), 0 );
		zmax = min( ceil( (pz + h - cz + 0.5*bz) / cellsizez ), nz-1 );

		zmid = floor( 0.5 * (zmin+zmax) + 0.5 );

		if (xmin < nx && ymin < ny && xmax >= 0 && ymax >= 0 && zmin < nz && zmax >= 0) {
			for (x=xmin; x<=xmax; x++) {
				cpx = -0.5*bx + bx*(x+0.5)/nx;
				for (y=ymin; y<=ymax; y++) {
					cpy = -0.5*by + by*(y+0.5)/ny;
					for (z0=zmid; z0>=zmin; z0--) {
						cpz = -0.5*bz + bz*(z0+0.5)/nz;
						r2 = ( sqr(px-cpx-cx) + sqr(py-cpy-cy) + sqr(pz-cpz-cz) );
						if (r2 > h2) break;
						grid[(x*ny + y)*nz + z0] += _getkernel( h, r2 ) * m * v / r;
					}

					for (z1=zmid+1; z1<=zmax; z1++) {
						cpz = -0.5*bz + bz*(z1+0.5)/nz;
						r2 = ( sqr(px-cpx-cx) + sqr(py-cpy-cy) + sqr(pz-cpz-cz) );
						if (r2 > h2) break;
						grid[(x*ny + y)*nz + z1] += _getkernel( h, r2 ) * m * v / r;
					}
				}
			}	
		}
	}

	printf( "Calculation took %gs\n", ((double)clock()-(double)start)/CLOCKS_PER_SEC );
	return PyArray_Return( pyGrid );
}
コード例 #3
0
ファイル: calcGrid.c プロジェクト: boywert/SussexBigRun2013
PyObject* _calcRadialProfile(PyObject *self, PyObject *args) {
	PyArrayObject *pos, *data, *pyProfile;
	int npart, nshells, mode;
	int dims[2];
	int *count;
	double cx, cy, cz, dr;
	double *data_pos, *data_data;
	double *profile;
	int part, shell;
	double px, py, pz, d, rr, v;
	time_t start;
	
	start = clock();

	mode = 1;
	nshells = 200;
	dr = 0;
	cx = cy = cz = 0;
	if (!PyArg_ParseTuple( args, "O!O!|iidddd:calcRadialProfile( pos, data, mode, nshells, dr, centerx, centery, centerz )", &PyArray_Type, &pos, &PyArray_Type, &data, &mode, &nshells, &dr, &cx, &cy, &cz )) {
		return 0;
	}

	if (pos->nd != 2 || pos->dimensions[1] != 3 || pos->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "pos has to be of dimensions [n,3] and type double" );
		return 0;
	}

	if (data->nd != 1 || data->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "data has to be of dimension [n] and type double" );
		return 0;
	}

	npart = pos->dimensions[0];
	if (npart != data->dimensions[0]) {
		PyErr_SetString( PyExc_ValueError, "pos and data have to have the same size in the first dimension" );
		return 0;
	}
	dims[0] = 2;
	dims[1] = nshells;
	pyProfile = (PyArrayObject *)PyArray_FromDims( 2, dims, PyArray_DOUBLE );
	profile = (double*)pyProfile->data;
	memset( profile, 0, 2*nshells*sizeof(double) );

	count = (int*)malloc( nshells*sizeof(int) );
	memset( count, 0, nshells*sizeof(int) );

	if (!dr) {
		data_pos = (double*)pos->data;
		for (part=0; part<npart; part++) {
			px = *data_pos;
			data_pos = (double*)((char*)data_pos + pos->strides[1]);
			py = *data_pos;
			data_pos = (double*)((char*)data_pos + pos->strides[1]);
			pz = *data_pos;
			data_pos = (double*)((char*)data_pos - 2*pos->strides[1] + pos->strides[0]);

			rr = sqrt( sqr(px-cx) + sqr(py-cy) + sqr(pz-cz) );
			if (rr > dr)
				dr = rr;
		}
		dr /= nshells;
		printf( "dr set to %g\n", dr );
	}

	data_pos = (double*)pos->data;
	data_data = (double*)data->data;

	for (part=0; part<npart; part++) {
		px = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		py = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		pz = *data_pos;
		data_pos = (double*)((char*)data_pos - 2*pos->strides[1] + pos->strides[0]);

		d = *data_data;
		data_data = (double*)((char*)data_data + data->strides[0]);

		rr = sqrt( sqr(px-cx) + sqr(py-cy) + sqr(pz-cz) );
		shell = floor( rr / dr );

		if (shell < nshells) {
			profile[ shell ] += d;
			count[ shell ] += 1;
		}
	}

	for (shell=0; shell<nshells; shell++) {
		profile[ nshells + shell ] = dr * (shell + 0.5);
	}

	switch (mode) {
		// sum
		case 0:
			break;
		// density
		case 1:
			for (shell=0; shell<nshells; shell++) {
				v = 4.0 / 3.0 * M_PI * dr*dr*dr * ( ((double)shell+1.)*((double)shell+1.)*((double)shell+1.) - (double)shell*(double)shell*(double)shell );
				profile[shell] /= v;
			}
			break;
		// average
		case 2:
			for (shell=0; shell<nshells; shell++) if (count[shell] > 0) profile[shell] /= count[shell];
			break;
	}

	free( count );

	printf( "Calculation took %gs\n", ((double)clock()-(double)start)/CLOCKS_PER_SEC );
	return PyArray_Return( pyProfile );
}
コード例 #4
0
// =============================================================================
PyObject * Epetra_NumPyMultiVector::ExtractView() const
{
  Py_INCREF(array);
  return PyArray_Return(array);
}
コード例 #5
0
ファイル: _rayleigh.c プロジェクト: tloredo/inference
static PyObject *
rsgrid (PyObject *self, PyObject *args) {
    PyObject *input;
    PyArrayObject *data, *P, *wvals;
    int ndat, nw, i, j, Pdims[1];
    double *times, *Pdata, *wdata;
    double *sd, *cd1, *swt, *cwt;
    double w_l, w_u, dw, dwt, wt, w, temp;
    double S, C;

/** Initialize objects to NULL that we may have to XDECREF if a constructor
 ** fails so that XDECREF has an argument to work with.  Strictly, this
 ** isn't needed for every object. */
    data = NULL;
    P = NULL;
    wvals = NULL;
    sd = NULL;
    cd1 = NULL;
    swt = NULL;
    cwt = NULL;

/** Parse the args; make the data array contiguous. */
    Py_TRY(PyArg_ParseTuple(args, "iddO", &nw, &w_l, &w_u, &input));
    data = (PyArrayObject *)
            PyArray_ContiguousFromObject(input, PyArray_DOUBLE, 1, 1);
    if (data == NULL) goto FAIL;

/** Store the # of data; make vector references to event times. */
    ndat = data->dimensions[0];
    times = DDATA(data);

/** Make space for the trig. */
	sd = (double *) malloc(ndat*sizeof(double));
	cd1 = (double *) malloc(ndat*sizeof(double));
	swt = (double *) malloc(ndat*sizeof(double));
	cwt = (double *) malloc(ndat*sizeof(double));

/** Setup for the trig recurrences we'll use in the frequency loop. */
	dw = (w_u - w_l) / (nw-1);
    for (j=0; j<ndat; j++) {
        dwt = dw * *(times+j);
	    sd[j] = sin(dwt);
	    cd1[j] = sin(0.5*dwt);
	    cd1[j] = -2.*cd1[j]*cd1[j];
	    wt = w_l * *(times+j);
	    swt[j] = sin(wt);
	    cwt[j] = cos(wt);
	}

/** Loop over frequencies. */
	Pdims[0] = nw;
    P = (PyArrayObject *)PyArray_FromDims(1, Pdims, PyArray_DOUBLE);
    if (P == NULL) goto FAIL;
    Pdata = DDATA(P);
    wvals = (PyArrayObject *)PyArray_FromDims(1, Pdims, PyArray_DOUBLE);
    if (wvals == NULL) goto FAIL;
    wdata = DDATA(wvals);
    w = w_l;
	for (i=0; i<nw; i++) {
	    wdata[i] = w;
	    w += dw;
		S = C = 0.;
		
		/* Loop over data to calculate the Rayleigh power;
		   also, use some trig to prepare for the next frequency. */
        for (j=0; j<ndat; j++) {
            S = S + swt[j];
            C = C + cwt[j];

		    temp = cwt[j];
		    cwt[j] = cwt[j] + (cwt[j]*cd1[j] - swt[j]*sd[j]);
		    swt[j] = swt[j] + (swt[j]*cd1[j] + temp*sd[j]);
        }
        Pdata[i] = (S*S + C*C)/ndat;
	}

/** Clean up and return everything in a tuple. */
    Py_DECREF(data);
    free(sd);
    free(cd1);
    free(swt);
    free(cwt);
    return Py_BuildValue("NN", PyArray_Return(wvals), PyArray_Return(P));

/** Misbehavior ends up here! */
FAIL:
    Py_XDECREF(data);
    Py_XDECREF(P);
    Py_XDECREF(wvals);
    if (sd != NULL) free(sd);
    if (cd1 != NULL) free(cd1);
    if (swt != NULL) free(swt);
    if (cwt != NULL) free(cwt);
    return NULL;
}
コード例 #6
0
ファイル: compiled_base.c プロジェクト: aniryou/numpy
/* ravel_multi_index implementation - see add_newdocs.py */
NPY_NO_EXPORT PyObject *
arr_ravel_multi_index(PyObject *self, PyObject *args, PyObject *kwds)
{
    int i, s;
    PyObject *mode0=NULL, *coords0=NULL;
    PyArrayObject *ret = NULL;
    PyArray_Dims dimensions={0,0};
    npy_intp ravel_strides[NPY_MAXDIMS];
    NPY_ORDER order = NPY_CORDER;
    NPY_CLIPMODE modes[NPY_MAXDIMS];

    PyArrayObject *op[NPY_MAXARGS];
    PyArray_Descr *dtype[NPY_MAXARGS];
    npy_uint32 op_flags[NPY_MAXARGS];

    NpyIter *iter = NULL;

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

    memset(op, 0, sizeof(op));
    dtype[0] = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                        "OO&|OO&:ravel_multi_index", kwlist,
                     &coords0,
                     PyArray_IntpConverter, &dimensions,
                     &mode0,
                     PyArray_OrderConverter, &order)) {
        goto fail;
    }

    if (dimensions.len+1 > NPY_MAXARGS) {
        PyErr_SetString(PyExc_ValueError,
                    "too many dimensions passed to ravel_multi_index");
        goto fail;
    }

    if (!PyArray_ConvertClipmodeSequence(mode0, modes, dimensions.len)) {
       goto fail;
    }

    switch (order) {
        case NPY_CORDER:
            s = 1;
            for (i = dimensions.len-1; i >= 0; --i) {
                ravel_strides[i] = s;
                s *= dimensions.ptr[i];
            }
            break;
        case NPY_FORTRANORDER:
            s = 1;
            for (i = 0; i < dimensions.len; ++i) {
                ravel_strides[i] = s;
                s *= dimensions.ptr[i];
            }
            break;
        default:
            PyErr_SetString(PyExc_ValueError,
                            "only 'C' or 'F' order is permitted");
            goto fail;
    }

    /* Get the multi_index into op */
    if (sequence_to_arrays(coords0, op, dimensions.len, "multi_index") < 0) {
        goto fail;
    }


    for (i = 0; i < dimensions.len; ++i) {
        op_flags[i] = NPY_ITER_READONLY|
                      NPY_ITER_ALIGNED;
    }
    op_flags[dimensions.len] = NPY_ITER_WRITEONLY|
                               NPY_ITER_ALIGNED|
                               NPY_ITER_ALLOCATE;
    dtype[0] = PyArray_DescrFromType(NPY_INTP);
    for (i = 1; i <= dimensions.len; ++i) {
        dtype[i] = dtype[0];
    }

    iter = NpyIter_MultiNew(dimensions.len+1, op, NPY_ITER_BUFFERED|
                                                  NPY_ITER_EXTERNAL_LOOP|
                                                  NPY_ITER_ZEROSIZE_OK,
                                                  NPY_KEEPORDER,
                                                  NPY_SAME_KIND_CASTING,
                                                  op_flags, dtype);
    if (iter == NULL) {
        goto fail;
    }

    if (NpyIter_GetIterSize(iter) != 0) {
        NpyIter_IterNextFunc *iternext;
        char **dataptr;
        npy_intp *strides;
        npy_intp *countptr;

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

        do {
            if (ravel_multi_index_loop(dimensions.len, dimensions.ptr,
                        ravel_strides, *countptr, modes,
                        dataptr, strides) != NPY_SUCCEED) {
                goto fail;
            }
        } while(iternext(iter));
    }

    ret = NpyIter_GetOperandArray(iter)[dimensions.len];
    Py_INCREF(ret);

    Py_DECREF(dtype[0]);
    for (i = 0; i < dimensions.len; ++i) {
        Py_XDECREF(op[i]);
    }
    PyDimMem_FREE(dimensions.ptr);
    NpyIter_Deallocate(iter);
    return PyArray_Return(ret);

fail:
    Py_XDECREF(dtype[0]);
    for (i = 0; i < dimensions.len; ++i) {
        Py_XDECREF(op[i]);
    }
    PyDimMem_FREE(dimensions.ptr);
    NpyIter_Deallocate(iter);
    return NULL;
}
コード例 #7
0
ファイル: _nonlinear_ld.c プロジェクト: mindriot101/batman
static PyObject *_nonlinear_ld(PyObject *self, PyObject *args)
{
	double rprs, d, fac, A_i, x, I; 
	int nthreads;
	npy_intp i, dims[1];
	double dx, A_f, x_in, x_out, delta, c1, c2, c3, c4;
	
	PyArrayObject *ds, *flux;
  	if(!PyArg_ParseTuple(args,"Oddddddi", &ds, &rprs, &c1, &c2, &c3, &c4, &fac, &nthreads)) return NULL;

	dims[0] = PyArray_DIMS(ds)[0]; 
	flux = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_TYPE(ds));	//creates numpy array to store return flux values

	double *f_array = PyArray_DATA(flux);
	double *d_array = PyArray_DATA(ds);

	/*
		NOTE:  the safest way to access numpy arrays is to use the PyArray_GETITEM and PyArray_SETITEM functions.
		Here we use a trick for faster access and more convenient access, where we set a pointer to the 
		beginning of the array with the PyArray_DATA (e.g., f_array) and access elements with e.g., f_array[i].
		Success of this operation depends on the numpy array storing data in blocks equal in size to a C double.
		If you run into trouble along these lines, I recommend changing the array access to something like:
			d = PyFloat_AsDouble(PyArray_GETITEM(ds, PyArray_GetPtr(ds, &i))); 
		where ds is a numpy array object.


		Laura Kreidberg 07/2015
	*/
	
	#if defined (_OPENMP)
	omp_set_num_threads(nthreads);	//specifies number of threads (if OpenMP is supported)
	#endif

	double norm = (-c1/10. - c2/6. - 3.*c3/14. - c4/4. + 0.5)*2.*M_PI; 	//normalization for intensity profile (faster to calculate it once, rather than every time intensity is called)		

	#if defined (_OPENMP)
	#pragma omp parallel for private(d, x_in, x_out, delta, x, dx, A_i, A_f, I)
	#endif
	for(i = 0; i < dims[0]; i++)
	{
		d = d_array[i];
		x_in = MAX(d - rprs, 0.);					//lower bound for integration
		x_out = MIN(d + rprs, 1.0);					//upper bound for integration

		if(x_in >= 1.) f_array[i] = 1.0;				//flux = 1. if the planet is not transiting
		else
		{
			delta = 0.;						//variable to store the integrated intensity, \int I dA
			x = x_in;						//starting radius for integration
			dx = fac*acos(x); 					//initial step size 

			x += dx;						//first step

			A_i = 0.;						//initial area
	
			while(x < x_out)
			{
				A_f = area(d, x, rprs);				//calculates area of overlapping circles
				I = intensity(x - dx/2.,c1,c2, c3, c4, norm); 	//intensity at the midpoint
				delta += (A_f - A_i)*I;				//increase in transit depth for this integration step
				dx = fac*acos(x);  				//updating step size
				x = x + dx;					//stepping to next element
				A_i = A_f;					//storing area
			}
			dx = x_out - x + dx;  					//calculating change in radius for last step  FIXME
			x = x_out;						//final radius for integration
			A_f = area(d, x, rprs);					//area for last integration step
			I = intensity(x - dx/2.,c1,c2, c3, c4, norm); 		//intensity at the midpoint 
			delta += (A_f - A_i)*I;					//increase in transit depth for this integration step

			f_array[i] = 1.0 - delta;	//flux equals 1 - \int I dA 
		}
	}
	return PyArray_Return((PyArrayObject *)flux);

} 
コード例 #8
0
static PyObject * blobproperties (PyObject *self, 
				  PyObject *args,  
				  PyObject *keywds)
{
   PyArrayObject *dataarray=NULL,*blobarray=NULL; /* in (not modified) */

   PyArrayObject *results=NULL;
   static char *kwlist[] = {
     "data",
     "blob",
     "npeaks",
     "omega",
     "verbose", 
     NULL};
   double *res;
   double fval;
   double omega=0;
   
   int np=0,verbose=0,type,f,s,peak,bad;

   int i,j, percent;
   npy_intp safelyneed[3];
   
   if(!PyArg_ParseTupleAndKeywords(args,keywds, "O!O!i|di",kwlist,      
				   &PyArray_Type, 
				   &dataarray,   /* array args - data */
				   &PyArray_Type, 
				   &blobarray,   /* blobs */
				   &np,  /* Number of peaks to treat */	   
				   &omega, /* omega angle - put 0 if unknown */
				   &verbose))     /* optional verbosity */
      return NULL;

   if(verbose)printf("omega = %f",omega);

   /* Check array is two dimensional */
   if(dataarray->nd != 2){     
     PyErr_SetString(PyExc_ValueError,
		     "data array must be 2d, first arg problem");
     return NULL;
   } 
   if(verbose!=0)printf("Welcome to blobproperties\n");
   /* Check array is two dimensional and int - 
      results from connectedpixels above */
   if(blobarray->nd != 2 && blobarray->descr->type_num != PyArray_INT){     
     PyErr_SetString(PyExc_ValueError,
		     "Blob array must be 2d and integer, second arg problem");
     return NULL;
   }

   type=dataarray->descr->type_num;
   /* Decide on fast/slow loop - inner versus outer */
   if(blobarray->strides[0] > blobarray->strides[1]) {
     f=1;  s=0;}
   else {
     f=0;  s=1;
   }
      
   if (verbose!=0){
     printf("Fast index is %d, slow index is %d, ",f,s);
     printf("strides[0]=%d, strides[1]=%d\n",
	    dataarray->strides[0],
	    dataarray->strides[1]);
   }
   /* results arrays */
   safelyneed[0]=np;
   safelyneed[1]=NPROPERTY;

   results = (PyArrayObject *) PyArray_SimpleNew(2, 
						safelyneed, 
						PyArray_DOUBLE);

   if( results == NULL){
     PyErr_SetString(PyExc_ValueError,
		     "Malloc failed fo results");
     return NULL;
   }
   Py_BEGIN_ALLOW_THREADS

   if(verbose>0)printf("malloc'ed the results\n");

   res = (double*)results->data;

   /* Initialise the results */
   for ( i=0 ; i<safelyneed[0] ; i++) {
     for ( j=0 ; j<NPROPERTY; j++){
           res[i*NPROPERTY+j]=0.;
        } 
     /* Set min to max +1 and vice versa */
     res[i*NPROPERTY+bb_mn_f]=blobarray->dimensions[f]+1;
     res[i*NPROPERTY+bb_mn_s]=blobarray->dimensions[s]+1;
     res[i*NPROPERTY+bb_mx_f]=-1;
     res[i*NPROPERTY+bb_mx_s]=-1;
     /* All pixels have the same omega in this frame */
     res[i*NPROPERTY+bb_mx_o]=omega;
     res[i*NPROPERTY+bb_mn_o]=omega;
   }
      
   if(verbose!=0)printf("Got some space to put the results in\n");

   percent=(blobarray->dimensions[s]-1)/80.0;
   if(percent < 1)percent=1;
   bad = 0;
   if(verbose!=0)printf("Scanning image\n");

   /* i,j is looping along the indices data array */
   for( i = 0 ; i <= (blobarray->dimensions[s]-1) ; i++ ){  
     if(verbose!=0 && (i%percent == 0) )printf(".");
     for( j = 0 ; j <= (blobarray->dimensions[f]-1) ; j++ ){

       peak =  *(int *) getptr(blobarray,f,s,i,j);
       
       if( peak > 0  && peak <=np ) {
	    fval = getval(getptr(dataarray,f,s,i,j),type);
	    /* printf("i,j,f,s,fval,peak %d %d %d %d %f %d\n",i,j,f,s,fval,peak); */
	    add_pixel( &res[NPROPERTY*(peak-1)] ,i , j ,fval , omega);
       }
       else{
	 if(peak!=0){
	   bad++;
	   if(verbose!=0 && bad<10){
	     printf("Found %d in your blob image at i=%d, j=%d\n",peak,i,j);}
	   /* Only complain 10 times - otherwise piles of crap go to screen */
	 }
       }
     } /* j */
   } /* i */
   if(verbose){
     printf("\nFound %d bad pixels in the blob image\n",bad);
   }
  Py_END_ALLOW_THREADS

   return Py_BuildValue("O", PyArray_Return(results) ); 
}
コード例 #9
0
PyObject* radonShiftCorrelate(PyObject *self, PyObject *args) {
/*
** Inputs:
** 	(1) 2D numpy array of first Radon transform (using doubles)
** 	(2) 2D numpy array of second Radon transform (using doubles)
** 	(3) interger of search radius (in pixels)
** Modifies:
** 	nothing
** Outputs:
** 	1D numpy array containing correlation values of angle (y-axis) and shift (x-axis)
*/
	Py_Initialize();

	/* Simple test loop */
	/*struct item *headtwo = NULL;
	int rad;
	for(rad=0; rad<8; rad++) {
		struct item *headtwo = NULL;
		headtwo = getAnglesList(rad, headtwo);
		fprintf(stderr, "radius %d, num angles %d\n", rad, list_length(headtwo));
		//if (rad < 3) print_list(headtwo);
		delete_list(headtwo);
	}
	fprintf(stderr, "Finish test radii\n");*/
	/* End simple test loop */	

	/* Parse tuples separately since args will differ between C fcns */
	int radius;
	PyArrayObject *radonone, *radontwo;
	//fprintf(stderr, "Start variable read\n");
	if (!PyArg_ParseTuple(args, "OOi", &radonone, &radontwo, &radius))
		return NULL;
	if (radonone == NULL) return NULL;
	if (radontwo == NULL) return NULL;

	/* Create list of angles to check, number of angles is based on radius */
	struct item *head = NULL;
	head = getAnglesList(radius, head);
	int numangles = list_length(head);
	//fprintf(stderr, "Finish get angles, radius %d, num angles %d\n", radius, list_length(head));

	/* dimensions error checking */
	if (radonone->dimensions[0] != radontwo->dimensions[0] 
		|| radonone->dimensions[1] != radontwo->dimensions[1]) {
		fprintf(stderr, "\n%s: Radon arrays are of different dimensions (%d,%d) vs. (%d,%d)\n\n",
			__FILE__,
			radonone->dimensions[0], radonone->dimensions[1],
			radontwo->dimensions[0], radontwo->dimensions[1]);
		return NULL;
	}

	/* Get the dimensions of the input */
	int numrows = radonone->dimensions[0];
	int numcols = radonone->dimensions[1];
	//fprintf(stderr, "Dimensions: %d rows by %d cols\n", numrows, numcols);
	if (2*radius > numcols) {
		fprintf(stderr, "\n%s: Shift diameter %d is larger than Radon array dimensions (%d,%d))\n\n",
			__FILE__, radius*2,
			radontwo->dimensions[0], radontwo->dimensions[1]);
		return NULL;
	}

	/*
	double test;
	test = *((double *)PyArray_GETPTR2(radonone, 0, 0));
	fprintf(stderr, "Array 1 test value at (0,0) = %.3f\n", test);
	test = *((double *)PyArray_GETPTR2(radontwo, 0, 0));
	fprintf(stderr, "Array 2 test value at (0,0) = %.3f\n", test);
	*/

	/* Determine the dimensions for the output */
	npy_intp outdims[2] = {numrows, numangles};

	/* Make a new double matrix of desired dimensions */
	//fprintf(stderr, "Creating output array of dimensions %d and %d\n", numrows, numangles);
	import_array(); // this is required to use PyArray_New() and PyArray_SimpleNew()
	PyArrayObject *output;
	//output = (PyArrayObject *) PyArray_New(&PyArray_Type, 2, outdims, NPY_DOUBLE, NULL, NULL, 0, 0, NULL);
	output = (PyArrayObject *) PyArray_SimpleNew(2, outdims, NPY_DOUBLE);
	//fprintf(stderr, "Finish create output array\n");

	/* Do the calculation. */

	int row;
	#pragma omp parallel for
	for (row=0; row<numrows; row++)  {
		struct item *current;
		int anglecol=0;
		for(current=head; current!=NULL; current=current->next) {
			/* calculation of cross correlation */
			double rawshift = radius*sin(current->angle);
			int shift;
			if (rawshift > 0) {
				shift = (int) (radius*sin(current->angle) + 0.5);
			} else {
				shift = (int) (radius*sin(current->angle) - 0.5);
			}
			//fprintf(stderr, "raw = %.3f; shift = %d\n", rawshift, shift);
			int i,j,ishift,jshift;
			double onevalue, twovalue;
			double outputsum = 0.0;
			//fprintf(stderr, "Position %d, %d\n", row, anglecol);
			for (i=0; i<numrows; i++)  {
				for (j=0; j<numcols; j++)  {
					ishift = i+row;
					if (ishift >= numrows) ishift -= numrows; // wrap overflow values
					if (ishift < 0) ishift += numrows; // wrap negative values
					jshift = j+shift;
					if (jshift >= numcols) jshift -= numcols; // wrap overflow values
					if (jshift < 0) jshift += numcols; // wrap negative values
					//fprintf(stderr, "%d, %d <-", ishift, jshift);
					onevalue = *((double *)PyArray_GETPTR2(radonone, ishift, jshift));
					//fprintf(stderr, "-> %d, %d\n", i, j);
					twovalue = *((double *)PyArray_GETPTR2(radontwo, i, j));
					outputsum += onevalue * twovalue;
			}}
			outputsum /= (numrows*numcols);
			*(double *) PyArray_GETPTR2(output, row, anglecol) = outputsum;
			/* interation variables */
			anglecol++;
	}  }

	/* clean up any memory leaks */
	delete_list(head);

	return PyArray_Return(output);
}
コード例 #10
0
ファイル: py_extension.c プロジェクト: alxio/gmmreg
static PyObject *
py_squared_distance_matrix(PyObject *self, PyObject *args)
{
    int m,n,d;
    double *dist;
    PyObject *A, *B, *g;
    PyArrayObject *arrayA, *arrayB, *arrayg;
    PyArrayObject *array_dist;
    /*
    double scale, result;
    PyObject *list;
    */
    int out_dim[2];
    /* send Python arrays to C */
    if (!PyArg_ParseTuple(args, "OOO",  &A, &B, &g))
    {
        return NULL;
    }

    /* printf("getting input success. \n"); */
    arrayA = (PyArrayObject *) PyArray_ContiguousFromObject(A, PyArray_DOUBLE, 1, 2);
    arrayB = (PyArrayObject *) PyArray_ContiguousFromObject(B, PyArray_DOUBLE, 1, 2);
    arrayg = (PyArrayObject *) PyArray_ContiguousFromObject(g, PyArray_DOUBLE, 1, 2);
    /* printf("converting success!\n"); */

    if (arrayA->nd > 2 || arrayA->descr->type_num != PyArray_DOUBLE) {
        PyErr_SetString(PyExc_ValueError,
        "array must be two-dimensional and of type float");
        return NULL;
    }
    /*printf("checking input success!\n");*/

    m = (arrayA->dimensions)[0];
    n = (arrayB->dimensions)[0];
    if (arrayA->nd>1)
        d = (arrayA->dimensions)[1];
    else
        d = 1;
    /* printf("m=%d,n=%d,d=%d\n",m,n,d); */
    dist = (double *) malloc(m*n*sizeof(double));

    /* call function */
    squared_distance_matrix((double*)(arrayA->data), (double*)(arrayB->data), (double*)(arrayg->data), m, n, d, dist);
    out_dim[0] = m;
    out_dim[1] = n;
    
    /* PyArray_FromDimsAndData() deprecated, use PyArray_SimpleNewFromData()
    http://blog.enthought.com/?p=62
    array_dist = (PyArrayObject*) PyArray_FromDimsAndData(2,out_dim,PyArray_DOUBLE, (char*)dist);
    */
    array_dist =  PyArray_SimpleNewFromData(2,out_dim,NPY_DOUBLE,dist);

    if (array_dist == NULL){
        printf("creating %dx%d array failed\n", out_dim[0],out_dim[1]);
        return NULL;
    }
    /*free(dist);*/

    /* send the result back to Python */
    Py_DECREF(arrayA);
    Py_DECREF(arrayB);
    Py_DECREF(arrayg);

    return PyArray_Return(array_dist);
    //return PyFloat_FromDouble(result);

    /*return Py_BuildValue("d", result);*/
}
コード例 #11
0
ファイル: py_extension.c プロジェクト: alxio/gmmreg
static PyObject *
py_gauss_transform(PyObject *self, PyObject *args)
{
    int m,n,dim;
    double scale, result;
    double *grad;
    PyObject *A, *B;
    PyArrayObject *arrayA, *arrayB;
    PyArrayObject *arrayGrad;
    PyObject *list;

    /* send Python arrays to C */
    if (!PyArg_ParseTuple(args, "OOd",  &A, &B, &scale))
    {
        return NULL;
    }

    /* printf("getting input success. \n"); */
    arrayA = (PyArrayObject *) PyArray_ContiguousFromObject(A, PyArray_DOUBLE, 1, 2);
    arrayB = (PyArrayObject *) PyArray_ContiguousFromObject(B, PyArray_DOUBLE, 1, 2);

    /* printf("converting success!\n"); */

    if (arrayA->nd > 2 || arrayA->descr->type_num != PyArray_DOUBLE) {
        PyErr_SetString(PyExc_ValueError,
        "array must be two-dimensional and of type float");
        return NULL;
    }
    /* printf("checking input success!\n"); */

    m = (arrayA->dimensions)[0];
    n = (arrayB->dimensions)[0];
    if (arrayA->nd>1)
        dim = (arrayA->dimensions)[1];
    else
        dim = 1;
    /* printf("m=%d,n=%d,dim=%d\n",m,n,dim); */
    grad = (double *) malloc(m*dim*sizeof(double));

    /* call function */
    result = GaussTransform((double*)(arrayA->data), (double*)(arrayB->data), m, n, dim, scale, grad);

    /* PyArray_FromDimsAndData() deprecated, use PyArray_SimpleNewFromData()
    http://blog.enthought.com/?p=62
    arrayGrad = (PyArrayObject*) PyArray_FromDimsAndData(2,arrayA->dimensions,PyArray_DOUBLE, (char*)grad);
    */
    arrayGrad = PyArray_SimpleNewFromData(2,arrayA->dimensions,NPY_DOUBLE,grad);
    if (arrayGrad == NULL){
        printf("creating %dx%d array failed\n", arrayA->dimensions[0],arrayA->dimensions[1]);
        return NULL;
    }
    /* free(grad); */

    /* send the result back to Python */
    Py_DECREF(arrayA);
    Py_DECREF(arrayB);


    //Build a list; send it back to interpreter
    list = PyList_New(0);
    // Check the API documentation for meaning of
    // return values.
    if(PyList_Append(list, PyFloat_FromDouble(result)) != 0)
    {
     // set exception context, raise (return 0)
        return 0;
    }
    if(PyList_Append(list, PyArray_Return(arrayGrad)) != 0)
    {
     // set exception context, raise (return 0)
        return 0;
    }

    return list;
    //return PyArray_Return(arrayGrad);
    //return PyFloat_FromDouble(result);

    /*return Py_BuildValue("d", result);*/
}
コード例 #12
0
ファイル: DistGeom.cpp プロジェクト: Acpharis/rdkit
  PyObject *embedBoundsMatrix(python::object boundsMatArg,int maxIters=10,
                              bool randomizeOnFailure=false,int numZeroFail=2,
                              python::list weights=python::list(),
                              int randomSeed=-1){
    PyObject *boundsMatObj = boundsMatArg.ptr();
    if(!PyArray_Check(boundsMatObj))
      throw_value_error("Argument isn't an array");
    
    PyArrayObject *boundsMat=reinterpret_cast<PyArrayObject *>(boundsMatObj);
    // get the dimensions of the array
    unsigned int nrows = boundsMat->dimensions[0];
    unsigned int ncols = boundsMat->dimensions[1];
    if(nrows!=ncols)
      throw_value_error("The array has to be square");
    if(nrows<=0)
      throw_value_error("The array has to have a nonzero size");
    if (boundsMat->descr->type_num != PyArray_DOUBLE)
      throw_value_error("Only double arrays are currently supported");

    unsigned int dSize = nrows*nrows;
    double *cData = new double[dSize];
    double *inData = reinterpret_cast<double *>(boundsMat->data);
    memcpy(static_cast<void *>(cData), 
           static_cast<const void *>(inData),
           dSize*sizeof(double));

    DistGeom::BoundsMatrix::DATA_SPTR sdata(cData);
    DistGeom::BoundsMatrix bm(nrows,sdata);

    RDGeom::Point3D *positions=new RDGeom::Point3D[nrows];
    std::vector<RDGeom::Point *> posPtrs;
    for (unsigned int i = 0; i < nrows; i++) {
      posPtrs.push_back(&positions[i]);
    }

    RDNumeric::DoubleSymmMatrix distMat(nrows, 0.0);

    // ---- ---- ---- ---- ---- ---- ---- ---- ---- 
    // start the embedding:
    bool gotCoords=false;
    for(int iter=0;iter<maxIters && !gotCoords;iter++){
      // pick a random distance matrix
      DistGeom::pickRandomDistMat(bm,distMat,randomSeed);

      // and embed it:
      gotCoords=DistGeom::computeInitialCoords(distMat,posPtrs,randomizeOnFailure,
                                               numZeroFail,randomSeed);

      // update the seed:
      if(randomSeed>=0) randomSeed+=iter*999;
    }

    if(gotCoords){
      std::map<std::pair<int,int>,double> weightMap;
      unsigned int nElems=PySequence_Size(weights.ptr());
      for(unsigned int entryIdx=0;entryIdx<nElems;entryIdx++){
        PyObject *entry=PySequence_GetItem(weights.ptr(),entryIdx);
        if(!PySequence_Check(entry) || PySequence_Size(entry)!=3){
          throw_value_error("weights argument must be a sequence of 3-sequences");
        }
        int idx1=PyInt_AsLong(PySequence_GetItem(entry,0));
        int idx2=PyInt_AsLong(PySequence_GetItem(entry,1));
        double w=PyFloat_AsDouble(PySequence_GetItem(entry,2));
        weightMap[std::make_pair(idx1,idx2)]=w;
      }
      DistGeom::VECT_CHIRALSET csets;
      ForceFields::ForceField *field = DistGeom::constructForceField(bm,posPtrs,csets,0.0, 0.0,
                                                                     &weightMap);
      CHECK_INVARIANT(field,"could not build dgeom force field");
      field->initialize();
      if(field->calcEnergy()>1e-5){
        int needMore=1;
        while(needMore){
          needMore=field->minimize();
        }
      }
      delete field;
    } else {
      throw_value_error("could not embed matrix");
    }

    // ---- ---- ---- ---- ---- ---- ---- ---- ---- 
    // construct the results matrix:
    npy_intp dims[2];
    dims[0] = nrows;
    dims[1] = 3;
    PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2,dims,NPY_DOUBLE);
    double *resData=reinterpret_cast<double *>(res->data);
    for(unsigned int i=0;i<nrows;i++){
      unsigned int iTab=i*3;
      for (unsigned int j = 0; j < 3; ++j) {
        resData[iTab + j]=positions[i][j]; //.x;
      }
    }
    delete [] positions;

    return PyArray_Return(res);
  }
コード例 #13
0
static PyObject *cosine_sim_expand_dkeys_cpu(PyObject *self, PyObject *args){
    PyArrayObject *keys_in, *mem_in, *numpy_buffer_temp;
	float *keys, *mem, keys_sq_sum, *mem_sq_sum;
	float *comb;
	
	if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &keys_in, &PyArray_Type, &mem_in)) 
		return NULL;
    
	int n_controllers = PyArray_DIM(keys_in, 0);
	int mem_length = PyArray_DIM(keys_in, 1);
	int M = PyArray_DIM(mem_in, 0); // num mem slots
	
	keys = (float *) PyArray_DATA(keys_in);
	mem = (float *) PyArray_DATA(mem_in);
	
	/////////////////////////  output buffer
	int dims[5];
	dims[0] = n_controllers;
	dims[1] = M;
	dims[2] = n_controllers;
	dims[3] = mem_length;
	numpy_buffer_temp = (PyArrayObject *) PyArray_FromDims(4, dims, NPY_FLOAT);
	comb = (float *) PyArray_DATA(numpy_buffer_temp);
	
	//////////////////////// keys_sq_sum, mem_sq_sum
	MALLOC(mem_sq_sum, M  * sizeof(DATA_TYPE))
	memset(mem_sq_sum, 0, M * sizeof(DATA_TYPE));
	
	for(int j = 0; j < M; j++){
		for(int k = 0; k < mem_length; k++){
			mem_sq_sum[j] += MEM(j,k) * MEM(j,k);
		}
		mem_sq_sum[j] = sqrt(mem_sq_sum[j]);
	}
	
	/////////////////////////
	// mem*denom - temp (keys*numer*mem_sq_sum)
	float numer, denom;
	for(int i = 0; i < n_controllers; i++){ // [1]
		keys_sq_sum = 0;
		for(int k = 0; k < mem_length; k++){
			keys_sq_sum += KEYS(i,k) * KEYS(i,k);
		}
		keys_sq_sum = sqrt(keys_sq_sum);
		
		for(int j = 0; j < M; j++){
			denom = keys_sq_sum * mem_sq_sum[j];
			numer = 0;
			for(int k = 0; k < mem_length; k++){
				numer += KEYS(i,k) * MEM(j,k);
				COMB(i,j,i,k) = MEM(j,k) / denom;
			}
			numer /= keys_sq_sum * denom * denom / mem_sq_sum[j];
			
			for(int k = 0; k < mem_length; k++){ // [2]
				COMB(i,j,i,k) -= KEYS(i,k) * numer;
			}
		}
	}
	
	free(mem_sq_sum);
	
	return PyArray_Return(numpy_buffer_temp);
}
コード例 #14
0
ファイル: number.c プロジェクト: danielballan/numpy
static PyObject *
_array_copy_nice(PyArrayObject *self)
{
    return PyArray_Return((PyArrayObject *) PyArray_Copy(self));
}
コード例 #15
0
// =============================================================================
PyObject * Epetra_NumPyIntSerialDenseVector::Values() const
{
  Py_INCREF(array);
  return PyArray_Return(array);
}
コード例 #16
0
static PyObject* gist_extract(PyObject *self, PyObject *args)
{
	int nblocks=4;
	int n_scale=3;
	int orientations_per_scale[50]={8,8,4};
	PyArrayObject *image, *descriptor;

	if (!PyArg_ParseTuple(args, "O", &image))
	{
		return NULL;
	}

	if (PyArray_TYPE(image) != NPY_UINT8) {
		PyErr_SetString(PyExc_TypeError, "type of image must be uint8");
		return NULL;
	}

	if (PyArray_NDIM(image) != 3) {
		PyErr_SetString(PyExc_TypeError, "dimensions of image must be 3.");
		return NULL;
	}

	npy_intp *dims_image = PyArray_DIMS(image);


	const int w = (int) *(dims_image+1);
	const int h = (int) *(dims_image);

	// Read image to color_image_t structure
	color_image_t *im=color_image_new(w,h);

	for (int y=0, i=0 ; y<h ; ++y) {
		for (int x=0 ; x<w ; ++x, ++i) {
			im->c1[i] = *(unsigned char *)PyArray_GETPTR3(image, y, x, 0);
			im->c2[i] = *(unsigned char *)PyArray_GETPTR3(image, y, x, 1);
			im->c3[i] = *(unsigned char *)PyArray_GETPTR3(image, y, x, 2);
		}
	}

	// Extract descriptor
	float *desc=color_gist_scaletab(im,nblocks,n_scale,orientations_per_scale);

	int descsize=0;
	/* compute descriptor size */
	for(int i=0;i<n_scale;i++)
		descsize+=nblocks*nblocks*orientations_per_scale[i];

	descsize*=3; /* color */


	// Allocate output
	npy_intp dim_desc[1] = {descsize};
	descriptor = (PyArrayObject *) PyArray_SimpleNew(1, dim_desc, NPY_FLOAT);

	// Set val
	for (int i=0 ; i<descsize ; ++i) {
		*(float *)PyArray_GETPTR1(descriptor, i) = desc[i];
	}

	// Release memory
	color_image_delete(im);
	free(desc);

	return PyArray_Return(descriptor);
}
コード例 #17
0
ファイル: compiled_base.c プロジェクト: aniryou/numpy
/* unravel_index implementation - see add_newdocs.py */
NPY_NO_EXPORT PyObject *
arr_unravel_index(PyObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *indices0 = NULL, *ret_tuple = NULL;
    PyArrayObject *ret_arr = NULL;
    PyArrayObject *indices = NULL;
    PyArray_Descr *dtype = NULL;
    PyArray_Dims dimensions={0,0};
    NPY_ORDER order = NPY_CORDER;
    npy_intp unravel_size;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return ret_tuple;

fail:
    Py_XDECREF(ret_tuple);
    Py_XDECREF(ret_arr);
    Py_XDECREF(dtype);
    Py_XDECREF(indices);
    PyDimMem_FREE(dimensions.ptr);
    NpyIter_Deallocate(iter);
    return NULL;
}
コード例 #18
0
PyObject *getEuclideanDistMat(python::object descripMat) {
  // Bit of a pain involved here, we accept three types of PyObjects here
  // 1. A Numeric Array
  //     - first find what 'type' of entry we have (float, double and int is all
  //     we recognize for now)
  //     - then point to contiguous piece of memory from the array that contains
  //     the data with a type*
  //     - then make a new type** pointer so that double index into this
  //     contiguous memory will work
  //       and then pass it along to the distance calculator
  // 2. A list of Numeric Vector (or 1D arrays)
  //     - in this case wrap descripMat with a PySequenceHolder<type*> where
  //     type is the
  //       type of entry in vector (accepted types are int, double and float
  //     - Then pass the PySequenceHolder to the metrci calculator
  // 3. A list (or tuple) of lists (or tuple)
  //     - In this case other than wrapping descripMat with a PySequenceHolder
  //       each of the indivual list in there are also wrapped by a
  //       PySequenceHolder
  //     - so the distance calculator is passed in a
  //     "PySequenceHolder<PySequenceHolder<double>>"
  //     - FIX: not that we always convert entry values to double here, even if
  //     we passed
  //       in a list of list of ints (or floats). Given that lists can be
  //       heterogeneous, I do not
  //       know how to ask a list what type of entries if contains.
  //
  //  OK my brain is going to explode now

  // first deal with situation where we have an Numeric Array
  PyObject *descMatObj = descripMat.ptr();
  PyArrayObject *distRes;
  if (PyArray_Check(descMatObj)) {
    // get the dimensions of the array
    int nrows = ((PyArrayObject *)descMatObj)->dimensions[0];
    int ncols = ((PyArrayObject *)descMatObj)->dimensions[1];
    int i;
    CHECK_INVARIANT((nrows > 0) && (ncols > 0), "");

    npy_intp dMatLen = nrows * (nrows - 1) / 2;

    // now that we have the dimensions declare the distance matrix which is
    // always a
    // 1D double array
    distRes = (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE);

    // grab a pointer to the data in the array so that we can directly put
    // values in there
    // and avoid copying :
    double *dMat = (double *)distRes->data;

    PyArrayObject *copy;
    copy = (PyArrayObject *)PyArray_ContiguousFromObject(
        descMatObj, ((PyArrayObject *)descMatObj)->descr->type_num, 2, 2);
    // if we have double array
    if (((PyArrayObject *)descMatObj)->descr->type_num == NPY_DOUBLE) {
      double *desc = (double *)copy->data;

      // REVIEW: create an adaptor object to hold a double * and support
      //  operator[]() so that we don't have to do this stuff:

      // here is the 2D array trick this so that when the distance calaculator
      // asks for desc2D[i] we basically get the ith row as double*
      double **desc2D = new double *[nrows];
      for (i = 0; i < nrows; i++) {
        desc2D[i] = desc;
        desc += ncols;
      }
      MetricMatrixCalc<double **, double *> mmCalc;
      mmCalc.setMetricFunc(&EuclideanDistanceMetric<double *, double *>);
      mmCalc.calcMetricMatrix(desc2D, nrows, ncols, dMat);

      delete[] desc2D;
      // we got the distance matrix we are happy so return
      return PyArray_Return(distRes);
    }

    // if we have a float array
    else if (((PyArrayObject *)descMatObj)->descr->type_num == NPY_FLOAT) {
      float *desc = (float *)copy->data;
      float **desc2D = new float *[nrows];
      for (i = 0; i < nrows; i++) {
        desc2D[i] = desc;
        desc += ncols;
      }
      MetricMatrixCalc<float **, float *> mmCalc;
      mmCalc.setMetricFunc(&EuclideanDistanceMetric<float *, float *>);
      mmCalc.calcMetricMatrix(desc2D, nrows, ncols, dMat);
      delete[] desc2D;
      return PyArray_Return(distRes);
    }

    // if we have an interger array
    else if (((PyArrayObject *)descMatObj)->descr->type_num == NPY_INT) {
      int *desc = (int *)copy->data;
      int **desc2D = new int *[nrows];
      for (i = 0; i < nrows; i++) {
        desc2D[i] = desc;
        desc += ncols;
      }
      MetricMatrixCalc<int **, int *> mmCalc;
      mmCalc.setMetricFunc(&EuclideanDistanceMetric<int *, int *>);
      mmCalc.calcMetricMatrix(desc2D, nrows, ncols, dMat);
      delete[] desc2D;
      return PyArray_Return(distRes);
    } else {
      // unreconiged type for the matrix, throw up
      throw_value_error(
          "The array has to be of type int, float, or double for "
          "GetEuclideanDistMat");
    }
  }  // done with an array input
  else {
    // REVIEW: removed a ton of code here

    // we have probably have a list or a tuple

    unsigned int ncols = 0;
    unsigned int nrows =
        python::extract<unsigned int>(descripMat.attr("__len__")());
    CHECK_INVARIANT(nrows > 0, "Empty list passed in");

    npy_intp dMatLen = nrows * (nrows - 1) / 2;
    distRes = (PyArrayObject *)PyArray_SimpleNew(1, &dMatLen, NPY_DOUBLE);
    double *dMat = (double *)distRes->data;

    // assume that we a have a list of list of values (that can be extracted to
    // double)
    std::vector<PySequenceHolder<double> > dData;
    dData.reserve(nrows);
    for (unsigned int i = 0; i < nrows; i++) {
      // PySequenceHolder<double> row(seq[i]);
      PySequenceHolder<double> row(descripMat[i]);
      if (i == 0) {
        ncols = row.size();
      } else if (row.size() != ncols) {
        throw_value_error("All subsequences must be the same length");
      }
      dData.push_back(row);
    }

    MetricMatrixCalc<std::vector<PySequenceHolder<double> >,
                     PySequenceHolder<double> > mmCalc;
    mmCalc.setMetricFunc(&EuclideanDistanceMetric<PySequenceHolder<double>,
                                                  PySequenceHolder<double> >);
    mmCalc.calcMetricMatrix(dData, nrows, ncols, dMat);
  }
  return PyArray_Return(distRes);
}
コード例 #19
0
ファイル: pyipopt.c プロジェクト: drousis/pyipopt
PyObject       *
solve(PyObject * self, PyObject * args)
{
	enum ApplicationReturnStatus status;	/* Solve return code */
	int             i;
	int             n;

	/* Return values */
	problem        *temp = (problem *) self;

	IpoptProblem    nlp = (IpoptProblem) (temp->nlp);
	DispatchData   *bigfield = (DispatchData *) (temp->data);

	/* int dX[1]; */
	npy_intp        dX[1];

	PyArrayObject  *x = NULL, *mL = NULL, *mU = NULL;
	Number          obj;	/* objective value */

	PyObject       *retval = NULL;
	PyArrayObject  *x0 = NULL;

	PyObject       *myuserdata = NULL;

	Number         *newx0 = NULL;

	if (!PyArg_ParseTuple(args, "O!|O", &PyArray_Type, &x0, &myuserdata)) {
		retval = NULL;
		goto done;
	}
	if (myuserdata != NULL) {
		bigfield->userdata = myuserdata;
		/*
		 * logger("[PyIPOPT] User specified data field to callback
		 * function.\n");
		 */
	}
	if (nlp == NULL) {
		PyErr_SetString(PyExc_TypeError,
				"nlp objective passed to solve is NULL\n Problem created?\n");
		retval = NULL;
		goto done;
	}
	if (bigfield->eval_h_python == NULL) {
		AddIpoptStrOption(nlp, "hessian_approximation", "limited-memory");
		/* logger("Can't find eval_h callback function\n"); */
	}
	/* allocate space for the initial point and set the values */
	npy_intp       *dim = ((PyArrayObject *) x0)->dimensions;
	n = dim[0];
	dX[0] = n;

	x = (PyArrayObject *) PyArray_SimpleNew(1, dX, PyArray_DOUBLE);
	if (!x) {
		retval = PyErr_NoMemory();
		goto done;
	}
	newx0 = (Number *) malloc(sizeof(Number) * n);
	if (!newx0) {
		retval = PyErr_NoMemory();
		goto done;
	}
	double *xdata = (double *) x0->data;
	for (i = 0; i < n; i++)
		newx0[i] = xdata[i];

	mL = (PyArrayObject *) PyArray_SimpleNew(1, dX, PyArray_DOUBLE);
	mU = (PyArrayObject *) PyArray_SimpleNew(1, dX, PyArray_DOUBLE);


	/* For status code, see IpReturnCodes_inc.h in Ipopt */

	status = IpoptSolve(nlp, newx0, NULL, &obj, NULL, (double *) mL->data, (double *) mU->data, (UserDataPtr) bigfield);
	double* return_x_data = (double *) x->data;
	for (i = 0; i < n; i++) {
		return_x_data[i] = newx0[i];
	}
	retval = Py_BuildValue(
			       "OOOdO",
			       PyArray_Return(x),
			       PyArray_Return(mL),
			       PyArray_Return(mU),
			       obj,
			       Py_BuildValue("i", status)
	);
	goto done;

done:
	/* clean up and return */
	if (retval == NULL) {
		Py_XDECREF(x);
		Py_XDECREF(mL);
		Py_XDECREF(mU);
	}
	free(newx0);

	return retval;
}
コード例 #20
0
ファイル: vl_ikmeans.cpp プロジェクト: DerThorsten/pyvlfeat
PyObject * vl_ikmeans_python(
		PyArrayObject & inputData,
		int K,
		int max_niters,
		char * method,
		int verb)
{
	// check types
	assert(inputData.descr->type_num == PyArray_UBYTE);
	assert(inputData.flags & NPY_FORTRAN);

	npy_intp M, N;
	int err = 0;

	vl_uint8 * data;

	VlIKMFilt *ikmf;

	M = inputData.dimensions[0]; /* n of components */
	N = inputData.dimensions[1]; /* n of elements */

	// K must be a positive integer not greater than the number of data.
	assert(K>0 && K<=N);

	int method_type = VL_IKM_LLOYD;

	if (strcmp("lloyd", method) == 0) {
		method_type = VL_IKM_LLOYD;
	} else if (strcmp("elkan", method) == 0) {
		method_type = VL_IKM_ELKAN;
	} else {
		assert(0);
	}

	/* ------------------------------------------------------------------
	 *                                                         Do the job
	 * --------------------------------------------------------------- */
	if (verb) {
		char const * method_name = 0;
		switch (method_type) {
		case VL_IKM_LLOYD:
			method_name = "Lloyd";
			break;
		case VL_IKM_ELKAN:
			method_name = "Elkan";
			break;
		default:
			assert (0);
		}
		printf("ikmeans: MaxInters = %d\n", max_niters);
		printf("ikmeans: Method    = %s\n", method_name);
	}

	data = (vl_uint8*) inputData.data;
	ikmf = vl_ikm_new(method_type);

	vl_ikm_set_verbosity(ikmf, verb);
	vl_ikm_set_max_niters(ikmf, max_niters);
	vl_ikm_init_rand_data(ikmf, data, M, N, K);

	err = vl_ikm_train(ikmf, data, N);
	if (err)
		printf("ikmeans: possible overflow!");

	/* ------------------------------------------------------------------
	 *                                                       Return results
	 * --------------------------------------------------------------- */

	// allocate PyArrayObject for centers (column-majored)
	npy_intp dims[2];
	dims[0] = M;
	dims[1] = K;
	PyArrayObject * centers = (PyArrayObject*) PyArray_NewFromDescr(
		&PyArray_Type, PyArray_DescrFromType(PyArray_INT32),
		2, dims, NULL, NULL, NPY_F_CONTIGUOUS, NULL);

	// copy data
	int * centers_data = (int*) centers->data;
	memcpy(centers_data, vl_ikm_get_centers(ikmf), sizeof(vl_ikm_acc) * M * K);


	// allocate PyArrayObject for cluster assignment array
	PyArrayObject * asgn = (PyArrayObject*) PyArray_SimpleNew(
		1, (npy_intp*) &N, PyArray_UINT32);

	// copy data
	unsigned int * asgn_data = (unsigned int*) asgn->data;
	int j;
	vl_ikm_push(ikmf, (vl_uint*) asgn_data, data, N);

	// clean
	vl_ikm_delete(ikmf);

	if (verb) {
		printf("ikmeans: done\n");
	}

	// construct tuple to return both results: (regions, frames)
	PyObject * tuple = PyTuple_New(2);
	PyTuple_SetItem(tuple, 0, PyArray_Return(centers));
	PyTuple_SetItem(tuple, 1, PyArray_Return(asgn));

	return tuple;
}
コード例 #21
0
ファイル: _odepackmodule.c プロジェクト: 1641731459/scipy
static PyObject *
odepack_odeint(PyObject *dummy, PyObject *args, PyObject *kwdict)
{
    PyObject *fcn, *y0, *p_tout, *o_rtol = NULL, *o_atol = NULL;
    PyArrayObject *ap_y = NULL, *ap_yout = NULL;
    PyArrayObject *ap_rtol = NULL, *ap_atol = NULL;
    PyArrayObject *ap_tout = NULL;
    PyObject *extra_args = NULL;
    PyObject *Dfun = Py_None;
    int neq, itol = 1, itask = 1, istate = 1, iopt = 0, lrw, *iwork, liw, jt = 4;
    double *y, t, *tout, *rtol, *atol, *rwork;
    double h0 = 0.0, hmax = 0.0, hmin = 0.0;
    int ixpr = 0, mxstep = 0, mxhnil = 0, mxordn = 12, mxords = 5, ml = -1, mu = -1;
    PyObject *o_tcrit = NULL;
    PyArrayObject *ap_tcrit = NULL;
    PyArrayObject *ap_hu = NULL, *ap_tcur = NULL, *ap_tolsf = NULL, *ap_tsw = NULL;
    PyArrayObject *ap_nst = NULL, *ap_nfe = NULL, *ap_nje = NULL, *ap_nqu = NULL;
    PyArrayObject *ap_mused = NULL;
    int imxer = 0, lenrw = 0, leniw = 0, col_deriv = 0;
    npy_intp out_sz = 0, dims[2];
    int k, ntimes, crit_ind = 0;
    int allocated = 0, full_output = 0, numcrit = 0;
    double *yout, *yout_ptr, *tout_ptr, *tcrit;
    double *wa;
    static char *kwlist[] = {"fun", "y0", "t", "args", "Dfun", "col_deriv",
                             "ml", "mu", "full_output", "rtol", "atol", "tcrit",
                             "h0", "hmax", "hmin", "ixpr", "mxstep", "mxhnil",
                             "mxordn", "mxords", NULL};
    odepack_params save_params;

    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "OOO|OOiiiiOOOdddiiiii", kwlist,
                                     &fcn, &y0, &p_tout, &extra_args, &Dfun,
                                     &col_deriv, &ml, &mu, &full_output, &o_rtol, &o_atol,
                                     &o_tcrit, &h0, &hmax, &hmin, &ixpr, &mxstep, &mxhnil,
                                     &mxordn, &mxords)) {
        return NULL;
    }

    if (o_tcrit == Py_None) {
        o_tcrit = NULL;
    }
    if (o_rtol == Py_None) {
        o_rtol = NULL;
    }
    if (o_atol == Py_None) {
        o_atol = NULL;
    }

    /* Set up jt, ml, and mu */
    if (Dfun == Py_None) {
        /* set jt for internally generated */
        jt++;
    }
    if (ml < 0 && mu < 0) {
        /* neither ml nor mu given, mark jt for full jacobian */
        jt -= 3;
    }
    if (ml < 0) {
        /* if one but not both are given */
        ml = 0;
    }
    if (mu < 0) {
        mu = 0;
    }

    /* Stash the current global_params in save_params. */
    memcpy(&save_params, &global_params, sizeof(save_params));

    if (extra_args == NULL) {
        if ((extra_args = PyTuple_New(0)) == NULL) {
            goto fail;
        }
    }
    else {
        Py_INCREF(extra_args);   /* We decrement on exit. */
    }
    if (!PyTuple_Check(extra_args)) {
        PYERR(odepack_error, "Extra arguments must be in a tuple");
    }
    if (!PyCallable_Check(fcn) || (Dfun != Py_None && !PyCallable_Check(Dfun))) {
        PYERR(odepack_error, "The function and its Jacobian must be callable functions.");
    }

    /* Set global_params from the function arguments. */
    global_params.python_function = fcn;
    global_params.extra_arguments = extra_args;
    global_params.python_jacobian = Dfun;
    global_params.jac_transpose = !(col_deriv);
    global_params.jac_type = jt;

    /* Initial input vector */
    ap_y = (PyArrayObject *) PyArray_ContiguousFromObject(y0, NPY_DOUBLE, 0, 0);
    if (ap_y == NULL) {
        goto fail;
    }
    if (PyArray_NDIM(ap_y) > 1) {
        PyErr_SetString(PyExc_ValueError, "Initial condition y0 must be one-dimensional.");
        goto fail;
    }
    y = (double *) PyArray_DATA(ap_y);
    neq = PyArray_Size((PyObject *) ap_y);
    dims[1] = neq;

    /* Set of output times for integration */
    ap_tout = (PyArrayObject *) PyArray_ContiguousFromObject(p_tout, NPY_DOUBLE, 0, 0);
    if (ap_tout == NULL) {
        goto fail;
    }
    if (PyArray_NDIM(ap_tout) > 1) {
        PyErr_SetString(PyExc_ValueError, "Output times t must be one-dimensional.");
        goto fail;
    }
    tout = (double *) PyArray_DATA(ap_tout);
    ntimes = PyArray_Size((PyObject *)ap_tout);
    dims[0] = ntimes;
    t = tout[0];

    /* Setup array to hold the output evaluations*/
    ap_yout= (PyArrayObject *) PyArray_SimpleNew(2,dims,NPY_DOUBLE);
    if (ap_yout== NULL) {
        goto fail;
    }
    yout = (double *) PyArray_DATA(ap_yout);
    /* Copy initial vector into first row of output */
    memcpy(yout, y, neq*sizeof(double));  /* copy initial value to output */
    yout_ptr = yout + neq;    /* set output pointer to next position */

    itol = setup_extra_inputs(&ap_rtol, o_rtol, &ap_atol, o_atol, &ap_tcrit,
                              o_tcrit, &numcrit, neq);
    if (itol < 0 ) {
        goto fail;  /* Something didn't work */
    }
    rtol = (double *) PyArray_DATA(ap_rtol);
    atol = (double *) PyArray_DATA(ap_atol);
    if (o_tcrit != NULL) {
        tcrit = (double *)(PyArray_DATA(ap_tcrit));
    }

    /* Find size of working arrays*/
    if (compute_lrw_liw(&lrw, &liw, neq, jt, ml, mu, mxordn, mxords) < 0) {
        goto fail;
    }

    if ((wa = (double *)malloc(lrw*sizeof(double) + liw*sizeof(int)))==NULL) {
        PyErr_NoMemory();
        goto fail;
    }
    allocated = 1;
    rwork = wa;
    iwork = (int *)(wa + lrw);

    iwork[0] = ml;
    iwork[1] = mu;

    if (h0 != 0.0 || hmax != 0.0 || hmin != 0.0 || ixpr != 0 || mxstep != 0 ||
            mxhnil != 0 || mxordn != 0 || mxords != 0) {
        rwork[4] = h0;
        rwork[5] = hmax;
        rwork[6] = hmin;
        iwork[4] = ixpr;
        iwork[5] = mxstep;
        iwork[6] = mxhnil;
        iwork[7] = mxordn;
        iwork[8] = mxords;
        iopt = 1;
    }
    istate = 1;
    k = 1;

    /* If full output make some useful output arrays */
    if (full_output) {
        out_sz = ntimes-1;
        ap_hu = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_tcur = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_tolsf = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_tsw = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_DOUBLE);
        ap_nst = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_nfe = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_nje = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_nqu = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        ap_mused = (PyArrayObject *) PyArray_SimpleNew(1, &out_sz, NPY_INT);
        if (ap_hu == NULL || ap_tcur == NULL || ap_tolsf == NULL ||
                ap_tsw == NULL || ap_nst == NULL || ap_nfe == NULL ||
                ap_nje == NULL || ap_nqu == NULL || ap_mused == NULL) {
            goto fail;
        }
    }

    if (o_tcrit != NULL) {
        /* There are critical points */
        itask = 4;
        rwork[0] = *tcrit;
    }
    while (k < ntimes && istate > 0) {    /* loop over desired times */

        tout_ptr = tout + k;
        /* Use tcrit if relevant */
        if (itask == 4 && *tout_ptr > *(tcrit + crit_ind)) {
            crit_ind++;
            rwork[0] = *(tcrit+crit_ind);
        }
        if (crit_ind >= numcrit) {
            itask = 1;  /* No more critical values */
        }

        LSODA(ode_function, &neq, y, &t, tout_ptr, &itol, rtol, atol, &itask,
              &istate, &iopt, rwork, &lrw, iwork, &liw,
              ode_jacobian_function, &jt);
        if (full_output) {
            *((double *)PyArray_DATA(ap_hu) + (k-1)) = rwork[10];
            *((double *)PyArray_DATA(ap_tcur) + (k-1)) = rwork[12];
            *((double *)PyArray_DATA(ap_tolsf) + (k-1)) = rwork[13];
            *((double *)PyArray_DATA(ap_tsw) + (k-1)) = rwork[14];
            *((int *)PyArray_DATA(ap_nst) + (k-1)) = iwork[10];
            *((int *)PyArray_DATA(ap_nfe) + (k-1)) = iwork[11];
            *((int *)PyArray_DATA(ap_nje) + (k-1)) = iwork[12];
            *((int *)PyArray_DATA(ap_nqu) + (k-1)) = iwork[13];
            if (istate == -5 || istate == -4) {
                imxer = iwork[15];
            }
            else {
                imxer = -1;
            }
            lenrw = iwork[16];
            leniw = iwork[17];
            *((int *)PyArray_DATA(ap_mused) + (k-1)) = iwork[18];
        }
        if (PyErr_Occurred()) {
            goto fail;
        }
        memcpy(yout_ptr, y, neq*sizeof(double));  /* copy integration result to output*/
        yout_ptr += neq;
        k++;
    }

    /* Restore global_params from the previously stashed save_params. */
    memcpy(&global_params, &save_params, sizeof(save_params));

    Py_DECREF(extra_args);
    Py_DECREF(ap_atol);
    Py_DECREF(ap_rtol);
    Py_XDECREF(ap_tcrit);
    Py_DECREF(ap_y);
    Py_DECREF(ap_tout);
    free(wa);

    /* Do Full output */
    if (full_output) {
        return Py_BuildValue("N{s:N,s:N,s:N,s:N,s:N,s:N,s:N,s:N,s:i,s:i,s:i,s:N}i",
                    PyArray_Return(ap_yout),
                    "hu", PyArray_Return(ap_hu),
                    "tcur", PyArray_Return(ap_tcur),
                    "tolsf", PyArray_Return(ap_tolsf),
                    "tsw", PyArray_Return(ap_tsw),
                    "nst", PyArray_Return(ap_nst),
                    "nfe", PyArray_Return(ap_nfe),
                    "nje", PyArray_Return(ap_nje),
                    "nqu", PyArray_Return(ap_nqu),
                    "imxer", imxer,
                    "lenrw", lenrw,
                    "leniw", leniw,
                    "mused", PyArray_Return(ap_mused),
                    istate);
    }
    else {
        return Py_BuildValue("Ni", PyArray_Return(ap_yout), istate);
    }

fail:
    /* Restore global_params from the previously stashed save_params. */
    memcpy(&global_params, &save_params, sizeof(save_params));

    Py_XDECREF(extra_args);
    Py_XDECREF(ap_y);
    Py_XDECREF(ap_rtol);
    Py_XDECREF(ap_atol);
    Py_XDECREF(ap_tcrit);
    Py_XDECREF(ap_tout);
    Py_XDECREF(ap_yout);
    if (allocated) {
        free(wa);
    }
    if (full_output) {
        Py_XDECREF(ap_hu);
        Py_XDECREF(ap_tcur);
        Py_XDECREF(ap_tolsf);
        Py_XDECREF(ap_tsw);
        Py_XDECREF(ap_nst);
        Py_XDECREF(ap_nfe);
        Py_XDECREF(ap_nje);
        Py_XDECREF(ap_nqu);
        Py_XDECREF(ap_mused);
    }
    return NULL;
}
コード例 #22
0
static PyObject * fillDensityGrid(PyObject *self, PyObject *args){
/*
 Function to fill the density grid based using the CT grid and a conversion table
 Input:
    ctGrid : 3D numpy array representing the CT
    conversionTable :2D Array: 2 rows, n columns: row 0 : CT values, row 1 :density values 
    
 
 Output: 
    3D numpy array representing a new CT grid.
 
 */ 
 
    //Initialize pointers that will receive input data
    PyArrayObject * ctGrid = NULL; // We assume that ct Value have been previously correctly scaled.
    PyArrayObject * conversionTable = NULL; // 
 
    //Parse input args:
    if (!PyArg_ParseTuple(args, "O!O!",  
        &PyArray_Type,&ctGrid, 
        &PyArray_Type,&conversionTable))  return NULL;

    if(!ctGrid) return NULL;
    if(!conversionTable) return NULL;

    
    //Cast values to float values: numpy creates array with float values
    if (ctGrid->descr->type_num != NPY_FLOAT) ctGrid = (PyArrayObject*)PyArray_Cast(ctGrid,PyArray_FLOAT);
    if (conversionTable->descr->type_num != NPY_FLOAT) conversionTable = (PyArrayObject*)PyArray_Cast(conversionTable,PyArray_FLOAT);
    
    float  * dataDensityGrid, * dataCTGrid, * dataConversion;
    
    dataCTGrid = (float*) ctGrid -> data;  
    dataConversion = (float*) conversionTable -> data; 
   
    int nbColsConvTab = conversionTable->dimensions[1];
  
    int nbFramesCT = ctGrid->dimensions[0];
    int nbRowsCT = ctGrid->dimensions[1];
    int nbColsCT = ctGrid-> dimensions[2];
    int dimGrid[] ={nbFramesCT,nbRowsCT,nbColsCT} ;
    
    PyArrayObject * densGrid = NULL;
       // create output grid
    if(  ( densGrid = (PyArrayObject *) PyArray_FromDims(ctGrid->nd, dimGrid, PyArray_FLOAT) ) == NULL ){
        PyErr_SetString(PyExc_ValueError,"Error - malloc in fillDensityGrid - densGrid allocation failed\n");
    }
    dataDensityGrid = (float*) densGrid -> data;
    
    
    float * slope, * intercept;
    slope = (float *) malloc(sizeof(float) * (nbColsConvTab-1) );
    if(!slope) {
        PyErr_SetString(PyExc_ValueError,"Error allocation slope tab in fillDensity\n");
   
    }
    intercept = (float *) malloc(sizeof(float) * (nbColsConvTab-1) );
    if(!intercept) {
        PyErr_SetString(PyExc_ValueError,"Error allocation intercept tab in fillDensity\n");

    }
    for(int i = 0; i < nbColsConvTab-1; i++){
        slope[i] = FLT_MAX;
        intercept[i] = FLT_MAX;
    }
    
    
    float ctValue;
    float convertedValue;
    int idx;
    for(int f = 0 ; f < nbFramesCT ; f++){ // End - iterate through frames
        for(int r = 0 ; r < nbRowsCT ; r++){ // End - iterate through rows
            for(int c = 0 ; c < nbColsCT ; c++){ // End - iterate through columns
                idx = f * nbColsCT * nbRowsCT + r * nbColsCT + c;
                ctValue = dataCTGrid[ idx ];
                convertedValue = 0;
                if( ctValue <= dataConversion[0] &&  ctValue >= (dataConversion[0] - absolute(dataConversion[0]*0.1) )) {
                    convertedValue = dataConversion[1 * nbColsConvTab];
                }
                else{
                    if (  ctValue >= dataConversion[nbColsConvTab - 1] &&  ctValue <= (dataConversion[nbColsConvTab - 1] + absolute(dataConversion[nbColsConvTab - 1]*0.1)) ){
                        convertedValue = dataConversion[1 * nbColsConvTab + nbColsConvTab - 1];
                    }
                    else{
                        if( ctValue > dataConversion[0] && ctValue < dataConversion[nbColsConvTab - 1])
                        {
                            for( int i = 0 ; i < nbColsConvTab-1 ; i ++){
                                if(slope[i] == FLT_MAX){
                                        slope[i] = (dataConversion[nbColsConvTab + i]- dataConversion[nbColsConvTab + i + 1])/ ( dataConversion[i]- dataConversion[i+1]);
                                }
                                if(intercept[i] == FLT_MAX){
                                        intercept[i] = dataConversion[nbColsConvTab + i] - dataConversion[i] * slope[i];
                                }
                                if(ctValue >= dataConversion[i] && ctValue < dataConversion[i+1]){
                                    convertedValue = ctValue * slope[i] + intercept[i];
                                    break;
                                }
                                
                            }
                        }
                        else{
                            printf("Error- fill density array - ct value out of range [%f , %f]: ctValue = %f\n",dataConversion[0],dataConversion[nbColsConvTab - 1],ctValue);
                            PyErr_SetString(PyExc_ValueError,"Error ct value in fill density array...");
                                                  
                            }
                    }
                }
                
                dataDensityGrid[ idx ] = convertedValue;

        
            } // End - iterate through columns
        } // End - iterate through rows
    } // End - iterate through frames
    free(slope);
    free(intercept);
    return PyArray_Return(densGrid);
}
コード例 #23
0
ファイル: __odrpack.c プロジェクト: 7islands/scipy
/* generates Python output from the raw output from DODRC */
PyObject *gen_output(int n, int m, int np, int nq, int ldwe, int ld2we,
                     PyArrayObject * beta, PyArrayObject * work,
                     PyArrayObject * iwork, int isodr, int info,
                     int full_output)
{
  PyArrayObject *sd_beta, *cov_beta;

  int delta, eps, xplus, fn, sd, vcv, rvar, wss, wssde, wssep, rcond;
  int eta, olmav, tau, alpha, actrs, pnorm, rnors, prers, partl, sstol;
  int taufc, apsma, betao, betac, betas, betan, s, ss, ssf, qraux, u;
  int fs, fjacb, we1, diff, delts, deltn, t, tt, omega, fjacd;
  int wrk1, wrk2, wrk3, wrk4, wrk5, wrk6, wrk7, lwkmn;

  PyObject *retobj;

  npy_intp dim1[1], dim2[2];

  if (info == 50005) {
      /* fatal error in fcn call; return NULL to propogate the exception */

      return NULL;
  }

  lwkmn = work->dimensions[0];

  F_FUNC(dwinf,DWINF)(&n, &m, &np, &nq, &ldwe, &ld2we, &isodr,
        &delta, &eps, &xplus, &fn, &sd, &vcv, &rvar, &wss, &wssde,
        &wssep, &rcond, &eta, &olmav, &tau, &alpha, &actrs, &pnorm,
        &rnors, &prers, &partl, &sstol, &taufc, &apsma, &betao, &betac,
        &betas, &betan, &s, &ss, &ssf, &qraux, &u, &fs, &fjacb, &we1,
        &diff, &delts, &deltn, &t, &tt, &omega, &fjacd, &wrk1, &wrk2,
        &wrk3, &wrk4, &wrk5, &wrk6, &wrk7, &lwkmn);

  /* convert FORTRAN indices to C indices */
  delta--;
  eps--;
  xplus--;
  fn--;
  sd--;
  vcv--;
  rvar--;
  wss--;
  wssde--;
  wssep--;
  rcond--;
  eta--;
  olmav--;
  tau--;
  alpha--;
  actrs--;
  pnorm--;
  rnors--;
  prers--;
  partl--;
  sstol--;
  taufc--;
  apsma--;
  betao--;
  betac--;
  betas--;
  betan--;
  s--;
  ss--;
  ssf--;
  qraux--;
  u--;
  fs--;
  fjacb--;
  we1--;
  diff--;
  delts--;
  deltn--;
  t--;
  tt--;
  omega--;
  fjacd--;
  wrk1--;
  wrk2--;
  wrk3--;
  wrk4--;
  wrk5--;
  wrk6--;
  wrk7--;

  dim1[0] = beta->dimensions[0];
  sd_beta = (PyArrayObject *) PyArray_SimpleNew(1, dim1, NPY_DOUBLE);
  dim2[0] = beta->dimensions[0];
  dim2[1] = beta->dimensions[0];
  cov_beta = (PyArrayObject *) PyArray_SimpleNew(2, dim2, NPY_DOUBLE);

  memcpy(sd_beta->data, (void *)((double *)(work->data) + sd),
         np * sizeof(double));
  memcpy(cov_beta->data, (void *)((double *)(work->data) + vcv),
         np * np * sizeof(double));

  if (!full_output)
    {
      retobj = Py_BuildValue("OOO", PyArray_Return(beta),
                             PyArray_Return(sd_beta),
                             PyArray_Return(cov_beta));
      Py_DECREF((PyObject *) sd_beta);
      Py_DECREF((PyObject *) cov_beta);

      return retobj;
    }
  else
    {
      PyArrayObject *deltaA, *epsA, *xplusA, *fnA;
      double res_var, sum_square, sum_square_delta, sum_square_eps;
      double inv_condnum, rel_error;
      PyObject *work_ind;

      work_ind =
        Py_BuildValue
        ("{s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i,s:i}",
         "delta", delta, "eps", eps, "xplus", xplus, "fn", fn, "sd", sd, "sd",
         vcv, "rvar", rvar, "wss", wss, "wssde", wssde, "wssep", wssep,
         "rcond", rcond, "eta", eta, "olmav", olmav, "tau", tau, "alpha",
         alpha, "actrs", actrs, "pnorm", pnorm, "rnors", rnors, "prers",
         prers, "partl", partl, "sstol", sstol, "taufc", taufc, "apsma",
         apsma, "betao", betao, "betac", betac, "betas", betas, "betan",
         betan, "s", s, "ss", ss, "ssf", ssf, "qraux", qraux, "u", u, "fs",
         fs, "fjacb", fjacb, "we1", we1, "diff", diff, "delts", delts,
         "deltn", deltn, "t", t, "tt", tt, "omega", omega, "fjacd", fjacd,
         "wrk1", wrk1, "wrk2", wrk2, "wrk3", wrk3, "wrk4", wrk4, "wrk5", wrk5,
         "wrk6", wrk6, "wrk7", wrk7);

      if (m == 1)
        {
          dim1[0] = n;
          deltaA =
            (PyArrayObject *) PyArray_SimpleNew(1, dim1, NPY_DOUBLE);
          xplusA =
            (PyArrayObject *) PyArray_SimpleNew(1, dim1, NPY_DOUBLE);
        }
      else
        {
          dim2[0] = m;
          dim2[1] = n;
          deltaA =
            (PyArrayObject *) PyArray_SimpleNew(2, dim2, NPY_DOUBLE);
          xplusA =
            (PyArrayObject *) PyArray_SimpleNew(2, dim2, NPY_DOUBLE);
        }

      if (nq == 1)
        {
          dim1[0] = n;
          epsA = (PyArrayObject *) PyArray_SimpleNew(1, dim1, NPY_DOUBLE);
          fnA = (PyArrayObject *) PyArray_SimpleNew(1, dim1, NPY_DOUBLE);
        }
      else
        {
          dim2[0] = nq;
          dim2[1] = n;
          epsA = (PyArrayObject *) PyArray_SimpleNew(2, dim2, NPY_DOUBLE);
          fnA = (PyArrayObject *) PyArray_SimpleNew(2, dim2, NPY_DOUBLE);
        }

      memcpy(deltaA->data, (void *)((double *)(work->data) + delta),
             m * n * sizeof(double));
      memcpy(epsA->data, (void *)((double *)(work->data) + eps),
             nq * n * sizeof(double));
      memcpy(xplusA->data, (void *)((double *)(work->data) + xplus),
             m * n * sizeof(double));
      memcpy(fnA->data, (void *)((double *)(work->data) + fn),
             nq * n * sizeof(double));

      res_var = *((double *)(work->data) + rvar);
      sum_square = *((double *)(work->data) + wss);
      sum_square_delta = *((double *)(work->data) + wssde);
      sum_square_eps = *((double *)(work->data) + wssep);
      inv_condnum = *((double *)(work->data) + rcond);
      rel_error = *((double *)(work->data) + eta);

      retobj =
        Py_BuildValue
        ("OOO{s:O,s:O,s:O,s:O,s:d,s:d,s:d,s:d,s:d,s:d,s:O,s:O,s:O,s:i}",
         PyArray_Return(beta), PyArray_Return(sd_beta),
         PyArray_Return(cov_beta), "delta", PyArray_Return(deltaA), "eps",
         PyArray_Return(epsA), "xplus", PyArray_Return(xplusA), "y",
         PyArray_Return(fnA), "res_var", res_var, "sum_square", sum_square,
         "sum_square_delta", sum_square_delta, "sum_square_eps",
         sum_square_eps, "inv_condnum", inv_condnum, "rel_error", rel_error,
         "work", PyArray_Return(work), "work_ind", work_ind, "iwork",
         PyArray_Return(iwork), "info", info);
      Py_DECREF((PyObject *) sd_beta);
      Py_DECREF((PyObject *) cov_beta);
      Py_DECREF((PyObject *) deltaA);
      Py_DECREF((PyObject *) epsA);
      Py_DECREF((PyObject *) xplusA);
      Py_DECREF((PyObject *) fnA);
      Py_DECREF((PyObject *) work_ind);

      return retobj;
    }
}
コード例 #24
0
// =============================================================================
PyObject * Epetra_NumPyIntSerialDenseMatrix::A()
{
  Py_INCREF(array);
  return PyArray_Return(array);
}
コード例 #25
0
ファイル: hds.c プロジェクト: trmrsh/starlink-pyndf
static PyObject*
pydat_get(HDSObject *self)
{
    // Recover C-pointer passed via Python
    HDSLoc* loc = HDS_retrieve_locator(self);

    // guard against structures
    int state, status = SAI__OK;
    errBegin(&status);
    datStruc(loc, &state, &status);
    if (raiseHDSException(&status)) return NULL;
    if(state) {
        PyErr_SetString(PyExc_IOError, "dat_get error: cannot use on structures");
        return NULL;
    }

    // get type
    char typ_str[DAT__SZTYP+1];
    datType(loc, typ_str, &status);

    // get shape
    const int NDIMX=7;
    int ndim;
    hdsdim tdim[NDIMX];
    datShape(loc, NDIMX, tdim, &ndim, &status);
    if (raiseHDSException(&status)) return NULL;

    PyArrayObject* arr = NULL;

    // Either return values as a single scalar or a numpy array

    // Reverse order of dimensions
    npy_intp rdim[NDIMX];
    int i;
    for(i=0; i<ndim; i++) rdim[i] = tdim[ndim-i-1];

    if(strcmp(typ_str, "_INTEGER") == 0 || strcmp(typ_str, "_LOGICAL") == 0) {
        arr = (PyArrayObject*) PyArray_SimpleNew(ndim, rdim, NPY_INT);
    } else if(strcmp(typ_str, "_REAL") == 0) {
        arr = (PyArrayObject*) PyArray_SimpleNew(ndim, rdim, NPY_FLOAT);
    } else if(strcmp(typ_str, "_DOUBLE") == 0) {
        arr = (PyArrayObject*) PyArray_SimpleNew(ndim, rdim, NPY_DOUBLE);
    } else if(strncmp(typ_str, "_CHAR", 5) == 0) {

        // work out the number of bytes
        size_t nbytes;
        datLen(loc, &nbytes, &status);
        if (status != SAI__OK) goto fail;

        int ncdim = 1+ndim;
        int cdim[ncdim];
        cdim[0] = nbytes+1;
        for(i=0; i<ndim; i++) cdim[i+1] = rdim[i];

        PyArray_Descr *descr = PyArray_DescrNewFromType(NPY_STRING);
        descr->elsize = nbytes;
        arr = (PyArrayObject*) PyArray_NewFromDescr(&PyArray_Type, descr, ndim, rdim,
                NULL, NULL, 0, NULL);

    } else if(strcmp(typ_str, "_WORD") == 0) {
        arr = (PyArrayObject*) PyArray_SimpleNew(ndim, rdim, NPY_SHORT);
    } else if(strcmp(typ_str, "_UWORD") == 0) {
        arr = (PyArrayObject*) PyArray_SimpleNew(ndim, rdim, NPY_USHORT);
    } else if(strcmp(typ_str, "_BYTE") == 0) {
        arr = (PyArrayObject*) PyArray_SimpleNew(ndim, rdim, NPY_BYTE);
    } else if(strcmp(typ_str, "_UBYTE") == 0) {
        arr = (PyArrayObject*) PyArray_SimpleNew(ndim, rdim, NPY_UBYTE);
    } else {
        PyErr_SetString(PyExc_IOError, "dat_get: encountered an unimplemented type");
        return NULL;
    }
    if(arr == NULL) goto fail;
    datGet(loc, typ_str, ndim, tdim, arr->data, &status);
    if(status != SAI__OK) goto fail;
    return PyArray_Return(arr);

fail:
    raiseHDSException(&status);
    Py_XDECREF(arr);
    return NULL;

};
コード例 #26
0
static PyObject *FIRsepsym2d(PyObject *NPY_UNUSED(dummy), PyObject *args)
{
  PyObject *image=NULL, *hrow=NULL, *hcol=NULL;
  PyArrayObject *a_image=NULL, *a_hrow=NULL, *a_hcol=NULL, *out=NULL;
  int thetype, M, N, ret;
  npy_intp outstrides[2], instrides[2];

  if (!PyArg_ParseTuple(args, "OOO", &image, &hrow, &hcol)) return NULL;

  thetype = PyArray_ObjectType(image, PyArray_FLOAT);
  thetype = NPY_MIN(thetype, PyArray_CDOUBLE);
  a_image = (PyArrayObject *)PyArray_FromObject(image, thetype, 2, 2);
  a_hrow = (PyArrayObject *)PyArray_ContiguousFromObject(hrow, thetype, 1, 1);
  a_hcol = (PyArrayObject *)PyArray_ContiguousFromObject(hcol, thetype, 1, 1);
  
  if ((a_image == NULL) || (a_hrow == NULL) || (a_hcol==NULL)) goto fail;
  
  out = (PyArrayObject *)PyArray_SimpleNew(2,DIMS(a_image),thetype);
  if (out == NULL) goto fail;
  M = DIMS(a_image)[0];
  N = DIMS(a_image)[1];

  convert_strides(STRIDES(a_image), instrides, ELSIZE(a_image), 2);
  outstrides[0] = N;
  outstrides[1] = 1;

  switch (thetype) {
  case PyArray_FLOAT:
    ret = S_separable_2Dconvolve_mirror((float *)DATA(a_image), 
					(float *)DATA(out), M, N,
					(float *)DATA(a_hrow), 
					(float *)DATA(a_hcol),
					DIMS(a_hrow)[0], DIMS(a_hcol)[0], 
					instrides, outstrides);
    break;
  case PyArray_DOUBLE:
    ret = D_separable_2Dconvolve_mirror((double *)DATA(a_image), 
					(double *)DATA(out), M, N, 
					(double *)DATA(a_hrow), 
					(double *)DATA(a_hcol),
					DIMS(a_hrow)[0], DIMS(a_hcol)[0], 
					instrides, outstrides);
    break;
#ifdef __GNUC__
  case PyArray_CFLOAT:
    ret = C_separable_2Dconvolve_mirror((__complex__ float *)DATA(a_image), 
					(__complex__ float *)DATA(out), M, N, 
					(__complex__ float *)DATA(a_hrow), 
					(__complex__ float *)DATA(a_hcol),
					DIMS(a_hrow)[0], DIMS(a_hcol)[0], 
					instrides, outstrides);
    break;
  case PyArray_CDOUBLE:
    ret = Z_separable_2Dconvolve_mirror((__complex__ double *)DATA(a_image), 
					(__complex__ double *)DATA(out), M, N, 
					(__complex__ double *)DATA(a_hrow), 
					(__complex__ double *)DATA(a_hcol),
					DIMS(a_hrow)[0], DIMS(a_hcol)[0], 
					instrides, outstrides);
    break;
#endif
  default:
    PYERR("Incorrect type.");
  }
  
  if (ret < 0) PYERR("Problem occured inside routine.");

  Py_DECREF(a_image);
  Py_DECREF(a_hrow);
  Py_DECREF(a_hcol);
  return PyArray_Return(out);
 
 fail:
  Py_XDECREF(a_image);
  Py_XDECREF(a_hrow);
  Py_XDECREF(a_hcol);
  Py_XDECREF(out);
  return NULL;

}
コード例 #27
0
ファイル: calcGrid.c プロジェクト: boywert/SussexBigRun2013
PyObject* _calcDensSlice(PyObject *self, PyObject *args) {
	PyArrayObject *pos, *hsml, *mass, *pyGrid;
	int npart, nx, ny, cells;
	int dims[2];
	double bx, by, cx, cy, cz;
	double *data_pos, *data_hsml, *data_mass;
	double *grid;
	int part;
	double px, py, pz, h, v, cpx, cpy, r2, h2;
	double p[3];
	int x, y;
	int xmin, xmax, ymin, ymax, axis0, axis1;
	double cellsizex, cellsizey;
	time_t start;
	
	start = clock();

	axis0 = 0;
	axis1 = 1;
	if (!PyArg_ParseTuple( args, "O!O!O!iiddddd|ii:calcDensSlice( pos, hsml, mass, nx, ny, boxx, boxy, centerx, centery, centerz, [axis0, axis1] )", &PyArray_Type, &pos, &PyArray_Type, &hsml, &PyArray_Type, &mass, &nx, &ny, &bx, &by, &cx, &cy, &cz, &axis0, &axis1 )) {
		return 0;
	}

	if (pos->nd != 2 || pos->dimensions[1] != 3 || pos->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "pos has to be of dimensions [n,3] and type double" );
		return 0;
	}

	if (hsml->nd != 1 || hsml->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "hsml has to be of dimension [n] and type double" );
		return 0;
	}

	if (mass->nd != 1 || mass->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "mass has to be of dimension [n] and type double" );
		return 0;
	}

	npart = pos->dimensions[0];
	if (npart != hsml->dimensions[0] || npart != mass->dimensions[0]) {
		PyErr_SetString( PyExc_ValueError, "pos, hsml and mass have to have the same size in the first dimension" );
		return 0;
	}

	dims[0] = nx;
	dims[1] = ny;
	pyGrid = (PyArrayObject *)PyArray_FromDims( 2, dims, PyArray_DOUBLE );
	grid = (double*)pyGrid->data;
	cells = nx*ny;
	memset( grid, 0, cells*sizeof(double) );

	cellsizex = bx / nx;
	cellsizey = by / ny;

	data_pos = (double*)pos->data;
	data_hsml = (double*)hsml->data;
	data_mass = (double*)mass->data;

	for (part=0; part<npart; part++) {
		p[0] = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		p[1] = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		p[2] = *data_pos;
		data_pos = (double*)((char*)data_pos - 2*pos->strides[1] + pos->strides[0]);
		
		px = p[ axis0 ];
		py = p[ axis1 ];
		pz = p[ 3 - axis0 - axis1 ];
		
		h = *data_hsml;
		data_hsml = (double*)((char*)data_hsml + hsml->strides[0]);
		h2 = h*h;

		v = *data_mass;
		data_mass = (double*)((char*)data_mass + mass->strides[0]);

		xmin = max( floor( (px - h - cx + 0.5*bx) / cellsizex ), 0 );
		xmax = min( ceil( (px + h - cx + 0.5*bx) / cellsizex ), nx-1 );
		ymin = max( floor( (py - h - cy + 0.5*by) / cellsizey ), 0 );
		ymax = min( ceil( (py + h - cy + 0.5*by) / cellsizey ), ny-1 );

		if (xmin < nx && ymin < ny && xmax >= 0 && ymax >= 0 && abs(pz-cz) < h) {
			for (x=xmin; x<=xmax; x++) {
				cpx = -0.5*bx + bx*(x+0.5)/nx;
				for (y=ymin; y<=ymax; y++) {
					cpy = -0.5*by + by*(y+0.5)/ny;
					r2 = sqr(px-cpx-cx) + sqr(py-cpy-cy) + sqr(pz-cz);
					if (r2 > h2) continue;
					grid[x*ny + y] += _getkernel( h, r2 ) * v;
				}
			}	
		}
	}

	printf( "Calculation took %gs\n", ((double)clock()-(double)start)/CLOCKS_PER_SEC );
	return PyArray_Return( pyGrid );
}
コード例 #28
0
static PyObject *IIRsymorder1(PyObject *NPY_UNUSED(dummy), PyObject *args)
{
  PyObject *sig=NULL;
  PyArrayObject *a_sig=NULL, *out=NULL;
  Py_complex c0, z1;
  double precision = -1.0;
  int thetype, N, ret;
  npy_intp outstrides, instrides;

  if (!PyArg_ParseTuple(args, "ODD|d", &sig, &c0, &z1, &precision))
    return NULL;

  thetype = PyArray_ObjectType(sig, PyArray_FLOAT);
  thetype = NPY_MIN(thetype, PyArray_CDOUBLE);
  a_sig = (PyArrayObject *)PyArray_FromObject(sig, thetype, 1, 1);
  
  if ((a_sig == NULL)) goto fail;
  
  out = (PyArrayObject *)PyArray_SimpleNew(1,DIMS(a_sig),thetype);
  if (out == NULL) goto fail;
  N = DIMS(a_sig)[0];

  convert_strides(STRIDES(a_sig), &instrides, ELSIZE(a_sig), 1);
  outstrides = 1;

  switch (thetype) {
  case PyArray_FLOAT:
    {
      float rc0 = c0.real;
      float rz1 = z1.real;

      if ((precision <= 0.0) || (precision > 1.0)) precision = 1e-6;      
      ret = S_IIR_forback1 (rc0, rz1, (float *)DATA(a_sig), 
			    (float *)DATA(out), N,
			    instrides, outstrides, (float )precision);
    }
    break;
  case PyArray_DOUBLE:
    {
      double rc0 = c0.real;
      double rz1 = z1.real;

      if ((precision <= 0.0) || (precision > 1.0)) precision = 1e-11;
      ret = D_IIR_forback1 (rc0, rz1, (double *)DATA(a_sig), 
			    (double *)DATA(out), N,
			    instrides, outstrides, precision);
    }
    break;
#ifdef __GNUC__
  case PyArray_CFLOAT:
    {
      __complex__ float zc0 = c0.real + 1.0i*c0.imag;
      __complex__ float zz1 = z1.real + 1.0i*z1.imag;      
      if ((precision <= 0.0) || (precision > 1.0)) precision = 1e-6;
      ret = C_IIR_forback1 (zc0, zz1, (__complex__ float *)DATA(a_sig), 
			    (__complex__ float *)DATA(out), N,
			    instrides, outstrides, (float )precision);
    }
    break;
  case PyArray_CDOUBLE:
    {
      __complex__ double zc0 = c0.real + 1.0i*c0.imag;
      __complex__ double zz1 = z1.real + 1.0i*z1.imag;      
      if ((precision <= 0.0) || (precision > 1.0)) precision = 1e-11;
      ret = Z_IIR_forback1 (zc0, zz1, (__complex__ double *)DATA(a_sig), 
			    (__complex__ double *)DATA(out), N,
			    instrides, outstrides, precision);
    }
    break;
#endif
  default:
    PYERR("Incorrect type.");
  }

  if (ret == 0) {
    Py_DECREF(a_sig);
    return PyArray_Return(out);
  }

  if (ret == -1) PYERR("Could not allocate enough memory.");
  if (ret == -2) PYERR("|z1| must be less than 1.0");
  if (ret == -3) PYERR("Sum to find symmetric boundary conditions did not converge.");

  PYERR("Unknown error.");

 
 fail:
  Py_XDECREF(a_sig);
  Py_XDECREF(out);
  return NULL;

}
コード例 #29
0
ファイル: calcGrid.c プロジェクト: boywert/SussexBigRun2013
PyObject* _calcAbundGrid(PyObject *self, PyObject *args) {
	PyArrayObject *pos, *hsml, *mass, *abund, *pyGrid;
	int npart, nx, ny, nz, cells, nspecies;
	int dims[4];
	double bx, by, bz, cx, cy, cz;
	double *data_pos, *data_hsml, *data_mass, *data_abund;
	double *grid;
	int part, species;
	double *xnuc;
	double px, py, pz, h, h2, m, cpx, cpy, cpz, r2, kk;
	int x, y, z0, z1;
	int xmin, xmax, ymin, ymax, zmin, zmax, zmid;
	double cellsizex, cellsizey, cellsizez;
	time_t start;
	
	start = clock();

	if (!PyArg_ParseTuple( args, "O!O!O!O!iiidddddd:calcAbundGrid( pos, hsml, mass, abund, nx, ny, nz, boxx, boxy, boxz, centerx, centery, centerz )", &PyArray_Type, &pos, &PyArray_Type, &hsml, &PyArray_Type, &mass, &PyArray_Type, &abund, &nx, &ny, &nz, &bx, &by, &bz, &cx, &cy, &cz )) {
		return 0;
	}

	if (pos->nd != 2 || pos->dimensions[1] != 3 || pos->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "pos has to be of dimensions [n,3] and type double" );
		return 0;
	}

	if (hsml->nd != 1 || hsml->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "hsml has to be of dimension [n] and type double" );
		return 0;
	}

	if (mass->nd != 1 || mass->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "mass has to be of dimension [n] and type double" );
		return 0;
	}

	if (abund->nd != 2 || abund->descr->type_num != PyArray_DOUBLE) {
		PyErr_SetString( PyExc_ValueError, "abund has to be of dimension [n,nspecies] and type double" );
		return 0;
	}
	
	nspecies = abund->dimensions[1];

	npart = pos->dimensions[0];
	if (npart != hsml->dimensions[0] || npart != mass->dimensions[0]  || npart != abund->dimensions[0]) {
		PyErr_SetString( PyExc_ValueError, "pos, hsml and abund have to have the same size in the first dimension" );
		return 0;
	}
	
	xnuc = (double*)malloc( nspecies * sizeof( double ) );

	dims[0] = nx;
	dims[1] = ny;
	dims[2] = nz;
	dims[3] = nspecies+1;
	pyGrid = (PyArrayObject *)PyArray_FromDims( 4, dims, PyArray_DOUBLE );
	grid = (double*)pyGrid->data;
	cells = nx*ny*nz*(nspecies+1);
	memset( grid, 0, cells*sizeof(double) );

	cellsizex = bx / nx;
	cellsizey = by / ny;
	cellsizez = bz / nz;

	data_pos = (double*)pos->data;
	data_hsml = (double*)hsml->data;
	data_mass = (double*)mass->data;
	data_abund = (double*)abund->data;

	for (part=0; part<npart; part++) {
		px = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		py = *data_pos;
		data_pos = (double*)((char*)data_pos + pos->strides[1]);
		pz = *data_pos;
		data_pos = (double*)((char*)data_pos - 2*pos->strides[1] + pos->strides[0]);
		
		h = *data_hsml;
		data_hsml = (double*)((char*)data_hsml + hsml->strides[0]);
		h2 = h*h;

		m = *data_mass;
		data_mass = (double*)((char*)data_mass + mass->strides[0]);

		for (species = 0; species < nspecies; species++ ) {
			xnuc[species] = *data_abund;
			data_abund = (double*)((char*)data_abund + abund->strides[1]);
		}
		data_abund = (double*)((char*)data_abund - nspecies*abund->strides[1] + abund->strides[0]);

		xmin = max( floor( (px - h - cx + 0.5*bx) / cellsizex ), 0 );
		xmax = min( ceil( (px + h - cx + 0.5*bx) / cellsizex ), nx-1 );
		ymin = max( floor( (py - h - cy + 0.5*by) / cellsizey ), 0 );
		ymax = min( ceil( (py + h - cy + 0.5*by) / cellsizey ), ny-1 );
		zmin = max( floor( (pz - h - cz + 0.5*bz) / cellsizez ), 0 );
		zmax = min( ceil( (pz + h - cz + 0.5*bz) / cellsizez ), nz-1 );

		zmid = floor( 0.5 * (zmin+zmax) + 0.5 );

		if (xmin < nx && ymin < ny && xmax >= 0 && ymax >= 0 && zmin < nz && zmax >= 0) {
			for (x=xmin; x<=xmax; x++) {
				cpx = -0.5*bx + bx*(x+0.5)/nx;
				for (y=ymin; y<=ymax; y++) {
					cpy = -0.5*by + by*(y+0.5)/ny;
					for (z0=zmid; z0>=zmin; z0--) {
						cpz = -0.5*bz + bz*(z0+0.5)/nz;
						r2 = ( sqr(px-cpx-cx) + sqr(py-cpy-cy) + sqr(pz-cpz-cz) );
						if (r2 > h2) break;
						
						kk = _getkernel( h, r2 ) * m;
						for (species = 0; species < nspecies; species++ )
							grid[((x*ny + y)*nz + z0)*(nspecies+1) + species] += kk * xnuc[species];
						grid[((x*ny + y)*nz + z0)*(nspecies+1) + nspecies] += kk;
					}

					for (z1=zmid+1; z1<=zmax; z1++) {
						cpz = -0.5*bz + bz*(z1+0.5)/nz;
						r2 = ( sqr(px-cpx-cx) + sqr(py-cpy-cy) + sqr(pz-cpz-cz) );
						if (r2 > h2) break;
						
						kk = _getkernel( h, r2 ) * m;
						for (species = 0; species < nspecies; species++ )
							grid[((x*ny + y)*nz + z1)*(nspecies+1) + species] += kk * xnuc[species];
						grid[((x*ny + y)*nz + z1)*(nspecies+1) + nspecies] += kk;
					}
				}
			}	
		}
	}
	
	free( xnuc );

	printf( "Calculation took %gs\n", ((double)clock()-(double)start)/CLOCKS_PER_SEC );
	return PyArray_Return( pyGrid );
}
コード例 #30
0
static PyObject*
kin_getarray(PyObject *self, PyObject *args)
{
    int kin;
    int job;
    
    if (!PyArg_ParseTuple(args, "ii:kin_getarray", &kin, &job)) 
        return NULL;

    // array attributes
    int iok = -22;
    size_t nrxns = kin_nReactions(kin);
    size_t nsp = kin_nSpecies(kin);
    size_t ix;
    if (job < 45 || job >= 90) ix = nrxns; else ix = nsp;
 
#ifdef HAS_NUMPY
    npy_intp nix = ix;
    PyArrayObject* x = (PyArrayObject*)PyArray_SimpleNew(1, &nix, PyArray_DOUBLE);
#else
    int nix = int(ix);
    PyArrayObject* x = 
        (PyArrayObject*)PyArray_FromDims(1, &nix, PyArray_DOUBLE);
#endif
    double* xd = (double*)x->data;

    switch (job) {
    case 10:
        iok = kin_getFwdRatesOfProgress(kin, nrxns, xd);
        break;
    case 20:
        iok = kin_getRevRatesOfProgress(kin, nrxns, xd);
        break;
    case 30:
        iok = kin_getNetRatesOfProgress(kin, nrxns, xd);
        break;
    case 32:
        iok = kin_getActivationEnergies(kin, nrxns, xd);
        break;
    case 34:
        iok = kin_getFwdRateConstants(kin, nrxns, xd);
        break;
    case 35:
        iok = kin_getRevRateConstants(kin, 1, nrxns, xd);
    case 36:
        iok = kin_getRevRateConstants(kin, 0, nrxns, xd);
        break;
    case 40:
        iok = kin_getEquilibriumConstants(kin, nrxns, xd);
        break;
    case 50:
        iok = kin_getCreationRates(kin, nsp, xd);
        break;
    case 60:
        iok = kin_getDestructionRates(kin, nsp, xd);
        break;
    case 70:
        iok = kin_getNetProductionRates(kin, nsp, xd);
        break;
    case 80:
        iok = kin_getSourceTerms(kin, nsp, xd);
        break;
    case 90:
        iok = kin_getDelta(kin, 0, nrxns, xd);
        break;
    case 91:
        iok = kin_getDelta(kin, 1, nrxns, xd);
        break;
    case 92:
        iok = kin_getDelta(kin, 2, nrxns, xd);
        break;
    case 93:
        iok = kin_getDelta(kin, 3, nrxns, xd);
        break;
    case 94:
        iok = kin_getDelta(kin, 4, nrxns, xd);
        break;
    case 95:
        iok = kin_getDelta(kin, 5, nrxns, xd);
        break;
    default:
        ;
    }
    if (iok >= 0) {
        return PyArray_Return(x);
    }
    else 
        return reportError(iok);
}