[PYTHON MATRIX-SIG] Applying a general function to an array

James Hugunin jjh@Goldilocks.LCS.MIT.EDU
Thu, 22 Feb 96 13:25:04 EST


I assume that you have a python function of the form:

PyObject *gaussian_call(PyObject *self, PyObject *args) {
	double x, r;

	PyArg_ParseTuple("d", &x);

	r = calculate(self, x);

	return Py_BuildValue("d", r);
}

if you convert this to the following, it will work on arbitrary arrays

PyObject *gaussian_call(PyObject *self, PyObject *args) {
	int n, i;
	PyObject *op;
	PyArrayObject *ap, *rp;

	PyArg_ParseTuple("O", &op);
	ap = PyArray_ContiguousFromObject(op, PyArray_DOUBLE, 0, 0);

	rp = PyArray_FromDims(ap->nd, ap->dimensions, PyArray_DOUBLE);

	n = PyArray_Size(ap);
	for(i=0; i<n; i++) {
		((double *)rp->data)[i] = 
			calculate(self, ((double *)ap->data)[i]);
	}

	return PyArray_Return(rp);
}

I admit this looks a little bit more complicated, but this new version
will work on any size/shape of array as well as on python scalars.
Any other solution will involve converting the elements of the array
into and out of python objects, and the overhead of doing this would
probably totally swap the computation.

I don't know if this is what you're looking for, but I hope it's helpful.

-Jim


=================
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
=================