summaryrefslogtreecommitdiff
path: root/numpy/core/src
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/core/src')
-rw-r--r--numpy/core/src/_isnan.c48
-rw-r--r--numpy/core/src/_signbit.c22
-rw-r--r--numpy/core/src/_sortmodule.c.src104
-rw-r--r--numpy/core/src/arraymethods.c2873
-rw-r--r--numpy/core/src/arrayobject.c17507
-rw-r--r--numpy/core/src/multiarraymodule.c11570
-rw-r--r--numpy/core/src/scalarmathmodule.c.src448
-rw-r--r--numpy/core/src/ucsnarrow.c124
-rw-r--r--numpy/core/src/ufuncobject.c5983
-rw-r--r--numpy/core/src/umathmodule.c.src2110
10 files changed, 20392 insertions, 20397 deletions
diff --git a/numpy/core/src/_isnan.c b/numpy/core/src/_isnan.c
index 3257c4ef2..bff6e0a49 100644
--- a/numpy/core/src/_isnan.c
+++ b/numpy/core/src/_isnan.c
@@ -3,44 +3,44 @@
static int
isnan(double x)
{
- union
- {
- double d;
- unsigned short s[4];
- unsigned int i[2];
- } u;
+ union
+ {
+ double d;
+ unsigned short s[4];
+ unsigned int i[2];
+ } u;
- u.d = x;
+ u.d = x;
#if SIZEOF_INT == 4
#ifdef WORDS_BIGENDIAN /* defined in pyconfig.h */
- if( ((u.i[0] & 0x7ff00000) == 0x7ff00000)
- && (((u.i[0] & 0x000fffff) != 0) || (u.i[1] != 0)))
- return 1;
+ if( ((u.i[0] & 0x7ff00000) == 0x7ff00000)
+ && (((u.i[0] & 0x000fffff) != 0) || (u.i[1] != 0)))
+ return 1;
#else
- if( ((u.i[1] & 0x7ff00000) == 0x7ff00000)
- && (((u.i[1] & 0x000fffff) != 0) || (u.i[0] != 0)))
- return 1;
+ if( ((u.i[1] & 0x7ff00000) == 0x7ff00000)
+ && (((u.i[1] & 0x000fffff) != 0) || (u.i[0] != 0)))
+ return 1;
#endif
#else /* SIZEOF_INT != 4 */
#ifdef WORDS_BIGENDIAN
- if( (u.s[0] & 0x7ff0) == 0x7ff0)
- {
- if( ((u.s[0] & 0x000f) | u.s[1] | u.s[2] | u.s[3]) != 0 )
- return 1;
- }
+ if( (u.s[0] & 0x7ff0) == 0x7ff0)
+ {
+ if( ((u.s[0] & 0x000f) | u.s[1] | u.s[2] | u.s[3]) != 0 )
+ return 1;
+ }
#else
- if( (u.s[3] & 0x7ff0) == 0x7ff0)
- {
- if( ((u.s[3] & 0x000f) | u.s[2] | u.s[1] | u.s[0]) != 0 )
- return 1;
- }
+ if( (u.s[3] & 0x7ff0) == 0x7ff0)
+ {
+ if( ((u.s[3] & 0x000f) | u.s[2] | u.s[1] | u.s[0]) != 0 )
+ return 1;
+ }
#endif
#endif /* SIZEOF_INT */
- return 0;
+ return 0;
}
diff --git a/numpy/core/src/_signbit.c b/numpy/core/src/_signbit.c
index 48a808ac7..2be3649fd 100644
--- a/numpy/core/src/_signbit.c
+++ b/numpy/core/src/_signbit.c
@@ -3,29 +3,29 @@
static int
signbit(double x)
{
- union
- {
- double d;
- short s[4];
- int i[2];
- } u;
+ union
+ {
+ double d;
+ short s[4];
+ int i[2];
+ } u;
- u.d = x;
+ u.d = x;
#if SIZEOF_INT == 4
#ifdef WORDS_BIGENDIAN /* defined in pyconfig.h */
- return u.i[0] < 0;
+ return u.i[0] < 0;
#else
- return u.i[1] < 0;
+ return u.i[1] < 0;
#endif
#else /* SIZEOF_INT != 4 */
#ifdef WORDS_BIGENDIAN
- return u.s[0] < 0;
+ return u.s[0] < 0;
#else
- return u.s[3] < 0;
+ return u.s[3] < 0;
#endif
#endif /* SIZEOF_INT */
diff --git a/numpy/core/src/_sortmodule.c.src b/numpy/core/src/_sortmodule.c.src
index 64ea04488..52cfe6219 100644
--- a/numpy/core/src/_sortmodule.c.src
+++ b/numpy/core/src/_sortmodule.c.src
@@ -47,10 +47,10 @@
/**begin repeat
-#TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE,CFLOAT,CDOUBLE,CLONGDOUBLE#
-#type=Bool,byte,ubyte,short,ushort,int,uint,long,ulong,longlong,ulonglong,float,double,longdouble,cfloat,cdouble,clongdouble#
-#lessthan=STDC_LT*14,NUMC_LT*3#
-#lessequal=STDC_LE*14,NUMC_LE*3#
+ #TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE,CFLOAT,CDOUBLE,CLONGDOUBLE#
+ #type=Bool,byte,ubyte,short,ushort,int,uint,long,ulong,longlong,ulonglong,float,double,longdouble,cfloat,cdouble,clongdouble#
+ #lessthan=STDC_LT*14,NUMC_LT*3#
+ #lessequal=STDC_LE*14,NUMC_LE*3#
**/
static int
@TYPE@_quicksort(@type@ *start, intp num, void *unused)
@@ -95,7 +95,7 @@ static int
for(pi = pl + 1; pi <= pr; ++pi) {
vp = *pi;
for(pj = pi, pt = pi - 1; pj > pl && @lessthan@(vp, *pt);) {
- *pj-- = *pt--;
+ *pj-- = *pt--;
}
*pj = vp;
}
@@ -376,10 +376,10 @@ static int
/**end repeat**/
/**begin repeat
-#TYPE=STRING, UNICODE#
-#type=char, PyArray_UCS4#
-#lessthan=STRING_LT, UNICODE_LT#
-#lessequal=STRING_LE, UNICODE_LE#
+ #TYPE=STRING, UNICODE#
+ #type=char, PyArray_UCS4#
+ #lessthan=STRING_LT, UNICODE_LT#
+ #lessequal=STRING_LE, UNICODE_LE#
**/
static void
@TYPE@_amergesort0(intp *pl, intp *pr, @type@ *v, intp *pw, int len)
@@ -423,68 +423,68 @@ static void
static int
@TYPE@_amergesort(@type@ *v, intp *tosort, intp num, PyArrayObject *arr)
{
- intp *pl, *pr, *pw;
- int elsize, chars;
+ intp *pl, *pr, *pw;
+ int elsize, chars;
- elsize = arr->descr->elsize;
+ elsize = arr->descr->elsize;
- chars = elsize / sizeof(@type@);
+ chars = elsize / sizeof(@type@);
- pl = tosort; pr = pl + num - 1;
- pw = PyDimMem_NEW((1+num/2));
+ pl = tosort; pr = pl + num - 1;
+ pw = PyDimMem_NEW((1+num/2));
- if (!pw) {
- PyErr_NoMemory();
- return -1;
- }
+ if (!pw) {
+ PyErr_NoMemory();
+ return -1;
+ }
- @TYPE@_amergesort0(pl, pr, v, pw, chars);
- PyDimMem_FREE(pw);
+ @TYPE@_amergesort0(pl, pr, v, pw, chars);
+ PyDimMem_FREE(pw);
- return 0;
+ return 0;
}
/**end repeat**/
static void
add_sortfuncs(void)
{
- PyArray_Descr *descr;
-
-/**begin repeat
-#TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE,CFLOAT,CDOUBLE,CLONGDOUBLE#
-**/
- descr = PyArray_DescrFromType(PyArray_@TYPE@);
- descr->f->sort[PyArray_QUICKSORT] = \
- (PyArray_SortFunc *)@TYPE@_quicksort;
- descr->f->argsort[PyArray_QUICKSORT] = \
- (PyArray_ArgSortFunc *)@TYPE@_aquicksort;
- descr->f->sort[PyArray_HEAPSORT] = \
- (PyArray_SortFunc *)@TYPE@_heapsort;
- descr->f->argsort[PyArray_HEAPSORT] = \
- (PyArray_ArgSortFunc *)@TYPE@_aheapsort;
- descr->f->sort[PyArray_MERGESORT] = \
- (PyArray_SortFunc *)@TYPE@_mergesort;
- descr->f->argsort[PyArray_MERGESORT] = \
- (PyArray_ArgSortFunc *)@TYPE@_amergesort;
-/**end repeat**/
-
- descr = PyArray_DescrFromType(PyArray_STRING);
- descr->f->argsort[PyArray_MERGESORT] = \
- (PyArray_ArgSortFunc *)STRING_amergesort;
- descr = PyArray_DescrFromType(PyArray_UNICODE);
- descr->f->argsort[PyArray_MERGESORT] = \
- (PyArray_ArgSortFunc *)UNICODE_amergesort;
+ PyArray_Descr *descr;
+
+ /**begin repeat
+ #TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE,CFLOAT,CDOUBLE,CLONGDOUBLE#
+ **/
+ descr = PyArray_DescrFromType(PyArray_@TYPE@);
+ descr->f->sort[PyArray_QUICKSORT] = \
+ (PyArray_SortFunc *)@TYPE@_quicksort;
+ descr->f->argsort[PyArray_QUICKSORT] = \
+ (PyArray_ArgSortFunc *)@TYPE@_aquicksort;
+ descr->f->sort[PyArray_HEAPSORT] = \
+ (PyArray_SortFunc *)@TYPE@_heapsort;
+ descr->f->argsort[PyArray_HEAPSORT] = \
+ (PyArray_ArgSortFunc *)@TYPE@_aheapsort;
+ descr->f->sort[PyArray_MERGESORT] = \
+ (PyArray_SortFunc *)@TYPE@_mergesort;
+ descr->f->argsort[PyArray_MERGESORT] = \
+ (PyArray_ArgSortFunc *)@TYPE@_amergesort;
+ /**end repeat**/
+
+ descr = PyArray_DescrFromType(PyArray_STRING);
+ descr->f->argsort[PyArray_MERGESORT] = \
+ (PyArray_ArgSortFunc *)STRING_amergesort;
+ descr = PyArray_DescrFromType(PyArray_UNICODE);
+ descr->f->argsort[PyArray_MERGESORT] = \
+ (PyArray_ArgSortFunc *)UNICODE_amergesort;
}
static struct PyMethodDef methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
PyMODINIT_FUNC
init_sort(void) {
- Py_InitModule("_sort", methods);
+ Py_InitModule("_sort", methods);
- import_array();
- add_sortfuncs();
+ import_array();
+ add_sortfuncs();
}
diff --git a/numpy/core/src/arraymethods.c b/numpy/core/src/arraymethods.c
index 3a1b0c37d..9c56e6459 100644
--- a/numpy/core/src/arraymethods.c
+++ b/numpy/core/src/arraymethods.c
@@ -1,321 +1,320 @@
-
/* Should only be used if x is known to be an nd-array */
#define _ARET(x) PyArray_Return((PyArrayObject *)(x))
static PyObject *
array_take(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int dimension=MAX_DIMS;
- PyObject *indices;
- PyArrayObject *out=NULL;
- NPY_CLIPMODE mode=NPY_RAISE;
- static char *kwlist[] = {"indices", "axis", "out", "mode", NULL};
+ int dimension=MAX_DIMS;
+ PyObject *indices;
+ PyArrayObject *out=NULL;
+ NPY_CLIPMODE mode=NPY_RAISE;
+ static char *kwlist[] = {"indices", "axis", "out", "mode", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O&", kwlist,
- &indices, PyArray_AxisConverter,
- &dimension,
- PyArray_OutputConverter,
- &out,
- PyArray_ClipmodeConverter,
- &mode))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O&", kwlist,
+ &indices, PyArray_AxisConverter,
+ &dimension,
+ PyArray_OutputConverter,
+ &out,
+ PyArray_ClipmodeConverter,
+ &mode))
+ return NULL;
- return _ARET(PyArray_TakeFrom(self, indices, dimension, out, mode));
+ return _ARET(PyArray_TakeFrom(self, indices, dimension, out, mode));
}
static PyObject *
array_fill(PyArrayObject *self, PyObject *args)
{
- PyObject *obj;
- if (!PyArg_ParseTuple(args, "O", &obj))
- return NULL;
- if (PyArray_FillWithScalar(self, obj) < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *obj;
+ if (!PyArg_ParseTuple(args, "O", &obj))
+ return NULL;
+ if (PyArray_FillWithScalar(self, obj) < 0) return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_put(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *indices, *values;
- NPY_CLIPMODE mode=NPY_RAISE;
- static char *kwlist[] = {"indices", "values", "mode", NULL};
+ PyObject *indices, *values;
+ NPY_CLIPMODE mode=NPY_RAISE;
+ static char *kwlist[] = {"indices", "values", "mode", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist,
- &indices, &values,
- PyArray_ClipmodeConverter,
- &mode))
- return NULL;
- return PyArray_PutTo(self, values, indices, mode);
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist,
+ &indices, &values,
+ PyArray_ClipmodeConverter,
+ &mode))
+ return NULL;
+ return PyArray_PutTo(self, values, indices, mode);
}
static PyObject *
array_reshape(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- PyArray_Dims newshape;
- PyObject *ret;
- PyArray_ORDER order=PyArray_CORDER;
- int n;
-
- if (kwds != NULL) {
- PyObject *ref;
- ref = PyDict_GetItemString(kwds, "order");
- if (ref == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "invalid keyword argument");
- return NULL;
- }
- if ((PyArray_OrderConverter(ref, &order) == PY_FAIL))
- return NULL;
- }
-
- n = PyTuple_Size(args);
- if (n <= 1) {
- if (PyTuple_GET_ITEM(args, 0) == Py_None)
- return PyArray_View(self, NULL, NULL);
- if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter,
- &newshape)) return NULL;
- }
- else {
- if (!PyArray_IntpConverter(args, &newshape)) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "invalid shape");
- }
- goto fail;
- }
- }
- ret = PyArray_Newshape(self, &newshape, order);
- PyDimMem_FREE(newshape.ptr);
- return ret;
+ PyArray_Dims newshape;
+ PyObject *ret;
+ PyArray_ORDER order=PyArray_CORDER;
+ int n;
+
+ if (kwds != NULL) {
+ PyObject *ref;
+ ref = PyDict_GetItemString(kwds, "order");
+ if (ref == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid keyword argument");
+ return NULL;
+ }
+ if ((PyArray_OrderConverter(ref, &order) == PY_FAIL))
+ return NULL;
+ }
+
+ n = PyTuple_Size(args);
+ if (n <= 1) {
+ if (PyTuple_GET_ITEM(args, 0) == Py_None)
+ return PyArray_View(self, NULL, NULL);
+ if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter,
+ &newshape)) return NULL;
+ }
+ else {
+ if (!PyArray_IntpConverter(args, &newshape)) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid shape");
+ }
+ goto fail;
+ }
+ }
+ ret = PyArray_Newshape(self, &newshape, order);
+ PyDimMem_FREE(newshape.ptr);
+ return ret;
fail:
- PyDimMem_FREE(newshape.ptr);
- return NULL;
+ PyDimMem_FREE(newshape.ptr);
+ return NULL;
}
static PyObject *
array_squeeze(PyArrayObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "")) return NULL;
- return PyArray_Squeeze(self);
+ if (!PyArg_ParseTuple(args, "")) return NULL;
+ return PyArray_Squeeze(self);
}
static PyObject *
array_view(PyArrayObject *self, PyObject *args)
{
- PyObject *otype=NULL;
- PyArray_Descr *type=NULL;
+ PyObject *otype=NULL;
+ PyArray_Descr *type=NULL;
- if (!PyArg_ParseTuple(args, "|O", &otype)) return NULL;
+ if (!PyArg_ParseTuple(args, "|O", &otype)) return NULL;
- if (otype) {
- if (PyType_Check(otype) && \
- PyType_IsSubtype((PyTypeObject *)otype,
- &PyArray_Type)) {
- return PyArray_View(self, NULL,
- (PyTypeObject *)otype);
- }
- else {
- if (PyArray_DescrConverter(otype, &type) == PY_FAIL)
- return NULL;
- }
- }
- return PyArray_View(self, type, NULL);
+ if (otype) {
+ if (PyType_Check(otype) && \
+ PyType_IsSubtype((PyTypeObject *)otype,
+ &PyArray_Type)) {
+ return PyArray_View(self, NULL,
+ (PyTypeObject *)otype);
+ }
+ else {
+ if (PyArray_DescrConverter(otype, &type) == PY_FAIL)
+ return NULL;
+ }
+ }
+ return PyArray_View(self, type, NULL);
}
static PyObject *
array_argmax(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
- PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return _ARET(PyArray_ArgMax(self, axis, out));
+ return _ARET(PyArray_ArgMax(self, axis, out));
}
static PyObject *
array_argmin(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
- PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return _ARET(PyArray_ArgMin(self, axis, out));
+ return _ARET(PyArray_ArgMin(self, axis, out));
}
static PyObject *
array_max(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
- PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return PyArray_Max(self, axis, out);
+ return PyArray_Max(self, axis, out);
}
static PyObject *
array_ptp(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
- PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return PyArray_Ptp(self, axis, out);
+ return PyArray_Ptp(self, axis, out);
}
static PyObject *
array_min(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
- PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return PyArray_Min(self, axis, out);
+ return PyArray_Min(self, axis, out);
}
static PyObject *
array_swapaxes(PyArrayObject *self, PyObject *args)
{
- int axis1, axis2;
+ int axis1, axis2;
- if (!PyArg_ParseTuple(args, "ii", &axis1, &axis2)) return NULL;
+ if (!PyArg_ParseTuple(args, "ii", &axis1, &axis2)) return NULL;
- return PyArray_SwapAxes(self, axis1, axis2);
+ return PyArray_SwapAxes(self, axis1, axis2);
}
/* steals typed reference */
/*OBJECT_API
- Get a subset of bytes from each element of the array
+ Get a subset of bytes from each element of the array
*/
static PyObject *
PyArray_GetField(PyArrayObject *self, PyArray_Descr *typed, int offset)
{
- PyObject *ret=NULL;
-
- if (offset < 0 || (offset + typed->elsize) > self->descr->elsize) {
- PyErr_Format(PyExc_ValueError,
- "Need 0 <= offset <= %d for requested type " \
- "but received offset = %d",
- self->descr->elsize-typed->elsize, offset);
- Py_DECREF(typed);
- return NULL;
- }
- ret = PyArray_NewFromDescr(self->ob_type,
- typed,
- self->nd, self->dimensions,
- self->strides,
- self->data + offset,
- self->flags, (PyObject *)self);
- if (ret == NULL) return NULL;
- Py_INCREF(self);
- ((PyArrayObject *)ret)->base = (PyObject *)self;
-
- PyArray_UpdateFlags((PyArrayObject *)ret, UPDATE_ALL);
- return ret;
+ PyObject *ret=NULL;
+
+ if (offset < 0 || (offset + typed->elsize) > self->descr->elsize) {
+ PyErr_Format(PyExc_ValueError,
+ "Need 0 <= offset <= %d for requested type " \
+ "but received offset = %d",
+ self->descr->elsize-typed->elsize, offset);
+ Py_DECREF(typed);
+ return NULL;
+ }
+ ret = PyArray_NewFromDescr(self->ob_type,
+ typed,
+ self->nd, self->dimensions,
+ self->strides,
+ self->data + offset,
+ self->flags, (PyObject *)self);
+ if (ret == NULL) return NULL;
+ Py_INCREF(self);
+ ((PyArrayObject *)ret)->base = (PyObject *)self;
+
+ PyArray_UpdateFlags((PyArrayObject *)ret, UPDATE_ALL);
+ return ret;
}
static PyObject *
array_getfield(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- PyArray_Descr *dtype;
- int offset = 0;
- static char *kwlist[] = {"dtype", "offset", 0};
+ PyArray_Descr *dtype;
+ int offset = 0;
+ static char *kwlist[] = {"dtype", "offset", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|i", kwlist,
- PyArray_DescrConverter,
- &dtype, &offset)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|i", kwlist,
+ PyArray_DescrConverter,
+ &dtype, &offset)) return NULL;
- return PyArray_GetField(self, dtype, offset);
+ return PyArray_GetField(self, dtype, offset);
}
/*OBJECT_API
- Set a subset of bytes from each element of the array
+ Set a subset of bytes from each element of the array
*/
static int
PyArray_SetField(PyArrayObject *self, PyArray_Descr *dtype,
- int offset, PyObject *val)
+ int offset, PyObject *val)
{
- PyObject *ret=NULL;
- int retval = 0;
-
- if (offset < 0 || (offset + dtype->elsize) > self->descr->elsize) {
- PyErr_Format(PyExc_ValueError,
- "Need 0 <= offset <= %d for requested type " \
- "but received offset = %d",
- self->descr->elsize-dtype->elsize, offset);
- Py_DECREF(dtype);
- return -1;
- }
- ret = PyArray_NewFromDescr(self->ob_type,
- dtype, self->nd, self->dimensions,
- self->strides, self->data + offset,
- self->flags, (PyObject *)self);
- if (ret == NULL) return -1;
- Py_INCREF(self);
- ((PyArrayObject *)ret)->base = (PyObject *)self;
-
- PyArray_UpdateFlags((PyArrayObject *)ret, UPDATE_ALL);
- retval = PyArray_CopyObject((PyArrayObject *)ret, val);
- Py_DECREF(ret);
- return retval;
+ PyObject *ret=NULL;
+ int retval = 0;
+
+ if (offset < 0 || (offset + dtype->elsize) > self->descr->elsize) {
+ PyErr_Format(PyExc_ValueError,
+ "Need 0 <= offset <= %d for requested type " \
+ "but received offset = %d",
+ self->descr->elsize-dtype->elsize, offset);
+ Py_DECREF(dtype);
+ return -1;
+ }
+ ret = PyArray_NewFromDescr(self->ob_type,
+ dtype, self->nd, self->dimensions,
+ self->strides, self->data + offset,
+ self->flags, (PyObject *)self);
+ if (ret == NULL) return -1;
+ Py_INCREF(self);
+ ((PyArrayObject *)ret)->base = (PyObject *)self;
+
+ PyArray_UpdateFlags((PyArrayObject *)ret, UPDATE_ALL);
+ retval = PyArray_CopyObject((PyArrayObject *)ret, val);
+ Py_DECREF(ret);
+ return retval;
}
static PyObject *
array_setfield(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- PyArray_Descr *dtype;
- int offset = 0;
- PyObject *value;
- static char *kwlist[] = {"value", "dtype", "offset", 0};
+ PyArray_Descr *dtype;
+ int offset = 0;
+ PyObject *value;
+ static char *kwlist[] = {"value", "dtype", "offset", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|i", kwlist,
- &value, PyArray_DescrConverter,
- &dtype, &offset)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&|i", kwlist,
+ &value, PyArray_DescrConverter,
+ &dtype, &offset)) return NULL;
- if (PyArray_SetField(self, dtype, offset, value) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (PyArray_SetField(self, dtype, offset, value) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* This doesn't change the descriptor just the actual data...
@@ -325,80 +324,80 @@ array_setfield(PyArrayObject *self, PyObject *args, PyObject *kwds)
static PyObject *
PyArray_Byteswap(PyArrayObject *self, Bool inplace)
{
- PyArrayObject *ret;
- intp size;
- PyArray_CopySwapNFunc *copyswapn;
- PyArrayIterObject *it;
-
- copyswapn = self->descr->f->copyswapn;
- if (inplace) {
- if (!PyArray_ISWRITEABLE(self)) {
- PyErr_SetString(PyExc_RuntimeError,
- "Cannot byte-swap in-place on a " \
- "read-only array");
- return NULL;
- }
- size = PyArray_SIZE(self);
- if (PyArray_ISONESEGMENT(self)) {
- copyswapn(self->data, self->descr->elsize, NULL, -1, size, 1, self);
- }
- else { /* Use iterator */
- int axis = -1;
- intp stride;
- it = (PyArrayIterObject *) \
- PyArray_IterAllButAxis((PyObject *)self, &axis);
- stride = self->strides[axis];
- size = self->dimensions[axis];
- while (it->index < it->size) {
- copyswapn(it->dataptr, stride, NULL, -1, size, 1, self);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
- }
-
- Py_INCREF(self);
- return (PyObject *)self;
- }
- else {
- PyObject *new;
- if ((ret = (PyArrayObject *)PyArray_NewCopy(self,-1)) == NULL)
- return NULL;
- new = PyArray_Byteswap(ret, TRUE);
- Py_DECREF(new);
- return (PyObject *)ret;
- }
+ PyArrayObject *ret;
+ intp size;
+ PyArray_CopySwapNFunc *copyswapn;
+ PyArrayIterObject *it;
+
+ copyswapn = self->descr->f->copyswapn;
+ if (inplace) {
+ if (!PyArray_ISWRITEABLE(self)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Cannot byte-swap in-place on a " \
+ "read-only array");
+ return NULL;
+ }
+ size = PyArray_SIZE(self);
+ if (PyArray_ISONESEGMENT(self)) {
+ copyswapn(self->data, self->descr->elsize, NULL, -1, size, 1, self);
+ }
+ else { /* Use iterator */
+ int axis = -1;
+ intp stride;
+ it = (PyArrayIterObject *) \
+ PyArray_IterAllButAxis((PyObject *)self, &axis);
+ stride = self->strides[axis];
+ size = self->dimensions[axis];
+ while (it->index < it->size) {
+ copyswapn(it->dataptr, stride, NULL, -1, size, 1, self);
+ PyArray_ITER_NEXT(it);
+ }
+ Py_DECREF(it);
+ }
+
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ else {
+ PyObject *new;
+ if ((ret = (PyArrayObject *)PyArray_NewCopy(self,-1)) == NULL)
+ return NULL;
+ new = PyArray_Byteswap(ret, TRUE);
+ Py_DECREF(new);
+ return (PyObject *)ret;
+ }
}
static PyObject *
array_byteswap(PyArrayObject *self, PyObject *args)
{
- Bool inplace=FALSE;
+ Bool inplace=FALSE;
- if (!PyArg_ParseTuple(args, "|O&", PyArray_BoolConverter, &inplace))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|O&", PyArray_BoolConverter, &inplace))
+ return NULL;
- return PyArray_Byteswap(self, inplace);
+ return PyArray_Byteswap(self, inplace);
}
static PyObject *
array_tolist(PyArrayObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "")) return NULL;
- return PyArray_ToList(self);
+ if (!PyArg_ParseTuple(args, "")) return NULL;
+ return PyArray_ToList(self);
}
static PyObject *
array_tostring(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- NPY_ORDER order=NPY_CORDER;
- static char *kwlist[] = {"order", NULL};
+ NPY_ORDER order=NPY_CORDER;
+ static char *kwlist[] = {"order", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist,
- PyArray_OrderConverter,
- &order)) return NULL;
- return PyArray_ToString(self, order);
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist,
+ PyArray_OrderConverter,
+ &order)) return NULL;
+ return PyArray_ToString(self, order);
}
@@ -408,264 +407,264 @@ array_tostring(PyArrayObject *self, PyObject *args, PyObject *kwds)
static PyObject *
array_tofile(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int ret;
- PyObject *file;
- FILE *fd;
- char *sep="";
- char *format="";
- static char *kwlist[] = {"file", "sep", "format", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ss", kwlist,
- &file, &sep, &format)) return NULL;
-
- if (PyString_Check(file) || PyUnicode_Check(file)) {
- file = PyObject_CallFunction((PyObject *)&PyFile_Type,
- "Os", file, "wb");
- if (file==NULL) return NULL;
- }
- else {
- Py_INCREF(file);
- }
- fd = PyFile_AsFile(file);
- if (fd == NULL) {
- PyErr_SetString(PyExc_IOError, "first argument must be a " \
- "string or open file");
- Py_DECREF(file);
- return NULL;
- }
- ret = PyArray_ToFile(self, fd, sep, format);
- Py_DECREF(file);
- if (ret < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ int ret;
+ PyObject *file;
+ FILE *fd;
+ char *sep="";
+ char *format="";
+ static char *kwlist[] = {"file", "sep", "format", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ss", kwlist,
+ &file, &sep, &format)) return NULL;
+
+ if (PyString_Check(file) || PyUnicode_Check(file)) {
+ file = PyObject_CallFunction((PyObject *)&PyFile_Type,
+ "Os", file, "wb");
+ if (file==NULL) return NULL;
+ }
+ else {
+ Py_INCREF(file);
+ }
+ fd = PyFile_AsFile(file);
+ if (fd == NULL) {
+ PyErr_SetString(PyExc_IOError, "first argument must be a " \
+ "string or open file");
+ Py_DECREF(file);
+ return NULL;
+ }
+ ret = PyArray_ToFile(self, fd, sep, format);
+ Py_DECREF(file);
+ if (ret < 0) return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_toscalar(PyArrayObject *self, PyObject *args) {
- int n, nd;
- n = PyTuple_GET_SIZE(args);
-
- if (n==1) {
- PyObject *obj;
- obj = PyTuple_GET_ITEM(args, 0);
- if (PyTuple_Check(obj)) {
- args = obj;
- n = PyTuple_GET_SIZE(args);
- }
+ int n, nd;
+ n = PyTuple_GET_SIZE(args);
+
+ if (n==1) {
+ PyObject *obj;
+ obj = PyTuple_GET_ITEM(args, 0);
+ if (PyTuple_Check(obj)) {
+ args = obj;
+ n = PyTuple_GET_SIZE(args);
}
-
- if (n==0) {
- if (self->nd == 0 || PyArray_SIZE(self) == 1)
- return self->descr->f->getitem(self->data, self);
- else {
- PyErr_SetString(PyExc_ValueError,
- "can only convert an array " \
- " of size 1 to a Python scalar");
- return NULL;
- }
+ }
+
+ if (n==0) {
+ if (self->nd == 0 || PyArray_SIZE(self) == 1)
+ return self->descr->f->getitem(self->data, self);
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "can only convert an array " \
+ " of size 1 to a Python scalar");
+ return NULL;
}
- else if (n != self->nd && (n > 1 || self->nd==0)) {
- PyErr_SetString(PyExc_ValueError,
- "incorrect number of indices for " \
- "array");
- return NULL;
+ }
+ else if (n != self->nd && (n > 1 || self->nd==0)) {
+ PyErr_SetString(PyExc_ValueError,
+ "incorrect number of indices for " \
+ "array");
+ return NULL;
+ }
+ else if (n==1) { /* allows for flat getting as well as 1-d case */
+ intp value, loc, index, factor;
+ intp factors[MAX_DIMS];
+ value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, 0));
+ if (error_converting(value)) {
+ PyErr_SetString(PyExc_ValueError, "invalid integer");
+ return NULL;
}
- else if (n==1) { /* allows for flat getting as well as 1-d case */
- intp value, loc, index, factor;
- intp factors[MAX_DIMS];
- value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, 0));
- if (error_converting(value)) {
- PyErr_SetString(PyExc_ValueError, "invalid integer");
- return NULL;
- }
- factor = PyArray_SIZE(self);
- if (value < 0) value += factor;
- if ((value >= factor) || (value < 0)) {
- PyErr_SetString(PyExc_ValueError,
- "index out of bounds");
- return NULL;
- }
- if (self->nd == 1) {
- value *= self->strides[0];
- return self->descr->f->getitem(self->data + value,
- self);
- }
- nd = self->nd;
- factor = 1;
- while (nd--) {
- factors[nd] = factor;
- factor *= self->dimensions[nd];
- }
- loc = 0;
- for (nd=0; nd < self->nd; nd++) {
- index = value / factors[nd];
- value = value % factors[nd];
- loc += self->strides[nd]*index;
- }
-
- return self->descr->f->getitem(self->data + loc,
- self);
-
+ factor = PyArray_SIZE(self);
+ if (value < 0) value += factor;
+ if ((value >= factor) || (value < 0)) {
+ PyErr_SetString(PyExc_ValueError,
+ "index out of bounds");
+ return NULL;
}
- else {
- intp loc, index[MAX_DIMS];
- nd = PyArray_IntpFromSequence(args, index, MAX_DIMS);
- if (nd < n) return NULL;
- loc = 0;
- while (nd--) {
- if (index[nd] < 0)
- index[nd] += self->dimensions[nd];
- if (index[nd] < 0 ||
- index[nd] >= self->dimensions[nd]) {
- PyErr_SetString(PyExc_ValueError,
- "index out of bounds");
- return NULL;
- }
- loc += self->strides[nd]*index[nd];
- }
- return self->descr->f->getitem(self->data + loc, self);
+ if (self->nd == 1) {
+ value *= self->strides[0];
+ return self->descr->f->getitem(self->data + value,
+ self);
+ }
+ nd = self->nd;
+ factor = 1;
+ while (nd--) {
+ factors[nd] = factor;
+ factor *= self->dimensions[nd];
+ }
+ loc = 0;
+ for (nd=0; nd < self->nd; nd++) {
+ index = value / factors[nd];
+ value = value % factors[nd];
+ loc += self->strides[nd]*index;
+ }
+
+ return self->descr->f->getitem(self->data + loc,
+ self);
+
+ }
+ else {
+ intp loc, index[MAX_DIMS];
+ nd = PyArray_IntpFromSequence(args, index, MAX_DIMS);
+ if (nd < n) return NULL;
+ loc = 0;
+ while (nd--) {
+ if (index[nd] < 0)
+ index[nd] += self->dimensions[nd];
+ if (index[nd] < 0 ||
+ index[nd] >= self->dimensions[nd]) {
+ PyErr_SetString(PyExc_ValueError,
+ "index out of bounds");
+ return NULL;
+ }
+ loc += self->strides[nd]*index[nd];
}
+ return self->descr->f->getitem(self->data + loc, self);
+ }
}
static PyObject *
array_setscalar(PyArrayObject *self, PyObject *args) {
- int n, nd;
- int ret = -1;
- PyObject *obj;
- n = PyTuple_GET_SIZE(args)-1;
-
- if (n < 0) {
- PyErr_SetString(PyExc_ValueError,
- "itemset must have at least one argument");
- return NULL;
+ int n, nd;
+ int ret = -1;
+ PyObject *obj;
+ n = PyTuple_GET_SIZE(args)-1;
+
+ if (n < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "itemset must have at least one argument");
+ return NULL;
+ }
+ obj = PyTuple_GET_ITEM(args, n);
+ if (n==0) {
+ if (self->nd == 0 || PyArray_SIZE(self) == 1) {
+ ret = self->descr->f->setitem(obj, self->data, self);
}
- obj = PyTuple_GET_ITEM(args, n);
- if (n==0) {
- if (self->nd == 0 || PyArray_SIZE(self) == 1) {
- ret = self->descr->f->setitem(obj, self->data, self);
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "can only place a scalar for an "
- " array of size 1");
- return NULL;
- }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "can only place a scalar for an "
+ " array of size 1");
+ return NULL;
}
- else if (n != self->nd && (n > 1 || self->nd==0)) {
- PyErr_SetString(PyExc_ValueError,
- "incorrect number of indices for " \
- "array");
- return NULL;
+ }
+ else if (n != self->nd && (n > 1 || self->nd==0)) {
+ PyErr_SetString(PyExc_ValueError,
+ "incorrect number of indices for " \
+ "array");
+ return NULL;
+ }
+ else if (n==1) { /* allows for flat setting as well as 1-d case */
+ intp value, loc, index, factor;
+ intp factors[MAX_DIMS];
+ PyObject *indobj;
+
+ indobj = PyTuple_GET_ITEM(args, 0);
+ if (PyTuple_Check(indobj)) {
+ PyObject *res;
+ PyObject *newargs;
+ PyObject *tmp;
+ int i, nn;
+ nn = PyTuple_GET_SIZE(indobj);
+ newargs = PyTuple_New(nn+1);
+ Py_INCREF(obj);
+ for (i=0; i<nn; i++) {
+ tmp = PyTuple_GET_ITEM(indobj, i);
+ Py_INCREF(tmp);
+ PyTuple_SET_ITEM(newargs, i, tmp);
+ }
+ PyTuple_SET_ITEM(newargs, nn, obj);
+ /* Call with a converted set of arguments */
+ res = array_setscalar(self, newargs);
+ Py_DECREF(newargs);
+ return res;
}
- else if (n==1) { /* allows for flat setting as well as 1-d case */
- intp value, loc, index, factor;
- intp factors[MAX_DIMS];
- PyObject *indobj;
-
- indobj = PyTuple_GET_ITEM(args, 0);
- if (PyTuple_Check(indobj)) {
- PyObject *res;
- PyObject *newargs;
- PyObject *tmp;
- int i, nn;
- nn = PyTuple_GET_SIZE(indobj);
- newargs = PyTuple_New(nn+1);
- Py_INCREF(obj);
- for (i=0; i<nn; i++) {
- tmp = PyTuple_GET_ITEM(indobj, i);
- Py_INCREF(tmp);
- PyTuple_SET_ITEM(newargs, i, tmp);
- }
- PyTuple_SET_ITEM(newargs, nn, obj);
- /* Call with a converted set of arguments */
- res = array_setscalar(self, newargs);
- Py_DECREF(newargs);
- return res;
- }
- value = PyArray_PyIntAsIntp(indobj);
- if (error_converting(value)) {
- PyErr_SetString(PyExc_ValueError, "invalid integer");
- return NULL;
- }
- if (value >= PyArray_SIZE(self)) {
- PyErr_SetString(PyExc_ValueError,
- "index out of bounds");
- return NULL;
- }
- if (self->nd == 1) {
- value *= self->strides[0];
- ret = self->descr->f->setitem(obj, self->data + value,
- self);
- goto finish;
- }
- nd = self->nd;
- factor = 1;
- while (nd--) {
- factors[nd] = factor;
- factor *= self->dimensions[nd];
- }
- loc = 0;
- for (nd=0; nd < self->nd; nd++) {
- index = value / factors[nd];
- value = value % factors[nd];
- loc += self->strides[nd]*index;
- }
-
- ret = self->descr->f->setitem(obj, self->data + loc, self);
+ value = PyArray_PyIntAsIntp(indobj);
+ if (error_converting(value)) {
+ PyErr_SetString(PyExc_ValueError, "invalid integer");
+ return NULL;
}
- else {
- intp loc, index[MAX_DIMS];
- PyObject *tupargs;
- tupargs = PyTuple_GetSlice(args, 0, n);
- nd = PyArray_IntpFromSequence(tupargs, index, MAX_DIMS);
- Py_DECREF(tupargs);
- if (nd < n) return NULL;
- loc = 0;
- while (nd--) {
- if (index[nd] < 0)
- index[nd] += self->dimensions[nd];
- if (index[nd] < 0 ||
- index[nd] >= self->dimensions[nd]) {
- PyErr_SetString(PyExc_ValueError,
- "index out of bounds");
- return NULL;
- }
- loc += self->strides[nd]*index[nd];
- }
- ret = self->descr->f->setitem(obj, self->data + loc, self);
+ if (value >= PyArray_SIZE(self)) {
+ PyErr_SetString(PyExc_ValueError,
+ "index out of bounds");
+ return NULL;
+ }
+ if (self->nd == 1) {
+ value *= self->strides[0];
+ ret = self->descr->f->setitem(obj, self->data + value,
+ self);
+ goto finish;
+ }
+ nd = self->nd;
+ factor = 1;
+ while (nd--) {
+ factors[nd] = factor;
+ factor *= self->dimensions[nd];
}
+ loc = 0;
+ for (nd=0; nd < self->nd; nd++) {
+ index = value / factors[nd];
+ value = value % factors[nd];
+ loc += self->strides[nd]*index;
+ }
+
+ ret = self->descr->f->setitem(obj, self->data + loc, self);
+ }
+ else {
+ intp loc, index[MAX_DIMS];
+ PyObject *tupargs;
+ tupargs = PyTuple_GetSlice(args, 0, n);
+ nd = PyArray_IntpFromSequence(tupargs, index, MAX_DIMS);
+ Py_DECREF(tupargs);
+ if (nd < n) return NULL;
+ loc = 0;
+ while (nd--) {
+ if (index[nd] < 0)
+ index[nd] += self->dimensions[nd];
+ if (index[nd] < 0 ||
+ index[nd] >= self->dimensions[nd]) {
+ PyErr_SetString(PyExc_ValueError,
+ "index out of bounds");
+ return NULL;
+ }
+ loc += self->strides[nd]*index[nd];
+ }
+ ret = self->descr->f->setitem(obj, self->data + loc, self);
+ }
finish:
- if (ret < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (ret < 0) return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_cast(PyArrayObject *self, PyObject *args)
{
- PyArray_Descr *descr=NULL;
- PyObject *obj;
-
- if (!PyArg_ParseTuple(args, "O&", PyArray_DescrConverter,
- &descr)) return NULL;
-
- if (descr == self->descr) {
- obj = _ARET(PyArray_NewCopy(self,NPY_ANYORDER));
- Py_XDECREF(descr);
- return obj;
- }
- if (descr->names != NULL) {
- int flags;
- flags = NPY_FORCECAST;
- if (PyArray_ISFORTRAN(self)) {
- flags |= NPY_FORTRAN;
- }
- return PyArray_FromArray(self, descr, flags);
- }
- return PyArray_CastToType(self, descr, PyArray_ISFORTRAN(self));
+ PyArray_Descr *descr=NULL;
+ PyObject *obj;
+
+ if (!PyArg_ParseTuple(args, "O&", PyArray_DescrConverter,
+ &descr)) return NULL;
+
+ if (descr == self->descr) {
+ obj = _ARET(PyArray_NewCopy(self,NPY_ANYORDER));
+ Py_XDECREF(descr);
+ return obj;
+ }
+ if (descr->names != NULL) {
+ int flags;
+ flags = NPY_FORCECAST;
+ if (PyArray_ISFORTRAN(self)) {
+ flags |= NPY_FORTRAN;
+ }
+ return PyArray_FromArray(self, descr, flags);
+ }
+ return PyArray_CastToType(self, descr, PyArray_ISFORTRAN(self));
}
/* default sub-type implementation */
@@ -674,321 +673,321 @@ array_cast(PyArrayObject *self, PyObject *args)
static PyObject *
array_wraparray(PyArrayObject *self, PyObject *args)
{
- PyObject *arr;
- PyObject *ret;
-
- if (PyTuple_Size(args) < 1) {
- PyErr_SetString(PyExc_TypeError,
- "only accepts 1 argument");
- return NULL;
- }
- arr = PyTuple_GET_ITEM(args, 0);
- if (!PyArray_Check(arr)) {
- PyErr_SetString(PyExc_TypeError,
- "can only be called with ndarray object");
- return NULL;
- }
-
- Py_INCREF(PyArray_DESCR(arr));
- ret = PyArray_NewFromDescr(self->ob_type,
- PyArray_DESCR(arr),
- PyArray_NDIM(arr),
- PyArray_DIMS(arr),
- PyArray_STRIDES(arr), PyArray_DATA(arr),
- PyArray_FLAGS(arr), (PyObject *)self);
- if (ret == NULL) return NULL;
- Py_INCREF(arr);
- PyArray_BASE(ret) = arr;
- return ret;
+ PyObject *arr;
+ PyObject *ret;
+
+ if (PyTuple_Size(args) < 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "only accepts 1 argument");
+ return NULL;
+ }
+ arr = PyTuple_GET_ITEM(args, 0);
+ if (!PyArray_Check(arr)) {
+ PyErr_SetString(PyExc_TypeError,
+ "can only be called with ndarray object");
+ return NULL;
+ }
+
+ Py_INCREF(PyArray_DESCR(arr));
+ ret = PyArray_NewFromDescr(self->ob_type,
+ PyArray_DESCR(arr),
+ PyArray_NDIM(arr),
+ PyArray_DIMS(arr),
+ PyArray_STRIDES(arr), PyArray_DATA(arr),
+ PyArray_FLAGS(arr), (PyObject *)self);
+ if (ret == NULL) return NULL;
+ Py_INCREF(arr);
+ PyArray_BASE(ret) = arr;
+ return ret;
}
static PyObject *
array_getarray(PyArrayObject *self, PyObject *args)
{
- PyArray_Descr *newtype=NULL;
- PyObject *ret;
-
- if (!PyArg_ParseTuple(args, "|O&", PyArray_DescrConverter,
- &newtype)) return NULL;
-
- /* convert to PyArray_Type */
- if (!PyArray_CheckExact(self)) {
- PyObject *new;
- PyTypeObject *subtype = &PyArray_Type;
-
- if (!PyType_IsSubtype(self->ob_type, &PyArray_Type)) {
- subtype = &PyArray_Type;
- }
-
- Py_INCREF(PyArray_DESCR(self));
- new = PyArray_NewFromDescr(subtype,
- PyArray_DESCR(self),
- PyArray_NDIM(self),
- PyArray_DIMS(self),
- PyArray_STRIDES(self),
- PyArray_DATA(self),
- PyArray_FLAGS(self), NULL);
- if (new == NULL) return NULL;
- Py_INCREF(self);
- PyArray_BASE(new) = (PyObject *)self;
- self = (PyArrayObject *)new;
- }
- else {
- Py_INCREF(self);
- }
-
- if ((newtype == NULL) || \
- PyArray_EquivTypes(self->descr, newtype)) {
- return (PyObject *)self;
- }
- else {
- ret = PyArray_CastToType(self, newtype, 0);
- Py_DECREF(self);
- return ret;
- }
+ PyArray_Descr *newtype=NULL;
+ PyObject *ret;
+
+ if (!PyArg_ParseTuple(args, "|O&", PyArray_DescrConverter,
+ &newtype)) return NULL;
+
+ /* convert to PyArray_Type */
+ if (!PyArray_CheckExact(self)) {
+ PyObject *new;
+ PyTypeObject *subtype = &PyArray_Type;
+
+ if (!PyType_IsSubtype(self->ob_type, &PyArray_Type)) {
+ subtype = &PyArray_Type;
+ }
+
+ Py_INCREF(PyArray_DESCR(self));
+ new = PyArray_NewFromDescr(subtype,
+ PyArray_DESCR(self),
+ PyArray_NDIM(self),
+ PyArray_DIMS(self),
+ PyArray_STRIDES(self),
+ PyArray_DATA(self),
+ PyArray_FLAGS(self), NULL);
+ if (new == NULL) return NULL;
+ Py_INCREF(self);
+ PyArray_BASE(new) = (PyObject *)self;
+ self = (PyArrayObject *)new;
+ }
+ else {
+ Py_INCREF(self);
+ }
+
+ if ((newtype == NULL) || \
+ PyArray_EquivTypes(self->descr, newtype)) {
+ return (PyObject *)self;
+ }
+ else {
+ ret = PyArray_CastToType(self, newtype, 0);
+ Py_DECREF(self);
+ return ret;
+ }
}
static PyObject *
array_copy(PyArrayObject *self, PyObject *args)
{
- PyArray_ORDER fortran=PyArray_CORDER;
- if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter,
- &fortran)) return NULL;
+ PyArray_ORDER fortran=PyArray_CORDER;
+ if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter,
+ &fortran)) return NULL;
- return PyArray_NewCopy(self, fortran);
+ return PyArray_NewCopy(self, fortran);
}
static PyObject *
array_resize(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- PyArray_Dims newshape;
- PyObject *ret;
- int n;
- int refcheck = 1;
- PyArray_ORDER fortran=PyArray_ANYORDER;
-
- if (kwds != NULL) {
- PyObject *ref;
- ref = PyDict_GetItemString(kwds, "refcheck");
- if (ref) {
- refcheck = PyInt_AsLong(ref);
- if (refcheck==-1 && PyErr_Occurred()) {
- return NULL;
- }
- }
- ref = PyDict_GetItemString(kwds, "order");
- if (ref != NULL ||
- (PyArray_OrderConverter(ref, &fortran) == PY_FAIL))
- return NULL;
- }
- n = PyTuple_Size(args);
- if (n <= 1) {
- if (PyTuple_GET_ITEM(args, 0) == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter,
- &newshape)) return NULL;
- }
- else {
- if (!PyArray_IntpConverter(args, &newshape)) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "invalid shape");
- }
- return NULL;
- }
- }
- ret = PyArray_Resize(self, &newshape, refcheck, fortran);
- PyDimMem_FREE(newshape.ptr);
- if (ret == NULL) return NULL;
- Py_DECREF(ret);
- Py_INCREF(Py_None);
- return Py_None;
+ PyArray_Dims newshape;
+ PyObject *ret;
+ int n;
+ int refcheck = 1;
+ PyArray_ORDER fortran=PyArray_ANYORDER;
+
+ if (kwds != NULL) {
+ PyObject *ref;
+ ref = PyDict_GetItemString(kwds, "refcheck");
+ if (ref) {
+ refcheck = PyInt_AsLong(ref);
+ if (refcheck==-1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ }
+ ref = PyDict_GetItemString(kwds, "order");
+ if (ref != NULL ||
+ (PyArray_OrderConverter(ref, &fortran) == PY_FAIL))
+ return NULL;
+ }
+ n = PyTuple_Size(args);
+ if (n <= 1) {
+ if (PyTuple_GET_ITEM(args, 0) == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter,
+ &newshape)) return NULL;
+ }
+ else {
+ if (!PyArray_IntpConverter(args, &newshape)) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid shape");
+ }
+ return NULL;
+ }
+ }
+ ret = PyArray_Resize(self, &newshape, refcheck, fortran);
+ PyDimMem_FREE(newshape.ptr);
+ if (ret == NULL) return NULL;
+ Py_DECREF(ret);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_repeat(PyArrayObject *self, PyObject *args, PyObject *kwds) {
- PyObject *repeats;
- int axis=MAX_DIMS;
- static char *kwlist[] = {"repeats", "axis", NULL};
+ PyObject *repeats;
+ int axis=MAX_DIMS;
+ static char *kwlist[] = {"repeats", "axis", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist,
- &repeats, PyArray_AxisConverter,
- &axis)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist,
+ &repeats, PyArray_AxisConverter,
+ &axis)) return NULL;
- return _ARET(PyArray_Repeat(self, repeats, axis));
+ return _ARET(PyArray_Repeat(self, repeats, axis));
}
static PyObject *
array_choose(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *choices;
- int n;
- PyArrayObject *out=NULL;
- NPY_CLIPMODE clipmode=NPY_RAISE;
-
- n = PyTuple_Size(args);
- if (n <= 1) {
- if (!PyArg_ParseTuple(args, "O", &choices))
- return NULL;
- }
- else {
- choices = args;
- }
- if (kwds && PyDict_Check(kwds)) {
- if (PyArray_OutputConverter(PyDict_GetItemString(kwds,
- "out"),
- &out) == PY_FAIL)
- return NULL;
- if (PyArray_ClipmodeConverter(PyDict_GetItemString(kwds,
- "mode"),
- &clipmode) == PY_FAIL)
- return NULL;
- }
+ PyObject *choices;
+ int n;
+ PyArrayObject *out=NULL;
+ NPY_CLIPMODE clipmode=NPY_RAISE;
+
+ n = PyTuple_Size(args);
+ if (n <= 1) {
+ if (!PyArg_ParseTuple(args, "O", &choices))
+ return NULL;
+ }
+ else {
+ choices = args;
+ }
+ if (kwds && PyDict_Check(kwds)) {
+ if (PyArray_OutputConverter(PyDict_GetItemString(kwds,
+ "out"),
+ &out) == PY_FAIL)
+ return NULL;
+ if (PyArray_ClipmodeConverter(PyDict_GetItemString(kwds,
+ "mode"),
+ &clipmode) == PY_FAIL)
+ return NULL;
+ }
- return _ARET(PyArray_Choose(self, choices, out, clipmode));
+ return _ARET(PyArray_Choose(self, choices, out, clipmode));
}
static PyObject *
array_sort(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=-1;
- int val;
- PyArray_SORTKIND which=PyArray_QUICKSORT;
- PyObject *order=NULL;
- PyArray_Descr *saved=NULL;
- PyArray_Descr *newd;
- static char *kwlist[] = {"axis", "kind", "order", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&O", kwlist, &axis,
- PyArray_SortkindConverter, &which,
- &order))
- return NULL;
-
- if (order == Py_None) order = NULL;
- if (order != NULL) {
- PyObject *new_name;
- PyObject *_numpy_internal;
- saved = self->descr;
- if (saved->names == NULL) {
- PyErr_SetString(PyExc_ValueError, "Cannot specify " \
- "order when the array has no fields.");
- return NULL;
- }
- _numpy_internal = PyImport_ImportModule("numpy.core._internal");
- if (_numpy_internal == NULL) return NULL;
- new_name = PyObject_CallMethod(_numpy_internal, "_newnames",
- "OO", saved, order);
- Py_DECREF(_numpy_internal);
- if (new_name == NULL) return NULL;
- newd = PyArray_DescrNew(saved);
- newd->names = new_name;
- self->descr = newd;
- }
-
- val = PyArray_Sort(self, axis, which);
- if (order != NULL) {
- Py_XDECREF(self->descr);
- self->descr = saved;
+ int axis=-1;
+ int val;
+ PyArray_SORTKIND which=PyArray_QUICKSORT;
+ PyObject *order=NULL;
+ PyArray_Descr *saved=NULL;
+ PyArray_Descr *newd;
+ static char *kwlist[] = {"axis", "kind", "order", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&O", kwlist, &axis,
+ PyArray_SortkindConverter, &which,
+ &order))
+ return NULL;
+
+ if (order == Py_None) order = NULL;
+ if (order != NULL) {
+ PyObject *new_name;
+ PyObject *_numpy_internal;
+ saved = self->descr;
+ if (saved->names == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Cannot specify " \
+ "order when the array has no fields.");
+ return NULL;
}
- if (val < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ _numpy_internal = PyImport_ImportModule("numpy.core._internal");
+ if (_numpy_internal == NULL) return NULL;
+ new_name = PyObject_CallMethod(_numpy_internal, "_newnames",
+ "OO", saved, order);
+ Py_DECREF(_numpy_internal);
+ if (new_name == NULL) return NULL;
+ newd = PyArray_DescrNew(saved);
+ newd->names = new_name;
+ self->descr = newd;
+ }
+
+ val = PyArray_Sort(self, axis, which);
+ if (order != NULL) {
+ Py_XDECREF(self->descr);
+ self->descr = saved;
+ }
+ if (val < 0) return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_argsort(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=-1;
- PyArray_SORTKIND which=PyArray_QUICKSORT;
- PyObject *order=NULL, *res;
- PyArray_Descr *newd, *saved=NULL;
- static char *kwlist[] = {"axis", "kind", "order", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O", kwlist,
- PyArray_AxisConverter, &axis,
- PyArray_SortkindConverter, &which,
- &order))
- return NULL;
-
- if (order == Py_None) order = NULL;
- if (order != NULL) {
- PyObject *new_name;
- PyObject *_numpy_internal;
- saved = self->descr;
- if (saved->names == NULL) {
- PyErr_SetString(PyExc_ValueError, "Cannot specify " \
- "order when the array has no fields.");
- return NULL;
- }
- _numpy_internal = PyImport_ImportModule("numpy.core._internal");
- if (_numpy_internal == NULL) return NULL;
- new_name = PyObject_CallMethod(_numpy_internal, "_newnames",
- "OO", saved, order);
- Py_DECREF(_numpy_internal);
- if (new_name == NULL) return NULL;
- newd = PyArray_DescrNew(saved);
- newd->names = new_name;
- self->descr = newd;
- }
-
- res = PyArray_ArgSort(self, axis, which);
- if (order != NULL) {
- Py_XDECREF(self->descr);
- self->descr = saved;
+ int axis=-1;
+ PyArray_SORTKIND which=PyArray_QUICKSORT;
+ PyObject *order=NULL, *res;
+ PyArray_Descr *newd, *saved=NULL;
+ static char *kwlist[] = {"axis", "kind", "order", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O", kwlist,
+ PyArray_AxisConverter, &axis,
+ PyArray_SortkindConverter, &which,
+ &order))
+ return NULL;
+
+ if (order == Py_None) order = NULL;
+ if (order != NULL) {
+ PyObject *new_name;
+ PyObject *_numpy_internal;
+ saved = self->descr;
+ if (saved->names == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Cannot specify " \
+ "order when the array has no fields.");
+ return NULL;
}
- return _ARET(res);
+ _numpy_internal = PyImport_ImportModule("numpy.core._internal");
+ if (_numpy_internal == NULL) return NULL;
+ new_name = PyObject_CallMethod(_numpy_internal, "_newnames",
+ "OO", saved, order);
+ Py_DECREF(_numpy_internal);
+ if (new_name == NULL) return NULL;
+ newd = PyArray_DescrNew(saved);
+ newd->names = new_name;
+ self->descr = newd;
+ }
+
+ res = PyArray_ArgSort(self, axis, which);
+ if (order != NULL) {
+ Py_XDECREF(self->descr);
+ self->descr = saved;
+ }
+ return _ARET(res);
}
static PyObject *
array_searchsorted(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"keys", "side", NULL};
- PyObject *keys;
- NPY_SEARCHSIDE side = NPY_SEARCHLEFT;
+ static char *kwlist[] = {"keys", "side", NULL};
+ PyObject *keys;
+ NPY_SEARCHSIDE side = NPY_SEARCHLEFT;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&:searchsorted",
- kwlist, &keys,
- PyArray_SearchsideConverter, &side))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&:searchsorted",
+ kwlist, &keys,
+ PyArray_SearchsideConverter, &side))
+ return NULL;
- return _ARET(PyArray_SearchSorted(self, keys, side));
+ return _ARET(PyArray_SearchSorted(self, keys, side));
}
static void
_deepcopy_call(char *iptr, char *optr, PyArray_Descr *dtype,
- PyObject *deepcopy, PyObject *visit)
+ PyObject *deepcopy, PyObject *visit)
{
- if (!PyDataType_REFCHK(dtype)) return;
- else if (PyDescr_HASFIELDS(dtype)) {
- PyObject *key, *value, *title=NULL;
- PyArray_Descr *new;
- int offset;
- Py_ssize_t pos=0;
- while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
- if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
- &title)) return;
- _deepcopy_call(iptr + offset, optr + offset, new,
- deepcopy, visit);
- }
+ if (!PyDataType_REFCHK(dtype)) return;
+ else if (PyDescr_HASFIELDS(dtype)) {
+ PyObject *key, *value, *title=NULL;
+ PyArray_Descr *new;
+ int offset;
+ Py_ssize_t pos=0;
+ while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
+ if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
+ &title)) return;
+ _deepcopy_call(iptr + offset, optr + offset, new,
+ deepcopy, visit);
}
- else {
- PyObject **itemp, **otemp;
- PyObject *res;
- itemp = (PyObject **)iptr;
- otemp = (PyObject **)optr;
- Py_XINCREF(*itemp);
- /* call deepcopy on this argument */
- res = PyObject_CallFunctionObjArgs(deepcopy,
- *itemp, visit, NULL);
- Py_XDECREF(*itemp);
- Py_XDECREF(*otemp);
- *otemp = res;
- }
+ }
+ else {
+ PyObject **itemp, **otemp;
+ PyObject *res;
+ itemp = (PyObject **)iptr;
+ otemp = (PyObject **)optr;
+ Py_XINCREF(*itemp);
+ /* call deepcopy on this argument */
+ res = PyObject_CallFunctionObjArgs(deepcopy,
+ *itemp, visit, NULL);
+ Py_XDECREF(*itemp);
+ Py_XDECREF(*otemp);
+ *otemp = res;
+ }
}
@@ -996,148 +995,148 @@ _deepcopy_call(char *iptr, char *optr, PyArray_Descr *dtype,
static PyObject *
array_deepcopy(PyArrayObject *self, PyObject *args)
{
- PyObject* visit;
- char *optr;
- PyArrayIterObject *it;
- PyObject *copy, *ret, *deepcopy;
-
- if (!PyArg_ParseTuple(args, "O", &visit)) return NULL;
- ret = PyArray_Copy(self);
- if (PyDataType_REFCHK(self->descr)) {
- copy = PyImport_ImportModule("copy");
- if (copy == NULL) return NULL;
- deepcopy = PyObject_GetAttrString(copy, "deepcopy");
- Py_DECREF(copy);
- if (deepcopy == NULL) return NULL;
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
- if (it == NULL) {Py_DECREF(deepcopy); return NULL;}
- optr = PyArray_DATA(ret);
- while(it->index < it->size) {
- _deepcopy_call(it->dataptr, optr, self->descr,
- deepcopy, visit);
- optr += self->descr->elsize;
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(deepcopy);
- Py_DECREF(it);
+ PyObject* visit;
+ char *optr;
+ PyArrayIterObject *it;
+ PyObject *copy, *ret, *deepcopy;
+
+ if (!PyArg_ParseTuple(args, "O", &visit)) return NULL;
+ ret = PyArray_Copy(self);
+ if (PyDataType_REFCHK(self->descr)) {
+ copy = PyImport_ImportModule("copy");
+ if (copy == NULL) return NULL;
+ deepcopy = PyObject_GetAttrString(copy, "deepcopy");
+ Py_DECREF(copy);
+ if (deepcopy == NULL) return NULL;
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
+ if (it == NULL) {Py_DECREF(deepcopy); return NULL;}
+ optr = PyArray_DATA(ret);
+ while(it->index < it->size) {
+ _deepcopy_call(it->dataptr, optr, self->descr,
+ deepcopy, visit);
+ optr += self->descr->elsize;
+ PyArray_ITER_NEXT(it);
}
- return _ARET(ret);
+ Py_DECREF(deepcopy);
+ Py_DECREF(it);
+ }
+ return _ARET(ret);
}
/* Convert Array to flat list (using getitem) */
static PyObject *
_getlist_pkl(PyArrayObject *self)
{
- PyObject *theobject;
- PyArrayIterObject *iter=NULL;
- PyObject *list;
- PyArray_GetItemFunc *getitem;
-
- getitem = self->descr->f->getitem;
- iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
- if (iter == NULL) return NULL;
- list = PyList_New(iter->size);
- if (list == NULL) {Py_DECREF(iter); return NULL;}
- while (iter->index < iter->size) {
- theobject = getitem(iter->dataptr, self);
- PyList_SET_ITEM(list, (int) iter->index, theobject);
- PyArray_ITER_NEXT(iter);
- }
- Py_DECREF(iter);
- return list;
+ PyObject *theobject;
+ PyArrayIterObject *iter=NULL;
+ PyObject *list;
+ PyArray_GetItemFunc *getitem;
+
+ getitem = self->descr->f->getitem;
+ iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
+ if (iter == NULL) return NULL;
+ list = PyList_New(iter->size);
+ if (list == NULL) {Py_DECREF(iter); return NULL;}
+ while (iter->index < iter->size) {
+ theobject = getitem(iter->dataptr, self);
+ PyList_SET_ITEM(list, (int) iter->index, theobject);
+ PyArray_ITER_NEXT(iter);
+ }
+ Py_DECREF(iter);
+ return list;
}
static int
_setlist_pkl(PyArrayObject *self, PyObject *list)
{
- PyObject *theobject;
- PyArrayIterObject *iter=NULL;
- PyArray_SetItemFunc *setitem;
+ PyObject *theobject;
+ PyArrayIterObject *iter=NULL;
+ PyArray_SetItemFunc *setitem;
- setitem = self->descr->f->setitem;
- iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
- if (iter == NULL) return -1;
- while(iter->index < iter->size) {
- theobject = PyList_GET_ITEM(list, (int) iter->index);
- setitem(theobject, iter->dataptr, self);
- PyArray_ITER_NEXT(iter);
- }
- Py_XDECREF(iter);
- return 0;
+ setitem = self->descr->f->setitem;
+ iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
+ if (iter == NULL) return -1;
+ while(iter->index < iter->size) {
+ theobject = PyList_GET_ITEM(list, (int) iter->index);
+ setitem(theobject, iter->dataptr, self);
+ PyArray_ITER_NEXT(iter);
+ }
+ Py_XDECREF(iter);
+ return 0;
}
static PyObject *
array_reduce(PyArrayObject *self, PyObject *args)
{
- /* version number of this pickle type. Increment if we need to
- change the format. Be sure to handle the old versions in
- array_setstate. */
- const int version = 1;
- PyObject *ret=NULL, *state=NULL, *obj=NULL, *mod=NULL;
- PyObject *mybool, *thestr=NULL;
- PyArray_Descr *descr;
-
- /* Return a tuple of (callable object, arguments, object's state) */
- /* We will put everything in the object's state, so that on UnPickle
- it can use the string object as memory without a copy */
-
- ret = PyTuple_New(3);
- if (ret == NULL) return NULL;
- mod = PyImport_ImportModule("numpy.core.multiarray");
- if (mod == NULL) {Py_DECREF(ret); return NULL;}
- obj = PyObject_GetAttrString(mod, "_reconstruct");
- Py_DECREF(mod);
- PyTuple_SET_ITEM(ret, 0, obj);
- PyTuple_SET_ITEM(ret, 1,
- Py_BuildValue("ONc",
- (PyObject *)self->ob_type,
- Py_BuildValue("(N)",
- PyInt_FromLong(0)),
- /* dummy data-type */
- 'b'));
-
- /* Now fill in object's state. This is a tuple with
- 5 arguments
-
- 1) an integer with the pickle version.
- 2) a Tuple giving the shape
- 3) a PyArray_Descr Object (with correct bytorder set)
- 4) a Bool stating if Fortran or not
- 5) a Python object representing the data (a string, or
- a list or any user-defined object).
-
- Notice because Python does not describe a mechanism to write
- raw data to the pickle, this performs a copy to a string first
- */
-
- state = PyTuple_New(5);
- if (state == NULL) {
- Py_DECREF(ret); return NULL;
- }
- PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version));
- PyTuple_SET_ITEM(state, 1, PyObject_GetAttrString((PyObject *)self,
- "shape"));
- descr = self->descr;
- Py_INCREF(descr);
- PyTuple_SET_ITEM(state, 2, (PyObject *)descr);
- mybool = (PyArray_ISFORTRAN(self) ? Py_True : Py_False);
- Py_INCREF(mybool);
- PyTuple_SET_ITEM(state, 3, mybool);
- if (PyDataType_FLAGCHK(self->descr, NPY_LIST_PICKLE)) {
- thestr = _getlist_pkl(self);
- }
- else {
- thestr = PyArray_ToString(self, NPY_ANYORDER);
- }
- if (thestr == NULL) {
- Py_DECREF(ret);
- Py_DECREF(state);
- return NULL;
- }
- PyTuple_SET_ITEM(state, 4, thestr);
- PyTuple_SET_ITEM(ret, 2, state);
- return ret;
+ /* version number of this pickle type. Increment if we need to
+ change the format. Be sure to handle the old versions in
+ array_setstate. */
+ const int version = 1;
+ PyObject *ret=NULL, *state=NULL, *obj=NULL, *mod=NULL;
+ PyObject *mybool, *thestr=NULL;
+ PyArray_Descr *descr;
+
+ /* Return a tuple of (callable object, arguments, object's state) */
+ /* We will put everything in the object's state, so that on UnPickle
+ it can use the string object as memory without a copy */
+
+ ret = PyTuple_New(3);
+ if (ret == NULL) return NULL;
+ mod = PyImport_ImportModule("numpy.core.multiarray");
+ if (mod == NULL) {Py_DECREF(ret); return NULL;}
+ obj = PyObject_GetAttrString(mod, "_reconstruct");
+ Py_DECREF(mod);
+ PyTuple_SET_ITEM(ret, 0, obj);
+ PyTuple_SET_ITEM(ret, 1,
+ Py_BuildValue("ONc",
+ (PyObject *)self->ob_type,
+ Py_BuildValue("(N)",
+ PyInt_FromLong(0)),
+ /* dummy data-type */
+ 'b'));
+
+ /* Now fill in object's state. This is a tuple with
+ 5 arguments
+
+ 1) an integer with the pickle version.
+ 2) a Tuple giving the shape
+ 3) a PyArray_Descr Object (with correct bytorder set)
+ 4) a Bool stating if Fortran or not
+ 5) a Python object representing the data (a string, or
+ a list or any user-defined object).
+
+ Notice because Python does not describe a mechanism to write
+ raw data to the pickle, this performs a copy to a string first
+ */
+
+ state = PyTuple_New(5);
+ if (state == NULL) {
+ Py_DECREF(ret); return NULL;
+ }
+ PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version));
+ PyTuple_SET_ITEM(state, 1, PyObject_GetAttrString((PyObject *)self,
+ "shape"));
+ descr = self->descr;
+ Py_INCREF(descr);
+ PyTuple_SET_ITEM(state, 2, (PyObject *)descr);
+ mybool = (PyArray_ISFORTRAN(self) ? Py_True : Py_False);
+ Py_INCREF(mybool);
+ PyTuple_SET_ITEM(state, 3, mybool);
+ if (PyDataType_FLAGCHK(self->descr, NPY_LIST_PICKLE)) {
+ thestr = _getlist_pkl(self);
+ }
+ else {
+ thestr = PyArray_ToString(self, NPY_ANYORDER);
+ }
+ if (thestr == NULL) {
+ Py_DECREF(ret);
+ Py_DECREF(state);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(state, 4, thestr);
+ PyTuple_SET_ITEM(ret, 2, state);
+ return ret;
}
@@ -1151,275 +1150,275 @@ static PyArray_Descr * _array_typedescr_fromstr(char *);
static PyObject *
array_setstate(PyArrayObject *self, PyObject *args)
{
- PyObject *shape;
- PyArray_Descr *typecode;
- int version = 1;
- int fortran;
- PyObject *rawdata;
- char *datastr;
- Py_ssize_t len;
- intp size, dimensions[MAX_DIMS];
- int nd;
-
- /* This will free any memory associated with a and
- use the string in setstate as the (writeable) memory.
- */
- if (!PyArg_ParseTuple(args, "(iO!O!iO)", &version, &PyTuple_Type,
- &shape, &PyArrayDescr_Type, &typecode,
- &fortran, &rawdata)) {
- PyErr_Clear();
- version = 0;
- if (!PyArg_ParseTuple(args, "(O!O!iO)", &PyTuple_Type,
- &shape, &PyArrayDescr_Type, &typecode,
- &fortran, &rawdata)) {
- return NULL;
- }
+ PyObject *shape;
+ PyArray_Descr *typecode;
+ int version = 1;
+ int fortran;
+ PyObject *rawdata;
+ char *datastr;
+ Py_ssize_t len;
+ intp size, dimensions[MAX_DIMS];
+ int nd;
+
+ /* This will free any memory associated with a and
+ use the string in setstate as the (writeable) memory.
+ */
+ if (!PyArg_ParseTuple(args, "(iO!O!iO)", &version, &PyTuple_Type,
+ &shape, &PyArrayDescr_Type, &typecode,
+ &fortran, &rawdata)) {
+ PyErr_Clear();
+ version = 0;
+ if (!PyArg_ParseTuple(args, "(O!O!iO)", &PyTuple_Type,
+ &shape, &PyArrayDescr_Type, &typecode,
+ &fortran, &rawdata)) {
+ return NULL;
}
-
- /* If we ever need another pickle format, increment the version
- number. But we should still be able to handle the old versions.
- We've only got one right now. */
- if (version != 1 && version != 0) {
- PyErr_Format(PyExc_ValueError,
- "can't handle version %d of numpy.ndarray pickle",
- version);
+ }
+
+ /* If we ever need another pickle format, increment the version
+ number. But we should still be able to handle the old versions.
+ We've only got one right now. */
+ if (version != 1 && version != 0) {
+ PyErr_Format(PyExc_ValueError,
+ "can't handle version %d of numpy.ndarray pickle",
+ version);
+ return NULL;
+ }
+
+ Py_XDECREF(self->descr);
+ self->descr = typecode;
+ Py_INCREF(typecode);
+ nd = PyArray_IntpFromSequence(shape, dimensions, MAX_DIMS);
+ if (nd < 0) return NULL;
+ size = PyArray_MultiplyList(dimensions, nd);
+ if (self->descr->elsize == 0) {
+ PyErr_SetString(PyExc_ValueError, "Invalid data-type size.");
+ return NULL;
+ }
+ if (size < 0 || size > MAX_INTP / self->descr->elsize) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ if (PyDataType_FLAGCHK(typecode, NPY_LIST_PICKLE)) {
+ if (!PyList_Check(rawdata)) {
+ PyErr_SetString(PyExc_TypeError,
+ "object pickle not returning list");
return NULL;
}
-
- Py_XDECREF(self->descr);
- self->descr = typecode;
- Py_INCREF(typecode);
- nd = PyArray_IntpFromSequence(shape, dimensions, MAX_DIMS);
- if (nd < 0) return NULL;
- size = PyArray_MultiplyList(dimensions, nd);
- if (self->descr->elsize == 0) {
- PyErr_SetString(PyExc_ValueError, "Invalid data-type size.");
- return NULL;
- }
- if (size < 0 || size > MAX_INTP / self->descr->elsize) {
- PyErr_NoMemory();
- return NULL;
- }
-
- if (PyDataType_FLAGCHK(typecode, NPY_LIST_PICKLE)) {
- if (!PyList_Check(rawdata)) {
- PyErr_SetString(PyExc_TypeError,
- "object pickle not returning list");
- return NULL;
- }
- }
- else {
- if (!PyString_Check(rawdata)) {
- PyErr_SetString(PyExc_TypeError,
- "pickle not returning string");
- return NULL;
- }
-
- if (PyString_AsStringAndSize(rawdata, &datastr, &len))
- return NULL;
-
- if ((len != (self->descr->elsize * size))) {
- PyErr_SetString(PyExc_ValueError,
- "buffer size does not" \
- " match array size");
- return NULL;
- }
- }
-
- if ((self->flags & OWNDATA)) {
- if (self->data != NULL)
- PyDataMem_FREE(self->data);
- self->flags &= ~OWNDATA;
+ }
+ else {
+ if (!PyString_Check(rawdata)) {
+ PyErr_SetString(PyExc_TypeError,
+ "pickle not returning string");
+ return NULL;
}
- Py_XDECREF(self->base);
- self->flags &= ~UPDATEIFCOPY;
+ if (PyString_AsStringAndSize(rawdata, &datastr, &len))
+ return NULL;
- if (self->dimensions != NULL) {
+ if ((len != (self->descr->elsize * size))) {
+ PyErr_SetString(PyExc_ValueError,
+ "buffer size does not" \
+ " match array size");
+ return NULL;
+ }
+ }
+
+ if ((self->flags & OWNDATA)) {
+ if (self->data != NULL)
+ PyDataMem_FREE(self->data);
+ self->flags &= ~OWNDATA;
+ }
+ Py_XDECREF(self->base);
+
+ self->flags &= ~UPDATEIFCOPY;
+
+ if (self->dimensions != NULL) {
+ PyDimMem_FREE(self->dimensions);
+ self->dimensions = NULL;
+ }
+
+ self->flags = DEFAULT;
+
+ self->nd = nd;
+
+ if (nd > 0) {
+ self->dimensions = PyDimMem_NEW(nd * 2);
+ self->strides = self->dimensions + nd;
+ memcpy(self->dimensions, dimensions, sizeof(intp)*nd);
+ (void) _array_fill_strides(self->strides, dimensions, nd,
+ (size_t) self->descr->elsize,
+ (fortran ? FORTRAN : CONTIGUOUS),
+ &(self->flags));
+ }
+
+ if (!PyDataType_FLAGCHK(typecode, NPY_LIST_PICKLE)) {
+ int swap=!PyArray_ISNOTSWAPPED(self);
+ self->data = datastr;
+ if (!_IsAligned(self) || swap) {
+ intp num = PyArray_NBYTES(self);
+ self->data = PyDataMem_NEW(num);
+ if (self->data == NULL) {
+ self->nd = 0;
PyDimMem_FREE(self->dimensions);
- self->dimensions = NULL;
- }
-
- self->flags = DEFAULT;
-
- self->nd = nd;
-
- if (nd > 0) {
- self->dimensions = PyDimMem_NEW(nd * 2);
- self->strides = self->dimensions + nd;
- memcpy(self->dimensions, dimensions, sizeof(intp)*nd);
- (void) _array_fill_strides(self->strides, dimensions, nd,
- (size_t) self->descr->elsize,
- (fortran ? FORTRAN : CONTIGUOUS),
- &(self->flags));
- }
-
- if (!PyDataType_FLAGCHK(typecode, NPY_LIST_PICKLE)) {
- int swap=!PyArray_ISNOTSWAPPED(self);
- self->data = datastr;
- if (!_IsAligned(self) || swap) {
- intp num = PyArray_NBYTES(self);
- self->data = PyDataMem_NEW(num);
- if (self->data == NULL) {
- self->nd = 0;
- PyDimMem_FREE(self->dimensions);
- return PyErr_NoMemory();
- }
- if (swap) { /* byte-swap on pickle-read */
- intp numels = num / self->descr->elsize;
- self->descr->f->copyswapn(self->data, self->descr->elsize,
- datastr, self->descr->elsize,
- numels, 1, self);
- if (!PyArray_ISEXTENDED(self)) {
- self->descr = PyArray_DescrFromType(self->descr->type_num);
- }
- else {
- self->descr = PyArray_DescrNew(typecode);
- if (self->descr->byteorder == PyArray_BIG)
- self->descr->byteorder = PyArray_LITTLE;
- else if (self->descr->byteorder == PyArray_LITTLE)
- self->descr->byteorder = PyArray_BIG;
- }
- Py_DECREF(typecode);
- }
- else {
- memcpy(self->data, datastr, num);
- }
- self->flags |= OWNDATA;
- self->base = NULL;
- }
- else {
- self->base = rawdata;
- Py_INCREF(self->base);
- }
- }
- else {
- self->data = PyDataMem_NEW(PyArray_NBYTES(self));
- if (self->data == NULL) {
- self->nd = 0;
- self->data = PyDataMem_NEW(self->descr->elsize);
- if (self->dimensions) PyDimMem_FREE(self->dimensions);
- return PyErr_NoMemory();
- }
- if (PyDataType_FLAGCHK(self->descr, NPY_NEEDS_INIT))
- memset(self->data, 0, PyArray_NBYTES(self));
- self->flags |= OWNDATA;
- self->base = NULL;
- if (_setlist_pkl(self, rawdata) < 0)
- return NULL;
- }
-
- PyArray_UpdateFlags(self, UPDATE_ALL);
-
- Py_INCREF(Py_None);
- return Py_None;
+ return PyErr_NoMemory();
+ }
+ if (swap) { /* byte-swap on pickle-read */
+ intp numels = num / self->descr->elsize;
+ self->descr->f->copyswapn(self->data, self->descr->elsize,
+ datastr, self->descr->elsize,
+ numels, 1, self);
+ if (!PyArray_ISEXTENDED(self)) {
+ self->descr = PyArray_DescrFromType(self->descr->type_num);
+ }
+ else {
+ self->descr = PyArray_DescrNew(typecode);
+ if (self->descr->byteorder == PyArray_BIG)
+ self->descr->byteorder = PyArray_LITTLE;
+ else if (self->descr->byteorder == PyArray_LITTLE)
+ self->descr->byteorder = PyArray_BIG;
+ }
+ Py_DECREF(typecode);
+ }
+ else {
+ memcpy(self->data, datastr, num);
+ }
+ self->flags |= OWNDATA;
+ self->base = NULL;
+ }
+ else {
+ self->base = rawdata;
+ Py_INCREF(self->base);
+ }
+ }
+ else {
+ self->data = PyDataMem_NEW(PyArray_NBYTES(self));
+ if (self->data == NULL) {
+ self->nd = 0;
+ self->data = PyDataMem_NEW(self->descr->elsize);
+ if (self->dimensions) PyDimMem_FREE(self->dimensions);
+ return PyErr_NoMemory();
+ }
+ if (PyDataType_FLAGCHK(self->descr, NPY_NEEDS_INIT))
+ memset(self->data, 0, PyArray_NBYTES(self));
+ self->flags |= OWNDATA;
+ self->base = NULL;
+ if (_setlist_pkl(self, rawdata) < 0)
+ return NULL;
+ }
+
+ PyArray_UpdateFlags(self, UPDATE_ALL);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/*OBJECT_API*/
static int
PyArray_Dump(PyObject *self, PyObject *file, int protocol)
{
- PyObject *cpick=NULL;
- PyObject *ret;
- if (protocol < 0) protocol = 2;
-
- cpick = PyImport_ImportModule("cPickle");
- if (cpick==NULL) return -1;
-
- if PyString_Check(file) {
- file = PyFile_FromString(PyString_AS_STRING(file), "wb");
- if (file==NULL) return -1;
- }
- else Py_INCREF(file);
- ret = PyObject_CallMethod(cpick, "dump", "OOi", self,
- file, protocol);
- Py_XDECREF(ret);
- Py_DECREF(file);
- Py_DECREF(cpick);
- if (PyErr_Occurred()) return -1;
- return 0;
+ PyObject *cpick=NULL;
+ PyObject *ret;
+ if (protocol < 0) protocol = 2;
+
+ cpick = PyImport_ImportModule("cPickle");
+ if (cpick==NULL) return -1;
+
+ if PyString_Check(file) {
+ file = PyFile_FromString(PyString_AS_STRING(file), "wb");
+ if (file==NULL) return -1;
+ }
+ else Py_INCREF(file);
+ ret = PyObject_CallMethod(cpick, "dump", "OOi", self,
+ file, protocol);
+ Py_XDECREF(ret);
+ Py_DECREF(file);
+ Py_DECREF(cpick);
+ if (PyErr_Occurred()) return -1;
+ return 0;
}
/*OBJECT_API*/
static PyObject *
PyArray_Dumps(PyObject *self, int protocol)
{
- PyObject *cpick=NULL;
- PyObject *ret;
- if (protocol < 0) protocol = 2;
+ PyObject *cpick=NULL;
+ PyObject *ret;
+ if (protocol < 0) protocol = 2;
- cpick = PyImport_ImportModule("cPickle");
- if (cpick==NULL) return NULL;
- ret = PyObject_CallMethod(cpick, "dumps", "Oi", self, protocol);
- Py_DECREF(cpick);
- return ret;
+ cpick = PyImport_ImportModule("cPickle");
+ if (cpick==NULL) return NULL;
+ ret = PyObject_CallMethod(cpick, "dumps", "Oi", self, protocol);
+ Py_DECREF(cpick);
+ return ret;
}
static PyObject *
array_dump(PyArrayObject *self, PyObject *args)
{
- PyObject *file=NULL;
- int ret;
+ PyObject *file=NULL;
+ int ret;
- if (!PyArg_ParseTuple(args, "O", &file))
- return NULL;
- ret = PyArray_Dump((PyObject *)self, file, 2);
- if (ret < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "O", &file))
+ return NULL;
+ ret = PyArray_Dump((PyObject *)self, file, 2);
+ if (ret < 0) return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_dumps(PyArrayObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- return PyArray_Dumps((PyObject *)self, 2);
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ return PyArray_Dumps((PyObject *)self, 2);
}
static PyObject *
array_transpose(PyArrayObject *self, PyObject *args)
{
- PyObject *shape=Py_None;
- int n;
- PyArray_Dims permute;
- PyObject *ret;
+ PyObject *shape=Py_None;
+ int n;
+ PyArray_Dims permute;
+ PyObject *ret;
- n = PyTuple_Size(args);
- if (n > 1) shape = args;
- else if (n == 1) shape = PyTuple_GET_ITEM(args, 0);
+ n = PyTuple_Size(args);
+ if (n > 1) shape = args;
+ else if (n == 1) shape = PyTuple_GET_ITEM(args, 0);
- if (shape == Py_None)
- ret = PyArray_Transpose(self, NULL);
- else {
- if (!PyArray_IntpConverter(shape, &permute)) return NULL;
- ret = PyArray_Transpose(self, &permute);
- PyDimMem_FREE(permute.ptr);
- }
+ if (shape == Py_None)
+ ret = PyArray_Transpose(self, NULL);
+ else {
+ if (!PyArray_IntpConverter(shape, &permute)) return NULL;
+ ret = PyArray_Transpose(self, &permute);
+ PyDimMem_FREE(permute.ptr);
+ }
- return ret;
+ return ret;
}
-/* Return typenumber from dtype2 unless it is NULL, then return
+/* Return typenumber from dtype2 unless it is NULL, then return
NPY_DOUBLE if dtype1->type_num is integer or bool
- and dtype1->type_num otherwise.
+ and dtype1->type_num otherwise.
*/
static int
_get_type_num_double(PyArray_Descr *dtype1, PyArray_Descr *dtype2)
{
- if (dtype2 != NULL)
- return dtype2->type_num;
-
- /* For integer or bool data-types */
- if (dtype1->type_num < NPY_FLOAT) {
- return NPY_DOUBLE;
- }
- else {
- return dtype1->type_num;
- }
+ if (dtype2 != NULL)
+ return dtype2->type_num;
+
+ /* For integer or bool data-types */
+ if (dtype1->type_num < NPY_FLOAT) {
+ return NPY_DOUBLE;
+ }
+ else {
+ return dtype1->type_num;
+ }
}
#define _CHKTYPENUM(typ) ((typ) ? (typ)->type_num : PyArray_NOTYPE)
@@ -1427,218 +1426,218 @@ _get_type_num_double(PyArray_Descr *dtype1, PyArray_Descr *dtype2)
static PyObject *
array_mean(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- int num;
- static char *kwlist[] = {"axis", "dtype", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ int num;
+ static char *kwlist[] = {"axis", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
- PyArray_AxisConverter,
- &axis, PyArray_DescrConverter2,
- &dtype,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis, PyArray_DescrConverter2,
+ &dtype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- num = _get_type_num_double(self->descr, dtype);
- return PyArray_Mean(self, axis, num, out);
+ num = _get_type_num_double(self->descr, dtype);
+ return PyArray_Mean(self, axis, num, out);
}
static PyObject *
array_sum(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "dtype", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
- PyArray_AxisConverter,
- &axis, PyArray_DescrConverter2,
- &dtype,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis, PyArray_DescrConverter2,
+ &dtype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- return PyArray_Sum(self, axis, _CHKTYPENUM(dtype), out);
+ return PyArray_Sum(self, axis, _CHKTYPENUM(dtype), out);
}
static PyObject *
array_cumsum(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "dtype", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
- PyArray_AxisConverter,
- &axis, PyArray_DescrConverter2,
- &dtype,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis, PyArray_DescrConverter2,
+ &dtype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- return PyArray_CumSum(self, axis, _CHKTYPENUM(dtype), out);
+ return PyArray_CumSum(self, axis, _CHKTYPENUM(dtype), out);
}
static PyObject *
array_prod(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "dtype", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
- PyArray_AxisConverter,
- &axis, PyArray_DescrConverter2,
- &dtype,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis, PyArray_DescrConverter2,
+ &dtype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- return PyArray_Prod(self, axis, _CHKTYPENUM(dtype), out);
+ return PyArray_Prod(self, axis, _CHKTYPENUM(dtype), out);
}
static PyObject *
array_cumprod(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "dtype", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
- PyArray_AxisConverter,
- &axis, PyArray_DescrConverter2,
- &dtype,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis, PyArray_DescrConverter2,
+ &dtype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- return PyArray_CumProd(self, axis, _CHKTYPENUM(dtype), out);
+ return PyArray_CumProd(self, axis, _CHKTYPENUM(dtype), out);
}
static PyObject *
array_any(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
- PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return PyArray_Any(self, axis, out);
+ return PyArray_Any(self, axis, out);
}
static PyObject *
array_all(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
- PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return PyArray_All(self, axis, out);
+ return PyArray_All(self, axis, out);
}
static PyObject *
array_stddev(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- int num;
- static char *kwlist[] = {"axis", "dtype", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ int num;
+ static char *kwlist[] = {"axis", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
- PyArray_AxisConverter,
- &axis, PyArray_DescrConverter2,
- &dtype,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis, PyArray_DescrConverter2,
+ &dtype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- num = _get_type_num_double(self->descr, dtype);
- return PyArray_Std(self, axis, num, out, 0);
+ num = _get_type_num_double(self->descr, dtype);
+ return PyArray_Std(self, axis, num, out, 0);
}
static PyObject *
array_variance(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- int num;
- static char *kwlist[] = {"axis", "dtype", "out", NULL};
+ int axis=MAX_DIMS;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ int num;
+ static char *kwlist[] = {"axis", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
- PyArray_AxisConverter,
- &axis, PyArray_DescrConverter2,
- &dtype,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist,
+ PyArray_AxisConverter,
+ &axis, PyArray_DescrConverter2,
+ &dtype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- num = _get_type_num_double(self->descr, dtype);
- return PyArray_Std(self, axis, num, out, 1);
+ num = _get_type_num_double(self->descr, dtype);
+ return PyArray_Std(self, axis, num, out, 1);
}
static PyObject *
array_compress(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis=MAX_DIMS;
- PyObject *condition;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"condition", "axis", "out", NULL};
+ int axis=MAX_DIMS;
+ PyObject *condition;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"condition", "axis", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&", kwlist,
- &condition, PyArray_AxisConverter,
- &axis,
- PyArray_OutputConverter,
- &out)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&", kwlist,
+ &condition, PyArray_AxisConverter,
+ &axis,
+ PyArray_OutputConverter,
+ &out)) return NULL;
- return _ARET(PyArray_Compress(self, condition, axis, out));
+ return _ARET(PyArray_Compress(self, condition, axis, out));
}
static PyObject *
array_nonzero(PyArrayObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "")) return NULL;
+ if (!PyArg_ParseTuple(args, "")) return NULL;
- return PyArray_Nonzero(self);
+ return PyArray_Nonzero(self);
}
static PyObject *
array_trace(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis1=0, axis2=1, offset=0;
- PyArray_Descr *dtype=NULL;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"offset", "axis1", "axis2", "dtype", "out", NULL};
+ int axis1=0, axis2=1, offset=0;
+ PyArray_Descr *dtype=NULL;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"offset", "axis1", "axis2", "dtype", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiiO&O&", kwlist,
- &offset, &axis1, &axis2,
- PyArray_DescrConverter2, &dtype,
- PyArray_OutputConverter, &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiiO&O&", kwlist,
+ &offset, &axis1, &axis2,
+ PyArray_DescrConverter2, &dtype,
+ PyArray_OutputConverter, &out))
+ return NULL;
- return _ARET(PyArray_Trace(self, offset, axis1, axis2,
- _CHKTYPENUM(dtype), out));
+ return _ARET(PyArray_Trace(self, offset, axis1, axis2,
+ _CHKTYPENUM(dtype), out));
}
#undef _CHKTYPENUM
@@ -1647,17 +1646,17 @@ array_trace(PyArrayObject *self, PyObject *args, PyObject *kwds)
static PyObject *
array_clip(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *min, *max;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"min", "max", "out", NULL};
+ PyObject *min, *max;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"min", "max", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist,
- &min, &max,
- PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist,
+ &min, &max,
+ PyArray_OutputConverter,
+ &out))
+ return NULL;
- return _ARET(PyArray_Clip(self, min, max, out));
+ return _ARET(PyArray_Clip(self, min, max, out));
}
@@ -1665,66 +1664,66 @@ static PyObject *
array_conjugate(PyArrayObject *self, PyObject *args)
{
- PyArrayObject *out=NULL;
- if (!PyArg_ParseTuple(args, "|O&",
- PyArray_OutputConverter,
- &out)) return NULL;
+ PyArrayObject *out=NULL;
+ if (!PyArg_ParseTuple(args, "|O&",
+ PyArray_OutputConverter,
+ &out)) return NULL;
- return PyArray_Conjugate(self, out);
+ return PyArray_Conjugate(self, out);
}
static PyObject *
array_diagonal(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int axis1=0, axis2=1, offset=0;
- static char *kwlist[] = {"offset", "axis1", "axis2", NULL};
+ int axis1=0, axis2=1, offset=0;
+ static char *kwlist[] = {"offset", "axis1", "axis2", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iii", kwlist,
- &offset, &axis1, &axis2))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iii", kwlist,
+ &offset, &axis1, &axis2))
+ return NULL;
- return _ARET(PyArray_Diagonal(self, offset, axis1, axis2));
+ return _ARET(PyArray_Diagonal(self, offset, axis1, axis2));
}
static PyObject *
array_flatten(PyArrayObject *self, PyObject *args)
{
- PyArray_ORDER fortran=PyArray_CORDER;
+ PyArray_ORDER fortran=PyArray_CORDER;
- if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter,
- &fortran)) return NULL;
+ if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter,
+ &fortran)) return NULL;
- return PyArray_Flatten(self, fortran);
+ return PyArray_Flatten(self, fortran);
}
static PyObject *
array_ravel(PyArrayObject *self, PyObject *args)
{
- PyArray_ORDER fortran=PyArray_CORDER;
+ PyArray_ORDER fortran=PyArray_CORDER;
- if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter,
- &fortran)) return NULL;
+ if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter,
+ &fortran)) return NULL;
- return PyArray_Ravel(self, fortran);
+ return PyArray_Ravel(self, fortran);
}
static PyObject *
array_round(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- int decimals = 0;
- PyArrayObject *out=NULL;
- static char *kwlist[] = {"decimals", "out", NULL};
+ int decimals = 0;
+ PyArrayObject *out=NULL;
+ static char *kwlist[] = {"decimals", "out", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&", kwlist,
- &decimals, PyArray_OutputConverter,
- &out))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&", kwlist,
+ &decimals, PyArray_OutputConverter,
+ &out))
+ return NULL;
- return _ARET(PyArray_Round(self, decimals, out));
+ return _ARET(PyArray_Round(self, decimals, out));
}
@@ -1735,205 +1734,205 @@ static Bool _IsWriteable(PyArrayObject *);
static PyObject *
array_setflags(PyArrayObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"write", "align", "uic", NULL};
- PyObject *write=Py_None;
- PyObject *align=Py_None;
- PyObject *uic=Py_None;
- int flagback = self->flags;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO", kwlist,
- &write, &align, &uic))
- return NULL;
-
- if (align != Py_None) {
- if (PyObject_Not(align)) self->flags &= ~ALIGNED;
- else if (_IsAligned(self)) self->flags |= ALIGNED;
- else {
- PyErr_SetString(PyExc_ValueError,
- "cannot set aligned flag of mis-"\
- "aligned array to True");
- return NULL;
- }
- }
-
- if (uic != Py_None) {
- if (PyObject_IsTrue(uic)) {
- self->flags = flagback;
- PyErr_SetString(PyExc_ValueError,
- "cannot set UPDATEIFCOPY " \
- "flag to True");
- return NULL;
- }
- else {
- self->flags &= ~UPDATEIFCOPY;
- Py_XDECREF(self->base);
- self->base = NULL;
- }
+ static char *kwlist[] = {"write", "align", "uic", NULL};
+ PyObject *write=Py_None;
+ PyObject *align=Py_None;
+ PyObject *uic=Py_None;
+ int flagback = self->flags;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO", kwlist,
+ &write, &align, &uic))
+ return NULL;
+
+ if (align != Py_None) {
+ if (PyObject_Not(align)) self->flags &= ~ALIGNED;
+ else if (_IsAligned(self)) self->flags |= ALIGNED;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot set aligned flag of mis-"\
+ "aligned array to True");
+ return NULL;
}
-
- if (write != Py_None) {
- if (PyObject_IsTrue(write))
- if (_IsWriteable(self)) {
- self->flags |= WRITEABLE;
- }
- else {
- self->flags = flagback;
- PyErr_SetString(PyExc_ValueError,
- "cannot set WRITEABLE " \
- "flag to True of this " \
- "array"); \
- return NULL;
- }
- else
- self->flags &= ~WRITEABLE;
+ }
+
+ if (uic != Py_None) {
+ if (PyObject_IsTrue(uic)) {
+ self->flags = flagback;
+ PyErr_SetString(PyExc_ValueError,
+ "cannot set UPDATEIFCOPY " \
+ "flag to True");
+ return NULL;
+ }
+ else {
+ self->flags &= ~UPDATEIFCOPY;
+ Py_XDECREF(self->base);
+ self->base = NULL;
}
+ }
+
+ if (write != Py_None) {
+ if (PyObject_IsTrue(write))
+ if (_IsWriteable(self)) {
+ self->flags |= WRITEABLE;
+ }
+ else {
+ self->flags = flagback;
+ PyErr_SetString(PyExc_ValueError,
+ "cannot set WRITEABLE " \
+ "flag to True of this " \
+ "array"); \
+ return NULL;
+ }
+ else
+ self->flags &= ~WRITEABLE;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_newbyteorder(PyArrayObject *self, PyObject *args)
{
- char endian = PyArray_SWAP;
- PyArray_Descr *new;
+ char endian = PyArray_SWAP;
+ PyArray_Descr *new;
- if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter,
- &endian)) return NULL;
+ if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter,
+ &endian)) return NULL;
- new = PyArray_DescrNewByteorder(self->descr, endian);
- if (!new) return NULL;
- return PyArray_View(self, new, NULL);
+ new = PyArray_DescrNewByteorder(self->descr, endian);
+ if (!new) return NULL;
+ return PyArray_View(self, new, NULL);
}
static PyMethodDef array_methods[] = {
- /* for subtypes */
- {"__array__", (PyCFunction)array_getarray,
- METH_VARARGS, NULL},
- {"__array_wrap__", (PyCFunction)array_wraparray,
- METH_VARARGS, NULL},
-
- /* for the copy module */
- {"__copy__", (PyCFunction)array_copy,
- METH_VARARGS, NULL},
- {"__deepcopy__", (PyCFunction)array_deepcopy,
- METH_VARARGS, NULL},
-
- /* for Pickling */
- {"__reduce__", (PyCFunction) array_reduce,
- METH_VARARGS, NULL},
- {"__setstate__", (PyCFunction) array_setstate,
- METH_VARARGS, NULL},
- {"dumps", (PyCFunction) array_dumps,
- METH_VARARGS, NULL},
- {"dump", (PyCFunction) array_dump,
- METH_VARARGS, NULL},
-
- /* Original and Extended methods added 2005 */
- {"all", (PyCFunction)array_all,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"any", (PyCFunction)array_any,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"argmax", (PyCFunction)array_argmax,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"argmin", (PyCFunction)array_argmin,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"argsort", (PyCFunction)array_argsort,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"astype", (PyCFunction)array_cast,
- METH_VARARGS, NULL},
- {"byteswap", (PyCFunction)array_byteswap,
- METH_VARARGS, NULL},
- {"choose", (PyCFunction)array_choose,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"clip", (PyCFunction)array_clip,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"compress", (PyCFunction)array_compress,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"conj", (PyCFunction)array_conjugate,
- METH_VARARGS, NULL},
- {"conjugate", (PyCFunction)array_conjugate,
- METH_VARARGS, NULL},
- {"copy", (PyCFunction)array_copy,
- METH_VARARGS, NULL},
- {"cumprod", (PyCFunction)array_cumprod,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"cumsum", (PyCFunction)array_cumsum,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"diagonal", (PyCFunction)array_diagonal,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"fill", (PyCFunction)array_fill,
- METH_VARARGS, NULL},
- {"flatten", (PyCFunction)array_flatten,
- METH_VARARGS, NULL},
- {"getfield", (PyCFunction)array_getfield,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"item", (PyCFunction)array_toscalar,
- METH_VARARGS, NULL},
- {"itemset", (PyCFunction) array_setscalar,
- METH_VARARGS, NULL},
- {"max", (PyCFunction)array_max,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"mean", (PyCFunction)array_mean,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"min", (PyCFunction)array_min,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"newbyteorder", (PyCFunction)array_newbyteorder,
- METH_VARARGS, NULL},
- {"nonzero", (PyCFunction)array_nonzero,
- METH_VARARGS, NULL},
- {"prod", (PyCFunction)array_prod,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"ptp", (PyCFunction)array_ptp,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"put", (PyCFunction)array_put,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"ravel", (PyCFunction)array_ravel,
- METH_VARARGS, NULL},
- {"repeat", (PyCFunction)array_repeat,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"reshape", (PyCFunction)array_reshape,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"resize", (PyCFunction)array_resize,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"round", (PyCFunction)array_round,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"searchsorted", (PyCFunction)array_searchsorted,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"setfield", (PyCFunction)array_setfield,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"setflags", (PyCFunction)array_setflags,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"sort", (PyCFunction)array_sort,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"squeeze", (PyCFunction)array_squeeze,
- METH_VARARGS, NULL},
- {"std", (PyCFunction)array_stddev,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"sum", (PyCFunction)array_sum,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"swapaxes", (PyCFunction)array_swapaxes,
- METH_VARARGS, NULL},
- {"take", (PyCFunction)array_take,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"tofile", (PyCFunction)array_tofile,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"tolist", (PyCFunction)array_tolist,
- METH_VARARGS, NULL},
- {"tostring", (PyCFunction)array_tostring,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"trace", (PyCFunction)array_trace,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"transpose", (PyCFunction)array_transpose,
- METH_VARARGS, NULL},
- {"var", (PyCFunction)array_variance,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"view", (PyCFunction)array_view,
- METH_VARARGS, NULL},
- {NULL, NULL} /* sentinel */
+ /* for subtypes */
+ {"__array__", (PyCFunction)array_getarray,
+ METH_VARARGS, NULL},
+ {"__array_wrap__", (PyCFunction)array_wraparray,
+ METH_VARARGS, NULL},
+
+ /* for the copy module */
+ {"__copy__", (PyCFunction)array_copy,
+ METH_VARARGS, NULL},
+ {"__deepcopy__", (PyCFunction)array_deepcopy,
+ METH_VARARGS, NULL},
+
+ /* for Pickling */
+ {"__reduce__", (PyCFunction) array_reduce,
+ METH_VARARGS, NULL},
+ {"__setstate__", (PyCFunction) array_setstate,
+ METH_VARARGS, NULL},
+ {"dumps", (PyCFunction) array_dumps,
+ METH_VARARGS, NULL},
+ {"dump", (PyCFunction) array_dump,
+ METH_VARARGS, NULL},
+
+ /* Original and Extended methods added 2005 */
+ {"all", (PyCFunction)array_all,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"any", (PyCFunction)array_any,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"argmax", (PyCFunction)array_argmax,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"argmin", (PyCFunction)array_argmin,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"argsort", (PyCFunction)array_argsort,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"astype", (PyCFunction)array_cast,
+ METH_VARARGS, NULL},
+ {"byteswap", (PyCFunction)array_byteswap,
+ METH_VARARGS, NULL},
+ {"choose", (PyCFunction)array_choose,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"clip", (PyCFunction)array_clip,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"compress", (PyCFunction)array_compress,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"conj", (PyCFunction)array_conjugate,
+ METH_VARARGS, NULL},
+ {"conjugate", (PyCFunction)array_conjugate,
+ METH_VARARGS, NULL},
+ {"copy", (PyCFunction)array_copy,
+ METH_VARARGS, NULL},
+ {"cumprod", (PyCFunction)array_cumprod,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"cumsum", (PyCFunction)array_cumsum,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"diagonal", (PyCFunction)array_diagonal,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"fill", (PyCFunction)array_fill,
+ METH_VARARGS, NULL},
+ {"flatten", (PyCFunction)array_flatten,
+ METH_VARARGS, NULL},
+ {"getfield", (PyCFunction)array_getfield,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"item", (PyCFunction)array_toscalar,
+ METH_VARARGS, NULL},
+ {"itemset", (PyCFunction) array_setscalar,
+ METH_VARARGS, NULL},
+ {"max", (PyCFunction)array_max,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"mean", (PyCFunction)array_mean,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"min", (PyCFunction)array_min,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"newbyteorder", (PyCFunction)array_newbyteorder,
+ METH_VARARGS, NULL},
+ {"nonzero", (PyCFunction)array_nonzero,
+ METH_VARARGS, NULL},
+ {"prod", (PyCFunction)array_prod,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"ptp", (PyCFunction)array_ptp,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"put", (PyCFunction)array_put,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"ravel", (PyCFunction)array_ravel,
+ METH_VARARGS, NULL},
+ {"repeat", (PyCFunction)array_repeat,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"reshape", (PyCFunction)array_reshape,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"resize", (PyCFunction)array_resize,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"round", (PyCFunction)array_round,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"searchsorted", (PyCFunction)array_searchsorted,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"setfield", (PyCFunction)array_setfield,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"setflags", (PyCFunction)array_setflags,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"sort", (PyCFunction)array_sort,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"squeeze", (PyCFunction)array_squeeze,
+ METH_VARARGS, NULL},
+ {"std", (PyCFunction)array_stddev,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"sum", (PyCFunction)array_sum,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"swapaxes", (PyCFunction)array_swapaxes,
+ METH_VARARGS, NULL},
+ {"take", (PyCFunction)array_take,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"tofile", (PyCFunction)array_tofile,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"tolist", (PyCFunction)array_tolist,
+ METH_VARARGS, NULL},
+ {"tostring", (PyCFunction)array_tostring,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"trace", (PyCFunction)array_trace,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"transpose", (PyCFunction)array_transpose,
+ METH_VARARGS, NULL},
+ {"var", (PyCFunction)array_variance,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"view", (PyCFunction)array_view,
+ METH_VARARGS, NULL},
+ {NULL, NULL} /* sentinel */
};
#undef _ARET
diff --git a/numpy/core/src/arrayobject.c b/numpy/core/src/arrayobject.c
index e269195cc..2847b7796 100644
--- a/numpy/core/src/arrayobject.c
+++ b/numpy/core/src/arrayobject.c
@@ -1,142 +1,141 @@
-
/*
Provide multidimensional arrays as a basic object type in python.
-Based on Original Numeric implementation
-Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu
+ Based on Original Numeric implementation
+ Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu
-with contributions from many Numeric Python developers 1995-2004
+ with contributions from many Numeric Python developers 1995-2004
-Heavily modified in 2005 with inspiration from Numarray
+ Heavily modified in 2005 with inspiration from Numarray
-by
+ by
-Travis Oliphant, oliphant@ee.byu.edu
-Brigham Young Univeristy
+ Travis Oliphant, oliphant@ee.byu.edu
+ Brigham Young Univeristy
-maintainer email: oliphant.travis@ieee.org
+ maintainer email: oliphant.travis@ieee.org
-Numarray design (which provided guidance) by
-Space Science Telescope Institute
+ Numarray design (which provided guidance) by
+ Space Science Telescope Institute
(J. Todd Miller, Perry Greenfield, Rick White)
*/
/*OBJECT_API
- Get Priority from object
+ Get Priority from object
*/
static double
PyArray_GetPriority(PyObject *obj, double default_)
{
- PyObject *ret;
- double priority=PyArray_PRIORITY;
+ PyObject *ret;
+ double priority=PyArray_PRIORITY;
- if (PyArray_CheckExact(obj))
- return priority;
-
- ret = PyObject_GetAttrString(obj, "__array_priority__");
- if (ret != NULL) priority = PyFloat_AsDouble(ret);
- if (PyErr_Occurred()) {
- PyErr_Clear();
- priority = default_;
- }
- Py_XDECREF(ret);
+ if (PyArray_CheckExact(obj))
return priority;
+
+ ret = PyObject_GetAttrString(obj, "__array_priority__");
+ if (ret != NULL) priority = PyFloat_AsDouble(ret);
+ if (PyErr_Occurred()) {
+ PyErr_Clear();
+ priority = default_;
+ }
+ Py_XDECREF(ret);
+ return priority;
}
static int
_check_object_rec(PyArray_Descr *descr)
{
- if (PyDataType_HASFIELDS(descr) && PyDataType_REFCHK(descr)) {
- PyErr_SetString(PyExc_TypeError, "Not supported for this data-type.");
- return -1;
- }
- return 0;
+ if (PyDataType_HASFIELDS(descr) && PyDataType_REFCHK(descr)) {
+ PyErr_SetString(PyExc_TypeError, "Not supported for this data-type.");
+ return -1;
+ }
+ return 0;
}
/* Backward compatibility only */
/* In both Zero and One
- ***You must free the memory once you are done with it
- using PyDataMem_FREE(ptr) or you create a memory leak***
+***You must free the memory once you are done with it
+using PyDataMem_FREE(ptr) or you create a memory leak***
- If arr is an Object array you are getting a
- BORROWED reference to Zero or One.
- Do not DECREF.
- Please INCREF if you will be hanging on to it.
+If arr is an Object array you are getting a
+BORROWED reference to Zero or One.
+Do not DECREF.
+Please INCREF if you will be hanging on to it.
- The memory for the ptr still must be freed in any case;
+The memory for the ptr still must be freed in any case;
*/
/*OBJECT_API
- Get pointer to zero of correct type for array.
+ Get pointer to zero of correct type for array.
*/
static char *
PyArray_Zero(PyArrayObject *arr)
{
- char *zeroval;
- int ret, storeflags;
- PyObject *obj;
+ char *zeroval;
+ int ret, storeflags;
+ PyObject *obj;
- if (_check_object_rec(arr->descr) < 0) return NULL;
- zeroval = PyDataMem_NEW(arr->descr->elsize);
- if (zeroval == NULL) {
- PyErr_SetNone(PyExc_MemoryError);
- return NULL;
- }
+ if (_check_object_rec(arr->descr) < 0) return NULL;
+ zeroval = PyDataMem_NEW(arr->descr->elsize);
+ if (zeroval == NULL) {
+ PyErr_SetNone(PyExc_MemoryError);
+ return NULL;
+ }
- obj=PyInt_FromLong((long) 0);
- if (PyArray_ISOBJECT(arr)) {
- memcpy(zeroval, &obj, sizeof(PyObject *));
- Py_DECREF(obj);
- return zeroval;
- }
- storeflags = arr->flags;
- arr->flags |= BEHAVED;
- ret = arr->descr->f->setitem(obj, zeroval, arr);
- arr->flags = storeflags;
+ obj=PyInt_FromLong((long) 0);
+ if (PyArray_ISOBJECT(arr)) {
+ memcpy(zeroval, &obj, sizeof(PyObject *));
Py_DECREF(obj);
- if (ret < 0) {
- PyDataMem_FREE(zeroval);
- return NULL;
- }
return zeroval;
+ }
+ storeflags = arr->flags;
+ arr->flags |= BEHAVED;
+ ret = arr->descr->f->setitem(obj, zeroval, arr);
+ arr->flags = storeflags;
+ Py_DECREF(obj);
+ if (ret < 0) {
+ PyDataMem_FREE(zeroval);
+ return NULL;
+ }
+ return zeroval;
}
/*OBJECT_API
- Get pointer to one of correct type for array
+ Get pointer to one of correct type for array
*/
static char *
PyArray_One(PyArrayObject *arr)
{
- char *oneval;
- int ret, storeflags;
- PyObject *obj;
-
- if (_check_object_rec(arr->descr) < 0) return NULL;
- oneval = PyDataMem_NEW(arr->descr->elsize);
- if (oneval == NULL) {
- PyErr_SetNone(PyExc_MemoryError);
- return NULL;
- }
+ char *oneval;
+ int ret, storeflags;
+ PyObject *obj;
- obj = PyInt_FromLong((long) 1);
- if (PyArray_ISOBJECT(arr)) {
- memcpy(oneval, &obj, sizeof(PyObject *));
- Py_DECREF(obj);
- return oneval;
- }
+ if (_check_object_rec(arr->descr) < 0) return NULL;
+ oneval = PyDataMem_NEW(arr->descr->elsize);
+ if (oneval == NULL) {
+ PyErr_SetNone(PyExc_MemoryError);
+ return NULL;
+ }
- storeflags = arr->flags;
- arr->flags |= BEHAVED;
- ret = arr->descr->f->setitem(obj, oneval, arr);
- arr->flags = storeflags;
+ obj = PyInt_FromLong((long) 1);
+ if (PyArray_ISOBJECT(arr)) {
+ memcpy(oneval, &obj, sizeof(PyObject *));
Py_DECREF(obj);
- if (ret < 0) {
- PyDataMem_FREE(oneval);
- return NULL;
- }
return oneval;
+ }
+
+ storeflags = arr->flags;
+ arr->flags |= BEHAVED;
+ ret = arr->descr->f->setitem(obj, oneval, arr);
+ arr->flags = storeflags;
+ Py_DECREF(obj);
+ if (ret < 0) {
+ PyDataMem_FREE(oneval);
+ return NULL;
+ }
+ return oneval;
}
/* End deprecated */
@@ -152,26 +151,26 @@ static PyObject *PyArray_New(PyTypeObject *, int nd, intp *,
static void
PyArray_Item_INCREF(char *data, PyArray_Descr *descr)
{
- PyObject **temp;
+ PyObject **temp;
- if (!PyDataType_REFCHK(descr)) return;
+ if (!PyDataType_REFCHK(descr)) return;
- if (descr->type_num == PyArray_OBJECT) {
- temp = (PyObject **)data;
- Py_XINCREF(*temp);
- }
- else if (PyDescr_HASFIELDS(descr)) {
- PyObject *key, *value, *title=NULL;
- PyArray_Descr *new;
- int offset;
- Py_ssize_t pos=0;
- while (PyDict_Next(descr->fields, &pos, &key, &value)) {
- if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
- &title)) return;
- PyArray_Item_INCREF(data + offset, new);
- }
+ if (descr->type_num == PyArray_OBJECT) {
+ temp = (PyObject **)data;
+ Py_XINCREF(*temp);
+ }
+ else if (PyDescr_HASFIELDS(descr)) {
+ PyObject *key, *value, *title=NULL;
+ PyArray_Descr *new;
+ int offset;
+ Py_ssize_t pos=0;
+ while (PyDict_Next(descr->fields, &pos, &key, &value)) {
+ if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
+ &title)) return;
+ PyArray_Item_INCREF(data + offset, new);
}
- return;
+ }
+ return;
}
/* XDECREF all objects found at this record */
@@ -180,26 +179,26 @@ PyArray_Item_INCREF(char *data, PyArray_Descr *descr)
static void
PyArray_Item_XDECREF(char *data, PyArray_Descr *descr)
{
- PyObject **temp;
+ PyObject **temp;
- if (!PyDataType_REFCHK(descr)) return;
+ if (!PyDataType_REFCHK(descr)) return;
- if (descr->type_num == PyArray_OBJECT) {
- temp = (PyObject **)data;
- Py_XDECREF(*temp);
- }
- else if PyDescr_HASFIELDS(descr) {
- PyObject *key, *value, *title=NULL;
- PyArray_Descr *new;
- int offset;
- Py_ssize_t pos=0;
- while (PyDict_Next(descr->fields, &pos, &key, &value)) {
- if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
- &title)) return;
- PyArray_Item_XDECREF(data + offset, new);
- }
+ if (descr->type_num == PyArray_OBJECT) {
+ temp = (PyObject **)data;
+ Py_XDECREF(*temp);
+ }
+ else if PyDescr_HASFIELDS(descr) {
+ PyObject *key, *value, *title=NULL;
+ PyArray_Descr *new;
+ int offset;
+ Py_ssize_t pos=0;
+ while (PyDict_Next(descr->fields, &pos, &key, &value)) {
+ if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
+ &title)) return;
+ PyArray_Item_XDECREF(data + offset, new);
+ }
}
- return;
+ return;
}
/* C-API functions */
@@ -207,147 +206,147 @@ PyArray_Item_XDECREF(char *data, PyArray_Descr *descr)
/* Used for arrays of python objects to increment the reference count of */
/* every python object in the array. */
/*OBJECT_API
- For object arrays, increment all internal references.
+ For object arrays, increment all internal references.
*/
static int
PyArray_INCREF(PyArrayObject *mp)
{
- intp i, n;
- PyObject **data, **temp;
- PyArrayIterObject *it;
+ intp i, n;
+ PyObject **data, **temp;
+ PyArrayIterObject *it;
- if (!PyDataType_REFCHK(mp->descr)) return 0;
+ if (!PyDataType_REFCHK(mp->descr)) return 0;
- if (mp->descr->type_num != PyArray_OBJECT) {
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
- if (it == NULL) return -1;
- while(it->index < it->size) {
- PyArray_Item_INCREF(it->dataptr, mp->descr);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
- return 0;
+ if (mp->descr->type_num != PyArray_OBJECT) {
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
+ if (it == NULL) return -1;
+ while(it->index < it->size) {
+ PyArray_Item_INCREF(it->dataptr, mp->descr);
+ PyArray_ITER_NEXT(it);
}
+ Py_DECREF(it);
+ return 0;
+ }
- if (PyArray_ISONESEGMENT(mp)) {
- data = (PyObject **)mp->data;
- n = PyArray_SIZE(mp);
- if (PyArray_ISALIGNED(mp)) {
- for(i=0; i<n; i++, data++) Py_XINCREF(*data);
- }
- else {
- for (i=0; i<n; i++, data++) {
- temp = data;
- Py_XINCREF(*temp);
- }
- }
+ if (PyArray_ISONESEGMENT(mp)) {
+ data = (PyObject **)mp->data;
+ n = PyArray_SIZE(mp);
+ if (PyArray_ISALIGNED(mp)) {
+ for(i=0; i<n; i++, data++) Py_XINCREF(*data);
}
- else { /* handles misaligned data too */
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
- if (it == NULL) return -1;
- while(it->index < it->size) {
- temp = (PyObject **)it->dataptr;
- Py_XINCREF(*temp);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
+ else {
+ for (i=0; i<n; i++, data++) {
+ temp = data;
+ Py_XINCREF(*temp);
+ }
}
- return 0;
+ }
+ else { /* handles misaligned data too */
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
+ if (it == NULL) return -1;
+ while(it->index < it->size) {
+ temp = (PyObject **)it->dataptr;
+ Py_XINCREF(*temp);
+ PyArray_ITER_NEXT(it);
+ }
+ Py_DECREF(it);
+ }
+ return 0;
}
/*OBJECT_API
- Decrement all internal references for object arrays.
- (or arrays with object fields)
+ Decrement all internal references for object arrays.
+ (or arrays with object fields)
*/
static int
PyArray_XDECREF(PyArrayObject *mp)
{
- intp i, n;
- PyObject **data;
- PyObject **temp;
- PyArrayIterObject *it;
+ intp i, n;
+ PyObject **data;
+ PyObject **temp;
+ PyArrayIterObject *it;
- if (!PyDataType_REFCHK(mp->descr)) return 0;
+ if (!PyDataType_REFCHK(mp->descr)) return 0;
- if (mp->descr->type_num != PyArray_OBJECT) {
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
- if (it == NULL) return -1;
- while(it->index < it->size) {
- PyArray_Item_XDECREF(it->dataptr, mp->descr);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
- return 0;
+ if (mp->descr->type_num != PyArray_OBJECT) {
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
+ if (it == NULL) return -1;
+ while(it->index < it->size) {
+ PyArray_Item_XDECREF(it->dataptr, mp->descr);
+ PyArray_ITER_NEXT(it);
}
+ Py_DECREF(it);
+ return 0;
+ }
- if (PyArray_ISONESEGMENT(mp)) {
- data = (PyObject **)mp->data;
- n = PyArray_SIZE(mp);
- if (PyArray_ISALIGNED(mp)) {
- for(i=0; i<n; i++, data++) Py_XDECREF(*data);
- }
- else {
- for (i=0; i<n; i++, data++) {
- temp = data;
- Py_XDECREF(*temp);
- }
- }
+ if (PyArray_ISONESEGMENT(mp)) {
+ data = (PyObject **)mp->data;
+ n = PyArray_SIZE(mp);
+ if (PyArray_ISALIGNED(mp)) {
+ for(i=0; i<n; i++, data++) Py_XDECREF(*data);
}
- else { /* handles misaligned data too */
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
- if (it == NULL) return -1;
- while(it->index < it->size) {
- temp = (PyObject **)it->dataptr;
- Py_XDECREF(*temp);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
+ else {
+ for (i=0; i<n; i++, data++) {
+ temp = data;
+ Py_XDECREF(*temp);
+ }
}
- return 0;
+ }
+ else { /* handles misaligned data too */
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
+ if (it == NULL) return -1;
+ while(it->index < it->size) {
+ temp = (PyObject **)it->dataptr;
+ Py_XDECREF(*temp);
+ PyArray_ITER_NEXT(it);
+ }
+ Py_DECREF(it);
+ }
+ return 0;
}
static void
_strided_byte_copy(char *dst, intp outstrides, char *src, intp instrides,
intp N, int elsize)
{
- intp i, j;
- char *tout = dst;
- char *tin = src;
-
-#define _FAST_MOVE(_type_) \
- for (i=0; i<N; i++) { \
- ((_type_ *)tout)[0] = ((_type_ *)tin)[0]; \
- tin += instrides; \
- tout += outstrides; \
- } \
- return
-
- switch(elsize) {
- case 8:
- _FAST_MOVE(Int64);
- case 4:
- _FAST_MOVE(Int32);
- case 1:
- _FAST_MOVE(Int8);
- case 2:
- _FAST_MOVE(Int16);
- case 16:
- for (i=0; i<N; i++) {
- ((Int64 *)tout)[0] = ((Int64 *)tin)[0];
- ((Int64 *)tout)[1] = ((Int64 *)tin)[1];
- tin += instrides;
- tout += outstrides;
- }
- return;
- default:
- for (i=0; i<N; i++) {
- for (j=0; j<elsize; j++) {
- *tout++ = *tin++;
- }
- tin = tin + instrides - elsize;
- tout = tout + outstrides - elsize;
- }
+ intp i, j;
+ char *tout = dst;
+ char *tin = src;
+
+#define _FAST_MOVE(_type_) \
+ for (i=0; i<N; i++) { \
+ ((_type_ *)tout)[0] = ((_type_ *)tin)[0]; \
+ tin += instrides; \
+ tout += outstrides; \
+ } \
+ return
+
+ switch(elsize) {
+ case 8:
+ _FAST_MOVE(Int64);
+ case 4:
+ _FAST_MOVE(Int32);
+ case 1:
+ _FAST_MOVE(Int8);
+ case 2:
+ _FAST_MOVE(Int16);
+ case 16:
+ for (i=0; i<N; i++) {
+ ((Int64 *)tout)[0] = ((Int64 *)tin)[0];
+ ((Int64 *)tout)[1] = ((Int64 *)tin)[1];
+ tin += instrides;
+ tout += outstrides;
}
+ return;
+ default:
+ for (i=0; i<N; i++) {
+ for (j=0; j<elsize; j++) {
+ *tout++ = *tin++;
+ }
+ tin = tin + instrides - elsize;
+ tout = tout + outstrides - elsize;
+ }
+ }
#undef _FAST_MOVE
}
@@ -357,33 +356,33 @@ static void
_unaligned_strided_byte_move(char *dst, intp outstrides, char *src,
intp instrides, intp N, int elsize)
{
- intp i;
- char *tout = dst;
- char *tin = src;
-
-
-#define _MOVE_N_SIZE(size) \
- for (i=0; i<N; i++) { \
- memmove(tout, tin, size); \
- tin += instrides; \
- tout += outstrides; \
- } \
- return
-
- switch(elsize) {
- case 8:
- _MOVE_N_SIZE(8);
- case 4:
- _MOVE_N_SIZE(4);
- case 1:
- _MOVE_N_SIZE(1);
- case 2:
- _MOVE_N_SIZE(2);
- case 16:
- _MOVE_N_SIZE(16);
- default:
- _MOVE_N_SIZE(elsize);
- }
+ intp i;
+ char *tout = dst;
+ char *tin = src;
+
+
+#define _MOVE_N_SIZE(size) \
+ for (i=0; i<N; i++) { \
+ memmove(tout, tin, size); \
+ tin += instrides; \
+ tout += outstrides; \
+ } \
+ return
+
+ switch(elsize) {
+ case 8:
+ _MOVE_N_SIZE(8);
+ case 4:
+ _MOVE_N_SIZE(4);
+ case 1:
+ _MOVE_N_SIZE(1);
+ case 2:
+ _MOVE_N_SIZE(2);
+ case 16:
+ _MOVE_N_SIZE(16);
+ default:
+ _MOVE_N_SIZE(elsize);
+ }
#undef _MOVE_N_SIZE
}
@@ -392,32 +391,32 @@ static void
_unaligned_strided_byte_copy(char *dst, intp outstrides, char *src,
intp instrides, intp N, int elsize)
{
- intp i;
- char *tout = dst;
- char *tin = src;
-
-#define _COPY_N_SIZE(size) \
- for (i=0; i<N; i++) { \
- memcpy(tout, tin, size); \
- tin += instrides; \
- tout += outstrides; \
- } \
- return
-
- switch(elsize) {
- case 8:
- _COPY_N_SIZE(8);
- case 4:
- _COPY_N_SIZE(4);
- case 1:
- _COPY_N_SIZE(1);
- case 2:
- _COPY_N_SIZE(2);
- case 16:
- _COPY_N_SIZE(16);
- default:
- _COPY_N_SIZE(elsize);
- }
+ intp i;
+ char *tout = dst;
+ char *tin = src;
+
+#define _COPY_N_SIZE(size) \
+ for (i=0; i<N; i++) { \
+ memcpy(tout, tin, size); \
+ tin += instrides; \
+ tout += outstrides; \
+ } \
+ return
+
+ switch(elsize) {
+ case 8:
+ _COPY_N_SIZE(8);
+ case 4:
+ _COPY_N_SIZE(4);
+ case 1:
+ _COPY_N_SIZE(1);
+ case 2:
+ _COPY_N_SIZE(2);
+ case 16:
+ _COPY_N_SIZE(16);
+ default:
+ _COPY_N_SIZE(elsize);
+ }
#undef _COPY_N_SIZE
}
@@ -425,51 +424,51 @@ _unaligned_strided_byte_copy(char *dst, intp outstrides, char *src,
static void
_strided_byte_swap(void *p, intp stride, intp n, int size)
{
- char *a, *b, c=0;
- int j,m;
-
- switch(size) {
- case 1: /* no byteswap necessary */
- break;
- case 4:
- for (a = (char*)p ; n > 0; n--, a += stride-1) {
- b = a + 3;
- c = *a; *a++ = *b; *b-- = c;
- c = *a; *a = *b; *b = c;
- }
- break;
- case 8:
- for (a = (char*)p ; n > 0; n--, a += stride-3) {
- b = a + 7;
- c = *a; *a++ = *b; *b-- = c;
- c = *a; *a++ = *b; *b-- = c;
- c = *a; *a++ = *b; *b-- = c;
- c = *a; *a = *b; *b = c;
- }
- break;
- case 2:
- for (a = (char*)p ; n > 0; n--, a += stride) {
- b = a + 1;
- c = *a; *a = *b; *b = c;
- }
- break;
- default:
- m = size / 2;
- for (a = (char *)p ; n > 0; n--, a += stride-m) {
- b = a + (size-1);
- for (j=0; j<m; j++) {
- c=*a; *a++ = *b; *b-- = c;
- }
- }
- break;
+ char *a, *b, c=0;
+ int j,m;
+
+ switch(size) {
+ case 1: /* no byteswap necessary */
+ break;
+ case 4:
+ for (a = (char*)p ; n > 0; n--, a += stride-1) {
+ b = a + 3;
+ c = *a; *a++ = *b; *b-- = c;
+ c = *a; *a = *b; *b = c;
+ }
+ break;
+ case 8:
+ for (a = (char*)p ; n > 0; n--, a += stride-3) {
+ b = a + 7;
+ c = *a; *a++ = *b; *b-- = c;
+ c = *a; *a++ = *b; *b-- = c;
+ c = *a; *a++ = *b; *b-- = c;
+ c = *a; *a = *b; *b = c;
+ }
+ break;
+ case 2:
+ for (a = (char*)p ; n > 0; n--, a += stride) {
+ b = a + 1;
+ c = *a; *a = *b; *b = c;
+ }
+ break;
+ default:
+ m = size / 2;
+ for (a = (char *)p ; n > 0; n--, a += stride-m) {
+ b = a + (size-1);
+ for (j=0; j<m; j++) {
+ c=*a; *a++ = *b; *b-- = c;
+ }
}
+ break;
+ }
}
static void
byte_swap_vector(void *p, intp n, int size)
{
- _strided_byte_swap(p, (intp) size, n, size);
- return;
+ _strided_byte_swap(p, (intp) size, n, size);
+ return;
}
/* If numitems > 1, then dst must be contiguous */
@@ -477,23 +476,23 @@ static void
copy_and_swap(void *dst, void *src, int itemsize, intp numitems,
intp srcstrides, int swap)
{
- int i;
- char *s1 = (char *)src;
- char *d1 = (char *)dst;
+ int i;
+ char *s1 = (char *)src;
+ char *d1 = (char *)dst;
- if ((numitems == 1) || (itemsize == srcstrides))
- memcpy(d1, s1, itemsize*numitems);
- else {
- for (i = 0; i < numitems; i++) {
- memcpy(d1, s1, itemsize);
- d1 += itemsize;
- s1 += srcstrides;
- }
+ if ((numitems == 1) || (itemsize == srcstrides))
+ memcpy(d1, s1, itemsize*numitems);
+ else {
+ for (i = 0; i < numitems; i++) {
+ memcpy(d1, s1, itemsize);
+ d1 += itemsize;
+ s1 += srcstrides;
}
+ }
- if (swap)
- byte_swap_vector(d1, numitems, itemsize);
+ if (swap)
+ byte_swap_vector(d1, numitems, itemsize);
}
@@ -517,97 +516,97 @@ static PyArray_Descr **userdescrs=NULL;
static intp
PyArray_PyIntAsIntp(PyObject *o)
{
- longlong long_value = -1;
- PyObject *obj;
- static char *msg = "an integer is required";
- PyObject *arr;
- PyArray_Descr *descr;
- intp ret;
+ longlong long_value = -1;
+ PyObject *obj;
+ static char *msg = "an integer is required";
+ PyObject *arr;
+ PyArray_Descr *descr;
+ intp ret;
- if (!o) {
- PyErr_SetString(PyExc_TypeError, msg);
- return -1;
- }
+ if (!o) {
+ PyErr_SetString(PyExc_TypeError, msg);
+ return -1;
+ }
- if (PyInt_Check(o)) {
- long_value = (longlong) PyInt_AS_LONG(o);
- goto finish;
- } else if (PyLong_Check(o)) {
- long_value = (longlong) PyLong_AsLongLong(o);
- goto finish;
- }
+ if (PyInt_Check(o)) {
+ long_value = (longlong) PyInt_AS_LONG(o);
+ goto finish;
+ } else if (PyLong_Check(o)) {
+ long_value = (longlong) PyLong_AsLongLong(o);
+ goto finish;
+ }
#if SIZEOF_INTP == SIZEOF_LONG
- descr = &LONG_Descr;
+ descr = &LONG_Descr;
#elif SIZEOF_INTP == SIZEOF_INT
- descr = &INT_Descr;
+ descr = &INT_Descr;
#else
- descr = &LONGLONG_Descr;
+ descr = &LONGLONG_Descr;
#endif
- arr = NULL;
+ arr = NULL;
- if (PyArray_Check(o)) {
- if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
- PyErr_SetString(PyExc_TypeError, msg);
- return -1;
- }
- Py_INCREF(descr);
- arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
- }
- else if (PyArray_IsScalar(o, Integer)) {
- Py_INCREF(descr);
- arr = PyArray_FromScalar(o, descr);
- }
- if (arr != NULL) {
- ret = *((intp *)PyArray_DATA(arr));
- Py_DECREF(arr);
- return ret;
+ if (PyArray_Check(o)) {
+ if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
+ PyErr_SetString(PyExc_TypeError, msg);
+ return -1;
}
+ Py_INCREF(descr);
+ arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
+ }
+ else if (PyArray_IsScalar(o, Integer)) {
+ Py_INCREF(descr);
+ arr = PyArray_FromScalar(o, descr);
+ }
+ if (arr != NULL) {
+ ret = *((intp *)PyArray_DATA(arr));
+ Py_DECREF(arr);
+ return ret;
+ }
#if (PY_VERSION_HEX >= 0x02050000)
- if (PyIndex_Check(o)) {
- PyObject* value = PyNumber_Index(o);
- if (value==NULL) {
- return -1;
- }
- long_value = (longlong) PyInt_AsSsize_t(value);
- goto finish;
- }
-#endif
- if (o->ob_type->tp_as_number != NULL && \
- o->ob_type->tp_as_number->nb_long != NULL) {
- obj = o->ob_type->tp_as_number->nb_long(o);
- if (obj != NULL) {
- long_value = (longlong) PyLong_AsLongLong(obj);
- Py_DECREF(obj);
- }
+ if (PyIndex_Check(o)) {
+ PyObject* value = PyNumber_Index(o);
+ if (value==NULL) {
+ return -1;
}
- else if (o->ob_type->tp_as_number != NULL && \
- o->ob_type->tp_as_number->nb_int != NULL) {
- obj = o->ob_type->tp_as_number->nb_int(o);
- if (obj != NULL) {
- long_value = (longlong) PyLong_AsLongLong(obj);
- Py_DECREF(obj);
- }
+ long_value = (longlong) PyInt_AsSsize_t(value);
+ goto finish;
+ }
+#endif
+ if (o->ob_type->tp_as_number != NULL && \
+ o->ob_type->tp_as_number->nb_long != NULL) {
+ obj = o->ob_type->tp_as_number->nb_long(o);
+ if (obj != NULL) {
+ long_value = (longlong) PyLong_AsLongLong(obj);
+ Py_DECREF(obj);
}
- else {
- PyErr_SetString(PyExc_NotImplementedError,"");
+ }
+ else if (o->ob_type->tp_as_number != NULL && \
+ o->ob_type->tp_as_number->nb_int != NULL) {
+ obj = o->ob_type->tp_as_number->nb_int(o);
+ if (obj != NULL) {
+ long_value = (longlong) PyLong_AsLongLong(obj);
+ Py_DECREF(obj);
}
+ }
+ else {
+ PyErr_SetString(PyExc_NotImplementedError,"");
+ }
finish:
- if error_converting(long_value) {
- PyErr_SetString(PyExc_TypeError, msg);
- return -1;
+ if error_converting(long_value) {
+ PyErr_SetString(PyExc_TypeError, msg);
+ return -1;
}
#if (SIZEOF_LONGLONG > SIZEOF_INTP)
- if ((long_value < MIN_INTP) || (long_value > MAX_INTP)) {
- PyErr_SetString(PyExc_ValueError,
- "integer won't fit into a C intp");
- return -1;
- }
+ if ((long_value < MIN_INTP) || (long_value > MAX_INTP)) {
+ PyErr_SetString(PyExc_ValueError,
+ "integer won't fit into a C intp");
+ return -1;
+ }
#endif
- return (intp) long_value;
+ return (intp) long_value;
}
@@ -617,267 +616,267 @@ static PyObject *array_int(PyArrayObject *v);
static int
PyArray_PyIntAsInt(PyObject *o)
{
- long long_value = -1;
- PyObject *obj;
- static char *msg = "an integer is required";
- PyObject *arr;
- PyArray_Descr *descr;
- int ret;
+ long long_value = -1;
+ PyObject *obj;
+ static char *msg = "an integer is required";
+ PyObject *arr;
+ PyArray_Descr *descr;
+ int ret;
- if (!o) {
- PyErr_SetString(PyExc_TypeError, msg);
- return -1;
- }
+ if (!o) {
+ PyErr_SetString(PyExc_TypeError, msg);
+ return -1;
+ }
- if (PyInt_Check(o)) {
- long_value = (long) PyInt_AS_LONG(o);
- goto finish;
- } else if (PyLong_Check(o)) {
- long_value = (long) PyLong_AsLong(o);
- goto finish;
- }
+ if (PyInt_Check(o)) {
+ long_value = (long) PyInt_AS_LONG(o);
+ goto finish;
+ } else if (PyLong_Check(o)) {
+ long_value = (long) PyLong_AsLong(o);
+ goto finish;
+ }
- descr = &INT_Descr;
- arr=NULL;
- if (PyArray_Check(o)) {
- if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
- PyErr_SetString(PyExc_TypeError, msg);
- return -1;
- }
- Py_INCREF(descr);
- arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
- }
- if (PyArray_IsScalar(o, Integer)) {
- Py_INCREF(descr);
- arr = PyArray_FromScalar(o, descr);
- }
- if (arr != NULL) {
- ret = *((int *)PyArray_DATA(arr));
- Py_DECREF(arr);
- return ret;
+ descr = &INT_Descr;
+ arr=NULL;
+ if (PyArray_Check(o)) {
+ if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
+ PyErr_SetString(PyExc_TypeError, msg);
+ return -1;
}
+ Py_INCREF(descr);
+ arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
+ }
+ if (PyArray_IsScalar(o, Integer)) {
+ Py_INCREF(descr);
+ arr = PyArray_FromScalar(o, descr);
+ }
+ if (arr != NULL) {
+ ret = *((int *)PyArray_DATA(arr));
+ Py_DECREF(arr);
+ return ret;
+ }
#if (PY_VERSION_HEX >= 0x02050000)
- if (PyIndex_Check(o)) {
- PyObject* value = PyNumber_Index(o);
- long_value = (longlong) PyInt_AsSsize_t(value);
- goto finish;
- }
+ if (PyIndex_Check(o)) {
+ PyObject* value = PyNumber_Index(o);
+ long_value = (longlong) PyInt_AsSsize_t(value);
+ goto finish;
+ }
#endif
- if (o->ob_type->tp_as_number != NULL && \
- o->ob_type->tp_as_number->nb_int != NULL) {
- obj = o->ob_type->tp_as_number->nb_int(o);
- if (obj == NULL) return -1;
- long_value = (long) PyLong_AsLong(obj);
- Py_DECREF(obj);
- }
- else if (o->ob_type->tp_as_number != NULL && \
- o->ob_type->tp_as_number->nb_long != NULL) {
- obj = o->ob_type->tp_as_number->nb_long(o);
- if (obj == NULL) return -1;
- long_value = (long) PyLong_AsLong(obj);
- Py_DECREF(obj);
- }
- else {
- PyErr_SetString(PyExc_NotImplementedError,"");
- }
+ if (o->ob_type->tp_as_number != NULL && \
+ o->ob_type->tp_as_number->nb_int != NULL) {
+ obj = o->ob_type->tp_as_number->nb_int(o);
+ if (obj == NULL) return -1;
+ long_value = (long) PyLong_AsLong(obj);
+ Py_DECREF(obj);
+ }
+ else if (o->ob_type->tp_as_number != NULL && \
+ o->ob_type->tp_as_number->nb_long != NULL) {
+ obj = o->ob_type->tp_as_number->nb_long(o);
+ if (obj == NULL) return -1;
+ long_value = (long) PyLong_AsLong(obj);
+ Py_DECREF(obj);
+ }
+ else {
+ PyErr_SetString(PyExc_NotImplementedError,"");
+ }
finish:
- if error_converting(long_value) {
- PyErr_SetString(PyExc_TypeError, msg);
- return -1;
+ if error_converting(long_value) {
+ PyErr_SetString(PyExc_TypeError, msg);
+ return -1;
}
#if (SIZEOF_LONG > SIZEOF_INT)
- if ((long_value < INT_MIN) || (long_value > INT_MAX)) {
- PyErr_SetString(PyExc_ValueError,
- "integer won't fit into a C int");
- return -1;
- }
+ if ((long_value < INT_MIN) || (long_value > INT_MAX)) {
+ PyErr_SetString(PyExc_ValueError,
+ "integer won't fit into a C int");
+ return -1;
+ }
#endif
- return (int) long_value;
+ return (int) long_value;
}
static char *
index2ptr(PyArrayObject *mp, intp i)
{
- intp dim0;
- if(mp->nd == 0) {
- PyErr_SetString(PyExc_IndexError,
- "0-d arrays can't be indexed");
- return NULL;
- }
- dim0 = mp->dimensions[0];
- if (i<0) i += dim0;
- if (i==0 && dim0 > 0)
- return mp->data;
-
- if (i>0 && i < dim0) {
- return mp->data+i*mp->strides[0];
- }
- PyErr_SetString(PyExc_IndexError,"index out of bounds");
+ intp dim0;
+ if(mp->nd == 0) {
+ PyErr_SetString(PyExc_IndexError,
+ "0-d arrays can't be indexed");
return NULL;
+ }
+ dim0 = mp->dimensions[0];
+ if (i<0) i += dim0;
+ if (i==0 && dim0 > 0)
+ return mp->data;
+
+ if (i>0 && i < dim0) {
+ return mp->data+i*mp->strides[0];
+ }
+ PyErr_SetString(PyExc_IndexError,"index out of bounds");
+ return NULL;
}
/*OBJECT_API
- Compute the size of an array (in number of items)
+ Compute the size of an array (in number of items)
*/
static intp
PyArray_Size(PyObject *op)
{
- if (PyArray_Check(op)) {
- return PyArray_SIZE((PyArrayObject *)op);
- }
- else {
- return 0;
- }
+ if (PyArray_Check(op)) {
+ return PyArray_SIZE((PyArrayObject *)op);
+ }
+ else {
+ return 0;
+ }
}
static int
_copy_from0d(PyArrayObject *dest, PyArrayObject *src, int usecopy, int swap)
{
- char *aligned=NULL;
- char *sptr;
- int numcopies, nbytes;
- void (*myfunc)(char *, intp, char *, intp, intp, int);
- int retval=-1;
+ char *aligned=NULL;
+ char *sptr;
+ int numcopies, nbytes;
+ void (*myfunc)(char *, intp, char *, intp, intp, int);
+ int retval=-1;
- NPY_BEGIN_THREADS_DEF
+ NPY_BEGIN_THREADS_DEF
numcopies = PyArray_SIZE(dest);
- if (numcopies < 1) return 0;
- nbytes = PyArray_ITEMSIZE(src);
-
- if (!PyArray_ISALIGNED(src)) {
- aligned = malloc((size_t)nbytes);
- if (aligned == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- memcpy(aligned, src->data, (size_t) nbytes);
- usecopy = 1;
- sptr = aligned;
- }
- else sptr = src->data;
- if (PyArray_ISALIGNED(dest)) {
- myfunc = _strided_byte_copy;
- }
- else if (usecopy) {
- myfunc = _unaligned_strided_byte_copy;
- }
- else {
- myfunc = _unaligned_strided_byte_move;
- }
+ if (numcopies < 1) return 0;
+ nbytes = PyArray_ITEMSIZE(src);
+
+ if (!PyArray_ISALIGNED(src)) {
+ aligned = malloc((size_t)nbytes);
+ if (aligned == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memcpy(aligned, src->data, (size_t) nbytes);
+ usecopy = 1;
+ sptr = aligned;
+ }
+ else sptr = src->data;
+ if (PyArray_ISALIGNED(dest)) {
+ myfunc = _strided_byte_copy;
+ }
+ else if (usecopy) {
+ myfunc = _unaligned_strided_byte_copy;
+ }
+ else {
+ myfunc = _unaligned_strided_byte_move;
+ }
- if ((dest->nd < 2) || PyArray_ISONESEGMENT(dest)) {
- char *dptr;
- intp dstride;
+ if ((dest->nd < 2) || PyArray_ISONESEGMENT(dest)) {
+ char *dptr;
+ intp dstride;
- dptr = dest->data;
- if (dest->nd == 1)
- dstride = dest->strides[0];
- else
- dstride = nbytes;
+ dptr = dest->data;
+ if (dest->nd == 1)
+ dstride = dest->strides[0];
+ else
+ dstride = nbytes;
- PyArray_INCREF(src);
- PyArray_XDECREF(dest);
+ PyArray_INCREF(src);
+ PyArray_XDECREF(dest);
- NPY_BEGIN_THREADS
+ NPY_BEGIN_THREADS
- myfunc(dptr, dstride, sptr, 0, numcopies, (int) nbytes);
- if (swap)
- _strided_byte_swap(dptr, dstride, numcopies, (int) nbytes);
+ myfunc(dptr, dstride, sptr, 0, numcopies, (int) nbytes);
+ if (swap)
+ _strided_byte_swap(dptr, dstride, numcopies, (int) nbytes);
- NPY_END_THREADS
+ NPY_END_THREADS
- }
- else {
- PyArrayIterObject *dit;
- int axis=-1;
- dit = (PyArrayIterObject *)\
- PyArray_IterAllButAxis((PyObject *)dest, &axis);
- if (dit == NULL) goto finish;
- PyArray_INCREF(src);
- PyArray_XDECREF(dest);
- NPY_BEGIN_THREADS
- while(dit->index < dit->size) {
- myfunc(dit->dataptr, PyArray_STRIDE(dest, axis),
- sptr, 0,
- PyArray_DIM(dest, axis), nbytes);
- if (swap)
- _strided_byte_swap(dit->dataptr,
- PyArray_STRIDE(dest, axis),
- PyArray_DIM(dest, axis), nbytes);
- PyArray_ITER_NEXT(dit);
- }
- NPY_END_THREADS
- Py_DECREF(dit);
- }
- retval = 0;
+ }
+ else {
+ PyArrayIterObject *dit;
+ int axis=-1;
+ dit = (PyArrayIterObject *)\
+ PyArray_IterAllButAxis((PyObject *)dest, &axis);
+ if (dit == NULL) goto finish;
+ PyArray_INCREF(src);
+ PyArray_XDECREF(dest);
+ NPY_BEGIN_THREADS
+ while(dit->index < dit->size) {
+ myfunc(dit->dataptr, PyArray_STRIDE(dest, axis),
+ sptr, 0,
+ PyArray_DIM(dest, axis), nbytes);
+ if (swap)
+ _strided_byte_swap(dit->dataptr,
+ PyArray_STRIDE(dest, axis),
+ PyArray_DIM(dest, axis), nbytes);
+ PyArray_ITER_NEXT(dit);
+ }
+ NPY_END_THREADS
+ Py_DECREF(dit);
+ }
+ retval = 0;
finish:
- if (aligned != NULL) free(aligned);
- return retval;
+ if (aligned != NULL) free(aligned);
+ return retval;
}
/* Special-case of PyArray_CopyInto when dst is 1-d
and contiguous (and aligned).
PyArray_CopyInto requires broadcastable arrays while
this one is a flattening operation...
- */
+*/
int _flat_copyinto(PyObject *dst, PyObject *src, NPY_ORDER order) {
- PyArrayIterObject *it;
- void (*myfunc)(char *, intp, char *, intp, intp, int);
- char *dptr;
- int axis;
- int elsize;
- intp nbytes;
- NPY_BEGIN_THREADS_DEF
+ PyArrayIterObject *it;
+ void (*myfunc)(char *, intp, char *, intp, intp, int);
+ char *dptr;
+ int axis;
+ int elsize;
+ intp nbytes;
+ NPY_BEGIN_THREADS_DEF
if (PyArray_NDIM(src) == 0) {
- PyArray_INCREF((PyArrayObject *)src);
- PyArray_XDECREF((PyArrayObject *)dst);
- NPY_BEGIN_THREADS
+ PyArray_INCREF((PyArrayObject *)src);
+ PyArray_XDECREF((PyArrayObject *)dst);
+ NPY_BEGIN_THREADS
memcpy(PyArray_BYTES(dst), PyArray_BYTES(src),
PyArray_ITEMSIZE(src));
- NPY_END_THREADS
+ NPY_END_THREADS
return 0;
}
- if (order == PyArray_FORTRANORDER) {
- axis = 0;
- }
- else {
- axis = PyArray_NDIM(src)-1;
- }
+ if (order == PyArray_FORTRANORDER) {
+ axis = 0;
+ }
+ else {
+ axis = PyArray_NDIM(src)-1;
+ }
- it = (PyArrayIterObject *)PyArray_IterAllButAxis(src, &axis);
- if (it == NULL) return -1;
+ it = (PyArrayIterObject *)PyArray_IterAllButAxis(src, &axis);
+ if (it == NULL) return -1;
- if (PyArray_ISALIGNED(src)) {
- myfunc = _strided_byte_copy;
- }
- else {
- myfunc = _unaligned_strided_byte_copy;
- }
+ if (PyArray_ISALIGNED(src)) {
+ myfunc = _strided_byte_copy;
+ }
+ else {
+ myfunc = _unaligned_strided_byte_copy;
+ }
- dptr = PyArray_BYTES(dst);
- elsize = PyArray_ITEMSIZE(dst);
- nbytes = elsize * PyArray_DIM(src, axis);
- PyArray_INCREF((PyArrayObject *)src);
- PyArray_XDECREF((PyArrayObject *)dst);
- NPY_BEGIN_THREADS
+ dptr = PyArray_BYTES(dst);
+ elsize = PyArray_ITEMSIZE(dst);
+ nbytes = elsize * PyArray_DIM(src, axis);
+ PyArray_INCREF((PyArrayObject *)src);
+ PyArray_XDECREF((PyArrayObject *)dst);
+ NPY_BEGIN_THREADS
while(it->index < it->size) {
- myfunc(dptr, elsize, it->dataptr,
- PyArray_STRIDE(src,axis),
- PyArray_DIM(src,axis), elsize);
- dptr += nbytes;
- PyArray_ITER_NEXT(it);
+ myfunc(dptr, elsize, it->dataptr,
+ PyArray_STRIDE(src,axis),
+ PyArray_DIM(src,axis), elsize);
+ dptr += nbytes;
+ PyArray_ITER_NEXT(it);
}
- NPY_END_THREADS
+ NPY_END_THREADS
Py_DECREF(it);
- return 0;
+ return 0;
}
@@ -886,48 +885,48 @@ _copy_from_same_shape(PyArrayObject *dest, PyArrayObject *src,
void (*myfunc)(char *, intp, char *, intp, intp, int),
int swap)
{
- int maxaxis=-1, elsize;
- intp maxdim;
- PyArrayIterObject *dit, *sit;
- NPY_BEGIN_THREADS_DEF
+ int maxaxis=-1, elsize;
+ intp maxdim;
+ PyArrayIterObject *dit, *sit;
+ NPY_BEGIN_THREADS_DEF
dit = (PyArrayIterObject *) \
- PyArray_IterAllButAxis((PyObject *)dest, &maxaxis);
- sit = (PyArrayIterObject *) \
- PyArray_IterAllButAxis((PyObject *)src, &maxaxis);
+ PyArray_IterAllButAxis((PyObject *)dest, &maxaxis);
+ sit = (PyArrayIterObject *) \
+ PyArray_IterAllButAxis((PyObject *)src, &maxaxis);
- maxdim = dest->dimensions[maxaxis];
+ maxdim = dest->dimensions[maxaxis];
- if ((dit == NULL) || (sit == NULL)) {
- Py_XDECREF(dit);
- Py_XDECREF(sit);
- return -1;
- }
- elsize = PyArray_ITEMSIZE(dest);
+ if ((dit == NULL) || (sit == NULL)) {
+ Py_XDECREF(dit);
+ Py_XDECREF(sit);
+ return -1;
+ }
+ elsize = PyArray_ITEMSIZE(dest);
- PyArray_INCREF(src);
- PyArray_XDECREF(dest);
+ PyArray_INCREF(src);
+ PyArray_XDECREF(dest);
- NPY_BEGIN_THREADS
+ NPY_BEGIN_THREADS
while(dit->index < dit->size) {
- /* strided copy of elsize bytes */
- myfunc(dit->dataptr, dest->strides[maxaxis],
- sit->dataptr, src->strides[maxaxis],
- maxdim, elsize);
- if (swap) {
- _strided_byte_swap(dit->dataptr,
- dest->strides[maxaxis],
- dest->dimensions[maxaxis],
- elsize);
- }
- PyArray_ITER_NEXT(dit);
- PyArray_ITER_NEXT(sit);
+ /* strided copy of elsize bytes */
+ myfunc(dit->dataptr, dest->strides[maxaxis],
+ sit->dataptr, src->strides[maxaxis],
+ maxdim, elsize);
+ if (swap) {
+ _strided_byte_swap(dit->dataptr,
+ dest->strides[maxaxis],
+ dest->dimensions[maxaxis],
+ elsize);
+ }
+ PyArray_ITER_NEXT(dit);
+ PyArray_ITER_NEXT(sit);
}
- NPY_END_THREADS
+ NPY_END_THREADS
Py_DECREF(sit);
- Py_DECREF(dit);
- return 0;
+ Py_DECREF(dit);
+ return 0;
}
static int
@@ -935,57 +934,57 @@ _broadcast_copy(PyArrayObject *dest, PyArrayObject *src,
void (*myfunc)(char *, intp, char *, intp, intp, int),
int swap)
{
- int elsize;
- PyArrayMultiIterObject *multi;
- int maxaxis; intp maxdim;
- NPY_BEGIN_THREADS_DEF
+ int elsize;
+ PyArrayMultiIterObject *multi;
+ int maxaxis; intp maxdim;
+ NPY_BEGIN_THREADS_DEF
elsize = PyArray_ITEMSIZE(dest);
- multi = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, dest, src);
- if (multi == NULL) return -1;
-
- if (multi->size != PyArray_SIZE(dest)) {
- PyErr_SetString(PyExc_ValueError,
- "array dimensions are not "\
- "compatible for copy");
- Py_DECREF(multi);
- return -1;
- }
+ multi = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, dest, src);
+ if (multi == NULL) return -1;
- maxaxis = PyArray_RemoveSmallest(multi);
- if (maxaxis < 0) { /* copy 1 0-d array to another */
- PyArray_INCREF(src);
- PyArray_XDECREF(dest);
- memcpy(dest->data, src->data, elsize);
- if (swap) byte_swap_vector(dest->data, 1, elsize);
- return 0;
- }
- maxdim = multi->dimensions[maxaxis];
+ if (multi->size != PyArray_SIZE(dest)) {
+ PyErr_SetString(PyExc_ValueError,
+ "array dimensions are not "\
+ "compatible for copy");
+ Py_DECREF(multi);
+ return -1;
+ }
- /* Increment the source and decrement the destination
- reference counts
- */
+ maxaxis = PyArray_RemoveSmallest(multi);
+ if (maxaxis < 0) { /* copy 1 0-d array to another */
PyArray_INCREF(src);
PyArray_XDECREF(dest);
+ memcpy(dest->data, src->data, elsize);
+ if (swap) byte_swap_vector(dest->data, 1, elsize);
+ return 0;
+ }
+ maxdim = multi->dimensions[maxaxis];
- NPY_BEGIN_THREADS
+ /* Increment the source and decrement the destination
+ reference counts
+ */
+ PyArray_INCREF(src);
+ PyArray_XDECREF(dest);
+
+ NPY_BEGIN_THREADS
while(multi->index < multi->size) {
- myfunc(multi->iters[0]->dataptr,
- multi->iters[0]->strides[maxaxis],
- multi->iters[1]->dataptr,
- multi->iters[1]->strides[maxaxis],
- maxdim, elsize);
- if (swap) {
- _strided_byte_swap(multi->iters[0]->dataptr,
- multi->iters[0]->strides[maxaxis],
- maxdim, elsize);
- }
- PyArray_MultiIter_NEXT(multi);
+ myfunc(multi->iters[0]->dataptr,
+ multi->iters[0]->strides[maxaxis],
+ multi->iters[1]->dataptr,
+ multi->iters[1]->strides[maxaxis],
+ maxdim, elsize);
+ if (swap) {
+ _strided_byte_swap(multi->iters[0]->dataptr,
+ multi->iters[0]->strides[maxaxis],
+ maxdim, elsize);
+ }
+ PyArray_MultiIter_NEXT(multi);
}
- NPY_END_THREADS
+ NPY_END_THREADS
Py_DECREF(multi);
- return 0;
+ return 0;
}
/* If destination is not the right type, then src
@@ -1002,157 +1001,157 @@ _broadcast_copy(PyArrayObject *dest, PyArrayObject *src,
static int
_array_copy_into(PyArrayObject *dest, PyArrayObject *src, int usecopy)
{
- int swap;
- void (*myfunc)(char *, intp, char *, intp, intp, int);
- int simple;
- int same;
- NPY_BEGIN_THREADS_DEF
+ int swap;
+ void (*myfunc)(char *, intp, char *, intp, intp, int);
+ int simple;
+ int same;
+ NPY_BEGIN_THREADS_DEF
if (!PyArray_EquivArrTypes(dest, src)) {
- return PyArray_CastTo(dest, src);
+ return PyArray_CastTo(dest, src);
}
- if (!PyArray_ISWRITEABLE(dest)) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot write to array");
- return -1;
- }
+ if (!PyArray_ISWRITEABLE(dest)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot write to array");
+ return -1;
+ }
- same = PyArray_SAMESHAPE(dest, src);
- simple = same && ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
- (PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
+ same = PyArray_SAMESHAPE(dest, src);
+ simple = same && ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
+ (PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
- if (simple) {
- PyArray_INCREF(src);
- PyArray_XDECREF(dest);
- NPY_BEGIN_THREADS
- if (usecopy)
- memcpy(dest->data, src->data, PyArray_NBYTES(dest));
- else
- memmove(dest->data, src->data, PyArray_NBYTES(dest));
- NPY_END_THREADS
- return 0;
- }
+ if (simple) {
+ PyArray_INCREF(src);
+ PyArray_XDECREF(dest);
+ NPY_BEGIN_THREADS
+ if (usecopy)
+ memcpy(dest->data, src->data, PyArray_NBYTES(dest));
+ else
+ memmove(dest->data, src->data, PyArray_NBYTES(dest));
+ NPY_END_THREADS
+ return 0;
+ }
- swap = PyArray_ISNOTSWAPPED(dest) != PyArray_ISNOTSWAPPED(src);
+ swap = PyArray_ISNOTSWAPPED(dest) != PyArray_ISNOTSWAPPED(src);
- if (src->nd == 0) {
- return _copy_from0d(dest, src, usecopy, swap);
- }
+ if (src->nd == 0) {
+ return _copy_from0d(dest, src, usecopy, swap);
+ }
- if (PyArray_ISALIGNED(dest) && PyArray_ISALIGNED(src)) {
- myfunc = _strided_byte_copy;
- }
- else if (usecopy) {
- myfunc = _unaligned_strided_byte_copy;
- }
- else {
- myfunc = _unaligned_strided_byte_move;
- }
+ if (PyArray_ISALIGNED(dest) && PyArray_ISALIGNED(src)) {
+ myfunc = _strided_byte_copy;
+ }
+ else if (usecopy) {
+ myfunc = _unaligned_strided_byte_copy;
+ }
+ else {
+ myfunc = _unaligned_strided_byte_move;
+ }
- /* Could combine these because _broadcasted_copy would work as well.
- But, same-shape copying is so common we want to speed it up.
- */
- if (same) {
- return _copy_from_same_shape(dest, src, myfunc, swap);
- }
- else {
- return _broadcast_copy(dest, src, myfunc, swap);
- }
+ /* Could combine these because _broadcasted_copy would work as well.
+ But, same-shape copying is so common we want to speed it up.
+ */
+ if (same) {
+ return _copy_from_same_shape(dest, src, myfunc, swap);
+ }
+ else {
+ return _broadcast_copy(dest, src, myfunc, swap);
+ }
}
/*OBJECT_API
- Copy an Array into another array -- memory must not overlap
- Does not require src and dest to have "broadcastable" shapes
- (only the same number of elements).
+ Copy an Array into another array -- memory must not overlap
+ Does not require src and dest to have "broadcastable" shapes
+ (only the same number of elements).
*/
static int
PyArray_CopyAnyInto(PyArrayObject *dest, PyArrayObject *src)
{
- int elsize, simple;
- PyArrayIterObject *idest, *isrc;
- void (*myfunc)(char *, intp, char *, intp, intp, int);
- NPY_BEGIN_THREADS_DEF
+ int elsize, simple;
+ PyArrayIterObject *idest, *isrc;
+ void (*myfunc)(char *, intp, char *, intp, intp, int);
+ NPY_BEGIN_THREADS_DEF
if (!PyArray_EquivArrTypes(dest, src)) {
- return PyArray_CastAnyTo(dest, src);
- }
-
- if (!PyArray_ISWRITEABLE(dest)) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot write to array");
- return -1;
- }
-
- if (PyArray_SIZE(dest) != PyArray_SIZE(src)) {
- PyErr_SetString(PyExc_ValueError,
- "arrays must have the same number of elements"
- " for copy");
- return -1;
+ return PyArray_CastAnyTo(dest, src);
}
- simple = ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
- (PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
+ if (!PyArray_ISWRITEABLE(dest)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot write to array");
+ return -1;
+ }
- if (simple) {
- PyArray_INCREF(src);
- PyArray_XDECREF(dest);
- NPY_BEGIN_THREADS
- memcpy(dest->data, src->data, PyArray_NBYTES(dest));
- NPY_END_THREADS
- return 0;
- }
+ if (PyArray_SIZE(dest) != PyArray_SIZE(src)) {
+ PyErr_SetString(PyExc_ValueError,
+ "arrays must have the same number of elements"
+ " for copy");
+ return -1;
+ }
- if (PyArray_SAMESHAPE(dest, src)) {
- int swap;
- if (PyArray_ISALIGNED(dest) && PyArray_ISALIGNED(src)) {
- myfunc = _strided_byte_copy;
- }
- else {
- myfunc = _unaligned_strided_byte_copy;
- }
- swap = PyArray_ISNOTSWAPPED(dest) != PyArray_ISNOTSWAPPED(src);
- return _copy_from_same_shape(dest, src, myfunc, swap);
- }
+ simple = ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
+ (PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
- /* Otherwise we have to do an iterator-based copy */
- idest = (PyArrayIterObject *)PyArray_IterNew((PyObject *)dest);
- if (idest == NULL) return -1;
- isrc = (PyArrayIterObject *)PyArray_IterNew((PyObject *)src);
- if (isrc == NULL) {Py_DECREF(idest); return -1;}
- elsize = dest->descr->elsize;
+ if (simple) {
PyArray_INCREF(src);
PyArray_XDECREF(dest);
NPY_BEGIN_THREADS
+ memcpy(dest->data, src->data, PyArray_NBYTES(dest));
+ NPY_END_THREADS
+ return 0;
+ }
+
+ if (PyArray_SAMESHAPE(dest, src)) {
+ int swap;
+ if (PyArray_ISALIGNED(dest) && PyArray_ISALIGNED(src)) {
+ myfunc = _strided_byte_copy;
+ }
+ else {
+ myfunc = _unaligned_strided_byte_copy;
+ }
+ swap = PyArray_ISNOTSWAPPED(dest) != PyArray_ISNOTSWAPPED(src);
+ return _copy_from_same_shape(dest, src, myfunc, swap);
+ }
+
+ /* Otherwise we have to do an iterator-based copy */
+ idest = (PyArrayIterObject *)PyArray_IterNew((PyObject *)dest);
+ if (idest == NULL) return -1;
+ isrc = (PyArrayIterObject *)PyArray_IterNew((PyObject *)src);
+ if (isrc == NULL) {Py_DECREF(idest); return -1;}
+ elsize = dest->descr->elsize;
+ PyArray_INCREF(src);
+ PyArray_XDECREF(dest);
+ NPY_BEGIN_THREADS
while(idest->index < idest->size) {
- memcpy(idest->dataptr, isrc->dataptr, elsize);
- PyArray_ITER_NEXT(idest);
- PyArray_ITER_NEXT(isrc);
+ memcpy(idest->dataptr, isrc->dataptr, elsize);
+ PyArray_ITER_NEXT(idest);
+ PyArray_ITER_NEXT(isrc);
}
- NPY_END_THREADS
+ NPY_END_THREADS
Py_DECREF(idest);
- Py_DECREF(isrc);
- return 0;
+ Py_DECREF(isrc);
+ return 0;
}
/*OBJECT_API
- Copy an Array into another array -- memory must not overlap.
+ Copy an Array into another array -- memory must not overlap.
*/
static int
PyArray_CopyInto(PyArrayObject *dest, PyArrayObject *src)
{
- return _array_copy_into(dest, src, 1);
+ return _array_copy_into(dest, src, 1);
}
/*OBJECT_API
- Move the memory of one array into another.
+ Move the memory of one array into another.
*/
static int
PyArray_MoveInto(PyArrayObject *dest, PyArrayObject *src)
{
- return _array_copy_into(dest, src, 0);
+ return _array_copy_into(dest, src, 0);
}
@@ -1160,54 +1159,54 @@ PyArray_MoveInto(PyArrayObject *dest, PyArrayObject *src)
static int
PyArray_CopyObject(PyArrayObject *dest, PyObject *src_object)
{
- PyArrayObject *src;
- PyObject *r;
- int ret;
-
- /* Special code to mimic Numeric behavior for
- character arrays.
- */
- if (dest->descr->type == PyArray_CHARLTR && dest->nd > 0 \
- && PyString_Check(src_object)) {
- int n_new, n_old;
- char *new_string;
- PyObject *tmp;
- n_new = dest->dimensions[dest->nd-1];
- n_old = PyString_Size(src_object);
- if (n_new > n_old) {
- new_string = (char *)malloc(n_new);
- memmove(new_string,
- PyString_AS_STRING(src_object),
- n_old);
- memset(new_string+n_old, ' ', n_new-n_old);
- tmp = PyString_FromStringAndSize(new_string, n_new);
- free(new_string);
- src_object = tmp;
- }
+ PyArrayObject *src;
+ PyObject *r;
+ int ret;
+
+ /* Special code to mimic Numeric behavior for
+ character arrays.
+ */
+ if (dest->descr->type == PyArray_CHARLTR && dest->nd > 0 \
+ && PyString_Check(src_object)) {
+ int n_new, n_old;
+ char *new_string;
+ PyObject *tmp;
+ n_new = dest->dimensions[dest->nd-1];
+ n_old = PyString_Size(src_object);
+ if (n_new > n_old) {
+ new_string = (char *)malloc(n_new);
+ memmove(new_string,
+ PyString_AS_STRING(src_object),
+ n_old);
+ memset(new_string+n_old, ' ', n_new-n_old);
+ tmp = PyString_FromStringAndSize(new_string, n_new);
+ free(new_string);
+ src_object = tmp;
}
+ }
- if (PyArray_Check(src_object)) {
- src = (PyArrayObject *)src_object;
- Py_INCREF(src);
- }
- else if (!PyArray_IsScalar(src_object, Generic) &&
- PyArray_HasArrayInterface(src_object, r)) {
- src = (PyArrayObject *)r;
- }
- else {
- PyArray_Descr* dtype;
- dtype = dest->descr;
- Py_INCREF(dtype);
- src = (PyArrayObject *)PyArray_FromAny(src_object, dtype, 0,
- dest->nd,
- FORTRAN_IF(dest),
- NULL);
- }
- if (src == NULL) return -1;
-
- ret = PyArray_MoveInto(dest, src);
- Py_DECREF(src);
- return ret;
+ if (PyArray_Check(src_object)) {
+ src = (PyArrayObject *)src_object;
+ Py_INCREF(src);
+ }
+ else if (!PyArray_IsScalar(src_object, Generic) &&
+ PyArray_HasArrayInterface(src_object, r)) {
+ src = (PyArrayObject *)r;
+ }
+ else {
+ PyArray_Descr* dtype;
+ dtype = dest->descr;
+ Py_INCREF(dtype);
+ src = (PyArrayObject *)PyArray_FromAny(src_object, dtype, 0,
+ dest->nd,
+ FORTRAN_IF(dest),
+ NULL);
+ }
+ if (src == NULL) return -1;
+
+ ret = PyArray_MoveInto(dest, src);
+ Py_DECREF(src);
+ return ret;
}
@@ -1217,228 +1216,228 @@ PyArray_CopyObject(PyArrayObject *dest, PyObject *src_object)
/* steals reference to descr -- and enforces native byteorder on it.*/
/*OBJECT_API
- Like FromDimsAndData but uses the Descr structure instead of typecode
- as input.
+ Like FromDimsAndData but uses the Descr structure instead of typecode
+ as input.
*/
static PyObject *
PyArray_FromDimsAndDataAndDescr(int nd, int *d,
PyArray_Descr *descr,
char *data)
{
- PyObject *ret;
+ PyObject *ret;
#if SIZEOF_INTP != SIZEOF_INT
- int i;
- intp newd[MAX_DIMS];
+ int i;
+ intp newd[MAX_DIMS];
#endif
- if (!PyArray_ISNBO(descr->byteorder))
- descr->byteorder = '=';
+ if (!PyArray_ISNBO(descr->byteorder))
+ descr->byteorder = '=';
#if SIZEOF_INTP != SIZEOF_INT
- for (i=0; i<nd; i++) newd[i] = (intp) d[i];
- ret = PyArray_NewFromDescr(&PyArray_Type, descr,
- nd, newd,
- NULL, data,
- (data ? CARRAY : 0), NULL);
+ for (i=0; i<nd; i++) newd[i] = (intp) d[i];
+ ret = PyArray_NewFromDescr(&PyArray_Type, descr,
+ nd, newd,
+ NULL, data,
+ (data ? CARRAY : 0), NULL);
#else
- ret = PyArray_NewFromDescr(&PyArray_Type, descr,
- nd, (intp *)d,
- NULL, data,
- (data ? CARRAY : 0), NULL);
+ ret = PyArray_NewFromDescr(&PyArray_Type, descr,
+ nd, (intp *)d,
+ NULL, data,
+ (data ? CARRAY : 0), NULL);
#endif
- return ret;
+ return ret;
}
/*OBJECT_API
- Construct an empty array from dimensions and typenum
+ Construct an empty array from dimensions and typenum
*/
static PyObject *
PyArray_FromDims(int nd, int *d, int type)
{
- PyObject *ret;
- ret = PyArray_FromDimsAndDataAndDescr(nd, d,
- PyArray_DescrFromType(type),
- NULL);
- /* Old FromDims set memory to zero --- some algorithms
- relied on that. Better keep it the same. If
- Object type, then it's already been set to zero, though.
- */
- if (ret && (PyArray_DESCR(ret)->type_num != PyArray_OBJECT)) {
- memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret));
- }
- return ret;
+ PyObject *ret;
+ ret = PyArray_FromDimsAndDataAndDescr(nd, d,
+ PyArray_DescrFromType(type),
+ NULL);
+ /* Old FromDims set memory to zero --- some algorithms
+ relied on that. Better keep it the same. If
+ Object type, then it's already been set to zero, though.
+ */
+ if (ret && (PyArray_DESCR(ret)->type_num != PyArray_OBJECT)) {
+ memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret));
+ }
+ return ret;
}
/* end old calls */
/*OBJECT_API
- Copy an array.
+ Copy an array.
*/
static PyObject *
PyArray_NewCopy(PyArrayObject *m1, NPY_ORDER fortran)
{
- PyArrayObject *ret;
- if (fortran == PyArray_ANYORDER)
- fortran = PyArray_ISFORTRAN(m1);
-
- Py_INCREF(m1->descr);
- ret = (PyArrayObject *)PyArray_NewFromDescr(m1->ob_type,
- m1->descr,
- m1->nd,
- m1->dimensions,
- NULL, NULL,
- fortran,
- (PyObject *)m1);
- if (ret == NULL) return NULL;
- if (PyArray_CopyInto(ret, m1) == -1) {
- Py_DECREF(ret);
- return NULL;
- }
+ PyArrayObject *ret;
+ if (fortran == PyArray_ANYORDER)
+ fortran = PyArray_ISFORTRAN(m1);
+
+ Py_INCREF(m1->descr);
+ ret = (PyArrayObject *)PyArray_NewFromDescr(m1->ob_type,
+ m1->descr,
+ m1->nd,
+ m1->dimensions,
+ NULL, NULL,
+ fortran,
+ (PyObject *)m1);
+ if (ret == NULL) return NULL;
+ if (PyArray_CopyInto(ret, m1) == -1) {
+ Py_DECREF(ret);
+ return NULL;
+ }
- return (PyObject *)ret;
+ return (PyObject *)ret;
}
static PyObject *array_big_item(PyArrayObject *, intp);
/* Does nothing with descr (cannot be NULL) */
/*OBJECT_API
- Get scalar-equivalent to a region of memory described by a descriptor.
+ Get scalar-equivalent to a region of memory described by a descriptor.
*/
static PyObject *
PyArray_Scalar(void *data, PyArray_Descr *descr, PyObject *base)
{
- PyTypeObject *type;
- PyObject *obj;
- void *destptr;
- PyArray_CopySwapFunc *copyswap;
- int type_num;
- int itemsize;
- int swap;
-
- type_num = descr->type_num;
- if (type_num == PyArray_BOOL)
- PyArrayScalar_RETURN_BOOL_FROM_LONG(*(Bool*)data);
- else if (PyDataType_FLAGCHK(descr, NPY_USE_GETITEM)) {
- return descr->f->getitem(data, base);
- }
- itemsize = descr->elsize;
- copyswap = descr->f->copyswap;
- type = descr->typeobj;
- swap = !PyArray_ISNBO(descr->byteorder);
- if PyTypeNum_ISSTRING(type_num) { /* Eliminate NULL bytes */
- char *dptr = data;
- dptr += itemsize-1;
- while(itemsize && *dptr-- == 0) itemsize--;
- if (type_num == PyArray_UNICODE && itemsize) {
- /* make sure itemsize is a multiple of 4 */
- /* so round up to nearest multiple */
- itemsize = (((itemsize-1) >> 2) + 1) << 2;
- }
+ PyTypeObject *type;
+ PyObject *obj;
+ void *destptr;
+ PyArray_CopySwapFunc *copyswap;
+ int type_num;
+ int itemsize;
+ int swap;
+
+ type_num = descr->type_num;
+ if (type_num == PyArray_BOOL)
+ PyArrayScalar_RETURN_BOOL_FROM_LONG(*(Bool*)data);
+ else if (PyDataType_FLAGCHK(descr, NPY_USE_GETITEM)) {
+ return descr->f->getitem(data, base);
+ }
+ itemsize = descr->elsize;
+ copyswap = descr->f->copyswap;
+ type = descr->typeobj;
+ swap = !PyArray_ISNBO(descr->byteorder);
+ if PyTypeNum_ISSTRING(type_num) { /* Eliminate NULL bytes */
+ char *dptr = data;
+ dptr += itemsize-1;
+ while(itemsize && *dptr-- == 0) itemsize--;
+ if (type_num == PyArray_UNICODE && itemsize) {
+ /* make sure itemsize is a multiple of 4 */
+ /* so round up to nearest multiple */
+ itemsize = (((itemsize-1) >> 2) + 1) << 2;
+ }
}
- if (type->tp_itemsize != 0) /* String type */
- obj = type->tp_alloc(type, itemsize);
- else
- obj = type->tp_alloc(type, 0);
- if (obj == NULL) return NULL;
- if PyTypeNum_ISFLEXIBLE(type_num) {
- if (type_num == PyArray_STRING) {
- destptr = PyString_AS_STRING(obj);
- ((PyStringObject *)obj)->ob_shash = -1;
- ((PyStringObject *)obj)->ob_sstate = \
- SSTATE_NOT_INTERNED;
- memcpy(destptr, data, itemsize);
- return obj;
- }
- else if (type_num == PyArray_UNICODE) {
- PyUnicodeObject *uni = (PyUnicodeObject*)obj;
- int length = itemsize >> 2;
+ if (type->tp_itemsize != 0) /* String type */
+ obj = type->tp_alloc(type, itemsize);
+ else
+ obj = type->tp_alloc(type, 0);
+ if (obj == NULL) return NULL;
+ if PyTypeNum_ISFLEXIBLE(type_num) {
+ if (type_num == PyArray_STRING) {
+ destptr = PyString_AS_STRING(obj);
+ ((PyStringObject *)obj)->ob_shash = -1;
+ ((PyStringObject *)obj)->ob_sstate = \
+ SSTATE_NOT_INTERNED;
+ memcpy(destptr, data, itemsize);
+ return obj;
+ }
+ else if (type_num == PyArray_UNICODE) {
+ PyUnicodeObject *uni = (PyUnicodeObject*)obj;
+ int length = itemsize >> 2;
#ifndef Py_UNICODE_WIDE
- char *buffer;
- int alloc=0;
- length *= 2;
+ char *buffer;
+ int alloc=0;
+ length *= 2;
#endif
- /* Need an extra slot and need to use
- Python memory manager */
- uni->str = NULL;
- destptr = PyMem_NEW(Py_UNICODE,length+1);
- if (destptr == NULL) {
- Py_DECREF(obj);
- return PyErr_NoMemory();
- }
- uni->str = (Py_UNICODE *)destptr;
- uni->str[0] = 0;
- uni->str[length] = 0;
- uni->length = length;
- uni->hash = -1;
- uni->defenc = NULL;
+ /* Need an extra slot and need to use
+ Python memory manager */
+ uni->str = NULL;
+ destptr = PyMem_NEW(Py_UNICODE,length+1);
+ if (destptr == NULL) {
+ Py_DECREF(obj);
+ return PyErr_NoMemory();
+ }
+ uni->str = (Py_UNICODE *)destptr;
+ uni->str[0] = 0;
+ uni->str[length] = 0;
+ uni->length = length;
+ uni->hash = -1;
+ uni->defenc = NULL;
#ifdef Py_UNICODE_WIDE
- memcpy(destptr, data, itemsize);
- if (swap)
- byte_swap_vector(destptr, length, 4);
+ memcpy(destptr, data, itemsize);
+ if (swap)
+ byte_swap_vector(destptr, length, 4);
#else
- /* need aligned data buffer */
- if ((swap) || ((((intp)data) % descr->alignment) != 0)) {
- buffer = _pya_malloc(itemsize);
- if (buffer == NULL)
- return PyErr_NoMemory();
- alloc = 1;
- memcpy(buffer, data, itemsize);
- if (swap) {
- byte_swap_vector(buffer,
- itemsize >> 2, 4);
- }
- }
- else buffer = data;
-
- /* Allocated enough for 2-characters per itemsize.
- Now convert from the data-buffer
- */
- length = PyUCS2Buffer_FromUCS4(uni->str,
- (PyArray_UCS4 *)buffer,
- itemsize >> 2);
- if (alloc) _pya_free(buffer);
- /* Resize the unicode result */
- if (MyPyUnicode_Resize(uni, length) < 0) {
- Py_DECREF(obj);
- return NULL;
- }
+ /* need aligned data buffer */
+ if ((swap) || ((((intp)data) % descr->alignment) != 0)) {
+ buffer = _pya_malloc(itemsize);
+ if (buffer == NULL)
+ return PyErr_NoMemory();
+ alloc = 1;
+ memcpy(buffer, data, itemsize);
+ if (swap) {
+ byte_swap_vector(buffer,
+ itemsize >> 2, 4);
+ }
+ }
+ else buffer = data;
+
+ /* Allocated enough for 2-characters per itemsize.
+ Now convert from the data-buffer
+ */
+ length = PyUCS2Buffer_FromUCS4(uni->str,
+ (PyArray_UCS4 *)buffer,
+ itemsize >> 2);
+ if (alloc) _pya_free(buffer);
+ /* Resize the unicode result */
+ if (MyPyUnicode_Resize(uni, length) < 0) {
+ Py_DECREF(obj);
+ return NULL;
+ }
#endif
+ return obj;
+ }
+ else {
+ PyVoidScalarObject *vobj = (PyVoidScalarObject *)obj;
+ vobj->base = NULL;
+ vobj->descr = descr;
+ Py_INCREF(descr);
+ vobj->obval = NULL;
+ vobj->ob_size = itemsize;
+ vobj->flags = BEHAVED | OWNDATA;
+ swap = 0;
+ if (descr->names) {
+ if (base) {
+ Py_INCREF(base);
+ vobj->base = base;
+ vobj->flags = PyArray_FLAGS(base);
+ vobj->flags &= ~OWNDATA;
+ vobj->obval = data;
return obj;
+ }
}
- else {
- PyVoidScalarObject *vobj = (PyVoidScalarObject *)obj;
- vobj->base = NULL;
- vobj->descr = descr;
- Py_INCREF(descr);
- vobj->obval = NULL;
- vobj->ob_size = itemsize;
- vobj->flags = BEHAVED | OWNDATA;
- swap = 0;
- if (descr->names) {
- if (base) {
- Py_INCREF(base);
- vobj->base = base;
- vobj->flags = PyArray_FLAGS(base);
- vobj->flags &= ~OWNDATA;
- vobj->obval = data;
- return obj;
- }
- }
- destptr = PyDataMem_NEW(itemsize);
- if (destptr == NULL) {
- Py_DECREF(obj);
- return PyErr_NoMemory();
- }
- vobj->obval = destptr;
+ destptr = PyDataMem_NEW(itemsize);
+ if (destptr == NULL) {
+ Py_DECREF(obj);
+ return PyErr_NoMemory();
}
+ vobj->obval = destptr;
+ }
}
- else {
- destptr = scalar_value(obj, descr);
- }
- /* copyswap for OBJECT increments the reference count */
- copyswap(destptr, data, swap, base);
- return obj;
+ else {
+ destptr = scalar_value(obj, descr);
+ }
+ /* copyswap for OBJECT increments the reference count */
+ copyswap(destptr, data, swap, base);
+ return obj;
}
/* returns an Array-Scalar Object of the type of arr
@@ -1455,31 +1454,31 @@ PyArray_Scalar(void *data, PyArray_Descr *descr, PyObject *base)
/* Return Array Scalar if 0-d array object is encountered */
/*OBJECT_API
- Return either an array or the appropriate Python object if the array
- is 0d and matches a Python type.
+ Return either an array or the appropriate Python object if the array
+ is 0d and matches a Python type.
*/
static PyObject *
PyArray_Return(PyArrayObject *mp)
{
- if (mp == NULL) return NULL;
+ if (mp == NULL) return NULL;
- if (PyErr_Occurred()) {
- Py_XDECREF(mp);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_XDECREF(mp);
+ return NULL;
+ }
- if (!PyArray_Check(mp)) return (PyObject *)mp;
+ if (!PyArray_Check(mp)) return (PyObject *)mp;
- if (mp->nd == 0) {
- PyObject *ret;
- ret = PyArray_ToScalar(mp->data, mp);
- Py_DECREF(mp);
- return ret;
- }
- else {
- return (PyObject *)mp;
- }
+ if (mp->nd == 0) {
+ PyObject *ret;
+ ret = PyArray_ToScalar(mp->data, mp);
+ Py_DECREF(mp);
+ return ret;
+ }
+ else {
+ return (PyObject *)mp;
+ }
}
@@ -1489,41 +1488,41 @@ PyArray_Return(PyArrayObject *mp)
static void
PyArray_InitArrFuncs(PyArray_ArrFuncs *f)
{
- int i;
- for (i=0; i<PyArray_NTYPES; i++) {
- f->cast[i] = NULL;
- }
- f->getitem = NULL;
- f->setitem = NULL;
- f->copyswapn = NULL;
- f->copyswap = NULL;
- f->compare = NULL;
- f->argmax = NULL;
- f->dotfunc = NULL;
- f->scanfunc = NULL;
- f->fromstr = NULL;
- f->nonzero = NULL;
- f->fill = NULL;
- f->fillwithscalar = NULL;
- for (i=0; i<PyArray_NSORTS; i++) {
- f->sort[i] = NULL;
- f->argsort[i] = NULL;
- }
- f->castdict = NULL;
- f->scalarkind = NULL;
- f->cancastscalarkindto = NULL;
- f->cancastto = NULL;
+ int i;
+ for (i=0; i<PyArray_NTYPES; i++) {
+ f->cast[i] = NULL;
+ }
+ f->getitem = NULL;
+ f->setitem = NULL;
+ f->copyswapn = NULL;
+ f->copyswap = NULL;
+ f->compare = NULL;
+ f->argmax = NULL;
+ f->dotfunc = NULL;
+ f->scanfunc = NULL;
+ f->fromstr = NULL;
+ f->nonzero = NULL;
+ f->fill = NULL;
+ f->fillwithscalar = NULL;
+ for (i=0; i<PyArray_NSORTS; i++) {
+ f->sort[i] = NULL;
+ f->argsort[i] = NULL;
+ }
+ f->castdict = NULL;
+ f->scalarkind = NULL;
+ f->cancastscalarkindto = NULL;
+ f->cancastto = NULL;
}
static Bool
_default_nonzero(void *ip, void *arr)
{
- int elsize = PyArray_ITEMSIZE(arr);
- char *ptr = ip;
- while (elsize--) {
- if (*ptr++ != 0) return TRUE;
- }
- return FALSE;
+ int elsize = PyArray_ITEMSIZE(arr);
+ char *ptr = ip;
+ while (elsize--) {
+ if (*ptr++ != 0) return TRUE;
+ }
+ return FALSE;
}
/*
@@ -1538,16 +1537,16 @@ _default_nonzero(void *ip, void *arr)
static int
PyArray_TypeNumFromName(char *str)
{
- int i;
- PyArray_Descr *descr;
+ int i;
+ PyArray_Descr *descr;
- for (i=0; i<NPY_NUMUSERTYPES; i++) {
- descr = userdescrs[i];
- if (strcmp(descr->typeobj->tp_name, str) == 0)
- return descr->type_num;
- }
+ for (i=0; i<NPY_NUMUSERTYPES; i++) {
+ descr = userdescrs[i];
+ if (strcmp(descr->typeobj->tp_name, str) == 0)
+ return descr->type_num;
+ }
- return PyArray_NOTYPE;
+ return PyArray_NOTYPE;
}
/*
@@ -1556,52 +1555,52 @@ PyArray_TypeNumFromName(char *str)
defined in arraytypes.inc
*/
/*MULTIARRAY_API
- Register Data type
- Does not change the reference count of descr
+ Register Data type
+ Does not change the reference count of descr
*/
static int
PyArray_RegisterDataType(PyArray_Descr *descr)
{
- PyArray_Descr *descr2;
- int typenum;
- int i;
- PyArray_ArrFuncs *f;
-
- /* See if this type is already registered */
- for (i=0; i<NPY_NUMUSERTYPES; i++) {
- descr2 = userdescrs[i];
- if (descr2 == descr)
- return descr->type_num;
- }
- typenum = PyArray_USERDEF + NPY_NUMUSERTYPES;
- descr->type_num = typenum;
- if (descr->elsize == 0) {
- PyErr_SetString(PyExc_ValueError, "cannot register a" \
- "flexible data-type");
- return -1;
- }
- f = descr->f;
- if (f->nonzero == NULL) {
- f->nonzero = _default_nonzero;
- }
- if (f->copyswap == NULL || f->getitem == NULL ||
- f->copyswapn == NULL || f->setitem == NULL) {
- PyErr_SetString(PyExc_ValueError, "a required array function" \
- " is missing.");
- return -1;
- }
- if (descr->typeobj == NULL) {
- PyErr_SetString(PyExc_ValueError, "missing typeobject");
- return -1;
- }
- userdescrs = realloc(userdescrs,
- (NPY_NUMUSERTYPES+1)*sizeof(void *));
- if (userdescrs == NULL) {
- PyErr_SetString(PyExc_MemoryError, "RegisterDataType");
- return -1;
- }
- userdescrs[NPY_NUMUSERTYPES++] = descr;
- return typenum;
+ PyArray_Descr *descr2;
+ int typenum;
+ int i;
+ PyArray_ArrFuncs *f;
+
+ /* See if this type is already registered */
+ for (i=0; i<NPY_NUMUSERTYPES; i++) {
+ descr2 = userdescrs[i];
+ if (descr2 == descr)
+ return descr->type_num;
+ }
+ typenum = PyArray_USERDEF + NPY_NUMUSERTYPES;
+ descr->type_num = typenum;
+ if (descr->elsize == 0) {
+ PyErr_SetString(PyExc_ValueError, "cannot register a" \
+ "flexible data-type");
+ return -1;
+ }
+ f = descr->f;
+ if (f->nonzero == NULL) {
+ f->nonzero = _default_nonzero;
+ }
+ if (f->copyswap == NULL || f->getitem == NULL ||
+ f->copyswapn == NULL || f->setitem == NULL) {
+ PyErr_SetString(PyExc_ValueError, "a required array function" \
+ " is missing.");
+ return -1;
+ }
+ if (descr->typeobj == NULL) {
+ PyErr_SetString(PyExc_ValueError, "missing typeobject");
+ return -1;
+ }
+ userdescrs = realloc(userdescrs,
+ (NPY_NUMUSERTYPES+1)*sizeof(void *));
+ if (userdescrs == NULL) {
+ PyErr_SetString(PyExc_MemoryError, "RegisterDataType");
+ return -1;
+ }
+ userdescrs[NPY_NUMUSERTYPES++] = descr;
+ return typenum;
}
/*MULTIARRAY_API
@@ -1612,41 +1611,41 @@ static int
PyArray_RegisterCastFunc(PyArray_Descr *descr, int totype,
PyArray_VectorUnaryFunc *castfunc)
{
- PyObject *cobj, *key;
- int ret;
- if (totype < PyArray_NTYPES) {
- descr->f->cast[totype] = castfunc;
- return 0;
- }
- if (!PyTypeNum_ISUSERDEF(totype)) {
- PyErr_SetString(PyExc_TypeError, "invalid type number.");
- return -1;
- }
- if (descr->f->castdict == NULL) {
- descr->f->castdict = PyDict_New();
- if (descr->f->castdict == NULL) return -1;
- }
- key = PyInt_FromLong(totype);
- if (PyErr_Occurred()) return -1;
- cobj = PyCObject_FromVoidPtr((void *)castfunc, NULL);
- if (cobj == NULL) {Py_DECREF(key); return -1;}
- ret = PyDict_SetItem(descr->f->castdict, key, cobj);
- Py_DECREF(key);
- Py_DECREF(cobj);
- return ret;
+ PyObject *cobj, *key;
+ int ret;
+ if (totype < PyArray_NTYPES) {
+ descr->f->cast[totype] = castfunc;
+ return 0;
+ }
+ if (!PyTypeNum_ISUSERDEF(totype)) {
+ PyErr_SetString(PyExc_TypeError, "invalid type number.");
+ return -1;
+ }
+ if (descr->f->castdict == NULL) {
+ descr->f->castdict = PyDict_New();
+ if (descr->f->castdict == NULL) return -1;
+ }
+ key = PyInt_FromLong(totype);
+ if (PyErr_Occurred()) return -1;
+ cobj = PyCObject_FromVoidPtr((void *)castfunc, NULL);
+ if (cobj == NULL) {Py_DECREF(key); return -1;}
+ ret = PyDict_SetItem(descr->f->castdict, key, cobj);
+ Py_DECREF(key);
+ Py_DECREF(cobj);
+ return ret;
}
static int *
_append_new(int *types, int insert)
{
- int n=0;
- int *newtypes;
+ int n=0;
+ int *newtypes;
- while (types[n] != PyArray_NOTYPE) n++;
- newtypes = (int *)realloc(types, (n+2)*sizeof(int));
- newtypes[n] = insert;
- newtypes[n+1] = PyArray_NOTYPE;
- return newtypes;
+ while (types[n] != PyArray_NOTYPE) n++;
+ newtypes = (int *)realloc(types, (n+2)*sizeof(int));
+ newtypes[n] = insert;
+ newtypes[n+1] = PyArray_NOTYPE;
+ return newtypes;
}
/*MULTIARRAY_API
@@ -1657,244 +1656,244 @@ static int
PyArray_RegisterCanCast(PyArray_Descr *descr, int totype,
NPY_SCALARKIND scalar)
{
- if (scalar == PyArray_NOSCALAR) {
- /* register with cancastto */
- /* These lists won't be freed once created
- -- they become part of the data-type */
- if (descr->f->cancastto == NULL) {
- descr->f->cancastto = (int *)malloc(1*sizeof(int));
- descr->f->cancastto[0] = PyArray_NOTYPE;
- }
- descr->f->cancastto = _append_new(descr->f->cancastto,
- totype);
+ if (scalar == PyArray_NOSCALAR) {
+ /* register with cancastto */
+ /* These lists won't be freed once created
+ -- they become part of the data-type */
+ if (descr->f->cancastto == NULL) {
+ descr->f->cancastto = (int *)malloc(1*sizeof(int));
+ descr->f->cancastto[0] = PyArray_NOTYPE;
}
- else {
- /* register with cancastscalarkindto */
- if (descr->f->cancastscalarkindto == NULL) {
- int i;
- descr->f->cancastscalarkindto = \
- (int **)malloc(PyArray_NSCALARKINDS* \
- sizeof(int*));
- for (i=0; i<PyArray_NSCALARKINDS; i++) {
- descr->f->cancastscalarkindto[i] = NULL;
- }
- }
- if (descr->f->cancastscalarkindto[scalar] == NULL) {
- descr->f->cancastscalarkindto[scalar] = \
- (int *)malloc(1*sizeof(int));
- descr->f->cancastscalarkindto[scalar][0] = \
- PyArray_NOTYPE;
- }
- descr->f->cancastscalarkindto[scalar] = \
- _append_new(descr->f->cancastscalarkindto[scalar],
- totype);
+ descr->f->cancastto = _append_new(descr->f->cancastto,
+ totype);
+ }
+ else {
+ /* register with cancastscalarkindto */
+ if (descr->f->cancastscalarkindto == NULL) {
+ int i;
+ descr->f->cancastscalarkindto = \
+ (int **)malloc(PyArray_NSCALARKINDS* \
+ sizeof(int*));
+ for (i=0; i<PyArray_NSCALARKINDS; i++) {
+ descr->f->cancastscalarkindto[i] = NULL;
+ }
}
- return 0;
+ if (descr->f->cancastscalarkindto[scalar] == NULL) {
+ descr->f->cancastscalarkindto[scalar] = \
+ (int *)malloc(1*sizeof(int));
+ descr->f->cancastscalarkindto[scalar][0] = \
+ PyArray_NOTYPE;
+ }
+ descr->f->cancastscalarkindto[scalar] = \
+ _append_new(descr->f->cancastscalarkindto[scalar],
+ totype);
+ }
+ return 0;
}
/*OBJECT_API
- To File
+ To File
*/
static int
PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format)
{
- intp size;
- intp n, n2;
- size_t n3, n4;
- PyArrayIterObject *it;
- PyObject *obj, *strobj, *tupobj;
-
- n3 = (sep ? strlen((const char *)sep) : 0);
- if (n3 == 0) { /* binary data */
- if (PyDataType_FLAGCHK(self->descr, NPY_LIST_PICKLE)) {
- PyErr_SetString(PyExc_ValueError, "cannot write " \
- "object arrays to a file in " \
- "binary mode");
- return -1;
+ intp size;
+ intp n, n2;
+ size_t n3, n4;
+ PyArrayIterObject *it;
+ PyObject *obj, *strobj, *tupobj;
+
+ n3 = (sep ? strlen((const char *)sep) : 0);
+ if (n3 == 0) { /* binary data */
+ if (PyDataType_FLAGCHK(self->descr, NPY_LIST_PICKLE)) {
+ PyErr_SetString(PyExc_ValueError, "cannot write " \
+ "object arrays to a file in " \
+ "binary mode");
+ return -1;
+ }
+
+ if (PyArray_ISCONTIGUOUS(self)) {
+ size = PyArray_SIZE(self);
+ NPY_BEGIN_ALLOW_THREADS
+ n=fwrite((const void *)self->data,
+ (size_t) self->descr->elsize,
+ (size_t) size, fp);
+ NPY_END_ALLOW_THREADS
+ if (n < size) {
+ PyErr_Format(PyExc_ValueError,
+ "%ld requested and %ld written",
+ (long) size, (long) n);
+ return -1;
}
+ }
+ else {
+ NPY_BEGIN_THREADS_DEF
- if (PyArray_ISCONTIGUOUS(self)) {
- size = PyArray_SIZE(self);
- NPY_BEGIN_ALLOW_THREADS
- n=fwrite((const void *)self->data,
- (size_t) self->descr->elsize,
- (size_t) size, fp);
- NPY_END_ALLOW_THREADS
- if (n < size) {
- PyErr_Format(PyExc_ValueError,
- "%ld requested and %ld written",
- (long) size, (long) n);
- return -1;
- }
- }
- else {
- NPY_BEGIN_THREADS_DEF
-
- it=(PyArrayIterObject *) \
- PyArray_IterNew((PyObject *)self);
- NPY_BEGIN_THREADS
- while(it->index < it->size) {
- if (fwrite((const void *)it->dataptr,
- (size_t) self->descr->elsize,
- 1, fp) < 1) {
- NPY_END_THREADS
- PyErr_Format(PyExc_IOError,
- "problem writing element"\
- " %d to file",
- (int)it->index);
- Py_DECREF(it);
- return -1;
- }
- PyArray_ITER_NEXT(it);
- }
+ it=(PyArrayIterObject *) \
+ PyArray_IterNew((PyObject *)self);
+ NPY_BEGIN_THREADS
+ while(it->index < it->size) {
+ if (fwrite((const void *)it->dataptr,
+ (size_t) self->descr->elsize,
+ 1, fp) < 1) {
NPY_END_THREADS
+ PyErr_Format(PyExc_IOError,
+ "problem writing element"\
+ " %d to file",
+ (int)it->index);
Py_DECREF(it);
+ return -1;
+ }
+ PyArray_ITER_NEXT(it);
}
+ NPY_END_THREADS
+ Py_DECREF(it);
}
- else { /* text data */
+ }
+ else { /* text data */
- it=(PyArrayIterObject *) \
- PyArray_IterNew((PyObject *)self);
- n4 = (format ? strlen((const char *)format) : 0);
- while(it->index < it->size) {
- obj = self->descr->f->getitem(it->dataptr, self);
- if (obj == NULL) {Py_DECREF(it); return -1;}
- if (n4 == 0) { /* standard writing */
- strobj = PyObject_Str(obj);
- Py_DECREF(obj);
- if (strobj == NULL) {Py_DECREF(it); return -1;}
- }
- else { /* use format string */
- tupobj = PyTuple_New(1);
- if (tupobj == NULL) {Py_DECREF(it); return -1;}
- PyTuple_SET_ITEM(tupobj,0,obj);
- obj = PyString_FromString((const char *)format);
- if (obj == NULL) {Py_DECREF(tupobj);
- Py_DECREF(it); return -1;}
- strobj = PyString_Format(obj, tupobj);
- Py_DECREF(obj);
- Py_DECREF(tupobj);
- if (strobj == NULL) {Py_DECREF(it); return -1;}
- }
- NPY_BEGIN_ALLOW_THREADS
- n=fwrite(PyString_AS_STRING(strobj), 1,
- n2=PyString_GET_SIZE(strobj), fp);
- NPY_END_ALLOW_THREADS
- if (n < n2) {
- PyErr_Format(PyExc_IOError,
- "problem writing element %d"\
- " to file",
- (int) it->index);
- Py_DECREF(strobj);
- Py_DECREF(it);
- return -1;
- }
- /* write separator for all but last one */
- if (it->index != it->size-1)
- if (fwrite(sep, 1, n3, fp) < n3) {
- PyErr_Format(PyExc_IOError,
- "problem writing "\
- "separator to file");
- Py_DECREF(strobj);
- Py_DECREF(it);
- return -1;
- }
- Py_DECREF(strobj);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
+ it=(PyArrayIterObject *) \
+ PyArray_IterNew((PyObject *)self);
+ n4 = (format ? strlen((const char *)format) : 0);
+ while(it->index < it->size) {
+ obj = self->descr->f->getitem(it->dataptr, self);
+ if (obj == NULL) {Py_DECREF(it); return -1;}
+ if (n4 == 0) { /* standard writing */
+ strobj = PyObject_Str(obj);
+ Py_DECREF(obj);
+ if (strobj == NULL) {Py_DECREF(it); return -1;}
+ }
+ else { /* use format string */
+ tupobj = PyTuple_New(1);
+ if (tupobj == NULL) {Py_DECREF(it); return -1;}
+ PyTuple_SET_ITEM(tupobj,0,obj);
+ obj = PyString_FromString((const char *)format);
+ if (obj == NULL) {Py_DECREF(tupobj);
+ Py_DECREF(it); return -1;}
+ strobj = PyString_Format(obj, tupobj);
+ Py_DECREF(obj);
+ Py_DECREF(tupobj);
+ if (strobj == NULL) {Py_DECREF(it); return -1;}
+ }
+ NPY_BEGIN_ALLOW_THREADS
+ n=fwrite(PyString_AS_STRING(strobj), 1,
+ n2=PyString_GET_SIZE(strobj), fp);
+ NPY_END_ALLOW_THREADS
+ if (n < n2) {
+ PyErr_Format(PyExc_IOError,
+ "problem writing element %d"\
+ " to file",
+ (int) it->index);
+ Py_DECREF(strobj);
+ Py_DECREF(it);
+ return -1;
+ }
+ /* write separator for all but last one */
+ if (it->index != it->size-1)
+ if (fwrite(sep, 1, n3, fp) < n3) {
+ PyErr_Format(PyExc_IOError,
+ "problem writing "\
+ "separator to file");
+ Py_DECREF(strobj);
+ Py_DECREF(it);
+ return -1;
+ }
+ Py_DECREF(strobj);
+ PyArray_ITER_NEXT(it);
}
- return 0;
+ Py_DECREF(it);
+ }
+ return 0;
}
/*OBJECT_API
- To List
+ To List
*/
static PyObject *
PyArray_ToList(PyArrayObject *self)
{
- PyObject *lp;
- PyArrayObject *v;
- intp sz, i;
+ PyObject *lp;
+ PyArrayObject *v;
+ intp sz, i;
- if (!PyArray_Check(self)) return (PyObject *)self;
+ if (!PyArray_Check(self)) return (PyObject *)self;
- if (self->nd == 0)
- return self->descr->f->getitem(self->data,self);
+ if (self->nd == 0)
+ return self->descr->f->getitem(self->data,self);
- sz = self->dimensions[0];
- lp = PyList_New(sz);
+ sz = self->dimensions[0];
+ lp = PyList_New(sz);
- for (i=0; i<sz; i++) {
- v=(PyArrayObject *)array_big_item(self, i);
- if (v->nd >= self->nd) {
- PyErr_SetString(PyExc_RuntimeError,
- "array_item not returning smaller-" \
- "dimensional array");
- Py_DECREF(v);
- Py_DECREF(lp);
- return NULL;
- }
- PyList_SetItem(lp, i, PyArray_ToList(v));
- Py_DECREF(v);
+ for (i=0; i<sz; i++) {
+ v=(PyArrayObject *)array_big_item(self, i);
+ if (v->nd >= self->nd) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "array_item not returning smaller-" \
+ "dimensional array");
+ Py_DECREF(v);
+ Py_DECREF(lp);
+ return NULL;
}
+ PyList_SetItem(lp, i, PyArray_ToList(v));
+ Py_DECREF(v);
+ }
- return lp;
+ return lp;
}
/*OBJECT_API*/
static PyObject *
PyArray_ToString(PyArrayObject *self, NPY_ORDER order)
{
- intp numbytes;
- intp index;
- char *dptr;
- int elsize;
- PyObject *ret;
- PyArrayIterObject *it;
-
- if (order == NPY_ANYORDER)
- order = PyArray_ISFORTRAN(self);
-
- /* if (PyArray_TYPE(self) == PyArray_OBJECT) {
- PyErr_SetString(PyExc_ValueError, "a string for the data" \
- "in an object array is not appropriate");
- return NULL;
- }
- */
-
- numbytes = PyArray_NBYTES(self);
- if ((PyArray_ISCONTIGUOUS(self) && (order == NPY_CORDER)) || \
- (PyArray_ISFORTRAN(self) && (order == NPY_FORTRANORDER))) {
- ret = PyString_FromStringAndSize(self->data, (int) numbytes);
+ intp numbytes;
+ intp index;
+ char *dptr;
+ int elsize;
+ PyObject *ret;
+ PyArrayIterObject *it;
+
+ if (order == NPY_ANYORDER)
+ order = PyArray_ISFORTRAN(self);
+
+ /* if (PyArray_TYPE(self) == PyArray_OBJECT) {
+ PyErr_SetString(PyExc_ValueError, "a string for the data" \
+ "in an object array is not appropriate");
+ return NULL;
+ }
+ */
+
+ numbytes = PyArray_NBYTES(self);
+ if ((PyArray_ISCONTIGUOUS(self) && (order == NPY_CORDER)) || \
+ (PyArray_ISFORTRAN(self) && (order == NPY_FORTRANORDER))) {
+ ret = PyString_FromStringAndSize(self->data, (int) numbytes);
+ }
+ else {
+ PyObject *new;
+ if (order == NPY_FORTRANORDER) {
+ /* iterators are always in C-order */
+ new = PyArray_Transpose(self, NULL);
+ if (new == NULL) return NULL;
}
else {
- PyObject *new;
- if (order == NPY_FORTRANORDER) {
- /* iterators are always in C-order */
- new = PyArray_Transpose(self, NULL);
- if (new == NULL) return NULL;
- }
- else {
- Py_INCREF(self);
- new = (PyObject *)self;
- }
- it = (PyArrayIterObject *)PyArray_IterNew(new);
- Py_DECREF(new);
- if (it==NULL) return NULL;
- ret = PyString_FromStringAndSize(NULL, (int) numbytes);
- if (ret == NULL) {Py_DECREF(it); return NULL;}
- dptr = PyString_AS_STRING(ret);
- index = it->size;
- elsize = self->descr->elsize;
- while(index--) {
- memcpy(dptr, it->dataptr, elsize);
- dptr += elsize;
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
+ Py_INCREF(self);
+ new = (PyObject *)self;
}
- return ret;
+ it = (PyArrayIterObject *)PyArray_IterNew(new);
+ Py_DECREF(new);
+ if (it==NULL) return NULL;
+ ret = PyString_FromStringAndSize(NULL, (int) numbytes);
+ if (ret == NULL) {Py_DECREF(it); return NULL;}
+ dptr = PyString_AS_STRING(ret);
+ index = it->size;
+ elsize = self->descr->elsize;
+ while(index--) {
+ memcpy(dptr, it->dataptr, elsize);
+ dptr += elsize;
+ PyArray_ITER_NEXT(it);
+ }
+ Py_DECREF(it);
+ }
+ return ret;
}
@@ -1906,49 +1905,49 @@ PyArray_ToString(PyArrayObject *self, NPY_ORDER order)
static void
array_dealloc(PyArrayObject *self) {
- if (self->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *)self);
+ if (self->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *)self);
- if(self->base) {
- /* UPDATEIFCOPY means that base points to an
- array that should be updated with the contents
- of this array upon destruction.
- self->base->flags must have been WRITEABLE
- (checked previously) and it was locked here
- thus, unlock it.
- */
- if (self->flags & UPDATEIFCOPY) {
- ((PyArrayObject *)self->base)->flags |= WRITEABLE;
- Py_INCREF(self); /* hold on to self in next call */
- if (PyArray_CopyAnyInto((PyArrayObject *)self->base,
- self) < 0) {
- PyErr_Print();
- PyErr_Clear();
- }
- /* Don't need to DECREF -- because we are deleting
- self already... */
- }
- /* In any case base is pointing to something that we need
- to DECREF -- either a view or a buffer object */
- Py_DECREF(self->base);
- }
-
- if ((self->flags & OWNDATA) && self->data) {
- /* Free internal references if an Object array */
- if (PyDataType_FLAGCHK(self->descr, NPY_ITEM_REFCOUNT)) {
- Py_INCREF(self); /*hold on to self */
- PyArray_XDECREF(self);
- /* Don't need to DECREF -- because we are deleting
- self already... */
- }
- PyDataMem_FREE(self->data);
+ if(self->base) {
+ /* UPDATEIFCOPY means that base points to an
+ array that should be updated with the contents
+ of this array upon destruction.
+ self->base->flags must have been WRITEABLE
+ (checked previously) and it was locked here
+ thus, unlock it.
+ */
+ if (self->flags & UPDATEIFCOPY) {
+ ((PyArrayObject *)self->base)->flags |= WRITEABLE;
+ Py_INCREF(self); /* hold on to self in next call */
+ if (PyArray_CopyAnyInto((PyArrayObject *)self->base,
+ self) < 0) {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ /* Don't need to DECREF -- because we are deleting
+ self already... */
+ }
+ /* In any case base is pointing to something that we need
+ to DECREF -- either a view or a buffer object */
+ Py_DECREF(self->base);
+ }
+
+ if ((self->flags & OWNDATA) && self->data) {
+ /* Free internal references if an Object array */
+ if (PyDataType_FLAGCHK(self->descr, NPY_ITEM_REFCOUNT)) {
+ Py_INCREF(self); /*hold on to self */
+ PyArray_XDECREF(self);
+ /* Don't need to DECREF -- because we are deleting
+ self already... */
}
+ PyDataMem_FREE(self->data);
+ }
- PyDimMem_FREE(self->dimensions);
+ PyDimMem_FREE(self->dimensions);
- Py_DECREF(self->descr);
+ Py_DECREF(self->descr);
- self->ob_type->tp_free((PyObject *)self);
+ self->ob_type->tp_free((PyObject *)self);
}
/*************************************************************************
@@ -1958,108 +1957,108 @@ array_dealloc(PyArrayObject *self) {
static Py_ssize_t
array_length(PyArrayObject *self)
{
- if (self->nd != 0) {
- return self->dimensions[0];
- } else {
- PyErr_SetString(PyExc_TypeError, "len() of unsized object");
- return -1;
- }
+ if (self->nd != 0) {
+ return self->dimensions[0];
+ } else {
+ PyErr_SetString(PyExc_TypeError, "len() of unsized object");
+ return -1;
+ }
}
static PyObject *
array_big_item(PyArrayObject *self, intp i)
{
- char *item;
- PyArrayObject *r;
-
- if(self->nd == 0) {
- PyErr_SetString(PyExc_IndexError,
- "0-d arrays can't be indexed");
- return NULL;
- }
- if ((item = index2ptr(self, i)) == NULL) return NULL;
+ char *item;
+ PyArrayObject *r;
- Py_INCREF(self->descr);
- r = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type,
- self->descr,
- self->nd-1,
- self->dimensions+1,
- self->strides+1, item,
- self->flags,
- (PyObject *)self);
- if (r == NULL) return NULL;
- Py_INCREF(self);
- r->base = (PyObject *)self;
- PyArray_UpdateFlags(r, CONTIGUOUS | FORTRAN);
- return (PyObject *)r;
+ if(self->nd == 0) {
+ PyErr_SetString(PyExc_IndexError,
+ "0-d arrays can't be indexed");
+ return NULL;
+ }
+ if ((item = index2ptr(self, i)) == NULL) return NULL;
+
+ Py_INCREF(self->descr);
+ r = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type,
+ self->descr,
+ self->nd-1,
+ self->dimensions+1,
+ self->strides+1, item,
+ self->flags,
+ (PyObject *)self);
+ if (r == NULL) return NULL;
+ Py_INCREF(self);
+ r->base = (PyObject *)self;
+ PyArray_UpdateFlags(r, CONTIGUOUS | FORTRAN);
+ return (PyObject *)r;
}
/* contains optimization for 1-d arrays */
static PyObject *
array_item_nice(PyArrayObject *self, Py_ssize_t i)
{
- if (self->nd == 1) {
- char *item;
- if ((item = index2ptr(self, i)) == NULL) return NULL;
- return PyArray_Scalar(item, self->descr, (PyObject *)self);
- }
- else {
- return PyArray_Return((PyArrayObject *)\
- array_big_item(self, (intp) i));
- }
+ if (self->nd == 1) {
+ char *item;
+ if ((item = index2ptr(self, i)) == NULL) return NULL;
+ return PyArray_Scalar(item, self->descr, (PyObject *)self);
+ }
+ else {
+ return PyArray_Return((PyArrayObject *)\
+ array_big_item(self, (intp) i));
+ }
}
static int
array_ass_big_item(PyArrayObject *self, intp i, PyObject *v)
{
- PyArrayObject *tmp;
- char *item;
- int ret;
+ PyArrayObject *tmp;
+ char *item;
+ int ret;
- if (v == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "can't delete array elements");
- return -1;
- }
- if (!PyArray_ISWRITEABLE(self)) {
- PyErr_SetString(PyExc_RuntimeError,
- "array is not writeable");
- return -1;
- }
- if (self->nd == 0) {
- PyErr_SetString(PyExc_IndexError,
- "0-d arrays can't be indexed.");
- return -1;
- }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "can't delete array elements");
+ return -1;
+ }
+ if (!PyArray_ISWRITEABLE(self)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "array is not writeable");
+ return -1;
+ }
+ if (self->nd == 0) {
+ PyErr_SetString(PyExc_IndexError,
+ "0-d arrays can't be indexed.");
+ return -1;
+ }
- if (self->nd > 1) {
- if((tmp = (PyArrayObject *)array_big_item(self, i)) == NULL)
- return -1;
- ret = PyArray_CopyObject(tmp, v);
- Py_DECREF(tmp);
- return ret;
- }
+ if (self->nd > 1) {
+ if((tmp = (PyArrayObject *)array_big_item(self, i)) == NULL)
+ return -1;
+ ret = PyArray_CopyObject(tmp, v);
+ Py_DECREF(tmp);
+ return ret;
+ }
- if ((item = index2ptr(self, i)) == NULL) return -1;
- if (self->descr->f->setitem(v, item, self) == -1) return -1;
- return 0;
+ if ((item = index2ptr(self, i)) == NULL) return -1;
+ if (self->descr->f->setitem(v, item, self) == -1) return -1;
+ return 0;
}
#if PY_VERSION_HEX < 0x02050000
- #if SIZEOF_INT == SIZEOF_INTP
- #define array_ass_item array_ass_big_item
- #endif
+#if SIZEOF_INT == SIZEOF_INTP
+#define array_ass_item array_ass_big_item
+#endif
#else
- #if SIZEOF_SIZE_T == SIZEOF_INTP
- #define array_ass_item array_ass_big_item
- #endif
+#if SIZEOF_SIZE_T == SIZEOF_INTP
+#define array_ass_item array_ass_big_item
+#endif
#endif
#ifndef array_ass_item
static int
array_ass_item(PyArrayObject *self, Py_ssize_t i, PyObject *v)
{
- return array_ass_big_item(self, (intp) i, v);
+ return array_ass_big_item(self, (intp) i, v);
}
#endif
@@ -2068,12 +2067,12 @@ array_ass_item(PyArrayObject *self, Py_ssize_t i, PyObject *v)
static int
slice_coerce_index(PyObject *o, intp *v)
{
- *v = PyArray_PyIntAsIntp(o);
- if (error_converting(*v)) {
- PyErr_Clear();
- return 0;
- }
- return 1;
+ *v = PyArray_PyIntAsIntp(o);
+ if (error_converting(*v)) {
+ PyErr_Clear();
+ return 0;
+ }
+ return 1;
}
@@ -2084,52 +2083,52 @@ slice_GetIndices(PySliceObject *r, intp length,
intp *start, intp *stop, intp *step,
intp *slicelength)
{
- intp defstop;
+ intp defstop;
- if (r->step == Py_None) {
- *step = 1;
- } else {
- if (!slice_coerce_index(r->step, step)) return -1;
- if (*step == 0) {
- PyErr_SetString(PyExc_ValueError,
- "slice step cannot be zero");
- return -1;
- }
+ if (r->step == Py_None) {
+ *step = 1;
+ } else {
+ if (!slice_coerce_index(r->step, step)) return -1;
+ if (*step == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice step cannot be zero");
+ return -1;
}
- /* defstart = *step < 0 ? length - 1 : 0; */
+ }
+ /* defstart = *step < 0 ? length - 1 : 0; */
- defstop = *step < 0 ? -1 : length;
+ defstop = *step < 0 ? -1 : length;
- if (r->start == Py_None) {
- *start = *step < 0 ? length-1 : 0;
- } else {
- if (!slice_coerce_index(r->start, start)) return -1;
- if (*start < 0) *start += length;
- if (*start < 0) *start = (*step < 0) ? -1 : 0;
- if (*start >= length) {
- *start = (*step < 0) ? length - 1 : length;
- }
+ if (r->start == Py_None) {
+ *start = *step < 0 ? length-1 : 0;
+ } else {
+ if (!slice_coerce_index(r->start, start)) return -1;
+ if (*start < 0) *start += length;
+ if (*start < 0) *start = (*step < 0) ? -1 : 0;
+ if (*start >= length) {
+ *start = (*step < 0) ? length - 1 : length;
}
+ }
- if (r->stop == Py_None) {
- *stop = defstop;
- } else {
- if (!slice_coerce_index(r->stop, stop)) return -1;
- if (*stop < 0) *stop += length;
+ if (r->stop == Py_None) {
+ *stop = defstop;
+ } else {
+ if (!slice_coerce_index(r->stop, stop)) return -1;
+ if (*stop < 0) *stop += length;
if (*stop < 0) *stop = -1;
if (*stop > length) *stop = length;
- }
+ }
- if ((*step < 0 && *stop >= *start) || \
- (*step > 0 && *start >= *stop)) {
- *slicelength = 0;
- } else if (*step < 0) {
- *slicelength = (*stop - *start + 1) / (*step) + 1;
- } else {
- *slicelength = (*stop - *start - 1) / (*step) + 1;
- }
+ if ((*step < 0 && *stop >= *start) || \
+ (*step > 0 && *start >= *stop)) {
+ *slicelength = 0;
+ } else if (*step < 0) {
+ *slicelength = (*stop - *start + 1) / (*step) + 1;
+ } else {
+ *slicelength = (*stop - *start - 1) / (*step) + 1;
+ }
- return 0;
+ return 0;
}
#define PseudoIndex -1
@@ -2139,49 +2138,49 @@ slice_GetIndices(PySliceObject *r, intp length,
static intp
parse_subindex(PyObject *op, intp *step_size, intp *n_steps, intp max)
{
- intp index;
-
- if (op == Py_None) {
- *n_steps = PseudoIndex;
- index = 0;
- } else if (op == Py_Ellipsis) {
- *n_steps = RubberIndex;
- index = 0;
- } else if (PySlice_Check(op)) {
- intp stop;
- if (slice_GetIndices((PySliceObject *)op, max,
- &index, &stop, step_size, n_steps) < 0) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_IndexError,
- "invalid slice");
- }
- goto fail;
- }
- if (*n_steps <= 0) {
- *n_steps = 0;
- *step_size = 1;
- index = 0;
- }
- } else {
- index = PyArray_PyIntAsIntp(op);
- if (error_converting(index)) {
- PyErr_SetString(PyExc_IndexError,
- "each subindex must be either a "\
- "slice, an integer, Ellipsis, or "\
- "newaxis");
- goto fail;
- }
- *n_steps = SingleIndex;
- *step_size = 0;
- if (index < 0) index += max;
- if (index >= max || index < 0) {
- PyErr_SetString(PyExc_IndexError, "invalid index");
- goto fail;
- }
+ intp index;
+
+ if (op == Py_None) {
+ *n_steps = PseudoIndex;
+ index = 0;
+ } else if (op == Py_Ellipsis) {
+ *n_steps = RubberIndex;
+ index = 0;
+ } else if (PySlice_Check(op)) {
+ intp stop;
+ if (slice_GetIndices((PySliceObject *)op, max,
+ &index, &stop, step_size, n_steps) < 0) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_IndexError,
+ "invalid slice");
+ }
+ goto fail;
+ }
+ if (*n_steps <= 0) {
+ *n_steps = 0;
+ *step_size = 1;
+ index = 0;
+ }
+ } else {
+ index = PyArray_PyIntAsIntp(op);
+ if (error_converting(index)) {
+ PyErr_SetString(PyExc_IndexError,
+ "each subindex must be either a "\
+ "slice, an integer, Ellipsis, or "\
+ "newaxis");
+ goto fail;
+ }
+ *n_steps = SingleIndex;
+ *step_size = 0;
+ if (index < 0) index += max;
+ if (index >= max || index < 0) {
+ PyErr_SetString(PyExc_IndexError, "invalid index");
+ goto fail;
}
- return index;
+ }
+ return index;
fail:
- return -1;
+ return -1;
}
@@ -2189,168 +2188,168 @@ static int
parse_index(PyArrayObject *self, PyObject *op,
intp *dimensions, intp *strides, intp *offset_ptr)
{
- int i, j, n;
- int nd_old, nd_new, n_add, n_pseudo;
- intp n_steps, start, offset, step_size;
- PyObject *op1=NULL;
- int is_slice;
+ int i, j, n;
+ int nd_old, nd_new, n_add, n_pseudo;
+ intp n_steps, start, offset, step_size;
+ PyObject *op1=NULL;
+ int is_slice;
- if (PySlice_Check(op) || op == Py_Ellipsis || op == Py_None) {
- n = 1;
- op1 = op;
- Py_INCREF(op);
- /* this relies on the fact that n==1 for loop below */
- is_slice = 1;
- }
- else {
- if (!PySequence_Check(op)) {
- PyErr_SetString(PyExc_IndexError,
- "index must be either an int "\
- "or a sequence");
- return -1;
- }
- n = PySequence_Length(op);
- is_slice = 0;
- }
+ if (PySlice_Check(op) || op == Py_Ellipsis || op == Py_None) {
+ n = 1;
+ op1 = op;
+ Py_INCREF(op);
+ /* this relies on the fact that n==1 for loop below */
+ is_slice = 1;
+ }
+ else {
+ if (!PySequence_Check(op)) {
+ PyErr_SetString(PyExc_IndexError,
+ "index must be either an int "\
+ "or a sequence");
+ return -1;
+ }
+ n = PySequence_Length(op);
+ is_slice = 0;
+ }
- nd_old = nd_new = 0;
+ nd_old = nd_new = 0;
- offset = 0;
- for(i=0; i<n; i++) {
- if (!is_slice) {
- if (!(op1=PySequence_GetItem(op, i))) {
- PyErr_SetString(PyExc_IndexError,
- "invalid index");
- return -1;
- }
- }
+ offset = 0;
+ for(i=0; i<n; i++) {
+ if (!is_slice) {
+ if (!(op1=PySequence_GetItem(op, i))) {
+ PyErr_SetString(PyExc_IndexError,
+ "invalid index");
+ return -1;
+ }
+ }
- start = parse_subindex(op1, &step_size, &n_steps,
- nd_old < self->nd ? \
- self->dimensions[nd_old] : 0);
- Py_DECREF(op1);
- if (start == -1) break;
+ start = parse_subindex(op1, &step_size, &n_steps,
+ nd_old < self->nd ? \
+ self->dimensions[nd_old] : 0);
+ Py_DECREF(op1);
+ if (start == -1) break;
- if (n_steps == PseudoIndex) {
- dimensions[nd_new] = 1; strides[nd_new] = 0;
- nd_new++;
- } else {
- if (n_steps == RubberIndex) {
- for(j=i+1, n_pseudo=0; j<n; j++) {
- op1 = PySequence_GetItem(op, j);
- if (op1 == Py_None) n_pseudo++;
- Py_DECREF(op1);
- }
- n_add = self->nd-(n-i-n_pseudo-1+nd_old);
- if (n_add < 0) {
- PyErr_SetString(PyExc_IndexError,
- "too many indices");
- return -1;
- }
- for(j=0; j<n_add; j++) {
- dimensions[nd_new] = \
- self->dimensions[nd_old];
- strides[nd_new] = \
- self->strides[nd_old];
- nd_new++; nd_old++;
- }
- } else {
- if (nd_old >= self->nd) {
- PyErr_SetString(PyExc_IndexError,
- "too many indices");
- return -1;
- }
- offset += self->strides[nd_old]*start;
- nd_old++;
- if (n_steps != SingleIndex) {
- dimensions[nd_new] = n_steps;
- strides[nd_new] = step_size * \
- self->strides[nd_old-1];
- nd_new++;
- }
- }
+ if (n_steps == PseudoIndex) {
+ dimensions[nd_new] = 1; strides[nd_new] = 0;
+ nd_new++;
+ } else {
+ if (n_steps == RubberIndex) {
+ for(j=i+1, n_pseudo=0; j<n; j++) {
+ op1 = PySequence_GetItem(op, j);
+ if (op1 == Py_None) n_pseudo++;
+ Py_DECREF(op1);
+ }
+ n_add = self->nd-(n-i-n_pseudo-1+nd_old);
+ if (n_add < 0) {
+ PyErr_SetString(PyExc_IndexError,
+ "too many indices");
+ return -1;
+ }
+ for(j=0; j<n_add; j++) {
+ dimensions[nd_new] = \
+ self->dimensions[nd_old];
+ strides[nd_new] = \
+ self->strides[nd_old];
+ nd_new++; nd_old++;
}
+ } else {
+ if (nd_old >= self->nd) {
+ PyErr_SetString(PyExc_IndexError,
+ "too many indices");
+ return -1;
+ }
+ offset += self->strides[nd_old]*start;
+ nd_old++;
+ if (n_steps != SingleIndex) {
+ dimensions[nd_new] = n_steps;
+ strides[nd_new] = step_size * \
+ self->strides[nd_old-1];
+ nd_new++;
+ }
+ }
}
- if (i < n) return -1;
- n_add = self->nd-nd_old;
- for(j=0; j<n_add; j++) {
- dimensions[nd_new] = self->dimensions[nd_old];
- strides[nd_new] = self->strides[nd_old];
- nd_new++; nd_old++;
- }
- *offset_ptr = offset;
- return nd_new;
+ }
+ if (i < n) return -1;
+ n_add = self->nd-nd_old;
+ for(j=0; j<n_add; j++) {
+ dimensions[nd_new] = self->dimensions[nd_old];
+ strides[nd_new] = self->strides[nd_old];
+ nd_new++; nd_old++;
+ }
+ *offset_ptr = offset;
+ return nd_new;
}
static void
_swap_axes(PyArrayMapIterObject *mit, PyArrayObject **ret, int getmap)
{
- PyObject *new;
- int n1, n2, n3, val, bnd;
- int i;
- PyArray_Dims permute;
- intp d[MAX_DIMS];
- PyArrayObject *arr;
-
- permute.ptr = d;
- permute.len = mit->nd;
-
- /* arr might not have the right number of dimensions
- and need to be reshaped first by pre-pending ones */
- arr = *ret;
- if (arr->nd != mit->nd) {
- for (i=1; i<=arr->nd; i++) {
- permute.ptr[mit->nd-i] = arr->dimensions[arr->nd-i];
- }
- for (i=0; i<mit->nd-arr->nd; i++) {
- permute.ptr[i] = 1;
- }
- new = PyArray_Newshape(arr, &permute, PyArray_ANYORDER);
- Py_DECREF(arr);
- *ret = (PyArrayObject *)new;
- if (new == NULL) return;
- }
-
- /* Setting and getting need to have different permutations.
- On the get we are permuting the returned object, but on
- setting we are permuting the object-to-be-set.
- The set permutation is the inverse of the get permutation.
- */
+ PyObject *new;
+ int n1, n2, n3, val, bnd;
+ int i;
+ PyArray_Dims permute;
+ intp d[MAX_DIMS];
+ PyArrayObject *arr;
- /* For getting the array the tuple for transpose is
- (n1,...,n1+n2-1,0,...,n1-1,n1+n2,...,n3-1)
- n1 is the number of dimensions of
- the broadcasted index array
- n2 is the number of dimensions skipped at the
- start
- n3 is the number of dimensions of the
- result
- */
+ permute.ptr = d;
+ permute.len = mit->nd;
- /* For setting the array the tuple for transpose is
- (n2,...,n1+n2-1,0,...,n2-1,n1+n2,...n3-1)
- */
- n1 = mit->iters[0]->nd_m1 + 1;
- n2 = mit->iteraxes[0];
- n3 = mit->nd;
-
- bnd = (getmap ? n1 : n2); /* use n1 as the boundary if getting
- but n2 if setting */
-
- val = bnd;
- i = 0;
- while(val < n1+n2)
- permute.ptr[i++] = val++;
- val = 0;
- while(val < bnd)
- permute.ptr[i++] = val++;
- val = n1+n2;
- while(val < n3)
- permute.ptr[i++] = val++;
-
- new = PyArray_Transpose(*ret, &permute);
- Py_DECREF(*ret);
+ /* arr might not have the right number of dimensions
+ and need to be reshaped first by pre-pending ones */
+ arr = *ret;
+ if (arr->nd != mit->nd) {
+ for (i=1; i<=arr->nd; i++) {
+ permute.ptr[mit->nd-i] = arr->dimensions[arr->nd-i];
+ }
+ for (i=0; i<mit->nd-arr->nd; i++) {
+ permute.ptr[i] = 1;
+ }
+ new = PyArray_Newshape(arr, &permute, PyArray_ANYORDER);
+ Py_DECREF(arr);
*ret = (PyArrayObject *)new;
+ if (new == NULL) return;
+ }
+
+ /* Setting and getting need to have different permutations.
+ On the get we are permuting the returned object, but on
+ setting we are permuting the object-to-be-set.
+ The set permutation is the inverse of the get permutation.
+ */
+
+ /* For getting the array the tuple for transpose is
+ (n1,...,n1+n2-1,0,...,n1-1,n1+n2,...,n3-1)
+ n1 is the number of dimensions of
+ the broadcasted index array
+ n2 is the number of dimensions skipped at the
+ start
+ n3 is the number of dimensions of the
+ result
+ */
+
+ /* For setting the array the tuple for transpose is
+ (n2,...,n1+n2-1,0,...,n2-1,n1+n2,...n3-1)
+ */
+ n1 = mit->iters[0]->nd_m1 + 1;
+ n2 = mit->iteraxes[0];
+ n3 = mit->nd;
+
+ bnd = (getmap ? n1 : n2); /* use n1 as the boundary if getting
+ but n2 if setting */
+
+ val = bnd;
+ i = 0;
+ while(val < n1+n2)
+ permute.ptr[i++] = val++;
+ val = 0;
+ while(val < bnd)
+ permute.ptr[i++] = val++;
+ val = n1+n2;
+ while(val < n3)
+ permute.ptr[i++] = val++;
+
+ new = PyArray_Transpose(*ret, &permute);
+ Py_DECREF(*ret);
+ *ret = (PyArrayObject *)new;
}
/* Prototypes for Mapping calls --- not part of the C-API
@@ -2366,175 +2365,175 @@ static PyObject *
PyArray_GetMap(PyArrayMapIterObject *mit)
{
- PyArrayObject *ret, *temp;
- PyArrayIterObject *it;
- int index;
- int swap;
- PyArray_CopySwapFunc *copyswap;
-
- /* Unbound map iterator --- Bind should have been called */
- if (mit->ait == NULL) return NULL;
-
- /* This relies on the map iterator object telling us the shape
- of the new array in nd and dimensions.
- */
- temp = mit->ait->ao;
- Py_INCREF(temp->descr);
- ret = (PyArrayObject *)\
- PyArray_NewFromDescr(temp->ob_type,
- temp->descr,
- mit->nd, mit->dimensions,
- NULL, NULL,
- PyArray_ISFORTRAN(temp),
- (PyObject *)temp);
- if (ret == NULL) return NULL;
-
- /* Now just iterate through the new array filling it in
- with the next object from the original array as
- defined by the mapping iterator */
-
- if ((it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ret))
- == NULL) {
- Py_DECREF(ret);
- return NULL;
- }
- index = it->size;
- swap = (PyArray_ISNOTSWAPPED(temp) != PyArray_ISNOTSWAPPED(ret));
- copyswap = ret->descr->f->copyswap;
- PyArray_MapIterReset(mit);
- while (index--) {
- copyswap(it->dataptr, mit->dataptr, swap, ret);
- PyArray_MapIterNext(mit);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(it);
+ PyArrayObject *ret, *temp;
+ PyArrayIterObject *it;
+ int index;
+ int swap;
+ PyArray_CopySwapFunc *copyswap;
+
+ /* Unbound map iterator --- Bind should have been called */
+ if (mit->ait == NULL) return NULL;
+
+ /* This relies on the map iterator object telling us the shape
+ of the new array in nd and dimensions.
+ */
+ temp = mit->ait->ao;
+ Py_INCREF(temp->descr);
+ ret = (PyArrayObject *)\
+ PyArray_NewFromDescr(temp->ob_type,
+ temp->descr,
+ mit->nd, mit->dimensions,
+ NULL, NULL,
+ PyArray_ISFORTRAN(temp),
+ (PyObject *)temp);
+ if (ret == NULL) return NULL;
+
+ /* Now just iterate through the new array filling it in
+ with the next object from the original array as
+ defined by the mapping iterator */
+
+ if ((it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ret))
+ == NULL) {
+ Py_DECREF(ret);
+ return NULL;
+ }
+ index = it->size;
+ swap = (PyArray_ISNOTSWAPPED(temp) != PyArray_ISNOTSWAPPED(ret));
+ copyswap = ret->descr->f->copyswap;
+ PyArray_MapIterReset(mit);
+ while (index--) {
+ copyswap(it->dataptr, mit->dataptr, swap, ret);
+ PyArray_MapIterNext(mit);
+ PyArray_ITER_NEXT(it);
+ }
+ Py_DECREF(it);
- /* check for consecutive axes */
- if ((mit->subspace != NULL) && (mit->consec)) {
- if (mit->iteraxes[0] > 0) { /* then we need to swap */
- _swap_axes(mit, &ret, 1);
- }
+ /* check for consecutive axes */
+ if ((mit->subspace != NULL) && (mit->consec)) {
+ if (mit->iteraxes[0] > 0) { /* then we need to swap */
+ _swap_axes(mit, &ret, 1);
}
- return (PyObject *)ret;
+ }
+ return (PyObject *)ret;
}
static int
PyArray_SetMap(PyArrayMapIterObject *mit, PyObject *op)
{
- PyObject *arr=NULL;
- PyArrayIterObject *it;
- int index;
- int swap;
- PyArray_CopySwapFunc *copyswap;
- PyArray_Descr *descr;
+ PyObject *arr=NULL;
+ PyArrayIterObject *it;
+ int index;
+ int swap;
+ PyArray_CopySwapFunc *copyswap;
+ PyArray_Descr *descr;
- /* Unbound Map Iterator */
- if (mit->ait == NULL) return -1;
+ /* Unbound Map Iterator */
+ if (mit->ait == NULL) return -1;
- descr = mit->ait->ao->descr;
- Py_INCREF(descr);
- arr = PyArray_FromAny(op, descr, 0, 0, FORCECAST, NULL);
- if (arr == NULL) return -1;
+ descr = mit->ait->ao->descr;
+ Py_INCREF(descr);
+ arr = PyArray_FromAny(op, descr, 0, 0, FORCECAST, NULL);
+ if (arr == NULL) return -1;
- if ((mit->subspace != NULL) && (mit->consec)) {
- if (mit->iteraxes[0] > 0) { /* then we need to swap */
- _swap_axes(mit, (PyArrayObject **)&arr, 0);
- if (arr == NULL) return -1;
- }
+ if ((mit->subspace != NULL) && (mit->consec)) {
+ if (mit->iteraxes[0] > 0) { /* then we need to swap */
+ _swap_axes(mit, (PyArrayObject **)&arr, 0);
+ if (arr == NULL) return -1;
}
+ }
- /* Be sure values array is "broadcastable"
- to shape of mit->dimensions, mit->nd */
+ /* Be sure values array is "broadcastable"
+ to shape of mit->dimensions, mit->nd */
- if ((it = (PyArrayIterObject *)\
- PyArray_BroadcastToShape(arr, mit->dimensions, mit->nd))==NULL) {
- Py_DECREF(arr);
- return -1;
- }
+ if ((it = (PyArrayIterObject *)\
+ PyArray_BroadcastToShape(arr, mit->dimensions, mit->nd))==NULL) {
+ Py_DECREF(arr);
+ return -1;
+ }
- index = mit->size;
- swap = (PyArray_ISNOTSWAPPED(mit->ait->ao) != \
- (PyArray_ISNOTSWAPPED(arr)));
- copyswap = PyArray_DESCR(arr)->f->copyswap;
- PyArray_MapIterReset(mit);
- /* Need to decref hasobject arrays */
- if (PyDataType_FLAGCHK(descr, NPY_ITEM_REFCOUNT)) {
- while (index--) {
- PyArray_Item_XDECREF(mit->dataptr, PyArray_DESCR(arr));
- PyArray_Item_INCREF(it->dataptr, PyArray_DESCR(arr));
- memmove(mit->dataptr, it->dataptr, sizeof(PyObject *));
- /* ignored unless VOID array with object's */
- if (swap)
- copyswap(mit->dataptr, NULL, swap, arr);
- PyArray_MapIterNext(mit);
- PyArray_ITER_NEXT(it);
- }
- Py_DECREF(arr);
- Py_DECREF(it);
- return 0;
- }
- while(index--) {
- memmove(mit->dataptr, it->dataptr, PyArray_ITEMSIZE(arr));
- if (swap)
- copyswap(mit->dataptr, NULL, swap, arr);
- PyArray_MapIterNext(mit);
- PyArray_ITER_NEXT(it);
+ index = mit->size;
+ swap = (PyArray_ISNOTSWAPPED(mit->ait->ao) != \
+ (PyArray_ISNOTSWAPPED(arr)));
+ copyswap = PyArray_DESCR(arr)->f->copyswap;
+ PyArray_MapIterReset(mit);
+ /* Need to decref hasobject arrays */
+ if (PyDataType_FLAGCHK(descr, NPY_ITEM_REFCOUNT)) {
+ while (index--) {
+ PyArray_Item_XDECREF(mit->dataptr, PyArray_DESCR(arr));
+ PyArray_Item_INCREF(it->dataptr, PyArray_DESCR(arr));
+ memmove(mit->dataptr, it->dataptr, sizeof(PyObject *));
+ /* ignored unless VOID array with object's */
+ if (swap)
+ copyswap(mit->dataptr, NULL, swap, arr);
+ PyArray_MapIterNext(mit);
+ PyArray_ITER_NEXT(it);
}
Py_DECREF(arr);
Py_DECREF(it);
return 0;
+ }
+ while(index--) {
+ memmove(mit->dataptr, it->dataptr, PyArray_ITEMSIZE(arr));
+ if (swap)
+ copyswap(mit->dataptr, NULL, swap, arr);
+ PyArray_MapIterNext(mit);
+ PyArray_ITER_NEXT(it);
+ }
+ Py_DECREF(arr);
+ Py_DECREF(it);
+ return 0;
}
int
count_new_axes_0d(PyObject *tuple)
{
- int i, argument_count;
- int ellipsis_count = 0;
- int newaxis_count = 0;
+ int i, argument_count;
+ int ellipsis_count = 0;
+ int newaxis_count = 0;
- argument_count = PyTuple_GET_SIZE(tuple);
+ argument_count = PyTuple_GET_SIZE(tuple);
- for (i = 0; i < argument_count; ++i) {
- PyObject *arg = PyTuple_GET_ITEM(tuple, i);
- if (arg == Py_Ellipsis && !ellipsis_count) ellipsis_count++;
- else if (arg == Py_None) newaxis_count++;
- else break;
- }
- if (i < argument_count) {
- PyErr_SetString(PyExc_IndexError,
- "0-d arrays can only use a single ()"
- " or a list of newaxes (and a single ...)"
- " as an index");
- return -1;
- }
- if (newaxis_count > MAX_DIMS) {
- PyErr_SetString(PyExc_IndexError,
- "too many dimensions");
- return -1;
- }
- return newaxis_count;
+ for (i = 0; i < argument_count; ++i) {
+ PyObject *arg = PyTuple_GET_ITEM(tuple, i);
+ if (arg == Py_Ellipsis && !ellipsis_count) ellipsis_count++;
+ else if (arg == Py_None) newaxis_count++;
+ else break;
+ }
+ if (i < argument_count) {
+ PyErr_SetString(PyExc_IndexError,
+ "0-d arrays can only use a single ()"
+ " or a list of newaxes (and a single ...)"
+ " as an index");
+ return -1;
+ }
+ if (newaxis_count > MAX_DIMS) {
+ PyErr_SetString(PyExc_IndexError,
+ "too many dimensions");
+ return -1;
+ }
+ return newaxis_count;
}
static PyObject *
add_new_axes_0d(PyArrayObject *arr, int newaxis_count)
{
- PyArrayObject *other;
- intp dimensions[MAX_DIMS];
- int i;
- for (i = 0; i < newaxis_count; ++i) {
- dimensions[i] = 1;
- }
- Py_INCREF(arr->descr);
- if ((other = (PyArrayObject *)
- PyArray_NewFromDescr(arr->ob_type, arr->descr,
- newaxis_count, dimensions,
- NULL, arr->data,
- arr->flags,
- (PyObject *)arr)) == NULL)
- return NULL;
- other->base = (PyObject *)arr;
- Py_INCREF(arr);
- return (PyObject *)other;
+ PyArrayObject *other;
+ intp dimensions[MAX_DIMS];
+ int i;
+ for (i = 0; i < newaxis_count; ++i) {
+ dimensions[i] = 1;
+ }
+ Py_INCREF(arr->descr);
+ if ((other = (PyArrayObject *)
+ PyArray_NewFromDescr(arr->ob_type, arr->descr,
+ newaxis_count, dimensions,
+ NULL, arr->data,
+ arr->flags,
+ (PyObject *)arr)) == NULL)
+ return NULL;
+ other->base = (PyObject *)arr;
+ Py_INCREF(arr);
+ return (PyObject *)other;
}
@@ -2549,67 +2548,67 @@ add_new_axes_0d(PyArrayObject *arr, int newaxis_count)
static int
fancy_indexing_check(PyObject *args)
{
- int i, n;
- PyObject *obj;
- int retval = SOBJ_NOTFANCY;
-
- if (PyTuple_Check(args)) {
- n = PyTuple_GET_SIZE(args);
- if (n >= MAX_DIMS) return SOBJ_TOOMANY;
- for (i=0; i<n; i++) {
- obj = PyTuple_GET_ITEM(args,i);
- if (PyArray_Check(obj)) {
- if (PyArray_ISINTEGER(obj) ||
- PyArray_ISBOOL(obj))
- retval = SOBJ_ISFANCY;
- else {
- retval = SOBJ_BADARRAY;
- break;
- }
- }
- else if (PySequence_Check(obj)) {
- retval = SOBJ_ISFANCY;
- }
+ int i, n;
+ PyObject *obj;
+ int retval = SOBJ_NOTFANCY;
+
+ if (PyTuple_Check(args)) {
+ n = PyTuple_GET_SIZE(args);
+ if (n >= MAX_DIMS) return SOBJ_TOOMANY;
+ for (i=0; i<n; i++) {
+ obj = PyTuple_GET_ITEM(args,i);
+ if (PyArray_Check(obj)) {
+ if (PyArray_ISINTEGER(obj) ||
+ PyArray_ISBOOL(obj))
+ retval = SOBJ_ISFANCY;
+ else {
+ retval = SOBJ_BADARRAY;
+ break;
}
+ }
+ else if (PySequence_Check(obj)) {
+ retval = SOBJ_ISFANCY;
+ }
}
- else if (PyArray_Check(args)) {
- if ((PyArray_TYPE(args)==PyArray_BOOL) ||
- (PyArray_ISINTEGER(args)))
- return SOBJ_ISFANCY;
+ }
+ else if (PyArray_Check(args)) {
+ if ((PyArray_TYPE(args)==PyArray_BOOL) ||
+ (PyArray_ISINTEGER(args)))
+ return SOBJ_ISFANCY;
+ else
+ return SOBJ_BADARRAY;
+ }
+ else if (PySequence_Check(args)) {
+ /* Sequences < MAX_DIMS with any slice objects
+ or newaxis, or Ellipsis is considered standard
+ as long as there are also no Arrays and or additional
+ sequences embedded.
+ */
+ retval = SOBJ_ISFANCY;
+ n = PySequence_Size(args);
+ if (n<0 || n>=MAX_DIMS) return SOBJ_ISFANCY;
+ for (i=0; i<n; i++) {
+ obj = PySequence_GetItem(args, i);
+ if (obj == NULL) return SOBJ_ISFANCY;
+ if (PyArray_Check(obj)) {
+ if (PyArray_ISINTEGER(obj) ||
+ PyArray_ISBOOL(obj))
+ retval = SOBJ_LISTTUP;
else
- return SOBJ_BADARRAY;
- }
- else if (PySequence_Check(args)) {
- /* Sequences < MAX_DIMS with any slice objects
- or newaxis, or Ellipsis is considered standard
- as long as there are also no Arrays and or additional
- sequences embedded.
- */
- retval = SOBJ_ISFANCY;
- n = PySequence_Size(args);
- if (n<0 || n>=MAX_DIMS) return SOBJ_ISFANCY;
- for (i=0; i<n; i++) {
- obj = PySequence_GetItem(args, i);
- if (obj == NULL) return SOBJ_ISFANCY;
- if (PyArray_Check(obj)) {
- if (PyArray_ISINTEGER(obj) ||
- PyArray_ISBOOL(obj))
- retval = SOBJ_LISTTUP;
- else
- retval = SOBJ_BADARRAY;
- }
- else if (PySequence_Check(obj)) {
- retval = SOBJ_LISTTUP;
- }
- else if (PySlice_Check(obj) || obj == Py_Ellipsis ||
- obj == Py_None) {
- retval = SOBJ_NOTFANCY;
- }
- Py_DECREF(obj);
- if (retval > SOBJ_ISFANCY) return retval;
- }
+ retval = SOBJ_BADARRAY;
+ }
+ else if (PySequence_Check(obj)) {
+ retval = SOBJ_LISTTUP;
+ }
+ else if (PySlice_Check(obj) || obj == Py_Ellipsis ||
+ obj == Py_None) {
+ retval = SOBJ_NOTFANCY;
+ }
+ Py_DECREF(obj);
+ if (retval > SOBJ_ISFANCY) return retval;
}
- return retval;
+ }
+ return retval;
}
/* Called when treating array object like a mapping -- called first from
@@ -2620,11 +2619,11 @@ fancy_indexing_check(PyObject *args)
/* There are two situations:
- 1 - the subscript is a standard view and a reference to the
- array can be returned
+ 1 - the subscript is a standard view and a reference to the
+ array can be returned
- 2 - the subscript uses Boolean masks or integer indexing and
- therefore a new array is created and returned.
+ 2 - the subscript uses Boolean masks or integer indexing and
+ therefore a new array is created and returned.
*/
@@ -2636,143 +2635,143 @@ static PyObject *iter_subscript(PyArrayIterObject *, PyObject *);
static PyObject *
array_subscript_simple(PyArrayObject *self, PyObject *op)
{
- intp dimensions[MAX_DIMS], strides[MAX_DIMS];
- intp offset;
- int nd;
- PyArrayObject *other;
- intp value;
-
- value = PyArray_PyIntAsIntp(op);
- if (!PyErr_Occurred()) {
- return array_big_item(self, value);
- }
- PyErr_Clear();
+ intp dimensions[MAX_DIMS], strides[MAX_DIMS];
+ intp offset;
+ int nd;
+ PyArrayObject *other;
+ intp value;
- /* Standard (view-based) Indexing */
- if ((nd = parse_index(self, op, dimensions, strides, &offset))
- == -1) return NULL;
-
- /* This will only work if new array will be a view */
- Py_INCREF(self->descr);
- if ((other = (PyArrayObject *) \
- PyArray_NewFromDescr(self->ob_type, self->descr,
- nd, dimensions,
- strides, self->data+offset,
- self->flags,
- (PyObject *)self)) == NULL)
- return NULL;
+ value = PyArray_PyIntAsIntp(op);
+ if (!PyErr_Occurred()) {
+ return array_big_item(self, value);
+ }
+ PyErr_Clear();
+
+ /* Standard (view-based) Indexing */
+ if ((nd = parse_index(self, op, dimensions, strides, &offset))
+ == -1) return NULL;
+
+ /* This will only work if new array will be a view */
+ Py_INCREF(self->descr);
+ if ((other = (PyArrayObject *) \
+ PyArray_NewFromDescr(self->ob_type, self->descr,
+ nd, dimensions,
+ strides, self->data+offset,
+ self->flags,
+ (PyObject *)self)) == NULL)
+ return NULL;
- other->base = (PyObject *)self;
- Py_INCREF(self);
+ other->base = (PyObject *)self;
+ Py_INCREF(self);
- PyArray_UpdateFlags(other, UPDATE_ALL);
+ PyArray_UpdateFlags(other, UPDATE_ALL);
- return (PyObject *)other;
+ return (PyObject *)other;
}
static PyObject *
array_subscript(PyArrayObject *self, PyObject *op)
{
- int nd, fancy;
- PyArrayObject *other;
- PyArrayMapIterObject *mit;
+ int nd, fancy;
+ PyArrayObject *other;
+ PyArrayMapIterObject *mit;
- if (PyString_Check(op) || PyUnicode_Check(op)) {
- if (self->descr->names) {
- PyObject *obj;
- obj = PyDict_GetItem(self->descr->fields, op);
- if (obj != NULL) {
- PyArray_Descr *descr;
- int offset;
- PyObject *title;
-
- if (PyArg_ParseTuple(obj, "Oi|O",
- &descr, &offset, &title)) {
- Py_INCREF(descr);
- return PyArray_GetField(self, descr,
- offset);
- }
- }
- }
+ if (PyString_Check(op) || PyUnicode_Check(op)) {
+ if (self->descr->names) {
+ PyObject *obj;
+ obj = PyDict_GetItem(self->descr->fields, op);
+ if (obj != NULL) {
+ PyArray_Descr *descr;
+ int offset;
+ PyObject *title;
- PyErr_Format(PyExc_ValueError,
- "field named %s not found.",
- PyString_AsString(op));
- return NULL;
+ if (PyArg_ParseTuple(obj, "Oi|O",
+ &descr, &offset, &title)) {
+ Py_INCREF(descr);
+ return PyArray_GetField(self, descr,
+ offset);
+ }
+ }
}
- if (self->nd == 0) {
- if (op == Py_Ellipsis) {
- /* XXX: This leads to a small inconsistency
- XXX: with the nd>0 case where (x[...] is x)
- XXX: is false for nd>0 case. */
- Py_INCREF(self);
- return (PyObject *)self;
- }
- if (op == Py_None)
- return add_new_axes_0d(self, 1);
- if (PyTuple_Check(op)) {
- if (0 == PyTuple_GET_SIZE(op)) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- if ((nd = count_new_axes_0d(op)) == -1)
- return NULL;
- return add_new_axes_0d(self, nd);
- }
- /* Allow Boolean mask selection also */
- if (PyBool_Check(op) || PyArray_IsScalar(op, Bool) ||
- (PyArray_Check(op) && (PyArray_DIMS(op)==0) &&
- PyArray_ISBOOL(op))) {
- if (PyObject_IsTrue(op)) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- else {
- intp oned = 0;
- Py_INCREF(self->descr);
- return PyArray_NewFromDescr(self->ob_type,
- self->descr,
- 1, &oned,
- NULL, NULL,
- NPY_DEFAULT,
- NULL);
- }
- }
- PyErr_SetString(PyExc_IndexError,
- "0-d arrays can't be indexed.");
+ PyErr_Format(PyExc_ValueError,
+ "field named %s not found.",
+ PyString_AsString(op));
+ return NULL;
+ }
+
+ if (self->nd == 0) {
+ if (op == Py_Ellipsis) {
+ /* XXX: This leads to a small inconsistency
+ XXX: with the nd>0 case where (x[...] is x)
+ XXX: is false for nd>0 case. */
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ if (op == Py_None)
+ return add_new_axes_0d(self, 1);
+ if (PyTuple_Check(op)) {
+ if (0 == PyTuple_GET_SIZE(op)) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ if ((nd = count_new_axes_0d(op)) == -1)
return NULL;
+ return add_new_axes_0d(self, nd);
}
-
- fancy = fancy_indexing_check(op);
-
- if (fancy != SOBJ_NOTFANCY) {
- int oned;
- oned = ((self->nd == 1) &&
- !(PyTuple_Check(op) && PyTuple_GET_SIZE(op) > 1));
-
- /* wrap arguments into a mapiter object */
- mit = (PyArrayMapIterObject *)\
- PyArray_MapIterNew(op, oned, fancy);
- if (mit == NULL) return NULL;
- if (oned) {
- PyArrayIterObject *it;
- PyObject *rval;
- it = (PyArrayIterObject *)\
- PyArray_IterNew((PyObject *)self);
- if (it == NULL) {Py_DECREF(mit); return NULL;}
- rval = iter_subscript(it, mit->indexobj);
- Py_DECREF(it);
- Py_DECREF(mit);
- return rval;
- }
- PyArray_MapIterBind(mit, self);
- other = (PyArrayObject *)PyArray_GetMap(mit);
- Py_DECREF(mit);
- return (PyObject *)other;
+ /* Allow Boolean mask selection also */
+ if (PyBool_Check(op) || PyArray_IsScalar(op, Bool) ||
+ (PyArray_Check(op) && (PyArray_DIMS(op)==0) &&
+ PyArray_ISBOOL(op))) {
+ if (PyObject_IsTrue(op)) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ else {
+ intp oned = 0;
+ Py_INCREF(self->descr);
+ return PyArray_NewFromDescr(self->ob_type,
+ self->descr,
+ 1, &oned,
+ NULL, NULL,
+ NPY_DEFAULT,
+ NULL);
+ }
}
+ PyErr_SetString(PyExc_IndexError,
+ "0-d arrays can't be indexed.");
+ return NULL;
+ }
+
+ fancy = fancy_indexing_check(op);
+
+ if (fancy != SOBJ_NOTFANCY) {
+ int oned;
+ oned = ((self->nd == 1) &&
+ !(PyTuple_Check(op) && PyTuple_GET_SIZE(op) > 1));
+
+ /* wrap arguments into a mapiter object */
+ mit = (PyArrayMapIterObject *)\
+ PyArray_MapIterNew(op, oned, fancy);
+ if (mit == NULL) return NULL;
+ if (oned) {
+ PyArrayIterObject *it;
+ PyObject *rval;
+ it = (PyArrayIterObject *)\
+ PyArray_IterNew((PyObject *)self);
+ if (it == NULL) {Py_DECREF(mit); return NULL;}
+ rval = iter_subscript(it, mit->indexobj);
+ Py_DECREF(it);
+ Py_DECREF(mit);
+ return rval;
+ }
+ PyArray_MapIterBind(mit, self);
+ other = (PyArrayObject *)PyArray_GetMap(mit);
+ Py_DECREF(mit);
+ return (PyObject *)other;
+ }
- return array_subscript_simple(self, op);
+ return array_subscript_simple(self, op);
}
@@ -2790,43 +2789,43 @@ static int iter_ass_subscript(PyArrayIterObject *, PyObject *, PyObject *);
static int
array_ass_sub_simple(PyArrayObject *self, PyObject *index, PyObject *op)
{
- int ret;
- PyArrayObject *tmp;
- intp value;
+ int ret;
+ PyArrayObject *tmp;
+ intp value;
- value = PyArray_PyIntAsIntp(index);
- if (!error_converting(value)) {
- return array_ass_big_item(self, value, op);
- }
- PyErr_Clear();
+ value = PyArray_PyIntAsIntp(index);
+ if (!error_converting(value)) {
+ return array_ass_big_item(self, value, op);
+ }
+ PyErr_Clear();
- /* Rest of standard (view-based) indexing */
+ /* Rest of standard (view-based) indexing */
- if (PyArray_CheckExact(self)) {
- tmp = (PyArrayObject *)array_subscript_simple(self, index);
- if (tmp == NULL) return -1;
- }
- else {
- PyObject *tmp0;
- tmp0 = PyObject_GetItem((PyObject *)self, index);
- if (tmp0 == NULL) return -1;
- if (!PyArray_Check(tmp0)) {
- PyErr_SetString(PyExc_RuntimeError,
- "Getitem not returning array.");
- Py_DECREF(tmp0);
- return -1;
- }
- tmp = (PyArrayObject *)tmp0;
- }
+ if (PyArray_CheckExact(self)) {
+ tmp = (PyArrayObject *)array_subscript_simple(self, index);
+ if (tmp == NULL) return -1;
+ }
+ else {
+ PyObject *tmp0;
+ tmp0 = PyObject_GetItem((PyObject *)self, index);
+ if (tmp0 == NULL) return -1;
+ if (!PyArray_Check(tmp0)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Getitem not returning array.");
+ Py_DECREF(tmp0);
+ return -1;
+ }
+ tmp = (PyArrayObject *)tmp0;
+ }
- if (PyArray_ISOBJECT(self) && (tmp->nd == 0)) {
- ret = tmp->descr->f->setitem(op, tmp->data, tmp);
- }
- else {
- ret = PyArray_CopyObject(tmp, op);
- }
- Py_DECREF(tmp);
- return ret;
+ if (PyArray_ISOBJECT(self) && (tmp->nd == 0)) {
+ ret = tmp->descr->f->setitem(op, tmp->data, tmp);
+ }
+ else {
+ ret = PyArray_CopyObject(tmp, op);
+ }
+ Py_DECREF(tmp);
+ return ret;
}
@@ -2836,150 +2835,150 @@ array_ass_sub_simple(PyArrayObject *self, PyObject *index, PyObject *op)
static int
_tuple_of_integers(PyObject *seq, intp *vals, int maxvals)
{
- int i;
- PyObject *obj;
- intp temp;
-
- for (i=0; i<maxvals; i++) {
- obj = PyTuple_GET_ITEM(seq, i);
- if ((PyArray_Check(obj) && PyArray_NDIM(obj) > 0) ||
- PyList_Check(obj)) return -1;
- temp = PyArray_PyIntAsIntp(obj);
- if (error_converting(temp)) return -1;
- vals[i] = temp;
- }
- return 0;
+ int i;
+ PyObject *obj;
+ intp temp;
+
+ for (i=0; i<maxvals; i++) {
+ obj = PyTuple_GET_ITEM(seq, i);
+ if ((PyArray_Check(obj) && PyArray_NDIM(obj) > 0) ||
+ PyList_Check(obj)) return -1;
+ temp = PyArray_PyIntAsIntp(obj);
+ if (error_converting(temp)) return -1;
+ vals[i] = temp;
+ }
+ return 0;
}
static int
array_ass_sub(PyArrayObject *self, PyObject *index, PyObject *op)
{
- int ret, oned, fancy;
- PyArrayMapIterObject *mit;
- intp vals[MAX_DIMS];
-
- if (op == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "cannot delete array elements");
- return -1;
- }
- if (!PyArray_ISWRITEABLE(self)) {
- PyErr_SetString(PyExc_RuntimeError,
- "array is not writeable");
- return -1;
- }
+ int ret, oned, fancy;
+ PyArrayMapIterObject *mit;
+ intp vals[MAX_DIMS];
- if (PyInt_Check(index) || PyArray_IsScalar(index, Integer) ||
- PyLong_Check(index) || (PyIndex_Check(index) &&
- !PySequence_Check(index))) {
- intp value;
- value = PyArray_PyIntAsIntp(index);
- if (PyErr_Occurred())
- PyErr_Clear();
- else
- return array_ass_big_item(self, value, op);
- }
-
- if (PyString_Check(index) || PyUnicode_Check(index)) {
- if (self->descr->names) {
- PyObject *obj;
- obj = PyDict_GetItem(self->descr->fields, index);
- if (obj != NULL) {
- PyArray_Descr *descr;
- int offset;
- PyObject *title;
-
- if (PyArg_ParseTuple(obj, "Oi|O",
- &descr, &offset, &title)) {
- Py_INCREF(descr);
- return PyArray_SetField(self, descr,
- offset, op);
- }
- }
- }
+ if (op == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot delete array elements");
+ return -1;
+ }
+ if (!PyArray_ISWRITEABLE(self)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "array is not writeable");
+ return -1;
+ }
- PyErr_Format(PyExc_ValueError,
- "field named %s not found.",
- PyString_AsString(index));
- return -1;
- }
+ if (PyInt_Check(index) || PyArray_IsScalar(index, Integer) ||
+ PyLong_Check(index) || (PyIndex_Check(index) &&
+ !PySequence_Check(index))) {
+ intp value;
+ value = PyArray_PyIntAsIntp(index);
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ else
+ return array_ass_big_item(self, value, op);
+ }
- if (self->nd == 0) {
- /* Several different exceptions to the 0-d no-indexing rule
+ if (PyString_Check(index) || PyUnicode_Check(index)) {
+ if (self->descr->names) {
+ PyObject *obj;
+ obj = PyDict_GetItem(self->descr->fields, index);
+ if (obj != NULL) {
+ PyArray_Descr *descr;
+ int offset;
+ PyObject *title;
- 1) ellipses
- 2) empty tuple
- 3) Using newaxis (None)
- 4) Boolean mask indexing
- */
- if (index == Py_Ellipsis || index == Py_None || \
- (PyTuple_Check(index) && (0 == PyTuple_GET_SIZE(index) || \
- count_new_axes_0d(index) > 0)))
- return self->descr->f->setitem(op, self->data, self);
- if (PyBool_Check(index) || PyArray_IsScalar(index, Bool) ||
- (PyArray_Check(index) && (PyArray_DIMS(index)==0) &&
- PyArray_ISBOOL(index))) {
- if (PyObject_IsTrue(index)) {
- return self->descr->f->setitem(op, self->data, self);
- }
- else { /* don't do anything */
- return 0;
- }
+ if (PyArg_ParseTuple(obj, "Oi|O",
+ &descr, &offset, &title)) {
+ Py_INCREF(descr);
+ return PyArray_SetField(self, descr,
+ offset, op);
}
- PyErr_SetString(PyExc_IndexError,
- "0-d arrays can't be indexed.");
- return -1;
+ }
}
-
- /* optimization for integer-tuple */
- if (self->nd > 1 &&
- (PyTuple_Check(index) && (PyTuple_GET_SIZE(index) == self->nd))
- && (_tuple_of_integers(index, vals, self->nd) >= 0)) {
- int i;
- char *item;
- for (i=0; i<self->nd; i++) {
- if (vals[i] < 0) vals[i] += self->dimensions[i];
- if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
- PyErr_Format(PyExc_IndexError,
- "index (%"INTP_FMT") out of range "\
- "(0<=index<%"INTP_FMT") in dimension %d",
- vals[i], self->dimensions[i], i);
- return -1;
- }
- }
- item = PyArray_GetPtr(self, vals);
- /* fprintf(stderr, "Here I am...\n");*/
- return self->descr->f->setitem(op, item, self);
+
+ PyErr_Format(PyExc_ValueError,
+ "field named %s not found.",
+ PyString_AsString(index));
+ return -1;
+ }
+
+ if (self->nd == 0) {
+ /* Several different exceptions to the 0-d no-indexing rule
+
+ 1) ellipses
+ 2) empty tuple
+ 3) Using newaxis (None)
+ 4) Boolean mask indexing
+ */
+ if (index == Py_Ellipsis || index == Py_None || \
+ (PyTuple_Check(index) && (0 == PyTuple_GET_SIZE(index) || \
+ count_new_axes_0d(index) > 0)))
+ return self->descr->f->setitem(op, self->data, self);
+ if (PyBool_Check(index) || PyArray_IsScalar(index, Bool) ||
+ (PyArray_Check(index) && (PyArray_DIMS(index)==0) &&
+ PyArray_ISBOOL(index))) {
+ if (PyObject_IsTrue(index)) {
+ return self->descr->f->setitem(op, self->data, self);
+ }
+ else { /* don't do anything */
+ return 0;
+ }
}
- PyErr_Clear();
+ PyErr_SetString(PyExc_IndexError,
+ "0-d arrays can't be indexed.");
+ return -1;
+ }
- fancy = fancy_indexing_check(index);
-
- if (fancy != SOBJ_NOTFANCY) {
- oned = ((self->nd == 1) &&
- !(PyTuple_Check(index) && PyTuple_GET_SIZE(index) > 1));
-
- mit = (PyArrayMapIterObject *) \
- PyArray_MapIterNew(index, oned, fancy);
- if (mit == NULL) return -1;
- if (oned) {
- PyArrayIterObject *it;
- int rval;
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
- if (it == NULL) {Py_DECREF(mit); return -1;}
- rval = iter_ass_subscript(it, mit->indexobj, op);
- Py_DECREF(it);
- Py_DECREF(mit);
- return rval;
- }
- PyArray_MapIterBind(mit, self);
- ret = PyArray_SetMap(mit, op);
- Py_DECREF(mit);
- return ret;
+ /* optimization for integer-tuple */
+ if (self->nd > 1 &&
+ (PyTuple_Check(index) && (PyTuple_GET_SIZE(index) == self->nd))
+ && (_tuple_of_integers(index, vals, self->nd) >= 0)) {
+ int i;
+ char *item;
+ for (i=0; i<self->nd; i++) {
+ if (vals[i] < 0) vals[i] += self->dimensions[i];
+ if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
+ PyErr_Format(PyExc_IndexError,
+ "index (%"INTP_FMT") out of range "\
+ "(0<=index<%"INTP_FMT") in dimension %d",
+ vals[i], self->dimensions[i], i);
+ return -1;
+ }
}
+ item = PyArray_GetPtr(self, vals);
+ /* fprintf(stderr, "Here I am...\n");*/
+ return self->descr->f->setitem(op, item, self);
+ }
+ PyErr_Clear();
+
+ fancy = fancy_indexing_check(index);
+
+ if (fancy != SOBJ_NOTFANCY) {
+ oned = ((self->nd == 1) &&
+ !(PyTuple_Check(index) && PyTuple_GET_SIZE(index) > 1));
+
+ mit = (PyArrayMapIterObject *) \
+ PyArray_MapIterNew(index, oned, fancy);
+ if (mit == NULL) return -1;
+ if (oned) {
+ PyArrayIterObject *it;
+ int rval;
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
+ if (it == NULL) {Py_DECREF(mit); return -1;}
+ rval = iter_ass_subscript(it, mit->indexobj, op);
+ Py_DECREF(it);
+ Py_DECREF(mit);
+ return rval;
+ }
+ PyArray_MapIterBind(mit, self);
+ ret = PyArray_SetMap(mit, op);
+ Py_DECREF(mit);
+ return ret;
+ }
- return array_ass_sub_simple(self, index, op);
+ return array_ass_sub_simple(self, index, op);
}
@@ -2993,94 +2992,94 @@ static PyObject *
array_subscript_nice(PyArrayObject *self, PyObject *op)
{
- PyArrayObject *mp;
- intp vals[MAX_DIMS];
+ PyArrayObject *mp;
+ intp vals[MAX_DIMS];
- if (PyInt_Check(op) || PyArray_IsScalar(op, Integer) || \
- PyLong_Check(op) || (PyIndex_Check(op) &&
- !PySequence_Check(op))) {
- intp value;
- value = PyArray_PyIntAsIntp(op);
- if (PyErr_Occurred())
- PyErr_Clear();
- else {
- return array_item_nice(self, (Py_ssize_t) value);
- }
+ if (PyInt_Check(op) || PyArray_IsScalar(op, Integer) || \
+ PyLong_Check(op) || (PyIndex_Check(op) &&
+ !PySequence_Check(op))) {
+ intp value;
+ value = PyArray_PyIntAsIntp(op);
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ else {
+ return array_item_nice(self, (Py_ssize_t) value);
}
- /* optimization for a tuple of integers */
- if (self->nd > 1 && PyTuple_Check(op) &&
- (PyTuple_GET_SIZE(op) == self->nd)
- && (_tuple_of_integers(op, vals, self->nd) >= 0)) {
- int i;
- char *item;
- for (i=0; i<self->nd; i++) {
- if (vals[i] < 0) vals[i] += self->dimensions[i];
- if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
- PyErr_Format(PyExc_IndexError,
- "index (%"INTP_FMT") out of range "\
- "(0<=index<=%"INTP_FMT") in dimension %d",
- vals[i], self->dimensions[i], i);
- return NULL;
- }
- }
- item = PyArray_GetPtr(self, vals);
- return PyArray_Scalar(item, self->descr, (PyObject *)self);
+ }
+ /* optimization for a tuple of integers */
+ if (self->nd > 1 && PyTuple_Check(op) &&
+ (PyTuple_GET_SIZE(op) == self->nd)
+ && (_tuple_of_integers(op, vals, self->nd) >= 0)) {
+ int i;
+ char *item;
+ for (i=0; i<self->nd; i++) {
+ if (vals[i] < 0) vals[i] += self->dimensions[i];
+ if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
+ PyErr_Format(PyExc_IndexError,
+ "index (%"INTP_FMT") out of range "\
+ "(0<=index<=%"INTP_FMT") in dimension %d",
+ vals[i], self->dimensions[i], i);
+ return NULL;
+ }
}
- PyErr_Clear();
+ item = PyArray_GetPtr(self, vals);
+ return PyArray_Scalar(item, self->descr, (PyObject *)self);
+ }
+ PyErr_Clear();
- mp = (PyArrayObject *)array_subscript(self, op);
+ mp = (PyArrayObject *)array_subscript(self, op);
- /* The following is just a copy of PyArray_Return with an
- additional logic in the nd == 0 case.
- */
+ /* The following is just a copy of PyArray_Return with an
+ additional logic in the nd == 0 case.
+ */
- if (mp == NULL) return NULL;
+ if (mp == NULL) return NULL;
- if (PyErr_Occurred()) {
- Py_XDECREF(mp);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_XDECREF(mp);
+ return NULL;
+ }
- if (mp->nd == 0) {
- Bool noellipses = TRUE;
- if ((op == Py_Ellipsis) || PyString_Check(op) || PyUnicode_Check(op))
- noellipses = FALSE;
- else if (PyBool_Check(op) || PyArray_IsScalar(op, Bool) ||
- (PyArray_Check(op) && (PyArray_DIMS(op)==0) &&
- PyArray_ISBOOL(op)))
- noellipses = FALSE;
- else if (PySequence_Check(op)) {
- int n, i;
- PyObject *temp;
- n = PySequence_Size(op);
- i=0;
- while (i<n && noellipses) {
- temp = PySequence_GetItem(op, i);
- if (temp == Py_Ellipsis)
- noellipses = FALSE;
- Py_DECREF(temp);
- i++;
- }
- }
- if (noellipses) {
- PyObject *ret;
- ret = PyArray_ToScalar(mp->data, mp);
- Py_DECREF(mp);
- return ret;
- }
+ if (mp->nd == 0) {
+ Bool noellipses = TRUE;
+ if ((op == Py_Ellipsis) || PyString_Check(op) || PyUnicode_Check(op))
+ noellipses = FALSE;
+ else if (PyBool_Check(op) || PyArray_IsScalar(op, Bool) ||
+ (PyArray_Check(op) && (PyArray_DIMS(op)==0) &&
+ PyArray_ISBOOL(op)))
+ noellipses = FALSE;
+ else if (PySequence_Check(op)) {
+ int n, i;
+ PyObject *temp;
+ n = PySequence_Size(op);
+ i=0;
+ while (i<n && noellipses) {
+ temp = PySequence_GetItem(op, i);
+ if (temp == Py_Ellipsis)
+ noellipses = FALSE;
+ Py_DECREF(temp);
+ i++;
+ }
}
- return (PyObject *)mp;
+ if (noellipses) {
+ PyObject *ret;
+ ret = PyArray_ToScalar(mp->data, mp);
+ Py_DECREF(mp);
+ return ret;
+ }
+ }
+ return (PyObject *)mp;
}
static PyMappingMethods array_as_mapping = {
#if PY_VERSION_HEX >= 0x02050000
- (lenfunc)array_length, /*mp_length*/
+ (lenfunc)array_length, /*mp_length*/
#else
- (inquiry)array_length, /*mp_length*/
+ (inquiry)array_length, /*mp_length*/
#endif
- (binaryfunc)array_subscript_nice, /*mp_subscript*/
- (objobjargproc)array_ass_sub, /*mp_ass_subscript*/
+ (binaryfunc)array_subscript_nice, /*mp_subscript*/
+ (objobjargproc)array_ass_sub, /*mp_ass_subscript*/
};
/****************** End of Mapping Protocol ******************************/
@@ -3095,75 +3094,75 @@ static PyMappingMethods array_as_mapping = {
static Py_ssize_t
array_getsegcount(PyArrayObject *self, Py_ssize_t *lenp)
{
- if (lenp)
- *lenp = PyArray_NBYTES(self);
+ if (lenp)
+ *lenp = PyArray_NBYTES(self);
- if (PyArray_ISONESEGMENT(self)) {
- return 1;
- }
+ if (PyArray_ISONESEGMENT(self)) {
+ return 1;
+ }
- if (lenp)
- *lenp = 0;
- return 0;
+ if (lenp)
+ *lenp = 0;
+ return 0;
}
static Py_ssize_t
array_getreadbuf(PyArrayObject *self, Py_ssize_t segment, void **ptrptr)
{
- if (segment != 0) {
- PyErr_SetString(PyExc_ValueError,
- "accessing non-existing array segment");
- return -1;
- }
-
- if (PyArray_ISONESEGMENT(self)) {
- *ptrptr = self->data;
- return PyArray_NBYTES(self);
- }
- PyErr_SetString(PyExc_ValueError, "array is not a single segment");
- *ptrptr = NULL;
+ if (segment != 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "accessing non-existing array segment");
return -1;
+ }
+
+ if (PyArray_ISONESEGMENT(self)) {
+ *ptrptr = self->data;
+ return PyArray_NBYTES(self);
+ }
+ PyErr_SetString(PyExc_ValueError, "array is not a single segment");
+ *ptrptr = NULL;
+ return -1;
}
static Py_ssize_t
array_getwritebuf(PyArrayObject *self, Py_ssize_t segment, void **ptrptr)
{
- if (PyArray_CHKFLAGS(self, WRITEABLE))
- return array_getreadbuf(self, segment, (void **) ptrptr);
- else {
- PyErr_SetString(PyExc_ValueError, "array cannot be "\
- "accessed as a writeable buffer");
- return -1;
- }
+ if (PyArray_CHKFLAGS(self, WRITEABLE))
+ return array_getreadbuf(self, segment, (void **) ptrptr);
+ else {
+ PyErr_SetString(PyExc_ValueError, "array cannot be "\
+ "accessed as a writeable buffer");
+ return -1;
+ }
}
static Py_ssize_t
array_getcharbuf(PyArrayObject *self, Py_ssize_t segment, constchar **ptrptr)
{
- if (self->descr->type_num == PyArray_STRING || \
- self->descr->type_num == PyArray_UNICODE || \
- self->descr->elsize == 1)
- return array_getreadbuf(self, segment, (void **) ptrptr);
- else {
- PyErr_SetString(PyExc_TypeError,
- "non-character (or 8-bit) array cannot be "\
- "interpreted as character buffer");
- return -1;
- }
+ if (self->descr->type_num == PyArray_STRING || \
+ self->descr->type_num == PyArray_UNICODE || \
+ self->descr->elsize == 1)
+ return array_getreadbuf(self, segment, (void **) ptrptr);
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "non-character (or 8-bit) array cannot be "\
+ "interpreted as character buffer");
+ return -1;
+ }
}
static PyBufferProcs array_as_buffer = {
#if PY_VERSION_HEX >= 0x02050000
- (readbufferproc)array_getreadbuf, /*bf_getreadbuffer*/
- (writebufferproc)array_getwritebuf, /*bf_getwritebuffer*/
- (segcountproc)array_getsegcount, /*bf_getsegcount*/
- (charbufferproc)array_getcharbuf, /*bf_getcharbuffer*/
+ (readbufferproc)array_getreadbuf, /*bf_getreadbuffer*/
+ (writebufferproc)array_getwritebuf, /*bf_getwritebuffer*/
+ (segcountproc)array_getsegcount, /*bf_getsegcount*/
+ (charbufferproc)array_getcharbuf, /*bf_getcharbuffer*/
#else
- (getreadbufferproc)array_getreadbuf, /*bf_getreadbuffer*/
- (getwritebufferproc)array_getwritebuf, /*bf_getwritebuffer*/
- (getsegcountproc)array_getsegcount, /*bf_getsegcount*/
- (getcharbufferproc)array_getcharbuf, /*bf_getcharbuffer*/
+ (getreadbufferproc)array_getreadbuf, /*bf_getreadbuffer*/
+ (getwritebufferproc)array_getwritebuf, /*bf_getwritebuffer*/
+ (getsegcountproc)array_getsegcount, /*bf_getsegcount*/
+ (getcharbufferproc)array_getcharbuf, /*bf_getcharbuffer*/
#endif
};
@@ -3176,197 +3175,197 @@ static PyBufferProcs array_as_buffer = {
typedef struct {
- PyObject *add,
- *subtract,
- *multiply,
- *divide,
- *remainder,
- *power,
- *square,
- *reciprocal,
- *ones_like,
- *sqrt,
- *negative,
- *absolute,
- *invert,
- *left_shift,
- *right_shift,
- *bitwise_and,
- *bitwise_xor,
- *bitwise_or,
- *less,
- *less_equal,
- *equal,
- *not_equal,
- *greater,
- *greater_equal,
- *floor_divide,
- *true_divide,
- *logical_or,
- *logical_and,
- *floor,
- *ceil,
- *maximum,
- *minimum,
- *rint,
- *conjugate;
+ PyObject *add,
+ *subtract,
+ *multiply,
+ *divide,
+ *remainder,
+ *power,
+ *square,
+ *reciprocal,
+ *ones_like,
+ *sqrt,
+ *negative,
+ *absolute,
+ *invert,
+ *left_shift,
+ *right_shift,
+ *bitwise_and,
+ *bitwise_xor,
+ *bitwise_or,
+ *less,
+ *less_equal,
+ *equal,
+ *not_equal,
+ *greater,
+ *greater_equal,
+ *floor_divide,
+ *true_divide,
+ *logical_or,
+ *logical_and,
+ *floor,
+ *ceil,
+ *maximum,
+ *minimum,
+ *rint,
+ *conjugate;
} NumericOps;
static NumericOps n_ops; /* NB: static objects inlitialized to zero */
/* Dictionary can contain any of the numeric operations, by name.
- Those not present will not be changed
- */
+ Those not present will not be changed
+*/
#define SET(op) temp=PyDict_GetItemString(dict, #op); \
- if (temp != NULL) { \
- if (!(PyCallable_Check(temp))) return -1; \
- Py_XDECREF(n_ops.op); \
- n_ops.op = temp; \
- }
+ if (temp != NULL) { \
+ if (!(PyCallable_Check(temp))) return -1; \
+ Py_XDECREF(n_ops.op); \
+ n_ops.op = temp; \
+ }
/*OBJECT_API
- Set internal structure with number functions that all arrays will use
+ Set internal structure with number functions that all arrays will use
*/
int
PyArray_SetNumericOps(PyObject *dict)
{
- PyObject *temp = NULL;
- SET(add);
- SET(subtract);
- SET(multiply);
- SET(divide);
- SET(remainder);
- SET(power);
- SET(square);
- SET(reciprocal);
- SET(ones_like);
- SET(sqrt);
- SET(negative);
- SET(absolute);
- SET(invert);
- SET(left_shift);
- SET(right_shift);
- SET(bitwise_and);
- SET(bitwise_or);
- SET(bitwise_xor);
- SET(less);
- SET(less_equal);
- SET(equal);
- SET(not_equal);
- SET(greater);
- SET(greater_equal);
- SET(floor_divide);
- SET(true_divide);
- SET(logical_or);
- SET(logical_and);
- SET(floor);
- SET(ceil);
- SET(maximum);
- SET(minimum);
- SET(rint);
- SET(conjugate);
- return 0;
+ PyObject *temp = NULL;
+ SET(add);
+ SET(subtract);
+ SET(multiply);
+ SET(divide);
+ SET(remainder);
+ SET(power);
+ SET(square);
+ SET(reciprocal);
+ SET(ones_like);
+ SET(sqrt);
+ SET(negative);
+ SET(absolute);
+ SET(invert);
+ SET(left_shift);
+ SET(right_shift);
+ SET(bitwise_and);
+ SET(bitwise_or);
+ SET(bitwise_xor);
+ SET(less);
+ SET(less_equal);
+ SET(equal);
+ SET(not_equal);
+ SET(greater);
+ SET(greater_equal);
+ SET(floor_divide);
+ SET(true_divide);
+ SET(logical_or);
+ SET(logical_and);
+ SET(floor);
+ SET(ceil);
+ SET(maximum);
+ SET(minimum);
+ SET(rint);
+ SET(conjugate);
+ return 0;
}
#define GET(op) if (n_ops.op && \
(PyDict_SetItemString(dict, #op, n_ops.op)==-1)) \
- goto fail;
+ goto fail;
/*OBJECT_API
- Get dictionary showing number functions that all arrays will use
+ Get dictionary showing number functions that all arrays will use
*/
static PyObject *
PyArray_GetNumericOps(void)
{
- PyObject *dict;
- if ((dict = PyDict_New())==NULL)
- return NULL;
- GET(add);
- GET(subtract);
- GET(multiply);
- GET(divide);
- GET(remainder);
- GET(power);
- GET(square);
- GET(reciprocal);
- GET(ones_like);
- GET(sqrt);
- GET(negative);
- GET(absolute);
- GET(invert);
- GET(left_shift);
- GET(right_shift);
- GET(bitwise_and);
- GET(bitwise_or);
- GET(bitwise_xor);
- GET(less);
- GET(less_equal);
- GET(equal);
- GET(not_equal);
- GET(greater);
- GET(greater_equal);
- GET(floor_divide);
- GET(true_divide);
- GET(logical_or);
- GET(logical_and);
- GET(floor);
- GET(ceil);
- GET(maximum);
- GET(minimum);
- GET(rint);
- GET(conjugate);
- return dict;
+ PyObject *dict;
+ if ((dict = PyDict_New())==NULL)
+ return NULL;
+ GET(add);
+ GET(subtract);
+ GET(multiply);
+ GET(divide);
+ GET(remainder);
+ GET(power);
+ GET(square);
+ GET(reciprocal);
+ GET(ones_like);
+ GET(sqrt);
+ GET(negative);
+ GET(absolute);
+ GET(invert);
+ GET(left_shift);
+ GET(right_shift);
+ GET(bitwise_and);
+ GET(bitwise_or);
+ GET(bitwise_xor);
+ GET(less);
+ GET(less_equal);
+ GET(equal);
+ GET(not_equal);
+ GET(greater);
+ GET(greater_equal);
+ GET(floor_divide);
+ GET(true_divide);
+ GET(logical_or);
+ GET(logical_and);
+ GET(floor);
+ GET(ceil);
+ GET(maximum);
+ GET(minimum);
+ GET(rint);
+ GET(conjugate);
+ return dict;
fail:
- Py_DECREF(dict);
- return NULL;
+ Py_DECREF(dict);
+ return NULL;
}
static PyObject *
_get_keywords(int rtype, PyArrayObject *out)
{
- PyObject *kwds=NULL;
- if (rtype != PyArray_NOTYPE || out != NULL) {
- kwds = PyDict_New();
- if (rtype != PyArray_NOTYPE) {
- PyArray_Descr *descr;
- descr = PyArray_DescrFromType(rtype);
- if (descr) {
- PyDict_SetItemString(kwds, "dtype",
- (PyObject *)descr);
- Py_DECREF(descr);
- }
- }
- if (out != NULL) {
- PyDict_SetItemString(kwds, "out",
- (PyObject *)out);
- }
+ PyObject *kwds=NULL;
+ if (rtype != PyArray_NOTYPE || out != NULL) {
+ kwds = PyDict_New();
+ if (rtype != PyArray_NOTYPE) {
+ PyArray_Descr *descr;
+ descr = PyArray_DescrFromType(rtype);
+ if (descr) {
+ PyDict_SetItemString(kwds, "dtype",
+ (PyObject *)descr);
+ Py_DECREF(descr);
+ }
+ }
+ if (out != NULL) {
+ PyDict_SetItemString(kwds, "out",
+ (PyObject *)out);
}
- return kwds;
+ }
+ return kwds;
}
static PyObject *
PyArray_GenericReduceFunction(PyArrayObject *m1, PyObject *op, int axis,
int rtype, PyArrayObject *out)
{
- PyObject *args, *ret=NULL, *meth;
- PyObject *kwds;
- if (op == NULL) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- args = Py_BuildValue("(Oi)", m1, axis);
- kwds = _get_keywords(rtype, out);
- meth = PyObject_GetAttrString(op, "reduce");
- if (meth && PyCallable_Check(meth)) {
- ret = PyObject_Call(meth, args, kwds);
- }
- Py_DECREF(args);
- Py_DECREF(meth);
- Py_XDECREF(kwds);
- return ret;
+ PyObject *args, *ret=NULL, *meth;
+ PyObject *kwds;
+ if (op == NULL) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ args = Py_BuildValue("(Oi)", m1, axis);
+ kwds = _get_keywords(rtype, out);
+ meth = PyObject_GetAttrString(op, "reduce");
+ if (meth && PyCallable_Check(meth)) {
+ ret = PyObject_Call(meth, args, kwds);
+ }
+ Py_DECREF(args);
+ Py_DECREF(meth);
+ Py_XDECREF(kwds);
+ return ret;
}
@@ -3374,94 +3373,94 @@ static PyObject *
PyArray_GenericAccumulateFunction(PyArrayObject *m1, PyObject *op, int axis,
int rtype, PyArrayObject *out)
{
- PyObject *args, *ret=NULL, *meth;
- PyObject *kwds;
- if (op == NULL) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- args = Py_BuildValue("(Oi)", m1, axis);
- kwds = _get_keywords(rtype, out);
- meth = PyObject_GetAttrString(op, "accumulate");
- if (meth && PyCallable_Check(meth)) {
- ret = PyObject_Call(meth, args, kwds);
- }
- Py_DECREF(args);
- Py_DECREF(meth);
- Py_XDECREF(kwds);
- return ret;
+ PyObject *args, *ret=NULL, *meth;
+ PyObject *kwds;
+ if (op == NULL) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ args = Py_BuildValue("(Oi)", m1, axis);
+ kwds = _get_keywords(rtype, out);
+ meth = PyObject_GetAttrString(op, "accumulate");
+ if (meth && PyCallable_Check(meth)) {
+ ret = PyObject_Call(meth, args, kwds);
+ }
+ Py_DECREF(args);
+ Py_DECREF(meth);
+ Py_XDECREF(kwds);
+ return ret;
}
static PyObject *
PyArray_GenericBinaryFunction(PyArrayObject *m1, PyObject *m2, PyObject *op)
{
- if (op == NULL) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return PyObject_CallFunction(op, "OO", m1, m2);
+ if (op == NULL) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return PyObject_CallFunction(op, "OO", m1, m2);
}
static PyObject *
PyArray_GenericUnaryFunction(PyArrayObject *m1, PyObject *op)
{
- if (op == NULL) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return PyObject_CallFunction(op, "(O)", m1);
+ if (op == NULL) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return PyObject_CallFunction(op, "(O)", m1);
}
static PyObject *
PyArray_GenericInplaceBinaryFunction(PyArrayObject *m1,
PyObject *m2, PyObject *op)
{
- if (op == NULL) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return PyObject_CallFunction(op, "OOO", m1, m2, m1);
+ if (op == NULL) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return PyObject_CallFunction(op, "OOO", m1, m2, m1);
}
static PyObject *
PyArray_GenericInplaceUnaryFunction(PyArrayObject *m1, PyObject *op)
{
- if (op == NULL) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return PyObject_CallFunction(op, "OO", m1, m1);
+ if (op == NULL) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return PyObject_CallFunction(op, "OO", m1, m1);
}
static PyObject *
array_add(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.add);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.add);
}
static PyObject *
array_subtract(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.subtract);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.subtract);
}
static PyObject *
array_multiply(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.multiply);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.multiply);
}
static PyObject *
array_divide(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.divide);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.divide);
}
static PyObject *
array_remainder(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.remainder);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.remainder);
}
static int
@@ -3471,41 +3470,41 @@ array_power_is_scalar(PyObject *o2, double* exp)
const int optimize_fpexps = 1;
if (PyInt_Check(o2)) {
- *exp = (double)PyInt_AsLong(o2);
- return 1;
+ *exp = (double)PyInt_AsLong(o2);
+ return 1;
}
if (optimize_fpexps && PyFloat_Check(o2)) {
- *exp = PyFloat_AsDouble(o2);
- return 1;
+ *exp = PyFloat_AsDouble(o2);
+ return 1;
}
if ((PyArray_IsZeroDim(o2) &&
((PyArray_ISINTEGER(o2) ||
(optimize_fpexps && PyArray_ISFLOAT(o2))))) ||
PyArray_IsScalar(o2, Integer) ||
(optimize_fpexps && PyArray_IsScalar(o2, Floating))) {
- temp = o2->ob_type->tp_as_number->nb_float(o2);
- if (temp != NULL) {
- *exp = PyFloat_AsDouble(o2);
- Py_DECREF(temp);
- return 1;
- }
+ temp = o2->ob_type->tp_as_number->nb_float(o2);
+ if (temp != NULL) {
+ *exp = PyFloat_AsDouble(o2);
+ Py_DECREF(temp);
+ return 1;
+ }
}
#if (PY_VERSION_HEX >= 0x02050000)
if (PyIndex_Check(o2)) {
- PyObject* value = PyNumber_Index(o2);
- Py_ssize_t val;
- if (value==NULL) {
- if (PyErr_Occurred())
- PyErr_Clear();
- return 0;
- }
- val = PyInt_AsSsize_t(value);
- if (val == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- return 0;
- }
- *exp = (double) val;
- return 1;
+ PyObject* value = PyNumber_Index(o2);
+ Py_ssize_t val;
+ if (value==NULL) {
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ return 0;
+ }
+ val = PyInt_AsSsize_t(value);
+ if (val == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ return 0;
+ }
+ *exp = (double) val;
+ return 1;
}
#endif
return 0;
@@ -3514,145 +3513,145 @@ array_power_is_scalar(PyObject *o2, double* exp)
/* optimize float array or complex array to a scalar power */
static PyObject *
fast_scalar_power(PyArrayObject *a1, PyObject *o2, int inplace) {
- double exp;
- if (PyArray_Check(a1) && array_power_is_scalar(o2, &exp)) {
- PyObject *fastop = NULL;
- if (PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1)) {
- if (exp == 1.0) {
- /* we have to do this one special, as the
- "copy" method of array objects isn't set
- up early enough to be added
- by PyArray_SetNumericOps.
- */
- if (inplace) {
- Py_INCREF(a1);
- return (PyObject *)a1;
- } else {
- return PyArray_Copy(a1);
- }
- } else if (exp == -1.0) {
- fastop = n_ops.reciprocal;
- } else if (exp == 0.0) {
- fastop = n_ops.ones_like;
- } else if (exp == 0.5) {
- fastop = n_ops.sqrt;
- } else if (exp == 2.0) {
- fastop = n_ops.square;
- } else {
- return NULL;
- }
- if (inplace) {
- return PyArray_GenericInplaceUnaryFunction(a1,
- fastop);
- } else {
- return PyArray_GenericUnaryFunction(a1,
- fastop);
- }
- }
- else if (exp==2.0) {
- fastop = n_ops.multiply;
- if (inplace) {
- return PyArray_GenericInplaceBinaryFunction \
- (a1, (PyObject *)a1, fastop);
- }
- else {
- return PyArray_GenericBinaryFunction \
- (a1, (PyObject *)a1, fastop);
- }
- }
+ double exp;
+ if (PyArray_Check(a1) && array_power_is_scalar(o2, &exp)) {
+ PyObject *fastop = NULL;
+ if (PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1)) {
+ if (exp == 1.0) {
+ /* we have to do this one special, as the
+ "copy" method of array objects isn't set
+ up early enough to be added
+ by PyArray_SetNumericOps.
+ */
+ if (inplace) {
+ Py_INCREF(a1);
+ return (PyObject *)a1;
+ } else {
+ return PyArray_Copy(a1);
+ }
+ } else if (exp == -1.0) {
+ fastop = n_ops.reciprocal;
+ } else if (exp == 0.0) {
+ fastop = n_ops.ones_like;
+ } else if (exp == 0.5) {
+ fastop = n_ops.sqrt;
+ } else if (exp == 2.0) {
+ fastop = n_ops.square;
+ } else {
+ return NULL;
+ }
+ if (inplace) {
+ return PyArray_GenericInplaceUnaryFunction(a1,
+ fastop);
+ } else {
+ return PyArray_GenericUnaryFunction(a1,
+ fastop);
+ }
}
- return NULL;
+ else if (exp==2.0) {
+ fastop = n_ops.multiply;
+ if (inplace) {
+ return PyArray_GenericInplaceBinaryFunction \
+ (a1, (PyObject *)a1, fastop);
+ }
+ else {
+ return PyArray_GenericBinaryFunction \
+ (a1, (PyObject *)a1, fastop);
+ }
+ }
+ }
+ return NULL;
}
static PyObject *
array_power(PyArrayObject *a1, PyObject *o2, PyObject *modulo)
{
- /* modulo is ignored! */
- PyObject *value;
- value = fast_scalar_power(a1, o2, 0);
- if (!value) {
- value = PyArray_GenericBinaryFunction(a1, o2, n_ops.power);
- }
- return value;
+ /* modulo is ignored! */
+ PyObject *value;
+ value = fast_scalar_power(a1, o2, 0);
+ if (!value) {
+ value = PyArray_GenericBinaryFunction(a1, o2, n_ops.power);
+ }
+ return value;
}
static PyObject *
array_negative(PyArrayObject *m1)
{
- return PyArray_GenericUnaryFunction(m1, n_ops.negative);
+ return PyArray_GenericUnaryFunction(m1, n_ops.negative);
}
static PyObject *
array_absolute(PyArrayObject *m1)
{
- return PyArray_GenericUnaryFunction(m1, n_ops.absolute);
+ return PyArray_GenericUnaryFunction(m1, n_ops.absolute);
}
static PyObject *
array_invert(PyArrayObject *m1)
{
- return PyArray_GenericUnaryFunction(m1, n_ops.invert);
+ return PyArray_GenericUnaryFunction(m1, n_ops.invert);
}
static PyObject *
array_left_shift(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.left_shift);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.left_shift);
}
static PyObject *
array_right_shift(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.right_shift);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.right_shift);
}
static PyObject *
array_bitwise_and(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_and);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_and);
}
static PyObject *
array_bitwise_or(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_or);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_or);
}
static PyObject *
array_bitwise_xor(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_xor);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_xor);
}
static PyObject *
array_inplace_add(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.add);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.add);
}
static PyObject *
array_inplace_subtract(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.subtract);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.subtract);
}
static PyObject *
array_inplace_multiply(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.multiply);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.multiply);
}
static PyObject *
array_inplace_divide(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.divide);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.divide);
}
static PyObject *
array_inplace_remainder(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.remainder);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.remainder);
}
static PyObject *
@@ -3670,99 +3669,99 @@ array_inplace_power(PyArrayObject *a1, PyObject *o2, PyObject *modulo)
static PyObject *
array_inplace_left_shift(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.left_shift);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.left_shift);
}
static PyObject *
array_inplace_right_shift(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.right_shift);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.right_shift);
}
static PyObject *
array_inplace_bitwise_and(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_and);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_and);
}
static PyObject *
array_inplace_bitwise_or(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_or);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_or);
}
static PyObject *
array_inplace_bitwise_xor(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_xor);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.bitwise_xor);
}
static PyObject *
array_floor_divide(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.floor_divide);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.floor_divide);
}
static PyObject *
array_true_divide(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericBinaryFunction(m1, m2, n_ops.true_divide);
+ return PyArray_GenericBinaryFunction(m1, m2, n_ops.true_divide);
}
static PyObject *
array_inplace_floor_divide(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2,
- n_ops.floor_divide);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2,
+ n_ops.floor_divide);
}
static PyObject *
array_inplace_true_divide(PyArrayObject *m1, PyObject *m2)
{
- return PyArray_GenericInplaceBinaryFunction(m1, m2,
- n_ops.true_divide);
+ return PyArray_GenericInplaceBinaryFunction(m1, m2,
+ n_ops.true_divide);
}
/* Array evaluates as "TRUE" if any of the elements are non-zero*/
static int
array_any_nonzero(PyArrayObject *mp)
{
- intp index;
- PyArrayIterObject *it;
- Bool anyTRUE = FALSE;
+ intp index;
+ PyArrayIterObject *it;
+ Bool anyTRUE = FALSE;
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
- if (it==NULL) return anyTRUE;
- index = it->size;
- while(index--) {
- if (mp->descr->f->nonzero(it->dataptr, mp)) {
- anyTRUE = TRUE;
- break;
- }
- PyArray_ITER_NEXT(it);
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
+ if (it==NULL) return anyTRUE;
+ index = it->size;
+ while(index--) {
+ if (mp->descr->f->nonzero(it->dataptr, mp)) {
+ anyTRUE = TRUE;
+ break;
}
- Py_DECREF(it);
- return anyTRUE;
+ PyArray_ITER_NEXT(it);
+ }
+ Py_DECREF(it);
+ return anyTRUE;
}
static int
_array_nonzero(PyArrayObject *mp)
{
- intp n;
- n = PyArray_SIZE(mp);
- if (n == 1) {
- return mp->descr->f->nonzero(mp->data, mp);
- }
- else if (n == 0) {
- return 0;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "The truth value of an array " \
- "with more than one element is ambiguous. " \
- "Use a.any() or a.all()");
- return -1;
- }
+ intp n;
+ n = PyArray_SIZE(mp);
+ if (n == 1) {
+ return mp->descr->f->nonzero(mp->data, mp);
+ }
+ else if (n == 0) {
+ return 0;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "The truth value of an array " \
+ "with more than one element is ambiguous. " \
+ "Use a.any() or a.all()");
+ return -1;
+ }
}
@@ -3770,221 +3769,221 @@ _array_nonzero(PyArrayObject *mp)
static PyObject *
array_divmod(PyArrayObject *op1, PyObject *op2)
{
- PyObject *divp, *modp, *result;
+ PyObject *divp, *modp, *result;
- divp = array_floor_divide(op1, op2);
- if (divp == NULL) return NULL;
- modp = array_remainder(op1, op2);
- if (modp == NULL) {
- Py_DECREF(divp);
- return NULL;
- }
- result = Py_BuildValue("OO", divp, modp);
+ divp = array_floor_divide(op1, op2);
+ if (divp == NULL) return NULL;
+ modp = array_remainder(op1, op2);
+ if (modp == NULL) {
Py_DECREF(divp);
- Py_DECREF(modp);
- return result;
+ return NULL;
+ }
+ result = Py_BuildValue("OO", divp, modp);
+ Py_DECREF(divp);
+ Py_DECREF(modp);
+ return result;
}
static PyObject *
array_int(PyArrayObject *v)
{
- PyObject *pv, *pv2;
- if (PyArray_SIZE(v) != 1) {
- PyErr_SetString(PyExc_TypeError, "only length-1 arrays can be"\
- " converted to Python scalars");
- return NULL;
- }
- pv = v->descr->f->getitem(v->data, v);
- if (pv == NULL) return NULL;
- if (pv->ob_type->tp_as_number == 0) {
- PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
- "scalar object is not a number");
- Py_DECREF(pv);
- return NULL;
- }
- if (pv->ob_type->tp_as_number->nb_int == 0) {
- PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
- "scalar number to int");
- Py_DECREF(pv);
- return NULL;
- }
-
- pv2 = pv->ob_type->tp_as_number->nb_int(pv);
+ PyObject *pv, *pv2;
+ if (PyArray_SIZE(v) != 1) {
+ PyErr_SetString(PyExc_TypeError, "only length-1 arrays can be"\
+ " converted to Python scalars");
+ return NULL;
+ }
+ pv = v->descr->f->getitem(v->data, v);
+ if (pv == NULL) return NULL;
+ if (pv->ob_type->tp_as_number == 0) {
+ PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
+ "scalar object is not a number");
+ Py_DECREF(pv);
+ return NULL;
+ }
+ if (pv->ob_type->tp_as_number->nb_int == 0) {
+ PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
+ "scalar number to int");
Py_DECREF(pv);
- return pv2;
+ return NULL;
+ }
+
+ pv2 = pv->ob_type->tp_as_number->nb_int(pv);
+ Py_DECREF(pv);
+ return pv2;
}
static PyObject *
array_float(PyArrayObject *v)
{
- PyObject *pv, *pv2;
- if (PyArray_SIZE(v) != 1) {
- PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
- "be converted to Python scalars");
- return NULL;
- }
- pv = v->descr->f->getitem(v->data, v);
- if (pv == NULL) return NULL;
- if (pv->ob_type->tp_as_number == 0) {
- PyErr_SetString(PyExc_TypeError, "cannot convert to a "\
- "float; scalar object is not a number");
- Py_DECREF(pv);
- return NULL;
- }
- if (pv->ob_type->tp_as_number->nb_float == 0) {
- PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
- "scalar number to float");
- Py_DECREF(pv);
- return NULL;
- }
- pv2 = pv->ob_type->tp_as_number->nb_float(pv);
+ PyObject *pv, *pv2;
+ if (PyArray_SIZE(v) != 1) {
+ PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
+ "be converted to Python scalars");
+ return NULL;
+ }
+ pv = v->descr->f->getitem(v->data, v);
+ if (pv == NULL) return NULL;
+ if (pv->ob_type->tp_as_number == 0) {
+ PyErr_SetString(PyExc_TypeError, "cannot convert to a "\
+ "float; scalar object is not a number");
Py_DECREF(pv);
- return pv2;
+ return NULL;
+ }
+ if (pv->ob_type->tp_as_number->nb_float == 0) {
+ PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
+ "scalar number to float");
+ Py_DECREF(pv);
+ return NULL;
+ }
+ pv2 = pv->ob_type->tp_as_number->nb_float(pv);
+ Py_DECREF(pv);
+ return pv2;
}
static PyObject *
array_long(PyArrayObject *v)
{
- PyObject *pv, *pv2;
- if (PyArray_SIZE(v) != 1) {
- PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
- "be converted to Python scalars");
- return NULL;
- }
- pv = v->descr->f->getitem(v->data, v);
- if (pv->ob_type->tp_as_number == 0) {
- PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
- "scalar object is not a number");
- return NULL;
- }
- if (pv->ob_type->tp_as_number->nb_long == 0) {
- PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
- "scalar number to long");
- return NULL;
- }
- pv2 = pv->ob_type->tp_as_number->nb_long(pv);
- Py_DECREF(pv);
- return pv2;
+ PyObject *pv, *pv2;
+ if (PyArray_SIZE(v) != 1) {
+ PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
+ "be converted to Python scalars");
+ return NULL;
+ }
+ pv = v->descr->f->getitem(v->data, v);
+ if (pv->ob_type->tp_as_number == 0) {
+ PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
+ "scalar object is not a number");
+ return NULL;
+ }
+ if (pv->ob_type->tp_as_number->nb_long == 0) {
+ PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
+ "scalar number to long");
+ return NULL;
+ }
+ pv2 = pv->ob_type->tp_as_number->nb_long(pv);
+ Py_DECREF(pv);
+ return pv2;
}
static PyObject *
array_oct(PyArrayObject *v)
{
- PyObject *pv, *pv2;
- if (PyArray_SIZE(v) != 1) {
- PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
- "be converted to Python scalars");
- return NULL;
- }
- pv = v->descr->f->getitem(v->data, v);
- if (pv->ob_type->tp_as_number == 0) {
- PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
- "scalar object is not a number");
- return NULL;
- }
- if (pv->ob_type->tp_as_number->nb_oct == 0) {
- PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
- "scalar number to oct");
- return NULL;
- }
- pv2 = pv->ob_type->tp_as_number->nb_oct(pv);
- Py_DECREF(pv);
- return pv2;
+ PyObject *pv, *pv2;
+ if (PyArray_SIZE(v) != 1) {
+ PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
+ "be converted to Python scalars");
+ return NULL;
+ }
+ pv = v->descr->f->getitem(v->data, v);
+ if (pv->ob_type->tp_as_number == 0) {
+ PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
+ "scalar object is not a number");
+ return NULL;
+ }
+ if (pv->ob_type->tp_as_number->nb_oct == 0) {
+ PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
+ "scalar number to oct");
+ return NULL;
+ }
+ pv2 = pv->ob_type->tp_as_number->nb_oct(pv);
+ Py_DECREF(pv);
+ return pv2;
}
static PyObject *
array_hex(PyArrayObject *v)
{
- PyObject *pv, *pv2;
- if (PyArray_SIZE(v) != 1) {
- PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
- "be converted to Python scalars");
- return NULL;
- }
- pv = v->descr->f->getitem(v->data, v);
- if (pv->ob_type->tp_as_number == 0) {
- PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
- "scalar object is not a number");
- return NULL;
- }
- if (pv->ob_type->tp_as_number->nb_hex == 0) {
- PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
- "scalar number to hex");
- return NULL;
- }
- pv2 = pv->ob_type->tp_as_number->nb_hex(pv);
- Py_DECREF(pv);
- return pv2;
+ PyObject *pv, *pv2;
+ if (PyArray_SIZE(v) != 1) {
+ PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
+ "be converted to Python scalars");
+ return NULL;
+ }
+ pv = v->descr->f->getitem(v->data, v);
+ if (pv->ob_type->tp_as_number == 0) {
+ PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
+ "scalar object is not a number");
+ return NULL;
+ }
+ if (pv->ob_type->tp_as_number->nb_hex == 0) {
+ PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
+ "scalar number to hex");
+ return NULL;
+ }
+ pv2 = pv->ob_type->tp_as_number->nb_hex(pv);
+ Py_DECREF(pv);
+ return pv2;
}
static PyObject *
_array_copy_nice(PyArrayObject *self)
{
- return PyArray_Return((PyArrayObject *) \
- PyArray_Copy(self));
+ return PyArray_Return((PyArrayObject *) \
+ PyArray_Copy(self));
}
#if PY_VERSION_HEX >= 0x02050000
static PyObject *
array_index(PyArrayObject *v)
{
- if (!PyArray_ISINTEGER(v) || PyArray_SIZE(v) != 1) {
- PyErr_SetString(PyExc_TypeError, "only integer arrays with " \
- "one element can be converted to an index");
- return NULL;
- }
- return v->descr->f->getitem(v->data, v);
+ if (!PyArray_ISINTEGER(v) || PyArray_SIZE(v) != 1) {
+ PyErr_SetString(PyExc_TypeError, "only integer arrays with " \
+ "one element can be converted to an index");
+ return NULL;
+ }
+ return v->descr->f->getitem(v->data, v);
}
#endif
static PyNumberMethods array_as_number = {
- (binaryfunc)array_add, /*nb_add*/
- (binaryfunc)array_subtract, /*nb_subtract*/
- (binaryfunc)array_multiply, /*nb_multiply*/
- (binaryfunc)array_divide, /*nb_divide*/
- (binaryfunc)array_remainder, /*nb_remainder*/
- (binaryfunc)array_divmod, /*nb_divmod*/
- (ternaryfunc)array_power, /*nb_power*/
- (unaryfunc)array_negative, /*nb_neg*/
- (unaryfunc)_array_copy_nice, /*nb_pos*/
- (unaryfunc)array_absolute, /*(unaryfunc)array_abs,*/
- (inquiry)_array_nonzero, /*nb_nonzero*/
- (unaryfunc)array_invert, /*nb_invert*/
- (binaryfunc)array_left_shift, /*nb_lshift*/
- (binaryfunc)array_right_shift, /*nb_rshift*/
- (binaryfunc)array_bitwise_and, /*nb_and*/
- (binaryfunc)array_bitwise_xor, /*nb_xor*/
- (binaryfunc)array_bitwise_or, /*nb_or*/
- 0, /*nb_coerce*/
- (unaryfunc)array_int, /*nb_int*/
- (unaryfunc)array_long, /*nb_long*/
- (unaryfunc)array_float, /*nb_float*/
- (unaryfunc)array_oct, /*nb_oct*/
- (unaryfunc)array_hex, /*nb_hex*/
-
- /*This code adds augmented assignment functionality*/
- /*that was made available in Python 2.0*/
- (binaryfunc)array_inplace_add, /*inplace_add*/
- (binaryfunc)array_inplace_subtract, /*inplace_subtract*/
- (binaryfunc)array_inplace_multiply, /*inplace_multiply*/
- (binaryfunc)array_inplace_divide, /*inplace_divide*/
- (binaryfunc)array_inplace_remainder, /*inplace_remainder*/
- (ternaryfunc)array_inplace_power, /*inplace_power*/
- (binaryfunc)array_inplace_left_shift, /*inplace_lshift*/
- (binaryfunc)array_inplace_right_shift, /*inplace_rshift*/
- (binaryfunc)array_inplace_bitwise_and, /*inplace_and*/
- (binaryfunc)array_inplace_bitwise_xor, /*inplace_xor*/
- (binaryfunc)array_inplace_bitwise_or, /*inplace_or*/
-
- (binaryfunc)array_floor_divide, /*nb_floor_divide*/
- (binaryfunc)array_true_divide, /*nb_true_divide*/
- (binaryfunc)array_inplace_floor_divide, /*nb_inplace_floor_divide*/
- (binaryfunc)array_inplace_true_divide, /*nb_inplace_true_divide*/
+ (binaryfunc)array_add, /*nb_add*/
+ (binaryfunc)array_subtract, /*nb_subtract*/
+ (binaryfunc)array_multiply, /*nb_multiply*/
+ (binaryfunc)array_divide, /*nb_divide*/
+ (binaryfunc)array_remainder, /*nb_remainder*/
+ (binaryfunc)array_divmod, /*nb_divmod*/
+ (ternaryfunc)array_power, /*nb_power*/
+ (unaryfunc)array_negative, /*nb_neg*/
+ (unaryfunc)_array_copy_nice, /*nb_pos*/
+ (unaryfunc)array_absolute, /*(unaryfunc)array_abs,*/
+ (inquiry)_array_nonzero, /*nb_nonzero*/
+ (unaryfunc)array_invert, /*nb_invert*/
+ (binaryfunc)array_left_shift, /*nb_lshift*/
+ (binaryfunc)array_right_shift, /*nb_rshift*/
+ (binaryfunc)array_bitwise_and, /*nb_and*/
+ (binaryfunc)array_bitwise_xor, /*nb_xor*/
+ (binaryfunc)array_bitwise_or, /*nb_or*/
+ 0, /*nb_coerce*/
+ (unaryfunc)array_int, /*nb_int*/
+ (unaryfunc)array_long, /*nb_long*/
+ (unaryfunc)array_float, /*nb_float*/
+ (unaryfunc)array_oct, /*nb_oct*/
+ (unaryfunc)array_hex, /*nb_hex*/
+
+ /*This code adds augmented assignment functionality*/
+ /*that was made available in Python 2.0*/
+ (binaryfunc)array_inplace_add, /*inplace_add*/
+ (binaryfunc)array_inplace_subtract, /*inplace_subtract*/
+ (binaryfunc)array_inplace_multiply, /*inplace_multiply*/
+ (binaryfunc)array_inplace_divide, /*inplace_divide*/
+ (binaryfunc)array_inplace_remainder, /*inplace_remainder*/
+ (ternaryfunc)array_inplace_power, /*inplace_power*/
+ (binaryfunc)array_inplace_left_shift, /*inplace_lshift*/
+ (binaryfunc)array_inplace_right_shift, /*inplace_rshift*/
+ (binaryfunc)array_inplace_bitwise_and, /*inplace_and*/
+ (binaryfunc)array_inplace_bitwise_xor, /*inplace_xor*/
+ (binaryfunc)array_inplace_bitwise_or, /*inplace_or*/
+
+ (binaryfunc)array_floor_divide, /*nb_floor_divide*/
+ (binaryfunc)array_true_divide, /*nb_true_divide*/
+ (binaryfunc)array_inplace_floor_divide, /*nb_inplace_floor_divide*/
+ (binaryfunc)array_inplace_true_divide, /*nb_inplace_true_divide*/
#if PY_VERSION_HEX >= 0x02050000
- (unaryfunc)array_index, /* nb_index */
+ (unaryfunc)array_index, /* nb_index */
#endif
};
@@ -4005,108 +4004,108 @@ static PyObject *
array_slice(PyArrayObject *self, Py_ssize_t ilow,
Py_ssize_t ihigh)
{
- PyArrayObject *r;
- Py_ssize_t l;
- char *data;
+ PyArrayObject *r;
+ Py_ssize_t l;
+ char *data;
- if (self->nd == 0) {
- PyErr_SetString(PyExc_ValueError, "cannot slice a 0-d array");
- return NULL;
- }
+ if (self->nd == 0) {
+ PyErr_SetString(PyExc_ValueError, "cannot slice a 0-d array");
+ return NULL;
+ }
- l=self->dimensions[0];
- if (ilow < 0) ilow = 0;
- else if (ilow > l) ilow = l;
- if (ihigh < ilow) ihigh = ilow;
- else if (ihigh > l) ihigh = l;
+ l=self->dimensions[0];
+ if (ilow < 0) ilow = 0;
+ else if (ilow > l) ilow = l;
+ if (ihigh < ilow) ihigh = ilow;
+ else if (ihigh > l) ihigh = l;
+
+ if (ihigh != ilow) {
+ data = index2ptr(self, ilow);
+ if (data == NULL) return NULL;
+ } else {
+ data = self->data;
+ }
- if (ihigh != ilow) {
- data = index2ptr(self, ilow);
- if (data == NULL) return NULL;
- } else {
- data = self->data;
- }
-
- self->dimensions[0] = ihigh-ilow;
- Py_INCREF(self->descr);
- r = (PyArrayObject *) \
- PyArray_NewFromDescr(self->ob_type, self->descr,
- self->nd, self->dimensions,
- self->strides, data,
- self->flags, (PyObject *)self);
- self->dimensions[0] = l;
- if (r == NULL) return NULL;
- r->base = (PyObject *)self;
- Py_INCREF(self);
- PyArray_UpdateFlags(r, UPDATE_ALL);
- return (PyObject *)r;
+ self->dimensions[0] = ihigh-ilow;
+ Py_INCREF(self->descr);
+ r = (PyArrayObject *) \
+ PyArray_NewFromDescr(self->ob_type, self->descr,
+ self->nd, self->dimensions,
+ self->strides, data,
+ self->flags, (PyObject *)self);
+ self->dimensions[0] = l;
+ if (r == NULL) return NULL;
+ r->base = (PyObject *)self;
+ Py_INCREF(self);
+ PyArray_UpdateFlags(r, UPDATE_ALL);
+ return (PyObject *)r;
}
static int
array_ass_slice(PyArrayObject *self, Py_ssize_t ilow,
Py_ssize_t ihigh, PyObject *v) {
- int ret;
- PyArrayObject *tmp;
+ int ret;
+ PyArrayObject *tmp;
- if (v == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "cannot delete array elements");
- return -1;
- }
- if (!PyArray_ISWRITEABLE(self)) {
- PyErr_SetString(PyExc_RuntimeError,
- "array is not writeable");
- return -1;
- }
- if ((tmp = (PyArrayObject *)array_slice(self, ilow, ihigh)) \
- == NULL)
- return -1;
- ret = PyArray_CopyObject(tmp, v);
- Py_DECREF(tmp);
+ if (v == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot delete array elements");
+ return -1;
+ }
+ if (!PyArray_ISWRITEABLE(self)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "array is not writeable");
+ return -1;
+ }
+ if ((tmp = (PyArrayObject *)array_slice(self, ilow, ihigh)) \
+ == NULL)
+ return -1;
+ ret = PyArray_CopyObject(tmp, v);
+ Py_DECREF(tmp);
- return ret;
+ return ret;
}
static int
array_contains(PyArrayObject *self, PyObject *el)
{
- /* equivalent to (self == el).any() */
+ /* equivalent to (self == el).any() */
- PyObject *res;
- int ret;
+ PyObject *res;
+ int ret;
- res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self,
- el, Py_EQ));
- if (res == NULL) return -1;
- ret = array_any_nonzero((PyArrayObject *)res);
- Py_DECREF(res);
- return ret;
+ res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self,
+ el, Py_EQ));
+ if (res == NULL) return -1;
+ ret = array_any_nonzero((PyArrayObject *)res);
+ Py_DECREF(res);
+ return ret;
}
static PySequenceMethods array_as_sequence = {
#if PY_VERSION_HEX >= 0x02050000
- (lenfunc)array_length, /*sq_length*/
- (binaryfunc)NULL, /* sq_concat is handled by nb_add*/
- (ssizeargfunc)NULL,
- (ssizeargfunc)array_item_nice,
- (ssizessizeargfunc)array_slice,
- (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
- (ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/
- (objobjproc) array_contains, /* sq_contains */
- (binaryfunc) NULL, /* sg_inplace_concat */
- (ssizeargfunc)NULL,
+ (lenfunc)array_length, /*sq_length*/
+ (binaryfunc)NULL, /* sq_concat is handled by nb_add*/
+ (ssizeargfunc)NULL,
+ (ssizeargfunc)array_item_nice,
+ (ssizessizeargfunc)array_slice,
+ (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
+ (ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/
+ (objobjproc) array_contains, /* sq_contains */
+ (binaryfunc) NULL, /* sg_inplace_concat */
+ (ssizeargfunc)NULL,
#else
- (inquiry)array_length, /*sq_length*/
- (binaryfunc)NULL, /* sq_concat is handled by nb_add*/
- (intargfunc)NULL, /* sq_repeat is handled nb_multiply*/
- (intargfunc)array_item_nice, /*sq_item*/
- (intintargfunc)array_slice, /*sq_slice*/
- (intobjargproc)array_ass_item, /*sq_ass_item*/
- (intintobjargproc)array_ass_slice, /*sq_ass_slice*/
- (objobjproc) array_contains, /* sq_contains */
- (binaryfunc) NULL, /* sg_inplace_concat */
- (intargfunc) NULL /* sg_inplace_repeat */
+ (inquiry)array_length, /*sq_length*/
+ (binaryfunc)NULL, /* sq_concat is handled by nb_add*/
+ (intargfunc)NULL, /* sq_repeat is handled nb_multiply*/
+ (intargfunc)array_item_nice, /*sq_item*/
+ (intintargfunc)array_slice, /*sq_slice*/
+ (intobjargproc)array_ass_item, /*sq_ass_item*/
+ (intintobjargproc)array_ass_slice, /*sq_ass_slice*/
+ (objobjproc) array_contains, /* sq_contains */
+ (binaryfunc) NULL, /* sg_inplace_concat */
+ (intargfunc) NULL /* sg_inplace_repeat */
#endif
};
@@ -4118,48 +4117,48 @@ static int
dump_data(char **string, int *n, int *max_n, char *data, int nd,
intp *dimensions, intp *strides, PyArrayObject* self)
{
- PyArray_Descr *descr=self->descr;
- PyObject *op, *sp;
- char *ostring;
- int i, N;
-
-#define CHECK_MEMORY if (*n >= *max_n-16) { *max_n *= 2; \
- *string = (char *)_pya_realloc(*string, *max_n); }
-
- if (nd == 0) {
-
- if ((op = descr->f->getitem(data, self)) == NULL) return -1;
- sp = PyObject_Repr(op);
- if (sp == NULL) {Py_DECREF(op); return -1;}
- ostring = PyString_AsString(sp);
- N = PyString_Size(sp)*sizeof(char);
- *n += N;
- CHECK_MEMORY
- memmove(*string+(*n-N), ostring, N);
- Py_DECREF(sp);
- Py_DECREF(op);
- return 0;
- } else {
- CHECK_MEMORY
- (*string)[*n] = '[';
- *n += 1;
- for(i=0; i<dimensions[0]; i++) {
- if (dump_data(string, n, max_n,
- data+(*strides)*i,
- nd-1, dimensions+1,
- strides+1, self) < 0)
- return -1;
- CHECK_MEMORY
- if (i<dimensions[0]-1) {
- (*string)[*n] = ',';
- (*string)[*n+1] = ' ';
- *n += 2;
- }
+ PyArray_Descr *descr=self->descr;
+ PyObject *op, *sp;
+ char *ostring;
+ int i, N;
+
+#define CHECK_MEMORY if (*n >= *max_n-16) { *max_n *= 2; \
+ *string = (char *)_pya_realloc(*string, *max_n); }
+
+ if (nd == 0) {
+
+ if ((op = descr->f->getitem(data, self)) == NULL) return -1;
+ sp = PyObject_Repr(op);
+ if (sp == NULL) {Py_DECREF(op); return -1;}
+ ostring = PyString_AsString(sp);
+ N = PyString_Size(sp)*sizeof(char);
+ *n += N;
+ CHECK_MEMORY
+ memmove(*string+(*n-N), ostring, N);
+ Py_DECREF(sp);
+ Py_DECREF(op);
+ return 0;
+ } else {
+ CHECK_MEMORY
+ (*string)[*n] = '[';
+ *n += 1;
+ for(i=0; i<dimensions[0]; i++) {
+ if (dump_data(string, n, max_n,
+ data+(*strides)*i,
+ nd-1, dimensions+1,
+ strides+1, self) < 0)
+ return -1;
+ CHECK_MEMORY
+ if (i<dimensions[0]-1) {
+ (*string)[*n] = ',';
+ (*string)[*n+1] = ' ';
+ *n += 2;
}
- CHECK_MEMORY
- (*string)[*n] = ']'; *n += 1;
- return 0;
}
+ CHECK_MEMORY
+ (*string)[*n] = ']'; *n += 1;
+ return 0;
+ }
#undef CHECK_MEMORY
}
@@ -4167,104 +4166,104 @@ dump_data(char **string, int *n, int *max_n, char *data, int nd,
static PyObject *
array_repr_builtin(PyArrayObject *self, int repr)
{
- PyObject *ret;
- char *string;
- int n, max_n;
+ PyObject *ret;
+ char *string;
+ int n, max_n;
- max_n = PyArray_NBYTES(self)*4*sizeof(char) + 7;
+ max_n = PyArray_NBYTES(self)*4*sizeof(char) + 7;
- if ((string = (char *)_pya_malloc(max_n)) == NULL) {
- PyErr_SetString(PyExc_MemoryError, "out of memory");
- return NULL;
- }
+ if ((string = (char *)_pya_malloc(max_n)) == NULL) {
+ PyErr_SetString(PyExc_MemoryError, "out of memory");
+ return NULL;
+ }
- if (repr) {
- n = 6;
- sprintf(string, "array(");
- }
- else {
- n = 0;
- }
- if (dump_data(&string, &n, &max_n, self->data,
- self->nd, self->dimensions,
- self->strides, self) < 0) {
- _pya_free(string); return NULL;
- }
+ if (repr) {
+ n = 6;
+ sprintf(string, "array(");
+ }
+ else {
+ n = 0;
+ }
+ if (dump_data(&string, &n, &max_n, self->data,
+ self->nd, self->dimensions,
+ self->strides, self) < 0) {
+ _pya_free(string); return NULL;
+ }
- if (repr) {
- if (PyArray_ISEXTENDED(self)) {
- char buf[100];
- snprintf(buf, sizeof(buf), "%d", self->descr->elsize);
- sprintf(string+n, ", '%c%s')", self->descr->type, buf);
- ret = PyString_FromStringAndSize(string, n+6+strlen(buf));
- }
- else {
- sprintf(string+n, ", '%c')", self->descr->type);
- ret = PyString_FromStringAndSize(string, n+6);
- }
+ if (repr) {
+ if (PyArray_ISEXTENDED(self)) {
+ char buf[100];
+ snprintf(buf, sizeof(buf), "%d", self->descr->elsize);
+ sprintf(string+n, ", '%c%s')", self->descr->type, buf);
+ ret = PyString_FromStringAndSize(string, n+6+strlen(buf));
}
else {
- ret = PyString_FromStringAndSize(string, n);
+ sprintf(string+n, ", '%c')", self->descr->type);
+ ret = PyString_FromStringAndSize(string, n+6);
}
+ }
+ else {
+ ret = PyString_FromStringAndSize(string, n);
+ }
- _pya_free(string);
- return ret;
+ _pya_free(string);
+ return ret;
}
static PyObject *PyArray_StrFunction=NULL;
static PyObject *PyArray_ReprFunction=NULL;
/*OBJECT_API
- Set the array print function to be a Python function.
+ Set the array print function to be a Python function.
*/
static void
PyArray_SetStringFunction(PyObject *op, int repr)
{
- if (repr) {
- /* Dispose of previous callback */
- Py_XDECREF(PyArray_ReprFunction);
- /* Add a reference to new callback */
- Py_XINCREF(op);
- /* Remember new callback */
- PyArray_ReprFunction = op;
- } else {
- /* Dispose of previous callback */
- Py_XDECREF(PyArray_StrFunction);
- /* Add a reference to new callback */
- Py_XINCREF(op);
- /* Remember new callback */
- PyArray_StrFunction = op;
- }
+ if (repr) {
+ /* Dispose of previous callback */
+ Py_XDECREF(PyArray_ReprFunction);
+ /* Add a reference to new callback */
+ Py_XINCREF(op);
+ /* Remember new callback */
+ PyArray_ReprFunction = op;
+ } else {
+ /* Dispose of previous callback */
+ Py_XDECREF(PyArray_StrFunction);
+ /* Add a reference to new callback */
+ Py_XINCREF(op);
+ /* Remember new callback */
+ PyArray_StrFunction = op;
+ }
}
static PyObject *
array_repr(PyArrayObject *self)
{
- PyObject *s, *arglist;
+ PyObject *s, *arglist;
- if (PyArray_ReprFunction == NULL) {
- s = array_repr_builtin(self, 1);
- } else {
- arglist = Py_BuildValue("(O)", self);
- s = PyEval_CallObject(PyArray_ReprFunction, arglist);
- Py_DECREF(arglist);
- }
- return s;
+ if (PyArray_ReprFunction == NULL) {
+ s = array_repr_builtin(self, 1);
+ } else {
+ arglist = Py_BuildValue("(O)", self);
+ s = PyEval_CallObject(PyArray_ReprFunction, arglist);
+ Py_DECREF(arglist);
+ }
+ return s;
}
static PyObject *
array_str(PyArrayObject *self)
{
- PyObject *s, *arglist;
+ PyObject *s, *arglist;
- if (PyArray_StrFunction == NULL) {
- s = array_repr_builtin(self, 0);
- } else {
- arglist = Py_BuildValue("(O)", self);
- s = PyEval_CallObject(PyArray_StrFunction, arglist);
- Py_DECREF(arglist);
- }
- return s;
+ if (PyArray_StrFunction == NULL) {
+ s = array_repr_builtin(self, 0);
+ } else {
+ arglist = Py_BuildValue("(O)", self);
+ s = PyEval_CallObject(PyArray_StrFunction, arglist);
+ Py_DECREF(arglist);
+ }
+ return s;
}
@@ -4274,15 +4273,15 @@ array_str(PyArrayObject *self)
static int
PyArray_CompareUCS4(npy_ucs4 *s1, npy_ucs4 *s2, register size_t len)
{
- register PyArray_UCS4 c1, c2;
- while(len-- > 0) {
- c1 = *s1++;
- c2 = *s2++;
- if (c1 != c2) {
- return (c1 < c2) ? -1 : 1;
- }
+ register PyArray_UCS4 c1, c2;
+ while(len-- > 0) {
+ c1 = *s1++;
+ c2 = *s2++;
+ if (c1 != c2) {
+ return (c1 < c2) ? -1 : 1;
}
- return 0;
+ }
+ return 0;
}
/* This also handles possibly mis-aligned data */
@@ -4294,36 +4293,36 @@ PyArray_CompareUCS4(npy_ucs4 *s1, npy_ucs4 *s2, register size_t len)
static int
_myunincmp(PyArray_UCS4 *s1, PyArray_UCS4 *s2, int len1, int len2)
{
- PyArray_UCS4 *sptr;
- PyArray_UCS4 *s1t=s1, *s2t=s2;
- int val;
- intp size;
- int diff;
+ PyArray_UCS4 *sptr;
+ PyArray_UCS4 *s1t=s1, *s2t=s2;
+ int val;
+ intp size;
+ int diff;
- if ((intp)s1 % sizeof(PyArray_UCS4) != 0) {
- size = len1*sizeof(PyArray_UCS4);
- s1t = malloc(size);
- memcpy(s1t, s1, size);
- }
- if ((intp)s2 % sizeof(PyArray_UCS4) != 0) {
- size = len2*sizeof(PyArray_UCS4);
- s2t = malloc(size);
- memcpy(s2t, s2, size);
- }
- val = PyArray_CompareUCS4(s1t, s2t, MIN(len1,len2));
- if ((val != 0) || (len1 == len2)) goto finish;
- if (len2 > len1) {sptr = s2t+len1; val = -1; diff=len2-len1;}
- else {sptr = s1t+len2; val = 1; diff=len1-len2;}
- while (diff--) {
- if (*sptr != 0) goto finish;
- sptr++;
- }
- val = 0;
+ if ((intp)s1 % sizeof(PyArray_UCS4) != 0) {
+ size = len1*sizeof(PyArray_UCS4);
+ s1t = malloc(size);
+ memcpy(s1t, s1, size);
+ }
+ if ((intp)s2 % sizeof(PyArray_UCS4) != 0) {
+ size = len2*sizeof(PyArray_UCS4);
+ s2t = malloc(size);
+ memcpy(s2t, s2, size);
+ }
+ val = PyArray_CompareUCS4(s1t, s2t, MIN(len1,len2));
+ if ((val != 0) || (len1 == len2)) goto finish;
+ if (len2 > len1) {sptr = s2t+len1; val = -1; diff=len2-len1;}
+ else {sptr = s1t+len2; val = 1; diff=len1-len2;}
+ while (diff--) {
+ if (*sptr != 0) goto finish;
+ sptr++;
+ }
+ val = 0;
finish:
- if (s1t != s1) free(s1t);
- if (s2t != s2) free(s2t);
- return val;
+ if (s1t != s1) free(s1t);
+ if (s2t != s2) free(s2t);
+ return val;
}
@@ -4337,19 +4336,19 @@ _myunincmp(PyArray_UCS4 *s1, PyArray_UCS4 *s2, int len1, int len2)
static int
_mystrncmp(char *s1, char *s2, int len1, int len2)
{
- char *sptr;
- int val;
- int diff;
-
- val = memcmp(s1, s2, MIN(len1, len2));
- if ((val != 0) || (len1 == len2)) return val;
- if (len2 > len1) {sptr = s2+len1; val = -1; diff=len2-len1;}
- else {sptr = s1+len2; val = 1; diff=len1-len2;}
- while (diff--) {
- if (*sptr != 0) return val;
- sptr++;
- }
- return 0; /* Only happens if NULLs are everywhere */
+ char *sptr;
+ int val;
+ int diff;
+
+ val = memcmp(s1, s2, MIN(len1, len2));
+ if ((val != 0) || (len1 == len2)) return val;
+ if (len2 > len1) {sptr = s2+len1; val = -1; diff=len2-len1;}
+ else {sptr = s1+len2; val = 1; diff=len1-len2;}
+ while (diff--) {
+ if (*sptr != 0) return val;
+ sptr++;
+ }
+ return 0; /* Only happens if NULLs are everywhere */
}
/* Borrowed from Numarray */
@@ -4363,27 +4362,27 @@ _mystrncmp(char *s1, char *s2, int len1, int len2)
static void _rstripw(char *s, int n)
{
- int i;
- for(i=n-1; i>=1; i--) /* Never strip to length 0. */
+ int i;
+ for(i=n-1; i>=1; i--) /* Never strip to length 0. */
{
- int c = s[i];
- if (!c || isspace(c))
- s[i] = 0;
- else
- break;
+ int c = s[i];
+ if (!c || isspace(c))
+ s[i] = 0;
+ else
+ break;
}
}
static void _unistripw(PyArray_UCS4 *s, int n)
{
- int i;
- for(i=n-1; i>=1; i--) /* Never strip to length 0. */
+ int i;
+ for(i=n-1; i>=1; i--) /* Never strip to length 0. */
{
- PyArray_UCS4 c = s[i];
- if (!c || isspace(c))
- s[i] = 0;
- else
- break;
+ PyArray_UCS4 c = s[i];
+ if (!c || isspace(c))
+ s[i] = 0;
+ else
+ break;
}
}
@@ -4391,143 +4390,143 @@ static void _unistripw(PyArray_UCS4 *s, int n)
static char *
_char_copy_n_strip(char *original, char *temp, int nc)
{
- if (nc > SMALL_STRING) {
- temp = malloc(nc);
- if (!temp) {
- PyErr_NoMemory();
- return NULL;
- }
+ if (nc > SMALL_STRING) {
+ temp = malloc(nc);
+ if (!temp) {
+ PyErr_NoMemory();
+ return NULL;
}
- memcpy(temp, original, nc);
- _rstripw(temp, nc);
- return temp;
+ }
+ memcpy(temp, original, nc);
+ _rstripw(temp, nc);
+ return temp;
}
static void
_char_release(char *ptr, int nc)
{
- if (nc > SMALL_STRING) {
- free(ptr);
- }
+ if (nc > SMALL_STRING) {
+ free(ptr);
+ }
}
static char *
_uni_copy_n_strip(char *original, char *temp, int nc)
{
- if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
- temp = malloc(nc*sizeof(PyArray_UCS4));
- if (!temp) {
- PyErr_NoMemory();
- return NULL;
- }
+ if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
+ temp = malloc(nc*sizeof(PyArray_UCS4));
+ if (!temp) {
+ PyErr_NoMemory();
+ return NULL;
}
- memcpy(temp, original, nc*sizeof(PyArray_UCS4));
- _unistripw((PyArray_UCS4 *)temp, nc);
- return temp;
+ }
+ memcpy(temp, original, nc*sizeof(PyArray_UCS4));
+ _unistripw((PyArray_UCS4 *)temp, nc);
+ return temp;
}
static void
_uni_release(char *ptr, int nc)
{
- if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
- free(ptr);
- }
+ if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
+ free(ptr);
+ }
}
/* End borrowed from numarray */
-#define _rstrip_loop(CMP) { \
- void *aptr, *bptr; \
- char atemp[SMALL_STRING], btemp[SMALL_STRING]; \
- while(size--) { \
- aptr = stripfunc(iself->dataptr, atemp, N1); \
- if (!aptr) return -1; \
- bptr = stripfunc(iother->dataptr, btemp, N2); \
- if (!bptr) { \
- relfunc(aptr, N1); \
- return -1; \
- } \
- val = cmpfunc(aptr, bptr, N1, N2); \
- *dptr = (val CMP 0); \
- PyArray_ITER_NEXT(iself); \
- PyArray_ITER_NEXT(iother); \
- dptr += 1; \
- relfunc(aptr, N1); \
- relfunc(bptr, N2); \
- } \
- }
-
-#define _reg_loop(CMP) { \
- while(size--) { \
- val = cmpfunc((void *)iself->dataptr, \
- (void *)iother->dataptr, \
- N1, N2); \
- *dptr = (val CMP 0); \
- PyArray_ITER_NEXT(iself); \
- PyArray_ITER_NEXT(iother); \
- dptr += 1; \
- } \
- }
-
-#define _loop(CMP) if (rstrip) _rstrip_loop(CMP) \
+#define _rstrip_loop(CMP) { \
+ void *aptr, *bptr; \
+ char atemp[SMALL_STRING], btemp[SMALL_STRING]; \
+ while(size--) { \
+ aptr = stripfunc(iself->dataptr, atemp, N1); \
+ if (!aptr) return -1; \
+ bptr = stripfunc(iother->dataptr, btemp, N2); \
+ if (!bptr) { \
+ relfunc(aptr, N1); \
+ return -1; \
+ } \
+ val = cmpfunc(aptr, bptr, N1, N2); \
+ *dptr = (val CMP 0); \
+ PyArray_ITER_NEXT(iself); \
+ PyArray_ITER_NEXT(iother); \
+ dptr += 1; \
+ relfunc(aptr, N1); \
+ relfunc(bptr, N2); \
+ } \
+ }
+
+#define _reg_loop(CMP) { \
+ while(size--) { \
+ val = cmpfunc((void *)iself->dataptr, \
+ (void *)iother->dataptr, \
+ N1, N2); \
+ *dptr = (val CMP 0); \
+ PyArray_ITER_NEXT(iself); \
+ PyArray_ITER_NEXT(iother); \
+ dptr += 1; \
+ } \
+ }
+
+#define _loop(CMP) if (rstrip) _rstrip_loop(CMP) \
else _reg_loop(CMP)
static int
_compare_strings(PyObject *result, PyArrayMultiIterObject *multi,
int cmp_op, void *func, int rstrip)
{
- PyArrayIterObject *iself, *iother;
- Bool *dptr;
- intp size;
- int val;
- int N1, N2;
- int (*cmpfunc)(void *, void *, int, int);
- void (*relfunc)(char *, int);
- char* (*stripfunc)(char *, char *, int);
-
- cmpfunc = func;
- dptr = (Bool *)PyArray_DATA(result);
- iself = multi->iters[0];
- iother = multi->iters[1];
- size = multi->size;
- N1 = iself->ao->descr->elsize;
- N2 = iother->ao->descr->elsize;
- if ((void *)cmpfunc == (void *)_myunincmp) {
- N1 >>= 2;
- N2 >>= 2;
- stripfunc = _uni_copy_n_strip;
- relfunc = _uni_release;
- }
- else {
- stripfunc = _char_copy_n_strip;
- relfunc = _char_release;
- }
- switch (cmp_op) {
- case Py_EQ:
- _loop(==)
- break;
- case Py_NE:
- _loop(!=)
- break;
- case Py_LT:
- _loop(<)
- break;
- case Py_LE:
- _loop(<=)
- break;
- case Py_GT:
- _loop(>)
- break;
- case Py_GE:
- _loop(>=)
- break;
- default:
- PyErr_SetString(PyExc_RuntimeError,
- "bad comparison operator");
- return -1;
- }
- return 0;
+ PyArrayIterObject *iself, *iother;
+ Bool *dptr;
+ intp size;
+ int val;
+ int N1, N2;
+ int (*cmpfunc)(void *, void *, int, int);
+ void (*relfunc)(char *, int);
+ char* (*stripfunc)(char *, char *, int);
+
+ cmpfunc = func;
+ dptr = (Bool *)PyArray_DATA(result);
+ iself = multi->iters[0];
+ iother = multi->iters[1];
+ size = multi->size;
+ N1 = iself->ao->descr->elsize;
+ N2 = iother->ao->descr->elsize;
+ if ((void *)cmpfunc == (void *)_myunincmp) {
+ N1 >>= 2;
+ N2 >>= 2;
+ stripfunc = _uni_copy_n_strip;
+ relfunc = _uni_release;
+ }
+ else {
+ stripfunc = _char_copy_n_strip;
+ relfunc = _char_release;
+ }
+ switch (cmp_op) {
+ case Py_EQ:
+ _loop(==)
+ break;
+ case Py_NE:
+ _loop(!=)
+ break;
+ case Py_LT:
+ _loop(<)
+ break;
+ case Py_LE:
+ _loop(<=)
+ break;
+ case Py_GT:
+ _loop(>)
+ break;
+ case Py_GE:
+ _loop(>=)
+ break;
+ default:
+ PyErr_SetString(PyExc_RuntimeError,
+ "bad comparison operator");
+ return -1;
+ }
+ return 0;
}
#undef _loop
@@ -4539,82 +4538,82 @@ static PyObject *
_strings_richcompare(PyArrayObject *self, PyArrayObject *other, int cmp_op,
int rstrip)
{
- PyObject *result;
- PyArrayMultiIterObject *mit;
- int val;
-
- /* Cast arrays to a common type */
- if (self->descr->type_num != other->descr->type_num) {
- PyObject *new;
- if (self->descr->type_num == PyArray_STRING && \
- other->descr->type_num == PyArray_UNICODE) {
- Py_INCREF(other);
- Py_INCREF(other->descr);
- new = PyArray_FromAny((PyObject *)self, other->descr,
- 0, 0, 0, NULL);
- if (new == NULL) return NULL;
- self = (PyArrayObject *)new;
- }
- else if (self->descr->type_num == PyArray_UNICODE && \
- other->descr->type_num == PyArray_STRING) {
- Py_INCREF(self);
- Py_INCREF(self->descr);
- new = PyArray_FromAny((PyObject *)other, self->descr,
- 0, 0, 0, NULL);
- if (new == NULL) return NULL;
- other = (PyArrayObject *)new;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "invalid string data-types "
- "in comparison");
- return NULL;
- }
- }
- else {
- Py_INCREF(self);
- Py_INCREF(other);
- }
+ PyObject *result;
+ PyArrayMultiIterObject *mit;
+ int val;
- /* Broad-cast the arrays to a common shape */
- mit = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, self, other);
- Py_DECREF(self);
- Py_DECREF(other);
- if (mit == NULL) return NULL;
-
- result = PyArray_NewFromDescr(&PyArray_Type,
- PyArray_DescrFromType(PyArray_BOOL),
- mit->nd,
- mit->dimensions,
- NULL, NULL, 0,
- NULL);
- if (result == NULL) goto finish;
-
- if (self->descr->type_num == PyArray_UNICODE) {
- val = _compare_strings(result, mit, cmp_op, _myunincmp,
- rstrip);
+ /* Cast arrays to a common type */
+ if (self->descr->type_num != other->descr->type_num) {
+ PyObject *new;
+ if (self->descr->type_num == PyArray_STRING && \
+ other->descr->type_num == PyArray_UNICODE) {
+ Py_INCREF(other);
+ Py_INCREF(other->descr);
+ new = PyArray_FromAny((PyObject *)self, other->descr,
+ 0, 0, 0, NULL);
+ if (new == NULL) return NULL;
+ self = (PyArrayObject *)new;
+ }
+ else if (self->descr->type_num == PyArray_UNICODE && \
+ other->descr->type_num == PyArray_STRING) {
+ Py_INCREF(self);
+ Py_INCREF(self->descr);
+ new = PyArray_FromAny((PyObject *)other, self->descr,
+ 0, 0, 0, NULL);
+ if (new == NULL) return NULL;
+ other = (PyArrayObject *)new;
}
else {
- val = _compare_strings(result, mit, cmp_op, _mystrncmp,
- rstrip);
+ PyErr_SetString(PyExc_TypeError,
+ "invalid string data-types "
+ "in comparison");
+ return NULL;
}
+ }
+ else {
+ Py_INCREF(self);
+ Py_INCREF(other);
+ }
+
+ /* Broad-cast the arrays to a common shape */
+ mit = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, self, other);
+ Py_DECREF(self);
+ Py_DECREF(other);
+ if (mit == NULL) return NULL;
+
+ result = PyArray_NewFromDescr(&PyArray_Type,
+ PyArray_DescrFromType(PyArray_BOOL),
+ mit->nd,
+ mit->dimensions,
+ NULL, NULL, 0,
+ NULL);
+ if (result == NULL) goto finish;
+
+ if (self->descr->type_num == PyArray_UNICODE) {
+ val = _compare_strings(result, mit, cmp_op, _myunincmp,
+ rstrip);
+ }
+ else {
+ val = _compare_strings(result, mit, cmp_op, _mystrncmp,
+ rstrip);
+ }
- if (val < 0) {Py_DECREF(result); result = NULL;}
+ if (val < 0) {Py_DECREF(result); result = NULL;}
finish:
- Py_DECREF(mit);
- return result;
+ Py_DECREF(mit);
+ return result;
}
/* VOID-type arrays can only be compared equal and not-equal
- in which case the fields are all compared by extracting the fields
- and testing one at a time...
- equality testing is performed using logical_ands on all the fields.
- in-equality testing is performed using logical_ors on all the fields.
+ in which case the fields are all compared by extracting the fields
+ and testing one at a time...
+ equality testing is performed using logical_ands on all the fields.
+ in-equality testing is performed using logical_ors on all the fields.
- VOID-type arrays without fields are compared for equality by comparing their
- memory at each location directly (using string-code).
- */
+ VOID-type arrays without fields are compared for equality by comparing their
+ memory at each location directly (using string-code).
+*/
static PyObject *array_richcompare(PyArrayObject *, PyObject *, int);
@@ -4622,334 +4621,334 @@ static PyObject *array_richcompare(PyArrayObject *, PyObject *, int);
static PyObject *
_void_compare(PyArrayObject *self, PyArrayObject *other, int cmp_op)
{
- if (!(cmp_op == Py_EQ || cmp_op == Py_NE)) {
- PyErr_SetString(PyExc_ValueError, "Void-arrays can only" \
- "be compared for equality.");
- return NULL;
- }
- if (PyArray_HASFIELDS(self)) {
- PyObject *res=NULL, *temp, *a, *b;
- PyObject *key, *value, *temp2;
- PyObject *op;
- Py_ssize_t pos=0;
- op = (cmp_op == Py_EQ ? n_ops.logical_and : n_ops.logical_or);
- while (PyDict_Next(self->descr->fields, &pos, &key, &value)) {
- a = PyArray_EnsureAnyArray(array_subscript(self, key));
- if (a==NULL) {Py_XDECREF(res); return NULL;}
- b = array_subscript(other, key);
- if (b==NULL) {Py_XDECREF(res); Py_DECREF(a); return NULL;}
- temp = array_richcompare((PyArrayObject *)a,b,cmp_op);
- Py_DECREF(a);
- Py_DECREF(b);
- if (temp == NULL) {Py_XDECREF(res); return NULL;}
- if (res == NULL) {
- res = temp;
- }
- else {
- temp2 = PyObject_CallFunction(op, "OO", res, temp);
- Py_DECREF(temp);
- Py_DECREF(res);
- if (temp2 == NULL) return NULL;
- res = temp2;
- }
- }
- if (res == NULL && !PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError, "No fields found.");
- }
- return res;
+ if (!(cmp_op == Py_EQ || cmp_op == Py_NE)) {
+ PyErr_SetString(PyExc_ValueError, "Void-arrays can only" \
+ "be compared for equality.");
+ return NULL;
+ }
+ if (PyArray_HASFIELDS(self)) {
+ PyObject *res=NULL, *temp, *a, *b;
+ PyObject *key, *value, *temp2;
+ PyObject *op;
+ Py_ssize_t pos=0;
+ op = (cmp_op == Py_EQ ? n_ops.logical_and : n_ops.logical_or);
+ while (PyDict_Next(self->descr->fields, &pos, &key, &value)) {
+ a = PyArray_EnsureAnyArray(array_subscript(self, key));
+ if (a==NULL) {Py_XDECREF(res); return NULL;}
+ b = array_subscript(other, key);
+ if (b==NULL) {Py_XDECREF(res); Py_DECREF(a); return NULL;}
+ temp = array_richcompare((PyArrayObject *)a,b,cmp_op);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (temp == NULL) {Py_XDECREF(res); return NULL;}
+ if (res == NULL) {
+ res = temp;
+ }
+ else {
+ temp2 = PyObject_CallFunction(op, "OO", res, temp);
+ Py_DECREF(temp);
+ Py_DECREF(res);
+ if (temp2 == NULL) return NULL;
+ res = temp2;
+ }
}
- else { /* compare as a string */
- /* assumes self and other have same descr->type */
- return _strings_richcompare(self, other, cmp_op, 0);
+ if (res == NULL && !PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError, "No fields found.");
}
+ return res;
+ }
+ else { /* compare as a string */
+ /* assumes self and other have same descr->type */
+ return _strings_richcompare(self, other, cmp_op, 0);
+ }
}
static PyObject *
array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op)
{
- PyObject *array_other, *result = NULL;
- int typenum;
-
- switch (cmp_op)
- {
- case Py_LT:
- result = PyArray_GenericBinaryFunction(self, other,
- n_ops.less);
- break;
- case Py_LE:
- result = PyArray_GenericBinaryFunction(self, other,
- n_ops.less_equal);
- break;
- case Py_EQ:
- if (other == Py_None) {
- Py_INCREF(Py_False);
- return Py_False;
- }
- /* Try to convert other to an array */
- if (!PyArray_Check(other)) {
- typenum = self->descr->type_num;
- if (typenum != PyArray_OBJECT) {
- typenum = PyArray_NOTYPE;
- }
- array_other = PyArray_FromObject(other,
- typenum, 0, 0);
- /* If not successful, then return False
- This fixes code that used to
- allow equality comparisons between arrays
- and other objects which would give a result
- of False
- */
- if ((array_other == NULL) || \
- (array_other == Py_None)) {
- Py_XDECREF(array_other);
- PyErr_Clear();
- Py_INCREF(Py_False);
- return Py_False;
- }
- }
- else {
- Py_INCREF(other);
- array_other = other;
- }
- result = PyArray_GenericBinaryFunction(self,
- array_other,
- n_ops.equal);
- if ((result == Py_NotImplemented) &&
- (self->descr->type_num == PyArray_VOID)) {
- int _res;
- _res = PyObject_RichCompareBool \
- ((PyObject *)self->descr,
- (PyObject *)\
- PyArray_DESCR(array_other),
- Py_EQ);
- if (_res < 0) {
- Py_DECREF(result);
- Py_DECREF(array_other);
- return NULL;
- }
- if (_res) {
- Py_DECREF(result);
- result = _void_compare\
- (self,
- (PyArrayObject *)array_other,
- cmp_op);
- Py_DECREF(array_other);
- }
- return result;
- }
- /* If the comparison results in NULL, then the
- two array objects can not be compared together so
- return zero
- */
- Py_DECREF(array_other);
- if (result == NULL) {
- PyErr_Clear();
- Py_INCREF(Py_False);
- return Py_False;
- }
- break;
- case Py_NE:
- if (other == Py_None) {
- Py_INCREF(Py_True);
- return Py_True;
- }
- /* Try to convert other to an array */
- if (!PyArray_Check(other)) {
- typenum = self->descr->type_num;
- if (typenum != PyArray_OBJECT) {
- typenum = PyArray_NOTYPE;
- }
- array_other = PyArray_FromObject(other,
- typenum, 0, 0);
- /* If not successful, then objects cannot be
- compared and cannot be equal, therefore,
- return True;
- */
- if ((array_other == NULL) || \
- (array_other == Py_None)) {
- Py_XDECREF(array_other);
- PyErr_Clear();
- Py_INCREF(Py_True);
- return Py_True;
- }
- }
- else {
- Py_INCREF(other);
- array_other = other;
- }
- result = PyArray_GenericBinaryFunction(self,
- array_other,
- n_ops.not_equal);
- if ((result == Py_NotImplemented) &&
- (self->descr->type_num == PyArray_VOID)) {
- int _res;
- _res = PyObject_RichCompareBool\
- ((PyObject *)self->descr,
- (PyObject *)\
- PyArray_DESCR(array_other),
- Py_EQ);
- if (_res < 0) {
- Py_DECREF(result);
- Py_DECREF(array_other);
- return NULL;
- }
- if (_res) {
- Py_DECREF(result);
- result = _void_compare\
- (self,
- (PyArrayObject *)array_other,
- cmp_op);
- Py_DECREF(array_other);
- }
- return result;
- }
-
- Py_DECREF(array_other);
- if (result == NULL) {
- PyErr_Clear();
- Py_INCREF(Py_True);
- return Py_True;
- }
- break;
- case Py_GT:
- result = PyArray_GenericBinaryFunction(self, other,
- n_ops.greater);
- break;
- case Py_GE:
- result = PyArray_GenericBinaryFunction(self, other,
- n_ops.greater_equal);
- break;
- default:
- result = Py_NotImplemented;
- Py_INCREF(result);
+ PyObject *array_other, *result = NULL;
+ int typenum;
+
+ switch (cmp_op)
+ {
+ case Py_LT:
+ result = PyArray_GenericBinaryFunction(self, other,
+ n_ops.less);
+ break;
+ case Py_LE:
+ result = PyArray_GenericBinaryFunction(self, other,
+ n_ops.less_equal);
+ break;
+ case Py_EQ:
+ if (other == Py_None) {
+ Py_INCREF(Py_False);
+ return Py_False;
+ }
+ /* Try to convert other to an array */
+ if (!PyArray_Check(other)) {
+ typenum = self->descr->type_num;
+ if (typenum != PyArray_OBJECT) {
+ typenum = PyArray_NOTYPE;
+ }
+ array_other = PyArray_FromObject(other,
+ typenum, 0, 0);
+ /* If not successful, then return False
+ This fixes code that used to
+ allow equality comparisons between arrays
+ and other objects which would give a result
+ of False
+ */
+ if ((array_other == NULL) || \
+ (array_other == Py_None)) {
+ Py_XDECREF(array_other);
+ PyErr_Clear();
+ Py_INCREF(Py_False);
+ return Py_False;
}
- if (result == Py_NotImplemented) {
- /* Try to handle string comparisons */
- if (self->descr->type_num == PyArray_OBJECT) return result;
- array_other = PyArray_FromObject(other,PyArray_NOTYPE, 0, 0);
- if (PyArray_ISSTRING(self) && PyArray_ISSTRING(array_other)) {
- Py_DECREF(result);
- result = _strings_richcompare(self, (PyArrayObject *)
- array_other, cmp_op, 0);
+ }
+ else {
+ Py_INCREF(other);
+ array_other = other;
+ }
+ result = PyArray_GenericBinaryFunction(self,
+ array_other,
+ n_ops.equal);
+ if ((result == Py_NotImplemented) &&
+ (self->descr->type_num == PyArray_VOID)) {
+ int _res;
+ _res = PyObject_RichCompareBool \
+ ((PyObject *)self->descr,
+ (PyObject *)\
+ PyArray_DESCR(array_other),
+ Py_EQ);
+ if (_res < 0) {
+ Py_DECREF(result);
+ Py_DECREF(array_other);
+ return NULL;
+ }
+ if (_res) {
+ Py_DECREF(result);
+ result = _void_compare\
+ (self,
+ (PyArrayObject *)array_other,
+ cmp_op);
+ Py_DECREF(array_other);
+ }
+ return result;
+ }
+ /* If the comparison results in NULL, then the
+ two array objects can not be compared together so
+ return zero
+ */
+ Py_DECREF(array_other);
+ if (result == NULL) {
+ PyErr_Clear();
+ Py_INCREF(Py_False);
+ return Py_False;
+ }
+ break;
+ case Py_NE:
+ if (other == Py_None) {
+ Py_INCREF(Py_True);
+ return Py_True;
+ }
+ /* Try to convert other to an array */
+ if (!PyArray_Check(other)) {
+ typenum = self->descr->type_num;
+ if (typenum != PyArray_OBJECT) {
+ typenum = PyArray_NOTYPE;
+ }
+ array_other = PyArray_FromObject(other,
+ typenum, 0, 0);
+ /* If not successful, then objects cannot be
+ compared and cannot be equal, therefore,
+ return True;
+ */
+ if ((array_other == NULL) || \
+ (array_other == Py_None)) {
+ Py_XDECREF(array_other);
+ PyErr_Clear();
+ Py_INCREF(Py_True);
+ return Py_True;
}
- Py_DECREF(array_other);
- }
- return result;
+ }
+ else {
+ Py_INCREF(other);
+ array_other = other;
+ }
+ result = PyArray_GenericBinaryFunction(self,
+ array_other,
+ n_ops.not_equal);
+ if ((result == Py_NotImplemented) &&
+ (self->descr->type_num == PyArray_VOID)) {
+ int _res;
+ _res = PyObject_RichCompareBool\
+ ((PyObject *)self->descr,
+ (PyObject *)\
+ PyArray_DESCR(array_other),
+ Py_EQ);
+ if (_res < 0) {
+ Py_DECREF(result);
+ Py_DECREF(array_other);
+ return NULL;
+ }
+ if (_res) {
+ Py_DECREF(result);
+ result = _void_compare\
+ (self,
+ (PyArrayObject *)array_other,
+ cmp_op);
+ Py_DECREF(array_other);
+ }
+ return result;
+ }
+
+ Py_DECREF(array_other);
+ if (result == NULL) {
+ PyErr_Clear();
+ Py_INCREF(Py_True);
+ return Py_True;
+ }
+ break;
+ case Py_GT:
+ result = PyArray_GenericBinaryFunction(self, other,
+ n_ops.greater);
+ break;
+ case Py_GE:
+ result = PyArray_GenericBinaryFunction(self, other,
+ n_ops.greater_equal);
+ break;
+ default:
+ result = Py_NotImplemented;
+ Py_INCREF(result);
+ }
+ if (result == Py_NotImplemented) {
+ /* Try to handle string comparisons */
+ if (self->descr->type_num == PyArray_OBJECT) return result;
+ array_other = PyArray_FromObject(other,PyArray_NOTYPE, 0, 0);
+ if (PyArray_ISSTRING(self) && PyArray_ISSTRING(array_other)) {
+ Py_DECREF(result);
+ result = _strings_richcompare(self, (PyArrayObject *)
+ array_other, cmp_op, 0);
+ }
+ Py_DECREF(array_other);
+ }
+ return result;
}
static PyObject *
_check_axis(PyArrayObject *arr, int *axis, int flags)
{
- PyObject *temp1, *temp2;
- int n = arr->nd;
+ PyObject *temp1, *temp2;
+ int n = arr->nd;
- if ((*axis >= MAX_DIMS) || (n==0)) {
- if (n != 1) {
- temp1 = PyArray_Ravel(arr,0);
- if (temp1 == NULL) {*axis=0; return NULL;}
- *axis = PyArray_NDIM(temp1)-1;
- }
- else {
- temp1 = (PyObject *)arr;
- Py_INCREF(temp1);
- *axis = 0;
- }
- if (!flags) return temp1;
- }
- else {
- temp1 = (PyObject *)arr;
- Py_INCREF(temp1);
- }
- if (flags) {
- temp2 = PyArray_CheckFromAny((PyObject *)temp1, NULL,
- 0, 0, flags, NULL);
- Py_DECREF(temp1);
- if (temp2 == NULL) return NULL;
+ if ((*axis >= MAX_DIMS) || (n==0)) {
+ if (n != 1) {
+ temp1 = PyArray_Ravel(arr,0);
+ if (temp1 == NULL) {*axis=0; return NULL;}
+ *axis = PyArray_NDIM(temp1)-1;
}
else {
- temp2 = (PyObject *)temp1;
- }
- n = PyArray_NDIM(temp2);
- if (*axis < 0) *axis += n;
- if ((*axis < 0) || (*axis >= n)) {
- PyErr_Format(PyExc_ValueError,
- "axis(=%d) out of bounds", *axis);
- Py_DECREF(temp2);
- return NULL;
+ temp1 = (PyObject *)arr;
+ Py_INCREF(temp1);
+ *axis = 0;
}
- return temp2;
+ if (!flags) return temp1;
+ }
+ else {
+ temp1 = (PyObject *)arr;
+ Py_INCREF(temp1);
+ }
+ if (flags) {
+ temp2 = PyArray_CheckFromAny((PyObject *)temp1, NULL,
+ 0, 0, flags, NULL);
+ Py_DECREF(temp1);
+ if (temp2 == NULL) return NULL;
+ }
+ else {
+ temp2 = (PyObject *)temp1;
+ }
+ n = PyArray_NDIM(temp2);
+ if (*axis < 0) *axis += n;
+ if ((*axis < 0) || (*axis >= n)) {
+ PyErr_Format(PyExc_ValueError,
+ "axis(=%d) out of bounds", *axis);
+ Py_DECREF(temp2);
+ return NULL;
+ }
+ return temp2;
}
#include "arraymethods.c"
/* Lifted from numarray */
/*MULTIARRAY_API
- PyArray_IntTupleFromIntp
+ PyArray_IntTupleFromIntp
*/
static PyObject *
PyArray_IntTupleFromIntp(int len, intp *vals)
{
- int i;
- PyObject *intTuple = PyTuple_New(len);
- if (!intTuple) goto fail;
- for(i=0; i<len; i++) {
+ int i;
+ PyObject *intTuple = PyTuple_New(len);
+ if (!intTuple) goto fail;
+ for(i=0; i<len; i++) {
#if SIZEOF_INTP <= SIZEOF_LONG
- PyObject *o = PyInt_FromLong((long) vals[i]);
+ PyObject *o = PyInt_FromLong((long) vals[i]);
#else
- PyObject *o = PyLong_FromLongLong((longlong) vals[i]);
+ PyObject *o = PyLong_FromLongLong((longlong) vals[i]);
#endif
- if (!o) {
- Py_DECREF(intTuple);
- intTuple = NULL;
- goto fail;
- }
- PyTuple_SET_ITEM(intTuple, i, o);
+ if (!o) {
+ Py_DECREF(intTuple);
+ intTuple = NULL;
+ goto fail;
}
- fail:
- return intTuple;
+ PyTuple_SET_ITEM(intTuple, i, o);
+ }
+ fail:
+ return intTuple;
}
/* Returns the number of dimensions or -1 if an error occurred */
/* vals must be large enough to hold maxvals */
/*MULTIARRAY_API
- PyArray_IntpFromSequence
+ PyArray_IntpFromSequence
*/
static int
PyArray_IntpFromSequence(PyObject *seq, intp *vals, int maxvals)
{
- int nd, i;
- PyObject *op;
+ int nd, i;
+ PyObject *op;
- /* Check to see if sequence is a single integer first.
- or, can be made into one */
- if ((nd=PySequence_Length(seq)) == -1) {
- if (PyErr_Occurred()) PyErr_Clear();
+ /* Check to see if sequence is a single integer first.
+ or, can be made into one */
+ if ((nd=PySequence_Length(seq)) == -1) {
+ if (PyErr_Occurred()) PyErr_Clear();
#if SIZEOF_LONG >= SIZEOF_INTP
- if (!(op = PyNumber_Int(seq))) return -1;
+ if (!(op = PyNumber_Int(seq))) return -1;
#else
- if (!(op = PyNumber_Long(seq))) return -1;
+ if (!(op = PyNumber_Long(seq))) return -1;
#endif
- nd = 1;
+ nd = 1;
#if SIZEOF_LONG >= SIZEOF_INTP
- vals[0] = (intp ) PyInt_AsLong(op);
+ vals[0] = (intp ) PyInt_AsLong(op);
#else
- vals[0] = (intp ) PyLong_AsLongLong(op);
+ vals[0] = (intp ) PyLong_AsLongLong(op);
#endif
- Py_DECREF(op);
- } else {
- for(i=0; i < MIN(nd,maxvals); i++) {
- op = PySequence_GetItem(seq, i);
- if (op == NULL) return -1;
+ Py_DECREF(op);
+ } else {
+ for(i=0; i < MIN(nd,maxvals); i++) {
+ op = PySequence_GetItem(seq, i);
+ if (op == NULL) return -1;
#if SIZEOF_LONG >= SIZEOF_INTP
- vals[i]=(intp )PyInt_AsLong(op);
+ vals[i]=(intp )PyInt_AsLong(op);
#else
- vals[i]=(intp )PyLong_AsLongLong(op);
+ vals[i]=(intp )PyLong_AsLongLong(op);
#endif
- Py_DECREF(op);
- if(PyErr_Occurred()) return -1;
- }
+ Py_DECREF(op);
+ if(PyErr_Occurred()) return -1;
}
- return nd;
+ }
+ return nd;
}
@@ -4961,22 +4960,22 @@ PyArray_IntpFromSequence(PyObject *seq, intp *vals, int maxvals)
static int
_IsContiguous(PyArrayObject *ap)
{
- register intp sd;
- register intp dim;
- register int i;
-
- if (ap->nd == 0) return 1;
- sd = ap->descr->elsize;
- if (ap->nd == 1) return (ap->dimensions[0] == 1 || \
- sd == ap->strides[0]);
- for (i = ap->nd-1; i >= 0; --i) {
- dim = ap->dimensions[i];
- /* contiguous by definition */
- if (dim == 0) return 1;
- if (ap->strides[i] != sd) return 0;
- sd *= dim;
- }
- return 1;
+ register intp sd;
+ register intp dim;
+ register int i;
+
+ if (ap->nd == 0) return 1;
+ sd = ap->descr->elsize;
+ if (ap->nd == 1) return (ap->dimensions[0] == 1 || \
+ sd == ap->strides[0]);
+ for (i = ap->nd-1; i >= 0; --i) {
+ dim = ap->dimensions[i];
+ /* contiguous by definition */
+ if (dim == 0) return 1;
+ if (ap->strides[i] != sd) return 0;
+ sd *= dim;
+ }
+ return 1;
}
@@ -4984,78 +4983,78 @@ _IsContiguous(PyArrayObject *ap)
static int
_IsFortranContiguous(PyArrayObject *ap)
{
- register intp sd;
- register intp dim;
- register int i;
-
- if (ap->nd == 0) return 1;
- sd = ap->descr->elsize;
- if (ap->nd == 1) return (ap->dimensions[0] == 1 || \
- sd == ap->strides[0]);
- for (i=0; i< ap->nd; ++i) {
- dim = ap->dimensions[i];
- /* fortran contiguous by definition */
- if (dim == 0) return 1;
- if (ap->strides[i] != sd) return 0;
- sd *= dim;
- }
- return 1;
+ register intp sd;
+ register intp dim;
+ register int i;
+
+ if (ap->nd == 0) return 1;
+ sd = ap->descr->elsize;
+ if (ap->nd == 1) return (ap->dimensions[0] == 1 || \
+ sd == ap->strides[0]);
+ for (i=0; i< ap->nd; ++i) {
+ dim = ap->dimensions[i];
+ /* fortran contiguous by definition */
+ if (dim == 0) return 1;
+ if (ap->strides[i] != sd) return 0;
+ sd *= dim;
+ }
+ return 1;
}
static int
_IsAligned(PyArrayObject *ap)
{
- int i, alignment, aligned=1;
- intp ptr;
- int type = ap->descr->type_num;
+ int i, alignment, aligned=1;
+ intp ptr;
+ int type = ap->descr->type_num;
- if ((type == PyArray_STRING) || (type == PyArray_VOID))
- return 1;
+ if ((type == PyArray_STRING) || (type == PyArray_VOID))
+ return 1;
- alignment = ap->descr->alignment;
- if (alignment == 1) return 1;
+ alignment = ap->descr->alignment;
+ if (alignment == 1) return 1;
- ptr = (intp) ap->data;
- aligned = (ptr % alignment) == 0;
- for (i=0; i <ap->nd; i++)
- aligned &= ((ap->strides[i] % alignment) == 0);
- return aligned != 0;
+ ptr = (intp) ap->data;
+ aligned = (ptr % alignment) == 0;
+ for (i=0; i <ap->nd; i++)
+ aligned &= ((ap->strides[i] % alignment) == 0);
+ return aligned != 0;
}
static Bool
_IsWriteable(PyArrayObject *ap)
{
- PyObject *base=ap->base;
- void *dummy;
- Py_ssize_t n;
-
- /* If we own our own data, then no-problem */
- if ((base == NULL) || (ap->flags & OWNDATA)) return TRUE;
-
- /* Get to the final base object
- If it is a writeable array, then return TRUE
- If we can find an array object
- or a writeable buffer object as the final base object
- or a string object (for pickling support memory savings).
- - this last could be removed if a proper pickleable
- buffer was added to Python.
- */
-
- while(PyArray_Check(base)) {
- if (PyArray_CHKFLAGS(base, OWNDATA))
- return (Bool) (PyArray_ISWRITEABLE(base));
- base = PyArray_BASE(base);
- }
+ PyObject *base=ap->base;
+ void *dummy;
+ Py_ssize_t n;
+
+ /* If we own our own data, then no-problem */
+ if ((base == NULL) || (ap->flags & OWNDATA)) return TRUE;
+
+ /* Get to the final base object
+ If it is a writeable array, then return TRUE
+ If we can find an array object
+ or a writeable buffer object as the final base object
+ or a string object (for pickling support memory savings).
+ - this last could be removed if a proper pickleable
+ buffer was added to Python.
+ */
+
+ while(PyArray_Check(base)) {
+ if (PyArray_CHKFLAGS(base, OWNDATA))
+ return (Bool) (PyArray_ISWRITEABLE(base));
+ base = PyArray_BASE(base);
+ }
- /* here so pickle support works seamlessly
- and unpickled array can be set and reset writeable
- -- could be abused -- */
- if PyString_Check(base) return TRUE;
+ /* here so pickle support works seamlessly
+ and unpickled array can be set and reset writeable
+ -- could be abused -- */
+ if PyString_Check(base) return TRUE;
- if (PyObject_AsWriteBuffer(base, &dummy, &n) < 0)
- return FALSE;
+ if (PyObject_AsWriteBuffer(base, &dummy, &n) < 0)
+ return FALSE;
- return TRUE;
+ return TRUE;
}
@@ -5064,49 +5063,49 @@ _IsWriteable(PyArrayObject *ap)
static int
PyArray_ElementStrides(PyObject *arr)
{
- register int itemsize = PyArray_ITEMSIZE(arr);
- register int i, N=PyArray_NDIM(arr);
- register intp *strides = PyArray_STRIDES(arr);
+ register int itemsize = PyArray_ITEMSIZE(arr);
+ register int i, N=PyArray_NDIM(arr);
+ register intp *strides = PyArray_STRIDES(arr);
- for (i=0; i<N; i++) {
- if ((strides[i] % itemsize) != 0) return 0;
- }
+ for (i=0; i<N; i++) {
+ if ((strides[i] % itemsize) != 0) return 0;
+ }
- return 1;
+ return 1;
}
/*OBJECT_API
- Update Several Flags at once.
+ Update Several Flags at once.
*/
static void
PyArray_UpdateFlags(PyArrayObject *ret, int flagmask)
{
- if (flagmask & FORTRAN) {
- if (_IsFortranContiguous(ret)) {
- ret->flags |= FORTRAN;
- if (ret->nd > 1) ret->flags &= ~CONTIGUOUS;
- }
- else ret->flags &= ~FORTRAN;
- }
- if (flagmask & CONTIGUOUS) {
- if (_IsContiguous(ret)) {
- ret->flags |= CONTIGUOUS;
- if (ret->nd > 1) ret->flags &= ~FORTRAN;
- }
- else ret->flags &= ~CONTIGUOUS;
- }
- if (flagmask & ALIGNED) {
- if (_IsAligned(ret)) ret->flags |= ALIGNED;
- else ret->flags &= ~ALIGNED;
+ if (flagmask & FORTRAN) {
+ if (_IsFortranContiguous(ret)) {
+ ret->flags |= FORTRAN;
+ if (ret->nd > 1) ret->flags &= ~CONTIGUOUS;
}
- /* This is not checked by default WRITEABLE is not
- part of UPDATE_ALL */
- if (flagmask & WRITEABLE) {
- if (_IsWriteable(ret)) ret->flags |= WRITEABLE;
- else ret->flags &= ~WRITEABLE;
+ else ret->flags &= ~FORTRAN;
+ }
+ if (flagmask & CONTIGUOUS) {
+ if (_IsContiguous(ret)) {
+ ret->flags |= CONTIGUOUS;
+ if (ret->nd > 1) ret->flags &= ~FORTRAN;
}
- return;
+ else ret->flags &= ~CONTIGUOUS;
+ }
+ if (flagmask & ALIGNED) {
+ if (_IsAligned(ret)) ret->flags |= ALIGNED;
+ else ret->flags &= ~ALIGNED;
+ }
+ /* This is not checked by default WRITEABLE is not
+ part of UPDATE_ALL */
+ if (flagmask & WRITEABLE) {
+ if (_IsWriteable(ret)) ret->flags |= WRITEABLE;
+ else ret->flags &= ~WRITEABLE;
+ }
+ return;
}
/* This routine checks to see if newstrides (of length nd) will not
@@ -5130,22 +5129,22 @@ static Bool
PyArray_CheckStrides(int elsize, int nd, intp numbytes, intp offset,
intp *dims, intp *newstrides)
{
- int i;
- intp byte_begin;
- intp begin;
- intp end;
+ int i;
+ intp byte_begin;
+ intp begin;
+ intp end;
- if (numbytes == 0)
- numbytes = PyArray_MultiplyList(dims, nd) * elsize;
+ if (numbytes == 0)
+ numbytes = PyArray_MultiplyList(dims, nd) * elsize;
- begin = -offset;
- end = numbytes - offset - elsize;
- for (i=0; i<nd; i++) {
- byte_begin = newstrides[i]*(dims[i]-1);
- if ((byte_begin < begin) || (byte_begin > end))
- return FALSE;
- }
- return TRUE;
+ begin = -offset;
+ end = numbytes - offset - elsize;
+ for (i=0; i<nd; i++) {
+ byte_begin = newstrides[i]*(dims[i]-1);
+ if ((byte_begin < begin) || (byte_begin > end))
+ return FALSE;
+ }
+ return TRUE;
}
@@ -5170,55 +5169,55 @@ static size_t
_array_fill_strides(intp *strides, intp *dims, int nd, size_t itemsize,
int inflag, int *objflags)
{
- int i;
- /* Only make Fortran strides if not contiguous as well */
- if ((inflag & FORTRAN) && !(inflag & CONTIGUOUS)) {
- for (i=0; i<nd; i++) {
- strides[i] = itemsize;
- itemsize *= dims[i] ? dims[i] : 1;
- }
- *objflags |= FORTRAN;
- if (nd > 1) *objflags &= ~CONTIGUOUS;
- else *objflags |= CONTIGUOUS;
- }
- else {
- for (i=nd-1;i>=0;i--) {
- strides[i] = itemsize;
- itemsize *= dims[i] ? dims[i] : 1;
- }
- *objflags |= CONTIGUOUS;
- if (nd > 1) *objflags &= ~FORTRAN;
- else *objflags |= FORTRAN;
+ int i;
+ /* Only make Fortran strides if not contiguous as well */
+ if ((inflag & FORTRAN) && !(inflag & CONTIGUOUS)) {
+ for (i=0; i<nd; i++) {
+ strides[i] = itemsize;
+ itemsize *= dims[i] ? dims[i] : 1;
}
- return itemsize;
+ *objflags |= FORTRAN;
+ if (nd > 1) *objflags &= ~CONTIGUOUS;
+ else *objflags |= CONTIGUOUS;
+ }
+ else {
+ for (i=nd-1;i>=0;i--) {
+ strides[i] = itemsize;
+ itemsize *= dims[i] ? dims[i] : 1;
+ }
+ *objflags |= CONTIGUOUS;
+ if (nd > 1) *objflags &= ~FORTRAN;
+ else *objflags |= FORTRAN;
+ }
+ return itemsize;
}
/*OBJECT_API
- Generic new array creation routine.
+ Generic new array creation routine.
*/
static PyObject *
PyArray_New(PyTypeObject *subtype, int nd, intp *dims, int type_num,
intp *strides, void *data, int itemsize, int flags,
PyObject *obj)
{
- PyArray_Descr *descr;
- PyObject *new;
+ PyArray_Descr *descr;
+ PyObject *new;
- descr = PyArray_DescrFromType(type_num);
- if (descr == NULL) return NULL;
- if (descr->elsize == 0) {
- if (itemsize < 1) {
- PyErr_SetString(PyExc_ValueError,
- "data type must provide an itemsize");
- Py_DECREF(descr);
- return NULL;
- }
- PyArray_DESCR_REPLACE(descr);
- descr->elsize = itemsize;
+ descr = PyArray_DescrFromType(type_num);
+ if (descr == NULL) return NULL;
+ if (descr->elsize == 0) {
+ if (itemsize < 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "data type must provide an itemsize");
+ Py_DECREF(descr);
+ return NULL;
}
- new = PyArray_NewFromDescr(subtype, descr, nd, dims, strides,
- data, flags, obj);
- return new;
+ PyArray_DESCR_REPLACE(descr);
+ descr->elsize = itemsize;
+ }
+ new = PyArray_NewFromDescr(subtype, descr, nd, dims, strides,
+ data, flags, obj);
+ return new;
}
/* Change a sub-array field to the base descriptor */
@@ -5233,462 +5232,462 @@ static int
_update_descr_and_dimensions(PyArray_Descr **des, intp *newdims,
intp *newstrides, int oldnd, int isfortran)
{
- PyArray_Descr *old;
- int newnd;
- int numnew;
- intp *mydim;
- int i;
- int tuple;
+ PyArray_Descr *old;
+ int newnd;
+ int numnew;
+ intp *mydim;
+ int i;
+ int tuple;
- old = *des;
- *des = old->subarray->base;
+ old = *des;
+ *des = old->subarray->base;
- mydim = newdims + oldnd;
- tuple = PyTuple_Check(old->subarray->shape);
- if (tuple) {
- numnew = PyTuple_GET_SIZE(old->subarray->shape);
- }
- else {
- numnew = 1;
- }
+ mydim = newdims + oldnd;
+ tuple = PyTuple_Check(old->subarray->shape);
+ if (tuple) {
+ numnew = PyTuple_GET_SIZE(old->subarray->shape);
+ }
+ else {
+ numnew = 1;
+ }
- newnd = oldnd + numnew;
- if (newnd > MAX_DIMS) goto finish;
- if (isfortran) {
- memmove(newdims+numnew, newdims, oldnd*sizeof(intp));
- mydim = newdims;
- }
+ newnd = oldnd + numnew;
+ if (newnd > MAX_DIMS) goto finish;
+ if (isfortran) {
+ memmove(newdims+numnew, newdims, oldnd*sizeof(intp));
+ mydim = newdims;
+ }
- if (tuple) {
- for (i=0; i<numnew; i++) {
- mydim[i] = (intp) PyInt_AsLong \
- (PyTuple_GET_ITEM(old->subarray->shape, i));
- }
- }
- else {
- mydim[0] = (intp) PyInt_AsLong(old->subarray->shape);
+ if (tuple) {
+ for (i=0; i<numnew; i++) {
+ mydim[i] = (intp) PyInt_AsLong \
+ (PyTuple_GET_ITEM(old->subarray->shape, i));
}
+ }
+ else {
+ mydim[0] = (intp) PyInt_AsLong(old->subarray->shape);
+ }
- if (newstrides) {
- intp tempsize;
- intp *mystrides;
- mystrides = newstrides + oldnd;
- if (isfortran) {
- memmove(newstrides+numnew, newstrides,
- oldnd*sizeof(intp));
- mystrides = newstrides;
- }
- /* Make new strides -- alwasy C-contiguous */
- tempsize = (*des)->elsize;
- for (i=numnew-1; i>=0; i--) {
- mystrides[i] = tempsize;
- tempsize *= mydim[i] ? mydim[i] : 1;
- }
+ if (newstrides) {
+ intp tempsize;
+ intp *mystrides;
+ mystrides = newstrides + oldnd;
+ if (isfortran) {
+ memmove(newstrides+numnew, newstrides,
+ oldnd*sizeof(intp));
+ mystrides = newstrides;
+ }
+ /* Make new strides -- alwasy C-contiguous */
+ tempsize = (*des)->elsize;
+ for (i=numnew-1; i>=0; i--) {
+ mystrides[i] = tempsize;
+ tempsize *= mydim[i] ? mydim[i] : 1;
}
+ }
finish:
- Py_INCREF(*des);
- Py_DECREF(old);
- return newnd;
+ Py_INCREF(*des);
+ Py_DECREF(old);
+ return newnd;
}
/* steals a reference to descr (even on failure) */
/*OBJECT_API
- Generic new array creation routine.
+ Generic new array creation routine.
*/
static PyObject *
PyArray_NewFromDescr(PyTypeObject *subtype, PyArray_Descr *descr, int nd,
intp *dims, intp *strides, void *data,
int flags, PyObject *obj)
{
- PyArrayObject *self;
- register int i;
- size_t sd;
- intp largest;
- intp size;
-
- if (descr->subarray) {
- PyObject *ret;
- intp newdims[2*MAX_DIMS];
- intp *newstrides=NULL;
- int isfortran=0;
- isfortran = (data && (flags & FORTRAN) && !(flags & CONTIGUOUS)) || \
- (!data && flags);
- memcpy(newdims, dims, nd*sizeof(intp));
- if (strides) {
- newstrides = newdims + MAX_DIMS;
- memcpy(newstrides, strides, nd*sizeof(intp));
- }
- nd =_update_descr_and_dimensions(&descr, newdims,
- newstrides, nd, isfortran);
- ret = PyArray_NewFromDescr(subtype, descr, nd, newdims,
- newstrides,
- data, flags, obj);
- return ret;
- }
+ PyArrayObject *self;
+ register int i;
+ size_t sd;
+ intp largest;
+ intp size;
- if (nd < 0) {
- PyErr_SetString(PyExc_ValueError,
- "number of dimensions must be >=0");
- Py_DECREF(descr);
- return NULL;
- }
- if (nd > MAX_DIMS) {
- PyErr_Format(PyExc_ValueError,
- "maximum number of dimensions is %d", MAX_DIMS);
- Py_DECREF(descr);
- return NULL;
- }
+ if (descr->subarray) {
+ PyObject *ret;
+ intp newdims[2*MAX_DIMS];
+ intp *newstrides=NULL;
+ int isfortran=0;
+ isfortran = (data && (flags & FORTRAN) && !(flags & CONTIGUOUS)) || \
+ (!data && flags);
+ memcpy(newdims, dims, nd*sizeof(intp));
+ if (strides) {
+ newstrides = newdims + MAX_DIMS;
+ memcpy(newstrides, strides, nd*sizeof(intp));
+ }
+ nd =_update_descr_and_dimensions(&descr, newdims,
+ newstrides, nd, isfortran);
+ ret = PyArray_NewFromDescr(subtype, descr, nd, newdims,
+ newstrides,
+ data, flags, obj);
+ return ret;
+ }
- /* Check dimensions */
- size = 1;
- sd = (size_t) descr->elsize;
- if (sd == 0) {
- if (!PyDataType_ISSTRING(descr)) {
- PyErr_SetString(PyExc_ValueError, "Empty data-type");
- Py_DECREF(descr);
- return NULL;
- }
- PyArray_DESCR_REPLACE(descr);
- if (descr->type_num == NPY_STRING) descr->elsize = 1;
- else descr->elsize = sizeof(PyArray_UCS4);
- sd = (size_t) descr->elsize;
- }
- largest = MAX_INTP / sd;
- for (i=0;i<nd;i++) {
- if (dims[i] == 0) continue;
- if (dims[i] < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative dimensions " \
- "are not allowed");
- Py_DECREF(descr);
- return NULL;
- }
- size *= dims[i];
- if (size > largest) {
- PyErr_SetString(PyExc_ValueError,
- "dimensions too large.");
- Py_DECREF(descr);
- return NULL;
- }
- }
+ if (nd < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "number of dimensions must be >=0");
+ Py_DECREF(descr);
+ return NULL;
+ }
+ if (nd > MAX_DIMS) {
+ PyErr_Format(PyExc_ValueError,
+ "maximum number of dimensions is %d", MAX_DIMS);
+ Py_DECREF(descr);
+ return NULL;
+ }
- self = (PyArrayObject *) subtype->tp_alloc(subtype, 0);
- if (self == NULL) {
- Py_DECREF(descr);
- return NULL;
+ /* Check dimensions */
+ size = 1;
+ sd = (size_t) descr->elsize;
+ if (sd == 0) {
+ if (!PyDataType_ISSTRING(descr)) {
+ PyErr_SetString(PyExc_ValueError, "Empty data-type");
+ Py_DECREF(descr);
+ return NULL;
}
- self->nd = nd;
- self->dimensions = NULL;
- self->data = NULL;
- if (data == NULL) {
- self->flags = DEFAULT;
- if (flags) {
- self->flags |= FORTRAN;
- if (nd > 1) self->flags &= ~CONTIGUOUS;
- flags = FORTRAN;
- }
+ PyArray_DESCR_REPLACE(descr);
+ if (descr->type_num == NPY_STRING) descr->elsize = 1;
+ else descr->elsize = sizeof(PyArray_UCS4);
+ sd = (size_t) descr->elsize;
+ }
+ largest = MAX_INTP / sd;
+ for (i=0;i<nd;i++) {
+ if (dims[i] == 0) continue;
+ if (dims[i] < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative dimensions " \
+ "are not allowed");
+ Py_DECREF(descr);
+ return NULL;
}
- else self->flags = (flags & ~UPDATEIFCOPY);
-
- self->descr = descr;
- self->base = (PyObject *)NULL;
- self->weakreflist = (PyObject *)NULL;
-
- if (nd > 0) {
- self->dimensions = PyDimMem_NEW(2*nd);
- if (self->dimensions == NULL) {
- PyErr_NoMemory();
- goto fail;
- }
- self->strides = self->dimensions + nd;
- memcpy(self->dimensions, dims, sizeof(intp)*nd);
- if (strides == NULL) { /* fill it in */
- sd = _array_fill_strides(self->strides, dims, nd, sd,
- flags, &(self->flags));
- }
- else { /* we allow strides even when we create
- the memory, but be careful with this...
- */
- memcpy(self->strides, strides, sizeof(intp)*nd);
- sd *= size;
- }
+ size *= dims[i];
+ if (size > largest) {
+ PyErr_SetString(PyExc_ValueError,
+ "dimensions too large.");
+ Py_DECREF(descr);
+ return NULL;
}
- else { self->dimensions = self->strides = NULL; }
+ }
- if (data == NULL) {
+ self = (PyArrayObject *) subtype->tp_alloc(subtype, 0);
+ if (self == NULL) {
+ Py_DECREF(descr);
+ return NULL;
+ }
+ self->nd = nd;
+ self->dimensions = NULL;
+ self->data = NULL;
+ if (data == NULL) {
+ self->flags = DEFAULT;
+ if (flags) {
+ self->flags |= FORTRAN;
+ if (nd > 1) self->flags &= ~CONTIGUOUS;
+ flags = FORTRAN;
+ }
+ }
+ else self->flags = (flags & ~UPDATEIFCOPY);
+
+ self->descr = descr;
+ self->base = (PyObject *)NULL;
+ self->weakreflist = (PyObject *)NULL;
+
+ if (nd > 0) {
+ self->dimensions = PyDimMem_NEW(2*nd);
+ if (self->dimensions == NULL) {
+ PyErr_NoMemory();
+ goto fail;
+ }
+ self->strides = self->dimensions + nd;
+ memcpy(self->dimensions, dims, sizeof(intp)*nd);
+ if (strides == NULL) { /* fill it in */
+ sd = _array_fill_strides(self->strides, dims, nd, sd,
+ flags, &(self->flags));
+ }
+ else { /* we allow strides even when we create
+ the memory, but be careful with this...
+ */
+ memcpy(self->strides, strides, sizeof(intp)*nd);
+ sd *= size;
+ }
+ }
+ else { self->dimensions = self->strides = NULL; }
- /* Allocate something even for zero-space arrays
- e.g. shape=(0,) -- otherwise buffer exposure
- (a.data) doesn't work as it should. */
+ if (data == NULL) {
- if (sd==0) sd = descr->elsize;
+ /* Allocate something even for zero-space arrays
+ e.g. shape=(0,) -- otherwise buffer exposure
+ (a.data) doesn't work as it should. */
- if ((data = PyDataMem_NEW(sd))==NULL) {
- PyErr_NoMemory();
- goto fail;
- }
- self->flags |= OWNDATA;
+ if (sd==0) sd = descr->elsize;
- /* It is bad to have unitialized OBJECT pointers */
- /* which could also be sub-fields of a VOID array */
- if (PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) {
- memset(data, 0, sd);
- }
+ if ((data = PyDataMem_NEW(sd))==NULL) {
+ PyErr_NoMemory();
+ goto fail;
}
- else {
- self->flags &= ~OWNDATA; /* If data is passed in,
- this object won't own it
- by default.
- Caller must arrange for
- this to be reset if truly
- desired */
- }
- self->data = data;
-
- /* call the __array_finalize__
- method if a subtype.
- If obj is NULL, then call method with Py_None
- */
- if ((subtype != &PyArray_Type)) {
- PyObject *res, *func, *args;
- static PyObject *str=NULL;
+ self->flags |= OWNDATA;
- if (str == NULL) {
- str = PyString_InternFromString("__array_finalize__");
- }
- func = PyObject_GetAttr((PyObject *)self, str);
- if (func && func != Py_None) {
- if (strides != NULL) { /* did not allocate own data
- or funny strides */
- /* update flags before finalize function */
- PyArray_UpdateFlags(self, UPDATE_ALL);
- }
- if PyCObject_Check(func) { /* A C-function is stored here */
- PyArray_FinalizeFunc *cfunc;
- cfunc = PyCObject_AsVoidPtr(func);
- Py_DECREF(func);
- if (cfunc(self, obj) < 0) goto fail;
- }
- else {
- args = PyTuple_New(1);
- if (obj == NULL) obj=Py_None;
- Py_INCREF(obj);
- PyTuple_SET_ITEM(args, 0, obj);
- res = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- Py_DECREF(func);
- if (res == NULL) goto fail;
- else Py_DECREF(res);
- }
+ /* It is bad to have unitialized OBJECT pointers */
+ /* which could also be sub-fields of a VOID array */
+ if (PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) {
+ memset(data, 0, sd);
+ }
+ }
+ else {
+ self->flags &= ~OWNDATA; /* If data is passed in,
+ this object won't own it
+ by default.
+ Caller must arrange for
+ this to be reset if truly
+ desired */
+ }
+ self->data = data;
+
+ /* call the __array_finalize__
+ method if a subtype.
+ If obj is NULL, then call method with Py_None
+ */
+ if ((subtype != &PyArray_Type)) {
+ PyObject *res, *func, *args;
+ static PyObject *str=NULL;
+
+ if (str == NULL) {
+ str = PyString_InternFromString("__array_finalize__");
+ }
+ func = PyObject_GetAttr((PyObject *)self, str);
+ if (func && func != Py_None) {
+ if (strides != NULL) { /* did not allocate own data
+ or funny strides */
+ /* update flags before finalize function */
+ PyArray_UpdateFlags(self, UPDATE_ALL);
+ }
+ if PyCObject_Check(func) { /* A C-function is stored here */
+ PyArray_FinalizeFunc *cfunc;
+ cfunc = PyCObject_AsVoidPtr(func);
+ Py_DECREF(func);
+ if (cfunc(self, obj) < 0) goto fail;
}
- else Py_XDECREF(func);
+ else {
+ args = PyTuple_New(1);
+ if (obj == NULL) obj=Py_None;
+ Py_INCREF(obj);
+ PyTuple_SET_ITEM(args, 0, obj);
+ res = PyObject_Call(func, args, NULL);
+ Py_DECREF(args);
+ Py_DECREF(func);
+ if (res == NULL) goto fail;
+ else Py_DECREF(res);
+ }
}
+ else Py_XDECREF(func);
+ }
- return (PyObject *)self;
+ return (PyObject *)self;
fail:
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
static void
_putzero(char *optr, PyObject *zero, PyArray_Descr *dtype)
{
- if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
- memset(optr, 0, dtype->elsize);
- }
- else if (PyDescr_HASFIELDS(dtype)) {
- PyObject *key, *value, *title=NULL;
- PyArray_Descr *new;
- int offset;
- Py_ssize_t pos=0;
- while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
- if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
- &title)) return;
- _putzero(optr + offset, zero, new);
- }
- }
- else {
- PyObject **temp;
- Py_INCREF(zero);
- temp = (PyObject **)optr;
- *temp = zero;
+ if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
+ memset(optr, 0, dtype->elsize);
+ }
+ else if (PyDescr_HASFIELDS(dtype)) {
+ PyObject *key, *value, *title=NULL;
+ PyArray_Descr *new;
+ int offset;
+ Py_ssize_t pos=0;
+ while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
+ if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
+ &title)) return;
+ _putzero(optr + offset, zero, new);
}
- return;
+ }
+ else {
+ PyObject **temp;
+ Py_INCREF(zero);
+ temp = (PyObject **)optr;
+ *temp = zero;
+ }
+ return;
}
/*OBJECT_API
- Resize (reallocate data). Only works if nothing else is referencing
- this array and it is contiguous.
- If refcheck is 0, then the reference count is not checked
- and assumed to be 1.
- You still must own this data and have no weak-references and no base
- object.
+ Resize (reallocate data). Only works if nothing else is referencing
+ this array and it is contiguous.
+ If refcheck is 0, then the reference count is not checked
+ and assumed to be 1.
+ You still must own this data and have no weak-references and no base
+ object.
*/
static PyObject *
PyArray_Resize(PyArrayObject *self, PyArray_Dims *newshape, int refcheck,
NPY_ORDER fortran)
{
- intp oldsize, newsize;
- int new_nd=newshape->len, k, n, elsize;
- int refcnt;
- intp* new_dimensions=newshape->ptr;
- intp new_strides[MAX_DIMS];
- size_t sd;
- intp *dimptr;
- char *new_data;
- intp largest;
-
- if (!PyArray_ISONESEGMENT(self)) {
- PyErr_SetString(PyExc_ValueError,
- "resize only works on single-segment arrays");
- return NULL;
- }
+ intp oldsize, newsize;
+ int new_nd=newshape->len, k, n, elsize;
+ int refcnt;
+ intp* new_dimensions=newshape->ptr;
+ intp new_strides[MAX_DIMS];
+ size_t sd;
+ intp *dimptr;
+ char *new_data;
+ intp largest;
+
+ if (!PyArray_ISONESEGMENT(self)) {
+ PyErr_SetString(PyExc_ValueError,
+ "resize only works on single-segment arrays");
+ return NULL;
+ }
- if (fortran == PyArray_ANYORDER)
- fortran = PyArray_CORDER;
+ if (fortran == PyArray_ANYORDER)
+ fortran = PyArray_CORDER;
- if (self->descr->elsize == 0) {
- PyErr_SetString(PyExc_ValueError, "Bad data-type size.");
- return NULL;
+ if (self->descr->elsize == 0) {
+ PyErr_SetString(PyExc_ValueError, "Bad data-type size.");
+ return NULL;
+ }
+ newsize = 1;
+ largest = MAX_INTP / self->descr->elsize;
+ for (k=0; k<new_nd; k++) {
+ if (new_dimensions[k]==0) break;
+ if (new_dimensions[k] < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative dimensions not allowed");
+ return NULL;
}
- newsize = 1;
- largest = MAX_INTP / self->descr->elsize;
- for (k=0; k<new_nd; k++) {
- if (new_dimensions[k]==0) break;
- if (new_dimensions[k] < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative dimensions not allowed");
- return NULL;
- }
- newsize *= new_dimensions[k];
- if (newsize <=0 || newsize > largest) {
- return PyErr_NoMemory();
- }
+ newsize *= new_dimensions[k];
+ if (newsize <=0 || newsize > largest) {
+ return PyErr_NoMemory();
}
- oldsize = PyArray_SIZE(self);
+ }
+ oldsize = PyArray_SIZE(self);
- if (oldsize != newsize) {
- if (!(self->flags & OWNDATA)) {
- PyErr_SetString(PyExc_ValueError,
- "cannot resize this array: " \
- "it does not own its data");
- return NULL;
- }
+ if (oldsize != newsize) {
+ if (!(self->flags & OWNDATA)) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot resize this array: " \
+ "it does not own its data");
+ return NULL;
+ }
- if (refcheck) refcnt = REFCOUNT(self);
- else refcnt = 1;
- if ((refcnt > 2) || (self->base != NULL) || \
- (self->weakreflist != NULL)) {
- PyErr_SetString(PyExc_ValueError,
- "cannot resize an array that has "\
- "been referenced or is referencing\n"\
- "another array in this way. Use the "\
- "resize function");
- return NULL;
- }
+ if (refcheck) refcnt = REFCOUNT(self);
+ else refcnt = 1;
+ if ((refcnt > 2) || (self->base != NULL) || \
+ (self->weakreflist != NULL)) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot resize an array that has "\
+ "been referenced or is referencing\n"\
+ "another array in this way. Use the "\
+ "resize function");
+ return NULL;
+ }
- if (newsize == 0) sd = self->descr->elsize;
- else sd = newsize * self->descr->elsize;
- /* Reallocate space if needed */
- new_data = PyDataMem_RENEW(self->data, sd);
- if (new_data == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "cannot allocate memory for array");
- return NULL;
- }
- self->data = new_data;
- }
-
- if ((newsize > oldsize) && PyArray_ISWRITEABLE(self)) {
- /* Fill new memory with zeros */
- elsize = self->descr->elsize;
- if (PyDataType_FLAGCHK(self->descr, NPY_ITEM_REFCOUNT)) {
- PyObject *zero = PyInt_FromLong(0);
- char *optr;
- optr = self->data + oldsize*elsize;
- n = newsize - oldsize;
- for (k=0; k<n; k++) {
- _putzero((char *)optr, zero, self->descr);
- optr += elsize;
- }
- Py_DECREF(zero);
- }
- else{
- memset(self->data+oldsize*elsize, 0,
- (newsize-oldsize)*elsize);
- }
+ if (newsize == 0) sd = self->descr->elsize;
+ else sd = newsize * self->descr->elsize;
+ /* Reallocate space if needed */
+ new_data = PyDataMem_RENEW(self->data, sd);
+ if (new_data == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "cannot allocate memory for array");
+ return NULL;
}
+ self->data = new_data;
+ }
- if (self->nd != new_nd) { /* Different number of dimensions. */
- self->nd = new_nd;
+ if ((newsize > oldsize) && PyArray_ISWRITEABLE(self)) {
+ /* Fill new memory with zeros */
+ elsize = self->descr->elsize;
+ if (PyDataType_FLAGCHK(self->descr, NPY_ITEM_REFCOUNT)) {
+ PyObject *zero = PyInt_FromLong(0);
+ char *optr;
+ optr = self->data + oldsize*elsize;
+ n = newsize - oldsize;
+ for (k=0; k<n; k++) {
+ _putzero((char *)optr, zero, self->descr);
+ optr += elsize;
+ }
+ Py_DECREF(zero);
+ }
+ else{
+ memset(self->data+oldsize*elsize, 0,
+ (newsize-oldsize)*elsize);
+ }
+ }
- /* Need new dimensions and strides arrays */
- dimptr = PyDimMem_RENEW(self->dimensions, 2*new_nd);
- if (dimptr == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "cannot allocate memory for array " \
- "(array may be corrupted)");
- return NULL;
- }
- self->dimensions = dimptr;
- self->strides = dimptr + new_nd;
+ if (self->nd != new_nd) { /* Different number of dimensions. */
+ self->nd = new_nd;
+
+ /* Need new dimensions and strides arrays */
+ dimptr = PyDimMem_RENEW(self->dimensions, 2*new_nd);
+ if (dimptr == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "cannot allocate memory for array " \
+ "(array may be corrupted)");
+ return NULL;
}
+ self->dimensions = dimptr;
+ self->strides = dimptr + new_nd;
+ }
- /* make new_strides variable */
- sd = (size_t) self->descr->elsize;
- sd = (size_t) _array_fill_strides(new_strides, new_dimensions, new_nd, sd,
- self->flags, &(self->flags));
+ /* make new_strides variable */
+ sd = (size_t) self->descr->elsize;
+ sd = (size_t) _array_fill_strides(new_strides, new_dimensions, new_nd, sd,
+ self->flags, &(self->flags));
- memmove(self->dimensions, new_dimensions, new_nd*sizeof(intp));
- memmove(self->strides, new_strides, new_nd*sizeof(intp));
+ memmove(self->dimensions, new_dimensions, new_nd*sizeof(intp));
+ memmove(self->strides, new_strides, new_nd*sizeof(intp));
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
_fillobject(char *optr, PyObject *obj, PyArray_Descr *dtype)
{
- if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
- if ((obj == Py_None) ||
- (PyInt_Check(obj) && PyInt_AsLong(obj)==0))
- return;
- else {
- PyObject *arr;
- Py_INCREF(dtype);
- arr = PyArray_NewFromDescr(&PyArray_Type, dtype,
- 0, NULL, NULL, NULL,
- 0, NULL);
- if (arr!=NULL)
- dtype->f->setitem(obj, optr, arr);
- Py_XDECREF(arr);
- }
- }
- else if (PyDescr_HASFIELDS(dtype)) {
- PyObject *key, *value, *title=NULL;
- PyArray_Descr *new;
- int offset;
- Py_ssize_t pos=0;
- while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
- if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
- &title)) return;
- _fillobject(optr + offset, obj, new);
- }
- }
+ if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
+ if ((obj == Py_None) ||
+ (PyInt_Check(obj) && PyInt_AsLong(obj)==0))
+ return;
else {
- PyObject **temp;
- Py_XINCREF(obj);
- temp = (PyObject **)optr;
- *temp = obj;
- return;
+ PyObject *arr;
+ Py_INCREF(dtype);
+ arr = PyArray_NewFromDescr(&PyArray_Type, dtype,
+ 0, NULL, NULL, NULL,
+ 0, NULL);
+ if (arr!=NULL)
+ dtype->f->setitem(obj, optr, arr);
+ Py_XDECREF(arr);
+ }
+ }
+ else if (PyDescr_HASFIELDS(dtype)) {
+ PyObject *key, *value, *title=NULL;
+ PyArray_Descr *new;
+ int offset;
+ Py_ssize_t pos=0;
+ while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
+ if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
+ &title)) return;
+ _fillobject(optr + offset, obj, new);
}
+ }
+ else {
+ PyObject **temp;
+ Py_XINCREF(obj);
+ temp = (PyObject **)optr;
+ *temp = obj;
+ return;
+ }
}
/* Assumes contiguous */
@@ -5696,240 +5695,240 @@ _fillobject(char *optr, PyObject *obj, PyArray_Descr *dtype)
static void
PyArray_FillObjectArray(PyArrayObject *arr, PyObject *obj)
{
- intp i,n;
+ intp i,n;
+ n = PyArray_SIZE(arr);
+ if (arr->descr->type_num == PyArray_OBJECT) {
+ PyObject **optr;
+ optr = (PyObject **)(arr->data);
n = PyArray_SIZE(arr);
- if (arr->descr->type_num == PyArray_OBJECT) {
- PyObject **optr;
- optr = (PyObject **)(arr->data);
- n = PyArray_SIZE(arr);
- if (obj == NULL) {
- for (i=0; i<n; i++) {
- *optr++ = NULL;
- }
- }
- else {
- for (i=0; i<n; i++) {
- Py_INCREF(obj);
- *optr++ = obj;
- }
- }
+ if (obj == NULL) {
+ for (i=0; i<n; i++) {
+ *optr++ = NULL;
+ }
}
else {
- char *optr;
- optr = arr->data;
- for (i=0; i<n; i++) {
- _fillobject(optr, obj, arr->descr);
- optr += arr->descr->elsize;
- }
+ for (i=0; i<n; i++) {
+ Py_INCREF(obj);
+ *optr++ = obj;
+ }
+ }
+ }
+ else {
+ char *optr;
+ optr = arr->data;
+ for (i=0; i<n; i++) {
+ _fillobject(optr, obj, arr->descr);
+ optr += arr->descr->elsize;
}
+ }
}
/*OBJECT_API*/
static int
PyArray_FillWithScalar(PyArrayObject *arr, PyObject *obj)
{
- PyObject *newarr;
- int itemsize, swap;
- void *fromptr;
- PyArray_Descr *descr;
- intp size;
- PyArray_CopySwapFunc *copyswap;
-
- itemsize = arr->descr->elsize;
- if (PyArray_ISOBJECT(arr)) {
- fromptr = &obj;
- swap = 0;
- newarr = NULL;
+ PyObject *newarr;
+ int itemsize, swap;
+ void *fromptr;
+ PyArray_Descr *descr;
+ intp size;
+ PyArray_CopySwapFunc *copyswap;
+
+ itemsize = arr->descr->elsize;
+ if (PyArray_ISOBJECT(arr)) {
+ fromptr = &obj;
+ swap = 0;
+ newarr = NULL;
+ }
+ else {
+ descr = PyArray_DESCR(arr);
+ Py_INCREF(descr);
+ newarr = PyArray_FromAny(obj, descr, 0,0, ALIGNED, NULL);
+ if (newarr == NULL) return -1;
+ fromptr = PyArray_DATA(newarr);
+ swap=!PyArray_ISNOTSWAPPED(arr);
+ }
+ size=PyArray_SIZE(arr);
+ copyswap = arr->descr->f->copyswap;
+ if (PyArray_ISONESEGMENT(arr)) {
+ char *toptr=PyArray_DATA(arr);
+ PyArray_FillWithScalarFunc* fillwithscalar =
+ arr->descr->f->fillwithscalar;
+ if (fillwithscalar && PyArray_ISALIGNED(arr)) {
+ copyswap(fromptr, NULL, swap, newarr);
+ fillwithscalar(toptr, size, fromptr, arr);
}
else {
- descr = PyArray_DESCR(arr);
- Py_INCREF(descr);
- newarr = PyArray_FromAny(obj, descr, 0,0, ALIGNED, NULL);
- if (newarr == NULL) return -1;
- fromptr = PyArray_DATA(newarr);
- swap=!PyArray_ISNOTSWAPPED(arr);
- }
- size=PyArray_SIZE(arr);
- copyswap = arr->descr->f->copyswap;
- if (PyArray_ISONESEGMENT(arr)) {
- char *toptr=PyArray_DATA(arr);
- PyArray_FillWithScalarFunc* fillwithscalar =
- arr->descr->f->fillwithscalar;
- if (fillwithscalar && PyArray_ISALIGNED(arr)) {
- copyswap(fromptr, NULL, swap, newarr);
- fillwithscalar(toptr, size, fromptr, arr);
- }
- else {
- while (size--) {
- copyswap(toptr, fromptr, swap, arr);
- toptr += itemsize;
- }
- }
+ while (size--) {
+ copyswap(toptr, fromptr, swap, arr);
+ toptr += itemsize;
+ }
}
- else {
- PyArrayIterObject *iter;
+ }
+ else {
+ PyArrayIterObject *iter;
- iter = (PyArrayIterObject *)\
- PyArray_IterNew((PyObject *)arr);
- if (iter == NULL) {
- Py_XDECREF(newarr);
- return -1;
- }
- while(size--) {
- copyswap(iter->dataptr, fromptr, swap, arr);
- PyArray_ITER_NEXT(iter);
- }
- Py_DECREF(iter);
+ iter = (PyArrayIterObject *)\
+ PyArray_IterNew((PyObject *)arr);
+ if (iter == NULL) {
+ Py_XDECREF(newarr);
+ return -1;
}
- Py_XDECREF(newarr);
- return 0;
+ while(size--) {
+ copyswap(iter->dataptr, fromptr, swap, arr);
+ PyArray_ITER_NEXT(iter);
+ }
+ Py_DECREF(iter);
+ }
+ Py_XDECREF(newarr);
+ return 0;
}
static PyObject *
array_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"shape", "dtype", "buffer",
- "offset", "strides",
- "order", NULL};
- PyArray_Descr *descr=NULL;
- int itemsize;
- PyArray_Dims dims = {NULL, 0};
- PyArray_Dims strides = {NULL, 0};
- PyArray_Chunk buffer;
- longlong offset=0;
- NPY_ORDER order=PyArray_CORDER;
- int fortran = 0;
- PyArrayObject *ret;
-
- buffer.ptr = NULL;
- /* Usually called with shape and type
- but can also be called with buffer, strides, and swapped info
- */
-
- /* For now, let's just use this to create an empty, contiguous
- array of a specific type and shape.
- */
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&LO&O&",
- kwlist, PyArray_IntpConverter,
- &dims,
- PyArray_DescrConverter,
- &descr,
- PyArray_BufferConverter,
- &buffer,
- &offset,
- &PyArray_IntpConverter,
- &strides,
- &PyArray_OrderConverter,
- &order))
- goto fail;
-
- if (order == PyArray_FORTRANORDER) fortran = 1;
-
- if (descr == NULL)
- descr = PyArray_DescrFromType(PyArray_DEFAULT);
-
- itemsize = descr->elsize;
+ static char *kwlist[] = {"shape", "dtype", "buffer",
+ "offset", "strides",
+ "order", NULL};
+ PyArray_Descr *descr=NULL;
+ int itemsize;
+ PyArray_Dims dims = {NULL, 0};
+ PyArray_Dims strides = {NULL, 0};
+ PyArray_Chunk buffer;
+ longlong offset=0;
+ NPY_ORDER order=PyArray_CORDER;
+ int fortran = 0;
+ PyArrayObject *ret;
+
+ buffer.ptr = NULL;
+ /* Usually called with shape and type
+ but can also be called with buffer, strides, and swapped info
+ */
+
+ /* For now, let's just use this to create an empty, contiguous
+ array of a specific type and shape.
+ */
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&LO&O&",
+ kwlist, PyArray_IntpConverter,
+ &dims,
+ PyArray_DescrConverter,
+ &descr,
+ PyArray_BufferConverter,
+ &buffer,
+ &offset,
+ &PyArray_IntpConverter,
+ &strides,
+ &PyArray_OrderConverter,
+ &order))
+ goto fail;
+
+ if (order == PyArray_FORTRANORDER) fortran = 1;
+
+ if (descr == NULL)
+ descr = PyArray_DescrFromType(PyArray_DEFAULT);
+
+ itemsize = descr->elsize;
+
+ if (itemsize == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "data-type with unspecified variable length");
+ goto fail;
+ }
- if (itemsize == 0) {
- PyErr_SetString(PyExc_ValueError,
- "data-type with unspecified variable length");
- goto fail;
+ if (strides.ptr != NULL) {
+ intp nb, off;
+ if (strides.len != dims.len) {
+ PyErr_SetString(PyExc_ValueError,
+ "strides, if given, must be " \
+ "the same length as shape");
+ goto fail;
}
- if (strides.ptr != NULL) {
- intp nb, off;
- if (strides.len != dims.len) {
- PyErr_SetString(PyExc_ValueError,
- "strides, if given, must be " \
- "the same length as shape");
- goto fail;
- }
-
- if (buffer.ptr == NULL) {
- nb = 0;
- off = 0;
- }
- else {
- nb = buffer.len;
- off = (intp) offset;
- }
+ if (buffer.ptr == NULL) {
+ nb = 0;
+ off = 0;
+ }
+ else {
+ nb = buffer.len;
+ off = (intp) offset;
+ }
- if (!PyArray_CheckStrides(itemsize, dims.len,
- nb, off,
- dims.ptr, strides.ptr)) {
- PyErr_SetString(PyExc_ValueError,
- "strides is incompatible " \
- "with shape of requested " \
- "array and size of buffer");
- goto fail;
- }
+ if (!PyArray_CheckStrides(itemsize, dims.len,
+ nb, off,
+ dims.ptr, strides.ptr)) {
+ PyErr_SetString(PyExc_ValueError,
+ "strides is incompatible " \
+ "with shape of requested " \
+ "array and size of buffer");
+ goto fail;
}
+ }
- if (buffer.ptr == NULL) {
- ret = (PyArrayObject *) \
- PyArray_NewFromDescr(subtype, descr,
- (int)dims.len,
- dims.ptr,
- strides.ptr, NULL, fortran, NULL);
- if (ret == NULL) {descr=NULL;goto fail;}
- if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT)) {
- /* place Py_None in object positions */
- PyArray_FillObjectArray(ret, Py_None);
- if (PyErr_Occurred()) {
- descr=NULL;
- goto fail;
- }
- }
+ if (buffer.ptr == NULL) {
+ ret = (PyArrayObject *) \
+ PyArray_NewFromDescr(subtype, descr,
+ (int)dims.len,
+ dims.ptr,
+ strides.ptr, NULL, fortran, NULL);
+ if (ret == NULL) {descr=NULL;goto fail;}
+ if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT)) {
+ /* place Py_None in object positions */
+ PyArray_FillObjectArray(ret, Py_None);
+ if (PyErr_Occurred()) {
+ descr=NULL;
+ goto fail;
+ }
}
- else { /* buffer given -- use it */
- if (dims.len == 1 && dims.ptr[0] == -1) {
- dims.ptr[0] = (buffer.len-(intp)offset) / itemsize;
- }
- else if ((strides.ptr == NULL) && \
- (buffer.len < ((intp)itemsize)* \
- PyArray_MultiplyList(dims.ptr, dims.len))) {
- PyErr_SetString(PyExc_TypeError,
- "buffer is too small for " \
- "requested array");
- goto fail;
- }
- /* get writeable and aligned */
- if (fortran) buffer.flags |= FORTRAN;
- ret = (PyArrayObject *)\
- PyArray_NewFromDescr(subtype, descr,
- dims.len, dims.ptr,
- strides.ptr,
- offset + (char *)buffer.ptr,
- buffer.flags, NULL);
- if (ret == NULL) {descr=NULL; goto fail;}
- PyArray_UpdateFlags(ret, UPDATE_ALL);
- ret->base = buffer.base;
- Py_INCREF(buffer.base);
- }
-
- PyDimMem_FREE(dims.ptr);
- if (strides.ptr) PyDimMem_FREE(strides.ptr);
- return (PyObject *)ret;
+ }
+ else { /* buffer given -- use it */
+ if (dims.len == 1 && dims.ptr[0] == -1) {
+ dims.ptr[0] = (buffer.len-(intp)offset) / itemsize;
+ }
+ else if ((strides.ptr == NULL) && \
+ (buffer.len < ((intp)itemsize)* \
+ PyArray_MultiplyList(dims.ptr, dims.len))) {
+ PyErr_SetString(PyExc_TypeError,
+ "buffer is too small for " \
+ "requested array");
+ goto fail;
+ }
+ /* get writeable and aligned */
+ if (fortran) buffer.flags |= FORTRAN;
+ ret = (PyArrayObject *)\
+ PyArray_NewFromDescr(subtype, descr,
+ dims.len, dims.ptr,
+ strides.ptr,
+ offset + (char *)buffer.ptr,
+ buffer.flags, NULL);
+ if (ret == NULL) {descr=NULL; goto fail;}
+ PyArray_UpdateFlags(ret, UPDATE_ALL);
+ ret->base = buffer.base;
+ Py_INCREF(buffer.base);
+ }
+
+ PyDimMem_FREE(dims.ptr);
+ if (strides.ptr) PyDimMem_FREE(strides.ptr);
+ return (PyObject *)ret;
fail:
- Py_XDECREF(descr);
- if (dims.ptr) PyDimMem_FREE(dims.ptr);
- if (strides.ptr) PyDimMem_FREE(strides.ptr);
- return NULL;
+ Py_XDECREF(descr);
+ if (dims.ptr) PyDimMem_FREE(dims.ptr);
+ if (strides.ptr) PyDimMem_FREE(strides.ptr);
+ return NULL;
}
static PyObject *
array_iter(PyArrayObject *arr)
{
- if (arr->nd == 0) {
- PyErr_SetString(PyExc_TypeError,
- "iteration over a 0-d array");
- return NULL;
- }
- return PySeqIter_New((PyObject *)arr);
+ if (arr->nd == 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "iteration over a 0-d array");
+ return NULL;
+ }
+ return PySeqIter_New((PyObject *)arr);
}
@@ -5938,124 +5937,124 @@ array_iter(PyArrayObject *arr)
static PyObject *
array_ndim_get(PyArrayObject *self)
{
- return PyInt_FromLong(self->nd);
+ return PyInt_FromLong(self->nd);
}
static PyObject *
array_flags_get(PyArrayObject *self)
{
- return PyArray_NewFlagsObject((PyObject *)self);
+ return PyArray_NewFlagsObject((PyObject *)self);
}
static PyObject *
array_shape_get(PyArrayObject *self)
{
- return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
+ return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
}
static int
array_shape_set(PyArrayObject *self, PyObject *val)
{
- int nd;
- PyObject *ret;
-
- /* Assumes C-order */
- ret = PyArray_Reshape(self, val);
- if (ret == NULL) return -1;
- if (PyArray_DATA(ret) != PyArray_DATA(self)) {
- Py_DECREF(ret);
- PyErr_SetString(PyExc_AttributeError,
- "incompatible shape for a non-contiguous "\
- "array");
- return -1;
- }
+ int nd;
+ PyObject *ret;
- /* Free old dimensions and strides */
- PyDimMem_FREE(self->dimensions);
- nd = PyArray_NDIM(ret);
- self->nd = nd;
- if (nd > 0) { /* create new dimensions and strides */
- self->dimensions = PyDimMem_NEW(2*nd);
- if (self->dimensions == NULL) {
- Py_DECREF(ret);
- PyErr_SetString(PyExc_MemoryError,"");
- return -1;
- }
- self->strides = self->dimensions + nd;
- memcpy(self->dimensions, PyArray_DIMS(ret),
- nd*sizeof(intp));
- memcpy(self->strides, PyArray_STRIDES(ret),
- nd*sizeof(intp));
- }
- else {self->dimensions=NULL; self->strides=NULL;}
+ /* Assumes C-order */
+ ret = PyArray_Reshape(self, val);
+ if (ret == NULL) return -1;
+ if (PyArray_DATA(ret) != PyArray_DATA(self)) {
Py_DECREF(ret);
- PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
- return 0;
+ PyErr_SetString(PyExc_AttributeError,
+ "incompatible shape for a non-contiguous "\
+ "array");
+ return -1;
+ }
+
+ /* Free old dimensions and strides */
+ PyDimMem_FREE(self->dimensions);
+ nd = PyArray_NDIM(ret);
+ self->nd = nd;
+ if (nd > 0) { /* create new dimensions and strides */
+ self->dimensions = PyDimMem_NEW(2*nd);
+ if (self->dimensions == NULL) {
+ Py_DECREF(ret);
+ PyErr_SetString(PyExc_MemoryError,"");
+ return -1;
+ }
+ self->strides = self->dimensions + nd;
+ memcpy(self->dimensions, PyArray_DIMS(ret),
+ nd*sizeof(intp));
+ memcpy(self->strides, PyArray_STRIDES(ret),
+ nd*sizeof(intp));
+ }
+ else {self->dimensions=NULL; self->strides=NULL;}
+ Py_DECREF(ret);
+ PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
+ return 0;
}
static PyObject *
array_strides_get(PyArrayObject *self)
{
- return PyArray_IntTupleFromIntp(self->nd, self->strides);
+ return PyArray_IntTupleFromIntp(self->nd, self->strides);
}
static int
array_strides_set(PyArrayObject *self, PyObject *obj)
{
- PyArray_Dims newstrides = {NULL, 0};
- PyArrayObject *new;
- intp numbytes=0;
- intp offset=0;
- Py_ssize_t buf_len;
- char *buf;
-
- if (!PyArray_IntpConverter(obj, &newstrides) || \
- newstrides.ptr == NULL) {
- PyErr_SetString(PyExc_TypeError, "invalid strides");
- return -1;
- }
- if (newstrides.len != self->nd) {
- PyErr_Format(PyExc_ValueError, "strides must be " \
- " same length as shape (%d)", self->nd);
- goto fail;
- }
- new = self;
- while(new->base && PyArray_Check(new->base)) {
- new = (PyArrayObject *)(new->base);
- }
- /* Get the available memory through the buffer
- interface on new->base or if that fails
- from the current new */
- if (new->base && PyObject_AsReadBuffer(new->base,
- (const void **)&buf,
- &buf_len) >= 0) {
- offset = self->data - buf;
- numbytes = buf_len + offset;
- }
- else {
- PyErr_Clear();
- numbytes = PyArray_MultiplyList(new->dimensions,
- new->nd)*new->descr->elsize;
- offset = self->data - new->data;
- }
+ PyArray_Dims newstrides = {NULL, 0};
+ PyArrayObject *new;
+ intp numbytes=0;
+ intp offset=0;
+ Py_ssize_t buf_len;
+ char *buf;
- if (!PyArray_CheckStrides(self->descr->elsize, self->nd, numbytes,
- offset,
- self->dimensions, newstrides.ptr)) {
- PyErr_SetString(PyExc_ValueError, "strides is not "\
- "compatible with available memory");
- goto fail;
- }
- memcpy(self->strides, newstrides.ptr, sizeof(intp)*newstrides.len);
- PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
- PyDimMem_FREE(newstrides.ptr);
- return 0;
+ if (!PyArray_IntpConverter(obj, &newstrides) || \
+ newstrides.ptr == NULL) {
+ PyErr_SetString(PyExc_TypeError, "invalid strides");
+ return -1;
+ }
+ if (newstrides.len != self->nd) {
+ PyErr_Format(PyExc_ValueError, "strides must be " \
+ " same length as shape (%d)", self->nd);
+ goto fail;
+ }
+ new = self;
+ while(new->base && PyArray_Check(new->base)) {
+ new = (PyArrayObject *)(new->base);
+ }
+ /* Get the available memory through the buffer
+ interface on new->base or if that fails
+ from the current new */
+ if (new->base && PyObject_AsReadBuffer(new->base,
+ (const void **)&buf,
+ &buf_len) >= 0) {
+ offset = self->data - buf;
+ numbytes = buf_len + offset;
+ }
+ else {
+ PyErr_Clear();
+ numbytes = PyArray_MultiplyList(new->dimensions,
+ new->nd)*new->descr->elsize;
+ offset = self->data - new->data;
+ }
+
+ if (!PyArray_CheckStrides(self->descr->elsize, self->nd, numbytes,
+ offset,
+ self->dimensions, newstrides.ptr)) {
+ PyErr_SetString(PyExc_ValueError, "strides is not "\
+ "compatible with available memory");
+ goto fail;
+ }
+ memcpy(self->strides, newstrides.ptr, sizeof(intp)*newstrides.len);
+ PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
+ PyDimMem_FREE(newstrides.ptr);
+ return 0;
fail:
- PyDimMem_FREE(newstrides.ptr);
- return -1;
+ PyDimMem_FREE(newstrides.ptr);
+ return -1;
}
@@ -6063,10 +6062,10 @@ array_strides_set(PyArrayObject *self, PyObject *obj)
static PyObject *
array_priority_get(PyArrayObject *self)
{
- if (PyArray_CheckExact(self))
- return PyFloat_FromDouble(PyArray_PRIORITY);
- else
- return PyFloat_FromDouble(PyArray_SUBTYPE_PRIORITY);
+ if (PyArray_CheckExact(self))
+ return PyFloat_FromDouble(PyArray_PRIORITY);
+ else
+ return PyFloat_FromDouble(PyArray_SUBTYPE_PRIORITY);
}
static PyObject *arraydescr_protocol_typestr_get(PyArray_Descr *);
@@ -6074,14 +6073,14 @@ static PyObject *arraydescr_protocol_typestr_get(PyArray_Descr *);
static PyObject *
array_typestr_get(PyArrayObject *self)
{
- return arraydescr_protocol_typestr_get(self->descr);
+ return arraydescr_protocol_typestr_get(self->descr);
}
static PyObject *
array_descr_get(PyArrayObject *self)
{
- Py_INCREF(self->descr);
- return (PyObject *)self->descr;
+ Py_INCREF(self->descr);
+ return (PyObject *)self->descr;
}
static PyObject *arraydescr_protocol_descr_get(PyArray_Descr *self);
@@ -6089,32 +6088,32 @@ static PyObject *arraydescr_protocol_descr_get(PyArray_Descr *self);
static PyObject *
array_protocol_descr_get(PyArrayObject *self)
{
- PyObject *res;
- PyObject *dobj;
+ PyObject *res;
+ PyObject *dobj;
- res = arraydescr_protocol_descr_get(self->descr);
- if (res) return res;
- PyErr_Clear();
+ res = arraydescr_protocol_descr_get(self->descr);
+ if (res) return res;
+ PyErr_Clear();
- /* get default */
- dobj = PyTuple_New(2);
- if (dobj == NULL) return NULL;
- PyTuple_SET_ITEM(dobj, 0, PyString_FromString(""));
- PyTuple_SET_ITEM(dobj, 1, array_typestr_get(self));
- res = PyList_New(1);
- if (res == NULL) {Py_DECREF(dobj); return NULL;}
- PyList_SET_ITEM(res, 0, dobj);
- return res;
+ /* get default */
+ dobj = PyTuple_New(2);
+ if (dobj == NULL) return NULL;
+ PyTuple_SET_ITEM(dobj, 0, PyString_FromString(""));
+ PyTuple_SET_ITEM(dobj, 1, array_typestr_get(self));
+ res = PyList_New(1);
+ if (res == NULL) {Py_DECREF(dobj); return NULL;}
+ PyList_SET_ITEM(res, 0, dobj);
+ return res;
}
static PyObject *
array_protocol_strides_get(PyArrayObject *self)
{
- if PyArray_ISCONTIGUOUS(self) {
- Py_INCREF(Py_None);
- return Py_None;
+ if PyArray_ISCONTIGUOUS(self) {
+ Py_INCREF(Py_None);
+ return Py_None;
}
- return PyArray_IntTupleFromIntp(self->nd, self->strides);
+ return PyArray_IntTupleFromIntp(self->nd, self->strides);
}
@@ -6122,326 +6121,326 @@ array_protocol_strides_get(PyArrayObject *self)
static PyObject *
array_dataptr_get(PyArrayObject *self)
{
- return Py_BuildValue("NO",
- PyLong_FromVoidPtr(self->data),
- (self->flags & WRITEABLE ? Py_False :
- Py_True));
+ return Py_BuildValue("NO",
+ PyLong_FromVoidPtr(self->data),
+ (self->flags & WRITEABLE ? Py_False :
+ Py_True));
}
static PyObject *
array_ctypes_get(PyArrayObject *self)
{
- PyObject *_numpy_internal;
- PyObject *ret;
- _numpy_internal = PyImport_ImportModule("numpy.core._internal");
- if (_numpy_internal == NULL) return NULL;
- ret = PyObject_CallMethod(_numpy_internal, "_ctypes",
- "ON", self,
- PyLong_FromVoidPtr(self->data));
- Py_DECREF(_numpy_internal);
- return ret;
+ PyObject *_numpy_internal;
+ PyObject *ret;
+ _numpy_internal = PyImport_ImportModule("numpy.core._internal");
+ if (_numpy_internal == NULL) return NULL;
+ ret = PyObject_CallMethod(_numpy_internal, "_ctypes",
+ "ON", self,
+ PyLong_FromVoidPtr(self->data));
+ Py_DECREF(_numpy_internal);
+ return ret;
}
static PyObject *
array_interface_get(PyArrayObject *self)
{
- PyObject *dict;
- PyObject *obj;
- dict = PyDict_New();
- if (dict == NULL) return NULL;
+ PyObject *dict;
+ PyObject *obj;
+ dict = PyDict_New();
+ if (dict == NULL) return NULL;
- /* dataptr */
- obj = array_dataptr_get(self);
- PyDict_SetItemString(dict, "data", obj);
- Py_DECREF(obj);
+ /* dataptr */
+ obj = array_dataptr_get(self);
+ PyDict_SetItemString(dict, "data", obj);
+ Py_DECREF(obj);
- obj = array_protocol_strides_get(self);
- PyDict_SetItemString(dict, "strides", obj);
- Py_DECREF(obj);
+ obj = array_protocol_strides_get(self);
+ PyDict_SetItemString(dict, "strides", obj);
+ Py_DECREF(obj);
- obj = array_protocol_descr_get(self);
- PyDict_SetItemString(dict, "descr", obj);
- Py_DECREF(obj);
+ obj = array_protocol_descr_get(self);
+ PyDict_SetItemString(dict, "descr", obj);
+ Py_DECREF(obj);
- obj = arraydescr_protocol_typestr_get(self->descr);
- PyDict_SetItemString(dict, "typestr", obj);
- Py_DECREF(obj);
+ obj = arraydescr_protocol_typestr_get(self->descr);
+ PyDict_SetItemString(dict, "typestr", obj);
+ Py_DECREF(obj);
- obj = array_shape_get(self);
- PyDict_SetItemString(dict, "shape", obj);
- Py_DECREF(obj);
+ obj = array_shape_get(self);
+ PyDict_SetItemString(dict, "shape", obj);
+ Py_DECREF(obj);
- obj = PyInt_FromLong(3);
- PyDict_SetItemString(dict, "version", obj);
- Py_DECREF(obj);
+ obj = PyInt_FromLong(3);
+ PyDict_SetItemString(dict, "version", obj);
+ Py_DECREF(obj);
- return dict;
+ return dict;
}
static PyObject *
array_data_get(PyArrayObject *self)
{
- intp nbytes;
- if (!(PyArray_ISONESEGMENT(self))) {
- PyErr_SetString(PyExc_AttributeError, "cannot get single-"\
- "segment buffer for discontiguous array");
- return NULL;
- }
- nbytes = PyArray_NBYTES(self);
- if PyArray_ISWRITEABLE(self)
- return PyBuffer_FromReadWriteObject((PyObject *)self, 0,
- (int) nbytes);
- else
- return PyBuffer_FromObject((PyObject *)self, 0, (int) nbytes);
+ intp nbytes;
+ if (!(PyArray_ISONESEGMENT(self))) {
+ PyErr_SetString(PyExc_AttributeError, "cannot get single-"\
+ "segment buffer for discontiguous array");
+ return NULL;
+ }
+ nbytes = PyArray_NBYTES(self);
+ if PyArray_ISWRITEABLE(self)
+ return PyBuffer_FromReadWriteObject((PyObject *)self, 0,
+ (int) nbytes);
+ else
+ return PyBuffer_FromObject((PyObject *)self, 0, (int) nbytes);
}
static int
array_data_set(PyArrayObject *self, PyObject *op)
{
- void *buf;
- Py_ssize_t buf_len;
- int writeable=1;
-
- if (PyObject_AsWriteBuffer(op, &buf, &buf_len) < 0) {
- writeable = 0;
- if (PyObject_AsReadBuffer(op, (const void **)&buf,
- &buf_len) < 0) {
- PyErr_SetString(PyExc_AttributeError,
- "object does not have single-segment " \
- "buffer interface");
- return -1;
- }
- }
- if (!PyArray_ISONESEGMENT(self)) {
- PyErr_SetString(PyExc_AttributeError, "cannot set single-" \
- "segment buffer for discontiguous array");
- return -1;
- }
- if (PyArray_NBYTES(self) > buf_len) {
- PyErr_SetString(PyExc_AttributeError,
- "not enough data for array");
- return -1;
- }
- if (self->flags & OWNDATA) {
- PyArray_XDECREF(self);
- PyDataMem_FREE(self->data);
+ void *buf;
+ Py_ssize_t buf_len;
+ int writeable=1;
+
+ if (PyObject_AsWriteBuffer(op, &buf, &buf_len) < 0) {
+ writeable = 0;
+ if (PyObject_AsReadBuffer(op, (const void **)&buf,
+ &buf_len) < 0) {
+ PyErr_SetString(PyExc_AttributeError,
+ "object does not have single-segment " \
+ "buffer interface");
+ return -1;
}
- if (self->base) {
- if (self->flags & UPDATEIFCOPY) {
- ((PyArrayObject *)self->base)->flags |= WRITEABLE;
- self->flags &= ~UPDATEIFCOPY;
- }
- Py_DECREF(self->base);
+ }
+ if (!PyArray_ISONESEGMENT(self)) {
+ PyErr_SetString(PyExc_AttributeError, "cannot set single-" \
+ "segment buffer for discontiguous array");
+ return -1;
+ }
+ if (PyArray_NBYTES(self) > buf_len) {
+ PyErr_SetString(PyExc_AttributeError,
+ "not enough data for array");
+ return -1;
+ }
+ if (self->flags & OWNDATA) {
+ PyArray_XDECREF(self);
+ PyDataMem_FREE(self->data);
+ }
+ if (self->base) {
+ if (self->flags & UPDATEIFCOPY) {
+ ((PyArrayObject *)self->base)->flags |= WRITEABLE;
+ self->flags &= ~UPDATEIFCOPY;
}
- Py_INCREF(op);
- self->base = op;
- self->data = buf;
- self->flags = CARRAY;
- if (!writeable)
- self->flags &= ~WRITEABLE;
- return 0;
+ Py_DECREF(self->base);
+ }
+ Py_INCREF(op);
+ self->base = op;
+ self->data = buf;
+ self->flags = CARRAY;
+ if (!writeable)
+ self->flags &= ~WRITEABLE;
+ return 0;
}
static PyObject *
array_itemsize_get(PyArrayObject *self)
{
- return PyInt_FromLong((long) self->descr->elsize);
+ return PyInt_FromLong((long) self->descr->elsize);
}
static PyObject *
array_size_get(PyArrayObject *self)
{
- intp size=PyArray_SIZE(self);
+ intp size=PyArray_SIZE(self);
#if SIZEOF_INTP <= SIZEOF_LONG
- return PyInt_FromLong((long) size);
+ return PyInt_FromLong((long) size);
#else
- if (size > MAX_LONG || size < MIN_LONG)
- return PyLong_FromLongLong(size);
- else
- return PyInt_FromLong((long) size);
+ if (size > MAX_LONG || size < MIN_LONG)
+ return PyLong_FromLongLong(size);
+ else
+ return PyInt_FromLong((long) size);
#endif
}
static PyObject *
array_nbytes_get(PyArrayObject *self)
{
- intp nbytes = PyArray_NBYTES(self);
+ intp nbytes = PyArray_NBYTES(self);
#if SIZEOF_INTP <= SIZEOF_LONG
- return PyInt_FromLong((long) nbytes);
+ return PyInt_FromLong((long) nbytes);
#else
- if (nbytes > MAX_LONG || nbytes < MIN_LONG)
- return PyLong_FromLongLong(nbytes);
- else
- return PyInt_FromLong((long) nbytes);
+ if (nbytes > MAX_LONG || nbytes < MIN_LONG)
+ return PyLong_FromLongLong(nbytes);
+ else
+ return PyInt_FromLong((long) nbytes);
#endif
}
/* If the type is changed.
- Also needing change: strides, itemsize
+ Also needing change: strides, itemsize
- Either itemsize is exactly the same
- or the array is single-segment (contiguous or fortran) with
- compatibile dimensions
+ Either itemsize is exactly the same
+ or the array is single-segment (contiguous or fortran) with
+ compatibile dimensions
- The shape and strides will be adjusted in that case as well.
+ The shape and strides will be adjusted in that case as well.
*/
static int
array_descr_set(PyArrayObject *self, PyObject *arg)
{
- PyArray_Descr *newtype=NULL;
- intp newdim;
- int index;
- char *msg = "new type not compatible with array.";
+ PyArray_Descr *newtype=NULL;
+ intp newdim;
+ int index;
+ char *msg = "new type not compatible with array.";
- if (!(PyArray_DescrConverter(arg, &newtype)) ||
- newtype == NULL) {
- PyErr_SetString(PyExc_TypeError, "invalid data-type for array");
- return -1;
- }
- if (PyDataType_FLAGCHK(newtype, NPY_ITEM_HASOBJECT) ||
- PyDataType_FLAGCHK(newtype, NPY_ITEM_IS_POINTER) ||
- PyDataType_FLAGCHK(self->descr, NPY_ITEM_HASOBJECT) ||
- PyDataType_FLAGCHK(self->descr, NPY_ITEM_IS_POINTER)) {
- PyErr_SetString(PyExc_TypeError, \
- "Cannot change data-type for object " \
- "array.");
- Py_DECREF(newtype);
- return -1;
- }
+ if (!(PyArray_DescrConverter(arg, &newtype)) ||
+ newtype == NULL) {
+ PyErr_SetString(PyExc_TypeError, "invalid data-type for array");
+ return -1;
+ }
+ if (PyDataType_FLAGCHK(newtype, NPY_ITEM_HASOBJECT) ||
+ PyDataType_FLAGCHK(newtype, NPY_ITEM_IS_POINTER) ||
+ PyDataType_FLAGCHK(self->descr, NPY_ITEM_HASOBJECT) ||
+ PyDataType_FLAGCHK(self->descr, NPY_ITEM_IS_POINTER)) {
+ PyErr_SetString(PyExc_TypeError, \
+ "Cannot change data-type for object " \
+ "array.");
+ Py_DECREF(newtype);
+ return -1;
+ }
- if (newtype->elsize == 0) {
- PyErr_SetString(PyExc_TypeError,
- "data-type must not be 0-sized");
- Py_DECREF(newtype);
- return -1;
- }
+ if (newtype->elsize == 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "data-type must not be 0-sized");
+ Py_DECREF(newtype);
+ return -1;
+ }
- if ((newtype->elsize != self->descr->elsize) && \
- (self->nd == 0 || !PyArray_ISONESEGMENT(self) || \
- newtype->subarray)) goto fail;
+ if ((newtype->elsize != self->descr->elsize) && \
+ (self->nd == 0 || !PyArray_ISONESEGMENT(self) || \
+ newtype->subarray)) goto fail;
- if (PyArray_ISCONTIGUOUS(self)) index = self->nd - 1;
- else index = 0;
+ if (PyArray_ISCONTIGUOUS(self)) index = self->nd - 1;
+ else index = 0;
- if (newtype->elsize < self->descr->elsize) {
- /* if it is compatible increase the size of the
- dimension at end (or at the front for FORTRAN)
- */
- if (self->descr->elsize % newtype->elsize != 0)
- goto fail;
- newdim = self->descr->elsize / newtype->elsize;
- self->dimensions[index] *= newdim;
- self->strides[index] = newtype->elsize;
- }
-
- else if (newtype->elsize > self->descr->elsize) {
-
- /* Determine if last (or first if FORTRAN) dimension
- is compatible */
-
- newdim = self->dimensions[index] * self->descr->elsize;
- if ((newdim % newtype->elsize) != 0) goto fail;
-
- self->dimensions[index] = newdim / newtype->elsize;
- self->strides[index] = newtype->elsize;
- }
-
- /* fall through -- adjust type*/
-
- Py_DECREF(self->descr);
- if (newtype->subarray) {
- /* create new array object from data and update
- dimensions, strides and descr from it */
- PyArrayObject *temp;
-
- /* We would decref newtype here --- temp will
- steal a reference to it */
- temp = (PyArrayObject *) \
- PyArray_NewFromDescr(&PyArray_Type, newtype, self->nd,
- self->dimensions, self->strides,
- self->data, self->flags, NULL);
- if (temp == NULL) return -1;
- PyDimMem_FREE(self->dimensions);
- self->dimensions = temp->dimensions;
- self->nd = temp->nd;
- self->strides = temp->strides;
- newtype = temp->descr;
- Py_INCREF(temp->descr);
- /* Fool deallocator not to delete these*/
- temp->nd = 0;
- temp->dimensions = NULL;
- Py_DECREF(temp);
- }
+ if (newtype->elsize < self->descr->elsize) {
+ /* if it is compatible increase the size of the
+ dimension at end (or at the front for FORTRAN)
+ */
+ if (self->descr->elsize % newtype->elsize != 0)
+ goto fail;
+ newdim = self->descr->elsize / newtype->elsize;
+ self->dimensions[index] *= newdim;
+ self->strides[index] = newtype->elsize;
+ }
- self->descr = newtype;
- PyArray_UpdateFlags(self, UPDATE_ALL);
+ else if (newtype->elsize > self->descr->elsize) {
- return 0;
+ /* Determine if last (or first if FORTRAN) dimension
+ is compatible */
+
+ newdim = self->dimensions[index] * self->descr->elsize;
+ if ((newdim % newtype->elsize) != 0) goto fail;
+
+ self->dimensions[index] = newdim / newtype->elsize;
+ self->strides[index] = newtype->elsize;
+ }
+
+ /* fall through -- adjust type*/
+
+ Py_DECREF(self->descr);
+ if (newtype->subarray) {
+ /* create new array object from data and update
+ dimensions, strides and descr from it */
+ PyArrayObject *temp;
+
+ /* We would decref newtype here --- temp will
+ steal a reference to it */
+ temp = (PyArrayObject *) \
+ PyArray_NewFromDescr(&PyArray_Type, newtype, self->nd,
+ self->dimensions, self->strides,
+ self->data, self->flags, NULL);
+ if (temp == NULL) return -1;
+ PyDimMem_FREE(self->dimensions);
+ self->dimensions = temp->dimensions;
+ self->nd = temp->nd;
+ self->strides = temp->strides;
+ newtype = temp->descr;
+ Py_INCREF(temp->descr);
+ /* Fool deallocator not to delete these*/
+ temp->nd = 0;
+ temp->dimensions = NULL;
+ Py_DECREF(temp);
+ }
+
+ self->descr = newtype;
+ PyArray_UpdateFlags(self, UPDATE_ALL);
+
+ return 0;
fail:
- PyErr_SetString(PyExc_ValueError, msg);
- Py_DECREF(newtype);
- return -1;
+ PyErr_SetString(PyExc_ValueError, msg);
+ Py_DECREF(newtype);
+ return -1;
}
static PyObject *
array_struct_get(PyArrayObject *self)
{
- PyArrayInterface *inter;
-
- inter = (PyArrayInterface *)_pya_malloc(sizeof(PyArrayInterface));
- if (inter==NULL) return PyErr_NoMemory();
- inter->two = 2;
- inter->nd = self->nd;
- inter->typekind = self->descr->kind;
- inter->itemsize = self->descr->elsize;
- inter->flags = self->flags;
- /* reset unused flags */
- inter->flags &= ~(UPDATEIFCOPY | OWNDATA);
- if (PyArray_ISNOTSWAPPED(self)) inter->flags |= NOTSWAPPED;
- /* Copy shape and strides over since these can be reset
- when the array is "reshaped".
- */
- if (self->nd > 0) {
- inter->shape = (intp *)_pya_malloc(2*sizeof(intp)*self->nd);
- if (inter->shape == NULL) {
- _pya_free(inter);
- return PyErr_NoMemory();
- }
- inter->strides = inter->shape + self->nd;
- memcpy(inter->shape, self->dimensions, sizeof(intp)*self->nd);
- memcpy(inter->strides, self->strides, sizeof(intp)*self->nd);
- }
- else {
- inter->shape = NULL;
- inter->strides = NULL;
- }
- inter->data = self->data;
- if (self->descr->names) {
- inter->descr = arraydescr_protocol_descr_get(self->descr);
- if (inter->descr == NULL) PyErr_Clear();
- else inter->flags &= ARR_HAS_DESCR;
- }
- else inter->descr = NULL;
- Py_INCREF(self);
- return PyCObject_FromVoidPtrAndDesc(inter, self, gentype_struct_free);
+ PyArrayInterface *inter;
+
+ inter = (PyArrayInterface *)_pya_malloc(sizeof(PyArrayInterface));
+ if (inter==NULL) return PyErr_NoMemory();
+ inter->two = 2;
+ inter->nd = self->nd;
+ inter->typekind = self->descr->kind;
+ inter->itemsize = self->descr->elsize;
+ inter->flags = self->flags;
+ /* reset unused flags */
+ inter->flags &= ~(UPDATEIFCOPY | OWNDATA);
+ if (PyArray_ISNOTSWAPPED(self)) inter->flags |= NOTSWAPPED;
+ /* Copy shape and strides over since these can be reset
+ when the array is "reshaped".
+ */
+ if (self->nd > 0) {
+ inter->shape = (intp *)_pya_malloc(2*sizeof(intp)*self->nd);
+ if (inter->shape == NULL) {
+ _pya_free(inter);
+ return PyErr_NoMemory();
+ }
+ inter->strides = inter->shape + self->nd;
+ memcpy(inter->shape, self->dimensions, sizeof(intp)*self->nd);
+ memcpy(inter->strides, self->strides, sizeof(intp)*self->nd);
+ }
+ else {
+ inter->shape = NULL;
+ inter->strides = NULL;
+ }
+ inter->data = self->data;
+ if (self->descr->names) {
+ inter->descr = arraydescr_protocol_descr_get(self->descr);
+ if (inter->descr == NULL) PyErr_Clear();
+ else inter->flags &= ARR_HAS_DESCR;
+ }
+ else inter->descr = NULL;
+ Py_INCREF(self);
+ return PyCObject_FromVoidPtrAndDesc(inter, self, gentype_struct_free);
}
static PyObject *
array_base_get(PyArrayObject *self)
{
- if (self->base == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else {
- Py_INCREF(self->base);
- return self->base;
- }
+ if (self->base == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else {
+ Py_INCREF(self->base);
+ return self->base;
+ }
}
/* Create a view of a complex array with an equivalent data-type
@@ -6451,197 +6450,197 @@ array_base_get(PyArrayObject *self)
static PyArrayObject *
_get_part(PyArrayObject *self, int imag)
{
- PyArray_Descr *type;
- PyArrayObject *ret;
- int offset;
+ PyArray_Descr *type;
+ PyArrayObject *ret;
+ int offset;
- type = PyArray_DescrFromType(self->descr->type_num -
- PyArray_NUM_FLOATTYPE);
- offset = (imag ? type->elsize : 0);
-
- if (!PyArray_ISNBO(self->descr->byteorder)) {
- PyArray_Descr *new;
- new = PyArray_DescrNew(type);
- new->byteorder = self->descr->byteorder;
- Py_DECREF(type);
- type = new;
- }
- ret = (PyArrayObject *) \
- PyArray_NewFromDescr(self->ob_type,
- type,
- self->nd,
- self->dimensions,
- self->strides,
- self->data + offset,
- self->flags, (PyObject *)self);
- if (ret == NULL) return NULL;
- ret->flags &= ~CONTIGUOUS;
- ret->flags &= ~FORTRAN;
- Py_INCREF(self);
- ret->base = (PyObject *)self;
- return ret;
+ type = PyArray_DescrFromType(self->descr->type_num -
+ PyArray_NUM_FLOATTYPE);
+ offset = (imag ? type->elsize : 0);
+
+ if (!PyArray_ISNBO(self->descr->byteorder)) {
+ PyArray_Descr *new;
+ new = PyArray_DescrNew(type);
+ new->byteorder = self->descr->byteorder;
+ Py_DECREF(type);
+ type = new;
+ }
+ ret = (PyArrayObject *) \
+ PyArray_NewFromDescr(self->ob_type,
+ type,
+ self->nd,
+ self->dimensions,
+ self->strides,
+ self->data + offset,
+ self->flags, (PyObject *)self);
+ if (ret == NULL) return NULL;
+ ret->flags &= ~CONTIGUOUS;
+ ret->flags &= ~FORTRAN;
+ Py_INCREF(self);
+ ret->base = (PyObject *)self;
+ return ret;
}
static PyObject *
array_real_get(PyArrayObject *self)
{
- PyArrayObject *ret;
+ PyArrayObject *ret;
- if (PyArray_ISCOMPLEX(self)) {
- ret = _get_part(self, 0);
- return (PyObject *)ret;
- }
- else {
- Py_INCREF(self);
- return (PyObject *)self;
- }
+ if (PyArray_ISCOMPLEX(self)) {
+ ret = _get_part(self, 0);
+ return (PyObject *)ret;
+ }
+ else {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
}
static int
array_real_set(PyArrayObject *self, PyObject *val)
{
- PyArrayObject *ret;
- PyArrayObject *new;
- int rint;
+ PyArrayObject *ret;
+ PyArrayObject *new;
+ int rint;
- if (PyArray_ISCOMPLEX(self)) {
- ret = _get_part(self, 0);
- if (ret == NULL) return -1;
- }
- else {
- Py_INCREF(self);
- ret = self;
- }
- new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL);
- if (new == NULL) {Py_DECREF(ret); return -1;}
- rint = PyArray_MoveInto(ret, new);
- Py_DECREF(ret);
- Py_DECREF(new);
- return rint;
+ if (PyArray_ISCOMPLEX(self)) {
+ ret = _get_part(self, 0);
+ if (ret == NULL) return -1;
+ }
+ else {
+ Py_INCREF(self);
+ ret = self;
+ }
+ new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL);
+ if (new == NULL) {Py_DECREF(ret); return -1;}
+ rint = PyArray_MoveInto(ret, new);
+ Py_DECREF(ret);
+ Py_DECREF(new);
+ return rint;
}
static PyObject *
array_imag_get(PyArrayObject *self)
{
- PyArrayObject *ret;
- PyArray_Descr *type;
+ PyArrayObject *ret;
+ PyArray_Descr *type;
- if (PyArray_ISCOMPLEX(self)) {
- ret = _get_part(self, 1);
- return (PyObject *) ret;
- }
+ if (PyArray_ISCOMPLEX(self)) {
+ ret = _get_part(self, 1);
+ return (PyObject *) ret;
+ }
+ else {
+ type = self->descr;
+ Py_INCREF(type);
+ ret = (PyArrayObject *)PyArray_Zeros(self->nd,
+ self->dimensions,
+ type,
+ PyArray_ISFORTRAN(self));
+ ret->flags &= ~WRITEABLE;
+ if (PyArray_CheckExact(self))
+ return (PyObject *)ret;
else {
- type = self->descr;
- Py_INCREF(type);
- ret = (PyArrayObject *)PyArray_Zeros(self->nd,
- self->dimensions,
- type,
- PyArray_ISFORTRAN(self));
- ret->flags &= ~WRITEABLE;
- if (PyArray_CheckExact(self))
- return (PyObject *)ret;
- else {
- PyObject *newret;
- newret = PyArray_View(ret, NULL, self->ob_type);
- Py_DECREF(ret);
- return newret;
- }
+ PyObject *newret;
+ newret = PyArray_View(ret, NULL, self->ob_type);
+ Py_DECREF(ret);
+ return newret;
}
+ }
}
static int
array_imag_set(PyArrayObject *self, PyObject *val)
{
- if (PyArray_ISCOMPLEX(self)) {
- PyArrayObject *ret;
- PyArrayObject *new;
- int rint;
-
- ret = _get_part(self, 1);
- if (ret == NULL) return -1;
- new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL);
- if (new == NULL) {Py_DECREF(ret); return -1;}
- rint = PyArray_MoveInto(ret, new);
- Py_DECREF(ret);
- Py_DECREF(new);
- return rint;
- }
- else {
- PyErr_SetString(PyExc_TypeError, "array does not have "\
- "imaginary part to set");
- return -1;
- }
+ if (PyArray_ISCOMPLEX(self)) {
+ PyArrayObject *ret;
+ PyArrayObject *new;
+ int rint;
+
+ ret = _get_part(self, 1);
+ if (ret == NULL) return -1;
+ new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL);
+ if (new == NULL) {Py_DECREF(ret); return -1;}
+ rint = PyArray_MoveInto(ret, new);
+ Py_DECREF(ret);
+ Py_DECREF(new);
+ return rint;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "array does not have "\
+ "imaginary part to set");
+ return -1;
+ }
}
static PyObject *
array_flat_get(PyArrayObject *self)
{
- return PyArray_IterNew((PyObject *)self);
+ return PyArray_IterNew((PyObject *)self);
}
static int
array_flat_set(PyArrayObject *self, PyObject *val)
{
- PyObject *arr=NULL;
- int retval = -1;
- PyArrayIterObject *selfit=NULL, *arrit=NULL;
- PyArray_Descr *typecode;
- int swap;
- PyArray_CopySwapFunc *copyswap;
-
- typecode = self->descr;
- Py_INCREF(typecode);
- arr = PyArray_FromAny(val, typecode,
- 0, 0, FORCECAST | FORTRAN_IF(self), NULL);
- if (arr == NULL) return -1;
- arrit = (PyArrayIterObject *)PyArray_IterNew(arr);
- if (arrit == NULL) goto exit;
- selfit = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
- if (selfit == NULL) goto exit;
-
- if (arrit->size == 0) {retval = 0; goto exit;}
-
- swap = PyArray_ISNOTSWAPPED(self) != PyArray_ISNOTSWAPPED(arr);
- copyswap = self->descr->f->copyswap;
- if (PyDataType_REFCHK(self->descr)) {
- while(selfit->index < selfit->size) {
- PyArray_Item_XDECREF(selfit->dataptr, self->descr);
- PyArray_Item_INCREF(arrit->dataptr, PyArray_DESCR(arr));
- memmove(selfit->dataptr, arrit->dataptr,
- sizeof(PyObject **));
- if (swap)
- copyswap(selfit->dataptr, NULL, swap, self);
- PyArray_ITER_NEXT(selfit);
- PyArray_ITER_NEXT(arrit);
- if (arrit->index == arrit->size)
- PyArray_ITER_RESET(arrit);
- }
- retval = 0;
- goto exit;
- }
-
+ PyObject *arr=NULL;
+ int retval = -1;
+ PyArrayIterObject *selfit=NULL, *arrit=NULL;
+ PyArray_Descr *typecode;
+ int swap;
+ PyArray_CopySwapFunc *copyswap;
+
+ typecode = self->descr;
+ Py_INCREF(typecode);
+ arr = PyArray_FromAny(val, typecode,
+ 0, 0, FORCECAST | FORTRAN_IF(self), NULL);
+ if (arr == NULL) return -1;
+ arrit = (PyArrayIterObject *)PyArray_IterNew(arr);
+ if (arrit == NULL) goto exit;
+ selfit = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
+ if (selfit == NULL) goto exit;
+
+ if (arrit->size == 0) {retval = 0; goto exit;}
+
+ swap = PyArray_ISNOTSWAPPED(self) != PyArray_ISNOTSWAPPED(arr);
+ copyswap = self->descr->f->copyswap;
+ if (PyDataType_REFCHK(self->descr)) {
while(selfit->index < selfit->size) {
- memmove(selfit->dataptr, arrit->dataptr, self->descr->elsize);
- if (swap)
- copyswap(selfit->dataptr, NULL, swap, self);
- PyArray_ITER_NEXT(selfit);
- PyArray_ITER_NEXT(arrit);
- if (arrit->index == arrit->size)
- PyArray_ITER_RESET(arrit);
+ PyArray_Item_XDECREF(selfit->dataptr, self->descr);
+ PyArray_Item_INCREF(arrit->dataptr, PyArray_DESCR(arr));
+ memmove(selfit->dataptr, arrit->dataptr,
+ sizeof(PyObject **));
+ if (swap)
+ copyswap(selfit->dataptr, NULL, swap, self);
+ PyArray_ITER_NEXT(selfit);
+ PyArray_ITER_NEXT(arrit);
+ if (arrit->index == arrit->size)
+ PyArray_ITER_RESET(arrit);
}
retval = 0;
+ goto exit;
+ }
+
+ while(selfit->index < selfit->size) {
+ memmove(selfit->dataptr, arrit->dataptr, self->descr->elsize);
+ if (swap)
+ copyswap(selfit->dataptr, NULL, swap, self);
+ PyArray_ITER_NEXT(selfit);
+ PyArray_ITER_NEXT(arrit);
+ if (arrit->index == arrit->size)
+ PyArray_ITER_RESET(arrit);
+ }
+ retval = 0;
exit:
- Py_XDECREF(selfit);
- Py_XDECREF(arrit);
- Py_XDECREF(arr);
- return retval;
+ Py_XDECREF(selfit);
+ Py_XDECREF(arrit);
+ Py_XDECREF(arr);
+ return retval;
}
static PyObject *
array_transpose_get(PyArrayObject *self)
{
- return PyArray_Transpose(self, NULL);
+ return PyArray_Transpose(self, NULL);
}
/* If this is None, no function call is made
@@ -6650,76 +6649,76 @@ array_transpose_get(PyArrayObject *self)
static PyObject *
array_finalize_get(PyArrayObject *self)
{
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyGetSetDef array_getsetlist[] = {
- {"ndim",
- (getter)array_ndim_get,
- NULL, NULL},
- {"flags",
- (getter)array_flags_get,
- NULL, NULL},
- {"shape",
- (getter)array_shape_get,
- (setter)array_shape_set,
- NULL},
- {"strides",
- (getter)array_strides_get,
- (setter)array_strides_set,
- NULL},
- {"data",
- (getter)array_data_get,
- (setter)array_data_set,
- NULL},
- {"itemsize",
- (getter)array_itemsize_get,
- NULL, NULL},
- {"size",
- (getter)array_size_get,
- NULL, NULL},
- {"nbytes",
- (getter)array_nbytes_get,
- NULL, NULL},
- {"base",
- (getter)array_base_get,
- NULL, NULL},
- {"dtype",
- (getter)array_descr_get,
- (setter)array_descr_set,
- NULL},
- {"real",
- (getter)array_real_get,
- (setter)array_real_set,
- NULL},
- {"imag",
- (getter)array_imag_get,
- (setter)array_imag_set,
- NULL},
- {"flat",
- (getter)array_flat_get,
- (setter)array_flat_set,
- NULL},
- {"ctypes",
- (getter)array_ctypes_get,
- NULL, NULL},
- {"T",
- (getter)array_transpose_get,
- NULL, NULL},
- {"__array_interface__",
- (getter)array_interface_get,
- NULL, NULL},
- {"__array_struct__",
- (getter)array_struct_get,
- NULL, NULL},
- {"__array_priority__",
- (getter)array_priority_get,
- NULL, NULL},
- {"__array_finalize__",
- (getter)array_finalize_get,
- NULL, NULL},
- {NULL, NULL, NULL, NULL}, /* Sentinel */
+ {"ndim",
+ (getter)array_ndim_get,
+ NULL, NULL},
+ {"flags",
+ (getter)array_flags_get,
+ NULL, NULL},
+ {"shape",
+ (getter)array_shape_get,
+ (setter)array_shape_set,
+ NULL},
+ {"strides",
+ (getter)array_strides_get,
+ (setter)array_strides_set,
+ NULL},
+ {"data",
+ (getter)array_data_get,
+ (setter)array_data_set,
+ NULL},
+ {"itemsize",
+ (getter)array_itemsize_get,
+ NULL, NULL},
+ {"size",
+ (getter)array_size_get,
+ NULL, NULL},
+ {"nbytes",
+ (getter)array_nbytes_get,
+ NULL, NULL},
+ {"base",
+ (getter)array_base_get,
+ NULL, NULL},
+ {"dtype",
+ (getter)array_descr_get,
+ (setter)array_descr_set,
+ NULL},
+ {"real",
+ (getter)array_real_get,
+ (setter)array_real_set,
+ NULL},
+ {"imag",
+ (getter)array_imag_get,
+ (setter)array_imag_set,
+ NULL},
+ {"flat",
+ (getter)array_flat_get,
+ (setter)array_flat_set,
+ NULL},
+ {"ctypes",
+ (getter)array_ctypes_get,
+ NULL, NULL},
+ {"T",
+ (getter)array_transpose_get,
+ NULL, NULL},
+ {"__array_interface__",
+ (getter)array_interface_get,
+ NULL, NULL},
+ {"__array_struct__",
+ (getter)array_struct_get,
+ NULL, NULL},
+ {"__array_priority__",
+ (getter)array_priority_get,
+ NULL, NULL},
+ {"__array_finalize__",
+ (getter)array_finalize_get,
+ NULL, NULL},
+ {NULL, NULL, NULL, NULL}, /* Sentinel */
};
/****************** end of attribute get and set routines *******************/
@@ -6728,73 +6727,73 @@ static PyGetSetDef array_getsetlist[] = {
static PyObject *
array_alloc(PyTypeObject *type, Py_ssize_t nitems)
{
- PyObject *obj;
- /* nitems will always be 0 */
- obj = (PyObject *)_pya_malloc(sizeof(PyArrayObject));
- PyObject_Init(obj, type);
- return obj;
+ PyObject *obj;
+ /* nitems will always be 0 */
+ obj = (PyObject *)_pya_malloc(sizeof(PyArrayObject));
+ PyObject_Init(obj, type);
+ return obj;
}
static PyTypeObject PyArray_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "numpy.ndarray", /*tp_name*/
- sizeof(PyArrayObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)array_dealloc, /*tp_dealloc */
- (printfunc)NULL, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- (cmpfunc)0, /*tp_compare*/
- (reprfunc)array_repr, /*tp_repr*/
- &array_as_number, /*tp_as_number*/
- &array_as_sequence, /*tp_as_sequence*/
- &array_as_mapping, /*tp_as_mapping*/
- (hashfunc)0, /*tp_hash*/
- (ternaryfunc)0, /*tp_call*/
- (reprfunc)array_str, /*tp_str*/
-
- (getattrofunc)0, /*tp_getattro*/
- (setattrofunc)0, /*tp_setattro*/
- &array_as_buffer, /*tp_as_buffer*/
- (Py_TPFLAGS_DEFAULT
- | Py_TPFLAGS_BASETYPE
- | Py_TPFLAGS_CHECKTYPES), /*tp_flags*/
- /*Documentation string */
- 0, /*tp_doc*/
-
- (traverseproc)0, /*tp_traverse */
- (inquiry)0, /*tp_clear */
- (richcmpfunc)array_richcompare, /*tp_richcompare */
- offsetof(PyArrayObject, weakreflist), /*tp_weaklistoffset */
-
- /* Iterator support (use standard) */
-
- (getiterfunc)array_iter, /* tp_iter */
- (iternextfunc)0, /* tp_iternext */
-
- /* Sub-classing (new-style object) support */
-
- array_methods, /* tp_methods */
- 0, /* tp_members */
- array_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)0, /* tp_init */
- array_alloc, /* tp_alloc */
- (newfunc)array_new, /* tp_new */
- 0, /* tp_free */
- 0, /* tp_is_gc */
- 0, /* tp_bases */
- 0, /* tp_mro */
- 0, /* tp_cache */
- 0, /* tp_subclasses */
- 0 /* tp_weaklist */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "numpy.ndarray", /*tp_name*/
+ sizeof(PyArrayObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)array_dealloc, /*tp_dealloc */
+ (printfunc)NULL, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ (cmpfunc)0, /*tp_compare*/
+ (reprfunc)array_repr, /*tp_repr*/
+ &array_as_number, /*tp_as_number*/
+ &array_as_sequence, /*tp_as_sequence*/
+ &array_as_mapping, /*tp_as_mapping*/
+ (hashfunc)0, /*tp_hash*/
+ (ternaryfunc)0, /*tp_call*/
+ (reprfunc)array_str, /*tp_str*/
+
+ (getattrofunc)0, /*tp_getattro*/
+ (setattrofunc)0, /*tp_setattro*/
+ &array_as_buffer, /*tp_as_buffer*/
+ (Py_TPFLAGS_DEFAULT
+ | Py_TPFLAGS_BASETYPE
+ | Py_TPFLAGS_CHECKTYPES), /*tp_flags*/
+ /*Documentation string */
+ 0, /*tp_doc*/
+
+ (traverseproc)0, /*tp_traverse */
+ (inquiry)0, /*tp_clear */
+ (richcmpfunc)array_richcompare, /*tp_richcompare */
+ offsetof(PyArrayObject, weakreflist), /*tp_weaklistoffset */
+
+ /* Iterator support (use standard) */
+
+ (getiterfunc)array_iter, /* tp_iter */
+ (iternextfunc)0, /* tp_iternext */
+
+ /* Sub-classing (new-style object) support */
+
+ array_methods, /* tp_methods */
+ 0, /* tp_members */
+ array_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)0, /* tp_init */
+ array_alloc, /* tp_alloc */
+ (newfunc)array_new, /* tp_new */
+ 0, /* tp_free */
+ 0, /* tp_is_gc */
+ 0, /* tp_bases */
+ 0, /* tp_mro */
+ 0, /* tp_cache */
+ 0, /* tp_subclasses */
+ 0 /* tp_weaklist */
};
/* The rest of this code is to build the right kind of array from a python */
@@ -6803,78 +6802,78 @@ static PyTypeObject PyArray_Type = {
static int
discover_depth(PyObject *s, int max, int stop_at_string, int stop_at_tuple)
{
- int d=0;
- PyObject *e;
-
- if(max < 1) return -1;
-
- if(! PySequence_Check(s) || PyInstance_Check(s) || \
- PySequence_Length(s) < 0) {
- PyErr_Clear(); return 0;
- }
- if (PyArray_Check(s))
- return PyArray_NDIM(s);
- if (PyArray_IsScalar(s, Generic)) return 0;
- if (PyString_Check(s) || PyBuffer_Check(s) || PyUnicode_Check(s))
- return stop_at_string ? 0:1;
- if (stop_at_tuple && PyTuple_Check(s)) return 0;
- if ((e=PyObject_GetAttrString(s, "__array_struct__")) != NULL) {
- d = -1;
- if (PyCObject_Check(e)) {
- PyArrayInterface *inter;
- inter = (PyArrayInterface *)PyCObject_AsVoidPtr(e);
- if (inter->two == 2) {
- d = inter->nd;
- }
- }
- Py_DECREF(e);
- if (d > -1) return d;
- }
- else PyErr_Clear();
- if ((e=PyObject_GetAttrString(s, "__array_interface__")) != NULL) {
- d = -1;
- if (PyDict_Check(e)) {
- PyObject *new;
- new = PyDict_GetItemString(e, "shape");
- if (new && PyTuple_Check(new))
- d = PyTuple_GET_SIZE(new);
- }
- Py_DECREF(e);
- if (d>-1) return d;
- }
- else PyErr_Clear();
+ int d=0;
+ PyObject *e;
+
+ if(max < 1) return -1;
- if (PySequence_Length(s) == 0)
- return 1;
- if ((e=PySequence_GetItem(s,0)) == NULL) return -1;
- if(e!=s) {
- d=discover_depth(e, max-1, stop_at_string, stop_at_tuple);
- if(d >= 0) d++;
+ if(! PySequence_Check(s) || PyInstance_Check(s) || \
+ PySequence_Length(s) < 0) {
+ PyErr_Clear(); return 0;
+ }
+ if (PyArray_Check(s))
+ return PyArray_NDIM(s);
+ if (PyArray_IsScalar(s, Generic)) return 0;
+ if (PyString_Check(s) || PyBuffer_Check(s) || PyUnicode_Check(s))
+ return stop_at_string ? 0:1;
+ if (stop_at_tuple && PyTuple_Check(s)) return 0;
+ if ((e=PyObject_GetAttrString(s, "__array_struct__")) != NULL) {
+ d = -1;
+ if (PyCObject_Check(e)) {
+ PyArrayInterface *inter;
+ inter = (PyArrayInterface *)PyCObject_AsVoidPtr(e);
+ if (inter->two == 2) {
+ d = inter->nd;
+ }
+ }
+ Py_DECREF(e);
+ if (d > -1) return d;
+ }
+ else PyErr_Clear();
+ if ((e=PyObject_GetAttrString(s, "__array_interface__")) != NULL) {
+ d = -1;
+ if (PyDict_Check(e)) {
+ PyObject *new;
+ new = PyDict_GetItemString(e, "shape");
+ if (new && PyTuple_Check(new))
+ d = PyTuple_GET_SIZE(new);
}
Py_DECREF(e);
- return d;
+ if (d>-1) return d;
+ }
+ else PyErr_Clear();
+
+ if (PySequence_Length(s) == 0)
+ return 1;
+ if ((e=PySequence_GetItem(s,0)) == NULL) return -1;
+ if(e!=s) {
+ d=discover_depth(e, max-1, stop_at_string, stop_at_tuple);
+ if(d >= 0) d++;
+ }
+ Py_DECREF(e);
+ return d;
}
static int
discover_itemsize(PyObject *s, int nd, int *itemsize)
{
- int n, r, i;
- PyObject *e;
+ int n, r, i;
+ PyObject *e;
- n = PyObject_Length(s);
+ n = PyObject_Length(s);
- if ((nd == 0) || PyString_Check(s) || \
- PyUnicode_Check(s) || PyBuffer_Check(s)) {
- *itemsize = MAX(*itemsize, n);
- return 0;
- }
- for (i=0; i<n; i++) {
- if ((e=PySequence_GetItem(s,i))==NULL) return -1;
- r=discover_itemsize(e,nd-1,itemsize);
- Py_DECREF(e);
- if (r == -1) return -1;
- }
+ if ((nd == 0) || PyString_Check(s) || \
+ PyUnicode_Check(s) || PyBuffer_Check(s)) {
+ *itemsize = MAX(*itemsize, n);
return 0;
+ }
+ for (i=0; i<n; i++) {
+ if ((e=PySequence_GetItem(s,i))==NULL) return -1;
+ r=discover_itemsize(e,nd-1,itemsize);
+ Py_DECREF(e);
+ if (r == -1) return -1;
+ }
+ return 0;
}
/* Take an arbitrary object known to represent
@@ -6884,30 +6883,30 @@ discover_itemsize(PyObject *s, int nd, int *itemsize)
static int
discover_dimensions(PyObject *s, int nd, intp *d, int check_it)
{
- PyObject *e;
- int r, n, i, n_lower;
-
- n=PyObject_Length(s);
- *d = n;
- if(*d < 0) return -1;
- if(nd <= 1) return 0;
- n_lower = 0;
- for(i=0; i<n; i++) {
- if ((e=PySequence_GetItem(s,i)) == NULL) return -1;
- r=discover_dimensions(e,nd-1,d+1,check_it);
- Py_DECREF(e);
-
- if (r == -1) return -1;
- if (check_it && n_lower != 0 && n_lower != d[1]) {
- PyErr_SetString(PyExc_ValueError,
- "inconsistent shape in sequence");
- return -1;
- }
- if (d[1] > n_lower) n_lower = d[1];
+ PyObject *e;
+ int r, n, i, n_lower;
+
+ n=PyObject_Length(s);
+ *d = n;
+ if(*d < 0) return -1;
+ if(nd <= 1) return 0;
+ n_lower = 0;
+ for(i=0; i<n; i++) {
+ if ((e=PySequence_GetItem(s,i)) == NULL) return -1;
+ r=discover_dimensions(e,nd-1,d+1,check_it);
+ Py_DECREF(e);
+
+ if (r == -1) return -1;
+ if (check_it && n_lower != 0 && n_lower != d[1]) {
+ PyErr_SetString(PyExc_ValueError,
+ "inconsistent shape in sequence");
+ return -1;
}
- d[1] = n_lower;
+ if (d[1] > n_lower) n_lower = d[1];
+ }
+ d[1] = n_lower;
- return 0;
+ return 0;
}
/* new reference */
@@ -6916,62 +6915,62 @@ discover_dimensions(PyObject *s, int nd, intp *d, int check_it)
static PyArray_Descr *
_array_small_type(PyArray_Descr *chktype, PyArray_Descr* mintype)
{
- PyArray_Descr *outtype;
- int outtype_num, save_num;
+ PyArray_Descr *outtype;
+ int outtype_num, save_num;
- if (PyArray_EquivTypes(chktype, mintype)) {
- Py_INCREF(mintype);
- return mintype;
- }
+ if (PyArray_EquivTypes(chktype, mintype)) {
+ Py_INCREF(mintype);
+ return mintype;
+ }
- if (chktype->type_num > mintype->type_num)
- outtype_num = chktype->type_num;
+ if (chktype->type_num > mintype->type_num)
+ outtype_num = chktype->type_num;
+ else {
+ if (PyDataType_ISOBJECT(chktype) && \
+ PyDataType_ISSTRING(mintype)) {
+ return PyArray_DescrFromType(NPY_OBJECT);
+ }
else {
- if (PyDataType_ISOBJECT(chktype) && \
- PyDataType_ISSTRING(mintype)) {
- return PyArray_DescrFromType(NPY_OBJECT);
- }
- else {
- outtype_num = mintype->type_num;
- }
+ outtype_num = mintype->type_num;
}
+ }
- save_num = outtype_num;
- while(outtype_num < PyArray_NTYPES &&
- !(PyArray_CanCastSafely(chktype->type_num, outtype_num)
- && PyArray_CanCastSafely(mintype->type_num, outtype_num)))
- outtype_num++;
- if (outtype_num == PyArray_NTYPES) {
- outtype = PyArray_DescrFromType(save_num);
+ save_num = outtype_num;
+ while(outtype_num < PyArray_NTYPES &&
+ !(PyArray_CanCastSafely(chktype->type_num, outtype_num)
+ && PyArray_CanCastSafely(mintype->type_num, outtype_num)))
+ outtype_num++;
+ if (outtype_num == PyArray_NTYPES) {
+ outtype = PyArray_DescrFromType(save_num);
+ }
+ else {
+ outtype = PyArray_DescrFromType(outtype_num);
+ }
+ if (PyTypeNum_ISEXTENDED(outtype->type_num)) {
+ int testsize = outtype->elsize;
+ register int chksize, minsize;
+ chksize = chktype->elsize;
+ minsize = mintype->elsize;
+ /* Handle string->unicode case separately
+ because string itemsize is 4* as large */
+ if (outtype->type_num == PyArray_UNICODE &&
+ mintype->type_num == PyArray_STRING) {
+ testsize = MAX(chksize, 4*minsize);
}
else {
- outtype = PyArray_DescrFromType(outtype_num);
- }
- if (PyTypeNum_ISEXTENDED(outtype->type_num)) {
- int testsize = outtype->elsize;
- register int chksize, minsize;
- chksize = chktype->elsize;
- minsize = mintype->elsize;
- /* Handle string->unicode case separately
- because string itemsize is 4* as large */
- if (outtype->type_num == PyArray_UNICODE &&
- mintype->type_num == PyArray_STRING) {
- testsize = MAX(chksize, 4*minsize);
- }
- else {
- testsize = MAX(chksize, minsize);
- }
- if (testsize != outtype->elsize) {
- PyArray_DESCR_REPLACE(outtype);
- outtype->elsize = testsize;
- Py_XDECREF(outtype->fields);
- outtype->fields = NULL;
- Py_XDECREF(outtype->names);
- outtype->names = NULL;
- }
+ testsize = MAX(chksize, minsize);
+ }
+ if (testsize != outtype->elsize) {
+ PyArray_DESCR_REPLACE(outtype);
+ outtype->elsize = testsize;
+ Py_XDECREF(outtype->fields);
+ outtype->fields = NULL;
+ Py_XDECREF(outtype->names);
+ outtype->names = NULL;
}
- return outtype;
+ }
+ return outtype;
}
static PyArray_Descr *
@@ -6979,26 +6978,26 @@ _array_find_python_scalar_type(PyObject *op)
{
if (PyFloat_Check(op)) {
return PyArray_DescrFromType(PyArray_DOUBLE);
- }
+ }
else if (PyComplex_Check(op)) {
- return PyArray_DescrFromType(PyArray_CDOUBLE);
- }
+ return PyArray_DescrFromType(PyArray_CDOUBLE);
+ }
else if (PyInt_Check(op)) {
- /* bools are a subclass of int */
- if (PyBool_Check(op)) {
- return PyArray_DescrFromType(PyArray_BOOL);
- } else {
- return PyArray_DescrFromType(PyArray_LONG);
- }
- }
+ /* bools are a subclass of int */
+ if (PyBool_Check(op)) {
+ return PyArray_DescrFromType(PyArray_BOOL);
+ } else {
+ return PyArray_DescrFromType(PyArray_LONG);
+ }
+ }
else if (PyLong_Check(op)) {
- /* if integer can fit into a longlong then return that
- */
- if ((PyLong_AsLongLong(op) == -1) && PyErr_Occurred()) {
- PyErr_Clear();
- return PyArray_DescrFromType(PyArray_OBJECT);
- }
- return PyArray_DescrFromType(PyArray_LONGLONG);
+ /* if integer can fit into a longlong then return that
+ */
+ if ((PyLong_AsLongLong(op) == -1) && PyErr_Occurred()) {
+ PyErr_Clear();
+ return PyArray_DescrFromType(PyArray_OBJECT);
+ }
+ return PyArray_DescrFromType(PyArray_LONGLONG);
}
return NULL;
}
@@ -7006,23 +7005,23 @@ _array_find_python_scalar_type(PyObject *op)
static PyArray_Descr *
_use_default_type(PyObject *op)
{
- int typenum, l;
- PyObject *type;
-
- typenum = -1;
- l = 0;
- type = (PyObject *)op->ob_type;
- while (l < PyArray_NUMUSERTYPES) {
- if (type == (PyObject *)(userdescrs[l]->typeobj)) {
- typenum = l + PyArray_USERDEF;
- break;
- }
- l++;
- }
- if (typenum == -1) {
- typenum = PyArray_OBJECT;
+ int typenum, l;
+ PyObject *type;
+
+ typenum = -1;
+ l = 0;
+ type = (PyObject *)op->ob_type;
+ while (l < PyArray_NUMUSERTYPES) {
+ if (type == (PyObject *)(userdescrs[l]->typeobj)) {
+ typenum = l + PyArray_USERDEF;
+ break;
}
- return PyArray_DescrFromType(typenum);
+ l++;
+ }
+ if (typenum == -1) {
+ typenum = PyArray_OBJECT;
+ }
+ return PyArray_DescrFromType(typenum);
}
@@ -7038,208 +7037,208 @@ _use_default_type(PyObject *op)
static PyArray_Descr *
_array_find_type(PyObject *op, PyArray_Descr *minitype, int max)
{
- int l;
- PyObject *ip;
- PyArray_Descr *chktype=NULL;
- PyArray_Descr *outtype;
-
- /* These need to come first because if op already carries
- a descr structure, then we want it to be the result if minitype
- is NULL.
- */
+ int l;
+ PyObject *ip;
+ PyArray_Descr *chktype=NULL;
+ PyArray_Descr *outtype;
+
+ /* These need to come first because if op already carries
+ a descr structure, then we want it to be the result if minitype
+ is NULL.
+ */
+
+ if (PyArray_Check(op)) {
+ chktype = PyArray_DESCR(op);
+ Py_INCREF(chktype);
+ if (minitype == NULL) return chktype;
+ Py_INCREF(minitype);
+ goto finish;
+ }
- if (PyArray_Check(op)) {
- chktype = PyArray_DESCR(op);
- Py_INCREF(chktype);
- if (minitype == NULL) return chktype;
- Py_INCREF(minitype);
- goto finish;
- }
+ if (PyArray_IsScalar(op, Generic)) {
+ chktype = PyArray_DescrFromScalar(op);
+ if (minitype == NULL) return chktype;
+ Py_INCREF(minitype);
+ goto finish;
+ }
- if (PyArray_IsScalar(op, Generic)) {
- chktype = PyArray_DescrFromScalar(op);
- if (minitype == NULL) return chktype;
- Py_INCREF(minitype);
- goto finish;
- }
+ if (minitype == NULL) {
+ minitype = PyArray_DescrFromType(PyArray_BOOL);
+ }
+ else Py_INCREF(minitype);
- if (minitype == NULL) {
- minitype = PyArray_DescrFromType(PyArray_BOOL);
- }
- else Py_INCREF(minitype);
+ if (max < 0) goto deflt;
- if (max < 0) goto deflt;
+ chktype = _array_find_python_scalar_type(op);
+ if (chktype) {
+ goto finish;
+ }
- chktype = _array_find_python_scalar_type(op);
- if (chktype) {
- goto finish;
+ if ((ip=PyObject_GetAttrString(op, "__array_interface__"))!=NULL) {
+ if (PyDict_Check(ip)) {
+ PyObject *new;
+ new = PyDict_GetItemString(ip, "typestr");
+ if (new && PyString_Check(new)) {
+ chktype =_array_typedescr_fromstr \
+ (PyString_AS_STRING(new));
+ }
}
+ Py_DECREF(ip);
+ if (chktype) goto finish;
+ }
+ else PyErr_Clear();
- if ((ip=PyObject_GetAttrString(op, "__array_interface__"))!=NULL) {
- if (PyDict_Check(ip)) {
- PyObject *new;
- new = PyDict_GetItemString(ip, "typestr");
- if (new && PyString_Check(new)) {
- chktype =_array_typedescr_fromstr \
- (PyString_AS_STRING(new));
- }
- }
- Py_DECREF(ip);
- if (chktype) goto finish;
- }
- else PyErr_Clear();
-
- if ((ip=PyObject_GetAttrString(op, "__array_struct__")) != NULL) {
- PyArrayInterface *inter;
- char buf[40];
- if (PyCObject_Check(ip)) {
- inter=(PyArrayInterface *)PyCObject_AsVoidPtr(ip);
- if (inter->two == 2) {
- snprintf(buf, 40, "|%c%d", inter->typekind,
- inter->itemsize);
- chktype = _array_typedescr_fromstr(buf);
- }
- }
- Py_DECREF(ip);
- if (chktype) goto finish;
+ if ((ip=PyObject_GetAttrString(op, "__array_struct__")) != NULL) {
+ PyArrayInterface *inter;
+ char buf[40];
+ if (PyCObject_Check(ip)) {
+ inter=(PyArrayInterface *)PyCObject_AsVoidPtr(ip);
+ if (inter->two == 2) {
+ snprintf(buf, 40, "|%c%d", inter->typekind,
+ inter->itemsize);
+ chktype = _array_typedescr_fromstr(buf);
+ }
}
- else PyErr_Clear();
+ Py_DECREF(ip);
+ if (chktype) goto finish;
+ }
+ else PyErr_Clear();
- if (PyString_Check(op)) {
- chktype = PyArray_DescrNewFromType(PyArray_STRING);
- chktype->elsize = PyString_GET_SIZE(op);
- goto finish;
- }
+ if (PyString_Check(op)) {
+ chktype = PyArray_DescrNewFromType(PyArray_STRING);
+ chktype->elsize = PyString_GET_SIZE(op);
+ goto finish;
+ }
- if (PyUnicode_Check(op)) {
- chktype = PyArray_DescrNewFromType(PyArray_UNICODE);
- chktype->elsize = PyUnicode_GET_DATA_SIZE(op);
+ if (PyUnicode_Check(op)) {
+ chktype = PyArray_DescrNewFromType(PyArray_UNICODE);
+ chktype->elsize = PyUnicode_GET_DATA_SIZE(op);
#ifndef Py_UNICODE_WIDE
- chktype->elsize <<= 1;
+ chktype->elsize <<= 1;
#endif
- goto finish;
- }
+ goto finish;
+ }
- if (PyBuffer_Check(op)) {
- chktype = PyArray_DescrNewFromType(PyArray_VOID);
- chktype->elsize = op->ob_type->tp_as_sequence->sq_length(op);
- PyErr_Clear();
- goto finish;
- }
+ if (PyBuffer_Check(op)) {
+ chktype = PyArray_DescrNewFromType(PyArray_VOID);
+ chktype->elsize = op->ob_type->tp_as_sequence->sq_length(op);
+ PyErr_Clear();
+ goto finish;
+ }
- if (PyObject_HasAttrString(op, "__array__")) {
- ip = PyObject_CallMethod(op, "__array__", NULL);
- if(ip && PyArray_Check(ip)) {
- chktype = PyArray_DESCR(ip);
- Py_INCREF(chktype);
- Py_DECREF(ip);
- goto finish;
- }
- Py_XDECREF(ip);
- if (PyErr_Occurred()) PyErr_Clear();
+ if (PyObject_HasAttrString(op, "__array__")) {
+ ip = PyObject_CallMethod(op, "__array__", NULL);
+ if(ip && PyArray_Check(ip)) {
+ chktype = PyArray_DESCR(ip);
+ Py_INCREF(chktype);
+ Py_DECREF(ip);
+ goto finish;
}
+ Py_XDECREF(ip);
+ if (PyErr_Occurred()) PyErr_Clear();
+ }
- if (PyInstance_Check(op)) goto deflt;
+ if (PyInstance_Check(op)) goto deflt;
- if (PySequence_Check(op)) {
+ if (PySequence_Check(op)) {
- l = PyObject_Length(op);
- if (l < 0 && PyErr_Occurred()) {
- PyErr_Clear();
- goto deflt;
- }
- if (l == 0 && minitype->type_num == PyArray_BOOL) {
- Py_DECREF(minitype);
- minitype = PyArray_DescrFromType(PyArray_DEFAULT);
- }
- while (--l >= 0) {
- PyArray_Descr *newtype;
- ip = PySequence_GetItem(op, l);
- if (ip==NULL) {
- PyErr_Clear();
- goto deflt;
- }
- chktype = _array_find_type(ip, minitype, max-1);
- newtype = _array_small_type(chktype, minitype);
- Py_DECREF(minitype);
- minitype = newtype;
- Py_DECREF(chktype);
- Py_DECREF(ip);
- }
- chktype = minitype;
- Py_INCREF(minitype);
- goto finish;
+ l = PyObject_Length(op);
+ if (l < 0 && PyErr_Occurred()) {
+ PyErr_Clear();
+ goto deflt;
+ }
+ if (l == 0 && minitype->type_num == PyArray_BOOL) {
+ Py_DECREF(minitype);
+ minitype = PyArray_DescrFromType(PyArray_DEFAULT);
}
+ while (--l >= 0) {
+ PyArray_Descr *newtype;
+ ip = PySequence_GetItem(op, l);
+ if (ip==NULL) {
+ PyErr_Clear();
+ goto deflt;
+ }
+ chktype = _array_find_type(ip, minitype, max-1);
+ newtype = _array_small_type(chktype, minitype);
+ Py_DECREF(minitype);
+ minitype = newtype;
+ Py_DECREF(chktype);
+ Py_DECREF(ip);
+ }
+ chktype = minitype;
+ Py_INCREF(minitype);
+ goto finish;
+ }
deflt:
- chktype = _use_default_type(op);
+ chktype = _use_default_type(op);
finish:
- outtype = _array_small_type(chktype, minitype);
- Py_DECREF(chktype);
- Py_DECREF(minitype);
- /* VOID Arrays should not occur by "default"
- unless input was already a VOID */
- if (outtype->type_num == PyArray_VOID && \
- minitype->type_num != PyArray_VOID) {
- Py_DECREF(outtype);
- return PyArray_DescrFromType(PyArray_OBJECT);
- }
- return outtype;
+ outtype = _array_small_type(chktype, minitype);
+ Py_DECREF(chktype);
+ Py_DECREF(minitype);
+ /* VOID Arrays should not occur by "default"
+ unless input was already a VOID */
+ if (outtype->type_num == PyArray_VOID && \
+ minitype->type_num != PyArray_VOID) {
+ Py_DECREF(outtype);
+ return PyArray_DescrFromType(PyArray_OBJECT);
+ }
+ return outtype;
}
/* adapted from Numarray */
-static int
+static int
setArrayFromSequence(PyArrayObject *a, PyObject *s, int dim, intp offset)
{
- Py_ssize_t i, slen = PySequence_Length(s);
- int res = 0;
+ Py_ssize_t i, slen = PySequence_Length(s);
+ int res = 0;
- if (dim > a->nd) {
- PyErr_Format(PyExc_ValueError,
- "setArrayFromSequence: sequence/array dimensions mismatch.");
- return -1;
- }
+ if (dim > a->nd) {
+ PyErr_Format(PyExc_ValueError,
+ "setArrayFromSequence: sequence/array dimensions mismatch.");
+ return -1;
+ }
- if (slen != a->dimensions[dim]) {
- PyErr_Format(PyExc_ValueError,
- "setArrayFromSequence: sequence/array shape mismatch.");
- return -1;
- }
+ if (slen != a->dimensions[dim]) {
+ PyErr_Format(PyExc_ValueError,
+ "setArrayFromSequence: sequence/array shape mismatch.");
+ return -1;
+ }
- for(i=0; i<slen; i++) {
- PyObject *o = PySequence_GetItem(s, i);
- if ((a->nd - dim) > 1) {
- res = setArrayFromSequence(a, o, dim+1, offset);
- }
- else {
- res = a->descr->f->setitem(o, (a->data + offset), a);
- }
- Py_DECREF(o);
- if (res < 0) return res;
- offset += a->strides[dim];
+ for(i=0; i<slen; i++) {
+ PyObject *o = PySequence_GetItem(s, i);
+ if ((a->nd - dim) > 1) {
+ res = setArrayFromSequence(a, o, dim+1, offset);
}
- return 0;
+ else {
+ res = a->descr->f->setitem(o, (a->data + offset), a);
+ }
+ Py_DECREF(o);
+ if (res < 0) return res;
+ offset += a->strides[dim];
+ }
+ return 0;
}
static int
Assign_Array(PyArrayObject *self, PyObject *v)
{
- if (!PySequence_Check(v)) {
- PyErr_SetString(PyExc_ValueError,
- "assignment from non-sequence");
- return -1;
- }
- if (self->nd == 0) {
- PyErr_SetString(PyExc_ValueError,
- "assignment to 0-d array");
- return -1;
- }
+ if (!PySequence_Check(v)) {
+ PyErr_SetString(PyExc_ValueError,
+ "assignment from non-sequence");
+ return -1;
+ }
+ if (self->nd == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "assignment to 0-d array");
+ return -1;
+ }
- return setArrayFromSequence(self, v, 0, 0);
+ return setArrayFromSequence(self, v, 0, 0);
}
/* "Array Scalars don't call this code" */
@@ -7247,42 +7246,42 @@ Assign_Array(PyArrayObject *self, PyObject *v)
static PyObject *
Array_FromPyScalar(PyObject *op, PyArray_Descr *typecode)
{
- PyArrayObject *ret;
- int itemsize;
- int type;
+ PyArrayObject *ret;
+ int itemsize;
+ int type;
- itemsize = typecode->elsize;
- type = typecode->type_num;
+ itemsize = typecode->elsize;
+ type = typecode->type_num;
- if (itemsize == 0 && PyTypeNum_ISEXTENDED(type)) {
- itemsize = PyObject_Length(op);
- if (type == PyArray_UNICODE) itemsize *= 4;
+ if (itemsize == 0 && PyTypeNum_ISEXTENDED(type)) {
+ itemsize = PyObject_Length(op);
+ if (type == PyArray_UNICODE) itemsize *= 4;
- if (itemsize != typecode->elsize) {
- PyArray_DESCR_REPLACE(typecode);
- typecode->elsize = itemsize;
- }
+ if (itemsize != typecode->elsize) {
+ PyArray_DESCR_REPLACE(typecode);
+ typecode->elsize = itemsize;
}
+ }
- ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, typecode,
- 0, NULL,
- NULL, NULL, 0, NULL);
- if (ret == NULL) return NULL;
- if (ret->nd > 0) {
- PyErr_SetString(PyExc_ValueError,
- "shape-mismatch on array construction");
- Py_DECREF(ret);
- return NULL;
- }
+ ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, typecode,
+ 0, NULL,
+ NULL, NULL, 0, NULL);
+ if (ret == NULL) return NULL;
+ if (ret->nd > 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "shape-mismatch on array construction");
+ Py_DECREF(ret);
+ return NULL;
+ }
- ret->descr->f->setitem(op, ret->data, ret);
+ ret->descr->f->setitem(op, ret->data, ret);
- if (PyErr_Occurred()) {
- Py_DECREF(ret);
- return NULL;
- } else {
- return (PyObject *)ret;
- }
+ if (PyErr_Occurred()) {
+ Py_DECREF(ret);
+ return NULL;
+ } else {
+ return (PyObject *)ret;
+ }
}
@@ -7297,253 +7296,253 @@ Array_FromPyScalar(PyObject *op, PyArray_Descr *typecode)
static int
object_depth_and_dimension(PyObject *s, int max, intp *dims)
{
- intp *newdims, *test_dims;
- int nd, test_nd;
- int i, islist;
- intp size;
- PyObject *obj;
+ intp *newdims, *test_dims;
+ int nd, test_nd;
+ int i, islist;
+ intp size;
+ PyObject *obj;
- islist = PyList_Check(s);
- if (!(islist || PyTuple_Check(s)) ||
- ((size = PySequence_Size(s)) == 0))
- return 0;
- if (max < 2) {
- if (max < 1) return 0;
- dims[0] = size;
- return 1;
- }
- newdims = PyDimMem_NEW(2*(max-1));
- test_dims = newdims + (max-1);
- if (islist) obj = PyList_GET_ITEM(s, 0);
- else obj = PyTuple_GET_ITEM(s, 0);
- nd = object_depth_and_dimension(obj, max-1, newdims);
- for (i=1; i<size; i++) {
- if (islist) obj = PyList_GET_ITEM(s, i);
- else obj = PyTuple_GET_ITEM(s, i);
- test_nd = object_depth_and_dimension(obj, max-1, test_dims);
- if ((nd != test_nd) ||
- (!PyArray_CompareLists(newdims, test_dims, nd))) {
- nd = 0;
- break;
- }
+ islist = PyList_Check(s);
+ if (!(islist || PyTuple_Check(s)) ||
+ ((size = PySequence_Size(s)) == 0))
+ return 0;
+ if (max < 2) {
+ if (max < 1) return 0;
+ dims[0] = size;
+ return 1;
+ }
+ newdims = PyDimMem_NEW(2*(max-1));
+ test_dims = newdims + (max-1);
+ if (islist) obj = PyList_GET_ITEM(s, 0);
+ else obj = PyTuple_GET_ITEM(s, 0);
+ nd = object_depth_and_dimension(obj, max-1, newdims);
+ for (i=1; i<size; i++) {
+ if (islist) obj = PyList_GET_ITEM(s, i);
+ else obj = PyTuple_GET_ITEM(s, i);
+ test_nd = object_depth_and_dimension(obj, max-1, test_dims);
+ if ((nd != test_nd) ||
+ (!PyArray_CompareLists(newdims, test_dims, nd))) {
+ nd = 0;
+ break;
}
+ }
- for (i=1; i<=nd; i++) dims[i] = newdims[i-1];
- dims[0] = size;
- PyDimMem_FREE(newdims);
- return nd+1;
+ for (i=1; i<=nd; i++) dims[i] = newdims[i-1];
+ dims[0] = size;
+ PyDimMem_FREE(newdims);
+ return nd+1;
}
static PyObject *
ObjectArray_FromNestedList(PyObject *s, PyArray_Descr *typecode, int fortran)
{
- int nd;
- intp d[MAX_DIMS];
- PyArrayObject *r;
+ int nd;
+ intp d[MAX_DIMS];
+ PyArrayObject *r;
- /* Get the depth and the number of dimensions */
- nd = object_depth_and_dimension(s, MAX_DIMS, d);
- if (nd < 0) return NULL;
+ /* Get the depth and the number of dimensions */
+ nd = object_depth_and_dimension(s, MAX_DIMS, d);
+ if (nd < 0) return NULL;
- if (nd == 0) return Array_FromPyScalar(s, typecode);
+ if (nd == 0) return Array_FromPyScalar(s, typecode);
- r=(PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
- nd, d,
- NULL, NULL,
- fortran, NULL);
+ r=(PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
+ nd, d,
+ NULL, NULL,
+ fortran, NULL);
- if(!r) return NULL;
- if(Assign_Array(r,s) == -1) {
- Py_DECREF(r);
- return NULL;
- }
- return (PyObject*)r;
+ if(!r) return NULL;
+ if(Assign_Array(r,s) == -1) {
+ Py_DECREF(r);
+ return NULL;
+ }
+ return (PyObject*)r;
}
/* isobject means that we are constructing an
object array on-purpose with a nested list.
Only a list is interpreted as a sequence with these rules
- */
+*/
/* steals reference to typecode */
static PyObject *
Array_FromSequence(PyObject *s, PyArray_Descr *typecode, int fortran,
int min_depth, int max_depth)
{
- PyArrayObject *r;
- int nd;
- intp d[MAX_DIMS];
- int stop_at_string;
- int stop_at_tuple;
- int check_it;
- int type = typecode->type_num;
- int itemsize = typecode->elsize;
-
- check_it = (typecode->type != PyArray_CHARLTR);
-
- stop_at_string = ((type == PyArray_OBJECT) ||
- (type == PyArray_STRING &&
- typecode->type == PyArray_STRINGLTR) ||
- (type == PyArray_UNICODE) ||
- (type == PyArray_VOID));
-
- stop_at_tuple = (type == PyArray_VOID && (typecode->names \
- || typecode->subarray));
-
- if (!((nd=discover_depth(s, MAX_DIMS+1, stop_at_string,
- stop_at_tuple)) > 0)) {
- if (nd==0)
- return Array_FromPyScalar(s, typecode);
- PyErr_SetString(PyExc_ValueError,
- "invalid input sequence");
- goto fail;
- }
+ PyArrayObject *r;
+ int nd;
+ intp d[MAX_DIMS];
+ int stop_at_string;
+ int stop_at_tuple;
+ int check_it;
+ int type = typecode->type_num;
+ int itemsize = typecode->elsize;
+
+ check_it = (typecode->type != PyArray_CHARLTR);
+
+ stop_at_string = ((type == PyArray_OBJECT) ||
+ (type == PyArray_STRING &&
+ typecode->type == PyArray_STRINGLTR) ||
+ (type == PyArray_UNICODE) ||
+ (type == PyArray_VOID));
+
+ stop_at_tuple = (type == PyArray_VOID && (typecode->names \
+ || typecode->subarray));
+
+ if (!((nd=discover_depth(s, MAX_DIMS+1, stop_at_string,
+ stop_at_tuple)) > 0)) {
+ if (nd==0)
+ return Array_FromPyScalar(s, typecode);
+ PyErr_SetString(PyExc_ValueError,
+ "invalid input sequence");
+ goto fail;
+ }
- if (max_depth && PyTypeNum_ISOBJECT(type) && (nd > max_depth)) {
- nd = max_depth;
- }
+ if (max_depth && PyTypeNum_ISOBJECT(type) && (nd > max_depth)) {
+ nd = max_depth;
+ }
- if ((max_depth && nd > max_depth) || \
- (min_depth && nd < min_depth)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid number of dimensions");
- goto fail;
- }
+ if ((max_depth && nd > max_depth) || \
+ (min_depth && nd < min_depth)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid number of dimensions");
+ goto fail;
+ }
- if(discover_dimensions(s,nd,d, check_it) == -1) goto fail;
+ if(discover_dimensions(s,nd,d, check_it) == -1) goto fail;
- if (typecode->type == PyArray_CHARLTR && nd > 0 && d[nd-1]==1) {
- nd = nd-1;
- }
+ if (typecode->type == PyArray_CHARLTR && nd > 0 && d[nd-1]==1) {
+ nd = nd-1;
+ }
- if (itemsize == 0 && PyTypeNum_ISEXTENDED(type)) {
- if (discover_itemsize(s, nd, &itemsize) == -1) goto fail;
- if (type == PyArray_UNICODE) itemsize*=4;
- }
+ if (itemsize == 0 && PyTypeNum_ISEXTENDED(type)) {
+ if (discover_itemsize(s, nd, &itemsize) == -1) goto fail;
+ if (type == PyArray_UNICODE) itemsize*=4;
+ }
- if (itemsize != typecode->elsize) {
- PyArray_DESCR_REPLACE(typecode);
- typecode->elsize = itemsize;
- }
+ if (itemsize != typecode->elsize) {
+ PyArray_DESCR_REPLACE(typecode);
+ typecode->elsize = itemsize;
+ }
- r=(PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
- nd, d,
- NULL, NULL,
- fortran, NULL);
+ r=(PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
+ nd, d,
+ NULL, NULL,
+ fortran, NULL);
- if(!r) return NULL;
- if(Assign_Array(r,s) == -1) {
- Py_DECREF(r);
- return NULL;
- }
- return (PyObject*)r;
+ if(!r) return NULL;
+ if(Assign_Array(r,s) == -1) {
+ Py_DECREF(r);
+ return NULL;
+ }
+ return (PyObject*)r;
fail:
- Py_DECREF(typecode);
- return NULL;
+ Py_DECREF(typecode);
+ return NULL;
}
/*OBJECT_API
- Is the typenum valid?
+ Is the typenum valid?
*/
static int
PyArray_ValidType(int type)
{
- PyArray_Descr *descr;
- int res=TRUE;
+ PyArray_Descr *descr;
+ int res=TRUE;
- descr = PyArray_DescrFromType(type);
- if (descr==NULL) res = FALSE;
- Py_DECREF(descr);
- return res;
+ descr = PyArray_DescrFromType(type);
+ if (descr==NULL) res = FALSE;
+ Py_DECREF(descr);
+ return res;
}
/* For backward compatibility */
/* steals reference to at --- cannot be NULL*/
/*OBJECT_API
- Cast an array using typecode structure.
+ Cast an array using typecode structure.
*/
static PyObject *
PyArray_CastToType(PyArrayObject *mp, PyArray_Descr *at, int fortran)
{
- PyObject *out;
- int ret;
- PyArray_Descr *mpd;
-
- mpd = mp->descr;
-
- if (((mpd == at) || ((mpd->type_num == at->type_num) && \
- PyArray_EquivByteorders(mpd->byteorder,\
- at->byteorder) && \
- ((mpd->elsize == at->elsize) || \
- (at->elsize==0)))) && \
- PyArray_ISBEHAVED_RO(mp)) {
- Py_DECREF(at);
- Py_INCREF(mp);
- return (PyObject *)mp;
- }
-
- if (at->elsize == 0) {
- PyArray_DESCR_REPLACE(at);
- if (at == NULL) return NULL;
- if (mpd->type_num == PyArray_STRING && \
- at->type_num == PyArray_UNICODE)
- at->elsize = mpd->elsize << 2;
- if (mpd->type_num == PyArray_UNICODE &&
- at->type_num == PyArray_STRING)
- at->elsize = mpd->elsize >> 2;
- if (at->type_num == PyArray_VOID)
- at->elsize = mpd->elsize;
- }
-
- out = PyArray_NewFromDescr(mp->ob_type, at,
- mp->nd,
- mp->dimensions,
- NULL, NULL,
- fortran,
- (PyObject *)mp);
-
- if (out == NULL) return NULL;
- ret = PyArray_CastTo((PyArrayObject *)out, mp);
- if (ret != -1) return out;
-
- Py_DECREF(out);
- return NULL;
+ PyObject *out;
+ int ret;
+ PyArray_Descr *mpd;
+
+ mpd = mp->descr;
+
+ if (((mpd == at) || ((mpd->type_num == at->type_num) && \
+ PyArray_EquivByteorders(mpd->byteorder,\
+ at->byteorder) && \
+ ((mpd->elsize == at->elsize) || \
+ (at->elsize==0)))) && \
+ PyArray_ISBEHAVED_RO(mp)) {
+ Py_DECREF(at);
+ Py_INCREF(mp);
+ return (PyObject *)mp;
+ }
+
+ if (at->elsize == 0) {
+ PyArray_DESCR_REPLACE(at);
+ if (at == NULL) return NULL;
+ if (mpd->type_num == PyArray_STRING && \
+ at->type_num == PyArray_UNICODE)
+ at->elsize = mpd->elsize << 2;
+ if (mpd->type_num == PyArray_UNICODE &&
+ at->type_num == PyArray_STRING)
+ at->elsize = mpd->elsize >> 2;
+ if (at->type_num == PyArray_VOID)
+ at->elsize = mpd->elsize;
+ }
+
+ out = PyArray_NewFromDescr(mp->ob_type, at,
+ mp->nd,
+ mp->dimensions,
+ NULL, NULL,
+ fortran,
+ (PyObject *)mp);
+
+ if (out == NULL) return NULL;
+ ret = PyArray_CastTo((PyArrayObject *)out, mp);
+ if (ret != -1) return out;
+
+ Py_DECREF(out);
+ return NULL;
}
/*OBJECT_API
- Get a cast function to cast from the input descriptor to the
- output type_number (must be a registered data-type).
- Returns NULL if un-successful.
+ Get a cast function to cast from the input descriptor to the
+ output type_number (must be a registered data-type).
+ Returns NULL if un-successful.
*/
static PyArray_VectorUnaryFunc *
PyArray_GetCastFunc(PyArray_Descr *descr, int type_num)
{
- PyArray_VectorUnaryFunc *castfunc=NULL;
- if (type_num < PyArray_NTYPES) {
- castfunc = descr->f->cast[type_num];
- }
- if (castfunc == NULL) {
- PyObject *obj = descr->f->castdict;
- if (obj && PyDict_Check(obj)) {
- PyObject *key;
- PyObject *cobj;
- key = PyInt_FromLong(type_num);
- cobj = PyDict_GetItem(obj, key);
- Py_DECREF(key);
- if (PyCObject_Check(cobj)) {
- castfunc = PyCObject_AsVoidPtr(cobj);
- }
- }
- if (castfunc) return castfunc;
+ PyArray_VectorUnaryFunc *castfunc=NULL;
+ if (type_num < PyArray_NTYPES) {
+ castfunc = descr->f->cast[type_num];
+ }
+ if (castfunc == NULL) {
+ PyObject *obj = descr->f->castdict;
+ if (obj && PyDict_Check(obj)) {
+ PyObject *key;
+ PyObject *cobj;
+ key = PyInt_FromLong(type_num);
+ cobj = PyDict_GetItem(obj, key);
+ Py_DECREF(key);
+ if (PyCObject_Check(cobj)) {
+ castfunc = PyCObject_AsVoidPtr(cobj);
+ }
}
- else return castfunc;
+ if (castfunc) return castfunc;
+ }
+ else return castfunc;
- PyErr_SetString(PyExc_ValueError,
- "No cast function available.");
- return NULL;
+ PyErr_SetString(PyExc_ValueError,
+ "No cast function available.");
+ return NULL;
}
/* Reference counts:
@@ -7563,129 +7562,129 @@ _strided_buffered_cast(char *dptr, intp dstride, int delsize, int dswap,
PyArray_VectorUnaryFunc *castfunc,
PyArrayObject *dest, PyArrayObject *src)
{
- int i;
- if (N <= bufsize) {
- /* 1. copy input to buffer and swap
- 2. cast input to output
- 3. swap output if necessary and copy from output buffer
- */
- scopyfunc(buffers[1], selsize, sptr, sstride, N, sswap, src);
- castfunc(buffers[1], buffers[0], N, src, dest);
- dcopyfunc(dptr, dstride, buffers[0], delsize, N, dswap, dest);
- return;
- }
-
- /* otherwise we need to divide up into bufsize pieces */
- i = 0;
- while(N > 0) {
- int newN;
- newN = MIN(N, bufsize);
- _strided_buffered_cast(dptr+i*dstride, dstride, delsize,
- dswap, dcopyfunc,
- sptr+i*sstride, sstride, selsize,
- sswap, scopyfunc,
- newN, buffers, bufsize, castfunc, dest, src);
- i += newN;
- N -= bufsize;
- }
+ int i;
+ if (N <= bufsize) {
+ /* 1. copy input to buffer and swap
+ 2. cast input to output
+ 3. swap output if necessary and copy from output buffer
+ */
+ scopyfunc(buffers[1], selsize, sptr, sstride, N, sswap, src);
+ castfunc(buffers[1], buffers[0], N, src, dest);
+ dcopyfunc(dptr, dstride, buffers[0], delsize, N, dswap, dest);
return;
+ }
+
+ /* otherwise we need to divide up into bufsize pieces */
+ i = 0;
+ while(N > 0) {
+ int newN;
+ newN = MIN(N, bufsize);
+ _strided_buffered_cast(dptr+i*dstride, dstride, delsize,
+ dswap, dcopyfunc,
+ sptr+i*sstride, sstride, selsize,
+ sswap, scopyfunc,
+ newN, buffers, bufsize, castfunc, dest, src);
+ i += newN;
+ N -= bufsize;
+ }
+ return;
}
static int
_broadcast_cast(PyArrayObject *out, PyArrayObject *in,
PyArray_VectorUnaryFunc *castfunc, int iswap, int oswap)
{
- int delsize, selsize, maxaxis, i, N;
- PyArrayMultiIterObject *multi;
- intp maxdim, ostrides, istrides;
- char *buffers[2];
- PyArray_CopySwapNFunc *ocopyfunc, *icopyfunc;
- char *obptr;
+ int delsize, selsize, maxaxis, i, N;
+ PyArrayMultiIterObject *multi;
+ intp maxdim, ostrides, istrides;
+ char *buffers[2];
+ PyArray_CopySwapNFunc *ocopyfunc, *icopyfunc;
+ char *obptr;
- NPY_BEGIN_THREADS_DEF
+ NPY_BEGIN_THREADS_DEF
delsize = PyArray_ITEMSIZE(out);
- selsize = PyArray_ITEMSIZE(in);
- multi = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, out, in);
- if (multi == NULL) return -1;
-
- if (multi->size != PyArray_SIZE(out)) {
- PyErr_SetString(PyExc_ValueError,
- "array dimensions are not "\
- "compatible for copy");
- Py_DECREF(multi);
- return -1;
- }
+ selsize = PyArray_ITEMSIZE(in);
+ multi = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, out, in);
+ if (multi == NULL) return -1;
- icopyfunc = in->descr->f->copyswapn;
- ocopyfunc = out->descr->f->copyswapn;
- maxaxis = PyArray_RemoveSmallest(multi);
- if (maxaxis < 0) { /* cast 1 0-d array to another */
- N = 1;
- maxdim = 1;
- ostrides = delsize;
- istrides = selsize;
- }
- else {
- maxdim = multi->dimensions[maxaxis];
- N = (int) (MIN(maxdim, PyArray_BUFSIZE));
- ostrides = multi->iters[0]->strides[maxaxis];
- istrides = multi->iters[1]->strides[maxaxis];
+ if (multi->size != PyArray_SIZE(out)) {
+ PyErr_SetString(PyExc_ValueError,
+ "array dimensions are not "\
+ "compatible for copy");
+ Py_DECREF(multi);
+ return -1;
+ }
- }
- buffers[0] = _pya_malloc(N*delsize);
- if (buffers[0] == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- buffers[1] = _pya_malloc(N*selsize);
- if (buffers[1] == NULL) {
- _pya_free(buffers[0]);
- PyErr_NoMemory();
- return -1;
- }
- if (PyDataType_FLAGCHK(out->descr, NPY_NEEDS_INIT))
- memset(buffers[0], 0, N*delsize);
- if (PyDataType_FLAGCHK(in->descr, NPY_NEEDS_INIT))
- memset(buffers[1], 0, N*selsize);
+ icopyfunc = in->descr->f->copyswapn;
+ ocopyfunc = out->descr->f->copyswapn;
+ maxaxis = PyArray_RemoveSmallest(multi);
+ if (maxaxis < 0) { /* cast 1 0-d array to another */
+ N = 1;
+ maxdim = 1;
+ ostrides = delsize;
+ istrides = selsize;
+ }
+ else {
+ maxdim = multi->dimensions[maxaxis];
+ N = (int) (MIN(maxdim, PyArray_BUFSIZE));
+ ostrides = multi->iters[0]->strides[maxaxis];
+ istrides = multi->iters[1]->strides[maxaxis];
+
+ }
+ buffers[0] = _pya_malloc(N*delsize);
+ if (buffers[0] == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ buffers[1] = _pya_malloc(N*selsize);
+ if (buffers[1] == NULL) {
+ _pya_free(buffers[0]);
+ PyErr_NoMemory();
+ return -1;
+ }
+ if (PyDataType_FLAGCHK(out->descr, NPY_NEEDS_INIT))
+ memset(buffers[0], 0, N*delsize);
+ if (PyDataType_FLAGCHK(in->descr, NPY_NEEDS_INIT))
+ memset(buffers[1], 0, N*selsize);
#if NPY_ALLOW_THREADS
- if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
- NPY_BEGIN_THREADS
- }
+ if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
+ NPY_BEGIN_THREADS
+ }
#endif
- while(multi->index < multi->size) {
- _strided_buffered_cast(multi->iters[0]->dataptr,
- ostrides,
- delsize, oswap, ocopyfunc,
- multi->iters[1]->dataptr,
- istrides,
- selsize, iswap, icopyfunc,
- maxdim, buffers, N,
- castfunc, out, in);
- PyArray_MultiIter_NEXT(multi);
- }
+ while(multi->index < multi->size) {
+ _strided_buffered_cast(multi->iters[0]->dataptr,
+ ostrides,
+ delsize, oswap, ocopyfunc,
+ multi->iters[1]->dataptr,
+ istrides,
+ selsize, iswap, icopyfunc,
+ maxdim, buffers, N,
+ castfunc, out, in);
+ PyArray_MultiIter_NEXT(multi);
+ }
#if NPY_ALLOW_THREADS
- if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
- NPY_END_THREADS
- }
+ if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
+ NPY_END_THREADS
+ }
#endif
- Py_DECREF(multi);
- if (PyDataType_REFCHK(in->descr)) {
- obptr = buffers[1];
- for (i=0; i<N; i++, obptr+=selsize)
- PyArray_Item_XDECREF(obptr, out->descr);
- }
- if (PyDataType_REFCHK(out->descr)) {
- obptr = buffers[0];
- for (i=0; i<N; i++, obptr+=delsize)
- PyArray_Item_XDECREF(obptr, out->descr);
- }
- _pya_free(buffers[0]);
- _pya_free(buffers[1]);
- if (PyErr_Occurred()) return -1;
- return 0;
+ Py_DECREF(multi);
+ if (PyDataType_REFCHK(in->descr)) {
+ obptr = buffers[1];
+ for (i=0; i<N; i++, obptr+=selsize)
+ PyArray_Item_XDECREF(obptr, out->descr);
+ }
+ if (PyDataType_REFCHK(out->descr)) {
+ obptr = buffers[0];
+ for (i=0; i<N; i++, obptr+=delsize)
+ PyArray_Item_XDECREF(obptr, out->descr);
+ }
+ _pya_free(buffers[0]);
+ _pya_free(buffers[1]);
+ if (PyErr_Occurred()) return -1;
+ return 0;
}
@@ -7697,64 +7696,64 @@ _broadcast_cast(PyArrayObject *out, PyArrayObject *in,
*/
/*OBJECT_API
- Cast to an already created array.
+ Cast to an already created array.
*/
static int
PyArray_CastTo(PyArrayObject *out, PyArrayObject *mp)
{
- int simple;
- int same;
- PyArray_VectorUnaryFunc *castfunc=NULL;
- int mpsize = PyArray_SIZE(mp);
- int iswap, oswap;
+ int simple;
+ int same;
+ PyArray_VectorUnaryFunc *castfunc=NULL;
+ int mpsize = PyArray_SIZE(mp);
+ int iswap, oswap;
- NPY_BEGIN_THREADS_DEF
+ NPY_BEGIN_THREADS_DEF
if (mpsize == 0) return 0;
- if (!PyArray_ISWRITEABLE(out)) {
- PyErr_SetString(PyExc_ValueError,
- "output array is not writeable");
- return -1;
- }
+ if (!PyArray_ISWRITEABLE(out)) {
+ PyErr_SetString(PyExc_ValueError,
+ "output array is not writeable");
+ return -1;
+ }
- castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
- if (castfunc == NULL) return -1;
+ castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
+ if (castfunc == NULL) return -1;
- same = PyArray_SAMESHAPE(out, mp);
- simple = same && ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
- (PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
+ same = PyArray_SAMESHAPE(out, mp);
+ simple = same && ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
+ (PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
- if (simple) {
+ if (simple) {
#if NPY_ALLOW_THREADS
- if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
- NPY_BEGIN_THREADS }
+ if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
+ NPY_BEGIN_THREADS }
#endif
- castfunc(mp->data, out->data, mpsize, mp, out);
+ castfunc(mp->data, out->data, mpsize, mp, out);
#if NPY_ALLOW_THREADS
- if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
- NPY_END_THREADS }
+ if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
+ NPY_END_THREADS }
#endif
- if (!PyArray_ISNUMBER(mp) && PyErr_Occurred()) return -1;
- }
+ if (!PyArray_ISNUMBER(mp) && PyErr_Occurred()) return -1;
+ }
- /* If the input or output is OBJECT, STRING, UNICODE, or VOID */
- /* then getitem and setitem are used for the cast */
- /* and byteswapping is handled by those methods */
+ /* If the input or output is OBJECT, STRING, UNICODE, or VOID */
+ /* then getitem and setitem are used for the cast */
+ /* and byteswapping is handled by those methods */
- if (PyArray_ISFLEXIBLE(mp) || PyArray_ISOBJECT(mp) || PyArray_ISOBJECT(out) ||
- PyArray_ISFLEXIBLE(out)) {
- iswap = oswap = 0;
- }
- else {
- iswap = PyArray_ISBYTESWAPPED(mp);
- oswap = PyArray_ISBYTESWAPPED(out);
- }
+ if (PyArray_ISFLEXIBLE(mp) || PyArray_ISOBJECT(mp) || PyArray_ISOBJECT(out) ||
+ PyArray_ISFLEXIBLE(out)) {
+ iswap = oswap = 0;
+ }
+ else {
+ iswap = PyArray_ISBYTESWAPPED(mp);
+ oswap = PyArray_ISBYTESWAPPED(out);
+ }
- return _broadcast_cast(out, mp, castfunc, iswap, oswap);
+ return _broadcast_cast(out, mp, castfunc, iswap, oswap);
}
@@ -7762,142 +7761,142 @@ static int
_bufferedcast(PyArrayObject *out, PyArrayObject *in,
PyArray_VectorUnaryFunc *castfunc)
{
- char *inbuffer, *bptr, *optr;
- char *outbuffer=NULL;
- PyArrayIterObject *it_in=NULL, *it_out=NULL;
- register intp i, index;
- intp ncopies = PyArray_SIZE(out) / PyArray_SIZE(in);
- int elsize=in->descr->elsize;
- int nels = PyArray_BUFSIZE;
- int el;
- int inswap, outswap=0;
- int obuf=!PyArray_ISCARRAY(out);
- int oelsize = out->descr->elsize;
- PyArray_CopySwapFunc *in_csn;
- PyArray_CopySwapFunc *out_csn;
- int retval = -1;
-
- in_csn = in->descr->f->copyswap;
- out_csn = out->descr->f->copyswap;
-
- /* If the input or output is STRING, UNICODE, or VOID */
- /* then getitem and setitem are used for the cast */
- /* and byteswapping is handled by those methods */
-
- inswap = !(PyArray_ISFLEXIBLE(in) || PyArray_ISNOTSWAPPED(in));
-
- inbuffer = PyDataMem_NEW(PyArray_BUFSIZE*elsize);
- if (inbuffer == NULL) return -1;
- if (PyArray_ISOBJECT(in))
- memset(inbuffer, 0, PyArray_BUFSIZE*elsize);
- it_in = (PyArrayIterObject *)PyArray_IterNew((PyObject *)in);
- if (it_in == NULL) goto exit;
-
- if (obuf) {
- outswap = !(PyArray_ISFLEXIBLE(out) || \
- PyArray_ISNOTSWAPPED(out));
- outbuffer = PyDataMem_NEW(PyArray_BUFSIZE*oelsize);
- if (outbuffer == NULL) goto exit;
- if (PyArray_ISOBJECT(out))
- memset(outbuffer, 0, PyArray_BUFSIZE*oelsize);
-
- it_out = (PyArrayIterObject *)PyArray_IterNew((PyObject *)out);
- if (it_out == NULL) goto exit;
-
- nels = MIN(nels, PyArray_BUFSIZE);
- }
-
- optr = (obuf) ? outbuffer: out->data;
- bptr = inbuffer;
- el = 0;
- while(ncopies--) {
- index = it_in->size;
- PyArray_ITER_RESET(it_in);
- while(index--) {
- in_csn(bptr, it_in->dataptr, inswap, in);
- bptr += elsize;
- PyArray_ITER_NEXT(it_in);
- el += 1;
- if ((el == nels) || (index == 0)) {
- /* buffer filled, do cast */
-
- castfunc(inbuffer, optr, el, in, out);
-
- if (obuf) {
- /* Copy from outbuffer to array */
- for(i=0; i<el; i++) {
- out_csn(it_out->dataptr,
- optr, outswap,
- out);
- optr += oelsize;
- PyArray_ITER_NEXT(it_out);
- }
- optr = outbuffer;
- }
- else {
- optr += out->descr->elsize * nels;
- }
- el = 0;
- bptr = inbuffer;
- }
+ char *inbuffer, *bptr, *optr;
+ char *outbuffer=NULL;
+ PyArrayIterObject *it_in=NULL, *it_out=NULL;
+ register intp i, index;
+ intp ncopies = PyArray_SIZE(out) / PyArray_SIZE(in);
+ int elsize=in->descr->elsize;
+ int nels = PyArray_BUFSIZE;
+ int el;
+ int inswap, outswap=0;
+ int obuf=!PyArray_ISCARRAY(out);
+ int oelsize = out->descr->elsize;
+ PyArray_CopySwapFunc *in_csn;
+ PyArray_CopySwapFunc *out_csn;
+ int retval = -1;
+
+ in_csn = in->descr->f->copyswap;
+ out_csn = out->descr->f->copyswap;
+
+ /* If the input or output is STRING, UNICODE, or VOID */
+ /* then getitem and setitem are used for the cast */
+ /* and byteswapping is handled by those methods */
+
+ inswap = !(PyArray_ISFLEXIBLE(in) || PyArray_ISNOTSWAPPED(in));
+
+ inbuffer = PyDataMem_NEW(PyArray_BUFSIZE*elsize);
+ if (inbuffer == NULL) return -1;
+ if (PyArray_ISOBJECT(in))
+ memset(inbuffer, 0, PyArray_BUFSIZE*elsize);
+ it_in = (PyArrayIterObject *)PyArray_IterNew((PyObject *)in);
+ if (it_in == NULL) goto exit;
+
+ if (obuf) {
+ outswap = !(PyArray_ISFLEXIBLE(out) || \
+ PyArray_ISNOTSWAPPED(out));
+ outbuffer = PyDataMem_NEW(PyArray_BUFSIZE*oelsize);
+ if (outbuffer == NULL) goto exit;
+ if (PyArray_ISOBJECT(out))
+ memset(outbuffer, 0, PyArray_BUFSIZE*oelsize);
+
+ it_out = (PyArrayIterObject *)PyArray_IterNew((PyObject *)out);
+ if (it_out == NULL) goto exit;
+
+ nels = MIN(nels, PyArray_BUFSIZE);
+ }
+
+ optr = (obuf) ? outbuffer: out->data;
+ bptr = inbuffer;
+ el = 0;
+ while(ncopies--) {
+ index = it_in->size;
+ PyArray_ITER_RESET(it_in);
+ while(index--) {
+ in_csn(bptr, it_in->dataptr, inswap, in);
+ bptr += elsize;
+ PyArray_ITER_NEXT(it_in);
+ el += 1;
+ if ((el == nels) || (index == 0)) {
+ /* buffer filled, do cast */
+
+ castfunc(inbuffer, optr, el, in, out);
+
+ if (obuf) {
+ /* Copy from outbuffer to array */
+ for(i=0; i<el; i++) {
+ out_csn(it_out->dataptr,
+ optr, outswap,
+ out);
+ optr += oelsize;
+ PyArray_ITER_NEXT(it_out);
+ }
+ optr = outbuffer;
+ }
+ else {
+ optr += out->descr->elsize * nels;
}
+ el = 0;
+ bptr = inbuffer;
+ }
}
- retval = 0;
+ }
+ retval = 0;
exit:
- Py_XDECREF(it_in);
- PyDataMem_FREE(inbuffer);
- PyDataMem_FREE(outbuffer);
- if (obuf) {
- Py_XDECREF(it_out);
- }
- return retval;
+ Py_XDECREF(it_in);
+ PyDataMem_FREE(inbuffer);
+ PyDataMem_FREE(outbuffer);
+ if (obuf) {
+ Py_XDECREF(it_out);
+ }
+ return retval;
}
/*OBJECT_API
- Cast to an already created array. Arrays don't have to be "broadcastable"
- Only requirement is they have the same number of elements.
+ Cast to an already created array. Arrays don't have to be "broadcastable"
+ Only requirement is they have the same number of elements.
*/
static int
PyArray_CastAnyTo(PyArrayObject *out, PyArrayObject *mp)
{
- int simple;
- PyArray_VectorUnaryFunc *castfunc=NULL;
- int mpsize = PyArray_SIZE(mp);
+ int simple;
+ PyArray_VectorUnaryFunc *castfunc=NULL;
+ int mpsize = PyArray_SIZE(mp);
- if (mpsize == 0) return 0;
- if (!PyArray_ISWRITEABLE(out)) {
- PyErr_SetString(PyExc_ValueError,
- "output array is not writeable");
- return -1;
- }
+ if (mpsize == 0) return 0;
+ if (!PyArray_ISWRITEABLE(out)) {
+ PyErr_SetString(PyExc_ValueError,
+ "output array is not writeable");
+ return -1;
+ }
- if (!(mpsize == PyArray_SIZE(out))) {
- PyErr_SetString(PyExc_ValueError,
- "arrays must have the same number of"
- " elements for the cast.");
- return -1;
- }
+ if (!(mpsize == PyArray_SIZE(out))) {
+ PyErr_SetString(PyExc_ValueError,
+ "arrays must have the same number of"
+ " elements for the cast.");
+ return -1;
+ }
- castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
- if (castfunc == NULL) return -1;
+ castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
+ if (castfunc == NULL) return -1;
- simple = ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
- (PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
+ simple = ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
+ (PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
- if (simple) {
- castfunc(mp->data, out->data, mpsize, mp, out);
- return 0;
- }
+ if (simple) {
+ castfunc(mp->data, out->data, mpsize, mp, out);
+ return 0;
+ }
- if (PyArray_SAMESHAPE(out, mp)) {
- int iswap, oswap;
- iswap = PyArray_ISBYTESWAPPED(mp) && !PyArray_ISFLEXIBLE(mp);
- oswap = PyArray_ISBYTESWAPPED(out) && !PyArray_ISFLEXIBLE(out);
- return _broadcast_cast(out, mp, castfunc, iswap, oswap);
- }
+ if (PyArray_SAMESHAPE(out, mp)) {
+ int iswap, oswap;
+ iswap = PyArray_ISBYTESWAPPED(mp) && !PyArray_ISFLEXIBLE(mp);
+ oswap = PyArray_ISBYTESWAPPED(out) && !PyArray_ISFLEXIBLE(out);
+ return _broadcast_cast(out, mp, castfunc, iswap, oswap);
+ }
- return _bufferedcast(out, mp, castfunc);
+ return _bufferedcast(out, mp, castfunc);
}
@@ -7908,229 +7907,229 @@ static PyObject *
PyArray_FromArray(PyArrayObject *arr, PyArray_Descr *newtype, int flags)
{
- PyArrayObject *ret=NULL;
- int itemsize;
- int copy = 0;
- int arrflags;
- PyArray_Descr *oldtype;
- char *msg = "cannot copy back to a read-only array";
- PyTypeObject *subtype;
+ PyArrayObject *ret=NULL;
+ int itemsize;
+ int copy = 0;
+ int arrflags;
+ PyArray_Descr *oldtype;
+ char *msg = "cannot copy back to a read-only array";
+ PyTypeObject *subtype;
- oldtype = PyArray_DESCR(arr);
+ oldtype = PyArray_DESCR(arr);
- subtype = arr->ob_type;
+ subtype = arr->ob_type;
- if (newtype == NULL) {newtype = oldtype; Py_INCREF(oldtype);}
+ if (newtype == NULL) {newtype = oldtype; Py_INCREF(oldtype);}
+ itemsize = newtype->elsize;
+ if (itemsize == 0) {
+ PyArray_DESCR_REPLACE(newtype);
+ if (newtype == NULL) return NULL;
+ newtype->elsize = oldtype->elsize;
itemsize = newtype->elsize;
- if (itemsize == 0) {
- PyArray_DESCR_REPLACE(newtype);
- if (newtype == NULL) return NULL;
- newtype->elsize = oldtype->elsize;
- itemsize = newtype->elsize;
- }
+ }
- /* Can't cast unless ndim-0 array, FORCECAST is specified
- or the cast is safe.
- */
- if (!(flags & FORCECAST) && !PyArray_NDIM(arr)==0 &&
- !PyArray_CanCastTo(oldtype, newtype)) {
+ /* Can't cast unless ndim-0 array, FORCECAST is specified
+ or the cast is safe.
+ */
+ if (!(flags & FORCECAST) && !PyArray_NDIM(arr)==0 &&
+ !PyArray_CanCastTo(oldtype, newtype)) {
+ Py_DECREF(newtype);
+ PyErr_SetString(PyExc_TypeError,
+ "array cannot be safely cast " \
+ "to required type");
+ return NULL;
+ }
+
+ /* Don't copy if sizes are compatible */
+ if ((flags & ENSURECOPY) || PyArray_EquivTypes(oldtype, newtype)) {
+ arrflags = arr->flags;
+
+ copy = (flags & ENSURECOPY) || \
+ ((flags & CONTIGUOUS) && (!(arrflags & CONTIGUOUS))) \
+ || ((flags & ALIGNED) && (!(arrflags & ALIGNED))) \
+ || (arr->nd > 1 && \
+ ((flags & FORTRAN) && (!(arrflags & FORTRAN)))) \
+ || ((flags & WRITEABLE) && (!(arrflags & WRITEABLE)));
+
+ if (copy) {
+ if ((flags & UPDATEIFCOPY) && \
+ (!PyArray_ISWRITEABLE(arr))) {
Py_DECREF(newtype);
- PyErr_SetString(PyExc_TypeError,
- "array cannot be safely cast " \
- "to required type");
+ PyErr_SetString(PyExc_ValueError, msg);
return NULL;
+ }
+ if ((flags & ENSUREARRAY)) {
+ subtype = &PyArray_Type;
+ }
+ ret = (PyArrayObject *) \
+ PyArray_NewFromDescr(subtype, newtype,
+ arr->nd,
+ arr->dimensions,
+ NULL, NULL,
+ flags & FORTRAN,
+ (PyObject *)arr);
+ if (ret == NULL) return NULL;
+ if (PyArray_CopyInto(ret, arr) == -1)
+ {Py_DECREF(ret); return NULL;}
+ if (flags & UPDATEIFCOPY) {
+ ret->flags |= UPDATEIFCOPY;
+ ret->base = (PyObject *)arr;
+ PyArray_FLAGS(ret->base) &= ~WRITEABLE;
+ Py_INCREF(arr);
+ }
}
-
- /* Don't copy if sizes are compatible */
- if ((flags & ENSURECOPY) || PyArray_EquivTypes(oldtype, newtype)) {
- arrflags = arr->flags;
-
- copy = (flags & ENSURECOPY) || \
- ((flags & CONTIGUOUS) && (!(arrflags & CONTIGUOUS))) \
- || ((flags & ALIGNED) && (!(arrflags & ALIGNED))) \
- || (arr->nd > 1 && \
- ((flags & FORTRAN) && (!(arrflags & FORTRAN)))) \
- || ((flags & WRITEABLE) && (!(arrflags & WRITEABLE)));
-
- if (copy) {
- if ((flags & UPDATEIFCOPY) && \
- (!PyArray_ISWRITEABLE(arr))) {
- Py_DECREF(newtype);
- PyErr_SetString(PyExc_ValueError, msg);
- return NULL;
- }
- if ((flags & ENSUREARRAY)) {
- subtype = &PyArray_Type;
- }
- ret = (PyArrayObject *) \
- PyArray_NewFromDescr(subtype, newtype,
- arr->nd,
- arr->dimensions,
- NULL, NULL,
- flags & FORTRAN,
- (PyObject *)arr);
- if (ret == NULL) return NULL;
- if (PyArray_CopyInto(ret, arr) == -1)
- {Py_DECREF(ret); return NULL;}
- if (flags & UPDATEIFCOPY) {
- ret->flags |= UPDATEIFCOPY;
- ret->base = (PyObject *)arr;
- PyArray_FLAGS(ret->base) &= ~WRITEABLE;
- Py_INCREF(arr);
- }
- }
- /* If no copy then just increase the reference
- count and return the input */
- else {
- Py_DECREF(newtype);
- if ((flags & ENSUREARRAY) &&
- !PyArray_CheckExact(arr)) {
- Py_INCREF(arr->descr);
- ret = (PyArrayObject *) \
- PyArray_NewFromDescr(&PyArray_Type,
- arr->descr,
- arr->nd,
- arr->dimensions,
- arr->strides,
- arr->data,
- arr->flags,NULL);
- if (ret == NULL) return NULL;
- ret->base = (PyObject *)arr;
- }
- else {
- ret = arr;
- }
- Py_INCREF(arr);
- }
- }
-
- /* The desired output type is different than the input
- array type and copy was not specified */
+ /* If no copy then just increase the reference
+ count and return the input */
else {
- if ((flags & UPDATEIFCOPY) && \
- (!PyArray_ISWRITEABLE(arr))) {
- Py_DECREF(newtype);
- PyErr_SetString(PyExc_ValueError, msg);
- return NULL;
- }
- if ((flags & ENSUREARRAY)) {
- subtype = &PyArray_Type;
- }
- ret = (PyArrayObject *) \
- PyArray_NewFromDescr(subtype, newtype,
- arr->nd, arr->dimensions,
- NULL, NULL,
- flags & FORTRAN,
- (PyObject *)arr);
+ Py_DECREF(newtype);
+ if ((flags & ENSUREARRAY) &&
+ !PyArray_CheckExact(arr)) {
+ Py_INCREF(arr->descr);
+ ret = (PyArrayObject *) \
+ PyArray_NewFromDescr(&PyArray_Type,
+ arr->descr,
+ arr->nd,
+ arr->dimensions,
+ arr->strides,
+ arr->data,
+ arr->flags,NULL);
if (ret == NULL) return NULL;
- if (PyArray_CastTo(ret, arr) < 0) {
- Py_DECREF(ret);
- return NULL;
- }
- if (flags & UPDATEIFCOPY) {
- ret->flags |= UPDATEIFCOPY;
- ret->base = (PyObject *)arr;
- PyArray_FLAGS(ret->base) &= ~WRITEABLE;
- Py_INCREF(arr);
- }
+ ret->base = (PyObject *)arr;
+ }
+ else {
+ ret = arr;
+ }
+ Py_INCREF(arr);
}
- return (PyObject *)ret;
+ }
+
+ /* The desired output type is different than the input
+ array type and copy was not specified */
+ else {
+ if ((flags & UPDATEIFCOPY) && \
+ (!PyArray_ISWRITEABLE(arr))) {
+ Py_DECREF(newtype);
+ PyErr_SetString(PyExc_ValueError, msg);
+ return NULL;
+ }
+ if ((flags & ENSUREARRAY)) {
+ subtype = &PyArray_Type;
+ }
+ ret = (PyArrayObject *) \
+ PyArray_NewFromDescr(subtype, newtype,
+ arr->nd, arr->dimensions,
+ NULL, NULL,
+ flags & FORTRAN,
+ (PyObject *)arr);
+ if (ret == NULL) return NULL;
+ if (PyArray_CastTo(ret, arr) < 0) {
+ Py_DECREF(ret);
+ return NULL;
+ }
+ if (flags & UPDATEIFCOPY) {
+ ret->flags |= UPDATEIFCOPY;
+ ret->base = (PyObject *)arr;
+ PyArray_FLAGS(ret->base) &= ~WRITEABLE;
+ Py_INCREF(arr);
+ }
+ }
+ return (PyObject *)ret;
}
/* new reference */
static PyArray_Descr *
_array_typedescr_fromstr(char *str)
{
- PyArray_Descr *descr;
- int type_num;
- char typechar;
- int size;
- char msg[] = "unsupported typestring";
- int swap;
- char swapchar;
-
- swapchar = str[0];
- str += 1;
-
-#define _MY_FAIL { \
- PyErr_SetString(PyExc_ValueError, msg); \
- return NULL; \
- }
-
- typechar = str[0];
- size = atoi(str + 1);
- switch (typechar) {
- case 'b':
- if (size == sizeof(Bool))
- type_num = PyArray_BOOL;
- else _MY_FAIL
- break;
- case 'u':
- if (size == sizeof(uintp))
- type_num = PyArray_UINTP;
- else if (size == sizeof(char))
- type_num = PyArray_UBYTE;
- else if (size == sizeof(short))
- type_num = PyArray_USHORT;
- else if (size == sizeof(ulong))
- type_num = PyArray_ULONG;
- else if (size == sizeof(int))
- type_num = PyArray_UINT;
- else if (size == sizeof(ulonglong))
- type_num = PyArray_ULONGLONG;
- else _MY_FAIL
- break;
- case 'i':
- if (size == sizeof(intp))
- type_num = PyArray_INTP;
- else if (size == sizeof(char))
- type_num = PyArray_BYTE;
- else if (size == sizeof(short))
- type_num = PyArray_SHORT;
- else if (size == sizeof(long))
- type_num = PyArray_LONG;
- else if (size == sizeof(int))
- type_num = PyArray_INT;
- else if (size == sizeof(longlong))
- type_num = PyArray_LONGLONG;
- else _MY_FAIL
- break;
- case 'f':
- if (size == sizeof(float))
- type_num = PyArray_FLOAT;
- else if (size == sizeof(double))
- type_num = PyArray_DOUBLE;
- else if (size == sizeof(longdouble))
- type_num = PyArray_LONGDOUBLE;
- else _MY_FAIL
- break;
- case 'c':
- if (size == sizeof(float)*2)
- type_num = PyArray_CFLOAT;
- else if (size == sizeof(double)*2)
- type_num = PyArray_CDOUBLE;
- else if (size == sizeof(longdouble)*2)
- type_num = PyArray_CLONGDOUBLE;
- else _MY_FAIL
- break;
- case 'O':
- if (size == sizeof(PyObject *))
- type_num = PyArray_OBJECT;
- else _MY_FAIL
- break;
- case PyArray_STRINGLTR:
- type_num = PyArray_STRING;
- break;
- case PyArray_UNICODELTR:
- type_num = PyArray_UNICODE;
- size <<= 2;
- break;
- case 'V':
- type_num = PyArray_VOID;
- break;
- default:
- _MY_FAIL
- }
+ PyArray_Descr *descr;
+ int type_num;
+ char typechar;
+ int size;
+ char msg[] = "unsupported typestring";
+ int swap;
+ char swapchar;
+
+ swapchar = str[0];
+ str += 1;
+
+#define _MY_FAIL { \
+ PyErr_SetString(PyExc_ValueError, msg); \
+ return NULL; \
+ }
+
+ typechar = str[0];
+ size = atoi(str + 1);
+ switch (typechar) {
+ case 'b':
+ if (size == sizeof(Bool))
+ type_num = PyArray_BOOL;
+ else _MY_FAIL
+ break;
+ case 'u':
+ if (size == sizeof(uintp))
+ type_num = PyArray_UINTP;
+ else if (size == sizeof(char))
+ type_num = PyArray_UBYTE;
+ else if (size == sizeof(short))
+ type_num = PyArray_USHORT;
+ else if (size == sizeof(ulong))
+ type_num = PyArray_ULONG;
+ else if (size == sizeof(int))
+ type_num = PyArray_UINT;
+ else if (size == sizeof(ulonglong))
+ type_num = PyArray_ULONGLONG;
+ else _MY_FAIL
+ break;
+ case 'i':
+ if (size == sizeof(intp))
+ type_num = PyArray_INTP;
+ else if (size == sizeof(char))
+ type_num = PyArray_BYTE;
+ else if (size == sizeof(short))
+ type_num = PyArray_SHORT;
+ else if (size == sizeof(long))
+ type_num = PyArray_LONG;
+ else if (size == sizeof(int))
+ type_num = PyArray_INT;
+ else if (size == sizeof(longlong))
+ type_num = PyArray_LONGLONG;
+ else _MY_FAIL
+ break;
+ case 'f':
+ if (size == sizeof(float))
+ type_num = PyArray_FLOAT;
+ else if (size == sizeof(double))
+ type_num = PyArray_DOUBLE;
+ else if (size == sizeof(longdouble))
+ type_num = PyArray_LONGDOUBLE;
+ else _MY_FAIL
+ break;
+ case 'c':
+ if (size == sizeof(float)*2)
+ type_num = PyArray_CFLOAT;
+ else if (size == sizeof(double)*2)
+ type_num = PyArray_CDOUBLE;
+ else if (size == sizeof(longdouble)*2)
+ type_num = PyArray_CLONGDOUBLE;
+ else _MY_FAIL
+ break;
+ case 'O':
+ if (size == sizeof(PyObject *))
+ type_num = PyArray_OBJECT;
+ else _MY_FAIL
+ break;
+ case PyArray_STRINGLTR:
+ type_num = PyArray_STRING;
+ break;
+ case PyArray_UNICODELTR:
+ type_num = PyArray_UNICODE;
+ size <<= 2;
+ break;
+ case 'V':
+ type_num = PyArray_VOID;
+ break;
+ default:
+ _MY_FAIL
+ }
#undef _MY_FAIL
@@ -8138,13 +8137,13 @@ _array_typedescr_fromstr(char *str)
if (descr == NULL) return NULL;
swap = !PyArray_ISNBO(swapchar);
if (descr->elsize == 0 || swap) {
- /* Need to make a new PyArray_Descr */
- PyArray_DESCR_REPLACE(descr);
- if (descr==NULL) return NULL;
- if (descr->elsize == 0)
- descr->elsize = size;
- if (swap)
- descr->byteorder = swapchar;
+ /* Need to make a new PyArray_Descr */
+ PyArray_DESCR_REPLACE(descr);
+ if (descr==NULL) return NULL;
+ if (descr->elsize == 0)
+ descr->elsize = size;
+ if (swap)
+ descr->byteorder = swapchar;
}
return descr;
}
@@ -8153,54 +8152,54 @@ _array_typedescr_fromstr(char *str)
static PyObject *
PyArray_FromStructInterface(PyObject *input)
{
- PyArray_Descr *thetype=NULL;
- char buf[40];
- PyArrayInterface *inter;
- PyObject *attr, *r;
- char endian = PyArray_NATBYTE;
+ PyArray_Descr *thetype=NULL;
+ char buf[40];
+ PyArrayInterface *inter;
+ PyObject *attr, *r;
+ char endian = PyArray_NATBYTE;
- attr = PyObject_GetAttrString(input, "__array_struct__");
- if (attr == NULL) {
- PyErr_Clear();
- return Py_NotImplemented;
- }
- if (!PyCObject_Check(attr)) goto fail;
- inter = PyCObject_AsVoidPtr(attr);
- if (inter->two != 2) goto fail;
- if ((inter->flags & NOTSWAPPED) != NOTSWAPPED) {
- endian = PyArray_OPPBYTE;
- inter->flags &= ~NOTSWAPPED;
- }
+ attr = PyObject_GetAttrString(input, "__array_struct__");
+ if (attr == NULL) {
+ PyErr_Clear();
+ return Py_NotImplemented;
+ }
+ if (!PyCObject_Check(attr)) goto fail;
+ inter = PyCObject_AsVoidPtr(attr);
+ if (inter->two != 2) goto fail;
+ if ((inter->flags & NOTSWAPPED) != NOTSWAPPED) {
+ endian = PyArray_OPPBYTE;
+ inter->flags &= ~NOTSWAPPED;
+ }
- if (inter->flags & ARR_HAS_DESCR) {
- if (PyArray_DescrConverter(inter->descr, &thetype) == PY_FAIL) {
- thetype = NULL;
- PyErr_Clear();
- }
+ if (inter->flags & ARR_HAS_DESCR) {
+ if (PyArray_DescrConverter(inter->descr, &thetype) == PY_FAIL) {
+ thetype = NULL;
+ PyErr_Clear();
}
+ }
- if (thetype == NULL) {
- snprintf(buf, 40, "%c%c%d", endian, inter->typekind, inter->itemsize);
- if (!(thetype=_array_typedescr_fromstr(buf))) {
- Py_DECREF(attr);
- return NULL;
- }
+ if (thetype == NULL) {
+ snprintf(buf, 40, "%c%c%d", endian, inter->typekind, inter->itemsize);
+ if (!(thetype=_array_typedescr_fromstr(buf))) {
+ Py_DECREF(attr);
+ return NULL;
}
+ }
- r = PyArray_NewFromDescr(&PyArray_Type, thetype,
- inter->nd, inter->shape,
- inter->strides, inter->data,
- inter->flags, NULL);
- Py_INCREF(input);
- PyArray_BASE(r) = input;
- Py_DECREF(attr);
- PyArray_UpdateFlags((PyArrayObject *)r, UPDATE_ALL);
- return r;
+ r = PyArray_NewFromDescr(&PyArray_Type, thetype,
+ inter->nd, inter->shape,
+ inter->strides, inter->data,
+ inter->flags, NULL);
+ Py_INCREF(input);
+ PyArray_BASE(r) = input;
+ Py_DECREF(attr);
+ PyArray_UpdateFlags((PyArrayObject *)r, UPDATE_ALL);
+ return r;
fail:
- PyErr_SetString(PyExc_ValueError, "invalid __array_struct__");
- Py_DECREF(attr);
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "invalid __array_struct__");
+ Py_DECREF(attr);
+ return NULL;
}
#define PyIntOrLong_Check(obj) (PyInt_Check(obj) || PyLong_Check(obj))
@@ -8209,198 +8208,198 @@ PyArray_FromStructInterface(PyObject *input)
static PyObject *
PyArray_FromInterface(PyObject *input)
{
- PyObject *attr=NULL, *item=NULL;
- PyObject *tstr=NULL, *shape=NULL;
- PyObject *inter=NULL;
- PyObject *base=NULL;
- PyArrayObject *ret;
- PyArray_Descr *type=NULL;
- char *data;
- Py_ssize_t buffer_len;
- int res, i, n;
- intp dims[MAX_DIMS], strides[MAX_DIMS];
- int dataflags = BEHAVED;
-
- /* Get the memory from __array_data__ and __array_offset__ */
- /* Get the shape */
- /* Get the typestring -- ignore array_descr */
- /* Get the strides */
-
- inter = PyObject_GetAttrString(input, "__array_interface__");
- if (inter == NULL) {PyErr_Clear(); return Py_NotImplemented;}
- if (!PyDict_Check(inter)) {Py_DECREF(inter); return Py_NotImplemented;}
-
- shape = PyDict_GetItemString(inter, "shape");
- if (shape == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
- tstr = PyDict_GetItemString(inter, "typestr");
- if (tstr == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
-
- attr = PyDict_GetItemString(inter, "data");
- base = input;
- if ((attr == NULL) || (attr==Py_None) || (!PyTuple_Check(attr))) {
- if (attr && (attr != Py_None)) item=attr;
- else item=input;
- res = PyObject_AsWriteBuffer(item, (void **)&data,
- &buffer_len);
- if (res < 0) {
- PyErr_Clear();
- res = PyObject_AsReadBuffer(item, (const void **)&data,
- &buffer_len);
- if (res < 0) goto fail;
- dataflags &= ~WRITEABLE;
- }
- attr = PyDict_GetItemString(inter, "offset");
- if (attr) {
- longlong num = PyLong_AsLongLong(attr);
- if (error_converting(num)) {
- PyErr_SetString(PyExc_TypeError,
- "offset "\
- "must be an integer");
- goto fail;
- }
- data += num;
- }
- base = item;
+ PyObject *attr=NULL, *item=NULL;
+ PyObject *tstr=NULL, *shape=NULL;
+ PyObject *inter=NULL;
+ PyObject *base=NULL;
+ PyArrayObject *ret;
+ PyArray_Descr *type=NULL;
+ char *data;
+ Py_ssize_t buffer_len;
+ int res, i, n;
+ intp dims[MAX_DIMS], strides[MAX_DIMS];
+ int dataflags = BEHAVED;
+
+ /* Get the memory from __array_data__ and __array_offset__ */
+ /* Get the shape */
+ /* Get the typestring -- ignore array_descr */
+ /* Get the strides */
+
+ inter = PyObject_GetAttrString(input, "__array_interface__");
+ if (inter == NULL) {PyErr_Clear(); return Py_NotImplemented;}
+ if (!PyDict_Check(inter)) {Py_DECREF(inter); return Py_NotImplemented;}
+
+ shape = PyDict_GetItemString(inter, "shape");
+ if (shape == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
+ tstr = PyDict_GetItemString(inter, "typestr");
+ if (tstr == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
+
+ attr = PyDict_GetItemString(inter, "data");
+ base = input;
+ if ((attr == NULL) || (attr==Py_None) || (!PyTuple_Check(attr))) {
+ if (attr && (attr != Py_None)) item=attr;
+ else item=input;
+ res = PyObject_AsWriteBuffer(item, (void **)&data,
+ &buffer_len);
+ if (res < 0) {
+ PyErr_Clear();
+ res = PyObject_AsReadBuffer(item, (const void **)&data,
+ &buffer_len);
+ if (res < 0) goto fail;
+ dataflags &= ~WRITEABLE;
+ }
+ attr = PyDict_GetItemString(inter, "offset");
+ if (attr) {
+ longlong num = PyLong_AsLongLong(attr);
+ if (error_converting(num)) {
+ PyErr_SetString(PyExc_TypeError,
+ "offset "\
+ "must be an integer");
+ goto fail;
+ }
+ data += num;
+ }
+ base = item;
+ }
+ else {
+ PyObject *dataptr;
+ if (PyTuple_GET_SIZE(attr) != 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "data must return " \
+ "a 2-tuple with (data pointer "\
+ "integer, read-only flag)");
+ goto fail;
+ }
+ dataptr = PyTuple_GET_ITEM(attr, 0);
+ if (PyString_Check(dataptr)) {
+ res = sscanf(PyString_AsString(dataptr),
+ "%p", (void **)&data);
+ if (res < 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "data string cannot be " \
+ "converted");
+ goto fail;
+ }
+ }
+ else if (PyIntOrLong_Check(dataptr)) {
+ data = PyLong_AsVoidPtr(dataptr);
}
else {
- PyObject *dataptr;
- if (PyTuple_GET_SIZE(attr) != 2) {
- PyErr_SetString(PyExc_TypeError,
- "data must return " \
- "a 2-tuple with (data pointer "\
- "integer, read-only flag)");
- goto fail;
- }
- dataptr = PyTuple_GET_ITEM(attr, 0);
- if (PyString_Check(dataptr)) {
- res = sscanf(PyString_AsString(dataptr),
- "%p", (void **)&data);
- if (res < 1) {
- PyErr_SetString(PyExc_TypeError,
- "data string cannot be " \
- "converted");
- goto fail;
- }
- }
- else if (PyIntOrLong_Check(dataptr)) {
- data = PyLong_AsVoidPtr(dataptr);
- }
- else {
- PyErr_SetString(PyExc_TypeError, "first element " \
- "of data tuple must be integer" \
- " or string.");
- goto fail;
- }
- if (PyObject_IsTrue(PyTuple_GET_ITEM(attr,1))) {
- dataflags &= ~WRITEABLE;
- }
+ PyErr_SetString(PyExc_TypeError, "first element " \
+ "of data tuple must be integer" \
+ " or string.");
+ goto fail;
}
- attr = tstr;
- if (!PyString_Check(attr)) {
- PyErr_SetString(PyExc_TypeError, "typestr must be a string");
- goto fail;
+ if (PyObject_IsTrue(PyTuple_GET_ITEM(attr,1))) {
+ dataflags &= ~WRITEABLE;
}
- type = _array_typedescr_fromstr(PyString_AS_STRING(attr));
- if (type==NULL) goto fail;
- attr = shape;
+ }
+ attr = tstr;
+ if (!PyString_Check(attr)) {
+ PyErr_SetString(PyExc_TypeError, "typestr must be a string");
+ goto fail;
+ }
+ type = _array_typedescr_fromstr(PyString_AS_STRING(attr));
+ if (type==NULL) goto fail;
+ attr = shape;
+ if (!PyTuple_Check(attr)) {
+ PyErr_SetString(PyExc_TypeError, "shape must be a tuple");
+ Py_DECREF(type);
+ goto fail;
+ }
+ n = PyTuple_GET_SIZE(attr);
+ for (i=0; i<n; i++) {
+ item = PyTuple_GET_ITEM(attr, i);
+ dims[i] = PyArray_PyIntAsIntp(item);
+ if (error_converting(dims[i])) break;
+ }
+
+ ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, type,
+ n, dims,
+ NULL, data,
+ dataflags, NULL);
+ if (ret == NULL) return NULL;
+ Py_INCREF(base);
+ ret->base = base;
+
+ attr = PyDict_GetItemString(inter, "strides");
+ if (attr != NULL && attr != Py_None) {
if (!PyTuple_Check(attr)) {
- PyErr_SetString(PyExc_TypeError, "shape must be a tuple");
- Py_DECREF(type);
- goto fail;
+ PyErr_SetString(PyExc_TypeError,
+ "strides must be a tuple");
+ Py_DECREF(ret);
+ return NULL;
}
- n = PyTuple_GET_SIZE(attr);
- for (i=0; i<n; i++) {
- item = PyTuple_GET_ITEM(attr, i);
- dims[i] = PyArray_PyIntAsIntp(item);
- if (error_converting(dims[i])) break;
+ if (n != PyTuple_GET_SIZE(attr)) {
+ PyErr_SetString(PyExc_ValueError,
+ "mismatch in length of "\
+ "strides and shape");
+ Py_DECREF(ret);
+ return NULL;
}
-
- ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, type,
- n, dims,
- NULL, data,
- dataflags, NULL);
- if (ret == NULL) return NULL;
- Py_INCREF(base);
- ret->base = base;
-
- attr = PyDict_GetItemString(inter, "strides");
- if (attr != NULL && attr != Py_None) {
- if (!PyTuple_Check(attr)) {
- PyErr_SetString(PyExc_TypeError,
- "strides must be a tuple");
- Py_DECREF(ret);
- return NULL;
- }
- if (n != PyTuple_GET_SIZE(attr)) {
- PyErr_SetString(PyExc_ValueError,
- "mismatch in length of "\
- "strides and shape");
- Py_DECREF(ret);
- return NULL;
- }
- for (i=0; i<n; i++) {
- item = PyTuple_GET_ITEM(attr, i);
- strides[i] = PyArray_PyIntAsIntp(item);
- if (error_converting(strides[i])) break;
- }
- if (PyErr_Occurred()) PyErr_Clear();
- memcpy(ret->strides, strides, n*sizeof(intp));
+ for (i=0; i<n; i++) {
+ item = PyTuple_GET_ITEM(attr, i);
+ strides[i] = PyArray_PyIntAsIntp(item);
+ if (error_converting(strides[i])) break;
}
- else PyErr_Clear();
- PyArray_UpdateFlags(ret, UPDATE_ALL);
- Py_DECREF(inter);
- return (PyObject *)ret;
+ if (PyErr_Occurred()) PyErr_Clear();
+ memcpy(ret->strides, strides, n*sizeof(intp));
+ }
+ else PyErr_Clear();
+ PyArray_UpdateFlags(ret, UPDATE_ALL);
+ Py_DECREF(inter);
+ return (PyObject *)ret;
fail:
- Py_XDECREF(inter);
- return NULL;
+ Py_XDECREF(inter);
+ return NULL;
}
/*OBJECT_API*/
static PyObject *
PyArray_FromArrayAttr(PyObject *op, PyArray_Descr *typecode, PyObject *context)
{
- PyObject *new;
- PyObject *array_meth;
+ PyObject *new;
+ PyObject *array_meth;
- array_meth = PyObject_GetAttrString(op, "__array__");
- if (array_meth == NULL) {PyErr_Clear(); return Py_NotImplemented;}
- if (context == NULL) {
- if (typecode == NULL) new = PyObject_CallFunction(array_meth,
- NULL);
- else new = PyObject_CallFunction(array_meth, "O", typecode);
+ array_meth = PyObject_GetAttrString(op, "__array__");
+ if (array_meth == NULL) {PyErr_Clear(); return Py_NotImplemented;}
+ if (context == NULL) {
+ if (typecode == NULL) new = PyObject_CallFunction(array_meth,
+ NULL);
+ else new = PyObject_CallFunction(array_meth, "O", typecode);
+ }
+ else {
+ if (typecode == NULL) {
+ new = PyObject_CallFunction(array_meth, "OO", Py_None,
+ context);
+ if (new == NULL && \
+ PyErr_ExceptionMatches(PyExc_TypeError)) {
+ PyErr_Clear();
+ new = PyObject_CallFunction(array_meth, "");
+ }
}
else {
- if (typecode == NULL) {
- new = PyObject_CallFunction(array_meth, "OO", Py_None,
- context);
- if (new == NULL && \
- PyErr_ExceptionMatches(PyExc_TypeError)) {
- PyErr_Clear();
- new = PyObject_CallFunction(array_meth, "");
- }
- }
- else {
- new = PyObject_CallFunction(array_meth, "OO",
- typecode, context);
- if (new == NULL && \
- PyErr_ExceptionMatches(PyExc_TypeError)) {
- PyErr_Clear();
- new = PyObject_CallFunction(array_meth, "O",
- typecode);
- }
- }
- }
- Py_DECREF(array_meth);
- if (new == NULL) return NULL;
- if (!PyArray_Check(new)) {
- PyErr_SetString(PyExc_ValueError,
- "object __array__ method not " \
- "producing an array");
- Py_DECREF(new);
- return NULL;
+ new = PyObject_CallFunction(array_meth, "OO",
+ typecode, context);
+ if (new == NULL && \
+ PyErr_ExceptionMatches(PyExc_TypeError)) {
+ PyErr_Clear();
+ new = PyObject_CallFunction(array_meth, "O",
+ typecode);
+ }
}
- return new;
+ }
+ Py_DECREF(array_meth);
+ if (new == NULL) return NULL;
+ if (!PyArray_Check(new)) {
+ PyErr_SetString(PyExc_ValueError,
+ "object __array__ method not " \
+ "producing an array");
+ Py_DECREF(new);
+ return NULL;
+ }
+ return new;
}
/* Does not check for ENSURECOPY and NOTSWAPPED in flags */
@@ -8410,108 +8409,108 @@ static PyObject *
PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
int max_depth, int flags, PyObject *context)
{
- /* This is the main code to make a NumPy array from a Python
- Object. It is called from lot's of different places which
- is why there are so many checks. The comments try to
- explain some of the checks. */
-
- PyObject *r=NULL;
- int seq = FALSE;
-
- /* Is input object already an array? */
- /* This is where the flags are used */
- if (PyArray_Check(op))
- r = PyArray_FromArray((PyArrayObject *)op, newtype, flags);
- else if (PyArray_IsScalar(op, Generic)) {
- if (flags & UPDATEIFCOPY) goto err;
- r = PyArray_FromScalar(op, newtype);
- } else if (newtype == NULL &&
- (newtype = _array_find_python_scalar_type(op))) {
- if (flags & UPDATEIFCOPY) goto err;
- r = Array_FromPyScalar(op, newtype);
+ /* This is the main code to make a NumPy array from a Python
+ Object. It is called from lot's of different places which
+ is why there are so many checks. The comments try to
+ explain some of the checks. */
+
+ PyObject *r=NULL;
+ int seq = FALSE;
+
+ /* Is input object already an array? */
+ /* This is where the flags are used */
+ if (PyArray_Check(op))
+ r = PyArray_FromArray((PyArrayObject *)op, newtype, flags);
+ else if (PyArray_IsScalar(op, Generic)) {
+ if (flags & UPDATEIFCOPY) goto err;
+ r = PyArray_FromScalar(op, newtype);
+ } else if (newtype == NULL &&
+ (newtype = _array_find_python_scalar_type(op))) {
+ if (flags & UPDATEIFCOPY) goto err;
+ r = Array_FromPyScalar(op, newtype);
+ }
+ else if (PyArray_HasArrayInterfaceType(op, newtype, context, r)) {
+ PyObject *new;
+ if (r == NULL) {Py_XDECREF(newtype); return NULL;}
+ if (newtype != NULL || flags != 0) {
+ new = PyArray_FromArray((PyArrayObject *)r, newtype,
+ flags);
+ Py_DECREF(r);
+ r = new;
}
- else if (PyArray_HasArrayInterfaceType(op, newtype, context, r)) {
- PyObject *new;
- if (r == NULL) {Py_XDECREF(newtype); return NULL;}
- if (newtype != NULL || flags != 0) {
- new = PyArray_FromArray((PyArrayObject *)r, newtype,
- flags);
- Py_DECREF(r);
- r = new;
- }
+ }
+ else {
+ int isobject=0;
+ if (flags & UPDATEIFCOPY) goto err;
+ if (newtype == NULL) {
+ newtype = _array_find_type(op, NULL, MAX_DIMS);
}
- else {
- int isobject=0;
- if (flags & UPDATEIFCOPY) goto err;
- if (newtype == NULL) {
- newtype = _array_find_type(op, NULL, MAX_DIMS);
- }
- else if (newtype->type_num == PyArray_OBJECT) {
- isobject = 1;
- }
- if (PySequence_Check(op)) {
- PyObject *thiserr=NULL;
- /* necessary but not sufficient */
- Py_INCREF(newtype);
- r = Array_FromSequence(op, newtype, flags & FORTRAN,
- min_depth, max_depth);
- if (r == NULL && (thiserr=PyErr_Occurred())) {
- if (PyErr_GivenExceptionMatches(thiserr,
- PyExc_MemoryError))
- return NULL;
- /* If object was explicitly requested,
- then try nested list object array creation
- */
- PyErr_Clear();
- if (isobject) {
- Py_INCREF(newtype);
- r = ObjectArray_FromNestedList \
- (op, newtype, flags & FORTRAN);
- seq = TRUE;
- Py_DECREF(newtype);
- }
- }
- else {
- seq = TRUE;
- Py_DECREF(newtype);
- }
+ else if (newtype->type_num == PyArray_OBJECT) {
+ isobject = 1;
+ }
+ if (PySequence_Check(op)) {
+ PyObject *thiserr=NULL;
+ /* necessary but not sufficient */
+ Py_INCREF(newtype);
+ r = Array_FromSequence(op, newtype, flags & FORTRAN,
+ min_depth, max_depth);
+ if (r == NULL && (thiserr=PyErr_Occurred())) {
+ if (PyErr_GivenExceptionMatches(thiserr,
+ PyExc_MemoryError))
+ return NULL;
+ /* If object was explicitly requested,
+ then try nested list object array creation
+ */
+ PyErr_Clear();
+ if (isobject) {
+ Py_INCREF(newtype);
+ r = ObjectArray_FromNestedList \
+ (op, newtype, flags & FORTRAN);
+ seq = TRUE;
+ Py_DECREF(newtype);
}
- if (!seq)
- r = Array_FromPyScalar(op, newtype);
+ }
+ else {
+ seq = TRUE;
+ Py_DECREF(newtype);
+ }
}
+ if (!seq)
+ r = Array_FromPyScalar(op, newtype);
+ }
- /* If we didn't succeed return NULL */
- if (r == NULL) return NULL;
+ /* If we didn't succeed return NULL */
+ if (r == NULL) return NULL;
- /* Be sure we succeed here */
+ /* Be sure we succeed here */
- if(!PyArray_Check(r)) {
- PyErr_SetString(PyExc_RuntimeError,
- "internal error: PyArray_FromAny "\
- "not producing an array");
- Py_DECREF(r);
- return NULL;
- }
+ if(!PyArray_Check(r)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "internal error: PyArray_FromAny "\
+ "not producing an array");
+ Py_DECREF(r);
+ return NULL;
+ }
- if (min_depth != 0 && ((PyArrayObject *)r)->nd < min_depth) {
- PyErr_SetString(PyExc_ValueError,
- "object of too small depth for desired array");
- Py_DECREF(r);
- return NULL;
- }
- if (max_depth != 0 && ((PyArrayObject *)r)->nd > max_depth) {
- PyErr_SetString(PyExc_ValueError,
- "object too deep for desired array");
- Py_DECREF(r);
- return NULL;
- }
- return r;
+ if (min_depth != 0 && ((PyArrayObject *)r)->nd < min_depth) {
+ PyErr_SetString(PyExc_ValueError,
+ "object of too small depth for desired array");
+ Py_DECREF(r);
+ return NULL;
+ }
+ if (max_depth != 0 && ((PyArrayObject *)r)->nd > max_depth) {
+ PyErr_SetString(PyExc_ValueError,
+ "object too deep for desired array");
+ Py_DECREF(r);
+ return NULL;
+ }
+ return r;
err:
- Py_XDECREF(newtype);
- PyErr_SetString(PyExc_TypeError,
- "UPDATEIFCOPY used for non-array input.");
- return NULL;
+ Py_XDECREF(newtype);
+ PyErr_SetString(PyExc_TypeError,
+ "UPDATEIFCOPY used for non-array input.");
+ return NULL;
}
/* new reference -- accepts NULL for mintype*/
@@ -8519,41 +8518,41 @@ PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
static PyArray_Descr *
PyArray_DescrFromObject(PyObject *op, PyArray_Descr *mintype)
{
- return _array_find_type(op, mintype, MAX_DIMS);
+ return _array_find_type(op, mintype, MAX_DIMS);
}
/*OBJECT_API
- Return the typecode of the array a Python object would be converted
- to
+ Return the typecode of the array a Python object would be converted
+ to
*/
static int
PyArray_ObjectType(PyObject *op, int minimum_type)
{
- PyArray_Descr *intype;
- PyArray_Descr *outtype;
- int ret;
+ PyArray_Descr *intype;
+ PyArray_Descr *outtype;
+ int ret;
- intype = PyArray_DescrFromType(minimum_type);
- if (intype == NULL) PyErr_Clear();
- outtype = _array_find_type(op, intype, MAX_DIMS);
- ret = outtype->type_num;
- Py_DECREF(outtype);
- Py_XDECREF(intype);
- return ret;
+ intype = PyArray_DescrFromType(minimum_type);
+ if (intype == NULL) PyErr_Clear();
+ outtype = _array_find_type(op, intype, MAX_DIMS);
+ ret = outtype->type_num;
+ Py_DECREF(outtype);
+ Py_XDECREF(intype);
+ return ret;
}
/* flags is any of
- CONTIGUOUS,
- FORTRAN,
- ALIGNED,
- WRITEABLE,
- NOTSWAPPED,
- ENSURECOPY,
- UPDATEIFCOPY,
- FORCECAST,
- ENSUREARRAY,
- ELEMENTSTRIDES
+ CONTIGUOUS,
+ FORTRAN,
+ ALIGNED,
+ WRITEABLE,
+ NOTSWAPPED,
+ ENSURECOPY,
+ UPDATEIFCOPY,
+ FORCECAST,
+ ENSUREARRAY,
+ ELEMENTSTRIDES
or'd (|) together
@@ -8590,35 +8589,35 @@ static PyObject *
PyArray_CheckFromAny(PyObject *op, PyArray_Descr *descr, int min_depth,
int max_depth, int requires, PyObject *context)
{
- PyObject *obj;
- if (requires & NOTSWAPPED) {
- if (!descr && PyArray_Check(op) && \
- !PyArray_ISNBO(PyArray_DESCR(op)->byteorder)) {
- descr = PyArray_DescrNew(PyArray_DESCR(op));
- }
- else if (descr && !PyArray_ISNBO(descr->byteorder)) {
- PyArray_DESCR_REPLACE(descr);
- }
- if (descr) {
- descr->byteorder = PyArray_NATIVE;
- }
+ PyObject *obj;
+ if (requires & NOTSWAPPED) {
+ if (!descr && PyArray_Check(op) && \
+ !PyArray_ISNBO(PyArray_DESCR(op)->byteorder)) {
+ descr = PyArray_DescrNew(PyArray_DESCR(op));
}
-
- obj = PyArray_FromAny(op, descr, min_depth, max_depth,
- requires, context);
- if (obj == NULL) return NULL;
- if ((requires & ELEMENTSTRIDES) &&
- !PyArray_ElementStrides(obj)) {
- PyObject *new;
- new = PyArray_NewCopy((PyArrayObject *)obj, PyArray_ANYORDER);
- Py_DECREF(obj);
- obj = new;
+ else if (descr && !PyArray_ISNBO(descr->byteorder)) {
+ PyArray_DESCR_REPLACE(descr);
}
- return obj;
+ if (descr) {
+ descr->byteorder = PyArray_NATIVE;
+ }
+ }
+
+ obj = PyArray_FromAny(op, descr, min_depth, max_depth,
+ requires, context);
+ if (obj == NULL) return NULL;
+ if ((requires & ELEMENTSTRIDES) &&
+ !PyArray_ElementStrides(obj)) {
+ PyObject *new;
+ new = PyArray_NewCopy((PyArrayObject *)obj, PyArray_ANYORDER);
+ Py_DECREF(obj);
+ obj = new;
+ }
+ return obj;
}
/* This is a quick wrapper around PyArray_FromAny(op, NULL, 0, 0,
- ENSUREARRAY) */
+ ENSUREARRAY) */
/* that special cases Arrays and PyArray_Scalars up front */
/* It *steals a reference* to the object */
/* It also guarantees that the result is PyArray_Type */
@@ -8630,139 +8629,139 @@ PyArray_CheckFromAny(PyObject *op, PyArray_Descr *descr, int min_depth,
static PyObject *
PyArray_EnsureArray(PyObject *op)
{
- PyObject *new;
+ PyObject *new;
- if (op == NULL) return NULL;
+ if (op == NULL) return NULL;
- if (PyArray_CheckExact(op)) return op;
+ if (PyArray_CheckExact(op)) return op;
- if (PyArray_Check(op)) {
- new = PyArray_View((PyArrayObject *)op, NULL, &PyArray_Type);
- Py_DECREF(op);
- return new;
- }
- if (PyArray_IsScalar(op, Generic)) {
- new = PyArray_FromScalar(op, NULL);
- Py_DECREF(op);
- return new;
- }
- new = PyArray_FromAny(op, NULL, 0, 0, ENSUREARRAY, NULL);
+ if (PyArray_Check(op)) {
+ new = PyArray_View((PyArrayObject *)op, NULL, &PyArray_Type);
Py_DECREF(op);
return new;
+ }
+ if (PyArray_IsScalar(op, Generic)) {
+ new = PyArray_FromScalar(op, NULL);
+ Py_DECREF(op);
+ return new;
+ }
+ new = PyArray_FromAny(op, NULL, 0, 0, ENSUREARRAY, NULL);
+ Py_DECREF(op);
+ return new;
}
/*OBJECT_API*/
static PyObject *
PyArray_EnsureAnyArray(PyObject *op)
{
- if (op && PyArray_Check(op)) return op;
- return PyArray_EnsureArray(op);
+ if (op && PyArray_Check(op)) return op;
+ return PyArray_EnsureArray(op);
}
/*OBJECT_API
- Check the type coercion rules.
+ Check the type coercion rules.
*/
static int
PyArray_CanCastSafely(int fromtype, int totype)
{
- PyArray_Descr *from, *to;
- register int felsize, telsize;
-
- if (fromtype == totype) return 1;
- if (fromtype == PyArray_BOOL) return 1;
- if (totype == PyArray_BOOL) return 0;
- if (totype == PyArray_OBJECT || totype == PyArray_VOID) return 1;
- if (fromtype == PyArray_OBJECT || fromtype == PyArray_VOID) return 0;
-
- from = PyArray_DescrFromType(fromtype);
- /* cancastto is a PyArray_NOTYPE terminated C-int-array of types that
- the data-type can be cast to safely.
- */
- if (from->f->cancastto) {
- int *curtype;
- curtype = from->f->cancastto;
- while (*curtype != PyArray_NOTYPE) {
- if (*curtype++ == totype) return 1;
- }
+ PyArray_Descr *from, *to;
+ register int felsize, telsize;
+
+ if (fromtype == totype) return 1;
+ if (fromtype == PyArray_BOOL) return 1;
+ if (totype == PyArray_BOOL) return 0;
+ if (totype == PyArray_OBJECT || totype == PyArray_VOID) return 1;
+ if (fromtype == PyArray_OBJECT || fromtype == PyArray_VOID) return 0;
+
+ from = PyArray_DescrFromType(fromtype);
+ /* cancastto is a PyArray_NOTYPE terminated C-int-array of types that
+ the data-type can be cast to safely.
+ */
+ if (from->f->cancastto) {
+ int *curtype;
+ curtype = from->f->cancastto;
+ while (*curtype != PyArray_NOTYPE) {
+ if (*curtype++ == totype) return 1;
}
- if (PyTypeNum_ISUSERDEF(totype)) return 0;
-
- to = PyArray_DescrFromType(totype);
- telsize = to->elsize;
- felsize = from->elsize;
- Py_DECREF(from);
- Py_DECREF(to);
-
- switch(fromtype) {
- case PyArray_BYTE:
- case PyArray_SHORT:
- case PyArray_INT:
- case PyArray_LONG:
- case PyArray_LONGLONG:
- if (PyTypeNum_ISINTEGER(totype)) {
- if (PyTypeNum_ISUNSIGNED(totype)) {
- return 0;
- }
- else {
- return (telsize >= felsize);
- }
- }
- else if (PyTypeNum_ISFLOAT(totype)) {
- if (felsize < 8)
- return (telsize > felsize);
- else
- return (telsize >= felsize);
- }
- else if (PyTypeNum_ISCOMPLEX(totype)) {
- if (felsize < 8)
- return ((telsize >> 1) > felsize);
- else
- return ((telsize >> 1) >= felsize);
- }
- else return totype > fromtype;
- case PyArray_UBYTE:
- case PyArray_USHORT:
- case PyArray_UINT:
- case PyArray_ULONG:
- case PyArray_ULONGLONG:
- if (PyTypeNum_ISINTEGER(totype)) {
- if (PyTypeNum_ISSIGNED(totype)) {
- return (telsize > felsize);
- }
- else {
- return (telsize >= felsize);
- }
- }
- else if (PyTypeNum_ISFLOAT(totype)) {
- if (felsize < 8)
- return (telsize > felsize);
- else
- return (telsize >= felsize);
- }
- else if (PyTypeNum_ISCOMPLEX(totype)) {
- if (felsize < 8)
- return ((telsize >> 1) > felsize);
- else
- return ((telsize >> 1) >= felsize);
- }
- else return totype > fromtype;
- case PyArray_FLOAT:
- case PyArray_DOUBLE:
- case PyArray_LONGDOUBLE:
- if (PyTypeNum_ISCOMPLEX(totype))
- return ((telsize >> 1) >= felsize);
- else
- return (totype > fromtype);
- case PyArray_CFLOAT:
- case PyArray_CDOUBLE:
- case PyArray_CLONGDOUBLE:
- return (totype > fromtype);
- case PyArray_STRING:
- case PyArray_UNICODE:
- return (totype > fromtype);
- default:
+ }
+ if (PyTypeNum_ISUSERDEF(totype)) return 0;
+
+ to = PyArray_DescrFromType(totype);
+ telsize = to->elsize;
+ felsize = from->elsize;
+ Py_DECREF(from);
+ Py_DECREF(to);
+
+ switch(fromtype) {
+ case PyArray_BYTE:
+ case PyArray_SHORT:
+ case PyArray_INT:
+ case PyArray_LONG:
+ case PyArray_LONGLONG:
+ if (PyTypeNum_ISINTEGER(totype)) {
+ if (PyTypeNum_ISUNSIGNED(totype)) {
return 0;
+ }
+ else {
+ return (telsize >= felsize);
+ }
+ }
+ else if (PyTypeNum_ISFLOAT(totype)) {
+ if (felsize < 8)
+ return (telsize > felsize);
+ else
+ return (telsize >= felsize);
+ }
+ else if (PyTypeNum_ISCOMPLEX(totype)) {
+ if (felsize < 8)
+ return ((telsize >> 1) > felsize);
+ else
+ return ((telsize >> 1) >= felsize);
+ }
+ else return totype > fromtype;
+ case PyArray_UBYTE:
+ case PyArray_USHORT:
+ case PyArray_UINT:
+ case PyArray_ULONG:
+ case PyArray_ULONGLONG:
+ if (PyTypeNum_ISINTEGER(totype)) {
+ if (PyTypeNum_ISSIGNED(totype)) {
+ return (telsize > felsize);
+ }
+ else {
+ return (telsize >= felsize);
+ }
}
+ else if (PyTypeNum_ISFLOAT(totype)) {
+ if (felsize < 8)
+ return (telsize > felsize);
+ else
+ return (telsize >= felsize);
+ }
+ else if (PyTypeNum_ISCOMPLEX(totype)) {
+ if (felsize < 8)
+ return ((telsize >> 1) > felsize);
+ else
+ return ((telsize >> 1) >= felsize);
+ }
+ else return totype > fromtype;
+ case PyArray_FLOAT:
+ case PyArray_DOUBLE:
+ case PyArray_LONGDOUBLE:
+ if (PyTypeNum_ISCOMPLEX(totype))
+ return ((telsize >> 1) >= felsize);
+ else
+ return (totype > fromtype);
+ case PyArray_CFLOAT:
+ case PyArray_CDOUBLE:
+ case PyArray_CLONGDOUBLE:
+ return (totype > fromtype);
+ case PyArray_STRING:
+ case PyArray_UNICODE:
+ return (totype > fromtype);
+ default:
+ return 0;
+ }
}
/* leaves reference count alone --- cannot be NULL*/
@@ -8770,48 +8769,48 @@ PyArray_CanCastSafely(int fromtype, int totype)
static Bool
PyArray_CanCastTo(PyArray_Descr *from, PyArray_Descr *to)
{
- int fromtype=from->type_num;
- int totype=to->type_num;
- Bool ret;
-
- ret = (Bool) PyArray_CanCastSafely(fromtype, totype);
- if (ret) { /* Check String and Unicode more closely */
- if (fromtype == PyArray_STRING) {
- if (totype == PyArray_STRING) {
- ret = (from->elsize <= to->elsize);
- }
- else if (totype == PyArray_UNICODE) {
- ret = (from->elsize << 2 \
- <= to->elsize);
- }
- }
- else if (fromtype == PyArray_UNICODE) {
- if (totype == PyArray_UNICODE) {
- ret = (from->elsize <= to->elsize);
- }
- }
- /* TODO: If totype is STRING or unicode
- see if the length is long enough to hold the
- stringified value of the object.
- */
+ int fromtype=from->type_num;
+ int totype=to->type_num;
+ Bool ret;
+
+ ret = (Bool) PyArray_CanCastSafely(fromtype, totype);
+ if (ret) { /* Check String and Unicode more closely */
+ if (fromtype == PyArray_STRING) {
+ if (totype == PyArray_STRING) {
+ ret = (from->elsize <= to->elsize);
+ }
+ else if (totype == PyArray_UNICODE) {
+ ret = (from->elsize << 2 \
+ <= to->elsize);
+ }
}
- return ret;
+ else if (fromtype == PyArray_UNICODE) {
+ if (totype == PyArray_UNICODE) {
+ ret = (from->elsize <= to->elsize);
+ }
+ }
+ /* TODO: If totype is STRING or unicode
+ see if the length is long enough to hold the
+ stringified value of the object.
+ */
+ }
+ return ret;
}
/*OBJECT_API
See if array scalars can be cast.
- */
+*/
static Bool
PyArray_CanCastScalar(PyTypeObject *from, PyTypeObject *to)
{
- int fromtype;
- int totype;
+ int fromtype;
+ int totype;
- fromtype = _typenum_fromtypeobj((PyObject *)from, 0);
- totype = _typenum_fromtypeobj((PyObject *)to, 0);
- if (fromtype == PyArray_NOTYPE || totype == PyArray_NOTYPE)
- return FALSE;
- return (Bool) PyArray_CanCastSafely(fromtype, totype);
+ fromtype = _typenum_fromtypeobj((PyObject *)from, 0);
+ totype = _typenum_fromtypeobj((PyObject *)to, 0);
+ if (fromtype == PyArray_NOTYPE || totype == PyArray_NOTYPE)
+ return FALSE;
+ return (Bool) PyArray_CanCastSafely(fromtype, totype);
}
@@ -8820,110 +8819,110 @@ PyArray_CanCastScalar(PyTypeObject *from, PyTypeObject *to)
/* and Python's array iterator ***/
/*OBJECT_API
- Get Iterator.
+ Get Iterator.
*/
static PyObject *
PyArray_IterNew(PyObject *obj)
{
- PyArrayIterObject *it;
- int i, nd;
- PyArrayObject *ao = (PyArrayObject *)obj;
+ PyArrayIterObject *it;
+ int i, nd;
+ PyArrayObject *ao = (PyArrayObject *)obj;
- if (!PyArray_Check(ao)) {
- PyErr_BadInternalCall();
- return NULL;
- }
+ if (!PyArray_Check(ao)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
- it = (PyArrayIterObject *)_pya_malloc(sizeof(PyArrayIterObject));
- PyObject_Init((PyObject *)it, &PyArrayIter_Type);
- /* it = PyObject_New(PyArrayIterObject, &PyArrayIter_Type);*/
- if (it == NULL)
- return NULL;
+ it = (PyArrayIterObject *)_pya_malloc(sizeof(PyArrayIterObject));
+ PyObject_Init((PyObject *)it, &PyArrayIter_Type);
+ /* it = PyObject_New(PyArrayIterObject, &PyArrayIter_Type);*/
+ if (it == NULL)
+ return NULL;
- nd = ao->nd;
- PyArray_UpdateFlags(ao, CONTIGUOUS);
- if PyArray_ISCONTIGUOUS(ao) it->contiguous = 1;
- else it->contiguous = 0;
- Py_INCREF(ao);
- it->ao = ao;
- it->size = PyArray_SIZE(ao);
- it->nd_m1 = nd - 1;
- it->factors[nd-1] = 1;
- for (i=0; i < nd; i++) {
- it->dims_m1[i] = ao->dimensions[i] - 1;
- it->strides[i] = ao->strides[i];
- it->backstrides[i] = it->strides[i] * \
- it->dims_m1[i];
- if (i > 0)
- it->factors[nd-i-1] = it->factors[nd-i] * \
- ao->dimensions[nd-i];
- }
- PyArray_ITER_RESET(it);
+ nd = ao->nd;
+ PyArray_UpdateFlags(ao, CONTIGUOUS);
+ if PyArray_ISCONTIGUOUS(ao) it->contiguous = 1;
+ else it->contiguous = 0;
+ Py_INCREF(ao);
+ it->ao = ao;
+ it->size = PyArray_SIZE(ao);
+ it->nd_m1 = nd - 1;
+ it->factors[nd-1] = 1;
+ for (i=0; i < nd; i++) {
+ it->dims_m1[i] = ao->dimensions[i] - 1;
+ it->strides[i] = ao->strides[i];
+ it->backstrides[i] = it->strides[i] * \
+ it->dims_m1[i];
+ if (i > 0)
+ it->factors[nd-i-1] = it->factors[nd-i] * \
+ ao->dimensions[nd-i];
+ }
+ PyArray_ITER_RESET(it);
- return (PyObject *)it;
+ return (PyObject *)it;
}
/*MULTIARRAY_API
Get Iterator broadcast to a particular shape
- */
+*/
static PyObject *
PyArray_BroadcastToShape(PyObject *obj, intp *dims, int nd)
{
- PyArrayIterObject *it;
- int i, diff, j, compat, k;
- PyArrayObject *ao = (PyArrayObject *)obj;
-
- if (ao->nd > nd) goto err;
- compat = 1;
- diff = j = nd - ao->nd;
- for (i=0; i<ao->nd; i++, j++) {
- if (ao->dimensions[i] == 1) continue;
- if (ao->dimensions[i] != dims[j]) {
- compat = 0;
- break;
- }
+ PyArrayIterObject *it;
+ int i, diff, j, compat, k;
+ PyArrayObject *ao = (PyArrayObject *)obj;
+
+ if (ao->nd > nd) goto err;
+ compat = 1;
+ diff = j = nd - ao->nd;
+ for (i=0; i<ao->nd; i++, j++) {
+ if (ao->dimensions[i] == 1) continue;
+ if (ao->dimensions[i] != dims[j]) {
+ compat = 0;
+ break;
}
- if (!compat) goto err;
+ }
+ if (!compat) goto err;
- it = (PyArrayIterObject *)_pya_malloc(sizeof(PyArrayIterObject));
- PyObject_Init((PyObject *)it, &PyArrayIter_Type);
+ it = (PyArrayIterObject *)_pya_malloc(sizeof(PyArrayIterObject));
+ PyObject_Init((PyObject *)it, &PyArrayIter_Type);
- if (it == NULL)
- return NULL;
+ if (it == NULL)
+ return NULL;
- PyArray_UpdateFlags(ao, CONTIGUOUS);
- if PyArray_ISCONTIGUOUS(ao) it->contiguous = 1;
- else it->contiguous = 0;
- Py_INCREF(ao);
- it->ao = ao;
- it->size = PyArray_MultiplyList(dims, nd);
- it->nd_m1 = nd - 1;
- it->factors[nd-1] = 1;
- for (i=0; i < nd; i++) {
- it->dims_m1[i] = dims[i] - 1;
- k = i - diff;
- if ((k < 0) ||
- ao->dimensions[k] != dims[i]) {
- it->contiguous = 0;
- it->strides[i] = 0;
- }
- else {
- it->strides[i] = ao->strides[k];
- }
- it->backstrides[i] = it->strides[i] * \
- it->dims_m1[i];
- if (i > 0)
- it->factors[nd-i-1] = it->factors[nd-i] * \
- dims[nd-i];
+ PyArray_UpdateFlags(ao, CONTIGUOUS);
+ if PyArray_ISCONTIGUOUS(ao) it->contiguous = 1;
+ else it->contiguous = 0;
+ Py_INCREF(ao);
+ it->ao = ao;
+ it->size = PyArray_MultiplyList(dims, nd);
+ it->nd_m1 = nd - 1;
+ it->factors[nd-1] = 1;
+ for (i=0; i < nd; i++) {
+ it->dims_m1[i] = dims[i] - 1;
+ k = i - diff;
+ if ((k < 0) ||
+ ao->dimensions[k] != dims[i]) {
+ it->contiguous = 0;
+ it->strides[i] = 0;
}
- PyArray_ITER_RESET(it);
+ else {
+ it->strides[i] = ao->strides[k];
+ }
+ it->backstrides[i] = it->strides[i] * \
+ it->dims_m1[i];
+ if (i > 0)
+ it->factors[nd-i-1] = it->factors[nd-i] * \
+ dims[nd-i];
+ }
+ PyArray_ITER_RESET(it);
- return (PyObject *)it;
+ return (PyObject *)it;
err:
- PyErr_SetString(PyExc_ValueError, "array is not broadcastable to "\
- "correct shape");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "array is not broadcastable to "\
+ "correct shape");
+ return NULL;
}
@@ -8931,49 +8930,49 @@ PyArray_BroadcastToShape(PyObject *obj, intp *dims, int nd)
/*OBJECT_API
- Get Iterator that iterates over all but one axis (don't use this with
- PyArray_ITER_GOTO1D). The axis will be over-written if negative
- with the axis having the smallest stride.
+ Get Iterator that iterates over all but one axis (don't use this with
+ PyArray_ITER_GOTO1D). The axis will be over-written if negative
+ with the axis having the smallest stride.
*/
static PyObject *
PyArray_IterAllButAxis(PyObject *obj, int *inaxis)
{
- PyArrayIterObject *it;
- int axis;
- it = (PyArrayIterObject *)PyArray_IterNew(obj);
- if (it == NULL) return NULL;
-
- if (PyArray_NDIM(obj)==0)
- return (PyObject *)it;
- if (*inaxis < 0) {
- int i, minaxis=0;
- intp minstride=0;
- i = 0;
- while (minstride==0 && i<PyArray_NDIM(obj)) {
- minstride = PyArray_STRIDE(obj,i);
- i++;
- }
- for (i=1; i<PyArray_NDIM(obj); i++) {
- if (PyArray_STRIDE(obj,i) > 0 &&
- PyArray_STRIDE(obj, i) < minstride) {
- minaxis = i;
- minstride = PyArray_STRIDE(obj,i);
- }
- }
- *inaxis = minaxis;
- }
- axis = *inaxis;
- /* adjust so that will not iterate over axis */
- it->contiguous = 0;
- if (it->size != 0) {
- it->size /= PyArray_DIM(obj,axis);
- }
- it->dims_m1[axis] = 0;
- it->backstrides[axis] = 0;
+ PyArrayIterObject *it;
+ int axis;
+ it = (PyArrayIterObject *)PyArray_IterNew(obj);
+ if (it == NULL) return NULL;
- /* (won't fix factors so don't use
- PyArray_ITER_GOTO1D with this iterator) */
+ if (PyArray_NDIM(obj)==0)
return (PyObject *)it;
+ if (*inaxis < 0) {
+ int i, minaxis=0;
+ intp minstride=0;
+ i = 0;
+ while (minstride==0 && i<PyArray_NDIM(obj)) {
+ minstride = PyArray_STRIDE(obj,i);
+ i++;
+ }
+ for (i=1; i<PyArray_NDIM(obj); i++) {
+ if (PyArray_STRIDE(obj,i) > 0 &&
+ PyArray_STRIDE(obj, i) < minstride) {
+ minaxis = i;
+ minstride = PyArray_STRIDE(obj,i);
+ }
+ }
+ *inaxis = minaxis;
+ }
+ axis = *inaxis;
+ /* adjust so that will not iterate over axis */
+ it->contiguous = 0;
+ if (it->size != 0) {
+ it->size /= PyArray_DIM(obj,axis);
+ }
+ it->dims_m1[axis] = 0;
+ it->backstrides[axis] = 0;
+
+ /* (won't fix factors so don't use
+ PyArray_ITER_GOTO1D with this iterator) */
+ return (PyObject *)it;
}
@@ -8981,50 +8980,50 @@ PyArray_IterAllButAxis(PyObject *obj, int *inaxis)
adjusted */
/*OBJECT_API
- Adjusts previously broadcasted iterators so that the axis with
+ Adjusts previously broadcasted iterators so that the axis with
the smallest sum of iterator strides is not iterated over.
Returns dimension which is smallest in the range [0,multi->nd).
A -1 is returned if multi->nd == 0.
- */
+*/
static int
PyArray_RemoveSmallest(PyArrayMultiIterObject *multi)
{
- PyArrayIterObject *it;
- int i, j;
- int axis;
- intp smallest;
- intp sumstrides[NPY_MAXDIMS];
+ PyArrayIterObject *it;
+ int i, j;
+ int axis;
+ intp smallest;
+ intp sumstrides[NPY_MAXDIMS];
- if (multi->nd == 0) return -1;
+ if (multi->nd == 0) return -1;
- for (i=0; i<multi->nd; i++) {
- sumstrides[i] = 0;
- for (j=0; j<multi->numiter; j++) {
- sumstrides[i] += multi->iters[j]->strides[i];
- }
+ for (i=0; i<multi->nd; i++) {
+ sumstrides[i] = 0;
+ for (j=0; j<multi->numiter; j++) {
+ sumstrides[i] += multi->iters[j]->strides[i];
}
- axis=0;
- smallest = sumstrides[0];
- /* Find longest dimension */
- for (i=1; i<multi->nd; i++) {
- if (sumstrides[i] < smallest) {
- axis = i;
- smallest = sumstrides[i];
- }
+ }
+ axis=0;
+ smallest = sumstrides[0];
+ /* Find longest dimension */
+ for (i=1; i<multi->nd; i++) {
+ if (sumstrides[i] < smallest) {
+ axis = i;
+ smallest = sumstrides[i];
}
+ }
- for (i=0; i<multi->numiter; i++) {
- it = multi->iters[i];
- it->contiguous = 0;
- if (it->size != 0)
- it->size /= (it->dims_m1[axis]+1);
- it->dims_m1[axis] = 0;
- it->backstrides[axis] = 0;
- }
+ for (i=0; i<multi->numiter; i++) {
+ it = multi->iters[i];
+ it->contiguous = 0;
+ if (it->size != 0)
+ it->size /= (it->dims_m1[axis]+1);
+ it->dims_m1[axis] = 0;
+ it->backstrides[axis] = 0;
+ }
- multi->size = multi->iters[0]->size;
- return axis;
+ multi->size = multi->iters[0]->size;
+ return axis;
}
/* Returns an array scalar holding the element desired */
@@ -9032,294 +9031,294 @@ PyArray_RemoveSmallest(PyArrayMultiIterObject *multi)
static PyObject *
arrayiter_next(PyArrayIterObject *it)
{
- PyObject *ret;
+ PyObject *ret;
- if (it->index < it->size) {
- ret = PyArray_ToScalar(it->dataptr, it->ao);
- PyArray_ITER_NEXT(it);
- return ret;
- }
- return NULL;
+ if (it->index < it->size) {
+ ret = PyArray_ToScalar(it->dataptr, it->ao);
+ PyArray_ITER_NEXT(it);
+ return ret;
+ }
+ return NULL;
}
static void
arrayiter_dealloc(PyArrayIterObject *it)
{
- Py_XDECREF(it->ao);
- _pya_free(it);
+ Py_XDECREF(it->ao);
+ _pya_free(it);
}
static Py_ssize_t
iter_length(PyArrayIterObject *self)
{
- return self->size;
+ return self->size;
}
static PyObject *
iter_subscript_Bool(PyArrayIterObject *self, PyArrayObject *ind)
{
- int index, strides, itemsize;
- intp count=0;
- char *dptr, *optr;
- PyObject *r;
- int swap;
- PyArray_CopySwapFunc *copyswap;
+ int index, strides, itemsize;
+ intp count=0;
+ char *dptr, *optr;
+ PyObject *r;
+ int swap;
+ PyArray_CopySwapFunc *copyswap;
- if (ind->nd != 1) {
- PyErr_SetString(PyExc_ValueError,
- "boolean index array should have 1 dimension");
- return NULL;
- }
- index = ind->dimensions[0];
- if (index > self->size) {
- PyErr_SetString(PyExc_ValueError,
- "too many boolean indices");
- return NULL;
- }
-
- strides = ind->strides[0];
- dptr = ind->data;
- /* Get size of return array */
- while(index--) {
- if (*((Bool *)dptr) != 0)
- count++;
- dptr += strides;
- }
- itemsize = self->ao->descr->elsize;
- Py_INCREF(self->ao->descr);
- r = PyArray_NewFromDescr(self->ao->ob_type,
- self->ao->descr, 1, &count,
- NULL, NULL,
- 0, (PyObject *)self->ao);
- if (r==NULL) return NULL;
-
- /* Set up loop */
- optr = PyArray_DATA(r);
- index = ind->dimensions[0];
- dptr = ind->data;
+ if (ind->nd != 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "boolean index array should have 1 dimension");
+ return NULL;
+ }
+ index = ind->dimensions[0];
+ if (index > self->size) {
+ PyErr_SetString(PyExc_ValueError,
+ "too many boolean indices");
+ return NULL;
+ }
- copyswap = self->ao->descr->f->copyswap;
- /* Loop over Boolean array */
- swap = (PyArray_ISNOTSWAPPED(self->ao) != PyArray_ISNOTSWAPPED(r));
- while(index--) {
- if (*((Bool *)dptr) != 0) {
- copyswap(optr, self->dataptr, swap, self->ao);
- optr += itemsize;
- }
- dptr += strides;
- PyArray_ITER_NEXT(self);
- }
- PyArray_ITER_RESET(self);
- return r;
+ strides = ind->strides[0];
+ dptr = ind->data;
+ /* Get size of return array */
+ while(index--) {
+ if (*((Bool *)dptr) != 0)
+ count++;
+ dptr += strides;
+ }
+ itemsize = self->ao->descr->elsize;
+ Py_INCREF(self->ao->descr);
+ r = PyArray_NewFromDescr(self->ao->ob_type,
+ self->ao->descr, 1, &count,
+ NULL, NULL,
+ 0, (PyObject *)self->ao);
+ if (r==NULL) return NULL;
+
+ /* Set up loop */
+ optr = PyArray_DATA(r);
+ index = ind->dimensions[0];
+ dptr = ind->data;
+
+ copyswap = self->ao->descr->f->copyswap;
+ /* Loop over Boolean array */
+ swap = (PyArray_ISNOTSWAPPED(self->ao) != PyArray_ISNOTSWAPPED(r));
+ while(index--) {
+ if (*((Bool *)dptr) != 0) {
+ copyswap(optr, self->dataptr, swap, self->ao);
+ optr += itemsize;
+ }
+ dptr += strides;
+ PyArray_ITER_NEXT(self);
+ }
+ PyArray_ITER_RESET(self);
+ return r;
}
static PyObject *
iter_subscript_int(PyArrayIterObject *self, PyArrayObject *ind)
{
- intp num;
- PyObject *r;
- PyArrayIterObject *ind_it;
- int itemsize;
- int swap;
- char *optr;
- int index;
- PyArray_CopySwapFunc *copyswap;
-
- itemsize = self->ao->descr->elsize;
- if (ind->nd == 0) {
- num = *((intp *)ind->data);
- if (num < 0) num += self->size;
- if (num < 0 || num >= self->size) {
- PyErr_Format(PyExc_IndexError,
- "index %d out of bounds" \
- " 0<=index<%d", (int) num,
- (int) self->size);
- r = NULL;
- }
- else {
- PyArray_ITER_GOTO1D(self, num);
- r = PyArray_ToScalar(self->dataptr, self->ao);
- }
- PyArray_ITER_RESET(self);
- return r;
+ intp num;
+ PyObject *r;
+ PyArrayIterObject *ind_it;
+ int itemsize;
+ int swap;
+ char *optr;
+ int index;
+ PyArray_CopySwapFunc *copyswap;
+
+ itemsize = self->ao->descr->elsize;
+ if (ind->nd == 0) {
+ num = *((intp *)ind->data);
+ if (num < 0) num += self->size;
+ if (num < 0 || num >= self->size) {
+ PyErr_Format(PyExc_IndexError,
+ "index %d out of bounds" \
+ " 0<=index<%d", (int) num,
+ (int) self->size);
+ r = NULL;
}
-
- Py_INCREF(self->ao->descr);
- r = PyArray_NewFromDescr(self->ao->ob_type, self->ao->descr,
- ind->nd, ind->dimensions,
- NULL, NULL,
- 0, (PyObject *)self->ao);
- if (r==NULL) return NULL;
-
- optr = PyArray_DATA(r);
- ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
- if (ind_it == NULL) {Py_DECREF(r); return NULL;}
- index = ind_it->size;
- copyswap = PyArray_DESCR(r)->f->copyswap;
- swap = (PyArray_ISNOTSWAPPED(r) != PyArray_ISNOTSWAPPED(self->ao));
- while(index--) {
- num = *((intp *)(ind_it->dataptr));
- if (num < 0) num += self->size;
- if (num < 0 || num >= self->size) {
- PyErr_Format(PyExc_IndexError,
- "index %d out of bounds" \
- " 0<=index<%d", (int) num,
- (int) self->size);
- Py_DECREF(ind_it);
- Py_DECREF(r);
- PyArray_ITER_RESET(self);
- return NULL;
- }
- PyArray_ITER_GOTO1D(self, num);
- copyswap(optr, self->dataptr, swap, r);
- optr += itemsize;
- PyArray_ITER_NEXT(ind_it);
+ else {
+ PyArray_ITER_GOTO1D(self, num);
+ r = PyArray_ToScalar(self->dataptr, self->ao);
}
- Py_DECREF(ind_it);
PyArray_ITER_RESET(self);
return r;
+ }
+
+ Py_INCREF(self->ao->descr);
+ r = PyArray_NewFromDescr(self->ao->ob_type, self->ao->descr,
+ ind->nd, ind->dimensions,
+ NULL, NULL,
+ 0, (PyObject *)self->ao);
+ if (r==NULL) return NULL;
+
+ optr = PyArray_DATA(r);
+ ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
+ if (ind_it == NULL) {Py_DECREF(r); return NULL;}
+ index = ind_it->size;
+ copyswap = PyArray_DESCR(r)->f->copyswap;
+ swap = (PyArray_ISNOTSWAPPED(r) != PyArray_ISNOTSWAPPED(self->ao));
+ while(index--) {
+ num = *((intp *)(ind_it->dataptr));
+ if (num < 0) num += self->size;
+ if (num < 0 || num >= self->size) {
+ PyErr_Format(PyExc_IndexError,
+ "index %d out of bounds" \
+ " 0<=index<%d", (int) num,
+ (int) self->size);
+ Py_DECREF(ind_it);
+ Py_DECREF(r);
+ PyArray_ITER_RESET(self);
+ return NULL;
+ }
+ PyArray_ITER_GOTO1D(self, num);
+ copyswap(optr, self->dataptr, swap, r);
+ optr += itemsize;
+ PyArray_ITER_NEXT(ind_it);
+ }
+ Py_DECREF(ind_it);
+ PyArray_ITER_RESET(self);
+ return r;
}
static PyObject *
iter_subscript(PyArrayIterObject *self, PyObject *ind)
{
- PyArray_Descr *indtype=NULL;
- intp start, step_size;
- intp n_steps;
- PyObject *r;
- char *dptr;
- int size;
- PyObject *obj = NULL;
- int swap;
- PyArray_CopySwapFunc *copyswap;
-
- if (ind == Py_Ellipsis) {
- ind = PySlice_New(NULL, NULL, NULL);
- obj = iter_subscript(self, ind);
- Py_DECREF(ind);
- return obj;
- }
- if (PyTuple_Check(ind)) {
- int len;
- len = PyTuple_GET_SIZE(ind);
- if (len > 1) goto fail;
- if (len == 0) {
- Py_INCREF(self->ao);
- return (PyObject *)self->ao;
- }
- ind = PyTuple_GET_ITEM(ind, 0);
+ PyArray_Descr *indtype=NULL;
+ intp start, step_size;
+ intp n_steps;
+ PyObject *r;
+ char *dptr;
+ int size;
+ PyObject *obj = NULL;
+ int swap;
+ PyArray_CopySwapFunc *copyswap;
+
+ if (ind == Py_Ellipsis) {
+ ind = PySlice_New(NULL, NULL, NULL);
+ obj = iter_subscript(self, ind);
+ Py_DECREF(ind);
+ return obj;
+ }
+ if (PyTuple_Check(ind)) {
+ int len;
+ len = PyTuple_GET_SIZE(ind);
+ if (len > 1) goto fail;
+ if (len == 0) {
+ Py_INCREF(self->ao);
+ return (PyObject *)self->ao;
}
+ ind = PyTuple_GET_ITEM(ind, 0);
+ }
- /* Tuples >1d not accepted --- i.e. no newaxis */
- /* Could implement this with adjusted strides
- and dimensions in iterator */
+ /* Tuples >1d not accepted --- i.e. no newaxis */
+ /* Could implement this with adjusted strides
+ and dimensions in iterator */
- /* Check for Boolean -- this is first becasue
- Bool is a subclass of Int */
- PyArray_ITER_RESET(self);
+ /* Check for Boolean -- this is first becasue
+ Bool is a subclass of Int */
+ PyArray_ITER_RESET(self);
- if (PyBool_Check(ind)) {
- if (PyObject_IsTrue(ind)) {
- return PyArray_ToScalar(self->dataptr, self->ao);
- }
- else { /* empty array */
- intp ii = 0;
- Py_INCREF(self->ao->descr);
- r = PyArray_NewFromDescr(self->ao->ob_type,
- self->ao->descr,
- 1, &ii,
- NULL, NULL, 0,
- (PyObject *)self->ao);
- return r;
- }
+ if (PyBool_Check(ind)) {
+ if (PyObject_IsTrue(ind)) {
+ return PyArray_ToScalar(self->dataptr, self->ao);
}
+ else { /* empty array */
+ intp ii = 0;
+ Py_INCREF(self->ao->descr);
+ r = PyArray_NewFromDescr(self->ao->ob_type,
+ self->ao->descr,
+ 1, &ii,
+ NULL, NULL, 0,
+ (PyObject *)self->ao);
+ return r;
+ }
+ }
- /* Check for Integer or Slice */
-
- if (PyLong_Check(ind) || PyInt_Check(ind) || PySlice_Check(ind)) {
- start = parse_subindex(ind, &step_size, &n_steps,
- self->size);
- if (start == -1)
- goto fail;
- if (n_steps == RubberIndex || n_steps == PseudoIndex) {
- PyErr_SetString(PyExc_IndexError,
- "cannot use Ellipsis or newaxes here");
- goto fail;
- }
- PyArray_ITER_GOTO1D(self, start)
- if (n_steps == SingleIndex) { /* Integer */
- r = PyArray_ToScalar(self->dataptr, self->ao);
- PyArray_ITER_RESET(self);
- return r;
- }
- size = self->ao->descr->elsize;
- Py_INCREF(self->ao->descr);
- r = PyArray_NewFromDescr(self->ao->ob_type,
- self->ao->descr,
- 1, &n_steps,
- NULL, NULL,
- 0, (PyObject *)self->ao);
- if (r==NULL) goto fail;
- dptr = PyArray_DATA(r);
- swap = !PyArray_ISNOTSWAPPED(self->ao);
- copyswap = PyArray_DESCR(r)->f->copyswap;
- while(n_steps--) {
- copyswap(dptr, self->dataptr, swap, r);
- start += step_size;
- PyArray_ITER_GOTO1D(self, start)
- dptr += size;
- }
+ /* Check for Integer or Slice */
+
+ if (PyLong_Check(ind) || PyInt_Check(ind) || PySlice_Check(ind)) {
+ start = parse_subindex(ind, &step_size, &n_steps,
+ self->size);
+ if (start == -1)
+ goto fail;
+ if (n_steps == RubberIndex || n_steps == PseudoIndex) {
+ PyErr_SetString(PyExc_IndexError,
+ "cannot use Ellipsis or newaxes here");
+ goto fail;
+ }
+ PyArray_ITER_GOTO1D(self, start)
+ if (n_steps == SingleIndex) { /* Integer */
+ r = PyArray_ToScalar(self->dataptr, self->ao);
PyArray_ITER_RESET(self);
return r;
+ }
+ size = self->ao->descr->elsize;
+ Py_INCREF(self->ao->descr);
+ r = PyArray_NewFromDescr(self->ao->ob_type,
+ self->ao->descr,
+ 1, &n_steps,
+ NULL, NULL,
+ 0, (PyObject *)self->ao);
+ if (r==NULL) goto fail;
+ dptr = PyArray_DATA(r);
+ swap = !PyArray_ISNOTSWAPPED(self->ao);
+ copyswap = PyArray_DESCR(r)->f->copyswap;
+ while(n_steps--) {
+ copyswap(dptr, self->dataptr, swap, r);
+ start += step_size;
+ PyArray_ITER_GOTO1D(self, start)
+ dptr += size;
}
+ PyArray_ITER_RESET(self);
+ return r;
+ }
- /* convert to INTP array if Integer array scalar or List */
+ /* convert to INTP array if Integer array scalar or List */
- indtype = PyArray_DescrFromType(PyArray_INTP);
- if (PyArray_IsScalar(ind, Integer) || PyList_Check(ind)) {
- Py_INCREF(indtype);
- obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
- if (obj == NULL) goto fail;
+ indtype = PyArray_DescrFromType(PyArray_INTP);
+ if (PyArray_IsScalar(ind, Integer) || PyList_Check(ind)) {
+ Py_INCREF(indtype);
+ obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
+ if (obj == NULL) goto fail;
+ }
+ else {
+ Py_INCREF(ind);
+ obj = ind;
+ }
+
+ if (PyArray_Check(obj)) {
+ /* Check for Boolean object */
+ if (PyArray_TYPE(obj)==PyArray_BOOL) {
+ r = iter_subscript_Bool(self, (PyArrayObject *)obj);
+ Py_DECREF(indtype);
+ }
+ /* Check for integer array */
+ else if (PyArray_ISINTEGER(obj)) {
+ PyObject *new;
+ new = PyArray_FromAny(obj, indtype, 0, 0,
+ FORCECAST | ALIGNED, NULL);
+ if (new==NULL) goto fail;
+ Py_DECREF(obj);
+ obj = new;
+ r = iter_subscript_int(self, (PyArrayObject *)obj);
}
else {
- Py_INCREF(ind);
- obj = ind;
- }
-
- if (PyArray_Check(obj)) {
- /* Check for Boolean object */
- if (PyArray_TYPE(obj)==PyArray_BOOL) {
- r = iter_subscript_Bool(self, (PyArrayObject *)obj);
- Py_DECREF(indtype);
- }
- /* Check for integer array */
- else if (PyArray_ISINTEGER(obj)) {
- PyObject *new;
- new = PyArray_FromAny(obj, indtype, 0, 0,
- FORCECAST | ALIGNED, NULL);
- if (new==NULL) goto fail;
- Py_DECREF(obj);
- obj = new;
- r = iter_subscript_int(self, (PyArrayObject *)obj);
- }
- else {
- goto fail;
- }
- Py_DECREF(obj);
- return r;
+ goto fail;
}
- else Py_DECREF(indtype);
+ Py_DECREF(obj);
+ return r;
+ }
+ else Py_DECREF(indtype);
fail:
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_IndexError, "unsupported iterator index");
- Py_XDECREF(indtype);
- Py_XDECREF(obj);
- return NULL;
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_IndexError, "unsupported iterator index");
+ Py_XDECREF(indtype);
+ Py_XDECREF(obj);
+ return NULL;
}
@@ -9328,241 +9327,241 @@ static int
iter_ass_sub_Bool(PyArrayIterObject *self, PyArrayObject *ind,
PyArrayIterObject *val, int swap)
{
- int index, strides;
- char *dptr;
- PyArray_CopySwapFunc *copyswap;
+ int index, strides;
+ char *dptr;
+ PyArray_CopySwapFunc *copyswap;
- if (ind->nd != 1) {
- PyErr_SetString(PyExc_ValueError,
- "boolean index array should have 1 dimension");
- return -1;
- }
- index = ind->dimensions[0];
- strides = ind->strides[0];
- dptr = ind->data;
- PyArray_ITER_RESET(self);
- /* Loop over Boolean array */
- copyswap = self->ao->descr->f->copyswap;
- while(index--) {
- if (*((Bool *)dptr) != 0) {
- copyswap(self->dataptr, val->dataptr, swap, self->ao);
- PyArray_ITER_NEXT(val);
- if (val->index==val->size)
- PyArray_ITER_RESET(val);
- }
- dptr += strides;
- PyArray_ITER_NEXT(self);
- }
- PyArray_ITER_RESET(self);
- return 0;
+ if (ind->nd != 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "boolean index array should have 1 dimension");
+ return -1;
+ }
+ index = ind->dimensions[0];
+ strides = ind->strides[0];
+ dptr = ind->data;
+ PyArray_ITER_RESET(self);
+ /* Loop over Boolean array */
+ copyswap = self->ao->descr->f->copyswap;
+ while(index--) {
+ if (*((Bool *)dptr) != 0) {
+ copyswap(self->dataptr, val->dataptr, swap, self->ao);
+ PyArray_ITER_NEXT(val);
+ if (val->index==val->size)
+ PyArray_ITER_RESET(val);
+ }
+ dptr += strides;
+ PyArray_ITER_NEXT(self);
+ }
+ PyArray_ITER_RESET(self);
+ return 0;
}
static int
iter_ass_sub_int(PyArrayIterObject *self, PyArrayObject *ind,
- PyArrayIterObject *val, int swap)
-{
- PyArray_Descr *typecode;
- intp num;
- PyArrayIterObject *ind_it;
- int index;
- PyArray_CopySwapFunc *copyswap;
-
- typecode = self->ao->descr;
- copyswap = self->ao->descr->f->copyswap;
- if (ind->nd == 0) {
- num = *((intp *)ind->data);
- PyArray_ITER_GOTO1D(self, num);
- copyswap(self->dataptr, val->dataptr, swap, self->ao);
- return 0;
- }
- ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
- if (ind_it == NULL) return -1;
- index = ind_it->size;
- while(index--) {
- num = *((intp *)(ind_it->dataptr));
- if (num < 0) num += self->size;
- if ((num < 0) || (num >= self->size)) {
- PyErr_Format(PyExc_IndexError,
- "index %d out of bounds" \
- " 0<=index<%d", (int) num,
- (int) self->size);
- Py_DECREF(ind_it);
- return -1;
- }
- PyArray_ITER_GOTO1D(self, num);
- copyswap(self->dataptr, val->dataptr, swap, self->ao);
- PyArray_ITER_NEXT(ind_it);
- PyArray_ITER_NEXT(val);
- if (val->index == val->size)
- PyArray_ITER_RESET(val);
- }
- Py_DECREF(ind_it);
+ PyArrayIterObject *val, int swap)
+{
+ PyArray_Descr *typecode;
+ intp num;
+ PyArrayIterObject *ind_it;
+ int index;
+ PyArray_CopySwapFunc *copyswap;
+
+ typecode = self->ao->descr;
+ copyswap = self->ao->descr->f->copyswap;
+ if (ind->nd == 0) {
+ num = *((intp *)ind->data);
+ PyArray_ITER_GOTO1D(self, num);
+ copyswap(self->dataptr, val->dataptr, swap, self->ao);
return 0;
+ }
+ ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
+ if (ind_it == NULL) return -1;
+ index = ind_it->size;
+ while(index--) {
+ num = *((intp *)(ind_it->dataptr));
+ if (num < 0) num += self->size;
+ if ((num < 0) || (num >= self->size)) {
+ PyErr_Format(PyExc_IndexError,
+ "index %d out of bounds" \
+ " 0<=index<%d", (int) num,
+ (int) self->size);
+ Py_DECREF(ind_it);
+ return -1;
+ }
+ PyArray_ITER_GOTO1D(self, num);
+ copyswap(self->dataptr, val->dataptr, swap, self->ao);
+ PyArray_ITER_NEXT(ind_it);
+ PyArray_ITER_NEXT(val);
+ if (val->index == val->size)
+ PyArray_ITER_RESET(val);
+ }
+ Py_DECREF(ind_it);
+ return 0;
}
static int
iter_ass_subscript(PyArrayIterObject *self, PyObject *ind, PyObject *val)
{
- PyObject *arrval=NULL;
- PyArrayIterObject *val_it=NULL;
- PyArray_Descr *type;
- PyArray_Descr *indtype=NULL;
- int swap, retval=-1;
- intp start, step_size;
- intp n_steps;
- PyObject *obj=NULL;
- PyArray_CopySwapFunc *copyswap;
-
-
- if (ind == Py_Ellipsis) {
- ind = PySlice_New(NULL, NULL, NULL);
- retval = iter_ass_subscript(self, ind, val);
- Py_DECREF(ind);
- return retval;
- }
+ PyObject *arrval=NULL;
+ PyArrayIterObject *val_it=NULL;
+ PyArray_Descr *type;
+ PyArray_Descr *indtype=NULL;
+ int swap, retval=-1;
+ intp start, step_size;
+ intp n_steps;
+ PyObject *obj=NULL;
+ PyArray_CopySwapFunc *copyswap;
+
+
+ if (ind == Py_Ellipsis) {
+ ind = PySlice_New(NULL, NULL, NULL);
+ retval = iter_ass_subscript(self, ind, val);
+ Py_DECREF(ind);
+ return retval;
+ }
- if (PyTuple_Check(ind)) {
- int len;
- len = PyTuple_GET_SIZE(ind);
- if (len > 1) goto finish;
- ind = PyTuple_GET_ITEM(ind, 0);
- }
+ if (PyTuple_Check(ind)) {
+ int len;
+ len = PyTuple_GET_SIZE(ind);
+ if (len > 1) goto finish;
+ ind = PyTuple_GET_ITEM(ind, 0);
+ }
- type = self->ao->descr;
+ type = self->ao->descr;
- /* Check for Boolean -- this is first becasue
- Bool is a subclass of Int */
+ /* Check for Boolean -- this is first becasue
+ Bool is a subclass of Int */
- if (PyBool_Check(ind)) {
- retval = 0;
- if (PyObject_IsTrue(ind)) {
- retval = type->f->setitem(val, self->dataptr, self->ao);
- }
- goto finish;
+ if (PyBool_Check(ind)) {
+ retval = 0;
+ if (PyObject_IsTrue(ind)) {
+ retval = type->f->setitem(val, self->dataptr, self->ao);
}
+ goto finish;
+ }
- if (PySequence_Check(ind) || PySlice_Check(ind)) goto skip;
- start = PyArray_PyIntAsIntp(ind);
- if (start==-1 && PyErr_Occurred()) PyErr_Clear();
- else {
- if (start < -self->size || start >= self->size) {
- PyErr_Format(PyExc_ValueError,
- "index (%" NPY_INTP_FMT \
- ") out of range", start);
- goto finish;
- }
- retval = 0;
- PyArray_ITER_GOTO1D(self, start);
- retval = type->f->setitem(val, self->dataptr, self->ao);
- PyArray_ITER_RESET(self);
- if (retval < 0) {
- PyErr_SetString(PyExc_ValueError,
- "Error setting single item of array.");
- }
- goto finish;
+ if (PySequence_Check(ind) || PySlice_Check(ind)) goto skip;
+ start = PyArray_PyIntAsIntp(ind);
+ if (start==-1 && PyErr_Occurred()) PyErr_Clear();
+ else {
+ if (start < -self->size || start >= self->size) {
+ PyErr_Format(PyExc_ValueError,
+ "index (%" NPY_INTP_FMT \
+ ") out of range", start);
+ goto finish;
}
+ retval = 0;
+ PyArray_ITER_GOTO1D(self, start);
+ retval = type->f->setitem(val, self->dataptr, self->ao);
+ PyArray_ITER_RESET(self);
+ if (retval < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "Error setting single item of array.");
+ }
+ goto finish;
+ }
skip:
- Py_INCREF(type);
- arrval = PyArray_FromAny(val, type, 0, 0, 0, NULL);
- if (arrval==NULL) return -1;
- val_it = (PyArrayIterObject *)PyArray_IterNew(arrval);
- if (val_it==NULL) goto finish;
- if (val_it->size == 0) {retval = 0; goto finish;}
-
- copyswap = PyArray_DESCR(arrval)->f->copyswap;
- swap = (PyArray_ISNOTSWAPPED(self->ao)!=PyArray_ISNOTSWAPPED(arrval));
-
- /* Check Slice */
-
- if (PySlice_Check(ind)) {
- start = parse_subindex(ind, &step_size, &n_steps,
- self->size);
- if (start == -1) goto finish;
- if (n_steps == RubberIndex || n_steps == PseudoIndex) {
- PyErr_SetString(PyExc_IndexError,
- "cannot use Ellipsis or newaxes here");
- goto finish;
- }
- PyArray_ITER_GOTO1D(self, start);
- if (n_steps == SingleIndex) { /* Integer */
- copyswap(self->dataptr, PyArray_DATA(arrval),
- swap, arrval);
- PyArray_ITER_RESET(self);
- retval=0;
- goto finish;
- }
- while(n_steps--) {
- copyswap(self->dataptr, val_it->dataptr,
- swap, arrval);
- start += step_size;
- PyArray_ITER_GOTO1D(self, start)
- PyArray_ITER_NEXT(val_it);
- if (val_it->index == val_it->size)
- PyArray_ITER_RESET(val_it);
- }
- PyArray_ITER_RESET(self);
- retval = 0;
- goto finish;
+ Py_INCREF(type);
+ arrval = PyArray_FromAny(val, type, 0, 0, 0, NULL);
+ if (arrval==NULL) return -1;
+ val_it = (PyArrayIterObject *)PyArray_IterNew(arrval);
+ if (val_it==NULL) goto finish;
+ if (val_it->size == 0) {retval = 0; goto finish;}
+
+ copyswap = PyArray_DESCR(arrval)->f->copyswap;
+ swap = (PyArray_ISNOTSWAPPED(self->ao)!=PyArray_ISNOTSWAPPED(arrval));
+
+ /* Check Slice */
+
+ if (PySlice_Check(ind)) {
+ start = parse_subindex(ind, &step_size, &n_steps,
+ self->size);
+ if (start == -1) goto finish;
+ if (n_steps == RubberIndex || n_steps == PseudoIndex) {
+ PyErr_SetString(PyExc_IndexError,
+ "cannot use Ellipsis or newaxes here");
+ goto finish;
}
-
- /* convert to INTP array if Integer array scalar or List */
-
- indtype = PyArray_DescrFromType(PyArray_INTP);
- if (PyList_Check(ind)) {
- Py_INCREF(indtype);
- obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
+ PyArray_ITER_GOTO1D(self, start);
+ if (n_steps == SingleIndex) { /* Integer */
+ copyswap(self->dataptr, PyArray_DATA(arrval),
+ swap, arrval);
+ PyArray_ITER_RESET(self);
+ retval=0;
+ goto finish;
}
- else {
- Py_INCREF(ind);
- obj = ind;
+ while(n_steps--) {
+ copyswap(self->dataptr, val_it->dataptr,
+ swap, arrval);
+ start += step_size;
+ PyArray_ITER_GOTO1D(self, start)
+ PyArray_ITER_NEXT(val_it);
+ if (val_it->index == val_it->size)
+ PyArray_ITER_RESET(val_it);
}
+ PyArray_ITER_RESET(self);
+ retval = 0;
+ goto finish;
+ }
- if (obj != NULL && PyArray_Check(obj)) {
- /* Check for Boolean object */
- if (PyArray_TYPE(obj)==PyArray_BOOL) {
- if (iter_ass_sub_Bool(self, (PyArrayObject *)obj,
- val_it, swap) < 0)
- goto finish;
- retval=0;
- }
- /* Check for integer array */
- else if (PyArray_ISINTEGER(obj)) {
- PyObject *new;
- Py_INCREF(indtype);
- new = PyArray_CheckFromAny(obj, indtype, 0, 0,
- FORCECAST | BEHAVED_NS, NULL);
- Py_DECREF(obj);
- obj = new;
- if (new==NULL) goto finish;
- if (iter_ass_sub_int(self, (PyArrayObject *)obj,
- val_it, swap) < 0)
- goto finish;
- retval=0;
- }
+ /* convert to INTP array if Integer array scalar or List */
+
+ indtype = PyArray_DescrFromType(PyArray_INTP);
+ if (PyList_Check(ind)) {
+ Py_INCREF(indtype);
+ obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
+ }
+ else {
+ Py_INCREF(ind);
+ obj = ind;
+ }
+
+ if (obj != NULL && PyArray_Check(obj)) {
+ /* Check for Boolean object */
+ if (PyArray_TYPE(obj)==PyArray_BOOL) {
+ if (iter_ass_sub_Bool(self, (PyArrayObject *)obj,
+ val_it, swap) < 0)
+ goto finish;
+ retval=0;
+ }
+ /* Check for integer array */
+ else if (PyArray_ISINTEGER(obj)) {
+ PyObject *new;
+ Py_INCREF(indtype);
+ new = PyArray_CheckFromAny(obj, indtype, 0, 0,
+ FORCECAST | BEHAVED_NS, NULL);
+ Py_DECREF(obj);
+ obj = new;
+ if (new==NULL) goto finish;
+ if (iter_ass_sub_int(self, (PyArrayObject *)obj,
+ val_it, swap) < 0)
+ goto finish;
+ retval=0;
}
+ }
finish:
- if (!PyErr_Occurred() && retval < 0)
- PyErr_SetString(PyExc_IndexError,
- "unsupported iterator index");
- Py_XDECREF(indtype);
- Py_XDECREF(obj);
- Py_XDECREF(val_it);
- Py_XDECREF(arrval);
- return retval;
+ if (!PyErr_Occurred() && retval < 0)
+ PyErr_SetString(PyExc_IndexError,
+ "unsupported iterator index");
+ Py_XDECREF(indtype);
+ Py_XDECREF(obj);
+ Py_XDECREF(val_it);
+ Py_XDECREF(arrval);
+ return retval;
}
static PyMappingMethods iter_as_mapping = {
#if PY_VERSION_HEX >= 0x02050000
- (lenfunc)iter_length, /*mp_length*/
+ (lenfunc)iter_length, /*mp_length*/
#else
- (inquiry)iter_length, /*mp_length*/
+ (inquiry)iter_length, /*mp_length*/
#endif
- (binaryfunc)iter_subscript, /*mp_subscript*/
- (objobjargproc)iter_ass_subscript, /*mp_ass_subscript*/
+ (binaryfunc)iter_subscript, /*mp_subscript*/
+ (objobjargproc)iter_ass_subscript, /*mp_ass_subscript*/
};
@@ -9571,143 +9570,143 @@ static PyObject *
iter_array(PyArrayIterObject *it, PyObject *op)
{
- PyObject *r;
- intp size;
-
- /* Any argument ignored */
-
- /* Two options:
- 1) underlying array is contiguous
- -- return 1-d wrapper around it
- 2) underlying array is not contiguous
- -- make new 1-d contiguous array with updateifcopy flag set
- to copy back to the old array
- */
-
- size = PyArray_SIZE(it->ao);
- Py_INCREF(it->ao->descr);
- if (PyArray_ISCONTIGUOUS(it->ao)) {
- r = PyArray_NewFromDescr(&PyArray_Type,
- it->ao->descr,
- 1, &size,
- NULL, it->ao->data,
- it->ao->flags,
- (PyObject *)it->ao);
- if (r==NULL) return NULL;
- }
- else {
- r = PyArray_NewFromDescr(&PyArray_Type,
- it->ao->descr,
- 1, &size,
- NULL, NULL,
- 0, (PyObject *)it->ao);
- if (r==NULL) return NULL;
- if (_flat_copyinto(r, (PyObject *)it->ao,
- PyArray_CORDER) < 0) {
- Py_DECREF(r);
- return NULL;
- }
- PyArray_FLAGS(r) |= UPDATEIFCOPY;
- it->ao->flags &= ~WRITEABLE;
+ PyObject *r;
+ intp size;
+
+ /* Any argument ignored */
+
+ /* Two options:
+ 1) underlying array is contiguous
+ -- return 1-d wrapper around it
+ 2) underlying array is not contiguous
+ -- make new 1-d contiguous array with updateifcopy flag set
+ to copy back to the old array
+ */
+
+ size = PyArray_SIZE(it->ao);
+ Py_INCREF(it->ao->descr);
+ if (PyArray_ISCONTIGUOUS(it->ao)) {
+ r = PyArray_NewFromDescr(&PyArray_Type,
+ it->ao->descr,
+ 1, &size,
+ NULL, it->ao->data,
+ it->ao->flags,
+ (PyObject *)it->ao);
+ if (r==NULL) return NULL;
+ }
+ else {
+ r = PyArray_NewFromDescr(&PyArray_Type,
+ it->ao->descr,
+ 1, &size,
+ NULL, NULL,
+ 0, (PyObject *)it->ao);
+ if (r==NULL) return NULL;
+ if (_flat_copyinto(r, (PyObject *)it->ao,
+ PyArray_CORDER) < 0) {
+ Py_DECREF(r);
+ return NULL;
}
- Py_INCREF(it->ao);
- PyArray_BASE(r) = (PyObject *)it->ao;
- return r;
+ PyArray_FLAGS(r) |= UPDATEIFCOPY;
+ it->ao->flags &= ~WRITEABLE;
+ }
+ Py_INCREF(it->ao);
+ PyArray_BASE(r) = (PyObject *)it->ao;
+ return r;
}
static PyObject *
iter_copy(PyArrayIterObject *it, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "")) return NULL;
- return PyArray_Flatten(it->ao, 0);
+ if (!PyArg_ParseTuple(args, "")) return NULL;
+ return PyArray_Flatten(it->ao, 0);
}
static PyMethodDef iter_methods[] = {
- /* to get array */
- {"__array__", (PyCFunction)iter_array, 1, NULL},
- {"copy", (PyCFunction)iter_copy, 1, NULL},
- {NULL, NULL} /* sentinel */
+ /* to get array */
+ {"__array__", (PyCFunction)iter_array, 1, NULL},
+ {"copy", (PyCFunction)iter_copy, 1, NULL},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
iter_richcompare(PyArrayIterObject *self, PyObject *other, int cmp_op)
{
- PyArrayObject *new;
- PyObject *ret;
- new = (PyArrayObject *)iter_array(self, NULL);
- if (new == NULL) return NULL;
- ret = array_richcompare(new, other, cmp_op);
- Py_DECREF(new);
- return ret;
+ PyArrayObject *new;
+ PyObject *ret;
+ new = (PyArrayObject *)iter_array(self, NULL);
+ if (new == NULL) return NULL;
+ ret = array_richcompare(new, other, cmp_op);
+ Py_DECREF(new);
+ return ret;
}
static PyMemberDef iter_members[] = {
- {"base", T_OBJECT, offsetof(PyArrayIterObject, ao), RO, NULL},
- {"index", T_INT, offsetof(PyArrayIterObject, index), RO, NULL},
- {NULL},
+ {"base", T_OBJECT, offsetof(PyArrayIterObject, ao), RO, NULL},
+ {"index", T_INT, offsetof(PyArrayIterObject, index), RO, NULL},
+ {NULL},
};
static PyObject *
iter_coords_get(PyArrayIterObject *self)
{
- int nd;
- nd = self->ao->nd;
- if (self->contiguous) { /* coordinates not kept track of --- need to generate
- from index */
- intp val;
- int i;
- val = self->index;
- for (i=0;i<nd; i++) {
- self->coordinates[i] = val / self->factors[i];
- val = val % self->factors[i];
- }
+ int nd;
+ nd = self->ao->nd;
+ if (self->contiguous) { /* coordinates not kept track of --- need to generate
+ from index */
+ intp val;
+ int i;
+ val = self->index;
+ for (i=0;i<nd; i++) {
+ self->coordinates[i] = val / self->factors[i];
+ val = val % self->factors[i];
}
- return PyArray_IntTupleFromIntp(nd, self->coordinates);
+ }
+ return PyArray_IntTupleFromIntp(nd, self->coordinates);
}
static PyGetSetDef iter_getsets[] = {
- {"coords",
- (getter)iter_coords_get,
- NULL,
- NULL},
- {NULL, NULL, NULL, NULL},
+ {"coords",
+ (getter)iter_coords_get,
+ NULL,
+ NULL},
+ {NULL, NULL, NULL, NULL},
};
static PyTypeObject PyArrayIter_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "numpy.flatiter", /* tp_name */
- sizeof(PyArrayIterObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)arrayiter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- &iter_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)iter_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- (iternextfunc)arrayiter_next, /* tp_iternext */
- iter_methods, /* tp_methods */
- iter_members, /* tp_members */
- iter_getsets, /* tp_getset */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "numpy.flatiter", /* tp_name */
+ sizeof(PyArrayIterObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)arrayiter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ &iter_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)iter_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ (iternextfunc)arrayiter_next, /* tp_iternext */
+ iter_methods, /* tp_methods */
+ iter_members, /* tp_members */
+ iter_getsets, /* tp_getset */
};
@@ -9730,147 +9729,147 @@ static int _nonzero_indices(PyObject *myBool, PyArrayIterObject **iters);
if possible -- otherwise, it is a Slice or Ellipsis object
and has to be interpreted on bind to a particular
array so leave it NULL for now.
- */
+*/
static int
_convert_obj(PyObject *obj, PyArrayIterObject **iter)
{
- PyArray_Descr *indtype;
- PyObject *arr;
+ PyArray_Descr *indtype;
+ PyObject *arr;
- if (PySlice_Check(obj) || (obj == Py_Ellipsis))
- return 0;
- else if (PyArray_Check(obj) && PyArray_ISBOOL(obj)) {
- return _nonzero_indices(obj, iter);
- }
- else {
- indtype = PyArray_DescrFromType(PyArray_INTP);
- arr = PyArray_FromAny(obj, indtype, 0, 0, FORCECAST, NULL);
- if (arr == NULL) return -1;
- *iter = (PyArrayIterObject *)PyArray_IterNew(arr);
- Py_DECREF(arr);
- if (*iter == NULL) return -1;
- }
- return 1;
+ if (PySlice_Check(obj) || (obj == Py_Ellipsis))
+ return 0;
+ else if (PyArray_Check(obj) && PyArray_ISBOOL(obj)) {
+ return _nonzero_indices(obj, iter);
+ }
+ else {
+ indtype = PyArray_DescrFromType(PyArray_INTP);
+ arr = PyArray_FromAny(obj, indtype, 0, 0, FORCECAST, NULL);
+ if (arr == NULL) return -1;
+ *iter = (PyArrayIterObject *)PyArray_IterNew(arr);
+ Py_DECREF(arr);
+ if (*iter == NULL) return -1;
+ }
+ return 1;
}
/* Adjust dimensionality and strides for index object iterators
--- i.e. broadcast
- */
+*/
/*OBJECT_API*/
static int
PyArray_Broadcast(PyArrayMultiIterObject *mit)
{
- int i, nd, k, j;
- intp tmp;
- PyArrayIterObject *it;
-
- /* Discover the broadcast number of dimensions */
- for (i=0, nd=0; i<mit->numiter; i++)
- nd = MAX(nd, mit->iters[i]->ao->nd);
- mit->nd = nd;
-
- /* Discover the broadcast shape in each dimension */
- for (i=0; i<nd; i++) {
- mit->dimensions[i] = 1;
- for (j=0; j<mit->numiter; j++) {
- it = mit->iters[j];
- /* This prepends 1 to shapes not already
- equal to nd */
- k = i + it->ao->nd - nd;
- if (k>=0) {
- tmp = it->ao->dimensions[k];
- if (tmp == 1) continue;
- if (mit->dimensions[i] == 1)
- mit->dimensions[i] = tmp;
- else if (mit->dimensions[i] != tmp) {
- PyErr_SetString(PyExc_ValueError,
- "shape mismatch: objects" \
- " cannot be broadcast" \
- " to a single shape");
- return -1;
- }
- }
+ int i, nd, k, j;
+ intp tmp;
+ PyArrayIterObject *it;
+
+ /* Discover the broadcast number of dimensions */
+ for (i=0, nd=0; i<mit->numiter; i++)
+ nd = MAX(nd, mit->iters[i]->ao->nd);
+ mit->nd = nd;
+
+ /* Discover the broadcast shape in each dimension */
+ for (i=0; i<nd; i++) {
+ mit->dimensions[i] = 1;
+ for (j=0; j<mit->numiter; j++) {
+ it = mit->iters[j];
+ /* This prepends 1 to shapes not already
+ equal to nd */
+ k = i + it->ao->nd - nd;
+ if (k>=0) {
+ tmp = it->ao->dimensions[k];
+ if (tmp == 1) continue;
+ if (mit->dimensions[i] == 1)
+ mit->dimensions[i] = tmp;
+ else if (mit->dimensions[i] != tmp) {
+ PyErr_SetString(PyExc_ValueError,
+ "shape mismatch: objects" \
+ " cannot be broadcast" \
+ " to a single shape");
+ return -1;
}
+ }
}
+ }
- /* Reset the iterator dimensions and strides of each iterator
- object -- using 0 valued strides for broadcasting */
-
- tmp = PyArray_MultiplyList(mit->dimensions, mit->nd);
- mit->size = tmp;
- for (i=0; i<mit->numiter; i++) {
- it = mit->iters[i];
- it->nd_m1 = mit->nd - 1;
- it->size = tmp;
- nd = it->ao->nd;
- it->factors[mit->nd-1] = 1;
- for (j=0; j < mit->nd; j++) {
- it->dims_m1[j] = mit->dimensions[j] - 1;
- k = j + nd - mit->nd;
- /* If this dimension was added or shape
- of underlying array was 1 */
- if ((k < 0) || \
- it->ao->dimensions[k] != mit->dimensions[j]) {
- it->contiguous = 0;
- it->strides[j] = 0;
- }
- else {
- it->strides[j] = it->ao->strides[k];
- }
- it->backstrides[j] = it->strides[j] * \
- it->dims_m1[j];
- if (j > 0)
- it->factors[mit->nd-j-1] = \
- it->factors[mit->nd-j] * \
- mit->dimensions[mit->nd-j];
- }
- PyArray_ITER_RESET(it);
+ /* Reset the iterator dimensions and strides of each iterator
+ object -- using 0 valued strides for broadcasting */
+
+ tmp = PyArray_MultiplyList(mit->dimensions, mit->nd);
+ mit->size = tmp;
+ for (i=0; i<mit->numiter; i++) {
+ it = mit->iters[i];
+ it->nd_m1 = mit->nd - 1;
+ it->size = tmp;
+ nd = it->ao->nd;
+ it->factors[mit->nd-1] = 1;
+ for (j=0; j < mit->nd; j++) {
+ it->dims_m1[j] = mit->dimensions[j] - 1;
+ k = j + nd - mit->nd;
+ /* If this dimension was added or shape
+ of underlying array was 1 */
+ if ((k < 0) || \
+ it->ao->dimensions[k] != mit->dimensions[j]) {
+ it->contiguous = 0;
+ it->strides[j] = 0;
+ }
+ else {
+ it->strides[j] = it->ao->strides[k];
+ }
+ it->backstrides[j] = it->strides[j] * \
+ it->dims_m1[j];
+ if (j > 0)
+ it->factors[mit->nd-j-1] = \
+ it->factors[mit->nd-j] * \
+ mit->dimensions[mit->nd-j];
}
- return 0;
+ PyArray_ITER_RESET(it);
+ }
+ return 0;
}
/* Reset the map iterator to the beginning */
static void
PyArray_MapIterReset(PyArrayMapIterObject *mit)
{
- int i,j; intp coord[MAX_DIMS];
- PyArrayIterObject *it;
- PyArray_CopySwapFunc *copyswap;
+ int i,j; intp coord[MAX_DIMS];
+ PyArrayIterObject *it;
+ PyArray_CopySwapFunc *copyswap;
- mit->index = 0;
+ mit->index = 0;
- copyswap = mit->iters[0]->ao->descr->f->copyswap;
+ copyswap = mit->iters[0]->ao->descr->f->copyswap;
- if (mit->subspace != NULL) {
- memcpy(coord, mit->bscoord, sizeof(intp)*mit->ait->ao->nd);
- PyArray_ITER_RESET(mit->subspace);
- for (i=0; i<mit->numiter; i++) {
- it = mit->iters[i];
- PyArray_ITER_RESET(it);
- j = mit->iteraxes[i];
- copyswap(coord+j,it->dataptr,
- !PyArray_ISNOTSWAPPED(it->ao),
- it->ao);
- }
- PyArray_ITER_GOTO(mit->ait, coord);
- mit->subspace->dataptr = mit->ait->dataptr;
- mit->dataptr = mit->subspace->dataptr;
- }
- else {
- for (i=0; i<mit->numiter; i++) {
- it = mit->iters[i];
- if (it->size != 0) {
- PyArray_ITER_RESET(it);
- copyswap(coord+i,it->dataptr,
- !PyArray_ISNOTSWAPPED(it->ao),
- it->ao);
- }
- else coord[i] = 0;
- }
- PyArray_ITER_GOTO(mit->ait, coord);
- mit->dataptr = mit->ait->dataptr;
+ if (mit->subspace != NULL) {
+ memcpy(coord, mit->bscoord, sizeof(intp)*mit->ait->ao->nd);
+ PyArray_ITER_RESET(mit->subspace);
+ for (i=0; i<mit->numiter; i++) {
+ it = mit->iters[i];
+ PyArray_ITER_RESET(it);
+ j = mit->iteraxes[i];
+ copyswap(coord+j,it->dataptr,
+ !PyArray_ISNOTSWAPPED(it->ao),
+ it->ao);
+ }
+ PyArray_ITER_GOTO(mit->ait, coord);
+ mit->subspace->dataptr = mit->ait->dataptr;
+ mit->dataptr = mit->subspace->dataptr;
+ }
+ else {
+ for (i=0; i<mit->numiter; i++) {
+ it = mit->iters[i];
+ if (it->size != 0) {
+ PyArray_ITER_RESET(it);
+ copyswap(coord+i,it->dataptr,
+ !PyArray_ISNOTSWAPPED(it->ao),
+ it->ao);
+ }
+ else coord[i] = 0;
}
- return;
+ PyArray_ITER_GOTO(mit->ait, coord);
+ mit->dataptr = mit->ait->dataptr;
+ }
+ return;
}
/* This function needs to update the state of the map iterator
@@ -9879,56 +9878,56 @@ PyArray_MapIterReset(PyArrayMapIterObject *mit)
static void
PyArray_MapIterNext(PyArrayMapIterObject *mit)
{
- int i, j;
- intp coord[MAX_DIMS];
- PyArrayIterObject *it;
- PyArray_CopySwapFunc *copyswap;
-
- mit->index += 1;
- if (mit->index >= mit->size) return;
- copyswap = mit->iters[0]->ao->descr->f->copyswap;
- /* Sub-space iteration */
- if (mit->subspace != NULL) {
- PyArray_ITER_NEXT(mit->subspace);
- if (mit->subspace->index >= mit->subspace->size) {
- /* reset coord to coordinates of
- beginning of the subspace */
- memcpy(coord, mit->bscoord,
- sizeof(intp)*mit->ait->ao->nd);
- PyArray_ITER_RESET(mit->subspace);
- for (i=0; i<mit->numiter; i++) {
- it = mit->iters[i];
- PyArray_ITER_NEXT(it);
- j = mit->iteraxes[i];
- copyswap(coord+j,it->dataptr,
- !PyArray_ISNOTSWAPPED(it->ao),
- it->ao);
- }
- PyArray_ITER_GOTO(mit->ait, coord);
- mit->subspace->dataptr = mit->ait->dataptr;
- }
- mit->dataptr = mit->subspace->dataptr;
- }
- else {
- for (i=0; i<mit->numiter; i++) {
- it = mit->iters[i];
- PyArray_ITER_NEXT(it);
- copyswap(coord+i,it->dataptr,
- !PyArray_ISNOTSWAPPED(it->ao),
- it->ao);
- }
- PyArray_ITER_GOTO(mit->ait, coord);
- mit->dataptr = mit->ait->dataptr;
+ int i, j;
+ intp coord[MAX_DIMS];
+ PyArrayIterObject *it;
+ PyArray_CopySwapFunc *copyswap;
+
+ mit->index += 1;
+ if (mit->index >= mit->size) return;
+ copyswap = mit->iters[0]->ao->descr->f->copyswap;
+ /* Sub-space iteration */
+ if (mit->subspace != NULL) {
+ PyArray_ITER_NEXT(mit->subspace);
+ if (mit->subspace->index >= mit->subspace->size) {
+ /* reset coord to coordinates of
+ beginning of the subspace */
+ memcpy(coord, mit->bscoord,
+ sizeof(intp)*mit->ait->ao->nd);
+ PyArray_ITER_RESET(mit->subspace);
+ for (i=0; i<mit->numiter; i++) {
+ it = mit->iters[i];
+ PyArray_ITER_NEXT(it);
+ j = mit->iteraxes[i];
+ copyswap(coord+j,it->dataptr,
+ !PyArray_ISNOTSWAPPED(it->ao),
+ it->ao);
+ }
+ PyArray_ITER_GOTO(mit->ait, coord);
+ mit->subspace->dataptr = mit->ait->dataptr;
}
- return;
+ mit->dataptr = mit->subspace->dataptr;
+ }
+ else {
+ for (i=0; i<mit->numiter; i++) {
+ it = mit->iters[i];
+ PyArray_ITER_NEXT(it);
+ copyswap(coord+i,it->dataptr,
+ !PyArray_ISNOTSWAPPED(it->ao),
+ it->ao);
+ }
+ PyArray_ITER_GOTO(mit->ait, coord);
+ mit->dataptr = mit->ait->dataptr;
+ }
+ return;
}
/* Bind a mapiteration to a particular array */
/* Determine if subspace iteration is necessary. If so,
- 1) Fill in mit->iteraxes
- 2) Create subspace iterator
- 3) Update nd, dimensions, and size.
+ 1) Fill in mit->iteraxes
+ 2) Create subspace iterator
+ 3) Update nd, dimensions, and size.
Subspace iteration is necessary if: arr->nd > mit->numiter
*/
@@ -9941,146 +9940,146 @@ PyArray_MapIterNext(PyArrayMapIterObject *mit)
static void
PyArray_MapIterBind(PyArrayMapIterObject *mit, PyArrayObject *arr)
{
- int subnd;
- PyObject *sub, *obj=NULL;
- int i, j, n, curraxis, ellipexp, noellip;
- PyArrayIterObject *it;
- intp dimsize;
- intp *indptr;
+ int subnd;
+ PyObject *sub, *obj=NULL;
+ int i, j, n, curraxis, ellipexp, noellip;
+ PyArrayIterObject *it;
+ intp dimsize;
+ intp *indptr;
- subnd = arr->nd - mit->numiter;
- if (subnd < 0) {
- PyErr_SetString(PyExc_ValueError,
- "too many indices for array");
- return;
- }
-
- mit->ait = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr);
- if (mit->ait == NULL) return;
+ subnd = arr->nd - mit->numiter;
+ if (subnd < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "too many indices for array");
+ return;
+ }
- /* no subspace iteration needed. Finish up and Return */
- if (subnd == 0) {
- n = arr->nd;
- for (i=0; i<n; i++) {
- mit->iteraxes[i] = i;
- }
- goto finish;
- }
+ mit->ait = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr);
+ if (mit->ait == NULL) return;
- /* all indexing arrays have been converted to 0
- therefore we can extract the subspace with a simple
- getitem call which will use view semantics
- */
- /* But, be sure to do it with a true array.
- */
- if (PyArray_CheckExact(arr)) {
- sub = array_subscript_simple(arr, mit->indexobj);
- }
- else {
- Py_INCREF(arr);
- obj = PyArray_EnsureArray((PyObject *)arr);
- if (obj == NULL) goto fail;
- sub = array_subscript_simple((PyArrayObject *)obj, mit->indexobj);
- Py_DECREF(obj);
+ /* no subspace iteration needed. Finish up and Return */
+ if (subnd == 0) {
+ n = arr->nd;
+ for (i=0; i<n; i++) {
+ mit->iteraxes[i] = i;
}
+ goto finish;
+ }
- if (sub == NULL) goto fail;
- mit->subspace = (PyArrayIterObject *)PyArray_IterNew(sub);
- Py_DECREF(sub);
- if (mit->subspace == NULL) goto fail;
-
- /* Expand dimensions of result */
- n = mit->subspace->ao->nd;
- for (i=0; i<n; i++)
- mit->dimensions[mit->nd+i] = mit->subspace->ao->dimensions[i];
- mit->nd += n;
-
- /* Now, we still need to interpret the ellipsis and slice objects
- to determine which axes the indexing arrays are referring to
- */
- n = PyTuple_GET_SIZE(mit->indexobj);
+ /* all indexing arrays have been converted to 0
+ therefore we can extract the subspace with a simple
+ getitem call which will use view semantics
+ */
+ /* But, be sure to do it with a true array.
+ */
+ if (PyArray_CheckExact(arr)) {
+ sub = array_subscript_simple(arr, mit->indexobj);
+ }
+ else {
+ Py_INCREF(arr);
+ obj = PyArray_EnsureArray((PyObject *)arr);
+ if (obj == NULL) goto fail;
+ sub = array_subscript_simple((PyArrayObject *)obj, mit->indexobj);
+ Py_DECREF(obj);
+ }
- /* The number of dimensions an ellipsis takes up */
- ellipexp = arr->nd - n + 1;
- /* Now fill in iteraxes -- remember indexing arrays have been
- converted to 0's in mit->indexobj */
- curraxis = 0;
- j = 0;
- noellip = 1; /* Only expand the first ellipsis */
- memset(mit->bscoord, 0, sizeof(intp)*arr->nd);
- for (i=0; i<n; i++) {
- /* We need to fill in the starting coordinates for
- the subspace */
- obj = PyTuple_GET_ITEM(mit->indexobj, i);
- if (PyInt_Check(obj) || PyLong_Check(obj))
- mit->iteraxes[j++] = curraxis++;
- else if (noellip && obj == Py_Ellipsis) {
- curraxis += ellipexp;
- noellip = 0;
- }
- else {
- intp start=0;
- intp stop, step;
- /* Should be slice object or
- another Ellipsis */
- if (obj == Py_Ellipsis) {
- mit->bscoord[curraxis] = 0;
- }
- else if (!PySlice_Check(obj) || \
- (slice_GetIndices((PySliceObject *)obj,
- arr->dimensions[curraxis],
- &start, &stop, &step,
- &dimsize) < 0)) {
- PyErr_Format(PyExc_ValueError,
- "unexpected object " \
- "(%s) in selection position %d",
- obj->ob_type->tp_name, i);
- goto fail;
- }
- else {
- mit->bscoord[curraxis] = start;
- }
- curraxis += 1;
- }
+ if (sub == NULL) goto fail;
+ mit->subspace = (PyArrayIterObject *)PyArray_IterNew(sub);
+ Py_DECREF(sub);
+ if (mit->subspace == NULL) goto fail;
+
+ /* Expand dimensions of result */
+ n = mit->subspace->ao->nd;
+ for (i=0; i<n; i++)
+ mit->dimensions[mit->nd+i] = mit->subspace->ao->dimensions[i];
+ mit->nd += n;
+
+ /* Now, we still need to interpret the ellipsis and slice objects
+ to determine which axes the indexing arrays are referring to
+ */
+ n = PyTuple_GET_SIZE(mit->indexobj);
+
+ /* The number of dimensions an ellipsis takes up */
+ ellipexp = arr->nd - n + 1;
+ /* Now fill in iteraxes -- remember indexing arrays have been
+ converted to 0's in mit->indexobj */
+ curraxis = 0;
+ j = 0;
+ noellip = 1; /* Only expand the first ellipsis */
+ memset(mit->bscoord, 0, sizeof(intp)*arr->nd);
+ for (i=0; i<n; i++) {
+ /* We need to fill in the starting coordinates for
+ the subspace */
+ obj = PyTuple_GET_ITEM(mit->indexobj, i);
+ if (PyInt_Check(obj) || PyLong_Check(obj))
+ mit->iteraxes[j++] = curraxis++;
+ else if (noellip && obj == Py_Ellipsis) {
+ curraxis += ellipexp;
+ noellip = 0;
}
- finish:
- /* Here check the indexes (now that we have iteraxes) */
- mit->size = PyArray_MultiplyList(mit->dimensions, mit->nd);
- if (mit->ait->size == 0 && mit->size != 0) {
- PyErr_SetString(PyExc_ValueError,
- "invalid index into a 0-size array");
+ else {
+ intp start=0;
+ intp stop, step;
+ /* Should be slice object or
+ another Ellipsis */
+ if (obj == Py_Ellipsis) {
+ mit->bscoord[curraxis] = 0;
+ }
+ else if (!PySlice_Check(obj) || \
+ (slice_GetIndices((PySliceObject *)obj,
+ arr->dimensions[curraxis],
+ &start, &stop, &step,
+ &dimsize) < 0)) {
+ PyErr_Format(PyExc_ValueError,
+ "unexpected object " \
+ "(%s) in selection position %d",
+ obj->ob_type->tp_name, i);
goto fail;
+ }
+ else {
+ mit->bscoord[curraxis] = start;
+ }
+ curraxis += 1;
}
+ }
+ finish:
+ /* Here check the indexes (now that we have iteraxes) */
+ mit->size = PyArray_MultiplyList(mit->dimensions, mit->nd);
+ if (mit->ait->size == 0 && mit->size != 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid index into a 0-size array");
+ goto fail;
+ }
- for (i=0; i<mit->numiter; i++) {
- intp indval;
- it = mit->iters[i];
- PyArray_ITER_RESET(it);
- dimsize = arr->dimensions[mit->iteraxes[i]];
- while(it->index < it->size) {
- indptr = ((intp *)it->dataptr);
- indval = *indptr;
- if (indval < 0) indval += dimsize;
- if (indval < 0 || indval >= dimsize) {
- PyErr_Format(PyExc_IndexError,
- "index (%d) out of range "\
- "(0<=index<=%d) in dimension %d",
- (int) indval, (int) (dimsize-1),
- mit->iteraxes[i]);
- goto fail;
- }
- PyArray_ITER_NEXT(it);
- }
- PyArray_ITER_RESET(it);
+ for (i=0; i<mit->numiter; i++) {
+ intp indval;
+ it = mit->iters[i];
+ PyArray_ITER_RESET(it);
+ dimsize = arr->dimensions[mit->iteraxes[i]];
+ while(it->index < it->size) {
+ indptr = ((intp *)it->dataptr);
+ indval = *indptr;
+ if (indval < 0) indval += dimsize;
+ if (indval < 0 || indval >= dimsize) {
+ PyErr_Format(PyExc_IndexError,
+ "index (%d) out of range "\
+ "(0<=index<=%d) in dimension %d",
+ (int) indval, (int) (dimsize-1),
+ mit->iteraxes[i]);
+ goto fail;
+ }
+ PyArray_ITER_NEXT(it);
}
- return;
+ PyArray_ITER_RESET(it);
+ }
+ return;
fail:
- Py_XDECREF(mit->subspace);
- Py_XDECREF(mit->ait);
- mit->subspace = NULL;
- mit->ait = NULL;
- return;
+ Py_XDECREF(mit->subspace);
+ Py_XDECREF(mit->ait);
+ mit->subspace = NULL;
+ mit->ait = NULL;
+ return;
}
/* This function takes a Boolean array and constructs index objects and
@@ -10089,119 +10088,119 @@ PyArray_MapIterBind(PyArrayMapIterObject *mit, PyArrayObject *arr)
static int
_nonzero_indices(PyObject *myBool, PyArrayIterObject **iters)
{
- PyArray_Descr *typecode;
- PyArrayObject *ba =NULL, *new=NULL;
- int nd, j;
- intp size, i, count;
- Bool *ptr;
- intp coords[MAX_DIMS], dims_m1[MAX_DIMS];
- intp *dptr[MAX_DIMS];
-
- typecode=PyArray_DescrFromType(PyArray_BOOL);
- ba = (PyArrayObject *)PyArray_FromAny(myBool, typecode, 0, 0,
- CARRAY, NULL);
- if (ba == NULL) return -1;
- nd = ba->nd;
- for (j=0; j<nd; j++) iters[j] = NULL;
- size = PyArray_SIZE(ba);
- ptr = (Bool *)ba->data;
- count = 0;
-
- /* pre-determine how many nonzero entries there are */
- for (i=0; i<size; i++)
- if (*(ptr++)) count++;
-
- /* create count-sized index arrays for each dimension */
- for (j=0; j<nd; j++) {
- new = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &count,
- PyArray_INTP, NULL, NULL,
- 0, 0, NULL);
- if (new == NULL) goto fail;
- iters[j] = (PyArrayIterObject *) \
- PyArray_IterNew((PyObject *)new);
- Py_DECREF(new);
- if (iters[j] == NULL) goto fail;
- dptr[j] = (intp *)iters[j]->ao->data;
- coords[j] = 0;
- dims_m1[j] = ba->dimensions[j]-1;
- }
+ PyArray_Descr *typecode;
+ PyArrayObject *ba =NULL, *new=NULL;
+ int nd, j;
+ intp size, i, count;
+ Bool *ptr;
+ intp coords[MAX_DIMS], dims_m1[MAX_DIMS];
+ intp *dptr[MAX_DIMS];
+
+ typecode=PyArray_DescrFromType(PyArray_BOOL);
+ ba = (PyArrayObject *)PyArray_FromAny(myBool, typecode, 0, 0,
+ CARRAY, NULL);
+ if (ba == NULL) return -1;
+ nd = ba->nd;
+ for (j=0; j<nd; j++) iters[j] = NULL;
+ size = PyArray_SIZE(ba);
+ ptr = (Bool *)ba->data;
+ count = 0;
+
+ /* pre-determine how many nonzero entries there are */
+ for (i=0; i<size; i++)
+ if (*(ptr++)) count++;
+
+ /* create count-sized index arrays for each dimension */
+ for (j=0; j<nd; j++) {
+ new = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &count,
+ PyArray_INTP, NULL, NULL,
+ 0, 0, NULL);
+ if (new == NULL) goto fail;
+ iters[j] = (PyArrayIterObject *) \
+ PyArray_IterNew((PyObject *)new);
+ Py_DECREF(new);
+ if (iters[j] == NULL) goto fail;
+ dptr[j] = (intp *)iters[j]->ao->data;
+ coords[j] = 0;
+ dims_m1[j] = ba->dimensions[j]-1;
+ }
- ptr = (Bool *)ba->data;
+ ptr = (Bool *)ba->data;
- if (count == 0) goto finish;
+ if (count == 0) goto finish;
- /* Loop through the Boolean array and copy coordinates
- for non-zero entries */
- for (i=0; i<size; i++) {
- if (*(ptr++)) {
- for (j=0; j<nd; j++)
- *(dptr[j]++) = coords[j];
- }
- /* Borrowed from ITER_NEXT macro */
- for (j=nd-1; j>=0; j--) {
- if (coords[j] < dims_m1[j]) {
- coords[j]++;
- break;
- }
- else {
- coords[j] = 0;
- }
- }
+ /* Loop through the Boolean array and copy coordinates
+ for non-zero entries */
+ for (i=0; i<size; i++) {
+ if (*(ptr++)) {
+ for (j=0; j<nd; j++)
+ *(dptr[j]++) = coords[j];
+ }
+ /* Borrowed from ITER_NEXT macro */
+ for (j=nd-1; j>=0; j--) {
+ if (coords[j] < dims_m1[j]) {
+ coords[j]++;
+ break;
+ }
+ else {
+ coords[j] = 0;
+ }
}
+ }
finish:
- Py_DECREF(ba);
- return nd;
+ Py_DECREF(ba);
+ return nd;
fail:
- for (j=0; j<nd; j++) {
- Py_XDECREF(iters[j]);
- }
- Py_XDECREF(ba);
- return -1;
+ for (j=0; j<nd; j++) {
+ Py_XDECREF(iters[j]);
+ }
+ Py_XDECREF(ba);
+ return -1;
}
static PyObject *
PyArray_MapIterNew(PyObject *indexobj, int oned, int fancy)
{
- PyArrayMapIterObject *mit;
- PyArray_Descr *indtype;
- PyObject *arr = NULL;
- int i, n, started, nonindex;
+ PyArrayMapIterObject *mit;
+ PyArray_Descr *indtype;
+ PyObject *arr = NULL;
+ int i, n, started, nonindex;
- if (fancy == SOBJ_BADARRAY) {
- PyErr_SetString(PyExc_IndexError, \
- "arrays used as indices must be of " \
- "integer (or boolean) type");
- return NULL;
- }
- if (fancy == SOBJ_TOOMANY) {
- PyErr_SetString(PyExc_IndexError, "too many indices");
- return NULL;
- }
+ if (fancy == SOBJ_BADARRAY) {
+ PyErr_SetString(PyExc_IndexError, \
+ "arrays used as indices must be of " \
+ "integer (or boolean) type");
+ return NULL;
+ }
+ if (fancy == SOBJ_TOOMANY) {
+ PyErr_SetString(PyExc_IndexError, "too many indices");
+ return NULL;
+ }
- mit = (PyArrayMapIterObject *)_pya_malloc(sizeof(PyArrayMapIterObject));
- PyObject_Init((PyObject *)mit, &PyArrayMapIter_Type);
- if (mit == NULL)
- return NULL;
- for (i=0; i<MAX_DIMS; i++)
- mit->iters[i] = NULL;
- mit->index = 0;
- mit->ait = NULL;
- mit->subspace = NULL;
- mit->numiter = 0;
- mit->consec = 1;
- Py_INCREF(indexobj);
+ mit = (PyArrayMapIterObject *)_pya_malloc(sizeof(PyArrayMapIterObject));
+ PyObject_Init((PyObject *)mit, &PyArrayMapIter_Type);
+ if (mit == NULL)
+ return NULL;
+ for (i=0; i<MAX_DIMS; i++)
+ mit->iters[i] = NULL;
+ mit->index = 0;
+ mit->ait = NULL;
+ mit->subspace = NULL;
+ mit->numiter = 0;
+ mit->consec = 1;
+ Py_INCREF(indexobj);
+ mit->indexobj = indexobj;
+
+ if (fancy == SOBJ_LISTTUP) {
+ PyObject *newobj;
+ newobj = PySequence_Tuple(indexobj);
+ if (newobj == NULL) goto fail;
+ Py_DECREF(indexobj);
+ indexobj = newobj;
mit->indexobj = indexobj;
-
- if (fancy == SOBJ_LISTTUP) {
- PyObject *newobj;
- newobj = PySequence_Tuple(indexobj);
- if (newobj == NULL) goto fail;
- Py_DECREF(indexobj);
- indexobj = newobj;
- mit->indexobj = indexobj;
- }
+ }
#undef SOBJ_NOTFANCY
#undef SOBJ_ISFANCY
@@ -10209,118 +10208,118 @@ PyArray_MapIterNew(PyObject *indexobj, int oned, int fancy)
#undef SOBJ_TOOMANY
#undef SOBJ_LISTTUP
- if (oned) return (PyObject *)mit;
-
- /* Must have some kind of fancy indexing if we are here */
- /* indexobj is either a list, an arrayobject, or a tuple
- (with at least 1 list or arrayobject or Bool object), */
-
- /* convert all inputs to iterators */
- if (PyArray_Check(indexobj) && \
- (PyArray_TYPE(indexobj) == PyArray_BOOL)) {
- mit->numiter = _nonzero_indices(indexobj, mit->iters);
- if (mit->numiter < 0) goto fail;
- mit->nd = 1;
- mit->dimensions[0] = mit->iters[0]->dims_m1[0]+1;
- Py_DECREF(mit->indexobj);
- mit->indexobj = PyTuple_New(mit->numiter);
- if (mit->indexobj == NULL) goto fail;
- for (i=0; i<mit->numiter; i++) {
- PyTuple_SET_ITEM(mit->indexobj, i,
- PyInt_FromLong(0));
- }
+ if (oned) return (PyObject *)mit;
+
+ /* Must have some kind of fancy indexing if we are here */
+ /* indexobj is either a list, an arrayobject, or a tuple
+ (with at least 1 list or arrayobject or Bool object), */
+
+ /* convert all inputs to iterators */
+ if (PyArray_Check(indexobj) && \
+ (PyArray_TYPE(indexobj) == PyArray_BOOL)) {
+ mit->numiter = _nonzero_indices(indexobj, mit->iters);
+ if (mit->numiter < 0) goto fail;
+ mit->nd = 1;
+ mit->dimensions[0] = mit->iters[0]->dims_m1[0]+1;
+ Py_DECREF(mit->indexobj);
+ mit->indexobj = PyTuple_New(mit->numiter);
+ if (mit->indexobj == NULL) goto fail;
+ for (i=0; i<mit->numiter; i++) {
+ PyTuple_SET_ITEM(mit->indexobj, i,
+ PyInt_FromLong(0));
}
+ }
- else if (PyArray_Check(indexobj) || !PyTuple_Check(indexobj)) {
- mit->numiter = 1;
- indtype = PyArray_DescrFromType(PyArray_INTP);
- arr = PyArray_FromAny(indexobj, indtype, 0, 0, FORCECAST, NULL);
- if (arr == NULL) goto fail;
- mit->iters[0] = (PyArrayIterObject *)PyArray_IterNew(arr);
- if (mit->iters[0] == NULL) {Py_DECREF(arr); goto fail;}
- mit->nd = PyArray_NDIM(arr);
- memcpy(mit->dimensions,PyArray_DIMS(arr),mit->nd*sizeof(intp));
- mit->size = PyArray_SIZE(arr);
- Py_DECREF(arr);
- Py_DECREF(mit->indexobj);
- mit->indexobj = Py_BuildValue("(N)", PyInt_FromLong(0));
- }
- else { /* must be a tuple */
- PyObject *obj;
- PyArrayIterObject **iterp;
- PyObject *new;
- int numiters, j, n2;
- /* Make a copy of the tuple -- we will be replacing
- index objects with 0's */
- n = PyTuple_GET_SIZE(indexobj);
- n2 = n;
- new = PyTuple_New(n2);
- if (new == NULL) goto fail;
- started = 0;
- nonindex = 0;
- j = 0;
- for (i=0; i<n; i++) {
- obj = PyTuple_GET_ITEM(indexobj,i);
- iterp = mit->iters + mit->numiter;
- if ((numiters=_convert_obj(obj, iterp)) < 0) {
- Py_DECREF(new);
- goto fail;
- }
- if (numiters > 0) {
- started = 1;
- if (nonindex) mit->consec = 0;
- mit->numiter += numiters;
- if (numiters == 1) {
- PyTuple_SET_ITEM(new,j++,
- PyInt_FromLong(0));
- }
- else { /* we need to grow the
- new indexing object and fill
- it with 0s for each of the iterators
- produced */
- int k;
- n2 += numiters - 1;
- if (_PyTuple_Resize(&new, n2) < 0)
- goto fail;
- for (k=0;k<numiters;k++) {
- PyTuple_SET_ITEM \
- (new,j++,
- PyInt_FromLong(0));
- }
- }
- }
- else {
- if (started) nonindex = 1;
- Py_INCREF(obj);
- PyTuple_SET_ITEM(new,j++,obj);
- }
- }
- Py_DECREF(mit->indexobj);
- mit->indexobj = new;
- /* Store the number of iterators actually converted */
- /* These will be mapped to actual axes at bind time */
- if (PyArray_Broadcast((PyArrayMultiIterObject *)mit) < 0)
+ else if (PyArray_Check(indexobj) || !PyTuple_Check(indexobj)) {
+ mit->numiter = 1;
+ indtype = PyArray_DescrFromType(PyArray_INTP);
+ arr = PyArray_FromAny(indexobj, indtype, 0, 0, FORCECAST, NULL);
+ if (arr == NULL) goto fail;
+ mit->iters[0] = (PyArrayIterObject *)PyArray_IterNew(arr);
+ if (mit->iters[0] == NULL) {Py_DECREF(arr); goto fail;}
+ mit->nd = PyArray_NDIM(arr);
+ memcpy(mit->dimensions,PyArray_DIMS(arr),mit->nd*sizeof(intp));
+ mit->size = PyArray_SIZE(arr);
+ Py_DECREF(arr);
+ Py_DECREF(mit->indexobj);
+ mit->indexobj = Py_BuildValue("(N)", PyInt_FromLong(0));
+ }
+ else { /* must be a tuple */
+ PyObject *obj;
+ PyArrayIterObject **iterp;
+ PyObject *new;
+ int numiters, j, n2;
+ /* Make a copy of the tuple -- we will be replacing
+ index objects with 0's */
+ n = PyTuple_GET_SIZE(indexobj);
+ n2 = n;
+ new = PyTuple_New(n2);
+ if (new == NULL) goto fail;
+ started = 0;
+ nonindex = 0;
+ j = 0;
+ for (i=0; i<n; i++) {
+ obj = PyTuple_GET_ITEM(indexobj,i);
+ iterp = mit->iters + mit->numiter;
+ if ((numiters=_convert_obj(obj, iterp)) < 0) {
+ Py_DECREF(new);
+ goto fail;
+ }
+ if (numiters > 0) {
+ started = 1;
+ if (nonindex) mit->consec = 0;
+ mit->numiter += numiters;
+ if (numiters == 1) {
+ PyTuple_SET_ITEM(new,j++,
+ PyInt_FromLong(0));
+ }
+ else { /* we need to grow the
+ new indexing object and fill
+ it with 0s for each of the iterators
+ produced */
+ int k;
+ n2 += numiters - 1;
+ if (_PyTuple_Resize(&new, n2) < 0)
goto fail;
+ for (k=0;k<numiters;k++) {
+ PyTuple_SET_ITEM \
+ (new,j++,
+ PyInt_FromLong(0));
+ }
+ }
+ }
+ else {
+ if (started) nonindex = 1;
+ Py_INCREF(obj);
+ PyTuple_SET_ITEM(new,j++,obj);
+ }
}
+ Py_DECREF(mit->indexobj);
+ mit->indexobj = new;
+ /* Store the number of iterators actually converted */
+ /* These will be mapped to actual axes at bind time */
+ if (PyArray_Broadcast((PyArrayMultiIterObject *)mit) < 0)
+ goto fail;
+ }
- return (PyObject *)mit;
+ return (PyObject *)mit;
fail:
- Py_DECREF(mit);
- return NULL;
+ Py_DECREF(mit);
+ return NULL;
}
static void
arraymapiter_dealloc(PyArrayMapIterObject *mit)
{
- int i;
- Py_XDECREF(mit->indexobj);
- Py_XDECREF(mit->ait);
- Py_XDECREF(mit->subspace);
- for (i=0; i<mit->numiter; i++)
- Py_XDECREF(mit->iters[i]);
- _pya_free(mit);
+ int i;
+ Py_XDECREF(mit->indexobj);
+ Py_XDECREF(mit->ait);
+ Py_XDECREF(mit->subspace);
+ for (i=0; i<mit->numiter; i++)
+ Py_XDECREF(mit->iters[i]);
+ _pya_free(mit);
}
/* The mapiter object must be created new each time. It does not work
@@ -10335,53 +10334,53 @@ arraymapiter_dealloc(PyArrayMapIterObject *mit)
*/
static PyTypeObject PyArrayMapIter_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "numpy.mapiter", /* tp_name */
- sizeof(PyArrayIterObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)arraymapiter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- (iternextfunc)0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
- 0, /* tp_is_gc */
- 0, /* tp_bases */
- 0, /* tp_mro */
- 0, /* tp_cache */
- 0, /* tp_subclasses */
- 0 /* tp_weaklist */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "numpy.mapiter", /* tp_name */
+ sizeof(PyArrayIterObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)arraymapiter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ (iternextfunc)0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
+ 0, /* tp_is_gc */
+ 0, /* tp_bases */
+ 0, /* tp_mro */
+ 0, /* tp_cache */
+ 0, /* tp_subclasses */
+ 0 /* tp_weaklist */
};
@@ -10389,152 +10388,152 @@ static PyTypeObject PyArrayMapIter_Type = {
/*OBJECT_API
- Get MultiIterator,
+ Get MultiIterator,
*/
static PyObject *
PyArray_MultiIterNew(int n, ...)
{
- va_list va;
- PyArrayMultiIterObject *multi;
- PyObject *current;
- PyObject *arr;
+ va_list va;
+ PyArrayMultiIterObject *multi;
+ PyObject *current;
+ PyObject *arr;
- int i, err=0;
+ int i, err=0;
- if (n < 2 || n > NPY_MAXARGS) {
- PyErr_Format(PyExc_ValueError,
- "Need between 2 and (%d) " \
- "array objects (inclusive).", NPY_MAXARGS);
- return NULL;
- }
+ if (n < 2 || n > NPY_MAXARGS) {
+ PyErr_Format(PyExc_ValueError,
+ "Need between 2 and (%d) " \
+ "array objects (inclusive).", NPY_MAXARGS);
+ return NULL;
+ }
- /* fprintf(stderr, "multi new...");*/
+ /* fprintf(stderr, "multi new...");*/
- multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
- if (multi == NULL) return PyErr_NoMemory();
- PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
+ multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
+ if (multi == NULL) return PyErr_NoMemory();
+ PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
- for (i=0; i<n; i++) multi->iters[i] = NULL;
- multi->numiter = n;
- multi->index = 0;
+ for (i=0; i<n; i++) multi->iters[i] = NULL;
+ multi->numiter = n;
+ multi->index = 0;
- va_start(va, n);
- for (i=0; i<n; i++) {
- current = va_arg(va, PyObject *);
- arr = PyArray_FROM_O(current);
- if (arr==NULL) {
- err=1; break;
- }
- else {
- multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr);
- Py_DECREF(arr);
- }
+ va_start(va, n);
+ for (i=0; i<n; i++) {
+ current = va_arg(va, PyObject *);
+ arr = PyArray_FROM_O(current);
+ if (arr==NULL) {
+ err=1; break;
+ }
+ else {
+ multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr);
+ Py_DECREF(arr);
}
+ }
- va_end(va);
+ va_end(va);
- if (!err && PyArray_Broadcast(multi) < 0) err=1;
+ if (!err && PyArray_Broadcast(multi) < 0) err=1;
- if (err) {
- Py_DECREF(multi);
- return NULL;
- }
+ if (err) {
+ Py_DECREF(multi);
+ return NULL;
+ }
- PyArray_MultiIter_RESET(multi);
+ PyArray_MultiIter_RESET(multi);
- return (PyObject *)multi;
+ return (PyObject *)multi;
}
static PyObject *
arraymultiter_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
{
- int n, i;
- PyArrayMultiIterObject *multi;
- PyObject *arr;
+ int n, i;
+ PyArrayMultiIterObject *multi;
+ PyObject *arr;
- if (kwds != NULL) {
- PyErr_SetString(PyExc_ValueError,
- "keyword arguments not accepted.");
- return NULL;
- }
-
- n = PyTuple_Size(args);
- if (n < 2 || n > NPY_MAXARGS) {
- if (PyErr_Occurred()) return NULL;
- PyErr_Format(PyExc_ValueError,
- "Need at least two and fewer than (%d) " \
- "array objects.", NPY_MAXARGS);
- return NULL;
- }
+ if (kwds != NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "keyword arguments not accepted.");
+ return NULL;
+ }
- multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
- if (multi == NULL) return PyErr_NoMemory();
- PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
+ n = PyTuple_Size(args);
+ if (n < 2 || n > NPY_MAXARGS) {
+ if (PyErr_Occurred()) return NULL;
+ PyErr_Format(PyExc_ValueError,
+ "Need at least two and fewer than (%d) " \
+ "array objects.", NPY_MAXARGS);
+ return NULL;
+ }
- multi->numiter = n;
- multi->index = 0;
- for (i=0; i<n; i++) multi->iters[i] = NULL;
- for (i=0; i<n; i++) {
- arr = PyArray_FromAny(PyTuple_GET_ITEM(args, i), NULL, 0, 0, 0, NULL);
- if (arr == NULL) goto fail;
- if ((multi->iters[i] = \
- (PyArrayIterObject *)PyArray_IterNew(arr))==NULL)
- goto fail;
- Py_DECREF(arr);
- }
- if (PyArray_Broadcast(multi) < 0) goto fail;
- PyArray_MultiIter_RESET(multi);
+ multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
+ if (multi == NULL) return PyErr_NoMemory();
+ PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
+
+ multi->numiter = n;
+ multi->index = 0;
+ for (i=0; i<n; i++) multi->iters[i] = NULL;
+ for (i=0; i<n; i++) {
+ arr = PyArray_FromAny(PyTuple_GET_ITEM(args, i), NULL, 0, 0, 0, NULL);
+ if (arr == NULL) goto fail;
+ if ((multi->iters[i] = \
+ (PyArrayIterObject *)PyArray_IterNew(arr))==NULL)
+ goto fail;
+ Py_DECREF(arr);
+ }
+ if (PyArray_Broadcast(multi) < 0) goto fail;
+ PyArray_MultiIter_RESET(multi);
- return (PyObject *)multi;
+ return (PyObject *)multi;
fail:
- Py_DECREF(multi);
- return NULL;
+ Py_DECREF(multi);
+ return NULL;
}
static PyObject *
arraymultiter_next(PyArrayMultiIterObject *multi)
{
- PyObject *ret;
- int i, n;
+ PyObject *ret;
+ int i, n;
- n = multi->numiter;
- ret = PyTuple_New(n);
- if (ret == NULL) return NULL;
- if (multi->index < multi->size) {
- for (i=0; i < n; i++) {
- PyArrayIterObject *it=multi->iters[i];
- PyTuple_SET_ITEM(ret, i,
- PyArray_ToScalar(it->dataptr, it->ao));
- PyArray_ITER_NEXT(it);
- }
- multi->index++;
- return ret;
+ n = multi->numiter;
+ ret = PyTuple_New(n);
+ if (ret == NULL) return NULL;
+ if (multi->index < multi->size) {
+ for (i=0; i < n; i++) {
+ PyArrayIterObject *it=multi->iters[i];
+ PyTuple_SET_ITEM(ret, i,
+ PyArray_ToScalar(it->dataptr, it->ao));
+ PyArray_ITER_NEXT(it);
}
- return NULL;
+ multi->index++;
+ return ret;
+ }
+ return NULL;
}
static void
arraymultiter_dealloc(PyArrayMultiIterObject *multi)
{
- int i;
+ int i;
- for (i=0; i<multi->numiter; i++)
- Py_XDECREF(multi->iters[i]);
- multi->ob_type->tp_free((PyObject *)multi);
+ for (i=0; i<multi->numiter; i++)
+ Py_XDECREF(multi->iters[i]);
+ multi->ob_type->tp_free((PyObject *)multi);
}
static PyObject *
arraymultiter_size_get(PyArrayMultiIterObject *self)
{
#if SIZEOF_INTP <= SIZEOF_LONG
- return PyInt_FromLong((long) self->size);
+ return PyInt_FromLong((long) self->size);
#else
- if (self->size < MAX_LONG)
- return PyInt_FromLong((long) self->size);
- else
- return PyLong_FromLongLong((longlong) self->size);
+ if (self->size < MAX_LONG)
+ return PyInt_FromLong((long) self->size);
+ else
+ return PyLong_FromLongLong((longlong) self->size);
#endif
}
@@ -10542,135 +10541,135 @@ static PyObject *
arraymultiter_index_get(PyArrayMultiIterObject *self)
{
#if SIZEOF_INTP <= SIZEOF_LONG
- return PyInt_FromLong((long) self->index);
+ return PyInt_FromLong((long) self->index);
#else
- if (self->size < MAX_LONG)
- return PyInt_FromLong((long) self->index);
- else
- return PyLong_FromLongLong((longlong) self->index);
+ if (self->size < MAX_LONG)
+ return PyInt_FromLong((long) self->index);
+ else
+ return PyLong_FromLongLong((longlong) self->index);
#endif
}
static PyObject *
arraymultiter_shape_get(PyArrayMultiIterObject *self)
{
- return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
+ return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
}
static PyObject *
arraymultiter_iters_get(PyArrayMultiIterObject *self)
{
- PyObject *res;
- int i, n;
- n = self->numiter;
- res = PyTuple_New(n);
- if (res == NULL) return res;
- for (i=0; i<n; i++) {
- Py_INCREF(self->iters[i]);
- PyTuple_SET_ITEM(res, i, (PyObject *)self->iters[i]);
- }
- return res;
+ PyObject *res;
+ int i, n;
+ n = self->numiter;
+ res = PyTuple_New(n);
+ if (res == NULL) return res;
+ for (i=0; i<n; i++) {
+ Py_INCREF(self->iters[i]);
+ PyTuple_SET_ITEM(res, i, (PyObject *)self->iters[i]);
+ }
+ return res;
}
static PyGetSetDef arraymultiter_getsetlist[] = {
- {"size",
- (getter)arraymultiter_size_get,
- NULL, NULL},
- {"index",
- (getter)arraymultiter_index_get,
- NULL, NULL},
- {"shape",
- (getter)arraymultiter_shape_get,
- NULL, NULL},
- {"iters",
- (getter)arraymultiter_iters_get,
- NULL, NULL},
- {NULL, NULL, NULL, NULL},
+ {"size",
+ (getter)arraymultiter_size_get,
+ NULL, NULL},
+ {"index",
+ (getter)arraymultiter_index_get,
+ NULL, NULL},
+ {"shape",
+ (getter)arraymultiter_shape_get,
+ NULL, NULL},
+ {"iters",
+ (getter)arraymultiter_iters_get,
+ NULL, NULL},
+ {NULL, NULL, NULL, NULL},
};
static PyMemberDef arraymultiter_members[] = {
- {"numiter", T_INT, offsetof(PyArrayMultiIterObject, numiter),
- RO, NULL},
- {"nd", T_INT, offsetof(PyArrayMultiIterObject, nd), RO, NULL},
- {NULL},
+ {"numiter", T_INT, offsetof(PyArrayMultiIterObject, numiter),
+ RO, NULL},
+ {"nd", T_INT, offsetof(PyArrayMultiIterObject, nd), RO, NULL},
+ {NULL},
};
static PyObject *
arraymultiter_reset(PyArrayMultiIterObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "")) return NULL;
+ if (!PyArg_ParseTuple(args, "")) return NULL;
- PyArray_MultiIter_RESET(self);
- Py_INCREF(Py_None);
- return Py_None;
+ PyArray_MultiIter_RESET(self);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef arraymultiter_methods[] = {
- {"reset", (PyCFunction) arraymultiter_reset, METH_VARARGS, NULL},
- {NULL, NULL},
+ {"reset", (PyCFunction) arraymultiter_reset, METH_VARARGS, NULL},
+ {NULL, NULL},
};
static PyTypeObject PyArrayMultiIter_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "numpy.broadcast", /* tp_name */
- sizeof(PyArrayMultiIterObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)arraymultiter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- (iternextfunc)arraymultiter_next, /* tp_iternext */
- arraymultiter_methods, /* tp_methods */
- arraymultiter_members, /* tp_members */
- arraymultiter_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)0, /* tp_init */
- 0, /* tp_alloc */
- arraymultiter_new, /* tp_new */
- 0, /* tp_free */
- 0, /* tp_is_gc */
- 0, /* tp_bases */
- 0, /* tp_mro */
- 0, /* tp_cache */
- 0, /* tp_subclasses */
- 0 /* tp_weaklist */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "numpy.broadcast", /* tp_name */
+ sizeof(PyArrayMultiIterObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)arraymultiter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ (iternextfunc)arraymultiter_next, /* tp_iternext */
+ arraymultiter_methods, /* tp_methods */
+ arraymultiter_members, /* tp_members */
+ arraymultiter_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)0, /* tp_init */
+ 0, /* tp_alloc */
+ arraymultiter_new, /* tp_new */
+ 0, /* tp_free */
+ 0, /* tp_is_gc */
+ 0, /* tp_bases */
+ 0, /* tp_mro */
+ 0, /* tp_cache */
+ 0, /* tp_subclasses */
+ 0 /* tp_weaklist */
};
/*OBJECT_API*/
static PyArray_Descr *
PyArray_DescrNewFromType(int type_num)
{
- PyArray_Descr *old;
- PyArray_Descr *new;
+ PyArray_Descr *old;
+ PyArray_Descr *new;
- old = PyArray_DescrFromType(type_num);
- new = PyArray_DescrNew(old);
- Py_DECREF(old);
- return new;
+ old = PyArray_DescrFromType(type_num);
+ new = PyArray_DescrNew(old);
+ Py_DECREF(old);
+ return new;
}
/*** Array Descr Objects for dynamic types **/
@@ -10691,27 +10690,27 @@ PyArray_DescrNewFromType(int type_num)
static PyArray_Descr *
PyArray_DescrNew(PyArray_Descr *base)
{
- PyArray_Descr *new;
-
- new = PyObject_New(PyArray_Descr, &PyArrayDescr_Type);
- if (new == NULL) return NULL;
- /* Don't copy PyObject_HEAD part */
- memcpy((char *)new+sizeof(PyObject),
- (char *)base+sizeof(PyObject),
- sizeof(PyArray_Descr)-sizeof(PyObject));
-
- if (new->fields == Py_None) new->fields = NULL;
- Py_XINCREF(new->fields);
- Py_XINCREF(new->names);
- if (new->subarray) {
- new->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
- memcpy(new->subarray, base->subarray,
- sizeof(PyArray_ArrayDescr));
- Py_INCREF(new->subarray->shape);
- Py_INCREF(new->subarray->base);
- }
- Py_XINCREF(new->typeobj);
- return new;
+ PyArray_Descr *new;
+
+ new = PyObject_New(PyArray_Descr, &PyArrayDescr_Type);
+ if (new == NULL) return NULL;
+ /* Don't copy PyObject_HEAD part */
+ memcpy((char *)new+sizeof(PyObject),
+ (char *)base+sizeof(PyObject),
+ sizeof(PyArray_Descr)-sizeof(PyObject));
+
+ if (new->fields == Py_None) new->fields = NULL;
+ Py_XINCREF(new->fields);
+ Py_XINCREF(new->names);
+ if (new->subarray) {
+ new->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
+ memcpy(new->subarray, base->subarray,
+ sizeof(PyArray_ArrayDescr));
+ Py_INCREF(new->subarray->shape);
+ Py_INCREF(new->subarray->base);
+ }
+ Py_XINCREF(new->typeobj);
+ return new;
}
/* should never be called for builtin-types unless
@@ -10720,23 +10719,23 @@ PyArray_DescrNew(PyArray_Descr *base)
static void
arraydescr_dealloc(PyArray_Descr *self)
{
- if (self->fields == Py_None) {
- fprintf(stderr, "*** Reference count error detected: \n" \
- "an attempt was made to deallocate %d (%c) ***\n",
- self->type_num, self->type);
- Py_INCREF(self);
- Py_INCREF(self);
- return;
- }
- Py_XDECREF(self->typeobj);
- Py_XDECREF(self->names);
- Py_XDECREF(self->fields);
- if (self->subarray) {
- Py_DECREF(self->subarray->shape);
- Py_DECREF(self->subarray->base);
- _pya_free(self->subarray);
- }
- self->ob_type->tp_free((PyObject *)self);
+ if (self->fields == Py_None) {
+ fprintf(stderr, "*** Reference count error detected: \n" \
+ "an attempt was made to deallocate %d (%c) ***\n",
+ self->type_num, self->type);
+ Py_INCREF(self);
+ Py_INCREF(self);
+ return;
+ }
+ Py_XDECREF(self->typeobj);
+ Py_XDECREF(self->names);
+ Py_XDECREF(self->fields);
+ if (self->subarray) {
+ Py_DECREF(self->subarray->shape);
+ Py_DECREF(self->subarray->base);
+ _pya_free(self->subarray);
+ }
+ self->ob_type->tp_free((PyObject *)self);
}
/* we need to be careful about setting attributes because these
@@ -10744,133 +10743,133 @@ arraydescr_dealloc(PyArray_Descr *self)
data. Currently no attributes of dtype objects can be set.
*/
static PyMemberDef arraydescr_members[] = {
- {"type", T_OBJECT, offsetof(PyArray_Descr, typeobj), RO, NULL},
- {"kind", T_CHAR, offsetof(PyArray_Descr, kind), RO, NULL},
- {"char", T_CHAR, offsetof(PyArray_Descr, type), RO, NULL},
- {"num", T_INT, offsetof(PyArray_Descr, type_num), RO, NULL},
- {"byteorder", T_CHAR, offsetof(PyArray_Descr, byteorder), RO, NULL},
- {"itemsize", T_INT, offsetof(PyArray_Descr, elsize), RO, NULL},
- {"alignment", T_INT, offsetof(PyArray_Descr, alignment), RO, NULL},
- {"flags", T_UBYTE, offsetof(PyArray_Descr, hasobject), RO, NULL},
- {"names", T_OBJECT, offsetof(PyArray_Descr, names), RO, NULL},
- {NULL},
+ {"type", T_OBJECT, offsetof(PyArray_Descr, typeobj), RO, NULL},
+ {"kind", T_CHAR, offsetof(PyArray_Descr, kind), RO, NULL},
+ {"char", T_CHAR, offsetof(PyArray_Descr, type), RO, NULL},
+ {"num", T_INT, offsetof(PyArray_Descr, type_num), RO, NULL},
+ {"byteorder", T_CHAR, offsetof(PyArray_Descr, byteorder), RO, NULL},
+ {"itemsize", T_INT, offsetof(PyArray_Descr, elsize), RO, NULL},
+ {"alignment", T_INT, offsetof(PyArray_Descr, alignment), RO, NULL},
+ {"flags", T_UBYTE, offsetof(PyArray_Descr, hasobject), RO, NULL},
+ {"names", T_OBJECT, offsetof(PyArray_Descr, names), RO, NULL},
+ {NULL},
};
static PyObject *
arraydescr_subdescr_get(PyArray_Descr *self)
{
- if (self->subarray == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return Py_BuildValue("OO", (PyObject *)self->subarray->base,
- self->subarray->shape);
+ if (self->subarray == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return Py_BuildValue("OO", (PyObject *)self->subarray->base,
+ self->subarray->shape);
}
static PyObject *
arraydescr_protocol_typestr_get(PyArray_Descr *self)
{
- char basic_=self->kind;
- char endian = self->byteorder;
- int size=self->elsize;
+ char basic_=self->kind;
+ char endian = self->byteorder;
+ int size=self->elsize;
- if (endian == '=') {
- endian = '<';
- if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
- }
+ if (endian == '=') {
+ endian = '<';
+ if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
+ }
- if (self->type_num == PyArray_UNICODE) {
- size >>= 2;
- }
- return PyString_FromFormat("%c%c%d", endian, basic_, size);
+ if (self->type_num == PyArray_UNICODE) {
+ size >>= 2;
+ }
+ return PyString_FromFormat("%c%c%d", endian, basic_, size);
}
static PyObject *
arraydescr_typename_get(PyArray_Descr *self)
{
- int len;
- PyTypeObject *typeobj = self->typeobj;
- PyObject *res;
- char *s;
- static int prefix_len=0;
-
- if (PyTypeNum_ISUSERDEF(self->type_num)) {
- s = strrchr(typeobj->tp_name, '.');
- if (s == NULL) {
- res = PyString_FromString(typeobj->tp_name);
- }
- else {
- res = PyString_FromStringAndSize(s+1, strlen(s)-1);
- }
- return res;
- }
- else {
- if (prefix_len == 0)
- prefix_len = strlen("numpy.");
+ int len;
+ PyTypeObject *typeobj = self->typeobj;
+ PyObject *res;
+ char *s;
+ static int prefix_len=0;
- len = strlen(typeobj->tp_name);
- if (*(typeobj->tp_name + (len-1)) == '_')
- len-=1;
- len -= prefix_len;
- res = PyString_FromStringAndSize(typeobj->tp_name+prefix_len, len);
+ if (PyTypeNum_ISUSERDEF(self->type_num)) {
+ s = strrchr(typeobj->tp_name, '.');
+ if (s == NULL) {
+ res = PyString_FromString(typeobj->tp_name);
}
- if (PyTypeNum_ISFLEXIBLE(self->type_num) && self->elsize != 0) {
- PyObject *p;
- p = PyString_FromFormat("%d", self->elsize * 8);
- PyString_ConcatAndDel(&res, p);
+ else {
+ res = PyString_FromStringAndSize(s+1, strlen(s)-1);
}
return res;
+ }
+ else {
+ if (prefix_len == 0)
+ prefix_len = strlen("numpy.");
+
+ len = strlen(typeobj->tp_name);
+ if (*(typeobj->tp_name + (len-1)) == '_')
+ len-=1;
+ len -= prefix_len;
+ res = PyString_FromStringAndSize(typeobj->tp_name+prefix_len, len);
+ }
+ if (PyTypeNum_ISFLEXIBLE(self->type_num) && self->elsize != 0) {
+ PyObject *p;
+ p = PyString_FromFormat("%d", self->elsize * 8);
+ PyString_ConcatAndDel(&res, p);
+ }
+ return res;
}
static PyObject *
arraydescr_base_get(PyArray_Descr *self)
{
- if (self->subarray == NULL) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- Py_INCREF(self->subarray->base);
- return (PyObject *)(self->subarray->base);
+ if (self->subarray == NULL) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ Py_INCREF(self->subarray->base);
+ return (PyObject *)(self->subarray->base);
}
static PyObject *
arraydescr_shape_get(PyArray_Descr *self)
{
- if (self->subarray == NULL) {
- return PyTuple_New(0);
- }
- if (PyTuple_Check(self->subarray->shape)) {
- Py_INCREF(self->subarray->shape);
- return (PyObject *)(self->subarray->shape);
- }
- return Py_BuildValue("(O)", self->subarray->shape);
+ if (self->subarray == NULL) {
+ return PyTuple_New(0);
+ }
+ if (PyTuple_Check(self->subarray->shape)) {
+ Py_INCREF(self->subarray->shape);
+ return (PyObject *)(self->subarray->shape);
+ }
+ return Py_BuildValue("(O)", self->subarray->shape);
}
static PyObject *
arraydescr_protocol_descr_get(PyArray_Descr *self)
{
- PyObject *dobj, *res;
- PyObject *_numpy_internal;
-
- if (self->names == NULL) {
- /* get default */
- dobj = PyTuple_New(2);
- if (dobj == NULL) return NULL;
- PyTuple_SET_ITEM(dobj, 0, PyString_FromString(""));
- PyTuple_SET_ITEM(dobj, 1, \
- arraydescr_protocol_typestr_get(self));
- res = PyList_New(1);
- if (res == NULL) {Py_DECREF(dobj); return NULL;}
- PyList_SET_ITEM(res, 0, dobj);
- return res;
- }
-
- _numpy_internal = PyImport_ImportModule("numpy.core._internal");
- if (_numpy_internal == NULL) return NULL;
- res = PyObject_CallMethod(_numpy_internal, "_array_descr",
- "O", self);
- Py_DECREF(_numpy_internal);
+ PyObject *dobj, *res;
+ PyObject *_numpy_internal;
+
+ if (self->names == NULL) {
+ /* get default */
+ dobj = PyTuple_New(2);
+ if (dobj == NULL) return NULL;
+ PyTuple_SET_ITEM(dobj, 0, PyString_FromString(""));
+ PyTuple_SET_ITEM(dobj, 1, \
+ arraydescr_protocol_typestr_get(self));
+ res = PyList_New(1);
+ if (res == NULL) {Py_DECREF(dobj); return NULL;}
+ PyList_SET_ITEM(res, 0, dobj);
return res;
+ }
+
+ _numpy_internal = PyImport_ImportModule("numpy.core._internal");
+ if (_numpy_internal == NULL) return NULL;
+ res = PyObject_CallMethod(_numpy_internal, "_array_descr",
+ "O", self);
+ Py_DECREF(_numpy_internal);
+ return res;
}
/* returns 1 for a builtin type
@@ -10880,31 +10879,31 @@ arraydescr_protocol_descr_get(PyArray_Descr *self)
static PyObject *
arraydescr_isbuiltin_get(PyArray_Descr *self)
{
- long val;
- val = 0;
- if (self->fields == Py_None) val = 1;
- if (PyTypeNum_ISUSERDEF(self->type_num)) val = 2;
- return PyInt_FromLong(val);
+ long val;
+ val = 0;
+ if (self->fields == Py_None) val = 1;
+ if (PyTypeNum_ISUSERDEF(self->type_num)) val = 2;
+ return PyInt_FromLong(val);
}
static int
_arraydescr_isnative(PyArray_Descr *self)
{
- if (self->names == NULL) {
- return PyArray_ISNBO(self->byteorder);
- }
- else {
- PyObject *key, *value, *title=NULL;
- PyArray_Descr *new;
- int offset;
- Py_ssize_t pos=0;
- while(PyDict_Next(self->fields, &pos, &key, &value)) {
- if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
- &title)) return -1;
- if (!_arraydescr_isnative(new)) return 0;
- }
+ if (self->names == NULL) {
+ return PyArray_ISNBO(self->byteorder);
+ }
+ else {
+ PyObject *key, *value, *title=NULL;
+ PyArray_Descr *new;
+ int offset;
+ Py_ssize_t pos=0;
+ while(PyDict_Next(self->fields, &pos, &key, &value)) {
+ if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
+ &title)) return -1;
+ if (!_arraydescr_isnative(new)) return 0;
}
- return 1;
+ }
+ return 1;
}
/* return Py_True if this data-type descriptor
@@ -10916,99 +10915,99 @@ _arraydescr_isnative(PyArray_Descr *self)
static PyObject *
arraydescr_isnative_get(PyArray_Descr *self)
{
- PyObject *ret;
- int retval;
- retval = _arraydescr_isnative(self);
- if (retval == -1) return NULL;
- ret = (retval ? Py_True : Py_False);
- Py_INCREF(ret);
- return ret;
+ PyObject *ret;
+ int retval;
+ retval = _arraydescr_isnative(self);
+ if (retval == -1) return NULL;
+ ret = (retval ? Py_True : Py_False);
+ Py_INCREF(ret);
+ return ret;
}
static PyObject *
arraydescr_fields_get(PyArray_Descr *self)
{
- if (self->names == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyDictProxy_New(self->fields);
+ if (self->names == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyDictProxy_New(self->fields);
}
static PyObject *
arraydescr_hasobject_get(PyArray_Descr *self)
{
- PyObject *res;
- if (PyDataType_FLAGCHK(self, NPY_ITEM_HASOBJECT))
- res = Py_True;
- else
- res = Py_False;
- Py_INCREF(res);
- return res;
+ PyObject *res;
+ if (PyDataType_FLAGCHK(self, NPY_ITEM_HASOBJECT))
+ res = Py_True;
+ else
+ res = Py_False;
+ Py_INCREF(res);
+ return res;
}
static PyGetSetDef arraydescr_getsets[] = {
- {"subdtype",
- (getter)arraydescr_subdescr_get,
- NULL, NULL},
- {"descr",
- (getter)arraydescr_protocol_descr_get,
- NULL, NULL},
- {"str",
- (getter)arraydescr_protocol_typestr_get,
- NULL, NULL},
- {"name",
- (getter)arraydescr_typename_get,
- NULL, NULL},
- {"base",
- (getter)arraydescr_base_get,
- NULL, NULL},
- {"shape",
- (getter)arraydescr_shape_get,
- NULL, NULL},
- {"isbuiltin",
- (getter)arraydescr_isbuiltin_get,
- NULL, NULL},
- {"isnative",
- (getter)arraydescr_isnative_get,
- NULL, NULL},
- {"fields",
- (getter)arraydescr_fields_get,
- NULL, NULL},
- {"hasobject",
- (getter)arraydescr_hasobject_get,
- NULL, NULL},
- {NULL, NULL, NULL, NULL},
+ {"subdtype",
+ (getter)arraydescr_subdescr_get,
+ NULL, NULL},
+ {"descr",
+ (getter)arraydescr_protocol_descr_get,
+ NULL, NULL},
+ {"str",
+ (getter)arraydescr_protocol_typestr_get,
+ NULL, NULL},
+ {"name",
+ (getter)arraydescr_typename_get,
+ NULL, NULL},
+ {"base",
+ (getter)arraydescr_base_get,
+ NULL, NULL},
+ {"shape",
+ (getter)arraydescr_shape_get,
+ NULL, NULL},
+ {"isbuiltin",
+ (getter)arraydescr_isbuiltin_get,
+ NULL, NULL},
+ {"isnative",
+ (getter)arraydescr_isnative_get,
+ NULL, NULL},
+ {"fields",
+ (getter)arraydescr_fields_get,
+ NULL, NULL},
+ {"hasobject",
+ (getter)arraydescr_hasobject_get,
+ NULL, NULL},
+ {NULL, NULL, NULL, NULL},
};
static PyObject *
arraydescr_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
{
- PyObject *odescr;
- PyArray_Descr *descr, *conv;
- Bool align=FALSE;
- Bool copy=FALSE;
- static char *kwlist[] = {"dtype", "align", "copy", NULL};
+ PyObject *odescr;
+ PyArray_Descr *descr, *conv;
+ Bool align=FALSE;
+ Bool copy=FALSE;
+ static char *kwlist[] = {"dtype", "align", "copy", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&",
- kwlist, &odescr,
- PyArray_BoolConverter, &align,
- PyArray_BoolConverter, &copy))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&",
+ kwlist, &odescr,
+ PyArray_BoolConverter, &align,
+ PyArray_BoolConverter, &copy))
+ return NULL;
- if (align) {
- if (!PyArray_DescrAlignConverter(odescr, &conv))
- return NULL;
- }
- else if (!PyArray_DescrConverter(odescr, &conv))
- return NULL;
- /* Get a new copy of it unless it's already a copy */
- if (copy && conv->fields == Py_None) {
- descr = PyArray_DescrNew(conv);
- Py_DECREF(conv);
- conv = descr;
- }
- return (PyObject *)conv;
+ if (align) {
+ if (!PyArray_DescrAlignConverter(odescr, &conv))
+ return NULL;
+ }
+ else if (!PyArray_DescrConverter(odescr, &conv))
+ return NULL;
+ /* Get a new copy of it unless it's already a copy */
+ if (copy && conv->fields == Py_None) {
+ descr = PyArray_DescrNew(conv);
+ Py_DECREF(conv);
+ conv = descr;
+ }
+ return (PyObject *)conv;
}
@@ -11016,104 +11015,104 @@ arraydescr_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
static PyObject *
arraydescr_reduce(PyArray_Descr *self, PyObject *args)
{
- /* version number of this pickle type. Increment if we need to
- change the format. Be sure to handle the old versions in
- arraydescr_setstate. */
- const int version = 3;
- PyObject *ret, *mod, *obj;
- PyObject *state;
- char endian;
- int elsize, alignment;
-
- ret = PyTuple_New(3);
- if (ret == NULL) return NULL;
- mod = PyImport_ImportModule("numpy.core.multiarray");
- if (mod == NULL) {Py_DECREF(ret); return NULL;}
- obj = PyObject_GetAttrString(mod, "dtype");
- Py_DECREF(mod);
- if (obj == NULL) {Py_DECREF(ret); return NULL;}
- PyTuple_SET_ITEM(ret, 0, obj);
- if (PyTypeNum_ISUSERDEF(self->type_num) || \
- ((self->type_num == PyArray_VOID && \
- self->typeobj != &PyVoidArrType_Type))) {
- obj = (PyObject *)self->typeobj;
- Py_INCREF(obj);
- }
- else {
- elsize = self->elsize;
- if (self->type_num == PyArray_UNICODE) {
- elsize >>= 2;
- }
- obj = PyString_FromFormat("%c%d",self->kind, elsize);
- }
- PyTuple_SET_ITEM(ret, 1, Py_BuildValue("(Nii)", obj, 0, 1));
-
- /* Now return the state which is at least
- byteorder, subarray, and fields */
- endian = self->byteorder;
- if (endian == '=') {
- endian = '<';
- if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
- }
- state = PyTuple_New(8);
- PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version));
- PyTuple_SET_ITEM(state, 1, PyString_FromFormat("%c", endian));
- PyTuple_SET_ITEM(state, 2, arraydescr_subdescr_get(self));
- if (self->names) {
- Py_INCREF(self->names);
- Py_INCREF(self->fields);
- PyTuple_SET_ITEM(state, 3, self->names);
- PyTuple_SET_ITEM(state, 4, self->fields);
- }
- else {
- PyTuple_SET_ITEM(state, 3, Py_None);
- PyTuple_SET_ITEM(state, 4, Py_None);
- Py_INCREF(Py_None);
- Py_INCREF(Py_None);
+ /* version number of this pickle type. Increment if we need to
+ change the format. Be sure to handle the old versions in
+ arraydescr_setstate. */
+ const int version = 3;
+ PyObject *ret, *mod, *obj;
+ PyObject *state;
+ char endian;
+ int elsize, alignment;
+
+ ret = PyTuple_New(3);
+ if (ret == NULL) return NULL;
+ mod = PyImport_ImportModule("numpy.core.multiarray");
+ if (mod == NULL) {Py_DECREF(ret); return NULL;}
+ obj = PyObject_GetAttrString(mod, "dtype");
+ Py_DECREF(mod);
+ if (obj == NULL) {Py_DECREF(ret); return NULL;}
+ PyTuple_SET_ITEM(ret, 0, obj);
+ if (PyTypeNum_ISUSERDEF(self->type_num) || \
+ ((self->type_num == PyArray_VOID && \
+ self->typeobj != &PyVoidArrType_Type))) {
+ obj = (PyObject *)self->typeobj;
+ Py_INCREF(obj);
+ }
+ else {
+ elsize = self->elsize;
+ if (self->type_num == PyArray_UNICODE) {
+ elsize >>= 2;
}
+ obj = PyString_FromFormat("%c%d",self->kind, elsize);
+ }
+ PyTuple_SET_ITEM(ret, 1, Py_BuildValue("(Nii)", obj, 0, 1));
+
+ /* Now return the state which is at least
+ byteorder, subarray, and fields */
+ endian = self->byteorder;
+ if (endian == '=') {
+ endian = '<';
+ if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
+ }
+ state = PyTuple_New(8);
+ PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version));
+ PyTuple_SET_ITEM(state, 1, PyString_FromFormat("%c", endian));
+ PyTuple_SET_ITEM(state, 2, arraydescr_subdescr_get(self));
+ if (self->names) {
+ Py_INCREF(self->names);
+ Py_INCREF(self->fields);
+ PyTuple_SET_ITEM(state, 3, self->names);
+ PyTuple_SET_ITEM(state, 4, self->fields);
+ }
+ else {
+ PyTuple_SET_ITEM(state, 3, Py_None);
+ PyTuple_SET_ITEM(state, 4, Py_None);
+ Py_INCREF(Py_None);
+ Py_INCREF(Py_None);
+ }
- /* for extended types it also includes elsize and alignment */
- if (PyTypeNum_ISEXTENDED(self->type_num)) {
- elsize = self->elsize;
- alignment = self->alignment;
- }
- else {elsize = -1; alignment = -1;}
+ /* for extended types it also includes elsize and alignment */
+ if (PyTypeNum_ISEXTENDED(self->type_num)) {
+ elsize = self->elsize;
+ alignment = self->alignment;
+ }
+ else {elsize = -1; alignment = -1;}
- PyTuple_SET_ITEM(state, 5, PyInt_FromLong(elsize));
- PyTuple_SET_ITEM(state, 6, PyInt_FromLong(alignment));
- PyTuple_SET_ITEM(state, 7, PyInt_FromLong(self->hasobject));
+ PyTuple_SET_ITEM(state, 5, PyInt_FromLong(elsize));
+ PyTuple_SET_ITEM(state, 6, PyInt_FromLong(alignment));
+ PyTuple_SET_ITEM(state, 7, PyInt_FromLong(self->hasobject));
- PyTuple_SET_ITEM(ret, 2, state);
- return ret;
+ PyTuple_SET_ITEM(ret, 2, state);
+ return ret;
}
/* returns 1 if this data-type has an object portion
used when setting the state because hasobject is not stored.
- */
+*/
static int
_descr_find_object(PyArray_Descr *self)
{
- if (self->hasobject || self->type_num == PyArray_OBJECT ||
- self->kind == 'O')
+ if (self->hasobject || self->type_num == PyArray_OBJECT ||
+ self->kind == 'O')
+ return NPY_OBJECT_DTYPE_FLAGS;
+ if (PyDescr_HASFIELDS(self)) {
+ PyObject *key, *value, *title=NULL;
+ PyArray_Descr *new;
+ int offset;
+ Py_ssize_t pos=0;
+ while (PyDict_Next(self->fields, &pos, &key, &value)) {
+ if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
+ &title)) {
+ PyErr_Clear();
+ return 0;
+ }
+ if (_descr_find_object(new)) {
+ new->hasobject = NPY_OBJECT_DTYPE_FLAGS;
return NPY_OBJECT_DTYPE_FLAGS;
- if (PyDescr_HASFIELDS(self)) {
- PyObject *key, *value, *title=NULL;
- PyArray_Descr *new;
- int offset;
- Py_ssize_t pos=0;
- while (PyDict_Next(self->fields, &pos, &key, &value)) {
- if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
- &title)) {
- PyErr_Clear();
- return 0;
- }
- if (_descr_find_object(new)) {
- new->hasobject = NPY_OBJECT_DTYPE_FLAGS;
- return NPY_OBJECT_DTYPE_FLAGS;
- }
- }
+ }
}
- return 0;
+ }
+ return 0;
}
/* state is at least byteorder, subarray, and fields but could include elsize
@@ -11123,373 +11122,373 @@ _descr_find_object(PyArray_Descr *self)
static PyObject *
arraydescr_setstate(PyArray_Descr *self, PyObject *args)
{
- int elsize = -1, alignment = -1;
- int version = 3;
- char endian;
- PyObject *subarray, *fields, *names=NULL;
- int incref_names = 1;
- int dtypeflags=0;
+ int elsize = -1, alignment = -1;
+ int version = 3;
+ char endian;
+ PyObject *subarray, *fields, *names=NULL;
+ int incref_names = 1;
+ int dtypeflags=0;
- if (self->fields == Py_None) {Py_INCREF(Py_None); return Py_None;}
+ if (self->fields == Py_None) {Py_INCREF(Py_None); return Py_None;}
- if (PyTuple_GET_SIZE(args) != 1 ||
- !(PyTuple_Check(PyTuple_GET_ITEM(args, 0)))) {
- PyErr_BadInternalCall();
- return NULL;
+ if (PyTuple_GET_SIZE(args) != 1 ||
+ !(PyTuple_Check(PyTuple_GET_ITEM(args, 0)))) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ switch (PyTuple_GET_SIZE(PyTuple_GET_ITEM(args,0))) {
+ case 8:
+ if (!PyArg_ParseTuple(args, "(icOOOiii)", &version, &endian,
+ &subarray, &names, &fields, &elsize,
+ &alignment, &dtypeflags)) {
+ return NULL;
}
- switch (PyTuple_GET_SIZE(PyTuple_GET_ITEM(args,0))) {
- case 8:
- if (!PyArg_ParseTuple(args, "(icOOOiii)", &version, &endian,
- &subarray, &names, &fields, &elsize,
- &alignment, &dtypeflags)) {
- return NULL;
- }
- break;
- case 7:
- if (!PyArg_ParseTuple(args, "(icOOOii)", &version, &endian,
- &subarray, &names, &fields, &elsize,
- &alignment)) {
- return NULL;
- }
- break;
- case 6:
- if (!PyArg_ParseTuple(args, "(icOOii)", &version,
- &endian, &subarray, &fields,
- &elsize, &alignment)) {
- PyErr_Clear();
- }
- break;
- case 5:
- version = 0;
- if (!PyArg_ParseTuple(args, "(cOOii)",
- &endian, &subarray, &fields, &elsize,
- &alignment)) {
- return NULL;
- }
- break;
- default:
- version = -1; /* raise an error */
+ break;
+ case 7:
+ if (!PyArg_ParseTuple(args, "(icOOOii)", &version, &endian,
+ &subarray, &names, &fields, &elsize,
+ &alignment)) {
+ return NULL;
}
-
- /* If we ever need another pickle format, increment the version
- number. But we should still be able to handle the old versions.
- */
- if (version < 0 || version > 3) {
- PyErr_Format(PyExc_ValueError,
- "can't handle version %d of numpy.dtype pickle",
- version);
+ break;
+ case 6:
+ if (!PyArg_ParseTuple(args, "(icOOii)", &version,
+ &endian, &subarray, &fields,
+ &elsize, &alignment)) {
+ PyErr_Clear();
+ }
+ break;
+ case 5:
+ version = 0;
+ if (!PyArg_ParseTuple(args, "(cOOii)",
+ &endian, &subarray, &fields, &elsize,
+ &alignment)) {
return NULL;
}
+ break;
+ default:
+ version = -1; /* raise an error */
+ }
- if (version == 1 || version == 0) {
- if (fields != Py_None) {
- PyObject *key, *list;
- key = PyInt_FromLong(-1);
- list = PyDict_GetItem(fields, key);
- if (!list) return NULL;
- Py_INCREF(list);
- names = list;
- PyDict_DelItem(fields, key);
- incref_names = 0;
- }
- else {
- names = Py_None;
- }
+ /* If we ever need another pickle format, increment the version
+ number. But we should still be able to handle the old versions.
+ */
+ if (version < 0 || version > 3) {
+ PyErr_Format(PyExc_ValueError,
+ "can't handle version %d of numpy.dtype pickle",
+ version);
+ return NULL;
+ }
+
+ if (version == 1 || version == 0) {
+ if (fields != Py_None) {
+ PyObject *key, *list;
+ key = PyInt_FromLong(-1);
+ list = PyDict_GetItem(fields, key);
+ if (!list) return NULL;
+ Py_INCREF(list);
+ names = list;
+ PyDict_DelItem(fields, key);
+ incref_names = 0;
+ }
+ else {
+ names = Py_None;
}
+ }
- if ((fields == Py_None && names != Py_None) || \
- (names == Py_None && fields != Py_None)) {
- PyErr_Format(PyExc_ValueError,
- "inconsistent fields and names");
- return NULL;
- }
+ if ((fields == Py_None && names != Py_None) || \
+ (names == Py_None && fields != Py_None)) {
+ PyErr_Format(PyExc_ValueError,
+ "inconsistent fields and names");
+ return NULL;
+ }
- if (endian != '|' &&
- PyArray_IsNativeByteOrder(endian)) endian = '=';
+ if (endian != '|' &&
+ PyArray_IsNativeByteOrder(endian)) endian = '=';
- self->byteorder = endian;
- if (self->subarray) {
- Py_XDECREF(self->subarray->base);
- Py_XDECREF(self->subarray->shape);
- _pya_free(self->subarray);
- }
- self->subarray = NULL;
+ self->byteorder = endian;
+ if (self->subarray) {
+ Py_XDECREF(self->subarray->base);
+ Py_XDECREF(self->subarray->shape);
+ _pya_free(self->subarray);
+ }
+ self->subarray = NULL;
- if (subarray != Py_None) {
- self->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
- self->subarray->base = (PyArray_Descr *)PyTuple_GET_ITEM(subarray, 0);
- Py_INCREF(self->subarray->base);
- self->subarray->shape = PyTuple_GET_ITEM(subarray, 1);
- Py_INCREF(self->subarray->shape);
- }
+ if (subarray != Py_None) {
+ self->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
+ self->subarray->base = (PyArray_Descr *)PyTuple_GET_ITEM(subarray, 0);
+ Py_INCREF(self->subarray->base);
+ self->subarray->shape = PyTuple_GET_ITEM(subarray, 1);
+ Py_INCREF(self->subarray->shape);
+ }
- if (fields != Py_None) {
- Py_XDECREF(self->fields);
- self->fields = fields;
- Py_INCREF(fields);
- Py_XDECREF(self->names);
- self->names = names;
- if (incref_names)
- Py_INCREF(names);
- }
+ if (fields != Py_None) {
+ Py_XDECREF(self->fields);
+ self->fields = fields;
+ Py_INCREF(fields);
+ Py_XDECREF(self->names);
+ self->names = names;
+ if (incref_names)
+ Py_INCREF(names);
+ }
- if (PyTypeNum_ISEXTENDED(self->type_num)) {
- self->elsize = elsize;
- self->alignment = alignment;
- }
+ if (PyTypeNum_ISEXTENDED(self->type_num)) {
+ self->elsize = elsize;
+ self->alignment = alignment;
+ }
- self->hasobject = dtypeflags;
- if (version < 3) {
- self->hasobject = _descr_find_object(self);
- }
- Py_INCREF(Py_None);
- return Py_None;
+ self->hasobject = dtypeflags;
+ if (version < 3) {
+ self->hasobject = _descr_find_object(self);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* returns a copy of the PyArray_Descr structure with the byteorder
altered:
- no arguments: The byteorder is swapped (in all subfields as well)
- single argument: The byteorder is forced to the given state
- (in all subfields as well)
+ no arguments: The byteorder is swapped (in all subfields as well)
+ single argument: The byteorder is forced to the given state
+ (in all subfields as well)
- Valid states: ('big', '>') or ('little' or '<')
- ('native', or '=')
+ Valid states: ('big', '>') or ('little' or '<')
+ ('native', or '=')
- If a descr structure with | is encountered it's own
- byte-order is not changed but any fields are:
+ If a descr structure with | is encountered it's own
+ byte-order is not changed but any fields are:
*/
/*OBJECT_API
Deep bytorder change of a data-type descriptor
*** Leaves reference count of self unchanged --- does not DECREF self ***
-*/
+ */
static PyArray_Descr *
PyArray_DescrNewByteorder(PyArray_Descr *self, char newendian)
{
- PyArray_Descr *new;
- char endian;
-
- new = PyArray_DescrNew(self);
- endian = new->byteorder;
- if (endian != PyArray_IGNORE) {
- if (newendian == PyArray_SWAP) { /* swap byteorder */
- if PyArray_ISNBO(endian) endian = PyArray_OPPBYTE;
- else endian = PyArray_NATBYTE;
- new->byteorder = endian;
- }
- else if (newendian != PyArray_IGNORE) {
- new->byteorder = newendian;
- }
+ PyArray_Descr *new;
+ char endian;
+
+ new = PyArray_DescrNew(self);
+ endian = new->byteorder;
+ if (endian != PyArray_IGNORE) {
+ if (newendian == PyArray_SWAP) { /* swap byteorder */
+ if PyArray_ISNBO(endian) endian = PyArray_OPPBYTE;
+ else endian = PyArray_NATBYTE;
+ new->byteorder = endian;
}
- if (new->names) {
- PyObject *newfields;
- PyObject *key, *value;
- PyObject *newvalue;
- PyObject *old;
- PyArray_Descr *newdescr;
- Py_ssize_t pos = 0;
- int len, i;
- newfields = PyDict_New();
- /* make new dictionary with replaced */
- /* PyArray_Descr Objects */
- while(PyDict_Next(self->fields, &pos, &key, &value)) {
- if (!PyString_Check(key) || \
- !PyTuple_Check(value) || \
- ((len=PyTuple_GET_SIZE(value)) < 2))
- continue;
-
- old = PyTuple_GET_ITEM(value, 0);
- if (!PyArray_DescrCheck(old)) continue;
- newdescr = PyArray_DescrNewByteorder \
- ((PyArray_Descr *)old, newendian);
- if (newdescr == NULL) {
- Py_DECREF(newfields); Py_DECREF(new);
- return NULL;
- }
- newvalue = PyTuple_New(len);
- PyTuple_SET_ITEM(newvalue, 0, \
- (PyObject *)newdescr);
- for(i=1; i<len; i++) {
- old = PyTuple_GET_ITEM(value, i);
- Py_INCREF(old);
- PyTuple_SET_ITEM(newvalue, i, old);
- }
- PyDict_SetItem(newfields, key, newvalue);
- Py_DECREF(newvalue);
- }
- Py_DECREF(new->fields);
- new->fields = newfields;
+ else if (newendian != PyArray_IGNORE) {
+ new->byteorder = newendian;
}
- if (new->subarray) {
- Py_DECREF(new->subarray->base);
- new->subarray->base = PyArray_DescrNewByteorder \
- (self->subarray->base, newendian);
+ }
+ if (new->names) {
+ PyObject *newfields;
+ PyObject *key, *value;
+ PyObject *newvalue;
+ PyObject *old;
+ PyArray_Descr *newdescr;
+ Py_ssize_t pos = 0;
+ int len, i;
+ newfields = PyDict_New();
+ /* make new dictionary with replaced */
+ /* PyArray_Descr Objects */
+ while(PyDict_Next(self->fields, &pos, &key, &value)) {
+ if (!PyString_Check(key) || \
+ !PyTuple_Check(value) || \
+ ((len=PyTuple_GET_SIZE(value)) < 2))
+ continue;
+
+ old = PyTuple_GET_ITEM(value, 0);
+ if (!PyArray_DescrCheck(old)) continue;
+ newdescr = PyArray_DescrNewByteorder \
+ ((PyArray_Descr *)old, newendian);
+ if (newdescr == NULL) {
+ Py_DECREF(newfields); Py_DECREF(new);
+ return NULL;
+ }
+ newvalue = PyTuple_New(len);
+ PyTuple_SET_ITEM(newvalue, 0, \
+ (PyObject *)newdescr);
+ for(i=1; i<len; i++) {
+ old = PyTuple_GET_ITEM(value, i);
+ Py_INCREF(old);
+ PyTuple_SET_ITEM(newvalue, i, old);
+ }
+ PyDict_SetItem(newfields, key, newvalue);
+ Py_DECREF(newvalue);
}
- return new;
+ Py_DECREF(new->fields);
+ new->fields = newfields;
+ }
+ if (new->subarray) {
+ Py_DECREF(new->subarray->base);
+ new->subarray->base = PyArray_DescrNewByteorder \
+ (self->subarray->base, newendian);
+ }
+ return new;
}
static PyObject *
arraydescr_newbyteorder(PyArray_Descr *self, PyObject *args)
{
- char endian=PyArray_SWAP;
+ char endian=PyArray_SWAP;
- if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter,
- &endian)) return NULL;
+ if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter,
+ &endian)) return NULL;
- return (PyObject *)PyArray_DescrNewByteorder(self, endian);
+ return (PyObject *)PyArray_DescrNewByteorder(self, endian);
}
static PyMethodDef arraydescr_methods[] = {
- /* for pickling */
- {"__reduce__", (PyCFunction)arraydescr_reduce, METH_VARARGS,
- NULL},
- {"__setstate__", (PyCFunction)arraydescr_setstate, METH_VARARGS,
- NULL},
- {"newbyteorder", (PyCFunction)arraydescr_newbyteorder, METH_VARARGS,
- NULL},
- {NULL, NULL} /* sentinel */
+ /* for pickling */
+ {"__reduce__", (PyCFunction)arraydescr_reduce, METH_VARARGS,
+ NULL},
+ {"__setstate__", (PyCFunction)arraydescr_setstate, METH_VARARGS,
+ NULL},
+ {"newbyteorder", (PyCFunction)arraydescr_newbyteorder, METH_VARARGS,
+ NULL},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
arraydescr_str(PyArray_Descr *self)
{
- PyObject *sub;
-
- if (self->names) {
- PyObject *lst;
- lst = arraydescr_protocol_descr_get(self);
- if (!lst) {
- sub = PyString_FromString("<err>");
- PyErr_Clear();
- }
- else sub = PyObject_Str(lst);
- Py_XDECREF(lst);
- if (self->type_num != PyArray_VOID) {
- PyObject *p;
- PyObject *t=PyString_FromString("'");
- p = arraydescr_protocol_typestr_get(self);
- PyString_Concat(&p, t);
- PyString_ConcatAndDel(&t, p);
- p = PyString_FromString("(");
- PyString_ConcatAndDel(&p, t);
- PyString_ConcatAndDel(&p, PyString_FromString(", "));
- PyString_ConcatAndDel(&p, sub);
- PyString_ConcatAndDel(&p, PyString_FromString(")"));
- sub = p;
- }
- }
- else if (self->subarray) {
- PyObject *p;
- PyObject *t = PyString_FromString("(");
- PyObject *sh;
- p = arraydescr_str(self->subarray->base);
- if (!self->subarray->base->names && !self->subarray->base->subarray) {
- PyObject *t=PyString_FromString("'");
- PyString_Concat(&p, t);
- PyString_ConcatAndDel(&t, p);
- p = t;
- }
- PyString_ConcatAndDel(&t, p);
- PyString_ConcatAndDel(&t, PyString_FromString(","));
- if (!PyTuple_Check(self->subarray->shape)) {
- sh = Py_BuildValue("(O)", self->subarray->shape);
- }
- else {
- sh = self->subarray->shape;
- Py_INCREF(sh);
- }
- PyString_ConcatAndDel(&t, PyObject_Str(sh));
- Py_DECREF(sh);
- PyString_ConcatAndDel(&t, PyString_FromString(")"));
- sub = t;
+ PyObject *sub;
+
+ if (self->names) {
+ PyObject *lst;
+ lst = arraydescr_protocol_descr_get(self);
+ if (!lst) {
+ sub = PyString_FromString("<err>");
+ PyErr_Clear();
+ }
+ else sub = PyObject_Str(lst);
+ Py_XDECREF(lst);
+ if (self->type_num != PyArray_VOID) {
+ PyObject *p;
+ PyObject *t=PyString_FromString("'");
+ p = arraydescr_protocol_typestr_get(self);
+ PyString_Concat(&p, t);
+ PyString_ConcatAndDel(&t, p);
+ p = PyString_FromString("(");
+ PyString_ConcatAndDel(&p, t);
+ PyString_ConcatAndDel(&p, PyString_FromString(", "));
+ PyString_ConcatAndDel(&p, sub);
+ PyString_ConcatAndDel(&p, PyString_FromString(")"));
+ sub = p;
}
- else if (PyDataType_ISFLEXIBLE(self) || !PyArray_ISNBO(self->byteorder)) {
- sub = arraydescr_protocol_typestr_get(self);
+ }
+ else if (self->subarray) {
+ PyObject *p;
+ PyObject *t = PyString_FromString("(");
+ PyObject *sh;
+ p = arraydescr_str(self->subarray->base);
+ if (!self->subarray->base->names && !self->subarray->base->subarray) {
+ PyObject *t=PyString_FromString("'");
+ PyString_Concat(&p, t);
+ PyString_ConcatAndDel(&t, p);
+ p = t;
+ }
+ PyString_ConcatAndDel(&t, p);
+ PyString_ConcatAndDel(&t, PyString_FromString(","));
+ if (!PyTuple_Check(self->subarray->shape)) {
+ sh = Py_BuildValue("(O)", self->subarray->shape);
}
else {
- sub = arraydescr_typename_get(self);
+ sh = self->subarray->shape;
+ Py_INCREF(sh);
}
- return sub;
+ PyString_ConcatAndDel(&t, PyObject_Str(sh));
+ Py_DECREF(sh);
+ PyString_ConcatAndDel(&t, PyString_FromString(")"));
+ sub = t;
+ }
+ else if (PyDataType_ISFLEXIBLE(self) || !PyArray_ISNBO(self->byteorder)) {
+ sub = arraydescr_protocol_typestr_get(self);
+ }
+ else {
+ sub = arraydescr_typename_get(self);
+ }
+ return sub;
}
static PyObject *
arraydescr_repr(PyArray_Descr *self)
{
- PyObject *sub, *s;
- s = PyString_FromString("dtype(");
- sub = arraydescr_str(self);
- if (!self->names && !self->subarray) {
- PyObject *t=PyString_FromString("'");
- PyString_Concat(&sub, t);
- PyString_ConcatAndDel(&t, sub);
- sub = t;
- }
- PyString_ConcatAndDel(&s, sub);
- sub = PyString_FromString(")");
- PyString_ConcatAndDel(&s, sub);
- return s;
+ PyObject *sub, *s;
+ s = PyString_FromString("dtype(");
+ sub = arraydescr_str(self);
+ if (!self->names && !self->subarray) {
+ PyObject *t=PyString_FromString("'");
+ PyString_Concat(&sub, t);
+ PyString_ConcatAndDel(&t, sub);
+ sub = t;
+ }
+ PyString_ConcatAndDel(&s, sub);
+ sub = PyString_FromString(")");
+ PyString_ConcatAndDel(&s, sub);
+ return s;
}
static PyObject *
arraydescr_richcompare(PyArray_Descr *self, PyObject *other, int cmp_op)
{
- PyArray_Descr *new=NULL;
- PyObject *result = Py_NotImplemented;
- if (!PyArray_DescrCheck(other)) {
- if (PyArray_DescrConverter(other, &new) == PY_FAIL)
- return NULL;
- }
- else {
- new = (PyArray_Descr *)other;
- Py_INCREF(new);
- }
- switch (cmp_op) {
- case Py_LT:
- if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new))
- result = Py_True;
- else
- result = Py_False;
- break;
- case Py_LE:
- if (PyArray_CanCastTo(self, new))
- result = Py_True;
- else
- result = Py_False;
- break;
- case Py_EQ:
- if (PyArray_EquivTypes(self, new))
- result = Py_True;
- else
- result = Py_False;
- break;
- case Py_NE:
- if (PyArray_EquivTypes(self, new))
- result = Py_False;
- else
- result = Py_True;
- break;
- case Py_GT:
- if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(new, self))
- result = Py_True;
- else
- result = Py_False;
- break;
- case Py_GE:
- if (PyArray_CanCastTo(new, self))
- result = Py_True;
- else
- result = Py_False;
- break;
- default:
- result = Py_NotImplemented;
- }
+ PyArray_Descr *new=NULL;
+ PyObject *result = Py_NotImplemented;
+ if (!PyArray_DescrCheck(other)) {
+ if (PyArray_DescrConverter(other, &new) == PY_FAIL)
+ return NULL;
+ }
+ else {
+ new = (PyArray_Descr *)other;
+ Py_INCREF(new);
+ }
+ switch (cmp_op) {
+ case Py_LT:
+ if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new))
+ result = Py_True;
+ else
+ result = Py_False;
+ break;
+ case Py_LE:
+ if (PyArray_CanCastTo(self, new))
+ result = Py_True;
+ else
+ result = Py_False;
+ break;
+ case Py_EQ:
+ if (PyArray_EquivTypes(self, new))
+ result = Py_True;
+ else
+ result = Py_False;
+ break;
+ case Py_NE:
+ if (PyArray_EquivTypes(self, new))
+ result = Py_False;
+ else
+ result = Py_True;
+ break;
+ case Py_GT:
+ if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(new, self))
+ result = Py_True;
+ else
+ result = Py_False;
+ break;
+ case Py_GE:
+ if (PyArray_CanCastTo(new, self))
+ result = Py_True;
+ else
+ result = Py_False;
+ break;
+ default:
+ result = Py_NotImplemented;
+ }
- Py_XDECREF(new);
- Py_INCREF(result);
- return result;
+ Py_XDECREF(new);
+ Py_INCREF(result);
+ return result;
}
/*************************************************************************
@@ -11500,194 +11499,194 @@ static Py_ssize_t
descr_length(PyObject *self0)
{
- PyArray_Descr *self = (PyArray_Descr *)self0;
+ PyArray_Descr *self = (PyArray_Descr *)self0;
- if (self->names)
- return PyTuple_GET_SIZE(self->names);
- else return 0;
+ if (self->names)
+ return PyTuple_GET_SIZE(self->names);
+ else return 0;
}
static PyObject *
descr_repeat(PyObject *self, Py_ssize_t length)
{
- PyObject *tup;
- PyArray_Descr *new;
- if (length < 0)
- return PyErr_Format(PyExc_ValueError,
+ PyObject *tup;
+ PyArray_Descr *new;
+ if (length < 0)
+ return PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "Array length must be >= 0, not %d",
+ "Array length must be >= 0, not %d",
#else
- "Array length must be >= 0, not %zd",
+ "Array length must be >= 0, not %zd",
#endif
- length);
- tup = Py_BuildValue("O" NPY_SSIZE_T_PYFMT, self, length);
- if (tup == NULL) return NULL;
- PyArray_DescrConverter(tup, &new);
- Py_DECREF(tup);
- return (PyObject *)new;
+ length);
+ tup = Py_BuildValue("O" NPY_SSIZE_T_PYFMT, self, length);
+ if (tup == NULL) return NULL;
+ PyArray_DescrConverter(tup, &new);
+ Py_DECREF(tup);
+ return (PyObject *)new;
}
static PyObject *
descr_subscript(PyArray_Descr *self, PyObject *op)
{
- if (self->names) {
- if (PyString_Check(op) || PyUnicode_Check(op)) {
- PyObject *obj;
- obj = PyDict_GetItem(self->fields, op);
- if (obj != NULL) {
- PyObject *descr;
- descr = PyTuple_GET_ITEM(obj, 0);
- Py_INCREF(descr);
- return descr;
- }
- else {
- PyErr_Format(PyExc_KeyError,
- "field named \'%s\' not found.",
- PyString_AsString(op));
- }
- }
- else {
- PyObject *name;
- int value;
- value = PyArray_PyIntAsInt(op);
- if (!PyErr_Occurred()) {
- int size;
- size = PyTuple_GET_SIZE(self->names);
- if (value < 0) value += size;
- if (value < 0 || value >= size) {
- PyErr_Format(PyExc_IndexError,
- "0<=index<%d not %d",
- size, value);
- return NULL;
- }
- name = PyTuple_GET_ITEM(self->names, value);
- return descr_subscript(self, name);
- }
- }
- PyErr_SetString(PyExc_ValueError,
- "only integers, strings or unicode values "
- "allowed for getting fields.");
+ if (self->names) {
+ if (PyString_Check(op) || PyUnicode_Check(op)) {
+ PyObject *obj;
+ obj = PyDict_GetItem(self->fields, op);
+ if (obj != NULL) {
+ PyObject *descr;
+ descr = PyTuple_GET_ITEM(obj, 0);
+ Py_INCREF(descr);
+ return descr;
+ }
+ else {
+ PyErr_Format(PyExc_KeyError,
+ "field named \'%s\' not found.",
+ PyString_AsString(op));
+ }
}
else {
- PyObject *astr;
- astr = arraydescr_str(self);
- PyErr_Format(PyExc_KeyError,
- "there are no fields in dtype %s.",
- PyString_AsString(astr));
- Py_DECREF(astr);
+ PyObject *name;
+ int value;
+ value = PyArray_PyIntAsInt(op);
+ if (!PyErr_Occurred()) {
+ int size;
+ size = PyTuple_GET_SIZE(self->names);
+ if (value < 0) value += size;
+ if (value < 0 || value >= size) {
+ PyErr_Format(PyExc_IndexError,
+ "0<=index<%d not %d",
+ size, value);
+ return NULL;
+ }
+ name = PyTuple_GET_ITEM(self->names, value);
+ return descr_subscript(self, name);
+ }
}
- return NULL;
+ PyErr_SetString(PyExc_ValueError,
+ "only integers, strings or unicode values "
+ "allowed for getting fields.");
+ }
+ else {
+ PyObject *astr;
+ astr = arraydescr_str(self);
+ PyErr_Format(PyExc_KeyError,
+ "there are no fields in dtype %s.",
+ PyString_AsString(astr));
+ Py_DECREF(astr);
+ }
+ return NULL;
}
static PySequenceMethods descr_as_sequence = {
- descr_length,
- (binaryfunc)NULL,
- descr_repeat,
+ descr_length,
+ (binaryfunc)NULL,
+ descr_repeat,
};
static PyMappingMethods descr_as_mapping = {
- descr_length, /*mp_length*/
- (binaryfunc)descr_subscript, /*mp_subscript*/
- (objobjargproc)NULL, /*mp_ass_subscript*/
+ descr_length, /*mp_length*/
+ (binaryfunc)descr_subscript, /*mp_subscript*/
+ (objobjargproc)NULL, /*mp_ass_subscript*/
};
/****************** End of Mapping Protocol ******************************/
static PyTypeObject PyArrayDescr_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "numpy.dtype", /* tp_name */
- sizeof(PyArray_Descr), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)arraydescr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)arraydescr_repr, /* tp_repr */
- 0, /* tp_as_number */
- &descr_as_sequence, /* tp_as_sequence */
- &descr_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)arraydescr_str, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)arraydescr_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- arraydescr_methods, /* tp_methods */
- arraydescr_members, /* tp_members */
- arraydescr_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- arraydescr_new, /* tp_new */
- 0, /* tp_free */
- 0, /* tp_is_gc */
- 0, /* tp_bases */
- 0, /* tp_mro */
- 0, /* tp_cache */
- 0, /* tp_subclasses */
- 0 /* tp_weaklist */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "numpy.dtype", /* tp_name */
+ sizeof(PyArray_Descr), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)arraydescr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)arraydescr_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &descr_as_sequence, /* tp_as_sequence */
+ &descr_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)arraydescr_str, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)arraydescr_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ arraydescr_methods, /* tp_methods */
+ arraydescr_members, /* tp_members */
+ arraydescr_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ arraydescr_new, /* tp_new */
+ 0, /* tp_free */
+ 0, /* tp_is_gc */
+ 0, /* tp_bases */
+ 0, /* tp_mro */
+ 0, /* tp_cache */
+ 0, /* tp_subclasses */
+ 0 /* tp_weaklist */
};
/** Array Flags Object **/
/*OBJECT_API
- Get New ArrayFlagsObject
+ Get New ArrayFlagsObject
*/
static PyObject *
PyArray_NewFlagsObject(PyObject *obj)
{
- PyObject *flagobj;
- int flags;
- if (obj == NULL) {
- flags = CONTIGUOUS | OWNDATA | FORTRAN | ALIGNED;
- }
- else {
- flags = PyArray_FLAGS(obj);
- }
- flagobj = PyArrayFlags_Type.tp_alloc(&PyArrayFlags_Type, 0);
- if (flagobj == NULL) return NULL;
- Py_XINCREF(obj);
- ((PyArrayFlagsObject *)flagobj)->arr = obj;
- ((PyArrayFlagsObject *)flagobj)->flags = flags;
+ PyObject *flagobj;
+ int flags;
+ if (obj == NULL) {
+ flags = CONTIGUOUS | OWNDATA | FORTRAN | ALIGNED;
+ }
+ else {
+ flags = PyArray_FLAGS(obj);
+ }
+ flagobj = PyArrayFlags_Type.tp_alloc(&PyArrayFlags_Type, 0);
+ if (flagobj == NULL) return NULL;
+ Py_XINCREF(obj);
+ ((PyArrayFlagsObject *)flagobj)->arr = obj;
+ ((PyArrayFlagsObject *)flagobj)->flags = flags;
- return flagobj;
+ return flagobj;
}
static void
arrayflags_dealloc(PyArrayFlagsObject *self)
{
- Py_XDECREF(self->arr);
- self->ob_type->tp_free((PyObject *)self);
+ Py_XDECREF(self->arr);
+ self->ob_type->tp_free((PyObject *)self);
}
-#define _define_get(UPPER, lower) \
-static PyObject * \
-arrayflags_ ## lower ## _get(PyArrayFlagsObject *self) \
-{ \
- PyObject *item; \
+#define _define_get(UPPER, lower) \
+ static PyObject * \
+ arrayflags_ ## lower ## _get(PyArrayFlagsObject *self) \
+ { \
+ PyObject *item; \
item = ((self->flags & (UPPER)) == (UPPER)) ? Py_True : Py_False; \
- Py_INCREF(item); \
- return item; \
-}
+ Py_INCREF(item); \
+ return item; \
+ }
_define_get(CONTIGUOUS, contiguous)
_define_get(FORTRAN, fortran)
@@ -11702,375 +11701,375 @@ _define_get(ALIGNED|WRITEABLE|CONTIGUOUS, carray)
static PyObject *
arrayflags_forc_get(PyArrayFlagsObject *self)
{
- PyObject *item;
+ PyObject *item;
- if (((self->flags & FORTRAN) == FORTRAN) ||
- ((self->flags & CONTIGUOUS) == CONTIGUOUS))
- item = Py_True;
- else
- item = Py_False;
+ if (((self->flags & FORTRAN) == FORTRAN) ||
+ ((self->flags & CONTIGUOUS) == CONTIGUOUS))
+ item = Py_True;
+ else
+ item = Py_False;
- Py_INCREF(item);
- return item;
+ Py_INCREF(item);
+ return item;
}
static PyObject *
arrayflags_fnc_get(PyArrayFlagsObject *self)
{
- PyObject *item;
+ PyObject *item;
- if (((self->flags & FORTRAN) == FORTRAN) &&
- !((self->flags & CONTIGUOUS) == CONTIGUOUS))
- item = Py_True;
- else
- item = Py_False;
+ if (((self->flags & FORTRAN) == FORTRAN) &&
+ !((self->flags & CONTIGUOUS) == CONTIGUOUS))
+ item = Py_True;
+ else
+ item = Py_False;
- Py_INCREF(item);
- return item;
+ Py_INCREF(item);
+ return item;
}
static PyObject *
arrayflags_farray_get(PyArrayFlagsObject *self)
{
- PyObject *item;
+ PyObject *item;
- if (((self->flags & (ALIGNED|WRITEABLE|FORTRAN)) == \
- (ALIGNED|WRITEABLE|FORTRAN)) &&
- !((self->flags & CONTIGUOUS) == CONTIGUOUS))
- item = Py_True;
- else
- item = Py_False;
+ if (((self->flags & (ALIGNED|WRITEABLE|FORTRAN)) == \
+ (ALIGNED|WRITEABLE|FORTRAN)) &&
+ !((self->flags & CONTIGUOUS) == CONTIGUOUS))
+ item = Py_True;
+ else
+ item = Py_False;
- Py_INCREF(item);
- return item;
+ Py_INCREF(item);
+ return item;
}
static PyObject *
arrayflags_num_get(PyArrayFlagsObject *self)
{
- return PyInt_FromLong(self->flags);
+ return PyInt_FromLong(self->flags);
}
/* relies on setflags order being write, align, uic */
static int
arrayflags_updateifcopy_set(PyArrayFlagsObject *self, PyObject *obj)
{
- PyObject *res;
- if (self->arr == NULL) {
- PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
- return -1;
- }
- res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, Py_None,
- (PyObject_IsTrue(obj) ? Py_True : Py_False));
- if (res == NULL) return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *res;
+ if (self->arr == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
+ return -1;
+ }
+ res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, Py_None,
+ (PyObject_IsTrue(obj) ? Py_True : Py_False));
+ if (res == NULL) return -1;
+ Py_DECREF(res);
+ return 0;
}
static int
arrayflags_aligned_set(PyArrayFlagsObject *self, PyObject *obj)
{
- PyObject *res;
- if (self->arr == NULL) {
- PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
- return -1;
- }
- res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None,
- (PyObject_IsTrue(obj) ? Py_True : Py_False),
- Py_None);
- if (res == NULL) return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *res;
+ if (self->arr == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
+ return -1;
+ }
+ res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None,
+ (PyObject_IsTrue(obj) ? Py_True : Py_False),
+ Py_None);
+ if (res == NULL) return -1;
+ Py_DECREF(res);
+ return 0;
}
static int
arrayflags_writeable_set(PyArrayFlagsObject *self, PyObject *obj)
{
- PyObject *res;
- if (self->arr == NULL) {
- PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
- return -1;
- }
- res = PyObject_CallMethod(self->arr, "setflags", "OOO",
- (PyObject_IsTrue(obj) ? Py_True : Py_False),
- Py_None, Py_None);
- if (res == NULL) return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *res;
+ if (self->arr == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
+ return -1;
+ }
+ res = PyObject_CallMethod(self->arr, "setflags", "OOO",
+ (PyObject_IsTrue(obj) ? Py_True : Py_False),
+ Py_None, Py_None);
+ if (res == NULL) return -1;
+ Py_DECREF(res);
+ return 0;
}
static PyGetSetDef arrayflags_getsets[] = {
- {"contiguous",
- (getter)arrayflags_contiguous_get,
- NULL,
- ""},
- {"c_contiguous",
- (getter)arrayflags_contiguous_get,
- NULL,
- ""},
- {"f_contiguous",
- (getter)arrayflags_fortran_get,
- NULL,
- ""},
- {"fortran",
- (getter)arrayflags_fortran_get,
- NULL,
- ""},
- {"updateifcopy",
- (getter)arrayflags_updateifcopy_get,
- (setter)arrayflags_updateifcopy_set,
- ""},
- {"owndata",
- (getter)arrayflags_owndata_get,
- NULL,
- ""},
- {"aligned",
- (getter)arrayflags_aligned_get,
- (setter)arrayflags_aligned_set,
- ""},
- {"writeable",
- (getter)arrayflags_writeable_get,
- (setter)arrayflags_writeable_set,
- ""},
- {"fnc",
- (getter)arrayflags_fnc_get,
- NULL,
- ""},
- {"forc",
- (getter)arrayflags_forc_get,
- NULL,
- ""},
- {"behaved",
- (getter)arrayflags_behaved_get,
- NULL,
- ""},
- {"carray",
- (getter)arrayflags_carray_get,
- NULL,
- ""},
- {"farray",
- (getter)arrayflags_farray_get,
- NULL,
- ""},
- {"num",
- (getter)arrayflags_num_get,
- NULL,
- ""},
- {NULL, NULL, NULL, NULL},
+ {"contiguous",
+ (getter)arrayflags_contiguous_get,
+ NULL,
+ ""},
+ {"c_contiguous",
+ (getter)arrayflags_contiguous_get,
+ NULL,
+ ""},
+ {"f_contiguous",
+ (getter)arrayflags_fortran_get,
+ NULL,
+ ""},
+ {"fortran",
+ (getter)arrayflags_fortran_get,
+ NULL,
+ ""},
+ {"updateifcopy",
+ (getter)arrayflags_updateifcopy_get,
+ (setter)arrayflags_updateifcopy_set,
+ ""},
+ {"owndata",
+ (getter)arrayflags_owndata_get,
+ NULL,
+ ""},
+ {"aligned",
+ (getter)arrayflags_aligned_get,
+ (setter)arrayflags_aligned_set,
+ ""},
+ {"writeable",
+ (getter)arrayflags_writeable_get,
+ (setter)arrayflags_writeable_set,
+ ""},
+ {"fnc",
+ (getter)arrayflags_fnc_get,
+ NULL,
+ ""},
+ {"forc",
+ (getter)arrayflags_forc_get,
+ NULL,
+ ""},
+ {"behaved",
+ (getter)arrayflags_behaved_get,
+ NULL,
+ ""},
+ {"carray",
+ (getter)arrayflags_carray_get,
+ NULL,
+ ""},
+ {"farray",
+ (getter)arrayflags_farray_get,
+ NULL,
+ ""},
+ {"num",
+ (getter)arrayflags_num_get,
+ NULL,
+ ""},
+ {NULL, NULL, NULL, NULL},
};
static PyObject *
arrayflags_getitem(PyArrayFlagsObject *self, PyObject *ind)
{
- char *key;
- int n;
- if (!PyString_Check(ind)) goto fail;
- key = PyString_AS_STRING(ind);
- n = PyString_GET_SIZE(ind);
- switch(n) {
- case 1:
- switch(key[0]) {
- case 'C':
- return arrayflags_contiguous_get(self);
- case 'F':
- return arrayflags_fortran_get(self);
- case 'W':
- return arrayflags_writeable_get(self);
- case 'B':
- return arrayflags_behaved_get(self);
- case 'O':
- return arrayflags_owndata_get(self);
- case 'A':
- return arrayflags_aligned_get(self);
- case 'U':
- return arrayflags_updateifcopy_get(self);
- default:
- goto fail;
- }
- break;
- case 2:
- if (strncmp(key, "CA", n)==0)
- return arrayflags_carray_get(self);
- if (strncmp(key, "FA", n)==0)
- return arrayflags_farray_get(self);
- break;
- case 3:
- if (strncmp(key, "FNC", n)==0)
- return arrayflags_fnc_get(self);
- break;
- case 4:
- if (strncmp(key, "FORC", n)==0)
- return arrayflags_forc_get(self);
- break;
- case 6:
- if (strncmp(key, "CARRAY", n)==0)
- return arrayflags_carray_get(self);
- if (strncmp(key, "FARRAY", n)==0)
- return arrayflags_farray_get(self);
- break;
- case 7:
- if (strncmp(key,"FORTRAN",n)==0)
- return arrayflags_fortran_get(self);
- if (strncmp(key,"BEHAVED",n)==0)
- return arrayflags_behaved_get(self);
- if (strncmp(key,"OWNDATA",n)==0)
- return arrayflags_owndata_get(self);
- if (strncmp(key,"ALIGNED",n)==0)
- return arrayflags_aligned_get(self);
- break;
- case 9:
- if (strncmp(key,"WRITEABLE",n)==0)
- return arrayflags_writeable_get(self);
- break;
- case 10:
- if (strncmp(key,"CONTIGUOUS",n)==0)
- return arrayflags_contiguous_get(self);
- break;
- case 12:
- if (strncmp(key, "UPDATEIFCOPY", n)==0)
- return arrayflags_updateifcopy_get(self);
- if (strncmp(key, "C_CONTIGUOUS", n)==0)
- return arrayflags_contiguous_get(self);
- if (strncmp(key, "F_CONTIGUOUS", n)==0)
- return arrayflags_fortran_get(self);
- break;
- }
+ char *key;
+ int n;
+ if (!PyString_Check(ind)) goto fail;
+ key = PyString_AS_STRING(ind);
+ n = PyString_GET_SIZE(ind);
+ switch(n) {
+ case 1:
+ switch(key[0]) {
+ case 'C':
+ return arrayflags_contiguous_get(self);
+ case 'F':
+ return arrayflags_fortran_get(self);
+ case 'W':
+ return arrayflags_writeable_get(self);
+ case 'B':
+ return arrayflags_behaved_get(self);
+ case 'O':
+ return arrayflags_owndata_get(self);
+ case 'A':
+ return arrayflags_aligned_get(self);
+ case 'U':
+ return arrayflags_updateifcopy_get(self);
+ default:
+ goto fail;
+ }
+ break;
+ case 2:
+ if (strncmp(key, "CA", n)==0)
+ return arrayflags_carray_get(self);
+ if (strncmp(key, "FA", n)==0)
+ return arrayflags_farray_get(self);
+ break;
+ case 3:
+ if (strncmp(key, "FNC", n)==0)
+ return arrayflags_fnc_get(self);
+ break;
+ case 4:
+ if (strncmp(key, "FORC", n)==0)
+ return arrayflags_forc_get(self);
+ break;
+ case 6:
+ if (strncmp(key, "CARRAY", n)==0)
+ return arrayflags_carray_get(self);
+ if (strncmp(key, "FARRAY", n)==0)
+ return arrayflags_farray_get(self);
+ break;
+ case 7:
+ if (strncmp(key,"FORTRAN",n)==0)
+ return arrayflags_fortran_get(self);
+ if (strncmp(key,"BEHAVED",n)==0)
+ return arrayflags_behaved_get(self);
+ if (strncmp(key,"OWNDATA",n)==0)
+ return arrayflags_owndata_get(self);
+ if (strncmp(key,"ALIGNED",n)==0)
+ return arrayflags_aligned_get(self);
+ break;
+ case 9:
+ if (strncmp(key,"WRITEABLE",n)==0)
+ return arrayflags_writeable_get(self);
+ break;
+ case 10:
+ if (strncmp(key,"CONTIGUOUS",n)==0)
+ return arrayflags_contiguous_get(self);
+ break;
+ case 12:
+ if (strncmp(key, "UPDATEIFCOPY", n)==0)
+ return arrayflags_updateifcopy_get(self);
+ if (strncmp(key, "C_CONTIGUOUS", n)==0)
+ return arrayflags_contiguous_get(self);
+ if (strncmp(key, "F_CONTIGUOUS", n)==0)
+ return arrayflags_fortran_get(self);
+ break;
+ }
fail:
- PyErr_SetString(PyExc_KeyError, "Unknown flag");
- return NULL;
+ PyErr_SetString(PyExc_KeyError, "Unknown flag");
+ return NULL;
}
static int
arrayflags_setitem(PyArrayFlagsObject *self, PyObject *ind, PyObject *item)
{
- char *key;
- int n;
- if (!PyString_Check(ind)) goto fail;
- key = PyString_AS_STRING(ind);
- n = PyString_GET_SIZE(ind);
- if (((n==9) && (strncmp(key, "WRITEABLE", n)==0)) ||
- ((n==1) && (strncmp(key, "W", n)==0)))
- return arrayflags_writeable_set(self, item);
- else if (((n==7) && (strncmp(key, "ALIGNED", n)==0)) ||
- ((n==1) && (strncmp(key, "A", n)==0)))
- return arrayflags_aligned_set(self, item);
- else if (((n==12) && (strncmp(key, "UPDATEIFCOPY", n)==0)) ||
- ((n==1) && (strncmp(key, "U", n)==0)))
- return arrayflags_updateifcopy_set(self, item);
-
-fail:
- PyErr_SetString(PyExc_KeyError, "Unknown flag");
- return -1;
+ char *key;
+ int n;
+ if (!PyString_Check(ind)) goto fail;
+ key = PyString_AS_STRING(ind);
+ n = PyString_GET_SIZE(ind);
+ if (((n==9) && (strncmp(key, "WRITEABLE", n)==0)) ||
+ ((n==1) && (strncmp(key, "W", n)==0)))
+ return arrayflags_writeable_set(self, item);
+ else if (((n==7) && (strncmp(key, "ALIGNED", n)==0)) ||
+ ((n==1) && (strncmp(key, "A", n)==0)))
+ return arrayflags_aligned_set(self, item);
+ else if (((n==12) && (strncmp(key, "UPDATEIFCOPY", n)==0)) ||
+ ((n==1) && (strncmp(key, "U", n)==0)))
+ return arrayflags_updateifcopy_set(self, item);
+
+ fail:
+ PyErr_SetString(PyExc_KeyError, "Unknown flag");
+ return -1;
}
static char *
_torf_(int flags, int val)
{
- if ((flags & val) == val) return "True";
- else return "False";
+ if ((flags & val) == val) return "True";
+ else return "False";
}
static PyObject *
arrayflags_print(PyArrayFlagsObject *self)
{
- int fl = self->flags;
+ int fl = self->flags;
- return PyString_FromFormat(" %s : %s\n %s : %s\n %s : %s\n"\
- " %s : %s\n %s : %s\n %s : %s",
- "C_CONTIGUOUS", _torf_(fl, CONTIGUOUS),
- "F_CONTIGUOUS", _torf_(fl, FORTRAN),
- "OWNDATA", _torf_(fl, OWNDATA),
- "WRITEABLE", _torf_(fl, WRITEABLE),
- "ALIGNED", _torf_(fl, ALIGNED),
- "UPDATEIFCOPY", _torf_(fl, UPDATEIFCOPY));
+ return PyString_FromFormat(" %s : %s\n %s : %s\n %s : %s\n"\
+ " %s : %s\n %s : %s\n %s : %s",
+ "C_CONTIGUOUS", _torf_(fl, CONTIGUOUS),
+ "F_CONTIGUOUS", _torf_(fl, FORTRAN),
+ "OWNDATA", _torf_(fl, OWNDATA),
+ "WRITEABLE", _torf_(fl, WRITEABLE),
+ "ALIGNED", _torf_(fl, ALIGNED),
+ "UPDATEIFCOPY", _torf_(fl, UPDATEIFCOPY));
}
static int
arrayflags_compare(PyArrayFlagsObject *self, PyArrayFlagsObject *other)
{
- if (self->flags == other->flags)
- return 0;
- else if (self->flags < other->flags)
- return -1;
- else
- return 1;
+ if (self->flags == other->flags)
+ return 0;
+ else if (self->flags < other->flags)
+ return -1;
+ else
+ return 1;
}
static PyMappingMethods arrayflags_as_mapping = {
#if PY_VERSION_HEX >= 0x02050000
- (lenfunc)NULL, /*mp_length*/
+ (lenfunc)NULL, /*mp_length*/
#else
- (inquiry)NULL, /*mp_length*/
+ (inquiry)NULL, /*mp_length*/
#endif
- (binaryfunc)arrayflags_getitem, /*mp_subscript*/
- (objobjargproc)arrayflags_setitem, /*mp_ass_subscript*/
+ (binaryfunc)arrayflags_getitem, /*mp_subscript*/
+ (objobjargproc)arrayflags_setitem, /*mp_ass_subscript*/
};
static PyObject *
arrayflags_new(PyTypeObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *arg=NULL;
- if (!PyArg_UnpackTuple(args, "flagsobj", 0, 1, &arg))
- return NULL;
+ PyObject *arg=NULL;
+ if (!PyArg_UnpackTuple(args, "flagsobj", 0, 1, &arg))
+ return NULL;
- if ((arg != NULL) && PyArray_Check(arg)) {
- return PyArray_NewFlagsObject(arg);
- }
- else {
- return PyArray_NewFlagsObject(NULL);
- }
+ if ((arg != NULL) && PyArray_Check(arg)) {
+ return PyArray_NewFlagsObject(arg);
+ }
+ else {
+ return PyArray_NewFlagsObject(NULL);
+ }
}
static PyTypeObject PyArrayFlags_Type = {
- PyObject_HEAD_INIT(NULL)
- 0,
- "numpy.flagsobj",
- sizeof(PyArrayFlagsObject),
- 0, /* tp_itemsize */
- /* methods */
- (destructor)arrayflags_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)arrayflags_compare, /* tp_compare */
- (reprfunc)arrayflags_print, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- &arrayflags_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)arrayflags_print, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- arrayflags_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- arrayflags_new, /* tp_new */
- 0, /* tp_free */
- 0, /* tp_is_gc */
- 0, /* tp_bases */
- 0, /* tp_mro */
- 0, /* tp_cache */
- 0, /* tp_subclasses */
- 0 /* tp_weaklist */
+ PyObject_HEAD_INIT(NULL)
+ 0,
+ "numpy.flagsobj",
+ sizeof(PyArrayFlagsObject),
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)arrayflags_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)arrayflags_compare, /* tp_compare */
+ (reprfunc)arrayflags_print, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ &arrayflags_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)arrayflags_print, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ arrayflags_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ arrayflags_new, /* tp_new */
+ 0, /* tp_free */
+ 0, /* tp_is_gc */
+ 0, /* tp_bases */
+ 0, /* tp_mro */
+ 0, /* tp_cache */
+ 0, /* tp_subclasses */
+ 0 /* tp_weaklist */
};
diff --git a/numpy/core/src/multiarraymodule.c b/numpy/core/src/multiarraymodule.c
index 4df198344..92b676813 100644
--- a/numpy/core/src/multiarraymodule.c
+++ b/numpy/core/src/multiarraymodule.c
@@ -30,55 +30,55 @@ static PyObject *typeDict=NULL; /* Must be explicitly loaded */
static PyArray_Descr *
_arraydescr_fromobj(PyObject *obj)
{
- PyObject *dtypedescr;
- PyArray_Descr *new;
- int ret;
-
- dtypedescr = PyObject_GetAttrString(obj, "dtype");
- PyErr_Clear();
- if (dtypedescr) {
- ret = PyArray_DescrConverter(dtypedescr, &new);
- Py_DECREF(dtypedescr);
- if (ret == PY_SUCCEED) return new;
- PyErr_Clear();
- }
- /* Understand basic ctypes */
- dtypedescr = PyObject_GetAttrString(obj, "_type_");
+ PyObject *dtypedescr;
+ PyArray_Descr *new;
+ int ret;
+
+ dtypedescr = PyObject_GetAttrString(obj, "dtype");
+ PyErr_Clear();
+ if (dtypedescr) {
+ ret = PyArray_DescrConverter(dtypedescr, &new);
+ Py_DECREF(dtypedescr);
+ if (ret == PY_SUCCEED) return new;
PyErr_Clear();
- if (dtypedescr) {
- ret = PyArray_DescrConverter(dtypedescr, &new);
- Py_DECREF(dtypedescr);
- if (ret == PY_SUCCEED) {
- PyObject *length;
- length = PyObject_GetAttrString(obj, "_length_");
- PyErr_Clear();
- if (length) { /* derived type */
- PyObject *newtup;
- PyArray_Descr *derived;
- newtup = Py_BuildValue("NO", new, length);
- ret = PyArray_DescrConverter(newtup, &derived);
- Py_DECREF(newtup);
- if (ret == PY_SUCCEED) return derived;
- PyErr_Clear();
- return NULL;
- }
- return new;
- }
+ }
+ /* Understand basic ctypes */
+ dtypedescr = PyObject_GetAttrString(obj, "_type_");
+ PyErr_Clear();
+ if (dtypedescr) {
+ ret = PyArray_DescrConverter(dtypedescr, &new);
+ Py_DECREF(dtypedescr);
+ if (ret == PY_SUCCEED) {
+ PyObject *length;
+ length = PyObject_GetAttrString(obj, "_length_");
+ PyErr_Clear();
+ if (length) { /* derived type */
+ PyObject *newtup;
+ PyArray_Descr *derived;
+ newtup = Py_BuildValue("NO", new, length);
+ ret = PyArray_DescrConverter(newtup, &derived);
+ Py_DECREF(newtup);
+ if (ret == PY_SUCCEED) return derived;
PyErr_Clear();
return NULL;
+ }
+ return new;
}
- /* Understand ctypes structures --
- bit-fields are not supported
- automatically aligns */
- dtypedescr = PyObject_GetAttrString(obj, "_fields_");
PyErr_Clear();
- if (dtypedescr) {
- ret = PyArray_DescrAlignConverter(dtypedescr, &new);
- Py_DECREF(dtypedescr);
- if (ret == PY_SUCCEED) return new;
- PyErr_Clear();
- }
- return NULL;
+ return NULL;
+ }
+ /* Understand ctypes structures --
+ bit-fields are not supported
+ automatically aligns */
+ dtypedescr = PyObject_GetAttrString(obj, "_fields_");
+ PyErr_Clear();
+ if (dtypedescr) {
+ ret = PyArray_DescrAlignConverter(dtypedescr, &new);
+ Py_DECREF(dtypedescr);
+ if (ret == PY_SUCCEED) return new;
+ PyErr_Clear();
+ }
+ return NULL;
}
@@ -101,348 +101,348 @@ _arraydescr_fromobj(PyObject *obj)
static PyObject *MultiArrayError;
/*MULTIARRAY_API
- Multiply a List of ints
+ Multiply a List of ints
*/
static int
PyArray_MultiplyIntList(register int *l1, register int n)
{
- register int s=1;
- while (n--) s *= (*l1++);
- return s;
+ register int s=1;
+ while (n--) s *= (*l1++);
+ return s;
}
/*MULTIARRAY_API
- Multiply a List
+ Multiply a List
*/
static intp
PyArray_MultiplyList(register intp *l1, register int n)
{
- register intp s=1;
- while (n--) s *= (*l1++);
- return s;
+ register intp s=1;
+ while (n--) s *= (*l1++);
+ return s;
}
/*MULTIARRAY_API
- Produce a pointer into array
+ Produce a pointer into array
*/
static void *
PyArray_GetPtr(PyArrayObject *obj, register intp* ind)
{
- register int n = obj->nd;
- register intp *strides = obj->strides;
- register char *dptr = obj->data;
+ register int n = obj->nd;
+ register intp *strides = obj->strides;
+ register char *dptr = obj->data;
- while (n--) dptr += (*strides++) * (*ind++);
- return (void *)dptr;
+ while (n--) dptr += (*strides++) * (*ind++);
+ return (void *)dptr;
}
/*MULTIARRAY_API
- Get axis from an object (possibly None) -- a converter function,
+ Get axis from an object (possibly None) -- a converter function,
*/
static int
PyArray_AxisConverter(PyObject *obj, int *axis)
{
- if (obj == Py_None) {
- *axis = MAX_DIMS;
- }
- else {
- *axis = (int) PyInt_AsLong(obj);
- if (PyErr_Occurred()) {
- return PY_FAIL;
- }
- }
- return PY_SUCCEED;
+ if (obj == Py_None) {
+ *axis = MAX_DIMS;
+ }
+ else {
+ *axis = (int) PyInt_AsLong(obj);
+ if (PyErr_Occurred()) {
+ return PY_FAIL;
+ }
+ }
+ return PY_SUCCEED;
}
/*MULTIARRAY_API
- Compare Lists
+ Compare Lists
*/
static int
PyArray_CompareLists(intp *l1, intp *l2, int n)
{
- int i;
- for(i=0;i<n;i++) {
- if (l1[i] != l2[i]) return 0;
- }
- return 1;
+ int i;
+ for(i=0;i<n;i++) {
+ if (l1[i] != l2[i]) return 0;
+ }
+ return 1;
}
/* steals a reference to type -- accepts NULL */
/*MULTIARRAY_API
- View
+ View
*/
static PyObject *
PyArray_View(PyArrayObject *self, PyArray_Descr *type, PyTypeObject *pytype)
{
- PyObject *new=NULL;
- PyTypeObject *subtype;
-
- if (pytype) subtype = pytype;
- else subtype = self->ob_type;
-
- Py_INCREF(self->descr);
- new = PyArray_NewFromDescr(subtype,
- self->descr,
- self->nd, self->dimensions,
- self->strides,
- self->data,
- self->flags, (PyObject *)self);
-
- if (new==NULL) return NULL;
- Py_INCREF(self);
- PyArray_BASE(new) = (PyObject *)self;
-
- if (type != NULL) {
- if (PyObject_SetAttrString(new, "dtype",
- (PyObject *)type) < 0) {
- Py_DECREF(new);
- Py_DECREF(type);
- return NULL;
- }
- Py_DECREF(type);
- }
- return new;
+ PyObject *new=NULL;
+ PyTypeObject *subtype;
+
+ if (pytype) subtype = pytype;
+ else subtype = self->ob_type;
+
+ Py_INCREF(self->descr);
+ new = PyArray_NewFromDescr(subtype,
+ self->descr,
+ self->nd, self->dimensions,
+ self->strides,
+ self->data,
+ self->flags, (PyObject *)self);
+
+ if (new==NULL) return NULL;
+ Py_INCREF(self);
+ PyArray_BASE(new) = (PyObject *)self;
+
+ if (type != NULL) {
+ if (PyObject_SetAttrString(new, "dtype",
+ (PyObject *)type) < 0) {
+ Py_DECREF(new);
+ Py_DECREF(type);
+ return NULL;
+ }
+ Py_DECREF(type);
+ }
+ return new;
}
/* Returns a contiguous array */
/*MULTIARRAY_API
- Ravel
+ Ravel
*/
static PyObject *
PyArray_Ravel(PyArrayObject *a, NPY_ORDER fortran)
{
- PyArray_Dims newdim = {NULL,1};
- intp val[1] = {-1};
+ PyArray_Dims newdim = {NULL,1};
+ intp val[1] = {-1};
- if (fortran == PyArray_ANYORDER)
- fortran = PyArray_ISFORTRAN(a);
+ if (fortran == PyArray_ANYORDER)
+ fortran = PyArray_ISFORTRAN(a);
- newdim.ptr = val;
- if (!fortran && PyArray_ISCONTIGUOUS(a)) {
- return PyArray_Newshape(a, &newdim, PyArray_CORDER);
- }
- else if (fortran && PyArray_ISFORTRAN(a)) {
- return PyArray_Newshape(a, &newdim, PyArray_FORTRANORDER);
- }
- else
- return PyArray_Flatten(a, fortran);
+ newdim.ptr = val;
+ if (!fortran && PyArray_ISCONTIGUOUS(a)) {
+ return PyArray_Newshape(a, &newdim, PyArray_CORDER);
+ }
+ else if (fortran && PyArray_ISFORTRAN(a)) {
+ return PyArray_Newshape(a, &newdim, PyArray_FORTRANORDER);
+ }
+ else
+ return PyArray_Flatten(a, fortran);
}
static double
power_of_ten(int n)
{
- static const double p10[] = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8};
- double ret;
- if (n < 9)
- ret = p10[n];
- else {
- ret = 1e9;
- while (n-- > 9)
- ret *= 10.;
- }
- return ret;
+ static const double p10[] = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8};
+ double ret;
+ if (n < 9)
+ ret = p10[n];
+ else {
+ ret = 1e9;
+ while (n-- > 9)
+ ret *= 10.;
+ }
+ return ret;
}
/*MULTIARRAY_API
- Round
+ Round
*/
static PyObject *
PyArray_Round(PyArrayObject *a, int decimals, PyArrayObject *out)
{
- PyObject *f, *ret=NULL, *tmp, *op1, *op2;
- int ret_int=0;
- PyArray_Descr *my_descr;
- if (out && (PyArray_SIZE(out) != PyArray_SIZE(a))) {
- PyErr_SetString(PyExc_ValueError,
- "invalid output shape");
- return NULL;
+ PyObject *f, *ret=NULL, *tmp, *op1, *op2;
+ int ret_int=0;
+ PyArray_Descr *my_descr;
+ if (out && (PyArray_SIZE(out) != PyArray_SIZE(a))) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid output shape");
+ return NULL;
+ }
+ if (PyArray_ISCOMPLEX(a)) {
+ PyObject *part;
+ PyObject *round_part;
+ PyObject *new;
+ int res;
+ if (out) {
+ new = (PyObject *)out;
+ Py_INCREF(new);
+ }
+ else {
+ new = PyArray_Copy(a);
+ if (new == NULL) return NULL;
}
- if (PyArray_ISCOMPLEX(a)) {
- PyObject *part;
- PyObject *round_part;
- PyObject *new;
- int res;
- if (out) {
- new = (PyObject *)out;
- Py_INCREF(new);
- }
- else {
- new = PyArray_Copy(a);
- if (new == NULL) return NULL;
- }
- /* new.real = a.real.round(decimals) */
- part = PyObject_GetAttrString(new, "real");
- if (part == NULL) {Py_DECREF(new); return NULL;}
- part = PyArray_EnsureAnyArray(part);
- round_part = PyArray_Round((PyArrayObject *)part,
- decimals, NULL);
- Py_DECREF(part);
- if (round_part == NULL) {Py_DECREF(new); return NULL;}
- res = PyObject_SetAttrString(new, "real", round_part);
- Py_DECREF(round_part);
- if (res < 0) {Py_DECREF(new); return NULL;}
-
- /* new.imag = a.imag.round(decimals) */
- part = PyObject_GetAttrString(new, "imag");
- if (part == NULL) {Py_DECREF(new); return NULL;}
- part = PyArray_EnsureAnyArray(part);
- round_part = PyArray_Round((PyArrayObject *)part,
- decimals, NULL);
- Py_DECREF(part);
- if (round_part == NULL) {Py_DECREF(new); return NULL;}
- res = PyObject_SetAttrString(new, "imag", round_part);
- Py_DECREF(round_part);
- if (res < 0) {Py_DECREF(new); return NULL;}
- return new;
- }
- /* do the most common case first */
- if (decimals >= 0) {
- if (PyArray_ISINTEGER(a)) {
- if (out) {
- if (PyArray_CopyAnyInto(out, a) < 0) return NULL;
- Py_INCREF(out);
- return (PyObject *)out;
- }
- else {
- Py_INCREF(a);
- return (PyObject *)a;
- }
- }
- if (decimals == 0) {
- if (out) {
- return PyObject_CallFunction(n_ops.rint, "OO",
- a, out);
- }
- return PyObject_CallFunction(n_ops.rint, "O", a);
- }
- op1 = n_ops.multiply;
- op2 = n_ops.true_divide;
+ /* new.real = a.real.round(decimals) */
+ part = PyObject_GetAttrString(new, "real");
+ if (part == NULL) {Py_DECREF(new); return NULL;}
+ part = PyArray_EnsureAnyArray(part);
+ round_part = PyArray_Round((PyArrayObject *)part,
+ decimals, NULL);
+ Py_DECREF(part);
+ if (round_part == NULL) {Py_DECREF(new); return NULL;}
+ res = PyObject_SetAttrString(new, "real", round_part);
+ Py_DECREF(round_part);
+ if (res < 0) {Py_DECREF(new); return NULL;}
+
+ /* new.imag = a.imag.round(decimals) */
+ part = PyObject_GetAttrString(new, "imag");
+ if (part == NULL) {Py_DECREF(new); return NULL;}
+ part = PyArray_EnsureAnyArray(part);
+ round_part = PyArray_Round((PyArrayObject *)part,
+ decimals, NULL);
+ Py_DECREF(part);
+ if (round_part == NULL) {Py_DECREF(new); return NULL;}
+ res = PyObject_SetAttrString(new, "imag", round_part);
+ Py_DECREF(round_part);
+ if (res < 0) {Py_DECREF(new); return NULL;}
+ return new;
+ }
+ /* do the most common case first */
+ if (decimals >= 0) {
+ if (PyArray_ISINTEGER(a)) {
+ if (out) {
+ if (PyArray_CopyAnyInto(out, a) < 0) return NULL;
+ Py_INCREF(out);
+ return (PyObject *)out;
+ }
+ else {
+ Py_INCREF(a);
+ return (PyObject *)a;
+ }
+ }
+ if (decimals == 0) {
+ if (out) {
+ return PyObject_CallFunction(n_ops.rint, "OO",
+ a, out);
+ }
+ return PyObject_CallFunction(n_ops.rint, "O", a);
+ }
+ op1 = n_ops.multiply;
+ op2 = n_ops.true_divide;
+ }
+ else {
+ op1 = n_ops.true_divide;
+ op2 = n_ops.multiply;
+ decimals = -decimals;
+ }
+ if (!out) {
+ if (PyArray_ISINTEGER(a)) {
+ ret_int = 1;
+ my_descr = PyArray_DescrFromType(NPY_DOUBLE);
}
else {
- op1 = n_ops.true_divide;
- op2 = n_ops.multiply;
- decimals = -decimals;
- }
- if (!out) {
- if (PyArray_ISINTEGER(a)) {
- ret_int = 1;
- my_descr = PyArray_DescrFromType(NPY_DOUBLE);
- }
- else {
- Py_INCREF(a->descr);
- my_descr = a->descr;
- }
- out = (PyArrayObject *)PyArray_Empty(a->nd, a->dimensions,
- my_descr,
- PyArray_ISFORTRAN(a));
- if (out == NULL) return NULL;
- }
- else Py_INCREF(out);
- f = PyFloat_FromDouble(power_of_ten(decimals));
- if (f==NULL) return NULL;
- ret = PyObject_CallFunction(op1, "OOO", a, f, out);
- if (ret==NULL) goto finish;
- tmp = PyObject_CallFunction(n_ops.rint, "OO", ret, ret);
- if (tmp == NULL) {Py_DECREF(ret); ret=NULL; goto finish;}
- Py_DECREF(tmp);
- tmp = PyObject_CallFunction(op2, "OOO", ret, f, ret);
- if (tmp == NULL) {Py_DECREF(ret); ret=NULL; goto finish;}
- Py_DECREF(tmp);
+ Py_INCREF(a->descr);
+ my_descr = a->descr;
+ }
+ out = (PyArrayObject *)PyArray_Empty(a->nd, a->dimensions,
+ my_descr,
+ PyArray_ISFORTRAN(a));
+ if (out == NULL) return NULL;
+ }
+ else Py_INCREF(out);
+ f = PyFloat_FromDouble(power_of_ten(decimals));
+ if (f==NULL) return NULL;
+ ret = PyObject_CallFunction(op1, "OOO", a, f, out);
+ if (ret==NULL) goto finish;
+ tmp = PyObject_CallFunction(n_ops.rint, "OO", ret, ret);
+ if (tmp == NULL) {Py_DECREF(ret); ret=NULL; goto finish;}
+ Py_DECREF(tmp);
+ tmp = PyObject_CallFunction(op2, "OOO", ret, f, ret);
+ if (tmp == NULL) {Py_DECREF(ret); ret=NULL; goto finish;}
+ Py_DECREF(tmp);
finish:
- Py_DECREF(f);
- Py_DECREF(out);
- if (ret_int) {
- Py_INCREF(a->descr);
- tmp = PyArray_CastToType((PyArrayObject *)ret,
- a->descr, PyArray_ISFORTRAN(a));
- Py_DECREF(ret);
- return tmp;
- }
- return ret;
+ Py_DECREF(f);
+ Py_DECREF(out);
+ if (ret_int) {
+ Py_INCREF(a->descr);
+ tmp = PyArray_CastToType((PyArrayObject *)ret,
+ a->descr, PyArray_ISFORTRAN(a));
+ Py_DECREF(ret);
+ return tmp;
+ }
+ return ret;
}
/*MULTIARRAY_API
- Flatten
+ Flatten
*/
static PyObject *
PyArray_Flatten(PyArrayObject *a, NPY_ORDER order)
{
- PyObject *ret;
- intp size;
+ PyObject *ret;
+ intp size;
- if (order == PyArray_ANYORDER)
- order = PyArray_ISFORTRAN(a);
+ if (order == PyArray_ANYORDER)
+ order = PyArray_ISFORTRAN(a);
- size = PyArray_SIZE(a);
- Py_INCREF(a->descr);
- ret = PyArray_NewFromDescr(a->ob_type,
- a->descr,
- 1, &size,
- NULL,
- NULL,
- 0, (PyObject *)a);
+ size = PyArray_SIZE(a);
+ Py_INCREF(a->descr);
+ ret = PyArray_NewFromDescr(a->ob_type,
+ a->descr,
+ 1, &size,
+ NULL,
+ NULL,
+ 0, (PyObject *)a);
- if (ret== NULL) return NULL;
- if (_flat_copyinto(ret, (PyObject *)a, order) < 0) {
- Py_DECREF(ret);
- return NULL;
- }
- return ret;
+ if (ret== NULL) return NULL;
+ if (_flat_copyinto(ret, (PyObject *)a, order) < 0) {
+ Py_DECREF(ret);
+ return NULL;
+ }
+ return ret;
}
/* For back-ward compatability *
-/ * Not recommended */
+ / * Not recommended */
/*MULTIARRAY_API
- Reshape an array
+ Reshape an array
*/
static PyObject *
PyArray_Reshape(PyArrayObject *self, PyObject *shape)
{
- PyObject *ret;
- PyArray_Dims newdims;
+ PyObject *ret;
+ PyArray_Dims newdims;
- if (!PyArray_IntpConverter(shape, &newdims)) return NULL;
- ret = PyArray_Newshape(self, &newdims, PyArray_CORDER);
- PyDimMem_FREE(newdims.ptr);
- return ret;
+ if (!PyArray_IntpConverter(shape, &newdims)) return NULL;
+ ret = PyArray_Newshape(self, &newdims, PyArray_CORDER);
+ PyDimMem_FREE(newdims.ptr);
+ return ret;
}
/* inserts 0 for strides where dimension will be 1 */
static int
_check_ones(PyArrayObject *self, int newnd, intp* newdims, intp *strides)
{
- int nd;
- intp *dims;
- Bool done=FALSE;
- int j, k;
-
- nd = self->nd;
- dims = self->dimensions;
-
- for (k=0, j=0; !done && (j<nd || k<newnd);) {
- if ((j<nd) && (k<newnd) && (newdims[k]==dims[j])) {
- strides[k] = self->strides[j];
- j++; k++;
- }
- else if ((k<newnd) && (newdims[k]==1)) {
- strides[k] = 0;
- k++;
- }
- else if ((j<nd) && (dims[j]==1)) {
- j++;
- }
- else done=TRUE;
- }
- if (done) return -1;
- return 0;
+ int nd;
+ intp *dims;
+ Bool done=FALSE;
+ int j, k;
+
+ nd = self->nd;
+ dims = self->dimensions;
+
+ for (k=0, j=0; !done && (j<nd || k<newnd);) {
+ if ((j<nd) && (k<newnd) && (newdims[k]==dims[j])) {
+ strides[k] = self->strides[j];
+ j++; k++;
+ }
+ else if ((k<newnd) && (newdims[k]==1)) {
+ strides[k] = 0;
+ k++;
+ }
+ else if ((j<nd) && (dims[j]==1)) {
+ j++;
+ }
+ else done=TRUE;
+ }
+ if (done) return -1;
+ return 0;
}
/* attempt to reshape an array without copying data
@@ -464,142 +464,142 @@ _check_ones(PyArrayObject *self, int newnd, intp* newdims, intp *strides)
*/
static int
_attempt_nocopy_reshape(PyArrayObject *self, int newnd, intp* newdims,
- intp *newstrides, int fortran)
-{
- int oldnd;
- intp olddims[MAX_DIMS];
- intp oldstrides[MAX_DIMS];
- int oi, oj, ok, ni, nj, nk;
- int np, op;
-
- oldnd = 0;
- for (oi=0; oi<self->nd; oi++) {
- if (self->dimensions[oi]!=1) {
- olddims[oldnd] = self->dimensions[oi];
- oldstrides[oldnd] = self->strides[oi];
- oldnd++;
- }
- }
-
- /*
- fprintf(stderr, "_attempt_nocopy_reshape( (");
- for (oi=0; oi<oldnd; oi++)
- fprintf(stderr, "(%d,%d), ", olddims[oi], oldstrides[oi]);
- fprintf(stderr, ") -> (");
- for (ni=0; ni<newnd; ni++)
- fprintf(stderr, "(%d,*), ", newdims[ni]);
- fprintf(stderr, "), fortran=%d)\n", fortran);
- */
-
-
- np = 1;
- for (ni=0; ni<newnd; ni++) np*=newdims[ni];
-
- op = 1;
- for (oi=0; oi<oldnd; oi++) op*=olddims[oi];
-
- if (np != op) return 0; /* different total sizes; no hope */
-
-
- oi = 0;
- oj = 1;
- ni = 0;
- nj = 1;
-
- while(ni<newnd && oi<oldnd) {
-
- np = newdims[ni];
- op = olddims[oi];
-
- while (np!=op) {
- if (np<op) {
- np *= newdims[nj++];
- } else {
- op *= olddims[oj++];
- }
- }
-
- for(ok=oi; ok<oj-1; ok++) {
- if (fortran) {
- if (oldstrides[ok+1] != \
- olddims[ok]*oldstrides[ok])
- return 0; /* not contiguous enough */
- } else { /* C order */
- if (oldstrides[ok] != \
- olddims[ok+1]*oldstrides[ok+1])
- return 0; /* not contiguous enough */
- }
- }
-
- if (fortran) {
- newstrides[ni]=oldstrides[oi];
- for (nk=ni+1;nk<nj;nk++)
- newstrides[nk]=newstrides[nk-1]*newdims[nk-1];
- } else { /* C order */
- newstrides[nj-1]=oldstrides[oj-1];
- for (nk=nj-1;nk>ni;nk--)
- newstrides[nk-1]=newstrides[nk]*newdims[nk];
- }
-
- ni = nj++;
- oi = oj++;
-
- }
-
- /*
- fprintf(stderr, "success: _attempt_nocopy_reshape (");
- for (oi=0; oi<oldnd; oi++)
- fprintf(stderr, "(%d,%d), ", olddims[oi], oldstrides[oi]);
- fprintf(stderr, ") -> (");
- for (ni=0; ni<newnd; ni++)
- fprintf(stderr, "(%d,%d), ", newdims[ni], newstrides[ni]);
- fprintf(stderr, ")\n");
- */
-
- return 1;
+ intp *newstrides, int fortran)
+{
+ int oldnd;
+ intp olddims[MAX_DIMS];
+ intp oldstrides[MAX_DIMS];
+ int oi, oj, ok, ni, nj, nk;
+ int np, op;
+
+ oldnd = 0;
+ for (oi=0; oi<self->nd; oi++) {
+ if (self->dimensions[oi]!=1) {
+ olddims[oldnd] = self->dimensions[oi];
+ oldstrides[oldnd] = self->strides[oi];
+ oldnd++;
+ }
+ }
+
+ /*
+ fprintf(stderr, "_attempt_nocopy_reshape( (");
+ for (oi=0; oi<oldnd; oi++)
+ fprintf(stderr, "(%d,%d), ", olddims[oi], oldstrides[oi]);
+ fprintf(stderr, ") -> (");
+ for (ni=0; ni<newnd; ni++)
+ fprintf(stderr, "(%d,*), ", newdims[ni]);
+ fprintf(stderr, "), fortran=%d)\n", fortran);
+ */
+
+
+ np = 1;
+ for (ni=0; ni<newnd; ni++) np*=newdims[ni];
+
+ op = 1;
+ for (oi=0; oi<oldnd; oi++) op*=olddims[oi];
+
+ if (np != op) return 0; /* different total sizes; no hope */
+
+
+ oi = 0;
+ oj = 1;
+ ni = 0;
+ nj = 1;
+
+ while(ni<newnd && oi<oldnd) {
+
+ np = newdims[ni];
+ op = olddims[oi];
+
+ while (np!=op) {
+ if (np<op) {
+ np *= newdims[nj++];
+ } else {
+ op *= olddims[oj++];
+ }
+ }
+
+ for(ok=oi; ok<oj-1; ok++) {
+ if (fortran) {
+ if (oldstrides[ok+1] != \
+ olddims[ok]*oldstrides[ok])
+ return 0; /* not contiguous enough */
+ } else { /* C order */
+ if (oldstrides[ok] != \
+ olddims[ok+1]*oldstrides[ok+1])
+ return 0; /* not contiguous enough */
+ }
+ }
+
+ if (fortran) {
+ newstrides[ni]=oldstrides[oi];
+ for (nk=ni+1;nk<nj;nk++)
+ newstrides[nk]=newstrides[nk-1]*newdims[nk-1];
+ } else { /* C order */
+ newstrides[nj-1]=oldstrides[oj-1];
+ for (nk=nj-1;nk>ni;nk--)
+ newstrides[nk-1]=newstrides[nk]*newdims[nk];
+ }
+
+ ni = nj++;
+ oi = oj++;
+
+ }
+
+ /*
+ fprintf(stderr, "success: _attempt_nocopy_reshape (");
+ for (oi=0; oi<oldnd; oi++)
+ fprintf(stderr, "(%d,%d), ", olddims[oi], oldstrides[oi]);
+ fprintf(stderr, ") -> (");
+ for (ni=0; ni<newnd; ni++)
+ fprintf(stderr, "(%d,%d), ", newdims[ni], newstrides[ni]);
+ fprintf(stderr, ")\n");
+ */
+
+ return 1;
}
static int
_fix_unknown_dimension(PyArray_Dims *newshape, intp s_original)
{
- intp *dimensions;
- intp i_unknown, s_known;
- int i, n;
- static char msg[] = "total size of new array must be unchanged";
-
- dimensions = newshape->ptr;
- n = newshape->len;
- s_known = 1;
- i_unknown = -1;
-
- for(i=0; i<n; i++) {
- if (dimensions[i] < 0) {
- if (i_unknown == -1) {
- i_unknown = i;
- } else {
- PyErr_SetString(PyExc_ValueError,
- "can only specify one" \
- " unknown dimension");
- return -1;
- }
- } else {
- s_known *= dimensions[i];
- }
- }
-
- if (i_unknown >= 0) {
- if ((s_known == 0) || (s_original % s_known != 0)) {
- PyErr_SetString(PyExc_ValueError, msg);
- return -1;
- }
- dimensions[i_unknown] = s_original/s_known;
- } else {
- if (s_original != s_known) {
- PyErr_SetString(PyExc_ValueError, msg);
- return -1;
- }
- }
- return 0;
+ intp *dimensions;
+ intp i_unknown, s_known;
+ int i, n;
+ static char msg[] = "total size of new array must be unchanged";
+
+ dimensions = newshape->ptr;
+ n = newshape->len;
+ s_known = 1;
+ i_unknown = -1;
+
+ for(i=0; i<n; i++) {
+ if (dimensions[i] < 0) {
+ if (i_unknown == -1) {
+ i_unknown = i;
+ } else {
+ PyErr_SetString(PyExc_ValueError,
+ "can only specify one" \
+ " unknown dimension");
+ return -1;
+ }
+ } else {
+ s_known *= dimensions[i];
+ }
+ }
+
+ if (i_unknown >= 0) {
+ if ((s_known == 0) || (s_original % s_known != 0)) {
+ PyErr_SetString(PyExc_ValueError, msg);
+ return -1;
+ }
+ dimensions[i_unknown] = s_original/s_known;
+ } else {
+ if (s_original != s_known) {
+ PyErr_SetString(PyExc_ValueError, msg);
+ return -1;
+ }
+ }
+ return 0;
}
/* Returns a new array
@@ -609,143 +609,143 @@ _fix_unknown_dimension(PyArray_Dims *newshape, intp s_original)
*/
/*MULTIARRAY_API
- New shape for an array
+ New shape for an array
*/
static PyObject *
PyArray_Newshape(PyArrayObject *self, PyArray_Dims *newdims,
- NPY_ORDER fortran)
-{
- intp i;
- intp *dimensions = newdims->ptr;
- PyArrayObject *ret;
- int n = newdims->len;
- Bool same, incref=TRUE;
- intp *strides = NULL;
- intp newstrides[MAX_DIMS];
- int flags;
-
- if (fortran == PyArray_ANYORDER)
- fortran = PyArray_ISFORTRAN(self);
-
- /* Quick check to make sure anything actually needs to be done */
- if (n == self->nd) {
- same = TRUE;
- i=0;
- while(same && i<n) {
- if (PyArray_DIM(self,i) != dimensions[i])
- same=FALSE;
- i++;
- }
- if (same) return PyArray_View(self, NULL, NULL);
- }
-
- /* Returns a pointer to an appropriate strides array
- if all we are doing is inserting ones into the shape,
- or removing ones from the shape
- or doing a combination of the two
- In this case we don't need to do anything but update strides and
- dimensions. So, we can handle non single-segment cases.
- */
- i=_check_ones(self, n, dimensions, newstrides);
- if (i==0) strides=newstrides;
-
- flags = self->flags;
-
- if (strides==NULL) { /* we are really re-shaping not just adding ones
- to the shape somewhere */
-
- /* fix any -1 dimensions and check new-dimensions against
- old size */
- if (_fix_unknown_dimension(newdims, PyArray_SIZE(self)) < 0)
- return NULL;
-
- /* sometimes we have to create a new copy of the array
- in order to get the right orientation and
- because we can't just re-use the buffer with the
- data in the order it is in.
- */
- if (!(PyArray_ISONESEGMENT(self)) ||
- (((PyArray_CHKFLAGS(self, NPY_CONTIGUOUS) &&
- fortran == NPY_FORTRANORDER)
- || (PyArray_CHKFLAGS(self, NPY_FORTRAN) &&
- fortran == NPY_CORDER)) && (self->nd > 1))) {
-
- int success=0;
- success = _attempt_nocopy_reshape(self,n,dimensions,
- newstrides,fortran);
- if (success) {
- /* no need to copy the array after all */
- strides = newstrides;
- flags = self->flags;
- } else {
- PyObject *new;
- new = PyArray_NewCopy(self, fortran);
- if (new == NULL) return NULL;
- incref = FALSE;
- self = (PyArrayObject *)new;
- flags = self->flags;
- }
- }
-
- /* We always have to interpret the contiguous buffer correctly
- */
-
- /* Make sure the flags argument is set.
- */
- if (n > 1) {
- if (fortran == NPY_FORTRANORDER) {
- flags &= ~NPY_CONTIGUOUS;
- flags |= NPY_FORTRAN;
- }
- else {
- flags &= ~NPY_FORTRAN;
- flags |= NPY_CONTIGUOUS;
- }
- }
- }
- else if (n > 0) {
- /* replace any 0-valued strides with
- appropriate value to preserve contiguousness
- */
- if (fortran == PyArray_FORTRANORDER) {
- if (strides[0] == 0)
- strides[0] = self->descr->elsize;
- for (i=1; i<n; i++) {
- if (strides[i] == 0)
- strides[i] = strides[i-1] * \
- dimensions[i-1];
- }
- }
- else {
- if (strides[n-1] == 0)
- strides[n-1] = self->descr->elsize;
- for (i=n-2; i>-1; i--) {
- if (strides[i] == 0)
- strides[i] = strides[i+1] * \
- dimensions[i+1];
- }
- }
- }
-
- Py_INCREF(self->descr);
- ret = (PyAO *)PyArray_NewFromDescr(self->ob_type,
- self->descr,
- n, dimensions,
- strides,
- self->data,
- flags, (PyObject *)self);
-
- if (ret== NULL) goto fail;
-
- if (incref) Py_INCREF(self);
- ret->base = (PyObject *)self;
- PyArray_UpdateFlags(ret, CONTIGUOUS | FORTRAN);
-
- return (PyObject *)ret;
+ NPY_ORDER fortran)
+{
+ intp i;
+ intp *dimensions = newdims->ptr;
+ PyArrayObject *ret;
+ int n = newdims->len;
+ Bool same, incref=TRUE;
+ intp *strides = NULL;
+ intp newstrides[MAX_DIMS];
+ int flags;
+
+ if (fortran == PyArray_ANYORDER)
+ fortran = PyArray_ISFORTRAN(self);
+
+ /* Quick check to make sure anything actually needs to be done */
+ if (n == self->nd) {
+ same = TRUE;
+ i=0;
+ while(same && i<n) {
+ if (PyArray_DIM(self,i) != dimensions[i])
+ same=FALSE;
+ i++;
+ }
+ if (same) return PyArray_View(self, NULL, NULL);
+ }
+
+ /* Returns a pointer to an appropriate strides array
+ if all we are doing is inserting ones into the shape,
+ or removing ones from the shape
+ or doing a combination of the two
+ In this case we don't need to do anything but update strides and
+ dimensions. So, we can handle non single-segment cases.
+ */
+ i=_check_ones(self, n, dimensions, newstrides);
+ if (i==0) strides=newstrides;
+
+ flags = self->flags;
+
+ if (strides==NULL) { /* we are really re-shaping not just adding ones
+ to the shape somewhere */
+
+ /* fix any -1 dimensions and check new-dimensions against
+ old size */
+ if (_fix_unknown_dimension(newdims, PyArray_SIZE(self)) < 0)
+ return NULL;
+
+ /* sometimes we have to create a new copy of the array
+ in order to get the right orientation and
+ because we can't just re-use the buffer with the
+ data in the order it is in.
+ */
+ if (!(PyArray_ISONESEGMENT(self)) ||
+ (((PyArray_CHKFLAGS(self, NPY_CONTIGUOUS) &&
+ fortran == NPY_FORTRANORDER)
+ || (PyArray_CHKFLAGS(self, NPY_FORTRAN) &&
+ fortran == NPY_CORDER)) && (self->nd > 1))) {
+
+ int success=0;
+ success = _attempt_nocopy_reshape(self,n,dimensions,
+ newstrides,fortran);
+ if (success) {
+ /* no need to copy the array after all */
+ strides = newstrides;
+ flags = self->flags;
+ } else {
+ PyObject *new;
+ new = PyArray_NewCopy(self, fortran);
+ if (new == NULL) return NULL;
+ incref = FALSE;
+ self = (PyArrayObject *)new;
+ flags = self->flags;
+ }
+ }
+
+ /* We always have to interpret the contiguous buffer correctly
+ */
+
+ /* Make sure the flags argument is set.
+ */
+ if (n > 1) {
+ if (fortran == NPY_FORTRANORDER) {
+ flags &= ~NPY_CONTIGUOUS;
+ flags |= NPY_FORTRAN;
+ }
+ else {
+ flags &= ~NPY_FORTRAN;
+ flags |= NPY_CONTIGUOUS;
+ }
+ }
+ }
+ else if (n > 0) {
+ /* replace any 0-valued strides with
+ appropriate value to preserve contiguousness
+ */
+ if (fortran == PyArray_FORTRANORDER) {
+ if (strides[0] == 0)
+ strides[0] = self->descr->elsize;
+ for (i=1; i<n; i++) {
+ if (strides[i] == 0)
+ strides[i] = strides[i-1] * \
+ dimensions[i-1];
+ }
+ }
+ else {
+ if (strides[n-1] == 0)
+ strides[n-1] = self->descr->elsize;
+ for (i=n-2; i>-1; i--) {
+ if (strides[i] == 0)
+ strides[i] = strides[i+1] * \
+ dimensions[i+1];
+ }
+ }
+ }
+
+ Py_INCREF(self->descr);
+ ret = (PyAO *)PyArray_NewFromDescr(self->ob_type,
+ self->descr,
+ n, dimensions,
+ strides,
+ self->data,
+ flags, (PyObject *)self);
+
+ if (ret== NULL) goto fail;
+
+ if (incref) Py_INCREF(self);
+ ret->base = (PyObject *)self;
+ PyArray_UpdateFlags(ret, CONTIGUOUS | FORTRAN);
+
+ return (PyObject *)ret;
fail:
- if (!incref) {Py_DECREF(self);}
- return NULL;
+ if (!incref) {Py_DECREF(self);}
+ return NULL;
}
@@ -753,907 +753,907 @@ PyArray_Newshape(PyArrayObject *self, PyArray_Dims *newdims,
/* return a new view of the array object with all of its unit-length
dimensions squeezed out if needed, otherwise
return the same array.
- */
+*/
/*MULTIARRAY_API*/
static PyObject *
PyArray_Squeeze(PyArrayObject *self)
{
- int nd = self->nd;
- int newnd = nd;
- intp dimensions[MAX_DIMS];
- intp strides[MAX_DIMS];
- int i,j;
- PyObject *ret;
-
- if (nd == 0) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- for (j=0, i=0; i<nd; i++) {
- if (self->dimensions[i] == 1) {
- newnd -= 1;
- }
- else {
- dimensions[j] = self->dimensions[i];
- strides[j++] = self->strides[i];
- }
- }
-
- Py_INCREF(self->descr);
- ret = PyArray_NewFromDescr(self->ob_type,
- self->descr,
- newnd, dimensions,
- strides, self->data,
- self->flags,
- (PyObject *)self);
- if (ret == NULL) return NULL;
- PyArray_FLAGS(ret) &= ~OWNDATA;
- PyArray_BASE(ret) = (PyObject *)self;
- Py_INCREF(self);
- return (PyObject *)ret;
+ int nd = self->nd;
+ int newnd = nd;
+ intp dimensions[MAX_DIMS];
+ intp strides[MAX_DIMS];
+ int i,j;
+ PyObject *ret;
+
+ if (nd == 0) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ for (j=0, i=0; i<nd; i++) {
+ if (self->dimensions[i] == 1) {
+ newnd -= 1;
+ }
+ else {
+ dimensions[j] = self->dimensions[i];
+ strides[j++] = self->strides[i];
+ }
+ }
+
+ Py_INCREF(self->descr);
+ ret = PyArray_NewFromDescr(self->ob_type,
+ self->descr,
+ newnd, dimensions,
+ strides, self->data,
+ self->flags,
+ (PyObject *)self);
+ if (ret == NULL) return NULL;
+ PyArray_FLAGS(ret) &= ~OWNDATA;
+ PyArray_BASE(ret) = (PyObject *)self;
+ Py_INCREF(self);
+ return (PyObject *)ret;
}
/*MULTIARRAY_API
- Mean
+ Mean
*/
static PyObject *
PyArray_Mean(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)
{
- PyObject *obj1=NULL, *obj2=NULL;
- PyObject *new, *ret;
+ PyObject *obj1=NULL, *obj2=NULL;
+ PyObject *new, *ret;
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
- obj1 = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis,
- rtype, out);
- obj2 = PyFloat_FromDouble((double) PyArray_DIM(new,axis));
- Py_DECREF(new);
- if (obj1 == NULL || obj2 == NULL) {
- Py_XDECREF(obj1);
- Py_XDECREF(obj2);
- return NULL;
- }
- if (!out) {
- ret = PyNumber_Divide(obj1, obj2);
- }
- else {
- ret = PyObject_CallFunction(n_ops.divide, "OOO", out, obj2, out);
- }
- Py_DECREF(obj1);
- Py_DECREF(obj2);
- return ret;
+ obj1 = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis,
+ rtype, out);
+ obj2 = PyFloat_FromDouble((double) PyArray_DIM(new,axis));
+ Py_DECREF(new);
+ if (obj1 == NULL || obj2 == NULL) {
+ Py_XDECREF(obj1);
+ Py_XDECREF(obj2);
+ return NULL;
+ }
+ if (!out) {
+ ret = PyNumber_Divide(obj1, obj2);
+ }
+ else {
+ ret = PyObject_CallFunction(n_ops.divide, "OOO", out, obj2, out);
+ }
+ Py_DECREF(obj1);
+ Py_DECREF(obj2);
+ return ret;
}
/* Set variance to 1 to by-pass square-root calculation and return variance */
/*MULTIARRAY_API
- Std
+ Std
*/
static PyObject *
PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out,
int variance)
{
- PyObject *obj1=NULL, *obj2=NULL, *new=NULL;
- PyObject *ret=NULL, *newshape=NULL;
- int i, n;
- intp val;
-
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
-
- /* Compute and reshape mean */
- obj1 = PyArray_EnsureArray(PyArray_Mean((PyAO *)new, axis, rtype, NULL));
- if (obj1 == NULL) {Py_DECREF(new); return NULL;}
- n = PyArray_NDIM(new);
- newshape = PyTuple_New(n);
- if (newshape == NULL) {Py_DECREF(obj1); Py_DECREF(new); return NULL;}
- for (i=0; i<n; i++) {
- if (i==axis) val = 1;
- else val = PyArray_DIM(new,i);
- PyTuple_SET_ITEM(newshape, i, PyInt_FromLong((long)val));
- }
- obj2 = PyArray_Reshape((PyAO *)obj1, newshape);
- Py_DECREF(obj1);
- Py_DECREF(newshape);
- if (obj2 == NULL) {Py_DECREF(new); return NULL;}
-
- /* Compute x = x - mx */
- obj1 = PyArray_EnsureArray(PyNumber_Subtract((PyObject *)new, obj2));
- Py_DECREF(obj2);
- if (obj1 == NULL) {Py_DECREF(new); return NULL;}
-
- /* Compute x * x */
- obj2 = PyArray_EnsureArray \
- (PyArray_GenericBinaryFunction((PyAO *)obj1, obj1, n_ops.multiply));
- Py_DECREF(obj1);
- if (obj2 == NULL) {Py_DECREF(new); return NULL;}
-
- /* Compute add.reduce(x*x,axis) */
- obj1 = PyArray_GenericReduceFunction((PyAO *)obj2, n_ops.add,
- axis, rtype, NULL);
- Py_DECREF(obj2);
- if (obj1 == NULL) {Py_DECREF(new); return NULL;}
-
- n = PyArray_DIM(new,axis);
- Py_DECREF(new);
- if (n==0) n=1;
- obj2 = PyFloat_FromDouble(1.0/((double )n));
- if (obj2 == NULL) {Py_DECREF(obj1); return NULL;}
- ret = PyNumber_Multiply(obj1, obj2);
- Py_DECREF(obj1);
- Py_DECREF(obj2);
-
- if (!variance) {
- obj1 = PyArray_EnsureArray(ret);
-
- /* sqrt() */
- ret = PyArray_GenericUnaryFunction((PyAO *)obj1, n_ops.sqrt);
- Py_DECREF(obj1);
- }
- if (ret == NULL || PyArray_CheckExact(self)) return ret;
- if (PyArray_Check(self) && self->ob_type == ret->ob_type) return ret;
- obj1 = PyArray_EnsureArray(ret);
- if (obj1 == NULL) return NULL;
- ret = PyArray_View((PyAO *)obj1, NULL, self->ob_type);
- Py_DECREF(obj1);
- if (out) {
- if (PyArray_CopyAnyInto(out, (PyArrayObject *)ret) < 0) {
- Py_DECREF(ret);
- return NULL;
- }
- Py_DECREF(ret);
- Py_INCREF(out);
- return (PyObject *)out;
+ PyObject *obj1=NULL, *obj2=NULL, *new=NULL;
+ PyObject *ret=NULL, *newshape=NULL;
+ int i, n;
+ intp val;
+
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+
+ /* Compute and reshape mean */
+ obj1 = PyArray_EnsureArray(PyArray_Mean((PyAO *)new, axis, rtype, NULL));
+ if (obj1 == NULL) {Py_DECREF(new); return NULL;}
+ n = PyArray_NDIM(new);
+ newshape = PyTuple_New(n);
+ if (newshape == NULL) {Py_DECREF(obj1); Py_DECREF(new); return NULL;}
+ for (i=0; i<n; i++) {
+ if (i==axis) val = 1;
+ else val = PyArray_DIM(new,i);
+ PyTuple_SET_ITEM(newshape, i, PyInt_FromLong((long)val));
+ }
+ obj2 = PyArray_Reshape((PyAO *)obj1, newshape);
+ Py_DECREF(obj1);
+ Py_DECREF(newshape);
+ if (obj2 == NULL) {Py_DECREF(new); return NULL;}
+
+ /* Compute x = x - mx */
+ obj1 = PyArray_EnsureArray(PyNumber_Subtract((PyObject *)new, obj2));
+ Py_DECREF(obj2);
+ if (obj1 == NULL) {Py_DECREF(new); return NULL;}
+
+ /* Compute x * x */
+ obj2 = PyArray_EnsureArray \
+ (PyArray_GenericBinaryFunction((PyAO *)obj1, obj1, n_ops.multiply));
+ Py_DECREF(obj1);
+ if (obj2 == NULL) {Py_DECREF(new); return NULL;}
+
+ /* Compute add.reduce(x*x,axis) */
+ obj1 = PyArray_GenericReduceFunction((PyAO *)obj2, n_ops.add,
+ axis, rtype, NULL);
+ Py_DECREF(obj2);
+ if (obj1 == NULL) {Py_DECREF(new); return NULL;}
+
+ n = PyArray_DIM(new,axis);
+ Py_DECREF(new);
+ if (n==0) n=1;
+ obj2 = PyFloat_FromDouble(1.0/((double )n));
+ if (obj2 == NULL) {Py_DECREF(obj1); return NULL;}
+ ret = PyNumber_Multiply(obj1, obj2);
+ Py_DECREF(obj1);
+ Py_DECREF(obj2);
+
+ if (!variance) {
+ obj1 = PyArray_EnsureArray(ret);
+
+ /* sqrt() */
+ ret = PyArray_GenericUnaryFunction((PyAO *)obj1, n_ops.sqrt);
+ Py_DECREF(obj1);
+ }
+ if (ret == NULL || PyArray_CheckExact(self)) return ret;
+ if (PyArray_Check(self) && self->ob_type == ret->ob_type) return ret;
+ obj1 = PyArray_EnsureArray(ret);
+ if (obj1 == NULL) return NULL;
+ ret = PyArray_View((PyAO *)obj1, NULL, self->ob_type);
+ Py_DECREF(obj1);
+ if (out) {
+ if (PyArray_CopyAnyInto(out, (PyArrayObject *)ret) < 0) {
+ Py_DECREF(ret);
+ return NULL;
}
- return ret;
+ Py_DECREF(ret);
+ Py_INCREF(out);
+ return (PyObject *)out;
+ }
+ return ret;
}
/*MULTIARRAY_API
- Sum
+ Sum
*/
static PyObject *
PyArray_Sum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)
{
- PyObject *new, *ret;
+ PyObject *new, *ret;
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
- ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis,
- rtype, out);
- Py_DECREF(new);
- return ret;
+ ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis,
+ rtype, out);
+ Py_DECREF(new);
+ return ret;
}
/*MULTIARRAY_API
- Prod
+ Prod
*/
static PyObject *
PyArray_Prod(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)
{
- PyObject *new, *ret;
+ PyObject *new, *ret;
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
- ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.multiply, axis,
- rtype, out);
- Py_DECREF(new);
- return ret;
+ ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.multiply, axis,
+ rtype, out);
+ Py_DECREF(new);
+ return ret;
}
/*MULTIARRAY_API
- CumSum
+ CumSum
*/
static PyObject *
PyArray_CumSum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)
{
- PyObject *new, *ret;
+ PyObject *new, *ret;
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
- ret = PyArray_GenericAccumulateFunction((PyAO *)new, n_ops.add, axis,
- rtype, out);
- Py_DECREF(new);
- return ret;
+ ret = PyArray_GenericAccumulateFunction((PyAO *)new, n_ops.add, axis,
+ rtype, out);
+ Py_DECREF(new);
+ return ret;
}
/*MULTIARRAY_API
- CumProd
+ CumProd
*/
static PyObject *
PyArray_CumProd(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)
{
- PyObject *new, *ret;
+ PyObject *new, *ret;
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
- ret = PyArray_GenericAccumulateFunction((PyAO *)new,
- n_ops.multiply, axis,
- rtype, out);
- Py_DECREF(new);
- return ret;
+ ret = PyArray_GenericAccumulateFunction((PyAO *)new,
+ n_ops.multiply, axis,
+ rtype, out);
+ Py_DECREF(new);
+ return ret;
}
/*MULTIARRAY_API
- Any
+ Any
*/
static PyObject *
PyArray_Any(PyArrayObject *self, int axis, PyArrayObject *out)
{
- PyObject *new, *ret;
+ PyObject *new, *ret;
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
- ret = PyArray_GenericReduceFunction((PyAO *)new,
- n_ops.logical_or, axis,
- PyArray_BOOL, out);
- Py_DECREF(new);
- return ret;
+ ret = PyArray_GenericReduceFunction((PyAO *)new,
+ n_ops.logical_or, axis,
+ PyArray_BOOL, out);
+ Py_DECREF(new);
+ return ret;
}
/*MULTIARRAY_API
- All
+ All
*/
static PyObject *
PyArray_All(PyArrayObject *self, int axis, PyArrayObject *out)
{
- PyObject *new, *ret;
+ PyObject *new, *ret;
- if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
+ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL;
- ret = PyArray_GenericReduceFunction((PyAO *)new,
- n_ops.logical_and, axis,
- PyArray_BOOL, out);
- Py_DECREF(new);
- return ret;
+ ret = PyArray_GenericReduceFunction((PyAO *)new,
+ n_ops.logical_and, axis,
+ PyArray_BOOL, out);
+ Py_DECREF(new);
+ return ret;
}
/*MULTIARRAY_API
- Compress
+ Compress
*/
static PyObject *
PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis,
PyArrayObject *out)
{
- PyArrayObject *cond;
- PyObject *res, *ret;
+ PyArrayObject *cond;
+ PyObject *res, *ret;
- cond = (PyAO *)PyArray_FROM_O(condition);
- if (cond == NULL) return NULL;
+ cond = (PyAO *)PyArray_FROM_O(condition);
+ if (cond == NULL) return NULL;
- if (cond->nd != 1) {
- Py_DECREF(cond);
- PyErr_SetString(PyExc_ValueError,
- "condition must be 1-d array");
- return NULL;
- }
-
- res = PyArray_Nonzero(cond);
+ if (cond->nd != 1) {
Py_DECREF(cond);
- if (res == NULL) return res;
- ret = PyArray_TakeFrom(self, PyTuple_GET_ITEM(res, 0), axis,
- out, NPY_RAISE);
- Py_DECREF(res);
- return ret;
+ PyErr_SetString(PyExc_ValueError,
+ "condition must be 1-d array");
+ return NULL;
+ }
+
+ res = PyArray_Nonzero(cond);
+ Py_DECREF(cond);
+ if (res == NULL) return res;
+ ret = PyArray_TakeFrom(self, PyTuple_GET_ITEM(res, 0), axis,
+ out, NPY_RAISE);
+ Py_DECREF(res);
+ return ret;
}
/*MULTIARRAY_API
- Nonzero
+ Nonzero
*/
static PyObject *
PyArray_Nonzero(PyArrayObject *self)
{
- int n=self->nd, j;
- intp count=0, i, size;
- PyArrayIterObject *it=NULL;
- PyObject *ret=NULL, *item;
- intp *dptr[MAX_DIMS];
+ int n=self->nd, j;
+ intp count=0, i, size;
+ PyArrayIterObject *it=NULL;
+ PyObject *ret=NULL, *item;
+ intp *dptr[MAX_DIMS];
- it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
- if (it==NULL) return NULL;
+ it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
+ if (it==NULL) return NULL;
- size = it->size;
- for (i=0; i<size; i++) {
- if (self->descr->f->nonzero(it->dataptr, self)) count++;
- PyArray_ITER_NEXT(it);
- }
+ size = it->size;
+ for (i=0; i<size; i++) {
+ if (self->descr->f->nonzero(it->dataptr, self)) count++;
+ PyArray_ITER_NEXT(it);
+ }
- PyArray_ITER_RESET(it);
- ret = PyTuple_New(n);
- if (ret == NULL) goto fail;
- for (j=0; j<n; j++) {
- item = PyArray_New(self->ob_type, 1, &count,
- PyArray_INTP, NULL, NULL, 0, 0,
- (PyObject *)self);
- if (item == NULL) goto fail;
- PyTuple_SET_ITEM(ret, j, item);
- dptr[j] = (intp *)PyArray_DATA(item);
- }
- if (n==1) {
- for (i=0; i<size; i++) {
- if (self->descr->f->nonzero(it->dataptr, self))
- *(dptr[0])++ = i;
- PyArray_ITER_NEXT(it);
- }
- }
- else {
- /* reset contiguous so that coordinates gets updated */
- it->contiguous = 0;
- for (i=0; i<size; i++) {
- if (self->descr->f->nonzero(it->dataptr, self))
- for (j=0; j<n; j++)
- *(dptr[j])++ = it->coordinates[j];
- PyArray_ITER_NEXT(it);
- }
- }
-
- Py_DECREF(it);
- return ret;
+ PyArray_ITER_RESET(it);
+ ret = PyTuple_New(n);
+ if (ret == NULL) goto fail;
+ for (j=0; j<n; j++) {
+ item = PyArray_New(self->ob_type, 1, &count,
+ PyArray_INTP, NULL, NULL, 0, 0,
+ (PyObject *)self);
+ if (item == NULL) goto fail;
+ PyTuple_SET_ITEM(ret, j, item);
+ dptr[j] = (intp *)PyArray_DATA(item);
+ }
+ if (n==1) {
+ for (i=0; i<size; i++) {
+ if (self->descr->f->nonzero(it->dataptr, self))
+ *(dptr[0])++ = i;
+ PyArray_ITER_NEXT(it);
+ }
+ }
+ else {
+ /* reset contiguous so that coordinates gets updated */
+ it->contiguous = 0;
+ for (i=0; i<size; i++) {
+ if (self->descr->f->nonzero(it->dataptr, self))
+ for (j=0; j<n; j++)
+ *(dptr[j])++ = it->coordinates[j];
+ PyArray_ITER_NEXT(it);
+ }
+ }
+
+ Py_DECREF(it);
+ return ret;
fail:
- Py_XDECREF(ret);
- Py_XDECREF(it);
- return NULL;
+ Py_XDECREF(ret);
+ Py_XDECREF(it);
+ return NULL;
}
static PyObject *
_slow_array_clip(PyArrayObject *self, PyObject *min, PyObject *max, PyArrayObject *out)
{
- PyObject *selector=NULL, *newtup=NULL, *ret=NULL;
- PyObject *res1=NULL, *res2=NULL, *res3=NULL;
- PyObject *two;
-
- two = PyInt_FromLong((long)2);
- res1 = PyArray_GenericBinaryFunction(self, max, n_ops.greater);
- res2 = PyArray_GenericBinaryFunction(self, min, n_ops.less);
- if ((res1 == NULL) || (res2 == NULL)) {
- Py_DECREF(two);
- Py_XDECREF(res1);
- Py_XDECREF(res2);
- return NULL;
- }
- res3 = PyNumber_Multiply(two, res1);
- Py_DECREF(two);
- Py_DECREF(res1);
- if (res3 == NULL) return NULL;
-
- selector = PyArray_EnsureAnyArray(PyNumber_Add(res2, res3));
- Py_DECREF(res2);
- Py_DECREF(res3);
- if (selector == NULL) return NULL;
-
- newtup = Py_BuildValue("(OOO)", (PyObject *)self, min, max);
- if (newtup == NULL) {Py_DECREF(selector); return NULL;}
- ret = PyArray_Choose((PyAO *)selector, newtup, out, NPY_RAISE);
- Py_DECREF(selector);
- Py_DECREF(newtup);
- return ret;
+ PyObject *selector=NULL, *newtup=NULL, *ret=NULL;
+ PyObject *res1=NULL, *res2=NULL, *res3=NULL;
+ PyObject *two;
+
+ two = PyInt_FromLong((long)2);
+ res1 = PyArray_GenericBinaryFunction(self, max, n_ops.greater);
+ res2 = PyArray_GenericBinaryFunction(self, min, n_ops.less);
+ if ((res1 == NULL) || (res2 == NULL)) {
+ Py_DECREF(two);
+ Py_XDECREF(res1);
+ Py_XDECREF(res2);
+ return NULL;
+ }
+ res3 = PyNumber_Multiply(two, res1);
+ Py_DECREF(two);
+ Py_DECREF(res1);
+ if (res3 == NULL) return NULL;
+
+ selector = PyArray_EnsureAnyArray(PyNumber_Add(res2, res3));
+ Py_DECREF(res2);
+ Py_DECREF(res3);
+ if (selector == NULL) return NULL;
+
+ newtup = Py_BuildValue("(OOO)", (PyObject *)self, min, max);
+ if (newtup == NULL) {Py_DECREF(selector); return NULL;}
+ ret = PyArray_Choose((PyAO *)selector, newtup, out, NPY_RAISE);
+ Py_DECREF(selector);
+ Py_DECREF(newtup);
+ return ret;
}
/*MULTIARRAY_API
- Clip
+ Clip
*/
static PyObject *
PyArray_Clip(PyArrayObject *self, PyObject *min, PyObject *max, PyArrayObject *out)
{
- PyArray_FastClipFunc *func;
- int outgood=0, ingood=0;
- PyArrayObject *maxa=NULL;
- PyArrayObject *mina=NULL;
- PyArrayObject *newout=NULL, *newin=NULL;
- PyArray_Descr *indescr, *newdescr;
- PyObject *zero;
-
- func = self->descr->f->fastclip;
- if (func == NULL || !PyArray_CheckAnyScalar(min) ||
- !PyArray_CheckAnyScalar(max))
- return _slow_array_clip(self, min, max, out);
-
- /* Use the fast scalar clip function */
-
- /* First we need to figure out the correct type */
- indescr = PyArray_DescrFromObject(min, NULL);
- if (indescr == NULL) return NULL;
- newdescr = PyArray_DescrFromObject(max, indescr);
+ PyArray_FastClipFunc *func;
+ int outgood=0, ingood=0;
+ PyArrayObject *maxa=NULL;
+ PyArrayObject *mina=NULL;
+ PyArrayObject *newout=NULL, *newin=NULL;
+ PyArray_Descr *indescr, *newdescr;
+ PyObject *zero;
+
+ func = self->descr->f->fastclip;
+ if (func == NULL || !PyArray_CheckAnyScalar(min) ||
+ !PyArray_CheckAnyScalar(max))
+ return _slow_array_clip(self, min, max, out);
+
+ /* Use the fast scalar clip function */
+
+ /* First we need to figure out the correct type */
+ indescr = PyArray_DescrFromObject(min, NULL);
+ if (indescr == NULL) return NULL;
+ newdescr = PyArray_DescrFromObject(max, indescr);
+ Py_DECREF(indescr);
+
+ if (newdescr == NULL) return NULL;
+ /* Use the scalar descriptor only if it is of a bigger
+ KIND than the input array (and then find the
+ type that matches both).
+ */
+ if (PyArray_ScalarKind(newdescr->type_num, NULL) >
+ PyArray_ScalarKind(self->descr->type_num, NULL)) {
+ indescr = _array_small_type(newdescr, self->descr);
+ func = indescr->f->fastclip;
+ }
+ else {
+ indescr = self->descr;
+ Py_INCREF(indescr);
+ }
+ Py_DECREF(newdescr);
+
+ if (!PyDataType_ISNOTSWAPPED(indescr)) {
+ PyArray_Descr *descr2;
+ descr2 = PyArray_DescrNewByteorder(indescr, '=');
Py_DECREF(indescr);
+ if (descr2 == NULL) goto fail;
+ indescr = descr2;
+ }
- if (newdescr == NULL) return NULL;
- /* Use the scalar descriptor only if it is of a bigger
- KIND than the input array (and then find the
- type that matches both).
- */
- if (PyArray_ScalarKind(newdescr->type_num, NULL) >
- PyArray_ScalarKind(self->descr->type_num, NULL)) {
- indescr = _array_small_type(newdescr, self->descr);
- func = indescr->f->fastclip;
+ /* Convert max to an array */
+ maxa = (NPY_AO *)PyArray_FromAny(max, indescr, 0, 0,
+ NPY_DEFAULT, NULL);
+ if (maxa == NULL) return NULL;
+
+
+ /* If we are unsigned, then make sure min is not <0 */
+ /* This is to match the behavior of
+ _slow_array_clip
+
+ We allow min and max to go beyond the limits
+ for other data-types in which case they
+ are interpreted as their modular counterparts.
+ */
+ if (PyArray_ISUNSIGNED(self)) {
+ int cmp;
+ zero = PyInt_FromLong(0);
+ cmp = PyObject_RichCompareBool(min, zero, Py_LT);
+ if (cmp == -1) { Py_DECREF(zero); goto fail;}
+ if (cmp == 1) {
+ min = zero;
}
else {
- indescr = self->descr;
- Py_INCREF(indescr);
- }
- Py_DECREF(newdescr);
-
- if (!PyDataType_ISNOTSWAPPED(indescr)) {
- PyArray_Descr *descr2;
- descr2 = PyArray_DescrNewByteorder(indescr, '=');
- Py_DECREF(indescr);
- if (descr2 == NULL) goto fail;
- indescr = descr2;
+ Py_DECREF(zero);
+ Py_INCREF(min);
}
+ }
+ else {
+ Py_INCREF(min);
+ }
- /* Convert max to an array */
- maxa = (NPY_AO *)PyArray_FromAny(max, indescr, 0, 0,
- NPY_DEFAULT, NULL);
- if (maxa == NULL) return NULL;
+ /* Convert min to an array */
+ Py_INCREF(indescr);
+ mina = (NPY_AO *)PyArray_FromAny(min, indescr, 0, 0,
+ NPY_DEFAULT, NULL);
+ Py_DECREF(min);
+ if (mina == NULL) goto fail;
- /* If we are unsigned, then make sure min is not <0 */
- /* This is to match the behavior of
- _slow_array_clip
+ /* Check to see if input is single-segment, aligned,
+ and in native byteorder */
+ if (PyArray_ISONESEGMENT(self) && PyArray_CHKFLAGS(self, ALIGNED) &&
+ PyArray_ISNOTSWAPPED(self) && (self->descr == indescr))
+ ingood = 1;
- We allow min and max to go beyond the limits
- for other data-types in which case they
- are interpreted as their modular counterparts.
- */
- if (PyArray_ISUNSIGNED(self)) {
- int cmp;
- zero = PyInt_FromLong(0);
- cmp = PyObject_RichCompareBool(min, zero, Py_LT);
- if (cmp == -1) { Py_DECREF(zero); goto fail;}
- if (cmp == 1) {
- min = zero;
- }
- else {
- Py_DECREF(zero);
- Py_INCREF(min);
- }
- }
- else {
- Py_INCREF(min);
- }
-
- /* Convert min to an array */
+ if (!ingood) {
+ int flags;
+ if (PyArray_ISFORTRAN(self)) flags = NPY_FARRAY;
+ else flags = NPY_CARRAY;
Py_INCREF(indescr);
- mina = (NPY_AO *)PyArray_FromAny(min, indescr, 0, 0,
- NPY_DEFAULT, NULL);
- Py_DECREF(min);
- if (mina == NULL) goto fail;
-
-
- /* Check to see if input is single-segment, aligned,
- and in native byteorder */
- if (PyArray_ISONESEGMENT(self) && PyArray_CHKFLAGS(self, ALIGNED) &&
- PyArray_ISNOTSWAPPED(self) && (self->descr == indescr))
- ingood = 1;
-
- if (!ingood) {
- int flags;
- if (PyArray_ISFORTRAN(self)) flags = NPY_FARRAY;
- else flags = NPY_CARRAY;
- Py_INCREF(indescr);
- newin = (NPY_AO *)PyArray_FromArray(self, indescr, flags);
- if (newin == NULL) goto fail;
- }
- else {
- newin = self;
- Py_INCREF(newin);
- }
+ newin = (NPY_AO *)PyArray_FromArray(self, indescr, flags);
+ if (newin == NULL) goto fail;
+ }
+ else {
+ newin = self;
+ Py_INCREF(newin);
+ }
- /* At this point, newin is a single-segment, aligned, and correct
- byte-order array of the correct type
+ /* At this point, newin is a single-segment, aligned, and correct
+ byte-order array of the correct type
- if ingood == 0, then it is a copy, otherwise,
- it is the original input.
- */
+ if ingood == 0, then it is a copy, otherwise,
+ it is the original input.
+ */
- /* If we have already made a copy of the data, then use
- that as the output array
- */
- if (out == NULL && !ingood) {
- out = newin;
- }
+ /* If we have already made a copy of the data, then use
+ that as the output array
+ */
+ if (out == NULL && !ingood) {
+ out = newin;
+ }
- /* Now, we know newin is a usable array for fastclip,
- we need to make sure the output array is available
- and usable */
- if (out == NULL) {
- Py_INCREF(indescr);
- out = (NPY_AO*)PyArray_NewFromDescr(self->ob_type,
- indescr, self->nd,
- self->dimensions,
- NULL, NULL,
- PyArray_ISFORTRAN(self),
- NULL);
- if (out == NULL) goto fail;
- outgood = 1;
- }
- else Py_INCREF(out);
- /* Input is good at this point */
- if (out == newin) {
- outgood = 1;
- }
- if (!outgood && PyArray_ISONESEGMENT(out) &&
- PyArray_CHKFLAGS(out, ALIGNED) && PyArray_ISNOTSWAPPED(out) &&
- PyArray_EquivTypes(out->descr, indescr)) {
- outgood = 1;
- }
-
- /* Do we still not have a suitable output array? */
- /* Create one, now */
- if (!outgood) {
- int oflags;
- if (PyArray_ISFORTRAN(out))
- oflags = NPY_FARRAY;
- else
- oflags = NPY_CARRAY;
- oflags |= NPY_UPDATEIFCOPY | NPY_FORCECAST;
- Py_INCREF(indescr);
- newout = (NPY_AO*)PyArray_FromArray(out, indescr, oflags);
- if (newout == NULL) goto fail;
- }
- else {
- newout = out;
- Py_INCREF(newout);
- }
+ /* Now, we know newin is a usable array for fastclip,
+ we need to make sure the output array is available
+ and usable */
+ if (out == NULL) {
+ Py_INCREF(indescr);
+ out = (NPY_AO*)PyArray_NewFromDescr(self->ob_type,
+ indescr, self->nd,
+ self->dimensions,
+ NULL, NULL,
+ PyArray_ISFORTRAN(self),
+ NULL);
+ if (out == NULL) goto fail;
+ outgood = 1;
+ }
+ else Py_INCREF(out);
+ /* Input is good at this point */
+ if (out == newin) {
+ outgood = 1;
+ }
+ if (!outgood && PyArray_ISONESEGMENT(out) &&
+ PyArray_CHKFLAGS(out, ALIGNED) && PyArray_ISNOTSWAPPED(out) &&
+ PyArray_EquivTypes(out->descr, indescr)) {
+ outgood = 1;
+ }
- /* make sure the shape of the output array is the same */
- if (!PyArray_SAMESHAPE(newin, newout)) {
- PyErr_SetString(PyExc_ValueError, "clip: Output array must have the"
- "same shape as the input.");
- goto fail;
- }
+ /* Do we still not have a suitable output array? */
+ /* Create one, now */
+ if (!outgood) {
+ int oflags;
+ if (PyArray_ISFORTRAN(out))
+ oflags = NPY_FARRAY;
+ else
+ oflags = NPY_CARRAY;
+ oflags |= NPY_UPDATEIFCOPY | NPY_FORCECAST;
+ Py_INCREF(indescr);
+ newout = (NPY_AO*)PyArray_FromArray(out, indescr, oflags);
+ if (newout == NULL) goto fail;
+ }
+ else {
+ newout = out;
+ Py_INCREF(newout);
+ }
- if (newout->data != newin->data) {
- memcpy(newout->data, newin->data, PyArray_NBYTES(newin));
- }
+ /* make sure the shape of the output array is the same */
+ if (!PyArray_SAMESHAPE(newin, newout)) {
+ PyErr_SetString(PyExc_ValueError, "clip: Output array must have the"
+ "same shape as the input.");
+ goto fail;
+ }
- /* Now we can call the fast-clip function */
+ if (newout->data != newin->data) {
+ memcpy(newout->data, newin->data, PyArray_NBYTES(newin));
+ }
- func(newin->data, PyArray_SIZE(newin), mina->data, maxa->data,
- newout->data);
+ /* Now we can call the fast-clip function */
- /* Clean up temporary variables */
- Py_DECREF(mina);
- Py_DECREF(maxa);
- Py_DECREF(newin);
- /* Copy back into out if out was not already a nice array. */
- Py_DECREF(newout);
- return (PyObject *)out;
+ func(newin->data, PyArray_SIZE(newin), mina->data, maxa->data,
+ newout->data);
+
+ /* Clean up temporary variables */
+ Py_DECREF(mina);
+ Py_DECREF(maxa);
+ Py_DECREF(newin);
+ /* Copy back into out if out was not already a nice array. */
+ Py_DECREF(newout);
+ return (PyObject *)out;
fail:
- Py_XDECREF(maxa);
- Py_XDECREF(mina);
- Py_XDECREF(newin);
- PyArray_XDECREF_ERR(newout);
- return NULL;
+ Py_XDECREF(maxa);
+ Py_XDECREF(mina);
+ Py_XDECREF(newin);
+ PyArray_XDECREF_ERR(newout);
+ return NULL;
}
/*MULTIARRAY_API
- Conjugate
+ Conjugate
*/
static PyObject *
PyArray_Conjugate(PyArrayObject *self, PyArrayObject *out)
{
- if (PyArray_ISCOMPLEX(self)) {
- if (out == NULL) {
- return PyArray_GenericUnaryFunction(self,
- n_ops.conjugate);
- }
- else {
- return PyArray_GenericBinaryFunction(self,
- (PyObject *)out,
- n_ops.conjugate);
- }
- }
- else {
- PyArrayObject *ret;
- if (out) {
- if (PyArray_CopyAnyInto(out, self)< 0)
- return NULL;
- ret = out;
- }
- else ret = self;
- Py_INCREF(ret);
- return (PyObject *)ret;
- }
+ if (PyArray_ISCOMPLEX(self)) {
+ if (out == NULL) {
+ return PyArray_GenericUnaryFunction(self,
+ n_ops.conjugate);
+ }
+ else {
+ return PyArray_GenericBinaryFunction(self,
+ (PyObject *)out,
+ n_ops.conjugate);
+ }
+ }
+ else {
+ PyArrayObject *ret;
+ if (out) {
+ if (PyArray_CopyAnyInto(out, self)< 0)
+ return NULL;
+ ret = out;
+ }
+ else ret = self;
+ Py_INCREF(ret);
+ return (PyObject *)ret;
+ }
}
/*MULTIARRAY_API
- Trace
+ Trace
*/
static PyObject *
PyArray_Trace(PyArrayObject *self, int offset, int axis1, int axis2,
int rtype, PyArrayObject *out)
{
- PyObject *diag=NULL, *ret=NULL;
+ PyObject *diag=NULL, *ret=NULL;
- diag = PyArray_Diagonal(self, offset, axis1, axis2);
- if (diag == NULL) return NULL;
- ret = PyArray_GenericReduceFunction((PyAO *)diag, n_ops.add, -1, rtype, out);
- Py_DECREF(diag);
- return ret;
+ diag = PyArray_Diagonal(self, offset, axis1, axis2);
+ if (diag == NULL) return NULL;
+ ret = PyArray_GenericReduceFunction((PyAO *)diag, n_ops.add, -1, rtype, out);
+ Py_DECREF(diag);
+ return ret;
}
/*MULTIARRAY_API
- Diagonal
+ Diagonal
*/
static PyObject *
PyArray_Diagonal(PyArrayObject *self, int offset, int axis1, int axis2)
{
- int n = self->nd;
- PyObject *new;
- PyArray_Dims newaxes;
- intp dims[MAX_DIMS];
- int i, pos;
-
- newaxes.ptr = dims;
- if (n < 2) {
- PyErr_SetString(PyExc_ValueError,
- "array.ndim must be >= 2");
- return NULL;
- }
- if (axis1 < 0) axis1 += n;
- if (axis2 < 0) axis2 += n;
- if ((axis1 == axis2) || (axis1 < 0) || (axis1 >= n) || \
- (axis2 < 0) || (axis2 >= n)) {
- PyErr_Format(PyExc_ValueError, "axis1(=%d) and axis2(=%d) "\
- "must be different and within range (nd=%d)",
- axis1, axis2, n);
- return NULL;
- }
-
- newaxes.len = n;
- /* insert at the end */
- newaxes.ptr[n-2] = axis1;
- newaxes.ptr[n-1] = axis2;
- pos = 0;
- for (i=0; i<n; i++) {
- if ((i==axis1) || (i==axis2)) continue;
- newaxes.ptr[pos++] = i;
- }
- new = PyArray_Transpose(self, &newaxes);
- if (new == NULL) return NULL;
- self = (PyAO *)new;
-
- if (n == 2) {
- PyObject *a=NULL, *indices=NULL, *ret=NULL;
- intp n1, n2, start, stop, step, count;
- intp *dptr;
- n1 = self->dimensions[0];
- n2 = self->dimensions[1];
- step = n2+1;
- if (offset < 0) {
- start = -n2 * offset;
- stop = MIN(n2, n1+offset)*(n2+1) - n2*offset;
- }
- else {
- start = offset;
- stop = MIN(n1, n2-offset)*(n2+1) + offset;
- }
-
- /* count = ceil((stop-start)/step) */
- count = ((stop-start) / step) + (((stop-start) % step) != 0);
-
- indices = PyArray_New(&PyArray_Type, 1, &count,
- PyArray_INTP, NULL, NULL, 0, 0, NULL);
- if (indices == NULL) {
- Py_DECREF(self); return NULL;
- }
- dptr = (intp *)PyArray_DATA(indices);
- for (n1=start; n1<stop; n1+=step) *dptr++ = n1;
- a = PyArray_IterNew((PyObject *)self);
- Py_DECREF(self);
- if (a == NULL) {Py_DECREF(indices); return NULL;}
- ret = PyObject_GetItem(a, indices);
- Py_DECREF(a);
- Py_DECREF(indices);
- return ret;
- }
-
- else {
- /*
- my_diagonal = []
- for i in range (s [0]) :
- my_diagonal.append (diagonal (a [i], offset))
- return array (my_diagonal)
- */
- PyObject *mydiagonal=NULL, *new=NULL, *ret=NULL, *sel=NULL;
- intp i, n1;
- int res;
- PyArray_Descr *typecode;
-
- typecode = self->descr;
-
- mydiagonal = PyList_New(0);
- if (mydiagonal == NULL) {Py_DECREF(self); return NULL;}
- n1 = self->dimensions[0];
- for (i=0; i<n1; i++) {
- new = PyInt_FromLong((long) i);
- sel = PyArray_EnsureAnyArray(PyObject_GetItem((PyObject *)self, new));
- Py_DECREF(new);
- if (sel == NULL) {
- Py_DECREF(self);
- Py_DECREF(mydiagonal);
- return NULL;
- }
- new = PyArray_Diagonal((PyAO *)sel, offset, n-3, n-2);
- Py_DECREF(sel);
- if (new == NULL) {
- Py_DECREF(self);
- Py_DECREF(mydiagonal);
- return NULL;
- }
- res = PyList_Append(mydiagonal, new);
- Py_DECREF(new);
- if (res < 0) {
- Py_DECREF(self);
- Py_DECREF(mydiagonal);
- return NULL;
- }
- }
- Py_DECREF(self);
- Py_INCREF(typecode);
- ret = PyArray_FromAny(mydiagonal, typecode, 0, 0, 0, NULL);
- Py_DECREF(mydiagonal);
- return ret;
- }
+ int n = self->nd;
+ PyObject *new;
+ PyArray_Dims newaxes;
+ intp dims[MAX_DIMS];
+ int i, pos;
+
+ newaxes.ptr = dims;
+ if (n < 2) {
+ PyErr_SetString(PyExc_ValueError,
+ "array.ndim must be >= 2");
+ return NULL;
+ }
+ if (axis1 < 0) axis1 += n;
+ if (axis2 < 0) axis2 += n;
+ if ((axis1 == axis2) || (axis1 < 0) || (axis1 >= n) || \
+ (axis2 < 0) || (axis2 >= n)) {
+ PyErr_Format(PyExc_ValueError, "axis1(=%d) and axis2(=%d) "\
+ "must be different and within range (nd=%d)",
+ axis1, axis2, n);
+ return NULL;
+ }
+
+ newaxes.len = n;
+ /* insert at the end */
+ newaxes.ptr[n-2] = axis1;
+ newaxes.ptr[n-1] = axis2;
+ pos = 0;
+ for (i=0; i<n; i++) {
+ if ((i==axis1) || (i==axis2)) continue;
+ newaxes.ptr[pos++] = i;
+ }
+ new = PyArray_Transpose(self, &newaxes);
+ if (new == NULL) return NULL;
+ self = (PyAO *)new;
+
+ if (n == 2) {
+ PyObject *a=NULL, *indices=NULL, *ret=NULL;
+ intp n1, n2, start, stop, step, count;
+ intp *dptr;
+ n1 = self->dimensions[0];
+ n2 = self->dimensions[1];
+ step = n2+1;
+ if (offset < 0) {
+ start = -n2 * offset;
+ stop = MIN(n2, n1+offset)*(n2+1) - n2*offset;
+ }
+ else {
+ start = offset;
+ stop = MIN(n1, n2-offset)*(n2+1) + offset;
+ }
+
+ /* count = ceil((stop-start)/step) */
+ count = ((stop-start) / step) + (((stop-start) % step) != 0);
+
+ indices = PyArray_New(&PyArray_Type, 1, &count,
+ PyArray_INTP, NULL, NULL, 0, 0, NULL);
+ if (indices == NULL) {
+ Py_DECREF(self); return NULL;
+ }
+ dptr = (intp *)PyArray_DATA(indices);
+ for (n1=start; n1<stop; n1+=step) *dptr++ = n1;
+ a = PyArray_IterNew((PyObject *)self);
+ Py_DECREF(self);
+ if (a == NULL) {Py_DECREF(indices); return NULL;}
+ ret = PyObject_GetItem(a, indices);
+ Py_DECREF(a);
+ Py_DECREF(indices);
+ return ret;
+ }
+
+ else {
+ /*
+ my_diagonal = []
+ for i in range (s [0]) :
+ my_diagonal.append (diagonal (a [i], offset))
+ return array (my_diagonal)
+ */
+ PyObject *mydiagonal=NULL, *new=NULL, *ret=NULL, *sel=NULL;
+ intp i, n1;
+ int res;
+ PyArray_Descr *typecode;
+
+ typecode = self->descr;
+
+ mydiagonal = PyList_New(0);
+ if (mydiagonal == NULL) {Py_DECREF(self); return NULL;}
+ n1 = self->dimensions[0];
+ for (i=0; i<n1; i++) {
+ new = PyInt_FromLong((long) i);
+ sel = PyArray_EnsureAnyArray(PyObject_GetItem((PyObject *)self, new));
+ Py_DECREF(new);
+ if (sel == NULL) {
+ Py_DECREF(self);
+ Py_DECREF(mydiagonal);
+ return NULL;
+ }
+ new = PyArray_Diagonal((PyAO *)sel, offset, n-3, n-2);
+ Py_DECREF(sel);
+ if (new == NULL) {
+ Py_DECREF(self);
+ Py_DECREF(mydiagonal);
+ return NULL;
+ }
+ res = PyList_Append(mydiagonal, new);
+ Py_DECREF(new);
+ if (res < 0) {
+ Py_DECREF(self);
+ Py_DECREF(mydiagonal);
+ return NULL;
+ }
+ }
+ Py_DECREF(self);
+ Py_INCREF(typecode);
+ ret = PyArray_FromAny(mydiagonal, typecode, 0, 0, 0, NULL);
+ Py_DECREF(mydiagonal);
+ return ret;
+ }
}
/* simulates a C-style 1-3 dimensional array which can be accesed using
- ptr[i] or ptr[i][j] or ptr[i][j][k] -- requires pointer allocation
- for 2-d and 3-d.
+ ptr[i] or ptr[i][j] or ptr[i][j][k] -- requires pointer allocation
+ for 2-d and 3-d.
- For 2-d and up, ptr is NOT equivalent to a statically defined
- 2-d or 3-d array. In particular, it cannot be passed into a
- function that requires a true pointer to a fixed-size array.
+ For 2-d and up, ptr is NOT equivalent to a statically defined
+ 2-d or 3-d array. In particular, it cannot be passed into a
+ function that requires a true pointer to a fixed-size array.
*/
/* steals a reference to typedescr -- can be NULL*/
/*MULTIARRAY_API
- Simulat a C-array
+ Simulat a C-array
*/
static int
PyArray_AsCArray(PyObject **op, void *ptr, intp *dims, int nd,
- PyArray_Descr* typedescr)
-{
- PyArrayObject *ap;
- intp n, m, i, j;
- char **ptr2;
- char ***ptr3;
-
- if ((nd < 1) || (nd > 3)) {
- PyErr_SetString(PyExc_ValueError,
- "C arrays of only 1-3 dimensions available");
- Py_XDECREF(typedescr);
- return -1;
- }
- if ((ap = (PyArrayObject*)PyArray_FromAny(*op, typedescr, nd, nd,
- CARRAY, NULL)) == NULL)
- return -1;
- switch(nd) {
- case 1:
- *((char **)ptr) = ap->data;
- break;
- case 2:
- n = ap->dimensions[0];
- ptr2 = (char **)_pya_malloc(n * sizeof(char *));
- if (!ptr2) goto fail;
- for (i=0; i<n; i++) {
- ptr2[i] = ap->data + i*ap->strides[0];
- }
- *((char ***)ptr) = ptr2;
- break;
- case 3:
- n = ap->dimensions[0];
- m = ap->dimensions[1];
- ptr3 = (char ***)_pya_malloc(n*(m+1) * sizeof(char *));
- if (!ptr3) goto fail;
- for (i=0; i<n; i++) {
- ptr3[i] = ptr3[n + (m-1)*i];
- for (j=0; j<m; j++) {
- ptr3[i][j] = ap->data + i*ap->strides[0] + \
- j*ap->strides[1];
- }
- }
- *((char ****)ptr) = ptr3;
- }
- memcpy(dims, ap->dimensions, nd*sizeof(intp));
- *op = (PyObject *)ap;
- return 0;
+ PyArray_Descr* typedescr)
+{
+ PyArrayObject *ap;
+ intp n, m, i, j;
+ char **ptr2;
+ char ***ptr3;
+
+ if ((nd < 1) || (nd > 3)) {
+ PyErr_SetString(PyExc_ValueError,
+ "C arrays of only 1-3 dimensions available");
+ Py_XDECREF(typedescr);
+ return -1;
+ }
+ if ((ap = (PyArrayObject*)PyArray_FromAny(*op, typedescr, nd, nd,
+ CARRAY, NULL)) == NULL)
+ return -1;
+ switch(nd) {
+ case 1:
+ *((char **)ptr) = ap->data;
+ break;
+ case 2:
+ n = ap->dimensions[0];
+ ptr2 = (char **)_pya_malloc(n * sizeof(char *));
+ if (!ptr2) goto fail;
+ for (i=0; i<n; i++) {
+ ptr2[i] = ap->data + i*ap->strides[0];
+ }
+ *((char ***)ptr) = ptr2;
+ break;
+ case 3:
+ n = ap->dimensions[0];
+ m = ap->dimensions[1];
+ ptr3 = (char ***)_pya_malloc(n*(m+1) * sizeof(char *));
+ if (!ptr3) goto fail;
+ for (i=0; i<n; i++) {
+ ptr3[i] = ptr3[n + (m-1)*i];
+ for (j=0; j<m; j++) {
+ ptr3[i][j] = ap->data + i*ap->strides[0] + \
+ j*ap->strides[1];
+ }
+ }
+ *((char ****)ptr) = ptr3;
+ }
+ memcpy(dims, ap->dimensions, nd*sizeof(intp));
+ *op = (PyObject *)ap;
+ return 0;
fail:
- PyErr_SetString(PyExc_MemoryError, "no memory");
- return -1;
+ PyErr_SetString(PyExc_MemoryError, "no memory");
+ return -1;
}
/* Deprecated --- Use PyArray_AsCArray instead */
/*MULTIARRAY_API
- Convert to a 1D C-array
+ Convert to a 1D C-array
*/
static int
PyArray_As1D(PyObject **op, char **ptr, int *d1, int typecode)
{
- intp newd1;
- PyArray_Descr *descr;
+ intp newd1;
+ PyArray_Descr *descr;
- descr = PyArray_DescrFromType(typecode);
- if (PyArray_AsCArray(op, (void *)ptr, &newd1, 1, descr) == -1)
- return -1;
- *d1 = (int) newd1;
- return 0;
+ descr = PyArray_DescrFromType(typecode);
+ if (PyArray_AsCArray(op, (void *)ptr, &newd1, 1, descr) == -1)
+ return -1;
+ *d1 = (int) newd1;
+ return 0;
}
/*MULTIARRAY_API
- Convert to a 2D C-array
+ Convert to a 2D C-array
*/
static int
PyArray_As2D(PyObject **op, char ***ptr, int *d1, int *d2, int typecode)
{
- intp newdims[2];
- PyArray_Descr *descr;
+ intp newdims[2];
+ PyArray_Descr *descr;
- descr = PyArray_DescrFromType(typecode);
- if (PyArray_AsCArray(op, (void *)ptr, newdims, 2, descr) == -1)
- return -1;
+ descr = PyArray_DescrFromType(typecode);
+ if (PyArray_AsCArray(op, (void *)ptr, newdims, 2, descr) == -1)
+ return -1;
- *d1 = (int ) newdims[0];
- *d2 = (int ) newdims[1];
- return 0;
+ *d1 = (int ) newdims[0];
+ *d2 = (int ) newdims[1];
+ return 0;
}
/* End Deprecated */
/*MULTIARRAY_API
- Free pointers created if As2D is called
+ Free pointers created if As2D is called
*/
static int
PyArray_Free(PyObject *op, void *ptr)
{
- PyArrayObject *ap = (PyArrayObject *)op;
+ PyArrayObject *ap = (PyArrayObject *)op;
- if ((ap->nd < 1) || (ap->nd > 3))
- return -1;
- if (ap->nd >= 2) {
- _pya_free(ptr);
- }
- Py_DECREF(ap);
- return 0;
+ if ((ap->nd < 1) || (ap->nd > 3))
+ return -1;
+ if (ap->nd >= 2) {
+ _pya_free(ptr);
+ }
+ Py_DECREF(ap);
+ return 0;
}
static PyObject *
_swap_and_concat(PyObject *op, int axis, int n)
{
- PyObject *newtup=NULL;
- PyObject *otmp, *arr;
- int i;
-
- newtup = PyTuple_New(n);
- if (newtup==NULL) return NULL;
- for (i=0; i<n; i++) {
- otmp = PySequence_GetItem(op, i);
- arr = PyArray_FROM_O(otmp);
- Py_DECREF(otmp);
- if (arr==NULL) goto fail;
- otmp = PyArray_SwapAxes((PyArrayObject *)arr, axis, 0);
- Py_DECREF(arr);
- if (otmp == NULL) goto fail;
- PyTuple_SET_ITEM(newtup, i, otmp);
- }
- otmp = PyArray_Concatenate(newtup, 0);
- Py_DECREF(newtup);
- if (otmp == NULL) return NULL;
- arr = PyArray_SwapAxes((PyArrayObject *)otmp, axis, 0);
- Py_DECREF(otmp);
- return arr;
+ PyObject *newtup=NULL;
+ PyObject *otmp, *arr;
+ int i;
+
+ newtup = PyTuple_New(n);
+ if (newtup==NULL) return NULL;
+ for (i=0; i<n; i++) {
+ otmp = PySequence_GetItem(op, i);
+ arr = PyArray_FROM_O(otmp);
+ Py_DECREF(otmp);
+ if (arr==NULL) goto fail;
+ otmp = PyArray_SwapAxes((PyArrayObject *)arr, axis, 0);
+ Py_DECREF(arr);
+ if (otmp == NULL) goto fail;
+ PyTuple_SET_ITEM(newtup, i, otmp);
+ }
+ otmp = PyArray_Concatenate(newtup, 0);
+ Py_DECREF(newtup);
+ if (otmp == NULL) return NULL;
+ arr = PyArray_SwapAxes((PyArrayObject *)otmp, axis, 0);
+ Py_DECREF(otmp);
+ return arr;
fail:
- Py_DECREF(newtup);
- return NULL;
+ Py_DECREF(newtup);
+ return NULL;
}
/*op is a python object supporting the sequence interface.
@@ -1663,355 +1663,355 @@ _swap_and_concat(PyObject *op, int axis, int n)
be flattened before concatenation
*/
/*MULTIARRAY_API
- Concatenate an arbitrary Python sequence into an array.
+ Concatenate an arbitrary Python sequence into an array.
*/
static PyObject *
PyArray_Concatenate(PyObject *op, int axis)
{
- PyArrayObject *ret, **mps;
- PyObject *otmp;
- int i, n, tmp, nd=0, new_dim;
- char *data;
- PyTypeObject *subtype;
- double prior1, prior2;
- intp numbytes;
-
- n = PySequence_Length(op);
- if (n == -1) {
- return NULL;
- }
- if (n == 0) {
- PyErr_SetString(PyExc_ValueError,
- "concatenation of zero-length sequences is "\
- "impossible");
- return NULL;
- }
-
- if ((axis < 0) || ((0 < axis) && (axis < MAX_DIMS)))
- return _swap_and_concat(op, axis, n);
-
- mps = PyArray_ConvertToCommonType(op, &n);
- if (mps == NULL) return NULL;
-
- /* Make sure these arrays are legal to concatenate. */
- /* Must have same dimensions except d0 */
-
- prior1 = PyArray_PRIORITY;
- subtype = &PyArray_Type;
- ret = NULL;
- for(i=0; i<n; i++) {
- if (axis >= MAX_DIMS) {
- otmp = PyArray_Ravel(mps[i],0);
- Py_DECREF(mps[i]);
- mps[i] = (PyArrayObject *)otmp;
- }
- if (mps[i]->ob_type != subtype) {
- prior2 = PyArray_GetPriority((PyObject *)(mps[i]), 0.0);
- if (prior2 > prior1) {
- prior1 = prior2;
- subtype = mps[i]->ob_type;
- }
- }
- }
-
- new_dim = 0;
- for(i=0; i<n; i++) {
- if (mps[i] == NULL) goto fail;
- if (i == 0) nd = mps[i]->nd;
- else {
- if (nd != mps[i]->nd) {
- PyErr_SetString(PyExc_ValueError,
- "arrays must have same "\
- "number of dimensions");
- goto fail;
- }
- if (!PyArray_CompareLists(mps[0]->dimensions+1,
- mps[i]->dimensions+1,
- nd-1)) {
- PyErr_SetString(PyExc_ValueError,
- "array dimensions must "\
- "agree except for d_0");
- goto fail;
- }
- }
- if (nd == 0) {
- PyErr_SetString(PyExc_ValueError,
- "0-d arrays can't be concatenated");
- goto fail;
- }
- new_dim += mps[i]->dimensions[0];
- }
-
- tmp = mps[0]->dimensions[0];
- mps[0]->dimensions[0] = new_dim;
- Py_INCREF(mps[0]->descr);
- ret = (PyArrayObject *)PyArray_NewFromDescr(subtype,
- mps[0]->descr, nd,
- mps[0]->dimensions,
- NULL, NULL, 0,
- (PyObject *)ret);
- mps[0]->dimensions[0] = tmp;
-
- if (ret == NULL) goto fail;
-
- data = ret->data;
- for(i=0; i<n; i++) {
- numbytes = PyArray_NBYTES(mps[i]);
- memcpy(data, mps[i]->data, numbytes);
- data += numbytes;
- }
-
- PyArray_INCREF(ret);
- for(i=0; i<n; i++) Py_XDECREF(mps[i]);
- PyDataMem_FREE(mps);
- return (PyObject *)ret;
+ PyArrayObject *ret, **mps;
+ PyObject *otmp;
+ int i, n, tmp, nd=0, new_dim;
+ char *data;
+ PyTypeObject *subtype;
+ double prior1, prior2;
+ intp numbytes;
+
+ n = PySequence_Length(op);
+ if (n == -1) {
+ return NULL;
+ }
+ if (n == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "concatenation of zero-length sequences is "\
+ "impossible");
+ return NULL;
+ }
+
+ if ((axis < 0) || ((0 < axis) && (axis < MAX_DIMS)))
+ return _swap_and_concat(op, axis, n);
+
+ mps = PyArray_ConvertToCommonType(op, &n);
+ if (mps == NULL) return NULL;
+
+ /* Make sure these arrays are legal to concatenate. */
+ /* Must have same dimensions except d0 */
+
+ prior1 = PyArray_PRIORITY;
+ subtype = &PyArray_Type;
+ ret = NULL;
+ for(i=0; i<n; i++) {
+ if (axis >= MAX_DIMS) {
+ otmp = PyArray_Ravel(mps[i],0);
+ Py_DECREF(mps[i]);
+ mps[i] = (PyArrayObject *)otmp;
+ }
+ if (mps[i]->ob_type != subtype) {
+ prior2 = PyArray_GetPriority((PyObject *)(mps[i]), 0.0);
+ if (prior2 > prior1) {
+ prior1 = prior2;
+ subtype = mps[i]->ob_type;
+ }
+ }
+ }
+
+ new_dim = 0;
+ for(i=0; i<n; i++) {
+ if (mps[i] == NULL) goto fail;
+ if (i == 0) nd = mps[i]->nd;
+ else {
+ if (nd != mps[i]->nd) {
+ PyErr_SetString(PyExc_ValueError,
+ "arrays must have same "\
+ "number of dimensions");
+ goto fail;
+ }
+ if (!PyArray_CompareLists(mps[0]->dimensions+1,
+ mps[i]->dimensions+1,
+ nd-1)) {
+ PyErr_SetString(PyExc_ValueError,
+ "array dimensions must "\
+ "agree except for d_0");
+ goto fail;
+ }
+ }
+ if (nd == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "0-d arrays can't be concatenated");
+ goto fail;
+ }
+ new_dim += mps[i]->dimensions[0];
+ }
+
+ tmp = mps[0]->dimensions[0];
+ mps[0]->dimensions[0] = new_dim;
+ Py_INCREF(mps[0]->descr);
+ ret = (PyArrayObject *)PyArray_NewFromDescr(subtype,
+ mps[0]->descr, nd,
+ mps[0]->dimensions,
+ NULL, NULL, 0,
+ (PyObject *)ret);
+ mps[0]->dimensions[0] = tmp;
+
+ if (ret == NULL) goto fail;
+
+ data = ret->data;
+ for(i=0; i<n; i++) {
+ numbytes = PyArray_NBYTES(mps[i]);
+ memcpy(data, mps[i]->data, numbytes);
+ data += numbytes;
+ }
+
+ PyArray_INCREF(ret);
+ for(i=0; i<n; i++) Py_XDECREF(mps[i]);
+ PyDataMem_FREE(mps);
+ return (PyObject *)ret;
fail:
- Py_XDECREF(ret);
- for(i=0; i<n; i++) Py_XDECREF(mps[i]);
- PyDataMem_FREE(mps);
- return NULL;
+ Py_XDECREF(ret);
+ for(i=0; i<n; i++) Py_XDECREF(mps[i]);
+ PyDataMem_FREE(mps);
+ return NULL;
}
/*MULTIARRAY_API
- SwapAxes
+ SwapAxes
*/
static PyObject *
PyArray_SwapAxes(PyArrayObject *ap, int a1, int a2)
{
- PyArray_Dims new_axes;
- intp dims[MAX_DIMS];
- int n, i, val;
- PyObject *ret;
-
- if (a1 == a2) {
- Py_INCREF(ap);
- return (PyObject *)ap;
- }
-
- n = ap->nd;
- if (n <= 1) {
- Py_INCREF(ap);
- return (PyObject *)ap;
- }
-
- if (a1 < 0) a1 += n;
- if (a2 < 0) a2 += n;
- if ((a1 < 0) || (a1 >= n)) {
- PyErr_SetString(PyExc_ValueError,
- "bad axis1 argument to swapaxes");
- return NULL;
- }
- if ((a2 < 0) || (a2 >= n)) {
- PyErr_SetString(PyExc_ValueError,
- "bad axis2 argument to swapaxes");
- return NULL;
- }
- new_axes.ptr = dims;
- new_axes.len = n;
-
- for (i=0; i<n; i++) {
- if (i == a1) val = a2;
- else if (i == a2) val = a1;
- else val = i;
- new_axes.ptr[i] = val;
- }
- ret = PyArray_Transpose(ap, &new_axes);
- return ret;
+ PyArray_Dims new_axes;
+ intp dims[MAX_DIMS];
+ int n, i, val;
+ PyObject *ret;
+
+ if (a1 == a2) {
+ Py_INCREF(ap);
+ return (PyObject *)ap;
+ }
+
+ n = ap->nd;
+ if (n <= 1) {
+ Py_INCREF(ap);
+ return (PyObject *)ap;
+ }
+
+ if (a1 < 0) a1 += n;
+ if (a2 < 0) a2 += n;
+ if ((a1 < 0) || (a1 >= n)) {
+ PyErr_SetString(PyExc_ValueError,
+ "bad axis1 argument to swapaxes");
+ return NULL;
+ }
+ if ((a2 < 0) || (a2 >= n)) {
+ PyErr_SetString(PyExc_ValueError,
+ "bad axis2 argument to swapaxes");
+ return NULL;
+ }
+ new_axes.ptr = dims;
+ new_axes.len = n;
+
+ for (i=0; i<n; i++) {
+ if (i == a1) val = a2;
+ else if (i == a2) val = a1;
+ else val = i;
+ new_axes.ptr[i] = val;
+ }
+ ret = PyArray_Transpose(ap, &new_axes);
+ return ret;
}
/*MULTIARRAY_API
- Return Transpose.
+ Return Transpose.
*/
static PyObject *
PyArray_Transpose(PyArrayObject *ap, PyArray_Dims *permute)
{
- intp *axes, axis;
- intp i, n;
- intp permutation[MAX_DIMS], reverse_permutation[MAX_DIMS];
- PyArrayObject *ret = NULL;
-
- if (permute == NULL) {
- n = ap->nd;
- for (i=0; i<n; i++) {
- permutation[i] = n-1-i;
- }
- } else {
- n = permute->len;
- axes = permute->ptr;
- if (n != ap->nd) {
- PyErr_SetString(PyExc_ValueError,
- "axes don't match array");
- return NULL;
- }
- for (i=0; i<n; i++) {
- reverse_permutation[i] = -1;
- }
- for (i=0; i<n; i++) {
- axis = axes[i];
- if (axis < 0) axis = ap->nd+axis;
- if (axis < 0 || axis >= ap->nd) {
- PyErr_SetString(PyExc_ValueError,
- "invalid axis for this array");
- return NULL;
- }
- if (reverse_permutation[axis] != -1) {
- PyErr_SetString(PyExc_ValueError,
- "repeated axis in transpose");
- return NULL;
- }
- reverse_permutation[axis] = i;
- permutation[i] = axis;
- }
- for (i=0; i<n; i++) {
- }
- }
+ intp *axes, axis;
+ intp i, n;
+ intp permutation[MAX_DIMS], reverse_permutation[MAX_DIMS];
+ PyArrayObject *ret = NULL;
- /* this allocates memory for dimensions and strides (but fills them
- incorrectly), sets up descr, and points data at ap->data. */
- Py_INCREF(ap->descr);
- ret = (PyArrayObject *)\
- PyArray_NewFromDescr(ap->ob_type,
- ap->descr,
- n, ap->dimensions,
- NULL, ap->data, ap->flags,
- (PyObject *)ap);
- if (ret == NULL) return NULL;
-
- /* point at true owner of memory: */
- ret->base = (PyObject *)ap;
- Py_INCREF(ap);
+ if (permute == NULL) {
+ n = ap->nd;
+ for (i=0; i<n; i++) {
+ permutation[i] = n-1-i;
+ }
+ } else {
+ n = permute->len;
+ axes = permute->ptr;
+ if (n != ap->nd) {
+ PyErr_SetString(PyExc_ValueError,
+ "axes don't match array");
+ return NULL;
+ }
+ for (i=0; i<n; i++) {
+ reverse_permutation[i] = -1;
+ }
+ for (i=0; i<n; i++) {
+ axis = axes[i];
+ if (axis < 0) axis = ap->nd+axis;
+ if (axis < 0 || axis >= ap->nd) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid axis for this array");
+ return NULL;
+ }
+ if (reverse_permutation[axis] != -1) {
+ PyErr_SetString(PyExc_ValueError,
+ "repeated axis in transpose");
+ return NULL;
+ }
+ reverse_permutation[axis] = i;
+ permutation[i] = axis;
+ }
+ for (i=0; i<n; i++) {
+ }
+ }
- /* fix the dimensions and strides of the return-array */
- for(i=0; i<n; i++) {
- ret->dimensions[i] = ap->dimensions[permutation[i]];
- ret->strides[i] = ap->strides[permutation[i]];
- }
- PyArray_UpdateFlags(ret, CONTIGUOUS | FORTRAN);
+ /* this allocates memory for dimensions and strides (but fills them
+ incorrectly), sets up descr, and points data at ap->data. */
+ Py_INCREF(ap->descr);
+ ret = (PyArrayObject *)\
+ PyArray_NewFromDescr(ap->ob_type,
+ ap->descr,
+ n, ap->dimensions,
+ NULL, ap->data, ap->flags,
+ (PyObject *)ap);
+ if (ret == NULL) return NULL;
+
+ /* point at true owner of memory: */
+ ret->base = (PyObject *)ap;
+ Py_INCREF(ap);
+
+ /* fix the dimensions and strides of the return-array */
+ for(i=0; i<n; i++) {
+ ret->dimensions[i] = ap->dimensions[permutation[i]];
+ ret->strides[i] = ap->strides[permutation[i]];
+ }
+ PyArray_UpdateFlags(ret, CONTIGUOUS | FORTRAN);
- return (PyObject *)ret;
+ return (PyObject *)ret;
}
/*MULTIARRAY_API
- Repeat the array.
+ Repeat the array.
*/
static PyObject *
PyArray_Repeat(PyArrayObject *aop, PyObject *op, int axis)
{
- intp *counts;
- intp n, n_outer, i, j, k, chunk, total;
- intp tmp;
- int nd;
- PyArrayObject *repeats=NULL;
- PyObject *ap=NULL;
- PyArrayObject *ret=NULL;
- char *new_data, *old_data;
-
- repeats = (PyAO *)PyArray_ContiguousFromAny(op, PyArray_INTP, 0, 1);
- if (repeats == NULL) return NULL;
- nd = repeats->nd;
- counts = (intp *)repeats->data;
-
- if ((ap=_check_axis(aop, &axis, CARRAY))==NULL) {
- Py_DECREF(repeats);
- return NULL;
- }
-
- aop = (PyAO *)ap;
-
- if (nd == 1)
- n = repeats->dimensions[0];
- else /* nd == 0 */
- n = aop->dimensions[axis];
-
- if (aop->dimensions[axis] != n) {
- PyErr_SetString(PyExc_ValueError,
- "a.shape[axis] != len(repeats)");
- goto fail;
- }
-
-
- if (nd == 0)
- total = counts[0]*n;
- else {
-
- total = 0;
- for(j=0; j<n; j++) {
- if (counts[j] < 0) {
- PyErr_SetString(PyExc_ValueError, "count < 0");
- goto fail;
- }
- total += counts[j];
- }
- }
-
-
- /* Construct new array */
- aop->dimensions[axis] = total;
- Py_INCREF(aop->descr);
- ret = (PyArrayObject *)PyArray_NewFromDescr(aop->ob_type,
- aop->descr,
- aop->nd,
- aop->dimensions,
- NULL, NULL, 0,
- (PyObject *)aop);
- aop->dimensions[axis] = n;
-
- if (ret == NULL) goto fail;
-
- new_data = ret->data;
- old_data = aop->data;
-
- chunk = aop->descr->elsize;
- for(i=axis+1; i<aop->nd; i++) {
- chunk *= aop->dimensions[i];
- }
-
- n_outer = 1;
- for(i=0; i<axis; i++) n_outer *= aop->dimensions[i];
-
- for(i=0; i<n_outer; i++) {
- for(j=0; j<n; j++) {
- tmp = (nd ? counts[j] : counts[0]);
- for(k=0; k<tmp; k++) {
- memcpy(new_data, old_data, chunk);
- new_data += chunk;
- }
- old_data += chunk;
- }
- }
-
- Py_DECREF(repeats);
- PyArray_INCREF(ret);
- Py_XDECREF(aop);
- return (PyObject *)ret;
+ intp *counts;
+ intp n, n_outer, i, j, k, chunk, total;
+ intp tmp;
+ int nd;
+ PyArrayObject *repeats=NULL;
+ PyObject *ap=NULL;
+ PyArrayObject *ret=NULL;
+ char *new_data, *old_data;
+
+ repeats = (PyAO *)PyArray_ContiguousFromAny(op, PyArray_INTP, 0, 1);
+ if (repeats == NULL) return NULL;
+ nd = repeats->nd;
+ counts = (intp *)repeats->data;
+
+ if ((ap=_check_axis(aop, &axis, CARRAY))==NULL) {
+ Py_DECREF(repeats);
+ return NULL;
+ }
+
+ aop = (PyAO *)ap;
+
+ if (nd == 1)
+ n = repeats->dimensions[0];
+ else /* nd == 0 */
+ n = aop->dimensions[axis];
+
+ if (aop->dimensions[axis] != n) {
+ PyErr_SetString(PyExc_ValueError,
+ "a.shape[axis] != len(repeats)");
+ goto fail;
+ }
+
+
+ if (nd == 0)
+ total = counts[0]*n;
+ else {
+
+ total = 0;
+ for(j=0; j<n; j++) {
+ if (counts[j] < 0) {
+ PyErr_SetString(PyExc_ValueError, "count < 0");
+ goto fail;
+ }
+ total += counts[j];
+ }
+ }
+
+
+ /* Construct new array */
+ aop->dimensions[axis] = total;
+ Py_INCREF(aop->descr);
+ ret = (PyArrayObject *)PyArray_NewFromDescr(aop->ob_type,
+ aop->descr,
+ aop->nd,
+ aop->dimensions,
+ NULL, NULL, 0,
+ (PyObject *)aop);
+ aop->dimensions[axis] = n;
+
+ if (ret == NULL) goto fail;
+
+ new_data = ret->data;
+ old_data = aop->data;
+
+ chunk = aop->descr->elsize;
+ for(i=axis+1; i<aop->nd; i++) {
+ chunk *= aop->dimensions[i];
+ }
+
+ n_outer = 1;
+ for(i=0; i<axis; i++) n_outer *= aop->dimensions[i];
+
+ for(i=0; i<n_outer; i++) {
+ for(j=0; j<n; j++) {
+ tmp = (nd ? counts[j] : counts[0]);
+ for(k=0; k<tmp; k++) {
+ memcpy(new_data, old_data, chunk);
+ new_data += chunk;
+ }
+ old_data += chunk;
+ }
+ }
+
+ Py_DECREF(repeats);
+ PyArray_INCREF(ret);
+ Py_XDECREF(aop);
+ return (PyObject *)ret;
fail:
- Py_DECREF(repeats);
- Py_XDECREF(aop);
- Py_XDECREF(ret);
- return NULL;
+ Py_DECREF(repeats);
+ Py_XDECREF(aop);
+ Py_XDECREF(ret);
+ return NULL;
}
static int
_signbit_set(PyArrayObject *arr)
{
- static char bitmask = (char) 0x80;
- char *ptr; /* points to the byte to test */
- char byteorder;
- int elsize;
+ static char bitmask = (char) 0x80;
+ char *ptr; /* points to the byte to test */
+ char byteorder;
+ int elsize;
- elsize = arr->descr->elsize;
- byteorder = arr->descr->byteorder;
- ptr = arr->data;
- if (elsize > 1 && \
- (byteorder == PyArray_LITTLE || \
- (byteorder == PyArray_NATIVE &&
- PyArray_ISNBO(PyArray_LITTLE))))
- ptr += elsize-1;
+ elsize = arr->descr->elsize;
+ byteorder = arr->descr->byteorder;
+ ptr = arr->data;
+ if (elsize > 1 && \
+ (byteorder == PyArray_LITTLE || \
+ (byteorder == PyArray_NATIVE &&
+ PyArray_ISNBO(PyArray_LITTLE))))
+ ptr += elsize-1;
- return ((*ptr & bitmask) != 0);
+ return ((*ptr & bitmask) != 0);
}
@@ -2019,66 +2019,66 @@ _signbit_set(PyArrayObject *arr)
static NPY_SCALARKIND
PyArray_ScalarKind(int typenum, PyArrayObject **arr)
{
- if (PyTypeNum_ISSIGNED(typenum)) {
- if (arr && _signbit_set(*arr)) return PyArray_INTNEG_SCALAR;
- else return PyArray_INTPOS_SCALAR;
- }
- if (PyTypeNum_ISFLOAT(typenum)) return PyArray_FLOAT_SCALAR;
- if (PyTypeNum_ISUNSIGNED(typenum)) return PyArray_INTPOS_SCALAR;
- if (PyTypeNum_ISCOMPLEX(typenum)) return PyArray_COMPLEX_SCALAR;
- if (PyTypeNum_ISBOOL(typenum)) return PyArray_BOOL_SCALAR;
-
- if (PyTypeNum_ISUSERDEF(typenum)) {
- NPY_SCALARKIND retval;
- PyArray_Descr* descr;
- descr = PyArray_DescrFromType(typenum);
- if (descr->f->scalarkind)
- retval = descr->f->scalarkind((arr ? *arr : NULL));
- else
- retval = PyArray_NOSCALAR;
- Py_DECREF(descr);
- return retval;
- }
- return PyArray_OBJECT_SCALAR;
+ if (PyTypeNum_ISSIGNED(typenum)) {
+ if (arr && _signbit_set(*arr)) return PyArray_INTNEG_SCALAR;
+ else return PyArray_INTPOS_SCALAR;
+ }
+ if (PyTypeNum_ISFLOAT(typenum)) return PyArray_FLOAT_SCALAR;
+ if (PyTypeNum_ISUNSIGNED(typenum)) return PyArray_INTPOS_SCALAR;
+ if (PyTypeNum_ISCOMPLEX(typenum)) return PyArray_COMPLEX_SCALAR;
+ if (PyTypeNum_ISBOOL(typenum)) return PyArray_BOOL_SCALAR;
+
+ if (PyTypeNum_ISUSERDEF(typenum)) {
+ NPY_SCALARKIND retval;
+ PyArray_Descr* descr;
+ descr = PyArray_DescrFromType(typenum);
+ if (descr->f->scalarkind)
+ retval = descr->f->scalarkind((arr ? *arr : NULL));
+ else
+ retval = PyArray_NOSCALAR;
+ Py_DECREF(descr);
+ return retval;
+ }
+ return PyArray_OBJECT_SCALAR;
}
/*OBJECT_API*/
static int
PyArray_CanCoerceScalar(int thistype, int neededtype,
- NPY_SCALARKIND scalar)
-{
- PyArray_Descr* from;
- int *castlist;
-
- if (scalar == PyArray_NOSCALAR) {
- return PyArray_CanCastSafely(thistype, neededtype);
- }
- from = PyArray_DescrFromType(thistype);
- if (from->f->cancastscalarkindto &&
- (castlist = from->f->cancastscalarkindto[scalar])) {
- while (*castlist != PyArray_NOTYPE)
- if (*castlist++ == neededtype) return 1;
- }
- switch(scalar) {
- case PyArray_BOOL_SCALAR:
- case PyArray_OBJECT_SCALAR:
- return PyArray_CanCastSafely(thistype, neededtype);
- default:
- if (PyTypeNum_ISUSERDEF(neededtype)) return FALSE;
- switch(scalar) {
- case PyArray_INTPOS_SCALAR:
- return (neededtype >= PyArray_BYTE);
- case PyArray_INTNEG_SCALAR:
- return (neededtype >= PyArray_BYTE) && \
- !(PyTypeNum_ISUNSIGNED(neededtype));
- case PyArray_FLOAT_SCALAR:
- return (neededtype >= PyArray_FLOAT);
- case PyArray_COMPLEX_SCALAR:
- return (neededtype >= PyArray_CFLOAT);
- default:
- return 1; /* should never get here... */
- }
- }
+ NPY_SCALARKIND scalar)
+{
+ PyArray_Descr* from;
+ int *castlist;
+
+ if (scalar == PyArray_NOSCALAR) {
+ return PyArray_CanCastSafely(thistype, neededtype);
+ }
+ from = PyArray_DescrFromType(thistype);
+ if (from->f->cancastscalarkindto &&
+ (castlist = from->f->cancastscalarkindto[scalar])) {
+ while (*castlist != PyArray_NOTYPE)
+ if (*castlist++ == neededtype) return 1;
+ }
+ switch(scalar) {
+ case PyArray_BOOL_SCALAR:
+ case PyArray_OBJECT_SCALAR:
+ return PyArray_CanCastSafely(thistype, neededtype);
+ default:
+ if (PyTypeNum_ISUSERDEF(neededtype)) return FALSE;
+ switch(scalar) {
+ case PyArray_INTPOS_SCALAR:
+ return (neededtype >= PyArray_BYTE);
+ case PyArray_INTNEG_SCALAR:
+ return (neededtype >= PyArray_BYTE) && \
+ !(PyTypeNum_ISUNSIGNED(neededtype));
+ case PyArray_FLOAT_SCALAR:
+ return (neededtype >= PyArray_FLOAT);
+ case PyArray_COMPLEX_SCALAR:
+ return (neededtype >= PyArray_CFLOAT);
+ default:
+ return 1; /* should never get here... */
+ }
+ }
}
@@ -2086,252 +2086,252 @@ PyArray_CanCoerceScalar(int thistype, int neededtype,
static PyArrayObject **
PyArray_ConvertToCommonType(PyObject *op, int *retn)
{
- int i, n, allscalars=0;
- PyArrayObject **mps=NULL;
- PyObject *otmp;
- PyArray_Descr *intype=NULL, *stype=NULL;
- PyArray_Descr *newtype=NULL;
- NPY_SCALARKIND scalarkind=NPY_NOSCALAR, intypekind=NPY_NOSCALAR;
-
- *retn = n = PySequence_Length(op);
- if (PyErr_Occurred()) {*retn = 0; return NULL;}
-
- mps = (PyArrayObject **)PyDataMem_NEW(n*sizeof(PyArrayObject *));
- if (mps == NULL) {
- *retn = 0;
- return (void*)PyErr_NoMemory();
- }
-
- if (PyArray_Check(op)) {
- for (i=0; i<n; i++) {
- mps[i] = (PyArrayObject *)\
- array_big_item((PyArrayObject *)op, i);
- }
- if (!PyArray_ISCARRAY(op)) {
- for (i=0; i<n; i++) {
- PyObject *obj;
- obj = PyArray_NewCopy(mps[i], NPY_CORDER);
- Py_DECREF(mps[i]);
- mps[i] = (PyArrayObject *)obj;
- }
- }
- return mps;
- }
-
- for(i=0; i<n; i++) {
- otmp = PySequence_GetItem(op, i);
- if (!PyArray_CheckAnyScalar(otmp)) {
- newtype = PyArray_DescrFromObject(otmp, intype);
- Py_XDECREF(intype);
- intype = newtype;
- mps[i] = NULL;
- intypekind = PyArray_ScalarKind(intype->type_num,
- NULL);
- }
- else {
- newtype = PyArray_DescrFromObject(otmp, stype);
- Py_XDECREF(stype);
- stype = newtype;
- scalarkind = PyArray_ScalarKind(newtype->type_num,
- NULL);
- mps[i] = (PyArrayObject *)Py_None;
- Py_INCREF(Py_None);
- }
- Py_XDECREF(otmp);
- }
- if (intype==NULL) { /* all scalars */
- allscalars = 1;
- intype = stype;
- Py_INCREF(intype);
- for (i=0; i<n; i++) {
- Py_XDECREF(mps[i]);
- mps[i] = NULL;
- }
- }
- else if ((stype != NULL) && (intypekind != scalarkind)) { \
- /* we need to upconvert to type that
- handles both intype and stype
-
- also don't forcecast the scalars.
- */
-
- if (!PyArray_CanCoerceScalar(stype->type_num,
- intype->type_num,
- scalarkind)) {
- newtype = _array_small_type(intype, stype);
- Py_XDECREF(intype);
- intype = newtype;
- }
- for (i=0; i<n; i++) {
- Py_XDECREF(mps[i]);
- mps[i] = NULL;
- }
+ int i, n, allscalars=0;
+ PyArrayObject **mps=NULL;
+ PyObject *otmp;
+ PyArray_Descr *intype=NULL, *stype=NULL;
+ PyArray_Descr *newtype=NULL;
+ NPY_SCALARKIND scalarkind=NPY_NOSCALAR, intypekind=NPY_NOSCALAR;
+
+ *retn = n = PySequence_Length(op);
+ if (PyErr_Occurred()) {*retn = 0; return NULL;}
+
+ mps = (PyArrayObject **)PyDataMem_NEW(n*sizeof(PyArrayObject *));
+ if (mps == NULL) {
+ *retn = 0;
+ return (void*)PyErr_NoMemory();
+ }
+
+ if (PyArray_Check(op)) {
+ for (i=0; i<n; i++) {
+ mps[i] = (PyArrayObject *)\
+ array_big_item((PyArrayObject *)op, i);
+ }
+ if (!PyArray_ISCARRAY(op)) {
+ for (i=0; i<n; i++) {
+ PyObject *obj;
+ obj = PyArray_NewCopy(mps[i], NPY_CORDER);
+ Py_DECREF(mps[i]);
+ mps[i] = (PyArrayObject *)obj;
+ }
}
+ return mps;
+ }
+
+ for(i=0; i<n; i++) {
+ otmp = PySequence_GetItem(op, i);
+ if (!PyArray_CheckAnyScalar(otmp)) {
+ newtype = PyArray_DescrFromObject(otmp, intype);
+ Py_XDECREF(intype);
+ intype = newtype;
+ mps[i] = NULL;
+ intypekind = PyArray_ScalarKind(intype->type_num,
+ NULL);
+ }
+ else {
+ newtype = PyArray_DescrFromObject(otmp, stype);
+ Py_XDECREF(stype);
+ stype = newtype;
+ scalarkind = PyArray_ScalarKind(newtype->type_num,
+ NULL);
+ mps[i] = (PyArrayObject *)Py_None;
+ Py_INCREF(Py_None);
+ }
+ Py_XDECREF(otmp);
+ }
+ if (intype==NULL) { /* all scalars */
+ allscalars = 1;
+ intype = stype;
+ Py_INCREF(intype);
+ for (i=0; i<n; i++) {
+ Py_XDECREF(mps[i]);
+ mps[i] = NULL;
+ }
+ }
+ else if ((stype != NULL) && (intypekind != scalarkind)) { \
+ /* we need to upconvert to type that
+ handles both intype and stype
+
+ also don't forcecast the scalars.
+ */
+
+ if (!PyArray_CanCoerceScalar(stype->type_num,
+ intype->type_num,
+ scalarkind)) {
+ newtype = _array_small_type(intype, stype);
+ Py_XDECREF(intype);
+ intype = newtype;
+ }
+ for (i=0; i<n; i++) {
+ Py_XDECREF(mps[i]);
+ mps[i] = NULL;
+ }
+ }
- /* Make sure all arrays are actual array objects. */
- for(i=0; i<n; i++) {
- int flags = CARRAY;
- if ((otmp = PySequence_GetItem(op, i)) == NULL)
- goto fail;
- if (!allscalars && ((PyObject *)(mps[i]) == Py_None)) {
- /* forcecast scalars */
- flags |= FORCECAST;
- Py_DECREF(Py_None);
- }
- Py_INCREF(intype);
- mps[i] = (PyArrayObject*)
- PyArray_FromAny(otmp, intype, 0, 0, flags, NULL);
- Py_DECREF(otmp);
- if (mps[i] == NULL) goto fail;
- }
- Py_DECREF(intype);
- Py_XDECREF(stype);
- return mps;
+ /* Make sure all arrays are actual array objects. */
+ for(i=0; i<n; i++) {
+ int flags = CARRAY;
+ if ((otmp = PySequence_GetItem(op, i)) == NULL)
+ goto fail;
+ if (!allscalars && ((PyObject *)(mps[i]) == Py_None)) {
+ /* forcecast scalars */
+ flags |= FORCECAST;
+ Py_DECREF(Py_None);
+ }
+ Py_INCREF(intype);
+ mps[i] = (PyArrayObject*)
+ PyArray_FromAny(otmp, intype, 0, 0, flags, NULL);
+ Py_DECREF(otmp);
+ if (mps[i] == NULL) goto fail;
+ }
+ Py_DECREF(intype);
+ Py_XDECREF(stype);
+ return mps;
fail:
- Py_XDECREF(intype);
- Py_XDECREF(stype);
- *retn = 0;
- for (i=0; i<n; i++) Py_XDECREF(mps[i]);
- PyDataMem_FREE(mps);
- return NULL;
+ Py_XDECREF(intype);
+ Py_XDECREF(stype);
+ *retn = 0;
+ for (i=0; i<n; i++) Py_XDECREF(mps[i]);
+ PyDataMem_FREE(mps);
+ return NULL;
}
/*MULTIARRAY_API
-*/
+ */
static PyObject *
PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret,
NPY_CLIPMODE clipmode)
{
- intp *sizes, offset;
- int n, elsize;
- intp i, m;
- char *ret_data;
- PyArrayObject **mps, *ap;
- intp *self_data, mi;
- int copyret=0;
- ap = NULL;
-
- /* Convert all inputs to arrays of a common type */
- mps = PyArray_ConvertToCommonType(op, &n);
- if (mps == NULL) return NULL;
-
- sizes = (intp *)_pya_malloc(n*sizeof(intp));
- if (sizes == NULL) goto fail;
-
- ap = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ip,
- PyArray_INTP,
- 0, 0);
- if (ap == NULL) goto fail;
-
- /* Check the dimensions of the arrays */
- for(i=0; i<n; i++) {
- if (mps[i] == NULL) goto fail;
- if (ap->nd < mps[i]->nd) {
- PyErr_SetString(PyExc_ValueError,
- "too many dimensions");
- goto fail;
- }
- if (!PyArray_CompareLists(ap->dimensions+(ap->nd-mps[i]->nd),
- mps[i]->dimensions, mps[i]->nd)) {
- PyErr_SetString(PyExc_ValueError,
- "array dimensions must agree");
- goto fail;
- }
- sizes[i] = PyArray_NBYTES(mps[i]);
- }
-
- if (!ret) {
- Py_INCREF(mps[0]->descr);
- ret = (PyArrayObject *)PyArray_NewFromDescr(ap->ob_type,
- mps[0]->descr,
- ap->nd,
- ap->dimensions,
- NULL, NULL, 0,
- (PyObject *)ap);
+ intp *sizes, offset;
+ int n, elsize;
+ intp i, m;
+ char *ret_data;
+ PyArrayObject **mps, *ap;
+ intp *self_data, mi;
+ int copyret=0;
+ ap = NULL;
+
+ /* Convert all inputs to arrays of a common type */
+ mps = PyArray_ConvertToCommonType(op, &n);
+ if (mps == NULL) return NULL;
+
+ sizes = (intp *)_pya_malloc(n*sizeof(intp));
+ if (sizes == NULL) goto fail;
+
+ ap = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ip,
+ PyArray_INTP,
+ 0, 0);
+ if (ap == NULL) goto fail;
+
+ /* Check the dimensions of the arrays */
+ for(i=0; i<n; i++) {
+ if (mps[i] == NULL) goto fail;
+ if (ap->nd < mps[i]->nd) {
+ PyErr_SetString(PyExc_ValueError,
+ "too many dimensions");
+ goto fail;
}
- else {
- PyArrayObject *obj;
- int flags = NPY_CARRAY | NPY_UPDATEIFCOPY | NPY_FORCECAST;
-
- if (PyArray_SIZE(ret) != PyArray_SIZE(ap)) {
- PyErr_SetString(PyExc_TypeError,
- "invalid shape for output array.");
- ret = NULL;
- goto fail;
- }
- if (clipmode == NPY_RAISE) {
- /* we need to make sure and get a copy
- so the input array is not changed
- before the error is called
- */
- flags |= NPY_ENSURECOPY;
- }
- Py_INCREF(mps[0]->descr);
- obj = (PyArrayObject *)PyArray_FromArray(ret, mps[0]->descr,
- flags);
- if (obj != ret) copyret = 1;
- ret = obj;
+ if (!PyArray_CompareLists(ap->dimensions+(ap->nd-mps[i]->nd),
+ mps[i]->dimensions, mps[i]->nd)) {
+ PyErr_SetString(PyExc_ValueError,
+ "array dimensions must agree");
+ goto fail;
}
+ sizes[i] = PyArray_NBYTES(mps[i]);
+ }
- if (ret == NULL) goto fail;
- elsize = ret->descr->elsize;
- m = PyArray_SIZE(ret);
- self_data = (intp *)ap->data;
- ret_data = ret->data;
-
- for (i=0; i<m; i++) {
- mi = *self_data;
- if (mi < 0 || mi >= n) {
- switch(clipmode) {
- case NPY_RAISE:
- PyErr_SetString(PyExc_ValueError,
- "invalid entry in choice "\
- "array");
- goto fail;
- case NPY_WRAP:
- if (mi < 0) {
- while(mi<0) mi += n;
- }
- else {
- while(mi>=n) mi -= n;
- }
- break;
- case NPY_CLIP:
- if (mi < 0) mi=0;
- else if (mi>=n) mi=n-1;
- break;
- }
+ if (!ret) {
+ Py_INCREF(mps[0]->descr);
+ ret = (PyArrayObject *)PyArray_NewFromDescr(ap->ob_type,
+ mps[0]->descr,
+ ap->nd,
+ ap->dimensions,
+ NULL, NULL, 0,
+ (PyObject *)ap);
+ }
+ else {
+ PyArrayObject *obj;
+ int flags = NPY_CARRAY | NPY_UPDATEIFCOPY | NPY_FORCECAST;
+
+ if (PyArray_SIZE(ret) != PyArray_SIZE(ap)) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid shape for output array.");
+ ret = NULL;
+ goto fail;
+ }
+ if (clipmode == NPY_RAISE) {
+ /* we need to make sure and get a copy
+ so the input array is not changed
+ before the error is called
+ */
+ flags |= NPY_ENSURECOPY;
+ }
+ Py_INCREF(mps[0]->descr);
+ obj = (PyArrayObject *)PyArray_FromArray(ret, mps[0]->descr,
+ flags);
+ if (obj != ret) copyret = 1;
+ ret = obj;
+ }
+
+ if (ret == NULL) goto fail;
+ elsize = ret->descr->elsize;
+ m = PyArray_SIZE(ret);
+ self_data = (intp *)ap->data;
+ ret_data = ret->data;
+
+ for (i=0; i<m; i++) {
+ mi = *self_data;
+ if (mi < 0 || mi >= n) {
+ switch(clipmode) {
+ case NPY_RAISE:
+ PyErr_SetString(PyExc_ValueError,
+ "invalid entry in choice "\
+ "array");
+ goto fail;
+ case NPY_WRAP:
+ if (mi < 0) {
+ while(mi<0) mi += n;
}
- offset = i*elsize;
- if (offset >= sizes[mi]) {offset = offset % sizes[mi]; }
- memmove(ret_data, mps[mi]->data+offset, elsize);
- ret_data += elsize; self_data++;
- }
-
- PyArray_INCREF(ret);
- for(i=0; i<n; i++) Py_XDECREF(mps[i]);
- Py_DECREF(ap);
- PyDataMem_FREE(mps);
- _pya_free(sizes);
- if (copyret) {
- PyObject *obj;
- obj = ret->base;
- Py_INCREF(obj);
- Py_DECREF(ret);
- ret = (PyArrayObject *)obj;
+ else {
+ while(mi>=n) mi -= n;
+ }
+ break;
+ case NPY_CLIP:
+ if (mi < 0) mi=0;
+ else if (mi>=n) mi=n-1;
+ break;
+ }
}
- return (PyObject *)ret;
+ offset = i*elsize;
+ if (offset >= sizes[mi]) {offset = offset % sizes[mi]; }
+ memmove(ret_data, mps[mi]->data+offset, elsize);
+ ret_data += elsize; self_data++;
+ }
+
+ PyArray_INCREF(ret);
+ for(i=0; i<n; i++) Py_XDECREF(mps[i]);
+ Py_DECREF(ap);
+ PyDataMem_FREE(mps);
+ _pya_free(sizes);
+ if (copyret) {
+ PyObject *obj;
+ obj = ret->base;
+ Py_INCREF(obj);
+ Py_DECREF(ret);
+ ret = (PyArrayObject *)obj;
+ }
+ return (PyObject *)ret;
fail:
- for(i=0; i<n; i++) Py_XDECREF(mps[i]);
- Py_XDECREF(ap);
- PyDataMem_FREE(mps);
- _pya_free(sizes);
- PyArray_XDECREF_ERR(ret);
- return NULL;
+ for(i=0; i<n; i++) Py_XDECREF(mps[i]);
+ Py_XDECREF(ap);
+ PyDataMem_FREE(mps);
+ _pya_free(sizes);
+ PyArray_XDECREF_ERR(ret);
+ return NULL;
}
/* These algorithms use special sorting. They are not called unless the
@@ -2348,151 +2348,151 @@ PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret,
static int
_new_sort(PyArrayObject *op, int axis, NPY_SORTKIND which)
{
- PyArrayIterObject *it;
- int needcopy=0, swap;
- intp N, size;
- int elsize;
- intp astride;
- PyArray_SortFunc *sort;
- BEGIN_THREADS_DEF
-
- it = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)op, &axis);
- swap = !PyArray_ISNOTSWAPPED(op);
- if (it == NULL) return -1;
-
- NPY_BEGIN_THREADS_DESCR(op->descr)
-
- sort = op->descr->f->sort[which];
- size = it->size;
- N = op->dimensions[axis];
- elsize = op->descr->elsize;
- astride = op->strides[axis];
-
- needcopy = !(op->flags & ALIGNED) || (astride != (intp) elsize) \
- || swap;
-
- if (needcopy) {
- char *buffer;
- buffer = PyDataMem_NEW(N*elsize);
- while (size--) {
- _unaligned_strided_byte_copy(buffer, (intp) elsize, it->dataptr,
- astride, N, elsize);
- if (swap) _strided_byte_swap(buffer, (intp) elsize, N, elsize);
- if (sort(buffer, N, op) < 0) {
- PyDataMem_FREE(buffer); goto fail;
- }
- if (swap) _strided_byte_swap(buffer, (intp) elsize, N, elsize);
-
- _unaligned_strided_byte_copy(it->dataptr, astride, buffer,
- (intp) elsize, N, elsize);
- PyArray_ITER_NEXT(it);
- }
- PyDataMem_FREE(buffer);
- }
- else {
- while (size--) {
- if (sort(it->dataptr, N, op) < 0) goto fail;
- PyArray_ITER_NEXT(it);
- }
- }
-
- NPY_END_THREADS_DESCR(op->descr)
-
- Py_DECREF(it);
- return 0;
+ PyArrayIterObject *it;
+ int needcopy=0, swap;
+ intp N, size;
+ int elsize;
+ intp astride;
+ PyArray_SortFunc *sort;
+ BEGIN_THREADS_DEF
+
+ it = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)op, &axis);
+ swap = !PyArray_ISNOTSWAPPED(op);
+ if (it == NULL) return -1;
+
+ NPY_BEGIN_THREADS_DESCR(op->descr)
+
+ sort = op->descr->f->sort[which];
+ size = it->size;
+ N = op->dimensions[axis];
+ elsize = op->descr->elsize;
+ astride = op->strides[axis];
+
+ needcopy = !(op->flags & ALIGNED) || (astride != (intp) elsize) \
+ || swap;
+
+ if (needcopy) {
+ char *buffer;
+ buffer = PyDataMem_NEW(N*elsize);
+ while (size--) {
+ _unaligned_strided_byte_copy(buffer, (intp) elsize, it->dataptr,
+ astride, N, elsize);
+ if (swap) _strided_byte_swap(buffer, (intp) elsize, N, elsize);
+ if (sort(buffer, N, op) < 0) {
+ PyDataMem_FREE(buffer); goto fail;
+ }
+ if (swap) _strided_byte_swap(buffer, (intp) elsize, N, elsize);
+
+ _unaligned_strided_byte_copy(it->dataptr, astride, buffer,
+ (intp) elsize, N, elsize);
+ PyArray_ITER_NEXT(it);
+ }
+ PyDataMem_FREE(buffer);
+ }
+ else {
+ while (size--) {
+ if (sort(it->dataptr, N, op) < 0) goto fail;
+ PyArray_ITER_NEXT(it);
+ }
+ }
+
+ NPY_END_THREADS_DESCR(op->descr)
+
+ Py_DECREF(it);
+ return 0;
fail:
- END_THREADS
+ END_THREADS
- Py_DECREF(it);
- return 0;
+ Py_DECREF(it);
+ return 0;
}
static PyObject*
_new_argsort(PyArrayObject *op, int axis, NPY_SORTKIND which)
{
- PyArrayIterObject *it=NULL;
- PyArrayIterObject *rit=NULL;
- PyObject *ret;
- int needcopy=0, i;
- intp N, size;
- int elsize, swap;
- intp astride, rstride, *iptr;
- PyArray_ArgSortFunc *argsort;
- BEGIN_THREADS_DEF
-
- ret = PyArray_New(op->ob_type, op->nd,
- op->dimensions, PyArray_INTP,
- NULL, NULL, 0, 0, (PyObject *)op);
- if (ret == NULL) return NULL;
-
- it = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)op, &axis);
- rit = (PyArrayIterObject *)PyArray_IterAllButAxis(ret, &axis);
- if (rit == NULL || it == NULL) goto fail;
-
- swap = !PyArray_ISNOTSWAPPED(op);
-
- NPY_BEGIN_THREADS_DESCR(op->descr)
-
- argsort = op->descr->f->argsort[which];
- size = it->size;
- N = op->dimensions[axis];
- elsize = op->descr->elsize;
- astride = op->strides[axis];
- rstride = PyArray_STRIDE(ret,axis);
-
- needcopy = swap || !(op->flags & ALIGNED) || (astride != (intp) elsize) || \
- (rstride != sizeof(intp));
-
- if (needcopy) {
- char *valbuffer, *indbuffer;
- valbuffer = PyDataMem_NEW(N*elsize);
- indbuffer = PyDataMem_NEW(N*sizeof(intp));
- while (size--) {
- _unaligned_strided_byte_copy(valbuffer, (intp) elsize, it->dataptr,
- astride, N, elsize);
- if (swap) _strided_byte_swap(valbuffer, (intp) elsize, N, elsize);
- iptr = (intp *)indbuffer;
- for (i=0; i<N; i++) *iptr++ = i;
- if (argsort(valbuffer, (intp *)indbuffer, N, op) < 0) {
- PyDataMem_FREE(valbuffer);
- PyDataMem_FREE(indbuffer);
- goto fail;
- }
- _unaligned_strided_byte_copy(rit->dataptr, rstride, indbuffer,
- sizeof(intp), N, sizeof(intp));
- PyArray_ITER_NEXT(it);
- PyArray_ITER_NEXT(rit);
- }
- PyDataMem_FREE(valbuffer);
+ PyArrayIterObject *it=NULL;
+ PyArrayIterObject *rit=NULL;
+ PyObject *ret;
+ int needcopy=0, i;
+ intp N, size;
+ int elsize, swap;
+ intp astride, rstride, *iptr;
+ PyArray_ArgSortFunc *argsort;
+ BEGIN_THREADS_DEF
+
+ ret = PyArray_New(op->ob_type, op->nd,
+ op->dimensions, PyArray_INTP,
+ NULL, NULL, 0, 0, (PyObject *)op);
+ if (ret == NULL) return NULL;
+
+ it = (PyArrayIterObject *)PyArray_IterAllButAxis((PyObject *)op, &axis);
+ rit = (PyArrayIterObject *)PyArray_IterAllButAxis(ret, &axis);
+ if (rit == NULL || it == NULL) goto fail;
+
+ swap = !PyArray_ISNOTSWAPPED(op);
+
+ NPY_BEGIN_THREADS_DESCR(op->descr)
+
+ argsort = op->descr->f->argsort[which];
+ size = it->size;
+ N = op->dimensions[axis];
+ elsize = op->descr->elsize;
+ astride = op->strides[axis];
+ rstride = PyArray_STRIDE(ret,axis);
+
+ needcopy = swap || !(op->flags & ALIGNED) || (astride != (intp) elsize) || \
+ (rstride != sizeof(intp));
+
+ if (needcopy) {
+ char *valbuffer, *indbuffer;
+ valbuffer = PyDataMem_NEW(N*elsize);
+ indbuffer = PyDataMem_NEW(N*sizeof(intp));
+ while (size--) {
+ _unaligned_strided_byte_copy(valbuffer, (intp) elsize, it->dataptr,
+ astride, N, elsize);
+ if (swap) _strided_byte_swap(valbuffer, (intp) elsize, N, elsize);
+ iptr = (intp *)indbuffer;
+ for (i=0; i<N; i++) *iptr++ = i;
+ if (argsort(valbuffer, (intp *)indbuffer, N, op) < 0) {
+ PyDataMem_FREE(valbuffer);
PyDataMem_FREE(indbuffer);
- }
- else {
- while (size--) {
- iptr = (intp *)rit->dataptr;
- for (i=0; i<N; i++) *iptr++ = i;
- if (argsort(it->dataptr, (intp *)rit->dataptr,
- N, op) < 0) goto fail;
- PyArray_ITER_NEXT(it);
- PyArray_ITER_NEXT(rit);
- }
- }
-
- NPY_END_THREADS_DESCR(op->descr)
-
- Py_DECREF(it);
- Py_DECREF(rit);
- return ret;
+ goto fail;
+ }
+ _unaligned_strided_byte_copy(rit->dataptr, rstride, indbuffer,
+ sizeof(intp), N, sizeof(intp));
+ PyArray_ITER_NEXT(it);
+ PyArray_ITER_NEXT(rit);
+ }
+ PyDataMem_FREE(valbuffer);
+ PyDataMem_FREE(indbuffer);
+ }
+ else {
+ while (size--) {
+ iptr = (intp *)rit->dataptr;
+ for (i=0; i<N; i++) *iptr++ = i;
+ if (argsort(it->dataptr, (intp *)rit->dataptr,
+ N, op) < 0) goto fail;
+ PyArray_ITER_NEXT(it);
+ PyArray_ITER_NEXT(rit);
+ }
+ }
+
+ NPY_END_THREADS_DESCR(op->descr)
+
+ Py_DECREF(it);
+ Py_DECREF(rit);
+ return ret;
fail:
- END_THREADS
+ END_THREADS
- Py_DECREF(ret);
- Py_XDECREF(it);
- Py_XDECREF(rit);
- return NULL;
+ Py_DECREF(ret);
+ Py_XDECREF(it);
+ Py_XDECREF(rit);
+ return NULL;
}
@@ -2503,7 +2503,7 @@ static PyArrayObject *global_obj;
static int
qsortCompare (const void *a, const void *b)
{
- return global_obj->descr->f->compare(a,b,global_obj);
+ return global_obj->descr->f->compare(a,b,global_obj);
}
/* Consumes reference to ap (op gets it)
@@ -2512,119 +2512,119 @@ qsortCompare (const void *a, const void *b)
orign must be defined locally.
*/
-#define SWAPAXES(op, ap) { \
- orign = (ap)->nd-1; \
- if (axis != orign) { \
- (op) = (PyAO *)PyArray_SwapAxes((ap), axis, orign); \
- Py_DECREF((ap)); \
- if ((op) == NULL) return NULL; \
- } \
- else (op) = (ap); \
- }
+#define SWAPAXES(op, ap) { \
+ orign = (ap)->nd-1; \
+ if (axis != orign) { \
+ (op) = (PyAO *)PyArray_SwapAxes((ap), axis, orign); \
+ Py_DECREF((ap)); \
+ if ((op) == NULL) return NULL; \
+ } \
+ else (op) = (ap); \
+ }
/* Consumes reference to ap (op gets it)
origin must be previously defined locally.
SWAPAXES must have been called previously.
op contains the swapped version of the array.
*/
-#define SWAPBACK(op, ap) { \
- if (axis != orign) { \
- (op) = (PyAO *)PyArray_SwapAxes((ap), axis, orign); \
- Py_DECREF((ap)); \
- if ((op) == NULL) return NULL; \
- } \
- else (op) = (ap); \
- }
+#define SWAPBACK(op, ap) { \
+ if (axis != orign) { \
+ (op) = (PyAO *)PyArray_SwapAxes((ap), axis, orign); \
+ Py_DECREF((ap)); \
+ if ((op) == NULL) return NULL; \
+ } \
+ else (op) = (ap); \
+ }
/* These swap axes in-place if necessary */
#define SWAPINTP(a,b) {intp c; c=(a); (a) = (b); (b) = c;}
-#define SWAPAXES2(ap) { \
- orign = (ap)->nd-1; \
- if (axis != orign) { \
- SWAPINTP(ap->dimensions[axis], ap->dimensions[orign]); \
- SWAPINTP(ap->strides[axis], ap->strides[orign]); \
- PyArray_UpdateFlags(ap, CONTIGUOUS | FORTRAN); \
- } \
- }
-
-#define SWAPBACK2(ap) { \
- if (axis != orign) { \
- SWAPINTP(ap->dimensions[axis], ap->dimensions[orign]); \
- SWAPINTP(ap->strides[axis], ap->strides[orign]); \
- PyArray_UpdateFlags(ap, CONTIGUOUS | FORTRAN); \
- } \
- }
+#define SWAPAXES2(ap) { \
+ orign = (ap)->nd-1; \
+ if (axis != orign) { \
+ SWAPINTP(ap->dimensions[axis], ap->dimensions[orign]); \
+ SWAPINTP(ap->strides[axis], ap->strides[orign]); \
+ PyArray_UpdateFlags(ap, CONTIGUOUS | FORTRAN); \
+ } \
+ }
+
+#define SWAPBACK2(ap) { \
+ if (axis != orign) { \
+ SWAPINTP(ap->dimensions[axis], ap->dimensions[orign]); \
+ SWAPINTP(ap->strides[axis], ap->strides[orign]); \
+ PyArray_UpdateFlags(ap, CONTIGUOUS | FORTRAN); \
+ } \
+ }
/*MULTIARRAY_API
- Sort an array in-place
+ Sort an array in-place
*/
static int
PyArray_Sort(PyArrayObject *op, int axis, NPY_SORTKIND which)
{
- PyArrayObject *ap=NULL, *store_arr=NULL;
- char *ip;
- int i, n, m, elsize, orign;
+ PyArrayObject *ap=NULL, *store_arr=NULL;
+ char *ip;
+ int i, n, m, elsize, orign;
- n = op->nd;
- if ((n==0) || (PyArray_SIZE(op)==1)) return 0;
+ n = op->nd;
+ if ((n==0) || (PyArray_SIZE(op)==1)) return 0;
- if (axis < 0) axis += n;
- if ((axis < 0) || (axis >= n)) {
- PyErr_Format(PyExc_ValueError,
- "axis(=%d) out of bounds", axis);
- return -1;
- }
- if (!PyArray_ISWRITEABLE(op)) {
- PyErr_SetString(PyExc_RuntimeError,
- "attempted sort on unwriteable array.");
- return -1;
- }
+ if (axis < 0) axis += n;
+ if ((axis < 0) || (axis >= n)) {
+ PyErr_Format(PyExc_ValueError,
+ "axis(=%d) out of bounds", axis);
+ return -1;
+ }
+ if (!PyArray_ISWRITEABLE(op)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "attempted sort on unwriteable array.");
+ return -1;
+ }
- /* Determine if we should use type-specific algorithm or not */
- if (op->descr->f->sort[which] != NULL) {
- return _new_sort(op, axis, which);
- }
+ /* Determine if we should use type-specific algorithm or not */
+ if (op->descr->f->sort[which] != NULL) {
+ return _new_sort(op, axis, which);
+ }
- if ((which != PyArray_QUICKSORT) || \
- op->descr->f->compare == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "desired sort not supported for this type");
- return -1;
- }
+ if ((which != PyArray_QUICKSORT) || \
+ op->descr->f->compare == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "desired sort not supported for this type");
+ return -1;
+ }
- SWAPAXES2(op);
+ SWAPAXES2(op);
- ap = (PyArrayObject *)PyArray_FromAny((PyObject *)op,
- NULL, 1, 0,
- DEFAULT | UPDATEIFCOPY, NULL);
- if (ap == NULL) goto fail;
+ ap = (PyArrayObject *)PyArray_FromAny((PyObject *)op,
+ NULL, 1, 0,
+ DEFAULT | UPDATEIFCOPY, NULL);
+ if (ap == NULL) goto fail;
- elsize = ap->descr->elsize;
- m = ap->dimensions[ap->nd-1];
- if (m == 0) goto finish;
+ elsize = ap->descr->elsize;
+ m = ap->dimensions[ap->nd-1];
+ if (m == 0) goto finish;
- n = PyArray_SIZE(ap)/m;
+ n = PyArray_SIZE(ap)/m;
- /* Store global -- allows re-entry -- restore before leaving*/
- store_arr = global_obj;
- global_obj = ap;
+ /* Store global -- allows re-entry -- restore before leaving*/
+ store_arr = global_obj;
+ global_obj = ap;
- for (ip=ap->data, i=0; i<n; i++, ip+=elsize*m) {
- qsort(ip, m, elsize, qsortCompare);
- }
+ for (ip=ap->data, i=0; i<n; i++, ip+=elsize*m) {
+ qsort(ip, m, elsize, qsortCompare);
+ }
- global_obj = store_arr;
+ global_obj = store_arr;
- if (PyErr_Occurred()) goto fail;
+ if (PyErr_Occurred()) goto fail;
finish:
- Py_DECREF(ap); /* Should update op if needed */
- SWAPBACK2(op);
- return 0;
+ Py_DECREF(ap); /* Should update op if needed */
+ SWAPBACK2(op);
+ return 0;
fail:
- Py_XDECREF(ap);
- SWAPBACK2(op);
- return -1;
+ Py_XDECREF(ap);
+ SWAPBACK2(op);
+ return -1;
}
@@ -2633,283 +2633,283 @@ static char *global_data;
static int
argsort_static_compare(const void *ip1, const void *ip2)
{
- int isize = global_obj->descr->elsize;
- const intp *ipa = ip1;
- const intp *ipb = ip2;
- return global_obj->descr->f->compare(global_data + (isize * *ipa),
- global_data + (isize * *ipb),
- global_obj);
+ int isize = global_obj->descr->elsize;
+ const intp *ipa = ip1;
+ const intp *ipb = ip2;
+ return global_obj->descr->f->compare(global_data + (isize * *ipa),
+ global_data + (isize * *ipb),
+ global_obj);
}
/*MULTIARRAY_API
- ArgSort an array
+ ArgSort an array
*/
static PyObject *
PyArray_ArgSort(PyArrayObject *op, int axis, NPY_SORTKIND which)
{
- PyArrayObject *ap=NULL, *ret=NULL, *store, *op2;
- intp *ip;
- intp i, j, n, m, orign;
- int argsort_elsize;
- char *store_ptr;
-
- n = op->nd;
- if ((n==0) || (PyArray_SIZE(op)==1)) {
- ret = (PyArrayObject *)PyArray_New(op->ob_type, op->nd,
- op->dimensions,
- PyArray_INTP,
- NULL, NULL, 0, 0,
- (PyObject *)op);
- if (ret == NULL) return NULL;
- *((intp *)ret->data) = 0;
- return (PyObject *)ret;
- }
-
- /* Creates new reference op2 */
- if ((op2=(PyAO *)_check_axis(op, &axis, 0))==NULL) return NULL;
-
- /* Determine if we should use new algorithm or not */
- if (op2->descr->f->argsort[which] != NULL) {
- ret = (PyArrayObject *)_new_argsort(op2, axis, which);
- Py_DECREF(op2);
- return (PyObject *)ret;
- }
-
- if ((which != PyArray_QUICKSORT) || op2->descr->f->compare == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "requested sort not available for type");
- Py_DECREF(op2);
- op = NULL;
- goto fail;
- }
-
- /* ap will contain the reference to op2 */
- SWAPAXES(ap, op2);
-
- op = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ap,
- PyArray_NOTYPE,
- 1, 0);
+ PyArrayObject *ap=NULL, *ret=NULL, *store, *op2;
+ intp *ip;
+ intp i, j, n, m, orign;
+ int argsort_elsize;
+ char *store_ptr;
+
+ n = op->nd;
+ if ((n==0) || (PyArray_SIZE(op)==1)) {
+ ret = (PyArrayObject *)PyArray_New(op->ob_type, op->nd,
+ op->dimensions,
+ PyArray_INTP,
+ NULL, NULL, 0, 0,
+ (PyObject *)op);
+ if (ret == NULL) return NULL;
+ *((intp *)ret->data) = 0;
+ return (PyObject *)ret;
+ }
- Py_DECREF(ap);
- if (op == NULL) return NULL;
+ /* Creates new reference op2 */
+ if ((op2=(PyAO *)_check_axis(op, &axis, 0))==NULL) return NULL;
- ret = (PyArrayObject *)PyArray_New(op->ob_type, op->nd,
- op->dimensions, PyArray_INTP,
- NULL, NULL, 0, 0, (PyObject *)op);
- if (ret == NULL) goto fail;
+ /* Determine if we should use new algorithm or not */
+ if (op2->descr->f->argsort[which] != NULL) {
+ ret = (PyArrayObject *)_new_argsort(op2, axis, which);
+ Py_DECREF(op2);
+ return (PyObject *)ret;
+ }
+
+ if ((which != PyArray_QUICKSORT) || op2->descr->f->compare == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "requested sort not available for type");
+ Py_DECREF(op2);
+ op = NULL;
+ goto fail;
+ }
+ /* ap will contain the reference to op2 */
+ SWAPAXES(ap, op2);
- ip = (intp *)ret->data;
- argsort_elsize = op->descr->elsize;
- m = op->dimensions[op->nd-1];
- if (m == 0) goto finish;
+ op = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ap,
+ PyArray_NOTYPE,
+ 1, 0);
- n = PyArray_SIZE(op)/m;
- store_ptr = global_data;
- global_data = op->data;
- store = global_obj;
- global_obj = op;
- for (i=0; i<n; i++, ip+=m, global_data += m*argsort_elsize) {
- for(j=0; j<m; j++) ip[j] = j;
- qsort((char *)ip, m, sizeof(intp),
- argsort_static_compare);
- }
- global_data = store_ptr;
- global_obj = store;
+ Py_DECREF(ap);
+ if (op == NULL) return NULL;
+
+ ret = (PyArrayObject *)PyArray_New(op->ob_type, op->nd,
+ op->dimensions, PyArray_INTP,
+ NULL, NULL, 0, 0, (PyObject *)op);
+ if (ret == NULL) goto fail;
+
+
+ ip = (intp *)ret->data;
+ argsort_elsize = op->descr->elsize;
+ m = op->dimensions[op->nd-1];
+ if (m == 0) goto finish;
+
+ n = PyArray_SIZE(op)/m;
+ store_ptr = global_data;
+ global_data = op->data;
+ store = global_obj;
+ global_obj = op;
+ for (i=0; i<n; i++, ip+=m, global_data += m*argsort_elsize) {
+ for(j=0; j<m; j++) ip[j] = j;
+ qsort((char *)ip, m, sizeof(intp),
+ argsort_static_compare);
+ }
+ global_data = store_ptr;
+ global_obj = store;
finish:
- Py_DECREF(op);
- SWAPBACK(op, ret);
- return (PyObject *)op;
+ Py_DECREF(op);
+ SWAPBACK(op, ret);
+ return (PyObject *)op;
fail:
- Py_XDECREF(op);
- Py_XDECREF(ret);
- return NULL;
+ Py_XDECREF(op);
+ Py_XDECREF(ret);
+ return NULL;
}
/*MULTIARRAY_API
- LexSort an array providing indices that will sort a collection of arrays
- lexicographically. The first key is sorted on first, followed by the second key
- -- requires that arg"merge"sort is available for each sort_key
+ LexSort an array providing indices that will sort a collection of arrays
+ lexicographically. The first key is sorted on first, followed by the second key
+ -- requires that arg"merge"sort is available for each sort_key
- Returns an index array that shows the indexes for the lexicographic sort along
- the given axis.
+ Returns an index array that shows the indexes for the lexicographic sort along
+ the given axis.
*/
static PyObject *
PyArray_LexSort(PyObject *sort_keys, int axis)
{
- PyArrayObject **mps;
- PyArrayIterObject **its;
- PyArrayObject *ret=NULL;
- PyArrayIterObject *rit=NULL;
- int n;
- int nd;
- int needcopy=0, i,j;
- intp N, size;
- int elsize;
- int maxelsize;
- intp astride, rstride, *iptr;
- int object=0;
- PyArray_ArgSortFunc *argsort;
-
- NPY_BEGIN_THREADS_DEF
-
- if (!PySequence_Check(sort_keys) || \
- ((n=PySequence_Size(sort_keys)) <= 0)) {
- PyErr_SetString(PyExc_TypeError,
- "need sequence of keys with len > 0 in lexsort");
- return NULL;
- }
- mps = (PyArrayObject **) _pya_malloc(n*sizeof(PyArrayObject));
- if (mps==NULL) return PyErr_NoMemory();
- its = (PyArrayIterObject **) _pya_malloc(n*sizeof(PyArrayIterObject));
- if (its == NULL) {_pya_free(mps); return PyErr_NoMemory();}
- for (i=0; i<n; i++) {mps[i] = NULL; its[i] = NULL;}
- for (i=0; i<n; i++) {
- PyObject *obj;
- obj = PySequence_GetItem(sort_keys, i);
- mps[i] = (PyArrayObject *)PyArray_FROM_O(obj);
- Py_DECREF(obj);
- if (mps[i] == NULL) goto fail;
- if (i>0) {
- if ((mps[i]->nd != mps[0]->nd) || \
- (!PyArray_CompareLists(mps[i]->dimensions,
- mps[0]->dimensions,
- mps[0]->nd))) {
- PyErr_SetString(PyExc_ValueError,
- "all keys need to be the same shape");
- goto fail;
- }
- }
- if (!mps[i]->descr->f->argsort[PyArray_MERGESORT]) {
- PyErr_Format(PyExc_TypeError,
- "merge sort not available for item %d", i);
- goto fail;
- }
- if (!object &&
- PyDataType_FLAGCHK(mps[i]->descr, NPY_NEEDS_PYAPI))
- object = 1;
- its[i] = (PyArrayIterObject *)PyArray_IterAllButAxis \
- ((PyObject *)mps[i], &axis);
- if (its[i]==NULL) goto fail;
- }
-
- /* Now we can check the axis */
- nd = mps[0]->nd;
- if ((nd==0) || (PyArray_SIZE(mps[0])==1)) {
- ret = (PyArrayObject *)PyArray_New(&PyArray_Type, mps[0]->nd,
- mps[0]->dimensions,
- PyArray_INTP,
- NULL, NULL, 0, 0, NULL);
-
- if (ret == NULL) goto fail;
- *((intp *)(ret->data)) = 0;
- goto finish;
- }
- if (axis < 0) axis += nd;
- if ((axis < 0) || (axis >= nd)) {
- PyErr_Format(PyExc_ValueError,
- "axis(=%d) out of bounds", axis);
- goto fail;
- }
-
- /* Now do the sorting */
-
- ret = (PyArrayObject *)PyArray_New(&PyArray_Type, mps[0]->nd,
- mps[0]->dimensions, PyArray_INTP,
- NULL, NULL, 0, 0, NULL);
- if (ret == NULL) goto fail;
-
- rit = (PyArrayIterObject *)\
- PyArray_IterAllButAxis((PyObject *)ret, &axis);
- if (rit == NULL) goto fail;
-
- if (!object) {NPY_BEGIN_THREADS}
-
- size = rit->size;
- N = mps[0]->dimensions[axis];
- rstride = PyArray_STRIDE(ret,axis);
-
- maxelsize = mps[0]->descr->elsize;
- needcopy = (rstride != sizeof(intp));
- for (j=0; j<n && !needcopy; j++) {
- needcopy = PyArray_ISBYTESWAPPED(mps[j]) || \
- !(mps[j]->flags & ALIGNED) || \
- (mps[j]->strides[axis] != (intp)mps[j]->descr->elsize);
- if (mps[j]->descr->elsize > maxelsize)
- maxelsize = mps[j]->descr->elsize;
- }
-
- if (needcopy) {
- char *valbuffer, *indbuffer;
- int *swaps;
- valbuffer = PyDataMem_NEW(N*maxelsize);
- indbuffer = PyDataMem_NEW(N*sizeof(intp));
- swaps = malloc(n*sizeof(int));
- for (j=0; j<n; j++) swaps[j] = PyArray_ISBYTESWAPPED(mps[j]);
- while (size--) {
- iptr = (intp *)indbuffer;
- for (i=0; i<N; i++) *iptr++ = i;
- for (j=0; j<n; j++) {
- elsize = mps[j]->descr->elsize;
- astride = mps[j]->strides[axis];
- argsort = mps[j]->descr->f->argsort[PyArray_MERGESORT];
- _unaligned_strided_byte_copy(valbuffer, (intp) elsize,
- its[j]->dataptr, astride, N, elsize);
- if (swaps[j])
- _strided_byte_swap(valbuffer, (intp) elsize, N, elsize);
- if (argsort(valbuffer, (intp *)indbuffer, N, mps[j]) < 0) {
- PyDataMem_FREE(valbuffer);
- PyDataMem_FREE(indbuffer);
- free(swaps);
- goto fail;
- }
- PyArray_ITER_NEXT(its[j]);
- }
- _unaligned_strided_byte_copy(rit->dataptr, rstride, indbuffer,
- sizeof(intp), N, sizeof(intp));
- PyArray_ITER_NEXT(rit);
- }
- PyDataMem_FREE(valbuffer);
- PyDataMem_FREE(indbuffer);
- free(swaps);
- }
- else {
- while (size--) {
- iptr = (intp *)rit->dataptr;
- for (i=0; i<N; i++) *iptr++ = i;
- for (j=0; j<n; j++) {
- argsort = mps[j]->descr->f->argsort[PyArray_MERGESORT];
- if (argsort(its[j]->dataptr, (intp *)rit->dataptr,
- N, mps[j]) < 0) goto fail;
- PyArray_ITER_NEXT(its[j]);
- }
- PyArray_ITER_NEXT(rit);
- }
- }
-
- if (!object) {NPY_END_THREADS}
+ PyArrayObject **mps;
+ PyArrayIterObject **its;
+ PyArrayObject *ret=NULL;
+ PyArrayIterObject *rit=NULL;
+ int n;
+ int nd;
+ int needcopy=0, i,j;
+ intp N, size;
+ int elsize;
+ int maxelsize;
+ intp astride, rstride, *iptr;
+ int object=0;
+ PyArray_ArgSortFunc *argsort;
+
+ NPY_BEGIN_THREADS_DEF
+
+ if (!PySequence_Check(sort_keys) || \
+ ((n=PySequence_Size(sort_keys)) <= 0)) {
+ PyErr_SetString(PyExc_TypeError,
+ "need sequence of keys with len > 0 in lexsort");
+ return NULL;
+ }
+ mps = (PyArrayObject **) _pya_malloc(n*sizeof(PyArrayObject));
+ if (mps==NULL) return PyErr_NoMemory();
+ its = (PyArrayIterObject **) _pya_malloc(n*sizeof(PyArrayIterObject));
+ if (its == NULL) {_pya_free(mps); return PyErr_NoMemory();}
+ for (i=0; i<n; i++) {mps[i] = NULL; its[i] = NULL;}
+ for (i=0; i<n; i++) {
+ PyObject *obj;
+ obj = PySequence_GetItem(sort_keys, i);
+ mps[i] = (PyArrayObject *)PyArray_FROM_O(obj);
+ Py_DECREF(obj);
+ if (mps[i] == NULL) goto fail;
+ if (i>0) {
+ if ((mps[i]->nd != mps[0]->nd) || \
+ (!PyArray_CompareLists(mps[i]->dimensions,
+ mps[0]->dimensions,
+ mps[0]->nd))) {
+ PyErr_SetString(PyExc_ValueError,
+ "all keys need to be the same shape");
+ goto fail;
+ }
+ }
+ if (!mps[i]->descr->f->argsort[PyArray_MERGESORT]) {
+ PyErr_Format(PyExc_TypeError,
+ "merge sort not available for item %d", i);
+ goto fail;
+ }
+ if (!object &&
+ PyDataType_FLAGCHK(mps[i]->descr, NPY_NEEDS_PYAPI))
+ object = 1;
+ its[i] = (PyArrayIterObject *)PyArray_IterAllButAxis \
+ ((PyObject *)mps[i], &axis);
+ if (its[i]==NULL) goto fail;
+ }
+
+ /* Now we can check the axis */
+ nd = mps[0]->nd;
+ if ((nd==0) || (PyArray_SIZE(mps[0])==1)) {
+ ret = (PyArrayObject *)PyArray_New(&PyArray_Type, mps[0]->nd,
+ mps[0]->dimensions,
+ PyArray_INTP,
+ NULL, NULL, 0, 0, NULL);
+
+ if (ret == NULL) goto fail;
+ *((intp *)(ret->data)) = 0;
+ goto finish;
+ }
+ if (axis < 0) axis += nd;
+ if ((axis < 0) || (axis >= nd)) {
+ PyErr_Format(PyExc_ValueError,
+ "axis(=%d) out of bounds", axis);
+ goto fail;
+ }
+
+ /* Now do the sorting */
+
+ ret = (PyArrayObject *)PyArray_New(&PyArray_Type, mps[0]->nd,
+ mps[0]->dimensions, PyArray_INTP,
+ NULL, NULL, 0, 0, NULL);
+ if (ret == NULL) goto fail;
+
+ rit = (PyArrayIterObject *)\
+ PyArray_IterAllButAxis((PyObject *)ret, &axis);
+ if (rit == NULL) goto fail;
+
+ if (!object) {NPY_BEGIN_THREADS}
+
+ size = rit->size;
+ N = mps[0]->dimensions[axis];
+ rstride = PyArray_STRIDE(ret,axis);
+
+ maxelsize = mps[0]->descr->elsize;
+ needcopy = (rstride != sizeof(intp));
+ for (j=0; j<n && !needcopy; j++) {
+ needcopy = PyArray_ISBYTESWAPPED(mps[j]) || \
+ !(mps[j]->flags & ALIGNED) || \
+ (mps[j]->strides[axis] != (intp)mps[j]->descr->elsize);
+ if (mps[j]->descr->elsize > maxelsize)
+ maxelsize = mps[j]->descr->elsize;
+ }
+
+ if (needcopy) {
+ char *valbuffer, *indbuffer;
+ int *swaps;
+ valbuffer = PyDataMem_NEW(N*maxelsize);
+ indbuffer = PyDataMem_NEW(N*sizeof(intp));
+ swaps = malloc(n*sizeof(int));
+ for (j=0; j<n; j++) swaps[j] = PyArray_ISBYTESWAPPED(mps[j]);
+ while (size--) {
+ iptr = (intp *)indbuffer;
+ for (i=0; i<N; i++) *iptr++ = i;
+ for (j=0; j<n; j++) {
+ elsize = mps[j]->descr->elsize;
+ astride = mps[j]->strides[axis];
+ argsort = mps[j]->descr->f->argsort[PyArray_MERGESORT];
+ _unaligned_strided_byte_copy(valbuffer, (intp) elsize,
+ its[j]->dataptr, astride, N, elsize);
+ if (swaps[j])
+ _strided_byte_swap(valbuffer, (intp) elsize, N, elsize);
+ if (argsort(valbuffer, (intp *)indbuffer, N, mps[j]) < 0) {
+ PyDataMem_FREE(valbuffer);
+ PyDataMem_FREE(indbuffer);
+ free(swaps);
+ goto fail;
+ }
+ PyArray_ITER_NEXT(its[j]);
+ }
+ _unaligned_strided_byte_copy(rit->dataptr, rstride, indbuffer,
+ sizeof(intp), N, sizeof(intp));
+ PyArray_ITER_NEXT(rit);
+ }
+ PyDataMem_FREE(valbuffer);
+ PyDataMem_FREE(indbuffer);
+ free(swaps);
+ }
+ else {
+ while (size--) {
+ iptr = (intp *)rit->dataptr;
+ for (i=0; i<N; i++) *iptr++ = i;
+ for (j=0; j<n; j++) {
+ argsort = mps[j]->descr->f->argsort[PyArray_MERGESORT];
+ if (argsort(its[j]->dataptr, (intp *)rit->dataptr,
+ N, mps[j]) < 0) goto fail;
+ PyArray_ITER_NEXT(its[j]);
+ }
+ PyArray_ITER_NEXT(rit);
+ }
+ }
+
+ if (!object) {NPY_END_THREADS}
finish:
- for (i=0; i<n; i++) {Py_XDECREF(mps[i]); Py_XDECREF(its[i]);}
- Py_XDECREF(rit);
- _pya_free(mps);
- _pya_free(its);
- return (PyObject *)ret;
+ for (i=0; i<n; i++) {Py_XDECREF(mps[i]); Py_XDECREF(its[i]);}
+ Py_XDECREF(rit);
+ _pya_free(mps);
+ _pya_free(its);
+ return (PyObject *)ret;
fail:
- NPY_END_THREADS
+ NPY_END_THREADS
- Py_XDECREF(rit);
- Py_XDECREF(ret);
- for (i=0; i<n; i++) {Py_XDECREF(mps[i]); Py_XDECREF(its[i]);}
- _pya_free(mps);
- _pya_free(its);
- return NULL;
+ Py_XDECREF(rit);
+ Py_XDECREF(ret);
+ for (i=0; i<n; i++) {Py_XDECREF(mps[i]); Py_XDECREF(its[i]);}
+ _pya_free(mps);
+ _pya_free(its);
+ return NULL;
}
@@ -2929,29 +2929,29 @@ PyArray_LexSort(PyObject *sort_keys, int axis)
static void
local_search_left(PyArrayObject *arr, PyArrayObject *key, PyArrayObject *ret)
{
- PyArray_CompareFunc *compare = key->descr->f->compare;
- intp nelts = arr->dimensions[arr->nd - 1];
- intp nkeys = PyArray_SIZE(key);
- char *parr = arr->data;
- char *pkey = key->data;
- intp *pret = (intp *)ret->data;
- int elsize = arr->descr->elsize;
- intp i;
-
- for(i = 0; i < nkeys; ++i) {
- intp imin = 0;
- intp imax = nelts;
- while (imin < imax) {
- intp imid = imin + ((imax - imin) >> 2);
- if (compare(parr + elsize*imid, pkey, key) < 0)
- imin = imid + 1;
- else
- imax = imid;
- }
- *pret = imin;
- pret += 1;
- pkey += elsize;
- }
+ PyArray_CompareFunc *compare = key->descr->f->compare;
+ intp nelts = arr->dimensions[arr->nd - 1];
+ intp nkeys = PyArray_SIZE(key);
+ char *parr = arr->data;
+ char *pkey = key->data;
+ intp *pret = (intp *)ret->data;
+ int elsize = arr->descr->elsize;
+ intp i;
+
+ for(i = 0; i < nkeys; ++i) {
+ intp imin = 0;
+ intp imax = nelts;
+ while (imin < imax) {
+ intp imid = imin + ((imax - imin) >> 2);
+ if (compare(parr + elsize*imid, pkey, key) < 0)
+ imin = imid + 1;
+ else
+ imax = imid;
+ }
+ *pret = imin;
+ pret += 1;
+ pkey += elsize;
+ }
}
@@ -2970,29 +2970,29 @@ local_search_left(PyArrayObject *arr, PyArrayObject *key, PyArrayObject *ret)
static void
local_search_right(PyArrayObject *arr, PyArrayObject *key, PyArrayObject *ret)
{
- PyArray_CompareFunc *compare = key->descr->f->compare;
- intp nelts = arr->dimensions[arr->nd - 1];
- intp nkeys = PyArray_SIZE(key);
- char *parr = arr->data;
- char *pkey = key->data;
- intp *pret = (intp *)ret->data;
- int elsize = arr->descr->elsize;
- intp i;
-
- for(i = 0; i < nkeys; ++i) {
- intp imin = 0;
- intp imax = nelts;
- while (imin < imax) {
- intp imid = imin + ((imax - imin) >> 2);
- if (compare(parr + elsize*imid, pkey, key) <= 0)
- imin = imid + 1;
- else
- imax = imid;
- }
- *pret = imin;
- pret += 1;
- pkey += elsize;
- }
+ PyArray_CompareFunc *compare = key->descr->f->compare;
+ intp nelts = arr->dimensions[arr->nd - 1];
+ intp nkeys = PyArray_SIZE(key);
+ char *parr = arr->data;
+ char *pkey = key->data;
+ intp *pret = (intp *)ret->data;
+ int elsize = arr->descr->elsize;
+ intp i;
+
+ for(i = 0; i < nkeys; ++i) {
+ intp imin = 0;
+ intp imax = nelts;
+ while (imin < imax) {
+ intp imid = imin + ((imax - imin) >> 2);
+ if (compare(parr + elsize*imid, pkey, key) <= 0)
+ imin = imid + 1;
+ else
+ imax = imid;
+ }
+ *pret = imin;
+ pret += 1;
+ pkey += elsize;
+ }
}
@@ -3002,1161 +3002,1161 @@ local_search_right(PyArrayObject *arr, PyArrayObject *key, PyArrayObject *ret)
static int
PyArray_SearchsideConverter(PyObject *obj, void *addr)
{
- NPY_SEARCHSIDE *side = (NPY_SEARCHSIDE *)addr;
- char *str = PyString_AsString(obj);
+ NPY_SEARCHSIDE *side = (NPY_SEARCHSIDE *)addr;
+ char *str = PyString_AsString(obj);
- if (!str || strlen(str) < 1) {
- PyErr_SetString(PyExc_ValueError,
- "expected nonempty string for keyword 'side'");
- return PY_FAIL;
- }
+ if (!str || strlen(str) < 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "expected nonempty string for keyword 'side'");
+ return PY_FAIL;
+ }
- if (str[0] == 'l' || str[0] == 'L')
- *side = NPY_SEARCHLEFT;
- else if (str[0] == 'r' || str[0] == 'R')
- *side = NPY_SEARCHRIGHT;
- else {
- PyErr_Format(PyExc_ValueError,
- "'%s' is an invalid value for keyword 'side'", str);
- return PY_FAIL;
- }
- return PY_SUCCEED;
+ if (str[0] == 'l' || str[0] == 'L')
+ *side = NPY_SEARCHLEFT;
+ else if (str[0] == 'r' || str[0] == 'R')
+ *side = NPY_SEARCHRIGHT;
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "'%s' is an invalid value for keyword 'side'", str);
+ return PY_FAIL;
+ }
+ return PY_SUCCEED;
}
/*MULTIARRAY_API
- Numeric.searchsorted(a,v)
+ Numeric.searchsorted(a,v)
*/
static PyObject *
PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2, NPY_SEARCHSIDE side)
{
- PyArrayObject *ap1=NULL;
- PyArrayObject *ap2=NULL;
- PyArrayObject *ret=NULL;
- int typenum = 0;
+ PyArrayObject *ap1=NULL;
+ PyArrayObject *ap2=NULL;
+ PyArrayObject *ret=NULL;
+ int typenum = 0;
- NPY_BEGIN_THREADS_DEF
+ NPY_BEGIN_THREADS_DEF
- typenum = PyArray_ObjectType((PyObject *)op1, 0);
- typenum = PyArray_ObjectType(op2, typenum);
+ typenum = PyArray_ObjectType((PyObject *)op1, 0);
+ typenum = PyArray_ObjectType(op2, typenum);
- /* need ap1 as contiguous array and of right type */
- ap1 = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)op1,
- typenum,
- 1, 1);
- if (ap1 == NULL)
- return NULL;
-
- /* need ap2 as contiguous array and of right type */
- ap2 = (PyArrayObject *)PyArray_ContiguousFromAny(op2, typenum,
- 0, 0);
- if (ap2 == NULL)
- goto fail;
-
- /* ret is a contiguous array of intp type to hold returned indices */
- ret = (PyArrayObject *)PyArray_New(ap2->ob_type, ap2->nd,
- ap2->dimensions, PyArray_INTP,
- NULL, NULL, 0, 0, (PyObject *)ap2);
- if (ret == NULL)
- goto fail;
+ /* need ap1 as contiguous array and of right type */
+ ap1 = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)op1,
+ typenum,
+ 1, 1);
+ if (ap1 == NULL)
+ return NULL;
- /* check that comparison function exists */
- if (ap2->descr->f->compare == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "compare not supported for type");
- goto fail;
- }
+ /* need ap2 as contiguous array and of right type */
+ ap2 = (PyArrayObject *)PyArray_ContiguousFromAny(op2, typenum,
+ 0, 0);
+ if (ap2 == NULL)
+ goto fail;
+
+ /* ret is a contiguous array of intp type to hold returned indices */
+ ret = (PyArrayObject *)PyArray_New(ap2->ob_type, ap2->nd,
+ ap2->dimensions, PyArray_INTP,
+ NULL, NULL, 0, 0, (PyObject *)ap2);
+ if (ret == NULL)
+ goto fail;
+
+ /* check that comparison function exists */
+ if (ap2->descr->f->compare == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "compare not supported for type");
+ goto fail;
+ }
- if (side == NPY_SEARCHLEFT) {
- NPY_BEGIN_THREADS_DESCR(ap2->descr)
- local_search_left(ap1, ap2, ret);
- NPY_END_THREADS_DESCR(ap2->descr)
- }
- else if (side == NPY_SEARCHRIGHT) {
- NPY_BEGIN_THREADS_DESCR(ap2->descr)
- local_search_right(ap1, ap2, ret);
- NPY_END_THREADS_DESCR(ap2->descr)
- }
- Py_DECREF(ap1);
- Py_DECREF(ap2);
- return (PyObject *)ret;
+ if (side == NPY_SEARCHLEFT) {
+ NPY_BEGIN_THREADS_DESCR(ap2->descr)
+ local_search_left(ap1, ap2, ret);
+ NPY_END_THREADS_DESCR(ap2->descr)
+ }
+ else if (side == NPY_SEARCHRIGHT) {
+ NPY_BEGIN_THREADS_DESCR(ap2->descr)
+ local_search_right(ap1, ap2, ret);
+ NPY_END_THREADS_DESCR(ap2->descr)
+ }
+ Py_DECREF(ap1);
+ Py_DECREF(ap2);
+ return (PyObject *)ret;
fail:
- Py_XDECREF(ap1);
- Py_XDECREF(ap2);
- Py_XDECREF(ret);
- return NULL;
+ Py_XDECREF(ap1);
+ Py_XDECREF(ap2);
+ Py_XDECREF(ret);
+ return NULL;
}
/*
- Make a new empty array, of the passed size, of a type that takes the
- priority of ap1 and ap2 into account.
- */
+ Make a new empty array, of the passed size, of a type that takes the
+ priority of ap1 and ap2 into account.
+*/
static PyArrayObject *
new_array_for_sum(PyArrayObject *ap1, PyArrayObject *ap2,
- int nd, intp dimensions[], int typenum)
-{
- PyArrayObject *ret;
- PyTypeObject *subtype;
- double prior1, prior2;
- /* Need to choose an output array that can hold a sum
- -- use priority to determine which subtype.
- */
- if (ap2->ob_type != ap1->ob_type) {
- prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0);
- prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0);
-
- subtype = (prior2 > prior1 ? ap2->ob_type : ap1->ob_type);
- } else {
- prior1 = prior2 = 0.0;
- subtype = ap1->ob_type;
- }
-
- ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions,
- typenum, NULL, NULL, 0, 0,
- (PyObject *)
- (prior2 > prior1 ? ap2 : ap1));
- return ret;
+ int nd, intp dimensions[], int typenum)
+{
+ PyArrayObject *ret;
+ PyTypeObject *subtype;
+ double prior1, prior2;
+ /* Need to choose an output array that can hold a sum
+ -- use priority to determine which subtype.
+ */
+ if (ap2->ob_type != ap1->ob_type) {
+ prior2 = PyArray_GetPriority((PyObject *)ap2, 0.0);
+ prior1 = PyArray_GetPriority((PyObject *)ap1, 0.0);
+
+ subtype = (prior2 > prior1 ? ap2->ob_type : ap1->ob_type);
+ } else {
+ prior1 = prior2 = 0.0;
+ subtype = ap1->ob_type;
+ }
+
+ ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions,
+ typenum, NULL, NULL, 0, 0,
+ (PyObject *)
+ (prior2 > prior1 ? ap2 : ap1));
+ return ret;
}
/* Could perhaps be redone to not make contiguous arrays
*/
/*MULTIARRAY_API
- Numeric.innerproduct(a,v)
+ Numeric.innerproduct(a,v)
*/
static PyObject *
PyArray_InnerProduct(PyObject *op1, PyObject *op2)
{
- PyArrayObject *ap1, *ap2, *ret=NULL;
- PyArrayIterObject *it1, *it2;
- intp i, j, l;
- int typenum, nd, axis;
- intp is1, is2, os;
- char *op;
- intp dimensions[MAX_DIMS];
- PyArray_DotFunc *dot;
- PyArray_Descr *typec;
-
- NPY_BEGIN_THREADS_DEF
-
- typenum = PyArray_ObjectType(op1, 0);
- typenum = PyArray_ObjectType(op2, typenum);
-
- typec = PyArray_DescrFromType(typenum);
- Py_INCREF(typec);
- ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 0, 0,
- BEHAVED, NULL);
- if (ap1 == NULL) {Py_DECREF(typec); return NULL;}
- ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 0, 0,
- BEHAVED, NULL);
- if (ap2 == NULL) goto fail;
-
- if (ap1->nd == 0 || ap2->nd == 0) {
- ret = (ap1->nd == 0 ? ap1 : ap2);
- ret = (PyArrayObject *)ret->ob_type->tp_as_number->\
- nb_multiply((PyObject *)ap1, (PyObject *)ap2);
- Py_DECREF(ap1);
- Py_DECREF(ap2);
- return (PyObject *)ret;
- }
-
- l = ap1->dimensions[ap1->nd-1];
-
- if (ap2->dimensions[ap2->nd-1] != l) {
- PyErr_SetString(PyExc_ValueError, "matrices are not aligned");
- goto fail;
- }
-
- nd = ap1->nd+ap2->nd-2;
- j = 0;
- for(i=0; i<ap1->nd-1; i++) {
- dimensions[j++] = ap1->dimensions[i];
- }
- for(i=0; i<ap2->nd-1; i++) {
- dimensions[j++] = ap2->dimensions[i];
- }
-
-
- /* Need to choose an output array that can hold a sum
- -- use priority to determine which subtype.
- */
- ret = new_array_for_sum(ap1, ap2, nd, dimensions, typenum);
- if (ret == NULL) goto fail;
-
- dot = (ret->descr->f->dotfunc);
-
- if (dot == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "dot not available for this type");
- goto fail;
- }
-
- is1 = ap1->strides[ap1->nd-1];
- is2 = ap2->strides[ap2->nd-1];
- op = ret->data; os = ret->descr->elsize;
-
- axis = ap1->nd-1;
- it1 = (PyArrayIterObject *)\
- PyArray_IterAllButAxis((PyObject *)ap1, &axis);
- axis = ap2->nd-1;
- it2 = (PyArrayIterObject *)\
- PyArray_IterAllButAxis((PyObject *)ap2, &axis);
-
- NPY_BEGIN_THREADS_DESCR(ap2->descr)
- while(1) {
- while(it2->index < it2->size) {
- dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret);
- op += os;
- PyArray_ITER_NEXT(it2);
- }
- PyArray_ITER_NEXT(it1);
- if (it1->index >= it1->size) break;
- PyArray_ITER_RESET(it2);
- }
- NPY_END_THREADS_DESCR(ap2->descr)
- Py_DECREF(it1);
- Py_DECREF(it2);
-
- if (PyErr_Occurred()) goto fail;
-
-
- Py_DECREF(ap1);
- Py_DECREF(ap2);
- return (PyObject *)ret;
+ PyArrayObject *ap1, *ap2, *ret=NULL;
+ PyArrayIterObject *it1, *it2;
+ intp i, j, l;
+ int typenum, nd, axis;
+ intp is1, is2, os;
+ char *op;
+ intp dimensions[MAX_DIMS];
+ PyArray_DotFunc *dot;
+ PyArray_Descr *typec;
+
+ NPY_BEGIN_THREADS_DEF
+
+ typenum = PyArray_ObjectType(op1, 0);
+ typenum = PyArray_ObjectType(op2, typenum);
+
+ typec = PyArray_DescrFromType(typenum);
+ Py_INCREF(typec);
+ ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 0, 0,
+ BEHAVED, NULL);
+ if (ap1 == NULL) {Py_DECREF(typec); return NULL;}
+ ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 0, 0,
+ BEHAVED, NULL);
+ if (ap2 == NULL) goto fail;
+
+ if (ap1->nd == 0 || ap2->nd == 0) {
+ ret = (ap1->nd == 0 ? ap1 : ap2);
+ ret = (PyArrayObject *)ret->ob_type->tp_as_number->\
+ nb_multiply((PyObject *)ap1, (PyObject *)ap2);
+ Py_DECREF(ap1);
+ Py_DECREF(ap2);
+ return (PyObject *)ret;
+ }
+
+ l = ap1->dimensions[ap1->nd-1];
+
+ if (ap2->dimensions[ap2->nd-1] != l) {
+ PyErr_SetString(PyExc_ValueError, "matrices are not aligned");
+ goto fail;
+ }
+
+ nd = ap1->nd+ap2->nd-2;
+ j = 0;
+ for(i=0; i<ap1->nd-1; i++) {
+ dimensions[j++] = ap1->dimensions[i];
+ }
+ for(i=0; i<ap2->nd-1; i++) {
+ dimensions[j++] = ap2->dimensions[i];
+ }
+
+
+ /* Need to choose an output array that can hold a sum
+ -- use priority to determine which subtype.
+ */
+ ret = new_array_for_sum(ap1, ap2, nd, dimensions, typenum);
+ if (ret == NULL) goto fail;
+
+ dot = (ret->descr->f->dotfunc);
+
+ if (dot == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "dot not available for this type");
+ goto fail;
+ }
+
+ is1 = ap1->strides[ap1->nd-1];
+ is2 = ap2->strides[ap2->nd-1];
+ op = ret->data; os = ret->descr->elsize;
+
+ axis = ap1->nd-1;
+ it1 = (PyArrayIterObject *)\
+ PyArray_IterAllButAxis((PyObject *)ap1, &axis);
+ axis = ap2->nd-1;
+ it2 = (PyArrayIterObject *)\
+ PyArray_IterAllButAxis((PyObject *)ap2, &axis);
+
+ NPY_BEGIN_THREADS_DESCR(ap2->descr)
+ while(1) {
+ while(it2->index < it2->size) {
+ dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret);
+ op += os;
+ PyArray_ITER_NEXT(it2);
+ }
+ PyArray_ITER_NEXT(it1);
+ if (it1->index >= it1->size) break;
+ PyArray_ITER_RESET(it2);
+ }
+ NPY_END_THREADS_DESCR(ap2->descr)
+ Py_DECREF(it1);
+ Py_DECREF(it2);
+
+ if (PyErr_Occurred()) goto fail;
+
+
+ Py_DECREF(ap1);
+ Py_DECREF(ap2);
+ return (PyObject *)ret;
fail:
- Py_XDECREF(ap1);
- Py_XDECREF(ap2);
- Py_XDECREF(ret);
- return NULL;
+ Py_XDECREF(ap1);
+ Py_XDECREF(ap2);
+ Py_XDECREF(ret);
+ return NULL;
}
/* just like inner product but does the swapaxes stuff on the fly */
/*MULTIARRAY_API
- Numeric.matrixproduct(a,v)
+ Numeric.matrixproduct(a,v)
*/
static PyObject *
PyArray_MatrixProduct(PyObject *op1, PyObject *op2)
{
- PyArrayObject *ap1, *ap2, *ret=NULL;
- PyArrayIterObject *it1, *it2;
- intp i, j, l;
- int typenum, nd, axis, matchDim;
- intp is1, is2, os;
- char *op;
- intp dimensions[MAX_DIMS];
- PyArray_DotFunc *dot;
- PyArray_Descr *typec;
-
- NPY_BEGIN_THREADS_DEF
-
- typenum = PyArray_ObjectType(op1, 0);
- typenum = PyArray_ObjectType(op2, typenum);
-
- typec = PyArray_DescrFromType(typenum);
- Py_INCREF(typec);
- ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 0, 0,
- BEHAVED, NULL);
- if (ap1 == NULL) {Py_DECREF(typec); return NULL;}
- ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 0, 0,
- BEHAVED, NULL);
- if (ap2 == NULL) goto fail;
-
- if (ap1->nd == 0 || ap2->nd == 0) {
- ret = (ap1->nd == 0 ? ap1 : ap2);
- ret = (PyArrayObject *)ret->ob_type->tp_as_number->\
- nb_multiply((PyObject *)ap1, (PyObject *)ap2);
- Py_DECREF(ap1);
- Py_DECREF(ap2);
- return (PyObject *)ret;
- }
-
- l = ap1->dimensions[ap1->nd-1];
- if (ap2->nd > 1) {
- matchDim = ap2->nd - 2;
- }
- else {
- matchDim = 0;
- }
-
- if (ap2->dimensions[matchDim] != l) {
- PyErr_SetString(PyExc_ValueError, "objects are not aligned");
- goto fail;
- }
-
- nd = ap1->nd+ap2->nd-2;
- if (nd > NPY_MAXDIMS) {
- PyErr_SetString(PyExc_ValueError,
- "dot: too many dimensions in result");
- goto fail;
+ PyArrayObject *ap1, *ap2, *ret=NULL;
+ PyArrayIterObject *it1, *it2;
+ intp i, j, l;
+ int typenum, nd, axis, matchDim;
+ intp is1, is2, os;
+ char *op;
+ intp dimensions[MAX_DIMS];
+ PyArray_DotFunc *dot;
+ PyArray_Descr *typec;
+
+ NPY_BEGIN_THREADS_DEF
+
+ typenum = PyArray_ObjectType(op1, 0);
+ typenum = PyArray_ObjectType(op2, typenum);
+
+ typec = PyArray_DescrFromType(typenum);
+ Py_INCREF(typec);
+ ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 0, 0,
+ BEHAVED, NULL);
+ if (ap1 == NULL) {Py_DECREF(typec); return NULL;}
+ ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 0, 0,
+ BEHAVED, NULL);
+ if (ap2 == NULL) goto fail;
+
+ if (ap1->nd == 0 || ap2->nd == 0) {
+ ret = (ap1->nd == 0 ? ap1 : ap2);
+ ret = (PyArrayObject *)ret->ob_type->tp_as_number->\
+ nb_multiply((PyObject *)ap1, (PyObject *)ap2);
+ Py_DECREF(ap1);
+ Py_DECREF(ap2);
+ return (PyObject *)ret;
+ }
+
+ l = ap1->dimensions[ap1->nd-1];
+ if (ap2->nd > 1) {
+ matchDim = ap2->nd - 2;
+ }
+ else {
+ matchDim = 0;
+ }
+
+ if (ap2->dimensions[matchDim] != l) {
+ PyErr_SetString(PyExc_ValueError, "objects are not aligned");
+ goto fail;
+ }
+
+ nd = ap1->nd+ap2->nd-2;
+ if (nd > NPY_MAXDIMS) {
+ PyErr_SetString(PyExc_ValueError,
+ "dot: too many dimensions in result");
+ goto fail;
+ }
+ j = 0;
+ for(i=0; i<ap1->nd-1; i++) {
+ dimensions[j++] = ap1->dimensions[i];
+ }
+ for(i=0; i<ap2->nd-2; i++) {
+ dimensions[j++] = ap2->dimensions[i];
+ }
+ if(ap2->nd > 1) {
+ dimensions[j++] = ap2->dimensions[ap2->nd-1];
+ }
+ /*
+ fprintf(stderr, "nd=%d dimensions=", nd);
+ for(i=0; i<j; i++)
+ fprintf(stderr, "%d ", dimensions[i]);
+ fprintf(stderr, "\n");
+ */
+
+ is1 = ap1->strides[ap1->nd-1]; is2 = ap2->strides[matchDim];
+
+ /* Choose which subtype to return */
+ ret = new_array_for_sum(ap1, ap2, nd, dimensions, typenum);
+ if (ret == NULL) goto fail;
+
+ /* Ensure that multiarray.dot(<Nx0>,<0xM>) -> zeros((N,M)) */
+ if (PyArray_SIZE(ap1) == 0 && PyArray_SIZE(ap2) == 0) {
+ memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret));
+ }
+ else { /* Ensure that multiarray.dot([],[]) -> 0 */
+ memset(PyArray_DATA(ret), 0, PyArray_ITEMSIZE(ret));
+ }
+
+
+ dot = ret->descr->f->dotfunc;
+ if (dot == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "dot not available for this type");
+ goto fail;
+ }
+
+ op = ret->data; os = ret->descr->elsize;
+
+ axis = ap1->nd-1;
+ it1 = (PyArrayIterObject *)\
+ PyArray_IterAllButAxis((PyObject *)ap1, &axis);
+ it2 = (PyArrayIterObject *)\
+ PyArray_IterAllButAxis((PyObject *)ap2, &matchDim);
+
+ NPY_BEGIN_THREADS_DESCR(ap2->descr)
+ while(1) {
+ while(it2->index < it2->size) {
+ dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret);
+ op += os;
+ PyArray_ITER_NEXT(it2);
+ }
+ PyArray_ITER_NEXT(it1);
+ if (it1->index >= it1->size) break;
+ PyArray_ITER_RESET(it2);
}
- j = 0;
- for(i=0; i<ap1->nd-1; i++) {
- dimensions[j++] = ap1->dimensions[i];
- }
- for(i=0; i<ap2->nd-2; i++) {
- dimensions[j++] = ap2->dimensions[i];
- }
- if(ap2->nd > 1) {
- dimensions[j++] = ap2->dimensions[ap2->nd-1];
- }
- /*
- fprintf(stderr, "nd=%d dimensions=", nd);
- for(i=0; i<j; i++)
- fprintf(stderr, "%d ", dimensions[i]);
- fprintf(stderr, "\n");
- */
-
- is1 = ap1->strides[ap1->nd-1]; is2 = ap2->strides[matchDim];
-
- /* Choose which subtype to return */
- ret = new_array_for_sum(ap1, ap2, nd, dimensions, typenum);
- if (ret == NULL) goto fail;
-
- /* Ensure that multiarray.dot(<Nx0>,<0xM>) -> zeros((N,M)) */
- if (PyArray_SIZE(ap1) == 0 && PyArray_SIZE(ap2) == 0) {
- memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret));
- }
- else { /* Ensure that multiarray.dot([],[]) -> 0 */
- memset(PyArray_DATA(ret), 0, PyArray_ITEMSIZE(ret));
- }
-
-
- dot = ret->descr->f->dotfunc;
- if (dot == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "dot not available for this type");
- goto fail;
- }
-
- op = ret->data; os = ret->descr->elsize;
-
- axis = ap1->nd-1;
- it1 = (PyArrayIterObject *)\
- PyArray_IterAllButAxis((PyObject *)ap1, &axis);
- it2 = (PyArrayIterObject *)\
- PyArray_IterAllButAxis((PyObject *)ap2, &matchDim);
-
- NPY_BEGIN_THREADS_DESCR(ap2->descr)
- while(1) {
- while(it2->index < it2->size) {
- dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret);
- op += os;
- PyArray_ITER_NEXT(it2);
- }
- PyArray_ITER_NEXT(it1);
- if (it1->index >= it1->size) break;
- PyArray_ITER_RESET(it2);
- }
- NPY_END_THREADS_DESCR(ap2->descr)
- Py_DECREF(it1);
- Py_DECREF(it2);
- if (PyErr_Occurred()) goto fail; /* only for OBJECT arrays */
-
- Py_DECREF(ap1);
- Py_DECREF(ap2);
- return (PyObject *)ret;
+ NPY_END_THREADS_DESCR(ap2->descr)
+ Py_DECREF(it1);
+ Py_DECREF(it2);
+ if (PyErr_Occurred()) goto fail; /* only for OBJECT arrays */
+
+ Py_DECREF(ap1);
+ Py_DECREF(ap2);
+ return (PyObject *)ret;
fail:
- Py_XDECREF(ap1);
- Py_XDECREF(ap2);
- Py_XDECREF(ret);
- return NULL;
+ Py_XDECREF(ap1);
+ Py_XDECREF(ap2);
+ Py_XDECREF(ret);
+ return NULL;
}
/*MULTIARRAY_API
- Fast Copy and Transpose
+ Fast Copy and Transpose
*/
static PyObject *
PyArray_CopyAndTranspose(PyObject *op)
{
- PyObject *ret, *arr;
- int nd;
- intp dims[2];
- intp i,j;
- int elsize, str2;
- char *iptr;
- char *optr;
-
- /* make sure it is well-behaved */
- arr = PyArray_FromAny(op, NULL, 0, 0, CARRAY, NULL);
- nd = PyArray_NDIM(arr);
- if (nd == 1) { /* we will give in to old behavior */
- ret = PyArray_Copy((PyArrayObject *)arr);
- Py_DECREF(arr);
- return ret;
- }
- else if (nd != 2) {
- Py_DECREF(arr);
- PyErr_SetString(PyExc_ValueError,
- "only 2-d arrays are allowed");
- return NULL;
- }
-
- /* Now construct output array */
- dims[0] = PyArray_DIM(arr,1);
- dims[1] = PyArray_DIM(arr,0);
- elsize = PyArray_ITEMSIZE(arr);
-
- Py_INCREF(PyArray_DESCR(arr));
- ret = PyArray_NewFromDescr(arr->ob_type,
- PyArray_DESCR(arr),
- 2, dims,
- NULL, NULL, 0, arr);
-
- if (ret == NULL) {
- Py_DECREF(arr);
- return NULL;
- }
- /* do 2-d loop */
- NPY_BEGIN_ALLOW_THREADS
- optr = PyArray_DATA(ret);
- str2 = elsize*dims[0];
- for (i=0; i<dims[0]; i++) {
- iptr = PyArray_BYTES(arr) + i*elsize;
- for (j=0; j<dims[1]; j++) {
- /* optr[i,j] = iptr[j,i] */
- memcpy(optr, iptr, elsize);
- optr += elsize;
- iptr += str2;
- }
- }
- NPY_END_ALLOW_THREADS
- Py_DECREF(arr);
- return ret;
+ PyObject *ret, *arr;
+ int nd;
+ intp dims[2];
+ intp i,j;
+ int elsize, str2;
+ char *iptr;
+ char *optr;
+
+ /* make sure it is well-behaved */
+ arr = PyArray_FromAny(op, NULL, 0, 0, CARRAY, NULL);
+ nd = PyArray_NDIM(arr);
+ if (nd == 1) { /* we will give in to old behavior */
+ ret = PyArray_Copy((PyArrayObject *)arr);
+ Py_DECREF(arr);
+ return ret;
+ }
+ else if (nd != 2) {
+ Py_DECREF(arr);
+ PyErr_SetString(PyExc_ValueError,
+ "only 2-d arrays are allowed");
+ return NULL;
+ }
+
+ /* Now construct output array */
+ dims[0] = PyArray_DIM(arr,1);
+ dims[1] = PyArray_DIM(arr,0);
+ elsize = PyArray_ITEMSIZE(arr);
+
+ Py_INCREF(PyArray_DESCR(arr));
+ ret = PyArray_NewFromDescr(arr->ob_type,
+ PyArray_DESCR(arr),
+ 2, dims,
+ NULL, NULL, 0, arr);
+
+ if (ret == NULL) {
+ Py_DECREF(arr);
+ return NULL;
+ }
+ /* do 2-d loop */
+ NPY_BEGIN_ALLOW_THREADS
+ optr = PyArray_DATA(ret);
+ str2 = elsize*dims[0];
+ for (i=0; i<dims[0]; i++) {
+ iptr = PyArray_BYTES(arr) + i*elsize;
+ for (j=0; j<dims[1]; j++) {
+ /* optr[i,j] = iptr[j,i] */
+ memcpy(optr, iptr, elsize);
+ optr += elsize;
+ iptr += str2;
+ }
+ }
+ NPY_END_ALLOW_THREADS
+ Py_DECREF(arr);
+ return ret;
}
/*MULTIARRAY_API
- Numeric.correlate(a1,a2,mode)
+ Numeric.correlate(a1,a2,mode)
*/
static PyObject *
PyArray_Correlate(PyObject *op1, PyObject *op2, int mode)
{
- PyArrayObject *ap1, *ap2, *ret=NULL;
- intp length;
- intp i, n1, n2, n, n_left, n_right;
- int typenum;
- intp is1, is2, os;
- char *ip1, *ip2, *op;
- PyArray_DotFunc *dot;
- PyArray_Descr *typec;
-
- NPY_BEGIN_THREADS_DEF
-
- typenum = PyArray_ObjectType(op1, 0);
- typenum = PyArray_ObjectType(op2, typenum);
-
- typec = PyArray_DescrFromType(typenum);
- Py_INCREF(typec);
- ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 1, 1,
- DEFAULT, NULL);
- if (ap1 == NULL) {Py_DECREF(typec); return NULL;}
- ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 1, 1,
- DEFAULT, NULL);
- if (ap2 == NULL) goto fail;
-
- n1 = ap1->dimensions[0];
- n2 = ap2->dimensions[0];
-
- if (n1 < n2) {
- ret = ap1; ap1 = ap2; ap2 = ret;
- ret = NULL; i = n1;n1=n2;n2=i;
- }
- length = n1;
- n = n2;
- switch(mode) {
- case 0:
- length = length-n+1;
- n_left = n_right = 0;
- break;
- case 1:
- n_left = (intp)(n/2);
- n_right = n-n_left-1;
- break;
- case 2:
- n_right = n-1;
- n_left = n-1;
- length = length+n-1;
- break;
- default:
- PyErr_SetString(PyExc_ValueError,
- "mode must be 0, 1, or 2");
- goto fail;
- }
-
- /* Need to choose an output array that can hold a sum
- -- use priority to determine which subtype.
- */
- ret = new_array_for_sum(ap1, ap2, 1, &length, typenum);
- if (ret == NULL) goto fail;
-
- dot = ret->descr->f->dotfunc;
- if (dot == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "function not available for this data type");
- goto fail;
- }
-
- NPY_BEGIN_THREADS_DESCR(ret->descr)
-
- is1 = ap1->strides[0]; is2 = ap2->strides[0];
- op = ret->data; os = ret->descr->elsize;
-
- ip1 = ap1->data; ip2 = ap2->data+n_left*is2;
- n = n-n_left;
- for(i=0; i<n_left; i++) {
- dot(ip1, is1, ip2, is2, op, n, ret);
- n++;
- ip2 -= is2;
- op += os;
- }
- for(i=0; i<(n1-n2+1); i++) {
- dot(ip1, is1, ip2, is2, op, n, ret);
- ip1 += is1;
- op += os;
- }
- for(i=0; i<n_right; i++) {
- n--;
- dot(ip1, is1, ip2, is2, op, n, ret);
- ip1 += is1;
- op += os;
- }
- NPY_END_THREADS_DESCR(ret->descr)
-
- if (PyErr_Occurred()) goto fail;
- Py_DECREF(ap1);
- Py_DECREF(ap2);
- return (PyObject *)ret;
+ PyArrayObject *ap1, *ap2, *ret=NULL;
+ intp length;
+ intp i, n1, n2, n, n_left, n_right;
+ int typenum;
+ intp is1, is2, os;
+ char *ip1, *ip2, *op;
+ PyArray_DotFunc *dot;
+ PyArray_Descr *typec;
+
+ NPY_BEGIN_THREADS_DEF
+
+ typenum = PyArray_ObjectType(op1, 0);
+ typenum = PyArray_ObjectType(op2, typenum);
+
+ typec = PyArray_DescrFromType(typenum);
+ Py_INCREF(typec);
+ ap1 = (PyArrayObject *)PyArray_FromAny(op1, typec, 1, 1,
+ DEFAULT, NULL);
+ if (ap1 == NULL) {Py_DECREF(typec); return NULL;}
+ ap2 = (PyArrayObject *)PyArray_FromAny(op2, typec, 1, 1,
+ DEFAULT, NULL);
+ if (ap2 == NULL) goto fail;
+
+ n1 = ap1->dimensions[0];
+ n2 = ap2->dimensions[0];
+
+ if (n1 < n2) {
+ ret = ap1; ap1 = ap2; ap2 = ret;
+ ret = NULL; i = n1;n1=n2;n2=i;
+ }
+ length = n1;
+ n = n2;
+ switch(mode) {
+ case 0:
+ length = length-n+1;
+ n_left = n_right = 0;
+ break;
+ case 1:
+ n_left = (intp)(n/2);
+ n_right = n-n_left-1;
+ break;
+ case 2:
+ n_right = n-1;
+ n_left = n-1;
+ length = length+n-1;
+ break;
+ default:
+ PyErr_SetString(PyExc_ValueError,
+ "mode must be 0, 1, or 2");
+ goto fail;
+ }
+
+ /* Need to choose an output array that can hold a sum
+ -- use priority to determine which subtype.
+ */
+ ret = new_array_for_sum(ap1, ap2, 1, &length, typenum);
+ if (ret == NULL) goto fail;
+
+ dot = ret->descr->f->dotfunc;
+ if (dot == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "function not available for this data type");
+ goto fail;
+ }
+
+ NPY_BEGIN_THREADS_DESCR(ret->descr)
+
+ is1 = ap1->strides[0]; is2 = ap2->strides[0];
+ op = ret->data; os = ret->descr->elsize;
+
+ ip1 = ap1->data; ip2 = ap2->data+n_left*is2;
+ n = n-n_left;
+ for(i=0; i<n_left; i++) {
+ dot(ip1, is1, ip2, is2, op, n, ret);
+ n++;
+ ip2 -= is2;
+ op += os;
+ }
+ for(i=0; i<(n1-n2+1); i++) {
+ dot(ip1, is1, ip2, is2, op, n, ret);
+ ip1 += is1;
+ op += os;
+ }
+ for(i=0; i<n_right; i++) {
+ n--;
+ dot(ip1, is1, ip2, is2, op, n, ret);
+ ip1 += is1;
+ op += os;
+ }
+ NPY_END_THREADS_DESCR(ret->descr)
+
+ if (PyErr_Occurred()) goto fail;
+ Py_DECREF(ap1);
+ Py_DECREF(ap2);
+ return (PyObject *)ret;
fail:
- Py_XDECREF(ap1);
- Py_XDECREF(ap2);
- Py_XDECREF(ret);
- return NULL;
+ Py_XDECREF(ap1);
+ Py_XDECREF(ap2);
+ Py_XDECREF(ret);
+ return NULL;
}
/*MULTIARRAY_API
- ArgMin
+ ArgMin
*/
static PyObject *
PyArray_ArgMin(PyArrayObject *ap, int axis, PyArrayObject *out)
{
- PyObject *obj, *new, *ret;
+ PyObject *obj, *new, *ret;
- if (PyArray_ISFLEXIBLE(ap)) {
- PyErr_SetString(PyExc_TypeError,
- "argmax is unsupported for this type");
- return NULL;
- }
- else if (PyArray_ISUNSIGNED(ap))
- obj = PyInt_FromLong((long) -1);
+ if (PyArray_ISFLEXIBLE(ap)) {
+ PyErr_SetString(PyExc_TypeError,
+ "argmax is unsupported for this type");
+ return NULL;
+ }
+ else if (PyArray_ISUNSIGNED(ap))
+ obj = PyInt_FromLong((long) -1);
- else if (PyArray_TYPE(ap)==PyArray_BOOL)
- obj = PyInt_FromLong((long) 1);
+ else if (PyArray_TYPE(ap)==PyArray_BOOL)
+ obj = PyInt_FromLong((long) 1);
- else
- obj = PyInt_FromLong((long) 0);
+ else
+ obj = PyInt_FromLong((long) 0);
- new = PyArray_EnsureAnyArray(PyNumber_Subtract(obj, (PyObject *)ap));
- Py_DECREF(obj);
- if (new == NULL) return NULL;
- ret = PyArray_ArgMax((PyArrayObject *)new, axis, out);
- Py_DECREF(new);
- return ret;
+ new = PyArray_EnsureAnyArray(PyNumber_Subtract(obj, (PyObject *)ap));
+ Py_DECREF(obj);
+ if (new == NULL) return NULL;
+ ret = PyArray_ArgMax((PyArrayObject *)new, axis, out);
+ Py_DECREF(new);
+ return ret;
}
/*MULTIARRAY_API
- Max
+ Max
*/
static PyObject *
PyArray_Max(PyArrayObject *ap, int axis, PyArrayObject *out)
{
- PyArrayObject *arr;
- PyObject *ret;
+ PyArrayObject *arr;
+ PyObject *ret;
- if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL)
- return NULL;
- ret = PyArray_GenericReduceFunction(arr, n_ops.maximum, axis,
- arr->descr->type_num, out);
- Py_DECREF(arr);
- return ret;
+ if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL)
+ return NULL;
+ ret = PyArray_GenericReduceFunction(arr, n_ops.maximum, axis,
+ arr->descr->type_num, out);
+ Py_DECREF(arr);
+ return ret;
}
/*MULTIARRAY_API
- Min
+ Min
*/
static PyObject *
PyArray_Min(PyArrayObject *ap, int axis, PyArrayObject *out)
{
- PyArrayObject *arr;
- PyObject *ret;
+ PyArrayObject *arr;
+ PyObject *ret;
- if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL)
- return NULL;
- ret = PyArray_GenericReduceFunction(arr, n_ops.minimum, axis,
- arr->descr->type_num, out);
- Py_DECREF(arr);
- return ret;
+ if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL)
+ return NULL;
+ ret = PyArray_GenericReduceFunction(arr, n_ops.minimum, axis,
+ arr->descr->type_num, out);
+ Py_DECREF(arr);
+ return ret;
}
/*MULTIARRAY_API
- Ptp
+ Ptp
*/
static PyObject *
PyArray_Ptp(PyArrayObject *ap, int axis, PyArrayObject *out)
{
- PyArrayObject *arr;
- PyObject *ret;
- PyObject *obj1=NULL, *obj2=NULL;
-
- if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL)
- return NULL;
- obj1 = PyArray_Max(arr, axis, out);
- if (obj1 == NULL) goto fail;
- obj2 = PyArray_Min(arr, axis, NULL);
- if (obj2 == NULL) goto fail;
- Py_DECREF(arr);
- if (out) {
- ret = PyObject_CallFunction(n_ops.subtract, "OOO", out, obj2, out);
- }
- else {
- ret = PyNumber_Subtract(obj1, obj2);
- }
- Py_DECREF(obj1);
- Py_DECREF(obj2);
- return ret;
+ PyArrayObject *arr;
+ PyObject *ret;
+ PyObject *obj1=NULL, *obj2=NULL;
+
+ if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL)
+ return NULL;
+ obj1 = PyArray_Max(arr, axis, out);
+ if (obj1 == NULL) goto fail;
+ obj2 = PyArray_Min(arr, axis, NULL);
+ if (obj2 == NULL) goto fail;
+ Py_DECREF(arr);
+ if (out) {
+ ret = PyObject_CallFunction(n_ops.subtract, "OOO", out, obj2, out);
+ }
+ else {
+ ret = PyNumber_Subtract(obj1, obj2);
+ }
+ Py_DECREF(obj1);
+ Py_DECREF(obj2);
+ return ret;
fail:
- Py_XDECREF(arr);
- Py_XDECREF(obj1);
- Py_XDECREF(obj2);
- return NULL;
+ Py_XDECREF(arr);
+ Py_XDECREF(obj1);
+ Py_XDECREF(obj2);
+ return NULL;
}
/*MULTIARRAY_API
- ArgMax
+ ArgMax
*/
static PyObject *
PyArray_ArgMax(PyArrayObject *op, int axis, PyArrayObject *out)
{
- PyArrayObject *ap=NULL, *rp=NULL;
- PyArray_ArgFunc* arg_func;
- char *ip;
- intp *rptr;
- intp i, n, m;
- int elsize;
- int copyret=0;
-
- NPY_BEGIN_THREADS_DEF
-
- if ((ap=(PyAO *)_check_axis(op, &axis, 0))==NULL) return NULL;
-
- /* We need to permute the array so that axis is placed at the end.
- And all other dimensions are shifted left.
- */
- if (axis != ap->nd-1) {
- PyArray_Dims newaxes;
- intp dims[MAX_DIMS];
- int i;
- newaxes.ptr = dims;
- newaxes.len = ap->nd;
- for (i=0; i<axis; i++) dims[i] = i;
- for (i=axis; i<ap->nd-1; i++) dims[i] = i+1;
- dims[ap->nd-1] = axis;
- op = (PyAO *)PyArray_Transpose(ap, &newaxes);
- Py_DECREF(ap);
- if (op == NULL) return NULL;
- }
- else {
- op = ap;
- }
-
- ap = (PyArrayObject *)\
- PyArray_ContiguousFromAny((PyObject *)op,
- PyArray_NOTYPE, 1, 0);
-
- Py_DECREF(op);
- if (ap == NULL) return NULL;
-
- arg_func = ap->descr->f->argmax;
- if (arg_func == NULL) {
- PyErr_SetString(PyExc_TypeError, "data type not ordered");
- goto fail;
- }
-
- elsize = ap->descr->elsize;
- m = ap->dimensions[ap->nd-1];
- if (m == 0) {
- PyErr_SetString(MultiArrayError,
- "attempt to get argmax/argmin "\
- "of an empty sequence??");
- goto fail;
- }
-
- if (!out) {
- rp = (PyArrayObject *)PyArray_New(ap->ob_type, ap->nd-1,
- ap->dimensions, PyArray_INTP,
- NULL, NULL, 0, 0,
- (PyObject *)ap);
- if (rp == NULL) goto fail;
+ PyArrayObject *ap=NULL, *rp=NULL;
+ PyArray_ArgFunc* arg_func;
+ char *ip;
+ intp *rptr;
+ intp i, n, m;
+ int elsize;
+ int copyret=0;
+
+ NPY_BEGIN_THREADS_DEF
+
+ if ((ap=(PyAO *)_check_axis(op, &axis, 0))==NULL) return NULL;
+
+ /* We need to permute the array so that axis is placed at the end.
+ And all other dimensions are shifted left.
+ */
+ if (axis != ap->nd-1) {
+ PyArray_Dims newaxes;
+ intp dims[MAX_DIMS];
+ int i;
+ newaxes.ptr = dims;
+ newaxes.len = ap->nd;
+ for (i=0; i<axis; i++) dims[i] = i;
+ for (i=axis; i<ap->nd-1; i++) dims[i] = i+1;
+ dims[ap->nd-1] = axis;
+ op = (PyAO *)PyArray_Transpose(ap, &newaxes);
+ Py_DECREF(ap);
+ if (op == NULL) return NULL;
+ }
+ else {
+ op = ap;
+ }
+
+ ap = (PyArrayObject *)\
+ PyArray_ContiguousFromAny((PyObject *)op,
+ PyArray_NOTYPE, 1, 0);
+
+ Py_DECREF(op);
+ if (ap == NULL) return NULL;
+
+ arg_func = ap->descr->f->argmax;
+ if (arg_func == NULL) {
+ PyErr_SetString(PyExc_TypeError, "data type not ordered");
+ goto fail;
+ }
+
+ elsize = ap->descr->elsize;
+ m = ap->dimensions[ap->nd-1];
+ if (m == 0) {
+ PyErr_SetString(MultiArrayError,
+ "attempt to get argmax/argmin "\
+ "of an empty sequence??");
+ goto fail;
+ }
+
+ if (!out) {
+ rp = (PyArrayObject *)PyArray_New(ap->ob_type, ap->nd-1,
+ ap->dimensions, PyArray_INTP,
+ NULL, NULL, 0, 0,
+ (PyObject *)ap);
+ if (rp == NULL) goto fail;
+ }
+ else {
+ if (PyArray_SIZE(out) != \
+ PyArray_MultiplyList(ap->dimensions, ap->nd-1)) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid shape for output array.");
}
- else {
- if (PyArray_SIZE(out) != \
- PyArray_MultiplyList(ap->dimensions, ap->nd-1)) {
- PyErr_SetString(PyExc_TypeError,
- "invalid shape for output array.");
- }
- rp = (PyArrayObject *)\
- PyArray_FromArray(out,
- PyArray_DescrFromType(PyArray_INTP),
- NPY_CARRAY | NPY_UPDATEIFCOPY);
- if (rp == NULL) goto fail;
- if (rp != out) copyret = 1;
- }
-
- NPY_BEGIN_THREADS_DESCR(ap->descr)
- n = PyArray_SIZE(ap)/m;
- rptr = (intp *)rp->data;
- for (ip = ap->data, i=0; i<n; i++, ip+=elsize*m) {
- arg_func(ip, m, rptr, ap);
- rptr += 1;
- }
- NPY_END_THREADS_DESCR(ap->descr)
-
- Py_DECREF(ap);
- if (copyret) {
- PyArrayObject *obj;
- obj = (PyArrayObject *)rp->base;
- Py_INCREF(obj);
- Py_DECREF(rp);
- rp = obj;
- }
- return (PyObject *)rp;
+ rp = (PyArrayObject *)\
+ PyArray_FromArray(out,
+ PyArray_DescrFromType(PyArray_INTP),
+ NPY_CARRAY | NPY_UPDATEIFCOPY);
+ if (rp == NULL) goto fail;
+ if (rp != out) copyret = 1;
+ }
+
+ NPY_BEGIN_THREADS_DESCR(ap->descr)
+ n = PyArray_SIZE(ap)/m;
+ rptr = (intp *)rp->data;
+ for (ip = ap->data, i=0; i<n; i++, ip+=elsize*m) {
+ arg_func(ip, m, rptr, ap);
+ rptr += 1;
+ }
+ NPY_END_THREADS_DESCR(ap->descr)
+
+ Py_DECREF(ap);
+ if (copyret) {
+ PyArrayObject *obj;
+ obj = (PyArrayObject *)rp->base;
+ Py_INCREF(obj);
+ Py_DECREF(rp);
+ rp = obj;
+ }
+ return (PyObject *)rp;
fail:
- Py_DECREF(ap);
- Py_XDECREF(rp);
- return NULL;
+ Py_DECREF(ap);
+ Py_XDECREF(rp);
+ return NULL;
}
/*MULTIARRAY_API
- Take
+ Take
*/
static PyObject *
PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis,
PyArrayObject *ret, NPY_CLIPMODE clipmode)
{
- PyArrayObject *self, *indices;
- intp nd, i, j, n, m, max_item, tmp, chunk;
- intp shape[MAX_DIMS];
- char *src, *dest;
- int copyret=0;
-
- indices = NULL;
- self = (PyAO *)_check_axis(self0, &axis, CARRAY);
- if (self == NULL) return NULL;
-
- indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0,
- PyArray_INTP,
- 1, 0);
- if (indices == NULL) goto fail;
-
- n = m = chunk = 1;
- nd = self->nd + indices->nd - 1;
- for (i=0; i< nd; i++) {
- if (i < axis) {
- shape[i] = self->dimensions[i];
- n *= shape[i];
- } else {
- if (i < axis+indices->nd) {
- shape[i] = indices->dimensions[i-axis];
- m *= shape[i];
- } else {
- shape[i] = self->dimensions[i-indices->nd+1];
- chunk *= shape[i];
- }
- }
+ PyArrayObject *self, *indices;
+ intp nd, i, j, n, m, max_item, tmp, chunk;
+ intp shape[MAX_DIMS];
+ char *src, *dest;
+ int copyret=0;
+
+ indices = NULL;
+ self = (PyAO *)_check_axis(self0, &axis, CARRAY);
+ if (self == NULL) return NULL;
+
+ indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0,
+ PyArray_INTP,
+ 1, 0);
+ if (indices == NULL) goto fail;
+
+ n = m = chunk = 1;
+ nd = self->nd + indices->nd - 1;
+ for (i=0; i< nd; i++) {
+ if (i < axis) {
+ shape[i] = self->dimensions[i];
+ n *= shape[i];
+ } else {
+ if (i < axis+indices->nd) {
+ shape[i] = indices->dimensions[i-axis];
+ m *= shape[i];
+ } else {
+ shape[i] = self->dimensions[i-indices->nd+1];
+ chunk *= shape[i];
+ }
}
- Py_INCREF(self->descr);
- if (!ret) {
- ret = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type,
- self->descr,
- nd, shape,
- NULL, NULL, 0,
- (PyObject *)self);
+ }
+ Py_INCREF(self->descr);
+ if (!ret) {
+ ret = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type,
+ self->descr,
+ nd, shape,
+ NULL, NULL, 0,
+ (PyObject *)self);
- if (ret == NULL) goto fail;
+ if (ret == NULL) goto fail;
+ }
+ else {
+ PyArrayObject *obj;
+ int flags = NPY_CARRAY | NPY_UPDATEIFCOPY;
+
+ if ((ret->nd != nd) ||
+ !PyArray_CompareLists(ret->dimensions, shape, nd)) {
+ PyErr_SetString(PyExc_ValueError,
+ "bad shape in output array");
+ ret = NULL;
+ Py_DECREF(self->descr);
+ goto fail;
}
- else {
- PyArrayObject *obj;
- int flags = NPY_CARRAY | NPY_UPDATEIFCOPY;
-
- if ((ret->nd != nd) ||
- !PyArray_CompareLists(ret->dimensions, shape, nd)) {
- PyErr_SetString(PyExc_ValueError,
- "bad shape in output array");
- ret = NULL;
- Py_DECREF(self->descr);
- goto fail;
- }
- if (clipmode == NPY_RAISE) {
- /* we need to make sure and get a copy
- so the input array is not changed
- before the error is called
- */
- flags |= NPY_ENSURECOPY;
- }
- obj = (PyArrayObject *)PyArray_FromArray(ret, self->descr,
- flags);
- if (obj != ret) copyret = 1;
- ret = obj;
+ if (clipmode == NPY_RAISE) {
+ /* we need to make sure and get a copy
+ so the input array is not changed
+ before the error is called
+ */
+ flags |= NPY_ENSURECOPY;
}
+ obj = (PyArrayObject *)PyArray_FromArray(ret, self->descr,
+ flags);
+ if (obj != ret) copyret = 1;
+ ret = obj;
+ }
- max_item = self->dimensions[axis];
- chunk = chunk * ret->descr->elsize;
- src = self->data;
- dest = ret->data;
-
- switch(clipmode) {
- case NPY_RAISE:
- for(i=0; i<n; i++) {
- for(j=0; j<m; j++) {
- tmp = ((intp *)(indices->data))[j];
- if (tmp < 0) tmp = tmp+max_item;
- if ((tmp < 0) || (tmp >= max_item)) {
- PyErr_SetString(PyExc_IndexError,
- "index out of range "\
- "for array");
- goto fail;
- }
- memmove(dest, src+tmp*chunk, chunk);
- dest += chunk;
- }
- src += chunk*max_item;
+ max_item = self->dimensions[axis];
+ chunk = chunk * ret->descr->elsize;
+ src = self->data;
+ dest = ret->data;
+
+ switch(clipmode) {
+ case NPY_RAISE:
+ for(i=0; i<n; i++) {
+ for(j=0; j<m; j++) {
+ tmp = ((intp *)(indices->data))[j];
+ if (tmp < 0) tmp = tmp+max_item;
+ if ((tmp < 0) || (tmp >= max_item)) {
+ PyErr_SetString(PyExc_IndexError,
+ "index out of range "\
+ "for array");
+ goto fail;
}
- break;
- case NPY_WRAP:
- for(i=0; i<n; i++) {
- for(j=0; j<m; j++) {
- tmp = ((intp *)(indices->data))[j];
- if (tmp < 0) while (tmp < 0) tmp += max_item;
- else if (tmp >= max_item)
- while (tmp >= max_item)
- tmp -= max_item;
- memmove(dest, src+tmp*chunk, chunk);
- dest += chunk;
- }
- src += chunk*max_item;
- }
- break;
- case NPY_CLIP:
- for(i=0; i<n; i++) {
- for(j=0; j<m; j++) {
- tmp = ((intp *)(indices->data))[j];
- if (tmp < 0)
- tmp = 0;
- else if (tmp >= max_item)
- tmp = max_item-1;
- memmove(dest, src+tmp*chunk, chunk);
- dest += chunk;
- }
- src += chunk*max_item;
- }
- break;
+ memmove(dest, src+tmp*chunk, chunk);
+ dest += chunk;
+ }
+ src += chunk*max_item;
+ }
+ break;
+ case NPY_WRAP:
+ for(i=0; i<n; i++) {
+ for(j=0; j<m; j++) {
+ tmp = ((intp *)(indices->data))[j];
+ if (tmp < 0) while (tmp < 0) tmp += max_item;
+ else if (tmp >= max_item)
+ while (tmp >= max_item)
+ tmp -= max_item;
+ memmove(dest, src+tmp*chunk, chunk);
+ dest += chunk;
+ }
+ src += chunk*max_item;
}
+ break;
+ case NPY_CLIP:
+ for(i=0; i<n; i++) {
+ for(j=0; j<m; j++) {
+ tmp = ((intp *)(indices->data))[j];
+ if (tmp < 0)
+ tmp = 0;
+ else if (tmp >= max_item)
+ tmp = max_item-1;
+ memmove(dest, src+tmp*chunk, chunk);
+ dest += chunk;
+ }
+ src += chunk*max_item;
+ }
+ break;
+ }
- PyArray_INCREF(ret);
+ PyArray_INCREF(ret);
- Py_XDECREF(indices);
- Py_XDECREF(self);
- if (copyret) {
- PyObject *obj;
- obj = ret->base;
- Py_INCREF(obj);
- Py_DECREF(ret);
- ret = (PyArrayObject *)obj;
- }
+ Py_XDECREF(indices);
+ Py_XDECREF(self);
+ if (copyret) {
+ PyObject *obj;
+ obj = ret->base;
+ Py_INCREF(obj);
+ Py_DECREF(ret);
+ ret = (PyArrayObject *)obj;
+ }
- return (PyObject *)ret;
+ return (PyObject *)ret;
fail:
- PyArray_XDECREF_ERR(ret);
- Py_XDECREF(indices);
- Py_XDECREF(self);
- return NULL;
+ PyArray_XDECREF_ERR(ret);
+ Py_XDECREF(indices);
+ Py_XDECREF(self);
+ return NULL;
}
/*MULTIARRAY_API
- Put values into an array
+ Put values into an array
*/
static PyObject *
PyArray_PutTo(PyArrayObject *self, PyObject* values0, PyObject *indices0,
NPY_CLIPMODE clipmode)
{
- PyArrayObject *indices, *values;
- int i, chunk, ni, max_item, nv, tmp;
- char *src, *dest;
- int copied = 0;
+ PyArrayObject *indices, *values;
+ int i, chunk, ni, max_item, nv, tmp;
+ char *src, *dest;
+ int copied = 0;
- indices = NULL;
- values = NULL;
+ indices = NULL;
+ values = NULL;
- if (!PyArray_Check(self)) {
- PyErr_SetString(PyExc_TypeError,
- "put: first argument must be an array");
- return NULL;
- }
- if (!PyArray_ISCONTIGUOUS(self)) {
- PyArrayObject *obj;
- int flags = NPY_CARRAY | NPY_UPDATEIFCOPY;
- if (clipmode == NPY_RAISE) {
- flags |= NPY_ENSURECOPY;
- }
- Py_INCREF(self->descr);
- obj = (PyArrayObject *)PyArray_FromArray(self,
- self->descr, flags);
- if (obj != self) copied = 1;
- self = obj;
+ if (!PyArray_Check(self)) {
+ PyErr_SetString(PyExc_TypeError,
+ "put: first argument must be an array");
+ return NULL;
+ }
+ if (!PyArray_ISCONTIGUOUS(self)) {
+ PyArrayObject *obj;
+ int flags = NPY_CARRAY | NPY_UPDATEIFCOPY;
+ if (clipmode == NPY_RAISE) {
+ flags |= NPY_ENSURECOPY;
}
- max_item = PyArray_SIZE(self);
- dest = self->data;
- chunk = self->descr->elsize;
-
- indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0,
- PyArray_INTP, 0, 0);
- if (indices == NULL) goto fail;
- ni = PyArray_SIZE(indices);
-
Py_INCREF(self->descr);
- values = (PyArrayObject *)PyArray_FromAny(values0, self->descr, 0, 0,
- DEFAULT | FORCECAST, NULL);
- if (values == NULL) goto fail;
- nv = PyArray_SIZE(values);
- if (nv <= 0) goto finish;
- if (PyDataType_REFCHK(self->descr)) {
- switch(clipmode) {
- case NPY_RAISE:
- for(i=0; i<ni; i++) {
- src = values->data + chunk * (i % nv);
- tmp = ((intp *)(indices->data))[i];
- if (tmp < 0) tmp = tmp+max_item;
- if ((tmp < 0) || (tmp >= max_item)) {
- PyErr_SetString(PyExc_IndexError,
- "index out of " \
- "range for array");
- goto fail;
- }
- PyArray_Item_INCREF(src, self->descr);
- PyArray_Item_XDECREF(dest+tmp*chunk, self->descr);
- memmove(dest + tmp * chunk, src, chunk);
- }
- break;
- case NPY_WRAP:
- for(i=0; i<ni; i++) {
- src = values->data + chunk * (i % nv);
- tmp = ((intp *)(indices->data))[i];
- if (tmp < 0) while(tmp < 0) tmp+=max_item;
- else if (tmp >= max_item)
- while(tmp >= max_item)
- tmp -= max_item;
- PyArray_Item_INCREF(src, self->descr);
- PyArray_Item_XDECREF(dest+tmp*chunk, self->descr);
- memmove(dest + tmp * chunk, src, chunk);
- }
- break;
- case NPY_CLIP:
- for(i=0; i<ni; i++) {
- src = values->data + chunk * (i % nv);
- tmp = ((intp *)(indices->data))[i];
- if (tmp < 0) tmp = 0;
- else if (tmp >= max_item)
- tmp = max_item - 1;
- PyArray_Item_INCREF(src, self->descr);
- PyArray_Item_XDECREF(dest+tmp*chunk, self->descr);
- memmove(dest + tmp * chunk, src, chunk);
- }
- break;
+ obj = (PyArrayObject *)PyArray_FromArray(self,
+ self->descr, flags);
+ if (obj != self) copied = 1;
+ self = obj;
+ }
+ max_item = PyArray_SIZE(self);
+ dest = self->data;
+ chunk = self->descr->elsize;
+
+ indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0,
+ PyArray_INTP, 0, 0);
+ if (indices == NULL) goto fail;
+ ni = PyArray_SIZE(indices);
+
+ Py_INCREF(self->descr);
+ values = (PyArrayObject *)PyArray_FromAny(values0, self->descr, 0, 0,
+ DEFAULT | FORCECAST, NULL);
+ if (values == NULL) goto fail;
+ nv = PyArray_SIZE(values);
+ if (nv <= 0) goto finish;
+ if (PyDataType_REFCHK(self->descr)) {
+ switch(clipmode) {
+ case NPY_RAISE:
+ for(i=0; i<ni; i++) {
+ src = values->data + chunk * (i % nv);
+ tmp = ((intp *)(indices->data))[i];
+ if (tmp < 0) tmp = tmp+max_item;
+ if ((tmp < 0) || (tmp >= max_item)) {
+ PyErr_SetString(PyExc_IndexError,
+ "index out of " \
+ "range for array");
+ goto fail;
}
+ PyArray_Item_INCREF(src, self->descr);
+ PyArray_Item_XDECREF(dest+tmp*chunk, self->descr);
+ memmove(dest + tmp * chunk, src, chunk);
+ }
+ break;
+ case NPY_WRAP:
+ for(i=0; i<ni; i++) {
+ src = values->data + chunk * (i % nv);
+ tmp = ((intp *)(indices->data))[i];
+ if (tmp < 0) while(tmp < 0) tmp+=max_item;
+ else if (tmp >= max_item)
+ while(tmp >= max_item)
+ tmp -= max_item;
+ PyArray_Item_INCREF(src, self->descr);
+ PyArray_Item_XDECREF(dest+tmp*chunk, self->descr);
+ memmove(dest + tmp * chunk, src, chunk);
+ }
+ break;
+ case NPY_CLIP:
+ for(i=0; i<ni; i++) {
+ src = values->data + chunk * (i % nv);
+ tmp = ((intp *)(indices->data))[i];
+ if (tmp < 0) tmp = 0;
+ else if (tmp >= max_item)
+ tmp = max_item - 1;
+ PyArray_Item_INCREF(src, self->descr);
+ PyArray_Item_XDECREF(dest+tmp*chunk, self->descr);
+ memmove(dest + tmp * chunk, src, chunk);
+ }
+ break;
}
- else {
- switch(clipmode) {
- case NPY_RAISE:
- for(i=0; i<ni; i++) {
- src = values->data + chunk * (i % nv);
- tmp = ((intp *)(indices->data))[i];
- if (tmp < 0) tmp = tmp+max_item;
- if ((tmp < 0) || (tmp >= max_item)) {
- PyErr_SetString(PyExc_IndexError,
- "index out of " \
- "range for array");
- goto fail;
- }
- memmove(dest + tmp * chunk, src, chunk);
- }
- break;
- case NPY_WRAP:
- for(i=0; i<ni; i++) {
- src = values->data + chunk * (i % nv);
- tmp = ((intp *)(indices->data))[i];
- if (tmp < 0) while(tmp < 0) tmp+=max_item;
- else if (tmp >= max_item)
- while(tmp >= max_item)
- tmp -= max_item;
- memmove(dest + tmp * chunk, src, chunk);
- }
- break;
- case NPY_CLIP:
- for(i=0; i<ni; i++) {
- src = values->data + chunk * (i % nv);
- tmp = ((intp *)(indices->data))[i];
- if (tmp < 0) tmp = 0;
- else if (tmp >= max_item)
- tmp = max_item - 1;
- memmove(dest + tmp * chunk, src, chunk);
- }
- break;
+ }
+ else {
+ switch(clipmode) {
+ case NPY_RAISE:
+ for(i=0; i<ni; i++) {
+ src = values->data + chunk * (i % nv);
+ tmp = ((intp *)(indices->data))[i];
+ if (tmp < 0) tmp = tmp+max_item;
+ if ((tmp < 0) || (tmp >= max_item)) {
+ PyErr_SetString(PyExc_IndexError,
+ "index out of " \
+ "range for array");
+ goto fail;
}
+ memmove(dest + tmp * chunk, src, chunk);
+ }
+ break;
+ case NPY_WRAP:
+ for(i=0; i<ni; i++) {
+ src = values->data + chunk * (i % nv);
+ tmp = ((intp *)(indices->data))[i];
+ if (tmp < 0) while(tmp < 0) tmp+=max_item;
+ else if (tmp >= max_item)
+ while(tmp >= max_item)
+ tmp -= max_item;
+ memmove(dest + tmp * chunk, src, chunk);
+ }
+ break;
+ case NPY_CLIP:
+ for(i=0; i<ni; i++) {
+ src = values->data + chunk * (i % nv);
+ tmp = ((intp *)(indices->data))[i];
+ if (tmp < 0) tmp = 0;
+ else if (tmp >= max_item)
+ tmp = max_item - 1;
+ memmove(dest + tmp * chunk, src, chunk);
+ }
+ break;
}
+ }
finish:
- Py_XDECREF(values);
- Py_XDECREF(indices);
- if (copied) {
- Py_DECREF(self);
- }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_XDECREF(values);
+ Py_XDECREF(indices);
+ if (copied) {
+ Py_DECREF(self);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
fail:
- Py_XDECREF(indices);
- Py_XDECREF(values);
- if (copied) {
- PyArray_XDECREF_ERR(self);
- }
- return NULL;
+ Py_XDECREF(indices);
+ Py_XDECREF(values);
+ if (copied) {
+ PyArray_XDECREF_ERR(self);
+ }
+ return NULL;
}
static PyObject *
array_putmask(PyObject *module, PyObject *args, PyObject *kwds)
{
- PyObject *mask, *values;
- PyObject *array;
+ PyObject *mask, *values;
+ PyObject *array;
- static char *kwlist[] = {"arr", "mask", "values", NULL};
+ static char *kwlist[] = {"arr", "mask", "values", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!OO:putmask", kwlist,
- &PyArray_Type,
- &array, &mask, &values))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!OO:putmask", kwlist,
+ &PyArray_Type,
+ &array, &mask, &values))
+ return NULL;
- return PyArray_PutMask((PyArrayObject *)array, values, mask);
+ return PyArray_PutMask((PyArrayObject *)array, values, mask);
}
/*MULTIARRAY_API
- Put values into an array according to a mask.
+ Put values into an array according to a mask.
*/
static PyObject *
PyArray_PutMask(PyArrayObject *self, PyObject* values0, PyObject* mask0)
{
- PyArray_FastPutmaskFunc *func;
- PyArrayObject *mask, *values;
- int i, chunk, ni, max_item, nv, tmp;
- char *src, *dest;
- int copied=0;
+ PyArray_FastPutmaskFunc *func;
+ PyArrayObject *mask, *values;
+ int i, chunk, ni, max_item, nv, tmp;
+ char *src, *dest;
+ int copied=0;
- mask = NULL;
- values = NULL;
+ mask = NULL;
+ values = NULL;
- if (!PyArray_Check(self)) {
- PyErr_SetString(PyExc_TypeError,
- "putmask: first argument must "\
- "be an array");
- return NULL;
- }
- if (!PyArray_ISCONTIGUOUS(self)) {
- PyArrayObject *obj;
- int flags = NPY_CARRAY | NPY_UPDATEIFCOPY;
- Py_INCREF(self->descr);
- obj = (PyArrayObject *)PyArray_FromArray(self,
- self->descr, flags);
- if (obj != self) copied = 1;
- self = obj;
- }
-
- max_item = PyArray_SIZE(self);
- dest = self->data;
- chunk = self->descr->elsize;
-
- mask = (PyArrayObject *)\
- PyArray_FROM_OTF(mask0, PyArray_BOOL, CARRAY | FORCECAST);
- if (mask == NULL) goto fail;
- ni = PyArray_SIZE(mask);
- if (ni != max_item) {
- PyErr_SetString(PyExc_ValueError,
+ if (!PyArray_Check(self)) {
+ PyErr_SetString(PyExc_TypeError,
+ "putmask: first argument must "\
+ "be an array");
+ return NULL;
+ }
+ if (!PyArray_ISCONTIGUOUS(self)) {
+ PyArrayObject *obj;
+ int flags = NPY_CARRAY | NPY_UPDATEIFCOPY;
+ Py_INCREF(self->descr);
+ obj = (PyArrayObject *)PyArray_FromArray(self,
+ self->descr, flags);
+ if (obj != self) copied = 1;
+ self = obj;
+ }
+
+ max_item = PyArray_SIZE(self);
+ dest = self->data;
+ chunk = self->descr->elsize;
+
+ mask = (PyArrayObject *)\
+ PyArray_FROM_OTF(mask0, PyArray_BOOL, CARRAY | FORCECAST);
+ if (mask == NULL) goto fail;
+ ni = PyArray_SIZE(mask);
+ if (ni != max_item) {
+ PyErr_SetString(PyExc_ValueError,
"putmask: mask and data must be "\
"the same size");
- goto fail;
- }
+ goto fail;
+ }
- values = (PyArrayObject *)\
- PyArray_ContiguousFromAny(values0, self->descr->type_num, 0, 0);
- if (values == NULL) goto fail;
- nv = PyArray_SIZE(values); /* zero if null array */
- if (nv <= 0) {
- Py_XDECREF(values);
- Py_XDECREF(mask);
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyDataType_REFCHK(self->descr)) {
- for(i=0; i<ni; i++) {
- tmp = ((Bool *)(mask->data))[i];
- if (tmp) {
- src = values->data + chunk * (i % nv);
- PyArray_Item_INCREF(src, self->descr);
- PyArray_Item_XDECREF(dest+i*chunk, self->descr);
- memmove(dest + i * chunk, src, chunk);
- }
+ values = (PyArrayObject *)\
+ PyArray_ContiguousFromAny(values0, self->descr->type_num, 0, 0);
+ if (values == NULL) goto fail;
+ nv = PyArray_SIZE(values); /* zero if null array */
+ if (nv <= 0) {
+ Py_XDECREF(values);
+ Py_XDECREF(mask);
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyDataType_REFCHK(self->descr)) {
+ for(i=0; i<ni; i++) {
+ tmp = ((Bool *)(mask->data))[i];
+ if (tmp) {
+ src = values->data + chunk * (i % nv);
+ PyArray_Item_INCREF(src, self->descr);
+ PyArray_Item_XDECREF(dest+i*chunk, self->descr);
+ memmove(dest + i * chunk, src, chunk);
+ }
+ }
+ }
+ else {
+ func = self->descr->f->fastputmask;
+ if (func == NULL) {
+ for(i=0; i<ni; i++) {
+ tmp = ((Bool *)(mask->data))[i];
+ if (tmp) {
+ src = values->data + chunk * (i % nv);
+ memmove(dest + i * chunk, src, chunk);
}
+ }
}
else {
- func = self->descr->f->fastputmask;
- if (func == NULL) {
- for(i=0; i<ni; i++) {
- tmp = ((Bool *)(mask->data))[i];
- if (tmp) {
- src = values->data + chunk * (i % nv);
- memmove(dest + i * chunk, src, chunk);
- }
- }
- }
- else {
- func(dest, mask->data, ni, values->data, nv);
- }
+ func(dest, mask->data, ni, values->data, nv);
}
+ }
- Py_XDECREF(values);
- Py_XDECREF(mask);
- if (copied) {
- Py_DECREF(self);
- }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_XDECREF(values);
+ Py_XDECREF(mask);
+ if (copied) {
+ Py_DECREF(self);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
fail:
- Py_XDECREF(mask);
- Py_XDECREF(values);
- if (copied) {
- PyArray_XDECREF_ERR(self);
- }
- return NULL;
+ Py_XDECREF(mask);
+ Py_XDECREF(values);
+ if (copied) {
+ PyArray_XDECREF_ERR(self);
+ }
+ return NULL;
}
@@ -4169,266 +4169,266 @@ PyArray_PutMask(PyArrayObject *self, PyObject* values0, PyObject* mask0)
*/
/*MULTIARRAY_API
- Useful to pass as converter function for O& processing in
- PyArgs_ParseTuple.
+ Useful to pass as converter function for O& processing in
+ PyArgs_ParseTuple.
*/
static int
PyArray_Converter(PyObject *object, PyObject **address)
{
- if (PyArray_Check(object)) {
- *address = object;
- Py_INCREF(object);
- return PY_SUCCEED;
- }
- else {
- *address = PyArray_FromAny(object, NULL, 0, 0, CARRAY, NULL);
- if (*address == NULL) return PY_FAIL;
- return PY_SUCCEED;
- }
+ if (PyArray_Check(object)) {
+ *address = object;
+ Py_INCREF(object);
+ return PY_SUCCEED;
+ }
+ else {
+ *address = PyArray_FromAny(object, NULL, 0, 0, CARRAY, NULL);
+ if (*address == NULL) return PY_FAIL;
+ return PY_SUCCEED;
+ }
}
/*MULTIARRAY_API
- Useful to pass as converter function for O& processing in
- PyArgs_ParseTuple for output arrays
+ Useful to pass as converter function for O& processing in
+ PyArgs_ParseTuple for output arrays
*/
static int
PyArray_OutputConverter(PyObject *object, PyArrayObject **address)
{
- if (object == NULL || object == Py_None) {
- *address = NULL;
- return PY_SUCCEED;
- }
- if (PyArray_Check(object)) {
- *address = (PyArrayObject *)object;
- return PY_SUCCEED;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "output must be an array");
- *address = NULL;
- return PY_FAIL;
- }
+ if (object == NULL || object == Py_None) {
+ *address = NULL;
+ return PY_SUCCEED;
+ }
+ if (PyArray_Check(object)) {
+ *address = (PyArrayObject *)object;
+ return PY_SUCCEED;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "output must be an array");
+ *address = NULL;
+ return PY_FAIL;
+ }
}
/*MULTIARRAY_API
- Convert an object to true / false
+ Convert an object to true / false
*/
static int
PyArray_BoolConverter(PyObject *object, Bool *val)
{
- if (PyObject_IsTrue(object))
- *val=TRUE;
- else *val=FALSE;
- if (PyErr_Occurred())
- return PY_FAIL;
- return PY_SUCCEED;
+ if (PyObject_IsTrue(object))
+ *val=TRUE;
+ else *val=FALSE;
+ if (PyErr_Occurred())
+ return PY_FAIL;
+ return PY_SUCCEED;
}
/*MULTIARRAY_API
- Convert an object to FORTRAN / C / ANY
+ Convert an object to FORTRAN / C / ANY
*/
static int
PyArray_OrderConverter(PyObject *object, NPY_ORDER *val)
{
- char *str;
- if (object == NULL || object == Py_None) {
- *val = PyArray_ANYORDER;
- }
- else if (!PyString_Check(object) || PyString_GET_SIZE(object) < 1) {
- if (PyObject_IsTrue(object))
- *val = PyArray_FORTRANORDER;
- else
- *val = PyArray_CORDER;
- if (PyErr_Occurred())
- return PY_FAIL;
- return PY_SUCCEED;
+ char *str;
+ if (object == NULL || object == Py_None) {
+ *val = PyArray_ANYORDER;
+ }
+ else if (!PyString_Check(object) || PyString_GET_SIZE(object) < 1) {
+ if (PyObject_IsTrue(object))
+ *val = PyArray_FORTRANORDER;
+ else
+ *val = PyArray_CORDER;
+ if (PyErr_Occurred())
+ return PY_FAIL;
+ return PY_SUCCEED;
+ }
+ else {
+ str = PyString_AS_STRING(object);
+ if (str[0] == 'C' || str[0] == 'c') {
+ *val = PyArray_CORDER;
+ }
+ else if (str[0] == 'F' || str[0] == 'f') {
+ *val = PyArray_FORTRANORDER;
+ }
+ else if (str[0] == 'A' || str[0] == 'a') {
+ *val = PyArray_ANYORDER;
}
else {
- str = PyString_AS_STRING(object);
- if (str[0] == 'C' || str[0] == 'c') {
- *val = PyArray_CORDER;
- }
- else if (str[0] == 'F' || str[0] == 'f') {
- *val = PyArray_FORTRANORDER;
- }
- else if (str[0] == 'A' || str[0] == 'a') {
- *val = PyArray_ANYORDER;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "order not understood");
- return PY_FAIL;
- }
+ PyErr_SetString(PyExc_TypeError,
+ "order not understood");
+ return PY_FAIL;
}
- return PY_SUCCEED;
+ }
+ return PY_SUCCEED;
}
/*MULTIARRAY_API
- Convert an object to NPY_RAISE / NPY_CLIP / NPY_WRAP
+ Convert an object to NPY_RAISE / NPY_CLIP / NPY_WRAP
*/
static int
PyArray_ClipmodeConverter(PyObject *object, NPY_CLIPMODE *val)
{
- if (object == NULL || object == Py_None) {
- *val = NPY_RAISE;
+ if (object == NULL || object == Py_None) {
+ *val = NPY_RAISE;
+ }
+ else if (PyString_Check(object)) {
+ char *str;
+ str = PyString_AS_STRING(object);
+ if (str[0] == 'C' || str[0] == 'c') {
+ *val = NPY_CLIP;
}
- else if (PyString_Check(object)) {
- char *str;
- str = PyString_AS_STRING(object);
- if (str[0] == 'C' || str[0] == 'c') {
- *val = NPY_CLIP;
- }
- else if (str[0] == 'W' || str[0] == 'w') {
- *val = NPY_WRAP;
- }
- else if (str[0] == 'R' || str[0] == 'r') {
- *val = NPY_RAISE;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "clipmode not understood");
- return PY_FAIL;
- }
+ else if (str[0] == 'W' || str[0] == 'w') {
+ *val = NPY_WRAP;
+ }
+ else if (str[0] == 'R' || str[0] == 'r') {
+ *val = NPY_RAISE;
}
else {
- int number;
- number = PyInt_AsLong(object);
- if (number == -1 && PyErr_Occurred()) goto fail;
- if (number <= (int) NPY_RAISE &&
- number >= (int) NPY_CLIP)
- *val = (NPY_CLIPMODE) number;
- else goto fail;
+ PyErr_SetString(PyExc_TypeError,
+ "clipmode not understood");
+ return PY_FAIL;
}
- return PY_SUCCEED;
+ }
+ else {
+ int number;
+ number = PyInt_AsLong(object);
+ if (number == -1 && PyErr_Occurred()) goto fail;
+ if (number <= (int) NPY_RAISE &&
+ number >= (int) NPY_CLIP)
+ *val = (NPY_CLIPMODE) number;
+ else goto fail;
+ }
+ return PY_SUCCEED;
fail:
- PyErr_SetString(PyExc_TypeError,
- "clipmode not understood");
- return PY_FAIL;
+ PyErr_SetString(PyExc_TypeError,
+ "clipmode not understood");
+ return PY_FAIL;
}
/*MULTIARRAY_API
- Typestr converter
+ Typestr converter
*/
static int
PyArray_TypestrConvert(int itemsize, int gentype)
{
- register int newtype = gentype;
-
- if (gentype == PyArray_GENBOOLLTR) {
- if (itemsize == 1)
- newtype = PyArray_BOOL;
- else
- newtype = PyArray_NOTYPE;
- }
- else if (gentype == PyArray_SIGNEDLTR) {
- switch(itemsize) {
- case 1:
- newtype = PyArray_INT8;
- break;
- case 2:
- newtype = PyArray_INT16;
- break;
- case 4:
- newtype = PyArray_INT32;
- break;
- case 8:
- newtype = PyArray_INT64;
- break;
+ register int newtype = gentype;
+
+ if (gentype == PyArray_GENBOOLLTR) {
+ if (itemsize == 1)
+ newtype = PyArray_BOOL;
+ else
+ newtype = PyArray_NOTYPE;
+ }
+ else if (gentype == PyArray_SIGNEDLTR) {
+ switch(itemsize) {
+ case 1:
+ newtype = PyArray_INT8;
+ break;
+ case 2:
+ newtype = PyArray_INT16;
+ break;
+ case 4:
+ newtype = PyArray_INT32;
+ break;
+ case 8:
+ newtype = PyArray_INT64;
+ break;
#ifdef PyArray_INT128
- case 16:
- newtype = PyArray_INT128;
- break;
+ case 16:
+ newtype = PyArray_INT128;
+ break;
#endif
- default:
- newtype = PyArray_NOTYPE;
- }
- }
-
- else if (gentype == PyArray_UNSIGNEDLTR) {
- switch(itemsize) {
- case 1:
- newtype = PyArray_UINT8;
- break;
- case 2:
- newtype = PyArray_UINT16;
- break;
- case 4:
- newtype = PyArray_UINT32;
- break;
- case 8:
- newtype = PyArray_UINT64;
- break;
+ default:
+ newtype = PyArray_NOTYPE;
+ }
+ }
+
+ else if (gentype == PyArray_UNSIGNEDLTR) {
+ switch(itemsize) {
+ case 1:
+ newtype = PyArray_UINT8;
+ break;
+ case 2:
+ newtype = PyArray_UINT16;
+ break;
+ case 4:
+ newtype = PyArray_UINT32;
+ break;
+ case 8:
+ newtype = PyArray_UINT64;
+ break;
#ifdef PyArray_INT128
- case 16:
- newtype = PyArray_UINT128;
- break;
+ case 16:
+ newtype = PyArray_UINT128;
+ break;
#endif
- default:
- newtype = PyArray_NOTYPE;
- break;
- }
- }
- else if (gentype == PyArray_FLOATINGLTR) {
- switch(itemsize) {
- case 4:
- newtype = PyArray_FLOAT32;
- break;
- case 8:
- newtype = PyArray_FLOAT64;
- break;
+ default:
+ newtype = PyArray_NOTYPE;
+ break;
+ }
+ }
+ else if (gentype == PyArray_FLOATINGLTR) {
+ switch(itemsize) {
+ case 4:
+ newtype = PyArray_FLOAT32;
+ break;
+ case 8:
+ newtype = PyArray_FLOAT64;
+ break;
#ifdef PyArray_FLOAT80
- case 10:
- newtype = PyArray_FLOAT80;
- break;
+ case 10:
+ newtype = PyArray_FLOAT80;
+ break;
#endif
#ifdef PyArray_FLOAT96
- case 12:
- newtype = PyArray_FLOAT96;
- break;
+ case 12:
+ newtype = PyArray_FLOAT96;
+ break;
#endif
#ifdef PyArray_FLOAT128
- case 16:
- newtype = PyArray_FLOAT128;
- break;
+ case 16:
+ newtype = PyArray_FLOAT128;
+ break;
#endif
- default:
- newtype = PyArray_NOTYPE;
- }
- }
-
- else if (gentype == PyArray_COMPLEXLTR) {
- switch(itemsize) {
- case 8:
- newtype = PyArray_COMPLEX64;
- break;
- case 16:
- newtype = PyArray_COMPLEX128;
- break;
+ default:
+ newtype = PyArray_NOTYPE;
+ }
+ }
+
+ else if (gentype == PyArray_COMPLEXLTR) {
+ switch(itemsize) {
+ case 8:
+ newtype = PyArray_COMPLEX64;
+ break;
+ case 16:
+ newtype = PyArray_COMPLEX128;
+ break;
#ifdef PyArray_FLOAT80
- case 20:
- newtype = PyArray_COMPLEX160;
- break;
+ case 20:
+ newtype = PyArray_COMPLEX160;
+ break;
#endif
#ifdef PyArray_FLOAT96
- case 24:
- newtype = PyArray_COMPLEX192;
- break;
+ case 24:
+ newtype = PyArray_COMPLEX192;
+ break;
#endif
#ifdef PyArray_FLOAT128
- case 32:
- newtype = PyArray_COMPLEX256;
- break;
+ case 32:
+ newtype = PyArray_COMPLEX256;
+ break;
#endif
- default:
- newtype = PyArray_NOTYPE;
- }
- }
+ default:
+ newtype = PyArray_NOTYPE;
+ }
+ }
- return newtype;
+ return newtype;
}
@@ -4444,34 +4444,34 @@ PyArray_TypestrConvert(int itemsize, int gentype)
/*MULTIARRAY_API
- Get buffer chunk from object
+ Get buffer chunk from object
*/
static int
PyArray_BufferConverter(PyObject *obj, PyArray_Chunk *buf)
{
- Py_ssize_t buflen;
+ Py_ssize_t buflen;
- buf->ptr = NULL;
- buf->flags = BEHAVED;
- buf->base = NULL;
+ buf->ptr = NULL;
+ buf->flags = BEHAVED;
+ buf->base = NULL;
- if (obj == Py_None)
- return PY_SUCCEED;
+ if (obj == Py_None)
+ return PY_SUCCEED;
- if (PyObject_AsWriteBuffer(obj, &(buf->ptr), &buflen) < 0) {
- PyErr_Clear();
- buf->flags &= ~WRITEABLE;
- if (PyObject_AsReadBuffer(obj, (const void **)&(buf->ptr),
- &buflen) < 0)
- return PY_FAIL;
- }
- buf->len = (intp) buflen;
+ if (PyObject_AsWriteBuffer(obj, &(buf->ptr), &buflen) < 0) {
+ PyErr_Clear();
+ buf->flags &= ~WRITEABLE;
+ if (PyObject_AsReadBuffer(obj, (const void **)&(buf->ptr),
+ &buflen) < 0)
+ return PY_FAIL;
+ }
+ buf->len = (intp) buflen;
- /* Point to the base of the buffer object if present */
- if (PyBuffer_Check(obj)) buf->base = ((PyArray_Chunk *)obj)->base;
- if (buf->base == NULL) buf->base = obj;
+ /* Point to the base of the buffer object if present */
+ if (PyBuffer_Check(obj)) buf->base = ((PyArray_Chunk *)obj)->base;
+ if (buf->base == NULL) buf->base = obj;
- return PY_SUCCEED;
+ return PY_SUCCEED;
}
@@ -4484,46 +4484,46 @@ PyArray_BufferConverter(PyObject *obj, PyArray_Chunk *buf)
*/
/*MULTIARRAY_API
- Get intp chunk from sequence
+ Get intp chunk from sequence
*/
static int
PyArray_IntpConverter(PyObject *obj, PyArray_Dims *seq)
{
- int len;
- int nd;
+ int len;
+ int nd;
- seq->ptr = NULL;
- seq->len = 0;
- if (obj == Py_None) return PY_SUCCEED;
- len = PySequence_Size(obj);
- if (len == -1) { /* Check to see if it is a number */
- if (PyNumber_Check(obj)) len = 1;
+ seq->ptr = NULL;
+ seq->len = 0;
+ if (obj == Py_None) return PY_SUCCEED;
+ len = PySequence_Size(obj);
+ if (len == -1) { /* Check to see if it is a number */
+ if (PyNumber_Check(obj)) len = 1;
+ }
+ if (len < 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected sequence object with len >= 0");
+ return PY_FAIL;
+ }
+ if (len > MAX_DIMS) {
+ PyErr_Format(PyExc_ValueError, "sequence too large; " \
+ "must be smaller than %d", MAX_DIMS);
+ return PY_FAIL;
+ }
+ if (len > 0) {
+ seq->ptr = PyDimMem_NEW(len);
+ if (seq->ptr == NULL) {
+ PyErr_NoMemory();
+ return PY_FAIL;
}
- if (len < 0) {
- PyErr_SetString(PyExc_TypeError,
- "expected sequence object with len >= 0");
- return PY_FAIL;
- }
- if (len > MAX_DIMS) {
- PyErr_Format(PyExc_ValueError, "sequence too large; " \
- "must be smaller than %d", MAX_DIMS);
- return PY_FAIL;
- }
- if (len > 0) {
- seq->ptr = PyDimMem_NEW(len);
- if (seq->ptr == NULL) {
- PyErr_NoMemory();
- return PY_FAIL;
- }
- }
- seq->len = len;
- nd = PyArray_IntpFromSequence(obj, (intp *)seq->ptr, len);
- if (nd == -1 || nd != len) {
- PyDimMem_FREE(seq->ptr);
- seq->ptr=NULL;
- return PY_FAIL;
- }
- return PY_SUCCEED;
+ }
+ seq->len = len;
+ nd = PyArray_IntpFromSequence(obj, (intp *)seq->ptr, len);
+ if (nd == -1 || nd != len) {
+ PyDimMem_FREE(seq->ptr);
+ seq->ptr=NULL;
+ return PY_FAIL;
+ }
+ return PY_SUCCEED;
}
@@ -4544,239 +4544,239 @@ PyArray_IntpConverter(PyObject *obj, PyArray_Dims *seq)
static PyArray_Descr *
_use_inherit(PyArray_Descr *type, PyObject *newobj, int *errflag)
{
- PyArray_Descr *new;
- PyArray_Descr *conv;
-
- *errflag = 0;
- if (!PyArray_DescrConverter(newobj, &conv)) {
- return NULL;
- }
- *errflag = 1;
- new = PyArray_DescrNew(type);
- if (new == NULL) goto fail;
-
- if (new->elsize && new->elsize != conv->elsize) {
- PyErr_SetString(PyExc_ValueError,
- "mismatch in size of old "\
- "and new data-descriptor");
- goto fail;
- }
- new->elsize = conv->elsize;
- if (conv->names) {
- new->fields = conv->fields;
- Py_XINCREF(new->fields);
- new->names = conv->names;
- Py_XINCREF(new->names);
- }
- new->hasobject = conv->hasobject;
- Py_DECREF(conv);
- *errflag = 0;
- return new;
+ PyArray_Descr *new;
+ PyArray_Descr *conv;
+
+ *errflag = 0;
+ if (!PyArray_DescrConverter(newobj, &conv)) {
+ return NULL;
+ }
+ *errflag = 1;
+ new = PyArray_DescrNew(type);
+ if (new == NULL) goto fail;
+
+ if (new->elsize && new->elsize != conv->elsize) {
+ PyErr_SetString(PyExc_ValueError,
+ "mismatch in size of old "\
+ "and new data-descriptor");
+ goto fail;
+ }
+ new->elsize = conv->elsize;
+ if (conv->names) {
+ new->fields = conv->fields;
+ Py_XINCREF(new->fields);
+ new->names = conv->names;
+ Py_XINCREF(new->names);
+ }
+ new->hasobject = conv->hasobject;
+ Py_DECREF(conv);
+ *errflag = 0;
+ return new;
fail:
- Py_DECREF(conv);
- return NULL;
+ Py_DECREF(conv);
+ return NULL;
}
static PyArray_Descr *
_convert_from_tuple(PyObject *obj)
{
- PyArray_Descr *type, *res;
- PyObject *val;
- int errflag;
-
- if (PyTuple_GET_SIZE(obj) != 2) return NULL;
-
- if (!PyArray_DescrConverter(PyTuple_GET_ITEM(obj,0), &type))
- return NULL;
- val = PyTuple_GET_ITEM(obj,1);
- /* try to interpret next item as a type */
- res = _use_inherit(type, val, &errflag);
- if (res || errflag) {
- Py_DECREF(type);
- if (res) return res;
- else return NULL;
- }
- PyErr_Clear();
- /* We get here if res was NULL but errflag wasn't set
- --- i.e. the conversion to a data-descr failed in _use_inherit
- */
-
- if (type->elsize == 0) { /* interpret next item as a typesize */
- int itemsize;
- itemsize = PyArray_PyIntAsInt(PyTuple_GET_ITEM(obj,1));
- if (error_converting(itemsize)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid itemsize in generic type "\
- "tuple");
- goto fail;
- }
- PyArray_DESCR_REPLACE(type);
- if (type->type_num == PyArray_UNICODE)
- type->elsize = itemsize << 2;
- else
- type->elsize = itemsize;
- }
- else {
- /* interpret next item as shape (if it's a tuple)
- and reset the type to PyArray_VOID with
- a new fields attribute.
- */
- PyArray_Dims shape={NULL,-1};
- PyArray_Descr *newdescr;
- if (!(PyArray_IntpConverter(val, &shape)) ||
- (shape.len > MAX_DIMS)) {
- PyDimMem_FREE(shape.ptr);
- PyErr_SetString(PyExc_ValueError,
- "invalid shape in fixed-type tuple.");
- goto fail;
- }
- /* If (type, 1) was given, it is equivalent to type...
- or (type, ()) was given it is equivalent to type... */
- if ((shape.len == 1 && shape.ptr[0] == 1 && PyNumber_Check(val)) || \
- (shape.len == 0 && PyTuple_Check(val))) {
- PyDimMem_FREE(shape.ptr);
- return type;
- }
- newdescr = PyArray_DescrNewFromType(PyArray_VOID);
- if (newdescr == NULL) {PyDimMem_FREE(shape.ptr); goto fail;}
- newdescr->elsize = type->elsize;
- newdescr->elsize *= PyArray_MultiplyList(shape.ptr,
- shape.len);
- PyDimMem_FREE(shape.ptr);
- newdescr->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
- newdescr->subarray->base = type;
- newdescr->hasobject = type->hasobject;
- Py_INCREF(val);
- newdescr->subarray->shape = val;
- Py_XDECREF(newdescr->fields);
- Py_XDECREF(newdescr->names);
- newdescr->fields = NULL;
- newdescr->names = NULL;
- type = newdescr;
- }
- return type;
+ PyArray_Descr *type, *res;
+ PyObject *val;
+ int errflag;
+
+ if (PyTuple_GET_SIZE(obj) != 2) return NULL;
+
+ if (!PyArray_DescrConverter(PyTuple_GET_ITEM(obj,0), &type))
+ return NULL;
+ val = PyTuple_GET_ITEM(obj,1);
+ /* try to interpret next item as a type */
+ res = _use_inherit(type, val, &errflag);
+ if (res || errflag) {
+ Py_DECREF(type);
+ if (res) return res;
+ else return NULL;
+ }
+ PyErr_Clear();
+ /* We get here if res was NULL but errflag wasn't set
+ --- i.e. the conversion to a data-descr failed in _use_inherit
+ */
+
+ if (type->elsize == 0) { /* interpret next item as a typesize */
+ int itemsize;
+ itemsize = PyArray_PyIntAsInt(PyTuple_GET_ITEM(obj,1));
+ if (error_converting(itemsize)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid itemsize in generic type "\
+ "tuple");
+ goto fail;
+ }
+ PyArray_DESCR_REPLACE(type);
+ if (type->type_num == PyArray_UNICODE)
+ type->elsize = itemsize << 2;
+ else
+ type->elsize = itemsize;
+ }
+ else {
+ /* interpret next item as shape (if it's a tuple)
+ and reset the type to PyArray_VOID with
+ a new fields attribute.
+ */
+ PyArray_Dims shape={NULL,-1};
+ PyArray_Descr *newdescr;
+ if (!(PyArray_IntpConverter(val, &shape)) ||
+ (shape.len > MAX_DIMS)) {
+ PyDimMem_FREE(shape.ptr);
+ PyErr_SetString(PyExc_ValueError,
+ "invalid shape in fixed-type tuple.");
+ goto fail;
+ }
+ /* If (type, 1) was given, it is equivalent to type...
+ or (type, ()) was given it is equivalent to type... */
+ if ((shape.len == 1 && shape.ptr[0] == 1 && PyNumber_Check(val)) || \
+ (shape.len == 0 && PyTuple_Check(val))) {
+ PyDimMem_FREE(shape.ptr);
+ return type;
+ }
+ newdescr = PyArray_DescrNewFromType(PyArray_VOID);
+ if (newdescr == NULL) {PyDimMem_FREE(shape.ptr); goto fail;}
+ newdescr->elsize = type->elsize;
+ newdescr->elsize *= PyArray_MultiplyList(shape.ptr,
+ shape.len);
+ PyDimMem_FREE(shape.ptr);
+ newdescr->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
+ newdescr->subarray->base = type;
+ newdescr->hasobject = type->hasobject;
+ Py_INCREF(val);
+ newdescr->subarray->shape = val;
+ Py_XDECREF(newdescr->fields);
+ Py_XDECREF(newdescr->names);
+ newdescr->fields = NULL;
+ newdescr->names = NULL;
+ type = newdescr;
+ }
+ return type;
fail:
- Py_XDECREF(type);
- return NULL;
+ Py_XDECREF(type);
+ return NULL;
}
/* obj is a list. Each item is a tuple with
-(field-name, data-type (either a list or a string), and an optional
- shape parameter).
+ (field-name, data-type (either a list or a string), and an optional
+ shape parameter).
*/
static PyArray_Descr *
_convert_from_array_descr(PyObject *obj, int align)
{
- int n, i, totalsize;
- int ret;
- PyObject *fields, *item, *newobj;
- PyObject *name, *tup, *title;
- PyObject *nameslist;
- PyArray_Descr *new;
- PyArray_Descr *conv;
- int dtypeflags=0;
- int maxalign = 0;
-
-
- n = PyList_GET_SIZE(obj);
- nameslist = PyTuple_New(n);
- if (!nameslist) return NULL;
- totalsize = 0;
- fields = PyDict_New();
- for (i=0; i<n; i++) {
- item = PyList_GET_ITEM(obj, i);
- if (!PyTuple_Check(item) || (PyTuple_GET_SIZE(item) < 2))
- goto fail;
- name = PyTuple_GET_ITEM(item, 0);
- if (PyString_Check(name)) {
- title=NULL;
- }
- else if (PyTuple_Check(name)) {
- if (PyTuple_GET_SIZE(name) != 2) goto fail;
- title = PyTuple_GET_ITEM(name, 0);
- name = PyTuple_GET_ITEM(name, 1);
- if (!PyString_Check(name))
- goto fail;
- }
- else goto fail;
- if (PyString_GET_SIZE(name)==0) {
- if (title==NULL)
- name = PyString_FromFormat("f%d", i);
- else {
- name = title;
- Py_INCREF(name);
- }
- }
- else {
- Py_INCREF(name);
- }
- PyTuple_SET_ITEM(nameslist, i, name);
- if (PyTuple_GET_SIZE(item) == 2) {
- ret = PyArray_DescrConverter(PyTuple_GET_ITEM(item, 1),
- &conv);
- if (ret == PY_FAIL)
- PyObject_Print(PyTuple_GET_ITEM(item,1),
- stderr, 0);
- }
- else if (PyTuple_GET_SIZE(item) == 3) {
- newobj = PyTuple_GetSlice(item, 1, 3);
- ret = PyArray_DescrConverter(newobj, &conv);
- Py_DECREF(newobj);
- }
- else goto fail;
- if (ret == PY_FAIL) goto fail;
- if ((PyDict_GetItem(fields, name) != NULL) ||
- (title &&
- (PyString_Check(title) || PyUnicode_Check(title)) &&
- (PyDict_GetItem(fields, title) != NULL))) {
- PyErr_SetString(PyExc_ValueError,
- "two fields with the same name");
- goto fail;
- }
- dtypeflags |= (conv->hasobject & NPY_FROM_FIELDS);
- tup = PyTuple_New((title == NULL ? 2 : 3));
- PyTuple_SET_ITEM(tup, 0, (PyObject *)conv);
- if (align) {
- int _align;
- _align = conv->alignment;
- if (_align > 1) totalsize = \
- ((totalsize + _align - 1)/_align)*_align;
- maxalign = MAX(maxalign, _align);
- }
- PyTuple_SET_ITEM(tup, 1, PyInt_FromLong((long) totalsize));
-
- /* Title can be "meta-data". Only insert it
- into the fields dictionary if it is a string
- */
- if (title != NULL) {
- Py_INCREF(title);
- PyTuple_SET_ITEM(tup, 2, title);
- if (PyString_Check(title) || PyUnicode_Check(title))
- PyDict_SetItem(fields, title, tup);
- }
- PyDict_SetItem(fields, name, tup);
- totalsize += conv->elsize;
- Py_DECREF(tup);
- }
- new = PyArray_DescrNewFromType(PyArray_VOID);
- new->fields = fields;
- new->names = nameslist;
- new->elsize = totalsize;
- new->hasobject=dtypeflags;
- if (maxalign > 1) {
- totalsize = ((totalsize+maxalign-1)/maxalign)*maxalign;
- }
- if (align) new->alignment = maxalign;
- return new;
+ int n, i, totalsize;
+ int ret;
+ PyObject *fields, *item, *newobj;
+ PyObject *name, *tup, *title;
+ PyObject *nameslist;
+ PyArray_Descr *new;
+ PyArray_Descr *conv;
+ int dtypeflags=0;
+ int maxalign = 0;
+
+
+ n = PyList_GET_SIZE(obj);
+ nameslist = PyTuple_New(n);
+ if (!nameslist) return NULL;
+ totalsize = 0;
+ fields = PyDict_New();
+ for (i=0; i<n; i++) {
+ item = PyList_GET_ITEM(obj, i);
+ if (!PyTuple_Check(item) || (PyTuple_GET_SIZE(item) < 2))
+ goto fail;
+ name = PyTuple_GET_ITEM(item, 0);
+ if (PyString_Check(name)) {
+ title=NULL;
+ }
+ else if (PyTuple_Check(name)) {
+ if (PyTuple_GET_SIZE(name) != 2) goto fail;
+ title = PyTuple_GET_ITEM(name, 0);
+ name = PyTuple_GET_ITEM(name, 1);
+ if (!PyString_Check(name))
+ goto fail;
+ }
+ else goto fail;
+ if (PyString_GET_SIZE(name)==0) {
+ if (title==NULL)
+ name = PyString_FromFormat("f%d", i);
+ else {
+ name = title;
+ Py_INCREF(name);
+ }
+ }
+ else {
+ Py_INCREF(name);
+ }
+ PyTuple_SET_ITEM(nameslist, i, name);
+ if (PyTuple_GET_SIZE(item) == 2) {
+ ret = PyArray_DescrConverter(PyTuple_GET_ITEM(item, 1),
+ &conv);
+ if (ret == PY_FAIL)
+ PyObject_Print(PyTuple_GET_ITEM(item,1),
+ stderr, 0);
+ }
+ else if (PyTuple_GET_SIZE(item) == 3) {
+ newobj = PyTuple_GetSlice(item, 1, 3);
+ ret = PyArray_DescrConverter(newobj, &conv);
+ Py_DECREF(newobj);
+ }
+ else goto fail;
+ if (ret == PY_FAIL) goto fail;
+ if ((PyDict_GetItem(fields, name) != NULL) ||
+ (title &&
+ (PyString_Check(title) || PyUnicode_Check(title)) &&
+ (PyDict_GetItem(fields, title) != NULL))) {
+ PyErr_SetString(PyExc_ValueError,
+ "two fields with the same name");
+ goto fail;
+ }
+ dtypeflags |= (conv->hasobject & NPY_FROM_FIELDS);
+ tup = PyTuple_New((title == NULL ? 2 : 3));
+ PyTuple_SET_ITEM(tup, 0, (PyObject *)conv);
+ if (align) {
+ int _align;
+ _align = conv->alignment;
+ if (_align > 1) totalsize = \
+ ((totalsize + _align - 1)/_align)*_align;
+ maxalign = MAX(maxalign, _align);
+ }
+ PyTuple_SET_ITEM(tup, 1, PyInt_FromLong((long) totalsize));
+
+ /* Title can be "meta-data". Only insert it
+ into the fields dictionary if it is a string
+ */
+ if (title != NULL) {
+ Py_INCREF(title);
+ PyTuple_SET_ITEM(tup, 2, title);
+ if (PyString_Check(title) || PyUnicode_Check(title))
+ PyDict_SetItem(fields, title, tup);
+ }
+ PyDict_SetItem(fields, name, tup);
+ totalsize += conv->elsize;
+ Py_DECREF(tup);
+ }
+ new = PyArray_DescrNewFromType(PyArray_VOID);
+ new->fields = fields;
+ new->names = nameslist;
+ new->elsize = totalsize;
+ new->hasobject=dtypeflags;
+ if (maxalign > 1) {
+ totalsize = ((totalsize+maxalign-1)/maxalign)*maxalign;
+ }
+ if (align) new->alignment = maxalign;
+ return new;
fail:
- Py_DECREF(fields);
- Py_DECREF(nameslist);
- return NULL;
+ Py_DECREF(fields);
+ Py_DECREF(nameslist);
+ return NULL;
}
@@ -4788,67 +4788,67 @@ _convert_from_array_descr(PyObject *obj, int align)
static PyArray_Descr *
_convert_from_list(PyObject *obj, int align)
{
- int n, i;
- int totalsize;
- PyObject *fields;
- PyArray_Descr *conv=NULL;
- PyArray_Descr *new;
- PyObject *key, *tup;
- PyObject *nameslist=NULL;
- int ret;
- int maxalign=0;
- int dtypeflags=0;
-
- n = PyList_GET_SIZE(obj);
- /* Ignore any empty string at end which _internal._commastring
- can produce */
- key = PyList_GET_ITEM(obj, n-1);
- if (PyString_Check(key) && PyString_GET_SIZE(key) == 0) n = n-1;
- /* End ignore code.*/
- totalsize = 0;
- if (n==0) return NULL;
- nameslist = PyTuple_New(n);
- if (!nameslist) return NULL;
- fields = PyDict_New();
- for (i=0; i<n; i++) {
- tup = PyTuple_New(2);
- key = PyString_FromFormat("f%d", i);
- ret = PyArray_DescrConverter(PyList_GET_ITEM(obj, i), &conv);
- if (ret == PY_FAIL) {
- Py_DECREF(tup);
- Py_DECREF(key);
- goto fail;
- }
- dtypeflags |= (conv->hasobject & NPY_FROM_FIELDS);
- PyTuple_SET_ITEM(tup, 0, (PyObject *)conv);
- if (align) {
- int _align;
- _align = conv->alignment;
- if (_align > 1) totalsize = \
- ((totalsize + _align - 1)/_align)*_align;
- maxalign = MAX(maxalign, _align);
- }
- PyTuple_SET_ITEM(tup, 1, PyInt_FromLong((long) totalsize));
- PyDict_SetItem(fields, key, tup);
- Py_DECREF(tup);
- PyTuple_SET_ITEM(nameslist, i, key);
- totalsize += conv->elsize;
- }
- new = PyArray_DescrNewFromType(PyArray_VOID);
- new->fields = fields;
- new->names = nameslist;
- new->hasobject=dtypeflags;
- if (maxalign > 1) {
- totalsize = ((totalsize+maxalign-1)/maxalign)*maxalign;
- }
- if (align) new->alignment = maxalign;
- new->elsize = totalsize;
- return new;
+ int n, i;
+ int totalsize;
+ PyObject *fields;
+ PyArray_Descr *conv=NULL;
+ PyArray_Descr *new;
+ PyObject *key, *tup;
+ PyObject *nameslist=NULL;
+ int ret;
+ int maxalign=0;
+ int dtypeflags=0;
+
+ n = PyList_GET_SIZE(obj);
+ /* Ignore any empty string at end which _internal._commastring
+ can produce */
+ key = PyList_GET_ITEM(obj, n-1);
+ if (PyString_Check(key) && PyString_GET_SIZE(key) == 0) n = n-1;
+ /* End ignore code.*/
+ totalsize = 0;
+ if (n==0) return NULL;
+ nameslist = PyTuple_New(n);
+ if (!nameslist) return NULL;
+ fields = PyDict_New();
+ for (i=0; i<n; i++) {
+ tup = PyTuple_New(2);
+ key = PyString_FromFormat("f%d", i);
+ ret = PyArray_DescrConverter(PyList_GET_ITEM(obj, i), &conv);
+ if (ret == PY_FAIL) {
+ Py_DECREF(tup);
+ Py_DECREF(key);
+ goto fail;
+ }
+ dtypeflags |= (conv->hasobject & NPY_FROM_FIELDS);
+ PyTuple_SET_ITEM(tup, 0, (PyObject *)conv);
+ if (align) {
+ int _align;
+ _align = conv->alignment;
+ if (_align > 1) totalsize = \
+ ((totalsize + _align - 1)/_align)*_align;
+ maxalign = MAX(maxalign, _align);
+ }
+ PyTuple_SET_ITEM(tup, 1, PyInt_FromLong((long) totalsize));
+ PyDict_SetItem(fields, key, tup);
+ Py_DECREF(tup);
+ PyTuple_SET_ITEM(nameslist, i, key);
+ totalsize += conv->elsize;
+ }
+ new = PyArray_DescrNewFromType(PyArray_VOID);
+ new->fields = fields;
+ new->names = nameslist;
+ new->hasobject=dtypeflags;
+ if (maxalign > 1) {
+ totalsize = ((totalsize+maxalign-1)/maxalign)*maxalign;
+ }
+ if (align) new->alignment = maxalign;
+ new->elsize = totalsize;
+ return new;
fail:
- Py_DECREF(nameslist);
- Py_DECREF(fields);
- return NULL;
+ Py_DECREF(nameslist);
+ Py_DECREF(fields);
+ return NULL;
}
@@ -4864,37 +4864,37 @@ _convert_from_list(PyObject *obj, int align)
static PyArray_Descr *
_convert_from_commastring(PyObject *obj, int align)
{
- PyObject *listobj;
- PyArray_Descr *res;
- PyObject *_numpy_internal;
-
- if (!PyString_Check(obj)) return NULL;
- _numpy_internal = PyImport_ImportModule("numpy.core._internal");
- if (_numpy_internal == NULL) return NULL;
- listobj = PyObject_CallMethod(_numpy_internal, "_commastring",
- "O", obj);
- Py_DECREF(_numpy_internal);
- if (!listobj) return NULL;
- if (!PyList_Check(listobj) || PyList_GET_SIZE(listobj)<1) {
- PyErr_SetString(PyExc_RuntimeError, "_commastring is " \
- "not returning a list with len >= 1");
- return NULL;
- }
- if (PyList_GET_SIZE(listobj) == 1) {
- if (PyArray_DescrConverter(PyList_GET_ITEM(listobj, 0),
- &res) == NPY_FAIL) {
- res = NULL;
- }
- }
- else {
- res = _convert_from_list(listobj, align);
- }
- Py_DECREF(listobj);
- if (!res && !PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError, "invalid data-type");
- return NULL;
- }
- return res;
+ PyObject *listobj;
+ PyArray_Descr *res;
+ PyObject *_numpy_internal;
+
+ if (!PyString_Check(obj)) return NULL;
+ _numpy_internal = PyImport_ImportModule("numpy.core._internal");
+ if (_numpy_internal == NULL) return NULL;
+ listobj = PyObject_CallMethod(_numpy_internal, "_commastring",
+ "O", obj);
+ Py_DECREF(_numpy_internal);
+ if (!listobj) return NULL;
+ if (!PyList_Check(listobj) || PyList_GET_SIZE(listobj)<1) {
+ PyErr_SetString(PyExc_RuntimeError, "_commastring is " \
+ "not returning a list with len >= 1");
+ return NULL;
+ }
+ if (PyList_GET_SIZE(listobj) == 1) {
+ if (PyArray_DescrConverter(PyList_GET_ITEM(listobj, 0),
+ &res) == NPY_FAIL) {
+ res = NULL;
+ }
+ }
+ else {
+ res = _convert_from_list(listobj, align);
+ }
+ Py_DECREF(listobj);
+ if (!res && !PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError, "invalid data-type");
+ return NULL;
+ }
+ return res;
}
@@ -4909,184 +4909,184 @@ _convert_from_commastring(PyObject *obj, int align)
Optional:
"offsets" --- integers indicating the offset into the
- record of the start of the field.
- if not given, then "consecutive offsets"
- will be assumed and placed in the dictionary.
+ record of the start of the field.
+ if not given, then "consecutive offsets"
+ will be assumed and placed in the dictionary.
"titles" --- Allows the use of an additional key
- for the fields dictionary.(if these are strings
- or unicode objects) or
- this can also be meta-data to
- be passed around with the field description.
+ for the fields dictionary.(if these are strings
+ or unicode objects) or
+ this can also be meta-data to
+ be passed around with the field description.
-Attribute-lookup-based field names merely has to query the fields
-dictionary of the data-descriptor. Any result present can be used
-to return the correct field.
+ Attribute-lookup-based field names merely has to query the fields
+ dictionary of the data-descriptor. Any result present can be used
+ to return the correct field.
-So, the notion of what is a name and what is a title is really quite
-arbitrary.
+ So, the notion of what is a name and what is a title is really quite
+ arbitrary.
-What does distinguish a title, however, is that if it is not None,
-it will be placed at the end of the tuple inserted into the
-fields dictionary.and can therefore be used to carry meta-data around.
+ What does distinguish a title, however, is that if it is not None,
+ it will be placed at the end of the tuple inserted into the
+ fields dictionary.and can therefore be used to carry meta-data around.
-If the dictionary does not have "names" and "formats" entries,
-then it will be checked for conformity and used directly.
+ If the dictionary does not have "names" and "formats" entries,
+ then it will be checked for conformity and used directly.
*/
static PyArray_Descr *
_use_fields_dict(PyObject *obj, int align)
{
- PyObject *_numpy_internal;
- PyArray_Descr *res;
- _numpy_internal = PyImport_ImportModule("numpy.core._internal");
- if (_numpy_internal == NULL) return NULL;
- res = (PyArray_Descr *)PyObject_CallMethod(_numpy_internal,
- "_usefields",
- "Oi", obj, align);
- Py_DECREF(_numpy_internal);
- return res;
+ PyObject *_numpy_internal;
+ PyArray_Descr *res;
+ _numpy_internal = PyImport_ImportModule("numpy.core._internal");
+ if (_numpy_internal == NULL) return NULL;
+ res = (PyArray_Descr *)PyObject_CallMethod(_numpy_internal,
+ "_usefields",
+ "Oi", obj, align);
+ Py_DECREF(_numpy_internal);
+ return res;
}
static PyArray_Descr *
_convert_from_dict(PyObject *obj, int align)
{
- PyArray_Descr *new;
- PyObject *fields=NULL;
- PyObject *names, *offsets, *descrs, *titles;
- int n, i;
- int totalsize;
- int maxalign=0;
- int dtypeflags=0;
-
- fields = PyDict_New();
- if (fields == NULL) return (PyArray_Descr *)PyErr_NoMemory();
-
- names = PyDict_GetItemString(obj, "names");
- descrs = PyDict_GetItemString(obj, "formats");
-
- if (!names || !descrs) {
- Py_DECREF(fields);
- return _use_fields_dict(obj, align);
- }
- n = PyObject_Length(names);
- offsets = PyDict_GetItemString(obj, "offsets");
- titles = PyDict_GetItemString(obj, "titles");
- if ((n > PyObject_Length(descrs)) || \
- (offsets && (n > PyObject_Length(offsets))) || \
- (titles && (n > PyObject_Length(titles)))) {
- PyErr_SetString(PyExc_ValueError,
- "all items in the dictionary must have" \
- " the same length.");
- goto fail;
- }
-
- totalsize = 0;
- for(i=0; i<n; i++) {
- PyObject *tup, *descr, *index, *item, *name, *off;
- int len, ret, _align=1;
- PyArray_Descr *newdescr;
-
- /* Build item to insert (descr, offset, [title])*/
- len = 2;
- item = NULL;
- index = PyInt_FromLong(i);
- if (titles) {
- item=PyObject_GetItem(titles, index);
- if (item && item != Py_None) len = 3;
- else Py_XDECREF(item);
- PyErr_Clear();
- }
- tup = PyTuple_New(len);
- descr = PyObject_GetItem(descrs, index);
- ret = PyArray_DescrConverter(descr, &newdescr);
- Py_DECREF(descr);
- if (ret == PY_FAIL) {
- Py_DECREF(tup);
- Py_DECREF(index);
- goto fail;
- }
- PyTuple_SET_ITEM(tup, 0, (PyObject *)newdescr);
- if (align) {
- _align = newdescr->alignment;
- maxalign = MAX(maxalign,_align);
- }
- if (offsets) {
- long offset;
- off = PyObject_GetItem(offsets, index);
- offset = PyInt_AsLong(off);
- PyTuple_SET_ITEM(tup, 1, off);
- if (offset < totalsize) {
- PyErr_SetString(PyExc_ValueError,
- "invalid offset (must be "\
- "ordered)");
- ret = PY_FAIL;
- }
- if (offset > totalsize) totalsize = offset;
- }
- else {
- if (align && _align > 1) {
- totalsize = ((totalsize + _align - 1) \
- /_align)*_align;
- }
- PyTuple_SET_ITEM(tup, 1, PyInt_FromLong(totalsize));
- }
- if (len == 3) PyTuple_SET_ITEM(tup, 2, item);
- name = PyObject_GetItem(names, index);
- Py_DECREF(index);
- if (!(PyString_Check(name) || PyUnicode_Check(name))) {
- PyErr_SetString(PyExc_ValueError,
- "field names must be strings");
- ret = PY_FAIL;
- }
+ PyArray_Descr *new;
+ PyObject *fields=NULL;
+ PyObject *names, *offsets, *descrs, *titles;
+ int n, i;
+ int totalsize;
+ int maxalign=0;
+ int dtypeflags=0;
+
+ fields = PyDict_New();
+ if (fields == NULL) return (PyArray_Descr *)PyErr_NoMemory();
- /* Insert into dictionary */
- if (PyDict_GetItem(fields, name) != NULL) {
- PyErr_SetString(PyExc_ValueError,
- "name already used as a name or "\
- "title");
- ret = PY_FAIL;
- }
- PyDict_SetItem(fields, name, tup);
- Py_DECREF(name);
- if (len == 3) {
- if ((PyString_Check(item) || PyUnicode_Check(item)) &&
- PyDict_GetItem(fields, item) != NULL) {
- PyErr_SetString(PyExc_ValueError,
- "title already used as a "\
- "name or title.");
- ret=PY_FAIL;
- }
- else {
- PyDict_SetItem(fields, item, tup);
- }
- }
- Py_DECREF(tup);
- if ((ret == PY_FAIL) || (newdescr->elsize == 0)) goto fail;
- dtypeflags |= (newdescr->hasobject & NPY_FROM_FIELDS);
- totalsize += newdescr->elsize;
- }
-
- new = PyArray_DescrNewFromType(PyArray_VOID);
- if (new == NULL) goto fail;
- if (maxalign > 1)
- totalsize = ((totalsize + maxalign - 1)/maxalign)*maxalign;
- if (align) new->alignment = maxalign;
- new->elsize = totalsize;
- if (!PyTuple_Check(names)) {
- names = PySequence_Tuple(names);
+ names = PyDict_GetItemString(obj, "names");
+ descrs = PyDict_GetItemString(obj, "formats");
+
+ if (!names || !descrs) {
+ Py_DECREF(fields);
+ return _use_fields_dict(obj, align);
+ }
+ n = PyObject_Length(names);
+ offsets = PyDict_GetItemString(obj, "offsets");
+ titles = PyDict_GetItemString(obj, "titles");
+ if ((n > PyObject_Length(descrs)) || \
+ (offsets && (n > PyObject_Length(offsets))) || \
+ (titles && (n > PyObject_Length(titles)))) {
+ PyErr_SetString(PyExc_ValueError,
+ "all items in the dictionary must have" \
+ " the same length.");
+ goto fail;
+ }
+
+ totalsize = 0;
+ for(i=0; i<n; i++) {
+ PyObject *tup, *descr, *index, *item, *name, *off;
+ int len, ret, _align=1;
+ PyArray_Descr *newdescr;
+
+ /* Build item to insert (descr, offset, [title])*/
+ len = 2;
+ item = NULL;
+ index = PyInt_FromLong(i);
+ if (titles) {
+ item=PyObject_GetItem(titles, index);
+ if (item && item != Py_None) len = 3;
+ else Py_XDECREF(item);
+ PyErr_Clear();
+ }
+ tup = PyTuple_New(len);
+ descr = PyObject_GetItem(descrs, index);
+ ret = PyArray_DescrConverter(descr, &newdescr);
+ Py_DECREF(descr);
+ if (ret == PY_FAIL) {
+ Py_DECREF(tup);
+ Py_DECREF(index);
+ goto fail;
+ }
+ PyTuple_SET_ITEM(tup, 0, (PyObject *)newdescr);
+ if (align) {
+ _align = newdescr->alignment;
+ maxalign = MAX(maxalign,_align);
+ }
+ if (offsets) {
+ long offset;
+ off = PyObject_GetItem(offsets, index);
+ offset = PyInt_AsLong(off);
+ PyTuple_SET_ITEM(tup, 1, off);
+ if (offset < totalsize) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid offset (must be "\
+ "ordered)");
+ ret = PY_FAIL;
+ }
+ if (offset > totalsize) totalsize = offset;
}
else {
- Py_INCREF(names);
+ if (align && _align > 1) {
+ totalsize = ((totalsize + _align - 1) \
+ /_align)*_align;
+ }
+ PyTuple_SET_ITEM(tup, 1, PyInt_FromLong(totalsize));
}
- new->names = names;
- new->fields = fields;
- new->hasobject = dtypeflags;
- return new;
+ if (len == 3) PyTuple_SET_ITEM(tup, 2, item);
+ name = PyObject_GetItem(names, index);
+ Py_DECREF(index);
+ if (!(PyString_Check(name) || PyUnicode_Check(name))) {
+ PyErr_SetString(PyExc_ValueError,
+ "field names must be strings");
+ ret = PY_FAIL;
+ }
+
+ /* Insert into dictionary */
+ if (PyDict_GetItem(fields, name) != NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "name already used as a name or "\
+ "title");
+ ret = PY_FAIL;
+ }
+ PyDict_SetItem(fields, name, tup);
+ Py_DECREF(name);
+ if (len == 3) {
+ if ((PyString_Check(item) || PyUnicode_Check(item)) &&
+ PyDict_GetItem(fields, item) != NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "title already used as a "\
+ "name or title.");
+ ret=PY_FAIL;
+ }
+ else {
+ PyDict_SetItem(fields, item, tup);
+ }
+ }
+ Py_DECREF(tup);
+ if ((ret == PY_FAIL) || (newdescr->elsize == 0)) goto fail;
+ dtypeflags |= (newdescr->hasobject & NPY_FROM_FIELDS);
+ totalsize += newdescr->elsize;
+ }
+
+ new = PyArray_DescrNewFromType(PyArray_VOID);
+ if (new == NULL) goto fail;
+ if (maxalign > 1)
+ totalsize = ((totalsize + maxalign - 1)/maxalign)*maxalign;
+ if (align) new->alignment = maxalign;
+ new->elsize = totalsize;
+ if (!PyTuple_Check(names)) {
+ names = PySequence_Tuple(names);
+ }
+ else {
+ Py_INCREF(names);
+ }
+ new->names = names;
+ new->fields = fields;
+ new->hasobject = dtypeflags;
+ return new;
fail:
- Py_XDECREF(fields);
- return NULL;
+ Py_XDECREF(fields);
+ return NULL;
}
#define _chk_byteorder(arg) (arg == '>' || arg == '<' || \
@@ -5095,111 +5095,111 @@ _convert_from_dict(PyObject *obj, int align)
static int
_check_for_commastring(char *type, int len)
{
- int i;
+ int i;
- /* Check for ints at start of string */
- if ((type[0] >= '0' && type[0] <= '9') ||
- ((len > 1) && _chk_byteorder(type[0]) &&
- (type[1] >= '0' && type[1] <= '9')))
- return 1;
+ /* Check for ints at start of string */
+ if ((type[0] >= '0' && type[0] <= '9') ||
+ ((len > 1) && _chk_byteorder(type[0]) &&
+ (type[1] >= '0' && type[1] <= '9')))
+ return 1;
- /* Check for empty tuple */
- if (((len > 1) && (type[0] == '(' && type[1] == ')')) ||
- ((len > 3) && _chk_byteorder(type[0]) &&
- (type[1] == '(' && type[2] == ')')))
- return 1;
+ /* Check for empty tuple */
+ if (((len > 1) && (type[0] == '(' && type[1] == ')')) ||
+ ((len > 3) && _chk_byteorder(type[0]) &&
+ (type[1] == '(' && type[2] == ')')))
+ return 1;
- /* Check for presence of commas */
- for (i=1;i<len;i++)
- if (type[i] == ',') return 1;
+ /* Check for presence of commas */
+ for (i=1;i<len;i++)
+ if (type[i] == ',') return 1;
- return 0;
+ return 0;
}
#undef _chk_byteorder
/*
- any object with
- the .fields attribute and/or .itemsize attribute
- (if the .fields attribute does not give
- the total size -- i.e. a partial record naming).
- If itemsize is given it must be >= size computed from fields
-
- The .fields attribute must return a convertible dictionary if
- present. Result inherits from PyArray_VOID.
+ any object with
+ the .fields attribute and/or .itemsize attribute
+ (if the .fields attribute does not give
+ the total size -- i.e. a partial record naming).
+ If itemsize is given it must be >= size computed from fields
+
+ The .fields attribute must return a convertible dictionary if
+ present. Result inherits from PyArray_VOID.
*/
/*MULTIARRAY_API
- Get type-descriptor from an object forcing alignment if possible
- None goes to DEFAULT type.
+ Get type-descriptor from an object forcing alignment if possible
+ None goes to DEFAULT type.
*/
static int
PyArray_DescrAlignConverter(PyObject *obj, PyArray_Descr **at)
{
- if PyDict_Check(obj) {
- *at = _convert_from_dict(obj, 1);
+ if PyDict_Check(obj) {
+ *at = _convert_from_dict(obj, 1);
}
- else if PyString_Check(obj) {
- *at = _convert_from_commastring(obj, 1);
+ else if PyString_Check(obj) {
+ *at = _convert_from_commastring(obj, 1);
}
- else if PyList_Check(obj) {
- *at = _convert_from_array_descr(obj, 1);
+ else if PyList_Check(obj) {
+ *at = _convert_from_array_descr(obj, 1);
}
- else {
- return PyArray_DescrConverter(obj, at);
- }
- if (*at == NULL) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "data-type-descriptor not understood");
- }
- return PY_FAIL;
+ else {
+ return PyArray_DescrConverter(obj, at);
+ }
+ if (*at == NULL) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "data-type-descriptor not understood");
}
- return PY_SUCCEED;
+ return PY_FAIL;
+ }
+ return PY_SUCCEED;
}
/*MULTIARRAY_API
- Get type-descriptor from an object forcing alignment if possible
- None goes to NULL.
+ Get type-descriptor from an object forcing alignment if possible
+ None goes to NULL.
*/
static int
PyArray_DescrAlignConverter2(PyObject *obj, PyArray_Descr **at)
{
- if PyDict_Check(obj) {
- *at = _convert_from_dict(obj, 1);
- }
- else if PyString_Check(obj) {
- *at = _convert_from_commastring(obj, 1);
+ if PyDict_Check(obj) {
+ *at = _convert_from_dict(obj, 1);
}
- else if PyList_Check(obj) {
- *at = _convert_from_array_descr(obj, 1);
+ else if PyString_Check(obj) {
+ *at = _convert_from_commastring(obj, 1);
}
- else {
- return PyArray_DescrConverter2(obj, at);
+ else if PyList_Check(obj) {
+ *at = _convert_from_array_descr(obj, 1);
}
- if (*at == NULL) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "data-type-descriptor not understood");
- }
- return PY_FAIL;
+ else {
+ return PyArray_DescrConverter2(obj, at);
+ }
+ if (*at == NULL) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "data-type-descriptor not understood");
}
- return PY_SUCCEED;
+ return PY_FAIL;
+ }
+ return PY_SUCCEED;
}
/*MULTIARRAY_API
- Get typenum from an object -- None goes to NULL
+ Get typenum from an object -- None goes to NULL
*/
static int
PyArray_DescrConverter2(PyObject *obj, PyArray_Descr **at)
{
- if (obj == Py_None) {
- *at = NULL;
- return PY_SUCCEED;
- }
- else return PyArray_DescrConverter(obj, at);
+ if (obj == Py_None) {
+ *at = NULL;
+ return PY_SUCCEED;
+ }
+ else return PyArray_DescrConverter(obj, at);
}
/* This function takes a Python object representing a type and converts it
@@ -5210,191 +5210,191 @@ PyArray_DescrConverter2(PyObject *obj, PyArray_Descr **at)
This is the central code that converts Python objects to
Type-descriptor objects that are used throughout numpy.
- */
+*/
/* new reference in *at */
/*MULTIARRAY_API
- Get typenum from an object -- None goes to PyArray_DEFAULT
+ Get typenum from an object -- None goes to PyArray_DEFAULT
*/
static int
PyArray_DescrConverter(PyObject *obj, PyArray_Descr **at)
{
- char *type;
- int check_num=PyArray_NOTYPE+10;
- int len;
- PyObject *item;
- int elsize = 0;
- char endian = '=';
-
- *at=NULL;
-
- /* default */
- if (obj == Py_None) {
- *at = PyArray_DescrFromType(PyArray_DEFAULT);
- return PY_SUCCEED;
- }
-
- if (PyArray_DescrCheck(obj)) {
- *at = (PyArray_Descr *)obj;
- Py_INCREF(*at);
- return PY_SUCCEED;
- }
-
- if (PyType_Check(obj)) {
- if (PyType_IsSubtype((PyTypeObject *)obj,
- &PyGenericArrType_Type)) {
- *at = PyArray_DescrFromTypeObject(obj);
- if (*at) return PY_SUCCEED;
- else return PY_FAIL;
- }
- check_num = PyArray_OBJECT;
- if (obj == (PyObject *)(&PyInt_Type))
- check_num = PyArray_LONG;
- else if (obj == (PyObject *)(&PyLong_Type))
- check_num = PyArray_LONGLONG;
- else if (obj == (PyObject *)(&PyFloat_Type))
- check_num = PyArray_DOUBLE;
- else if (obj == (PyObject *)(&PyComplex_Type))
- check_num = PyArray_CDOUBLE;
- else if (obj == (PyObject *)(&PyBool_Type))
- check_num = PyArray_BOOL;
- else if (obj == (PyObject *)(&PyString_Type))
- check_num = PyArray_STRING;
- else if (obj == (PyObject *)(&PyUnicode_Type))
- check_num = PyArray_UNICODE;
- else if (obj == (PyObject *)(&PyBuffer_Type))
- check_num = PyArray_VOID;
- else {
- *at = _arraydescr_fromobj(obj);
- if (*at) return PY_SUCCEED;
- }
- goto finish;
- }
-
- /* or a typecode string */
-
- if (PyString_Check(obj)) {
- /* Check for a string typecode. */
- type = PyString_AS_STRING(obj);
- len = PyString_GET_SIZE(obj);
- if (len <= 0) goto fail;
-
- /* check for commas present
- or first (or second) element a digit */
- if (_check_for_commastring(type, len)) {
- *at = _convert_from_commastring(obj, 0);
- if (*at) return PY_SUCCEED;
- return PY_FAIL;
- }
- check_num = (int) type[0];
- if ((char) check_num == '>' || (char) check_num == '<' || \
- (char) check_num == '|' || (char) check_num == '=') {
- if (len <= 1) goto fail;
- endian = (char) check_num;
- type++; len--;
- check_num = (int) type[0];
- if (endian == '|') endian = '=';
- }
- if (len > 1) {
- elsize = atoi(type+1);
- if (elsize == 0) {
- check_num = PyArray_NOTYPE+10;
- }
- /* When specifying length of UNICODE
- the number of characters is given to match
- the STRING interface. Each character can be
- more than one byte and itemsize must be
- the number of bytes.
- */
- else if (check_num == PyArray_UNICODELTR) {
- elsize <<= 2;
- }
- /* Support for generic processing
- c4, i4, f8, etc...
- */
- else if ((check_num != PyArray_STRINGLTR) && \
- (check_num != PyArray_VOIDLTR) && \
- (check_num != PyArray_STRINGLTR2)) {
- check_num = \
- PyArray_TypestrConvert(elsize,
- check_num);
- if (check_num == PyArray_NOTYPE)
- check_num += 10;
- elsize = 0;
- }
- }
- }
- /* or a tuple */
- else if (PyTuple_Check(obj)) {
- *at = _convert_from_tuple(obj);
- if (*at == NULL){
- if (PyErr_Occurred()) return PY_FAIL;
- goto fail;
- }
- return PY_SUCCEED;
- }
- /* or a list */
- else if (PyList_Check(obj)) {
- *at = _convert_from_array_descr(obj,0);
- if (*at == NULL) {
- if (PyErr_Occurred()) return PY_FAIL;
- goto fail;
- }
- return PY_SUCCEED;
- }
- /* or a dictionary */
- else if (PyDict_Check(obj)) {
- *at = _convert_from_dict(obj,0);
- if (*at == NULL) {
- if (PyErr_Occurred()) return PY_FAIL;
- goto fail;
- }
- return PY_SUCCEED;
- }
- else if (PyArray_Check(obj)) goto fail;
- else /* goto fail;*/ {
- *at = _arraydescr_fromobj(obj);
- if (*at) return PY_SUCCEED;
- if (PyErr_Occurred()) return PY_FAIL;
- goto fail;
- }
- if (PyErr_Occurred()) goto fail;
-
- /*
- if (check_num == PyArray_NOTYPE) return PY_FAIL;
- */
+ char *type;
+ int check_num=PyArray_NOTYPE+10;
+ int len;
+ PyObject *item;
+ int elsize = 0;
+ char endian = '=';
- finish:
- if ((check_num == PyArray_NOTYPE+10) || \
- (*at = PyArray_DescrFromType(check_num))==NULL) {
- /* Now check to see if the object is registered
- in typeDict */
- if (typeDict != NULL) {
- item = PyDict_GetItem(typeDict, obj);
- if (item) return PyArray_DescrConverter(item, at);
- }
- goto fail;
- }
-
- if (((*at)->elsize == 0) && (elsize != 0)) {
- PyArray_DESCR_REPLACE(*at);
- (*at)->elsize = elsize;
- }
- if (endian != '=' && PyArray_ISNBO(endian)) endian = '=';
-
- if (endian != '=' && (*at)->byteorder != '|' && \
- (*at)->byteorder != endian) {
- PyArray_DESCR_REPLACE(*at);
- (*at)->byteorder = endian;
- }
+ *at=NULL;
+ /* default */
+ if (obj == Py_None) {
+ *at = PyArray_DescrFromType(PyArray_DEFAULT);
return PY_SUCCEED;
+ }
+
+ if (PyArray_DescrCheck(obj)) {
+ *at = (PyArray_Descr *)obj;
+ Py_INCREF(*at);
+ return PY_SUCCEED;
+ }
+
+ if (PyType_Check(obj)) {
+ if (PyType_IsSubtype((PyTypeObject *)obj,
+ &PyGenericArrType_Type)) {
+ *at = PyArray_DescrFromTypeObject(obj);
+ if (*at) return PY_SUCCEED;
+ else return PY_FAIL;
+ }
+ check_num = PyArray_OBJECT;
+ if (obj == (PyObject *)(&PyInt_Type))
+ check_num = PyArray_LONG;
+ else if (obj == (PyObject *)(&PyLong_Type))
+ check_num = PyArray_LONGLONG;
+ else if (obj == (PyObject *)(&PyFloat_Type))
+ check_num = PyArray_DOUBLE;
+ else if (obj == (PyObject *)(&PyComplex_Type))
+ check_num = PyArray_CDOUBLE;
+ else if (obj == (PyObject *)(&PyBool_Type))
+ check_num = PyArray_BOOL;
+ else if (obj == (PyObject *)(&PyString_Type))
+ check_num = PyArray_STRING;
+ else if (obj == (PyObject *)(&PyUnicode_Type))
+ check_num = PyArray_UNICODE;
+ else if (obj == (PyObject *)(&PyBuffer_Type))
+ check_num = PyArray_VOID;
+ else {
+ *at = _arraydescr_fromobj(obj);
+ if (*at) return PY_SUCCEED;
+ }
+ goto finish;
+ }
+
+ /* or a typecode string */
+
+ if (PyString_Check(obj)) {
+ /* Check for a string typecode. */
+ type = PyString_AS_STRING(obj);
+ len = PyString_GET_SIZE(obj);
+ if (len <= 0) goto fail;
+
+ /* check for commas present
+ or first (or second) element a digit */
+ if (_check_for_commastring(type, len)) {
+ *at = _convert_from_commastring(obj, 0);
+ if (*at) return PY_SUCCEED;
+ return PY_FAIL;
+ }
+ check_num = (int) type[0];
+ if ((char) check_num == '>' || (char) check_num == '<' || \
+ (char) check_num == '|' || (char) check_num == '=') {
+ if (len <= 1) goto fail;
+ endian = (char) check_num;
+ type++; len--;
+ check_num = (int) type[0];
+ if (endian == '|') endian = '=';
+ }
+ if (len > 1) {
+ elsize = atoi(type+1);
+ if (elsize == 0) {
+ check_num = PyArray_NOTYPE+10;
+ }
+ /* When specifying length of UNICODE
+ the number of characters is given to match
+ the STRING interface. Each character can be
+ more than one byte and itemsize must be
+ the number of bytes.
+ */
+ else if (check_num == PyArray_UNICODELTR) {
+ elsize <<= 2;
+ }
+ /* Support for generic processing
+ c4, i4, f8, etc...
+ */
+ else if ((check_num != PyArray_STRINGLTR) && \
+ (check_num != PyArray_VOIDLTR) && \
+ (check_num != PyArray_STRINGLTR2)) {
+ check_num = \
+ PyArray_TypestrConvert(elsize,
+ check_num);
+ if (check_num == PyArray_NOTYPE)
+ check_num += 10;
+ elsize = 0;
+ }
+ }
+ }
+ /* or a tuple */
+ else if (PyTuple_Check(obj)) {
+ *at = _convert_from_tuple(obj);
+ if (*at == NULL){
+ if (PyErr_Occurred()) return PY_FAIL;
+ goto fail;
+ }
+ return PY_SUCCEED;
+ }
+ /* or a list */
+ else if (PyList_Check(obj)) {
+ *at = _convert_from_array_descr(obj,0);
+ if (*at == NULL) {
+ if (PyErr_Occurred()) return PY_FAIL;
+ goto fail;
+ }
+ return PY_SUCCEED;
+ }
+ /* or a dictionary */
+ else if (PyDict_Check(obj)) {
+ *at = _convert_from_dict(obj,0);
+ if (*at == NULL) {
+ if (PyErr_Occurred()) return PY_FAIL;
+ goto fail;
+ }
+ return PY_SUCCEED;
+ }
+ else if (PyArray_Check(obj)) goto fail;
+ else /* goto fail;*/ {
+ *at = _arraydescr_fromobj(obj);
+ if (*at) return PY_SUCCEED;
+ if (PyErr_Occurred()) return PY_FAIL;
+ goto fail;
+ }
+ if (PyErr_Occurred()) goto fail;
+
+ /*
+ if (check_num == PyArray_NOTYPE) return PY_FAIL;
+ */
+
+ finish:
+ if ((check_num == PyArray_NOTYPE+10) || \
+ (*at = PyArray_DescrFromType(check_num))==NULL) {
+ /* Now check to see if the object is registered
+ in typeDict */
+ if (typeDict != NULL) {
+ item = PyDict_GetItem(typeDict, obj);
+ if (item) return PyArray_DescrConverter(item, at);
+ }
+ goto fail;
+ }
+
+ if (((*at)->elsize == 0) && (elsize != 0)) {
+ PyArray_DESCR_REPLACE(*at);
+ (*at)->elsize = elsize;
+ }
+ if (endian != '=' && PyArray_ISNBO(endian)) endian = '=';
+
+ if (endian != '=' && (*at)->byteorder != '|' && \
+ (*at)->byteorder != endian) {
+ PyArray_DESCR_REPLACE(*at);
+ (*at)->byteorder = endian;
+ }
+
+ return PY_SUCCEED;
fail:
- PyErr_SetString(PyExc_TypeError,
- "data type not understood");
- *at=NULL;
- return PY_FAIL;
+ PyErr_SetString(PyExc_TypeError,
+ "data type not understood");
+ *at=NULL;
+ return PY_FAIL;
}
/*MULTIARRAY_API
@@ -5403,36 +5403,36 @@ PyArray_DescrConverter(PyObject *obj, PyArray_Descr **at)
static int
PyArray_ByteorderConverter(PyObject *obj, char *endian)
{
- char *str;
- *endian = PyArray_SWAP;
- str = PyString_AsString(obj);
- if (!str) return PY_FAIL;
- if (strlen(str) < 1) {
- PyErr_SetString(PyExc_ValueError,
- "Byteorder string must be at least length 1");
- return PY_FAIL;
- }
- *endian = str[0];
- if (str[0] != PyArray_BIG && str[0] != PyArray_LITTLE && \
- str[0] != PyArray_NATIVE) {
- if (str[0] == 'b' || str[0] == 'B')
- *endian = PyArray_BIG;
- else if (str[0] == 'l' || str[0] == 'L')
- *endian = PyArray_LITTLE;
- else if (str[0] == 'n' || str[0] == 'N')
- *endian = PyArray_NATIVE;
- else if (str[0] == 'i' || str[0] == 'I')
- *endian = PyArray_IGNORE;
- else if (str[0] == 's' || str[0] == 'S')
- *endian = PyArray_SWAP;
- else {
- PyErr_Format(PyExc_ValueError,
- "%s is an unrecognized byteorder",
- str);
- return PY_FAIL;
- }
- }
- return PY_SUCCEED;
+ char *str;
+ *endian = PyArray_SWAP;
+ str = PyString_AsString(obj);
+ if (!str) return PY_FAIL;
+ if (strlen(str) < 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "Byteorder string must be at least length 1");
+ return PY_FAIL;
+ }
+ *endian = str[0];
+ if (str[0] != PyArray_BIG && str[0] != PyArray_LITTLE && \
+ str[0] != PyArray_NATIVE) {
+ if (str[0] == 'b' || str[0] == 'B')
+ *endian = PyArray_BIG;
+ else if (str[0] == 'l' || str[0] == 'L')
+ *endian = PyArray_LITTLE;
+ else if (str[0] == 'n' || str[0] == 'N')
+ *endian = PyArray_NATIVE;
+ else if (str[0] == 'i' || str[0] == 'I')
+ *endian = PyArray_IGNORE;
+ else if (str[0] == 's' || str[0] == 'S')
+ *endian = PyArray_SWAP;
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "%s is an unrecognized byteorder",
+ str);
+ return PY_FAIL;
+ }
+ }
+ return PY_SUCCEED;
}
/*MULTIARRAY_API
@@ -5441,47 +5441,47 @@ PyArray_ByteorderConverter(PyObject *obj, char *endian)
static int
PyArray_SortkindConverter(PyObject *obj, NPY_SORTKIND *sortkind)
{
- char *str;
- *sortkind = PyArray_QUICKSORT;
- str = PyString_AsString(obj);
- if (!str) return PY_FAIL;
- if (strlen(str) < 1) {
- PyErr_SetString(PyExc_ValueError,
- "Sort kind string must be at least length 1");
- return PY_FAIL;
- }
- if (str[0] == 'q' || str[0] == 'Q')
- *sortkind = PyArray_QUICKSORT;
- else if (str[0] == 'h' || str[0] == 'H')
- *sortkind = PyArray_HEAPSORT;
- else if (str[0] == 'm' || str[0] == 'M')
- *sortkind = PyArray_MERGESORT;
- else {
- PyErr_Format(PyExc_ValueError,
- "%s is an unrecognized kind of sort",
- str);
- return PY_FAIL;
- }
- return PY_SUCCEED;
+ char *str;
+ *sortkind = PyArray_QUICKSORT;
+ str = PyString_AsString(obj);
+ if (!str) return PY_FAIL;
+ if (strlen(str) < 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "Sort kind string must be at least length 1");
+ return PY_FAIL;
+ }
+ if (str[0] == 'q' || str[0] == 'Q')
+ *sortkind = PyArray_QUICKSORT;
+ else if (str[0] == 'h' || str[0] == 'H')
+ *sortkind = PyArray_HEAPSORT;
+ else if (str[0] == 'm' || str[0] == 'M')
+ *sortkind = PyArray_MERGESORT;
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "%s is an unrecognized kind of sort",
+ str);
+ return PY_FAIL;
+ }
+ return PY_SUCCEED;
}
/* compare the field dictionary for two types
return 1 if the same or 0 if not
- */
+*/
static int
_equivalent_fields(PyObject *field1, PyObject *field2) {
- int same, val;
+ int same, val;
- if (field1 == field2) return 1;
- if (field1 == NULL || field2 == NULL) return 0;
- val = PyObject_Compare(field1, field2);
- if (val != 0 || PyErr_Occurred()) same = 0;
- else same = 1;
- PyErr_Clear();
- return same;
+ if (field1 == field2) return 1;
+ if (field1 == NULL || field2 == NULL) return 0;
+ val = PyObject_Compare(field1, field2);
+ if (val != 0 || PyErr_Occurred()) same = 0;
+ else same = 1;
+ PyErr_Clear();
+ return same;
}
/* This function returns true if the two typecodes are
@@ -5492,36 +5492,36 @@ _equivalent_fields(PyObject *field1, PyObject *field2) {
static unsigned char
PyArray_EquivTypes(PyArray_Descr *typ1, PyArray_Descr *typ2)
{
- register int typenum1=typ1->type_num;
- register int typenum2=typ2->type_num;
- register int size1=typ1->elsize;
- register int size2=typ2->elsize;
+ register int typenum1=typ1->type_num;
+ register int typenum2=typ2->type_num;
+ register int size1=typ1->elsize;
+ register int size2=typ2->elsize;
- if (size1 != size2) return FALSE;
+ if (size1 != size2) return FALSE;
- if (PyArray_ISNBO(typ1->byteorder) != PyArray_ISNBO(typ2->byteorder))
- return FALSE;
+ if (PyArray_ISNBO(typ1->byteorder) != PyArray_ISNBO(typ2->byteorder))
+ return FALSE;
- if (typenum1 == PyArray_VOID || \
- typenum2 == PyArray_VOID) {
- return ((typenum1 == typenum2) &&
- _equivalent_fields(typ1->fields, typ2->fields));
- }
- return (typ1->kind == typ2->kind);
+ if (typenum1 == PyArray_VOID || \
+ typenum2 == PyArray_VOID) {
+ return ((typenum1 == typenum2) &&
+ _equivalent_fields(typ1->fields, typ2->fields));
+ }
+ return (typ1->kind == typ2->kind);
}
/*MULTIARRAY_API*/
static unsigned char
PyArray_EquivTypenums(int typenum1, int typenum2)
{
- PyArray_Descr *d1, *d2;
- Bool ret;
- d1 = PyArray_DescrFromType(typenum1);
- d2 = PyArray_DescrFromType(typenum2);
- ret = PyArray_EquivTypes(d1, d2);
- Py_DECREF(d1);
- Py_DECREF(d2);
- return ret;
+ PyArray_Descr *d1, *d2;
+ Bool ret;
+ d1 = PyArray_DescrFromType(typenum1);
+ d2 = PyArray_DescrFromType(typenum2);
+ ret = PyArray_EquivTypes(d1, d2);
+ Py_DECREF(d1);
+ Py_DECREF(d2);
+ return ret;
}
/*** END C-API FUNCTIONS **/
@@ -5529,29 +5529,29 @@ PyArray_EquivTypenums(int typenum1, int typenum2)
static PyObject *
_prepend_ones(PyArrayObject *arr, int nd, int ndmin)
{
- intp newdims[MAX_DIMS];
- intp newstrides[MAX_DIMS];
- int i,k,num;
- PyObject *ret;
-
- num = ndmin-nd;
- for (i=0; i<num; i++) {
- newdims[i] = 1;
- newstrides[i] = arr->descr->elsize;
- }
- for (i=num;i<ndmin;i++) {
- k = i-num;
- newdims[i] = arr->dimensions[k];
- newstrides[i] = arr->strides[k];
- }
- Py_INCREF(arr->descr);
- ret = PyArray_NewFromDescr(arr->ob_type, arr->descr, ndmin,
- newdims, newstrides, arr->data, arr->flags,
- (PyObject *)arr);
- /* steals a reference to arr --- so don't increment
- here */
- PyArray_BASE(ret) = (PyObject *)arr;
- return ret;
+ intp newdims[MAX_DIMS];
+ intp newstrides[MAX_DIMS];
+ int i,k,num;
+ PyObject *ret;
+
+ num = ndmin-nd;
+ for (i=0; i<num; i++) {
+ newdims[i] = 1;
+ newstrides[i] = arr->descr->elsize;
+ }
+ for (i=num;i<ndmin;i++) {
+ k = i-num;
+ newdims[i] = arr->dimensions[k];
+ newstrides[i] = arr->strides[k];
+ }
+ Py_INCREF(arr->descr);
+ ret = PyArray_NewFromDescr(arr->ob_type, arr->descr, ndmin,
+ newdims, newstrides, arr->data, arr->flags,
+ (PyObject *)arr);
+ /* steals a reference to arr --- so don't increment
+ here */
+ PyArray_BASE(ret) = (PyObject *)arr;
+ return ret;
}
@@ -5566,283 +5566,283 @@ _prepend_ones(PyArrayObject *arr, int nd, int ndmin)
static PyObject *
_array_fromobject(PyObject *ignored, PyObject *args, PyObject *kws)
{
- PyObject *op, *ret=NULL;
- static char *kwd[]= {"object", "dtype", "copy", "order", "subok",
- "ndmin", NULL};
- Bool subok=FALSE;
- Bool copy=TRUE;
- int ndmin=0, nd;
- PyArray_Descr *type=NULL;
- PyArray_Descr *oldtype=NULL;
- NPY_ORDER order=PyArray_ANYORDER;
- int flags=0;
-
- if (PyTuple_GET_SIZE(args) > 2) {
- PyErr_SetString(PyExc_ValueError,
- "only 2 non-keyword arguments accepted");
- return NULL;
+ PyObject *op, *ret=NULL;
+ static char *kwd[]= {"object", "dtype", "copy", "order", "subok",
+ "ndmin", NULL};
+ Bool subok=FALSE;
+ Bool copy=TRUE;
+ int ndmin=0, nd;
+ PyArray_Descr *type=NULL;
+ PyArray_Descr *oldtype=NULL;
+ NPY_ORDER order=PyArray_ANYORDER;
+ int flags=0;
+
+ if (PyTuple_GET_SIZE(args) > 2) {
+ PyErr_SetString(PyExc_ValueError,
+ "only 2 non-keyword arguments accepted");
+ return NULL;
+ }
+
+ if(!PyArg_ParseTupleAndKeywords(args, kws, "O|O&O&O&O&i", kwd, &op,
+ PyArray_DescrConverter2,
+ &type,
+ PyArray_BoolConverter, &copy,
+ PyArray_OrderConverter, &order,
+ PyArray_BoolConverter, &subok,
+ &ndmin))
+ return NULL;
+
+ /* fast exit if simple call */
+ if ((subok && PyArray_Check(op)) ||
+ (!subok && PyArray_CheckExact(op))) {
+ if (type==NULL) {
+ if (!copy && STRIDING_OK(op, order)) {
+ Py_INCREF(op);
+ ret = op;
+ goto finish;
+ }
+ else {
+ ret = PyArray_NewCopy((PyArrayObject*)op,
+ order);
+ goto finish;
+ }
+ }
+ /* One more chance */
+ oldtype = PyArray_DESCR(op);
+ if (PyArray_EquivTypes(oldtype, type)) {
+ if (!copy && STRIDING_OK(op, order)) {
+ Py_INCREF(op);
+ ret = op;
+ goto finish;
+ }
+ else {
+ ret = PyArray_NewCopy((PyArrayObject*)op,
+ order);
+ if (oldtype == type) goto finish;
+ Py_INCREF(oldtype);
+ Py_DECREF(PyArray_DESCR(ret));
+ PyArray_DESCR(ret) = oldtype;
+ goto finish;
+ }
}
+ }
+
+ if (copy) {
+ flags = ENSURECOPY;
+ }
+ if (order == PyArray_CORDER) {
+ flags |= CONTIGUOUS;
+ }
+ else if ((order == PyArray_FORTRANORDER) ||
+ /* order == PyArray_ANYORDER && */
+ (PyArray_Check(op) && PyArray_ISFORTRAN(op))) {
+ flags |= FORTRAN;
+ }
+ if (!subok) {
+ flags |= ENSUREARRAY;
+ }
- if(!PyArg_ParseTupleAndKeywords(args, kws, "O|O&O&O&O&i", kwd, &op,
- PyArray_DescrConverter2,
- &type,
- PyArray_BoolConverter, &copy,
- PyArray_OrderConverter, &order,
- PyArray_BoolConverter, &subok,
- &ndmin))
- return NULL;
-
- /* fast exit if simple call */
- if ((subok && PyArray_Check(op)) ||
- (!subok && PyArray_CheckExact(op))) {
- if (type==NULL) {
- if (!copy && STRIDING_OK(op, order)) {
- Py_INCREF(op);
- ret = op;
- goto finish;
- }
- else {
- ret = PyArray_NewCopy((PyArrayObject*)op,
- order);
- goto finish;
- }
- }
- /* One more chance */
- oldtype = PyArray_DESCR(op);
- if (PyArray_EquivTypes(oldtype, type)) {
- if (!copy && STRIDING_OK(op, order)) {
- Py_INCREF(op);
- ret = op;
- goto finish;
- }
- else {
- ret = PyArray_NewCopy((PyArrayObject*)op,
- order);
- if (oldtype == type) goto finish;
- Py_INCREF(oldtype);
- Py_DECREF(PyArray_DESCR(ret));
- PyArray_DESCR(ret) = oldtype;
- goto finish;
- }
- }
- }
-
- if (copy) {
- flags = ENSURECOPY;
- }
- if (order == PyArray_CORDER) {
- flags |= CONTIGUOUS;
- }
- else if ((order == PyArray_FORTRANORDER) ||
- /* order == PyArray_ANYORDER && */
- (PyArray_Check(op) && PyArray_ISFORTRAN(op))) {
- flags |= FORTRAN;
- }
- if (!subok) {
- flags |= ENSUREARRAY;
- }
-
- flags |= NPY_FORCECAST;
-
- ret = PyArray_CheckFromAny(op, type, 0, 0, flags, NULL);
+ flags |= NPY_FORCECAST;
+
+ ret = PyArray_CheckFromAny(op, type, 0, 0, flags, NULL);
finish:
- if (!ret || (nd=PyArray_NDIM(ret)) >= ndmin) return ret;
- /* create a new array from the same data with ones in the shape */
- /* steals a reference to ret */
- return _prepend_ones((PyArrayObject *)ret, nd, ndmin);
+ if (!ret || (nd=PyArray_NDIM(ret)) >= ndmin) return ret;
+ /* create a new array from the same data with ones in the shape */
+ /* steals a reference to ret */
+ return _prepend_ones((PyArrayObject *)ret, nd, ndmin);
}
/* accepts NULL type */
/* steals referenct to type */
/*MULTIARRAY_API
- Empty
+ Empty
*/
static PyObject *
PyArray_Empty(int nd, intp *dims, PyArray_Descr *type, int fortran)
{
- PyArrayObject *ret;
+ PyArrayObject *ret;
- if (!type) type = PyArray_DescrFromType(PyArray_DEFAULT);
- ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
- type, nd, dims,
- NULL, NULL,
- fortran, NULL);
- if (ret == NULL) return NULL;
+ if (!type) type = PyArray_DescrFromType(PyArray_DEFAULT);
+ ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
+ type, nd, dims,
+ NULL, NULL,
+ fortran, NULL);
+ if (ret == NULL) return NULL;
- if (PyDataType_REFCHK(type)) {
- PyArray_FillObjectArray(ret, Py_None);
- if (PyErr_Occurred()) {Py_DECREF(ret); return NULL;}
- }
- return (PyObject *)ret;
+ if (PyDataType_REFCHK(type)) {
+ PyArray_FillObjectArray(ret, Py_None);
+ if (PyErr_Occurred()) {Py_DECREF(ret); return NULL;}
+ }
+ return (PyObject *)ret;
}
static PyObject *
array_empty(PyObject *ignored, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"shape","dtype","order",NULL};
- PyArray_Descr *typecode=NULL;
- PyArray_Dims shape = {NULL, 0};
- NPY_ORDER order = PyArray_CORDER;
- Bool fortran;
- PyObject *ret=NULL;
+ static char *kwlist[] = {"shape","dtype","order",NULL};
+ PyArray_Descr *typecode=NULL;
+ PyArray_Dims shape = {NULL, 0};
+ NPY_ORDER order = PyArray_CORDER;
+ Bool fortran;
+ PyObject *ret=NULL;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&",
- kwlist, PyArray_IntpConverter,
- &shape,
- PyArray_DescrConverter,
- &typecode,
- PyArray_OrderConverter, &order))
- goto fail;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&",
+ kwlist, PyArray_IntpConverter,
+ &shape,
+ PyArray_DescrConverter,
+ &typecode,
+ PyArray_OrderConverter, &order))
+ goto fail;
- if (order == PyArray_FORTRANORDER) fortran = TRUE;
- else fortran = FALSE;
+ if (order == PyArray_FORTRANORDER) fortran = TRUE;
+ else fortran = FALSE;
- ret = PyArray_Empty(shape.len, shape.ptr, typecode, fortran);
- PyDimMem_FREE(shape.ptr);
- return ret;
+ ret = PyArray_Empty(shape.len, shape.ptr, typecode, fortran);
+ PyDimMem_FREE(shape.ptr);
+ return ret;
fail:
- PyDimMem_FREE(shape.ptr);
- return ret;
+ PyDimMem_FREE(shape.ptr);
+ return ret;
}
static PyObject *
array_scalar(PyObject *ignored, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"dtype","obj", NULL};
- PyArray_Descr *typecode;
- PyObject *obj=NULL;
- int alloc=0;
- void *dptr;
- PyObject *ret;
-
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|O",
- kwlist, &PyArrayDescr_Type,
- &typecode,
- &obj))
- return NULL;
-
- if (typecode->elsize == 0) {
- PyErr_SetString(PyExc_ValueError, \
- "itemsize cannot be zero");
- return NULL;
- }
-
- if (PyDataType_FLAGCHK(typecode, NPY_ITEM_IS_POINTER)) {
- if (obj == NULL) obj = Py_None;
- dptr = &obj;
- }
- else {
- if (obj == NULL) {
- dptr = _pya_malloc(typecode->elsize);
- if (dptr == NULL) {
- return PyErr_NoMemory();
- }
- memset(dptr, '\0', typecode->elsize);
- alloc = 1;
- }
- else {
- if (!PyString_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "initializing object must "\
- "be a string");
- return NULL;
- }
- if (PyString_GET_SIZE(obj) < typecode->elsize) {
- PyErr_SetString(PyExc_ValueError,
- "initialization string is too"\
- " small");
- return NULL;
- }
- dptr = PyString_AS_STRING(obj);
- }
- }
-
- ret = PyArray_Scalar(dptr, typecode, NULL);
-
- /* free dptr which contains zeros */
- if (alloc) _pya_free(dptr);
- return ret;
+ static char *kwlist[] = {"dtype","obj", NULL};
+ PyArray_Descr *typecode;
+ PyObject *obj=NULL;
+ int alloc=0;
+ void *dptr;
+ PyObject *ret;
+
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|O",
+ kwlist, &PyArrayDescr_Type,
+ &typecode,
+ &obj))
+ return NULL;
+
+ if (typecode->elsize == 0) {
+ PyErr_SetString(PyExc_ValueError, \
+ "itemsize cannot be zero");
+ return NULL;
+ }
+
+ if (PyDataType_FLAGCHK(typecode, NPY_ITEM_IS_POINTER)) {
+ if (obj == NULL) obj = Py_None;
+ dptr = &obj;
+ }
+ else {
+ if (obj == NULL) {
+ dptr = _pya_malloc(typecode->elsize);
+ if (dptr == NULL) {
+ return PyErr_NoMemory();
+ }
+ memset(dptr, '\0', typecode->elsize);
+ alloc = 1;
+ }
+ else {
+ if (!PyString_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "initializing object must "\
+ "be a string");
+ return NULL;
+ }
+ if (PyString_GET_SIZE(obj) < typecode->elsize) {
+ PyErr_SetString(PyExc_ValueError,
+ "initialization string is too"\
+ " small");
+ return NULL;
+ }
+ dptr = PyString_AS_STRING(obj);
+ }
+ }
+
+ ret = PyArray_Scalar(dptr, typecode, NULL);
+
+ /* free dptr which contains zeros */
+ if (alloc) _pya_free(dptr);
+ return ret;
}
/* steal a reference */
/* accepts NULL type */
/*MULTIARRAY_API
- Zeros
+ Zeros
*/
static PyObject *
PyArray_Zeros(int nd, intp *dims, PyArray_Descr *type, int fortran)
{
- PyArrayObject *ret;
- intp n;
-
- if (!type) type = PyArray_DescrFromType(PyArray_DEFAULT);
- ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
- type,
- nd, dims,
- NULL, NULL,
- fortran, NULL);
- if (ret == NULL) return NULL;
-
- if (PyDataType_REFCHK(type)) {
- PyObject *zero = PyInt_FromLong(0);
- PyArray_FillObjectArray(ret, zero);
- Py_DECREF(zero);
- if (PyErr_Occurred()) {Py_DECREF(ret); return NULL;}
- }
- else {
- n = PyArray_NBYTES(ret);
- memset(ret->data, 0, n);
- }
- return (PyObject *)ret;
+ PyArrayObject *ret;
+ intp n;
+
+ if (!type) type = PyArray_DescrFromType(PyArray_DEFAULT);
+ ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
+ type,
+ nd, dims,
+ NULL, NULL,
+ fortran, NULL);
+ if (ret == NULL) return NULL;
+
+ if (PyDataType_REFCHK(type)) {
+ PyObject *zero = PyInt_FromLong(0);
+ PyArray_FillObjectArray(ret, zero);
+ Py_DECREF(zero);
+ if (PyErr_Occurred()) {Py_DECREF(ret); return NULL;}
+ }
+ else {
+ n = PyArray_NBYTES(ret);
+ memset(ret->data, 0, n);
+ }
+ return (PyObject *)ret;
}
static PyObject *
array_zeros(PyObject *ignored, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"shape","dtype","order",NULL}; /* XXX ? */
- PyArray_Descr *typecode=NULL;
- PyArray_Dims shape = {NULL, 0};
- NPY_ORDER order = PyArray_CORDER;
- Bool fortran = FALSE;
- PyObject *ret=NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&",
- kwlist, PyArray_IntpConverter,
- &shape,
- PyArray_DescrConverter,
- &typecode,
- PyArray_OrderConverter,
- &order))
- goto fail;
-
- if (order == PyArray_FORTRANORDER) fortran = TRUE;
- else fortran = FALSE;
- ret = PyArray_Zeros(shape.len, shape.ptr, typecode, (int) fortran);
- PyDimMem_FREE(shape.ptr);
- return ret;
+ static char *kwlist[] = {"shape","dtype","order",NULL}; /* XXX ? */
+ PyArray_Descr *typecode=NULL;
+ PyArray_Dims shape = {NULL, 0};
+ NPY_ORDER order = PyArray_CORDER;
+ Bool fortran = FALSE;
+ PyObject *ret=NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&",
+ kwlist, PyArray_IntpConverter,
+ &shape,
+ PyArray_DescrConverter,
+ &typecode,
+ PyArray_OrderConverter,
+ &order))
+ goto fail;
+
+ if (order == PyArray_FORTRANORDER) fortran = TRUE;
+ else fortran = FALSE;
+ ret = PyArray_Zeros(shape.len, shape.ptr, typecode, (int) fortran);
+ PyDimMem_FREE(shape.ptr);
+ return ret;
fail:
- PyDimMem_FREE(shape.ptr);
- return ret;
+ PyDimMem_FREE(shape.ptr);
+ return ret;
}
static PyObject *
array_set_typeDict(PyObject *ignored, PyObject *args)
{
- PyObject *dict;
- if (!PyArg_ParseTuple(args, "O", &dict)) return NULL;
- Py_XDECREF(typeDict); /* Decrement old reference (if any)*/
- typeDict = dict;
- Py_INCREF(dict); /* Create an internal reference to it */
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *dict;
+ if (!PyArg_ParseTuple(args, "O", &dict)) return NULL;
+ Py_XDECREF(typeDict); /* Decrement old reference (if any)*/
+ typeDict = dict;
+ Py_INCREF(dict); /* Create an internal reference to it */
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -5851,7 +5851,7 @@ array_set_typeDict(PyObject *ignored, PyObject *args)
As much as possible, we try to use the same code for both files and strings,
so the semantics for fromstring and fromfile are the same, especially with
regards to the handling of text representations.
- */
+*/
typedef int (*next_element)(void **, void *, PyArray_Descr *, void *);
@@ -5859,21 +5859,21 @@ typedef int (*skip_separator)(void **, const char *, void *);
static int
fromstr_next_element(char **s, void *dptr, PyArray_Descr *dtype,
- const char *end)
+ const char *end)
{
- int r = dtype->f->fromstr(*s, dptr, s, dtype);
- if (end != NULL && *s > end) {
- return -1;
- }
- return r;
+ int r = dtype->f->fromstr(*s, dptr, s, dtype);
+ if (end != NULL && *s > end) {
+ return -1;
+ }
+ return r;
}
static int
fromfile_next_element(FILE **fp, void *dptr, PyArray_Descr *dtype,
- void *stream_data)
+ void *stream_data)
{
- /* the NULL argument is for backwards-compatibility */
- return dtype->f->scanfunc(*fp, dptr, NULL, dtype);
+ /* the NULL argument is for backwards-compatibility */
+ return dtype->f->scanfunc(*fp, dptr, NULL, dtype);
}
/* Remove multiple whitespace from the separator, and add a space to the
@@ -5882,35 +5882,35 @@ fromfile_next_element(FILE **fp, void *dptr, PyArray_Descr *dtype,
static char *
swab_separator(char *sep)
{
- int skip_space = 0;
- char *s, *start;
- s = start = malloc(strlen(sep)+3);
- /* add space to front if there isn't one */
- if (*sep != '\0' && !isspace(*sep)) {
- *s = ' '; s++;
- }
- while (*sep != '\0') {
- if (isspace(*sep)) {
- if (skip_space) {
- sep++;
- } else {
- *s = ' ';
- s++; sep++;
- skip_space = 1;
- }
- } else {
- *s = *sep;
- s++; sep++;
- skip_space = 0;
- }
- }
- /* add space to end if there isn't one */
- if (s != start && s[-1] == ' ') {
- *s = ' ';
- s++;
- }
- *s = '\0';
- return start;
+ int skip_space = 0;
+ char *s, *start;
+ s = start = malloc(strlen(sep)+3);
+ /* add space to front if there isn't one */
+ if (*sep != '\0' && !isspace(*sep)) {
+ *s = ' '; s++;
+ }
+ while (*sep != '\0') {
+ if (isspace(*sep)) {
+ if (skip_space) {
+ sep++;
+ } else {
+ *s = ' ';
+ s++; sep++;
+ skip_space = 1;
+ }
+ } else {
+ *s = *sep;
+ s++; sep++;
+ skip_space = 0;
+ }
+ }
+ /* add space to end if there isn't one */
+ if (s != start && s[-1] == ' ') {
+ *s = ' ';
+ s++;
+ }
+ *s = '\0';
+ return start;
}
/* Assuming that the separator is the next bit in the string (file), skip it.
@@ -5921,126 +5921,126 @@ swab_separator(char *sep)
If we can't match the separator, return -2.
If we hit the end of the string (file), return -1.
Otherwise, return 0.
- */
+*/
static int
fromstr_skip_separator(char **s, const char *sep, const char *end)
{
- char *string = *s;
- int result = 0;
- while (1) {
- char c = *string;
- if (c == '\0' || (end != NULL && string >= end)) {
- result = -1;
- break;
- } else if (*sep == '\0') {
- /* matched separator */
- result = 0;
- break;
- } else if (*sep == ' ') {
- if (!isspace(c)) {
- sep++;
- continue;
- }
- } else if (*sep != c) {
- result = -2;
- break;
- } else {
- sep++;
- }
- string++;
- }
- *s = string;
- return result;
+ char *string = *s;
+ int result = 0;
+ while (1) {
+ char c = *string;
+ if (c == '\0' || (end != NULL && string >= end)) {
+ result = -1;
+ break;
+ } else if (*sep == '\0') {
+ /* matched separator */
+ result = 0;
+ break;
+ } else if (*sep == ' ') {
+ if (!isspace(c)) {
+ sep++;
+ continue;
+ }
+ } else if (*sep != c) {
+ result = -2;
+ break;
+ } else {
+ sep++;
+ }
+ string++;
+ }
+ *s = string;
+ return result;
}
static int
fromfile_skip_separator(FILE **fp, const char *sep, void *stream_data)
{
- int result = 0;
- while (1) {
- int c = fgetc(*fp);
- if (c == EOF) {
- result = -1;
- break;
- } else if (*sep == '\0') {
- /* matched separator */
- ungetc(c, *fp);
- result = 0;
- break;
- } else if (*sep == ' ') {
- if (!isspace(c)) {
- sep++;
- ungetc(c, *fp);
- }
- } else if (*sep != c) {
- ungetc(c, *fp);
- result = -2;
- break;
- } else {
- sep++;
- }
- }
- return result;
+ int result = 0;
+ while (1) {
+ int c = fgetc(*fp);
+ if (c == EOF) {
+ result = -1;
+ break;
+ } else if (*sep == '\0') {
+ /* matched separator */
+ ungetc(c, *fp);
+ result = 0;
+ break;
+ } else if (*sep == ' ') {
+ if (!isspace(c)) {
+ sep++;
+ ungetc(c, *fp);
+ }
+ } else if (*sep != c) {
+ ungetc(c, *fp);
+ result = -2;
+ break;
+ } else {
+ sep++;
+ }
+ }
+ return result;
}
/* Create an array by reading from the given stream, using the passed
next_element and skip_separator functions.
- */
+*/
#define FROM_BUFFER_SIZE 4096
static PyArrayObject *
array_from_text(PyArray_Descr *dtype, intp num, char *sep, size_t *nread,
- void *stream, next_element next, skip_separator skip_sep,
- void *stream_data)
-{
- PyArrayObject *r;
- intp i;
- char *dptr, *clean_sep;
-
- intp thisbuf = 0;
- intp size;
- intp bytes, totalbytes;
-
- size = (num >= 0) ? num : FROM_BUFFER_SIZE;
-
- r = (PyArrayObject *)
- PyArray_NewFromDescr(&PyArray_Type,
- dtype,
- 1, &size,
- NULL, NULL,
- 0, NULL);
- if (r == NULL) return NULL;
- clean_sep = swab_separator(sep);
- NPY_BEGIN_ALLOW_THREADS;
- totalbytes = bytes = size * dtype->elsize;
- dptr = r->data;
- for (i=0; num < 0 || i < num; i++) {
- if (next(&stream, dptr, dtype, stream_data) < 0)
- break;
- *nread += 1;
- thisbuf += 1;
- dptr += dtype->elsize;
- if (num < 0 && thisbuf == size) {
- totalbytes += bytes;
- r->data = PyDataMem_RENEW(r->data, totalbytes);
- dptr = r->data + (totalbytes - bytes);
- thisbuf = 0;
- }
- if (skip_sep(&stream, clean_sep, stream_data) < 0)
- break;
- }
- if (num < 0) {
- r->data = PyDataMem_RENEW(r->data, (*nread)*dtype->elsize);
- PyArray_DIM(r,0) = *nread;
- }
- NPY_END_ALLOW_THREADS;
- free(clean_sep);
- if (PyErr_Occurred()) {
- Py_DECREF(r);
- return NULL;
- }
- return r;
+ void *stream, next_element next, skip_separator skip_sep,
+ void *stream_data)
+{
+ PyArrayObject *r;
+ intp i;
+ char *dptr, *clean_sep;
+
+ intp thisbuf = 0;
+ intp size;
+ intp bytes, totalbytes;
+
+ size = (num >= 0) ? num : FROM_BUFFER_SIZE;
+
+ r = (PyArrayObject *)
+ PyArray_NewFromDescr(&PyArray_Type,
+ dtype,
+ 1, &size,
+ NULL, NULL,
+ 0, NULL);
+ if (r == NULL) return NULL;
+ clean_sep = swab_separator(sep);
+ NPY_BEGIN_ALLOW_THREADS;
+ totalbytes = bytes = size * dtype->elsize;
+ dptr = r->data;
+ for (i=0; num < 0 || i < num; i++) {
+ if (next(&stream, dptr, dtype, stream_data) < 0)
+ break;
+ *nread += 1;
+ thisbuf += 1;
+ dptr += dtype->elsize;
+ if (num < 0 && thisbuf == size) {
+ totalbytes += bytes;
+ r->data = PyDataMem_RENEW(r->data, totalbytes);
+ dptr = r->data + (totalbytes - bytes);
+ thisbuf = 0;
+ }
+ if (skip_sep(&stream, clean_sep, stream_data) < 0)
+ break;
+ }
+ if (num < 0) {
+ r->data = PyDataMem_RENEW(r->data, (*nread)*dtype->elsize);
+ PyArray_DIM(r,0) = *nread;
+ }
+ NPY_END_ALLOW_THREADS;
+ free(clean_sep);
+ if (PyErr_Occurred()) {
+ Py_DECREF(r);
+ return NULL;
+ }
+ return r;
}
#undef FROM_BUFFER_SIZE
@@ -6064,106 +6064,106 @@ array_from_text(PyArray_Descr *dtype, intp num, char *sep, size_t *nread,
text data, with ``sep`` as the separator between elements. Whitespace in
the separator matches any length of whitespace in the text, and a match
for whitespace around the separator is added.
- */
+*/
static PyObject *
PyArray_FromString(char *data, intp slen, PyArray_Descr *dtype,
- intp num, char *sep)
+ intp num, char *sep)
{
- int itemsize;
- PyArrayObject *ret;
- Bool binary;
+ int itemsize;
+ PyArrayObject *ret;
+ Bool binary;
+
+ if (dtype == NULL)
+ dtype=PyArray_DescrFromType(PyArray_DEFAULT);
+
+ if (PyDataType_FLAGCHK(dtype, NPY_ITEM_IS_POINTER)) {
+ PyErr_SetString(PyExc_ValueError,
+ "Cannot create an object array from" \
+ " a string");
+ Py_DECREF(dtype);
+ return NULL;
+ }
- if (dtype == NULL)
- dtype=PyArray_DescrFromType(PyArray_DEFAULT);
+ itemsize = dtype->elsize;
+ if (itemsize == 0) {
+ PyErr_SetString(PyExc_ValueError, "zero-valued itemsize");
+ Py_DECREF(dtype);
+ return NULL;
+ }
- if (PyDataType_FLAGCHK(dtype, NPY_ITEM_IS_POINTER)) {
+ binary = ((sep == NULL) || (strlen(sep) == 0));
+
+ if (binary) {
+ if (num < 0 ) {
+ if (slen % itemsize != 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "string size must be a "\
+ "multiple of element size");
+ Py_DECREF(dtype);
+ return NULL;
+ }
+ num = slen/itemsize;
+ } else {
+ if (slen < num*itemsize) {
PyErr_SetString(PyExc_ValueError,
- "Cannot create an object array from" \
- " a string");
+ "string is smaller than " \
+ "requested size");
Py_DECREF(dtype);
return NULL;
+ }
}
- itemsize = dtype->elsize;
- if (itemsize == 0) {
- PyErr_SetString(PyExc_ValueError, "zero-valued itemsize");
- Py_DECREF(dtype);
- return NULL;
- }
-
- binary = ((sep == NULL) || (strlen(sep) == 0));
-
- if (binary) {
- if (num < 0 ) {
- if (slen % itemsize != 0) {
- PyErr_SetString(PyExc_ValueError,
- "string size must be a "\
- "multiple of element size");
- Py_DECREF(dtype);
- return NULL;
- }
- num = slen/itemsize;
- } else {
- if (slen < num*itemsize) {
- PyErr_SetString(PyExc_ValueError,
- "string is smaller than " \
- "requested size");
- Py_DECREF(dtype);
- return NULL;
- }
- }
-
- ret = (PyArrayObject *)
- PyArray_NewFromDescr(&PyArray_Type, dtype,
- 1, &num, NULL, NULL,
- 0, NULL);
- if (ret == NULL) return NULL;
- memcpy(ret->data, data, num*dtype->elsize);
- } else {
- /* read from character-based string */
- size_t nread = 0;
- char *end;
- if (dtype->f->scanfunc == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "don't know how to read " \
- "character strings with that " \
- "array type");
- Py_DECREF(dtype);
- return NULL;
- }
- if (slen < 0) {
- end = NULL;
- } else {
- end = data + slen;
- }
- ret = array_from_text(dtype, num, sep, &nread,
- data,
- (next_element) fromstr_next_element,
- (skip_separator) fromstr_skip_separator,
- end);
- }
- return (PyObject *)ret;
+ ret = (PyArrayObject *)
+ PyArray_NewFromDescr(&PyArray_Type, dtype,
+ 1, &num, NULL, NULL,
+ 0, NULL);
+ if (ret == NULL) return NULL;
+ memcpy(ret->data, data, num*dtype->elsize);
+ } else {
+ /* read from character-based string */
+ size_t nread = 0;
+ char *end;
+ if (dtype->f->scanfunc == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "don't know how to read " \
+ "character strings with that " \
+ "array type");
+ Py_DECREF(dtype);
+ return NULL;
+ }
+ if (slen < 0) {
+ end = NULL;
+ } else {
+ end = data + slen;
+ }
+ ret = array_from_text(dtype, num, sep, &nread,
+ data,
+ (next_element) fromstr_next_element,
+ (skip_separator) fromstr_skip_separator,
+ end);
+ }
+ return (PyObject *)ret;
}
static PyObject *
array_fromstring(PyObject *ignored, PyObject *args, PyObject *keywds)
{
- char *data;
- Py_ssize_t nin=-1;
- char *sep=NULL;
- Py_ssize_t s;
- static char *kwlist[] = {"string", "dtype", "count", "sep", NULL};
- PyArray_Descr *descr=NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&"
- NPY_SSIZE_T_PYFMT "s", kwlist,
- &data, &s,
- PyArray_DescrConverter, &descr,
- &nin, &sep)) {
- return NULL;
- }
+ char *data;
+ Py_ssize_t nin=-1;
+ char *sep=NULL;
+ Py_ssize_t s;
+ static char *kwlist[] = {"string", "dtype", "count", "sep", NULL};
+ PyArray_Descr *descr=NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&"
+ NPY_SSIZE_T_PYFMT "s", kwlist,
+ &data, &s,
+ PyArray_DescrConverter, &descr,
+ &nin, &sep)) {
+ return NULL;
+ }
- return PyArray_FromString(data, (intp)s, descr, (intp)nin, sep);
+ return PyArray_FromString(data, (intp)s, descr, (intp)nin, sep);
}
@@ -6171,36 +6171,36 @@ array_fromstring(PyObject *ignored, PyObject *args, PyObject *keywds)
static PyArrayObject *
array_fromfile_binary(FILE *fp, PyArray_Descr *dtype, intp num, size_t *nread)
{
- PyArrayObject *r;
- intp start, numbytes;
-
- if (num < 0) {
- int fail=0;
- start = (intp )ftell(fp);
- if (start < 0) fail=1;
- if (fseek(fp, 0, SEEK_END) < 0) fail=1;
- numbytes = (intp) ftell(fp);
- if (numbytes < 0) fail=1;
- numbytes -= start;
- if (fseek(fp, start, SEEK_SET) < 0) fail=1;
- if (fail) {
- PyErr_SetString(PyExc_IOError,
- "could not seek in file");
- Py_DECREF(dtype);
- return NULL;
- }
- num = numbytes / dtype->elsize;
- }
- r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
- dtype,
- 1, &num,
- NULL, NULL,
- 0, NULL);
- if (r==NULL) return NULL;
- NPY_BEGIN_ALLOW_THREADS;
- *nread = fread(r->data, dtype->elsize, num, fp);
- NPY_END_ALLOW_THREADS;
- return r;
+ PyArrayObject *r;
+ intp start, numbytes;
+
+ if (num < 0) {
+ int fail=0;
+ start = (intp )ftell(fp);
+ if (start < 0) fail=1;
+ if (fseek(fp, 0, SEEK_END) < 0) fail=1;
+ numbytes = (intp) ftell(fp);
+ if (numbytes < 0) fail=1;
+ numbytes -= start;
+ if (fseek(fp, start, SEEK_SET) < 0) fail=1;
+ if (fail) {
+ PyErr_SetString(PyExc_IOError,
+ "could not seek in file");
+ Py_DECREF(dtype);
+ return NULL;
+ }
+ num = numbytes / dtype->elsize;
+ }
+ r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
+ dtype,
+ 1, &num,
+ NULL, NULL,
+ 0, NULL);
+ if (r==NULL) return NULL;
+ NPY_BEGIN_ALLOW_THREADS;
+ *nread = fread(r->data, dtype->elsize, num, fp);
+ NPY_END_ALLOW_THREADS;
+ return r;
}
/*OBJECT_API
@@ -6225,87 +6225,87 @@ array_fromfile_binary(FILE *fp, PyArray_Descr *dtype, intp num, size_t *nread)
static PyObject *
PyArray_FromFile(FILE *fp, PyArray_Descr *dtype, intp num, char *sep)
{
- PyArrayObject *ret;
- size_t nread = 0;
+ PyArrayObject *ret;
+ size_t nread = 0;
- if (PyDataType_REFCHK(dtype)) {
- PyErr_SetString(PyExc_ValueError,
- "cannot read into object array");
- Py_DECREF(dtype);
- return NULL;
+ if (PyDataType_REFCHK(dtype)) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot read into object array");
+ Py_DECREF(dtype);
+ return NULL;
+ }
+ if (dtype->elsize == 0) {
+ PyErr_SetString(PyExc_ValueError, "0-sized elements.");
+ Py_DECREF(dtype);
+ return NULL;
+ }
+
+ if ((sep == NULL) || (strlen(sep) == 0)) {
+ ret = array_fromfile_binary(fp, dtype, num, &nread);
+ } else {
+ if (dtype->f->scanfunc == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "don't know how to read " \
+ "character files with that " \
+ "array type");
+ Py_DECREF(dtype);
+ return NULL;
}
- if (dtype->elsize == 0) {
- PyErr_SetString(PyExc_ValueError, "0-sized elements.");
- Py_DECREF(dtype);
- return NULL;
- }
-
- if ((sep == NULL) || (strlen(sep) == 0)) {
- ret = array_fromfile_binary(fp, dtype, num, &nread);
- } else {
- if (dtype->f->scanfunc == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "don't know how to read " \
- "character files with that " \
- "array type");
- Py_DECREF(dtype);
- return NULL;
- }
- ret = array_from_text(dtype, num, sep, &nread,
- fp,
- (next_element) fromfile_next_element,
- (skip_separator) fromfile_skip_separator,
- NULL);
- }
- if (((intp) nread) < num) {
- fprintf(stderr, "%ld items requested but only %ld read\n",
- (long) num, (long) nread);
- ret->data = PyDataMem_RENEW(ret->data,
- nread * ret->descr->elsize);
- PyArray_DIM(ret,0) = nread;
- }
- return (PyObject *)ret;
+ ret = array_from_text(dtype, num, sep, &nread,
+ fp,
+ (next_element) fromfile_next_element,
+ (skip_separator) fromfile_skip_separator,
+ NULL);
+ }
+ if (((intp) nread) < num) {
+ fprintf(stderr, "%ld items requested but only %ld read\n",
+ (long) num, (long) nread);
+ ret->data = PyDataMem_RENEW(ret->data,
+ nread * ret->descr->elsize);
+ PyArray_DIM(ret,0) = nread;
+ }
+ return (PyObject *)ret;
}
static PyObject *
array_fromfile(PyObject *ignored, PyObject *args, PyObject *keywds)
{
- PyObject *file=NULL, *ret;
- FILE *fp;
- char *sep="";
- Py_ssize_t nin=-1;
- static char *kwlist[] = {"file", "dtype", "count", "sep", NULL};
- PyArray_Descr *type=NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, keywds,
- "O|O&" NPY_SSIZE_T_PYFMT "s",
- kwlist,
- &file,
- PyArray_DescrConverter, &type,
- &nin, &sep)) {
- return NULL;
- }
-
- if (type == NULL) type = PyArray_DescrFromType(PyArray_DEFAULT);
-
- if (PyString_Check(file) || PyUnicode_Check(file)) {
- file = PyObject_CallFunction((PyObject *)&PyFile_Type,
- "Os", file, "rb");
- if (file==NULL) return NULL;
- }
- else {
- Py_INCREF(file);
- }
- fp = PyFile_AsFile(file);
- if (fp == NULL) {
- PyErr_SetString(PyExc_IOError,
- "first argument must be an open file");
- Py_DECREF(file);
- return NULL;
- }
- ret = PyArray_FromFile(fp, type, (intp) nin, sep);
- Py_DECREF(file);
- return ret;
+ PyObject *file=NULL, *ret;
+ FILE *fp;
+ char *sep="";
+ Py_ssize_t nin=-1;
+ static char *kwlist[] = {"file", "dtype", "count", "sep", NULL};
+ PyArray_Descr *type=NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, keywds,
+ "O|O&" NPY_SSIZE_T_PYFMT "s",
+ kwlist,
+ &file,
+ PyArray_DescrConverter, &type,
+ &nin, &sep)) {
+ return NULL;
+ }
+
+ if (type == NULL) type = PyArray_DescrFromType(PyArray_DEFAULT);
+
+ if (PyString_Check(file) || PyUnicode_Check(file)) {
+ file = PyObject_CallFunction((PyObject *)&PyFile_Type,
+ "Os", file, "rb");
+ if (file==NULL) return NULL;
+ }
+ else {
+ Py_INCREF(file);
+ }
+ fp = PyFile_AsFile(file);
+ if (fp == NULL) {
+ PyErr_SetString(PyExc_IOError,
+ "first argument must be an open file");
+ Py_DECREF(file);
+ return NULL;
+ }
+ ret = PyArray_FromFile(fp, type, (intp) nin, sep);
+ Py_DECREF(file);
+ return ret;
}
@@ -6314,335 +6314,335 @@ array_fromfile(PyObject *ignored, PyObject *args, PyObject *keywds)
static PyObject *
PyArray_FromIter(PyObject *obj, PyArray_Descr *dtype, intp count)
{
- PyObject *value;
- PyObject *iter = PyObject_GetIter(obj);
- PyArrayObject *ret = NULL;
- intp i, elsize, elcount;
- char *item, *new_data;
+ PyObject *value;
+ PyObject *iter = PyObject_GetIter(obj);
+ PyArrayObject *ret = NULL;
+ intp i, elsize, elcount;
+ char *item, *new_data;
- if (iter == NULL) goto done;
+ if (iter == NULL) goto done;
- elcount = (count < 0) ? 0 : count;
- elsize = dtype->elsize;
+ elcount = (count < 0) ? 0 : count;
+ elsize = dtype->elsize;
- /* We would need to alter the memory RENEW code to decrement any
- reference counts before throwing away any memory.
- */
- if (PyDataType_REFCHK(dtype)) {
- PyErr_SetString(PyExc_ValueError, "cannot create "\
- "object arrays from iterator");
- goto done;
- }
+ /* We would need to alter the memory RENEW code to decrement any
+ reference counts before throwing away any memory.
+ */
+ if (PyDataType_REFCHK(dtype)) {
+ PyErr_SetString(PyExc_ValueError, "cannot create "\
+ "object arrays from iterator");
+ goto done;
+ }
- ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1,
- &elcount, NULL,NULL, 0, NULL);
- dtype = NULL;
- if (ret == NULL) goto done;
-
- for (i = 0; (i < count || count == -1) &&
- (value = PyIter_Next(iter)); i++) {
-
- if (i >= elcount) {
- /*
- Grow ret->data:
- this is similar for the strategy for PyListObject, but we use
- 50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ...
- */
- elcount = (i >> 1) + (i < 4 ? 4 : 2) + i;
- if (elcount <= (intp)((~(size_t)0) / elsize))
- new_data = PyDataMem_RENEW(ret->data, elcount * elsize);
- else
- new_data = NULL;
- if (new_data == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "cannot allocate array memory");
- Py_DECREF(value);
- goto done;
- }
- ret->data = new_data;
+ ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1,
+ &elcount, NULL,NULL, 0, NULL);
+ dtype = NULL;
+ if (ret == NULL) goto done;
+
+ for (i = 0; (i < count || count == -1) &&
+ (value = PyIter_Next(iter)); i++) {
+
+ if (i >= elcount) {
+ /*
+ Grow ret->data:
+ this is similar for the strategy for PyListObject, but we use
+ 50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ...
+ */
+ elcount = (i >> 1) + (i < 4 ? 4 : 2) + i;
+ if (elcount <= (intp)((~(size_t)0) / elsize))
+ new_data = PyDataMem_RENEW(ret->data, elcount * elsize);
+ else
+ new_data = NULL;
+ if (new_data == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "cannot allocate array memory");
+ Py_DECREF(value);
+ goto done;
}
- ret->dimensions[0] = i+1;
+ ret->data = new_data;
+ }
+ ret->dimensions[0] = i+1;
- if (((item = index2ptr(ret, i)) == NULL) ||
- (ret->descr->f->setitem(value, item, ret) == -1)) {
- Py_DECREF(value);
- goto done;
- }
+ if (((item = index2ptr(ret, i)) == NULL) ||
+ (ret->descr->f->setitem(value, item, ret) == -1)) {
Py_DECREF(value);
-
+ goto done;
}
+ Py_DECREF(value);
- if (i < count) {
- PyErr_SetString(PyExc_ValueError, "iterator too short");
- goto done;
- }
+ }
- /*
- Realloc the data so that don't keep extra memory tied up
- (assuming realloc is reasonably good about reusing space...)
- */
- if (i==0) i = 1;
- ret->data = PyDataMem_RENEW(ret->data, i * elsize);
- if (ret->data == NULL) {
- PyErr_SetString(PyExc_MemoryError, "cannot allocate array memory");
- goto done;
- }
+ if (i < count) {
+ PyErr_SetString(PyExc_ValueError, "iterator too short");
+ goto done;
+ }
-done:
- Py_XDECREF(iter);
- Py_XDECREF(dtype);
- if (PyErr_Occurred()) {
- Py_XDECREF(ret);
- return NULL;
- }
- return (PyObject *)ret;
+ /*
+ Realloc the data so that don't keep extra memory tied up
+ (assuming realloc is reasonably good about reusing space...)
+ */
+ if (i==0) i = 1;
+ ret->data = PyDataMem_RENEW(ret->data, i * elsize);
+ if (ret->data == NULL) {
+ PyErr_SetString(PyExc_MemoryError, "cannot allocate array memory");
+ goto done;
+ }
+
+ done:
+ Py_XDECREF(iter);
+ Py_XDECREF(dtype);
+ if (PyErr_Occurred()) {
+ Py_XDECREF(ret);
+ return NULL;
+ }
+ return (PyObject *)ret;
}
static PyObject *
array_fromiter(PyObject *ignored, PyObject *args, PyObject *keywds)
{
- PyObject *iter;
- Py_ssize_t nin=-1;
- static char *kwlist[] = {"iter", "dtype", "count", NULL};
- PyArray_Descr *descr=NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, keywds,
- "OO&|" NPY_SSIZE_T_PYFMT,
- kwlist,
- &iter,
- PyArray_DescrConverter, &descr,
- &nin)) {
- return NULL;
- }
+ PyObject *iter;
+ Py_ssize_t nin=-1;
+ static char *kwlist[] = {"iter", "dtype", "count", NULL};
+ PyArray_Descr *descr=NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, keywds,
+ "OO&|" NPY_SSIZE_T_PYFMT,
+ kwlist,
+ &iter,
+ PyArray_DescrConverter, &descr,
+ &nin)) {
+ return NULL;
+ }
- return PyArray_FromIter(iter, descr, (intp)nin);
+ return PyArray_FromIter(iter, descr, (intp)nin);
}
/*OBJECT_API*/
static PyObject *
PyArray_FromBuffer(PyObject *buf, PyArray_Descr *type,
- intp count, intp offset)
-{
- PyArrayObject *ret;
- char *data;
- Py_ssize_t ts;
- intp s, n;
- int itemsize;
- int write=1;
-
-
- if (PyDataType_REFCHK(type)) {
- PyErr_SetString(PyExc_ValueError,
- "cannot create an OBJECT array from memory"\
- " buffer");
- Py_DECREF(type);
- return NULL;
- }
- if (type->elsize == 0) {
- PyErr_SetString(PyExc_ValueError,
- "itemsize cannot be zero in type");
- Py_DECREF(type);
- return NULL;
- }
-
- if (buf->ob_type->tp_as_buffer == NULL || \
- (buf->ob_type->tp_as_buffer->bf_getwritebuffer == NULL && \
- buf->ob_type->tp_as_buffer->bf_getreadbuffer == NULL)) {
- PyObject *newbuf;
- newbuf = PyObject_GetAttrString(buf, "__buffer__");
- if (newbuf == NULL) {Py_DECREF(type); return NULL;}
- buf = newbuf;
- }
- else {Py_INCREF(buf);}
-
- if (PyObject_AsWriteBuffer(buf, (void *)&data, &ts)==-1) {
- write = 0;
- PyErr_Clear();
- if (PyObject_AsReadBuffer(buf, (void *)&data, &ts)==-1) {
- Py_DECREF(buf);
- Py_DECREF(type);
- return NULL;
- }
- }
-
- if ((offset < 0) || (offset >= ts)) {
- PyErr_Format(PyExc_ValueError,
- "offset must be positive and smaller than %"
- INTP_FMT, (intp)ts);
- }
-
- data += offset;
- s = (intp)ts - offset;
- n = (intp)count;
- itemsize = type->elsize;
-
- if (n < 0 ) {
- if (s % itemsize != 0) {
- PyErr_SetString(PyExc_ValueError,
- "buffer size must be a multiple"\
- " of element size");
- Py_DECREF(buf);
- Py_DECREF(type);
- return NULL;
- }
- n = s/itemsize;
- } else {
- if (s < n*itemsize) {
- PyErr_SetString(PyExc_ValueError,
- "buffer is smaller than requested"\
- " size");
- Py_DECREF(buf);
- Py_DECREF(type);
- return NULL;
- }
- }
-
- if ((ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
- type,
- 1, &n,
- NULL, data,
- DEFAULT,
- NULL)) == NULL) {
- Py_DECREF(buf);
- return NULL;
- }
-
- if (!write) ret->flags &= ~WRITEABLE;
-
- /* Store a reference for decref on deallocation */
- ret->base = buf;
- PyArray_UpdateFlags(ret, ALIGNED);
- return (PyObject *)ret;
+ intp count, intp offset)
+{
+ PyArrayObject *ret;
+ char *data;
+ Py_ssize_t ts;
+ intp s, n;
+ int itemsize;
+ int write=1;
+
+
+ if (PyDataType_REFCHK(type)) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot create an OBJECT array from memory"\
+ " buffer");
+ Py_DECREF(type);
+ return NULL;
+ }
+ if (type->elsize == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "itemsize cannot be zero in type");
+ Py_DECREF(type);
+ return NULL;
+ }
+
+ if (buf->ob_type->tp_as_buffer == NULL || \
+ (buf->ob_type->tp_as_buffer->bf_getwritebuffer == NULL && \
+ buf->ob_type->tp_as_buffer->bf_getreadbuffer == NULL)) {
+ PyObject *newbuf;
+ newbuf = PyObject_GetAttrString(buf, "__buffer__");
+ if (newbuf == NULL) {Py_DECREF(type); return NULL;}
+ buf = newbuf;
+ }
+ else {Py_INCREF(buf);}
+
+ if (PyObject_AsWriteBuffer(buf, (void *)&data, &ts)==-1) {
+ write = 0;
+ PyErr_Clear();
+ if (PyObject_AsReadBuffer(buf, (void *)&data, &ts)==-1) {
+ Py_DECREF(buf);
+ Py_DECREF(type);
+ return NULL;
+ }
+ }
+
+ if ((offset < 0) || (offset >= ts)) {
+ PyErr_Format(PyExc_ValueError,
+ "offset must be positive and smaller than %"
+ INTP_FMT, (intp)ts);
+ }
+
+ data += offset;
+ s = (intp)ts - offset;
+ n = (intp)count;
+ itemsize = type->elsize;
+
+ if (n < 0 ) {
+ if (s % itemsize != 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "buffer size must be a multiple"\
+ " of element size");
+ Py_DECREF(buf);
+ Py_DECREF(type);
+ return NULL;
+ }
+ n = s/itemsize;
+ } else {
+ if (s < n*itemsize) {
+ PyErr_SetString(PyExc_ValueError,
+ "buffer is smaller than requested"\
+ " size");
+ Py_DECREF(buf);
+ Py_DECREF(type);
+ return NULL;
+ }
+ }
+
+ if ((ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
+ type,
+ 1, &n,
+ NULL, data,
+ DEFAULT,
+ NULL)) == NULL) {
+ Py_DECREF(buf);
+ return NULL;
+ }
+
+ if (!write) ret->flags &= ~WRITEABLE;
+
+ /* Store a reference for decref on deallocation */
+ ret->base = buf;
+ PyArray_UpdateFlags(ret, ALIGNED);
+ return (PyObject *)ret;
}
static PyObject *
array_frombuffer(PyObject *ignored, PyObject *args, PyObject *keywds)
{
- PyObject *obj=NULL;
- Py_ssize_t nin=-1, offset=0;
- static char *kwlist[] = {"buffer", "dtype", "count", "offset", NULL};
- PyArray_Descr *type=NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|O&"
- NPY_SSIZE_T_PYFMT
- NPY_SSIZE_T_PYFMT, kwlist,
- &obj,
- PyArray_DescrConverter, &type,
- &nin, &offset)) {
- return NULL;
- }
- if (type==NULL)
- type = PyArray_DescrFromType(PyArray_DEFAULT);
+ PyObject *obj=NULL;
+ Py_ssize_t nin=-1, offset=0;
+ static char *kwlist[] = {"buffer", "dtype", "count", "offset", NULL};
+ PyArray_Descr *type=NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|O&"
+ NPY_SSIZE_T_PYFMT
+ NPY_SSIZE_T_PYFMT, kwlist,
+ &obj,
+ PyArray_DescrConverter, &type,
+ &nin, &offset)) {
+ return NULL;
+ }
+ if (type==NULL)
+ type = PyArray_DescrFromType(PyArray_DEFAULT);
- return PyArray_FromBuffer(obj, type, (intp)nin, (intp)offset);
+ return PyArray_FromBuffer(obj, type, (intp)nin, (intp)offset);
}
static PyObject *
array_concatenate(PyObject *dummy, PyObject *args, PyObject *kwds)
{
- PyObject *a0;
- int axis=0;
- static char *kwlist[] = {"seq", "axis", NULL};
+ PyObject *a0;
+ int axis=0;
+ static char *kwlist[] = {"seq", "axis", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist,
- &a0,
- PyArray_AxisConverter, &axis))
- return NULL;
- return PyArray_Concatenate(a0, axis);
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist,
+ &a0,
+ PyArray_AxisConverter, &axis))
+ return NULL;
+ return PyArray_Concatenate(a0, axis);
}
static PyObject *array_innerproduct(PyObject *dummy, PyObject *args) {
- PyObject *b0, *a0;
+ PyObject *b0, *a0;
- if (!PyArg_ParseTuple(args, "OO", &a0, &b0)) return NULL;
+ if (!PyArg_ParseTuple(args, "OO", &a0, &b0)) return NULL;
- return _ARET(PyArray_InnerProduct(a0, b0));
+ return _ARET(PyArray_InnerProduct(a0, b0));
}
static PyObject *array_matrixproduct(PyObject *dummy, PyObject *args) {
- PyObject *v, *a;
+ PyObject *v, *a;
- if (!PyArg_ParseTuple(args, "OO", &a, &v)) return NULL;
+ if (!PyArg_ParseTuple(args, "OO", &a, &v)) return NULL;
- return _ARET(PyArray_MatrixProduct(a, v));
+ return _ARET(PyArray_MatrixProduct(a, v));
}
static PyObject *array_fastCopyAndTranspose(PyObject *dummy, PyObject *args) {
- PyObject *a0;
+ PyObject *a0;
- if (!PyArg_ParseTuple(args, "O", &a0)) return NULL;
+ if (!PyArg_ParseTuple(args, "O", &a0)) return NULL;
- return _ARET(PyArray_CopyAndTranspose(a0));
+ return _ARET(PyArray_CopyAndTranspose(a0));
}
static PyObject *array_correlate(PyObject *dummy, PyObject *args, PyObject *kwds) {
- PyObject *shape, *a0;
- int mode=0;
- static char *kwlist[] = {"a", "v", "mode", NULL};
+ PyObject *shape, *a0;
+ int mode=0;
+ static char *kwlist[] = {"a", "v", "mode", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
- &a0, &shape, &mode)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
+ &a0, &shape, &mode)) return NULL;
- return PyArray_Correlate(a0, shape, mode);
+ return PyArray_Correlate(a0, shape, mode);
}
/*MULTIARRAY_API
- Arange,
+ Arange,
*/
static PyObject *
PyArray_Arange(double start, double stop, double step, int type_num)
{
- intp length;
- PyObject *range;
- PyArray_ArrFuncs *funcs;
- PyObject *obj;
- int ret;
+ intp length;
+ PyObject *range;
+ PyArray_ArrFuncs *funcs;
+ PyObject *obj;
+ int ret;
- length = (intp ) ceil((stop - start)/step);
+ length = (intp ) ceil((stop - start)/step);
- if (length <= 0) {
- length = 0;
- return PyArray_New(&PyArray_Type, 1, &length, type_num,
- NULL, NULL, 0, 0, NULL);
- }
+ if (length <= 0) {
+ length = 0;
+ return PyArray_New(&PyArray_Type, 1, &length, type_num,
+ NULL, NULL, 0, 0, NULL);
+ }
- range = PyArray_New(&PyArray_Type, 1, &length, type_num,
- NULL, NULL, 0, 0, NULL);
- if (range == NULL) return NULL;
+ range = PyArray_New(&PyArray_Type, 1, &length, type_num,
+ NULL, NULL, 0, 0, NULL);
+ if (range == NULL) return NULL;
- funcs = PyArray_DESCR(range)->f;
+ funcs = PyArray_DESCR(range)->f;
- /* place start in the buffer and the next value in the second position */
- /* if length > 2, then call the inner loop, otherwise stop */
+ /* place start in the buffer and the next value in the second position */
+ /* if length > 2, then call the inner loop, otherwise stop */
- obj = PyFloat_FromDouble(start);
- ret = funcs->setitem(obj, PyArray_DATA(range), (PyArrayObject *)range);
- Py_DECREF(obj);
- if (ret < 0) goto fail;
- if (length == 1) return range;
+ obj = PyFloat_FromDouble(start);
+ ret = funcs->setitem(obj, PyArray_DATA(range), (PyArrayObject *)range);
+ Py_DECREF(obj);
+ if (ret < 0) goto fail;
+ if (length == 1) return range;
- obj = PyFloat_FromDouble(start + step);
- ret = funcs->setitem(obj, PyArray_BYTES(range)+PyArray_ITEMSIZE(range),
- (PyArrayObject *)range);
- Py_DECREF(obj);
- if (ret < 0) goto fail;
- if (length == 2) return range;
+ obj = PyFloat_FromDouble(start + step);
+ ret = funcs->setitem(obj, PyArray_BYTES(range)+PyArray_ITEMSIZE(range),
+ (PyArrayObject *)range);
+ Py_DECREF(obj);
+ if (ret < 0) goto fail;
+ if (length == 2) return range;
- if (!funcs->fill) {
- PyErr_SetString(PyExc_ValueError, "no fill-function for data-type.");
- Py_DECREF(range);
- return NULL;
- }
- funcs->fill(PyArray_DATA(range), length, (PyArrayObject *)range);
- if (PyErr_Occurred()) goto fail;
+ if (!funcs->fill) {
+ PyErr_SetString(PyExc_ValueError, "no fill-function for data-type.");
+ Py_DECREF(range);
+ return NULL;
+ }
+ funcs->fill(PyArray_DATA(range), length, (PyArrayObject *)range);
+ if (PyErr_Occurred()) goto fail;
- return range;
+ return range;
fail:
- Py_DECREF(range);
- return NULL;
+ Py_DECREF(range);
+ return NULL;
}
/* the formula is
@@ -6651,336 +6651,336 @@ PyArray_Arange(double start, double stop, double step, int type_num)
static intp
_calc_length(PyObject *start, PyObject *stop, PyObject *step, PyObject **next, int cmplx)
{
- intp len;
- PyObject *val;
- double value;
-
- *next = PyNumber_Subtract(stop, start);
- if (!(*next)) {
- if (PyTuple_Check(stop)) {
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "arange: scalar arguments expected "\
- "instead of a tuple.");
- }
- return -1;
+ intp len;
+ PyObject *val;
+ double value;
+
+ *next = PyNumber_Subtract(stop, start);
+ if (!(*next)) {
+ if (PyTuple_Check(stop)) {
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "arange: scalar arguments expected "\
+ "instead of a tuple.");
}
- val = PyNumber_TrueDivide(*next, step);
- Py_DECREF(*next); *next=NULL;
- if (!val) return -1;
- if (cmplx && PyComplex_Check(val)) {
- value = PyComplex_RealAsDouble(val);
- if (error_converting(value)) {Py_DECREF(val); return -1;}
- len = (intp) ceil(value);
- value = PyComplex_ImagAsDouble(val);
- Py_DECREF(val);
- if (error_converting(value)) return -1;
- len = MIN(len, (intp) ceil(value));
- }
- else {
- value = PyFloat_AsDouble(val);
- Py_DECREF(val);
- if (error_converting(value)) return -1;
- len = (intp) ceil(value);
- }
-
- if (len > 0) {
- *next = PyNumber_Add(start, step);
- if (!next) return -1;
- }
- return len;
+ return -1;
+ }
+ val = PyNumber_TrueDivide(*next, step);
+ Py_DECREF(*next); *next=NULL;
+ if (!val) return -1;
+ if (cmplx && PyComplex_Check(val)) {
+ value = PyComplex_RealAsDouble(val);
+ if (error_converting(value)) {Py_DECREF(val); return -1;}
+ len = (intp) ceil(value);
+ value = PyComplex_ImagAsDouble(val);
+ Py_DECREF(val);
+ if (error_converting(value)) return -1;
+ len = MIN(len, (intp) ceil(value));
+ }
+ else {
+ value = PyFloat_AsDouble(val);
+ Py_DECREF(val);
+ if (error_converting(value)) return -1;
+ len = (intp) ceil(value);
+ }
+
+ if (len > 0) {
+ *next = PyNumber_Add(start, step);
+ if (!next) return -1;
+ }
+ return len;
}
/* this doesn't change the references */
/*MULTIARRAY_API
- ArangeObj,
+ ArangeObj,
*/
static PyObject *
PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype)
{
- PyObject *range;
- PyArray_ArrFuncs *funcs;
- PyObject *next;
- intp length;
- PyArray_Descr *native=NULL;
- int swap;
-
- if (!dtype) {
- PyArray_Descr *deftype;
- PyArray_Descr *newtype;
- /* intentionally made to be PyArray_LONG default */
- deftype = PyArray_DescrFromType(PyArray_LONG);
- newtype = PyArray_DescrFromObject(start, deftype);
- Py_DECREF(deftype);
- deftype = newtype;
- if (stop && stop != Py_None) {
- newtype = PyArray_DescrFromObject(stop, deftype);
- Py_DECREF(deftype);
- deftype = newtype;
- }
- if (step && step != Py_None) {
- newtype = PyArray_DescrFromObject(step, deftype);
- Py_DECREF(deftype);
- deftype = newtype;
- }
- dtype = deftype;
- }
- else Py_INCREF(dtype);
-
- if (!step || step == Py_None) {
- step = PyInt_FromLong(1);
- }
- else Py_XINCREF(step);
-
- if (!stop || stop == Py_None) {
- stop = start;
- start = PyInt_FromLong(0);
- }
- else Py_INCREF(start);
-
- /* calculate the length and next = start + step*/
- length = _calc_length(start, stop, step, &next,
- PyTypeNum_ISCOMPLEX(dtype->type_num));
-
- if (PyErr_Occurred()) {Py_DECREF(dtype); goto fail;}
- if (length <= 0) {
- length = 0;
- range = PyArray_SimpleNewFromDescr(1, &length, dtype);
- Py_DECREF(step); Py_DECREF(start); return range;
- }
-
- /* If dtype is not in native byte-order then get native-byte
- order version. And then swap on the way out.
- */
- if (!PyArray_ISNBO(dtype->byteorder)) {
- native = PyArray_DescrNewByteorder(dtype, PyArray_NATBYTE);
- swap = 1;
- }
- else {
- native = dtype;
- swap = 0;
- }
-
- range = PyArray_SimpleNewFromDescr(1, &length, native);
- if (range == NULL) goto fail;
-
- funcs = PyArray_DESCR(range)->f;
-
- /* place start in the buffer and the next value in the second position */
- /* if length > 2, then call the inner loop, otherwise stop */
-
- if (funcs->setitem(start, PyArray_DATA(range), (PyArrayObject *)range) < 0)
- goto fail;
- if (length == 1) goto finish;
- if (funcs->setitem(next, PyArray_BYTES(range)+PyArray_ITEMSIZE(range),
- (PyArrayObject *)range) < 0) goto fail;
- if (length == 2) goto finish;
-
- if (!funcs->fill) {
- PyErr_SetString(PyExc_ValueError, "no fill-function for data-type.");
- Py_DECREF(range);
- goto fail;
- }
- funcs->fill(PyArray_DATA(range), length, (PyArrayObject *)range);
- if (PyErr_Occurred()) goto fail;
-
- if (swap) {
- PyObject *new;
- new = PyArray_Byteswap((PyArrayObject *)range, 1);
- Py_DECREF(new);
- Py_DECREF(PyArray_DESCR(range));
- PyArray_DESCR(range) = dtype; /* steals the reference */
- }
+ PyObject *range;
+ PyArray_ArrFuncs *funcs;
+ PyObject *next;
+ intp length;
+ PyArray_Descr *native=NULL;
+ int swap;
+
+ if (!dtype) {
+ PyArray_Descr *deftype;
+ PyArray_Descr *newtype;
+ /* intentionally made to be PyArray_LONG default */
+ deftype = PyArray_DescrFromType(PyArray_LONG);
+ newtype = PyArray_DescrFromObject(start, deftype);
+ Py_DECREF(deftype);
+ deftype = newtype;
+ if (stop && stop != Py_None) {
+ newtype = PyArray_DescrFromObject(stop, deftype);
+ Py_DECREF(deftype);
+ deftype = newtype;
+ }
+ if (step && step != Py_None) {
+ newtype = PyArray_DescrFromObject(step, deftype);
+ Py_DECREF(deftype);
+ deftype = newtype;
+ }
+ dtype = deftype;
+ }
+ else Py_INCREF(dtype);
+
+ if (!step || step == Py_None) {
+ step = PyInt_FromLong(1);
+ }
+ else Py_XINCREF(step);
+
+ if (!stop || stop == Py_None) {
+ stop = start;
+ start = PyInt_FromLong(0);
+ }
+ else Py_INCREF(start);
+
+ /* calculate the length and next = start + step*/
+ length = _calc_length(start, stop, step, &next,
+ PyTypeNum_ISCOMPLEX(dtype->type_num));
+
+ if (PyErr_Occurred()) {Py_DECREF(dtype); goto fail;}
+ if (length <= 0) {
+ length = 0;
+ range = PyArray_SimpleNewFromDescr(1, &length, dtype);
+ Py_DECREF(step); Py_DECREF(start); return range;
+ }
+
+ /* If dtype is not in native byte-order then get native-byte
+ order version. And then swap on the way out.
+ */
+ if (!PyArray_ISNBO(dtype->byteorder)) {
+ native = PyArray_DescrNewByteorder(dtype, PyArray_NATBYTE);
+ swap = 1;
+ }
+ else {
+ native = dtype;
+ swap = 0;
+ }
+
+ range = PyArray_SimpleNewFromDescr(1, &length, native);
+ if (range == NULL) goto fail;
+
+ funcs = PyArray_DESCR(range)->f;
+
+ /* place start in the buffer and the next value in the second position */
+ /* if length > 2, then call the inner loop, otherwise stop */
+
+ if (funcs->setitem(start, PyArray_DATA(range), (PyArrayObject *)range) < 0)
+ goto fail;
+ if (length == 1) goto finish;
+ if (funcs->setitem(next, PyArray_BYTES(range)+PyArray_ITEMSIZE(range),
+ (PyArrayObject *)range) < 0) goto fail;
+ if (length == 2) goto finish;
+
+ if (!funcs->fill) {
+ PyErr_SetString(PyExc_ValueError, "no fill-function for data-type.");
+ Py_DECREF(range);
+ goto fail;
+ }
+ funcs->fill(PyArray_DATA(range), length, (PyArrayObject *)range);
+ if (PyErr_Occurred()) goto fail;
+
+ if (swap) {
+ PyObject *new;
+ new = PyArray_Byteswap((PyArrayObject *)range, 1);
+ Py_DECREF(new);
+ Py_DECREF(PyArray_DESCR(range));
+ PyArray_DESCR(range) = dtype; /* steals the reference */
+ }
finish:
- Py_DECREF(start);
- Py_DECREF(step);
- Py_DECREF(next);
- return range;
+ Py_DECREF(start);
+ Py_DECREF(step);
+ Py_DECREF(next);
+ return range;
fail:
- Py_DECREF(start);
- Py_DECREF(step);
- Py_XDECREF(next);
- return NULL;
+ Py_DECREF(start);
+ Py_DECREF(step);
+ Py_XDECREF(next);
+ return NULL;
}
static PyObject *
array_arange(PyObject *ignored, PyObject *args, PyObject *kws) {
- PyObject *o_start=NULL, *o_stop=NULL, *o_step=NULL;
- static char *kwd[]= {"start", "stop", "step", "dtype", NULL};
- PyArray_Descr *typecode=NULL;
-
- if(!PyArg_ParseTupleAndKeywords(args, kws, "O|OOO&", kwd, &o_start,
- &o_stop, &o_step,
- PyArray_DescrConverter2,
- &typecode))
- return NULL;
+ PyObject *o_start=NULL, *o_stop=NULL, *o_step=NULL;
+ static char *kwd[]= {"start", "stop", "step", "dtype", NULL};
+ PyArray_Descr *typecode=NULL;
+
+ if(!PyArg_ParseTupleAndKeywords(args, kws, "O|OOO&", kwd, &o_start,
+ &o_stop, &o_step,
+ PyArray_DescrConverter2,
+ &typecode))
+ return NULL;
- return PyArray_ArangeObj(o_start, o_stop, o_step, typecode);
+ return PyArray_ArangeObj(o_start, o_stop, o_step, typecode);
}
/*
-Included at the very first so not auto-grabbed and thus not
-labeled.
+ Included at the very first so not auto-grabbed and thus not
+ labeled.
*/
static unsigned int
PyArray_GetNDArrayCVersion(void)
{
- return (unsigned int)NPY_VERSION;
+ return (unsigned int)NPY_VERSION;
}
static PyObject *
array__get_ndarray_c_version(PyObject *dummy, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {NULL};
- if(!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist )) return NULL;
+ static char *kwlist[] = {NULL};
+ if(!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist )) return NULL;
- return PyInt_FromLong( (long) PyArray_GetNDArrayCVersion() );
+ return PyInt_FromLong( (long) PyArray_GetNDArrayCVersion() );
}
static PyObject *
array__reconstruct(PyObject *dummy, PyObject *args)
{
- PyObject *ret;
- PyTypeObject *subtype;
- PyArray_Dims shape = {NULL, 0};
- PyArray_Descr *dtype=NULL;
- if (!PyArg_ParseTuple(args, "O!O&O&", &PyType_Type, &subtype,
- PyArray_IntpConverter, &shape,
- PyArray_DescrConverter, &dtype))
- goto fail;
-
- if (!PyType_IsSubtype(subtype, &PyArray_Type)) {
- PyErr_SetString(PyExc_TypeError,
- "_reconstruct: First argument must be " \
- "a sub-type of ndarray");
- goto fail;
- }
-
- ret = PyArray_NewFromDescr(subtype, dtype,
- (int)shape.len, shape.ptr,
- NULL, NULL, 0, NULL);
- if (shape.ptr) PyDimMem_FREE(shape.ptr);
- return ret;
+ PyObject *ret;
+ PyTypeObject *subtype;
+ PyArray_Dims shape = {NULL, 0};
+ PyArray_Descr *dtype=NULL;
+ if (!PyArg_ParseTuple(args, "O!O&O&", &PyType_Type, &subtype,
+ PyArray_IntpConverter, &shape,
+ PyArray_DescrConverter, &dtype))
+ goto fail;
+
+ if (!PyType_IsSubtype(subtype, &PyArray_Type)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_reconstruct: First argument must be " \
+ "a sub-type of ndarray");
+ goto fail;
+ }
+
+ ret = PyArray_NewFromDescr(subtype, dtype,
+ (int)shape.len, shape.ptr,
+ NULL, NULL, 0, NULL);
+ if (shape.ptr) PyDimMem_FREE(shape.ptr);
+ return ret;
fail:
- Py_XDECREF(dtype);
- if (shape.ptr) PyDimMem_FREE(shape.ptr);
- return NULL;
+ Py_XDECREF(dtype);
+ if (shape.ptr) PyDimMem_FREE(shape.ptr);
+ return NULL;
}
static PyObject *
array_set_string_function(PyObject *dummy, PyObject *args, PyObject *kwds)
{
- PyObject *op=NULL;
- int repr=1;
- static char *kwlist[] = {"f", "repr", NULL};
+ PyObject *op=NULL;
+ int repr=1;
+ static char *kwlist[] = {"f", "repr", NULL};
- if(!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi", kwlist,
- &op, &repr)) return NULL;
+ if(!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi", kwlist,
+ &op, &repr)) return NULL;
- /* reset the array_repr function to built-in */
- if (op == Py_None) op = NULL;
- if (op != NULL && !PyCallable_Check(op)) {
- PyErr_SetString(PyExc_TypeError,
- "Argument must be callable.");
- return NULL;
- }
- PyArray_SetStringFunction(op, repr);
- Py_INCREF(Py_None);
- return Py_None;
+ /* reset the array_repr function to built-in */
+ if (op == Py_None) op = NULL;
+ if (op != NULL && !PyCallable_Check(op)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Argument must be callable.");
+ return NULL;
+ }
+ PyArray_SetStringFunction(op, repr);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_set_ops_function(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *oldops=NULL;
+ PyObject *oldops=NULL;
- if ((oldops = PyArray_GetNumericOps())==NULL) return NULL;
+ if ((oldops = PyArray_GetNumericOps())==NULL) return NULL;
- /* Should probably ensure that objects are at least callable */
- /* Leave this to the caller for now --- error will be raised
- later when use is attempted
- */
- if (kwds && PyArray_SetNumericOps(kwds) == -1) {
- Py_DECREF(oldops);
- PyErr_SetString(PyExc_ValueError,
- "one or more objects not callable");
- return NULL;
- }
- return oldops;
+ /* Should probably ensure that objects are at least callable */
+ /* Leave this to the caller for now --- error will be raised
+ later when use is attempted
+ */
+ if (kwds && PyArray_SetNumericOps(kwds) == -1) {
+ Py_DECREF(oldops);
+ PyErr_SetString(PyExc_ValueError,
+ "one or more objects not callable");
+ return NULL;
+ }
+ return oldops;
}
/*MULTIARRAY_API
- Where
+ Where
*/
static PyObject *
PyArray_Where(PyObject *condition, PyObject *x, PyObject *y)
{
- PyArrayObject *arr;
- PyObject *tup=NULL, *obj=NULL;
- PyObject *ret=NULL, *zero=NULL;
+ PyArrayObject *arr;
+ PyObject *tup=NULL, *obj=NULL;
+ PyObject *ret=NULL, *zero=NULL;
- arr = (PyArrayObject *)PyArray_FromAny(condition, NULL, 0, 0, 0, NULL);
- if (arr == NULL) return NULL;
+ arr = (PyArrayObject *)PyArray_FromAny(condition, NULL, 0, 0, 0, NULL);
+ if (arr == NULL) return NULL;
- if ((x==NULL) && (y==NULL)) {
- ret = PyArray_Nonzero(arr);
- Py_DECREF(arr);
- return ret;
- }
+ if ((x==NULL) && (y==NULL)) {
+ ret = PyArray_Nonzero(arr);
+ Py_DECREF(arr);
+ return ret;
+ }
- if ((x==NULL) || (y==NULL)) {
- Py_DECREF(arr);
- PyErr_SetString(PyExc_ValueError, "either both or neither "
- "of x and y should be given");
- return NULL;
- }
+ if ((x==NULL) || (y==NULL)) {
+ Py_DECREF(arr);
+ PyErr_SetString(PyExc_ValueError, "either both or neither "
+ "of x and y should be given");
+ return NULL;
+ }
- zero = PyInt_FromLong((long) 0);
+ zero = PyInt_FromLong((long) 0);
- obj = PyArray_EnsureAnyArray(PyArray_GenericBinaryFunction(arr, zero,
- n_ops.not_equal));
- Py_DECREF(zero);
- Py_DECREF(arr);
- if (obj == NULL) return NULL;
+ obj = PyArray_EnsureAnyArray(PyArray_GenericBinaryFunction(arr, zero,
+ n_ops.not_equal));
+ Py_DECREF(zero);
+ Py_DECREF(arr);
+ if (obj == NULL) return NULL;
- tup = Py_BuildValue("(OO)", y, x);
- if (tup == NULL) {Py_DECREF(obj); return NULL;}
+ tup = Py_BuildValue("(OO)", y, x);
+ if (tup == NULL) {Py_DECREF(obj); return NULL;}
- ret = PyArray_Choose((PyAO *)obj, tup, NULL, NPY_RAISE);
+ ret = PyArray_Choose((PyAO *)obj, tup, NULL, NPY_RAISE);
- Py_DECREF(obj);
- Py_DECREF(tup);
- return ret;
+ Py_DECREF(obj);
+ Py_DECREF(tup);
+ return ret;
}
static PyObject *
array_where(PyObject *ignored, PyObject *args)
{
- PyObject *obj=NULL, *x=NULL, *y=NULL;
+ PyObject *obj=NULL, *x=NULL, *y=NULL;
- if (!PyArg_ParseTuple(args, "O|OO", &obj, &x, &y)) return NULL;
+ if (!PyArg_ParseTuple(args, "O|OO", &obj, &x, &y)) return NULL;
- return PyArray_Where(obj, x, y);
+ return PyArray_Where(obj, x, y);
}
static PyObject *
array_lexsort(PyObject *ignored, PyObject *args, PyObject *kwds)
{
- int axis=-1;
- PyObject *obj;
- static char *kwlist[] = {"keys", "axis", NULL};
+ int axis=-1;
+ PyObject *obj;
+ static char *kwlist[] = {"keys", "axis", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i", kwlist,
- &obj, &axis)) return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i", kwlist,
+ &obj, &axis)) return NULL;
- return _ARET(PyArray_LexSort(obj, axis));
+ return _ARET(PyArray_LexSort(obj, axis));
}
#undef _ARET
@@ -6988,60 +6988,60 @@ array_lexsort(PyObject *ignored, PyObject *args, PyObject *kwds)
static PyObject *
array_can_cast_safely(PyObject *dummy, PyObject *args, PyObject *kwds)
{
- PyArray_Descr *d1=NULL;
- PyArray_Descr *d2=NULL;
- Bool ret;
- PyObject *retobj;
- static char *kwlist[] = {"from", "to", NULL};
-
- if(!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&", kwlist,
- PyArray_DescrConverter, &d1,
- PyArray_DescrConverter, &d2))
- return NULL;
- if (d1 == NULL || d2 == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "did not understand one of the types; " \
- "'None' not accepted");
- return NULL;
- }
-
- ret = PyArray_CanCastTo(d1, d2);
- retobj = (ret ? Py_True : Py_False);
- Py_INCREF(retobj);
- return retobj;
+ PyArray_Descr *d1=NULL;
+ PyArray_Descr *d2=NULL;
+ Bool ret;
+ PyObject *retobj;
+ static char *kwlist[] = {"from", "to", NULL};
+
+ if(!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&", kwlist,
+ PyArray_DescrConverter, &d1,
+ PyArray_DescrConverter, &d2))
+ return NULL;
+ if (d1 == NULL || d2 == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "did not understand one of the types; " \
+ "'None' not accepted");
+ return NULL;
+ }
+
+ ret = PyArray_CanCastTo(d1, d2);
+ retobj = (ret ? Py_True : Py_False);
+ Py_INCREF(retobj);
+ return retobj;
}
static PyObject *
new_buffer(PyObject *dummy, PyObject *args)
{
- int size;
+ int size;
- if(!PyArg_ParseTuple(args, "i", &size))
- return NULL;
+ if(!PyArg_ParseTuple(args, "i", &size))
+ return NULL;
- return PyBuffer_New(size);
+ return PyBuffer_New(size);
}
static PyObject *
buffer_buffer(PyObject *dummy, PyObject *args, PyObject *kwds)
{
- PyObject *obj;
- Py_ssize_t offset=0, size=Py_END_OF_BUFFER, n;
- void *unused;
- static char *kwlist[] = {"object", "offset", "size", NULL};
+ PyObject *obj;
+ Py_ssize_t offset=0, size=Py_END_OF_BUFFER, n;
+ void *unused;
+ static char *kwlist[] = {"object", "offset", "size", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|" NPY_SSIZE_T_PYFMT \
- NPY_SSIZE_T_PYFMT, kwlist,
- &obj, &offset, &size))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|" NPY_SSIZE_T_PYFMT \
+ NPY_SSIZE_T_PYFMT, kwlist,
+ &obj, &offset, &size))
+ return NULL;
- if (PyObject_AsWriteBuffer(obj, &unused, &n) < 0) {
- PyErr_Clear();
- return PyBuffer_FromObject(obj, offset, size);
- }
- else
- return PyBuffer_FromReadWriteObject(obj, offset, size);
+ if (PyObject_AsWriteBuffer(obj, &unused, &n) < 0) {
+ PyErr_Clear();
+ return PyBuffer_FromObject(obj, offset, size);
+ }
+ else
+ return PyBuffer_FromReadWriteObject(obj, offset, size);
}
#ifndef _MSC_VER
@@ -7051,76 +7051,76 @@ jmp_buf _NPY_SIGSEGV_BUF;
static void
_SigSegv_Handler(int signum)
{
- longjmp(_NPY_SIGSEGV_BUF, signum);
+ longjmp(_NPY_SIGSEGV_BUF, signum);
}
#endif
-#define _test_code() { \
- test = *((char*)memptr); \
- if (!ro) { \
- *((char *)memptr) = '\0'; \
- *((char *)memptr) = test; \
- } \
- test = *((char*)memptr+size-1); \
- if (!ro) { \
- *((char *)memptr+size-1) = '\0'; \
- *((char *)memptr+size-1) = test; \
- } \
- }
+#define _test_code() { \
+ test = *((char*)memptr); \
+ if (!ro) { \
+ *((char *)memptr) = '\0'; \
+ *((char *)memptr) = test; \
+ } \
+ test = *((char*)memptr+size-1); \
+ if (!ro) { \
+ *((char *)memptr+size-1) = '\0'; \
+ *((char *)memptr+size-1) = test; \
+ } \
+ }
static PyObject *
as_buffer(PyObject *dummy, PyObject *args, PyObject *kwds)
{
- PyObject *mem;
- Py_ssize_t size;
- Bool ro=FALSE, check=TRUE;
- void *memptr;
- static char *kwlist[] = {"mem", "size", "readonly", "check", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O" \
- NPY_SSIZE_T_PYFMT "|O&O&", kwlist,
- &mem, &size, PyArray_BoolConverter,
- &ro, PyArray_BoolConverter,
- &check)) return NULL;
- memptr = PyLong_AsVoidPtr(mem);
- if (memptr == NULL) return NULL;
-
- if (check) {
- /* Try to dereference the start and end of the memory region */
- /* Catch segfault and report error if it occurs */
- char test;
- int err=0;
+ PyObject *mem;
+ Py_ssize_t size;
+ Bool ro=FALSE, check=TRUE;
+ void *memptr;
+ static char *kwlist[] = {"mem", "size", "readonly", "check", NULL};
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O" \
+ NPY_SSIZE_T_PYFMT "|O&O&", kwlist,
+ &mem, &size, PyArray_BoolConverter,
+ &ro, PyArray_BoolConverter,
+ &check)) return NULL;
+ memptr = PyLong_AsVoidPtr(mem);
+ if (memptr == NULL) return NULL;
+
+ if (check) {
+ /* Try to dereference the start and end of the memory region */
+ /* Catch segfault and report error if it occurs */
+ char test;
+ int err=0;
#ifdef _MSC_VER
- __try {
- _test_code();
- }
- __except(1) {
- err = 1;
- }
+ __try {
+ _test_code();
+ }
+ __except(1) {
+ err = 1;
+ }
#else
- PyOS_sighandler_t _npy_sig_save;
- _npy_sig_save = PyOS_setsig(SIGSEGV, _SigSegv_Handler);
+ PyOS_sighandler_t _npy_sig_save;
+ _npy_sig_save = PyOS_setsig(SIGSEGV, _SigSegv_Handler);
- if (setjmp(_NPY_SIGSEGV_BUF) == 0) {
- _test_code();
- }
- else {
- err = 1;
- }
- PyOS_setsig(SIGSEGV, _npy_sig_save);
+ if (setjmp(_NPY_SIGSEGV_BUF) == 0) {
+ _test_code();
+ }
+ else {
+ err = 1;
+ }
+ PyOS_setsig(SIGSEGV, _npy_sig_save);
#endif
- if (err) {
- PyErr_SetString(PyExc_ValueError,
- "cannot use memory location as " \
- "a buffer.");
- return NULL;
- }
+ if (err) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot use memory location as " \
+ "a buffer.");
+ return NULL;
}
+ }
- if (ro) {
- return PyBuffer_FromMemory(memptr, size);
- }
- return PyBuffer_FromReadWriteMemory(memptr, size);
+ if (ro) {
+ return PyBuffer_FromMemory(memptr, size);
+ }
+ return PyBuffer_FromReadWriteMemory(memptr, size);
}
#undef _test_code
@@ -7162,7 +7162,7 @@ compare_chararrays(PyObject *dummy, PyObject *args, PyObject *kwds)
Py_ssize_t strlen;
PyObject *res=NULL;
static char msg[] = \
- "comparision must be '==', '!=', '<', '>', '<=', '>='";
+ "comparision must be '==', '!=', '<', '>', '<=', '>='";
static char *kwlist[] = {"a1", "a2", "cmp", "rstrip", NULL};
@@ -7170,37 +7170,37 @@ compare_chararrays(PyObject *dummy, PyObject *args, PyObject *kwds)
&array, &other,
&cmp_str, &strlen,
PyArray_BoolConverter, &rstrip))
- return NULL;
+ return NULL;
if (strlen < 1 || strlen > 2) goto err;
if (strlen > 1) {
- if (cmp_str[1] != '=') goto err;
- if (cmp_str[0] == '=') cmp_op = Py_EQ;
- else if (cmp_str[0] == '!') cmp_op = Py_NE;
- else if (cmp_str[0] == '<') cmp_op = Py_LE;
- else if (cmp_str[0] == '>') cmp_op = Py_GE;
- else goto err;
+ if (cmp_str[1] != '=') goto err;
+ if (cmp_str[0] == '=') cmp_op = Py_EQ;
+ else if (cmp_str[0] == '!') cmp_op = Py_NE;
+ else if (cmp_str[0] == '<') cmp_op = Py_LE;
+ else if (cmp_str[0] == '>') cmp_op = Py_GE;
+ else goto err;
}
else {
- if (cmp_str[0] == '<') cmp_op = Py_LT;
- else if (cmp_str[0] == '>') cmp_op = Py_GT;
- else goto err;
+ if (cmp_str[0] == '<') cmp_op = Py_LT;
+ else if (cmp_str[0] == '>') cmp_op = Py_GT;
+ else goto err;
}
newarr = (PyArrayObject *)PyArray_FROM_O(array);
if (newarr == NULL) return NULL;
newoth = (PyArrayObject *)PyArray_FROM_O(other);
if (newoth == NULL) {
- Py_DECREF(newarr);
- return NULL;
+ Py_DECREF(newarr);
+ return NULL;
}
if (PyArray_ISSTRING(newarr) && PyArray_ISSTRING(newoth)) {
- res = _strings_richcompare(newarr, newoth, cmp_op, rstrip != 0);
+ res = _strings_richcompare(newarr, newoth, cmp_op, rstrip != 0);
}
else {
- PyErr_SetString(PyExc_TypeError,
- "comparison of non-string arrays");
+ PyErr_SetString(PyExc_TypeError,
+ "comparison of non-string arrays");
}
Py_DECREF(newarr);
@@ -7218,20 +7218,20 @@ compare_chararrays(PyObject *dummy, PyObject *args, PyObject *kwds)
SIGJMP_BUF _NPY_SIGINT_BUF;
/*MULTIARRAY_API
-*/
+ */
static void
_PyArray_SigintHandler(int signum)
{
- PyOS_setsig(signum, SIG_IGN);
- SIGLONGJMP(_NPY_SIGINT_BUF, signum);
+ PyOS_setsig(signum, SIG_IGN);
+ SIGLONGJMP(_NPY_SIGINT_BUF, signum);
}
/*MULTIARRAY_API
-*/
+ */
static void*
_PyArray_GetSigintBuf(void)
{
- return (void *)&_NPY_SIGINT_BUF;
+ return (void *)&_NPY_SIGINT_BUF;
}
#else
@@ -7239,13 +7239,13 @@ _PyArray_GetSigintBuf(void)
static void
_PyArray_SigintHandler(int signum)
{
- return;
+ return;
}
static void*
_PyArray_GetSigintBuf(void)
{
- return NULL;
+ return NULL;
}
#endif
@@ -7254,95 +7254,95 @@ _PyArray_GetSigintBuf(void)
static PyObject *
test_interrupt(PyObject *self, PyObject *args)
{
- int kind=0;
- int a = 0;
+ int kind=0;
+ int a = 0;
- if (!PyArg_ParseTuple(args, "|i", &kind)) return NULL;
+ if (!PyArg_ParseTuple(args, "|i", &kind)) return NULL;
- if (kind) {
- Py_BEGIN_ALLOW_THREADS
- while (a>=0) {
- if ((a % 1000 == 0) &&
- PyOS_InterruptOccurred()) break;
- a+=1;
- }
- Py_END_ALLOW_THREADS
- }
- else {
+ if (kind) {
+ Py_BEGIN_ALLOW_THREADS
+ while (a>=0) {
+ if ((a % 1000 == 0) &&
+ PyOS_InterruptOccurred()) break;
+ a+=1;
+ }
+ Py_END_ALLOW_THREADS
+ }
+ else {
- NPY_SIGINT_ON
+ NPY_SIGINT_ON
- while(a>=0) {
- a += 1;
- }
+ while(a>=0) {
+ a += 1;
+ }
- NPY_SIGINT_OFF
- }
+ NPY_SIGINT_OFF
+ }
- return PyInt_FromLong(a);
+ return PyInt_FromLong(a);
}
static struct PyMethodDef array_module_methods[] = {
- {"_get_ndarray_c_version", (PyCFunction)array__get_ndarray_c_version,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"_reconstruct", (PyCFunction)array__reconstruct,
- METH_VARARGS, NULL},
- {"set_string_function", (PyCFunction)array_set_string_function,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"set_numeric_ops", (PyCFunction)array_set_ops_function,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"set_typeDict", (PyCFunction)array_set_typeDict,
- METH_VARARGS, NULL},
-
- {"array", (PyCFunction)_array_fromobject,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"arange", (PyCFunction)array_arange,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"zeros", (PyCFunction)array_zeros,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"empty", (PyCFunction)array_empty,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"scalar", (PyCFunction)array_scalar,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"where", (PyCFunction)array_where,
- METH_VARARGS, NULL},
- {"lexsort", (PyCFunction)array_lexsort,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"putmask", (PyCFunction)array_putmask,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"fromstring",(PyCFunction)array_fromstring,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"fromiter",(PyCFunction)array_fromiter,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"concatenate", (PyCFunction)array_concatenate,
- METH_VARARGS|METH_KEYWORDS, NULL},
- {"inner", (PyCFunction)array_innerproduct,
- METH_VARARGS, NULL},
- {"dot", (PyCFunction)array_matrixproduct,
- METH_VARARGS, NULL},
- {"_fastCopyAndTranspose", (PyCFunction)array_fastCopyAndTranspose,
- METH_VARARGS, NULL},
- {"correlate", (PyCFunction)array_correlate,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"frombuffer", (PyCFunction)array_frombuffer,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"fromfile", (PyCFunction)array_fromfile,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"can_cast", (PyCFunction)array_can_cast_safely,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"newbuffer", (PyCFunction)new_buffer,
- METH_VARARGS, NULL},
- {"getbuffer", (PyCFunction)buffer_buffer,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"int_asbuffer", (PyCFunction)as_buffer,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"format_longfloat", (PyCFunction)format_longfloat,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"compare_chararrays", (PyCFunction)compare_chararrays,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"test_interrupt", (PyCFunction)test_interrupt,
- METH_VARARGS, NULL},
- {NULL, NULL, 0} /* sentinel */
+ {"_get_ndarray_c_version", (PyCFunction)array__get_ndarray_c_version,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"_reconstruct", (PyCFunction)array__reconstruct,
+ METH_VARARGS, NULL},
+ {"set_string_function", (PyCFunction)array_set_string_function,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"set_numeric_ops", (PyCFunction)array_set_ops_function,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"set_typeDict", (PyCFunction)array_set_typeDict,
+ METH_VARARGS, NULL},
+
+ {"array", (PyCFunction)_array_fromobject,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"arange", (PyCFunction)array_arange,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"zeros", (PyCFunction)array_zeros,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"empty", (PyCFunction)array_empty,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"scalar", (PyCFunction)array_scalar,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"where", (PyCFunction)array_where,
+ METH_VARARGS, NULL},
+ {"lexsort", (PyCFunction)array_lexsort,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"putmask", (PyCFunction)array_putmask,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"fromstring",(PyCFunction)array_fromstring,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"fromiter",(PyCFunction)array_fromiter,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"concatenate", (PyCFunction)array_concatenate,
+ METH_VARARGS|METH_KEYWORDS, NULL},
+ {"inner", (PyCFunction)array_innerproduct,
+ METH_VARARGS, NULL},
+ {"dot", (PyCFunction)array_matrixproduct,
+ METH_VARARGS, NULL},
+ {"_fastCopyAndTranspose", (PyCFunction)array_fastCopyAndTranspose,
+ METH_VARARGS, NULL},
+ {"correlate", (PyCFunction)array_correlate,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"frombuffer", (PyCFunction)array_frombuffer,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"fromfile", (PyCFunction)array_fromfile,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"can_cast", (PyCFunction)array_can_cast_safely,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"newbuffer", (PyCFunction)new_buffer,
+ METH_VARARGS, NULL},
+ {"getbuffer", (PyCFunction)buffer_buffer,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"int_asbuffer", (PyCFunction)as_buffer,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"format_longfloat", (PyCFunction)format_longfloat,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"compare_chararrays", (PyCFunction)compare_chararrays,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"test_interrupt", (PyCFunction)test_interrupt,
+ METH_VARARGS, NULL},
+ {NULL, NULL, 0} /* sentinel */
};
#include "__multiarray_api.c"
@@ -7360,116 +7360,116 @@ static int
setup_scalartypes(PyObject *dict)
{
- initialize_numeric_types();
+ initialize_numeric_types();
- if (PyType_Ready(&PyBool_Type) < 0) return -1;
- if (PyType_Ready(&PyInt_Type) < 0) return -1;
- if (PyType_Ready(&PyFloat_Type) < 0) return -1;
- if (PyType_Ready(&PyComplex_Type) < 0) return -1;
- if (PyType_Ready(&PyString_Type) < 0) return -1;
- if (PyType_Ready(&PyUnicode_Type) < 0) return -1;
+ if (PyType_Ready(&PyBool_Type) < 0) return -1;
+ if (PyType_Ready(&PyInt_Type) < 0) return -1;
+ if (PyType_Ready(&PyFloat_Type) < 0) return -1;
+ if (PyType_Ready(&PyComplex_Type) < 0) return -1;
+ if (PyType_Ready(&PyString_Type) < 0) return -1;
+ if (PyType_Ready(&PyUnicode_Type) < 0) return -1;
#define SINGLE_INHERIT(child, parent) \
- Py##child##ArrType_Type.tp_base = &Py##parent##ArrType_Type; \
- if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \
- PyErr_Print(); \
- PyErr_Format(PyExc_SystemError, \
- "could not initialize Py%sArrType_Type", \
- #child); \
- return -1; \
- }
+ Py##child##ArrType_Type.tp_base = &Py##parent##ArrType_Type; \
+ if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \
+ PyErr_Print(); \
+ PyErr_Format(PyExc_SystemError, \
+ "could not initialize Py%sArrType_Type", \
+ #child); \
+ return -1; \
+ }
- if (PyType_Ready(&PyGenericArrType_Type) < 0)
- return -1;
+ if (PyType_Ready(&PyGenericArrType_Type) < 0)
+ return -1;
- SINGLE_INHERIT(Number, Generic);
- SINGLE_INHERIT(Integer, Number);
- SINGLE_INHERIT(Inexact, Number);
- SINGLE_INHERIT(SignedInteger, Integer);
- SINGLE_INHERIT(UnsignedInteger, Integer);
- SINGLE_INHERIT(Floating, Inexact);
- SINGLE_INHERIT(ComplexFloating, Inexact);
- SINGLE_INHERIT(Flexible, Generic);
- SINGLE_INHERIT(Character, Flexible);
+ SINGLE_INHERIT(Number, Generic);
+ SINGLE_INHERIT(Integer, Number);
+ SINGLE_INHERIT(Inexact, Number);
+ SINGLE_INHERIT(SignedInteger, Integer);
+ SINGLE_INHERIT(UnsignedInteger, Integer);
+ SINGLE_INHERIT(Floating, Inexact);
+ SINGLE_INHERIT(ComplexFloating, Inexact);
+ SINGLE_INHERIT(Flexible, Generic);
+ SINGLE_INHERIT(Character, Flexible);
#define DUAL_INHERIT(child, parent1, parent2) \
- Py##child##ArrType_Type.tp_base = &Py##parent2##ArrType_Type; \
- Py##child##ArrType_Type.tp_bases = \
- Py_BuildValue("(OO)", &Py##parent2##ArrType_Type, \
- &Py##parent1##_Type); \
- if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \
- PyErr_Print(); \
- PyErr_Format(PyExc_SystemError, \
- "could not initialize Py%sArrType_Type", \
- #child); \
- return -1; \
- }\
- Py##child##ArrType_Type.tp_hash = Py##parent1##_Type.tp_hash;
-
-#define DUAL_INHERIT2(child, parent1, parent2) \
- Py##child##ArrType_Type.tp_base = &Py##parent1##_Type; \
- Py##child##ArrType_Type.tp_bases = \
- Py_BuildValue("(OO)", &Py##parent1##_Type, \
- &Py##parent2##ArrType_Type); \
- Py##child##ArrType_Type.tp_richcompare = \
- Py##parent1##_Type.tp_richcompare; \
- Py##child##ArrType_Type.tp_compare = \
- Py##parent1##_Type.tp_compare; \
- Py##child##ArrType_Type.tp_hash = Py##parent1##_Type.tp_hash; \
- if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \
- PyErr_Print(); \
- PyErr_Format(PyExc_SystemError, \
- "could not initialize Py%sArrType_Type", \
- #child); \
- return -1; \
- }
-
- SINGLE_INHERIT(Bool, Generic);
- SINGLE_INHERIT(Byte, SignedInteger);
- SINGLE_INHERIT(Short, SignedInteger);
+ Py##child##ArrType_Type.tp_base = &Py##parent2##ArrType_Type; \
+ Py##child##ArrType_Type.tp_bases = \
+ Py_BuildValue("(OO)", &Py##parent2##ArrType_Type, \
+ &Py##parent1##_Type); \
+ if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \
+ PyErr_Print(); \
+ PyErr_Format(PyExc_SystemError, \
+ "could not initialize Py%sArrType_Type", \
+ #child); \
+ return -1; \
+ } \
+ Py##child##ArrType_Type.tp_hash = Py##parent1##_Type.tp_hash;
+
+#define DUAL_INHERIT2(child, parent1, parent2) \
+ Py##child##ArrType_Type.tp_base = &Py##parent1##_Type; \
+ Py##child##ArrType_Type.tp_bases = \
+ Py_BuildValue("(OO)", &Py##parent1##_Type, \
+ &Py##parent2##ArrType_Type); \
+ Py##child##ArrType_Type.tp_richcompare = \
+ Py##parent1##_Type.tp_richcompare; \
+ Py##child##ArrType_Type.tp_compare = \
+ Py##parent1##_Type.tp_compare; \
+ Py##child##ArrType_Type.tp_hash = Py##parent1##_Type.tp_hash; \
+ if (PyType_Ready(&Py##child##ArrType_Type) < 0) { \
+ PyErr_Print(); \
+ PyErr_Format(PyExc_SystemError, \
+ "could not initialize Py%sArrType_Type", \
+ #child); \
+ return -1; \
+ }
+
+ SINGLE_INHERIT(Bool, Generic);
+ SINGLE_INHERIT(Byte, SignedInteger);
+ SINGLE_INHERIT(Short, SignedInteger);
#if SIZEOF_INT == SIZEOF_LONG
- DUAL_INHERIT(Int, Int, SignedInteger);
+ DUAL_INHERIT(Int, Int, SignedInteger);
#else
- SINGLE_INHERIT(Int, SignedInteger);
+ SINGLE_INHERIT(Int, SignedInteger);
#endif
- DUAL_INHERIT(Long, Int, SignedInteger);
+ DUAL_INHERIT(Long, Int, SignedInteger);
#if SIZEOF_LONGLONG == SIZEOF_LONG
- DUAL_INHERIT(LongLong, Int, SignedInteger);
+ DUAL_INHERIT(LongLong, Int, SignedInteger);
#else
- SINGLE_INHERIT(LongLong, SignedInteger);
+ SINGLE_INHERIT(LongLong, SignedInteger);
#endif
- /* fprintf(stderr, "tp_free = %p, PyObject_Del = %p, int_tp_free = %p, base.tp_free = %p\n", PyIntArrType_Type.tp_free, PyObject_Del, PyInt_Type.tp_free, PySignedIntegerArrType_Type.tp_free);
- */
- SINGLE_INHERIT(UByte, UnsignedInteger);
- SINGLE_INHERIT(UShort, UnsignedInteger);
- SINGLE_INHERIT(UInt, UnsignedInteger);
- SINGLE_INHERIT(ULong, UnsignedInteger);
- SINGLE_INHERIT(ULongLong, UnsignedInteger);
+ /* fprintf(stderr, "tp_free = %p, PyObject_Del = %p, int_tp_free = %p, base.tp_free = %p\n", PyIntArrType_Type.tp_free, PyObject_Del, PyInt_Type.tp_free, PySignedIntegerArrType_Type.tp_free);
+ */
+ SINGLE_INHERIT(UByte, UnsignedInteger);
+ SINGLE_INHERIT(UShort, UnsignedInteger);
+ SINGLE_INHERIT(UInt, UnsignedInteger);
+ SINGLE_INHERIT(ULong, UnsignedInteger);
+ SINGLE_INHERIT(ULongLong, UnsignedInteger);
- SINGLE_INHERIT(Float, Floating);
- DUAL_INHERIT(Double, Float, Floating);
- SINGLE_INHERIT(LongDouble, Floating);
+ SINGLE_INHERIT(Float, Floating);
+ DUAL_INHERIT(Double, Float, Floating);
+ SINGLE_INHERIT(LongDouble, Floating);
- SINGLE_INHERIT(CFloat, ComplexFloating);
- DUAL_INHERIT(CDouble, Complex, ComplexFloating);
- SINGLE_INHERIT(CLongDouble, ComplexFloating);
+ SINGLE_INHERIT(CFloat, ComplexFloating);
+ DUAL_INHERIT(CDouble, Complex, ComplexFloating);
+ SINGLE_INHERIT(CLongDouble, ComplexFloating);
- DUAL_INHERIT2(String, String, Character);
- DUAL_INHERIT2(Unicode, Unicode, Character);
+ DUAL_INHERIT2(String, String, Character);
+ DUAL_INHERIT2(Unicode, Unicode, Character);
- SINGLE_INHERIT(Void, Flexible);
+ SINGLE_INHERIT(Void, Flexible);
- SINGLE_INHERIT(Object, Generic);
+ SINGLE_INHERIT(Object, Generic);
- return 0;
+ return 0;
#undef SINGLE_INHERIT
#undef DUAL_INHERIT
- /* Clean up string and unicode array types so they act more like
- strings -- get their tables from the standard types.
- */
+ /* Clean up string and unicode array types so they act more like
+ strings -- get their tables from the standard types.
+ */
}
/* place a flag dictionary in d */
@@ -7477,135 +7477,135 @@ setup_scalartypes(PyObject *dict)
static void
set_flaginfo(PyObject *d)
{
- PyObject *s;
- PyObject *newd;
+ PyObject *s;
+ PyObject *newd;
- newd = PyDict_New();
+ newd = PyDict_New();
-#define _addnew(val, one) \
- PyDict_SetItemString(newd, #val, s=PyInt_FromLong(val)); \
- Py_DECREF(s); \
- PyDict_SetItemString(newd, #one, s=PyInt_FromLong(val)); \
- Py_DECREF(s)
+#define _addnew(val, one) \
+ PyDict_SetItemString(newd, #val, s=PyInt_FromLong(val)); \
+ Py_DECREF(s); \
+ PyDict_SetItemString(newd, #one, s=PyInt_FromLong(val)); \
+ Py_DECREF(s)
-#define _addone(val) \
- PyDict_SetItemString(newd, #val, s=PyInt_FromLong(val)); \
- Py_DECREF(s)
+#define _addone(val) \
+ PyDict_SetItemString(newd, #val, s=PyInt_FromLong(val)); \
+ Py_DECREF(s)
- _addnew(OWNDATA, O);
- _addnew(FORTRAN, F);
- _addnew(CONTIGUOUS, C);
- _addnew(ALIGNED, A);
- _addnew(UPDATEIFCOPY, U);
- _addnew(WRITEABLE, W);
- _addone(C_CONTIGUOUS);
- _addone(F_CONTIGUOUS);
+ _addnew(OWNDATA, O);
+ _addnew(FORTRAN, F);
+ _addnew(CONTIGUOUS, C);
+ _addnew(ALIGNED, A);
+ _addnew(UPDATEIFCOPY, U);
+ _addnew(WRITEABLE, W);
+ _addone(C_CONTIGUOUS);
+ _addone(F_CONTIGUOUS);
#undef _addone
#undef _addnew
- PyDict_SetItemString(d, "_flagdict", newd);
- Py_DECREF(newd);
- return;
+ PyDict_SetItemString(d, "_flagdict", newd);
+ Py_DECREF(newd);
+ return;
}
/* Initialization function for the module */
PyMODINIT_FUNC initmultiarray(void) {
- PyObject *m, *d, *s;
- PyObject *c_api;
+ PyObject *m, *d, *s;
+ PyObject *c_api;
- /* Create the module and add the functions */
- m = Py_InitModule("multiarray", array_module_methods);
- if (!m) goto err;
+ /* Create the module and add the functions */
+ m = Py_InitModule("multiarray", array_module_methods);
+ if (!m) goto err;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- if (!d) goto err;
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ if (!d) goto err;
- PyArray_Type.tp_free = _pya_free;
- if (PyType_Ready(&PyArray_Type) < 0)
- return;
+ PyArray_Type.tp_free = _pya_free;
+ if (PyType_Ready(&PyArray_Type) < 0)
+ return;
- if (setup_scalartypes(d) < 0) goto err;
+ if (setup_scalartypes(d) < 0) goto err;
- PyArrayIter_Type.tp_iter = PyObject_SelfIter;
- PyArrayMultiIter_Type.tp_iter = PyObject_SelfIter;
- PyArrayMultiIter_Type.tp_free = _pya_free;
- if (PyType_Ready(&PyArrayIter_Type) < 0)
- return;
+ PyArrayIter_Type.tp_iter = PyObject_SelfIter;
+ PyArrayMultiIter_Type.tp_iter = PyObject_SelfIter;
+ PyArrayMultiIter_Type.tp_free = _pya_free;
+ if (PyType_Ready(&PyArrayIter_Type) < 0)
+ return;
- if (PyType_Ready(&PyArrayMapIter_Type) < 0)
- return;
+ if (PyType_Ready(&PyArrayMapIter_Type) < 0)
+ return;
- if (PyType_Ready(&PyArrayMultiIter_Type) < 0)
- return;
+ if (PyType_Ready(&PyArrayMultiIter_Type) < 0)
+ return;
- PyArrayDescr_Type.tp_hash = (hashfunc)_Py_HashPointer;
- if (PyType_Ready(&PyArrayDescr_Type) < 0)
- return;
+ PyArrayDescr_Type.tp_hash = (hashfunc)_Py_HashPointer;
+ if (PyType_Ready(&PyArrayDescr_Type) < 0)
+ return;
- if (PyType_Ready(&PyArrayFlags_Type) < 0)
- return;
+ if (PyType_Ready(&PyArrayFlags_Type) < 0)
+ return;
- c_api = PyCObject_FromVoidPtr((void *)PyArray_API, NULL);
- PyDict_SetItemString(d, "_ARRAY_API", c_api);
- Py_DECREF(c_api);
- if (PyErr_Occurred()) goto err;
+ c_api = PyCObject_FromVoidPtr((void *)PyArray_API, NULL);
+ PyDict_SetItemString(d, "_ARRAY_API", c_api);
+ Py_DECREF(c_api);
+ if (PyErr_Occurred()) goto err;
- MultiArrayError = PyString_FromString ("multiarray.error");
- PyDict_SetItemString (d, "error", MultiArrayError);
+ MultiArrayError = PyString_FromString ("multiarray.error");
+ PyDict_SetItemString (d, "error", MultiArrayError);
- s = PyString_FromString("3.0");
- PyDict_SetItemString(d, "__version__", s);
- Py_DECREF(s);
+ s = PyString_FromString("3.0");
+ PyDict_SetItemString(d, "__version__", s);
+ Py_DECREF(s);
-#define ADDCONST(NAME) \
- s = PyInt_FromLong(NPY_##NAME); \
- PyDict_SetItemString(d, #NAME, s); \
- Py_DECREF(s)
+#define ADDCONST(NAME) \
+ s = PyInt_FromLong(NPY_##NAME); \
+ PyDict_SetItemString(d, #NAME, s); \
+ Py_DECREF(s)
- ADDCONST(ALLOW_THREADS);
- ADDCONST(BUFSIZE);
- ADDCONST(CLIP);
+ ADDCONST(ALLOW_THREADS);
+ ADDCONST(BUFSIZE);
+ ADDCONST(CLIP);
- ADDCONST(ITEM_HASOBJECT);
- ADDCONST(LIST_PICKLE);
- ADDCONST(ITEM_IS_POINTER);
- ADDCONST(NEEDS_INIT);
- ADDCONST(NEEDS_PYAPI);
- ADDCONST(USE_GETITEM);
- ADDCONST(USE_SETITEM);
+ ADDCONST(ITEM_HASOBJECT);
+ ADDCONST(LIST_PICKLE);
+ ADDCONST(ITEM_IS_POINTER);
+ ADDCONST(NEEDS_INIT);
+ ADDCONST(NEEDS_PYAPI);
+ ADDCONST(USE_GETITEM);
+ ADDCONST(USE_SETITEM);
- ADDCONST(RAISE);
- ADDCONST(WRAP);
- ADDCONST(MAXDIMS);
+ ADDCONST(RAISE);
+ ADDCONST(WRAP);
+ ADDCONST(MAXDIMS);
#undef ADDCONST
- Py_INCREF(&PyArray_Type);
- PyDict_SetItemString(d, "ndarray", (PyObject *)&PyArray_Type);
- Py_INCREF(&PyArrayIter_Type);
- PyDict_SetItemString(d, "flatiter", (PyObject *)&PyArrayIter_Type);
- Py_INCREF(&PyArrayMultiIter_Type);
- PyDict_SetItemString(d, "broadcast",
- (PyObject *)&PyArrayMultiIter_Type);
- Py_INCREF(&PyArrayDescr_Type);
- PyDict_SetItemString(d, "dtype", (PyObject *)&PyArrayDescr_Type);
+ Py_INCREF(&PyArray_Type);
+ PyDict_SetItemString(d, "ndarray", (PyObject *)&PyArray_Type);
+ Py_INCREF(&PyArrayIter_Type);
+ PyDict_SetItemString(d, "flatiter", (PyObject *)&PyArrayIter_Type);
+ Py_INCREF(&PyArrayMultiIter_Type);
+ PyDict_SetItemString(d, "broadcast",
+ (PyObject *)&PyArrayMultiIter_Type);
+ Py_INCREF(&PyArrayDescr_Type);
+ PyDict_SetItemString(d, "dtype", (PyObject *)&PyArrayDescr_Type);
- Py_INCREF(&PyArrayFlags_Type);
- PyDict_SetItemString(d, "flagsobj", (PyObject *)&PyArrayFlags_Type);
+ Py_INCREF(&PyArrayFlags_Type);
+ PyDict_SetItemString(d, "flagsobj", (PyObject *)&PyArrayFlags_Type);
- set_flaginfo(d);
+ set_flaginfo(d);
- if (set_typeinfo(d) != 0) goto err;
- return;
+ if (set_typeinfo(d) != 0) goto err;
+ return;
err:
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot load multiarray module.");
- }
- return;
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot load multiarray module.");
+ }
+ return;
}
diff --git a/numpy/core/src/scalarmathmodule.c.src b/numpy/core/src/scalarmathmodule.c.src
index 0310b3567..8cb77e0b4 100644
--- a/numpy/core/src/scalarmathmodule.c.src
+++ b/numpy/core/src/scalarmathmodule.c.src
@@ -41,10 +41,10 @@ static int ulonglong_overflow(ulonglong a, ulonglong b)
/* *c = ((x + y)<<32) + w; */
#if SIZEOF_LONGLONG == 64
return z || (x>>32) || (y>>32) ||
- (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 32);
+ (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 32);
#elif SIZEOF_LONGLONG == 128
return z || (x>>64) || (y>>64) ||
- (((x & 0xFFFFFFFFFFFFFFFFL) + (y & 0xFFFFFFFFFFFFFFFFL) + (w >> 64)) >> 64);
+ (((x & 0xFFFFFFFFFFFFFFFFL) + (y & 0xFFFFFFFFFFFFFFFFL) + (w >> 64)) >> 64);
#else
return 0;
#endif
@@ -90,10 +90,10 @@ static int slonglong_overflow(longlong a0, longlong b0)
#if SIZEOF_LONGLONG == 64
return z || (x>>31) || (y>>31) ||
- (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 31);
+ (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 31);
#elif SIZEOF_LONGLONG == 128
return z || (x>>63) || (y>>63) ||
- (((x & 0xFFFFFFFFFFFFFFFFL) + (y & 0xFFFFFFFFFFFFFFFFL) + (w >> 64)) >> 63);
+ (((x & 0xFFFFFFFFFFFFFFFFL) + (y & 0xFFFFFFFFFFFFFFFFL) + (w >> 64)) >> 63);
#else
return 0;
#endif
@@ -103,16 +103,16 @@ static int slonglong_overflow(longlong a0, longlong b0)
/* Basic operations:
-BINARY:
+ BINARY:
-add, subtract, multiply, divide, remainder, divmod, power,
-floor_divide, true_divide
+ add, subtract, multiply, divide, remainder, divmod, power,
+ floor_divide, true_divide
-lshift, rshift, and, or, xor (integers only)
+ lshift, rshift, and, or, xor (integers only)
-UNARY:
+ UNARY:
-negative, positive, absolute, nonzero, invert, int, long, float, oct, hex
+ negative, positive, absolute, nonzero, invert, int, long, float, oct, hex
*/
@@ -123,7 +123,7 @@ static void
@name@_ctype_add(@name@ a, @name@ b, @name@ *out) {
*out = a + b;
if ((*out^a) >= 0 || (*out^b) >= 0)
- return;
+ return;
generate_overflow_error();
return;
}
@@ -131,7 +131,7 @@ static void
@name@_ctype_subtract(@name@ a, @name@ b, @name@ *out) {
*out = a - b;
if ((*out^a) >= 0 || (*out^~b) >= 0)
- return;
+ return;
generate_overflow_error();
return;
}
@@ -143,7 +143,7 @@ static void
@name@_ctype_add(@name@ a, @name@ b, @name@ *out) {
*out = a + b;
if (*out >= a && *out >= b)
- return;
+ return;
generate_overflow_error();
return;
}
@@ -179,7 +179,7 @@ static void
#else
if (temp > MAX_@NAME@)
#endif
- generate_overflow_error();
+ generate_overflow_error();
return;
}
#endif
@@ -195,7 +195,7 @@ static void
@name@_ctype_multiply(@name@ a, @name@ b, @name@ *out) {
*out = a * b;
if (@char@longlong_overflow(a, b))
- generate_overflow_error();
+ generate_overflow_error();
return;
}
#endif
@@ -208,13 +208,13 @@ static void
static void
@name@_ctype_divide(@name@ a, @name@ b, @name@ *out) {
if (b == 0) {
- generate_divbyzero_error();
- *out = 0;
+ generate_divbyzero_error();
+ *out = 0;
}
#if @neg@
else if (b == -1 && a < 0 && a == -a) {
- generate_overflow_error();
- *out = a / b;
+ generate_overflow_error();
+ *out = a / b;
}
#endif
else {
@@ -224,7 +224,7 @@ static void
if (((a > 0) != (b > 0)) && (a % b != 0)) tmp--;
*out = tmp;
#else
- *out = a / b;
+ *out = a / b;
#endif
}
}
@@ -232,17 +232,17 @@ static void
static void
@name@_ctype_remainder(@name@ a, @name@ b, @name@ *out) {
if (a == 0 || b == 0) {
- if (b == 0) generate_divbyzero_error();
- *out = 0;
+ if (b == 0) generate_divbyzero_error();
+ *out = 0;
return;
}
#if @neg@
else if ((a > 0) == (b > 0)) {
- *out = a % b;
+ *out = a % b;
}
else { /* handled like Python does */
- *out = a % b;
- if (*out) *out += b;
+ *out = a % b;
+ if (*out) *out += b;
}
#else
*out = a % b;
@@ -254,7 +254,7 @@ static void
#name=byte,ubyte,short,ushort,int,uint,long,ulong,longlong,ulonglong#
#otyp=float*4, double*6#
**/
-#define @name@_ctype_true_divide(a, b, out) \
+#define @name@_ctype_true_divide(a, b, out) \
*(out) = ((@otyp@) (a)) / ((@otyp@) (b));
/**end repeat**/
@@ -276,9 +276,9 @@ static void
if (temp == 0)
break; /* Avoid ix / 0 */
}
- b >>= 1; /* Shift exponent down by 1 bit */
+ b >>= 1; /* Shift exponent down by 1 bit */
if (b==0) break;
- /* Square the value of temp */
+ /* Square the value of temp */
@name@_ctype_multiply(temp, temp, &mult);
temp = mult;
}
@@ -309,7 +309,7 @@ static @name@ (*_basic_@name@_fmod)(@name@, @name@);
#define @name@_ctype_multiply(a, b, outp) *(outp) = a * b
#define @name@_ctype_divide(a, b, outp) *(outp) = a / b
#define @name@_ctype_true_divide @name@_ctype_divide
-#define @name@_ctype_floor_divide(a, b, outp) \
+#define @name@_ctype_floor_divide(a, b, outp) \
*(outp) = _basic_@name@_floor((a) / (b))
/**end repeat**/
@@ -318,29 +318,29 @@ static @name@ (*_basic_@name@_fmod)(@name@, @name@);
#rtype=float, double, longdouble#
#c=f,,l#
**/
-#define @name@_ctype_add(a, b, outp) do{ \
- (outp)->real = (a).real + (b).real; \
- (outp)->imag = (a).imag + (b).imag; \
+#define @name@_ctype_add(a, b, outp) do{ \
+ (outp)->real = (a).real + (b).real; \
+ (outp)->imag = (a).imag + (b).imag; \
}while(0)
-#define @name@_ctype_subtract(a, b, outp) do{ \
- (outp)->real = (a).real - (b).real; \
- (outp)->imag = (a).imag - (b).imag; \
+#define @name@_ctype_subtract(a, b, outp) do{ \
+ (outp)->real = (a).real - (b).real; \
+ (outp)->imag = (a).imag - (b).imag; \
}while(0)
-#define @name@_ctype_multiply(a, b, outp) do{ \
- (outp)->real = (a).real * (b).real - (a).imag * (b).imag; \
- (outp)->imag = (a).real * (b).imag + (a).imag * (b).real; \
+#define @name@_ctype_multiply(a, b, outp) do{ \
+ (outp)->real = (a).real * (b).real - (a).imag * (b).imag; \
+ (outp)->imag = (a).real * (b).imag + (a).imag * (b).real; \
}while(0)
-#define @name@_ctype_divide(a, b, outp) do{ \
- @rtype@ d = (b).real*(b).real + (b).imag*(b).imag; \
- (outp)->real = ((a).real*(b).real + (a).imag*(b).imag)/d; \
- (outp)->imag = ((a).imag*(b).real - (a).real*(b).imag)/d; \
+#define @name@_ctype_divide(a, b, outp) do{ \
+ @rtype@ d = (b).real*(b).real + (b).imag*(b).imag; \
+ (outp)->real = ((a).real*(b).real + (a).imag*(b).imag)/d; \
+ (outp)->imag = ((a).imag*(b).real - (a).real*(b).imag)/d; \
}while(0)
#define @name@_ctype_true_divide @name@_ctype_divide
-#define @name@_ctype_floor_divide(a, b, outp) do { \
- (outp)->real = _basic_@rtype@_floor \
- (((a).real*(b).real + (a).imag*(b).imag) / \
- ((b).real*(b).real + (b).imag*(b).imag)); \
- (outp)->imag = 0; \
+#define @name@_ctype_floor_divide(a, b, outp) do { \
+ (outp)->real = _basic_@rtype@_floor \
+ (((a).real*(b).real + (a).imag*(b).imag) / \
+ ((b).real*(b).real + (b).imag*(b).imag)); \
+ (outp)->imag = 0; \
}while(0)
/**end repeat**/
@@ -361,9 +361,9 @@ static void
/**begin repeat
#name=byte,ubyte,short,ushort,int,uint,long,ulong,longlong,ulonglong,float,double,longdouble,cfloat,cdouble,clongdouble#
**/
-#define @name@_ctype_divmod(a, b, out, out2) { \
- @name@_ctype_floor_divide(a, b, out); \
- @name@_ctype_remainder(a, b, out2); \
+#define @name@_ctype_divmod(a, b, out, out2) { \
+ @name@_ctype_floor_divide(a, b, out); \
+ @name@_ctype_remainder(a, b, out2); \
}
/**end repeat**/
@@ -474,16 +474,16 @@ static void
/* The general strategy for commutative binary operators is to
-1) Convert the types to the common type if both are scalars (0 return)
-2) If both are not scalars use ufunc machinery (-2 return)
-3) If both are scalars but cannot be cast to the right type
-return NotImplmented (-1 return)
+ 1) Convert the types to the common type if both are scalars (0 return)
+ 2) If both are not scalars use ufunc machinery (-2 return)
+ 3) If both are scalars but cannot be cast to the right type
+ return NotImplmented (-1 return)
-4) Perform the function on the C-type.
-5) If an error condition occurred, check to see
-what the current error-handling is and handle the error.
+ 4) Perform the function on the C-type.
+ 5) If an error condition occurred, check to see
+ what the current error-handling is and handle the error.
-6) Construct and return the output scalar.
+ 6) Construct and return the output scalar.
*/
@@ -499,34 +499,34 @@ _@name@_convert_to_ctype(PyObject *a, @name@ *arg1)
PyObject *temp;
if (PyArray_IsScalar(a, @Name@)) {
- *arg1 = PyArrayScalar_VAL(a, @Name@);
- return 0;
+ *arg1 = PyArrayScalar_VAL(a, @Name@);
+ return 0;
}
else if (PyArray_IsScalar(a, Generic)) {
- PyArray_Descr *descr1;
- int ret;
- if (!PyArray_IsScalar(a, Number)) return -1;
- descr1 = PyArray_DescrFromTypeObject((PyObject *)(a->ob_type));
- if (PyArray_CanCastSafely(descr1->type_num, PyArray_@NAME@)) {
- PyArray_CastScalarDirect(a, descr1, arg1, PyArray_@NAME@);
- ret = 0;
- }
- else ret = -1;
- Py_DECREF(descr1);
- return ret;
+ PyArray_Descr *descr1;
+ int ret;
+ if (!PyArray_IsScalar(a, Number)) return -1;
+ descr1 = PyArray_DescrFromTypeObject((PyObject *)(a->ob_type));
+ if (PyArray_CanCastSafely(descr1->type_num, PyArray_@NAME@)) {
+ PyArray_CastScalarDirect(a, descr1, arg1, PyArray_@NAME@);
+ ret = 0;
+ }
+ else ret = -1;
+ Py_DECREF(descr1);
+ return ret;
}
else if ((temp = PyArray_ScalarFromObject(a)) != NULL) {
- int retval;
- retval = _@name@_convert_to_ctype(temp, arg1);
- Py_DECREF(temp);
- return retval;
+ int retval;
+ retval = _@name@_convert_to_ctype(temp, arg1);
+ Py_DECREF(temp);
+ return retval;
}
return -2;
}
static int
_@name@_convert2_to_ctypes(PyObject *a, @name@ *arg1,
- PyObject *b, @name@ *arg2)
+ PyObject *b, @name@ *arg2)
{
int ret;
ret = _@name@_convert_to_ctype(a, arg1);
@@ -568,10 +568,10 @@ static PyObject *
case 0:
break;
case -1: /* one of them can't be cast safely
- must be mixed-types*/
- return PyArray_Type.tp_as_number->nb_@oper@(a,b);
+ must be mixed-types*/
+ return PyArray_Type.tp_as_number->nb_@oper@(a,b);
case -2: /* use default handling */
- if (PyErr_Occurred()) return NULL;
+ if (PyErr_Occurred()) return NULL;
return PyGenericArrType_Type.tp_as_number->nb_@oper@(a,b);
}
@@ -591,14 +591,14 @@ static PyObject *
/* Check status flag. If it is set, then look up what to do */
retstatus = PyUFunc_getfperr();
if (retstatus) {
- int bufsize, errmask;
- PyObject *errobj;
- if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask,
- &errobj) < 0)
- return NULL;
+ int bufsize, errmask;
+ PyObject *errobj;
+ if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask,
+ &errobj) < 0)
+ return NULL;
first = 1;
- if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first))
- return NULL;
+ if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first))
+ return NULL;
}
#endif
@@ -643,7 +643,7 @@ static PyObject *
#if @cmplx@
@name@ out = {0,0};
@otyp@ out1;
- out1.real = out.imag = 0;
+ out1.real = out.imag = 0;
#else
@name@ out = 0;
@otyp@ out1=0;
@@ -653,10 +653,10 @@ static PyObject *
case 0:
break;
case -1: /* can't cast both safely
- mixed-types? */
- return PyArray_Type.tp_as_number->nb_power(a,b,NULL);
+ mixed-types? */
+ return PyArray_Type.tp_as_number->nb_power(a,b,NULL);
case -2: /* use default handling */
- if (PyErr_Occurred()) return NULL;
+ if (PyErr_Occurred()) return NULL;
return PyGenericArrType_Type.tp_as_number->nb_power(a,b,NULL);
}
@@ -666,47 +666,47 @@ static PyObject *
/* as a function call. */
#if @cmplx@
if (arg2.real == 0 && arg1.real == 0) {
- out1.real = out.real = 1;
- out1.imag = out.imag = 0;
+ out1.real = out.real = 1;
+ out1.imag = out.imag = 0;
}
#else
if (arg2 == 0) {
- out1 = out = 1;
+ out1 = out = 1;
}
#endif
#if @isint@
else if (arg2 < 0) {
- @name@_ctype_power(arg1, -arg2, &out);
- out1 = (@otyp@) (1.0 / out);
+ @name@_ctype_power(arg1, -arg2, &out);
+ out1 = (@otyp@) (1.0 / out);
}
#endif
else {
- @name@_ctype_power(arg1, arg2, &out);
+ @name@_ctype_power(arg1, arg2, &out);
}
/* Check status flag. If it is set, then look up what to do */
retstatus = PyUFunc_getfperr();
if (retstatus) {
- int bufsize, errmask;
- PyObject *errobj;
- if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask,
- &errobj) < 0)
- return NULL;
+ int bufsize, errmask;
+ PyObject *errobj;
+ if (PyUFunc_GetPyValues("@name@_scalars", &bufsize, &errmask,
+ &errobj) < 0)
+ return NULL;
first = 1;
- if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first))
- return NULL;
+ if (PyUFunc_handlefperr(errmask, errobj, retstatus, &first))
+ return NULL;
}
#if @isint@
if (arg2 < 0) {
- ret = PyArrayScalar_New(@OName@);
- if (ret==NULL) return NULL;
- PyArrayScalar_ASSIGN(ret, @OName@, out1);
+ ret = PyArrayScalar_New(@OName@);
+ if (ret==NULL) return NULL;
+ PyArrayScalar_ASSIGN(ret, @OName@, out1);
}
else {
- ret = PyArrayScalar_New(@Name@);
- if (ret==NULL) return NULL;
- PyArrayScalar_ASSIGN(ret, @Name@, out);
+ ret = PyArrayScalar_New(@Name@);
+ if (ret==NULL) return NULL;
+ PyArrayScalar_ASSIGN(ret, @Name@, out);
}
#else
ret = PyArrayScalar_New(@Name@);
@@ -720,8 +720,8 @@ static PyObject *
/**begin repeat
-#name=(cfloat,cdouble,clongdouble)*2#
-#oper=divmod*3,remainder*3#
+ #name=(cfloat,cdouble,clongdouble)*2#
+ #oper=divmod*3,remainder*3#
**/
#define @name@_@oper@ NULL
/**end repeat**/
@@ -751,10 +751,10 @@ static PyObject *
case 0:
break;
case -1: /* can't cast both safely use different add function */
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
case -2: /* use default handling */
- if (PyErr_Occurred()) return NULL;
+ if (PyErr_Occurred()) return NULL;
return PyGenericArrType_Type.tp_as_number->nb_@oper@(a);
}
@@ -771,7 +771,7 @@ static PyObject *
/**end repeat**/
/**begin repeat
-#name=float,double,longdouble,cfloat,cdouble,clongdouble#
+ #name=float,double,longdouble,cfloat,cdouble,clongdouble#
**/
#define @name@_invert NULL
/**end repeat**/
@@ -787,7 +787,7 @@ static int
@name@ arg1;
if (_@name@_convert_to_ctype(a, &arg1) < 0) {
- if (PyErr_Occurred()) return -1;
+ if (PyErr_Occurred()) return -1;
return PyGenericArrType_Type.tp_as_number->nb_nonzero(a);
}
@@ -822,8 +822,8 @@ static PyObject *
modf(x, &ix);
x = ix;
#endif
- if(LONG_MIN < x && x < LONG_MAX)
- return PyInt_FromLong(x);
+ if(LONG_MIN < x && x < LONG_MAX)
+ return PyInt_FromLong(x);
return @func@(x);
}
/**end repeat**/
@@ -865,9 +865,9 @@ static PyObject *
#op=<=,>=,<,>,==,!=#
**/
#define def_cmp_@oper@(arg1, arg2) (arg1 @op@ arg2)
-#define cmplx_cmp_@oper@(arg1, arg2) ((arg1.real == arg2.real) ? \
- arg1.imag @op@ arg2.imag : \
- arg1.real @op@ arg2.real)
+#define cmplx_cmp_@oper@(arg1, arg2) ((arg1.real == arg2.real) ? \
+ arg1.imag @op@ arg2.imag : \
+ arg1.real @op@ arg2.real)
/**end repeat**/
/**begin repeat
@@ -882,40 +882,40 @@ static PyObject*
switch(_@name@_convert2_to_ctypes(self, &arg1, other, &arg2)) {
case 0:
- break;
+ break;
case -1: /* can't cast both safely use different add function */
case -2: /* use ufunc */
- if (PyErr_Occurred()) return NULL;
- return PyGenericArrType_Type.tp_richcompare(self, other, cmp_op);
+ if (PyErr_Occurred()) return NULL;
+ return PyGenericArrType_Type.tp_richcompare(self, other, cmp_op);
}
/* here we do the actual calculation with arg1 and arg2 */
switch (cmp_op) {
case Py_EQ:
- out = @simp@_cmp_eq(arg1, arg2);
- break;
+ out = @simp@_cmp_eq(arg1, arg2);
+ break;
case Py_NE:
- out = @simp@_cmp_ne(arg1, arg2);
- break;
+ out = @simp@_cmp_ne(arg1, arg2);
+ break;
case Py_LE:
- out = @simp@_cmp_le(arg1, arg2);
- break;
+ out = @simp@_cmp_le(arg1, arg2);
+ break;
case Py_GE:
- out = @simp@_cmp_ge(arg1, arg2);
- break;
+ out = @simp@_cmp_ge(arg1, arg2);
+ break;
case Py_LT:
- out = @simp@_cmp_lt(arg1, arg2);
- break;
+ out = @simp@_cmp_lt(arg1, arg2);
+ break;
case Py_GT:
- out = @simp@_cmp_gt(arg1, arg2);
- break;
+ out = @simp@_cmp_gt(arg1, arg2);
+ break;
}
if (out) {
- PyArrayScalar_RETURN_TRUE;
+ PyArrayScalar_RETURN_TRUE;
}
else {
- PyArrayScalar_RETURN_FALSE;
+ PyArrayScalar_RETURN_FALSE;
}
}
/**end repeat**/
@@ -1066,7 +1066,7 @@ get_functions(void)
Py_DECREF(obj);
return
- ret = 0;
+ ret = 0;
fail:
Py_DECREF(mm);
return ret;
@@ -1083,28 +1083,28 @@ alter_pyscalars(PyObject *dummy, PyObject *args)
PyObject *obj;
n = PyTuple_GET_SIZE(args);
while(n--) {
- obj = PyTuple_GET_ITEM(args, n);
- if (obj == (PyObject *)(&PyInt_Type)) {
- PyInt_Type.tp_as_number = PyLongArrType_Type.tp_as_number;
- PyInt_Type.tp_compare = PyLongArrType_Type.tp_compare;
- PyInt_Type.tp_richcompare = PyLongArrType_Type.tp_richcompare;
- }
- else if (obj == (PyObject *)(&PyFloat_Type)) {
- PyFloat_Type.tp_as_number = PyDoubleArrType_Type.tp_as_number;
- PyFloat_Type.tp_compare = PyDoubleArrType_Type.tp_compare;
- PyFloat_Type.tp_richcompare = PyDoubleArrType_Type.tp_richcompare;
- }
- else if (obj == (PyObject *)(&PyComplex_Type)) {
- PyComplex_Type.tp_as_number = PyCDoubleArrType_Type.tp_as_number;
- PyComplex_Type.tp_compare = PyCDoubleArrType_Type.tp_compare;
- PyComplex_Type.tp_richcompare = \
- PyCDoubleArrType_Type.tp_richcompare;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "arguments must be int, float, or complex");
- return NULL;
- }
+ obj = PyTuple_GET_ITEM(args, n);
+ if (obj == (PyObject *)(&PyInt_Type)) {
+ PyInt_Type.tp_as_number = PyLongArrType_Type.tp_as_number;
+ PyInt_Type.tp_compare = PyLongArrType_Type.tp_compare;
+ PyInt_Type.tp_richcompare = PyLongArrType_Type.tp_richcompare;
+ }
+ else if (obj == (PyObject *)(&PyFloat_Type)) {
+ PyFloat_Type.tp_as_number = PyDoubleArrType_Type.tp_as_number;
+ PyFloat_Type.tp_compare = PyDoubleArrType_Type.tp_compare;
+ PyFloat_Type.tp_richcompare = PyDoubleArrType_Type.tp_richcompare;
+ }
+ else if (obj == (PyObject *)(&PyComplex_Type)) {
+ PyComplex_Type.tp_as_number = PyCDoubleArrType_Type.tp_as_number;
+ PyComplex_Type.tp_compare = PyCDoubleArrType_Type.tp_compare;
+ PyComplex_Type.tp_richcompare = \
+ PyCDoubleArrType_Type.tp_richcompare;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "arguments must be int, float, or complex");
+ return NULL;
+ }
}
Py_INCREF(Py_None);
return Py_None;
@@ -1118,27 +1118,27 @@ restore_pyscalars(PyObject *dummy, PyObject *args)
PyObject *obj;
n = PyTuple_GET_SIZE(args);
while(n--) {
- obj = PyTuple_GET_ITEM(args, n);
- if (obj == (PyObject *)(&PyInt_Type)) {
- PyInt_Type.tp_as_number = saved_tables[0];
- PyInt_Type.tp_compare = saved_tables[1];
- PyInt_Type.tp_richcompare = saved_tables[2];
- }
- else if (obj == (PyObject *)(&PyFloat_Type)) {
- PyFloat_Type.tp_as_number = saved_tables[3];
- PyFloat_Type.tp_compare = saved_tables[4];
- PyFloat_Type.tp_richcompare = saved_tables[5];
- }
- else if (obj == (PyObject *)(&PyComplex_Type)) {
- PyComplex_Type.tp_as_number = saved_tables[6];
- PyComplex_Type.tp_compare = saved_tables[7];
- PyComplex_Type.tp_richcompare = saved_tables[8];
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "arguments must be int, float, or complex");
- return NULL;
- }
+ obj = PyTuple_GET_ITEM(args, n);
+ if (obj == (PyObject *)(&PyInt_Type)) {
+ PyInt_Type.tp_as_number = saved_tables[0];
+ PyInt_Type.tp_compare = saved_tables[1];
+ PyInt_Type.tp_richcompare = saved_tables[2];
+ }
+ else if (obj == (PyObject *)(&PyFloat_Type)) {
+ PyFloat_Type.tp_as_number = saved_tables[3];
+ PyFloat_Type.tp_compare = saved_tables[4];
+ PyFloat_Type.tp_richcompare = saved_tables[5];
+ }
+ else if (obj == (PyObject *)(&PyComplex_Type)) {
+ PyComplex_Type.tp_as_number = saved_tables[6];
+ PyComplex_Type.tp_compare = saved_tables[7];
+ PyComplex_Type.tp_richcompare = saved_tables[8];
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "arguments must be int, float, or complex");
+ return NULL;
+ }
}
Py_INCREF(Py_None);
return Py_None;
@@ -1152,27 +1152,27 @@ use_pythonmath(PyObject *dummy, PyObject *args)
PyObject *obj;
n = PyTuple_GET_SIZE(args);
while(n--) {
- obj = PyTuple_GET_ITEM(args, n);
- if (obj == (PyObject *)(&PyInt_Type)) {
- PyLongArrType_Type.tp_as_number = saved_tables[0];
- PyLongArrType_Type.tp_compare = saved_tables[1];
- PyLongArrType_Type.tp_richcompare = saved_tables[2];
- }
- else if (obj == (PyObject *)(&PyFloat_Type)) {
- PyDoubleArrType_Type.tp_as_number = saved_tables[3];
- PyDoubleArrType_Type.tp_compare = saved_tables[4];
- PyDoubleArrType_Type.tp_richcompare = saved_tables[5];
- }
- else if (obj == (PyObject *)(&PyComplex_Type)) {
- PyCDoubleArrType_Type.tp_as_number = saved_tables[6];
- PyCDoubleArrType_Type.tp_compare = saved_tables[7];
- PyCDoubleArrType_Type.tp_richcompare = saved_tables[8];
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "arguments must be int, float, or complex");
- return NULL;
- }
+ obj = PyTuple_GET_ITEM(args, n);
+ if (obj == (PyObject *)(&PyInt_Type)) {
+ PyLongArrType_Type.tp_as_number = saved_tables[0];
+ PyLongArrType_Type.tp_compare = saved_tables[1];
+ PyLongArrType_Type.tp_richcompare = saved_tables[2];
+ }
+ else if (obj == (PyObject *)(&PyFloat_Type)) {
+ PyDoubleArrType_Type.tp_as_number = saved_tables[3];
+ PyDoubleArrType_Type.tp_compare = saved_tables[4];
+ PyDoubleArrType_Type.tp_richcompare = saved_tables[5];
+ }
+ else if (obj == (PyObject *)(&PyComplex_Type)) {
+ PyCDoubleArrType_Type.tp_as_number = saved_tables[6];
+ PyCDoubleArrType_Type.tp_compare = saved_tables[7];
+ PyCDoubleArrType_Type.tp_richcompare = saved_tables[8];
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "arguments must be int, float, or complex");
+ return NULL;
+ }
}
Py_INCREF(Py_None);
return Py_None;
@@ -1186,27 +1186,27 @@ use_scalarmath(PyObject *dummy, PyObject *args)
PyObject *obj;
n = PyTuple_GET_SIZE(args);
while(n--) {
- obj = PyTuple_GET_ITEM(args, n);
- if (obj == (PyObject *)(&PyInt_Type)) {
- PyLongArrType_Type.tp_as_number = saved_tables_arrtype[0];
- PyLongArrType_Type.tp_compare = saved_tables_arrtype[1];
- PyLongArrType_Type.tp_richcompare = saved_tables_arrtype[2];
- }
- else if (obj == (PyObject *)(&PyFloat_Type)) {
- PyDoubleArrType_Type.tp_as_number = saved_tables_arrtype[3];
- PyDoubleArrType_Type.tp_compare = saved_tables_arrtype[4];
- PyDoubleArrType_Type.tp_richcompare = saved_tables_arrtype[5];
- }
- else if (obj == (PyObject *)(&PyComplex_Type)) {
- PyCDoubleArrType_Type.tp_as_number = saved_tables_arrtype[6];
- PyCDoubleArrType_Type.tp_compare = saved_tables_arrtype[7];
- PyCDoubleArrType_Type.tp_richcompare = saved_tables_arrtype[8];
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "arguments must be int, float, or complex");
- return NULL;
- }
+ obj = PyTuple_GET_ITEM(args, n);
+ if (obj == (PyObject *)(&PyInt_Type)) {
+ PyLongArrType_Type.tp_as_number = saved_tables_arrtype[0];
+ PyLongArrType_Type.tp_compare = saved_tables_arrtype[1];
+ PyLongArrType_Type.tp_richcompare = saved_tables_arrtype[2];
+ }
+ else if (obj == (PyObject *)(&PyFloat_Type)) {
+ PyDoubleArrType_Type.tp_as_number = saved_tables_arrtype[3];
+ PyDoubleArrType_Type.tp_compare = saved_tables_arrtype[4];
+ PyDoubleArrType_Type.tp_richcompare = saved_tables_arrtype[5];
+ }
+ else if (obj == (PyObject *)(&PyComplex_Type)) {
+ PyCDoubleArrType_Type.tp_as_number = saved_tables_arrtype[6];
+ PyCDoubleArrType_Type.tp_compare = saved_tables_arrtype[7];
+ PyCDoubleArrType_Type.tp_richcompare = saved_tables_arrtype[8];
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "arguments must be int, float, or complex");
+ return NULL;
+ }
}
Py_INCREF(Py_None);
return Py_None;
diff --git a/numpy/core/src/ucsnarrow.c b/numpy/core/src/ucsnarrow.c
index 6eceadd0e..2d6fec082 100644
--- a/numpy/core/src/ucsnarrow.c
+++ b/numpy/core/src/ucsnarrow.c
@@ -11,27 +11,27 @@
is ucs4length + number of surrogate pairs found.
values above 0xffff are converted to surrogate pairs.
- */
+*/
static int
PyUCS2Buffer_FromUCS4(Py_UNICODE *ucs2, PyArray_UCS4 *ucs4, int ucs4length)
{
- register int i;
- int numucs2 = 0;
- PyArray_UCS4 chr;
- for (i=0; i<ucs4length; i++) {
- chr = *ucs4++;
- if (chr > 0xffff) {
- numucs2++;
- chr -= 0x10000L;
- *ucs2++ = 0xD800 + (Py_UNICODE) (chr >> 10);
- *ucs2++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
- }
- else {
- *ucs2++ = (Py_UNICODE) chr;
- }
- numucs2++;
+ register int i;
+ int numucs2 = 0;
+ PyArray_UCS4 chr;
+ for (i=0; i<ucs4length; i++) {
+ chr = *ucs4++;
+ if (chr > 0xffff) {
+ numucs2++;
+ chr -= 0x10000L;
+ *ucs2++ = 0xD800 + (Py_UNICODE) (chr >> 10);
+ *ucs2++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
+ }
+ else {
+ *ucs2++ = (Py_UNICODE) chr;
}
- return numucs2;
+ numucs2++;
+ }
+ return numucs2;
}
@@ -47,62 +47,62 @@ PyUCS2Buffer_FromUCS4(Py_UNICODE *ucs2, PyArray_UCS4 *ucs4, int ucs4length)
static int
PyUCS2Buffer_AsUCS4(Py_UNICODE *ucs2, PyArray_UCS4 *ucs4, int ucs2len, int ucs4len)
{
- register int i;
- register PyArray_UCS4 chr;
- register Py_UNICODE ch;
- register int numchars=0;
+ register int i;
+ register PyArray_UCS4 chr;
+ register Py_UNICODE ch;
+ register int numchars=0;
- for (i=0; (i < ucs2len) && (numchars < ucs4len); i++) {
- ch = *ucs2++;
- if (ch >= 0xd800 && ch <= 0xdfff) {
- /* surrogate pair */
- chr = ((PyArray_UCS4)(ch-0xd800)) << 10;
- chr += *ucs2++ + 0x2400; /* -0xdc00 + 0x10000 */
- i++;
- }
- else {
- chr = (PyArray_UCS4) ch;
- }
- *ucs4++ = chr;
- numchars++;
- }
- return numchars;
+ for (i=0; (i < ucs2len) && (numchars < ucs4len); i++) {
+ ch = *ucs2++;
+ if (ch >= 0xd800 && ch <= 0xdfff) {
+ /* surrogate pair */
+ chr = ((PyArray_UCS4)(ch-0xd800)) << 10;
+ chr += *ucs2++ + 0x2400; /* -0xdc00 + 0x10000 */
+ i++;
+ }
+ else {
+ chr = (PyArray_UCS4) ch;
+ }
+ *ucs4++ = chr;
+ numchars++;
+ }
+ return numchars;
}
static PyObject *
MyPyUnicode_New(int length)
{
- PyUnicodeObject *unicode;
- unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
- if (unicode == NULL) return NULL;
- unicode->str = PyMem_NEW(Py_UNICODE, length+1);
- if (!unicode->str) {
- _Py_ForgetReference((PyObject *)unicode);
- PyObject_Del(unicode);
- return PyErr_NoMemory();
- }
- unicode->str[0] = 0;
- unicode->str[length] = 0;
- unicode->length = length;
- unicode->hash = -1;
- unicode->defenc = NULL;
- return (PyObject *)unicode;
+ PyUnicodeObject *unicode;
+ unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
+ if (unicode == NULL) return NULL;
+ unicode->str = PyMem_NEW(Py_UNICODE, length+1);
+ if (!unicode->str) {
+ _Py_ForgetReference((PyObject *)unicode);
+ PyObject_Del(unicode);
+ return PyErr_NoMemory();
+ }
+ unicode->str[0] = 0;
+ unicode->str[length] = 0;
+ unicode->length = length;
+ unicode->hash = -1;
+ unicode->defenc = NULL;
+ return (PyObject *)unicode;
}
static int
MyPyUnicode_Resize(PyUnicodeObject *uni, int length)
{
- void *oldstr;
+ void *oldstr;
- oldstr = uni->str;
- PyMem_RESIZE(uni->str, Py_UNICODE, length+1);
- if (!uni->str) {
- uni->str = oldstr;
- PyErr_NoMemory();
- return -1;
- }
- uni->str[length] = 0;
- uni->length = length;
- return 0;
+ oldstr = uni->str;
+ PyMem_RESIZE(uni->str, Py_UNICODE, length+1);
+ if (!uni->str) {
+ uni->str = oldstr;
+ PyErr_NoMemory();
+ return -1;
+ }
+ uni->str[length] = 0;
+ uni->length = length;
+ return 0;
}
diff --git a/numpy/core/src/ufuncobject.c b/numpy/core/src/ufuncobject.c
index a75e5a862..ecedf7822 100644
--- a/numpy/core/src/ufuncobject.c
+++ b/numpy/core/src/ufuncobject.c
@@ -32,68 +32,67 @@ typedef longdouble (LongdoubleBinaryFunc)(longdouble x, longdouble y);
typedef void (CdoubleBinaryFunc)(cdouble *x, cdouble *y, cdouble *res);
typedef void (CfloatBinaryFunc)(cfloat *x, cfloat *y, cfloat *res);
typedef void (ClongdoubleBinaryFunc)(clongdouble *x, clongdouble *y, \
- clongdouble *res);
+ clongdouble *res);
#define USE_USE_DEFAULTS 1
-
/*UFUNC_API*/
static void
PyUFunc_ff_f_As_dd_d(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n=dimensions[0];
- register intp is1=steps[0],is2=steps[1],os=steps[2];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
+ register intp i, n=dimensions[0];
+ register intp is1=steps[0],is2=steps[1],os=steps[2];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- *(float *)op = (float)((DoubleBinaryFunc *)func) \
- ((double)*(float *)ip1, (double)*(float *)ip2);
- }
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ *(float *)op = (float)((DoubleBinaryFunc *)func) \
+ ((double)*(float *)ip1, (double)*(float *)ip2);
+ }
}
/*UFUNC_API*/
static void
PyUFunc_ff_f(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n=dimensions[0];
- register intp is1=steps[0],is2=steps[1],os=steps[2];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
+ register intp i, n=dimensions[0];
+ register intp is1=steps[0],is2=steps[1],os=steps[2];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- *(float *)op = ((FloatBinaryFunc *)func)(*(float *)ip1,
- *(float *)ip2);
- }
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ *(float *)op = ((FloatBinaryFunc *)func)(*(float *)ip1,
+ *(float *)ip2);
+ }
}
/*UFUNC_API*/
static void
PyUFunc_dd_d(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n=dimensions[0];
- register intp is1=steps[0],is2=steps[1],os=steps[2];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
+ register intp i, n=dimensions[0];
+ register intp is1=steps[0],is2=steps[1],os=steps[2];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- *(double *)op = ((DoubleBinaryFunc *)func)\
- (*(double *)ip1, *(double *)ip2);
- }
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ *(double *)op = ((DoubleBinaryFunc *)func)\
+ (*(double *)ip1, *(double *)ip2);
+ }
}
/*UFUNC_API*/
static void
PyUFunc_gg_g(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n=dimensions[0];
- register intp is1=steps[0],is2=steps[1],os=steps[2];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
+ register intp i, n=dimensions[0];
+ register intp is1=steps[0],is2=steps[1],os=steps[2];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- *(longdouble *)op = \
- ((LongdoubleBinaryFunc *)func)(*(longdouble *)ip1,
- *(longdouble *)ip2);
- }
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ *(longdouble *)op = \
+ ((LongdoubleBinaryFunc *)func)(*(longdouble *)ip1,
+ *(longdouble *)ip2);
+ }
}
@@ -101,96 +100,96 @@ PyUFunc_gg_g(char **args, intp *dimensions, intp *steps, void *func)
static void
PyUFunc_FF_F_As_DD_D(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i,n=dimensions[0],is1=steps[0],is2=steps[1],os=steps[2];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
- cdouble x, y, r;
-
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- x.real = ((float *)ip1)[0]; x.imag = ((float *)ip1)[1];
- y.real = ((float *)ip2)[0]; y.imag = ((float *)ip2)[1];
- ((CdoubleBinaryFunc *)func)(&x, &y, &r);
- ((float *)op)[0] = (float)r.real;
- ((float *)op)[1] = (float)r.imag;
- }
+ register intp i,n=dimensions[0],is1=steps[0],is2=steps[1],os=steps[2];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
+ cdouble x, y, r;
+
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ x.real = ((float *)ip1)[0]; x.imag = ((float *)ip1)[1];
+ y.real = ((float *)ip2)[0]; y.imag = ((float *)ip2)[1];
+ ((CdoubleBinaryFunc *)func)(&x, &y, &r);
+ ((float *)op)[0] = (float)r.real;
+ ((float *)op)[1] = (float)r.imag;
+ }
}
/*UFUNC_API*/
static void
PyUFunc_DD_D(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
- cdouble x,y,r;
-
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- x.real = ((double *)ip1)[0]; x.imag = ((double *)ip1)[1];
- y.real = ((double *)ip2)[0]; y.imag = ((double *)ip2)[1];
- ((CdoubleBinaryFunc *)func)(&x, &y, &r);
- ((double *)op)[0] = r.real;
- ((double *)op)[1] = r.imag;
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
+ cdouble x,y,r;
+
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ x.real = ((double *)ip1)[0]; x.imag = ((double *)ip1)[1];
+ y.real = ((double *)ip2)[0]; y.imag = ((double *)ip2)[1];
+ ((CdoubleBinaryFunc *)func)(&x, &y, &r);
+ ((double *)op)[0] = r.real;
+ ((double *)op)[1] = r.imag;
+ }
}
/*UFUNC_API*/
static void
PyUFunc_FF_F(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
- cfloat x,y,r;
-
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- x.real = ((float *)ip1)[0]; x.imag = ((float *)ip1)[1];
- y.real = ((float *)ip2)[0]; y.imag = ((float *)ip2)[1];
- ((CfloatBinaryFunc *)func)(&x, &y, &r);
- ((float *)op)[0] = r.real;
- ((float *)op)[1] = r.imag;
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
+ cfloat x,y,r;
+
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ x.real = ((float *)ip1)[0]; x.imag = ((float *)ip1)[1];
+ y.real = ((float *)ip2)[0]; y.imag = ((float *)ip2)[1];
+ ((CfloatBinaryFunc *)func)(&x, &y, &r);
+ ((float *)op)[0] = r.real;
+ ((float *)op)[1] = r.imag;
+ }
}
/*UFUNC_API*/
static void
PyUFunc_GG_G(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
- clongdouble x,y,r;
-
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- x.real = ((longdouble *)ip1)[0];
- x.imag = ((longdouble *)ip1)[1];
- y.real = ((longdouble *)ip2)[0];
- y.imag = ((longdouble *)ip2)[1];
- ((ClongdoubleBinaryFunc *)func)(&x, &y, &r);
- ((longdouble *)op)[0] = r.real;
- ((longdouble *)op)[1] = r.imag;
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
+ clongdouble x,y,r;
+
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ x.real = ((longdouble *)ip1)[0];
+ x.imag = ((longdouble *)ip1)[1];
+ y.real = ((longdouble *)ip2)[0];
+ y.imag = ((longdouble *)ip2)[1];
+ ((ClongdoubleBinaryFunc *)func)(&x, &y, &r);
+ ((longdouble *)op)[0] = r.real;
+ ((longdouble *)op)[1] = r.imag;
+ }
}
/*UFUNC_API*/
static void
PyUFunc_OO_O(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2], \
- n=dimensions[0];
- char *ip1=args[0], *ip2=args[1], *op=args[2];
- PyObject *tmp;
- PyObject *x1, *x2;
-
- for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
- x1 = *((PyObject **)ip1);
- x2 = *((PyObject **)ip2);
- if ((x1 == NULL) || (x2 == NULL)) goto done;
- if ( (void *) func == (void *) PyNumber_Power)
- tmp = ((ternaryfunc)func)(x1, x2, Py_None);
- else
- tmp = ((binaryfunc)func)(x1, x2);
- if (PyErr_Occurred()) goto done;
- Py_XDECREF(*((PyObject **)op));
- *((PyObject **)op) = tmp;
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2], \
+ n=dimensions[0];
+ char *ip1=args[0], *ip2=args[1], *op=args[2];
+ PyObject *tmp;
+ PyObject *x1, *x2;
+
+ for(i=0; i<n; i++, ip1+=is1, ip2+=is2, op+=os) {
+ x1 = *((PyObject **)ip1);
+ x2 = *((PyObject **)ip2);
+ if ((x1 == NULL) || (x2 == NULL)) goto done;
+ if ( (void *) func == (void *) PyNumber_Power)
+ tmp = ((ternaryfunc)func)(x1, x2, Py_None);
+ else
+ tmp = ((binaryfunc)func)(x1, x2);
+ if (PyErr_Occurred()) goto done;
+ Py_XDECREF(*((PyObject **)op));
+ *((PyObject **)op) = tmp;
+ }
done:
- return;
+ return;
}
/*UFUNC_API*/
@@ -238,47 +237,47 @@ typedef void ClongdoubleUnaryFunc(clongdouble *x, clongdouble *res);
static void
PyUFunc_f_f_As_d_d(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n=dimensions[0];
- char *ip1=args[0], *op=args[1];
- for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
- *(float *)op = (float)((DoubleUnaryFunc *)func)((double)*(float *)ip1);
- }
+ register intp i, n=dimensions[0];
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
+ *(float *)op = (float)((DoubleUnaryFunc *)func)((double)*(float *)ip1);
+ }
}
/*UFUNC_API*/
static void
PyUFunc_d_d(char **args, intp *dimensions, intp *steps, void *func)
{
- intp i;
- char *ip1=args[0], *op=args[1];
- for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
- *(double *)op = ((DoubleUnaryFunc *)func)(*(double *)ip1);
- }
+ intp i;
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
+ *(double *)op = ((DoubleUnaryFunc *)func)(*(double *)ip1);
+ }
}
/*UFUNC_API*/
static void
PyUFunc_f_f(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp n=dimensions[0];
- char *ip1=args[0], *op=args[1];
- for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
- *(float *)op = ((FloatUnaryFunc *)func)(*(float *)ip1);
- }
+ register intp i;
+ intp n=dimensions[0];
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
+ *(float *)op = ((FloatUnaryFunc *)func)(*(float *)ip1);
+ }
}
/*UFUNC_API*/
static void
PyUFunc_g_g(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp n=dimensions[0];
- char *ip1=args[0], *op=args[1];
- for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
- *(longdouble *)op = ((LongdoubleUnaryFunc *)func)\
- (*(longdouble *)ip1);
- }
+ register intp i;
+ intp n=dimensions[0];
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
+ *(longdouble *)op = ((LongdoubleUnaryFunc *)func)\
+ (*(longdouble *)ip1);
+ }
}
@@ -286,30 +285,30 @@ PyUFunc_g_g(char **args, intp *dimensions, intp *steps, void *func)
static void
PyUFunc_F_F_As_D_D(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i; cdouble x, res;
- intp n=dimensions[0];
- char *ip1=args[0], *op=args[1];
- for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
- x.real = ((float *)ip1)[0]; x.imag = ((float *)ip1)[1];
- ((CdoubleUnaryFunc *)func)(&x, &res);
- ((float *)op)[0] = (float)res.real;
- ((float *)op)[1] = (float)res.imag;
- }
+ register intp i; cdouble x, res;
+ intp n=dimensions[0];
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<n; i++, ip1+=steps[0], op+=steps[1]) {
+ x.real = ((float *)ip1)[0]; x.imag = ((float *)ip1)[1];
+ ((CdoubleUnaryFunc *)func)(&x, &res);
+ ((float *)op)[0] = (float)res.real;
+ ((float *)op)[1] = (float)res.imag;
+ }
}
/*UFUNC_API*/
static void
PyUFunc_F_F(char **args, intp *dimensions, intp *steps, void *func)
{
- intp i; cfloat x, res;
- char *ip1=args[0], *op=args[1];
- for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
- x.real = ((float *)ip1)[0];
- x.imag = ((float *)ip1)[1];
- ((CfloatUnaryFunc *)func)(&x, &res);
- ((float *)op)[0] = res.real;
- ((float *)op)[1] = res.imag;
- }
+ intp i; cfloat x, res;
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
+ x.real = ((float *)ip1)[0];
+ x.imag = ((float *)ip1)[1];
+ ((CfloatUnaryFunc *)func)(&x, &res);
+ ((float *)op)[0] = res.real;
+ ((float *)op)[1] = res.imag;
+ }
}
@@ -317,15 +316,15 @@ PyUFunc_F_F(char **args, intp *dimensions, intp *steps, void *func)
static void
PyUFunc_D_D(char **args, intp *dimensions, intp *steps, void *func)
{
- intp i; cdouble x, res;
- char *ip1=args[0], *op=args[1];
- for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
- x.real = ((double *)ip1)[0];
- x.imag = ((double *)ip1)[1];
- ((CdoubleUnaryFunc *)func)(&x, &res);
- ((double *)op)[0] = res.real;
- ((double *)op)[1] = res.imag;
- }
+ intp i; cdouble x, res;
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
+ x.real = ((double *)ip1)[0];
+ x.imag = ((double *)ip1)[1];
+ ((CdoubleUnaryFunc *)func)(&x, &res);
+ ((double *)op)[0] = res.real;
+ ((double *)op)[1] = res.imag;
+ }
}
@@ -333,68 +332,67 @@ PyUFunc_D_D(char **args, intp *dimensions, intp *steps, void *func)
static void
PyUFunc_G_G(char **args, intp *dimensions, intp *steps, void *func)
{
- intp i; clongdouble x, res;
- char *ip1=args[0], *op=args[1];
- for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
- x.real = ((longdouble *)ip1)[0];
- x.imag = ((longdouble *)ip1)[1];
- ((ClongdoubleUnaryFunc *)func)(&x, &res);
- ((double *)op)[0] = res.real;
- ((double *)op)[1] = res.imag;
- }
+ intp i; clongdouble x, res;
+ char *ip1=args[0], *op=args[1];
+ for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
+ x.real = ((longdouble *)ip1)[0];
+ x.imag = ((longdouble *)ip1)[1];
+ ((ClongdoubleUnaryFunc *)func)(&x, &res);
+ ((double *)op)[0] = res.real;
+ ((double *)op)[1] = res.imag;
+ }
}
/*UFUNC_API*/
static void
PyUFunc_O_O(char **args, intp *dimensions, intp *steps, void *func)
{
- intp i; PyObject *tmp, *x1;
- char *ip1=args[0], *op=args[1];
-
- for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
- x1 = *(PyObject **)ip1;
- if (x1 == NULL) goto done;
- tmp = ((unaryfunc)func)(x1);
- if ((tmp==NULL) || PyErr_Occurred()) goto done;
- Py_XDECREF(*((PyObject **)op));
- *((PyObject **)op) = tmp;
- }
+ intp i; PyObject *tmp, *x1;
+ char *ip1=args[0], *op=args[1];
+
+ for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
+ x1 = *(PyObject **)ip1;
+ if (x1 == NULL) goto done;
+ tmp = ((unaryfunc)func)(x1);
+ if ((tmp==NULL) || PyErr_Occurred()) goto done;
+ Py_XDECREF(*((PyObject **)op));
+ *((PyObject **)op) = tmp;
+ }
done:
- return;
+ return;
}
/*UFUNC_API*/
static void
PyUFunc_O_O_method(char **args, intp *dimensions, intp *steps, void *func)
{
- intp i; PyObject *tmp, *meth, *arglist, *x1;
- char *ip1=args[0], *op=args[1];
-
- for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
- x1 = *(PyObject **)ip1;
- if (x1 == NULL) goto done;
- meth = PyObject_GetAttrString(x1, (char *)func);
- if (meth != NULL) {
- arglist = PyTuple_New(0);
- if (arglist == NULL) {
- Py_DECREF(meth);
- goto done;
- }
- tmp = PyEval_CallObject(meth, arglist);
- Py_DECREF(arglist);
- Py_DECREF(meth);
- if ((tmp==NULL) || PyErr_Occurred()) goto done;
- Py_XDECREF(*((PyObject **)op));
- *((PyObject **)op) = tmp;
- }
- }
+ intp i; PyObject *tmp, *meth, *arglist, *x1;
+ char *ip1=args[0], *op=args[1];
+
+ for(i=0; i<*dimensions; i++, ip1+=steps[0], op+=steps[1]) {
+ x1 = *(PyObject **)ip1;
+ if (x1 == NULL) goto done;
+ meth = PyObject_GetAttrString(x1, (char *)func);
+ if (meth != NULL) {
+ arglist = PyTuple_New(0);
+ if (arglist == NULL) {
+ Py_DECREF(meth);
+ goto done;
+ }
+ tmp = PyEval_CallObject(meth, arglist);
+ Py_DECREF(arglist);
+ Py_DECREF(meth);
+ if ((tmp==NULL) || PyErr_Occurred()) goto done;
+ Py_XDECREF(*((PyObject **)op));
+ *((PyObject **)op) = tmp;
+ }
+ }
done:
- return;
+ return;
}
-
/* a general-purpose ufunc that deals with general-purpose Python callable.
func is a structure with nin, nout, and a Python callable function
*/
@@ -403,52 +401,52 @@ PyUFunc_O_O_method(char **args, intp *dimensions, intp *steps, void *func)
static void
PyUFunc_On_Om(char **args, intp *dimensions, intp *steps, void *func)
{
- intp i, j;
- intp n=dimensions[0];
- PyUFunc_PyFuncData *data = (PyUFunc_PyFuncData *)func;
- int nin = data->nin, nout=data->nout;
- int ntot;
- PyObject *tocall = data->callable;
- char *ptrs[NPY_MAXARGS];
- PyObject *arglist, *result;
- PyObject *in, **op;
-
- ntot = nin+nout;
-
- for (j=0; j < ntot; j++) ptrs[j] = args[j];
- for(i=0; i<n; i++) {
- arglist = PyTuple_New(nin);
- if (arglist == NULL) return;
- for (j=0; j < nin; j++) {
- in = *((PyObject **)ptrs[j]);
- if (in == NULL) {Py_DECREF(arglist); return;}
- PyTuple_SET_ITEM(arglist, j, in);
- Py_INCREF(in);
+ intp i, j;
+ intp n=dimensions[0];
+ PyUFunc_PyFuncData *data = (PyUFunc_PyFuncData *)func;
+ int nin = data->nin, nout=data->nout;
+ int ntot;
+ PyObject *tocall = data->callable;
+ char *ptrs[NPY_MAXARGS];
+ PyObject *arglist, *result;
+ PyObject *in, **op;
+
+ ntot = nin+nout;
+
+ for (j=0; j < ntot; j++) ptrs[j] = args[j];
+ for(i=0; i<n; i++) {
+ arglist = PyTuple_New(nin);
+ if (arglist == NULL) return;
+ for (j=0; j < nin; j++) {
+ in = *((PyObject **)ptrs[j]);
+ if (in == NULL) {Py_DECREF(arglist); return;}
+ PyTuple_SET_ITEM(arglist, j, in);
+ Py_INCREF(in);
+ }
+ result = PyEval_CallObject(tocall, arglist);
+ Py_DECREF(arglist);
+ if (result == NULL) return;
+ if PyTuple_Check(result) {
+ if (nout != PyTuple_Size(result)) {
+ Py_DECREF(result);
+ return;
}
- result = PyEval_CallObject(tocall, arglist);
- Py_DECREF(arglist);
- if (result == NULL) return;
- if PyTuple_Check(result) {
- if (nout != PyTuple_Size(result)) {
- Py_DECREF(result);
- return;
- }
- for (j=0; j < nout; j++) {
- op = (PyObject **)ptrs[j+nin];
- Py_XDECREF(*op);
- *op = PyTuple_GET_ITEM(result, j);
- Py_INCREF(*op);
- }
- Py_DECREF(result);
+ for (j=0; j < nout; j++) {
+ op = (PyObject **)ptrs[j+nin];
+ Py_XDECREF(*op);
+ *op = PyTuple_GET_ITEM(result, j);
+ Py_INCREF(*op);
}
- else {
- op = (PyObject **)ptrs[nin];
- Py_XDECREF(*op);
- *op = result;
- }
- for (j=0; j < ntot; j++) ptrs[j] += steps[j];
- }
- return;
+ Py_DECREF(result);
+ }
+ else {
+ op = (PyObject **)ptrs[nin];
+ Py_XDECREF(*op);
+ *op = result;
+ }
+ for (j=0; j < ntot; j++) ptrs[j] += steps[j];
+ }
+ return;
}
@@ -465,83 +463,83 @@ PyUFunc_On_Om(char **args, intp *dimensions, intp *steps, void *func)
/*
2. for each of the flags
- determine whether to ignore, warn, raise error, or call Python function.
- If ignore, do nothing
- If warn, print a warning and continue
- If raise return an error
- If call, call a user-defined function with string
+ determine whether to ignore, warn, raise error, or call Python function.
+ If ignore, do nothing
+ If warn, print a warning and continue
+ If raise return an error
+ If call, call a user-defined function with string
*/
static int
_error_handler(int method, PyObject *errobj, char *errtype, int retstatus, int *first)
{
- PyObject *pyfunc, *ret, *args;
- char *name=PyString_AS_STRING(PyTuple_GET_ITEM(errobj,0));
- char msg[100];
-
- ALLOW_C_API_DEF
-
- ALLOW_C_API
-
- switch(method) {
- case UFUNC_ERR_WARN:
- snprintf(msg, 100, "%s encountered in %s", errtype, name);
- if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0) goto fail;
- break;
- case UFUNC_ERR_RAISE:
- PyErr_Format(PyExc_FloatingPointError,
- "%s encountered in %s",
- errtype, name);
- goto fail;
- case UFUNC_ERR_CALL:
- pyfunc = PyTuple_GET_ITEM(errobj, 1);
-
- if (pyfunc == Py_None) {
- PyErr_Format(PyExc_NameError,
- "python callback specified for %s (in " \
- " %s) but no function found.",
- errtype, name);
- goto fail;
- }
- args = Py_BuildValue("NN", PyString_FromString(errtype),
- PyInt_FromLong((long) retstatus));
- if (args == NULL) goto fail;
- ret = PyObject_CallObject(pyfunc, args);
- Py_DECREF(args);
- if (ret == NULL) goto fail;
- Py_DECREF(ret);
-
- break;
+ PyObject *pyfunc, *ret, *args;
+ char *name=PyString_AS_STRING(PyTuple_GET_ITEM(errobj,0));
+ char msg[100];
+
+ ALLOW_C_API_DEF
+
+ ALLOW_C_API
+
+ switch(method) {
+ case UFUNC_ERR_WARN:
+ snprintf(msg, 100, "%s encountered in %s", errtype, name);
+ if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0) goto fail;
+ break;
+ case UFUNC_ERR_RAISE:
+ PyErr_Format(PyExc_FloatingPointError,
+ "%s encountered in %s",
+ errtype, name);
+ goto fail;
+ case UFUNC_ERR_CALL:
+ pyfunc = PyTuple_GET_ITEM(errobj, 1);
+
+ if (pyfunc == Py_None) {
+ PyErr_Format(PyExc_NameError,
+ "python callback specified for %s (in " \
+ " %s) but no function found.",
+ errtype, name);
+ goto fail;
+ }
+ args = Py_BuildValue("NN", PyString_FromString(errtype),
+ PyInt_FromLong((long) retstatus));
+ if (args == NULL) goto fail;
+ ret = PyObject_CallObject(pyfunc, args);
+ Py_DECREF(args);
+ if (ret == NULL) goto fail;
+ Py_DECREF(ret);
+
+ break;
case UFUNC_ERR_PRINT:
- if (*first) {
- fprintf(stderr, "Warning: %s encountered in %s\n", errtype, name);
- *first = 0;
- }
- break;
+ if (*first) {
+ fprintf(stderr, "Warning: %s encountered in %s\n", errtype, name);
+ *first = 0;
+ }
+ break;
case UFUNC_ERR_LOG:
- if (first) {
- *first = 0;
- pyfunc = PyTuple_GET_ITEM(errobj, 1);
- if (pyfunc == Py_None) {
- PyErr_Format(PyExc_NameError,
- "log specified for %s (in %s) but no " \
- "object with write method found.",
- errtype, name);
- goto fail;
- }
- snprintf(msg, 100, "Warning: %s encountered in %s\n", errtype, name);
- ret = PyObject_CallMethod(pyfunc, "write", "s", msg);
- if (ret == NULL) goto fail;
- Py_DECREF(ret);
+ if (first) {
+ *first = 0;
+ pyfunc = PyTuple_GET_ITEM(errobj, 1);
+ if (pyfunc == Py_None) {
+ PyErr_Format(PyExc_NameError,
+ "log specified for %s (in %s) but no " \
+ "object with write method found.",
+ errtype, name);
+ goto fail;
}
- break;
- }
- DISABLE_C_API
- return 0;
+ snprintf(msg, 100, "Warning: %s encountered in %s\n", errtype, name);
+ ret = PyObject_CallMethod(pyfunc, "write", "s", msg);
+ if (ret == NULL) goto fail;
+ Py_DECREF(ret);
+ }
+ break;
+ }
+ DISABLE_C_API
+ return 0;
fail:
- DISABLE_C_API
- return -1;
+ DISABLE_C_API
+ return -1;
}
@@ -549,31 +547,31 @@ _error_handler(int method, PyObject *errobj, char *errtype, int retstatus, int *
static int
PyUFunc_getfperr(void)
{
- int retstatus;
- UFUNC_CHECK_STATUS(retstatus);
- return retstatus;
+ int retstatus;
+ UFUNC_CHECK_STATUS(retstatus);
+ return retstatus;
}
-#define HANDLEIT(NAME, str) {if (retstatus & UFUNC_FPE_##NAME) { \
- handle = errmask & UFUNC_MASK_##NAME;\
- if (handle && \
- _error_handler(handle >> UFUNC_SHIFT_##NAME, \
- errobj, str, retstatus, first) < 0) \
- return -1; \
- }}
+#define HANDLEIT(NAME, str) {if (retstatus & UFUNC_FPE_##NAME) { \
+ handle = errmask & UFUNC_MASK_##NAME; \
+ if (handle && \
+ _error_handler(handle >> UFUNC_SHIFT_##NAME, \
+ errobj, str, retstatus, first) < 0) \
+ return -1; \
+ }}
/*UFUNC_API*/
static int
PyUFunc_handlefperr(int errmask, PyObject *errobj, int retstatus, int *first)
{
- int handle;
- if (errmask && retstatus) {
- HANDLEIT(DIVIDEBYZERO, "divide by zero");
- HANDLEIT(OVERFLOW, "overflow");
- HANDLEIT(UNDERFLOW, "underflow");
- HANDLEIT(INVALID, "invalid value");
- }
- return 0;
+ int handle;
+ if (errmask && retstatus) {
+ HANDLEIT(DIVIDEBYZERO, "divide by zero");
+ HANDLEIT(OVERFLOW, "overflow");
+ HANDLEIT(UNDERFLOW, "underflow");
+ HANDLEIT(INVALID, "invalid value");
+ }
+ return 0;
}
#undef HANDLEIT
@@ -583,11 +581,11 @@ PyUFunc_handlefperr(int errmask, PyObject *errobj, int retstatus, int *first)
static int
PyUFunc_checkfperr(int errmask, PyObject *errobj, int *first)
{
- int retstatus;
+ int retstatus;
- /* 1. check hardware flag --- this is platform dependent code */
- retstatus = PyUFunc_getfperr();
- return PyUFunc_handlefperr(errmask, errobj, retstatus, first);
+ /* 1. check hardware flag --- this is platform dependent code */
+ retstatus = PyUFunc_getfperr();
+ return PyUFunc_handlefperr(errmask, errobj, retstatus, first);
}
@@ -596,7 +594,7 @@ PyUFunc_checkfperr(int errmask, PyObject *errobj, int *first)
static void
PyUFunc_clearfperr()
{
- PyUFunc_getfperr();
+ PyUFunc_getfperr();
}
@@ -613,333 +611,333 @@ PyUFunc_clearfperr()
static char
_lowest_type(char intype)
{
- switch(intype) {
- /* case PyArray_BYTE */
- case PyArray_SHORT:
- case PyArray_INT:
- case PyArray_LONG:
- case PyArray_LONGLONG:
- return PyArray_BYTE;
- /* case PyArray_UBYTE */
- case PyArray_USHORT:
- case PyArray_UINT:
- case PyArray_ULONG:
- case PyArray_ULONGLONG:
- return PyArray_UBYTE;
- /* case PyArray_FLOAT:*/
- case PyArray_DOUBLE:
- case PyArray_LONGDOUBLE:
- return PyArray_FLOAT;
- /* case PyArray_CFLOAT:*/
- case PyArray_CDOUBLE:
- case PyArray_CLONGDOUBLE:
- return PyArray_CFLOAT;
- default:
- return intype;
- }
+ switch(intype) {
+ /* case PyArray_BYTE */
+ case PyArray_SHORT:
+ case PyArray_INT:
+ case PyArray_LONG:
+ case PyArray_LONGLONG:
+ return PyArray_BYTE;
+ /* case PyArray_UBYTE */
+ case PyArray_USHORT:
+ case PyArray_UINT:
+ case PyArray_ULONG:
+ case PyArray_ULONGLONG:
+ return PyArray_UBYTE;
+ /* case PyArray_FLOAT:*/
+ case PyArray_DOUBLE:
+ case PyArray_LONGDOUBLE:
+ return PyArray_FLOAT;
+ /* case PyArray_CFLOAT:*/
+ case PyArray_CDOUBLE:
+ case PyArray_CLONGDOUBLE:
+ return PyArray_CFLOAT;
+ default:
+ return intype;
+ }
}
static char *_types_msg = "function not supported for these types, " \
- "and can't coerce safely to supported types";
+ "and can't coerce safely to supported types";
-/* Called for non-NULL user-defined functions.
+/* Called for non-NULL user-defined functions.
The object should be a CObject pointing to a linked-list of functions
- storing the function, data, and signature of all user-defined functions.
- There must be a match with the input argument types or an error
- will occur.
- */
+ storing the function, data, and signature of all user-defined functions.
+ There must be a match with the input argument types or an error
+ will occur.
+*/
static int
-_find_matching_userloop(PyObject *obj, int *arg_types,
+_find_matching_userloop(PyObject *obj, int *arg_types,
PyArray_SCALARKIND *scalars,
- PyUFuncGenericFunction *function, void **data,
+ PyUFuncGenericFunction *function, void **data,
int nargs, int nin)
{
- PyUFunc_Loop1d *funcdata;
- int i;
- funcdata = (PyUFunc_Loop1d *)PyCObject_AsVoidPtr(obj);
- while (funcdata != NULL) {
- for (i=0; i<nin; i++) {
- if (!PyArray_CanCoerceScalar(arg_types[i],
- funcdata->arg_types[i],
- scalars[i]))
- break;
- }
- if (i==nin) { /* match found */
- *function = funcdata->func;
- *data = funcdata->data;
- /* Make sure actual arg_types supported
- by the loop are used */
- for (i=0; i<nargs; i++) {
- arg_types[i] = funcdata->arg_types[i];
- }
- return 0;
- }
- funcdata = funcdata->next;
- }
- PyErr_SetString(PyExc_TypeError, _types_msg);
- return -1;
+ PyUFunc_Loop1d *funcdata;
+ int i;
+ funcdata = (PyUFunc_Loop1d *)PyCObject_AsVoidPtr(obj);
+ while (funcdata != NULL) {
+ for (i=0; i<nin; i++) {
+ if (!PyArray_CanCoerceScalar(arg_types[i],
+ funcdata->arg_types[i],
+ scalars[i]))
+ break;
+ }
+ if (i==nin) { /* match found */
+ *function = funcdata->func;
+ *data = funcdata->data;
+ /* Make sure actual arg_types supported
+ by the loop are used */
+ for (i=0; i<nargs; i++) {
+ arg_types[i] = funcdata->arg_types[i];
+ }
+ return 0;
+ }
+ funcdata = funcdata->next;
+ }
+ PyErr_SetString(PyExc_TypeError, _types_msg);
+ return -1;
}
/* if only one type is specified then it is the "first" output data-type
- and the first signature matching this output data-type is returned.
-
+ and the first signature matching this output data-type is returned.
+
if a tuple of types is specified then an exact match to the signature
is searched and it much match exactly or an error occurs
*/
static int
-extract_specified_loop(PyUFuncObject *self, int *arg_types,
+extract_specified_loop(PyUFuncObject *self, int *arg_types,
PyUFuncGenericFunction *function, void **data,
PyObject *type_tup, int userdef)
{
- Py_ssize_t n=1;
- int *rtypenums;
- static char msg[] = "loop written to specified type(s) not found";
- PyArray_Descr *dtype;
- int nargs;
- int i, j;
- int strtype=0;
-
- nargs = self->nargs;
-
- if (PyTuple_Check(type_tup)) {
- n = PyTuple_GET_SIZE(type_tup);
- if (n != 1 && n != nargs) {
- PyErr_Format(PyExc_ValueError,
- "a type-tuple must be specified " \
- "of length 1 or %d for %s", nargs,
- self->name ? self->name : "(unknown)");
- return -1;
- }
+ Py_ssize_t n=1;
+ int *rtypenums;
+ static char msg[] = "loop written to specified type(s) not found";
+ PyArray_Descr *dtype;
+ int nargs;
+ int i, j;
+ int strtype=0;
+
+ nargs = self->nargs;
+
+ if (PyTuple_Check(type_tup)) {
+ n = PyTuple_GET_SIZE(type_tup);
+ if (n != 1 && n != nargs) {
+ PyErr_Format(PyExc_ValueError,
+ "a type-tuple must be specified " \
+ "of length 1 or %d for %s", nargs,
+ self->name ? self->name : "(unknown)");
+ return -1;
}
- else if PyString_Check(type_tup) {
- Py_ssize_t slen;
- char *thestr;
- slen = PyString_GET_SIZE(type_tup);
- thestr = PyString_AS_STRING(type_tup);
- for (i=0; i < slen-2; i++) {
- if (thestr[i] == '-' && thestr[i+1] == '>')
- break;
- }
- if (i < slen-2) {
- strtype = 1;
- n = slen-2;
- if (i != self->nin ||
- slen-2-i != self->nout) {
- PyErr_Format(PyExc_ValueError,
- "a type-string for %s, " \
- "requires %d typecode(s) before " \
- "and %d after the -> sign",
- self->name ? self->name : "(unknown)",
- self->nin, self->nout);
- return -1;
- }
+ }
+ else if PyString_Check(type_tup) {
+ Py_ssize_t slen;
+ char *thestr;
+ slen = PyString_GET_SIZE(type_tup);
+ thestr = PyString_AS_STRING(type_tup);
+ for (i=0; i < slen-2; i++) {
+ if (thestr[i] == '-' && thestr[i+1] == '>')
+ break;
+ }
+ if (i < slen-2) {
+ strtype = 1;
+ n = slen-2;
+ if (i != self->nin ||
+ slen-2-i != self->nout) {
+ PyErr_Format(PyExc_ValueError,
+ "a type-string for %s, " \
+ "requires %d typecode(s) before " \
+ "and %d after the -> sign",
+ self->name ? self->name : "(unknown)",
+ self->nin, self->nout);
+ return -1;
}
+ }
}
- rtypenums = (int *)_pya_malloc(n*sizeof(int));
- if (rtypenums==NULL) {
- PyErr_NoMemory();
- return -1;
+ rtypenums = (int *)_pya_malloc(n*sizeof(int));
+ if (rtypenums==NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ if (strtype) {
+ char *ptr;
+ ptr = PyString_AS_STRING(type_tup);
+ i = 0;
+ while (i < n) {
+ if (*ptr == '-' || *ptr == '>') {
+ ptr++;
+ continue;
+ }
+ dtype = PyArray_DescrFromType((int) *ptr);
+ if (dtype == NULL) goto fail;
+ rtypenums[i] = dtype->type_num;
+ Py_DECREF(dtype);
+ ptr++; i++;
}
-
- if (strtype) {
- char *ptr;
- ptr = PyString_AS_STRING(type_tup);
- i = 0;
- while (i < n) {
- if (*ptr == '-' || *ptr == '>') {
- ptr++;
- continue;
- }
- dtype = PyArray_DescrFromType((int) *ptr);
- if (dtype == NULL) goto fail;
- rtypenums[i] = dtype->type_num;
- Py_DECREF(dtype);
- ptr++; i++;
- }
+ }
+ else if (PyTuple_Check(type_tup)) {
+ for (i=0; i<n; i++) {
+ if (PyArray_DescrConverter(PyTuple_GET_ITEM \
+ (type_tup, i),
+ &dtype) == NPY_FAIL)
+ goto fail;
+ rtypenums[i] = dtype->type_num;
+ Py_DECREF(dtype);
}
- else if (PyTuple_Check(type_tup)) {
- for (i=0; i<n; i++) {
- if (PyArray_DescrConverter(PyTuple_GET_ITEM \
- (type_tup, i),
- &dtype) == NPY_FAIL)
- goto fail;
- rtypenums[i] = dtype->type_num;
- Py_DECREF(dtype);
- }
+ }
+ else {
+ if (PyArray_DescrConverter(type_tup, &dtype) == NPY_FAIL) {
+ goto fail;
}
- else {
- if (PyArray_DescrConverter(type_tup, &dtype) == NPY_FAIL) {
- goto fail;
+ rtypenums[0] = dtype->type_num;
+ Py_DECREF(dtype);
+ }
+
+ if (userdef > 0) { /* search in the user-defined functions */
+ PyObject *key, *obj;
+ PyUFunc_Loop1d *funcdata;
+ obj = NULL;
+ key = PyInt_FromLong((long) userdef);
+ if (key == NULL) goto fail;
+ obj = PyDict_GetItem(self->userloops, key);
+ Py_DECREF(key);
+ if (obj == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "user-defined type used in ufunc" \
+ " with no registered loops");
+ goto fail;
+ }
+ /* extract the correct function
+ data and argtypes
+ */
+ funcdata = (PyUFunc_Loop1d *)PyCObject_AsVoidPtr(obj);
+ while (funcdata != NULL) {
+ if (n != 1) {
+ for (i=0; i<nargs; i++) {
+ if (rtypenums[i] != funcdata->arg_types[i])
+ break;
}
- rtypenums[0] = dtype->type_num;
- Py_DECREF(dtype);
- }
-
- if (userdef > 0) { /* search in the user-defined functions */
- PyObject *key, *obj;
- PyUFunc_Loop1d *funcdata;
- obj = NULL;
- key = PyInt_FromLong((long) userdef);
- if (key == NULL) goto fail;
- obj = PyDict_GetItem(self->userloops, key);
- Py_DECREF(key);
- if (obj == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "user-defined type used in ufunc" \
- " with no registered loops");
- goto fail;
- }
- /* extract the correct function
- data and argtypes
- */
- funcdata = (PyUFunc_Loop1d *)PyCObject_AsVoidPtr(obj);
- while (funcdata != NULL) {
- if (n != 1) {
- for (i=0; i<nargs; i++) {
- if (rtypenums[i] != funcdata->arg_types[i])
- break;
- }
- }
- else if (rtypenums[0] == funcdata->arg_types[self->nin]) {
- i = nargs;
- }
- else i = -1;
- if (i == nargs) {
- *function = funcdata->func;
- *data = funcdata->data;
- for (i=0; i<nargs; i++) {
- arg_types[i] = funcdata->arg_types[i];
- }
- Py_DECREF(obj);
- goto finish;
- }
- funcdata = funcdata->next;
+ }
+ else if (rtypenums[0] == funcdata->arg_types[self->nin]) {
+ i = nargs;
+ }
+ else i = -1;
+ if (i == nargs) {
+ *function = funcdata->func;
+ *data = funcdata->data;
+ for (i=0; i<nargs; i++) {
+ arg_types[i] = funcdata->arg_types[i];
}
- PyErr_SetString(PyExc_TypeError, msg);
- goto fail;
+ Py_DECREF(obj);
+ goto finish;
+ }
+ funcdata = funcdata->next;
}
+ PyErr_SetString(PyExc_TypeError, msg);
+ goto fail;
+ }
- /* look for match in self->functions */
+ /* look for match in self->functions */
- for (j=0; j<self->ntypes; j++) {
- if (n != 1) {
- for (i=0; i<nargs; i++) {
- if (rtypenums[i] != self->types[j*nargs + i])
- break;
- }
- }
- else if (rtypenums[0] == self->types[j*nargs+self->nin]) {
- i = nargs;
- }
- else i = -1;
- if (i == nargs) {
- *function = self->functions[j];
- *data = self->data[j];
- for (i=0; i<nargs; i++) {
- arg_types[i] = self->types[j*nargs+i];
- }
- goto finish;
- }
+ for (j=0; j<self->ntypes; j++) {
+ if (n != 1) {
+ for (i=0; i<nargs; i++) {
+ if (rtypenums[i] != self->types[j*nargs + i])
+ break;
+ }
}
- PyErr_SetString(PyExc_TypeError, msg);
+ else if (rtypenums[0] == self->types[j*nargs+self->nin]) {
+ i = nargs;
+ }
+ else i = -1;
+ if (i == nargs) {
+ *function = self->functions[j];
+ *data = self->data[j];
+ for (i=0; i<nargs; i++) {
+ arg_types[i] = self->types[j*nargs+i];
+ }
+ goto finish;
+ }
+ }
+ PyErr_SetString(PyExc_TypeError, msg);
fail:
- _pya_free(rtypenums);
- return -1;
+ _pya_free(rtypenums);
+ return -1;
finish:
- _pya_free(rtypenums);
- return 0;
-
+ _pya_free(rtypenums);
+ return 0;
+
}
/* Called to determine coercion
- Can change arg_types.
- */
+ Can change arg_types.
+*/
static int
select_types(PyUFuncObject *self, int *arg_types,
PyUFuncGenericFunction *function, void **data,
- PyArray_SCALARKIND *scalars,
+ PyArray_SCALARKIND *scalars,
PyObject *typetup)
{
- int i, j;
- char start_type;
- int userdef=-1;
-
- if (self->userloops) {
- for (i=0; i<self->nin; i++) {
- if (PyTypeNum_ISUSERDEF(arg_types[i])) {
- userdef = arg_types[i];
- break;
- }
- }
- }
-
- if (typetup != NULL)
- return extract_specified_loop(self, arg_types, function, data,
- typetup, userdef);
-
- if (userdef > 0) {
- PyObject *key, *obj;
- int ret;
- obj = NULL;
- key = PyInt_FromLong((long) userdef);
- if (key == NULL) return -1;
- obj = PyDict_GetItem(self->userloops, key);
- Py_DECREF(key);
- if (obj == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "user-defined type used in ufunc" \
- " with no registered loops");
- return -1;
- }
- /* extract the correct function
- data and argtypes
- */
- ret = _find_matching_userloop(obj, arg_types, scalars,
- function, data, self->nargs,
- self->nin);
- return ret;
- }
-
- start_type = arg_types[0];
- /* If the first argument is a scalar we need to place
- the start type as the lowest type in the class
- */
- if (scalars[0] != PyArray_NOSCALAR) {
- start_type = _lowest_type(start_type);
- }
-
- i = 0;
- while (i<self->ntypes && start_type > self->types[i*self->nargs])
- i++;
-
- for(;i<self->ntypes; i++) {
- for(j=0; j<self->nin; j++) {
- if (!PyArray_CanCoerceScalar(arg_types[j],
- self->types[i*self->nargs+j],
- scalars[j]))
- break;
- }
- if (j == self->nin) break;
- }
- if(i>=self->ntypes) {
- PyErr_SetString(PyExc_TypeError, _types_msg);
- return -1;
- }
- for(j=0; j<self->nargs; j++)
- arg_types[j] = self->types[i*self->nargs+j];
-
- if (self->data)
- *data = self->data[i];
- else
- *data = NULL;
- *function = self->functions[i];
+ int i, j;
+ char start_type;
+ int userdef=-1;
+
+ if (self->userloops) {
+ for (i=0; i<self->nin; i++) {
+ if (PyTypeNum_ISUSERDEF(arg_types[i])) {
+ userdef = arg_types[i];
+ break;
+ }
+ }
+ }
+
+ if (typetup != NULL)
+ return extract_specified_loop(self, arg_types, function, data,
+ typetup, userdef);
+
+ if (userdef > 0) {
+ PyObject *key, *obj;
+ int ret;
+ obj = NULL;
+ key = PyInt_FromLong((long) userdef);
+ if (key == NULL) return -1;
+ obj = PyDict_GetItem(self->userloops, key);
+ Py_DECREF(key);
+ if (obj == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "user-defined type used in ufunc" \
+ " with no registered loops");
+ return -1;
+ }
+ /* extract the correct function
+ data and argtypes
+ */
+ ret = _find_matching_userloop(obj, arg_types, scalars,
+ function, data, self->nargs,
+ self->nin);
+ return ret;
+ }
+
+ start_type = arg_types[0];
+ /* If the first argument is a scalar we need to place
+ the start type as the lowest type in the class
+ */
+ if (scalars[0] != PyArray_NOSCALAR) {
+ start_type = _lowest_type(start_type);
+ }
+
+ i = 0;
+ while (i<self->ntypes && start_type > self->types[i*self->nargs])
+ i++;
+
+ for(;i<self->ntypes; i++) {
+ for(j=0; j<self->nin; j++) {
+ if (!PyArray_CanCoerceScalar(arg_types[j],
+ self->types[i*self->nargs+j],
+ scalars[j]))
+ break;
+ }
+ if (j == self->nin) break;
+ }
+ if(i>=self->ntypes) {
+ PyErr_SetString(PyExc_TypeError, _types_msg);
+ return -1;
+ }
+ for(j=0; j<self->nargs; j++)
+ arg_types[j] = self->types[i*self->nargs+j];
+
+ if (self->data)
+ *data = self->data[i];
+ else
+ *data = NULL;
+ *function = self->functions[i];
- return 0;
+ return 0;
}
#if USE_USE_DEFAULTS==1
@@ -949,60 +947,60 @@ static PyObject *PyUFunc_PYVALS_NAME=NULL;
static int
-_extract_pyvals(PyObject *ref, char *name, int *bufsize,
+_extract_pyvals(PyObject *ref, char *name, int *bufsize,
int *errmask, PyObject **errobj)
{
- PyObject *retval;
-
- *errobj = NULL;
- if (!PyList_Check(ref) || (PyList_GET_SIZE(ref)!=3)) {
- PyErr_Format(PyExc_TypeError, "%s must be a length 3 list.",
- UFUNC_PYVALS_NAME);
- return -1;
- }
-
- *bufsize = PyInt_AsLong(PyList_GET_ITEM(ref, 0));
- if ((*bufsize == -1) && PyErr_Occurred()) return -1;
- if ((*bufsize < PyArray_MIN_BUFSIZE) || \
- (*bufsize > PyArray_MAX_BUFSIZE) || \
- (*bufsize % 16 != 0)) {
- PyErr_Format(PyExc_ValueError,
- "buffer size (%d) is not in range "
- "(%"INTP_FMT" - %"INTP_FMT") or not a multiple of 16",
- *bufsize, (intp) PyArray_MIN_BUFSIZE,
- (intp) PyArray_MAX_BUFSIZE);
- return -1;
- }
-
- *errmask = PyInt_AsLong(PyList_GET_ITEM(ref, 1));
- if (*errmask < 0) {
- if (PyErr_Occurred()) return -1;
- PyErr_Format(PyExc_ValueError, \
- "invalid error mask (%d)",
- *errmask);
- return -1;
- }
-
- retval = PyList_GET_ITEM(ref, 2);
- if (retval != Py_None && !PyCallable_Check(retval)) {
- PyObject *temp;
- temp = PyObject_GetAttrString(retval, "write");
- if (temp == NULL || !PyCallable_Check(temp)) {
- PyErr_SetString(PyExc_TypeError,
- "python object must be callable or have " \
- "a callable write method");
- Py_XDECREF(temp);
- return -1;
- }
- Py_DECREF(temp);
- }
-
- *errobj = Py_BuildValue("NO",
- PyString_FromString(name),
- retval);
- if (*errobj == NULL) return -1;
+ PyObject *retval;
+
+ *errobj = NULL;
+ if (!PyList_Check(ref) || (PyList_GET_SIZE(ref)!=3)) {
+ PyErr_Format(PyExc_TypeError, "%s must be a length 3 list.",
+ UFUNC_PYVALS_NAME);
+ return -1;
+ }
+
+ *bufsize = PyInt_AsLong(PyList_GET_ITEM(ref, 0));
+ if ((*bufsize == -1) && PyErr_Occurred()) return -1;
+ if ((*bufsize < PyArray_MIN_BUFSIZE) || \
+ (*bufsize > PyArray_MAX_BUFSIZE) || \
+ (*bufsize % 16 != 0)) {
+ PyErr_Format(PyExc_ValueError,
+ "buffer size (%d) is not in range "
+ "(%"INTP_FMT" - %"INTP_FMT") or not a multiple of 16",
+ *bufsize, (intp) PyArray_MIN_BUFSIZE,
+ (intp) PyArray_MAX_BUFSIZE);
+ return -1;
+ }
+
+ *errmask = PyInt_AsLong(PyList_GET_ITEM(ref, 1));
+ if (*errmask < 0) {
+ if (PyErr_Occurred()) return -1;
+ PyErr_Format(PyExc_ValueError, \
+ "invalid error mask (%d)",
+ *errmask);
+ return -1;
+ }
+
+ retval = PyList_GET_ITEM(ref, 2);
+ if (retval != Py_None && !PyCallable_Check(retval)) {
+ PyObject *temp;
+ temp = PyObject_GetAttrString(retval, "write");
+ if (temp == NULL || !PyCallable_Check(temp)) {
+ PyErr_SetString(PyExc_TypeError,
+ "python object must be callable or have " \
+ "a callable write method");
+ Py_XDECREF(temp);
+ return -1;
+ }
+ Py_DECREF(temp);
+ }
+
+ *errobj = Py_BuildValue("NO",
+ PyString_FromString(name),
+ retval);
+ if (*errobj == NULL) return -1;
- return 0;
+ return 0;
}
@@ -1011,33 +1009,33 @@ _extract_pyvals(PyObject *ref, char *name, int *bufsize,
static int
PyUFunc_GetPyValues(char *name, int *bufsize, int *errmask, PyObject **errobj)
{
- PyObject *thedict;
- PyObject *ref=NULL;
-
- #if USE_USE_DEFAULTS==1
- if (PyUFunc_NUM_NODEFAULTS != 0) {
- #endif
- if (PyUFunc_PYVALS_NAME == NULL) {
- PyUFunc_PYVALS_NAME = \
- PyString_InternFromString(UFUNC_PYVALS_NAME);
- }
- thedict = PyThreadState_GetDict();
- if (thedict == NULL) {
- thedict = PyEval_GetBuiltins();
- }
- ref = PyDict_GetItem(thedict, PyUFunc_PYVALS_NAME);
- #if USE_USE_DEFAULTS==1
- }
- #endif
- if (ref == NULL) {
- *errmask = UFUNC_ERR_DEFAULT;
- *errobj = Py_BuildValue("NO",
- PyString_FromString(name),
- Py_None);
- *bufsize = PyArray_BUFSIZE;
- return 0;
- }
- return _extract_pyvals(ref, name, bufsize, errmask, errobj);
+ PyObject *thedict;
+ PyObject *ref=NULL;
+
+#if USE_USE_DEFAULTS==1
+ if (PyUFunc_NUM_NODEFAULTS != 0) {
+#endif
+ if (PyUFunc_PYVALS_NAME == NULL) {
+ PyUFunc_PYVALS_NAME = \
+ PyString_InternFromString(UFUNC_PYVALS_NAME);
+ }
+ thedict = PyThreadState_GetDict();
+ if (thedict == NULL) {
+ thedict = PyEval_GetBuiltins();
+ }
+ ref = PyDict_GetItem(thedict, PyUFunc_PYVALS_NAME);
+#if USE_USE_DEFAULTS==1
+ }
+#endif
+ if (ref == NULL) {
+ *errmask = UFUNC_ERR_DEFAULT;
+ *errobj = Py_BuildValue("NO",
+ PyString_FromString(name),
+ Py_None);
+ *bufsize = PyArray_BUFSIZE;
+ return 0;
+ }
+ return _extract_pyvals(ref, name, bufsize, errmask, errobj);
}
/* Create copies for any arrays that are less than loop->bufsize
@@ -1048,51 +1046,51 @@ PyUFunc_GetPyValues(char *name, int *bufsize, int *errmask, PyObject **errobj)
static int
_create_copies(PyUFuncLoopObject *loop, int *arg_types, PyArrayObject **mps)
{
- int nin = loop->ufunc->nin;
- int i;
- intp size;
- PyObject *new;
- PyArray_Descr *ntype;
- PyArray_Descr *atype;
-
- for (i=0; i<nin; i++) {
- size = PyArray_SIZE(mps[i]);
- /* if the type of mps[i] is equivalent to arg_types[i] */
- /* then set arg_types[i] equal to type of
- mps[i] for later checking....
- */
- if (PyArray_TYPE(mps[i]) != arg_types[i]) {
- ntype = mps[i]->descr;
- atype = PyArray_DescrFromType(arg_types[i]);
- if (PyArray_EquivTypes(atype, ntype)) {
- arg_types[i] = ntype->type_num;
- }
- Py_DECREF(atype);
- }
- if (size < loop->bufsize) {
- if (!(PyArray_ISBEHAVED_RO(mps[i])) || \
- PyArray_TYPE(mps[i]) != arg_types[i]) {
- ntype = PyArray_DescrFromType(arg_types[i]);
- new = PyArray_FromAny((PyObject *)mps[i],
- ntype, 0, 0,
- FORCECAST | ALIGNED, NULL);
- if (new == NULL) return -1;
- Py_DECREF(mps[i]);
- mps[i] = (PyArrayObject *)new;
- }
- }
- }
-
- return 0;
-}
-
-#define _GETATTR_(str, rstr) if (strcmp(name, #str) == 0) { \
- return PyObject_HasAttrString(op, "__" #rstr "__");}
+ int nin = loop->ufunc->nin;
+ int i;
+ intp size;
+ PyObject *new;
+ PyArray_Descr *ntype;
+ PyArray_Descr *atype;
+
+ for (i=0; i<nin; i++) {
+ size = PyArray_SIZE(mps[i]);
+ /* if the type of mps[i] is equivalent to arg_types[i] */
+ /* then set arg_types[i] equal to type of
+ mps[i] for later checking....
+ */
+ if (PyArray_TYPE(mps[i]) != arg_types[i]) {
+ ntype = mps[i]->descr;
+ atype = PyArray_DescrFromType(arg_types[i]);
+ if (PyArray_EquivTypes(atype, ntype)) {
+ arg_types[i] = ntype->type_num;
+ }
+ Py_DECREF(atype);
+ }
+ if (size < loop->bufsize) {
+ if (!(PyArray_ISBEHAVED_RO(mps[i])) || \
+ PyArray_TYPE(mps[i]) != arg_types[i]) {
+ ntype = PyArray_DescrFromType(arg_types[i]);
+ new = PyArray_FromAny((PyObject *)mps[i],
+ ntype, 0, 0,
+ FORCECAST | ALIGNED, NULL);
+ if (new == NULL) return -1;
+ Py_DECREF(mps[i]);
+ mps[i] = (PyArrayObject *)new;
+ }
+ }
+ }
+
+ return 0;
+}
+
+#define _GETATTR_(str, rstr) if (strcmp(name, #str) == 0) { \
+ return PyObject_HasAttrString(op, "__" #rstr "__");}
static int
_has_reflected_op(PyObject *op, char *name)
{
- _GETATTR_(add, radd)
+ _GETATTR_(add, radd)
_GETATTR_(subtract, rsub)
_GETATTR_(multiply, rmul)
_GETATTR_(divide, rdiv)
@@ -1114,611 +1112,611 @@ static Py_ssize_t
construct_arrays(PyUFuncLoopObject *loop, PyObject *args, PyArrayObject **mps,
PyObject *typetup)
{
- Py_ssize_t nargs;
- int i;
- int arg_types[NPY_MAXARGS];
- PyArray_SCALARKIND scalars[NPY_MAXARGS];
- PyArray_SCALARKIND maxarrkind, maxsckind, new;
- PyUFuncObject *self=loop->ufunc;
- Bool allscalars=TRUE;
- PyTypeObject *subtype=&PyArray_Type;
- PyObject *context=NULL;
- PyObject *obj;
- int flexible=0;
- int object=0;
-
- /* Check number of arguments */
- nargs = PyTuple_Size(args);
- if ((nargs < self->nin) || (nargs > self->nargs)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid number of arguments");
- return -1;
+ Py_ssize_t nargs;
+ int i;
+ int arg_types[NPY_MAXARGS];
+ PyArray_SCALARKIND scalars[NPY_MAXARGS];
+ PyArray_SCALARKIND maxarrkind, maxsckind, new;
+ PyUFuncObject *self=loop->ufunc;
+ Bool allscalars=TRUE;
+ PyTypeObject *subtype=&PyArray_Type;
+ PyObject *context=NULL;
+ PyObject *obj;
+ int flexible=0;
+ int object=0;
+
+ /* Check number of arguments */
+ nargs = PyTuple_Size(args);
+ if ((nargs < self->nin) || (nargs > self->nargs)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid number of arguments");
+ return -1;
+ }
+
+ /* Get each input argument */
+ maxarrkind = PyArray_NOSCALAR;
+ maxsckind = PyArray_NOSCALAR;
+ for (i=0; i<self->nin; i++) {
+ obj = PyTuple_GET_ITEM(args,i);
+ if (!PyArray_Check(obj) && !PyArray_IsScalar(obj, Generic)) {
+ context = Py_BuildValue("OOi", self, args, i);
+ }
+ else context = NULL;
+ mps[i] = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, 0, context);
+ Py_XDECREF(context);
+ if (mps[i] == NULL) return -1;
+ arg_types[i] = PyArray_TYPE(mps[i]);
+ if (!flexible && PyTypeNum_ISFLEXIBLE(arg_types[i])) {
+ flexible = 1;
+ }
+ if (!object && PyTypeNum_ISOBJECT(arg_types[i])) {
+ object = 1;
+ }
+ /*
+ fprintf(stderr, "array %d has reference %d\n", i,
+ (mps[i])->ob_refcnt);
+ */
+
+ /* Scalars are 0-dimensional arrays
+ at this point
+ */
+
+ /* We need to keep track of whether or not scalars
+ are mixed with arrays of different kinds.
+ */
+
+ if (mps[i]->nd > 0) {
+ scalars[i] = PyArray_NOSCALAR;
+ allscalars=FALSE;
+ new = PyArray_ScalarKind(arg_types[i], NULL);
+ maxarrkind = NPY_MAX(new, maxarrkind);
+ }
+ else {
+ scalars[i] = PyArray_ScalarKind(arg_types[i], &(mps[i]));
+ maxsckind = NPY_MAX(scalars[i], maxsckind);
}
+ }
- /* Get each input argument */
- maxarrkind = PyArray_NOSCALAR;
- maxsckind = PyArray_NOSCALAR;
+ if (flexible && !object) {
+ loop->notimplemented = 1;
+ return nargs;
+ }
+
+ /* If everything is a scalar, or scalars mixed with arrays of
+ different kinds of lesser types then use normal coercion rules */
+ if (allscalars || (maxsckind > maxarrkind)) {
for (i=0; i<self->nin; i++) {
- obj = PyTuple_GET_ITEM(args,i);
- if (!PyArray_Check(obj) && !PyArray_IsScalar(obj, Generic)) {
- context = Py_BuildValue("OOi", self, args, i);
- }
- else context = NULL;
- mps[i] = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, 0, context);
- Py_XDECREF(context);
- if (mps[i] == NULL) return -1;
- arg_types[i] = PyArray_TYPE(mps[i]);
- if (!flexible && PyTypeNum_ISFLEXIBLE(arg_types[i])) {
- flexible = 1;
- }
- if (!object && PyTypeNum_ISOBJECT(arg_types[i])) {
- object = 1;
- }
- /*
- fprintf(stderr, "array %d has reference %d\n", i,
- (mps[i])->ob_refcnt);
- */
-
- /* Scalars are 0-dimensional arrays
- at this point
- */
-
- /* We need to keep track of whether or not scalars
- are mixed with arrays of different kinds.
- */
-
- if (mps[i]->nd > 0) {
- scalars[i] = PyArray_NOSCALAR;
- allscalars=FALSE;
- new = PyArray_ScalarKind(arg_types[i], NULL);
- maxarrkind = NPY_MAX(new, maxarrkind);
- }
- else {
- scalars[i] = PyArray_ScalarKind(arg_types[i], &(mps[i]));
- maxsckind = NPY_MAX(scalars[i], maxsckind);
- }
+ scalars[i] = PyArray_NOSCALAR;
}
+ }
+
+ /* Select an appropriate function for these argument types. */
+ if (select_types(loop->ufunc, arg_types, &(loop->function),
+ &(loop->funcdata), scalars, typetup) == -1)
+ return -1;
- if (flexible && !object) {
- loop->notimplemented = 1;
- return nargs;
+ /* FAIL with NotImplemented if the other object has
+ the __r<op>__ method and has __array_priority__ as
+ an attribute (signalling it can handle ndarray's)
+ and is not already an ndarray
+ */
+ if ((arg_types[1] == PyArray_OBJECT) && \
+ (loop->ufunc->nin==2) && (loop->ufunc->nout == 1)) {
+ PyObject *_obj = PyTuple_GET_ITEM(args, 1);
+ if (!PyArray_CheckExact(_obj) && \
+ PyObject_HasAttrString(_obj, "__array_priority__") && \
+ _has_reflected_op(_obj, loop->ufunc->name)) {
+ loop->notimplemented = 1;
+ return nargs;
}
+ }
- /* If everything is a scalar, or scalars mixed with arrays of
- different kinds of lesser types then use normal coercion rules */
- if (allscalars || (maxsckind > maxarrkind)) {
- for (i=0; i<self->nin; i++) {
- scalars[i] = PyArray_NOSCALAR;
- }
- }
+ /* Create copies for some of the arrays if they are small
+ enough and not already contiguous */
+ if (_create_copies(loop, arg_types, mps) < 0) return -1;
- /* Select an appropriate function for these argument types. */
- if (select_types(loop->ufunc, arg_types, &(loop->function),
- &(loop->funcdata), scalars, typetup) == -1)
- return -1;
-
- /* FAIL with NotImplemented if the other object has
- the __r<op>__ method and has __array_priority__ as
- an attribute (signalling it can handle ndarray's)
- and is not already an ndarray
- */
- if ((arg_types[1] == PyArray_OBJECT) && \
- (loop->ufunc->nin==2) && (loop->ufunc->nout == 1)) {
- PyObject *_obj = PyTuple_GET_ITEM(args, 1);
- if (!PyArray_CheckExact(_obj) && \
- PyObject_HasAttrString(_obj, "__array_priority__") && \
- _has_reflected_op(_obj, loop->ufunc->name)) {
- loop->notimplemented = 1;
- return nargs;
- }
+ /* Create Iterators for the Inputs */
+ for (i=0; i<self->nin; i++) {
+ loop->iters[i] = (PyArrayIterObject *) \
+ PyArray_IterNew((PyObject *)mps[i]);
+ if (loop->iters[i] == NULL) return -1;
+ }
+
+ /* Broadcast the result */
+ loop->numiter = self->nin;
+ if (PyArray_Broadcast((PyArrayMultiIterObject *)loop) < 0)
+ return -1;
+
+ /* Get any return arguments */
+ for (i=self->nin; i<nargs; i++) {
+ mps[i] = (PyArrayObject *)PyTuple_GET_ITEM(args, i);
+ if (((PyObject *)mps[i])==Py_None) {
+ mps[i] = NULL;
+ continue;
+ }
+ Py_INCREF(mps[i]);
+ if (!PyArray_Check((PyObject *)mps[i])) {
+ PyObject *new;
+ if (PyArrayIter_Check(mps[i])) {
+ new = PyObject_CallMethod((PyObject *)mps[i],
+ "__array__", NULL);
+ Py_DECREF(mps[i]);
+ mps[i] = (PyArrayObject *)new;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "return arrays must be "\
+ "of ArrayType");
+ Py_DECREF(mps[i]);
+ mps[i] = NULL;
+ return -1;
+ }
}
+ if (mps[i]->nd != loop->nd ||
+ !PyArray_CompareLists(mps[i]->dimensions,
+ loop->dimensions, loop->nd)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid return array shape");
+ Py_DECREF(mps[i]);
+ mps[i] = NULL;
+ return -1;
+ }
+ if (!PyArray_ISWRITEABLE(mps[i])) {
+ PyErr_SetString(PyExc_ValueError,
+ "return array is not writeable");
+ Py_DECREF(mps[i]);
+ mps[i] = NULL;
+ return -1;
+ }
+ }
- /* Create copies for some of the arrays if they are small
- enough and not already contiguous */
- if (_create_copies(loop, arg_types, mps) < 0) return -1;
-
- /* Create Iterators for the Inputs */
- for (i=0; i<self->nin; i++) {
- loop->iters[i] = (PyArrayIterObject *) \
- PyArray_IterNew((PyObject *)mps[i]);
- if (loop->iters[i] == NULL) return -1;
- }
-
- /* Broadcast the result */
- loop->numiter = self->nin;
- if (PyArray_Broadcast((PyArrayMultiIterObject *)loop) < 0)
- return -1;
-
- /* Get any return arguments */
- for (i=self->nin; i<nargs; i++) {
- mps[i] = (PyArrayObject *)PyTuple_GET_ITEM(args, i);
- if (((PyObject *)mps[i])==Py_None) {
- mps[i] = NULL;
- continue;
- }
- Py_INCREF(mps[i]);
- if (!PyArray_Check((PyObject *)mps[i])) {
- PyObject *new;
- if (PyArrayIter_Check(mps[i])) {
- new = PyObject_CallMethod((PyObject *)mps[i],
- "__array__", NULL);
- Py_DECREF(mps[i]);
- mps[i] = (PyArrayObject *)new;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "return arrays must be "\
- "of ArrayType");
- Py_DECREF(mps[i]);
- mps[i] = NULL;
- return -1;
- }
- }
- if (mps[i]->nd != loop->nd ||
- !PyArray_CompareLists(mps[i]->dimensions,
- loop->dimensions, loop->nd)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid return array shape");
- Py_DECREF(mps[i]);
- mps[i] = NULL;
- return -1;
+ /* construct any missing return arrays and make output iterators */
+
+ for (i=self->nin; i<self->nargs; i++) {
+ PyArray_Descr *ntype;
+
+ if (mps[i] == NULL) {
+ mps[i] = (PyArrayObject *)PyArray_New(subtype,
+ loop->nd,
+ loop->dimensions,
+ arg_types[i],
+ NULL, NULL,
+ 0, 0, NULL);
+ if (mps[i] == NULL) return -1;
+ }
+
+ /* reset types for outputs that are equivalent
+ -- no sense casting uselessly
+ */
+ else {
+ if (mps[i]->descr->type_num != arg_types[i]) {
+ PyArray_Descr *atype;
+ ntype = mps[i]->descr;
+ atype = PyArray_DescrFromType(arg_types[i]);
+ if (PyArray_EquivTypes(atype, ntype)) {
+ arg_types[i] = ntype->type_num;
}
- if (!PyArray_ISWRITEABLE(mps[i])) {
- PyErr_SetString(PyExc_ValueError,
- "return array is not writeable");
- Py_DECREF(mps[i]);
- mps[i] = NULL;
- return -1;
+ Py_DECREF(atype);
+ }
+
+ /* still not the same -- or will we have to use buffers?*/
+ if (mps[i]->descr->type_num != arg_types[i] ||
+ !PyArray_ISBEHAVED_RO(mps[i])) {
+ if (loop->size < loop->bufsize) {
+ PyObject *new;
+ /* Copy the array to a temporary copy
+ and set the UPDATEIFCOPY flag
+ */
+ ntype = PyArray_DescrFromType(arg_types[i]);
+ new = PyArray_FromAny((PyObject *)mps[i],
+ ntype, 0, 0,
+ FORCECAST | ALIGNED |
+ UPDATEIFCOPY, NULL);
+ if (new == NULL) return -1;
+ Py_DECREF(mps[i]);
+ mps[i] = (PyArrayObject *)new;
}
+ }
}
- /* construct any missing return arrays and make output iterators */
+ loop->iters[i] = (PyArrayIterObject *) \
+ PyArray_IterNew((PyObject *)mps[i]);
+ if (loop->iters[i] == NULL) return -1;
+ }
- for (i=self->nin; i<self->nargs; i++) {
- PyArray_Descr *ntype;
- if (mps[i] == NULL) {
- mps[i] = (PyArrayObject *)PyArray_New(subtype,
- loop->nd,
- loop->dimensions,
- arg_types[i],
- NULL, NULL,
- 0, 0, NULL);
- if (mps[i] == NULL) return -1;
- }
+ /* If any of different type, or misaligned or swapped
+ then must use buffers */
- /* reset types for outputs that are equivalent
- -- no sense casting uselessly
- */
- else {
- if (mps[i]->descr->type_num != arg_types[i]) {
- PyArray_Descr *atype;
- ntype = mps[i]->descr;
- atype = PyArray_DescrFromType(arg_types[i]);
- if (PyArray_EquivTypes(atype, ntype)) {
- arg_types[i] = ntype->type_num;
- }
- Py_DECREF(atype);
- }
-
- /* still not the same -- or will we have to use buffers?*/
- if (mps[i]->descr->type_num != arg_types[i] ||
- !PyArray_ISBEHAVED_RO(mps[i])) {
- if (loop->size < loop->bufsize) {
- PyObject *new;
- /* Copy the array to a temporary copy
- and set the UPDATEIFCOPY flag
- */
- ntype = PyArray_DescrFromType(arg_types[i]);
- new = PyArray_FromAny((PyObject *)mps[i],
- ntype, 0, 0,
- FORCECAST | ALIGNED |
- UPDATEIFCOPY, NULL);
- if (new == NULL) return -1;
- Py_DECREF(mps[i]);
- mps[i] = (PyArrayObject *)new;
- }
- }
- }
-
- loop->iters[i] = (PyArrayIterObject *) \
- PyArray_IterNew((PyObject *)mps[i]);
- if (loop->iters[i] == NULL) return -1;
- }
-
-
- /* If any of different type, or misaligned or swapped
- then must use buffers */
-
- loop->bufcnt = 0;
- loop->obj = 0;
+ loop->bufcnt = 0;
+ loop->obj = 0;
- /* Determine looping method needed */
- loop->meth = NO_UFUNCLOOP;
+ /* Determine looping method needed */
+ loop->meth = NO_UFUNCLOOP;
- if (loop->size == 0) return nargs;
+ if (loop->size == 0) return nargs;
- for (i=0; i<self->nargs; i++) {
- loop->needbuffer[i] = 0;
- if (arg_types[i] != mps[i]->descr->type_num ||
- !PyArray_ISBEHAVED_RO(mps[i])) {
- loop->meth = BUFFER_UFUNCLOOP;
- loop->needbuffer[i] = 1;
- }
- if (!loop->obj && mps[i]->descr->type_num == PyArray_OBJECT) {
- loop->obj = 1;
- }
+ for (i=0; i<self->nargs; i++) {
+ loop->needbuffer[i] = 0;
+ if (arg_types[i] != mps[i]->descr->type_num ||
+ !PyArray_ISBEHAVED_RO(mps[i])) {
+ loop->meth = BUFFER_UFUNCLOOP;
+ loop->needbuffer[i] = 1;
+ }
+ if (!loop->obj && mps[i]->descr->type_num == PyArray_OBJECT) {
+ loop->obj = 1;
}
+ }
- if (loop->meth == NO_UFUNCLOOP) {
+ if (loop->meth == NO_UFUNCLOOP) {
- loop->meth = ONE_UFUNCLOOP;
+ loop->meth = ONE_UFUNCLOOP;
- /* All correct type and BEHAVED */
- /* Check for non-uniform stridedness */
+ /* All correct type and BEHAVED */
+ /* Check for non-uniform stridedness */
- for (i=0; i<self->nargs; i++) {
- if (!(loop->iters[i]->contiguous)) {
- /* may still have uniform stride
- if (broadcated result) <= 1-d */
- if (mps[i]->nd != 0 && \
- (loop->iters[i]->nd_m1 > 0)) {
- loop->meth = NOBUFFER_UFUNCLOOP;
- break;
- }
- }
+ for (i=0; i<self->nargs; i++) {
+ if (!(loop->iters[i]->contiguous)) {
+ /* may still have uniform stride
+ if (broadcated result) <= 1-d */
+ if (mps[i]->nd != 0 && \
+ (loop->iters[i]->nd_m1 > 0)) {
+ loop->meth = NOBUFFER_UFUNCLOOP;
+ break;
}
- if (loop->meth == ONE_UFUNCLOOP) {
- for (i=0; i<self->nargs; i++) {
- loop->bufptr[i] = mps[i]->data;
- }
- }
- }
-
- loop->numiter = self->nargs;
-
- /* Fill in steps */
- if (loop->meth != ONE_UFUNCLOOP) {
- int ldim;
- intp minsum;
- intp maxdim;
- PyArrayIterObject *it;
- intp stride_sum[NPY_MAXDIMS];
- int j;
-
- /* Fix iterators */
-
- /* Optimize axis the iteration takes place over
-
- The first thought was to have the loop go
- over the largest dimension to minimize the number of loops
-
- However, on processors with slow memory bus and cache,
- the slowest loops occur when the memory access occurs for
- large strides.
-
- Thus, choose the axis for which strides of the last iterator is
- smallest but non-zero.
- */
-
- for (i=0; i<loop->nd; i++) {
- stride_sum[i] = 0;
- for (j=0; j<loop->numiter; j++) {
- stride_sum[i] += loop->iters[j]->strides[i];
- }
- }
-
- ldim = loop->nd - 1;
- minsum = stride_sum[loop->nd-1];
- for (i=loop->nd - 2; i>=0; i--) {
- if (stride_sum[i] < minsum ) {
- ldim = i;
- minsum = stride_sum[i];
- }
- }
-
- maxdim = loop->dimensions[ldim];
- loop->size /= maxdim;
- loop->bufcnt = maxdim;
- loop->lastdim = ldim;
-
- /* Fix the iterators so the inner loop occurs over the
- largest dimensions -- This can be done by
- setting the size to 1 in that dimension
- (just in the iterators)
- */
-
- for (i=0; i<loop->numiter; i++) {
- it = loop->iters[i];
- it->contiguous = 0;
- it->size /= (it->dims_m1[ldim]+1);
- it->dims_m1[ldim] = 0;
- it->backstrides[ldim] = 0;
-
- /* (won't fix factors because we
- don't use PyArray_ITER_GOTO1D
- so don't change them) */
-
- /* Set the steps to the strides in that dimension */
- loop->steps[i] = it->strides[ldim];
- }
-
- /* fix up steps where we will be copying data to
- buffers and calculate the ninnerloops and leftover
- values -- if step size is already zero that is not changed...
- */
- if (loop->meth == BUFFER_UFUNCLOOP) {
- loop->leftover = maxdim % loop->bufsize;
- loop->ninnerloops = (maxdim / loop->bufsize) + 1;
- for (i=0; i<self->nargs; i++) {
- if (loop->needbuffer[i] && loop->steps[i]) {
- loop->steps[i] = mps[i]->descr->elsize;
- }
- /* These are changed later if casting is needed */
- }
- }
- }
- else { /* uniformly-strided case ONE_UFUNCLOOP */
- for (i=0; i<self->nargs; i++) {
- if (PyArray_SIZE(mps[i]) == 1)
- loop->steps[i] = 0;
- else
- loop->steps[i] = mps[i]->strides[mps[i]->nd-1];
- }
- }
-
-
- /* Finally, create memory for buffers if we need them */
-
- /* buffers for scalars are specially made small -- scalars are
- not copied multiple times */
- if (loop->meth == BUFFER_UFUNCLOOP) {
- int cnt = 0, cntcast = 0; /* keeps track of bytes to allocate */
- int scnt = 0, scntcast = 0;
- char *castptr;
- char *bufptr;
- int last_was_scalar=0;
- int last_cast_was_scalar=0;
- int oldbufsize=0;
- int oldsize=0;
- int scbufsize = 4*sizeof(double);
- int memsize;
- PyArray_Descr *descr;
+ }
+ }
+ if (loop->meth == ONE_UFUNCLOOP) {
+ for (i=0; i<self->nargs; i++) {
+ loop->bufptr[i] = mps[i]->data;
+ }
+ }
+ }
- /* compute the element size */
- for (i=0; i<self->nargs;i++) {
- if (!loop->needbuffer) continue;
- if (arg_types[i] != mps[i]->descr->type_num) {
- descr = PyArray_DescrFromType(arg_types[i]);
- if (loop->steps[i])
- cntcast += descr->elsize;
- else
- scntcast += descr->elsize;
- if (i < self->nin) {
- loop->cast[i] = \
- PyArray_GetCastFunc(mps[i]->descr,
- arg_types[i]);
- }
- else {
- loop->cast[i] = PyArray_GetCastFunc \
- (descr, mps[i]->descr->type_num);
- }
- Py_DECREF(descr);
- if (!loop->cast[i]) return -1;
- }
- loop->swap[i] = !(PyArray_ISNOTSWAPPED(mps[i]));
- if (loop->steps[i])
- cnt += mps[i]->descr->elsize;
- else
- scnt += mps[i]->descr->elsize;
- }
- memsize = loop->bufsize*(cnt+cntcast) + scbufsize*(scnt+scntcast);
- loop->buffer[0] = PyDataMem_NEW(memsize);
-
- /* fprintf(stderr, "Allocated buffer at %p of size %d, cnt=%d, cntcast=%d\n", loop->buffer[0], loop->bufsize * (cnt + cntcast), cnt, cntcast); */
-
- if (loop->buffer[0] == NULL) {PyErr_NoMemory(); return -1;}
- if (loop->obj) memset(loop->buffer[0], 0, memsize);
- castptr = loop->buffer[0] + loop->bufsize*cnt + scbufsize*scnt;
- bufptr = loop->buffer[0];
- loop->objfunc = 0;
- for (i=0; i<self->nargs; i++) {
- if (!loop->needbuffer[i]) continue;
- loop->buffer[i] = bufptr + (last_was_scalar ? scbufsize : \
- loop->bufsize)*oldbufsize;
- last_was_scalar = (loop->steps[i] == 0);
- bufptr = loop->buffer[i];
- oldbufsize = mps[i]->descr->elsize;
- /* fprintf(stderr, "buffer[%d] = %p\n", i, loop->buffer[i]); */
- if (loop->cast[i]) {
- PyArray_Descr *descr;
- loop->castbuf[i] = castptr + (last_cast_was_scalar ? scbufsize : \
- loop->bufsize)*oldsize;
- last_cast_was_scalar = last_was_scalar;
- /* fprintf(stderr, "castbuf[%d] = %p\n", i, loop->castbuf[i]); */
- descr = PyArray_DescrFromType(arg_types[i]);
- oldsize = descr->elsize;
- Py_DECREF(descr);
- loop->bufptr[i] = loop->castbuf[i];
- castptr = loop->castbuf[i];
- if (loop->steps[i])
- loop->steps[i] = oldsize;
- }
- else {
- loop->bufptr[i] = loop->buffer[i];
- }
- if (!loop->objfunc && loop->obj) {
- if (arg_types[i] == PyArray_OBJECT) {
- loop->objfunc = 1;
- }
- }
- }
- }
- return nargs;
-}
+ loop->numiter = self->nargs;
-static void
-ufuncreduce_dealloc(PyUFuncReduceObject *self)
-{
- if (self->ufunc) {
- Py_XDECREF(self->it);
- Py_XDECREF(self->rit);
- Py_XDECREF(self->ret);
- Py_XDECREF(self->errobj);
- Py_XDECREF(self->decref);
- if (self->buffer) PyDataMem_FREE(self->buffer);
- Py_DECREF(self->ufunc);
- }
- _pya_free(self);
-}
+ /* Fill in steps */
+ if (loop->meth != ONE_UFUNCLOOP) {
+ int ldim;
+ intp minsum;
+ intp maxdim;
+ PyArrayIterObject *it;
+ intp stride_sum[NPY_MAXDIMS];
+ int j;
-static void
-ufuncloop_dealloc(PyUFuncLoopObject *self)
-{
- int i;
+ /* Fix iterators */
- if (self->ufunc != NULL) {
- for (i=0; i<self->ufunc->nargs; i++)
- Py_XDECREF(self->iters[i]);
- if (self->buffer[0]) PyDataMem_FREE(self->buffer[0]);
- Py_XDECREF(self->errobj);
- Py_DECREF(self->ufunc);
- }
- _pya_free(self);
-}
+ /* Optimize axis the iteration takes place over
-static PyUFuncLoopObject *
-construct_loop(PyUFuncObject *self, PyObject *args, PyObject *kwds, PyArrayObject **mps)
-{
- PyUFuncLoopObject *loop;
- int i;
- PyObject *typetup=NULL;
- PyObject *extobj=NULL;
- char *name;
+ The first thought was to have the loop go
+ over the largest dimension to minimize the number of loops
+
+ However, on processors with slow memory bus and cache,
+ the slowest loops occur when the memory access occurs for
+ large strides.
+
+ Thus, choose the axis for which strides of the last iterator is
+ smallest but non-zero.
+ */
- if (self == NULL) {
- PyErr_SetString(PyExc_ValueError, "function not supported");
- return NULL;
- }
- if ((loop = _pya_malloc(sizeof(PyUFuncLoopObject)))==NULL) {
- PyErr_NoMemory(); return loop;
+ for (i=0; i<loop->nd; i++) {
+ stride_sum[i] = 0;
+ for (j=0; j<loop->numiter; j++) {
+ stride_sum[i] += loop->iters[j]->strides[i];
+ }
}
- loop->index = 0;
- loop->ufunc = self;
- Py_INCREF(self);
- loop->buffer[0] = NULL;
- for (i=0; i<self->nargs; i++) {
- loop->iters[i] = NULL;
- loop->cast[i] = NULL;
+ ldim = loop->nd - 1;
+ minsum = stride_sum[loop->nd-1];
+ for (i=loop->nd - 2; i>=0; i--) {
+ if (stride_sum[i] < minsum ) {
+ ldim = i;
+ minsum = stride_sum[i];
+ }
}
- loop->errobj = NULL;
- loop->notimplemented = 0;
- loop->first = 1;
- name = self->name ? self->name : "";
+ maxdim = loop->dimensions[ldim];
+ loop->size /= maxdim;
+ loop->bufcnt = maxdim;
+ loop->lastdim = ldim;
- /* Extract sig= keyword and
- extobj= keyword if present
- Raise an error if anything else present in the keyword dictionary
+ /* Fix the iterators so the inner loop occurs over the
+ largest dimensions -- This can be done by
+ setting the size to 1 in that dimension
+ (just in the iterators)
*/
- if (kwds != NULL) {
- PyObject *key, *value;
- Py_ssize_t pos=0;
- while (PyDict_Next(kwds, &pos, &key, &value)) {
- if (!PyString_Check(key)) {
- PyErr_SetString(PyExc_TypeError,
- "invalid keyword");
- goto fail;
- }
- if (strncmp(PyString_AS_STRING(key),"extobj",6) == 0) {
- extobj = value;
- }
- else if (strncmp(PyString_AS_STRING(key),"sig",5)==0) {
- typetup = value;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "'%s' is an invalid keyword " \
- "to %s",
- PyString_AS_STRING(key), name);
- goto fail;
- }
- }
+
+ for (i=0; i<loop->numiter; i++) {
+ it = loop->iters[i];
+ it->contiguous = 0;
+ it->size /= (it->dims_m1[ldim]+1);
+ it->dims_m1[ldim] = 0;
+ it->backstrides[ldim] = 0;
+
+ /* (won't fix factors because we
+ don't use PyArray_ITER_GOTO1D
+ so don't change them) */
+
+ /* Set the steps to the strides in that dimension */
+ loop->steps[i] = it->strides[ldim];
}
- if (extobj == NULL) {
- if (PyUFunc_GetPyValues(name,
- &(loop->bufsize), &(loop->errormask),
- &(loop->errobj)) < 0) goto fail;
+ /* fix up steps where we will be copying data to
+ buffers and calculate the ninnerloops and leftover
+ values -- if step size is already zero that is not changed...
+ */
+ if (loop->meth == BUFFER_UFUNCLOOP) {
+ loop->leftover = maxdim % loop->bufsize;
+ loop->ninnerloops = (maxdim / loop->bufsize) + 1;
+ for (i=0; i<self->nargs; i++) {
+ if (loop->needbuffer[i] && loop->steps[i]) {
+ loop->steps[i] = mps[i]->descr->elsize;
+ }
+ /* These are changed later if casting is needed */
+ }
}
- else {
- if (_extract_pyvals(extobj, name,
- &(loop->bufsize), &(loop->errormask),
- &(loop->errobj)) < 0) goto fail;
+ }
+ else { /* uniformly-strided case ONE_UFUNCLOOP */
+ for (i=0; i<self->nargs; i++) {
+ if (PyArray_SIZE(mps[i]) == 1)
+ loop->steps[i] = 0;
+ else
+ loop->steps[i] = mps[i]->strides[mps[i]->nd-1];
}
-
- /* Setup the arrays */
- if (construct_arrays(loop, args, mps, typetup) < 0) goto fail;
+ }
- PyUFunc_clearfperr();
- return loop;
+ /* Finally, create memory for buffers if we need them */
+
+ /* buffers for scalars are specially made small -- scalars are
+ not copied multiple times */
+ if (loop->meth == BUFFER_UFUNCLOOP) {
+ int cnt = 0, cntcast = 0; /* keeps track of bytes to allocate */
+ int scnt = 0, scntcast = 0;
+ char *castptr;
+ char *bufptr;
+ int last_was_scalar=0;
+ int last_cast_was_scalar=0;
+ int oldbufsize=0;
+ int oldsize=0;
+ int scbufsize = 4*sizeof(double);
+ int memsize;
+ PyArray_Descr *descr;
+
+ /* compute the element size */
+ for (i=0; i<self->nargs;i++) {
+ if (!loop->needbuffer) continue;
+ if (arg_types[i] != mps[i]->descr->type_num) {
+ descr = PyArray_DescrFromType(arg_types[i]);
+ if (loop->steps[i])
+ cntcast += descr->elsize;
+ else
+ scntcast += descr->elsize;
+ if (i < self->nin) {
+ loop->cast[i] = \
+ PyArray_GetCastFunc(mps[i]->descr,
+ arg_types[i]);
+ }
+ else {
+ loop->cast[i] = PyArray_GetCastFunc \
+ (descr, mps[i]->descr->type_num);
+ }
+ Py_DECREF(descr);
+ if (!loop->cast[i]) return -1;
+ }
+ loop->swap[i] = !(PyArray_ISNOTSWAPPED(mps[i]));
+ if (loop->steps[i])
+ cnt += mps[i]->descr->elsize;
+ else
+ scnt += mps[i]->descr->elsize;
+ }
+ memsize = loop->bufsize*(cnt+cntcast) + scbufsize*(scnt+scntcast);
+ loop->buffer[0] = PyDataMem_NEW(memsize);
- fail:
- ufuncloop_dealloc(loop);
- return NULL;
-}
+ /* fprintf(stderr, "Allocated buffer at %p of size %d, cnt=%d, cntcast=%d\n", loop->buffer[0], loop->bufsize * (cnt + cntcast), cnt, cntcast); */
+ if (loop->buffer[0] == NULL) {PyErr_NoMemory(); return -1;}
+ if (loop->obj) memset(loop->buffer[0], 0, memsize);
+ castptr = loop->buffer[0] + loop->bufsize*cnt + scbufsize*scnt;
+ bufptr = loop->buffer[0];
+ loop->objfunc = 0;
+ for (i=0; i<self->nargs; i++) {
+ if (!loop->needbuffer[i]) continue;
+ loop->buffer[i] = bufptr + (last_was_scalar ? scbufsize : \
+ loop->bufsize)*oldbufsize;
+ last_was_scalar = (loop->steps[i] == 0);
+ bufptr = loop->buffer[i];
+ oldbufsize = mps[i]->descr->elsize;
+ /* fprintf(stderr, "buffer[%d] = %p\n", i, loop->buffer[i]); */
+ if (loop->cast[i]) {
+ PyArray_Descr *descr;
+ loop->castbuf[i] = castptr + (last_cast_was_scalar ? scbufsize : \
+ loop->bufsize)*oldsize;
+ last_cast_was_scalar = last_was_scalar;
+ /* fprintf(stderr, "castbuf[%d] = %p\n", i, loop->castbuf[i]); */
+ descr = PyArray_DescrFromType(arg_types[i]);
+ oldsize = descr->elsize;
+ Py_DECREF(descr);
+ loop->bufptr[i] = loop->castbuf[i];
+ castptr = loop->castbuf[i];
+ if (loop->steps[i])
+ loop->steps[i] = oldsize;
+ }
+ else {
+ loop->bufptr[i] = loop->buffer[i];
+ }
+ if (!loop->objfunc && loop->obj) {
+ if (arg_types[i] == PyArray_OBJECT) {
+ loop->objfunc = 1;
+ }
+ }
+ }
+ }
+ return nargs;
+}
-/*
static void
-_printbytebuf(PyUFuncLoopObject *loop, int bufnum)
+ufuncreduce_dealloc(PyUFuncReduceObject *self)
{
- int i;
-
- fprintf(stderr, "Printing byte buffer %d\n", bufnum);
- for (i=0; i<loop->bufcnt; i++) {
- fprintf(stderr, " %d\n", *(((byte *)(loop->buffer[bufnum]))+i));
- }
+ if (self->ufunc) {
+ Py_XDECREF(self->it);
+ Py_XDECREF(self->rit);
+ Py_XDECREF(self->ret);
+ Py_XDECREF(self->errobj);
+ Py_XDECREF(self->decref);
+ if (self->buffer) PyDataMem_FREE(self->buffer);
+ Py_DECREF(self->ufunc);
+ }
+ _pya_free(self);
}
static void
-_printlongbuf(PyUFuncLoopObject *loop, int bufnum)
+ufuncloop_dealloc(PyUFuncLoopObject *self)
{
- int i;
+ int i;
- fprintf(stderr, "Printing long buffer %d\n", bufnum);
- for (i=0; i<loop->bufcnt; i++) {
- fprintf(stderr, " %ld\n", *(((long *)(loop->buffer[bufnum]))+i));
- }
+ if (self->ufunc != NULL) {
+ for (i=0; i<self->ufunc->nargs; i++)
+ Py_XDECREF(self->iters[i]);
+ if (self->buffer[0]) PyDataMem_FREE(self->buffer[0]);
+ Py_XDECREF(self->errobj);
+ Py_DECREF(self->ufunc);
+ }
+ _pya_free(self);
}
-static void
-_printlongbufptr(PyUFuncLoopObject *loop, int bufnum)
+static PyUFuncLoopObject *
+construct_loop(PyUFuncObject *self, PyObject *args, PyObject *kwds, PyArrayObject **mps)
{
- int i;
+ PyUFuncLoopObject *loop;
+ int i;
+ PyObject *typetup=NULL;
+ PyObject *extobj=NULL;
+ char *name;
- fprintf(stderr, "Printing long buffer %d\n", bufnum);
- for (i=0; i<loop->bufcnt; i++) {
- fprintf(stderr, " %ld\n", *(((long *)(loop->bufptr[bufnum]))+i));
- }
-}
+ if (self == NULL) {
+ PyErr_SetString(PyExc_ValueError, "function not supported");
+ return NULL;
+ }
+ if ((loop = _pya_malloc(sizeof(PyUFuncLoopObject)))==NULL) {
+ PyErr_NoMemory(); return loop;
+ }
+
+ loop->index = 0;
+ loop->ufunc = self;
+ Py_INCREF(self);
+ loop->buffer[0] = NULL;
+ for (i=0; i<self->nargs; i++) {
+ loop->iters[i] = NULL;
+ loop->cast[i] = NULL;
+ }
+ loop->errobj = NULL;
+ loop->notimplemented = 0;
+ loop->first = 1;
+
+ name = self->name ? self->name : "";
+
+ /* Extract sig= keyword and
+ extobj= keyword if present
+ Raise an error if anything else present in the keyword dictionary
+ */
+ if (kwds != NULL) {
+ PyObject *key, *value;
+ Py_ssize_t pos=0;
+ while (PyDict_Next(kwds, &pos, &key, &value)) {
+ if (!PyString_Check(key)) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid keyword");
+ goto fail;
+ }
+ if (strncmp(PyString_AS_STRING(key),"extobj",6) == 0) {
+ extobj = value;
+ }
+ else if (strncmp(PyString_AS_STRING(key),"sig",5)==0) {
+ typetup = value;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "'%s' is an invalid keyword " \
+ "to %s",
+ PyString_AS_STRING(key), name);
+ goto fail;
+ }
+ }
+ }
+ if (extobj == NULL) {
+ if (PyUFunc_GetPyValues(name,
+ &(loop->bufsize), &(loop->errormask),
+ &(loop->errobj)) < 0) goto fail;
+ }
+ else {
+ if (_extract_pyvals(extobj, name,
+ &(loop->bufsize), &(loop->errormask),
+ &(loop->errobj)) < 0) goto fail;
+ }
+ /* Setup the arrays */
+ if (construct_arrays(loop, args, mps, typetup) < 0) goto fail;
-static void
-_printcastbuf(PyUFuncLoopObject *loop, int bufnum)
-{
- int i;
+ PyUFunc_clearfperr();
+
+ return loop;
- fprintf(stderr, "Printing long buffer %d\n", bufnum);
- for (i=0; i<loop->bufcnt; i++) {
- fprintf(stderr, " %ld\n", *(((long *)(loop->castbuf[bufnum]))+i));
- }
+ fail:
+ ufuncloop_dealloc(loop);
+ return NULL;
}
+
+/*
+ static void
+ _printbytebuf(PyUFuncLoopObject *loop, int bufnum)
+ {
+ int i;
+
+ fprintf(stderr, "Printing byte buffer %d\n", bufnum);
+ for (i=0; i<loop->bufcnt; i++) {
+ fprintf(stderr, " %d\n", *(((byte *)(loop->buffer[bufnum]))+i));
+ }
+ }
+
+ static void
+ _printlongbuf(PyUFuncLoopObject *loop, int bufnum)
+ {
+ int i;
+
+ fprintf(stderr, "Printing long buffer %d\n", bufnum);
+ for (i=0; i<loop->bufcnt; i++) {
+ fprintf(stderr, " %ld\n", *(((long *)(loop->buffer[bufnum]))+i));
+ }
+ }
+
+ static void
+ _printlongbufptr(PyUFuncLoopObject *loop, int bufnum)
+ {
+ int i;
+
+ fprintf(stderr, "Printing long buffer %d\n", bufnum);
+ for (i=0; i<loop->bufcnt; i++) {
+ fprintf(stderr, " %ld\n", *(((long *)(loop->bufptr[bufnum]))+i));
+ }
+ }
+
+
+
+ static void
+ _printcastbuf(PyUFuncLoopObject *loop, int bufnum)
+ {
+ int i;
+
+ fprintf(stderr, "Printing long buffer %d\n", bufnum);
+ for (i=0; i<loop->bufcnt; i++) {
+ fprintf(stderr, " %ld\n", *(((long *)(loop->castbuf[bufnum]))+i));
+ }
+ }
+
*/
@@ -1742,588 +1740,588 @@ _printcastbuf(PyUFuncLoopObject *loop, int bufnum)
/*UFUNC_API*/
static int
PyUFunc_GenericFunction(PyUFuncObject *self, PyObject *args, PyObject *kwds,
- PyArrayObject **mps)
+ PyArrayObject **mps)
{
- PyUFuncLoopObject *loop;
- int i;
- NPY_BEGIN_THREADS_DEF
+ PyUFuncLoopObject *loop;
+ int i;
+ NPY_BEGIN_THREADS_DEF
if (!(loop = construct_loop(self, args, kwds, mps))) return -1;
- if (loop->notimplemented) {ufuncloop_dealloc(loop); return -2;}
-
- NPY_LOOP_BEGIN_THREADS
-
- switch(loop->meth) {
- case ONE_UFUNCLOOP:
- /* Everything is contiguous, notswapped, aligned,
- and of the right type. -- Fastest.
- Or if not contiguous, then a single-stride
- increment moves through the entire array.
- */
- /*fprintf(stderr, "ONE...%d\n", loop->size);*/
- loop->function((char **)loop->bufptr, &(loop->size),
- loop->steps, loop->funcdata);
- UFUNC_CHECK_ERROR(loop);
- break;
- case NOBUFFER_UFUNCLOOP:
- /* Everything is notswapped, aligned and of the
- right type but not contiguous. -- Almost as fast.
- */
- /*fprintf(stderr, "NOBUFFER...%d\n", loop->size);*/
- while (loop->index < loop->size) {
- for (i=0; i<self->nargs; i++)
- loop->bufptr[i] = loop->iters[i]->dataptr;
-
- loop->function((char **)loop->bufptr, &(loop->bufcnt),
- loop->steps, loop->funcdata);
- UFUNC_CHECK_ERROR(loop);
-
- /* Adjust loop pointers */
-
- for (i=0; i<self->nargs; i++) {
- PyArray_ITER_NEXT(loop->iters[i]);
- }
- loop->index++;
- }
- break;
- case BUFFER_UFUNCLOOP: {
- PyArray_CopySwapNFunc *copyswapn[NPY_MAXARGS];
- PyArrayIterObject **iters=loop->iters;
- int *swap=loop->swap;
- char **dptr=loop->dptr;
- int mpselsize[NPY_MAXARGS];
- intp laststrides[NPY_MAXARGS];
- int fastmemcpy[NPY_MAXARGS];
- int *needbuffer=loop->needbuffer;
- intp index=loop->index, size=loop->size;
- int bufsize;
- intp bufcnt;
- int copysizes[NPY_MAXARGS];
- char **bufptr = loop->bufptr;
- char **buffer = loop->buffer;
- char **castbuf = loop->castbuf;
- intp *steps = loop->steps;
- char *tptr[NPY_MAXARGS];
- int ninnerloops = loop->ninnerloops;
- Bool pyobject[NPY_MAXARGS];
- int datasize[NPY_MAXARGS];
- int j, k, stopcondition;
- char *myptr1, *myptr2;
-
-
- for (i=0; i<self->nargs; i++) {
- copyswapn[i] = mps[i]->descr->f->copyswapn;
- mpselsize[i] = mps[i]->descr->elsize;
- pyobject[i] = (loop->obj && \
- (mps[i]->descr->type_num == PyArray_OBJECT));
- laststrides[i] = iters[i]->strides[loop->lastdim];
- if (steps[i] && laststrides[i] != mpselsize[i]) fastmemcpy[i] = 0;
- else fastmemcpy[i] = 1;
- }
- /* Do generic buffered looping here (works for any kind of
- arrays -- some need buffers, some don't.
- */
-
- /* New algorithm: N is the largest dimension. B is the buffer-size.
- quotient is loop->ninnerloops-1
- remainder is loop->leftover
-
- Compute N = quotient * B + remainder.
- quotient = N / B # integer math
- (store quotient + 1) as the number of innerloops
- remainder = N % B # integer remainder
-
- On the inner-dimension we will have (quotient + 1) loops where
- the size of the inner function is B for all but the last when the niter size is
- remainder.
-
- So, the code looks very similar to NOBUFFER_LOOP except the inner-most loop is
- replaced with...
-
- for(i=0; i<quotient+1; i++) {
- if (i==quotient+1) make itersize remainder size
- copy only needed items to buffer.
- swap input buffers if needed
- cast input buffers if needed
- call loop_function()
- cast outputs in buffers if needed
- swap outputs in buffers if needed
- copy only needed items back to output arrays.
- update all data-pointers by strides*niter
- }
- */
-
-
- /* fprintf(stderr, "BUFFER...%d,%d,%d\n", loop->size,
- loop->ninnerloops, loop->leftover);
- */
- /*
- for (i=0; i<self->nargs; i++) {
- fprintf(stderr, "iters[%d]->dataptr = %p, %p of size %d\n", i,
- iters[i], iters[i]->ao->data, PyArray_NBYTES(iters[i]->ao));
- }
- */
-
- stopcondition = ninnerloops;
- if (loop->leftover == 0) stopcondition--;
- while (index < size) {
- bufsize=loop->bufsize;
- for (i=0; i<self->nargs; i++) {
- tptr[i] = loop->iters[i]->dataptr;
- if (needbuffer[i]) {
- dptr[i] = bufptr[i];
- datasize[i] = (steps[i] ? bufsize : 1);
- copysizes[i] = datasize[i] * mpselsize[i];
- }
- else {
- dptr[i] = tptr[i];
- }
- }
-
- /* This is the inner function over the last dimension */
- for (k=1; k<=stopcondition; k++) {
- if (k==ninnerloops) {
- bufsize = loop->leftover;
- for (i=0; i<self->nargs;i++) {
- if (!needbuffer[i]) continue;
- datasize[i] = (steps[i] ? bufsize : 1);
- copysizes[i] = datasize[i] * mpselsize[i];
- }
- }
+ if (loop->notimplemented) {ufuncloop_dealloc(loop); return -2;}
+
+ NPY_LOOP_BEGIN_THREADS
+
+ switch(loop->meth) {
+ case ONE_UFUNCLOOP:
+ /* Everything is contiguous, notswapped, aligned,
+ and of the right type. -- Fastest.
+ Or if not contiguous, then a single-stride
+ increment moves through the entire array.
+ */
+ /*fprintf(stderr, "ONE...%d\n", loop->size);*/
+ loop->function((char **)loop->bufptr, &(loop->size),
+ loop->steps, loop->funcdata);
+ UFUNC_CHECK_ERROR(loop);
+ break;
+ case NOBUFFER_UFUNCLOOP:
+ /* Everything is notswapped, aligned and of the
+ right type but not contiguous. -- Almost as fast.
+ */
+ /*fprintf(stderr, "NOBUFFER...%d\n", loop->size);*/
+ while (loop->index < loop->size) {
+ for (i=0; i<self->nargs; i++)
+ loop->bufptr[i] = loop->iters[i]->dataptr;
- for (i=0; i<self->nin; i++) {
- if (!needbuffer[i]) continue;
- if (fastmemcpy[i])
- memcpy(buffer[i], tptr[i],
- copysizes[i]);
- else {
- myptr1 = buffer[i];
- myptr2 = tptr[i];
- for (j=0; j<bufsize; j++) {
- memcpy(myptr1, myptr2, mpselsize[i]);
- myptr1 += mpselsize[i];
- myptr2 += laststrides[i];
- }
- }
-
- /* swap the buffer if necessary */
- if (swap[i]) {
- /* fprintf(stderr, "swapping...\n");*/
- copyswapn[i](buffer[i], mpselsize[i], NULL, -1,
- (intp) datasize[i], 1,
- mps[i]);
- }
- /* cast to the other buffer if necessary */
- if (loop->cast[i]) {
- loop->cast[i](buffer[i],
- castbuf[i],
- (intp) datasize[i],
- NULL, NULL);
- }
- }
-
- bufcnt = (intp) bufsize;
- loop->function((char **)dptr, &bufcnt, steps, loop->funcdata);
-
- for (i=self->nin; i<self->nargs; i++) {
- if (!needbuffer[i]) continue;
- if (loop->cast[i]) {
- loop->cast[i](castbuf[i],
- buffer[i],
- (intp) datasize[i],
- NULL, NULL);
- }
- if (swap[i]) {
- copyswapn[i](buffer[i], mpselsize[i], NULL, -1,
- (intp) datasize[i], 1,
- mps[i]);
- }
- /* copy back to output arrays */
- /* decref what's already there for object arrays */
- if (pyobject[i]) {
- myptr1 = tptr[i];
- for (j=0; j<datasize[i]; j++) {
- Py_XDECREF(*((PyObject **)myptr1));
- myptr1 += laststrides[i];
- }
- }
- if (fastmemcpy[i])
- memcpy(tptr[i], buffer[i], copysizes[i]);
- else {
- myptr2 = buffer[i];
- myptr1 = tptr[i];
- for (j=0; j<bufsize; j++) {
- memcpy(myptr1, myptr2,
- mpselsize[i]);
- myptr1 += laststrides[i];
- myptr2 += mpselsize[i];
- }
- }
+ loop->function((char **)loop->bufptr, &(loop->bufcnt),
+ loop->steps, loop->funcdata);
+ UFUNC_CHECK_ERROR(loop);
+
+ /* Adjust loop pointers */
+
+ for (i=0; i<self->nargs; i++) {
+ PyArray_ITER_NEXT(loop->iters[i]);
+ }
+ loop->index++;
+ }
+ break;
+ case BUFFER_UFUNCLOOP: {
+ PyArray_CopySwapNFunc *copyswapn[NPY_MAXARGS];
+ PyArrayIterObject **iters=loop->iters;
+ int *swap=loop->swap;
+ char **dptr=loop->dptr;
+ int mpselsize[NPY_MAXARGS];
+ intp laststrides[NPY_MAXARGS];
+ int fastmemcpy[NPY_MAXARGS];
+ int *needbuffer=loop->needbuffer;
+ intp index=loop->index, size=loop->size;
+ int bufsize;
+ intp bufcnt;
+ int copysizes[NPY_MAXARGS];
+ char **bufptr = loop->bufptr;
+ char **buffer = loop->buffer;
+ char **castbuf = loop->castbuf;
+ intp *steps = loop->steps;
+ char *tptr[NPY_MAXARGS];
+ int ninnerloops = loop->ninnerloops;
+ Bool pyobject[NPY_MAXARGS];
+ int datasize[NPY_MAXARGS];
+ int j, k, stopcondition;
+ char *myptr1, *myptr2;
+
+
+ for (i=0; i<self->nargs; i++) {
+ copyswapn[i] = mps[i]->descr->f->copyswapn;
+ mpselsize[i] = mps[i]->descr->elsize;
+ pyobject[i] = (loop->obj && \
+ (mps[i]->descr->type_num == PyArray_OBJECT));
+ laststrides[i] = iters[i]->strides[loop->lastdim];
+ if (steps[i] && laststrides[i] != mpselsize[i]) fastmemcpy[i] = 0;
+ else fastmemcpy[i] = 1;
+ }
+ /* Do generic buffered looping here (works for any kind of
+ arrays -- some need buffers, some don't.
+ */
+
+ /* New algorithm: N is the largest dimension. B is the buffer-size.
+ quotient is loop->ninnerloops-1
+ remainder is loop->leftover
+
+ Compute N = quotient * B + remainder.
+ quotient = N / B # integer math
+ (store quotient + 1) as the number of innerloops
+ remainder = N % B # integer remainder
+
+ On the inner-dimension we will have (quotient + 1) loops where
+ the size of the inner function is B for all but the last when the niter size is
+ remainder.
+
+ So, the code looks very similar to NOBUFFER_LOOP except the inner-most loop is
+ replaced with...
+
+ for(i=0; i<quotient+1; i++) {
+ if (i==quotient+1) make itersize remainder size
+ copy only needed items to buffer.
+ swap input buffers if needed
+ cast input buffers if needed
+ call loop_function()
+ cast outputs in buffers if needed
+ swap outputs in buffers if needed
+ copy only needed items back to output arrays.
+ update all data-pointers by strides*niter
+ }
+ */
+
+
+ /* fprintf(stderr, "BUFFER...%d,%d,%d\n", loop->size,
+ loop->ninnerloops, loop->leftover);
+ */
+ /*
+ for (i=0; i<self->nargs; i++) {
+ fprintf(stderr, "iters[%d]->dataptr = %p, %p of size %d\n", i,
+ iters[i], iters[i]->ao->data, PyArray_NBYTES(iters[i]->ao));
+ }
+ */
+
+ stopcondition = ninnerloops;
+ if (loop->leftover == 0) stopcondition--;
+ while (index < size) {
+ bufsize=loop->bufsize;
+ for (i=0; i<self->nargs; i++) {
+ tptr[i] = loop->iters[i]->dataptr;
+ if (needbuffer[i]) {
+ dptr[i] = bufptr[i];
+ datasize[i] = (steps[i] ? bufsize : 1);
+ copysizes[i] = datasize[i] * mpselsize[i];
+ }
+ else {
+ dptr[i] = tptr[i];
+ }
+ }
+
+ /* This is the inner function over the last dimension */
+ for (k=1; k<=stopcondition; k++) {
+ if (k==ninnerloops) {
+ bufsize = loop->leftover;
+ for (i=0; i<self->nargs;i++) {
+ if (!needbuffer[i]) continue;
+ datasize[i] = (steps[i] ? bufsize : 1);
+ copysizes[i] = datasize[i] * mpselsize[i];
+ }
+ }
+
+ for (i=0; i<self->nin; i++) {
+ if (!needbuffer[i]) continue;
+ if (fastmemcpy[i])
+ memcpy(buffer[i], tptr[i],
+ copysizes[i]);
+ else {
+ myptr1 = buffer[i];
+ myptr2 = tptr[i];
+ for (j=0; j<bufsize; j++) {
+ memcpy(myptr1, myptr2, mpselsize[i]);
+ myptr1 += mpselsize[i];
+ myptr2 += laststrides[i];
+ }
+ }
+
+ /* swap the buffer if necessary */
+ if (swap[i]) {
+ /* fprintf(stderr, "swapping...\n");*/
+ copyswapn[i](buffer[i], mpselsize[i], NULL, -1,
+ (intp) datasize[i], 1,
+ mps[i]);
+ }
+ /* cast to the other buffer if necessary */
+ if (loop->cast[i]) {
+ loop->cast[i](buffer[i],
+ castbuf[i],
+ (intp) datasize[i],
+ NULL, NULL);
+ }
+ }
+
+ bufcnt = (intp) bufsize;
+ loop->function((char **)dptr, &bufcnt, steps, loop->funcdata);
+
+ for (i=self->nin; i<self->nargs; i++) {
+ if (!needbuffer[i]) continue;
+ if (loop->cast[i]) {
+ loop->cast[i](castbuf[i],
+ buffer[i],
+ (intp) datasize[i],
+ NULL, NULL);
+ }
+ if (swap[i]) {
+ copyswapn[i](buffer[i], mpselsize[i], NULL, -1,
+ (intp) datasize[i], 1,
+ mps[i]);
+ }
+ /* copy back to output arrays */
+ /* decref what's already there for object arrays */
+ if (pyobject[i]) {
+ myptr1 = tptr[i];
+ for (j=0; j<datasize[i]; j++) {
+ Py_XDECREF(*((PyObject **)myptr1));
+ myptr1 += laststrides[i];
+ }
+ }
+ if (fastmemcpy[i])
+ memcpy(tptr[i], buffer[i], copysizes[i]);
+ else {
+ myptr2 = buffer[i];
+ myptr1 = tptr[i];
+ for (j=0; j<bufsize; j++) {
+ memcpy(myptr1, myptr2,
+ mpselsize[i]);
+ myptr1 += laststrides[i];
+ myptr2 += mpselsize[i];
+ }
+ }
+ }
+ if (k == stopcondition) continue;
+ for (i=0; i<self->nargs; i++) {
+ tptr[i] += bufsize * laststrides[i];
+ if (!needbuffer[i]) dptr[i] = tptr[i];
+ }
+ }
+ /* end inner function over last dimension */
+
+ if (loop->objfunc) { /* DECREF castbuf when underlying function used object arrays
+ and casting was needed to get to object arrays */
+ for (i=0; i<self->nargs; i++) {
+ if (loop->cast[i]) {
+ if (steps[i] == 0) {
+ Py_XDECREF(*((PyObject **)castbuf[i]));
+ }
+ else {
+ int size = loop->bufsize;
+ PyObject **objptr = (PyObject **)castbuf[i];
+ /* size is loop->bufsize unless there
+ was only one loop */
+ if (ninnerloops == 1) \
+ size = loop->leftover;
+
+ for (j=0; j<size; j++) {
+ Py_XDECREF(*objptr);
+ *objptr = NULL;
+ objptr += 1;
}
- if (k == stopcondition) continue;
- for (i=0; i<self->nargs; i++) {
- tptr[i] += bufsize * laststrides[i];
- if (!needbuffer[i]) dptr[i] = tptr[i];
- }
- }
- /* end inner function over last dimension */
-
- if (loop->objfunc) { /* DECREF castbuf when underlying function used object arrays
- and casting was needed to get to object arrays */
- for (i=0; i<self->nargs; i++) {
- if (loop->cast[i]) {
- if (steps[i] == 0) {
- Py_XDECREF(*((PyObject **)castbuf[i]));
- }
- else {
- int size = loop->bufsize;
- PyObject **objptr = (PyObject **)castbuf[i];
- /* size is loop->bufsize unless there
- was only one loop */
- if (ninnerloops == 1) \
- size = loop->leftover;
-
- for (j=0; j<size; j++) {
- Py_XDECREF(*objptr);
- *objptr = NULL;
- objptr += 1;
- }
- }
- }
- }
-
- }
-
- UFUNC_CHECK_ERROR(loop);
-
- for (i=0; i<self->nargs; i++) {
- PyArray_ITER_NEXT(loop->iters[i]);
- }
- index++;
+ }
+ }
+ }
+
}
+
+ UFUNC_CHECK_ERROR(loop);
+
+ for (i=0; i<self->nargs; i++) {
+ PyArray_ITER_NEXT(loop->iters[i]);
+ }
+ index++;
+ }
}
}
- NPY_LOOP_END_THREADS
+ NPY_LOOP_END_THREADS
ufuncloop_dealloc(loop);
- return 0;
+ return 0;
fail:
- NPY_LOOP_END_THREADS
+ NPY_LOOP_END_THREADS
- if (loop) ufuncloop_dealloc(loop);
- return -1;
+ if (loop) ufuncloop_dealloc(loop);
+ return -1;
}
static PyArrayObject *
_getidentity(PyUFuncObject *self, int otype, char *str)
{
- PyObject *obj, *arr;
- PyArray_Descr *typecode;
+ PyObject *obj, *arr;
+ PyArray_Descr *typecode;
- if (self->identity == PyUFunc_None) {
- PyErr_Format(PyExc_ValueError,
- "zero-size array to ufunc.%s " \
- "without identity", str);
- return NULL;
- }
- if (self->identity == PyUFunc_One) {
- obj = PyInt_FromLong((long) 1);
- } else {
- obj = PyInt_FromLong((long) 0);
- }
+ if (self->identity == PyUFunc_None) {
+ PyErr_Format(PyExc_ValueError,
+ "zero-size array to ufunc.%s " \
+ "without identity", str);
+ return NULL;
+ }
+ if (self->identity == PyUFunc_One) {
+ obj = PyInt_FromLong((long) 1);
+ } else {
+ obj = PyInt_FromLong((long) 0);
+ }
- typecode = PyArray_DescrFromType(otype);
- arr = PyArray_FromAny(obj, typecode, 0, 0, CARRAY, NULL);
- Py_DECREF(obj);
- return (PyArrayObject *)arr;
+ typecode = PyArray_DescrFromType(otype);
+ arr = PyArray_FromAny(obj, typecode, 0, 0, CARRAY, NULL);
+ Py_DECREF(obj);
+ return (PyArrayObject *)arr;
}
static int
_create_reduce_copy(PyUFuncReduceObject *loop, PyArrayObject **arr, int rtype)
{
- intp maxsize;
- PyObject *new;
- PyArray_Descr *ntype;
-
- maxsize = PyArray_SIZE(*arr);
-
- if (maxsize < loop->bufsize) {
- if (!(PyArray_ISBEHAVED_RO(*arr)) || \
- PyArray_TYPE(*arr) != rtype) {
- ntype = PyArray_DescrFromType(rtype);
- new = PyArray_FromAny((PyObject *)(*arr),
- ntype, 0, 0,
- FORCECAST | ALIGNED, NULL);
- if (new == NULL) return -1;
- *arr = (PyArrayObject *)new;
- loop->decref = new;
- }
- }
+ intp maxsize;
+ PyObject *new;
+ PyArray_Descr *ntype;
+
+ maxsize = PyArray_SIZE(*arr);
+
+ if (maxsize < loop->bufsize) {
+ if (!(PyArray_ISBEHAVED_RO(*arr)) || \
+ PyArray_TYPE(*arr) != rtype) {
+ ntype = PyArray_DescrFromType(rtype);
+ new = PyArray_FromAny((PyObject *)(*arr),
+ ntype, 0, 0,
+ FORCECAST | ALIGNED, NULL);
+ if (new == NULL) return -1;
+ *arr = (PyArrayObject *)new;
+ loop->decref = new;
+ }
+ }
- /* Don't decref *arr before re-assigning
- because it was not going to be DECREF'd anyway.
+ /* Don't decref *arr before re-assigning
+ because it was not going to be DECREF'd anyway.
- If a copy is made, then the copy will be removed
- on deallocation of the loop structure by setting
- loop->decref.
- */
+ If a copy is made, then the copy will be removed
+ on deallocation of the loop structure by setting
+ loop->decref.
+ */
- return 0;
+ return 0;
}
static PyUFuncReduceObject *
construct_reduce(PyUFuncObject *self, PyArrayObject **arr, PyArrayObject *out,
int axis, int otype, int operation, intp ind_size, char *str)
{
- PyUFuncReduceObject *loop;
- PyArrayObject *idarr;
- PyArrayObject *aar;
- intp loop_i[MAX_DIMS], outsize=0;
- int arg_types[3];
- PyArray_SCALARKIND scalars[3] = {PyArray_NOSCALAR, PyArray_NOSCALAR,
- PyArray_NOSCALAR};
- int i, j, nd;
- int flags;
- /* Reduce type is the type requested of the input
- during reduction */
-
- nd = (*arr)->nd;
+ PyUFuncReduceObject *loop;
+ PyArrayObject *idarr;
+ PyArrayObject *aar;
+ intp loop_i[MAX_DIMS], outsize=0;
+ int arg_types[3];
+ PyArray_SCALARKIND scalars[3] = {PyArray_NOSCALAR, PyArray_NOSCALAR,
+ PyArray_NOSCALAR};
+ int i, j, nd;
+ int flags;
+ /* Reduce type is the type requested of the input
+ during reduction */
+
+ nd = (*arr)->nd;
+ arg_types[0] = otype;
+ arg_types[1] = otype;
+ arg_types[2] = otype;
+ if ((loop = _pya_malloc(sizeof(PyUFuncReduceObject)))==NULL) {
+ PyErr_NoMemory(); return loop;
+ }
+
+ loop->retbase=0;
+ loop->swap = 0;
+ loop->index = 0;
+ loop->ufunc = self;
+ Py_INCREF(self);
+ loop->cast = NULL;
+ loop->buffer = NULL;
+ loop->ret = NULL;
+ loop->it = NULL;
+ loop->rit = NULL;
+ loop->errobj = NULL;
+ loop->first = 1;
+ loop->decref=NULL;
+ loop->N = (*arr)->dimensions[axis];
+ loop->instrides = (*arr)->strides[axis];
+
+ if (select_types(loop->ufunc, arg_types, &(loop->function),
+ &(loop->funcdata), scalars, NULL) == -1) goto fail;
+
+ /* output type may change -- if it does
+ reduction is forced into that type
+ and we need to select the reduction function again
+ */
+ if (otype != arg_types[2]) {
+ otype = arg_types[2];
arg_types[0] = otype;
arg_types[1] = otype;
- arg_types[2] = otype;
- if ((loop = _pya_malloc(sizeof(PyUFuncReduceObject)))==NULL) {
- PyErr_NoMemory(); return loop;
- }
-
- loop->retbase=0;
- loop->swap = 0;
- loop->index = 0;
- loop->ufunc = self;
- Py_INCREF(self);
- loop->cast = NULL;
- loop->buffer = NULL;
- loop->ret = NULL;
- loop->it = NULL;
- loop->rit = NULL;
- loop->errobj = NULL;
- loop->first = 1;
- loop->decref=NULL;
- loop->N = (*arr)->dimensions[axis];
- loop->instrides = (*arr)->strides[axis];
-
- if (select_types(loop->ufunc, arg_types, &(loop->function),
- &(loop->funcdata), scalars, NULL) == -1) goto fail;
-
- /* output type may change -- if it does
- reduction is forced into that type
- and we need to select the reduction function again
- */
- if (otype != arg_types[2]) {
- otype = arg_types[2];
- arg_types[0] = otype;
- arg_types[1] = otype;
- if (select_types(loop->ufunc, arg_types, &(loop->function),
- &(loop->funcdata), scalars, NULL) == -1)
- goto fail;
- }
-
- /* get looping parameters from Python */
- if (PyUFunc_GetPyValues(str, &(loop->bufsize), &(loop->errormask),
- &(loop->errobj)) < 0) goto fail;
-
- /* Make copy if misbehaved or not otype for small arrays */
- if (_create_reduce_copy(loop, arr, otype) < 0) goto fail;
- aar = *arr;
-
- if (loop->N == 0) {
- loop->meth = ZERO_EL_REDUCELOOP;
- }
- else if (PyArray_ISBEHAVED_RO(aar) && \
- otype == (aar)->descr->type_num) {
- if (loop->N == 1) {
- loop->meth = ONE_EL_REDUCELOOP;
- }
- else {
- loop->meth = NOBUFFER_UFUNCLOOP;
- loop->steps[1] = (aar)->strides[axis];
- loop->N -= 1;
- }
+ if (select_types(loop->ufunc, arg_types, &(loop->function),
+ &(loop->funcdata), scalars, NULL) == -1)
+ goto fail;
+ }
+
+ /* get looping parameters from Python */
+ if (PyUFunc_GetPyValues(str, &(loop->bufsize), &(loop->errormask),
+ &(loop->errobj)) < 0) goto fail;
+
+ /* Make copy if misbehaved or not otype for small arrays */
+ if (_create_reduce_copy(loop, arr, otype) < 0) goto fail;
+ aar = *arr;
+
+ if (loop->N == 0) {
+ loop->meth = ZERO_EL_REDUCELOOP;
+ }
+ else if (PyArray_ISBEHAVED_RO(aar) && \
+ otype == (aar)->descr->type_num) {
+ if (loop->N == 1) {
+ loop->meth = ONE_EL_REDUCELOOP;
}
else {
- loop->meth = BUFFER_UFUNCLOOP;
- loop->swap = !(PyArray_ISNOTSWAPPED(aar));
+ loop->meth = NOBUFFER_UFUNCLOOP;
+ loop->steps[1] = (aar)->strides[axis];
+ loop->N -= 1;
}
+ }
+ else {
+ loop->meth = BUFFER_UFUNCLOOP;
+ loop->swap = !(PyArray_ISNOTSWAPPED(aar));
+ }
- /* Determine if object arrays are involved */
- if (otype == PyArray_OBJECT || aar->descr->type_num == PyArray_OBJECT)
- loop->obj = 1;
- else
- loop->obj = 0;
-
- if (loop->meth == ZERO_EL_REDUCELOOP) {
- idarr = _getidentity(self, otype, str);
- if (idarr == NULL) goto fail;
- if (idarr->descr->elsize > UFUNC_MAXIDENTITY) {
- PyErr_Format(PyExc_RuntimeError,
- "UFUNC_MAXIDENTITY (%d)" \
- " is too small (needs to be at least %d)",
- UFUNC_MAXIDENTITY, idarr->descr->elsize);
- Py_DECREF(idarr);
- goto fail;
- }
- memcpy(loop->idptr, idarr->data, idarr->descr->elsize);
- Py_DECREF(idarr);
- }
-
- /* Construct return array */
- flags = NPY_CARRAY | NPY_UPDATEIFCOPY | NPY_FORCECAST;
- switch(operation) {
- case UFUNC_REDUCE:
- for (j=0, i=0; i<nd; i++) {
- if (i != axis)
- loop_i[j++] = (aar)->dimensions[i];
-
- }
- if (out == NULL) {
- loop->ret = (PyArrayObject *) \
- PyArray_New(aar->ob_type, aar->nd-1, loop_i,
- otype, NULL, NULL, 0, 0,
- (PyObject *)aar);
- }
- else {
- outsize = PyArray_MultiplyList(loop_i, aar->nd-1);
- }
- break;
- case UFUNC_ACCUMULATE:
- if (out == NULL) {
- loop->ret = (PyArrayObject *) \
- PyArray_New(aar->ob_type, aar->nd, aar->dimensions,
- otype, NULL, NULL, 0, 0, (PyObject *)aar);
- }
- else {
- outsize = PyArray_MultiplyList(aar->dimensions, aar->nd);
- }
- break;
- case UFUNC_REDUCEAT:
- memcpy(loop_i, aar->dimensions, nd*sizeof(intp));
- /* Index is 1-d array */
- loop_i[axis] = ind_size;
- if (out == NULL) {
- loop->ret = (PyArrayObject *) \
- PyArray_New(aar->ob_type, aar->nd, loop_i, otype,
- NULL, NULL, 0, 0, (PyObject *)aar);
- }
- else {
- outsize = PyArray_MultiplyList(loop_i, aar->nd);
- }
- if (ind_size == 0) {
- loop->meth = ZERO_EL_REDUCELOOP;
- return loop;
- }
- if (loop->meth == ONE_EL_REDUCELOOP)
- loop->meth = NOBUFFER_REDUCELOOP;
- break;
- }
- if (out) {
- if (PyArray_SIZE(out) != outsize) {
- PyErr_SetString(PyExc_ValueError,
- "wrong shape for output");
- goto fail;
- }
- loop->ret = (PyArrayObject *) \
- PyArray_FromArray(out, PyArray_DescrFromType(otype),
- flags);
- if (loop->ret && loop->ret != out) {
- loop->retbase = 1;
- }
+ /* Determine if object arrays are involved */
+ if (otype == PyArray_OBJECT || aar->descr->type_num == PyArray_OBJECT)
+ loop->obj = 1;
+ else
+ loop->obj = 0;
+
+ if (loop->meth == ZERO_EL_REDUCELOOP) {
+ idarr = _getidentity(self, otype, str);
+ if (idarr == NULL) goto fail;
+ if (idarr->descr->elsize > UFUNC_MAXIDENTITY) {
+ PyErr_Format(PyExc_RuntimeError,
+ "UFUNC_MAXIDENTITY (%d)" \
+ " is too small (needs to be at least %d)",
+ UFUNC_MAXIDENTITY, idarr->descr->elsize);
+ Py_DECREF(idarr);
+ goto fail;
}
- if (loop->ret == NULL) goto fail;
- loop->insize = aar->descr->elsize;
- loop->outsize = loop->ret->descr->elsize;
- loop->bufptr[0] = loop->ret->data;
+ memcpy(loop->idptr, idarr->data, idarr->descr->elsize);
+ Py_DECREF(idarr);
+ }
- if (loop->meth == ZERO_EL_REDUCELOOP) {
- loop->size = PyArray_SIZE(loop->ret);
- return loop;
- }
+ /* Construct return array */
+ flags = NPY_CARRAY | NPY_UPDATEIFCOPY | NPY_FORCECAST;
+ switch(operation) {
+ case UFUNC_REDUCE:
+ for (j=0, i=0; i<nd; i++) {
+ if (i != axis)
+ loop_i[j++] = (aar)->dimensions[i];
- loop->it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)aar);
- if (loop->it == NULL) return NULL;
+ }
+ if (out == NULL) {
+ loop->ret = (PyArrayObject *) \
+ PyArray_New(aar->ob_type, aar->nd-1, loop_i,
+ otype, NULL, NULL, 0, 0,
+ (PyObject *)aar);
+ }
+ else {
+ outsize = PyArray_MultiplyList(loop_i, aar->nd-1);
+ }
+ break;
+ case UFUNC_ACCUMULATE:
+ if (out == NULL) {
+ loop->ret = (PyArrayObject *) \
+ PyArray_New(aar->ob_type, aar->nd, aar->dimensions,
+ otype, NULL, NULL, 0, 0, (PyObject *)aar);
+ }
+ else {
+ outsize = PyArray_MultiplyList(aar->dimensions, aar->nd);
+ }
+ break;
+ case UFUNC_REDUCEAT:
+ memcpy(loop_i, aar->dimensions, nd*sizeof(intp));
+ /* Index is 1-d array */
+ loop_i[axis] = ind_size;
+ if (out == NULL) {
+ loop->ret = (PyArrayObject *) \
+ PyArray_New(aar->ob_type, aar->nd, loop_i, otype,
+ NULL, NULL, 0, 0, (PyObject *)aar);
+ }
+ else {
+ outsize = PyArray_MultiplyList(loop_i, aar->nd);
+ }
+ if (ind_size == 0) {
+ loop->meth = ZERO_EL_REDUCELOOP;
+ return loop;
+ }
+ if (loop->meth == ONE_EL_REDUCELOOP)
+ loop->meth = NOBUFFER_REDUCELOOP;
+ break;
+ }
+ if (out) {
+ if (PyArray_SIZE(out) != outsize) {
+ PyErr_SetString(PyExc_ValueError,
+ "wrong shape for output");
+ goto fail;
+ }
+ loop->ret = (PyArrayObject *) \
+ PyArray_FromArray(out, PyArray_DescrFromType(otype),
+ flags);
+ if (loop->ret && loop->ret != out) {
+ loop->retbase = 1;
+ }
+ }
+ if (loop->ret == NULL) goto fail;
+ loop->insize = aar->descr->elsize;
+ loop->outsize = loop->ret->descr->elsize;
+ loop->bufptr[0] = loop->ret->data;
+
+ if (loop->meth == ZERO_EL_REDUCELOOP) {
+ loop->size = PyArray_SIZE(loop->ret);
+ return loop;
+ }
- if (loop->meth == ONE_EL_REDUCELOOP) {
- loop->size = loop->it->size;
- return loop;
- }
+ loop->it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)aar);
+ if (loop->it == NULL) return NULL;
- /* Fix iterator to loop over correct dimension */
- /* Set size in axis dimension to 1 */
+ if (loop->meth == ONE_EL_REDUCELOOP) {
+ loop->size = loop->it->size;
+ return loop;
+ }
- loop->it->contiguous = 0;
- loop->it->size /= (loop->it->dims_m1[axis]+1);
- loop->it->dims_m1[axis] = 0;
- loop->it->backstrides[axis] = 0;
+ /* Fix iterator to loop over correct dimension */
+ /* Set size in axis dimension to 1 */
+ loop->it->contiguous = 0;
+ loop->it->size /= (loop->it->dims_m1[axis]+1);
+ loop->it->dims_m1[axis] = 0;
+ loop->it->backstrides[axis] = 0;
- loop->size = loop->it->size;
- if (operation == UFUNC_REDUCE) {
- loop->steps[0] = 0;
- }
- else {
- loop->rit = (PyArrayIterObject *) \
- PyArray_IterNew((PyObject *)(loop->ret));
- if (loop->rit == NULL) return NULL;
-
- /* Fix iterator to loop over correct dimension */
- /* Set size in axis dimension to 1 */
-
- loop->rit->contiguous = 0;
- loop->rit->size /= (loop->rit->dims_m1[axis]+1);
- loop->rit->dims_m1[axis] = 0;
- loop->rit->backstrides[axis] = 0;
-
- if (operation == UFUNC_ACCUMULATE)
- loop->steps[0] = loop->ret->strides[axis];
- else
- loop->steps[0] = 0;
- }
- loop->steps[2] = loop->steps[0];
- loop->bufptr[2] = loop->bufptr[0] + loop->steps[2];
-
-
- if (loop->meth == BUFFER_UFUNCLOOP) {
- int _size;
- loop->steps[1] = loop->outsize;
- if (otype != aar->descr->type_num) {
- _size=loop->bufsize*(loop->outsize + \
- aar->descr->elsize);
- loop->buffer = PyDataMem_NEW(_size);
- if (loop->buffer == NULL) goto fail;
- if (loop->obj) memset(loop->buffer, 0, _size);
- loop->castbuf = loop->buffer + \
- loop->bufsize*aar->descr->elsize;
- loop->bufptr[1] = loop->castbuf;
- loop->cast = PyArray_GetCastFunc(aar->descr, otype);
- if (loop->cast == NULL) goto fail;
- }
- else {
- _size = loop->bufsize * loop->outsize;
- loop->buffer = PyDataMem_NEW(_size);
- if (loop->buffer == NULL) goto fail;
- if (loop->obj) memset(loop->buffer, 0, _size);
- loop->bufptr[1] = loop->buffer;
- }
- }
+ loop->size = loop->it->size;
+
+ if (operation == UFUNC_REDUCE) {
+ loop->steps[0] = 0;
+ }
+ else {
+ loop->rit = (PyArrayIterObject *) \
+ PyArray_IterNew((PyObject *)(loop->ret));
+ if (loop->rit == NULL) return NULL;
+ /* Fix iterator to loop over correct dimension */
+ /* Set size in axis dimension to 1 */
- PyUFunc_clearfperr();
- return loop;
+ loop->rit->contiguous = 0;
+ loop->rit->size /= (loop->rit->dims_m1[axis]+1);
+ loop->rit->dims_m1[axis] = 0;
+ loop->rit->backstrides[axis] = 0;
+
+ if (operation == UFUNC_ACCUMULATE)
+ loop->steps[0] = loop->ret->strides[axis];
+ else
+ loop->steps[0] = 0;
+ }
+ loop->steps[2] = loop->steps[0];
+ loop->bufptr[2] = loop->bufptr[0] + loop->steps[2];
+
+
+ if (loop->meth == BUFFER_UFUNCLOOP) {
+ int _size;
+ loop->steps[1] = loop->outsize;
+ if (otype != aar->descr->type_num) {
+ _size=loop->bufsize*(loop->outsize + \
+ aar->descr->elsize);
+ loop->buffer = PyDataMem_NEW(_size);
+ if (loop->buffer == NULL) goto fail;
+ if (loop->obj) memset(loop->buffer, 0, _size);
+ loop->castbuf = loop->buffer + \
+ loop->bufsize*aar->descr->elsize;
+ loop->bufptr[1] = loop->castbuf;
+ loop->cast = PyArray_GetCastFunc(aar->descr, otype);
+ if (loop->cast == NULL) goto fail;
+ }
+ else {
+ _size = loop->bufsize * loop->outsize;
+ loop->buffer = PyDataMem_NEW(_size);
+ if (loop->buffer == NULL) goto fail;
+ if (loop->obj) memset(loop->buffer, 0, _size);
+ loop->bufptr[1] = loop->buffer;
+ }
+ }
+
+
+ PyUFunc_clearfperr();
+ return loop;
fail:
- ufuncreduce_dealloc(loop);
- return NULL;
+ ufuncreduce_dealloc(loop);
+ return NULL;
}
@@ -2339,142 +2337,142 @@ static PyObject *
PyUFunc_Reduce(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out,
int axis, int otype)
{
- PyArrayObject *ret=NULL;
- PyUFuncReduceObject *loop;
- intp i, n;
- char *dptr;
- NPY_BEGIN_THREADS_DEF
+ PyArrayObject *ret=NULL;
+ PyUFuncReduceObject *loop;
+ intp i, n;
+ char *dptr;
+ NPY_BEGIN_THREADS_DEF
/* Construct loop object */
loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_REDUCE, 0,
- "reduce");
- if (!loop) return NULL;
+ "reduce");
+ if (!loop) return NULL;
- NPY_LOOP_BEGIN_THREADS
+ NPY_LOOP_BEGIN_THREADS
switch(loop->meth) {
case ZERO_EL_REDUCELOOP:
- /* fprintf(stderr, "ZERO..%d\n", loop->size); */
- for(i=0; i<loop->size; i++) {
- if (loop->obj) Py_INCREF(*((PyObject **)loop->idptr));
- memmove(loop->bufptr[0], loop->idptr, loop->outsize);
- loop->bufptr[0] += loop->outsize;
- }
- break;
+ /* fprintf(stderr, "ZERO..%d\n", loop->size); */
+ for(i=0; i<loop->size; i++) {
+ if (loop->obj) Py_INCREF(*((PyObject **)loop->idptr));
+ memmove(loop->bufptr[0], loop->idptr, loop->outsize);
+ loop->bufptr[0] += loop->outsize;
+ }
+ break;
case ONE_EL_REDUCELOOP:
- /*fprintf(stderr, "ONEDIM..%d\n", loop->size); */
- while(loop->index < loop->size) {
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->it->dataptr));
- memmove(loop->bufptr[0], loop->it->dataptr,
- loop->outsize);
- PyArray_ITER_NEXT(loop->it);
- loop->bufptr[0] += loop->outsize;
- loop->index++;
- }
- break;
+ /*fprintf(stderr, "ONEDIM..%d\n", loop->size); */
+ while(loop->index < loop->size) {
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->it->dataptr));
+ memmove(loop->bufptr[0], loop->it->dataptr,
+ loop->outsize);
+ PyArray_ITER_NEXT(loop->it);
+ loop->bufptr[0] += loop->outsize;
+ loop->index++;
+ }
+ break;
case NOBUFFER_UFUNCLOOP:
- /*fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
- while(loop->index < loop->size) {
- /* Copy first element to output */
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->it->dataptr));
- memmove(loop->bufptr[0], loop->it->dataptr,
- loop->outsize);
- /* Adjust input pointer */
- loop->bufptr[1] = loop->it->dataptr+loop->steps[1];
- loop->function((char **)loop->bufptr,
- &(loop->N),
- loop->steps, loop->funcdata);
- UFUNC_CHECK_ERROR(loop);
-
- PyArray_ITER_NEXT(loop->it)
- loop->bufptr[0] += loop->outsize;
- loop->bufptr[2] = loop->bufptr[0];
- loop->index++;
- }
- break;
+ /*fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
+ while(loop->index < loop->size) {
+ /* Copy first element to output */
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->it->dataptr));
+ memmove(loop->bufptr[0], loop->it->dataptr,
+ loop->outsize);
+ /* Adjust input pointer */
+ loop->bufptr[1] = loop->it->dataptr+loop->steps[1];
+ loop->function((char **)loop->bufptr,
+ &(loop->N),
+ loop->steps, loop->funcdata);
+ UFUNC_CHECK_ERROR(loop);
+
+ PyArray_ITER_NEXT(loop->it)
+ loop->bufptr[0] += loop->outsize;
+ loop->bufptr[2] = loop->bufptr[0];
+ loop->index++;
+ }
+ break;
case BUFFER_UFUNCLOOP:
- /* use buffer for arr */
- /*
- For each row to reduce
- 1. copy first item over to output (casting if necessary)
- 2. Fill inner buffer
- 3. When buffer is filled or end of row
- a. Cast input buffers if needed
- b. Call inner function.
- 4. Repeat 2 until row is done.
- */
- /* fprintf(stderr, "BUFFERED..%d %d\n", loop->size,
- loop->swap); */
- while(loop->index < loop->size) {
- loop->inptr = loop->it->dataptr;
- /* Copy (cast) First term over to output */
- if (loop->cast) {
- /* A little tricky because we need to
- cast it first */
- arr->descr->f->copyswap(loop->buffer,
- loop->inptr,
- loop->swap,
- NULL);
- loop->cast(loop->buffer, loop->castbuf,
- 1, NULL, NULL);
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->castbuf));
- memcpy(loop->bufptr[0], loop->castbuf,
- loop->outsize);
- }
- else { /* Simple copy */
- arr->descr->f->copyswap(loop->bufptr[0],
- loop->inptr,
- loop->swap, NULL);
- }
- loop->inptr += loop->instrides;
- n = 1;
- while(n < loop->N) {
- /* Copy up to loop->bufsize elements to
- buffer */
- dptr = loop->buffer;
- for (i=0; i<loop->bufsize; i++, n++) {
- if (n == loop->N) break;
- arr->descr->f->copyswap(dptr,
- loop->inptr,
- loop->swap,
- NULL);
- loop->inptr += loop->instrides;
- dptr += loop->insize;
- }
- if (loop->cast)
- loop->cast(loop->buffer,
- loop->castbuf,
- i, NULL, NULL);
- loop->function((char **)loop->bufptr,
- &i,
- loop->steps, loop->funcdata);
- loop->bufptr[0] += loop->steps[0]*i;
- loop->bufptr[2] += loop->steps[2]*i;
- UFUNC_CHECK_ERROR(loop);
- }
- PyArray_ITER_NEXT(loop->it);
- loop->bufptr[0] += loop->outsize;
- loop->bufptr[2] = loop->bufptr[0];
- loop->index++;
+ /* use buffer for arr */
+ /*
+ For each row to reduce
+ 1. copy first item over to output (casting if necessary)
+ 2. Fill inner buffer
+ 3. When buffer is filled or end of row
+ a. Cast input buffers if needed
+ b. Call inner function.
+ 4. Repeat 2 until row is done.
+ */
+ /* fprintf(stderr, "BUFFERED..%d %d\n", loop->size,
+ loop->swap); */
+ while(loop->index < loop->size) {
+ loop->inptr = loop->it->dataptr;
+ /* Copy (cast) First term over to output */
+ if (loop->cast) {
+ /* A little tricky because we need to
+ cast it first */
+ arr->descr->f->copyswap(loop->buffer,
+ loop->inptr,
+ loop->swap,
+ NULL);
+ loop->cast(loop->buffer, loop->castbuf,
+ 1, NULL, NULL);
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->castbuf));
+ memcpy(loop->bufptr[0], loop->castbuf,
+ loop->outsize);
+ }
+ else { /* Simple copy */
+ arr->descr->f->copyswap(loop->bufptr[0],
+ loop->inptr,
+ loop->swap, NULL);
}
+ loop->inptr += loop->instrides;
+ n = 1;
+ while(n < loop->N) {
+ /* Copy up to loop->bufsize elements to
+ buffer */
+ dptr = loop->buffer;
+ for (i=0; i<loop->bufsize; i++, n++) {
+ if (n == loop->N) break;
+ arr->descr->f->copyswap(dptr,
+ loop->inptr,
+ loop->swap,
+ NULL);
+ loop->inptr += loop->instrides;
+ dptr += loop->insize;
+ }
+ if (loop->cast)
+ loop->cast(loop->buffer,
+ loop->castbuf,
+ i, NULL, NULL);
+ loop->function((char **)loop->bufptr,
+ &i,
+ loop->steps, loop->funcdata);
+ loop->bufptr[0] += loop->steps[0]*i;
+ loop->bufptr[2] += loop->steps[2]*i;
+ UFUNC_CHECK_ERROR(loop);
+ }
+ PyArray_ITER_NEXT(loop->it);
+ loop->bufptr[0] += loop->outsize;
+ loop->bufptr[2] = loop->bufptr[0];
+ loop->index++;
+ }
}
- NPY_LOOP_END_THREADS
+ NPY_LOOP_END_THREADS
- /* Hang on to this reference -- will be decref'd with loop */
+ /* Hang on to this reference -- will be decref'd with loop */
if (loop->retbase) ret = (PyArrayObject *)loop->ret->base;
else ret = loop->ret;
- Py_INCREF(ret);
- ufuncreduce_dealloc(loop);
- return (PyObject *)ret;
+ Py_INCREF(ret);
+ ufuncreduce_dealloc(loop);
+ return (PyObject *)ret;
fail:
- NPY_LOOP_END_THREADS
+ NPY_LOOP_END_THREADS
if (loop) ufuncreduce_dealloc(loop);
- return NULL;
+ return NULL;
}
@@ -2482,456 +2480,456 @@ static PyObject *
PyUFunc_Accumulate(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out,
int axis, int otype)
{
- PyArrayObject *ret=NULL;
- PyUFuncReduceObject *loop;
- intp i, n;
- char *dptr;
- NPY_BEGIN_THREADS_DEF
+ PyArrayObject *ret=NULL;
+ PyUFuncReduceObject *loop;
+ intp i, n;
+ char *dptr;
+ NPY_BEGIN_THREADS_DEF
/* Construct loop object */
loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_ACCUMULATE, 0,
- "accumulate");
- if (!loop) return NULL;
+ "accumulate");
+ if (!loop) return NULL;
- NPY_LOOP_BEGIN_THREADS
+ NPY_LOOP_BEGIN_THREADS
switch(loop->meth) {
case ZERO_EL_REDUCELOOP: /* Accumulate */
- /* fprintf(stderr, "ZERO..%d\n", loop->size); */
- for(i=0; i<loop->size; i++) {
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->idptr));
- memcpy(loop->bufptr[0], loop->idptr, loop->outsize);
- loop->bufptr[0] += loop->outsize;
- }
- break;
+ /* fprintf(stderr, "ZERO..%d\n", loop->size); */
+ for(i=0; i<loop->size; i++) {
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->idptr));
+ memcpy(loop->bufptr[0], loop->idptr, loop->outsize);
+ loop->bufptr[0] += loop->outsize;
+ }
+ break;
case ONE_EL_REDUCELOOP: /* Accumulate */
- /* fprintf(stderr, "ONEDIM..%d\n", loop->size); */
- while(loop->index < loop->size) {
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->it->dataptr));
- memcpy(loop->bufptr[0], loop->it->dataptr,
- loop->outsize);
- PyArray_ITER_NEXT(loop->it);
- loop->bufptr[0] += loop->outsize;
- loop->index++;
- }
- break;
+ /* fprintf(stderr, "ONEDIM..%d\n", loop->size); */
+ while(loop->index < loop->size) {
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->it->dataptr));
+ memcpy(loop->bufptr[0], loop->it->dataptr,
+ loop->outsize);
+ PyArray_ITER_NEXT(loop->it);
+ loop->bufptr[0] += loop->outsize;
+ loop->index++;
+ }
+ break;
case NOBUFFER_UFUNCLOOP: /* Accumulate */
- /* fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
- while(loop->index < loop->size) {
- /* Copy first element to output */
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->it->dataptr));
- memcpy(loop->bufptr[0], loop->it->dataptr,
- loop->outsize);
- /* Adjust input pointer */
- loop->bufptr[1] = loop->it->dataptr+loop->steps[1];
- loop->function((char **)loop->bufptr,
- &(loop->N),
- loop->steps, loop->funcdata);
- UFUNC_CHECK_ERROR(loop);
-
- PyArray_ITER_NEXT(loop->it);
- PyArray_ITER_NEXT(loop->rit);
- loop->bufptr[0] = loop->rit->dataptr;
- loop->bufptr[2] = loop->bufptr[0] + loop->steps[0];
- loop->index++;
- }
- break;
+ /* fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
+ while(loop->index < loop->size) {
+ /* Copy first element to output */
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->it->dataptr));
+ memcpy(loop->bufptr[0], loop->it->dataptr,
+ loop->outsize);
+ /* Adjust input pointer */
+ loop->bufptr[1] = loop->it->dataptr+loop->steps[1];
+ loop->function((char **)loop->bufptr,
+ &(loop->N),
+ loop->steps, loop->funcdata);
+ UFUNC_CHECK_ERROR(loop);
+
+ PyArray_ITER_NEXT(loop->it);
+ PyArray_ITER_NEXT(loop->rit);
+ loop->bufptr[0] = loop->rit->dataptr;
+ loop->bufptr[2] = loop->bufptr[0] + loop->steps[0];
+ loop->index++;
+ }
+ break;
case BUFFER_UFUNCLOOP: /* Accumulate */
- /* use buffer for arr */
- /*
- For each row to reduce
- 1. copy identity over to output (casting if necessary)
- 2. Fill inner buffer
- 3. When buffer is filled or end of row
- a. Cast input buffers if needed
- b. Call inner function.
- 4. Repeat 2 until row is done.
- */
- /* fprintf(stderr, "BUFFERED..%d %p\n", loop->size,
- loop->cast); */
- while(loop->index < loop->size) {
- loop->inptr = loop->it->dataptr;
- /* Copy (cast) First term over to output */
- if (loop->cast) {
- /* A little tricky because we need to
- cast it first */
- arr->descr->f->copyswap(loop->buffer,
- loop->inptr,
- loop->swap,
- NULL);
- loop->cast(loop->buffer, loop->castbuf,
- 1, NULL, NULL);
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->castbuf));
- memcpy(loop->bufptr[0], loop->castbuf,
- loop->outsize);
- }
- else { /* Simple copy */
- arr->descr->f->copyswap(loop->bufptr[0],
- loop->inptr,
- loop->swap,
- NULL);
- }
- loop->inptr += loop->instrides;
- n = 1;
- while(n < loop->N) {
- /* Copy up to loop->bufsize elements to
- buffer */
- dptr = loop->buffer;
- for (i=0; i<loop->bufsize; i++, n++) {
- if (n == loop->N) break;
- arr->descr->f->copyswap(dptr,
- loop->inptr,
- loop->swap,
- NULL);
- loop->inptr += loop->instrides;
- dptr += loop->insize;
- }
- if (loop->cast)
- loop->cast(loop->buffer,
- loop->castbuf,
- i, NULL, NULL);
- loop->function((char **)loop->bufptr,
- &i,
- loop->steps, loop->funcdata);
- loop->bufptr[0] += loop->steps[0]*i;
- loop->bufptr[2] += loop->steps[2]*i;
- UFUNC_CHECK_ERROR(loop);
- }
- PyArray_ITER_NEXT(loop->it);
- PyArray_ITER_NEXT(loop->rit);
- loop->bufptr[0] = loop->rit->dataptr;
- loop->bufptr[2] = loop->bufptr[0] + loop->steps[0];
- loop->index++;
+ /* use buffer for arr */
+ /*
+ For each row to reduce
+ 1. copy identity over to output (casting if necessary)
+ 2. Fill inner buffer
+ 3. When buffer is filled or end of row
+ a. Cast input buffers if needed
+ b. Call inner function.
+ 4. Repeat 2 until row is done.
+ */
+ /* fprintf(stderr, "BUFFERED..%d %p\n", loop->size,
+ loop->cast); */
+ while(loop->index < loop->size) {
+ loop->inptr = loop->it->dataptr;
+ /* Copy (cast) First term over to output */
+ if (loop->cast) {
+ /* A little tricky because we need to
+ cast it first */
+ arr->descr->f->copyswap(loop->buffer,
+ loop->inptr,
+ loop->swap,
+ NULL);
+ loop->cast(loop->buffer, loop->castbuf,
+ 1, NULL, NULL);
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->castbuf));
+ memcpy(loop->bufptr[0], loop->castbuf,
+ loop->outsize);
+ }
+ else { /* Simple copy */
+ arr->descr->f->copyswap(loop->bufptr[0],
+ loop->inptr,
+ loop->swap,
+ NULL);
}
+ loop->inptr += loop->instrides;
+ n = 1;
+ while(n < loop->N) {
+ /* Copy up to loop->bufsize elements to
+ buffer */
+ dptr = loop->buffer;
+ for (i=0; i<loop->bufsize; i++, n++) {
+ if (n == loop->N) break;
+ arr->descr->f->copyswap(dptr,
+ loop->inptr,
+ loop->swap,
+ NULL);
+ loop->inptr += loop->instrides;
+ dptr += loop->insize;
+ }
+ if (loop->cast)
+ loop->cast(loop->buffer,
+ loop->castbuf,
+ i, NULL, NULL);
+ loop->function((char **)loop->bufptr,
+ &i,
+ loop->steps, loop->funcdata);
+ loop->bufptr[0] += loop->steps[0]*i;
+ loop->bufptr[2] += loop->steps[2]*i;
+ UFUNC_CHECK_ERROR(loop);
+ }
+ PyArray_ITER_NEXT(loop->it);
+ PyArray_ITER_NEXT(loop->rit);
+ loop->bufptr[0] = loop->rit->dataptr;
+ loop->bufptr[2] = loop->bufptr[0] + loop->steps[0];
+ loop->index++;
+ }
}
- NPY_LOOP_END_THREADS
+ NPY_LOOP_END_THREADS
- /* Hang on to this reference -- will be decref'd with loop */
+ /* Hang on to this reference -- will be decref'd with loop */
if (loop->retbase) ret = (PyArrayObject *)loop->ret->base;
else ret = loop->ret;
- Py_INCREF(ret);
- ufuncreduce_dealloc(loop);
- return (PyObject *)ret;
+ Py_INCREF(ret);
+ ufuncreduce_dealloc(loop);
+ return (PyObject *)ret;
fail:
- NPY_LOOP_END_THREADS
+ NPY_LOOP_END_THREADS
if (loop) ufuncreduce_dealloc(loop);
- return NULL;
+ return NULL;
}
/* Reduceat performs a reduce over an axis using the indices as a guide
-op.reduceat(array,indices) computes
-op.reduce(array[indices[i]:indices[i+1]]
+ op.reduceat(array,indices) computes
+ op.reduce(array[indices[i]:indices[i+1]]
for i=0..end with an implicit indices[i+1]=len(array)
- assumed when i=end-1
+ assumed when i=end-1
-if indices[i+1] <= indices[i]+1
+ if indices[i+1] <= indices[i]+1
then the result is array[indices[i]] for that value
-op.accumulate(array) is the same as
-op.reduceat(array,indices)[::2]
-where indices is range(len(array)-1) with a zero placed in every other sample
- indices = zeros(len(array)*2-1)
- indices[1::2] = range(1,len(array))
+ op.accumulate(array) is the same as
+ op.reduceat(array,indices)[::2]
+ where indices is range(len(array)-1) with a zero placed in every other sample
+ indices = zeros(len(array)*2-1)
+ indices[1::2] = range(1,len(array))
-output shape is based on the size of indices
- */
+ output shape is based on the size of indices
+*/
static PyObject *
PyUFunc_Reduceat(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *ind,
PyArrayObject *out, int axis, int otype)
{
- PyArrayObject *ret;
- PyUFuncReduceObject *loop;
- intp *ptr=(intp *)ind->data;
- intp nn=ind->dimensions[0];
- intp mm=arr->dimensions[axis]-1;
- intp n, i, j;
- char *dptr;
- NPY_BEGIN_THREADS_DEF
-
- /* Check for out-of-bounds values in indices array */
- for (i=0; i<nn; i++) {
- if ((*ptr < 0) || (*ptr > mm)) {
- PyErr_Format(PyExc_IndexError,
- "index out-of-bounds (0, %d)", (int) mm);
- return NULL;
- }
- ptr++;
- }
-
- ptr = (intp *)ind->data;
- /* Construct loop object */
- loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_REDUCEAT, nn,
- "reduceat");
- if (!loop) return NULL;
-
- NPY_LOOP_BEGIN_THREADS
- switch(loop->meth) {
- /* zero-length index -- return array immediately */
- case ZERO_EL_REDUCELOOP:
- /* fprintf(stderr, "ZERO..\n"); */
- break;
- /* NOBUFFER -- behaved array and same type */
- case NOBUFFER_UFUNCLOOP: /* Reduceat */
- /* fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
- while(loop->index < loop->size) {
- ptr = (intp *)ind->data;
- for (i=0; i<nn; i++) {
- loop->bufptr[1] = loop->it->dataptr + \
- (*ptr)*loop->instrides;
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->bufptr[1]));
- memcpy(loop->bufptr[0], loop->bufptr[1],
- loop->outsize);
- mm = (i==nn-1 ? arr->dimensions[axis]-*ptr : \
- *(ptr+1) - *ptr) - 1;
- if (mm > 0) {
- loop->bufptr[1] += loop->instrides;
- loop->bufptr[2] = loop->bufptr[0];
- loop->function((char **)loop->bufptr,
- &mm, loop->steps,
- loop->funcdata);
- UFUNC_CHECK_ERROR(loop);
- }
- loop->bufptr[0] += loop->ret->strides[axis];
- ptr++;
- }
- PyArray_ITER_NEXT(loop->it);
- PyArray_ITER_NEXT(loop->rit);
- loop->bufptr[0] = loop->rit->dataptr;
- loop->index++;
- }
- break;
-
- /* BUFFER -- misbehaved array or different types */
- case BUFFER_UFUNCLOOP: /* Reduceat */
- /* fprintf(stderr, "BUFFERED..%d\n", loop->size); */
- while(loop->index < loop->size) {
- ptr = (intp *)ind->data;
- for (i=0; i<nn; i++) {
- if (loop->obj)
- Py_INCREF(*((PyObject **)loop->idptr));
- memcpy(loop->bufptr[0], loop->idptr,
- loop->outsize);
- n = 0;
- mm = (i==nn-1 ? arr->dimensions[axis] - *ptr :\
- *(ptr+1) - *ptr);
- if (mm < 1) mm = 1;
- loop->inptr = loop->it->dataptr + \
- (*ptr)*loop->instrides;
- while (n < mm) {
- /* Copy up to loop->bufsize elements
- to buffer */
- dptr = loop->buffer;
- for (j=0; j<loop->bufsize; j++, n++) {
- if (n == mm) break;
- arr->descr->f->copyswap\
- (dptr,
- loop->inptr,
- loop->swap, NULL);
- loop->inptr += loop->instrides;
- dptr += loop->insize;
- }
- if (loop->cast)
- loop->cast(loop->buffer,
- loop->castbuf,
- j, NULL, NULL);
- loop->bufptr[2] = loop->bufptr[0];
- loop->function((char **)loop->bufptr,
- &j, loop->steps,
- loop->funcdata);
- UFUNC_CHECK_ERROR(loop);
- loop->bufptr[0] += j*loop->steps[0];
- }
- loop->bufptr[0] += loop->ret->strides[axis];
- ptr++;
- }
- PyArray_ITER_NEXT(loop->it);
- PyArray_ITER_NEXT(loop->rit);
- loop->bufptr[0] = loop->rit->dataptr;
- loop->index++;
- }
- break;
- }
-
- NPY_LOOP_END_THREADS
+ PyArrayObject *ret;
+ PyUFuncReduceObject *loop;
+ intp *ptr=(intp *)ind->data;
+ intp nn=ind->dimensions[0];
+ intp mm=arr->dimensions[axis]-1;
+ intp n, i, j;
+ char *dptr;
+ NPY_BEGIN_THREADS_DEF
+
+ /* Check for out-of-bounds values in indices array */
+ for (i=0; i<nn; i++) {
+ if ((*ptr < 0) || (*ptr > mm)) {
+ PyErr_Format(PyExc_IndexError,
+ "index out-of-bounds (0, %d)", (int) mm);
+ return NULL;
+ }
+ ptr++;
+ }
+
+ ptr = (intp *)ind->data;
+ /* Construct loop object */
+ loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_REDUCEAT, nn,
+ "reduceat");
+ if (!loop) return NULL;
+
+ NPY_LOOP_BEGIN_THREADS
+ switch(loop->meth) {
+ /* zero-length index -- return array immediately */
+ case ZERO_EL_REDUCELOOP:
+ /* fprintf(stderr, "ZERO..\n"); */
+ break;
+ /* NOBUFFER -- behaved array and same type */
+ case NOBUFFER_UFUNCLOOP: /* Reduceat */
+ /* fprintf(stderr, "NOBUFFER..%d\n", loop->size); */
+ while(loop->index < loop->size) {
+ ptr = (intp *)ind->data;
+ for (i=0; i<nn; i++) {
+ loop->bufptr[1] = loop->it->dataptr + \
+ (*ptr)*loop->instrides;
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->bufptr[1]));
+ memcpy(loop->bufptr[0], loop->bufptr[1],
+ loop->outsize);
+ mm = (i==nn-1 ? arr->dimensions[axis]-*ptr : \
+ *(ptr+1) - *ptr) - 1;
+ if (mm > 0) {
+ loop->bufptr[1] += loop->instrides;
+ loop->bufptr[2] = loop->bufptr[0];
+ loop->function((char **)loop->bufptr,
+ &mm, loop->steps,
+ loop->funcdata);
+ UFUNC_CHECK_ERROR(loop);
+ }
+ loop->bufptr[0] += loop->ret->strides[axis];
+ ptr++;
+ }
+ PyArray_ITER_NEXT(loop->it);
+ PyArray_ITER_NEXT(loop->rit);
+ loop->bufptr[0] = loop->rit->dataptr;
+ loop->index++;
+ }
+ break;
+
+ /* BUFFER -- misbehaved array or different types */
+ case BUFFER_UFUNCLOOP: /* Reduceat */
+ /* fprintf(stderr, "BUFFERED..%d\n", loop->size); */
+ while(loop->index < loop->size) {
+ ptr = (intp *)ind->data;
+ for (i=0; i<nn; i++) {
+ if (loop->obj)
+ Py_INCREF(*((PyObject **)loop->idptr));
+ memcpy(loop->bufptr[0], loop->idptr,
+ loop->outsize);
+ n = 0;
+ mm = (i==nn-1 ? arr->dimensions[axis] - *ptr :\
+ *(ptr+1) - *ptr);
+ if (mm < 1) mm = 1;
+ loop->inptr = loop->it->dataptr + \
+ (*ptr)*loop->instrides;
+ while (n < mm) {
+ /* Copy up to loop->bufsize elements
+ to buffer */
+ dptr = loop->buffer;
+ for (j=0; j<loop->bufsize; j++, n++) {
+ if (n == mm) break;
+ arr->descr->f->copyswap\
+ (dptr,
+ loop->inptr,
+ loop->swap, NULL);
+ loop->inptr += loop->instrides;
+ dptr += loop->insize;
+ }
+ if (loop->cast)
+ loop->cast(loop->buffer,
+ loop->castbuf,
+ j, NULL, NULL);
+ loop->bufptr[2] = loop->bufptr[0];
+ loop->function((char **)loop->bufptr,
+ &j, loop->steps,
+ loop->funcdata);
+ UFUNC_CHECK_ERROR(loop);
+ loop->bufptr[0] += j*loop->steps[0];
+ }
+ loop->bufptr[0] += loop->ret->strides[axis];
+ ptr++;
+ }
+ PyArray_ITER_NEXT(loop->it);
+ PyArray_ITER_NEXT(loop->rit);
+ loop->bufptr[0] = loop->rit->dataptr;
+ loop->index++;
+ }
+ break;
+ }
+
+ NPY_LOOP_END_THREADS
/* Hang on to this reference -- will be decref'd with loop */
if (loop->retbase) ret = (PyArrayObject *)loop->ret->base;
else ret = loop->ret;
- Py_INCREF(ret);
- ufuncreduce_dealloc(loop);
- return (PyObject *)ret;
+ Py_INCREF(ret);
+ ufuncreduce_dealloc(loop);
+ return (PyObject *)ret;
fail:
- NPY_LOOP_END_THREADS
+ NPY_LOOP_END_THREADS
if (loop) ufuncreduce_dealloc(loop);
- return NULL;
+ return NULL;
}
/* This code handles reduce, reduceat, and accumulate
(accumulate and reduce are special cases of the more general reduceat
- but they are handled separately for speed)
+ but they are handled separately for speed)
*/
static PyObject *
PyUFunc_GenericReduction(PyUFuncObject *self, PyObject *args,
PyObject *kwds, int operation)
{
- int axis=0;
- PyArrayObject *mp, *ret = NULL;
- PyObject *op, *res=NULL;
- PyObject *obj_ind, *context;
- PyArrayObject *indices = NULL;
- PyArray_Descr *otype=NULL;
- PyArrayObject *out=NULL;
- static char *kwlist1[] = {"array", "axis", "dtype", "out", NULL};
- static char *kwlist2[] = {"array", "indices", "axis", "dtype", "out", NULL};
- static char *_reduce_type[] = {"reduce", "accumulate", \
- "reduceat", NULL};
- if (self == NULL) {
- PyErr_SetString(PyExc_ValueError, "function not supported");
- return NULL;
- }
-
- if (self->nin != 2) {
- PyErr_Format(PyExc_ValueError,
- "%s only supported for binary functions",
- _reduce_type[operation]);
- return NULL;
- }
- if (self->nout != 1) {
- PyErr_Format(PyExc_ValueError,
- "%s only supported for functions " \
- "returning a single value",
- _reduce_type[operation]);
- return NULL;
- }
-
- if (operation == UFUNC_REDUCEAT) {
- PyArray_Descr *indtype;
- indtype = PyArray_DescrFromType(PyArray_INTP);
- if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO|iO&O&", kwlist2,
- &op, &obj_ind, &axis,
- PyArray_DescrConverter2,
- &otype,
- PyArray_OutputConverter,
- &out)) return NULL;
- indices = (PyArrayObject *)PyArray_FromAny(obj_ind, indtype,
- 1, 1, CARRAY, NULL);
- if (indices == NULL) return NULL;
- }
- else {
- if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|iO&O&", kwlist1,
- &op, &axis,
- PyArray_DescrConverter2,
- &otype,
- PyArray_OutputConverter,
- &out)) return NULL;
- }
-
- /* Ensure input is an array */
- if (!PyArray_Check(op) && !PyArray_IsScalar(op, Generic)) {
- context = Py_BuildValue("O(O)i", self, op, 0);
- }
- else {
- context = NULL;
- }
- mp = (PyArrayObject *)PyArray_FromAny(op, NULL, 0, 0, 0, context);
- Py_XDECREF(context);
- if (mp == NULL) return NULL;
+ int axis=0;
+ PyArrayObject *mp, *ret = NULL;
+ PyObject *op, *res=NULL;
+ PyObject *obj_ind, *context;
+ PyArrayObject *indices = NULL;
+ PyArray_Descr *otype=NULL;
+ PyArrayObject *out=NULL;
+ static char *kwlist1[] = {"array", "axis", "dtype", "out", NULL};
+ static char *kwlist2[] = {"array", "indices", "axis", "dtype", "out", NULL};
+ static char *_reduce_type[] = {"reduce", "accumulate", \
+ "reduceat", NULL};
+ if (self == NULL) {
+ PyErr_SetString(PyExc_ValueError, "function not supported");
+ return NULL;
+ }
- /* Check to see if input is zero-dimensional */
- if (mp->nd == 0) {
- PyErr_Format(PyExc_TypeError, "cannot %s on a scalar",
- _reduce_type[operation]);
- Py_DECREF(mp);
- return NULL;
- }
+ if (self->nin != 2) {
+ PyErr_Format(PyExc_ValueError,
+ "%s only supported for binary functions",
+ _reduce_type[operation]);
+ return NULL;
+ }
+ if (self->nout != 1) {
+ PyErr_Format(PyExc_ValueError,
+ "%s only supported for functions " \
+ "returning a single value",
+ _reduce_type[operation]);
+ return NULL;
+ }
- /* Check to see that type (and otype) is not FLEXIBLE */
- if (PyArray_ISFLEXIBLE(mp) ||
- (otype && PyTypeNum_ISFLEXIBLE(otype->type_num))) {
- PyErr_Format(PyExc_TypeError,
- "cannot perform %s with flexible type",
- _reduce_type[operation]);
- Py_DECREF(mp);
- return NULL;
- }
+ if (operation == UFUNC_REDUCEAT) {
+ PyArray_Descr *indtype;
+ indtype = PyArray_DescrFromType(PyArray_INTP);
+ if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO|iO&O&", kwlist2,
+ &op, &obj_ind, &axis,
+ PyArray_DescrConverter2,
+ &otype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
+ indices = (PyArrayObject *)PyArray_FromAny(obj_ind, indtype,
+ 1, 1, CARRAY, NULL);
+ if (indices == NULL) return NULL;
+ }
+ else {
+ if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|iO&O&", kwlist1,
+ &op, &axis,
+ PyArray_DescrConverter2,
+ &otype,
+ PyArray_OutputConverter,
+ &out)) return NULL;
+ }
- if (axis < 0) axis += mp->nd;
- if (axis < 0 || axis >= mp->nd) {
- PyErr_SetString(PyExc_ValueError, "axis not in array");
- Py_DECREF(mp);
- return NULL;
- }
-
- /* If out is specified it determines otype unless otype
- already specified.
- */
- if (otype == NULL && out != NULL) {
- otype = out->descr;
- Py_INCREF(otype);
- }
-
- if (otype == NULL) {
- /* For integer types --- make sure at
- least a long is used for add and multiply
- reduction --- to avoid overflow */
- int typenum = PyArray_TYPE(mp);
- if ((typenum < NPY_FLOAT) && \
- ((strcmp(self->name,"add")==0) || \
- (strcmp(self->name,"multiply")==0))) {
- if (PyTypeNum_ISBOOL(typenum))
- typenum = PyArray_LONG;
- else if (mp->descr->elsize < sizeof(long)) {
- if (PyTypeNum_ISUNSIGNED(typenum))
- typenum = PyArray_ULONG;
- else
- typenum = PyArray_LONG;
- }
- }
- otype = PyArray_DescrFromType(typenum);
+ /* Ensure input is an array */
+ if (!PyArray_Check(op) && !PyArray_IsScalar(op, Generic)) {
+ context = Py_BuildValue("O(O)i", self, op, 0);
+ }
+ else {
+ context = NULL;
+ }
+ mp = (PyArrayObject *)PyArray_FromAny(op, NULL, 0, 0, 0, context);
+ Py_XDECREF(context);
+ if (mp == NULL) return NULL;
+
+ /* Check to see if input is zero-dimensional */
+ if (mp->nd == 0) {
+ PyErr_Format(PyExc_TypeError, "cannot %s on a scalar",
+ _reduce_type[operation]);
+ Py_DECREF(mp);
+ return NULL;
+ }
+
+ /* Check to see that type (and otype) is not FLEXIBLE */
+ if (PyArray_ISFLEXIBLE(mp) ||
+ (otype && PyTypeNum_ISFLEXIBLE(otype->type_num))) {
+ PyErr_Format(PyExc_TypeError,
+ "cannot perform %s with flexible type",
+ _reduce_type[operation]);
+ Py_DECREF(mp);
+ return NULL;
+ }
+
+ if (axis < 0) axis += mp->nd;
+ if (axis < 0 || axis >= mp->nd) {
+ PyErr_SetString(PyExc_ValueError, "axis not in array");
+ Py_DECREF(mp);
+ return NULL;
+ }
+
+ /* If out is specified it determines otype unless otype
+ already specified.
+ */
+ if (otype == NULL && out != NULL) {
+ otype = out->descr;
+ Py_INCREF(otype);
+ }
+
+ if (otype == NULL) {
+ /* For integer types --- make sure at
+ least a long is used for add and multiply
+ reduction --- to avoid overflow */
+ int typenum = PyArray_TYPE(mp);
+ if ((typenum < NPY_FLOAT) && \
+ ((strcmp(self->name,"add")==0) || \
+ (strcmp(self->name,"multiply")==0))) {
+ if (PyTypeNum_ISBOOL(typenum))
+ typenum = PyArray_LONG;
+ else if (mp->descr->elsize < sizeof(long)) {
+ if (PyTypeNum_ISUNSIGNED(typenum))
+ typenum = PyArray_ULONG;
+ else
+ typenum = PyArray_LONG;
+ }
}
+ otype = PyArray_DescrFromType(typenum);
+ }
- switch(operation) {
- case UFUNC_REDUCE:
- ret = (PyArrayObject *)PyUFunc_Reduce(self, mp, out, axis,
- otype->type_num);
- break;
- case UFUNC_ACCUMULATE:
- ret = (PyArrayObject *)PyUFunc_Accumulate(self, mp, out, axis,
- otype->type_num);
- break;
- case UFUNC_REDUCEAT:
- ret = (PyArrayObject *)PyUFunc_Reduceat(self, mp, indices, out,
- axis, otype->type_num);
- Py_DECREF(indices);
- break;
+ switch(operation) {
+ case UFUNC_REDUCE:
+ ret = (PyArrayObject *)PyUFunc_Reduce(self, mp, out, axis,
+ otype->type_num);
+ break;
+ case UFUNC_ACCUMULATE:
+ ret = (PyArrayObject *)PyUFunc_Accumulate(self, mp, out, axis,
+ otype->type_num);
+ break;
+ case UFUNC_REDUCEAT:
+ ret = (PyArrayObject *)PyUFunc_Reduceat(self, mp, indices, out,
+ axis, otype->type_num);
+ Py_DECREF(indices);
+ break;
+ }
+ Py_DECREF(mp);
+ Py_DECREF(otype);
+ if (ret==NULL) return NULL;
+ if (op->ob_type != ret->ob_type) {
+ res = PyObject_CallMethod(op, "__array_wrap__", "O", ret);
+ if (res == NULL) PyErr_Clear();
+ else if (res == Py_None) Py_DECREF(res);
+ else {
+ Py_DECREF(ret);
+ return res;
}
- Py_DECREF(mp);
- Py_DECREF(otype);
- if (ret==NULL) return NULL;
- if (op->ob_type != ret->ob_type) {
- res = PyObject_CallMethod(op, "__array_wrap__", "O", ret);
- if (res == NULL) PyErr_Clear();
- else if (res == Py_None) Py_DECREF(res);
- else {
- Py_DECREF(ret);
- return res;
- }
- }
- return PyArray_Return(ret);
+ }
+ return PyArray_Return(ret);
}
@@ -2949,304 +2947,304 @@ PyUFunc_GenericReduction(PyUFuncObject *self, PyObject *args,
A NULL is placed in output_wrap for outputs that
should just have PyArray_Return called.
- */
+*/
static void
_find_array_wrap(PyObject *args, PyObject **output_wrap, int nin, int nout)
{
- Py_ssize_t nargs;
- int i;
- int np = 0;
- double priority, maxpriority;
- PyObject *with_wrap[NPY_MAXARGS], *wraps[NPY_MAXARGS];
- PyObject *obj, *wrap = NULL;
-
- nargs = PyTuple_GET_SIZE(args);
- for (i=0; i<nin; i++) {
- obj = PyTuple_GET_ITEM(args, i);
- if (PyArray_CheckExact(obj) || \
- PyArray_IsAnyScalar(obj))
- continue;
- wrap = PyObject_GetAttrString(obj, "__array_wrap__");
- if (wrap) {
- if (PyCallable_Check(wrap)) {
- with_wrap[np] = obj;
- wraps[np] = wrap;
- ++np;
- }
- else {
- Py_DECREF(wrap);
- wrap = NULL;
- }
- }
- else {
- PyErr_Clear();
- }
- }
- if (np >= 2) {
- wrap = wraps[0];
- maxpriority = PyArray_GetPriority(with_wrap[0],
- PyArray_SUBTYPE_PRIORITY);
- for (i = 1; i < np; ++i) {
- priority = \
- PyArray_GetPriority(with_wrap[i],
- PyArray_SUBTYPE_PRIORITY);
- if (priority > maxpriority) {
- maxpriority = priority;
- Py_DECREF(wrap);
- wrap = wraps[i];
- } else {
- Py_DECREF(wraps[i]);
- }
- }
+ Py_ssize_t nargs;
+ int i;
+ int np = 0;
+ double priority, maxpriority;
+ PyObject *with_wrap[NPY_MAXARGS], *wraps[NPY_MAXARGS];
+ PyObject *obj, *wrap = NULL;
+
+ nargs = PyTuple_GET_SIZE(args);
+ for (i=0; i<nin; i++) {
+ obj = PyTuple_GET_ITEM(args, i);
+ if (PyArray_CheckExact(obj) || \
+ PyArray_IsAnyScalar(obj))
+ continue;
+ wrap = PyObject_GetAttrString(obj, "__array_wrap__");
+ if (wrap) {
+ if (PyCallable_Check(wrap)) {
+ with_wrap[np] = obj;
+ wraps[np] = wrap;
+ ++np;
+ }
+ else {
+ Py_DECREF(wrap);
+ wrap = NULL;
+ }
}
+ else {
+ PyErr_Clear();
+ }
+ }
+ if (np >= 2) {
+ wrap = wraps[0];
+ maxpriority = PyArray_GetPriority(with_wrap[0],
+ PyArray_SUBTYPE_PRIORITY);
+ for (i = 1; i < np; ++i) {
+ priority = \
+ PyArray_GetPriority(with_wrap[i],
+ PyArray_SUBTYPE_PRIORITY);
+ if (priority > maxpriority) {
+ maxpriority = priority;
+ Py_DECREF(wrap);
+ wrap = wraps[i];
+ } else {
+ Py_DECREF(wraps[i]);
+ }
+ }
+ }
- /* Here wrap is the wrapping function determined from the
- input arrays (could be NULL).
-
- For all the output arrays decide what to do.
-
- 1) Use the wrap function determined from the input arrays
- This is the default if the output array is not
- passed in.
-
- 2) Use the __array_wrap__ method of the output object
- passed in. -- this is special cased for
- exact ndarray so that no PyArray_Return is
- done in that case.
- */
-
- for (i=0; i<nout; i++) {
- int j = nin + i;
- int incref=1;
- output_wrap[i] = wrap;
- if (j < nargs) {
- obj = PyTuple_GET_ITEM(args, j);
- if (obj == Py_None)
- continue;
- if (PyArray_CheckExact(obj)) {
- output_wrap[i] = Py_None;
- }
- else {
- PyObject *owrap;
- owrap = PyObject_GetAttrString \
- (obj,"__array_wrap__");
- incref=0;
- if (!(owrap) || !(PyCallable_Check(owrap))) {
- Py_XDECREF(owrap);
- owrap = wrap;
- incref=1;
- PyErr_Clear();
- }
- output_wrap[i] = owrap;
- }
- }
- if (incref) {
- Py_XINCREF(output_wrap[i]);
+ /* Here wrap is the wrapping function determined from the
+ input arrays (could be NULL).
+
+ For all the output arrays decide what to do.
+
+ 1) Use the wrap function determined from the input arrays
+ This is the default if the output array is not
+ passed in.
+
+ 2) Use the __array_wrap__ method of the output object
+ passed in. -- this is special cased for
+ exact ndarray so that no PyArray_Return is
+ done in that case.
+ */
+
+ for (i=0; i<nout; i++) {
+ int j = nin + i;
+ int incref=1;
+ output_wrap[i] = wrap;
+ if (j < nargs) {
+ obj = PyTuple_GET_ITEM(args, j);
+ if (obj == Py_None)
+ continue;
+ if (PyArray_CheckExact(obj)) {
+ output_wrap[i] = Py_None;
+ }
+ else {
+ PyObject *owrap;
+ owrap = PyObject_GetAttrString \
+ (obj,"__array_wrap__");
+ incref=0;
+ if (!(owrap) || !(PyCallable_Check(owrap))) {
+ Py_XDECREF(owrap);
+ owrap = wrap;
+ incref=1;
+ PyErr_Clear();
}
+ output_wrap[i] = owrap;
+ }
}
+ if (incref) {
+ Py_XINCREF(output_wrap[i]);
+ }
+ }
- Py_XDECREF(wrap);
- return;
+ Py_XDECREF(wrap);
+ return;
}
static PyObject *
ufunc_generic_call(PyUFuncObject *self, PyObject *args, PyObject *kwds)
{
- int i;
- PyTupleObject *ret;
- PyArrayObject *mps[NPY_MAXARGS];
- PyObject *retobj[NPY_MAXARGS];
- PyObject *wraparr[NPY_MAXARGS];
- PyObject *res;
- int errval;
-
- /* Initialize all array objects to NULL to make cleanup easier
- if something goes wrong. */
- for(i=0; i<self->nargs; i++) mps[i] = NULL;
-
- errval = PyUFunc_GenericFunction(self, args, kwds, mps);
- if (errval < 0) {
- for(i=0; i<self->nargs; i++) {
- PyArray_XDECREF_ERR(mps[i]);
- }
- if (errval == -1)
- return NULL;
- else {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- }
-
- for(i=0; i<self->nin; i++) Py_DECREF(mps[i]);
-
-
- /* Use __array_wrap__ on all outputs
- if present on one of the input arguments.
- If present for multiple inputs:
- use __array_wrap__ of input object with largest
- __array_priority__ (default = 0.0)
- */
-
- /* Exception: we should not wrap outputs for items already
- passed in as output-arguments. These items should either
- be left unwrapped or wrapped by calling their own __array_wrap__
- routine.
-
- For each output argument, wrap will be either
- NULL --- call PyArray_Return() -- default if no output arguments given
- None --- array-object passed in don't call PyArray_Return
- method --- the __array_wrap__ method to call.
+ int i;
+ PyTupleObject *ret;
+ PyArrayObject *mps[NPY_MAXARGS];
+ PyObject *retobj[NPY_MAXARGS];
+ PyObject *wraparr[NPY_MAXARGS];
+ PyObject *res;
+ int errval;
+
+ /* Initialize all array objects to NULL to make cleanup easier
+ if something goes wrong. */
+ for(i=0; i<self->nargs; i++) mps[i] = NULL;
+
+ errval = PyUFunc_GenericFunction(self, args, kwds, mps);
+ if (errval < 0) {
+ for(i=0; i<self->nargs; i++) {
+ PyArray_XDECREF_ERR(mps[i]);
+ }
+ if (errval == -1)
+ return NULL;
+ else {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ }
+
+ for(i=0; i<self->nin; i++) Py_DECREF(mps[i]);
+
+
+ /* Use __array_wrap__ on all outputs
+ if present on one of the input arguments.
+ If present for multiple inputs:
+ use __array_wrap__ of input object with largest
+ __array_priority__ (default = 0.0)
+ */
+
+ /* Exception: we should not wrap outputs for items already
+ passed in as output-arguments. These items should either
+ be left unwrapped or wrapped by calling their own __array_wrap__
+ routine.
+
+ For each output argument, wrap will be either
+ NULL --- call PyArray_Return() -- default if no output arguments given
+ None --- array-object passed in don't call PyArray_Return
+ method --- the __array_wrap__ method to call.
+ */
+ _find_array_wrap(args, wraparr, self->nin, self->nout);
+
+ /* wrap outputs */
+ for (i=0; i<self->nout; i++) {
+ int j=self->nin+i;
+ PyObject *wrap;
+ /* check to see if any UPDATEIFCOPY flags are set
+ which meant that a temporary output was generated
*/
- _find_array_wrap(args, wraparr, self->nin, self->nout);
-
- /* wrap outputs */
- for (i=0; i<self->nout; i++) {
- int j=self->nin+i;
- PyObject *wrap;
- /* check to see if any UPDATEIFCOPY flags are set
- which meant that a temporary output was generated
- */
- if (mps[j]->flags & UPDATEIFCOPY) {
- PyObject *old = mps[j]->base;
- Py_INCREF(old); /* we want to hang on to this */
- Py_DECREF(mps[j]); /* should trigger the copy
- back into old */
- mps[j] = (PyArrayObject *)old;
- }
- wrap = wraparr[i];
- if (wrap != NULL) {
- if (wrap == Py_None) {
- Py_DECREF(wrap);
- retobj[i] = (PyObject *)mps[j];
- continue;
- }
- res = PyObject_CallFunction(wrap, "O(OOi)",
- mps[j], self, args, i);
- if (res == NULL && \
- PyErr_ExceptionMatches(PyExc_TypeError)) {
- PyErr_Clear();
- res = PyObject_CallFunctionObjArgs(wrap,
- mps[j],
- NULL);
- }
- Py_DECREF(wrap);
- if (res == NULL) goto fail;
- else if (res == Py_None) Py_DECREF(res);
- else {
- Py_DECREF(mps[j]);
- retobj[i] = res;
- continue;
- }
- }
- /* default behavior */
- retobj[i] = PyArray_Return(mps[j]);
- }
-
- if (self->nout == 1) {
- return retobj[0];
- } else {
- ret = (PyTupleObject *)PyTuple_New(self->nout);
- for(i=0; i<self->nout; i++) {
- PyTuple_SET_ITEM(ret, i, retobj[i]);
- }
- return (PyObject *)ret;
- }
+ if (mps[j]->flags & UPDATEIFCOPY) {
+ PyObject *old = mps[j]->base;
+ Py_INCREF(old); /* we want to hang on to this */
+ Py_DECREF(mps[j]); /* should trigger the copy
+ back into old */
+ mps[j] = (PyArrayObject *)old;
+ }
+ wrap = wraparr[i];
+ if (wrap != NULL) {
+ if (wrap == Py_None) {
+ Py_DECREF(wrap);
+ retobj[i] = (PyObject *)mps[j];
+ continue;
+ }
+ res = PyObject_CallFunction(wrap, "O(OOi)",
+ mps[j], self, args, i);
+ if (res == NULL && \
+ PyErr_ExceptionMatches(PyExc_TypeError)) {
+ PyErr_Clear();
+ res = PyObject_CallFunctionObjArgs(wrap,
+ mps[j],
+ NULL);
+ }
+ Py_DECREF(wrap);
+ if (res == NULL) goto fail;
+ else if (res == Py_None) Py_DECREF(res);
+ else {
+ Py_DECREF(mps[j]);
+ retobj[i] = res;
+ continue;
+ }
+ }
+ /* default behavior */
+ retobj[i] = PyArray_Return(mps[j]);
+ }
+
+ if (self->nout == 1) {
+ return retobj[0];
+ } else {
+ ret = (PyTupleObject *)PyTuple_New(self->nout);
+ for(i=0; i<self->nout; i++) {
+ PyTuple_SET_ITEM(ret, i, retobj[i]);
+ }
+ return (PyObject *)ret;
+ }
fail:
- for(i=self->nin; i<self->nargs; i++) Py_XDECREF(mps[i]);
- return NULL;
+ for(i=self->nin; i<self->nargs; i++) Py_XDECREF(mps[i]);
+ return NULL;
}
static PyObject *
ufunc_geterr(PyObject *dummy, PyObject *args)
{
- PyObject *thedict;
- PyObject *res;
-
- if (!PyArg_ParseTuple(args, "")) return NULL;
-
- if (PyUFunc_PYVALS_NAME == NULL) {
- PyUFunc_PYVALS_NAME = PyString_InternFromString(UFUNC_PYVALS_NAME);
- }
- thedict = PyThreadState_GetDict();
- if (thedict == NULL) {
- thedict = PyEval_GetBuiltins();
- }
- res = PyDict_GetItem(thedict, PyUFunc_PYVALS_NAME);
- if (res != NULL) {
- Py_INCREF(res);
- return res;
- }
- /* Construct list of defaults */
- res = PyList_New(3);
- if (res == NULL) return NULL;
- PyList_SET_ITEM(res, 0, PyInt_FromLong(PyArray_BUFSIZE));
- PyList_SET_ITEM(res, 1, PyInt_FromLong(UFUNC_ERR_DEFAULT));
- PyList_SET_ITEM(res, 2, Py_None); Py_INCREF(Py_None);
- return res;
+ PyObject *thedict;
+ PyObject *res;
+
+ if (!PyArg_ParseTuple(args, "")) return NULL;
+
+ if (PyUFunc_PYVALS_NAME == NULL) {
+ PyUFunc_PYVALS_NAME = PyString_InternFromString(UFUNC_PYVALS_NAME);
+ }
+ thedict = PyThreadState_GetDict();
+ if (thedict == NULL) {
+ thedict = PyEval_GetBuiltins();
+ }
+ res = PyDict_GetItem(thedict, PyUFunc_PYVALS_NAME);
+ if (res != NULL) {
+ Py_INCREF(res);
+ return res;
+ }
+ /* Construct list of defaults */
+ res = PyList_New(3);
+ if (res == NULL) return NULL;
+ PyList_SET_ITEM(res, 0, PyInt_FromLong(PyArray_BUFSIZE));
+ PyList_SET_ITEM(res, 1, PyInt_FromLong(UFUNC_ERR_DEFAULT));
+ PyList_SET_ITEM(res, 2, Py_None); Py_INCREF(Py_None);
+ return res;
}
#if USE_USE_DEFAULTS==1
/*
-This is a strategy to buy a little speed up and avoid the dictionary
-look-up in the default case. It should work in the presence of
-threads. If it is deemed too complicated or it doesn't actually work
-it could be taken out.
+ This is a strategy to buy a little speed up and avoid the dictionary
+ look-up in the default case. It should work in the presence of
+ threads. If it is deemed too complicated or it doesn't actually work
+ it could be taken out.
*/
static int
ufunc_update_use_defaults(void)
{
- PyObject *errobj;
- int errmask, bufsize;
- int res;
+ PyObject *errobj;
+ int errmask, bufsize;
+ int res;
- PyUFunc_NUM_NODEFAULTS += 1;
- res = PyUFunc_GetPyValues("test", &bufsize, &errmask,
- &errobj);
- PyUFunc_NUM_NODEFAULTS -= 1;
+ PyUFunc_NUM_NODEFAULTS += 1;
+ res = PyUFunc_GetPyValues("test", &bufsize, &errmask,
+ &errobj);
+ PyUFunc_NUM_NODEFAULTS -= 1;
- if (res < 0) return -1;
+ if (res < 0) return -1;
- if ((errmask != UFUNC_ERR_DEFAULT) || \
- (bufsize != PyArray_BUFSIZE) || \
- (PyTuple_GET_ITEM(errobj, 1) != Py_None)) {
- PyUFunc_NUM_NODEFAULTS += 1;
- }
- else if (PyUFunc_NUM_NODEFAULTS > 0) {
- PyUFunc_NUM_NODEFAULTS -= 1;
- }
- return 0;
+ if ((errmask != UFUNC_ERR_DEFAULT) || \
+ (bufsize != PyArray_BUFSIZE) || \
+ (PyTuple_GET_ITEM(errobj, 1) != Py_None)) {
+ PyUFunc_NUM_NODEFAULTS += 1;
+ }
+ else if (PyUFunc_NUM_NODEFAULTS > 0) {
+ PyUFunc_NUM_NODEFAULTS -= 1;
+ }
+ return 0;
}
#endif
static PyObject *
ufunc_seterr(PyObject *dummy, PyObject *args)
{
- PyObject *thedict;
- int res;
- PyObject *val;
- static char *msg = "Error object must be a list of length 3";
-
- if (!PyArg_ParseTuple(args, "O", &val)) return NULL;
-
- if (!PyList_CheckExact(val) || PyList_GET_SIZE(val) != 3) {
- PyErr_SetString(PyExc_ValueError, msg);
- return NULL;
- }
- if (PyUFunc_PYVALS_NAME == NULL) {
- PyUFunc_PYVALS_NAME = PyString_InternFromString(UFUNC_PYVALS_NAME);
- }
- thedict = PyThreadState_GetDict();
- if (thedict == NULL) {
- thedict = PyEval_GetBuiltins();
- }
- res = PyDict_SetItem(thedict, PyUFunc_PYVALS_NAME, val);
- if (res < 0) return NULL;
+ PyObject *thedict;
+ int res;
+ PyObject *val;
+ static char *msg = "Error object must be a list of length 3";
+
+ if (!PyArg_ParseTuple(args, "O", &val)) return NULL;
+
+ if (!PyList_CheckExact(val) || PyList_GET_SIZE(val) != 3) {
+ PyErr_SetString(PyExc_ValueError, msg);
+ return NULL;
+ }
+ if (PyUFunc_PYVALS_NAME == NULL) {
+ PyUFunc_PYVALS_NAME = PyString_InternFromString(UFUNC_PYVALS_NAME);
+ }
+ thedict = PyThreadState_GetDict();
+ if (thedict == NULL) {
+ thedict = PyEval_GetBuiltins();
+ }
+ res = PyDict_SetItem(thedict, PyUFunc_PYVALS_NAME, val);
+ if (res < 0) return NULL;
#if USE_USE_DEFAULTS==1
- if (ufunc_update_use_defaults() < 0) return NULL;
+ if (ufunc_update_use_defaults() < 0) return NULL;
#endif
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -3258,312 +3256,312 @@ doc_frompyfunc[] = "frompyfunc(func, nin, nout) take an arbitrary python functio
static PyObject *
ufunc_frompyfunc(PyObject *dummy, PyObject *args, PyObject *kwds) {
- /* Keywords are ignored for now */
+ /* Keywords are ignored for now */
- PyObject *function, *pyname=NULL;
- int nin, nout, i;
- PyUFunc_PyFuncData *fdata;
- PyUFuncObject *self;
- char *fname, *str;
- Py_ssize_t fname_len=-1;
- int offset[2];
+ PyObject *function, *pyname=NULL;
+ int nin, nout, i;
+ PyUFunc_PyFuncData *fdata;
+ PyUFuncObject *self;
+ char *fname, *str;
+ Py_ssize_t fname_len=-1;
+ int offset[2];
- if (!PyArg_ParseTuple(args, "Oii", &function, &nin, &nout)) return NULL;
+ if (!PyArg_ParseTuple(args, "Oii", &function, &nin, &nout)) return NULL;
- if (!PyCallable_Check(function)) {
- PyErr_SetString(PyExc_TypeError, "function must be callable");
- return NULL;
- }
+ if (!PyCallable_Check(function)) {
+ PyErr_SetString(PyExc_TypeError, "function must be callable");
+ return NULL;
+ }
- self = _pya_malloc(sizeof(PyUFuncObject));
- if (self == NULL) return NULL;
- PyObject_Init((PyObject *)self, &PyUFunc_Type);
+ self = _pya_malloc(sizeof(PyUFuncObject));
+ if (self == NULL) return NULL;
+ PyObject_Init((PyObject *)self, &PyUFunc_Type);
- self->userloops = NULL;
- self->nin = nin;
- self->nout = nout;
- self->nargs = nin+nout;
- self->identity = PyUFunc_None;
- self->functions = pyfunc_functions;
+ self->userloops = NULL;
+ self->nin = nin;
+ self->nout = nout;
+ self->nargs = nin+nout;
+ self->identity = PyUFunc_None;
+ self->functions = pyfunc_functions;
- self->ntypes = 1;
- self->check_return = 0;
+ self->ntypes = 1;
+ self->check_return = 0;
- pyname = PyObject_GetAttrString(function, "__name__");
- if (pyname)
- (void) PyString_AsStringAndSize(pyname, &fname, &fname_len);
+ pyname = PyObject_GetAttrString(function, "__name__");
+ if (pyname)
+ (void) PyString_AsStringAndSize(pyname, &fname, &fname_len);
- if (PyErr_Occurred()) {
- fname = "?";
- fname_len = 1;
- PyErr_Clear();
- }
- Py_XDECREF(pyname);
+ if (PyErr_Occurred()) {
+ fname = "?";
+ fname_len = 1;
+ PyErr_Clear();
+ }
+ Py_XDECREF(pyname);
- /* self->ptr holds a pointer for enough memory for
- self->data[0] (fdata)
- self->data
- self->name
- self->types
+ /* self->ptr holds a pointer for enough memory for
+ self->data[0] (fdata)
+ self->data
+ self->name
+ self->types
- To be safest, all of these need their memory aligned on void * pointers
- Therefore, we may need to allocate extra space.
- */
- offset[0] = sizeof(PyUFunc_PyFuncData);
- i = (sizeof(PyUFunc_PyFuncData) % sizeof(void *));
- if (i) offset[0] += (sizeof(void *) - i);
- offset[1] = self->nargs;
- i = (self->nargs % sizeof(void *));
- if (i) offset[1] += (sizeof(void *)-i);
+ To be safest, all of these need their memory aligned on void * pointers
+ Therefore, we may need to allocate extra space.
+ */
+ offset[0] = sizeof(PyUFunc_PyFuncData);
+ i = (sizeof(PyUFunc_PyFuncData) % sizeof(void *));
+ if (i) offset[0] += (sizeof(void *) - i);
+ offset[1] = self->nargs;
+ i = (self->nargs % sizeof(void *));
+ if (i) offset[1] += (sizeof(void *)-i);
- self->ptr = _pya_malloc(offset[0] + offset[1] + sizeof(void *) + \
- (fname_len+14));
+ self->ptr = _pya_malloc(offset[0] + offset[1] + sizeof(void *) + \
+ (fname_len+14));
- if (self->ptr == NULL) return PyErr_NoMemory();
- Py_INCREF(function);
- self->obj = function;
- fdata = (PyUFunc_PyFuncData *)(self->ptr);
- fdata->nin = nin;
- fdata->nout = nout;
- fdata->callable = function;
+ if (self->ptr == NULL) return PyErr_NoMemory();
+ Py_INCREF(function);
+ self->obj = function;
+ fdata = (PyUFunc_PyFuncData *)(self->ptr);
+ fdata->nin = nin;
+ fdata->nout = nout;
+ fdata->callable = function;
- self->data = (void **)(((char *)self->ptr) + offset[0]);
- self->data[0] = (void *)fdata;
+ self->data = (void **)(((char *)self->ptr) + offset[0]);
+ self->data[0] = (void *)fdata;
- self->types = (char *)self->data + sizeof(void *);
- for (i=0; i<self->nargs; i++) self->types[i] = PyArray_OBJECT;
+ self->types = (char *)self->data + sizeof(void *);
+ for (i=0; i<self->nargs; i++) self->types[i] = PyArray_OBJECT;
- str = self->types + offset[1];
- memcpy(str, fname, fname_len);
- memcpy(str+fname_len, " (vectorized)", 14);
+ str = self->types + offset[1];
+ memcpy(str, fname, fname_len);
+ memcpy(str+fname_len, " (vectorized)", 14);
- self->name = str;
+ self->name = str;
- /* Do a better job someday */
- self->doc = "dynamic ufunc based on a python function";
+ /* Do a better job someday */
+ self->doc = "dynamic ufunc based on a python function";
- return (PyObject *)self;
+ return (PyObject *)self;
}
/*UFUNC_API*/
static int
-PyUFunc_ReplaceLoopBySignature(PyUFuncObject *func,
- PyUFuncGenericFunction newfunc,
- int *signature,
- PyUFuncGenericFunction *oldfunc)
-{
- int i,j;
- int res = -1;
- /* Find the location of the matching signature */
- for (i=0; i<func->ntypes; i++) {
- for (j=0; j<func->nargs; j++) {
- if (signature[j] != func->types[i*func->nargs+j])
- break;
- }
- if (j < func->nargs) continue;
-
- if (oldfunc != NULL) {
- *oldfunc = func->functions[i];
- }
- func->functions[i] = newfunc;
- res = 0;
+PyUFunc_ReplaceLoopBySignature(PyUFuncObject *func,
+ PyUFuncGenericFunction newfunc,
+ int *signature,
+ PyUFuncGenericFunction *oldfunc)
+{
+ int i,j;
+ int res = -1;
+ /* Find the location of the matching signature */
+ for (i=0; i<func->ntypes; i++) {
+ for (j=0; j<func->nargs; j++) {
+ if (signature[j] != func->types[i*func->nargs+j])
break;
- }
- return res;
+ }
+ if (j < func->nargs) continue;
+
+ if (oldfunc != NULL) {
+ *oldfunc = func->functions[i];
+ }
+ func->functions[i] = newfunc;
+ res = 0;
+ break;
+ }
+ return res;
}
/*UFUNC_API*/
static PyObject *
PyUFunc_FromFuncAndData(PyUFuncGenericFunction *func, void **data,
- char *types, int ntypes,
- int nin, int nout, int identity,
- char *name, char *doc, int check_return)
+ char *types, int ntypes,
+ int nin, int nout, int identity,
+ char *name, char *doc, int check_return)
{
- PyUFuncObject *self;
+ PyUFuncObject *self;
- self = _pya_malloc(sizeof(PyUFuncObject));
- if (self == NULL) return NULL;
- PyObject_Init((PyObject *)self, &PyUFunc_Type);
+ self = _pya_malloc(sizeof(PyUFuncObject));
+ if (self == NULL) return NULL;
+ PyObject_Init((PyObject *)self, &PyUFunc_Type);
- self->nin = nin;
- self->nout = nout;
- self->nargs = nin+nout;
- self->identity = identity;
+ self->nin = nin;
+ self->nout = nout;
+ self->nargs = nin+nout;
+ self->identity = identity;
- self->functions = func;
- self->data = data;
- self->types = types;
- self->ntypes = ntypes;
- self->check_return = check_return;
- self->ptr = NULL;
- self->obj = NULL;
- self->userloops=NULL;
+ self->functions = func;
+ self->data = data;
+ self->types = types;
+ self->ntypes = ntypes;
+ self->check_return = check_return;
+ self->ptr = NULL;
+ self->obj = NULL;
+ self->userloops=NULL;
- if (name == NULL) self->name = "?";
- else self->name = name;
+ if (name == NULL) self->name = "?";
+ else self->name = name;
- if (doc == NULL) self->doc = "NULL";
- else self->doc = doc;
+ if (doc == NULL) self->doc = "NULL";
+ else self->doc = doc;
- return (PyObject *)self;
+ return (PyObject *)self;
}
/* This is the first-part of the CObject structure.
I don't think this will change, but if it should, then
- this needs to be fixed. The exposed C-API was insufficient
+ this needs to be fixed. The exposed C-API was insufficient
because I needed to replace the pointer and it wouldn't
- let me with a destructor set (even though it works fine
- with the destructor).
- */
+ let me with a destructor set (even though it works fine
+ with the destructor).
+*/
typedef struct {
- PyObject_HEAD
- void *c_obj;
+ PyObject_HEAD
+ void *c_obj;
} _simple_cobj;
#define _SETCPTR(cobj, val) ((_simple_cobj *)(cobj))->c_obj = (val)
/* return 1 if arg1 > arg2, 0 if arg1 == arg2, and -1 if arg1 < arg2
*/
-static int
+static int
cmp_arg_types(int *arg1, int *arg2, int n)
{
- while (n--) {
- if (PyArray_EquivTypenums(*arg1, *arg2)) continue;
- if (PyArray_CanCastSafely(*arg1, *arg2))
- return -1;
- return 1;
- }
- return 0;
+ while (n--) {
+ if (PyArray_EquivTypenums(*arg1, *arg2)) continue;
+ if (PyArray_CanCastSafely(*arg1, *arg2))
+ return -1;
+ return 1;
+ }
+ return 0;
}
-/* This frees the linked-list structure
+/* This frees the linked-list structure
when the CObject is destroyed (removed
from the internal dictionary)
*/
static void
_loop1d_list_free(void *ptr)
{
- PyUFunc_Loop1d *funcdata;
- if (ptr == NULL) return;
- funcdata = (PyUFunc_Loop1d *)ptr;
- if (funcdata == NULL) return;
- _pya_free(funcdata->arg_types);
- _loop1d_list_free(funcdata->next);
- _pya_free(funcdata);
+ PyUFunc_Loop1d *funcdata;
+ if (ptr == NULL) return;
+ funcdata = (PyUFunc_Loop1d *)ptr;
+ if (funcdata == NULL) return;
+ _pya_free(funcdata->arg_types);
+ _loop1d_list_free(funcdata->next);
+ _pya_free(funcdata);
}
/*UFUNC_API*/
static int
PyUFunc_RegisterLoopForType(PyUFuncObject *ufunc,
- int usertype,
- PyUFuncGenericFunction function,
- int *arg_types,
- void *data)
-{
- PyArray_Descr *descr;
- PyUFunc_Loop1d *funcdata;
- PyObject *key, *cobj;
- int i;
- int *newtypes=NULL;
-
- descr=PyArray_DescrFromType(usertype);
- if ((usertype < PyArray_USERDEF) || (descr==NULL)) {
- PyErr_SetString(PyExc_TypeError,
- "unknown user-defined type");
- return -1;
- }
- Py_DECREF(descr);
-
- if (ufunc->userloops == NULL) {
- ufunc->userloops = PyDict_New();
- }
- key = PyInt_FromLong((long) usertype);
- if (key == NULL) return -1;
- funcdata = _pya_malloc(sizeof(PyUFunc_Loop1d));
- if (funcdata == NULL) goto fail;
- newtypes = _pya_malloc(sizeof(int)*ufunc->nargs);
- if (newtypes == NULL) goto fail;
- if (arg_types != NULL) {
- for (i=0; i<ufunc->nargs; i++) {
- newtypes[i] = arg_types[i];
- }
- }
- else {
- for (i=0; i<ufunc->nargs; i++) {
- newtypes[i] = usertype;
- }
- }
-
- funcdata->func = function;
- funcdata->arg_types = newtypes;
- funcdata->data = data;
- funcdata->next = NULL;
-
- /* Get entry for this user-defined type*/
- cobj = PyDict_GetItem(ufunc->userloops, key);
+ int usertype,
+ PyUFuncGenericFunction function,
+ int *arg_types,
+ void *data)
+{
+ PyArray_Descr *descr;
+ PyUFunc_Loop1d *funcdata;
+ PyObject *key, *cobj;
+ int i;
+ int *newtypes=NULL;
+
+ descr=PyArray_DescrFromType(usertype);
+ if ((usertype < PyArray_USERDEF) || (descr==NULL)) {
+ PyErr_SetString(PyExc_TypeError,
+ "unknown user-defined type");
+ return -1;
+ }
+ Py_DECREF(descr);
- /* If it's not there, then make one and return. */
- if (cobj == NULL) {
- cobj = PyCObject_FromVoidPtr((void *)funcdata,
- _loop1d_list_free);
- if (cobj == NULL) goto fail;
- PyDict_SetItem(ufunc->userloops, key, cobj);
- Py_DECREF(cobj);
- Py_DECREF(key);
- return 0;
+ if (ufunc->userloops == NULL) {
+ ufunc->userloops = PyDict_New();
+ }
+ key = PyInt_FromLong((long) usertype);
+ if (key == NULL) return -1;
+ funcdata = _pya_malloc(sizeof(PyUFunc_Loop1d));
+ if (funcdata == NULL) goto fail;
+ newtypes = _pya_malloc(sizeof(int)*ufunc->nargs);
+ if (newtypes == NULL) goto fail;
+ if (arg_types != NULL) {
+ for (i=0; i<ufunc->nargs; i++) {
+ newtypes[i] = arg_types[i];
}
- else {
- PyUFunc_Loop1d *current, *prev=NULL;
- int cmp=1;
- /* There is already at least 1 loop. Place this one in
- lexicographic order. If the next one signature
- is exactly like this one, then just replace.
- Otherwise insert.
- */
- current = (PyUFunc_Loop1d *)PyCObject_AsVoidPtr(cobj);
- while (current != NULL) {
- cmp = cmp_arg_types(current->arg_types, newtypes,
- ufunc->nargs);
- if (cmp >= 0) break;
- prev = current;
- current = current->next;
- }
- if (cmp == 0) { /* just replace it with new function */
- current->func = function;
- current->data = data;
- _pya_free(newtypes);
- _pya_free(funcdata);
- }
- else { /* insert it before the current one
- by hacking the internals of cobject to
- replace the function pointer ---
- can't use CObject API because destructor is set.
- */
- funcdata->next = current;
- if (prev == NULL) { /* place this at front */
- _SETCPTR(cobj, funcdata);
- }
- else {
- prev->next = funcdata;
- }
- }
+ }
+ else {
+ for (i=0; i<ufunc->nargs; i++) {
+ newtypes[i] = usertype;
}
+ }
+
+ funcdata->func = function;
+ funcdata->arg_types = newtypes;
+ funcdata->data = data;
+ funcdata->next = NULL;
+
+ /* Get entry for this user-defined type*/
+ cobj = PyDict_GetItem(ufunc->userloops, key);
+
+ /* If it's not there, then make one and return. */
+ if (cobj == NULL) {
+ cobj = PyCObject_FromVoidPtr((void *)funcdata,
+ _loop1d_list_free);
+ if (cobj == NULL) goto fail;
+ PyDict_SetItem(ufunc->userloops, key, cobj);
+ Py_DECREF(cobj);
Py_DECREF(key);
return 0;
-
+ }
+ else {
+ PyUFunc_Loop1d *current, *prev=NULL;
+ int cmp=1;
+ /* There is already at least 1 loop. Place this one in
+ lexicographic order. If the next one signature
+ is exactly like this one, then just replace.
+ Otherwise insert.
+ */
+ current = (PyUFunc_Loop1d *)PyCObject_AsVoidPtr(cobj);
+ while (current != NULL) {
+ cmp = cmp_arg_types(current->arg_types, newtypes,
+ ufunc->nargs);
+ if (cmp >= 0) break;
+ prev = current;
+ current = current->next;
+ }
+ if (cmp == 0) { /* just replace it with new function */
+ current->func = function;
+ current->data = data;
+ _pya_free(newtypes);
+ _pya_free(funcdata);
+ }
+ else { /* insert it before the current one
+ by hacking the internals of cobject to
+ replace the function pointer ---
+ can't use CObject API because destructor is set.
+ */
+ funcdata->next = current;
+ if (prev == NULL) { /* place this at front */
+ _SETCPTR(cobj, funcdata);
+ }
+ else {
+ prev->next = funcdata;
+ }
+ }
+ }
+ Py_DECREF(key);
+ return 0;
+
fail:
- Py_DECREF(key);
- _pya_free(funcdata);
- _pya_free(newtypes);
- if (!PyErr_Occurred()) PyErr_NoMemory();
- return -1;
+ Py_DECREF(key);
+ _pya_free(funcdata);
+ _pya_free(newtypes);
+ if (!PyErr_Occurred()) PyErr_NoMemory();
+ return -1;
}
#undef _SETCPTR
@@ -3572,20 +3570,20 @@ PyUFunc_RegisterLoopForType(PyUFuncObject *ufunc,
static void
ufunc_dealloc(PyUFuncObject *self)
{
- if (self->ptr) _pya_free(self->ptr);
- Py_XDECREF(self->userloops);
- Py_XDECREF(self->obj);
- _pya_free(self);
+ if (self->ptr) _pya_free(self->ptr);
+ Py_XDECREF(self->userloops);
+ Py_XDECREF(self->obj);
+ _pya_free(self);
}
static PyObject *
ufunc_repr(PyUFuncObject *self)
{
- char buf[100];
+ char buf[100];
- sprintf(buf, "<ufunc '%.50s'>", self->name);
+ sprintf(buf, "<ufunc '%.50s'>", self->name);
- return PyString_FromString(buf);
+ return PyString_FromString(buf);
}
@@ -3595,77 +3593,77 @@ ufunc_repr(PyUFuncObject *self)
where a has b.ndim NewAxis terms appended.
The result has dimensions a.ndim + b.ndim
- */
+*/
static PyObject *
ufunc_outer(PyUFuncObject *self, PyObject *args, PyObject *kwds)
{
- int i;
- PyObject *ret;
- PyArrayObject *ap1=NULL, *ap2=NULL, *ap_new=NULL;
- PyObject *new_args, *tmp;
- PyObject *shape1, *shape2, *newshape;
-
- if(self->nin != 2) {
- PyErr_SetString(PyExc_ValueError,
- "outer product only supported "\
- "for binary functions");
- return NULL;
- }
-
- if (PySequence_Length(args) != 2) {
- PyErr_SetString(PyExc_TypeError,
- "exactly two arguments expected");
- return NULL;
- }
-
- tmp = PySequence_GetItem(args, 0);
- if (tmp == NULL) return NULL;
- ap1 = (PyArrayObject *) \
- PyArray_FromObject(tmp, PyArray_NOTYPE, 0, 0);
- Py_DECREF(tmp);
- if (ap1 == NULL) return NULL;
-
- tmp = PySequence_GetItem(args, 1);
- if (tmp == NULL) return NULL;
- ap2 = (PyArrayObject *)PyArray_FromObject(tmp, PyArray_NOTYPE, 0, 0);
- Py_DECREF(tmp);
- if (ap2 == NULL) {Py_DECREF(ap1); return NULL;}
-
- /* Construct new shape tuple */
- shape1 = PyTuple_New(ap1->nd);
- if (shape1 == NULL) goto fail;
- for (i=0; i<ap1->nd; i++)
- PyTuple_SET_ITEM(shape1, i,
- PyLong_FromLongLong((longlong)ap1-> \
- dimensions[i]));
-
- shape2 = PyTuple_New(ap2->nd);
- for (i=0; i<ap2->nd; i++)
- PyTuple_SET_ITEM(shape2, i, PyInt_FromLong((long) 1));
- if (shape2 == NULL) {Py_DECREF(shape1); goto fail;}
- newshape = PyNumber_Add(shape1, shape2);
- Py_DECREF(shape1);
- Py_DECREF(shape2);
- if (newshape == NULL) goto fail;
-
- ap_new = (PyArrayObject *)PyArray_Reshape(ap1, newshape);
- Py_DECREF(newshape);
- if (ap_new == NULL) goto fail;
-
- new_args = Py_BuildValue("(OO)", ap_new, ap2);
- Py_DECREF(ap1);
- Py_DECREF(ap2);
- Py_DECREF(ap_new);
- ret = ufunc_generic_call(self, new_args, kwds);
- Py_DECREF(new_args);
- return ret;
+ int i;
+ PyObject *ret;
+ PyArrayObject *ap1=NULL, *ap2=NULL, *ap_new=NULL;
+ PyObject *new_args, *tmp;
+ PyObject *shape1, *shape2, *newshape;
+
+ if(self->nin != 2) {
+ PyErr_SetString(PyExc_ValueError,
+ "outer product only supported "\
+ "for binary functions");
+ return NULL;
+ }
+
+ if (PySequence_Length(args) != 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "exactly two arguments expected");
+ return NULL;
+ }
+
+ tmp = PySequence_GetItem(args, 0);
+ if (tmp == NULL) return NULL;
+ ap1 = (PyArrayObject *) \
+ PyArray_FromObject(tmp, PyArray_NOTYPE, 0, 0);
+ Py_DECREF(tmp);
+ if (ap1 == NULL) return NULL;
+
+ tmp = PySequence_GetItem(args, 1);
+ if (tmp == NULL) return NULL;
+ ap2 = (PyArrayObject *)PyArray_FromObject(tmp, PyArray_NOTYPE, 0, 0);
+ Py_DECREF(tmp);
+ if (ap2 == NULL) {Py_DECREF(ap1); return NULL;}
+
+ /* Construct new shape tuple */
+ shape1 = PyTuple_New(ap1->nd);
+ if (shape1 == NULL) goto fail;
+ for (i=0; i<ap1->nd; i++)
+ PyTuple_SET_ITEM(shape1, i,
+ PyLong_FromLongLong((longlong)ap1-> \
+ dimensions[i]));
+
+ shape2 = PyTuple_New(ap2->nd);
+ for (i=0; i<ap2->nd; i++)
+ PyTuple_SET_ITEM(shape2, i, PyInt_FromLong((long) 1));
+ if (shape2 == NULL) {Py_DECREF(shape1); goto fail;}
+ newshape = PyNumber_Add(shape1, shape2);
+ Py_DECREF(shape1);
+ Py_DECREF(shape2);
+ if (newshape == NULL) goto fail;
+
+ ap_new = (PyArrayObject *)PyArray_Reshape(ap1, newshape);
+ Py_DECREF(newshape);
+ if (ap_new == NULL) goto fail;
+
+ new_args = Py_BuildValue("(OO)", ap_new, ap2);
+ Py_DECREF(ap1);
+ Py_DECREF(ap2);
+ Py_DECREF(ap_new);
+ ret = ufunc_generic_call(self, new_args, kwds);
+ Py_DECREF(new_args);
+ return ret;
fail:
- Py_XDECREF(ap1);
- Py_XDECREF(ap2);
- Py_XDECREF(ap_new);
- return NULL;
+ Py_XDECREF(ap1);
+ Py_XDECREF(ap2);
+ Py_XDECREF(ap_new);
+ return NULL;
}
@@ -3673,219 +3671,218 @@ static PyObject *
ufunc_reduce(PyUFuncObject *self, PyObject *args, PyObject *kwds)
{
- return PyUFunc_GenericReduction(self, args, kwds, UFUNC_REDUCE);
+ return PyUFunc_GenericReduction(self, args, kwds, UFUNC_REDUCE);
}
static PyObject *
ufunc_accumulate(PyUFuncObject *self, PyObject *args, PyObject *kwds)
{
- return PyUFunc_GenericReduction(self, args, kwds, UFUNC_ACCUMULATE);
+ return PyUFunc_GenericReduction(self, args, kwds, UFUNC_ACCUMULATE);
}
static PyObject *
ufunc_reduceat(PyUFuncObject *self, PyObject *args, PyObject *kwds)
{
- return PyUFunc_GenericReduction(self, args, kwds, UFUNC_REDUCEAT);
+ return PyUFunc_GenericReduction(self, args, kwds, UFUNC_REDUCEAT);
}
static struct PyMethodDef ufunc_methods[] = {
- {"reduce", (PyCFunction)ufunc_reduce, METH_VARARGS | METH_KEYWORDS},
- {"accumulate", (PyCFunction)ufunc_accumulate,
- METH_VARARGS | METH_KEYWORDS},
- {"reduceat", (PyCFunction)ufunc_reduceat,
- METH_VARARGS | METH_KEYWORDS},
- {"outer", (PyCFunction)ufunc_outer, METH_VARARGS | METH_KEYWORDS},
- {NULL, NULL} /* sentinel */
+ {"reduce", (PyCFunction)ufunc_reduce, METH_VARARGS | METH_KEYWORDS},
+ {"accumulate", (PyCFunction)ufunc_accumulate,
+ METH_VARARGS | METH_KEYWORDS},
+ {"reduceat", (PyCFunction)ufunc_reduceat,
+ METH_VARARGS | METH_KEYWORDS},
+ {"outer", (PyCFunction)ufunc_outer, METH_VARARGS | METH_KEYWORDS},
+ {NULL, NULL} /* sentinel */
};
/* construct the string
- y1,y2,...,yn
+ y1,y2,...,yn
*/
static PyObject *
_makeargs(int num, char *ltr)
{
- PyObject *str;
- int i;
- switch (num) {
- case 0:
- return PyString_FromString("");
- case 1:
- return PyString_FromString(ltr);
- }
- str = PyString_FromFormat("%s1,%s2", ltr, ltr);
- for(i = 3; i <= num; ++i) {
- PyString_ConcatAndDel(&str, PyString_FromFormat(",%s%d", ltr, i));
- }
- return str;
+ PyObject *str;
+ int i;
+ switch (num) {
+ case 0:
+ return PyString_FromString("");
+ case 1:
+ return PyString_FromString(ltr);
+ }
+ str = PyString_FromFormat("%s1,%s2", ltr, ltr);
+ for(i = 3; i <= num; ++i) {
+ PyString_ConcatAndDel(&str, PyString_FromFormat(",%s%d", ltr, i));
+ }
+ return str;
}
static char
_typecharfromnum(int num) {
- PyArray_Descr *descr;
- char ret;
+ PyArray_Descr *descr;
+ char ret;
- descr = PyArray_DescrFromType(num);
- ret = descr->type;
- Py_DECREF(descr);
- return ret;
+ descr = PyArray_DescrFromType(num);
+ ret = descr->type;
+ Py_DECREF(descr);
+ return ret;
}
static PyObject *
ufunc_get_doc(PyUFuncObject *self)
{
- /* Put docstring first or FindMethod finds it...*/
- /* could so some introspection on name and nin + nout */
- /* to automate the first part of it */
- /* the doc string shouldn't need the calling convention */
- /* construct
- y1,y2,,... = name(x1,x2,...) __doc__
- */
- PyObject *outargs, *inargs, *doc;
- outargs = _makeargs(self->nout, "y");
- inargs = _makeargs(self->nin, "x");
- doc = PyString_FromFormat("%s = %s(%s) %s",
- PyString_AS_STRING(outargs),
- self->name,
- PyString_AS_STRING(inargs),
- self->doc);
- Py_DECREF(outargs);
- Py_DECREF(inargs);
- return doc;
+ /* Put docstring first or FindMethod finds it...*/
+ /* could so some introspection on name and nin + nout */
+ /* to automate the first part of it */
+ /* the doc string shouldn't need the calling convention */
+ /* construct
+ y1,y2,,... = name(x1,x2,...) __doc__
+ */
+ PyObject *outargs, *inargs, *doc;
+ outargs = _makeargs(self->nout, "y");
+ inargs = _makeargs(self->nin, "x");
+ doc = PyString_FromFormat("%s = %s(%s) %s",
+ PyString_AS_STRING(outargs),
+ self->name,
+ PyString_AS_STRING(inargs),
+ self->doc);
+ Py_DECREF(outargs);
+ Py_DECREF(inargs);
+ return doc;
}
static PyObject *
ufunc_get_nin(PyUFuncObject *self)
{
- return PyInt_FromLong(self->nin);
+ return PyInt_FromLong(self->nin);
}
static PyObject *
ufunc_get_nout(PyUFuncObject *self)
{
- return PyInt_FromLong(self->nout);
+ return PyInt_FromLong(self->nout);
}
static PyObject *
ufunc_get_nargs(PyUFuncObject *self)
{
- return PyInt_FromLong(self->nargs);
+ return PyInt_FromLong(self->nargs);
}
static PyObject *
ufunc_get_ntypes(PyUFuncObject *self)
{
- return PyInt_FromLong(self->ntypes);
+ return PyInt_FromLong(self->ntypes);
}
static PyObject *
ufunc_get_types(PyUFuncObject *self)
{
- /* return a list with types grouped
- input->output */
- PyObject *list;
- PyObject *str;
- int k, j, n, nt=self->ntypes;
- int ni = self->nin;
- int no = self->nout;
- char *t;
- list = PyList_New(nt);
- if (list == NULL) return NULL;
- t = _pya_malloc(no+ni+2);
- n = 0;
- for (k=0; k<nt; k++) {
- for (j=0; j<ni; j++) {
- t[j] = _typecharfromnum(self->types[n]);
- n++;
- }
- t[ni] = '-';
- t[ni+1] = '>';
- for (j=0; j<no; j++) {
- t[ni+2+j] = \
- _typecharfromnum(self->types[n]);
- n++;
- }
- str = PyString_FromStringAndSize(t, no+ni+2);
- PyList_SET_ITEM(list, k, str);
- }
- _pya_free(t);
- return list;
-
+ /* return a list with types grouped
+ input->output */
+ PyObject *list;
+ PyObject *str;
+ int k, j, n, nt=self->ntypes;
+ int ni = self->nin;
+ int no = self->nout;
+ char *t;
+ list = PyList_New(nt);
+ if (list == NULL) return NULL;
+ t = _pya_malloc(no+ni+2);
+ n = 0;
+ for (k=0; k<nt; k++) {
+ for (j=0; j<ni; j++) {
+ t[j] = _typecharfromnum(self->types[n]);
+ n++;
+ }
+ t[ni] = '-';
+ t[ni+1] = '>';
+ for (j=0; j<no; j++) {
+ t[ni+2+j] = \
+ _typecharfromnum(self->types[n]);
+ n++;
+ }
+ str = PyString_FromStringAndSize(t, no+ni+2);
+ PyList_SET_ITEM(list, k, str);
+ }
+ _pya_free(t);
+ return list;
}
static PyObject *
ufunc_get_name(PyUFuncObject *self)
{
- return PyString_FromString(self->name);
+ return PyString_FromString(self->name);
}
static PyObject *
ufunc_get_identity(PyUFuncObject *self)
{
- switch(self->identity) {
- case PyUFunc_One:
- return PyInt_FromLong(1);
- case PyUFunc_Zero:
- return PyInt_FromLong(0);
- }
- return Py_None;
+ switch(self->identity) {
+ case PyUFunc_One:
+ return PyInt_FromLong(1);
+ case PyUFunc_Zero:
+ return PyInt_FromLong(0);
+ }
+ return Py_None;
}
#undef _typecharfromnum
static char Ufunctype__doc__[] =
- "Optimized functions make it possible to implement arithmetic "\
- "with arrays efficiently";
+ "Optimized functions make it possible to implement arithmetic "\
+ "with arrays efficiently";
static PyGetSetDef ufunc_getset[] = {
- {"__doc__", (getter)ufunc_get_doc, NULL, "documentation string"},
- {"nin", (getter)ufunc_get_nin, NULL, "number of inputs"},
- {"nout", (getter)ufunc_get_nout, NULL, "number of outputs"},
- {"nargs", (getter)ufunc_get_nargs, NULL, "number of arguments"},
- {"ntypes", (getter)ufunc_get_ntypes, NULL, "number of types"},
- {"types", (getter)ufunc_get_types, NULL, "return a list with types grouped input->output"},
- {"__name__", (getter)ufunc_get_name, NULL, "function name"},
- {"identity", (getter)ufunc_get_identity, NULL, "identity value"},
- {NULL, NULL, NULL, NULL}, /* Sentinel */
+ {"__doc__", (getter)ufunc_get_doc, NULL, "documentation string"},
+ {"nin", (getter)ufunc_get_nin, NULL, "number of inputs"},
+ {"nout", (getter)ufunc_get_nout, NULL, "number of outputs"},
+ {"nargs", (getter)ufunc_get_nargs, NULL, "number of arguments"},
+ {"ntypes", (getter)ufunc_get_ntypes, NULL, "number of types"},
+ {"types", (getter)ufunc_get_types, NULL, "return a list with types grouped input->output"},
+ {"__name__", (getter)ufunc_get_name, NULL, "function name"},
+ {"identity", (getter)ufunc_get_identity, NULL, "identity value"},
+ {NULL, NULL, NULL, NULL}, /* Sentinel */
};
static PyTypeObject PyUFunc_Type = {
- PyObject_HEAD_INIT(0)
- 0, /*ob_size*/
- "numpy.ufunc", /*tp_name*/
- sizeof(PyUFuncObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)ufunc_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc)0, /*tp_compare*/
- (reprfunc)ufunc_repr, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- (hashfunc)0, /*tp_hash*/
- (ternaryfunc)ufunc_generic_call, /*tp_call*/
- (reprfunc)ufunc_repr, /*tp_str*/
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- Ufunctype__doc__, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- ufunc_methods, /* tp_methods */
- 0, /* tp_members */
- ufunc_getset, /* tp_getset */
+ PyObject_HEAD_INIT(0)
+ 0, /*ob_size*/
+ "numpy.ufunc", /*tp_name*/
+ sizeof(PyUFuncObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)ufunc_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc)0, /*tp_compare*/
+ (reprfunc)ufunc_repr, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ (hashfunc)0, /*tp_hash*/
+ (ternaryfunc)ufunc_generic_call, /*tp_call*/
+ (reprfunc)ufunc_repr, /*tp_str*/
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ Ufunctype__doc__, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ ufunc_methods, /* tp_methods */
+ 0, /* tp_members */
+ ufunc_getset, /* tp_getset */
};
/* End of code for ufunc objects */
diff --git a/numpy/core/src/umathmodule.c.src b/numpy/core/src/umathmodule.c.src
index 5611a6937..5e24d89a8 100644
--- a/numpy/core/src/umathmodule.c.src
+++ b/numpy/core/src/umathmodule.c.src
@@ -30,13 +30,13 @@ extern double modf (double, double *);
#endif
static float fabsf(float x)
{
- return (float)fabs((double)(x));
+ return (float)fabs((double)(x));
}
#endif
#ifndef HAVE_HYPOTF
static float hypotf(float x, float y)
{
- return (float)hypot((double)(x), (double)(y));
+ return (float)hypot((double)(x), (double)(y));
}
#endif
#ifndef HAVE_RINTF
@@ -45,19 +45,19 @@ static double rint (double x);
#endif
static float rintf(float x)
{
- return (float)rint((double)(x));
+ return (float)rint((double)(x));
}
#endif
#ifndef HAVE_FREXPF
static float frexpf(float x, int * i)
{
- return (float)frexp((double)(x), i);
+ return (float)frexp((double)(x), i);
}
#endif
#ifndef HAVE_LDEXPF
static float ldexpf(float x, int i)
{
- return (float)ldexp((double)(x), i);
+ return (float)ldexp((double)(x), i);
}
#endif
#define tanhf nc_tanhf
@@ -66,33 +66,33 @@ static float ldexpf(float x, int i)
#ifndef HAVE_INVERSE_HYPERBOLIC
static double acosh(double x)
{
- return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2));
+ return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2));
}
double log1p(double);
static double asinh(double xx)
{
- double x, d;
- int sign;
- if (xx < 0.0) {
- sign = -1;
- x = -xx;
- }
- else {
- sign = 1;
- x = xx;
- }
- if (x > 1e8) {
- d = x;
- } else {
- d = sqrt(x*x + 1);
- }
- return sign*log1p(x*(1.0 + x/(d+1)));
+ double x, d;
+ int sign;
+ if (xx < 0.0) {
+ sign = -1;
+ x = -xx;
+ }
+ else {
+ sign = 1;
+ x = xx;
+ }
+ if (x > 1e8) {
+ d = x;
+ } else {
+ d = sqrt(x*x + 1);
+ }
+ return sign*log1p(x*(1.0 + x/(d+1)));
}
static double atanh(double x)
{
- return 0.5*log1p(2.0*x/(1.0-x));
+ return 0.5*log1p(2.0*x/(1.0-x));
}
#endif
@@ -121,7 +121,7 @@ float sqrtf(float);
#endif
static float acoshf(float x)
{
- return 2*logf(sqrtf((x+1)/2)+sqrtf((x-1)/2));
+ return 2*logf(sqrtf((x+1)/2)+sqrtf((x-1)/2));
}
#ifdef asinhf
@@ -129,22 +129,22 @@ static float acoshf(float x)
#endif
static float asinhf(float xx)
{
- float x, d;
- int sign;
- if (xx < 0) {
- sign = -1;
- x = -xx;
- }
- else {
- sign = 1;
- x = xx;
- }
- if (x > 1e5) {
- d = x;
- } else {
- d = sqrtf(x*x + 1);
- }
- return sign*log1pf(x*(1 + x/(d+1)));
+ float x, d;
+ int sign;
+ if (xx < 0) {
+ sign = -1;
+ x = -xx;
+ }
+ else {
+ sign = 1;
+ x = xx;
+ }
+ if (x > 1e5) {
+ d = x;
+ } else {
+ d = sqrtf(x*x + 1);
+ }
+ return sign*log1pf(x*(1 + x/(d+1)));
}
#ifdef atanhf
@@ -152,7 +152,7 @@ static float asinhf(float xx)
#endif
static float atanhf(float x)
{
- return log1pf(2*x/(1-x))/2;
+ return log1pf(2*x/(1-x))/2;
}
#else
#ifdef acoshf
@@ -160,7 +160,7 @@ static float atanhf(float x)
#endif
static float acoshf(float x)
{
- return (float)acosh((double)(x));
+ return (float)acosh((double)(x));
}
#ifdef asinhf
@@ -168,7 +168,7 @@ static float acoshf(float x)
#endif
static float asinhf(float x)
{
- return (float)asinh((double)(x));
+ return (float)asinh((double)(x));
}
#ifdef atanhf
@@ -176,7 +176,7 @@ static float asinhf(float x)
#endif
static float atanhf(float x)
{
- return (float)atanh((double)(x));
+ return (float)atanh((double)(x));
}
#endif
#endif
@@ -201,7 +201,7 @@ longdouble log1pl(longdouble);
#endif
static longdouble acoshl(longdouble x)
{
- return 2*logl(sqrtl((x+1.0)/2)+sqrtl((x-1.0)/2));
+ return 2*logl(sqrtl((x+1.0)/2)+sqrtl((x-1.0)/2));
}
#ifdef asinhl
@@ -209,22 +209,22 @@ static longdouble acoshl(longdouble x)
#endif
static longdouble asinhl(longdouble xx)
{
- longdouble x, d;
- int sign;
- if (xx < 0.0) {
- sign = -1;
- x = -xx;
- }
- else {
- sign = 1;
- x = xx;
- }
- if (x > 1e17) {
- d = x;
- } else {
- d = sqrtl(x*x + 1);
- }
- return sign*log1pl(x*(1.0 + x/(d+1)));
+ longdouble x, d;
+ int sign;
+ if (xx < 0.0) {
+ sign = -1;
+ x = -xx;
+ }
+ else {
+ sign = 1;
+ x = xx;
+ }
+ if (x > 1e17) {
+ d = x;
+ } else {
+ d = sqrtl(x*x + 1);
+ }
+ return sign*log1pl(x*(1.0 + x/(d+1)));
}
#ifdef atanhl
@@ -232,7 +232,7 @@ static longdouble asinhl(longdouble xx)
#endif
static longdouble atanhl(longdouble x)
{
- return 0.5*log1pl(2.0*x/(1.0-x));
+ return 0.5*log1pl(2.0*x/(1.0-x));
}
#else
@@ -242,7 +242,7 @@ static longdouble atanhl(longdouble x)
#endif
static longdouble acoshl(longdouble x)
{
- return (longdouble)acosh((double)(x));
+ return (longdouble)acosh((double)(x));
}
#ifdef asinhl
@@ -250,7 +250,7 @@ static longdouble acoshl(longdouble x)
#endif
static longdouble asinhl(longdouble x)
{
- return (longdouble)asinh((double)(x));
+ return (longdouble)asinh((double)(x));
}
#ifdef atanhl
@@ -258,7 +258,7 @@ static longdouble asinhl(longdouble x)
#endif
static longdouble atanhl(longdouble x)
{
- return (longdouble)atanh((double)(x));
+ return (longdouble)atanh((double)(x));
}
#endif
@@ -272,21 +272,21 @@ extern double hypot(double, double);
#else
static double hypot(double x, double y)
{
- double yx;
+ double yx;
- x = fabs(x);
- y = fabs(y);
- if (x < y) {
- double temp = x;
- x = y;
- y = temp;
- }
- if (x == 0.)
- return 0.;
- else {
- yx = y/x;
- return x*sqrt(1.+yx*yx);
- }
+ x = fabs(x);
+ y = fabs(y);
+ if (x < y) {
+ double temp = x;
+ x = y;
+ y = temp;
+ }
+ if (x == 0.)
+ return 0.;
+ else {
+ yx = y/x;
+ return x*sqrt(1.+yx*yx);
+ }
}
#endif
@@ -295,22 +295,22 @@ static double hypot(double x, double y)
static double
rint (double x)
{
- double y, r;
+ double y, r;
- y = floor(x);
- r = x - y;
+ y = floor(x);
+ r = x - y;
- if (r > 0.5) goto rndup;
+ if (r > 0.5) goto rndup;
- /* Round to nearest even */
- if (r==0.5) {
- r = y - 2.0*floor(0.5*y);
- if (r==1.0) {
- rndup:
- y+=1.0;
- }
- }
- return y;
+ /* Round to nearest even */
+ if (r==0.5) {
+ r = y - 2.0*floor(0.5*y);
+ if (r==1.0) {
+ rndup:
+ y+=1.0;
+ }
+ }
+ return y;
}
#endif
@@ -321,12 +321,12 @@ rint (double x)
/* Define isnan, isinf, isfinite, signbit if needed */
/* Use fpclassify if possible */
/* isnan, isinf --
- these will use macros and then fpclassify if available before
- defaulting to a dumb convert-to-double version...
+ these will use macros and then fpclassify if available before
+ defaulting to a dumb convert-to-double version...
isfinite -- define a macro if not already available
signbit -- if macro available use it, otherwise define a function
- and a dumb convert-to-double version for other types.
+ and a dumb convert-to-double version for other types.
*/
#if defined(fpclassify)
@@ -417,67 +417,67 @@ rint (double x)
/* First, the C functions that do the real work */
/* if C99 extensions not available then define dummy functions that use the
- double versions for
+ double versions for
- sin, cos, tan
- sinh, cosh, tanh,
- fabs, floor, ceil, fmod, sqrt, log10, log, exp, fabs
- asin, acos, atan,
- asinh, acosh, atanh
+ sin, cos, tan
+ sinh, cosh, tanh,
+ fabs, floor, ceil, fmod, sqrt, log10, log, exp, fabs
+ asin, acos, atan,
+ asinh, acosh, atanh
- hypot, atan2, pow
+ hypot, atan2, pow
*/
/**begin repeat
-#kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,sqrt,log10,log,exp,asin,acos,atan,rint)*2#
-#typ=longdouble*17, float*17#
-#c=l*17,f*17#
-#TYPE=LONGDOUBLE*17, FLOAT*17#
+ #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,sqrt,log10,log,exp,asin,acos,atan,rint)*2#
+ #typ=longdouble*17, float*17#
+ #c=l*17,f*17#
+ #TYPE=LONGDOUBLE*17, FLOAT*17#
*/
#ifndef HAVE_@TYPE@_FUNCS
#ifdef @kind@@c@
#undef @kind@@c@
#endif
@typ@ @kind@@c@(@typ@ x) {
- return (@typ@) @kind@((double)x);
+ return (@typ@) @kind@((double)x);
}
#endif
/**end repeat**/
/**begin repeat
-#kind=(atan2,hypot,pow,fmod)*2#
-#typ=longdouble*4, float*4#
-#c=l*4,f*4#
-#TYPE=LONGDOUBLE*4,FLOAT*4#
+ #kind=(atan2,hypot,pow,fmod)*2#
+ #typ=longdouble*4, float*4#
+ #c=l*4,f*4#
+ #TYPE=LONGDOUBLE*4,FLOAT*4#
*/
#ifndef HAVE_@TYPE@_FUNCS
#ifdef @kind@@c@
#undef @kind@@c@
#endif
@typ@ @kind@@c@(@typ@ x, @typ@ y) {
- return (@typ@) @kind@((double)x, (double) y);
+ return (@typ@) @kind@((double)x, (double) y);
}
#endif
/**end repeat**/
/**begin repeat
-#kind=modf*2#
-#typ=longdouble, float#
-#c=l,f#
-#TYPE=LONGDOUBLE, FLOAT#
+ #kind=modf*2#
+ #typ=longdouble, float#
+ #c=l,f#
+ #TYPE=LONGDOUBLE, FLOAT#
*/
#ifndef HAVE_@TYPE@_FUNCS
#ifdef modf@c@
#undef modf@c@
#endif
@typ@ modf@c@(@typ@ x, @typ@ *iptr) {
- double nx, niptr, y;
- nx = (double) x;
- y = modf(nx, &niptr);
- *iptr = (@typ@) niptr;
- return (@typ@) y;
+ double nx, niptr, y;
+ nx = (double) x;
+ y = modf(nx, &niptr);
+ *iptr = (@typ@) niptr;
+ return (@typ@) y;
}
#endif
/**end repeat**/
@@ -487,12 +487,12 @@ rint (double x)
#ifndef HAVE_LOG1P
double log1p(double x)
{
- double u = 1. + x;
- if (u == 1.0) {
- return x;
- } else {
- return log(u) * x / (u-1.);
- }
+ double u = 1. + x;
+ if (u == 1.0) {
+ return x;
+ } else {
+ return log(u) * x / (u-1.);
+ }
}
#endif
@@ -502,12 +502,12 @@ double log1p(double x)
#endif
longdouble log1pl(longdouble x)
{
- longdouble u = 1. + x;
- if (u == 1.0) {
- return x;
- } else {
- return logl(u) * x / (u-1.);
- }
+ longdouble u = 1. + x;
+ if (u == 1.0) {
+ return x;
+ } else {
+ return logl(u) * x / (u-1.);
+ }
}
#endif
@@ -517,26 +517,26 @@ longdouble log1pl(longdouble x)
#endif
float log1pf(float x)
{
- float u = 1 + x;
- if (u == 1) {
- return x;
- } else {
- return logf(u) * x / (u-1);
- }
+ float u = 1 + x;
+ if (u == 1) {
+ return x;
+ } else {
+ return logf(u) * x / (u-1);
+ }
}
#endif
#ifndef HAVE_EXPM1
static double expm1(double x)
{
- double u = exp(x);
- if (u == 1.0) {
- return x;
- } else if (u-1.0 == -1.0) {
- return -1;
- } else {
- return (u-1.0) * x/log(u);
- }
+ double u = exp(x);
+ if (u == 1.0) {
+ return x;
+ } else if (u-1.0 == -1.0) {
+ return -1;
+ } else {
+ return (u-1.0) * x/log(u);
+ }
}
#endif
@@ -546,14 +546,14 @@ static double expm1(double x)
#endif
static longdouble expm1l(longdouble x)
{
- longdouble u = expl(x);
- if (u == 1.0) {
- return x;
- } else if (u-1.0 == -1.0) {
- return -1;
- } else {
- return (u-1.0) * x/logl(u);
- }
+ longdouble u = expl(x);
+ if (u == 1.0) {
+ return x;
+ } else if (u-1.0 == -1.0) {
+ return -1;
+ } else {
+ return (u-1.0) * x/logl(u);
+ }
}
#endif
@@ -563,14 +563,14 @@ static longdouble expm1l(longdouble x)
#endif
static float expm1f(float x)
{
- float u = expf(x);
- if (u == 1) {
- return x;
- } else if (u-1 == -1) {
- return -1;
- } else {
- return (u-1) * x/logf(u);
- }
+ float u = expf(x);
+ if (u == 1) {
+ return x;
+ } else if (u-1 == -1) {
+ return -1;
+ } else {
+ return (u-1) * x/logf(u);
+ }
}
#endif
@@ -584,8 +584,8 @@ static float expm1f(float x)
/**begin repeat
-#typ=float, double, longdouble#
-#c=f,,l#
+ #typ=float, double, longdouble#
+ #c=f,,l#
*/
/* constants */
@@ -594,290 +594,290 @@ static c@typ@ nc_half@c@ = {0.5, 0.};
static c@typ@ nc_i@c@ = {0., 1.};
static c@typ@ nc_i2@c@ = {0., 0.5};
/*
-static c@typ@ nc_mi@c@ = {0., -1.};
-static c@typ@ nc_pi2@c@ = {M_PI/2., 0.};
+ static c@typ@ nc_mi@c@ = {0., -1.};
+ static c@typ@ nc_pi2@c@ = {M_PI/2., 0.};
*/
static void
nc_sum@c@(c@typ@ *a, c@typ@ *b, c@typ@ *r)
{
- r->real = a->real + b->real;
- r->imag = a->imag + b->imag;
- return;
+ r->real = a->real + b->real;
+ r->imag = a->imag + b->imag;
+ return;
}
static void
nc_diff@c@(c@typ@ *a, c@typ@ *b, c@typ@ *r)
{
- r->real = a->real - b->real;
- r->imag = a->imag - b->imag;
- return;
+ r->real = a->real - b->real;
+ r->imag = a->imag - b->imag;
+ return;
}
static void
nc_neg@c@(c@typ@ *a, c@typ@ *r)
{
- r->real = -a->real;
- r->imag = -a->imag;
- return;
+ r->real = -a->real;
+ r->imag = -a->imag;
+ return;
}
static void
nc_prod@c@(c@typ@ *a, c@typ@ *b, c@typ@ *r)
{
- register @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag;
- r->real = ar*br - ai*bi;
- r->imag = ar*bi + ai*br;
- return;
+ register @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag;
+ r->real = ar*br - ai*bi;
+ r->imag = ar*bi + ai*br;
+ return;
}
static void
nc_quot@c@(c@typ@ *a, c@typ@ *b, c@typ@ *r)
{
- register @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag;
- register @typ@ d = br*br + bi*bi;
- r->real = (ar*br + ai*bi)/d;
- r->imag = (ai*br - ar*bi)/d;
- return;
+ register @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag;
+ register @typ@ d = br*br + bi*bi;
+ r->real = (ar*br + ai*bi)/d;
+ r->imag = (ai*br - ar*bi)/d;
+ return;
}
static void
nc_sqrt@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ s,d;
- if (x->real == 0. && x->imag == 0.)
- *r = *x;
- else {
- s = sqrt@c@((fabs@c@(x->real) + hypot@c@(x->real,x->imag))/2);
- d = x->imag/(2*s);
- if (x->real > 0) {
- r->real = s;
- r->imag = d;
- }
- else if (x->imag >= 0) {
- r->real = d;
- r->imag = s;
- }
- else {
- r->real = -d;
- r->imag = -s;
- }
- }
- return;
+ @typ@ s,d;
+ if (x->real == 0. && x->imag == 0.)
+ *r = *x;
+ else {
+ s = sqrt@c@((fabs@c@(x->real) + hypot@c@(x->real,x->imag))/2);
+ d = x->imag/(2*s);
+ if (x->real > 0) {
+ r->real = s;
+ r->imag = d;
+ }
+ else if (x->imag >= 0) {
+ r->real = d;
+ r->imag = s;
+ }
+ else {
+ r->real = -d;
+ r->imag = -s;
+ }
+ }
+ return;
}
static void
nc_rint@c@(c@typ@ *x, c@typ@ *r)
{
- r->real = rint@c@(x->real);
- r->imag = rint@c@(x->imag);
+ r->real = rint@c@(x->real);
+ r->imag = rint@c@(x->imag);
}
static void
nc_log@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ l = hypot@c@(x->real,x->imag);
- r->imag = atan2@c@(x->imag, x->real);
- r->real = log@c@(l);
- return;
+ @typ@ l = hypot@c@(x->real,x->imag);
+ r->imag = atan2@c@(x->imag, x->real);
+ r->real = log@c@(l);
+ return;
}
static void
nc_log1p@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ l = hypot@c@(x->real + 1,x->imag);
- r->imag = atan2@c@(x->imag, x->real + 1);
- r->real = log@c@(l);
- return;
+ @typ@ l = hypot@c@(x->real + 1,x->imag);
+ r->imag = atan2@c@(x->imag, x->real + 1);
+ r->real = log@c@(l);
+ return;
}
static void
nc_exp@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ a = exp@c@(x->real);
- r->real = a*cos@c@(x->imag);
- r->imag = a*sin@c@(x->imag);
- return;
+ @typ@ a = exp@c@(x->real);
+ r->real = a*cos@c@(x->imag);
+ r->imag = a*sin@c@(x->imag);
+ return;
}
static void
nc_expm1@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ a = exp@c@(x->real);
- r->real = a*cos@c@(x->imag) - 1;
- r->imag = a*sin@c@(x->imag);
- return;
+ @typ@ a = exp@c@(x->real);
+ r->real = a*cos@c@(x->imag) - 1;
+ r->imag = a*sin@c@(x->imag);
+ return;
}
static void
nc_pow@c@(c@typ@ *a, c@typ@ *b, c@typ@ *r)
{
- intp n;
- @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag;
-
- if (br == 0. && bi == 0.) {
- r->real = 1.;
- r->imag = 0.;
- return;
- }
- if (ar == 0. && ai == 0.) {
- r->real = 0.;
- r->imag = 0.;
- return;
- }
- if (bi == 0 && (n=(intp)br) == br) {
- if (n > -100 && n < 100) {
- c@typ@ p, aa;
- intp mask = 1;
- if (n < 0) n = -n;
- aa = nc_1@c@;
- p.real = ar; p.imag = ai;
- while (1) {
- if (n & mask)
- nc_prod@c@(&aa,&p,&aa);
- mask <<= 1;
- if (n < mask || mask <= 0) break;
- nc_prod@c@(&p,&p,&p);
- }
- r->real = aa.real; r->imag = aa.imag;
- if (br < 0) nc_quot@c@(&nc_1@c@, r, r);
- return;
+ intp n;
+ @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag;
+
+ if (br == 0. && bi == 0.) {
+ r->real = 1.;
+ r->imag = 0.;
+ return;
+ }
+ if (ar == 0. && ai == 0.) {
+ r->real = 0.;
+ r->imag = 0.;
+ return;
+ }
+ if (bi == 0 && (n=(intp)br) == br) {
+ if (n > -100 && n < 100) {
+ c@typ@ p, aa;
+ intp mask = 1;
+ if (n < 0) n = -n;
+ aa = nc_1@c@;
+ p.real = ar; p.imag = ai;
+ while (1) {
+ if (n & mask)
+ nc_prod@c@(&aa,&p,&aa);
+ mask <<= 1;
+ if (n < mask || mask <= 0) break;
+ nc_prod@c@(&p,&p,&p);
}
+ r->real = aa.real; r->imag = aa.imag;
+ if (br < 0) nc_quot@c@(&nc_1@c@, r, r);
+ return;
}
- /* complexobect.c uses an inline version of this formula
- investigate whether this had better performance or accuracy */
- nc_log@c@(a, r);
- nc_prod@c@(r, b, r);
- nc_exp@c@(r, r);
- return;
+ }
+ /* complexobect.c uses an inline version of this formula
+ investigate whether this had better performance or accuracy */
+ nc_log@c@(a, r);
+ nc_prod@c@(r, b, r);
+ nc_exp@c@(r, r);
+ return;
}
static void
nc_prodi@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ xr = x->real;
- r->real = -x->imag;
- r->imag = xr;
- return;
+ @typ@ xr = x->real;
+ r->real = -x->imag;
+ r->imag = xr;
+ return;
}
static void
nc_acos@c@(c@typ@ *x, c@typ@ *r)
{
- nc_prod@c@(x,x,r);
- nc_diff@c@(&nc_1@c@, r, r);
- nc_sqrt@c@(r, r);
- nc_prodi@c@(r, r);
- nc_sum@c@(x, r, r);
- nc_log@c@(r, r);
- nc_prodi@c@(r, r);
- nc_neg@c@(r, r);
- return;
- /* return nc_neg(nc_prodi(nc_log(nc_sum(x,nc_prod(nc_i,
- nc_sqrt(nc_diff(nc_1,nc_prod(x,x))))))));
- */
+ nc_prod@c@(x,x,r);
+ nc_diff@c@(&nc_1@c@, r, r);
+ nc_sqrt@c@(r, r);
+ nc_prodi@c@(r, r);
+ nc_sum@c@(x, r, r);
+ nc_log@c@(r, r);
+ nc_prodi@c@(r, r);
+ nc_neg@c@(r, r);
+ return;
+ /* return nc_neg(nc_prodi(nc_log(nc_sum(x,nc_prod(nc_i,
+ nc_sqrt(nc_diff(nc_1,nc_prod(x,x))))))));
+ */
}
static void
nc_acosh@c@(c@typ@ *x, c@typ@ *r)
{
- nc_prod@c@(x, x, r);
- nc_diff@c@(&nc_1@c@, r, r);
- nc_sqrt@c@(r, r);
- nc_prodi@c@(r, r);
- nc_sum@c@(x, r, r);
- nc_log@c@(r, r);
- return;
- /*
- return nc_log(nc_sum(x,nc_prod(nc_i,
- nc_sqrt(nc_diff(nc_1,nc_prod(x,x))))));
- */
+ nc_prod@c@(x, x, r);
+ nc_diff@c@(&nc_1@c@, r, r);
+ nc_sqrt@c@(r, r);
+ nc_prodi@c@(r, r);
+ nc_sum@c@(x, r, r);
+ nc_log@c@(r, r);
+ return;
+ /*
+ return nc_log(nc_sum(x,nc_prod(nc_i,
+ nc_sqrt(nc_diff(nc_1,nc_prod(x,x))))));
+ */
}
static void
nc_asin@c@(c@typ@ *x, c@typ@ *r)
{
- c@typ@ a, *pa=&a;
- nc_prod@c@(x, x, r);
- nc_diff@c@(&nc_1@c@, r, r);
- nc_sqrt@c@(r, r);
- nc_prodi@c@(x, pa);
- nc_sum@c@(pa, r, r);
- nc_log@c@(r, r);
- nc_prodi@c@(r, r);
- nc_neg@c@(r, r);
- return;
- /*
- return nc_neg(nc_prodi(nc_log(nc_sum(nc_prod(nc_i,x),
- nc_sqrt(nc_diff(nc_1,nc_prod(x,x)))))));
- */
+ c@typ@ a, *pa=&a;
+ nc_prod@c@(x, x, r);
+ nc_diff@c@(&nc_1@c@, r, r);
+ nc_sqrt@c@(r, r);
+ nc_prodi@c@(x, pa);
+ nc_sum@c@(pa, r, r);
+ nc_log@c@(r, r);
+ nc_prodi@c@(r, r);
+ nc_neg@c@(r, r);
+ return;
+ /*
+ return nc_neg(nc_prodi(nc_log(nc_sum(nc_prod(nc_i,x),
+ nc_sqrt(nc_diff(nc_1,nc_prod(x,x)))))));
+ */
}
static void
nc_asinh@c@(c@typ@ *x, c@typ@ *r)
{
- nc_prod@c@(x, x, r);
- nc_sum@c@(&nc_1@c@, r, r);
- nc_sqrt@c@(r, r);
- nc_diff@c@(r, x, r);
- nc_log@c@(r, r);
- nc_neg@c@(r, r);
- return;
- /*
- return nc_neg(nc_log(nc_diff(nc_sqrt(nc_sum(nc_1,nc_prod(x,x))),x)));
- */
+ nc_prod@c@(x, x, r);
+ nc_sum@c@(&nc_1@c@, r, r);
+ nc_sqrt@c@(r, r);
+ nc_diff@c@(r, x, r);
+ nc_log@c@(r, r);
+ nc_neg@c@(r, r);
+ return;
+ /*
+ return nc_neg(nc_log(nc_diff(nc_sqrt(nc_sum(nc_1,nc_prod(x,x))),x)));
+ */
}
static void
nc_atan@c@(c@typ@ *x, c@typ@ *r)
{
- c@typ@ a, *pa=&a;
- nc_diff@c@(&nc_i@c@, x, pa);
- nc_sum@c@(&nc_i@c@, x, r);
- nc_quot@c@(r, pa, r);
- nc_log@c@(r,r);
- nc_prod@c@(&nc_i2@c@, r, r);
- return;
- /*
- return nc_prod(nc_i2,nc_log(nc_quot(nc_sum(nc_i,x),nc_diff(nc_i,x))));
- */
+ c@typ@ a, *pa=&a;
+ nc_diff@c@(&nc_i@c@, x, pa);
+ nc_sum@c@(&nc_i@c@, x, r);
+ nc_quot@c@(r, pa, r);
+ nc_log@c@(r,r);
+ nc_prod@c@(&nc_i2@c@, r, r);
+ return;
+ /*
+ return nc_prod(nc_i2,nc_log(nc_quot(nc_sum(nc_i,x),nc_diff(nc_i,x))));
+ */
}
static void
nc_atanh@c@(c@typ@ *x, c@typ@ *r)
{
- c@typ@ a, *pa=&a;
- nc_diff@c@(&nc_1@c@, x, r);
- nc_sum@c@(&nc_1@c@, x, pa);
- nc_quot@c@(pa, r, r);
- nc_log@c@(r, r);
- nc_prod@c@(&nc_half@c@, r, r);
- return;
- /*
- return nc_prod(nc_half,nc_log(nc_quot(nc_sum(nc_1,x),nc_diff(nc_1,x))));
- */
+ c@typ@ a, *pa=&a;
+ nc_diff@c@(&nc_1@c@, x, r);
+ nc_sum@c@(&nc_1@c@, x, pa);
+ nc_quot@c@(pa, r, r);
+ nc_log@c@(r, r);
+ nc_prod@c@(&nc_half@c@, r, r);
+ return;
+ /*
+ return nc_prod(nc_half,nc_log(nc_quot(nc_sum(nc_1,x),nc_diff(nc_1,x))));
+ */
}
static void
nc_cos@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ xr=x->real, xi=x->imag;
- r->real = cos@c@(xr)*cosh@c@(xi);
- r->imag = -sin@c@(xr)*sinh@c@(xi);
- return;
+ @typ@ xr=x->real, xi=x->imag;
+ r->real = cos@c@(xr)*cosh@c@(xi);
+ r->imag = -sin@c@(xr)*sinh@c@(xi);
+ return;
}
static void
nc_cosh@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ xr=x->real, xi=x->imag;
- r->real = cos@c@(xi)*cosh@c@(xr);
- r->imag = sin@c@(xi)*sinh@c@(xr);
- return;
+ @typ@ xr=x->real, xi=x->imag;
+ r->real = cos@c@(xi)*cosh@c@(xr);
+ r->imag = sin@c@(xi)*sinh@c@(xr);
+ return;
}
@@ -886,70 +886,70 @@ nc_cosh@c@(c@typ@ *x, c@typ@ *r)
static void
nc_log10@c@(c@typ@ *x, c@typ@ *r)
{
- nc_log@c@(x, r);
- r->real *= (@typ@) M_LOG10_E;
- r->imag *= (@typ@) M_LOG10_E;
- return;
+ nc_log@c@(x, r);
+ r->real *= (@typ@) M_LOG10_E;
+ r->imag *= (@typ@) M_LOG10_E;
+ return;
}
static void
nc_sin@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ xr=x->real, xi=x->imag;
- r->real = sin@c@(xr)*cosh@c@(xi);
- r->imag = cos@c@(xr)*sinh@c@(xi);
- return;
+ @typ@ xr=x->real, xi=x->imag;
+ r->real = sin@c@(xr)*cosh@c@(xi);
+ r->imag = cos@c@(xr)*sinh@c@(xi);
+ return;
}
static void
nc_sinh@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ xr=x->real, xi=x->imag;
- r->real = cos@c@(xi)*sinh@c@(xr);
- r->imag = sin@c@(xi)*cosh@c@(xr);
- return;
+ @typ@ xr=x->real, xi=x->imag;
+ r->real = cos@c@(xi)*sinh@c@(xr);
+ r->imag = sin@c@(xi)*cosh@c@(xr);
+ return;
}
static void
nc_tan@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ sr,cr,shi,chi;
- @typ@ rs,is,rc,ic;
- @typ@ d;
- @typ@ xr=x->real, xi=x->imag;
- sr = sin@c@(xr);
- cr = cos@c@(xr);
- shi = sinh@c@(xi);
- chi = cosh@c@(xi);
- rs = sr*chi;
- is = cr*shi;
- rc = cr*chi;
- ic = -sr*shi;
- d = rc*rc + ic*ic;
- r->real = (rs*rc+is*ic)/d;
- r->imag = (is*rc-rs*ic)/d;
- return;
+ @typ@ sr,cr,shi,chi;
+ @typ@ rs,is,rc,ic;
+ @typ@ d;
+ @typ@ xr=x->real, xi=x->imag;
+ sr = sin@c@(xr);
+ cr = cos@c@(xr);
+ shi = sinh@c@(xi);
+ chi = cosh@c@(xi);
+ rs = sr*chi;
+ is = cr*shi;
+ rc = cr*chi;
+ ic = -sr*shi;
+ d = rc*rc + ic*ic;
+ r->real = (rs*rc+is*ic)/d;
+ r->imag = (is*rc-rs*ic)/d;
+ return;
}
static void
nc_tanh@c@(c@typ@ *x, c@typ@ *r)
{
- @typ@ si,ci,shr,chr;
- @typ@ rs,is,rc,ic;
- @typ@ d;
- @typ@ xr=x->real, xi=x->imag;
- si = sin@c@(xi);
- ci = cos@c@(xi);
- shr = sinh@c@(xr);
- chr = cosh@c@(xr);
- rs = ci*shr;
- is = si*chr;
- rc = ci*chr;
- ic = si*shr;
- d = rc*rc + ic*ic;
- r->real = (rs*rc+is*ic)/d;
- r->imag = (is*rc-rs*ic)/d;
- return;
+ @typ@ si,ci,shr,chr;
+ @typ@ rs,is,rc,ic;
+ @typ@ d;
+ @typ@ xr=x->real, xi=x->imag;
+ si = sin@c@(xi);
+ ci = cos@c@(xi);
+ shr = sinh@c@(xr);
+ chr = cosh@c@(xr);
+ rs = ci*shr;
+ is = si*chr;
+ rc = ci*chr;
+ ic = si*shr;
+ d = rc*rc + ic*ic;
+ r->real = (rs*rc+is*ic)/d;
+ r->imag = (is*rc-rs*ic)/d;
+ return;
}
/**end repeat**/
@@ -957,43 +957,43 @@ nc_tanh@c@(c@typ@ *x, c@typ@ *r)
/**begin repeat
-#TYPE=(BOOL, BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*2#
-#OP=||, +*13, ^, -*13#
-#kind=add*14, subtract*14#
-#typ=(Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2#
+ #TYPE=(BOOL, BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*2#
+ #OP=||, +*13, ^, -*13#
+ #kind=add*14, subtract*14#
+ #typ=(Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((@typ@ *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2);
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((@typ@ *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=(CFLOAT, CDOUBLE, CLONGDOUBLE)*2#
-#OP=+*3,-*3#
-#kind=add*3,subtract*3#
-#typ=(float, double, longdouble)*2#
+ #TYPE=(CFLOAT, CDOUBLE, CLONGDOUBLE)*2#
+ #OP=+*3,-*3#
+ #kind=add*3,subtract*3#
+ #typ=(float, double, longdouble)*2#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- ((@typ@ *)op)[0]=((@typ@ *)i1)[0] @OP@ ((@typ@ *)i2)[0];
- ((@typ@ *)op)[1]=((@typ@ *)i1)[1] @OP@ ((@typ@ *)i2)[1];
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ ((@typ@ *)op)[0]=((@typ@ *)i1)[0] @OP@ ((@typ@ *)i2)[0];
+ ((@typ@ *)op)[1]=((@typ@ *)i1)[1] @OP@ ((@typ@ *)i2)[1];
+ }
}
/**end repeat**/
@@ -1001,85 +1001,85 @@ static void
static void
BOOL_multiply(char **args, intp *dimensions, intp *steps, void *func) {
- register intp i;
- intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((Bool *)op) = *((Bool *)i1) && *((Bool *)i2);
- }
+ register intp i;
+ intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((Bool *)op) = *((Bool *)i1) && *((Bool *)i2);
+ }
}
/**begin repeat
-#TYP= BYTE, SHORT, INT, LONG, LONGLONG, UBYTE, USHORT, UINT, ULONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE#
-#typ= byte, short, int, long, longlong, ubyte, ushort, uint, ulong, ulonglong, float, double, longdouble#
+ #TYP= BYTE, SHORT, INT, LONG, LONGLONG, UBYTE, USHORT, UINT, ULONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE#
+ #typ= byte, short, int, long, longlong, ubyte, ushort, uint, ulong, ulonglong, float, double, longdouble#
*/
static void
@TYP@_multiply(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((@typ@ *)op) = (*((@typ@ *)i1)) * (*((@typ@ *)i2));
- }
+ register intp i;
+ intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((@typ@ *)op) = (*((@typ@ *)i1)) * (*((@typ@ *)i2));
+ }
}
/**end repeat**/
/**begin repeat
-#TYP= CFLOAT, CDOUBLE, CLONGDOUBLE#
-#typ= float, double, longdouble#
-#c=f,,l#
+ #TYP= CFLOAT, CDOUBLE, CLONGDOUBLE#
+ #typ= float, double, longdouble#
+ #c=f,,l#
*/
static void
@TYP@_multiply(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- register @typ@ ar=((c@typ@ *)i1)->real, \
- ai=((c@typ@ *)i1)->imag, \
- br=((c@typ@ *)i2)->real, \
- bi=((c@typ@ *)i2)->imag;
- ((c@typ@ *)op)->real = ar*br - ai*bi;
- ((c@typ@ *)op)->imag = ar*bi + ai*br;
- }
+ register intp i;
+ intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ register @typ@ ar=((c@typ@ *)i1)->real, \
+ ai=((c@typ@ *)i1)->imag, \
+ br=((c@typ@ *)i2)->real, \
+ bi=((c@typ@ *)i2)->imag;
+ ((c@typ@ *)op)->real = ar*br - ai*bi;
+ ((c@typ@ *)op)->imag = ar*bi + ai*br;
+ }
}
static void
@TYP@_divide(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- register @typ@ ar=((c@typ@ *)i1)->real, \
- ai=((c@typ@ *)i1)->imag, \
- br=((c@typ@ *)i2)->real, \
- bi=((c@typ@ *)i2)->imag;
- register @typ@ d = br*br + bi*bi;
- ((c@typ@ *)op)->real = (ar*br + ai*bi)/d;
- ((c@typ@ *)op)->imag = (ai*br - ar*bi)/d;
- }
+ register intp i;
+ intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ register @typ@ ar=((c@typ@ *)i1)->real, \
+ ai=((c@typ@ *)i1)->imag, \
+ br=((c@typ@ *)i2)->real, \
+ bi=((c@typ@ *)i2)->imag;
+ register @typ@ d = br*br + bi*bi;
+ ((c@typ@ *)op)->real = (ar*br + ai*bi)/d;
+ ((c@typ@ *)op)->imag = (ai*br - ar*bi)/d;
+ }
}
static void
@TYP@_floor_divide(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- register @typ@ ar=((c@typ@ *)i1)->real, \
- ai=((c@typ@ *)i1)->imag, \
- br=((c@typ@ *)i2)->real, \
- bi=((c@typ@ *)i2)->imag;
- register @typ@ d = br*br + bi*bi;
- ((c@typ@ *)op)->real = floor@c@((ar*br + ai*bi)/d);
- ((c@typ@ *)op)->imag = 0;
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ register @typ@ ar=((c@typ@ *)i1)->real, \
+ ai=((c@typ@ *)i1)->imag, \
+ br=((c@typ@ *)i2)->real, \
+ bi=((c@typ@ *)i2)->imag;
+ register @typ@ d = br*br + bi*bi;
+ ((c@typ@ *)op)->real = floor@c@((ar*br + ai*bi)/d);
+ ((c@typ@ *)op)->imag = 0;
+ }
}
#define @TYP@_true_divide @TYP@_divide
@@ -1087,74 +1087,74 @@ static void
/**begin repeat
-#TYP=UBYTE,USHORT,UINT,ULONG,ULONGLONG#
-#typ=ubyte, ushort, uint, ulong, ulonglong#
+ #TYP=UBYTE,USHORT,UINT,ULONG,ULONGLONG#
+ #typ=ubyte, ushort, uint, ulong, ulonglong#
*/
static void
@TYP@_divide(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- if (*((@typ@ *)i2)==0) {
- generate_divbyzero_error();
- *((@typ@ *)op)=0;
- }
- else {
- *((@typ@ *)op)= *((@typ@ *)i1) / *((@typ@ *)i2);
- }
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ if (*((@typ@ *)i2)==0) {
+ generate_divbyzero_error();
+ *((@typ@ *)op)=0;
+ }
+ else {
+ *((@typ@ *)op)= *((@typ@ *)i1) / *((@typ@ *)i2);
+ }
+ }
}
/**end repeat**/
/**begin repeat
-#TYP=BYTE,SHORT,INT,LONG,LONGLONG#
-#typ=char, short, int, long, longlong#
+ #TYP=BYTE,SHORT,INT,LONG,LONGLONG#
+ #typ=char, short, int, long, longlong#
*/
static void
@TYP@_divide(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- @typ@ x, y, tmp;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- y = *((@typ@ *)i2);
- if (y == 0) {
- generate_divbyzero_error();
- *((@typ@ *)op)=0;
- }
- else {
- x = *((@typ@ *)i1);
- tmp = x / y;
- if (((x > 0) != (y > 0)) && (x % y != 0)) tmp--;
- *((@typ@ *)op)= tmp;
- }
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ @typ@ x, y, tmp;
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ y = *((@typ@ *)i2);
+ if (y == 0) {
+ generate_divbyzero_error();
+ *((@typ@ *)op)=0;
+ }
+ else {
+ x = *((@typ@ *)i1);
+ tmp = x / y;
+ if (((x > 0) != (y > 0)) && (x % y != 0)) tmp--;
+ *((@typ@ *)op)= tmp;
+ }
+ }
}
/**end repeat**/
/**begin repeat
-#TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG#
-#typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong#
-#otyp=float*4, double*6#
+ #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG#
+ #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong#
+ #otyp=float*4, double*6#
*/
static void
@TYP@_true_divide(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- if (*((@typ@ *)i2)==0) {
- generate_divbyzero_error();
- *((@otyp@ *)op)=0;
- }
- else {
- *((@otyp@ *)op)= \
- (@otyp@)((double)*((@typ@ *)i1) / (double)*((@typ@ *)i2));
- }
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ if (*((@typ@ *)i2)==0) {
+ generate_divbyzero_error();
+ *((@otyp@ *)op)=0;
+ }
+ else {
+ *((@otyp@ *)op)= \
+ (@otyp@)((double)*((@typ@ *)i1) / (double)*((@typ@ *)i2));
+ }
+ }
}
#define @TYP@_floor_divide @TYP@_divide
/**end repeat**/
@@ -1162,41 +1162,41 @@ static void
/**begin repeat
-#TYP=FLOAT,DOUBLE,LONGDOUBLE#
-#typ=float,double,longdouble#
+ #TYP=FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=float,double,longdouble#
*/
static void
@TYP@_divide(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((@typ@ *)op)=*((@typ@ *)i1) / *((@typ@ *)i2);
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((@typ@ *)op)=*((@typ@ *)i1) / *((@typ@ *)i2);
+ }
}
#define @TYP@_true_divide @TYP@_divide
/**end repeat**/
/**begin repeat
-#TYP=FLOAT,DOUBLE,LONGDOUBLE#
-#typ=float,double,longdouble#
-#c=f,,l#
+ #TYP=FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=float,double,longdouble#
+ #c=f,,l#
*/
static void
@TYP@_floor_divide(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((@typ@ *)op)=floor@c@(*((@typ@ *)i1) / *((@typ@ *)i2));
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((@typ@ *)op)=floor@c@(*((@typ@ *)i1) / *((@typ@ *)i2));
+ }
}
/**end repeat**/
/**begin repeat
-#TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
-#typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
+ #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
*/
static void
@TYP@_square(char **args, intp *dimensions, intp *steps, void *data)
@@ -1212,8 +1212,8 @@ static void
/**end repeat**/
/**begin repeat
-#TYP=CFLOAT,CDOUBLE,CLONGDOUBLE#
-#typ=float, double, longdouble#
+ #TYP=CFLOAT,CDOUBLE,CLONGDOUBLE#
+ #typ=float, double, longdouble#
*/
static void
@TYP@_square(char **args, intp *dimensions, intp *steps, void *data)
@@ -1242,8 +1242,8 @@ Py_square(PyObject *o)
/**begin repeat
-#TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
-#typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
+ #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
*/
static void
@TYP@_reciprocal(char **args, intp *dimensions, intp *steps, void *data)
@@ -1259,8 +1259,8 @@ static void
/**end repeat**/
/**begin repeat
-#TYP=CFLOAT,CDOUBLE,CLONGDOUBLE#
-#typ=float, double, longdouble#
+ #TYP=CFLOAT,CDOUBLE,CLONGDOUBLE#
+ #typ=float, double, longdouble#
*/
static void
@TYP@_reciprocal(char **args, intp *dimensions, intp *steps, void *data)
@@ -1305,42 +1305,42 @@ Py_reciprocal(PyObject *o)
static PyObject *
_npy_ObjectMax(PyObject *i1, PyObject *i2)
{
- int cmp;
- PyObject *res;
- if (PyObject_Cmp(i1, i2, &cmp) < 0) return NULL;
-
- if (cmp >= 0) {
- res = i1;
- }
- else {
- res = i2;
- }
- Py_INCREF(res);
- return res;
+ int cmp;
+ PyObject *res;
+ if (PyObject_Cmp(i1, i2, &cmp) < 0) return NULL;
+
+ if (cmp >= 0) {
+ res = i1;
+ }
+ else {
+ res = i2;
+ }
+ Py_INCREF(res);
+ return res;
}
static PyObject *
_npy_ObjectMin(PyObject *i1, PyObject *i2)
{
- int cmp;
- PyObject *res;
- if (PyObject_Cmp(i1, i2, &cmp) < 0) return NULL;
-
- if (cmp <= 0) {
- res = i1;
- }
- else {
- res = i2;
- }
- Py_INCREF(res);
- return res;
+ int cmp;
+ PyObject *res;
+ if (PyObject_Cmp(i1, i2, &cmp) < 0) return NULL;
+
+ if (cmp <= 0) {
+ res = i1;
+ }
+ else {
+ res = i2;
+ }
+ Py_INCREF(res);
+ return res;
}
/* ones_like is defined here because it's used for x**0 */
/**begin repeat
-#TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
-#typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
+ #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
*/
static void
@TYP@_ones_like(char **args, intp *dimensions, intp *steps, void *data)
@@ -1355,121 +1355,121 @@ static void
/**end repeat**/
/**begin repeat
-#TYP=CFLOAT,CDOUBLE,CLONGDOUBLE#
-#typ=float, double, longdouble#
+ #TYP=CFLOAT,CDOUBLE,CLONGDOUBLE#
+ #typ=float, double, longdouble#
*/
static void
@TYP@_ones_like(char **args, intp *dimensions, intp *steps, void *data)
{
- intp i, is1 = steps[0], os = steps[1], n = dimensions[0];
- char *i1 = args[0], *op = args[1];
- c@typ@ *y;
+ intp i, is1 = steps[0], os = steps[1], n = dimensions[0];
+ char *i1 = args[0], *op = args[1];
+ c@typ@ *y;
- for (i = 0; i < n; i++, i1 += is1, op += os) {
- y = (c@typ@ *)op;
- y->real = 1.0;
- y->imag = 0.0;
- }
+ for (i = 0; i < n; i++, i1 += is1, op += os) {
+ y = (c@typ@ *)op;
+ y->real = 1.0;
+ y->imag = 0.0;
+ }
}
/**end repeat**/
static PyObject *
Py_get_one(PyObject *o)
{
- return PyInt_FromLong(1);
+ return PyInt_FromLong(1);
}
/**begin repeat
-#TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG#
-#typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong#
-#btyp=float*4, double*6#
+ #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG#
+ #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong#
+ #btyp=float*4, double*6#
*/
static void
@TYP@_power(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0],is2=steps[1];
- register intp os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- @btyp@ x, y;
+ register intp i, is1=steps[0],is2=steps[1];
+ register intp os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ @btyp@ x, y;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- x = (@btyp@)*((@typ@ *)i1);
- y = (@btyp@)*((@typ@ *)i2);
- *((@typ@ *)op) = (@typ@) pow(x,y);
- }
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ x = (@btyp@)*((@typ@ *)i1);
+ y = (@btyp@)*((@typ@ *)i2);
+ *((@typ@ *)op) = (@typ@) pow(x,y);
+ }
}
/**end repeat**/
/**begin repeat
-#TYP=UBYTE, BYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE#
-#typ=ubyte, char, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
+ #TYP=UBYTE, BYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE#
+ #typ=ubyte, char, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
*/
static void
@TYP@_conjugate(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, is1=steps[0], os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((@typ@ *)op)=*((@typ@ *)i1);
- }
+ register intp i, is1=steps[0], os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((@typ@ *)op)=*((@typ@ *)i1);
+ }
}
/**end repeat**/
/**begin repeat
-#TYP=CFLOAT, CDOUBLE, CLONGDOUBLE#
-#typ=float, double, longdouble#
+ #TYP=CFLOAT, CDOUBLE, CLONGDOUBLE#
+ #typ=float, double, longdouble#
*/
static void
@TYP@_conjugate(char **args, intp *dimensions, intp *steps, void *func) {
- register intp i, is1=steps[0], os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
+ register intp i, is1=steps[0], os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- ((@typ@ *)op)[0]=((@typ@ *)i1)[0];
- ((@typ@ *)op)[1]=-(((@typ@ *)i1)[1]);
- }
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ ((@typ@ *)op)[0]=((@typ@ *)i1)[0];
+ ((@typ@ *)op)[1]=-(((@typ@ *)i1)[1]);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=BOOL,UBYTE,USHORT,UINT,ULONG,ULONGLONG#
-#typ=Bool, ubyte, ushort, uint, ulong, ulonglong#
+ #TYPE=BOOL,UBYTE,USHORT,UINT,ULONG,ULONGLONG#
+ #typ=Bool, ubyte, ushort, uint, ulong, ulonglong#
*/
static void
@TYPE@_absolute(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n;
- intp is1=steps[0], os=steps[1];
- char *i1=args[0], *op=args[1];
+ register intp i, n;
+ intp is1=steps[0], os=steps[1];
+ char *i1=args[0], *op=args[1];
n=dimensions[0];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((@typ@ *)op) = *((@typ@*)i1);
- }
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((@typ@ *)op) = *((@typ@*)i1);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=BYTE,SHORT,INT,LONG,LONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
-#typ=byte, short, int, long, longlong, float, double, longdouble#
+ #TYPE=BYTE,SHORT,INT,LONG,LONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=byte, short, int, long, longlong, float, double, longdouble#
*/
static void
@TYPE@_absolute(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n;
- intp is1=steps[0], os=steps[1];
- char *i1=args[0], *op=args[1];
+ register intp i, n;
+ intp is1=steps[0], os=steps[1];
+ char *i1=args[0], *op=args[1];
- n=dimensions[0];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((@typ@ *)op) = *((@typ@ *)i1) < 0 ? -*((@typ@ *)i1) : *((@typ@ *)i1);
- }
+ n=dimensions[0];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((@typ@ *)op) = *((@typ@ *)i1) < 0 ? -*((@typ@ *)i1) : *((@typ@ *)i1);
+ }
}
/**end repeat**/
@@ -1481,118 +1481,118 @@ static void
static void
@TYPE@_absolute(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i, n;
- register intp is1=steps[0], os=steps[1];
- char *i1=args[0], *op=args[1];
- n=dimensions[0];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((@typ@ *)op) = (@typ@)sqrt@c@(((@typ@ *)i1)[0]*((@typ@ *)i1)[0] + ((@typ@ *)i1)[1]*((@typ@ *)i1)[1]);
- }
+ register intp i, n;
+ register intp is1=steps[0], os=steps[1];
+ char *i1=args[0], *op=args[1];
+ n=dimensions[0];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((@typ@ *)op) = (@typ@)sqrt@c@(((@typ@ *)i1)[0]*((@typ@ *)i1)[0] + ((@typ@ *)i1)[1]*((@typ@ *)i1)[1]);
+ }
}
/**end repeat**/
/**begin repeat
-#kind=greater, greater_equal, less, less_equal, equal, not_equal, logical_and, logical_or, bitwise_and, bitwise_or, bitwise_xor#
-#OP=>, >=, <, <=, ==, !=, &&, ||, &, |, ^#
+ #kind=greater, greater_equal, less, less_equal, equal, not_equal, logical_and, logical_or, bitwise_and, bitwise_or, bitwise_xor#
+ #OP=>, >=, <, <=, ==, !=, &&, ||, &, |, ^#
**/
static void
BOOL_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- Bool in1, in2;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- in1 = (*((Bool *)i1) != 0);
- in2 = (*((Bool *)i2) != 0);
- *((Bool *)op)= in1 @OP@ in2;
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ Bool in1, in2;
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ in1 = (*((Bool *)i1) != 0);
+ in2 = (*((Bool *)i2) != 0);
+ *((Bool *)op)= in1 @OP@ in2;
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*4#
-#OP= >*13, >=*13, <*13, <=*13#
-#typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*4#
-#kind= greater*13, greater_equal*13, less*13, less_equal*13#
+ #TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*4#
+ #OP= >*13, >=*13, <*13, <=*13#
+ #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*4#
+ #kind= greater*13, greater_equal*13, less*13, less_equal*13#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((Bool *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2);
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((Bool *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=(CFLOAT,CDOUBLE,CLONGDOUBLE)*4#
-#OP= >*3, >=*3, <*3, <=*3#
-#typ=(cfloat, cdouble, clongdouble)*4#
-#kind= greater*3, greater_equal*3, less*3, less_equal*3#
+ #TYPE=(CFLOAT,CDOUBLE,CLONGDOUBLE)*4#
+ #OP= >*3, >=*3, <*3, <=*3#
+ #typ=(cfloat, cdouble, clongdouble)*4#
+ #kind= greater*3, greater_equal*3, less*3, less_equal*3#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- if (((@typ@ *)i1)->real == ((@typ@ *)i2)->real)
- *((Bool *)op)=((@typ@ *)i1)->imag @OP@ \
- ((@typ@ *)i2)->imag;
- else
- *((Bool *)op)=((@typ@ *)i1)->real @OP@ \
- ((@typ@ *)i2)->real;
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ if (((@typ@ *)i1)->real == ((@typ@ *)i2)->real)
+ *((Bool *)op)=((@typ@ *)i1)->imag @OP@ \
+ ((@typ@ *)i2)->imag;
+ else
+ *((Bool *)op)=((@typ@ *)i1)->real @OP@ \
+ ((@typ@ *)i2)->real;
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*4#
-#typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*4#
-#OP= ==*13, !=*13, &&*13, ||*13#
-#kind=equal*13, not_equal*13, logical_and*13, logical_or*13#
+ #TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*4#
+ #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*4#
+ #OP= ==*13, !=*13, &&*13, ||*13#
+ #kind=equal*13, not_equal*13, logical_and*13, logical_or*13#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((Bool *)op) = *((@typ@ *)i1) @OP@ *((@typ@ *)i2);
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((Bool *)op) = *((@typ@ *)i1) @OP@ *((@typ@ *)i2);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=(CFLOAT, CDOUBLE, CLONGDOUBLE)*4#
-#typ=(float, double, longdouble)*4#
-#OP= ==*3, !=*3, &&*3, ||*3#
-#OP2= &&*3, ||*3, &&*3, ||*3#
-#kind=equal*3, not_equal*3, logical_and*3, logical_or*3#
+ #TYPE=(CFLOAT, CDOUBLE, CLONGDOUBLE)*4#
+ #typ=(float, double, longdouble)*4#
+ #OP= ==*3, !=*3, &&*3, ||*3#
+ #OP2= &&*3, ||*3, &&*3, ||*3#
+ #kind=equal*3, not_equal*3, logical_and*3, logical_or*3#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((Bool *)op) = (*((@typ@ *)i1) @OP@ *((@typ@ *)i2)) @OP2@ (*((@typ@ *)i1+1) @OP@ *((@typ@ *)i2+1));
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((Bool *)op) = (*((@typ@ *)i1) @OP@ *((@typ@ *)i2)) @OP2@ (*((@typ@ *)i1+1) @OP@ *((@typ@ *)i2+1));
+ }
}
/**end repeat**/
@@ -1601,36 +1601,36 @@ static void
/**begin repeat
-#kind=greater, greater_equal, less, less_equal, equal, not_equal#
-#op=GT, GE, LT, LE, EQ, NE#
+ #kind=greater, greater_equal, less, less_equal, equal, not_equal#
+ #op=GT, GE, LT, LE, EQ, NE#
*/
static void
OBJECT_@kind@(char **args, intp *dimensions, intp *steps, void *func) {
- register intp i, is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((Bool *)op)=PyObject_RichCompareBool(*((PyObject **)i1),
- *((PyObject **)i2),
- Py_@op@);
- }
+ register intp i, is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((Bool *)op)=PyObject_RichCompareBool(*((PyObject **)i1),
+ *((PyObject **)i2),
+ Py_@op@);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
-#typ=byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
-#styp=byte, byte, short, short, int, int, long, long, longlong, longlong, float, double, longdouble#
+ #TYPE=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
+ #styp=byte, byte, short, short, int, int, long, long, longlong, longlong, float, double, longdouble#
*/
- static void
+static void
@TYPE@_negative(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((@typ@ *)op) = (@typ@) (- (@styp@)*((@typ@ *)i1));
- }
+ register intp i;
+ intp is1=steps[0],os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((@typ@ *)op) = (@typ@) (- (@styp@)*((@typ@ *)i1));
+ }
}
/**end repeat**/
@@ -1640,41 +1640,41 @@ OBJECT_@kind@(char **args, intp *dimensions, intp *steps, void *func) {
#define _SIGN2(x) ((x) == 0 ? 0 : 1)
#define _SIGNC(x) (((x).real > 0) ? 1 : ((x).real < 0 ? -1 : ((x).imag > 0 ? 1 : ((x).imag < 0) ? -1 : 0)))
/**begin repeat
-#TYPE=BYTE,SHORT,INT,LONG,LONGLONG,FLOAT,DOUBLE,LONGDOUBLE,UBYTE,USHORT,UINT,ULONG,ULONGLONG#
-#typ=byte,short,int,long,longlong,float,double,longdouble,ubyte,ushort,uint,ulong,ulonglong#
-#func=_SIGN1*8,_SIGN2*5#
- */
+ #TYPE=BYTE,SHORT,INT,LONG,LONGLONG,FLOAT,DOUBLE,LONGDOUBLE,UBYTE,USHORT,UINT,ULONG,ULONGLONG#
+ #typ=byte,short,int,long,longlong,float,double,longdouble,ubyte,ushort,uint,ulong,ulonglong#
+ #func=_SIGN1*8,_SIGN2*5#
+*/
static void
@TYPE@_sign(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- @typ@ t1;
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- t1 = *((@typ@ *)i1);
- *((@typ@ *)op) = (@typ@) @func@(t1);
- }
+ register intp i;
+ intp is1=steps[0],os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ @typ@ t1;
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ t1 = *((@typ@ *)i1);
+ *((@typ@ *)op) = (@typ@) @func@(t1);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=CFLOAT,CDOUBLE,CLONGDOUBLE#
-#typ=cfloat,cdouble,clongdouble#
-#rtyp=float,double,longdouble#
- */
+ #TYPE=CFLOAT,CDOUBLE,CLONGDOUBLE#
+ #typ=cfloat,cdouble,clongdouble#
+ #rtyp=float,double,longdouble#
+*/
static void
@TYPE@_sign(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- @typ@ t1;
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- t1 = *((@typ@ *)i1);
- (*((@typ@ *)op)).real = (@rtyp@)_SIGNC(t1);
- (*((@typ@ *)op)).imag = (@rtyp@)0;
- }
+ register intp i;
+ intp is1=steps[0],os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ @typ@ t1;
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ t1 = *((@typ@ *)i1);
+ (*((@typ@ *)op)).real = (@rtyp@)_SIGNC(t1);
+ (*((@typ@ *)op)).imag = (@rtyp@)0;
+ }
}
/**end repeat**/
@@ -1686,50 +1686,50 @@ static void
static void
OBJECT_sign(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- PyObject *t1, *zero, *res;
- zero = PyInt_FromLong(0);
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- t1 = *((PyObject **)i1);
- res = PyInt_FromLong((long) PyObject_Compare(t1, zero));
- *((PyObject **)op) = res;
- }
- Py_DECREF(zero);
+ register intp i;
+ intp is1=steps[0],os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ PyObject *t1, *zero, *res;
+ zero = PyInt_FromLong(0);
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ t1 = *((PyObject **)i1);
+ res = PyInt_FromLong((long) PyObject_Compare(t1, zero));
+ *((PyObject **)op) = res;
+ }
+ Py_DECREF(zero);
}
/**begin repeat
-#TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
-#typ=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
+ #TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
*/
static void
@TYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((Bool *)op) = ! *((@typ@ *)i1);
- }
+ register intp i;
+ intp is1=steps[0],os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((Bool *)op) = ! *((@typ@ *)i1);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=CFLOAT,CDOUBLE,CLONGDOUBLE#
-#typ=cfloat, cdouble, clongdouble#
+ #TYPE=CFLOAT,CDOUBLE,CLONGDOUBLE#
+ #typ=cfloat, cdouble, clongdouble#
*/
static void
@TYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((Bool *)op) = ! (((@typ@ *)i1)->real || \
- ((@typ@ *)i1)->imag);
- }
+ register intp i;
+ intp is1=steps[0],os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((Bool *)op) = ! (((@typ@ *)i1)->real || \
+ ((@typ@ *)i1)->imag);
+ }
}
/**end repeat**/
@@ -1737,128 +1737,128 @@ static void
/**begin repeat
-#TYPE=BYTE,SHORT,INT,LONG,LONGLONG#
-#typ=byte, short, int, long, longlong#
-#c=f*2,,,l*1#
+ #TYPE=BYTE,SHORT,INT,LONG,LONGLONG#
+ #typ=byte, short, int, long, longlong#
+ #c=f*2,,,l*1#
*/
static void
@TYPE@_remainder(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- register @typ@ ix,iy, tmp;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- ix = *((@typ@ *)i1);
- iy = *((@typ@ *)i2);
- if (iy == 0 || ix == 0) {
- if (iy == 0) generate_divbyzero_error();
- *((@typ@ *)op) = 0;
- }
- else if ((ix > 0) == (iy > 0)) {
- *((@typ@ *)op) = ix % iy;
- }
- else { /* handle mixed case the way Python does */
- tmp = ix % iy;
- if (tmp) tmp += iy;
- *((@typ@ *)op)= tmp;
- }
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ register @typ@ ix,iy, tmp;
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ ix = *((@typ@ *)i1);
+ iy = *((@typ@ *)i2);
+ if (iy == 0 || ix == 0) {
+ if (iy == 0) generate_divbyzero_error();
+ *((@typ@ *)op) = 0;
+ }
+ else if ((ix > 0) == (iy > 0)) {
+ *((@typ@ *)op) = ix % iy;
+ }
+ else { /* handle mixed case the way Python does */
+ tmp = ix % iy;
+ if (tmp) tmp += iy;
+ *((@typ@ *)op)= tmp;
+ }
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=UBYTE,USHORT,UINT,ULONG,ULONGLONG#
-#typ=ubyte, ushort, uint, ulong, ulonglong#
+ #TYPE=UBYTE,USHORT,UINT,ULONG,ULONGLONG#
+ #typ=ubyte, ushort, uint, ulong, ulonglong#
*/
static void
@TYPE@_remainder(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- register @typ@ ix,iy;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- ix = *((@typ@ *)i1);
- iy = *((@typ@ *)i2);
- if (iy == 0) {
- generate_divbyzero_error();
- *((@typ@ *)op) = 0;
- }
- *((@typ@ *)op) = ix % iy;
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ register @typ@ ix,iy;
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ ix = *((@typ@ *)i1);
+ iy = *((@typ@ *)i2);
+ if (iy == 0) {
+ generate_divbyzero_error();
+ *((@typ@ *)op) = 0;
+ }
+ *((@typ@ *)op) = ix % iy;
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=FLOAT,DOUBLE,LONGDOUBLE#
-#typ=float,double,longdouble#
-#c=f,,l#
+ #TYPE=FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=float,double,longdouble#
+ #c=f,,l#
*/
static void
@TYPE@_remainder(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- @typ@ x, y, res;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- x = *((@typ@ *)i1);
- y = *((@typ@ *)i2);
- res = fmod@c@(x, y);
- if (res && ((y < 0) != (res < 0))) {
- res += y;
- }
- *((@typ@ *)op)= res;
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ @typ@ x, y, res;
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ x = *((@typ@ *)i1);
+ y = *((@typ@ *)i2);
+ res = fmod@c@(x, y);
+ if (res && ((y < 0) != (res < 0))) {
+ res += y;
+ }
+ *((@typ@ *)op)= res;
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG#
-#typ=byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong#
+ #TYPE=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG#
+ #typ=byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong#
*/
static void
@TYPE@_fmod(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- @typ@ x, y;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- x = *((@typ@ *)i1);
- y = *((@typ@ *)i2);
- if (y == 0) {
- generate_divbyzero_error();
- *((@typ@ *)op) = 0;
- }
- else {
- *((@typ@ *)op)= x % y;
- }
-
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ @typ@ x, y;
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ x = *((@typ@ *)i1);
+ y = *((@typ@ *)i2);
+ if (y == 0) {
+ generate_divbyzero_error();
+ *((@typ@ *)op) = 0;
+ }
+ else {
+ *((@typ@ *)op)= x % y;
+ }
+
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG)*5#
-#typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong)*5#
-#OP= &*10, |*10, ^*10, <<*10, >>*10#
-#kind=bitwise_and*10, bitwise_or*10, bitwise_xor*10, left_shift*10, right_shift*10#
+ #TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG)*5#
+ #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong)*5#
+ #OP= &*10, |*10, ^*10, <<*10, >>*10#
+ #kind=bitwise_and*10, bitwise_or*10, bitwise_xor*10, left_shift*10, right_shift*10#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- register char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((@typ@ *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2);
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ register char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((@typ@ *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2);
+ }
}
/**end repeat**/
@@ -1870,61 +1870,61 @@ static void
static void
@TYPE@_invert(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0], os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((@typ@ *)op) = ~ *((@typ@*)i1);
- }
+ register intp i;
+ intp is1=steps[0], os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((@typ@ *)op) = ~ *((@typ@*)i1);
+ }
}
/**end repeat**/
static void
BOOL_invert(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0], os=steps[1], n=dimensions[0];
- char *i1=args[0], *op=args[1];
- for(i=0; i<n; i++, i1+=is1, op+=os) {
- *((Bool *)op) = (*((Bool *)i1) ? FALSE : TRUE);
- }
+ register intp i;
+ intp is1=steps[0], os=steps[1], n=dimensions[0];
+ char *i1=args[0], *op=args[1];
+ for(i=0; i<n; i++, i1+=is1, op+=os) {
+ *((Bool *)op) = (*((Bool *)i1) ? FALSE : TRUE);
+ }
}
/**begin repeat
-#TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
-#typ=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
+ #TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE#
+ #typ=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble#
*/
static void
@TYPE@_logical_xor(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((Bool *)op)=(*((@typ@ *)i1) || *((@typ@ *)i2)) && !(*((@typ@ *)i1) && *((@typ@ *)i2));
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((Bool *)op)=(*((@typ@ *)i1) || *((@typ@ *)i2)) && !(*((@typ@ *)i1) && *((@typ@ *)i2));
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=CFLOAT,CDOUBLE,CLONGDOUBLE#
-#typ=cfloat, cdouble, clongdouble#
+ #TYPE=CFLOAT,CDOUBLE,CLONGDOUBLE#
+ #typ=cfloat, cdouble, clongdouble#
*/
static void
@TYPE@_logical_xor(char **args, intp *dimensions, intp *steps, void *func)
{
- Bool p1, p2;
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- p1 = ((@typ@ *)i1)->real || ((@typ@ *)i1)->imag;
- p2 = ((@typ@ *)i2)->real || ((@typ@ *)i2)->imag;
- *((Bool *)op)= (p1 || p2) && !(p1 && p2);
- }
+ Bool p1, p2;
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ p1 = ((@typ@ *)i1)->real || ((@typ@ *)i1)->imag;
+ p2 = ((@typ@ *)i2)->real || ((@typ@ *)i2)->imag;
+ *((Bool *)op)= (p1 || p2) && !(p1 && p2);
+ }
}
/**end repeat**/
@@ -1932,46 +1932,46 @@ static void
/**begin repeat
-#TYPE=(BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*2#
-#OP= >*14, <*14#
-#typ=(Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2#
-#kind= maximum*14, minimum*14#
+ #TYPE=(BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*2#
+ #OP= >*14, <*14#
+ #typ=(Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2#
+ #kind= maximum*14, minimum*14#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- *((@typ@ *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2) ? *((@typ@ *)i1) : *((@typ@ *)i2);
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ *((@typ@ *)op)=*((@typ@ *)i1) @OP@ *((@typ@ *)i2) ? *((@typ@ *)i1) : *((@typ@ *)i2);
+ }
}
/**end repeat**/
/**begin repeat
-#TYPE=(CFLOAT,CDOUBLE,CLONGDOUBLE)*2#
-#OP= >*3, <*3#
-#typ=(cfloat, cdouble, clongdouble)*2#
-#kind= maximum*3, minimum*3#
+ #TYPE=(CFLOAT,CDOUBLE,CLONGDOUBLE)*2#
+ #OP= >*3, <*3#
+ #typ=(cfloat, cdouble, clongdouble)*2#
+ #kind= maximum*3, minimum*3#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- @typ@ *i1c, *i2c;
- for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- i1c = (@typ@ *)i1;
- i2c = (@typ@ *)i2;
- if ((i1c->real @OP@ i2c->real) || \
- ((i1c->real==i2c->real) && (i1c->imag @OP@ i2c->imag)))
- memmove(op, i1, sizeof(@typ@));
- else
- memmove(op, i2, sizeof(@typ@));
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ @typ@ *i1c, *i2c;
+ for(i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ i1c = (@typ@ *)i1;
+ i2c = (@typ@ *)i2;
+ if ((i1c->real @OP@ i2c->real) || \
+ ((i1c->real==i2c->real) && (i1c->imag @OP@ i2c->imag)))
+ memmove(op, i1, sizeof(@typ@));
+ else
+ memmove(op, i2, sizeof(@typ@));
+ }
}
/**end repeat**/
@@ -1979,41 +1979,41 @@ static void
/*** isinf, isinf, isfinite, signbit ***/
/**begin repeat
-#kind=isnan*3, isinf*3, isfinite*3, signbit*3#
-#TYPE=(FLOAT, DOUBLE, LONGDOUBLE)*4#
-#typ=(float, double, longdouble)*4#
-#c=(f,,l)*4#
+ #kind=isnan*3, isinf*3, isfinite*3, signbit*3#
+ #TYPE=(FLOAT, DOUBLE, LONGDOUBLE)*4#
+ #typ=(float, double, longdouble)*4#
+ #c=(f,,l)*4#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is=steps[0], os=steps[1], n=dimensions[0];
- char *ip=args[0], *op=args[1];
- for(i=0; i<n; i++, ip+=is, op+=os) {
- *((Bool *)op) = (Bool) (@kind@@c@(*((@typ@ *)ip)) != 0);
- }
+ register intp i;
+ intp is=steps[0], os=steps[1], n=dimensions[0];
+ char *ip=args[0], *op=args[1];
+ for(i=0; i<n; i++, ip+=is, op+=os) {
+ *((Bool *)op) = (Bool) (@kind@@c@(*((@typ@ *)ip)) != 0);
+ }
}
/**end repeat**/
/**begin repeat
-#kind=isnan*3, isinf*3, isfinite*3#
-#TYPE=(CFLOAT, CDOUBLE, CLONGDOUBLE)*3#
-#typ=(float, double, longdouble)*3#
-#c=(f,,l)*3#
-#OP=||*6,&&*3#
+ #kind=isnan*3, isinf*3, isfinite*3#
+ #TYPE=(CFLOAT, CDOUBLE, CLONGDOUBLE)*3#
+ #typ=(float, double, longdouble)*3#
+ #c=(f,,l)*3#
+ #OP=||*6,&&*3#
*/
static void
@TYPE@_@kind@(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is=steps[0], os=steps[1], n=dimensions[0];
- char *ip=args[0], *op=args[1];
- for(i=0; i<n; i++, ip+=is, op+=os) {
- *((Bool *)op) = @kind@@c@(((@typ@ *)ip)[0]) @OP@ \
- @kind@@c@(((@typ@ *)ip)[1]);
- }
+ register intp i;
+ intp is=steps[0], os=steps[1], n=dimensions[0];
+ char *ip=args[0], *op=args[1];
+ for(i=0; i<n; i++, ip+=is, op+=os) {
+ *((Bool *)op) = @kind@@c@(((@typ@ *)ip)[0]) @OP@ \
+ @kind@@c@(((@typ@ *)ip)[1]);
+ }
}
/**end repeat**/
@@ -2023,63 +2023,63 @@ static void
/****** modf ****/
/**begin repeat
-#TYPE=FLOAT, DOUBLE, LONGDOUBLE#
-#typ=float, double, longdouble#
-#c=f,,l#
+ #TYPE=FLOAT, DOUBLE, LONGDOUBLE#
+ #typ=float, double, longdouble#
+ #c=f,,l#
*/
static void
@TYPE@_modf(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os1=steps[1],os2=steps[2],n=dimensions[0];
- char *i1=args[0], *op1=args[1], *op2=args[2];
- @typ@ x1, y1, y2;
- for (i=0; i<n; i++, i1+=is1, op1+=os1, op2+=os2) {
- x1 = *((@typ@ *)i1);
- y1 = modf@c@(x1, &y2);
- *((@typ@ *)op1) = y1;
- *((@typ@ *)op2) = y2;
- }
+ register intp i;
+ intp is1=steps[0],os1=steps[1],os2=steps[2],n=dimensions[0];
+ char *i1=args[0], *op1=args[1], *op2=args[2];
+ @typ@ x1, y1, y2;
+ for (i=0; i<n; i++, i1+=is1, op1+=os1, op2+=os2) {
+ x1 = *((@typ@ *)i1);
+ y1 = modf@c@(x1, &y2);
+ *((@typ@ *)op1) = y1;
+ *((@typ@ *)op2) = y2;
+ }
}
/**end repeat**/
#define HAVE_DOUBLE_FUNCS
/**begin repeat
-#TYPE=FLOAT, DOUBLE, LONGDOUBLE#
-#typ=float, double, longdouble#
-#c=f,,l#
+ #TYPE=FLOAT, DOUBLE, LONGDOUBLE#
+ #typ=float, double, longdouble#
+ #c=f,,l#
*/
#ifdef HAVE_@TYPE@_FUNCS
static void
@TYPE@_frexp(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],os1=steps[1],os2=steps[2],n=dimensions[0];
- char *i1=args[0], *op1=args[1], *op2=args[2];
- @typ@ x1, y1;
- int y2;
- for (i=0; i<n; i++, i1+=is1, op1+=os1, op2+=os2) {
- x1 = *((@typ@ *)i1);
- y1 = frexp@c@(x1, &y2);
- *((@typ@ *)op1) = y1;
- *((int *) op2) = y2;
- }
+ register intp i;
+ intp is1=steps[0],os1=steps[1],os2=steps[2],n=dimensions[0];
+ char *i1=args[0], *op1=args[1], *op2=args[2];
+ @typ@ x1, y1;
+ int y2;
+ for (i=0; i<n; i++, i1+=is1, op1+=os1, op2+=os2) {
+ x1 = *((@typ@ *)i1);
+ y1 = frexp@c@(x1, &y2);
+ *((@typ@ *)op1) = y1;
+ *((int *) op2) = y2;
+ }
}
static void
@TYPE@_ldexp(char **args, intp *dimensions, intp *steps, void *func)
{
- register intp i;
- intp is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
- char *i1=args[0], *i2=args[1], *op=args[2];
- @typ@ x1, y1;
- int x2;
- for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
- x1 = *((@typ@ *)i1);
- x2 = *((int *)i2);
- y1 = ldexp@c@(x1, x2);
- *((@typ@ *)op) = y1;
- }
+ register intp i;
+ intp is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0];
+ char *i1=args[0], *i2=args[1], *op=args[2];
+ @typ@ x1, y1;
+ int x2;
+ for (i=0; i<n; i++, i1+=is1, i2+=is2, op+=os) {
+ x1 = *((@typ@ *)i1);
+ x2 = *((int *)i2);
+ y1 = ldexp@c@(x1, x2);
+ *((@typ@ *)op) = y1;
+ }
}
#endif
/**end repeat**/
@@ -2088,43 +2088,43 @@ static void
static PyUFuncGenericFunction frexp_functions[] = {
#ifdef HAVE_FLOAT_FUNCS
- FLOAT_frexp,
+ FLOAT_frexp,
#endif
- DOUBLE_frexp
+ DOUBLE_frexp
#ifdef HAVE_LONGDOUBLE_FUNCS
- ,LONGDOUBLE_frexp
+ ,LONGDOUBLE_frexp
#endif
};
static void * blank3_data[] = { (void *)NULL, (void *)NULL, (void *)NULL};
static char frexp_signatures[] = {
#ifdef HAVE_FLOAT_FUNCS
- PyArray_FLOAT, PyArray_FLOAT, PyArray_INT,
+ PyArray_FLOAT, PyArray_FLOAT, PyArray_INT,
#endif
- PyArray_DOUBLE, PyArray_DOUBLE, PyArray_INT
+ PyArray_DOUBLE, PyArray_DOUBLE, PyArray_INT
#ifdef HAVE_LONGDOUBLE_FUNCS
- ,PyArray_LONGDOUBLE, PyArray_LONGDOUBLE, PyArray_INT
+ ,PyArray_LONGDOUBLE, PyArray_LONGDOUBLE, PyArray_INT
#endif
};
static PyUFuncGenericFunction ldexp_functions[] = {
#ifdef HAVE_FLOAT_FUNCS
- FLOAT_ldexp,
+ FLOAT_ldexp,
#endif
- DOUBLE_ldexp
+ DOUBLE_ldexp
#ifdef HAVE_LONGDOUBLE_FUNCS
- ,LONGDOUBLE_ldexp
+ ,LONGDOUBLE_ldexp
#endif
};
static char ldexp_signatures[] = {
#ifdef HAVE_FLOAT_FUNCS
- PyArray_FLOAT, PyArray_INT, PyArray_FLOAT,
+ PyArray_FLOAT, PyArray_INT, PyArray_FLOAT,
#endif
- PyArray_DOUBLE, PyArray_INT, PyArray_DOUBLE
+ PyArray_DOUBLE, PyArray_INT, PyArray_DOUBLE
#ifdef HAVE_LONGDOUBLE_FUNCS
- ,PyArray_LONGDOUBLE, PyArray_INT, PyArray_LONGDOUBLE
+ ,PyArray_LONGDOUBLE, PyArray_INT, PyArray_LONGDOUBLE
#endif
};
@@ -2173,143 +2173,143 @@ pzero_init(void)
static void
InitOtherOperators(PyObject *dictionary) {
- PyObject *f;
- int num=1;
+ PyObject *f;
+ int num=1;
#ifdef HAVE_LONGDOUBLE_FUNCS
- num += 1;
+ num += 1;
#endif
#ifdef HAVE_FLOAT_FUNCS
- num += 1;
-#endif
- f = PyUFunc_FromFuncAndData(frexp_functions, blank3_data,
- frexp_signatures, num,
- 1, 2, PyUFunc_None, "frexp",
- "Split the number, x, into a normalized"\
- " fraction (y1) and exponent (y2)",0);
- PyDict_SetItemString(dictionary, "frexp", f);
- Py_DECREF(f);
-
- f = PyUFunc_FromFuncAndData(ldexp_functions, blank3_data, ldexp_signatures, num,
- 2, 1, PyUFunc_None, "ldexp",
- "Compute y = x1 * 2**x2.",0);
- PyDict_SetItemString(dictionary, "ldexp", f);
- Py_DECREF(f);
- return;
+ num += 1;
+#endif
+ f = PyUFunc_FromFuncAndData(frexp_functions, blank3_data,
+ frexp_signatures, num,
+ 1, 2, PyUFunc_None, "frexp",
+ "Split the number, x, into a normalized"\
+ " fraction (y1) and exponent (y2)",0);
+ PyDict_SetItemString(dictionary, "frexp", f);
+ Py_DECREF(f);
+
+ f = PyUFunc_FromFuncAndData(ldexp_functions, blank3_data, ldexp_signatures, num,
+ 2, 1, PyUFunc_None, "ldexp",
+ "Compute y = x1 * 2**x2.",0);
+ PyDict_SetItemString(dictionary, "ldexp", f);
+ Py_DECREF(f);
+ return;
}
static struct PyMethodDef methods[] = {
- {"frompyfunc", (PyCFunction) ufunc_frompyfunc,
- METH_VARARGS | METH_KEYWORDS, doc_frompyfunc},
- {"seterrobj", (PyCFunction) ufunc_seterr,
- METH_VARARGS, NULL},
- {"geterrobj", (PyCFunction) ufunc_geterr,
- METH_VARARGS, NULL},
- {NULL, NULL, 0} /* sentinel */
+ {"frompyfunc", (PyCFunction) ufunc_frompyfunc,
+ METH_VARARGS | METH_KEYWORDS, doc_frompyfunc},
+ {"seterrobj", (PyCFunction) ufunc_seterr,
+ METH_VARARGS, NULL},
+ {"geterrobj", (PyCFunction) ufunc_geterr,
+ METH_VARARGS, NULL},
+ {NULL, NULL, 0} /* sentinel */
};
PyMODINIT_FUNC initumath(void) {
- PyObject *m, *d, *s, *s2, *c_api;
- double pinf, pzero, mynan;
- int UFUNC_FLOATING_POINT_SUPPORT = 1;
+ PyObject *m, *d, *s, *s2, *c_api;
+ double pinf, pzero, mynan;
+ int UFUNC_FLOATING_POINT_SUPPORT = 1;
#ifdef NO_UFUNC_FLOATING_POINT_SUPPORT
- UFUNC_FLOATING_POINT_SUPPORT = 0;
-#endif
- /* Create the module and add the functions */
- m = Py_InitModule("umath", methods);
-
- /* Import the array */
- if (_import_array() < 0) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_ImportError,
- "umath failed: Could not import array core.");
- }
- return;
+ UFUNC_FLOATING_POINT_SUPPORT = 0;
+#endif
+ /* Create the module and add the functions */
+ m = Py_InitModule("umath", methods);
+
+ /* Import the array */
+ if (_import_array() < 0) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ImportError,
+ "umath failed: Could not import array core.");
}
+ return;
+ }
- /* Initialize the types */
- if (PyType_Ready(&PyUFunc_Type) < 0)
- return;
+ /* Initialize the types */
+ if (PyType_Ready(&PyUFunc_Type) < 0)
+ return;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
- c_api = PyCObject_FromVoidPtr((void *)PyUFunc_API, NULL);
- if (PyErr_Occurred()) goto err;
- PyDict_SetItemString(d, "_UFUNC_API", c_api);
- Py_DECREF(c_api);
- if (PyErr_Occurred()) goto err;
+ c_api = PyCObject_FromVoidPtr((void *)PyUFunc_API, NULL);
+ if (PyErr_Occurred()) goto err;
+ PyDict_SetItemString(d, "_UFUNC_API", c_api);
+ Py_DECREF(c_api);
+ if (PyErr_Occurred()) goto err;
- s = PyString_FromString("0.4.0");
- PyDict_SetItemString(d, "__version__", s);
- Py_DECREF(s);
+ s = PyString_FromString("0.4.0");
+ PyDict_SetItemString(d, "__version__", s);
+ Py_DECREF(s);
- /* Load the ufunc operators into the array module's namespace */
- InitOperators(d);
+ /* Load the ufunc operators into the array module's namespace */
+ InitOperators(d);
- InitOtherOperators(d);
+ InitOtherOperators(d);
- PyDict_SetItemString(d, "pi", s = PyFloat_FromDouble(M_PI));
- Py_DECREF(s);
- PyDict_SetItemString(d, "e", s = PyFloat_FromDouble(exp(1.0)));
- Py_DECREF(s);
+ PyDict_SetItemString(d, "pi", s = PyFloat_FromDouble(M_PI));
+ Py_DECREF(s);
+ PyDict_SetItemString(d, "e", s = PyFloat_FromDouble(exp(1.0)));
+ Py_DECREF(s);
#define ADDCONST(str) PyModule_AddIntConstant(m, #str, UFUNC_##str)
#define ADDSCONST(str) PyModule_AddStringConstant(m, "UFUNC_" #str, UFUNC_##str)
- ADDCONST(ERR_IGNORE);
- ADDCONST(ERR_WARN);
- ADDCONST(ERR_CALL);
- ADDCONST(ERR_RAISE);
- ADDCONST(ERR_PRINT);
- ADDCONST(ERR_LOG);
- ADDCONST(ERR_DEFAULT);
- ADDCONST(ERR_DEFAULT2);
+ ADDCONST(ERR_IGNORE);
+ ADDCONST(ERR_WARN);
+ ADDCONST(ERR_CALL);
+ ADDCONST(ERR_RAISE);
+ ADDCONST(ERR_PRINT);
+ ADDCONST(ERR_LOG);
+ ADDCONST(ERR_DEFAULT);
+ ADDCONST(ERR_DEFAULT2);
- ADDCONST(SHIFT_DIVIDEBYZERO);
- ADDCONST(SHIFT_OVERFLOW);
- ADDCONST(SHIFT_UNDERFLOW);
- ADDCONST(SHIFT_INVALID);
+ ADDCONST(SHIFT_DIVIDEBYZERO);
+ ADDCONST(SHIFT_OVERFLOW);
+ ADDCONST(SHIFT_UNDERFLOW);
+ ADDCONST(SHIFT_INVALID);
- ADDCONST(FPE_DIVIDEBYZERO);
- ADDCONST(FPE_OVERFLOW);
- ADDCONST(FPE_UNDERFLOW);
- ADDCONST(FPE_INVALID);
+ ADDCONST(FPE_DIVIDEBYZERO);
+ ADDCONST(FPE_OVERFLOW);
+ ADDCONST(FPE_UNDERFLOW);
+ ADDCONST(FPE_INVALID);
- ADDCONST(FLOATING_POINT_SUPPORT);
+ ADDCONST(FLOATING_POINT_SUPPORT);
- ADDSCONST(PYVALS_NAME);
+ ADDSCONST(PYVALS_NAME);
#undef ADDCONST
#undef ADDSCONST
- PyModule_AddIntConstant(m, "UFUNC_BUFSIZE_DEFAULT", (long)PyArray_BUFSIZE);
+ PyModule_AddIntConstant(m, "UFUNC_BUFSIZE_DEFAULT", (long)PyArray_BUFSIZE);
- pinf = pinf_init();
- pzero = pzero_init();
- mynan = pinf / pinf;
+ pinf = pinf_init();
+ pzero = pzero_init();
+ mynan = pinf / pinf;
- PyModule_AddObject(m, "PINF", PyFloat_FromDouble(pinf));
- PyModule_AddObject(m, "NINF", PyFloat_FromDouble(-pinf));
- PyModule_AddObject(m, "PZERO", PyFloat_FromDouble(pzero));
- PyModule_AddObject(m, "NZERO", PyFloat_FromDouble(-pzero));
- PyModule_AddObject(m, "NAN", PyFloat_FromDouble(mynan));
+ PyModule_AddObject(m, "PINF", PyFloat_FromDouble(pinf));
+ PyModule_AddObject(m, "NINF", PyFloat_FromDouble(-pinf));
+ PyModule_AddObject(m, "PZERO", PyFloat_FromDouble(pzero));
+ PyModule_AddObject(m, "NZERO", PyFloat_FromDouble(-pzero));
+ PyModule_AddObject(m, "NAN", PyFloat_FromDouble(mynan));
- s = PyDict_GetItemString(d, "conjugate");
- s2 = PyDict_GetItemString(d, "remainder");
- /* Setup the array object's numerical structures with appropriate
- ufuncs in d*/
- PyArray_SetNumericOps(d);
+ s = PyDict_GetItemString(d, "conjugate");
+ s2 = PyDict_GetItemString(d, "remainder");
+ /* Setup the array object's numerical structures with appropriate
+ ufuncs in d*/
+ PyArray_SetNumericOps(d);
- PyDict_SetItemString(d, "conj", s);
- PyDict_SetItemString(d, "mod", s2);
+ PyDict_SetItemString(d, "conj", s);
+ PyDict_SetItemString(d, "mod", s2);
- return;
+ return;
err:
- /* Check for errors */
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot load umath module.");
- }
- return;
+ /* Check for errors */
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot load umath module.");
+ }
+ return;
}