From numpy-svn at scipy.org Tue Aug 1 02:36:33 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 1 Aug 2006 01:36:33 -0500 (CDT) Subject: [Numpy-svn] r2941 - trunk/numpy/core/include/numpy Message-ID: <20060801063633.F0F6839C00B@new.scipy.org> Author: oliphant Date: 2006-08-01 01:36:28 -0500 (Tue, 01 Aug 2006) New Revision: 2941 Modified: trunk/numpy/core/include/numpy/arrayobject.h Log: Add IntpArrType_Type Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-01 00:07:42 UTC (rev 2940) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-01 06:36:28 UTC (rev 2941) @@ -654,6 +654,7 @@ #elif SIZEOF_PY_INTPTR_T == SIZEOF_LONG #define NPY_INTP NPY_LONG #define NPY_UINTP NPY_ULONG + #define PyIntpArrType_Type PyLongArrType_Type #define PyUIntpArrType_Type PyULongArrType_Type #define NPY_MAX_INTP NPY_MAX_LONG #define NPY_MIN_INTP MIN_LONG From numpy-svn at scipy.org Tue Aug 1 16:23:19 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 1 Aug 2006 15:23:19 -0500 (CDT) Subject: [Numpy-svn] r2942 - trunk/numpy/random/mtrand Message-ID: <20060801202319.538AE39C00F@new.scipy.org> Author: oliphant Date: 2006-08-01 15:23:15 -0500 (Tue, 01 Aug 2006) New Revision: 2942 Modified: trunk/numpy/random/mtrand/mtrand.c trunk/numpy/random/mtrand/numpy.pxi Log: Add PyArray_ContiguousFromObject to numpy.pxi Modified: trunk/numpy/random/mtrand/mtrand.c =================================================================== --- trunk/numpy/random/mtrand/mtrand.c 2006-08-01 06:36:28 UTC (rev 2941) +++ trunk/numpy/random/mtrand/mtrand.c 2006-08-01 20:23:15 UTC (rev 2942) @@ -1,4 +1,4 @@ -/* Generated by Pyrex 0.9.4.1 on Wed Jul 26 11:44:23 2006 */ +/* Generated by Pyrex 0.9.4.1 on Tue Aug 1 14:19:59 2006 */ #include "Python.h" #include "structmember.h" @@ -1764,7 +1764,6 @@ } static PyObject *__pyx_n_type; -static PyObject *__pyx_n_PyArray_ContiguousFromObject; static PyObject *__pyx_f_6mtrand_11RandomState_seed(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_6mtrand_11RandomState_seed[] = "Seed the generator.\n\n seed(seed=None)\n\n seed can be an integer, an array (or other sequence) of integers of any\n length, or None. If seed is None, then RandomState will try to read data\n from /dev/urandom (or the Windows analogue) if available or seed from\n the clock otherwise.\n "; @@ -1778,8 +1777,6 @@ PyObject *__pyx_3 = 0; PyObject *__pyx_4 = 0; unsigned long __pyx_5; - PyObject *__pyx_6 = 0; - PyObject *__pyx_7 = 0; static char *__pyx_argnames[] = {"seed",0}; __pyx_v_seed = __pyx_k3; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "|O", __pyx_argnames, &__pyx_v_seed)) return 0; @@ -1816,26 +1813,11 @@ /*else*/ { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":502 */ - __pyx_3 = __Pyx_GetName(__pyx_b, __pyx_n_PyArray_ContiguousFromObject); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; goto __pyx_L1;} - __pyx_4 = PyInt_FromLong(NPY_LONG); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; goto __pyx_L1;} - __pyx_2 = PyInt_FromLong(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; goto __pyx_L1;} - __pyx_6 = PyInt_FromLong(1); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; goto __pyx_L1;} - __pyx_7 = PyTuple_New(4); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; goto __pyx_L1;} - Py_INCREF(__pyx_v_seed); - PyTuple_SET_ITEM(__pyx_7, 0, __pyx_v_seed); - PyTuple_SET_ITEM(__pyx_7, 1, __pyx_4); - PyTuple_SET_ITEM(__pyx_7, 2, __pyx_2); - PyTuple_SET_ITEM(__pyx_7, 3, __pyx_6); - __pyx_4 = 0; - __pyx_2 = 0; - __pyx_6 = 0; - __pyx_4 = PyObject_CallObject(__pyx_3, __pyx_7); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; goto __pyx_L1;} - Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(__pyx_7); __pyx_7 = 0; - Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_4))); + __pyx_3 = PyArray_ContiguousFromObject(__pyx_v_seed,NPY_LONG,1,1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 502; goto __pyx_L1;} + Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_3))); Py_DECREF(((PyObject *)arrayObject_obj)); - arrayObject_obj = ((PyArrayObject *)__pyx_4); - Py_DECREF(__pyx_4); __pyx_4 = 0; + arrayObject_obj = ((PyArrayObject *)__pyx_3); + Py_DECREF(__pyx_3); __pyx_3 = 0; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":503 */ init_by_array(((struct __pyx_obj_6mtrand_RandomState *)__pyx_v_self)->internal_state,((unsigned long (*))arrayObject_obj->data),(arrayObject_obj->dimensions[0])); @@ -1848,8 +1830,6 @@ Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); Py_XDECREF(__pyx_4); - Py_XDECREF(__pyx_6); - Py_XDECREF(__pyx_7); __Pyx_AddTraceback("mtrand.RandomState.seed"); __pyx_r = 0; __pyx_L0:; @@ -1945,8 +1925,6 @@ PyObject *__pyx_2 = 0; int __pyx_3; PyObject *__pyx_4 = 0; - PyObject *__pyx_5 = 0; - PyObject *__pyx_6 = 0; static char *__pyx_argnames[] = {"state",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_state)) return 0; Py_INCREF(__pyx_v_self); @@ -1997,39 +1975,24 @@ Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":529 */ - __pyx_4 = __Pyx_GetName(__pyx_b, __pyx_n_PyArray_ContiguousFromObject); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; goto __pyx_L1;} - __pyx_2 = PyInt_FromLong(NPY_LONG); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; goto __pyx_L1;} - __pyx_1 = PyInt_FromLong(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; goto __pyx_L1;} - __pyx_5 = PyInt_FromLong(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; goto __pyx_L1;} - __pyx_6 = PyTuple_New(4); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; goto __pyx_L1;} - Py_INCREF(__pyx_v_key); - PyTuple_SET_ITEM(__pyx_6, 0, __pyx_v_key); - PyTuple_SET_ITEM(__pyx_6, 1, __pyx_2); - PyTuple_SET_ITEM(__pyx_6, 2, __pyx_1); - PyTuple_SET_ITEM(__pyx_6, 3, __pyx_5); - __pyx_2 = 0; - __pyx_1 = 0; - __pyx_5 = 0; - __pyx_2 = PyObject_CallObject(__pyx_4, __pyx_6); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; goto __pyx_L1;} - Py_DECREF(__pyx_4); __pyx_4 = 0; - Py_DECREF(__pyx_6); __pyx_6 = 0; - Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_2))); + __pyx_4 = PyArray_ContiguousFromObject(__pyx_v_key,NPY_LONG,1,1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; goto __pyx_L1;} + Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_4))); Py_DECREF(((PyObject *)arrayObject_obj)); - arrayObject_obj = ((PyArrayObject *)__pyx_2); - Py_DECREF(__pyx_2); __pyx_2 = 0; + arrayObject_obj = ((PyArrayObject *)__pyx_4); + Py_DECREF(__pyx_4); __pyx_4 = 0; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":530 */ __pyx_3 = ((arrayObject_obj->dimensions[0]) != 624); if (__pyx_3) { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":531 */ - __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; goto __pyx_L1;} - __pyx_5 = PyTuple_New(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; goto __pyx_L1;} + __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; goto __pyx_L1;} + __pyx_1 = PyTuple_New(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; goto __pyx_L1;} Py_INCREF(__pyx_k69p); - PyTuple_SET_ITEM(__pyx_5, 0, __pyx_k69p); - __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_5); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; goto __pyx_L1;} + PyTuple_SET_ITEM(__pyx_1, 0, __pyx_k69p); + __pyx_4 = PyObject_CallObject(__pyx_2, __pyx_1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; goto __pyx_L1;} + Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; - Py_DECREF(__pyx_5); __pyx_5 = 0; __Pyx_Raise(__pyx_4, 0, 0); Py_DECREF(__pyx_4); __pyx_4 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; goto __pyx_L1;} @@ -2049,8 +2012,6 @@ Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_4); - Py_XDECREF(__pyx_5); - Py_XDECREF(__pyx_6); __Pyx_AddTraceback("mtrand.RandomState.set_state"); __pyx_r = 0; __pyx_L0:; @@ -7045,9 +7006,7 @@ PyObject *__pyx_2 = 0; PyObject *__pyx_3 = 0; long __pyx_4; - PyObject *__pyx_5 = 0; - PyObject *__pyx_6 = 0; - int __pyx_7; + int __pyx_5; static char *__pyx_argnames[] = {"n","pvals","size",0}; __pyx_v_size = __pyx_k59; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "lO|O", __pyx_argnames, &__pyx_v_n, &__pyx_v_pvals, &__pyx_v_size)) return 0; @@ -7072,42 +7031,27 @@ __pyx_v_d = __pyx_4; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1169 */ - __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_PyArray_ContiguousFromObject); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; goto __pyx_L1;} - __pyx_2 = PyInt_FromLong(NPY_DOUBLE); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; goto __pyx_L1;} - __pyx_3 = PyInt_FromLong(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; goto __pyx_L1;} - __pyx_5 = PyInt_FromLong(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; goto __pyx_L1;} - __pyx_6 = PyTuple_New(4); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; goto __pyx_L1;} - Py_INCREF(__pyx_v_pvals); - PyTuple_SET_ITEM(__pyx_6, 0, __pyx_v_pvals); - PyTuple_SET_ITEM(__pyx_6, 1, __pyx_2); - PyTuple_SET_ITEM(__pyx_6, 2, __pyx_3); - PyTuple_SET_ITEM(__pyx_6, 3, __pyx_5); - __pyx_2 = 0; - __pyx_3 = 0; - __pyx_5 = 0; - __pyx_2 = PyObject_CallObject(__pyx_1, __pyx_6); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; goto __pyx_L1;} - Py_DECREF(__pyx_1); __pyx_1 = 0; - Py_DECREF(__pyx_6); __pyx_6 = 0; - Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_2))); + __pyx_1 = PyArray_ContiguousFromObject(__pyx_v_pvals,NPY_DOUBLE,1,1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1169; goto __pyx_L1;} + Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_1))); Py_DECREF(((PyObject *)arrayObject_parr)); - arrayObject_parr = ((PyArrayObject *)__pyx_2); - Py_DECREF(__pyx_2); __pyx_2 = 0; + arrayObject_parr = ((PyArrayObject *)__pyx_1); + Py_DECREF(__pyx_1); __pyx_1 = 0; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1170 */ __pyx_v_pix = ((double (*))arrayObject_parr->data); /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1172 */ - __pyx_7 = (__pyx_f_6mtrand_kahan_sum(__pyx_v_pix,(__pyx_v_d - 1)) > 1.0); - if (__pyx_7) { + __pyx_5 = (__pyx_f_6mtrand_kahan_sum(__pyx_v_pix,(__pyx_v_d - 1)) > 1.0); + if (__pyx_5) { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1173 */ - __pyx_3 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; goto __pyx_L1;} - __pyx_5 = PyTuple_New(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; goto __pyx_L1;} + __pyx_2 = __Pyx_GetName(__pyx_b, __pyx_n_ValueError); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; goto __pyx_L1;} + __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; goto __pyx_L1;} Py_INCREF(__pyx_k123p); - PyTuple_SET_ITEM(__pyx_5, 0, __pyx_k123p); - __pyx_1 = PyObject_CallObject(__pyx_3, __pyx_5); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; goto __pyx_L1;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k123p); + __pyx_1 = PyObject_CallObject(__pyx_2, __pyx_3); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; goto __pyx_L1;} + Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(__pyx_5); __pyx_5 = 0; __Pyx_Raise(__pyx_1, 0, 0); Py_DECREF(__pyx_1); __pyx_1 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1173; goto __pyx_L1;} @@ -7116,31 +7060,31 @@ __pyx_L2:; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1175 */ - __pyx_7 = __pyx_v_size == Py_None; - if (__pyx_7) { + __pyx_5 = __pyx_v_size == Py_None; + if (__pyx_5) { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1176 */ - __pyx_6 = PyInt_FromLong(__pyx_v_d); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1176; goto __pyx_L1;} - __pyx_2 = PyTuple_New(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1176; goto __pyx_L1;} - PyTuple_SET_ITEM(__pyx_2, 0, __pyx_6); - __pyx_6 = 0; - Py_DECREF(__pyx_v_shape); - __pyx_v_shape = __pyx_2; + __pyx_2 = PyInt_FromLong(__pyx_v_d); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1176; goto __pyx_L1;} + __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1176; goto __pyx_L1;} + PyTuple_SET_ITEM(__pyx_3, 0, __pyx_2); __pyx_2 = 0; + Py_DECREF(__pyx_v_shape); + __pyx_v_shape = __pyx_3; + __pyx_3 = 0; goto __pyx_L3; } - __pyx_3 = __Pyx_GetName(__pyx_b, __pyx_n_type); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} - __pyx_5 = PyTuple_New(1); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} + __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_type); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} + __pyx_2 = PyTuple_New(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} Py_INCREF(__pyx_v_size); - PyTuple_SET_ITEM(__pyx_5, 0, __pyx_v_size); - __pyx_1 = PyObject_CallObject(__pyx_3, __pyx_5); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_v_size); + __pyx_3 = PyObject_CallObject(__pyx_1, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + Py_DECREF(__pyx_2); __pyx_2 = 0; + __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_int); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} + __pyx_5 = __pyx_3 == __pyx_1; Py_DECREF(__pyx_3); __pyx_3 = 0; - Py_DECREF(__pyx_5); __pyx_5 = 0; - __pyx_6 = __Pyx_GetName(__pyx_b, __pyx_n_int); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1177; goto __pyx_L1;} - __pyx_7 = __pyx_1 == __pyx_6; Py_DECREF(__pyx_1); __pyx_1 = 0; - Py_DECREF(__pyx_6); __pyx_6 = 0; - if (__pyx_7) { + if (__pyx_5) { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1178 */ __pyx_2 = PyInt_FromLong(__pyx_v_d); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1178; goto __pyx_L1;} @@ -7157,34 +7101,34 @@ /*else*/ { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1180 */ - __pyx_5 = PyInt_FromLong(__pyx_v_d); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1180; goto __pyx_L1;} - __pyx_1 = PyTuple_New(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1180; goto __pyx_L1;} - PyTuple_SET_ITEM(__pyx_1, 0, __pyx_5); - __pyx_5 = 0; - __pyx_6 = PyNumber_Add(__pyx_v_size, __pyx_1); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1180; goto __pyx_L1;} - Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_1 = PyInt_FromLong(__pyx_v_d); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1180; goto __pyx_L1;} + __pyx_2 = PyTuple_New(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1180; goto __pyx_L1;} + PyTuple_SET_ITEM(__pyx_2, 0, __pyx_1); + __pyx_1 = 0; + __pyx_3 = PyNumber_Add(__pyx_v_size, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1180; goto __pyx_L1;} + Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_v_shape); - __pyx_v_shape = __pyx_6; - __pyx_6 = 0; + __pyx_v_shape = __pyx_3; + __pyx_3 = 0; } __pyx_L3:; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1182 */ - __pyx_2 = __Pyx_GetName(__pyx_m, __pyx_n__sp); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} - __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_n_zeros); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} - Py_DECREF(__pyx_2); __pyx_2 = 0; - __pyx_5 = __Pyx_GetName(__pyx_b, __pyx_n_int); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} + __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n__sp); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} + __pyx_2 = PyObject_GetAttr(__pyx_1, __pyx_n_zeros); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} + Py_DECREF(__pyx_1); __pyx_1 = 0; + __pyx_3 = __Pyx_GetName(__pyx_b, __pyx_n_int); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} __pyx_1 = PyTuple_New(2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} Py_INCREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_1, 0, __pyx_v_shape); - PyTuple_SET_ITEM(__pyx_1, 1, __pyx_5); - __pyx_5 = 0; - __pyx_6 = PyObject_CallObject(__pyx_3, __pyx_1); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} - Py_DECREF(__pyx_3); __pyx_3 = 0; + PyTuple_SET_ITEM(__pyx_1, 1, __pyx_3); + __pyx_3 = 0; + __pyx_3 = PyObject_CallObject(__pyx_2, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1182; goto __pyx_L1;} + Py_DECREF(__pyx_2); __pyx_2 = 0; Py_DECREF(__pyx_1); __pyx_1 = 0; Py_DECREF(__pyx_v_multin); - __pyx_v_multin = __pyx_6; - __pyx_6 = 0; + __pyx_v_multin = __pyx_3; + __pyx_3 = 0; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1183 */ Py_INCREF(((PyObject *)((PyArrayObject *)__pyx_v_multin))); @@ -7200,8 +7144,8 @@ /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1186 */ while (1) { __pyx_L4:; - __pyx_7 = (__pyx_v_i < PyArray_SIZE(arrayObject_mnarr)); - if (!__pyx_7) break; + __pyx_5 = (__pyx_v_i < PyArray_SIZE(arrayObject_mnarr)); + if (!__pyx_5) break; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1187 */ __pyx_v_Sum = 1.0; @@ -7220,8 +7164,8 @@ __pyx_v_dn = (__pyx_v_dn - (__pyx_v_mnix[(__pyx_v_i + __pyx_v_j)])); /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1192 */ - __pyx_7 = (__pyx_v_dn <= 0); - if (__pyx_7) { + __pyx_5 = (__pyx_v_dn <= 0); + if (__pyx_5) { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1193 */ goto __pyx_L7; @@ -7236,8 +7180,8 @@ __pyx_L7:; /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1195 */ - __pyx_7 = (__pyx_v_dn > 0); - if (__pyx_7) { + __pyx_5 = (__pyx_v_dn > 0); + if (__pyx_5) { /* "/home/oliphant/numpy/numpy/random/mtrand/mtrand.pyx":1196 */ (__pyx_v_mnix[((__pyx_v_i + __pyx_v_d) - 1)]) = __pyx_v_dn; @@ -7261,8 +7205,6 @@ Py_XDECREF(__pyx_1); Py_XDECREF(__pyx_2); Py_XDECREF(__pyx_3); - Py_XDECREF(__pyx_5); - Py_XDECREF(__pyx_6); __Pyx_AddTraceback("mtrand.RandomState.multinomial"); __pyx_r = 0; __pyx_L0:; @@ -7450,7 +7392,6 @@ static __Pyx_InternTabEntry __pyx_intern_tab[] = { {&__pyx_n_MT19937, "MT19937"}, - {&__pyx_n_PyArray_ContiguousFromObject, "PyArray_ContiguousFromObject"}, {&__pyx_n_ValueError, "ValueError"}, {&__pyx_n___RandomState_ctor, "__RandomState_ctor"}, {&__pyx_n__rand, "_rand"}, Modified: trunk/numpy/random/mtrand/numpy.pxi =================================================================== --- trunk/numpy/random/mtrand/numpy.pxi 2006-08-01 06:36:28 UTC (rev 2941) +++ trunk/numpy/random/mtrand/numpy.pxi 2006-08-01 20:23:15 UTC (rev 2942) @@ -105,6 +105,8 @@ int PyArray_Check(object obj) object PyArray_ContiguousFromAny(object obj, NPY_TYPES type, int mindim, int maxdim) + object PyArray_ContiguousFromObject(object obj, NPY_TYPES type, + int mindim, int maxdim) npy_intp PyArray_SIZE(ndarray arr) npy_intp PyArray_NBYTES(ndarray arr) void *PyArray_DATA(ndarray arr) From numpy-svn at scipy.org Wed Aug 2 12:38:05 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 2 Aug 2006 11:38:05 -0500 (CDT) Subject: [Numpy-svn] r2943 - in trunk/numpy: . lib numarray Message-ID: <20060802163805.6E3E639C039@new.scipy.org> Author: oliphant Date: 2006-08-02 11:37:59 -0500 (Wed, 02 Aug 2006) New Revision: 2943 Added: trunk/numpy/numarray/numclass.py trunk/numpy/numarray/numerictypes.py Modified: trunk/numpy/lib/twodim_base.py trunk/numpy/matlib.py trunk/numpy/numarray/__init__.py Log: Add diagflat. Begin to add numarray compatibility Modified: trunk/numpy/lib/twodim_base.py =================================================================== --- trunk/numpy/lib/twodim_base.py 2006-08-01 20:23:15 UTC (rev 2942) +++ trunk/numpy/lib/twodim_base.py 2006-08-02 16:37:59 UTC (rev 2943) @@ -2,7 +2,7 @@ """ -__all__ = ['diag','eye','fliplr','flipud','rot90','tri','triu','tril', +__all__ = ['diag','diagflat','eye','fliplr','flipud','rot90','tri','triu','tril', 'vander','histogram2d'] from numpy.core.numeric import asanyarray, int_, equal, subtract, arange, \ @@ -81,7 +81,26 @@ else: raise ValueError, "Input must be 1- or 2-d." - +def diagflat(v,k=0): + try: + wrap = v.__array_wrap__ + except AttributeError: + wrap = None + v = asarray(v).ravel() + s = len(v) + n = s + abs(k) + res = zeros((n,n), v.dtype) + if (k>=0): + i = arange(0,n-k) + fi = i+k+i*n + else: + i = arange(0,n+k) + fi = i+(i-k)*n + res.flat[fi] = v + if not wrap: + return res + return wrap(res) + def tri(N, M=None, k=0, dtype=float): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. Modified: trunk/numpy/matlib.py =================================================================== --- trunk/numpy/matlib.py 2006-08-01 20:23:15 UTC (rev 2942) +++ trunk/numpy/matlib.py 2006-08-02 16:37:59 UTC (rev 2943) @@ -47,3 +47,5 @@ if isinstance(args[0], tuple): args = args[0] return asmatrix(N.random.rand(*args)) + + Modified: trunk/numpy/numarray/__init__.py =================================================================== --- trunk/numpy/numarray/__init__.py 2006-08-01 20:23:15 UTC (rev 2942) +++ trunk/numpy/numarray/__init__.py 2006-08-02 16:37:59 UTC (rev 2943) @@ -1,2 +1,5 @@ from util import * +from numclass import * + __all__ = util.__all__ +__all__ += numclass.__all__ Added: trunk/numpy/numarray/numclass.py =================================================================== --- trunk/numpy/numarray/numclass.py 2006-08-01 20:23:15 UTC (rev 2942) +++ trunk/numpy/numarray/numclass.py 2006-08-02 16:37:59 UTC (rev 2943) @@ -0,0 +1,133 @@ +from numpy.core.multiarray import ndarray +import numerictypes as _nt +import numpy as N +import sys as _sys + +__all__ = ['NumArray'] + +class NumArray(ndarray): + def __new__(klass, shape=None, type=None, buffer=None, + byteoffset=0, bytestride=None, byteorder=_sys.byteorder, + aligned=1, real=None, imag=None): + + type = _nt.getType(type) + dtype = N.dtype(type._dtype) + if byteorder in ['little', 'big']: + if byteorder is not _sys.byteorder: + dtype = dtype.newbyteorder() + else: + raise ValueError("byteorder must be 'little' or 'big'") + + if buffer is None: + self = ndarray.__new__(klass, shape, dtype) + else: + self = ndarray.__new__(klass, shape, dtype, buffer=buffer, + offset=byteoffset, strides=bytestride) + + self._type = type + + if real is not None: + self.real = real + + if imag is not None: + self.imag = imag + + self._byteorder = byteorder + + return self + + def argmax(self, axis=-1): + return ndarray.argmax(self, axis) + + def argmin(self, axis=-1): + return ndarray.argmax(self, axis) + + def argsort(self, axis=-1, kind='quicksort'): + return ndarray.argmax(self, axis, kind) + + def astype(self, type=None): + return self.astype(_getdtype(type)) + + def byteswap(self): + ndarray.byteswap(self, True) + + def byteswapped(self): + return ndarray.byteswap(self, False) + + def getdtypechar(self): + return self.dtype.char + + def getimag(self): + return self.imag + + getimaginary = getimag + + imaginary = property(getimaginary, None, "") + + def getreal(self): + return self.real + + def is_c_array(self): + return self.dtype.isnative and self.flags.carray + + def is_f_array(self): + return self.dtype.isnative and self.flags.farray + + def is_fortran_contiguous(self): + return self.flags.contiguous + + def new(self, type=None): + if type is not None: + dtype = _getdtype(type) + return N.empty(self.shape, dtype) + else: + return N.empty_like(self) + + def setimag(self, value): + self.imag = value + + setimaginary = setimag + + def setreal(self, value): + self.real = value + + def sinfo(self): + self.info() + + def sort(self, axis=-1, kind='quicksort'): + ndarray.sort(self, axis, kind) + + def spacesaver(self): + return False + + def stddev(self): + return self.std() + + def sum(self, type=None): + dtype = _getdtype(type) + return ndarray.sum(self, dtype=dtype) + + def togglebyteorder(self): + self.dtype = self.dtype.newbyteorder() + + def type(self): + return self._type + + def typecode(self): + return _numtypecode[self.dtype.char] + + dtypechar = property(getdtypechar, None, "") + + def info(self): + print "class: ", self.__class__ + print "shape: ", self.shape + print "strides: ", self.strides + print "byteoffset: 0" + print "bytestride: ", self.strides[0] + print "itemsize: ", self.itemsize + print "aligned: ", self.flags.isaligned + print "contiguous: ", self.flags.contiguous + print "buffer: ", self.data + print "data pointer:", self._as_paramater_ + print "byteorder: ", self._byteorder + print "byteswap: ", not self.dtype.isnative Added: trunk/numpy/numarray/numerictypes.py =================================================================== --- trunk/numpy/numarray/numerictypes.py 2006-08-01 20:23:15 UTC (rev 2942) +++ trunk/numpy/numarray/numerictypes.py 2006-08-02 16:37:59 UTC (rev 2943) @@ -0,0 +1,508 @@ +"""numerictypes: Define the numeric type objects + +This module is designed so 'from numerictypes import *' is safe. +Exported symbols include: + + Dictionary with all registered number types (including aliases): + typeDict + + Numeric type objects: + Bool + Int8 Int16 Int32 Int64 + UInt8 UInt16 UInt32 UInt64 + Float32 Double64 + Complex32 Complex64 + + Numeric type classes: + NumericType + BooleanType + SignedType + UnsignedType + IntegralType + SignedIntegralType + UnsignedIntegralType + FloatingType + ComplexType + +$Id: numerictypes.py,v 1.55 2005/12/01 16:22:03 jaytmiller Exp $ +""" + +MAX_ALIGN = 8 +MAX_INT_SIZE = 8 + +import numpy +LP64 = numpy.intp(0).itemsize == 8 + +HasUInt64 = 0 +try: + numpy.int64(0) +except: + HasUInt64 = 0 + +#from typeconv import typeConverters as _typeConverters +#import numinclude +#from _numerictype import _numerictype, typeDict +import types as _types +import copy as _copy +import sys as _sys + +# Enumeration of numarray type codes +typeDict = {} + +_tAny = 0 +_tBool = 1 +_tInt8 = 2 +_tUInt8 = 3 +_tInt16 = 4 +_tUInt16 = 5 +_tInt32 = 6 +_tUInt32 = 7 +_tInt64 = 8 +_tUInt64 = 9 +_tFloat32 = 10 +_tFloat64 = 11 +_tComplex32 = 12 +_tComplex64 = 13 +_tObject = 14 + +def IsType(rep): + """Determines whether the given object or string, 'rep', represents + a numarray type.""" + return isinstance(rep, NumericType) or typeDict.has_key(rep) + +def _register(name, type, force=0): + """Register the type object. Raise an exception if it is already registered + unless force is true. + """ + if typeDict.has_key(name) and not force: + raise ValueError("Type %s has already been registered" % name) + typeDict[name] = type + return type + + +class NumericType(object): + """Numeric type class + + Used both as a type identification and the repository of + characteristics and conversion functions. + """ + def __new__(type, name, bytes, default, typeno): + """__new__() implements a 'quasi-singleton pattern because attempts + to create duplicate types return the first created instance of that + particular type parameterization, i.e. the second time you try to + create "Int32", you get the original Int32, not a new one. + """ + if typeDict.has_key(name): + self = typeDict[name] + if self.bytes != bytes or self.default != default or \ + self.typeno != typeno: + raise ValueError("Redeclaration of existing NumericType "\ + "with different parameters.") + return self + else: + self = object.__new__(type) + self.name = "no name" + self.bytes = None + self.default = None + self.typeno = -1 + return self + + def __init__(self, name, bytes, default, typeno): + if not isinstance(name, str): + raise TypeError("name must be a string") + self.name = name + self.bytes = bytes + self.default = default + self.typeno = typeno + self._conv = None + _register(self.name, self) + + def __getnewargs__(self): + """support the pickling protocol.""" + return (self.name, self.bytes, self.default, self.typeno) + + def __getstate__(self): + """support pickling protocol... no __setstate__ required.""" + False + +class BooleanType(NumericType): + pass + +class SignedType: + """Marker class used for signed type check""" + pass + +class UnsignedType: + """Marker class used for unsigned type check""" + pass + +class IntegralType(NumericType): + pass + +class SignedIntegralType(IntegralType, SignedType): + pass + +class UnsignedIntegralType(IntegralType, UnsignedType): + pass + +class FloatingType(NumericType): + pass + +class ComplexType(NumericType): + pass + +class AnyType(NumericType): + pass + +class ObjectType(NumericType): + pass + +# C-API Type Any + +Any = AnyType("Any", None, None, _tAny) + +Object = ObjectType("Object", None, None, _tObject) + +# Numeric Types: + +Bool = BooleanType("Bool", 1, 0, _tBool) +Int8 = SignedIntegralType( "Int8", 1, 0, _tInt8) +Int16 = SignedIntegralType("Int16", 2, 0, _tInt16) +Int32 = SignedIntegralType("Int32", 4, 0, _tInt32) +Int64 = SignedIntegralType("Int64", 8, 0, _tInt64) + +Float32 = FloatingType("Float32", 4, 0.0, _tFloat32) +Float64 = FloatingType("Float64", 8, 0.0, _tFloat64) + +UInt8 = UnsignedIntegralType( "UInt8", 1, 0, _tUInt8) +UInt16 = UnsignedIntegralType("UInt16", 2, 0, _tUInt16) +UInt32 = UnsignedIntegralType("UInt32", 4, 0, _tUInt32) +UInt64 = UnsignedIntegralType("UInt64", 8, 0, _tUInt64) + +Complex32 = ComplexType("Complex32", 8, complex(0.0), _tComplex32) +Complex64 = ComplexType("Complex64", 16, complex(0.0), _tComplex64) + +# Aliases + +Byte = _register("Byte", Int8) +Short = _register("Short", Int16) +Int = _register("Int", Int32) +if LP64: + Long = _register("Long", Int64) + if HasUInt64: + _register("ULong", UInt64) + MaybeLong = _register("MaybeLong", Int64) +else: + Long = _register("Long", Int32) + _register("ULong", UInt32) + MaybeLong = _register("MaybeLong", Int32) + + +_register("UByte", UInt8) +_register("UShort", UInt16) +_register("UInt", UInt32) +Float = _register("Float", Float64) +Complex = _register("Complex", Complex64) + +# short forms + +_register("b1", Bool) +_register("u1", UInt8) +_register("u2", UInt16) +_register("u4", UInt32) +_register("i1", Int8) +_register("i2", Int16) +_register("i4", Int32) + +_register("i8", Int64) +if HasUInt64: + _register("u8", UInt64) + +_register("f4", Float32) +_register("f8", Float64) +_register("c8", Complex32) +_register("c16", Complex64) + +# NumPy forms + +_register("1", Int8) +_register("B", Bool) +_register("c", Int8) +_register("b", UInt8) +_register("s", Int16) +_register("w", UInt16) +_register("i", Int32) +_register("N", Int64) +_register("u", UInt32) +_register("U", UInt64) + +if LP64: + _register("l", Int64) +else: + _register("l", Int32) + +_register("d", Float64) +_register("f", Float32) +_register("D", Complex64) +_register("F", Complex32) + +# scipy.base forms + +def _scipy_alias(scipy_type, numarray_type): + _register(scipy_type, eval(numarray_type)) + globals()[scipy_type] = globals()[numarray_type] + +_scipy_alias("bool_", "Bool") +_scipy_alias("bool8", "Bool") +_scipy_alias("int8", "Int8") +_scipy_alias("uint8", "UInt8") +_scipy_alias("int16", "Int16") +_scipy_alias("uint16", "UInt16") +_scipy_alias("int32", "Int32") +_scipy_alias("uint32", "UInt32") +_scipy_alias("int64", "Int64") +_scipy_alias("uint64", "UInt64") + +_scipy_alias("float64", "Float64") +_scipy_alias("float32", "Float32") +_scipy_alias("complex128", "Complex64") +_scipy_alias("complex64", "Complex32") + +# The rest is used by numeric modules to determine conversions + +# Ranking of types from lowest to highest (sorta) +if not HasUInt64: + genericTypeRank = ['Bool','Int8','UInt8','Int16','UInt16', + 'Int32', 'UInt32', 'Int64', + 'Float32','Float64', 'Complex32', 'Complex64', 'Object'] +else: + genericTypeRank = ['Bool','Int8','UInt8','Int16','UInt16', + 'Int32', 'UInt32', 'Int64', 'UInt64', + 'Float32','Float64', 'Complex32', 'Complex64', 'Object'] + +if _sys.version_info >= (2,3,0): + pythonTypeRank = [ bool, int, long, float, complex ] +else: + pythonTypeRank = [ int, long, float, complex ] + +# The next line is not platform independent XXX Needs to be generalized +if not LP64: + pythonTypeMap = { + int:("Int32","int"), + long:("Int64","int"), + float:("Float64","float"), + complex:("Complex64","complex")} + + scalarTypeMap = { + int:"Int32", + long:"Int64", + float:"Float64", + complex:"Complex64"} +else: + pythonTypeMap = { + int:("Int64","int"), + long:("Int64","int"), + float:("Float64","float"), + complex:("Complex64","complex")} + + scalarTypeMap = { + int:"Int64", + long:"Int64", + float:"Float64", + complex:"Complex64"} + +if _sys.version_info >= (2,3,0): + pythonTypeMap.update({bool:("Bool","bool") }) + scalarTypeMap.update({bool:"Bool"}) + +# Generate coercion matrix + +def _initGenericCoercions(): + global genericCoercions + genericCoercions = {} + + # vector with ... + for ntype1 in genericTypeRank: + nt1 = typeDict[ntype1] + rank1 = genericTypeRank.index(ntype1) + ntypesize1, inttype1, signedtype1 = nt1.bytes, \ + isinstance(nt1, IntegralType), isinstance(nt1, SignedIntegralType) + for ntype2 in genericTypeRank: + # vector + nt2 = typeDict[ntype2] + ntypesize2, inttype2, signedtype2 = nt2.bytes, \ + isinstance(nt2, IntegralType), isinstance(nt2, SignedIntegralType) + rank2 = genericTypeRank.index(ntype2) + if (signedtype1 != signedtype2) and inttype1 and inttype2: + # mixing of signed and unsigned ints is a special case + # If unsigned same size or larger, final size needs to be bigger + # if possible + if signedtype1: + if ntypesize2 >= ntypesize1: + size = min(2*ntypesize2, MAX_INT_SIZE) + else: + size = ntypesize1 + else: + if ntypesize1 >= ntypesize2: + size = min(2*ntypesize1, MAX_INT_SIZE) + else: + size = ntypesize2 + outtype = "Int"+str(8*size) + else: + if rank1 >= rank2: + outtype = ntype1 + else: + outtype = ntype2 + genericCoercions[(ntype1, ntype2)] = outtype + + for ntype2 in pythonTypeRank: + # scalar + mapto, kind = pythonTypeMap[ntype2] + if ((inttype1 and kind=="int") or (not inttype1 and kind=="float")): + # both are of the same "kind" thus vector type dominates + outtype = ntype1 + else: + rank2 = genericTypeRank.index(mapto) + if rank1 >= rank2: + outtype = ntype1 + else: + outtype = mapto + genericCoercions[(ntype1, ntype2)] = outtype + genericCoercions[(ntype2, ntype1)] = outtype + + # scalar-scalar + for ntype1 in pythonTypeRank: + maptype1 = scalarTypeMap[ntype1] + genericCoercions[(ntype1,)] = maptype1 + for ntype2 in pythonTypeRank: + maptype2 = scalarTypeMap[ntype2] + genericCoercions[(ntype1, ntype2)] = genericCoercions[(maptype1, maptype2)] + + # Special cases more easily dealt with outside of the loop + genericCoercions[("Complex32", "Float64")] = "Complex64" + genericCoercions[("Float64", "Complex32")] = "Complex64" + genericCoercions[("Complex32", "Int64")] = "Complex64" + genericCoercions[("Int64", "Complex32")] = "Complex64" + genericCoercions[("Complex32", "UInt64")] = "Complex64" + genericCoercions[("UInt64", "Complex32")] = "Complex64" + + genericCoercions[("Int64","Float32")] = "Float64" + genericCoercions[("Float32", "Int64")] = "Float64" + genericCoercions[("UInt64","Float32")] = "Float64" + genericCoercions[("Float32", "UInt64")] = "Float64" + + genericCoercions[(float, "Bool")] = "Float64" + genericCoercions[("Bool", float)] = "Float64" + + genericCoercions[(float,float,float)] = "Float64" # for scipy.special + genericCoercions[(int,int,float)] = "Float64" # for scipy.special + +_initGenericCoercions() + +# If complex is subclassed, the following may not be necessary +genericPromotionExclusions = { + 'Bool': (), + 'Int8': (), + 'Int16': (), + 'Int32': ('Float32','Complex32'), + 'UInt8': (), + 'UInt16': (), + 'UInt32': ('Float32','Complex32'), + 'Int64' : ('Float32','Complex32'), + 'UInt64' : ('Float32','Complex32'), + 'Float32': (), + 'Float64': ('Complex32',), + 'Complex32':(), + 'Complex64':() +} # e.g., don't allow promotion from Float64 to Complex32 or Int64 to Float32 + +# Numeric typecodes +typecodes = {'Integer': '1silN', + 'UnsignedInteger': 'bBwuU', + 'Float': 'fd', + 'Character': 'c', + 'Complex': 'FD' } + +if HasUInt64: + _MaximumType = { + Bool : UInt64, + + Int8 : Int64, + Int16 : Int64, + Int32 : Int64, + Int64 : Int64, + + UInt8 : UInt64, + UInt16 : UInt64, + UInt32 : UInt64, + UInt8 : UInt64, + + Float32 : Float64, + Float64 : Float64, + + Complex32 : Complex64, + Complex64 : Complex64 + } +else: + _MaximumType = { + Bool : Int64, + + Int8 : Int64, + Int16 : Int64, + Int32 : Int64, + Int64 : Int64, + + UInt8 : Int64, + UInt16 : Int64, + UInt32 : Int64, + UInt8 : Int64, + + Float32 : Float64, + Float64 : Float64, + + Complex32 : Complex64, + Complex64 : Complex64 + } + +def MaximumType(t): + """returns the type of highest precision of the same general kind as 't'""" + return _MaximumType[t] + + +def getType(type): + """Return the numeric type object for type + + type may be the name of a type object or the actual object + """ + if isinstance(type, NumericType): + return type + try: + return typeDict[type] + except KeyError: + raise TypeError("Not a numeric type") + +if _sys.version_info >= (2,3): + scalarTypes = (bool,int,long,float,complex) +else: + scalarTypes = (int,long,float,complex) + +_scipy_dtypechar = { + Int8 : 'b', + UInt8 : 'B', + Int16 : 'h', + UInt16 : 'H', + Int32 : 'i', + UInt32 : 'I', + Int64 : 'q', + UInt64 : 'Q', + Float32 : 'f', + Float64 : 'd', + Complex32 : 'F', # Note the switchup here: + Complex64 : 'D' # numarray.Complex32 == scipy.complex64, etc. + } + +_scipy_dtypechar_inverse = {} +for key,value in _scipy_dtypechar.items(): + _scipy_dtypechar_inverse[value] = key + + From numpy-svn at scipy.org Wed Aug 2 13:30:50 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 2 Aug 2006 12:30:50 -0500 (CDT) Subject: [Numpy-svn] r2944 - trunk/numpy/core/src Message-ID: <20060802173050.CC87439C0A1@new.scipy.org> Author: oliphant Date: 2006-08-02 12:30:48 -0500 (Wed, 02 Aug 2006) New Revision: 2944 Modified: trunk/numpy/core/src/arrayobject.c Log: Make it so that .T is *always* .transpose() Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-02 16:37:59 UTC (rev 2943) +++ trunk/numpy/core/src/arrayobject.c 2006-08-02 17:30:48 UTC (rev 2944) @@ -6329,10 +6329,6 @@ static PyObject * array_transpose_get(PyArrayObject *self) { - if (self->nd < 2) { - Py_INCREF(self); - return (PyObject *)self; - } return PyArray_Transpose(self, NULL); } From numpy-svn at scipy.org Wed Aug 2 16:44:50 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 2 Aug 2006 15:44:50 -0500 (CDT) Subject: [Numpy-svn] r2945 - in trunk/numpy/core: . tests Message-ID: <20060802204450.B50A339C0A1@new.scipy.org> Author: stefan Date: 2006-08-02 15:44:43 -0500 (Wed, 02 Aug 2006) New Revision: 2945 Modified: trunk/numpy/core/defchararray.py trunk/numpy/core/tests/test_regression.py Log: Fix rstrip for character arrays (ticket #222). Modified: trunk/numpy/core/defchararray.py =================================================================== --- trunk/numpy/core/defchararray.py 2006-08-02 17:30:48 UTC (rev 2944) +++ trunk/numpy/core/defchararray.py 2006-08-02 20:44:43 UTC (rev 2945) @@ -135,14 +135,13 @@ for k, val in enumerate(myiter): newval = [] for chk in val[1:]: - if chk.dtype is object_ and chk.item() is None: + if not chk or (chk.dtype is object_ and chk.item() is None): break newval.append(chk) newitem = getattr(val[0],name)(*newval) maxsize = max(len(newitem), maxsize) res[k] = newitem newarr = chararray(myiter.shape, maxsize, self.dtype is unicode_) - print res, maxsize newarr[:] = res return newarr Modified: trunk/numpy/core/tests/test_regression.py =================================================================== --- trunk/numpy/core/tests/test_regression.py 2006-08-02 17:30:48 UTC (rev 2944) +++ trunk/numpy/core/tests/test_regression.py 2006-08-02 20:44:43 UTC (rev 2945) @@ -331,6 +331,13 @@ def check_unique_zero_sized(self,level=rlevel): """Ticket #205""" assert_array_equal([], N.unique(N.array([]))) + + def check_chararray_rstrip(self,level=rlevel): + """Ticket #222""" + x = N.chararray((1,),5) + x[0] = 'a ' + x = x.rstrip() + assert_equal(x[0], 'a') if __name__ == "__main__": NumpyTest().run() From numpy-svn at scipy.org Wed Aug 2 22:42:42 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 2 Aug 2006 21:42:42 -0500 (CDT) Subject: [Numpy-svn] r2946 - in branches/distutils-revamp: . command fcompiler Message-ID: <20060803024242.5A44339C061@new.scipy.org> Author: cookedm Date: 2006-08-02 21:42:25 -0500 (Wed, 02 Aug 2006) New Revision: 2946 Added: branches/distutils-revamp/environment.py Modified: branches/distutils-revamp/ccompiler.py branches/distutils-revamp/command/build_clib.py branches/distutils-revamp/command/build_ext.py branches/distutils-revamp/command/config.py branches/distutils-revamp/command/config_compiler.py branches/distutils-revamp/exec_command.py branches/distutils-revamp/fcompiler/__init__.py branches/distutils-revamp/fcompiler/absoft.py branches/distutils-revamp/fcompiler/compaq.py branches/distutils-revamp/fcompiler/g95.py branches/distutils-revamp/fcompiler/gnu.py branches/distutils-revamp/fcompiler/hpux.py branches/distutils-revamp/fcompiler/ibm.py branches/distutils-revamp/fcompiler/intel.py branches/distutils-revamp/fcompiler/lahey.py branches/distutils-revamp/fcompiler/mips.py branches/distutils-revamp/fcompiler/nag.py branches/distutils-revamp/fcompiler/none.py branches/distutils-revamp/fcompiler/pg.py branches/distutils-revamp/fcompiler/sun.py branches/distutils-revamp/fcompiler/vast.py branches/distutils-revamp/intelccompiler.py branches/distutils-revamp/system_info.py Log: [distutils-revamp] Rework building of extensions using Fortran. * less stuff done in Fortran compiler modules at import time * list of available compilers built up from modules in numpy.distutils.fcompiler * finding executables centralized in one place and made sane. For instance, setting the Fortran 77 or 90 compilers will also make the right compiler used for the version command and the linker. * environment configuration for FCompiler put into one place. The environment module takes care of environment variables and distutils configs, and the FCompiler class has everything that's configurable grouped in one place. Much easier to tell how to customize it now. * fcompiler only set in config_fc * build_ext implies build_clib * some other cleanups There's still some rough edges here. Modified: branches/distutils-revamp/ccompiler.py =================================================================== --- branches/distutils-revamp/ccompiler.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/ccompiler.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -245,6 +245,8 @@ version_cmd = self.version_cmd except AttributeError: return None + if not version_cmd or not version_cmd[0]: + return None cmd = ' '.join(version_cmd) try: matcher = self.version_match @@ -264,9 +266,7 @@ version = None if status in ok_status: version = matcher(output) - if not version: - log.warn("Couldn't match compiler version for %r" % (output,)) - else: + if version: version = LooseVersion(version) self.version = version return version Modified: branches/distutils-revamp/command/build_clib.py =================================================================== --- branches/distutils-revamp/command/build_clib.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/command/build_clib.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -21,13 +21,11 @@ def initialize_options(self): old_build_clib.initialize_options(self) self.fcompiler = None - return def finalize_options(self): old_build_clib.finalize_options(self) self.set_undefined_options('build_ext', ('fcompiler', 'fcompiler')) - return def have_f_sources(self): for (lib_name, build_info) in self.libraries: @@ -65,13 +63,6 @@ self.compiler.show_customization() if self.have_f_sources(): - from numpy.distutils.fcompiler import new_fcompiler - self.fcompiler = new_fcompiler(compiler=self.fcompiler, - verbose=self.verbose, - dry_run=self.dry_run, - force=self.force) - self.fcompiler.customize(self.distribution) - libraries = self.libraries self.libraries = None self.fcompiler.customize_cmd(self) @@ -80,7 +71,6 @@ self.fcompiler.show_customization() self.build_libraries(self.libraries) - return def get_source_files(self): self.check_library_list(self.libraries) @@ -91,7 +81,6 @@ def build_libraries(self, libraries): - for (lib_name, build_info) in libraries: # default compilers compiler = self.compiler @@ -105,8 +94,6 @@ "a list of source filenames") % lib_name sources = list(sources) - - lib_file = compiler.library_filename(lib_name, output_dir=self.build_clib) @@ -192,5 +179,3 @@ clib_libraries.extend(binfo[1].get('libraries',[])) if clib_libraries: build_info['libraries'] = clib_libraries - - return Modified: branches/distutils-revamp/command/build_ext.py =================================================================== --- branches/distutils-revamp/command/build_ext.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/command/build_ext.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -31,7 +31,6 @@ def initialize_options(self): old_build_ext.initialize_options(self) self.fcompiler = None - return def finalize_options(self): incl_dirs = self.include_dirs @@ -40,18 +39,19 @@ self.include_dirs.extend(self.distribution.include_dirs or []) self.set_undefined_options('config_fc', ('fcompiler', 'fcompiler')) - return def run(self): if not self.extensions: return # Make sure that extension sources are complete. - for ext in self.extensions: - if not all_strings(ext.sources): - self.run_command('build_src') + self.run_command('build_src') +# for ext in self.extensions: +# if not all_strings(ext.sources): +# self.run_command('build_src') if self.distribution.has_c_libraries(): + self.run_command('build_clib') build_clib = self.get_finalized_command('build_clib') self.library_dirs.append(build_clib.build_clib) else: @@ -64,25 +64,25 @@ # Determine if Fortran compiler is needed. if build_clib and build_clib.fcompiler is not None: - need_f_compiler = 1 + need_f_compiler = True else: - need_f_compiler = 0 + need_f_compiler = False for ext in self.extensions: if has_f_sources(ext.sources): - need_f_compiler = 1 + need_f_compiler = True break if getattr(ext,'language','c') in ['f77','f90']: - need_f_compiler = 1 + need_f_compiler = True break # Determine if C++ compiler is needed. need_cxx_compiler = 0 for ext in self.extensions: if has_cxx_sources(ext.sources): - need_cxx_compiler = 1 + need_cxx_compiler = True break - if getattr(ext,'language','c')=='c++': - need_cxx_compiler = 1 + if getattr(ext,'language','c') == 'c++': + need_cxx_compiler = True break from distutils.ccompiler import new_compiler @@ -96,22 +96,16 @@ # Initialize Fortran/C++ compilers if needed. if need_f_compiler: - from numpy.distutils.fcompiler import new_fcompiler - self.fcompiler = new_fcompiler(compiler=self.fcompiler, - verbose=self.verbose, - dry_run=self.dry_run, - force=self.force) if self.fcompiler.get_version(): - self.fcompiler.customize(self.distribution) self.fcompiler.customize_cmd(self) self.fcompiler.show_customization() else: - self.warn('fcompiler=%s is not available.' % (self.fcompiler.compiler_type)) + self.warn('fcompiler=%s is not available.' % ( + self.fcompiler.compiler_type,)) self.fcompiler = None # Build extensions self.build_extensions() - return def swig_sources(self, sources): # Do nothing. Swig sources have beed handled in build_src command. Modified: branches/distutils-revamp/command/config.py =================================================================== --- branches/distutils-revamp/command/config.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/command/config.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -21,15 +21,16 @@ def initialize_options(self): self.fcompiler = None old_config.initialize_options(self) - return def finalize_options(self): old_config.finalize_options(self) f = self.distribution.get_command_obj('config_fc') self.set_undefined_options('config_fc', ('fcompiler', 'fcompiler')) - return + def run(self): + self._check_compiler() + def _check_compiler (self): old_config._check_compiler(self) from numpy.distutils.fcompiler import FCompiler, new_fcompiler @@ -39,7 +40,6 @@ self.fcompiler.customize(self.distribution) self.fcompiler.customize_cmd(self) self.fcompiler.show_customization() - return def _wrap_method(self,mth,lang,args): from distutils.ccompiler import CompileError Modified: branches/distutils-revamp/command/config_compiler.py =================================================================== --- branches/distutils-revamp/command/config_compiler.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/command/config_compiler.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -1,6 +1,9 @@ import sys +import distutils.core from distutils.core import Command +from distutils import log +from numpy.distutils.fcompiler import show_fcompilers, new_fcompiler #XXX: Implement confic_cc for enhancing C/C++ compiler options. #XXX: Linker flags @@ -10,9 +13,10 @@ if _cache: return _cache.append(1) - from numpy.distutils.fcompiler import show_fcompilers from numpy.distutils.core import get_distribution - show_fcompilers(get_distribution()) + dist = get_distribution() + print dist.verbose + show_fcompilers(dist) class config_fc(Command): """ Distutils command to hold user specified options @@ -52,12 +56,13 @@ self.debug = None self.noopt = None self.noarch = None - return def finalize_options(self): - # Do nothing. - return + fc = new_fcompiler(compiler=self.fcompiler, + verbose=self.distribution.verbose) + fc.customize(self.distribution) + self.fcompiler = fc + log.info('%s (%s)' % (fc.description, fc.get_version())) def run(self): - # Do nothing. - return + pass Added: branches/distutils-revamp/environment.py =================================================================== --- branches/distutils-revamp/environment.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/environment.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -0,0 +1,49 @@ +import os +from distutils.dist import Distribution + +__metaclass__ = type + +class EnvironmentConfig: + def __init__(self, distutils_section='DEFAULT', **kw): + self._distutils_section = distutils_section + self._conf_keys = kw + self._conf = None + self._hook_handler = None + + def __getattr__(self, name): + try: + conf_desc = self._conf_keys[name] + except KeyError: + raise AttributeError(name) + return self._get_var(name, conf_desc) + + def get(self, name, default=None): + try: + conf_desc = self._conf_keys[name] + except KeyError: + return default + var = self._get_var(name, conf_desc) + if var is None: + var = default + return var + + def _get_var(self, name, conf_desc): + hook, envvar, confvar = conf_desc + var = self._hook_handler(name, hook) + if envvar is not None: + var = os.environ.get(envvar, var) + if confvar is not None and self._conf: + var = self._conf.get(confvar, (None, var))[1] + return var + + def clone(self, hook_handler): + ec = self.__class__(distutils_section=self._distutils_section, + **self._conf_keys) + ec._hook_handler = hook_handler + return ec + + def use_distribution(self, dist): + if isinstance(dist, Distribution): + self._conf = dist.get_option_dict(self._distutils_section) + else: + self._conf = dist Modified: branches/distutils-revamp/exec_command.py =================================================================== --- branches/distutils-revamp/exec_command.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/exec_command.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -123,60 +123,48 @@ ############################################################ def find_executable(exe, path=None): - """ Return full path of a executable. + """Return full path of a executable. + + Symbolic links are not followed. """ log.debug('find_executable(%r)' % exe) orig_exe = exe + if path is None: path = os.environ.get('PATH',os.defpath) if os.name=='posix' and sys.version[:3]>'2.1': realpath = os.path.realpath else: realpath = lambda a:a - if exe[0]=='"': + + if exe.startswith('"'): exe = exe[1:-1] - suffices = [''] + + suffixes = [''] if os.name in ['nt','dos','os2']: fn,ext = os.path.splitext(exe) - extra_suffices = ['.exe','.com','.bat'] - if ext.lower() not in extra_suffices: - suffices = extra_suffices + extra_suffixes = ['.exe','.com','.bat'] + if ext.lower() not in extra_suffixes: + suffixes = extra_suffixes + if os.path.isabs(exe): paths = [''] else: - paths = map(os.path.abspath, path.split(os.pathsep)) - if 0 and os.name == 'nt': - new_paths = [] - cygwin_paths = [] - for path in paths: - d,p = os.path.splitdrive(path) - if p.lower().find('cygwin') >= 0: - cygwin_paths.append(path) - else: - new_paths.append(path) - paths = new_paths + cygwin_paths + paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ] + for path in paths: - fn = os.path.join(path,exe) - for s in suffices: + fn = os.path.join(path, exe) + for s in suffixes: f_ext = fn+s if not os.path.islink(f_ext): - # see comment below. f_ext = realpath(f_ext) - if os.path.isfile(f_ext) and os.access(f_ext,os.X_OK): + if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK): log.debug('Found executable %s' % f_ext) return f_ext - if os.path.islink(exe): - # Don't follow symbolic links. E.g. when using colorgcc then - # gcc -> /usr/bin/colorgcc - # g77 -> /usr/bin/colorgcc - pass - else: - exe = realpath(exe) - if not os.path.isfile(exe) or os.access(exe,os.X_OK): - log.warn('Could not locate executable %s' % orig_exe) - return orig_exe - return exe + log.warn('Could not locate executable %s' % orig_exe) + return None + ############################################################ def _preserve_environment( names ): Modified: branches/distutils-revamp/fcompiler/__init__.py =================================================================== --- branches/distutils-revamp/fcompiler/__init__.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/__init__.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -10,7 +10,11 @@ import os import sys import re -from types import StringType,NoneType +try: + set +except NameError: + from sets import Set as set + from distutils.sysconfig import get_config_var from distutils.fancy_getopt import FancyGetopt from distutils.errors import DistutilsModuleError,DistutilsArgError,\ @@ -19,11 +23,16 @@ from numpy.distutils.ccompiler import CCompiler, gen_lib_options from numpy.distutils import log -from numpy.distutils.command.config_compiler import config_fc -from numpy.distutils.core import get_distribution from numpy.distutils.misc_util import is_string, is_sequence +from numpy.distutils.environment import EnvironmentConfig +from numpy.distutils.exec_command import find_executable from distutils.spawn import _nt_quote_args +__metaclass__ = type + +class CompilerNotFound(Exception): + pass + class FCompiler(CCompiler): """ Abstract base class to define the interface that must be implemented by real Fortran compiler classes. @@ -54,8 +63,52 @@ libraries library_dirs """ + # for documentation purposes, these are the environment variables + # used. + # Each configuration descripition is + # (, , ) + # The hook names are handled by the self._environment_hook method. + distutils_vars = EnvironmentConfig( + noopt = (None, None, 'noopt'), + noarch = (None, None, 'noarch'), + debug = (None, None, 'debug'), + verbose = (None, None, 'verbose'), + ) + command_vars = EnvironmentConfig( + distutils_section='config_fc', + compiler_f77 = ('exe.compiler_f77', 'F77', 'f77exec'), + compiler_f90 = ('exe.compiler_f90', 'F90', 'f90exec'), + compiler_fix = ('exe.compiler_fix', 'F90', 'f90exec'), + version_cmd = ('self.get_version_cmd', None, None), + linker_so = ('self.get_linker_so', 'LDSHARED', None), + linker_exe = ('self.get_linker_exe', 'LD', None), + archiver = (None, 'AR', None), + ranlib = (None, 'RANLIB', None), + ) + flag_vars = EnvironmentConfig( + distutils_section='config_fc', + version = ('flags.version', None, None), + f77 = ('flags.f77', 'F77FLAGS', 'f77flags'), + f90 = ('flags.f90', 'F90FLAGS', 'f90flags'), + free = ('flags.free', 'FREEFLAGS', 'freeflags'), + fix = ('flags.fix', None, None), + opt = ('flags.opt', 'FOPT', 'opt'), + opt_f77 = ('flags.opt_f77', None, None), + opt_f90 = ('flags.opt_f90', None, None), + arch = ('flags.arch', 'FARCH', 'arch'), + arch_f77 = ('flags.arch_f77', None, None), + arch_f90 = ('flags.arch_f90', None, None), + debug = ('flags.debug', 'FDEBUG', None, None), + debug_f77 = ('flags.debug_f77', None, None), + debug_f90 = ('flags.debug_f90', None, None), + flags = ('self.get_flags', 'FFLAGS', None), + linker_so = ('flags.linker_so', 'LDFLAGS', None), + linker_exe = ('flags.linker_exe', 'LDFLAGS', None), + ar = ('flags.ar', 'ARFLAGS', None), + ) + language_map = {'.f':'f77', '.for':'f77', '.F':'f77', # XXX: needs preprocessor @@ -69,14 +122,15 @@ version_pattern = None + possible_executables = [] executables = { - 'version_cmd' : ["f77","-v"], + 'version_cmd' : ["f77", "-v"], 'compiler_f77' : ["f77"], 'compiler_f90' : ["f90"], - 'compiler_fix' : ["f90","-fixed"], - 'linker_so' : ["f90","-shared"], + 'compiler_fix' : ["f90", "-fixed"], + 'linker_so' : ["f90", "-shared"], 'linker_exe' : ["f90"], - 'archiver' : ["ar","-cr"], + 'archiver' : ["ar", "-cr"], 'ranlib' : None, } @@ -105,64 +159,111 @@ shared_lib_format = "%s%s" exe_extension = "" + def __init__(self, *args, **kw): + CCompiler.__init__(self, *args, **kw) + self.distutils_vars = self.distutils_vars.clone(self._environment_hook) + self.command_vars = self.command_vars.clone(self._environment_hook) + self.flag_vars = self.flag_vars.clone(self._environment_hook) + self.executables = self.executables.copy() + for e in ['version_cmd', 'compiler_f77', 'compiler_f90', + 'compiler_fix', 'linker_so', 'linker_exe', 'archiver', + 'ranlib']: + if e not in self.executables: + self.executables[e] = None + ###################################################################### ## Methods that subclasses may redefine. But don't call these methods! ## They are private to FCompiler class and may return unexpected ## results if used elsewhere. So, you have been warned.. + def find_executables(self): + """Go through the self.executables dictionary, and attempt to + find and assign appropiate executables. + + Executable names are looked for in the environment (environment + variables, the distutils.cfg, and command line), the 0th-element of + the command list, and the self.possible_executables list. + + Also, if the 0th element is "" or "", the Fortran 77 + or the Fortran 90 compiler executable is used, unless overridden + by an environment setting. + """ + exe_cache = {} + def cached_find_executable(exe): + if exe in exe_cache: + return exe_cache[exe] + fc_exe = find_executable(exe) + exe_cache[exe] = fc_exe + return fc_exe + def set_exe(exe_key, f77=None, f90=None): + cmd = self.executables.get(exe_key, None) + if not cmd: + return None + # Note that we get cmd[0] here if the environment doesn't + # have anything set + exe_from_environ = getattr(self.command_vars, exe_key) + if not exe_from_environ: + possibles = [f90, f77] + self.possible_executables + else: + possibles = [exe_from_environ] + self.possible_executables + + seen = set() + unique_possibles = [] + for e in possibles: + if e == '': + e = f77 + elif e == '': + e = f90 + if not e or e in seen: + continue + seen.add(e) + unique_possibles.append(e) + + for exe in unique_possibles: + fc_exe = cached_find_executable(exe) + if fc_exe: + cmd[0] = fc_exe + return fc_exe + return None + + f77 = set_exe('compiler_f77') + if not f77: + raise CompilerNotFound('f77') + f90 = set_exe('compiler_f90') + if not f90: + raise CompilerNotFound('f90') + set_exe('compiler_fix', f90=f90) + + set_exe('linker_so', f77=f77, f90=f90) + set_exe('linker_exe', f77=f77, f90=f90) + set_exe('version_cmd', f77=f77, f90=f90) + + set_exe('archiver') + set_exe('ranlib') + def get_version_cmd(self): - """ Compiler command to print out version information. """ - f77 = self.executables['compiler_f77'] - if f77 is not None: - f77 = f77[0] + """Compiler command to print out version information.""" cmd = self.executables['version_cmd'] - if cmd is not None: - cmd = cmd[0] - if cmd==f77: - cmd = self.compiler_f77[0] - else: - f90 = self.executables['compiler_f90'] - if f90 is not None: - f90 = f90[0] - if cmd==f90: - cmd = self.compiler_f90[0] - return cmd + if cmd: + return cmd[0] + else: + return None def get_linker_so(self): - """ Linker command to build shared libraries. """ - f77 = self.executables['compiler_f77'] - if f77 is not None: - f77 = f77[0] - ln = self.executables['linker_so'] - if ln is not None: - ln = ln[0] - if ln==f77: - ln = self.compiler_f77[0] - else: - f90 = self.executables['compiler_f90'] - if f90 is not None: - f90 = f90[0] - if ln==f90: - ln = self.compiler_f90[0] - return ln + """Linker command to build shared libraries.""" + cmd = self.executables['linker_so'] + if cmd: + return cmd[0] + else: + return None def get_linker_exe(self): - """ Linker command to build shared libraries. """ - f77 = self.executables['compiler_f77'] - if f77 is not None: - f77 = f77[0] - ln = self.executables.get('linker_exe') - if ln is not None: - ln = ln[0] - if ln==f77: - ln = self.compiler_f77[0] - else: - f90 = self.executables['compiler_f90'] - if f90 is not None: - f90 = f90[0] - if ln==f90: - ln = self.compiler_f90[0] - return ln + """Linker command to build shared libraries.""" + cmd = self.executables['linker_exe'] + if cmd: + return cmd[0] + else: + return None def get_flags(self): """ List of flags common to all compiler types. """ @@ -242,86 +343,66 @@ instance is needed for (iii) and (iv). """ log.info('customize %s' % (self.__class__.__name__)) - from distutils.dist import Distribution - if dist is None: - # These hooks are for testing only! - dist = Distribution() -# dist.script_name = os.path.basename(sys.argv[0]) -# dist.script_args = ['config_fc'] + sys.argv[1:] -# dist.cmdclass['config_fc'] = config_fc -# dist.parse_config_files() -# dist.parse_command_line() - if isinstance(dist, Distribution): - conf = dist.get_option_dict('config_fc') - else: - assert isinstance(dist,dict) - conf = dist - noopt = conf.get('noopt',[None,0])[1] + self.distutils_vars.use_distribution(dist) + self.command_vars.use_distribution(dist) + self.flag_vars.use_distribution(dist) + + self.find_executables() + + noopt = self.distutils_vars.get('noopt', False) if 0: # change to `if 1:` when making release. # Don't use architecture dependent compiler flags: - noarch = 1 + noarch = True else: - noarch = conf.get('noarch',[None,noopt])[1] - debug = conf.get('debug',[None,0])[1] + noarch = self.distutils_vars.get('noarch', noopt) + debug = self.distutils_vars.get('debug', False) - f77 = self.__get_cmd('compiler_f77','F77',(conf,'f77exec')) - f90 = self.__get_cmd('compiler_f90','F90',(conf,'f90exec')) - # Temporarily setting f77,f90 compilers so that - # version_cmd can use their executables. - if f77: - self.set_executables(compiler_f77=[f77]) - if f90: - self.set_executables(compiler_f90=[f90]) + f77 = self.command_vars.compiler_f77 + f90 = self.command_vars.compiler_f90 # Must set version_cmd before others as self.get_flags* # methods may call self.get_version. - vers_cmd = self.__get_cmd(self.get_version_cmd) + vers_cmd = self.command_vars.version_cmd if vers_cmd: - vflags = self.__get_flags(self.get_flags_version) + vflags = self.flag_vars.version self.set_executables(version_cmd=[vers_cmd]+vflags) if f77: - f77flags = self.__get_flags(self.get_flags_f77,'F77FLAGS', - (conf,'f77flags')) + f77flags = self.flag_vars.f77 if f90: - f90flags = self.__get_flags(self.get_flags_f90,'F90FLAGS', - (conf,'f90flags')) - freeflags = self.__get_flags(self.get_flags_free,'FREEFLAGS', - (conf,'freeflags')) + f90flags = self.flag_vars.f90 + freeflags = self.flag_vars.free # XXX Assuming that free format is default for f90 compiler. - fix = self.__get_cmd('compiler_fix','F90',(conf,'f90exec')) + fix = self.command_vars.compiler_fix if fix: - fixflags = self.__get_flags(self.get_flags_fix) + f90flags + fixflags = self.flag_vars.fix + f90flags - oflags,aflags,dflags = [],[],[] + oflags, aflags, dflags = [], [], [] + def to_list(flags): + if is_string(flags): + return [flags] + return flags + # examine get_flags__ for extra flags + # only add them if the method is different from get_flags_ + def get_flags(tag, flags): + # note that self.flag_vars. calls self.get_flags_() + flags.extend(to_list(getattr(self.flag_vars, tag))) + this_get = getattr(self, 'get_flags_' + tag) + for name, c, flagvar in [('f77', f77, f77flags), + ('f90', f90, f90flags), + ('f90', fix, fixflags)]: + t = '%s_%s' % (tag, name) + if c and this_get is not getattr(self, 'get_flags_' + t): + flagvar.extend(to_list(getattr(self.flag_vars, t))) + return oflags if not noopt: - oflags = self.__get_flags(self.get_flags_opt,'FOPT',(conf,'opt')) - if f77 and self.get_flags_opt is not self.get_flags_opt_f77: - f77flags += self.__get_flags(self.get_flags_opt_f77) - if f90 and self.get_flags_opt is not self.get_flags_opt_f90: - f90flags += self.__get_flags(self.get_flags_opt_f90) - if fix and self.get_flags_opt is not self.get_flags_opt_f90: - fixflags += self.__get_flags(self.get_flags_opt_f90) + get_flags('opt', oflags) if not noarch: - aflags = self.__get_flags(self.get_flags_arch,'FARCH', - (conf,'arch')) - if f77 and self.get_flags_arch is not self.get_flags_arch_f77: - f77flags += self.__get_flags(self.get_flags_arch_f77) - if f90 and self.get_flags_arch is not self.get_flags_arch_f90: - f90flags += self.__get_flags(self.get_flags_arch_f90) - if fix and self.get_flags_arch is not self.get_flags_arch_f90: - fixflags += self.__get_flags(self.get_flags_arch_f90) + get_flags('arch', aflags) if debug: - dflags = self.__get_flags(self.get_flags_debug,'FDEBUG') - if f77 and self.get_flags_debug is not self.get_flags_debug_f77: - f77flags += self.__get_flags(self.get_flags_debug_f77) - if f90 and self.get_flags_debug is not self.get_flags_debug_f90: - f90flags += self.__get_flags(self.get_flags_debug_f90) - if fix and self.get_flags_debug is not self.get_flags_debug_f90: - fixflags += self.__get_flags(self.get_flags_debug_f90) + get_flags('debug', dflags) - fflags = self.__get_flags(self.get_flags,'FFLAGS') \ - + dflags + oflags + aflags + fflags = to_list(self.flag_vars.flags) + dflags + oflags + aflags if f77: self.set_executables(compiler_f77=[f77]+f77flags+fflags) @@ -329,30 +410,31 @@ self.set_executables(compiler_f90=[f90]+freeflags+f90flags+fflags) if fix: self.set_executables(compiler_fix=[fix]+fixflags+fflags) + #XXX: Do we need LDSHARED->SOSHARED, LDFLAGS->SOFLAGS - linker_so = self.__get_cmd(self.get_linker_so,'LDSHARED') + linker_so = self.command_vars.linker_so if linker_so: - linker_so_flags = self.__get_flags(self.get_flags_linker_so,'LDFLAGS') + linker_so_flags = to_list(self.flag_vars.linker_so) self.set_executables(linker_so=[linker_so]+linker_so_flags) - linker_exe = self.__get_cmd(self.get_linker_exe,'LD') + linker_exe = self.command_vars.linker_exe if linker_exe: - linker_exe_flags = self.__get_flags(self.get_flags_linker_exe,'LDFLAGS') + linker_exe_flags = to_list(self.flag_vars.linker_exe) self.set_executables(linker_exe=[linker_exe]+linker_exe_flags) - ar = self.__get_cmd('archiver','AR') + + ar = self.command_vars.archiver if ar: - arflags = self.__get_flags(self.get_flags_ar,'ARFLAGS') + arflags = to_list(self.flag_vars.arflags) self.set_executables(archiver=[ar]+arflags) - ranlib = self.__get_cmd('ranlib','RANLIB') + ranlib = self.command_vars.ranlib if ranlib: self.set_executables(ranlib=[ranlib]) self.set_library_dirs(self.get_library_dirs()) self.set_libraries(self.get_libraries()) - - verbose = conf.get('verbose',[None,0])[1] + verbose = self.distutils_vars.get('verbose', self.verbose) if verbose: self.dump_properties() return @@ -365,7 +447,7 @@ 'object_switch','compile_switch']: if hasattr(self,key): v = getattr(self,key) - props.append((key, None, '= '+`v`)) + props.append((key, None, '= '+repr(v))) props.sort() pretty_printer = FancyGetopt(props) @@ -412,7 +494,8 @@ if os.name == 'nt': compiler = _nt_quote_args(compiler) - command = compiler + cc_args + extra_flags + s_args + o_args + extra_postargs + command = compiler + cc_args + extra_flags + s_args + o_args \ + + extra_postargs display = '%s: %s' % (os.path.basename(compiler[0]) + flavor, src) @@ -495,153 +578,119 @@ log.debug("skipping %s (up-to-date)", output_filename) return - - ## Private methods: - - def __get_cmd(self, command, envvar=None, confvar=None): - if command is None: - var = None - elif is_string(command): - var = self.executables[command] - if var is not None: - var = var[0] + def _environment_hook(self, name, hook_name): + if hook_name is None: + return None + if is_string(hook_name): + if hook_name.startswith('self.'): + hook_name = hook_name[5:] + hook = getattr(self, hook_name) + return hook() + elif hook_name.startswith('exe.'): + hook_name = hook_name[4:] + var = self.executables[hook_name] + if var: + return var[0] + else: + return None + elif hook_name.startswith('flags.'): + hook_name = hook_name[6:] + hook = getattr(self, 'get_flags_' + hook_name) + return hook() else: - var = command() - if envvar is not None: - var = os.environ.get(envvar, var) - if confvar is not None: - var = confvar[0].get(confvar[1], [None,var])[1] - return var + return hook_name() - def __get_flags(self, command, envvar=None, confvar=None): - if command is None: - var = [] - elif is_string(command): - var = self.executables[command][1:] - else: - var = command() - if envvar is not None: - var = os.environ.get(envvar, var) - if confvar is not None: - var = confvar[0].get(confvar[1], [None,var])[1] - if is_string(var): - var = split_quoted(var) - return var - ## class FCompiler -fcompiler_class = {'gnu':('gnu','GnuFCompiler', - "GNU Fortran Compiler"), - 'gnu95':('gnu','Gnu95FCompiler', - "GNU 95 Fortran Compiler"), - 'g95':('g95','G95FCompiler', - "G95 Fortran Compiler"), - 'pg':('pg','PGroupFCompiler', - "Portland Group Fortran Compiler"), - 'absoft':('absoft','AbsoftFCompiler', - "Absoft Corp Fortran Compiler"), - 'mips':('mips','MipsFCompiler', - "MIPSpro Fortran Compiler"), - 'sun':('sun','SunFCompiler', - "Sun|Forte Fortran 95 Compiler"), - 'intel':('intel','IntelFCompiler', - "Intel Fortran Compiler for 32-bit apps"), - 'intelv':('intel','IntelVisualFCompiler', - "Intel Visual Fortran Compiler for 32-bit apps"), - 'intele':('intel','IntelItaniumFCompiler', - "Intel Fortran Compiler for Itanium apps"), - 'intelev':('intel','IntelItaniumVisualFCompiler', - "Intel Visual Fortran Compiler for Itanium apps"), - 'intelem':('intel','IntelEM64TFCompiler', - "Intel Fortran Compiler for EM64T-based apps"), - 'nag':('nag','NAGFCompiler', - "NAGWare Fortran 95 Compiler"), - 'compaq':('compaq','CompaqFCompiler', - "Compaq Fortran Compiler"), - 'compaqv':('compaq','CompaqVisualFCompiler', - "DIGITAL|Compaq Visual Fortran Compiler"), - 'vast':('vast','VastFCompiler', - "Pacific-Sierra Research Fortran 90 Compiler"), - 'hpux':('hpux','HPUXFCompiler', - "HP Fortran 90 Compiler"), - 'lahey':('lahey','LaheyFCompiler', - "Lahey/Fujitsu Fortran 95 Compiler"), - 'ibm':('ibm','IbmFCompiler', - "IBM XL Fortran Compiler"), - 'f':('f','FFCompiler', - "Fortran Company/NAG F Compiler"), - 'none':('none','NoneFCompiler',"Fake Fortran compiler") - } - _default_compilers = ( # Platform mappings - ('win32',('gnu','intelv','absoft','compaqv','intelev','gnu95','g95')), - ('cygwin.*',('gnu','intelv','absoft','compaqv','intelev','gnu95','g95')), - ('linux.*',('gnu','intel','lahey','pg','absoft','nag','vast','compaq', + ('win32', ('gnu','intelv','absoft','compaqv','intelev','gnu95','g95')), + ('cygwin.*', ('gnu','intelv','absoft','compaqv','intelev','gnu95','g95')), + ('linux.*', ('gnu','intel','lahey','pg','absoft','nag','vast','compaq', 'intele','intelem','gnu95','g95')), - ('darwin.*',('nag','absoft','ibm','gnu','gnu95','g95')), - ('sunos.*',('sun','gnu','gnu95','g95')), - ('irix.*',('mips','gnu','gnu95',)), - ('aix.*',('ibm','gnu','gnu95',)), + ('darwin.*', ('nag', 'absoft', 'ibm', 'intel', 'gnu', 'gnu95', 'g95')), + ('sunos.*', ('sun','gnu','gnu95','g95')), + ('irix.*', ('mips','gnu','gnu95',)), + ('aix.*', ('ibm','gnu','gnu95',)), # OS mappings - ('posix',('gnu','gnu95',)), - ('nt',('gnu','gnu95',)), - ('mac',('gnu','gnu95',)), + ('posix', ('gnu','gnu95',)), + ('nt', ('gnu','gnu95',)), + ('mac', ('gnu','gnu95',)), ) -def _find_existing_fcompiler(compilers, osname=None, platform=None): +fcompiler_class = None + +def load_all_fcompiler_classes(): + """Cache all the FCompiler classes found in modules in the + numpy.distutils.fcompiler package. + """ + from glob import glob + global fcompiler_class + if fcompiler_class is not None: + return + pys = os.path.join(os.path.dirname(__file__), '*.py') + fcompiler_class = {} + for fname in glob(pys): + module_name, ext = os.path.splitext(os.path.basename(fname)) + module_name = 'numpy.distutils.fcompiler.' + module_name + __import__ (module_name) + module = sys.modules[module_name] + if hasattr(module, 'compilers'): + for cname in module.compilers: + klass = getattr(module, cname) + fcompiler_class[klass.compiler_type] = (klass.compiler_type, + klass, + klass.description) + +def _find_existing_fcompiler(compiler_types, osname=None, platform=None): + from numpy.distutils.core import get_distribution dist = get_distribution(always=True) - for compiler in compilers: + for compiler_type in compiler_types: v = None try: - c = new_fcompiler(plat=platform, compiler=compiler) + c = new_fcompiler(plat=platform, compiler=compiler_type) c.customize(dist) v = c.get_version() except DistutilsModuleError: pass - except Exception, e: - log.warn(str(e)) + except CompilerNotFound: + pass if v is not None: - return compiler - return + return compiler_type + return None def get_default_fcompiler(osname=None, platform=None): - """ Determine the default Fortran compiler to use for the given platform. """ + """Determine the default Fortran compiler to use for the given platform.""" if osname is None: osname = os.name if platform is None: platform = sys.platform - matching_compilers = [] - for pattern, compiler in _default_compilers: - if re.match(pattern, platform) is not None or \ - re.match(pattern, osname) is not None: - if is_sequence(compiler): - matching_compilers.extend(list(compiler)) - else: - matching_compilers.append(compiler) - if not matching_compilers: - matching_compilers.append('gnu') - compiler = _find_existing_fcompiler(matching_compilers, - osname=osname, - platform=platform) - if compiler is not None: - return compiler - return matching_compilers[0] + matching_compiler_types = [] + for pattern, compiler_type in _default_compilers: + if re.match(pattern, platform) or re.match(pattern, osname): + matching_compiler_types.extend(list(compiler_type)) + if not matching_compiler_types: + matching_compiler_types.append('gnu') + compiler_type = _find_existing_fcompiler(matching_compiler_types, + osname=osname, + platform=platform) + return compiler_type def new_fcompiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): - """ Generate an instance of some FCompiler subclass for the supplied + """Generate an instance of some FCompiler subclass for the supplied platform/compiler combination. """ + load_all_fcompiler_classes() if plat is None: plat = os.name + if compiler is None: + compiler = get_default_fcompiler(plat) try: - if compiler is None: - compiler = get_default_fcompiler(plat) - (module_name, class_name, long_description) = fcompiler_class[compiler] + module_name, klass, long_description = fcompiler_class[compiler] except KeyError: msg = "don't know how to compile Fortran code on platform '%s'" % plat if compiler is not None: @@ -650,29 +699,16 @@ % (','.join(fcompiler_class.keys())) raise DistutilsPlatformError, msg - try: - module_name = 'numpy.distutils.fcompiler.'+module_name - __import__ (module_name) - module = sys.modules[module_name] - klass = vars(module)[class_name] - except ImportError: - raise DistutilsModuleError, \ - "can't compile Fortran code: unable to load module '%s'" % \ - module_name - except KeyError: - raise DistutilsModuleError, \ - ("can't compile Fortran code: unable to find class '%s' " + - "in module '%s'") % (class_name, module_name) - compiler = klass(None, dry_run, force) - log.debug('new_fcompiler returns %s' % (klass)) + compiler = klass(verbose=verbose, dry_run=dry_run, force=force) return compiler def show_fcompilers(dist = None): - """ Print list of available compilers (used by the "--help-fcompiler" + """Print list of available compilers (used by the "--help-fcompiler" option to "config_fc"). """ if dist is None: from distutils.dist import Distribution + from numpy.distutils.command.config_compiler import config_fc dist = Distribution() dist.script_name = os.path.basename(sys.argv[0]) dist.script_args = ['config_fc'] + sys.argv[1:] @@ -683,20 +719,21 @@ compilers = [] compilers_na = [] compilers_ni = [] + if not fcompiler_class: + load_all_fcompiler_classes() + not_available = object() for compiler in fcompiler_class.keys(): - v = 'N/A' + v = not_available try: - c = new_fcompiler(compiler=compiler) + c = new_fcompiler(compiler=compiler, verbose=dist.verbose) c.customize(dist) v = c.get_version() - except DistutilsModuleError: - pass - except Exception, msg: - log.warn(msg) + except (DistutilsModuleError, CompilerNotFound): + v = not_available if v is None: compilers_na.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2])) - elif v=='N/A': + elif v is not_available: compilers_ni.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2])) else: @@ -705,6 +742,7 @@ compilers.sort() compilers_na.sort() + compilers_ni.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("List of available Fortran compilers:") pretty_printer = FancyGetopt(compilers_na) Modified: branches/distutils-revamp/fcompiler/absoft.py =================================================================== --- branches/distutils-revamp/fcompiler/absoft.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/absoft.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -13,9 +13,12 @@ from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file from numpy.distutils.misc_util import cyg2win32 +compilers = ['AbsoftFCompiler'] + class AbsoftFCompiler(FCompiler): compiler_type = 'absoft' + description = 'Absoft Corp Fortran Compiler' #version_pattern = r'FORTRAN 77 Compiler (?P[^\s*,]*).*?Absoft Corp' version_pattern = r'(f90:.*?(Absoft Pro FORTRAN Version|FORTRAN 77 Compiler|Absoft Fortran Compiler Version|Copyright Absoft Corporation.*?Version))'+\ r' (?P[^\s*,]*)(.*?Absoft Corp|)' @@ -28,12 +31,12 @@ # Note that fink installs g77 as f77, so need to use f90 for detection. executables = { - 'version_cmd' : ["f90", "-V -c %(fname)s.f -o %(fname)s.o" \ + 'version_cmd' : ["", "-V -c %(fname)s.f -o %(fname)s.o" \ % {'fname':cyg2win32(dummy_fortran_file())}], 'compiler_f77' : ["f77"], 'compiler_fix' : ["f90"], 'compiler_f90' : ["f90"], - 'linker_so' : ["f90"], + 'linker_so' : [""], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } Modified: branches/distutils-revamp/fcompiler/compaq.py =================================================================== --- branches/distutils-revamp/fcompiler/compaq.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/compaq.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -7,9 +7,17 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler +compilers = ['CompaqFCompiler'] +if os.name != 'posix': + # Otherwise we'd get a false positive on posix systems with + # case-insensitive filesystems (like darwin), because we'll pick + # up /bin/df + compilers.append('CompaqVisualFCompiler') + class CompaqFCompiler(FCompiler): compiler_type = 'compaq' + description = 'Compaq Fortran Compiler' version_pattern = r'Compaq Fortran (?P[^\s]*).*' if sys.platform[:5]=='linux': @@ -18,11 +26,11 @@ fc_exe = 'f90' executables = { - 'version_cmd' : [fc_exe, "-version"], + 'version_cmd' : ['', "-version"], 'compiler_f77' : [fc_exe, "-f77rtl","-fixed"], 'compiler_fix' : [fc_exe, "-fixed"], 'compiler_f90' : [fc_exe], - 'linker_so' : [fc_exe], + 'linker_so' : [''], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } @@ -47,6 +55,7 @@ class CompaqVisualFCompiler(FCompiler): compiler_type = 'compaqv' + description = 'DIGITAL or Compaq Visual Fortran Compiler' version_pattern = r'(DIGITAL|Compaq) Visual Fortran Optimizing Compiler'\ ' Version (?P[^\s]*).*' @@ -68,11 +77,11 @@ ar_exe = m.lib executables = { - 'version_cmd' : ['DF', "/what"], - 'compiler_f77' : ['DF', "/f77rtl","/fixed"], - 'compiler_fix' : ['DF', "/fixed"], - 'compiler_f90' : ['DF'], - 'linker_so' : ['DF'], + 'version_cmd' : ['', "/what"], + 'compiler_f77' : [fc_exe, "/f77rtl","/fixed"], + 'compiler_fix' : [fc_exe, "/fixed"], + 'compiler_f90' : [fc_exe], + 'linker_so' : [''], 'archiver' : [ar_exe, "/OUT:"], 'ranlib' : None } Modified: branches/distutils-revamp/fcompiler/g95.py =================================================================== --- branches/distutils-revamp/fcompiler/g95.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/g95.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -6,20 +6,23 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler +compilers = ['G95FCompiler'] + class G95FCompiler(FCompiler): compiler_type = 'g95' + description = 'G95 Fortran Compiler' version_pattern = r'G95 \((GCC (?P[\d.]+)|.*?) \(g95!\) (?P.*)\).*' # $ g95 --version # G95 (GCC 4.0.3 (g95!) May 22 2006) executables = { - 'version_cmd' : ["g95", "--version"], + 'version_cmd' : ["", "--version"], 'compiler_f77' : ["g95", "-ffixed-form"], 'compiler_fix' : ["g95", "-ffixed-form"], 'compiler_f90' : ["g95"], - 'linker_so' : ["g95","-shared"], + 'linker_so' : ["","-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } Modified: branches/distutils-revamp/fcompiler/gnu.py =================================================================== --- branches/distutils-revamp/fcompiler/gnu.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/gnu.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -7,12 +7,15 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler -from numpy.distutils.exec_command import exec_command, find_executable +from numpy.distutils.exec_command import exec_command from numpy.distutils.misc_util import mingw32, msvc_runtime_library +compilers = ['GnuFCompiler', 'Gnu95FCompiler'] + class GnuFCompiler(FCompiler): compiler_type = 'gnu' + description = 'GNU Fortran Compiler' version_match = simple_version_match(start=r'GNU Fortran (?!95)') # 'g77 --version' results @@ -22,25 +25,23 @@ # GNU Fortran 0.5.25 20010319 (prerelease) # Redhat: GNU Fortran (GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) 3.2.2 20030222 (Red Hat Linux 3.2.2-5) - for fc_exe in map(find_executable,['g77','f77']): - if os.path.isfile(fc_exe): - break + possible_executables = ['g77', 'f77'] executables = { - 'version_cmd' : [fc_exe,"--version"], - 'compiler_f77' : [fc_exe, "-g", "-Wall","-fno-second-underscore"], + 'version_cmd' : [None, "--version"], + 'compiler_f77' : [None, "-g", "-Wall","-fno-second-underscore"], 'compiler_f90' : None, 'compiler_fix' : None, - 'linker_so' : [fc_exe, "-g", "-Wall"], + 'linker_so' : [None, "-g", "-Wall"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], - 'linker_exe' : [fc_exe, "-g", "-Wall"] + 'linker_exe' : [None, "-g", "-Wall"] } module_dir_switch = None module_include_switch = None # Cygwin: f771: warning: -fPIC ignored for target (all code is # position independent) - if os.name != 'nt' and sys.platform!='cygwin': + if os.name != 'nt' and sys.platform != 'cygwin': pic_flags = ['-fPIC'] # use -mno-cygwin for g77 when Python is not Cygwin-Python @@ -59,10 +60,8 @@ def get_flags_linker_so(self): opt = self.linker_so[1:] - if sys.platform=='darwin': - target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) - if target is None: - target = '10.3' + if sys.platform == 'darwin': + target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', '10.3') major, minor = target.split('.') if int(minor) < 3: minor = '3' @@ -74,7 +73,7 @@ opt.extend(['-undefined', 'dynamic_lookup', '-bundle']) else: opt.append("-shared") - if sys.platform[:5]=='sunos': + if sys.platform.startswith('sunos'): # SunOS often has dynamically loaded symbols defined in the # static library libg2c.a The linker doesn't like this. To # ignore the problem, use the -mimpure-text flag. It isn't @@ -146,13 +145,10 @@ def get_flags_arch(self): opt = [] - if sys.platform=='darwin': - if os.name != 'posix': - # this should presumably correspond to Apple - if cpu.is_ppc(): - opt.append('-arch ppc') - elif cpu.is_i386(): - opt.append('-arch i386') + if sys.platform == 'darwin': + # Since Apple doesn't distribute a GNU Fortran compiler, we + # can't add -arch ppc or -arch i386, as only their version + # of the GNU compilers accepts those. for a in '601 602 603 603e 604 604e 620 630 740 7400 7450 750'\ '403 505 801 821 823 860'.split(): if getattr(cpu,'is_ppc%s'%a)(): @@ -238,6 +234,7 @@ class Gnu95FCompiler(GnuFCompiler): compiler_type = 'gnu95' + description = 'GNU 95 Fortran Compiler' version_match = simple_version_match(start='GNU Fortran 95') # 'gfortran --version' results: @@ -245,18 +242,16 @@ # OS X: GNU Fortran 95 (GCC) 4.1.0 # GNU Fortran 95 (GCC) 4.2.0 20060218 (experimental) - for fc_exe in map(find_executable,['gfortran','f95']): - if os.path.isfile(fc_exe): - break + possible_executables = ['gfortran', 'f95'] executables = { - 'version_cmd' : [fc_exe,"--version"], - 'compiler_f77' : [fc_exe,"-Wall","-ffixed-form","-fno-second-underscore"], - 'compiler_f90' : [fc_exe,"-Wall","-fno-second-underscore"], - 'compiler_fix' : [fc_exe,"-Wall","-ffixed-form","-fno-second-underscore"], - 'linker_so' : [fc_exe,"-Wall"], + 'version_cmd' : ["", "--version"], + 'compiler_f77' : [None, "-Wall", "-ffixed-form", "-fno-second-underscore"], + 'compiler_f90' : [None, "-Wall", "-fno-second-underscore"], + 'compiler_fix' : [None, "-Wall", "-ffixed-form", "-fno-second-underscore"], + 'linker_so' : ["", "-Wall"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], - 'linker_exe' : [fc_exe,"-Wall"] + 'linker_exe' : [None,"-Wall"] } # use -mno-cygwin flag for g77 when Python is not Cygwin-Python @@ -273,7 +268,7 @@ def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': - opt.remove('cc_dynamic') + opt.remove('cc_dynamic') return opt if __name__ == '__main__': Modified: branches/distutils-revamp/fcompiler/hpux.py =================================================================== --- branches/distutils-revamp/fcompiler/hpux.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/hpux.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -4,13 +4,16 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler +compilers = ['HPUXFCompiler'] + class HPUXFCompiler(FCompiler): compiler_type = 'hpux' + description = 'HP Fortran 90 Compiler' version_pattern = r'HP F90 (?P[^\s*,]*)' executables = { - 'version_cmd' : ["f90", "+version"], + 'version_cmd' : ["", "+version"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90"], 'compiler_f90' : ["f90"], Modified: branches/distutils-revamp/fcompiler/ibm.py =================================================================== --- branches/distutils-revamp/fcompiler/ibm.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/ibm.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -5,13 +5,16 @@ from numpy.distutils.fcompiler import FCompiler from distutils import log -class IbmFCompiler(FCompiler): +compilers = ['IBMFCompiler'] +class IBMFCompiler(FCompiler): + compiler_type = 'ibm' + description = 'IBM XL Fortran Compiler' version_pattern = r'xlf\(1\)\s*IBM XL Fortran (Advanced Edition |)Version (?P[^\s*]*)' executables = { - 'version_cmd' : ["xlf"], + 'version_cmd' : [""], 'compiler_f77' : ["xlf"], 'compiler_fix' : ["xlf90", "-qfixed"], 'compiler_f90' : ["xlf90"], Modified: branches/distutils-revamp/fcompiler/intel.py =================================================================== --- branches/distutils-revamp/fcompiler/intel.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/intel.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -5,25 +5,28 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file -from numpy.distutils.exec_command import find_executable +compilers = ['IntelFCompiler', 'IntelVisualFCompiler', + 'IntelItaniumFCompiler', 'IntelItaniumVisualFCompiler', + 'IntelEM64TFCompiler'] + class IntelFCompiler(FCompiler): compiler_type = 'intel' + description = 'Intel Fortran Compiler for 32-bit apps' version_pattern = r'Intel\(R\) Fortran Compiler for 32-bit '\ 'applications, Version (?P[^\s*]*)' - for fc_exe in map(find_executable,['ifort','ifc']): - if os.path.isfile(fc_exe): - break + possible_executables = ['ifort', 'ifc'] + executables = { - 'version_cmd' : [fc_exe, "-FI -V -c %(fname)s.f -o %(fname)s.o" \ + 'version_cmd' : ["", "-FI -V -c %(fname)s.f -o %(fname)s.o" \ % {'fname':dummy_fortran_file()}], - 'compiler_f77' : [fc_exe,"-72","-w90","-w95"], - 'compiler_fix' : [fc_exe,"-FI"], - 'compiler_f90' : [fc_exe], - 'linker_so' : [fc_exe,"-shared"], + 'compiler_f77' : [None,"-72","-w90","-w95"], + 'compiler_f90' : [None], + 'compiler_fix' : [None,"-FI"], + 'linker_so' : ["","-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } @@ -74,42 +77,40 @@ class IntelItaniumFCompiler(IntelFCompiler): compiler_type = 'intele' + description = 'Intel Fortran Compiler for Itanium apps' version_pattern = r'Intel\(R\) Fortran 90 Compiler Itanium\(TM\) Compiler'\ ' for the Itanium\(TM\)-based applications,'\ ' Version (?P[^\s*]*)' - for fc_exe in map(find_executable,['ifort','efort','efc']): - if os.path.isfile(fc_exe): - break + possible_executables = ['ifort', 'efort', 'efc'] executables = { - 'version_cmd' : [fc_exe, "-FI -V -c %(fname)s.f -o %(fname)s.o" \ + 'version_cmd' : ['', "-FI -V -c %(fname)s.f -o %(fname)s.o" \ % {'fname':dummy_fortran_file()}], - 'compiler_f77' : [fc_exe,"-FI","-w90","-w95"], - 'compiler_fix' : [fc_exe,"-FI"], - 'compiler_f90' : [fc_exe], - 'linker_so' : [fc_exe,"-shared"], + 'compiler_f77' : [None,"-FI","-w90","-w95"], + 'compiler_fix' : [None,"-FI"], + 'compiler_f90' : [None], + 'linker_so' : ['', "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } class IntelEM64TFCompiler(IntelFCompiler): compiler_type = 'intelem' + description = 'Intel Fortran Compiler for EM64T-based apps' version_pattern = r'Intel\(R\) Fortran Compiler for Intel\(R\) EM64T-based '\ 'applications, Version (?P[^\s*]*)' - for fc_exe in map(find_executable,['ifort','efort','efc']): - if os.path.isfile(fc_exe): - break + possible_executables = ['ifort', 'efort', 'efc'] executables = { - 'version_cmd' : [fc_exe, "-FI -V -c %(fname)s.f -o %(fname)s.o" \ + 'version_cmd' : ['', "-FI -V -c %(fname)s.f -o %(fname)s.o" \ % {'fname':dummy_fortran_file()}], - 'compiler_f77' : [fc_exe,"-FI","-w90","-w95"], - 'compiler_fix' : [fc_exe,"-FI"], - 'compiler_f90' : [fc_exe], - 'linker_so' : [fc_exe,"-shared"], + 'compiler_f77' : [None, "-FI", "-w90", "-w95"], + 'compiler_fix' : [None, "-FI"], + 'compiler_f90' : [None], + 'linker_so' : ['', "-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } @@ -123,6 +124,7 @@ class IntelVisualFCompiler(FCompiler): compiler_type = 'intelv' + description = 'Intel Visual Fortran Compiler for 32-bit apps' version_pattern = r'Intel\(R\) Fortran Compiler for 32-bit applications, '\ 'Version (?P[^\s*]*)' @@ -133,12 +135,12 @@ ar_exe = MSVCCompiler().lib executables = { - 'version_cmd' : [fc_exe, "-FI -V -c %(fname)s.f -o %(fname)s.o" \ + 'version_cmd' : ['', "-FI -V -c %(fname)s.f -o %(fname)s.o" \ % {'fname':dummy_fortran_file()}], 'compiler_f77' : [fc_exe,"-FI","-w90","-w95"], 'compiler_fix' : [fc_exe,"-FI","-4L72","-w"], 'compiler_f90' : [fc_exe], - 'linker_so' : [fc_exe,"-shared"], + 'linker_so' : ['', "-shared"], 'archiver' : [ar_exe, "/verbose", "/OUT:"], 'ranlib' : None } @@ -179,6 +181,7 @@ class IntelItaniumVisualFCompiler(IntelVisualFCompiler): compiler_type = 'intelev' + description = 'Intel Visual Fortran Compiler for Itanium apps' version_pattern = r'Intel\(R\) Fortran 90 Compiler Itanium\(TM\) Compiler'\ ' for the Itanium\(TM\)-based applications,'\ ' Version (?P[^\s*]*)' @@ -187,12 +190,12 @@ ar_exe = IntelVisualFCompiler.ar_exe executables = { - 'version_cmd' : [fc_exe, "-FI -V -c %(fname)s.f -o %(fname)s.o" \ + 'version_cmd' : ['', "-FI -V -c %(fname)s.f -o %(fname)s.o" \ % {'fname':dummy_fortran_file()}], 'compiler_f77' : [fc_exe,"-FI","-w90","-w95"], 'compiler_fix' : [fc_exe,"-FI","-4L72","-w"], 'compiler_f90' : [fc_exe], - 'linker_so' : [fc_exe,"-shared"], + 'linker_so' : ['',"-shared"], 'archiver' : [ar_exe, "/verbose", "/OUT:"], 'ranlib' : None } Modified: branches/distutils-revamp/fcompiler/lahey.py =================================================================== --- branches/distutils-revamp/fcompiler/lahey.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/lahey.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -4,13 +4,16 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler +compilers = ['LaheyFCompiler'] + class LaheyFCompiler(FCompiler): compiler_type = 'lahey' + description = 'Lahey/Fujitsu Fortran 95 Compiler' version_pattern = r'Lahey/Fujitsu Fortran 95 Compiler Release (?P[^\s*]*)' executables = { - 'version_cmd' : ["lf95", "--version"], + 'version_cmd' : ["", "--version"], 'compiler_f77' : ["lf95", "--fix"], 'compiler_fix' : ["lf95", "--fix"], 'compiler_f90' : ["lf95"], Modified: branches/distutils-revamp/fcompiler/mips.py =================================================================== --- branches/distutils-revamp/fcompiler/mips.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/mips.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -4,13 +4,16 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler -class MipsFCompiler(FCompiler): +compilers = ['MIPSFCompiler'] +class MIPSFCompiler(FCompiler): + compiler_type = 'mips' + description = 'MIPSpro Fortran Compiler' version_pattern = r'MIPSpro Compilers: Version (?P[^\s*,]*)' executables = { - 'version_cmd' : ["f90", "-version"], + 'version_cmd' : ["", "-version"], 'compiler_f77' : ["f77", "-f77"], 'compiler_fix' : ["f90", "-fixedform"], 'compiler_f90' : ["f90"], Modified: branches/distutils-revamp/fcompiler/nag.py =================================================================== --- branches/distutils-revamp/fcompiler/nag.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/nag.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -4,17 +4,20 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler +compilers = ['NAGFCompiler'] + class NAGFCompiler(FCompiler): compiler_type = 'nag' + description = 'NAGWare Fortran 95 Compiler' version_pattern = r'NAGWare Fortran 95 compiler Release (?P[^\s]*)' executables = { - 'version_cmd' : ["f95", "-V"], + 'version_cmd' : ["", "-V"], 'compiler_f77' : ["f95", "-fixed"], 'compiler_fix' : ["f95", "-fixed"], 'compiler_f90' : ["f95"], - 'linker_so' : ["f95"], + 'linker_so' : [""], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } Modified: branches/distutils-revamp/fcompiler/none.py =================================================================== --- branches/distutils-revamp/fcompiler/none.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/none.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -1,20 +1,27 @@ from numpy.distutils.fcompiler import FCompiler +compilers = ['NoneFCompiler'] + class NoneFCompiler(FCompiler): compiler_type = 'none' + description = 'Fake Fortran compiler' - executables = {'compiler_f77':['/path/to/nowhere/none'], - 'compiler_f90':['/path/to/nowhere/none'], - 'compiler_fix':['/path/to/nowhere/none'], - 'linker_so':['/path/to/nowhere/none'], - 'archiver':['/path/to/nowhere/none'], - 'ranlib':['/path/to/nowhere/none'], - 'version_cmd':['/path/to/nowhere/none'], + executables = {'compiler_f77' : None, + 'compiler_f90' : None, + 'compiler_fix' : None, + 'linker_so' : None, + 'linker_exe' : None, + 'archiver' : None, + 'ranlib' : None, + 'version_cmd' : None, } + def find_executables(self): + pass + if __name__ == '__main__': from distutils import log log.set_verbosity(2) Modified: branches/distutils-revamp/fcompiler/pg.py =================================================================== --- branches/distutils-revamp/fcompiler/pg.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/pg.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -7,13 +7,16 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler +compilers = ['PGroupFCompiler'] + class PGroupFCompiler(FCompiler): compiler_type = 'pg' + description = 'Portland Group Fortran Compiler' version_pattern = r'\s*pg(f77|f90|hpf) (?P[\d.-]+).*' executables = { - 'version_cmd' : ["pgf77", "-V 2>/dev/null"], + 'version_cmd' : ["", "-V 2>/dev/null"], 'compiler_f77' : ["pgf77"], 'compiler_fix' : ["pgf90", "-Mfixed"], 'compiler_f90' : ["pgf90"], Modified: branches/distutils-revamp/fcompiler/sun.py =================================================================== --- branches/distutils-revamp/fcompiler/sun.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/sun.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -5,20 +5,23 @@ from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler +compilers = ['SunFCompiler'] + class SunFCompiler(FCompiler): compiler_type = 'sun' + description = 'Sun or Forte Fortran 95 Compiler' # ex: # f90: Sun WorkShop 6 update 2 Fortran 95 6.2 Patch 111690-10 2003/08/28 version_match = simple_version_match( start=r'f9[05]: (Sun|Forte|WorkShop).*Fortran 95') executables = { - 'version_cmd' : ["f90", "-V"], + 'version_cmd' : ["", "-V"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90", "-fixed"], 'compiler_f90' : ["f90"], - 'linker_so' : ["f90","-Bdynamic","-G"], + 'linker_so' : ["","-Bdynamic","-G"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } Modified: branches/distutils-revamp/fcompiler/vast.py =================================================================== --- branches/distutils-revamp/fcompiler/vast.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/fcompiler/vast.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -4,9 +4,12 @@ from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler.gnu import GnuFCompiler +compilers = ['VastFCompiler'] + class VastFCompiler(GnuFCompiler): compiler_type = 'vast' + description = 'Pacific-Sierra Research Fortran 90 Compiler' version_pattern = r'\s*Pacific-Sierra Research vf90 '\ '(Personal|Professional)\s+(?P[^\s]*)' @@ -19,7 +22,7 @@ 'compiler_f77' : ["g77"], 'compiler_fix' : ["f90", "-Wv,-ya"], 'compiler_f90' : ["f90"], - 'linker_so' : ["f90"], + 'linker_so' : [""], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } @@ -28,8 +31,8 @@ def get_version_cmd(self): f90 = self.compiler_f90[0] - d,b = os.path.split(f90) - vf90 = os.path.join(d,'v'+b) + d, b = os.path.split(f90) + vf90 = os.path.join(d, 'v'+b) return vf90 def get_flags_arch(self): Modified: branches/distutils-revamp/intelccompiler.py =================================================================== --- branches/distutils-revamp/intelccompiler.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/intelccompiler.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -26,5 +26,5 @@ # On Itanium, the Intel Compiler used to be called ecc, let's search for # it (now it's also icc, so ecc is last in the search). for cc_exe in map(find_executable,['icc','ecc']): - if os.path.isfile(cc_exe): + if cc_exe: break Modified: branches/distutils-revamp/system_info.py =================================================================== --- branches/distutils-revamp/system_info.py 2006-08-02 20:44:43 UTC (rev 2945) +++ branches/distutils-revamp/system_info.py 2006-08-03 02:42:25 UTC (rev 2946) @@ -1621,7 +1621,7 @@ def calc_info(self): config_exe = find_executable(self.get_config_exe()) - if not os.path.isfile(config_exe): + if not config_exe: log.warn('File not found: %s. Cannot determine %s info.' \ % (config_exe, self.section)) return From numpy-svn at scipy.org Thu Aug 3 09:19:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 3 Aug 2006 08:19:56 -0500 (CDT) Subject: [Numpy-svn] r2947 - trunk/numpy/lib Message-ID: <20060803131956.B177D39C0F2@new.scipy.org> Author: stefan Date: 2006-08-03 08:19:50 -0500 (Thu, 03 Aug 2006) New Revision: 2947 Modified: trunk/numpy/lib/function_base.py Log: Format docstrings to be consistent with others. Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-03 02:42:25 UTC (rev 2946) +++ trunk/numpy/lib/function_base.py 2006-08-03 13:19:50 UTC (rev 2947) @@ -395,8 +395,10 @@ return a[slice1]-a[slice2] add_docstring(digitize, - r"""(x,bins) --> index of the bin to which each value of x belongs. + r"""digitize(x,bins) + Return the index of the bin to which each value of x belongs. + Each index i returned is such that bins[i-1] <= x < bins[i] if bins is monotonically increasing, or bins [i-1] > x >= bins[i] if bins is monotonically decreasing. @@ -405,7 +407,9 @@ """) add_docstring(bincount, - r"""(x,weights=None) --> the number of occurrences of each value in x. + r"""bincount(x,weights=None) + + Return the number of occurrences of each value in x. x must be a list of non-negative integers. The output, b[i], represents the number of times that i is found in x. If weights @@ -416,7 +420,7 @@ """) add_docstring(add_docstring, - r"""(obj, docstring) --> None + r"""docstring(obj, docstring) Add a docstring to a built-in obj if possible. If the obj already has a docstring raise a RuntimeError From numpy-svn at scipy.org Thu Aug 3 13:00:25 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 3 Aug 2006 12:00:25 -0500 (CDT) Subject: [Numpy-svn] r2948 - in trunk/numpy: core oldnumeric Message-ID: <20060803170025.3981939C02F@new.scipy.org> Author: oliphant Date: 2006-08-03 12:00:19 -0500 (Thu, 03 Aug 2006) New Revision: 2948 Modified: trunk/numpy/core/defchararray.py trunk/numpy/oldnumeric/compat.py Log: Strip white-space on element retrieval Modified: trunk/numpy/core/defchararray.py =================================================================== --- trunk/numpy/core/defchararray.py 2006-08-03 13:19:50 UTC (rev 2947) +++ trunk/numpy/core/defchararray.py 2006-08-03 17:00:19 UTC (rev 2948) @@ -9,9 +9,10 @@ _unicode = unicode # special sub-class for character arrays (string_ and unicode_) -# This adds equality testing and methods of str and unicode types +# This adds + and * operations and methods of str and unicode types # which operate on an element-by-element basis +# It also strips white-space on element retrieval class chararray(ndarray): def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, @@ -40,36 +41,11 @@ if not _globalvar and self.dtype.char not in 'SUb': raise ValueError, "Can only create a chararray from string data." + def __getitem__(self, obj): + val = ndarray.__getitem__(self, obj) + if isinstance(val, (string_, unicode_)): + return val.rstrip() -## def _richcmpfunc(self, other, op): -## b = broadcast(self, other) -## result = empty(b.shape, dtype=bool) -## res = result.flat -## for k, val in enumerate(b): -## r1 = val[0].rstrip('\x00') -## r2 = val[1] -## res[k] = eval("r1 %s r2" % op, {'r1':r1,'r2':r2}) -## return result - - # these have been moved to C -## def __eq__(self, other): -## return self._richcmpfunc(other, '==') - -## def __ne__(self, other): -## return self._richcmpfunc(other, '!=') - -## def __ge__(self, other): -## return self._richcmpfunc(other, '>=') - -## def __le__(self, other): -## return self._richcmpfunc(other, '<=') - -## def __gt__(self, other): -## return self._richcmpfunc(other, '>') - -## def __lt__(self, other): -## return self._richcmpfunc(other, '<') - def __add__(self, other): b = broadcast(self, other) arr = b.iters[1].base Modified: trunk/numpy/oldnumeric/compat.py =================================================================== --- trunk/numpy/oldnumeric/compat.py 2006-08-03 13:19:50 UTC (rev 2947) +++ trunk/numpy/oldnumeric/compat.py 2006-08-03 17:00:19 UTC (rev 2948) @@ -144,7 +144,6 @@ innerproduct = deprecate(mu.inner, 'innerproduct', 'inner') - def DumpArray(m, fp): m.dump(fp) From numpy-svn at scipy.org Thu Aug 3 16:14:16 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 3 Aug 2006 15:14:16 -0500 (CDT) Subject: [Numpy-svn] r2949 - in trunk/numpy/core: . src Message-ID: <20060803201416.9669039C088@new.scipy.org> Author: oliphant Date: 2006-08-03 15:14:09 -0500 (Thu, 03 Aug 2006) New Revision: 2949 Modified: trunk/numpy/core/__init__.py trunk/numpy/core/numeric.py trunk/numpy/core/numerictypes.py trunk/numpy/core/src/arrayobject.c Log: Clean up scalar-types functions a bit. Modified: trunk/numpy/core/__init__.py =================================================================== --- trunk/numpy/core/__init__.py 2006-08-03 17:00:19 UTC (rev 2948) +++ trunk/numpy/core/__init__.py 2006-08-03 20:14:09 UTC (rev 2949) @@ -5,7 +5,7 @@ import multiarray import umath import numerictypes as nt -multiarray.set_typeDict(nt.typeDict) +multiarray.set_typeDict(nt.sctypeDict) import _sort from numeric import * from fromnumeric import * Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-03 17:00:19 UTC (rev 2948) +++ trunk/numpy/core/numeric.py 2006-08-03 20:14:09 UTC (rev 2949) @@ -354,7 +354,7 @@ if isinstance(num, generic): return True else: - return type(num) in ScalarType + return issctype(type(num)) _lkup = { '0':'0000', Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-03 17:00:19 UTC (rev 2948) +++ trunk/numpy/core/numerictypes.py 2006-08-03 20:14:09 UTC (rev 2949) @@ -76,19 +76,19 @@ """ # we add more at the bottom -__all__ = ['typeDict', 'typeNA', 'sctypes', 'ScalarType', 'obj2sctype', +__all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes', 'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char', 'maximum_sctype', 'issctype', 'typecodes'] -from multiarray import typeinfo, ndarray, array, empty +from multiarray import typeinfo, ndarray, array, empty, dtype import types as _types # we don't export these for import *, but we do want them accessible # as numerictypes.bool, etc. from __builtin__ import bool, int, long, float, complex, object, unicode, str -typeDict = {} # Contains all leaf-node numeric types with aliases -typeNA = {} # Contails all leaf-node types -> numarray type equivalences +sctypeDict = {} # Contains all leaf-node scalar types with aliases +sctypeNA = {} # Contails all leaf-node types -> numarray type equivalences allTypes = {} # Collect the types we will add to the module here def _evalname(name): @@ -151,9 +151,9 @@ # define C-name and insert typenum and typechar references also allTypes[name] = typeobj - typeDict[name] = typeobj - typeDict[typeinfo[a][0]] = typeobj - typeDict[typeinfo[a][1]] = typeobj + sctypeDict[name] = typeobj + sctypeDict[typeinfo[a][0]] = typeobj + sctypeDict[typeinfo[a][1]] = typeobj else: # generic class allTypes[name] = typeinfo[a] @@ -173,21 +173,21 @@ if (name != 'longdouble' and name != 'clongdouble') or \ myname not in allTypes.keys(): allTypes[myname] = typeobj - typeDict[myname] = typeobj + sctypeDict[myname] = typeobj if base == 'complex': na_name = '%s%d' % (base.capitalize(), bit/2) elif base == 'bool': na_name = base.capitalize() - typeDict[na_name] = typeobj + sctypeDict[na_name] = typeobj else: na_name = "%s%d" % (base.capitalize(), bit) - typeDict[na_name] = typeobj - typeNA[na_name] = typeobj - typeNA[typeobj] = na_name - typeNA[typeinfo[a][0]] = na_name + sctypeDict[na_name] = typeobj + sctypeNA[na_name] = typeobj + sctypeNA[typeobj] = na_name + sctypeNA[typeinfo[a][0]] = na_name if char != '': - typeDict[char] = typeobj - typeNA[char] = na_name + sctypeDict[char] = typeobj + sctypeNA[char] = na_name _add_aliases() # Integers handled so that @@ -214,16 +214,16 @@ uintname = 'uint%d' % bits allTypes[intname] = typeobj allTypes[uintname] = utypeobj - typeDict[intname] = typeobj - typeDict[uintname] = utypeobj - typeDict[Intname] = typeobj - typeDict[UIntname] = utypeobj - typeNA[Intname] = typeobj - typeNA[UIntname] = utypeobj - typeNA[typeobj] = Intname - typeNA[utypeobj] = UIntname - typeNA[val[0]] = Intname - typeNA[uval[0]] = UIntname + sctypeDict[intname] = typeobj + sctypeDict[uintname] = utypeobj + sctypeDict[Intname] = typeobj + sctypeDict[UIntname] = utypeobj + sctypeNA[Intname] = typeobj + sctypeNA[UIntname] = utypeobj + sctypeNA[typeobj] = Intname + sctypeNA[utypeobj] = UIntname + sctypeNA[val[0]] = Intname + sctypeNA[uval[0]] = UIntname _add_integer_aliases() # We use these later @@ -255,13 +255,13 @@ ('object_', 'object')] for alias, t in type_pairs: allTypes[alias] = allTypes[t] - typeDict[alias] = typeDict[t] + sctypeDict[alias] = sctypeDict[t] # Remove aliases overriding python types and modules for t in ['ulong', 'object', 'unicode', 'int', 'long', 'float', 'complex', 'bool', 'string']: try: del allTypes[t] - del typeDict[t] + del sctypeDict[t] except KeyError: pass _set_up_aliases() @@ -342,11 +342,15 @@ def issctype(rep): """Determines whether the given object represents a numeric array type.""" + if not isinstance(rep, (type, dtype)): + return False try: - char = sctype2char(rep) - return True - except (KeyError, ValueError, TypeError): + res = obj2sctype(rep) + if res: + return True return False + except: + return False def obj2sctype(rep, default=None): try: @@ -354,11 +358,13 @@ return rep except TypeError: pass + if isinstance(rep, dtype): + return rep.type if isinstance(rep, type): return _python_type(rep) if isinstance(rep, ndarray): return rep.dtype.type - res = typeDict.get(rep, default) + res = sctypeDict.get(rep, default) return res @@ -417,6 +423,11 @@ else: _typestr[key] = empty((1,),key).dtype.str[1:] +# Make sure all typestrings are in sctypeDict +for key, val in _typestr.items(): + if val not in sctypeDict: + sctypeDict[val] = key + # Now add the types we've determined to this module for key in allTypes: globals()[key] = allTypes[key] @@ -432,3 +443,7 @@ 'AllInteger':'bBhHiIlLqQpP', 'AllFloat':'fdgFDG', 'All':'?bhilqpBHILQPfdgFDGSUVO'} + +# backwards compatibility --- deprecated name +typeDict = sctypeDict +typeNA = sctypeNA Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-03 17:00:19 UTC (rev 2948) +++ trunk/numpy/core/src/arrayobject.c 2006-08-03 20:14:09 UTC (rev 2949) @@ -10877,14 +10877,13 @@ } switch (cmp_op) { case Py_LT: - if (PyArray_CanCastTo(self, new)) + if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new)) result = Py_True; else result = Py_False; break; case Py_LE: - if (PyArray_EquivTypes(self, new) || - PyArray_CanCastTo(self, new)) + if (PyArray_CanCastTo(self, new)) result = Py_True; else result = Py_False; @@ -10902,14 +10901,13 @@ result = Py_True; break; case Py_GT: - if (PyArray_CanCastTo(new, self)) + if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(new, self)) result = Py_True; else result = Py_False; break; case Py_GE: - if (PyArray_EquivTypes(self, new) || - PyArray_CanCastTo(new, self)) + if (PyArray_CanCastTo(new, self)) result = Py_True; else result = Py_False; From numpy-svn at scipy.org Thu Aug 3 16:19:34 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 3 Aug 2006 15:19:34 -0500 (CDT) Subject: [Numpy-svn] r2950 - trunk/numpy/core Message-ID: <20060803201934.29FF439C088@new.scipy.org> Author: oliphant Date: 2006-08-03 15:19:30 -0500 (Thu, 03 Aug 2006) New Revision: 2950 Modified: trunk/numpy/core/numeric.py trunk/numpy/core/numerictypes.py Log: A few corrections to scalar-type tests Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-03 20:14:09 UTC (rev 2949) +++ trunk/numpy/core/numeric.py 2006-08-03 20:19:30 UTC (rev 2950) @@ -354,7 +354,7 @@ if isinstance(num, generic): return True else: - return issctype(type(num)) + return type(num) in ScalarType _lkup = { '0':'0000', Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-03 20:14:09 UTC (rev 2949) +++ trunk/numpy/core/numerictypes.py 2006-08-03 20:19:30 UTC (rev 2950) @@ -346,7 +346,7 @@ return False try: res = obj2sctype(rep) - if res: + if res and res != object_: return True return False except: From numpy-svn at scipy.org Thu Aug 3 19:37:02 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 3 Aug 2006 18:37:02 -0500 (CDT) Subject: [Numpy-svn] r2951 - trunk/numpy/core Message-ID: <20060803233702.44E3B39C0A7@new.scipy.org> Author: oliphant Date: 2006-08-03 18:37:00 -0500 (Thu, 03 Aug 2006) New Revision: 2951 Modified: trunk/numpy/core/numerictypes.py Log: Make sure the scalars corresponding to intp and uintp are added. Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-03 20:19:30 UTC (rev 2950) +++ trunk/numpy/core/numerictypes.py 2006-08-03 23:37:00 UTC (rev 2951) @@ -302,8 +302,13 @@ bits = 8*bytes _add_array_type('float', bits) _add_array_type('complex', bits) + _gi = dtype('p') + if _gi.type not in sctypes['int']: + sctypes['int'].append(_gi.type) + sctypes['uint'].append(dtype('P').type) _set_array_types() + genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'int128', 'uint128', 'float16', From numpy-svn at scipy.org Fri Aug 4 14:47:32 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 13:47:32 -0500 (CDT) Subject: [Numpy-svn] r2952 - in trunk/numpy: . core core/blasdot lib/tests oldnumeric Message-ID: <20060804184732.8196839C040@new.scipy.org> Author: oliphant Date: 2006-08-04 13:47:25 -0500 (Fri, 04 Aug 2006) New Revision: 2952 Modified: trunk/numpy/add_newdocs.py trunk/numpy/core/blasdot/_dotblas.c trunk/numpy/core/fromnumeric.py trunk/numpy/core/numeric.py trunk/numpy/lib/tests/test_function_base.py trunk/numpy/oldnumeric/__init__.py trunk/numpy/oldnumeric/compat.py Log: Convert so that axis arguments are consistent for methods and functions. Place functions for which this changes the Numeric default into oldnumeric. Modified: trunk/numpy/add_newdocs.py =================================================================== --- trunk/numpy/add_newdocs.py 2006-08-03 23:37:00 UTC (rev 2951) +++ trunk/numpy/add_newdocs.py 2006-08-04 18:47:25 UTC (rev 2952) @@ -226,7 +226,7 @@ """) add_newdoc('numpy.core.multiarray','concatenate', -"""concatenate((a1, a2, ...), axis=None) +"""concatenate((a1, a2, ...), axis=0) Join arrays together. Modified: trunk/numpy/core/blasdot/_dotblas.c =================================================================== --- trunk/numpy/core/blasdot/_dotblas.c 2006-08-03 23:37:00 UTC (rev 2951) +++ trunk/numpy/core/blasdot/_dotblas.c 2006-08-04 18:47:25 UTC (rev 2952) @@ -172,7 +172,7 @@ } -static char doc_matrixproduct[] = "matrixproduct(a,b)\nReturns the dot product of a and b for arrays of floating point types.\nLike the generic numpy equivalent the product sum is over\nthe last dimension of a and the second-to-last dimension of b.\nNB: The first argument is not conjugated."; +static char doc_matrixproduct[] = "dot(a,b)\nReturns the dot product of a and b for arrays of floating point types.\nLike the generic numpy equivalent the product sum is over\nthe last dimension of a and the second-to-last dimension of b.\nNB: The first argument is not conjugated."; static PyObject * dotblas_matrixproduct(PyObject *dummy, PyObject *args) Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-03 23:37:00 UTC (rev 2951) +++ trunk/numpy/core/fromnumeric.py 2006-08-04 18:47:25 UTC (rev 2952) @@ -1,8 +1,7 @@ # Module containing non-deprecated functions borrowed from Numeric. -__all__ = ['asarray', 'array', 'concatenate', - # functions that are now methods - 'take', 'reshape', 'choose', 'repeat', 'put', 'putmask', +# functions that are now methods +__all__ = ['take', 'reshape', 'choose', 'repeat', 'put', 'putmask', 'swapaxes', 'transpose', 'sort', 'argsort', 'argmax', 'argmin', 'searchsorted', 'alen', 'resize', 'diagonal', 'trace', 'ravel', 'nonzero', 'shape', @@ -44,7 +43,7 @@ result = wrap(result) return result -def take(a, indices, axis=0): +def take(a, indices, axis=None): try: take = a.take except AttributeError: @@ -53,8 +52,8 @@ # not deprecated --- copy if necessary, view otherwise def reshape(a, newshape, order='C'): - """Change the shape of a to newshape. Return a new view object if possible - otherwise return a copy. + """Change the shape of a to newshape. + Return a new view object if possible otherwise return a copy. """ try: reshape = a.reshape @@ -69,7 +68,7 @@ return _wrapit(a, 'choose', choices) return choose(choices) -def repeat(a, repeats, axis=0): +def repeat(a, repeats, axis=None): """repeat elements of a repeats times along axis repeats is a sequence of length a.shape[axis] telling how many times to repeat each element. @@ -222,7 +221,6 @@ """ return asarray(a).trace(offset, axis1, axis2, dtype) -# not deprecated --- always returns a 1-d array. Copy-if-necessary. def ravel(m,order='C'): """ravel(m) returns a 1d array corresponding to all the elements of it's argument. The new array is a view of m if possible, otherwise it is @@ -279,7 +277,7 @@ return _wrapit(m, 'clip', m_min, m_max) return clip(m_min, m_max) -def sum(x, axis=0, dtype=None): +def sum(x, axis=None, dtype=None): """Sum the array over the given axis. The optional dtype argument is the data type for intermediate calculations. @@ -308,7 +306,7 @@ return _wrapit(x, 'sum', axis, dtype) return sum(axis, dtype) -def product (x, axis=0, dtype=None): +def product (x, axis=None, dtype=None): """Product of the array elements over the given axis.""" try: prod = x.prod @@ -316,7 +314,7 @@ return _wrapit(x, 'prod', axis, dtype) return prod(axis, dtype) -def sometrue (x, axis=0): +def sometrue (x, axis=None): """Perform a logical_or over the given axis.""" try: any = x.any @@ -324,7 +322,7 @@ return _wrapit(x, 'any', axis) return any(axis) -def alltrue (x, axis=0): +def alltrue (x, axis=None): """Perform a logical_and over the given axis.""" try: all = x.all @@ -350,7 +348,7 @@ return _wrapit(x, 'all', axis) return all(axis) -def cumsum (x, axis=0, dtype=None): +def cumsum (x, axis=None, dtype=None): """Sum the array over the given axis.""" try: cumsum = x.cumsum @@ -358,7 +356,7 @@ return _wrapit(x, 'cumsum', axis, dtype) return cumsum(axis, dtype) -def cumproduct (x, axis=0, dtype=None): +def cumproduct (x, axis=None, dtype=None): """Sum the array over the given axis.""" try: cumprod = x.cumprod @@ -366,7 +364,7 @@ return _wrapit(x, 'cumprod', axis, dtype) return cumprod(axis, dtype) -def ptp(a, axis=0): +def ptp(a, axis=None): """Return maximum - minimum along the the given dimension """ try: @@ -375,7 +373,7 @@ return _wrapit(a, 'ptp', axis) return ptp(axis) -def amax(a, axis=0): +def amax(a, axis=None): """Return the maximum of 'a' along dimension axis. """ try: @@ -384,7 +382,7 @@ return _wrapit(a, 'max', axis) return max(axis) -def amin(a, axis=0): +def amin(a, axis=None): """Return the minimum of a along dimension axis. """ try: @@ -402,7 +400,7 @@ except TypeError: return len(array(a,ndmin=1)) -def prod(a, axis=0, dtype=None): +def prod(a, axis=None, dtype=None): """Return the product of the elements along the given axis """ try: @@ -411,7 +409,7 @@ return _wrapit(a, 'prod', axis, dtype) return prod(axis, dtype) -def cumprod(a, axis=0, dtype=None): +def cumprod(a, axis=None, dtype=None): """Return the cumulative product of the elments along the given axis """ try: @@ -463,8 +461,8 @@ around = round_ -def mean(a, axis=0, dtype=None): - """mean(a, axis=0, dtype=None) +def mean(a, axis=None, dtype=None): + """mean(a, axis=None, dtype=None) Return the arithmetic mean. The mean is the sum of the elements divided by the number of elements. @@ -477,8 +475,8 @@ return _wrapit(a, 'mean', axis, dtype) return mean(axis, dtype) -def std(a, axis=0, dtype=None): - """std(sample, axis=0, dtype=None) +def std(a, axis=None, dtype=None): + """std(sample, axis=None, dtype=None) Return the standard deviation, a measure of the spread of a distribution. The standard deviation is the square root of the average of the squared @@ -492,8 +490,8 @@ return _wrapit(a, 'std', axis, dtype) return std(axis, dtype) -def var(a, axis=0, dtype=None): - """var(sample, axis=0, dtype=None) +def var(a, axis=None, dtype=None): + """var(sample, axis=None, dtype=None) Return the variance, a measure of the spread of a distribution. The variance is the average of the squared deviations from the mean, Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-03 23:37:00 UTC (rev 2951) +++ trunk/numpy/core/numeric.py 2006-08-04 18:47:25 UTC (rev 2952) @@ -323,7 +323,6 @@ set_string_function(array_str, 0) set_string_function(array_repr, 1) - little_endian = (sys.byteorder == 'little') def indices(dimensions, dtype=int): @@ -337,7 +336,7 @@ return array(lst) def fromfunction(function, dimensions, **kwargs): - """fromfunction(function, dimensions) returns an array constructed by + """fromfunction(function, dimensions, dtype=int) returns an array constructed by calling function on a tuple of number grids. The function should accept as many arguments as there are dimensions which is a list of numbers indicating the length of the desired output for each axis. @@ -345,7 +344,8 @@ The function can also accept keyword arguments which will be passed in as well. """ - args = indices(dimensions) + dtype = kwargs.get('dtype', int) + args = indices(dimensions,dtype=dtype) return function(*args,**kwargs) def isscalar(num): Modified: trunk/numpy/lib/tests/test_function_base.py =================================================================== --- trunk/numpy/lib/tests/test_function_base.py 2006-08-03 23:37:00 UTC (rev 2951) +++ trunk/numpy/lib/tests/test_function_base.py 2006-08-04 18:47:25 UTC (rev 2952) @@ -20,7 +20,7 @@ def check_nd(self): y1 = [[0,0,0],[0,1,0],[1,1,0]] assert(any(y1)) - assert_array_equal(sometrue(y1),[1,1,0]) + assert_array_equal(sometrue(y1,axis=0),[1,1,0]) assert_array_equal(sometrue(y1,axis=1),[0,1,1]) class test_all(NumpyTestCase): @@ -36,7 +36,7 @@ def check_nd(self): y1 = [[0,0,1],[0,1,1],[1,1,1]] assert(not all(y1)) - assert_array_equal(alltrue(y1),[0,0,1]) + assert_array_equal(alltrue(y1,axis=0),[0,0,1]) assert_array_equal(alltrue(y1,axis=1),[0,0,1]) class test_average(NumpyTestCase): Modified: trunk/numpy/oldnumeric/__init__.py =================================================================== --- trunk/numpy/oldnumeric/__init__.py 2006-08-03 23:37:00 UTC (rev 2951) +++ trunk/numpy/oldnumeric/__init__.py 2006-08-04 18:47:25 UTC (rev 2952) @@ -2,20 +2,32 @@ from numpy import * from compat import * from olddefaults import * +from typeconv import * +from functions import * import numpy import compat import olddefaults +import typeconv +import functions __version__ = numpy.__version__ __all__ = ['__version__'] __all__ += numpy.__all__ __all__ += compat.__all__ +__all__ += typeconv.__all__ for name in olddefaults.__all__: if name not in __all__: __all__.append(name) +for name in functions.__all__: + if name not in __all__: + __all__.apend(name) + +del name del numpy del compat del olddefaults +del functions +del typeconv Modified: trunk/numpy/oldnumeric/compat.py =================================================================== --- trunk/numpy/oldnumeric/compat.py 2006-08-03 23:37:00 UTC (rev 2951) +++ trunk/numpy/oldnumeric/compat.py 2006-08-04 18:47:25 UTC (rev 2952) @@ -7,7 +7,7 @@ 'UInt8','UInt16','UInt32', 'UnsignedInt32', 'UnsignedInteger', # UnsignedInt64 and Unsigned128 added below if possible # same for Int64 and Int128, Float128, and Complex128 - 'Int8', 'Int16', 'Int32', + 'Int8', 'Int16', 'Int32', 'Int0', 'Int', 'Float0', 'Float', 'Complex0', 'Complex', 'PyObject', 'Float32', 'Float64', 'Float16', 'Float8', 'Complex32', 'Complex64', 'Complex8', 'Complex16', @@ -19,6 +19,7 @@ 'dump', 'dumps' ] + import numpy.core.multiarray as mu import numpy.core.umath as um import numpy.core.numerictypes as nt @@ -38,6 +39,7 @@ def sarray(a, dtype=None, copy=False): return array(a, dtype, copy) + #Use this to add a new axis to an array #compatibility only NewAxis = None From numpy-svn at scipy.org Fri Aug 4 16:55:00 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 15:55:00 -0500 (CDT) Subject: [Numpy-svn] r2953 - trunk/numpy/lib Message-ID: <20060804205500.25F5339C062@new.scipy.org> Author: oliphant Date: 2006-08-04 15:54:57 -0500 (Fri, 04 Aug 2006) New Revision: 2953 Added: trunk/numpy/lib/convertnumericA.py trunk/numpy/lib/convertnumericB.py Removed: trunk/numpy/lib/convertcode.py Log: Change axis=0 to axis=None to be consistent with methods and move axis=0 functions to oldnumeric Deleted: trunk/numpy/lib/convertcode.py =================================================================== --- trunk/numpy/lib/convertcode.py 2006-08-04 18:47:25 UTC (rev 2952) +++ trunk/numpy/lib/convertcode.py 2006-08-04 20:54:57 UTC (rev 2953) @@ -1,160 +0,0 @@ -""" -This module converts code written for Numeric to run with numpy - -Makes the following changes: - * Converts typecharacters - * Changes import statements (warns of use of from Numeric import *) - * Changes import statements (using numerix) ... - * Makes search and replace changes to: - - .typecode() - - .iscontiguous() - - .byteswapped() - - .itemsize() - * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] - * Change typecode= to dtype= - * Eliminates savespace=xxx - * Replace xxx.spacesaver() with True - * Convert xx.savespace(?) to pass + ## xx.savespace(?) - #### -- not * Convert a.shape = ? to a.reshape(?) - * Prints warning for use of bool, int, float, copmlex, object, and unicode - * replaces matrixmultiply with dot -""" -__all__ = ['fromfile', 'fromstr'] - -import sys -import os -import re -import glob - -flatindex_re = re.compile('([.]flat(\s*?[[=]))') - -# Not very safe. Disabled for now.. -def replacetypechars(astr): - astr = astr.replace("'s'","'h'") - astr = astr.replace("'b'","'B'") - astr = astr.replace("'1'","'b'") - astr = astr.replace("'w'","'H'") - astr = astr.replace("'u'","'I'") - return astr - -def changeimports(fstr, name, newname): - importstr = 'import %s' % name - importasstr = 'import %s as ' % name - fromstr = 'from %s import ' % name - fromall=0 - - fstr = fstr.replace(importasstr, 'import %s as ' % newname) - fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) - - ind = 0 - Nlen = len(fromstr) - Nlen2 = len("from %s import " % newname) - while 1: - found = fstr.find(fromstr,ind) - if (found < 0): - break - ind = found + Nlen - if fstr[ind] == '*': - continue - fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) - ind += Nlen2 - Nlen - return fstr, fromall - -def replaceattr(astr): - astr = astr.replace(".typecode()",".dtype.char") - astr = astr.replace(".iscontiguous()",".flags.contiguous") - astr = astr.replace(".byteswapped()",".byteswap()") - astr = astr.replace(".toscalar()", ".item()") - astr = astr.replace(".itemsize()",".itemsize") - astr = astr.replace("matrixmultiply","dot") - # preserve uses of flat that should be o.k. - tmpstr = flatindex_re.sub(r"@@@@\2",astr) - # replace other uses of flat - tmpstr = tmpstr.replace(".flat",".ravel()") - # put back .flat where it was valid - astr = tmpstr.replace("@@@@", ".flat") - return astr - -svspc = re.compile(r'(\S+\s*[(].+),\s*savespace\s*=.+\s*[)]') -svspc2 = re.compile(r'([^,(\s]+[.]spacesaver[(][)])') -svspc3 = re.compile(r'(\S+[.]savespace[(].*[)])') -#shpe = re.compile(r'(\S+\s*)[.]shape\s*=[^=]\s*(.+)') -def replaceother(astr): - astr = re.sub(r'typecode\s*=', 'dtype=', astr) - astr = astr.replace("UserArray","ndarray") - astr = astr.replace('ArrayType', 'ndarray') - astr = astr.replace('NewAxis', 'newaxis') - astr = svspc.sub(r'\1)',astr) - astr = svspc2.sub('True',astr) - astr = svspc3.sub(r'pass ## \1', astr) - #astr = shpe.sub('\\1=\\1.reshape(\\2)', astr) - return astr - -import datetime -def fromstr(filestr): - #filestr = replacetypechars(filestr) - filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'multiarray', - 'numpy.core.multiarray') - filestr, fromall1 = changeimports(filestr, 'umath', - 'numpy.core.umath') - filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric') - filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy') - filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy') - filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.lib.mlab') - filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', - 'numpy.linalg.old') - filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') - filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') - filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') - filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.dft.old') - filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') - fromall = fromall1 or fromall2 or fromall3 - filestr = replaceattr(filestr) - filestr = replaceother(filestr) - today = datetime.date.today().strftime('%b %d, %Y') - name = os.path.split(sys.argv[0])[-1] - filestr = '## Automatically adapted for '\ - 'numpy %s by %s\n\n%s' % (today, name, filestr) - return filestr - -def makenewfile(name, filestr): - fid = file(name, 'w') - fid.write(filestr) - fid.close() - -def getandcopy(name): - fid = file(name) - filestr = fid.read() - fid.close() - base, ext = os.path.splitext(name) - makenewfile(base+'.orig', filestr) - return filestr - -def convertfile(filename): - """Convert the filename given from using Numeric to using NumPy - - Copies the file to filename.orig and then over-writes the file - with the updated code - """ - filestr = getandcopy(filename) - filestr = fromstr(filestr) - makenewfile(filename, filestr) - -def fromargs(args): - filename = args[1] - convertfile(filename) - -def convertall(direc=os.path.curdir): - """Convert all .py files to use NumPy (from Numeric) in the directory given - - For each file, a backup of .py is made as - .py.orig. A new file named .py - is then written with the updated code. - """ - files = glob.glob(os.path.join(direc,'*.py')) - for afile in files: - convertfile(afile) - -if __name__ == '__main__': - fromargs(sys.argv) Added: trunk/numpy/lib/convertnumericA.py =================================================================== --- trunk/numpy/lib/convertnumericA.py 2006-08-04 18:47:25 UTC (rev 2952) +++ trunk/numpy/lib/convertnumericA.py 2006-08-04 20:54:57 UTC (rev 2953) @@ -0,0 +1,139 @@ +""" +This module converts code written for Numeric to run with numpy + +Makes the following changes: + * Changes import statements (warns of use of from Numeric import *) + * Changes import statements (using numerix) ... + * Makes search and replace changes to: + - .typecode() + - .iscontiguous() + - .byteswapped() + - .itemsize() + - .toscalar() + * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] + * Replace xxx.spacesaver() with True + * Convert xx.savespace(?) to pass + ## xx.savespace(?) +""" +__all__ = ['fromfile', 'fromstr'] + +import sys +import os +import re +import glob + +flatindex_re = re.compile('([.]flat(\s*?[[=]))') + +def changeimports(fstr, name, newname): + importstr = 'import %s' % name + importasstr = 'import %s as ' % name + fromstr = 'from %s import ' % name + fromall=0 + + fstr = fstr.replace(importasstr, 'import %s as ' % newname) + fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) + + ind = 0 + Nlen = len(fromstr) + Nlen2 = len("from %s import " % newname) + while 1: + found = fstr.find(fromstr,ind) + if (found < 0): + break + ind = found + Nlen + if fstr[ind] == '*': + continue + fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) + ind += Nlen2 - Nlen + return fstr, fromall + +def replaceattr(astr): + astr = astr.replace(".typecode()",".dtype.char") + astr = astr.replace(".iscontiguous()",".flags.contiguous") + astr = astr.replace(".byteswapped()",".byteswap()") + astr = astr.replace(".toscalar()", ".item()") + astr = astr.replace(".itemsize()",".itemsize") + # preserve uses of flat that should be o.k. + tmpstr = flatindex_re.sub(r"@@@@\2",astr) + # replace other uses of flat + tmpstr = tmpstr.replace(".flat",".ravel()") + # put back .flat where it was valid + astr = tmpstr.replace("@@@@", ".flat") + return astr + +svspc2 = re.compile(r'([^,(\s]+[.]spacesaver[(][)])') +svspc3 = re.compile(r'(\S+[.]savespace[(].*[)])') +#shpe = re.compile(r'(\S+\s*)[.]shape\s*=[^=]\s*(.+)') +def replaceother(astr): + astr = svspc2.sub('True',astr) + astr = svspc3.sub(r'pass ## \1', astr) + #astr = shpe.sub('\\1=\\1.reshape(\\2)', astr) + return astr + +import datetime +def fromstr(filestr): + #filestr = replacetypechars(filestr) + filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'multiarray', + 'numpy.core.multiarray') + filestr, fromall1 = changeimports(filestr, 'umath', + 'numpy.core.umath') + filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric') + filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy') + filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy') + filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.lib.mlab') + filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', + 'numpy.linalg.old') + filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') + filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') + filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.dft.old') + filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') + fromall = fromall1 or fromall2 or fromall3 + filestr = replaceattr(filestr) + filestr = replaceother(filestr) + today = datetime.date.today().strftime('%b %d, %Y') + name = os.path.split(sys.argv[0])[-1] + filestr = '## Automatically adapted for '\ + 'numpy.oldnumeric %s by %s\n\n%s' % (today, name, filestr) + return filestr + +def makenewfile(name, filestr): + fid = file(name, 'w') + fid.write(filestr) + fid.close() + +def getandcopy(name): + fid = file(name) + filestr = fid.read() + fid.close() + base, ext = os.path.splitext(name) + makenewfile(base+'.orig', filestr) + return filestr + +def convertfile(filename): + """Convert the filename given from using Numeric to using NumPy + + Copies the file to filename.orig and then over-writes the file + with the updated code + """ + filestr = getandcopy(filename) + filestr = fromstr(filestr) + makenewfile(filename, filestr) + +def fromargs(args): + filename = args[1] + convertfile(filename) + +def convertall(direc=os.path.curdir): + """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given + + For each file, a backup of .py is made as + .py.orig. A new file named .py + is then written with the updated code. + """ + files = glob.glob(os.path.join(direc,'*.py')) + for afile in files: + convertfile(afile) + +if __name__ == '__main__': + fromargs(sys.argv) Added: trunk/numpy/lib/convertnumericB.py =================================================================== --- trunk/numpy/lib/convertnumericB.py 2006-08-04 18:47:25 UTC (rev 2952) +++ trunk/numpy/lib/convertnumericB.py 2006-08-04 20:54:57 UTC (rev 2953) @@ -0,0 +1,129 @@ +""" +This module converts code written for numpy.oldnumeric to work +with numpy + +Makes the following changes: + * Converts typecharacters + * Changes import statements + * Change typecode= to dtype= + * Eliminates savespace=xxx + * replaces matrixmultiply with dot + * converts functions that don't give axis= keyword that have changed + * converts functions that don't give typecode= keyword that have changed + * converts use of capitalized type-names + + * converts old function names in linalg.old, random.old, dft.old + +""" +__all__ = ['fromfile', 'fromstr'] + +import sys +import os +import re +import glob + +# To convert typecharacters we need to +# Not very safe. Disabled for now.. +def replacetypechars(astr): + astr = astr.replace("'s'","'h'") + astr = astr.replace("'b'","'B'") + astr = astr.replace("'1'","'b'") + astr = astr.replace("'w'","'H'") + astr = astr.replace("'u'","'I'") + return astr + +def changeimports(fstr, name, newname): + importstr = 'import %s' % name + importasstr = 'import %s as ' % name + fromstr = 'from %s import ' % name + fromall=0 + + fstr = fstr.replace(importasstr, 'import %s as ' % newname) + fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) + + ind = 0 + Nlen = len(fromstr) + Nlen2 = len("from %s import " % newname) + while 1: + found = fstr.find(fromstr,ind) + if (found < 0): + break + ind = found + Nlen + if fstr[ind] == '*': + continue + fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) + ind += Nlen2 - Nlen + return fstr, fromall + +def replaceattr(astr): + astr = astr.replace("matrixmultiply","dot") + return astr + +def replaceother(astr): + astr = re.sub(r'typecode\s*=', 'dtype=', astr) + astr = astr.replace('ArrayType', 'ndarray') + astr = astr.replace('NewAxis', 'newaxis') + return astr + +import datetime +def fromstr(filestr): + #filestr = replacetypechars(filestr) + filestr, fromall1 = changeimports(filestr, 'numpy.oldnumeric', 'numpy') + filestr, fromall1 = changeimports(filestr, 'numpy.core.multiarray', 'numpy') + filestr, fromall1 = changeimports(filestr, 'numpy.core.umath', 'numpy') + filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', + 'numpy.linalg.old') + filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') + filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') + filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.dft.old') + filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') + fromall = fromall1 or fromall2 or fromall3 + filestr = replaceattr(filestr) + filestr = replaceother(filestr) + today = datetime.date.today().strftime('%b %d, %Y') + name = os.path.split(sys.argv[0])[-1] + filestr = '## Automatically adapted for '\ + 'numpy %s by %s\n\n%s' % (today, name, filestr) + return filestr + +def makenewfile(name, filestr): + fid = file(name, 'w') + fid.write(filestr) + fid.close() + +def getandcopy(name): + fid = file(name) + filestr = fid.read() + fid.close() + base, ext = os.path.splitext(name) + makenewfile(base+'.orig', filestr) + return filestr + +def convertfile(filename): + """Convert the filename given from using Numeric to using NumPy + + Copies the file to filename.orig and then over-writes the file + with the updated code + """ + filestr = getandcopy(filename) + filestr = fromstr(filestr) + makenewfile(filename, filestr) + +def fromargs(args): + filename = args[1] + convertfile(filename) + +def convertall(direc=os.path.curdir): + """Convert all .py files to use NumPy (from Numeric) in the directory given + + For each file, a backup of .py is made as + .py.orig. A new file named .py + is then written with the updated code. + """ + files = glob.glob(os.path.join(direc,'*.py')) + for afile in files: + convertfile(afile) + +if __name__ == '__main__': + fromargs(sys.argv) From numpy-svn at scipy.org Fri Aug 4 19:32:24 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 18:32:24 -0500 (CDT) Subject: [Numpy-svn] r2954 - in trunk/numpy: . fft fft/tests lib linalg oldnumeric random Message-ID: <20060804233224.DD9D639C010@new.scipy.org> Author: oliphant Date: 2006-08-04 18:32:12 -0500 (Fri, 04 Aug 2006) New Revision: 2954 Added: trunk/numpy/fft/ trunk/numpy/lib/user_array.py trunk/numpy/oldnumeric/linear_algebra.py trunk/numpy/oldnumeric/mlab.py trunk/numpy/oldnumeric/random_array.py trunk/numpy/oldnumeric/rng.py trunk/numpy/oldnumeric/rng_stats.py Removed: trunk/numpy/dft/ trunk/numpy/lib/UserArray.py trunk/numpy/lib/mlab.py trunk/numpy/linalg/old.py trunk/numpy/random/old.py trunk/numpy/random/oldrng.py trunk/numpy/random/oldrngstats.py Modified: trunk/numpy/__init__.py trunk/numpy/dual.py trunk/numpy/fft/setup.py trunk/numpy/fft/tests/test_helper.py trunk/numpy/lib/convertnumericA.py trunk/numpy/lib/convertnumericB.py trunk/numpy/oldnumeric/__init__.py trunk/numpy/oldnumeric/compat.py trunk/numpy/oldnumeric/olddefaults.py trunk/numpy/setup.py Log: Many name-changes in oldnumeric. This may break some numpy code that was using the oldnumeric interface. Modified: trunk/numpy/__init__.py =================================================================== --- trunk/numpy/__init__.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/__init__.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -37,14 +37,14 @@ import lib from lib import * import linalg - import dft + import fft import random __all__ = ['__version__', 'pkgload', 'PackageLoader', 'ScipyTest', 'NumpyTest', 'show_config'] __all__ += core.__all__ __all__ += lib.__all__ - __all__ += ['linalg', 'dft', 'random'] + __all__ += ['linalg', 'fft', 'random'] if __doc__ is not None: __doc__ += """ @@ -57,7 +57,7 @@ to have in the main name-space. random --- Core Random Tools linalg --- Core Linear Algebra Tools -dft --- Core FFT routines +fft --- Core FFT routines testing --- Scipy testing tools These packages require explicit import Modified: trunk/numpy/dual.py =================================================================== --- trunk/numpy/dual.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/dual.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -8,7 +8,7 @@ 'eigh','eigvalsh','lstsq', 'pinv','cholesky','i0'] import numpy.linalg as linpkg -import numpy.dft as fftpkg +import numpy.fft as fftpkg from numpy.lib import i0 import sys Copied: trunk/numpy/fft (from rev 2952, trunk/numpy/dft) Modified: trunk/numpy/fft/setup.py =================================================================== --- trunk/numpy/dft/setup.py 2006-08-04 18:47:25 UTC (rev 2952) +++ trunk/numpy/fft/setup.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -3,7 +3,7 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration - config = Configuration('dft',parent_package,top_path) + config = Configuration('fft',parent_package,top_path) config.add_data_dir('tests') Modified: trunk/numpy/fft/tests/test_helper.py =================================================================== --- trunk/numpy/dft/tests/test_helper.py 2006-08-04 18:47:25 UTC (rev 2952) +++ trunk/numpy/fft/tests/test_helper.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -6,7 +6,7 @@ import sys from numpy.testing import * set_package_path() -from numpy.dft import fftshift,ifftshift,fftfreq +from numpy.fft import fftshift,ifftshift,fftfreq del sys.path[0] from numpy import pi Deleted: trunk/numpy/lib/UserArray.py =================================================================== --- trunk/numpy/lib/UserArray.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/lib/UserArray.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,217 +0,0 @@ -""" -Standard container-class for easy backward compatibility with Numeric. -Try to inherit from the ndarray instead of using this class as this is not -complete. -""" - -from numpy.core import array, asarray, absolute, add, subtract, multiply, \ - divide, remainder, power, left_shift, right_shift, bitwise_and, \ - bitwise_or, bitwise_xor, invert, less, less_equal, not_equal, equal, \ - greater, greater_equal, shape, reshape, arange, sin, sqrt, transpose - -class UserArray(object): - def __init__(self, data, dtype=None, copy=True): - self.array = array(data, dtype, copy=copy) - - def __repr__(self): - if len(self.shape) > 0: - return self.__class__.__name__+repr(self.array)[len("array"):] - else: - return self.__class__.__name__+"("+repr(self.array)+")" - - def __array__(self,t=None): - if t: return self.array.astype(t) - return self.array - - # Array as sequence - def __len__(self): return len(self.array) - - def __getitem__(self, index): - return self._rc(self.array[index]) - - def __getslice__(self, i, j): - return self._rc(self.array[i:j]) - - - def __setitem__(self, index, value): - self.array[index] = asarray(value,self.dtype) - def __setslice__(self, i, j, value): - self.array[i:j] = asarray(value,self.dtype) - - def __abs__(self): - return self._rc(absolute(self.array)) - def __neg__(self): - return self._rc(-self.array) - - def __add__(self, other): - return self._rc(self.array+asarray(other)) - __radd__ = __add__ - - def __iadd__(self, other): - add(self.array, other, self.array) - return self - - def __sub__(self, other): - return self._rc(self.array-asarray(other)) - def __rsub__(self, other): - return self._rc(asarray(other)-self.array) - def __isub__(self, other): - subtract(self.array, other, self.array) - return self - - def __mul__(self, other): - return self._rc(multiply(self.array,asarray(other))) - __rmul__ = __mul__ - def __imul__(self, other): - multiply(self.array, other, self.array) - return self - - def __div__(self, other): - return self._rc(divide(self.array,asarray(other))) - def __rdiv__(self, other): - return self._rc(divide(asarray(other),self.array)) - def __idiv__(self, other): - divide(self.array, other, self.array) - return self - - def __mod__(self, other): - return self._rc(remainder(self.array, other)) - def __rmod__(self, other): - return self._rc(remainder(other, self.array)) - def __imod__(self, other): - remainder(self.array, other, self.array) - return self - - def __divmod__(self, other): - return (self._rc(divide(self.array,other)), - self._rc(remainder(self.array, other))) - def __rdivmod__(self, other): - return (self._rc(divide(other, self.array)), - self._rc(remainder(other, self.array))) - - def __pow__(self,other): - return self._rc(power(self.array,asarray(other))) - def __rpow__(self,other): - return self._rc(power(asarray(other),self.array)) - def __ipow__(self,other): - power(self.array, other, self.array) - return self - - def __lshift__(self,other): - return self._rc(left_shift(self.array, other)) - def __rshift__(self,other): - return self._rc(right_shift(self.array, other)) - def __rlshift__(self,other): - return self._rc(left_shift(other, self.array)) - def __rrshift__(self,other): - return self._rc(right_shift(other, self.array)) - def __ilshift__(self,other): - left_shift(self.array, other, self.array) - return self - def __irshift__(self,other): - right_shift(self.array, other, self.array) - return self - - def __and__(self, other): - return self._rc(bitwise_and(self.array, other)) - def __rand__(self, other): - return self._rc(bitwise_and(other, self.array)) - def __iand__(self, other): - bitwise_and(self.array, other, self.array) - return self - - def __xor__(self, other): - return self._rc(bitwise_xor(self.array, other)) - def __rxor__(self, other): - return self._rc(bitwise_xor(other, self.array)) - def __ixor__(self, other): - bitwise_xor(self.array, other, self.array) - return self - - def __or__(self, other): - return self._rc(bitwise_or(self.array, other)) - def __ror__(self, other): - return self._rc(bitwise_or(other, self.array)) - def __ior__(self, other): - bitwise_or(self.array, other, self.array) - return self - - def __neg__(self): - return self._rc(-self.array) - def __pos__(self): - return self._rc(self.array) - def __abs__(self): - return self._rc(abs(self.array)) - def __invert__(self): - return self._rc(invert(self.array)) - - def _scalarfunc(self, func): - if len(self.shape) == 0: - return func(self[0]) - else: - raise TypeError, "only rank-0 arrays can be converted to Python scalars." - - def __complex__(self): return self._scalarfunc(complex) - def __float__(self): return self._scalarfunc(float) - def __int__(self): return self._scalarfunc(int) - def __long__(self): return self._scalarfunc(long) - def __hex__(self): return self._scalarfunc(hex) - def __oct__(self): return self._scalarfunc(oct) - - def __lt__(self,other): return self._rc(less(self.array,other)) - def __le__(self,other): return self._rc(less_equal(self.array,other)) - def __eq__(self,other): return self._rc(equal(self.array,other)) - def __ne__(self,other): return self._rc(not_equal(self.array,other)) - def __gt__(self,other): return self._rc(greater(self.array,other)) - def __ge__(self,other): return self._rc(greater_equal(self.array,other)) - - def copy(self): return self._rc(self.array.copy()) - - def tostring(self): return self.array.tostring() - - def byteswap(self): return self._rc(self.array.byteswap()) - - def astype(self, typecode): return self._rc(self.array.astype(typecode)) - - def _rc(self, a): - if len(shape(a)) == 0: return a - else: return self.__class__(a) - - def __array_wrap__(self, *args): - return self.__class__(args[0]) - - def __setattr__(self,attr,value): - if attr == 'array': - object.__setattr__(self, attr, value) - return - try: - self.array.__setattr__(attr, value) - except AttributeError: - object.__setattr__(self, attr, value) - - # Only called after other approaches fail. - def __getattr__(self,attr): - if (attr == 'array'): - return object.__getattribute__(self, attr) - return self.array.__getattribute__(attr) - -############################################################# -# Test of class UserArray -############################################################# -if __name__ == '__main__': - temp=reshape(arange(10000),(100,100)) - - ua=UserArray(temp) - # new object created begin test - print dir(ua) - print shape(ua),ua.shape # I have changed Numeric.py - - ua_small=ua[:3,:5] - print ua_small - ua_small[0,0]=10 # this did not change ua[0,0], which is not normal behavior - print ua_small[0,0],ua[0,0] - print sin(ua_small)/3.*6.+sqrt(ua_small**2) - print less(ua_small,103),type(less(ua_small,103)) - print type(ua_small*reshape(arange(15),shape(ua_small))) - print reshape(ua_small,(5,3)) - print transpose(ua_small) Modified: trunk/numpy/lib/convertnumericA.py =================================================================== --- trunk/numpy/lib/convertnumericA.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/lib/convertnumericA.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -73,21 +73,21 @@ def fromstr(filestr): #filestr = replacetypechars(filestr) filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'multiarray', - 'numpy.core.multiarray') - filestr, fromall1 = changeimports(filestr, 'umath', - 'numpy.core.umath') - filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric') - filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy') - filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy') - filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.lib.mlab') - filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', - 'numpy.linalg.old') - filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') - filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') - filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') - filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.dft.old') - filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') + filestr, fromall1 = changeimports(filestr, 'multiarray','numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric.precision') + filestr, fromall1 = changeimports(filestr, 'UserArray', 'numpy.oldnumeric.user_array') + filestr, fromall1 = changeimports(filestr, 'ArrayPrinter', 'numpy.oldnumeric.array_printer') + filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy.oldnumeric') + filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy.oldnumeric') + filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') + filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.oldnumeric.mlab') + filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.oldnumeric.linear_algebra') + filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.oldnumeric.rng') + filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.oldnumeric.rng_stats') + filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.oldnumeric.random_array') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.oldnumeric.fft') + filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.oldnumeric.ma') fromall = fromall1 or fromall2 or fromall3 filestr = replaceattr(filestr) filestr = replaceother(filestr) Modified: trunk/numpy/lib/convertnumericB.py =================================================================== --- trunk/numpy/lib/convertnumericB.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/lib/convertnumericB.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -56,7 +56,7 @@ return fstr, fromall def replaceattr(astr): - astr = astr.replace("matrixmultiply","dot") + astr = astr.replace("matrixmultiply","dot") return astr def replaceother(astr): @@ -76,7 +76,7 @@ filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') - filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.dft.old') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.fft.old') filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') fromall = fromall1 or fromall2 or fromall3 filestr = replaceattr(filestr) Deleted: trunk/numpy/lib/mlab.py =================================================================== --- trunk/numpy/lib/mlab.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/lib/mlab.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,18 +0,0 @@ -# This module is for compatibility only. All functions are defined elsewhere. - -from numpy.core.numeric import * - -from twodim_base import diag, fliplr, flipud, rot90, tril, triu - -# use old defaults -from numpy.oldnumeric import eye, tri - -from numpy.core.fromnumeric import amax as max, amin as min -from function_base import msort, median, trapz, diff, cov, corrcoef, \ - kaiser, blackman, bartlett, hanning, hamming, sinc, angle -from numpy.core.fromnumeric import cumsum, ptp, mean, std, prod, cumprod, \ - squeeze -from polynomial import roots - -from numpy.random import rand, randn -from numpy.dual import eig, svd Added: trunk/numpy/lib/user_array.py =================================================================== --- trunk/numpy/lib/user_array.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/lib/user_array.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -0,0 +1,217 @@ +""" +Standard container-class for easy multiple-inheritance. +Try to inherit from the ndarray instead of using this class as this is not +complete. +""" + +from numpy.core import array, asarray, absolute, add, subtract, multiply, \ + divide, remainder, power, left_shift, right_shift, bitwise_and, \ + bitwise_or, bitwise_xor, invert, less, less_equal, not_equal, equal, \ + greater, greater_equal, shape, reshape, arange, sin, sqrt, transpose + +class container(object): + def __init__(self, data, dtype=None, copy=True): + self.array = array(data, dtype, copy=copy) + + def __repr__(self): + if len(self.shape) > 0: + return self.__class__.__name__+repr(self.array)[len("array"):] + else: + return self.__class__.__name__+"("+repr(self.array)+")" + + def __array__(self,t=None): + if t: return self.array.astype(t) + return self.array + + # Array as sequence + def __len__(self): return len(self.array) + + def __getitem__(self, index): + return self._rc(self.array[index]) + + def __getslice__(self, i, j): + return self._rc(self.array[i:j]) + + + def __setitem__(self, index, value): + self.array[index] = asarray(value,self.dtype) + def __setslice__(self, i, j, value): + self.array[i:j] = asarray(value,self.dtype) + + def __abs__(self): + return self._rc(absolute(self.array)) + def __neg__(self): + return self._rc(-self.array) + + def __add__(self, other): + return self._rc(self.array+asarray(other)) + __radd__ = __add__ + + def __iadd__(self, other): + add(self.array, other, self.array) + return self + + def __sub__(self, other): + return self._rc(self.array-asarray(other)) + def __rsub__(self, other): + return self._rc(asarray(other)-self.array) + def __isub__(self, other): + subtract(self.array, other, self.array) + return self + + def __mul__(self, other): + return self._rc(multiply(self.array,asarray(other))) + __rmul__ = __mul__ + def __imul__(self, other): + multiply(self.array, other, self.array) + return self + + def __div__(self, other): + return self._rc(divide(self.array,asarray(other))) + def __rdiv__(self, other): + return self._rc(divide(asarray(other),self.array)) + def __idiv__(self, other): + divide(self.array, other, self.array) + return self + + def __mod__(self, other): + return self._rc(remainder(self.array, other)) + def __rmod__(self, other): + return self._rc(remainder(other, self.array)) + def __imod__(self, other): + remainder(self.array, other, self.array) + return self + + def __divmod__(self, other): + return (self._rc(divide(self.array,other)), + self._rc(remainder(self.array, other))) + def __rdivmod__(self, other): + return (self._rc(divide(other, self.array)), + self._rc(remainder(other, self.array))) + + def __pow__(self,other): + return self._rc(power(self.array,asarray(other))) + def __rpow__(self,other): + return self._rc(power(asarray(other),self.array)) + def __ipow__(self,other): + power(self.array, other, self.array) + return self + + def __lshift__(self,other): + return self._rc(left_shift(self.array, other)) + def __rshift__(self,other): + return self._rc(right_shift(self.array, other)) + def __rlshift__(self,other): + return self._rc(left_shift(other, self.array)) + def __rrshift__(self,other): + return self._rc(right_shift(other, self.array)) + def __ilshift__(self,other): + left_shift(self.array, other, self.array) + return self + def __irshift__(self,other): + right_shift(self.array, other, self.array) + return self + + def __and__(self, other): + return self._rc(bitwise_and(self.array, other)) + def __rand__(self, other): + return self._rc(bitwise_and(other, self.array)) + def __iand__(self, other): + bitwise_and(self.array, other, self.array) + return self + + def __xor__(self, other): + return self._rc(bitwise_xor(self.array, other)) + def __rxor__(self, other): + return self._rc(bitwise_xor(other, self.array)) + def __ixor__(self, other): + bitwise_xor(self.array, other, self.array) + return self + + def __or__(self, other): + return self._rc(bitwise_or(self.array, other)) + def __ror__(self, other): + return self._rc(bitwise_or(other, self.array)) + def __ior__(self, other): + bitwise_or(self.array, other, self.array) + return self + + def __neg__(self): + return self._rc(-self.array) + def __pos__(self): + return self._rc(self.array) + def __abs__(self): + return self._rc(abs(self.array)) + def __invert__(self): + return self._rc(invert(self.array)) + + def _scalarfunc(self, func): + if len(self.shape) == 0: + return func(self[0]) + else: + raise TypeError, "only rank-0 arrays can be converted to Python scalars." + + def __complex__(self): return self._scalarfunc(complex) + def __float__(self): return self._scalarfunc(float) + def __int__(self): return self._scalarfunc(int) + def __long__(self): return self._scalarfunc(long) + def __hex__(self): return self._scalarfunc(hex) + def __oct__(self): return self._scalarfunc(oct) + + def __lt__(self,other): return self._rc(less(self.array,other)) + def __le__(self,other): return self._rc(less_equal(self.array,other)) + def __eq__(self,other): return self._rc(equal(self.array,other)) + def __ne__(self,other): return self._rc(not_equal(self.array,other)) + def __gt__(self,other): return self._rc(greater(self.array,other)) + def __ge__(self,other): return self._rc(greater_equal(self.array,other)) + + def copy(self): return self._rc(self.array.copy()) + + def tostring(self): return self.array.tostring() + + def byteswap(self): return self._rc(self.array.byteswap()) + + def astype(self, typecode): return self._rc(self.array.astype(typecode)) + + def _rc(self, a): + if len(shape(a)) == 0: return a + else: return self.__class__(a) + + def __array_wrap__(self, *args): + return self.__class__(args[0]) + + def __setattr__(self,attr,value): + if attr == 'array': + object.__setattr__(self, attr, value) + return + try: + self.array.__setattr__(attr, value) + except AttributeError: + object.__setattr__(self, attr, value) + + # Only called after other approaches fail. + def __getattr__(self,attr): + if (attr == 'array'): + return object.__getattribute__(self, attr) + return self.array.__getattribute__(attr) + +############################################################# +# Test of class container +############################################################# +if __name__ == '__main__': + temp=reshape(arange(10000),(100,100)) + + ua=container(temp) + # new object created begin test + print dir(ua) + print shape(ua),ua.shape # I have changed Numeric.py + + ua_small=ua[:3,:5] + print ua_small + ua_small[0,0]=10 # this did not change ua[0,0], which is not normal behavior + print ua_small[0,0],ua[0,0] + print sin(ua_small)/3.*6.+sqrt(ua_small**2) + print less(ua_small,103),type(less(ua_small,103)) + print type(ua_small*reshape(arange(15),shape(ua_small))) + print reshape(ua_small,(5,3)) + print transpose(ua_small) Deleted: trunk/numpy/linalg/old.py =================================================================== --- trunk/numpy/linalg/old.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/linalg/old.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,84 +0,0 @@ - -"""Backward compatible with LinearAlgebra from Numeric -""" -# This module is a lite version of the linalg.py module in SciPy which contains -# high-level Python interface to the LAPACK library. The lite version -# only accesses the following LAPACK functions: dgesv, zgesv, dgeev, -# zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, dpotrf. - - -__all__ = ['LinAlgError', 'solve_linear_equations', - 'inverse', 'cholesky_decomposition', 'eigenvalues', - 'Heigenvalues', 'generalized_inverse', - 'determinant', 'singular_value_decomposition', - 'eigenvectors', 'Heigenvectors', - 'linear_least_squares' - ] - -from numpy.core import transpose -import linalg - -# Linear equations - -LinAlgError = linalg.LinAlgError - -def solve_linear_equations(a, b): - return linalg.solve(a,b) - -# Matrix inversion - -def inverse(a): - return linalg.inv(a) - -# Cholesky decomposition - -def cholesky_decomposition(a): - return linalg.cholesky(a) - -# Eigenvalues - -def eigenvalues(a): - return linalg.eigvals(a) - -def Heigenvalues(a, UPLO='L'): - return linalg.eigvalsh(a,UPLO) - -# Eigenvectors - -def eigenvectors(A): - w, v = linalg.eig(A) - return w, transpose(v) - -def Heigenvectors(A): - w, v = linalg.eigh(A) - return w, transpose(v) - -# Generalized inverse - -def generalized_inverse(a, rcond = 1.e-10): - return linalg.pinv(a, rcond) - -# Determinant - -def determinant(a): - return linalg.det(a) - -# Linear Least Squares - -def linear_least_squares(a, b, rcond=1.e-10): - """returns x,resids,rank,s -where x minimizes 2-norm(|b - Ax|) - resids is the sum square residuals - rank is the rank of A - s is the rank of the singular values of A in descending order - -If b is a matrix then x is also a matrix with corresponding columns. -If the rank of A is less than the number of columns of A or greater than -the number of rows, then residuals will be returned as an empty array -otherwise resids = sum((b-dot(A,x)**2). -Singular values less than s[0]*rcond are treated as zero. -""" - return linalg.lstsq(a,b,rcond) - -def singular_value_decomposition(A, full_matrices=0): - return linalg.svd(A, full_matrices) Modified: trunk/numpy/oldnumeric/__init__.py =================================================================== --- trunk/numpy/oldnumeric/__init__.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/oldnumeric/__init__.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,33 +1,25 @@ +# Don't add these to the __all__ variable from numpy import * + +# Add these from compat import * from olddefaults import * -from typeconv import * from functions import * -import numpy import compat import olddefaults -import typeconv import functions +import numpy __version__ = numpy.__version__ +del numpy __all__ = ['__version__'] -__all__ += numpy.__all__ __all__ += compat.__all__ -__all__ += typeconv.__all__ -for name in olddefaults.__all__: - if name not in __all__: - __all__.append(name) - -for name in functions.__all__: - if name not in __all__: - __all__.apend(name) +__all__ += olddefaults.__all__ +__all__ += functions.__all__ -del name -del numpy del compat del olddefaults del functions -del typeconv Modified: trunk/numpy/oldnumeric/compat.py =================================================================== --- trunk/numpy/oldnumeric/compat.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/oldnumeric/compat.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -54,7 +54,7 @@ # backward compatible names from old Precision.py -Character = 'S1' +Character = 'c' UnsignedInt8 = _dt_(nt.uint8) UInt8 = UnsignedInt8 UnsignedInt16 = _dt_(nt.uint16) Added: trunk/numpy/oldnumeric/linear_algebra.py =================================================================== --- trunk/numpy/oldnumeric/linear_algebra.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/oldnumeric/linear_algebra.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -0,0 +1,84 @@ + +"""Backward compatible with LinearAlgebra from Numeric +""" +# This module is a lite version of the linalg.py module in SciPy which contains +# high-level Python interface to the LAPACK library. The lite version +# only accesses the following LAPACK functions: dgesv, zgesv, dgeev, +# zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, dpotrf. + + +__all__ = ['LinAlgError', 'solve_linear_equations', + 'inverse', 'cholesky_decomposition', 'eigenvalues', + 'Heigenvalues', 'generalized_inverse', + 'determinant', 'singular_value_decomposition', + 'eigenvectors', 'Heigenvectors', + 'linear_least_squares' + ] + +from numpy.core import transpose +import numpy.linalg as linalg + +# Linear equations + +LinAlgError = linalg.LinAlgError + +def solve_linear_equations(a, b): + return linalg.solve(a,b) + +# Matrix inversion + +def inverse(a): + return linalg.inv(a) + +# Cholesky decomposition + +def cholesky_decomposition(a): + return linalg.cholesky(a) + +# Eigenvalues + +def eigenvalues(a): + return linalg.eigvals(a) + +def Heigenvalues(a, UPLO='L'): + return linalg.eigvalsh(a,UPLO) + +# Eigenvectors + +def eigenvectors(A): + w, v = linalg.eig(A) + return w, transpose(v) + +def Heigenvectors(A): + w, v = linalg.eigh(A) + return w, transpose(v) + +# Generalized inverse + +def generalized_inverse(a, rcond = 1.e-10): + return linalg.pinv(a, rcond) + +# Determinant + +def determinant(a): + return linalg.det(a) + +# Linear Least Squares + +def linear_least_squares(a, b, rcond=1.e-10): + """returns x,resids,rank,s +where x minimizes 2-norm(|b - Ax|) + resids is the sum square residuals + rank is the rank of A + s is the rank of the singular values of A in descending order + +If b is a matrix then x is also a matrix with corresponding columns. +If the rank of A is less than the number of columns of A or greater than +the number of rows, then residuals will be returned as an empty array +otherwise resids = sum((b-dot(A,x)**2). +Singular values less than s[0]*rcond are treated as zero. +""" + return linalg.lstsq(a,b,rcond) + +def singular_value_decomposition(A, full_matrices=0): + return linalg.svd(A, full_matrices) Copied: trunk/numpy/oldnumeric/mlab.py (from rev 2952, trunk/numpy/lib/mlab.py) =================================================================== --- trunk/numpy/lib/mlab.py 2006-08-04 18:47:25 UTC (rev 2952) +++ trunk/numpy/oldnumeric/mlab.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -0,0 +1,72 @@ +# This module is for compatibility only. All functions are defined elsewhere. + +from numpy.oldnumeric import * + +__all__ = numpy.oldnumeric.__all__ + +__all__ += ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] + +import linear_algebra as LinearAlgebra +import random_array as RandomArray +from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \ + angle, roots, ptp as _Nptp, kaiser, cumprod as _Ncumprod, \ + diag, msort, prod as _Nprod, std as _Nstd, hamming, flipud, \ + amax as _Nmax, amin as _Nmin, blackman, bartlett, corrcoef as _Ncorrcoef,\ + cov as _Ncov, squeeze, sinc, median, fliplr, mean as _Nmean + +from numpy.linalg import eig, svd +from numpy.random import rand, randn + +from typeconv import oldtype2dtype as o2d + +def eye(N, M=None, k=0, typecode=None): + """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, + and everything else is zeros. + """ + dtype = o2d[typecode] + if M is None: M = N + m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) + if m.dtype != dtype: + return m.astype(dtype) + +def tri(N, M=None, k=0, typecode=None): + """ returns a N-by-M array where all the diagonals starting from + lower left corner up to the k-th are all ones. + """ + dtype = o2d[typecode] + if M is None: M = N + m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) + if m.dtype != dtype: + return m.astype(dtype) + +def trapz(y, x=None, axis=-1): + return _Ntrapz(y, x, axis=axis) + +def ptp(x, axis=0): + return _Nptp(x, axis) + +def cumprod(x, axis=0): + return _Ncumprod(x, axis) + +def max(x, axis=0): + return _Nmax(x, axis) + +def min(x, axis=0): + return _Nmin(x, axis) + +def prod(x, axis=0): + return _Nprod(x, axis) + +def std(x, axis=0): + return _Nstd(x, axis) + +def mean(x, axis=0): + return _Nmean(x, axis) + +def cov(m, y=None, rowvar=0, bias=0): + return _Ncov(m, y, rowvar, bias) + +def corrcoef(x, y=None): + return _Ncorrcoef(x,y,0,0) + + Modified: trunk/numpy/oldnumeric/olddefaults.py =================================================================== --- trunk/numpy/oldnumeric/olddefaults.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/oldnumeric/olddefaults.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,45 +1,32 @@ -__all__ = ['ones', 'empty', 'identity', 'zeros', 'eye', 'tri'] +__all__ = ['ones', 'empty', 'identity', 'zeros'] import numpy.core.multiarray as mu import numpy.core.numeric as nn - -def ones(shape, dtype=int, order='C'): +from typeconv import convtypecode + +def ones(shape, typecode='l', savespace=0, dtype=None): """ones(shape, dtype=int) returns an array of the given dimensions which is initialized to all ones. """ - a = mu.empty(shape, dtype, order) + dtype = convtypecode(typecode,dtype) + a = mu.empty(shape, dtype) a.fill(1) return a -def zeros(shape, dtype=int, order='C'): +def zeros(shape, typecode='l', savespace=0, dtype=None): """zeros(shape, dtype=int) returns an array of the given dimensions which is initialized to all zeros """ - return mu.zeros(shape, dtype, order) + dtype = convtypecode(typecode,dtype) + return mu.zeros(shape, dtype) -def identity(n,dtype=int): +def identity(n,typecode='l', dtype=None): """identity(n) returns the identity 2-d array of shape n x n. """ + dtype = convtypecode(typecode, dtype) return nn.identity(n, dtype) -def eye(N, M=None, k=0, dtype=int): - """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, - and everything else is zeros. - """ - if M is None: M = N - m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) - if m.dtype != dtype: - return m.astype(dtype) - -def tri(N, M=None, k=0, dtype=int): - """ returns a N-by-M array where all the diagonals starting from - lower left corner up to the k-th are all ones. - """ - if M is None: M = N - m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) - if m.dtype != dtype: - return m.astype(dtype) - -def empty(shape, dtype=int, order='C'): +def empty(shape, typecode='l', dtype=None): + dtype = convtypecode(typecode, dtype) return mu.empty(shape, dtype, order) Added: trunk/numpy/oldnumeric/random_array.py =================================================================== --- trunk/numpy/oldnumeric/random_array.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/oldnumeric/random_array.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -0,0 +1,268 @@ +# Backward compatible module for RandomArray + +__all__ = ['ArgumentError','F','beta','binomial','chi_square', 'exponential', 'gamma', 'get_seed', + 'mean_var_test', 'multinomial', 'multivariate_normal', 'negative_binomial', + 'noncentral_F', 'noncentral_chi_square', 'normal', 'permutation', 'poisson', 'randint', + 'random', 'random_integers', 'seed', 'standard_normal', 'uniform'] + +ArgumentError = ValueError + +import numpy.random.mtrand as mt +import numpy as Numeric + +from types import IntType + +def seed(x=0, y=0): + if (x == 0 or y == 0): + mt.seed() + else: + mt.seed((x,y)) + +def get_seed(): + raise NotImplementedError, \ + "If you want to save the state of the random number generator.\n"\ + "Then you should use obj = numpy.random.get_state() followed by.\n"\ + "numpy.random.set_state(obj)." + +def random(shape=[]): + "random(n) or random([n, m, ...]) returns array of random numbers" + if shape == []: + shape = None + return mt.random_sample(shape) + +def uniform(minimum, maximum, shape=[]): + """uniform(minimum, maximum, shape=[]) returns array of given shape of random reals + in given range""" + if shape == []: + shape = None + return mt.uniform(minimum, maximum, shape) + +def randint(minimum, maximum=None, shape=[]): + """randint(min, max, shape=[]) = random integers >=min, < max + If max not given, random integers >= 0, = 0.6: + raise SystemExit, "uniform returned out of desired range" + print "randint(1, 10, shape=[50])" + print randint(1, 10, shape=[50]) + print "permutation(10)", permutation(10) + print "randint(3,9)", randint(3,9) + print "random_integers(10, shape=[20])" + print random_integers(10, shape=[20]) + s = 3.0 + x = normal(2.0, s, [10, 1000]) + if len(x.shape) != 2 or x.shape[0] != 10 or x.shape[1] != 1000: + raise SystemExit, "standard_normal returned wrong shape" + x.shape = (10000,) + mean_var_test(x, "normally distributed numbers with mean 2 and variance %f"%(s**2,), 2, s**2, 0) + x = exponential(3, 10000) + mean_var_test(x, "random numbers exponentially distributed with mean %f"%(s,), s, s**2, 2) + x = multivariate_normal(Numeric.array([10,20]), Numeric.array(([1,2],[2,4]))) + print "\nA multivariate normal", x + if x.shape != (2,): raise SystemExit, "multivariate_normal returned wrong shape" + x = multivariate_normal(Numeric.array([10,20]), Numeric.array([[1,2],[2,4]]), [4,3]) + print "A 4x3x2 array containing multivariate normals" + print x + if x.shape != (4,3,2): raise SystemExit, "multivariate_normal returned wrong shape" + x = multivariate_normal(Numeric.array([-100,0,100]), Numeric.array([[3,2,1],[2,2,1],[1,1,1]]), 10000) + x_mean = Numeric.sum(x)/10000. + print "Average of 10000 multivariate normals with mean [-100,0,100]" + print x_mean + x_minus_mean = x - x_mean + print "Estimated covariance of 10000 multivariate normals with covariance [[3,2,1],[2,2,1],[1,1,1]]" + print Numeric.dot(Numeric.transpose(x_minus_mean),x_minus_mean)/9999. + x = beta(5.0, 10.0, 10000) + mean_var_test(x, "beta(5.,10.) random numbers", 0.333, 0.014) + x = gamma(.01, 2., 10000) + mean_var_test(x, "gamma(.01,2.) random numbers", 2*100, 2*100*100) + x = chi_square(11., 10000) + mean_var_test(x, "chi squared random numbers with 11 degrees of freedom", 11, 22, 2*Numeric.sqrt(2./11.)) + x = F(5., 10., 10000) + mean_var_test(x, "F random numbers with 5 and 10 degrees of freedom", 1.25, 1.35) + x = poisson(50., 10000) + mean_var_test(x, "poisson random numbers with mean 50", 50, 50, 0.14) + print "\nEach element is the result of 16 binomial trials with probability 0.5:" + print binomial(16, 0.5, 16) + print "\nEach element is the result of 16 negative binomial trials with probability 0.5:" + print negative_binomial(16, 0.5, [16,]) + print "\nEach row is the result of 16 multinomial trials with probabilities [0.1, 0.5, 0.1 0.3]:" + x = multinomial(16, [0.1, 0.5, 0.1], 8) + print x + print "Mean = ", Numeric.sum(x)/8. + +if __name__ == '__main__': + test() + + Added: trunk/numpy/oldnumeric/rng.py =================================================================== --- trunk/numpy/oldnumeric/rng.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/oldnumeric/rng.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -0,0 +1,137 @@ +# This module re-creates the RNG interface from Numeric +# Replace import RNG with import numpy.oldnumeric.rng as RNG +# +# It is for backwards compatibility only. + + +__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution','NormalDistribution', + 'UniformDistribution', 'error', 'default_distribution', 'random_sample', 'ranf', + 'standard_generator'] + +import numpy.random.mtrand as mt +import math + +class error(Exception): + pass + +class Distribution(object): + def __init__(self, meth, *args): + self._meth = meth + self._args = args + + def density(self,x): + raise NotImplementedError + + def __call__(self, x): + return self.density(x) + + def _onesample(self, rng): + return getattr(rng, self._meth)(*self._args) + + def _sample(self, rng, n): + kwds = {'size' : n} + return getattr(rng, self._meth)(*self._args, **kwds) + + +class ExponentialDistribution(Distribution): + def __init__(self, lambda_): + if (lambda_ <= 0): + raise error, "parameter must be positive" + Distribution.__init__(self, 'exponential', lambda_) + + def density(x): + if x < 0: + return 0.0 + else: + lambda_ = self._args[0] + return lambda_*exp(-lambda_*x) + +class LogNormalDistribution(Distribution): + def __init__(self, m, s): + m = float(m) + s = float(s) + if (s <= 0): + raise error, "standard deviation must be positive" + Distribution.__init__(self, 'lognormal', m, s) + sn = math.log(1.0+s*s/(m*m)); + self._mn = math.log(m)-0.5*sn + self._sn = math.sqrt(sn) + self._fac = 1.0/math.sqrt(2*math.pi)/self._sn + + def density(x): + m,s = self._args + y = (math.log(x)-self._mn)/self._sn + return self._fac*exp(-0.5*y*y)/x + + +class NormalDistribution(Distribution): + def __init__(self, m, s): + m = float(m) + s = float(s) + if (s <= 0): + raise error, "standard deviation must be positive" + Distribution.__init__(self, 'normal', m, s) + self._fac = 1.0/math.sqrt(2*math.pi)/s + + def density(x): + m,s = self._args + y = (x-m)/s + return self._fac*exp(-0.5*y*y) + +class UniformDistribution(Distribution): + def __init__(self, a, b): + a = float(a) + b = float(b) + width = b-a + if (width <=0): + raise error, "width of uniform distribution must be > 0" + Distribution.__init__(self, 'uniform', a, b) + self._fac = 1.0/width + + def density(x): + a, b = self._args + if (x < a) or (x >= b): + return 0.0 + else: + return self._fac + +default_distribution = UniformDistribution(0.0,1.0) + +class CreateGenerator(object): + def __init__(self, seed, dist=None): + if seed <= 0: + self._rng = mt.RandomState() + elif seed > 0: + self._rng = mt.RandomState(seed) + if dist is None: + dist = default_distribution + if not isinstance(dist, Distribution): + raise error, "Not a distribution object" + self._dist = dist + + def ranf(self): + return self._dist._onesample(self._rng) + + def sample(self, n): + return self._dist._sample(self._rng, n) + + +standard_generator = CreateGenerator(-1) + +def ranf(): + "ranf() = a random number from the standard generator." + return standard_generator.ranf() + +def random_sample(*n): + """random_sample(n) = array of n random numbers; + + random_sample(n1, n2, ...)= random array of shape (n1, n2, ..)""" + + if not n: + return standard_generator.ranf() + m = 1 + for i in n: + m = m * i + return standard_generator.sample(m).reshape(*n) + + Added: trunk/numpy/oldnumeric/rng_stats.py =================================================================== --- trunk/numpy/oldnumeric/rng_stats.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/oldnumeric/rng_stats.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -0,0 +1,35 @@ + +__all__ = ['average', 'histogram', 'standardDeviation', 'variance'] + +import numpy.oldnumeric as Numeric + +def average(data): + data = Numeric.array(data) + return Numeric.add.reduce(data)/len(data) + +def variance(data): + data = Numeric.array(data) + return Numeric.add.reduce((data-average(data))**2)/(len(data)-1) + +def standardDeviation(data): + data = Numeric.array(data) + return Numeric.sqrt(variance(data)) + +def histogram(data, nbins, range = None): + data = Numeric.array(data, Numeric.Float) + if range is None: + min = Numeric.minimum.reduce(data) + max = Numeric.maximum.reduce(data) + else: + min, max = range + data = Numeric.repeat(data, + Numeric.logical_and(Numeric.less_equal(data, max), + Numeric.greater_equal(data, + min))) + bin_width = (max-min)/nbins + data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int) + histo = Numeric.add.reduce(Numeric.equal( + Numeric.arange(nbins)[:,Numeric.NewAxis], data), -1) + histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data)) + bins = min + bin_width*(Numeric.arange(nbins)+0.5) + return Numeric.transpose(Numeric.array([bins, histo])) Deleted: trunk/numpy/random/old.py =================================================================== --- trunk/numpy/random/old.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/random/old.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,267 +0,0 @@ - -__all__ = ['ArgumentError','F','beta','binomial','chi_square', 'exponential', 'gamma', 'get_seed', - 'mean_var_test', 'multinomial', 'multivariate_normal', 'negative_binomial', - 'noncentral_F', 'noncentral_chi_square', 'normal', 'permutation', 'poisson', 'randint', - 'random', 'random_integers', 'seed', 'standard_normal', 'uniform'] - -ArgumentError = ValueError - -import numpy.random.mtrand as mt -import numpy as Numeric - -from types import IntType - -def seed(x=0, y=0): - if (x == 0 or y == 0): - mt.seed() - else: - mt.seed((x,y)) - -def get_seed(): - raise NotImplementedError, \ - "If you want to save the state of the random number generator.\n"\ - "Then you should use obj = numpy.random.get_state() followed by.\n"\ - "numpy.random.set_state(obj)." - -def random(shape=[]): - "random(n) or random([n, m, ...]) returns array of random numbers" - if shape == []: - shape = None - return mt.random_sample(shape) - -def uniform(minimum, maximum, shape=[]): - """uniform(minimum, maximum, shape=[]) returns array of given shape of random reals - in given range""" - if shape == []: - shape = None - return mt.uniform(minimum, maximum, shape) - -def randint(minimum, maximum=None, shape=[]): - """randint(min, max, shape=[]) = random integers >=min, < max - If max not given, random integers >= 0, = 0.6: - raise SystemExit, "uniform returned out of desired range" - print "randint(1, 10, shape=[50])" - print randint(1, 10, shape=[50]) - print "permutation(10)", permutation(10) - print "randint(3,9)", randint(3,9) - print "random_integers(10, shape=[20])" - print random_integers(10, shape=[20]) - s = 3.0 - x = normal(2.0, s, [10, 1000]) - if len(x.shape) != 2 or x.shape[0] != 10 or x.shape[1] != 1000: - raise SystemExit, "standard_normal returned wrong shape" - x.shape = (10000,) - mean_var_test(x, "normally distributed numbers with mean 2 and variance %f"%(s**2,), 2, s**2, 0) - x = exponential(3, 10000) - mean_var_test(x, "random numbers exponentially distributed with mean %f"%(s,), s, s**2, 2) - x = multivariate_normal(Numeric.array([10,20]), Numeric.array(([1,2],[2,4]))) - print "\nA multivariate normal", x - if x.shape != (2,): raise SystemExit, "multivariate_normal returned wrong shape" - x = multivariate_normal(Numeric.array([10,20]), Numeric.array([[1,2],[2,4]]), [4,3]) - print "A 4x3x2 array containing multivariate normals" - print x - if x.shape != (4,3,2): raise SystemExit, "multivariate_normal returned wrong shape" - x = multivariate_normal(Numeric.array([-100,0,100]), Numeric.array([[3,2,1],[2,2,1],[1,1,1]]), 10000) - x_mean = Numeric.sum(x)/10000. - print "Average of 10000 multivariate normals with mean [-100,0,100]" - print x_mean - x_minus_mean = x - x_mean - print "Estimated covariance of 10000 multivariate normals with covariance [[3,2,1],[2,2,1],[1,1,1]]" - print Numeric.dot(Numeric.transpose(x_minus_mean),x_minus_mean)/9999. - x = beta(5.0, 10.0, 10000) - mean_var_test(x, "beta(5.,10.) random numbers", 0.333, 0.014) - x = gamma(.01, 2., 10000) - mean_var_test(x, "gamma(.01,2.) random numbers", 2*100, 2*100*100) - x = chi_square(11., 10000) - mean_var_test(x, "chi squared random numbers with 11 degrees of freedom", 11, 22, 2*Numeric.sqrt(2./11.)) - x = F(5., 10., 10000) - mean_var_test(x, "F random numbers with 5 and 10 degrees of freedom", 1.25, 1.35) - x = poisson(50., 10000) - mean_var_test(x, "poisson random numbers with mean 50", 50, 50, 0.14) - print "\nEach element is the result of 16 binomial trials with probability 0.5:" - print binomial(16, 0.5, 16) - print "\nEach element is the result of 16 negative binomial trials with probability 0.5:" - print negative_binomial(16, 0.5, [16,]) - print "\nEach row is the result of 16 multinomial trials with probabilities [0.1, 0.5, 0.1 0.3]:" - x = multinomial(16, [0.1, 0.5, 0.1], 8) - print x - print "Mean = ", Numeric.sum(x)/8. - -if __name__ == '__main__': - test() - - Deleted: trunk/numpy/random/oldrng.py =================================================================== --- trunk/numpy/random/oldrng.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/random/oldrng.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,136 +0,0 @@ -# This module re-creates the RNG interface from Numeric -# Replace import RNG with import numpy.random.oldrng as RNG -# -# It is for backwards compatibility only. - - -__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution','NormalDistribution', - 'UniformDistribution', 'error', 'default_distribution', 'random_sample', 'ranf', - 'standard_generator'] - -import numpy.random.mtrand as mt -import math - -class error(Exception): - pass - -class Distribution(object): - def __init__(self, meth, *args): - self._meth = meth - self._args = args - - def density(self,x): - raise NotImplementedError - - def __call__(self, x): - return self.density(x) - - def _onesample(self, rng): - return getattr(rng, self._meth)(*self._args) - - def _sample(self, rng, n): - kwds = {'size' : n} - return getattr(rng, self._meth)(*self._args, **kwds) - - -class ExponentialDistribution(Distribution): - def __init__(self, lambda_): - if (lambda_ <= 0): - raise error, "parameter must be positive" - Distribution.__init__(self, 'exponential', lambda_) - - def density(x): - if x < 0: - return 0.0 - else: - lambda_ = self._args[0] - return lambda_*exp(-lambda_*x) - -class LogNormalDistribution(Distribution): - def __init__(self, m, s): - m = float(m) - s = float(s) - if (s <= 0): - raise error, "standard deviation must be positive" - Distribution.__init__(self, 'lognormal', m, s) - sn = math.log(1.0+s*s/(m*m)); - self._mn = math.log(m)-0.5*sn - self._sn = math.sqrt(sn) - self._fac = 1.0/math.sqrt(2*math.pi)/self._sn - - def density(x): - m,s = self._args - y = (math.log(x)-self._mn)/self._sn - return self._fac*exp(-0.5*y*y)/x - - -class NormalDistribution(Distribution): - def __init__(self, m, s): - m = float(m) - s = float(s) - if (s <= 0): - raise error, "standard deviation must be positive" - Distribution.__init__(self, 'normal', m, s) - self._fac = 1.0/math.sqrt(2*math.pi)/s - - def density(x): - m,s = self._args - y = (x-m)/s - return self._fac*exp(-0.5*y*y) - -class UniformDistribution(Distribution): - def __init__(self, a, b): - a = float(a) - b = float(b) - width = b-a - if (width <=0): - raise error, "width of uniform distribution must be > 0" - Distribution.__init__(self, 'uniform', a, b) - self._fac = 1.0/width - - def density(x): - a, b = self._args - if (x < a) or (x >= b): - return 0.0 - else: - return self._fac - -default_distribution = UniformDistribution(0.0,1.0) - -class CreateGenerator(object): - def __init__(self, seed, dist=None): - if seed <= 0: - self._rng = mt.RandomState() - elif seed > 0: - self._rng = mt.RandomState(seed) - if dist is None: - dist = default_distribution - if not isinstance(dist, Distribution): - raise error, "Not a distribution object" - self._dist = dist - - def ranf(self): - return self._dist._onesample(self._rng) - - def sample(self, n): - return self._dist._sample(self._rng, n) - - -standard_generator = CreateGenerator(-1) - -def ranf(): - "ranf() = a random number from the standard generator." - return standard_generator.ranf() - -def random_sample(*n): - """random_sample(n) = array of n random numbers; - - random_sample(n1, n2, ...)= random array of shape (n1, n2, ..)""" - - if not n: - return standard_generator.ranf() - m = 1 - for i in n: - m = m * i - return standard_generator.sample(m).reshape(*n) - Deleted: trunk/numpy/random/oldrngstats.py =================================================================== --- trunk/numpy/random/oldrngstats.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/random/oldrngstats.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -1,35 +0,0 @@ - -__all__ = ['average', 'histogram', 'standardDeviation', 'variance'] - -import numpy.oldnumeric as Numeric - -def average(data): - data = Numeric.array(data) - return Numeric.add.reduce(data)/len(data) - -def variance(data): - data = Numeric.array(data) - return Numeric.add.reduce((data-average(data))**2)/(len(data)-1) - -def standardDeviation(data): - data = Numeric.array(data) - return Numeric.sqrt(variance(data)) - -def histogram(data, nbins, range = None): - data = Numeric.array(data, Numeric.Float) - if range is None: - min = Numeric.minimum.reduce(data) - max = Numeric.maximum.reduce(data) - else: - min, max = range - data = Numeric.repeat(data, - Numeric.logical_and(Numeric.less_equal(data, max), - Numeric.greater_equal(data, - min))) - bin_width = (max-min)/nbins - data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int) - histo = Numeric.add.reduce(Numeric.equal( - Numeric.arange(nbins)[:,Numeric.NewAxis], data), -1) - histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data)) - bins = min + bin_width*(Numeric.arange(nbins)+0.5) - return Numeric.transpose(Numeric.array([bins, histo])) Modified: trunk/numpy/setup.py =================================================================== --- trunk/numpy/setup.py 2006-08-04 20:54:57 UTC (rev 2953) +++ trunk/numpy/setup.py 2006-08-04 23:32:12 UTC (rev 2954) @@ -11,6 +11,7 @@ config.add_subpackage('oldnumeric') config.add_subpackage('numarray') config.add_subpackage('dft') + config.add_subpackage('fft') config.add_subpackage('linalg') config.add_subpackage('random') config.add_data_dir('doc') From numpy-svn at scipy.org Fri Aug 4 19:35:05 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 18:35:05 -0500 (CDT) Subject: [Numpy-svn] r2955 - trunk/numpy/lib Message-ID: <20060804233505.2545239C010@new.scipy.org> Author: oliphant Date: 2006-08-04 18:35:03 -0500 (Fri, 04 Aug 2006) New Revision: 2955 Added: trunk/numpy/lib/UserArray.py Log: Add back a compatibility UserArray. Added: trunk/numpy/lib/UserArray.py =================================================================== --- trunk/numpy/lib/UserArray.py 2006-08-04 23:32:12 UTC (rev 2954) +++ trunk/numpy/lib/UserArray.py 2006-08-04 23:35:03 UTC (rev 2955) @@ -0,0 +1,3 @@ +from user_array import container as UserArray +import warnings +warnings.warn('UserArray.UserArray is deprecated use user_array.container') From numpy-svn at scipy.org Fri Aug 4 19:38:30 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 18:38:30 -0500 (CDT) Subject: [Numpy-svn] r2956 - in trunk/numpy: . dft lib Message-ID: <20060804233830.22CF239C010@new.scipy.org> Author: oliphant Date: 2006-08-04 18:38:27 -0500 (Fri, 04 Aug 2006) New Revision: 2956 Added: trunk/numpy/dft/ trunk/numpy/dft/__init__.py Modified: trunk/numpy/lib/UserArray.py Log: Add back dft stub and alter warning. Added: trunk/numpy/dft/__init__.py =================================================================== --- trunk/numpy/dft/__init__.py 2006-08-04 23:35:03 UTC (rev 2955) +++ trunk/numpy/dft/__init__.py 2006-08-04 23:38:27 UTC (rev 2956) @@ -0,0 +1,4 @@ +import warnings +warnings.warn("The dft subpackage will be removed by 1.0 final -- it is now called fft") +from numpy.fft import * +del warnings Modified: trunk/numpy/lib/UserArray.py =================================================================== --- trunk/numpy/lib/UserArray.py 2006-08-04 23:35:03 UTC (rev 2955) +++ trunk/numpy/lib/UserArray.py 2006-08-04 23:38:27 UTC (rev 2956) @@ -1,3 +1,3 @@ from user_array import container as UserArray import warnings -warnings.warn('UserArray.UserArray is deprecated use user_array.container') +warnings.warn('UserArray.UserArray will be removed by 1.0final use user_array.container') From numpy-svn at scipy.org Fri Aug 4 21:21:04 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 20:21:04 -0500 (CDT) Subject: [Numpy-svn] r2957 - trunk/numpy/oldnumeric Message-ID: <20060805012104.2219339C010@new.scipy.org> Author: oliphant Date: 2006-08-04 20:20:56 -0500 (Fri, 04 Aug 2006) New Revision: 2957 Added: trunk/numpy/oldnumeric/array_printer.py trunk/numpy/oldnumeric/functions.py trunk/numpy/oldnumeric/ma.py trunk/numpy/oldnumeric/matrix.py trunk/numpy/oldnumeric/misc.py trunk/numpy/oldnumeric/precision.py trunk/numpy/oldnumeric/typeconv.py trunk/numpy/oldnumeric/ufuncs.py trunk/numpy/oldnumeric/user_array.py Removed: trunk/numpy/oldnumeric/olddefaults.py Modified: trunk/numpy/oldnumeric/__init__.py trunk/numpy/oldnumeric/compat.py Log: More fixes to backward compatibility Modified: trunk/numpy/oldnumeric/__init__.py =================================================================== --- trunk/numpy/oldnumeric/__init__.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/__init__.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -2,14 +2,26 @@ # Don't add these to the __all__ variable from numpy import * +def _move_axis_to_0(a, axis): + if axis == 0: + return a + n = len(a.shape) + if axis < 0: + axis += n + axes = range(1, axis+1) + [0,] + range(axis+1, n) + return transpose(a, axes) + # Add these from compat import * -from olddefaults import * from functions import * +from precision import * +from ufuncs import * import compat -import olddefaults +import precision import functions +import misc +import ufuncs import numpy __version__ = numpy.__version__ @@ -17,9 +29,13 @@ __all__ = ['__version__'] __all__ += compat.__all__ -__all__ += olddefaults.__all__ +__all__ += precision.__all__ __all__ += functions.__all__ +__all__ += ufuncs.__all__ +__all__ += misc.__all__ del compat -del olddefaults del functions +del precision +del ufuncs +del misc Added: trunk/numpy/oldnumeric/array_printer.py =================================================================== --- trunk/numpy/oldnumeric/array_printer.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/array_printer.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,16 @@ + +__all__ = ['array2string'] + +from numpy import array2string as _array2string + +def array2string(a, max_line_width=None, precision=None, + suppress_small=None, separator=' ', + array_output=0): + if array_output: + prefix="array(" + style=repr + else: + prefix = "" + style=str + return _array2string(a, max_line_width, precision, + suppress_small, separator, prefix, style) Modified: trunk/numpy/oldnumeric/compat.py =================================================================== --- trunk/numpy/oldnumeric/compat.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/compat.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -2,15 +2,7 @@ __all__ = ['NewAxis', 'UFuncType', 'UfuncType', 'ArrayType', 'arraytype', - 'LittleEndian', 'Bool', - 'Character', 'UnsignedInt8', 'UnsignedInt16', 'UnsignedInt', 'UInt', - 'UInt8','UInt16','UInt32', 'UnsignedInt32', 'UnsignedInteger', - # UnsignedInt64 and Unsigned128 added below if possible - # same for Int64 and Int128, Float128, and Complex128 - 'Int8', 'Int16', 'Int32', - 'Int0', 'Int', 'Float0', 'Float', 'Complex0', 'Complex', - 'PyObject', 'Float32', 'Float64', 'Float16', 'Float8', - 'Complex32', 'Complex64', 'Complex8', 'Complex16', + 'LittleEndian', 'sarray', 'arrayrange', 'cross_correlate', 'matrixmultiply', 'outerproduct', 'innerproduct', 'cross_product', 'array_constructor', @@ -19,26 +11,20 @@ 'dump', 'dumps' ] - -import numpy.core.multiarray as mu +import numpy.core.multiarray as multiarray import numpy.core.umath as um -import numpy.core.numerictypes as nt -from numpy.core.numeric import asarray, array, asanyarray, \ - correlate, outer, concatenate, cross +from numpy.core.numeric import array, correlate, outer, cross from numpy.core.umath import sign, absolute, multiply -import numpy.core.numeric as _nx import sys -_dt_ = nt.sctype2char import types from cPickle import dump, dumps -multiarray = mu - def sarray(a, dtype=None, copy=False): return array(a, dtype, copy) +mu = multiarray #Use this to add a new axis to an array #compatibility only @@ -52,86 +38,6 @@ LittleEndian = (sys.byteorder == 'little') -# backward compatible names from old Precision.py - -Character = 'c' -UnsignedInt8 = _dt_(nt.uint8) -UInt8 = UnsignedInt8 -UnsignedInt16 = _dt_(nt.uint16) -UInt16 = UnsignedInt16 -UnsignedInt32 = _dt_(nt.uint32) -UInt32 = UnsignedInt32 -UnsignedInt = _dt_(nt.uint) -UInt = UnsignedInt - -try: - UnsignedInt64 = _dt_(nt.uint64) -except AttributeError: - pass -else: - UInt64 = UnsignedInt64 - __all__ += ['UnsignedInt64', 'UInt64'] -try: - UnsignedInt128 = _dt_(nt.uint128) -except AttributeError: - pass -else: - UInt128 = UnsignedInt128 - __all__ += ['UnsignedInt128','UInt128'] - -Int8 = _dt_(nt.int8) -Int16 = _dt_(nt.int16) -Int32 = _dt_(nt.int32) - -try: - Int64 = _dt_(nt.int64) -except AttributeError: - pass -else: - __all__ += ['Int64'] - -try: - Int128 = _dt_(nt.int128) -except AttributeError: - pass -else: - __all__ += ['Int128'] - -Bool = _dt_(bool) -Int0 = _dt_(int) -Int = _dt_(int) -Float0 = _dt_(float) -Float = _dt_(float) -Complex0 = _dt_(complex) -Complex = _dt_(complex) -PyObject = _dt_(nt.object_) -Float32 = _dt_(nt.float32) -Float64 = _dt_(nt.float64) - -Float16='f' -Float8='f' -UnsignedInteger='L' -Complex8='F' -Complex16='F' - -try: - Float128 = _dt_(nt.float128) -except AttributeError: - pass -else: - __all__ += ['Float128'] - -Complex32 = _dt_(nt.complex64) -Complex64 = _dt_(nt.complex128) - -try: - Complex128 = _dt_(nt.complex256) -except AttributeError: - pass -else: - __all__ += ['Complex128'] - - from numpy import deprecate # backward compatibility Added: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/functions.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,62 @@ +# Functions that should behave the same as Numeric + +import numpy as N +import numpy.core.multiarray as mu +import numpy.core.numeric as nn +from typeconv import convtypecode + +__all__ = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', + 'cumsum', 'cumproduct'] +__all__ += ['ones', 'empty', 'identity', 'zeros'] + +def take(a, indicies, axis=0): + return N.take(a, indicies, axis) + +def repeat(a, repeats, axis=0): + return N.repeats(a, repeats, axis) + +def sum(x, axis=0): + return N.sum(x, axis) + +def product(x, axis=0): + return N.product(x, axis) + +def sometrue(x, axis=0): + return N.sometrue(x, axis) + +def alltrue(x, axis=0): + return N.alltrue(x, axis) + +def cumsum(x, axis=0): + return N.cumsum(x, axis) + +def cumproduct(x, axis=0): + return N.cumproduct(x, axis) + + +def ones(shape, typecode='l', savespace=0, dtype=None): + """ones(shape, dtype=int) returns an array of the given + dimensions which is initialized to all ones. + """ + dtype = convtypecode(typecode,dtype) + a = mu.empty(shape, dtype) + a.fill(1) + return a + +def zeros(shape, typecode='l', savespace=0, dtype=None): + """zeros(shape, dtype=int) returns an array of the given + dimensions which is initialized to all zeros + """ + dtype = convtypecode(typecode,dtype) + return mu.zeros(shape, dtype) + +def identity(n,typecode='l', dtype=None): + """identity(n) returns the identity 2-d array of shape n x n. + """ + dtype = convtypecode(typecode, dtype) + return nn.identity(n, dtype) + +def empty(shape, typecode='l', dtype=None): + dtype = convtypecode(typecode, dtype) + return mu.empty(shape, dtype, order) + Added: trunk/numpy/oldnumeric/ma.py =================================================================== --- trunk/numpy/oldnumeric/ma.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/ma.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,11 @@ + +from numpy.core.ma import getmask as _getmask, nomask as _nomask +from numpy.core.ma import * + +del getmask, nomask + +def getmask(a): + res = _getmask(a) + if res is _nomask: + return None + return res Added: trunk/numpy/oldnumeric/matrix.py =================================================================== --- trunk/numpy/oldnumeric/matrix.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/matrix.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,70 @@ +# This module is for compatibility only. + +__all__ = ['UserArray', 'squeeze', 'Matrix', 'asarray', 'dot', 'k', 'Numeric', 'LinearAlgebra', 'identity', 'multiply', 'types', 'string'] + +import string +import types +import numpy.oldnumeric as Numeric +from user_array import UserArray, asarray +from numpy.oldnumeric import dot, identity, multiply +from mlab import squeeze +import linear_algebra as LinearAlgebra + +from numpy import matrix as Matrix + +# Hidden names that will be the same. + +_table = [None]*256 +for k in range(256): + _table[k] = chr(k) +_table = ''.join(_table) + +_numchars = string.digits + ".-+jeEL" +_todelete = [] +for k in _table: + if k not in _numchars: + _todelete.append(k) +_todelete = ''.join(_todelete) + + +def _eval(astr): + return eval(astr.translate(_table,_todelete)) + +def _convert_from_string(data): + data.find + rows = data.split(';') + newdata = [] + count = 0 + for row in rows: + trow = row.split(',') + newrow = [] + for col in trow: + temp = col.split() + newrow.extend(map(_eval,temp)) + if count == 0: + Ncols = len(newrow) + elif len(newrow) != Ncols: + raise ValueError, "Rows not the same size." + count += 1 + newdata.append(newrow) + return newdata + + +_lkup = {'0':'000', + '1':'001', + '2':'010', + '3':'011', + '4':'100', + '5':'101', + '6':'110', + '7':'111'} + +def _binary(num): + ostr = oct(num) + bin = '' + for ch in ostr[1:]: + bin += _lkup[ch] + ind = 0 + while bin[ind] == '0': + ind += 1 + return bin[ind:] Added: trunk/numpy/oldnumeric/misc.py =================================================================== --- trunk/numpy/oldnumeric/misc.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/misc.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,3 @@ + + +__all__ = ['load', 'sort', 'copy_reg', 'clip', 'putmask', 'Unpickler', 'rank', 'sign', 'shape', 'types', 'array', 'allclose', 'size', 'nonzero', 'asarray', 'reshape', 'argmax', 'choose', 'swapaxes', 'array_str', 'pi', 'ravel', 'math', 'compress', 'concatenate', 'pickle_array', 'around', 'trace', 'vdot', 'transpose', 'array2string', 'diagonal', 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', 'array_repr', 'e', 'argmin', 'StringIO', 'pickle', 'average', 'arange', 'argsort', 'convolve', 'fromstring', 'indices', 'loads', 'Pickler', 'where', 'dot'] Deleted: trunk/numpy/oldnumeric/olddefaults.py =================================================================== --- trunk/numpy/oldnumeric/olddefaults.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/olddefaults.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -1,32 +0,0 @@ -__all__ = ['ones', 'empty', 'identity', 'zeros'] - -import numpy.core.multiarray as mu -import numpy.core.numeric as nn -from typeconv import convtypecode - -def ones(shape, typecode='l', savespace=0, dtype=None): - """ones(shape, dtype=int) returns an array of the given - dimensions which is initialized to all ones. - """ - dtype = convtypecode(typecode,dtype) - a = mu.empty(shape, dtype) - a.fill(1) - return a - -def zeros(shape, typecode='l', savespace=0, dtype=None): - """zeros(shape, dtype=int) returns an array of the given - dimensions which is initialized to all zeros - """ - dtype = convtypecode(typecode,dtype) - return mu.zeros(shape, dtype) - -def identity(n,typecode='l', dtype=None): - """identity(n) returns the identity 2-d array of shape n x n. - """ - dtype = convtypecode(typecode, dtype) - return nn.identity(n, dtype) - -def empty(shape, typecode='l', dtype=None): - dtype = convtypecode(typecode, dtype) - return mu.empty(shape, dtype, order) - Added: trunk/numpy/oldnumeric/precision.py =================================================================== --- trunk/numpy/oldnumeric/precision.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/precision.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,167 @@ +# Lifted from Precision.py. This is for compatibility only. Notice that the +# capitalized names have their old character strings + +__all__ = ['Character', 'Complex', 'Float', + 'PrecisionError', 'PyObject', 'Int', 'UInt', + 'UnsignedInteger', 'string', 'typecodes', 'zeros'] + +import string +from olddefaults import zeros + +typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', 'Float':'fd', 'Complex':'FD'} + +def _get_precisions(typecodes): + lst = [] + for t in typecodes: + lst.append( (zeros( (1,), t ).itemsize*8, t) ) + return lst + +def _fill_table(typecodes, table={}): + for key, value in typecodes.items(): + table[key] = _get_precisions(value) + return table + +_code_table = _fill_table(typecodes) + +class PrecisionError(Exception): + pass + +def _lookup(table, key, required_bits): + lst = table[key] + for bits, typecode in lst: + if bits >= required_bits: + return typecode + raise PrecisionError, key+" of "+str(required_bits)+" bits not available on this system" + +Character = 'c' + +try: + UnsignedInt8 = _lookup(_code_table, "UnsignedInteger", 8) + UInt8 = UnsignedInt8 + __all__.extend(['UnsignedInt8', 'UInt8']) +except(PrecisionError): + pass +try: + UnsignedInt16 = _lookup(_code_table, "UnsignedInteger", 16) + UInt16 = UnsignedInt16 + __all__.extend(['UnsignedInt16', 'UInt16']) +except(PrecisionError): + pass +try: + UnsignedInt32 = _lookup(_code_table, "UnsignedInteger", 32) + UInt32 = UnsignedInt32 + __all__.extend(['UnsignedInt32', 'UInt32']) +except(PrecisionError): + pass +try: + UnsignedInt64 = _lookup(_code_table, "UnsignedInteger", 64) + UInt64 = UnsignedInt64 + __all__.extend(['UnsignedInt64', 'UInt64']) +except(PrecisionError): + pass +try: + UnsignedInt128 = _lookup(_code_table, "UnsignedInteger", 128) + UInt128 = UnsignedInt128 + __all__.extend(['UnsignedInt128', 'UInt128']) +except(PrecisionError): + pass +UnsignedInteger = 'u' +UInt = UnsignedInteger + +try: + Int0 = _lookup(_code_table, 'Integer', 0) + __all__.append('Int0') +except(PrecisionError): + pass +try: + Int8 = _lookup(_code_table, 'Integer', 8) + __all__.append('Int8') +except(PrecisionError): + pass +try: + Int16 = _lookup(_code_table, 'Integer', 16) + __all__.append('Int16') +except(PrecisionError): + pass +try: + Int32 = _lookup(_code_table, 'Integer', 32) + __all__.append('Int32') +except(PrecisionError): + pass +try: + Int64 = _lookup(_code_table, 'Integer', 64) + __all__.append('Int64') +except(PrecisionError): + pass +try: + Int128 = _lookup(_code_table, 'Integer', 128) + __all__.append('Int128') +except(PrecisionError): + pass +Int = 'l' + +try: + Float0 = _lookup(_code_table, 'Float', 0) + __all__.append('Float0') +except(PrecisionError): + pass +try: + Float8 = _lookup(_code_table, 'Float', 8) + __all__.append('Float8') +except(PrecisionError): + pass +try: + Float16 = _lookup(_code_table, 'Float', 16) + __all__.append('Float16') +except(PrecisionError): + pass +try: + Float32 = _lookup(_code_table, 'Float', 32) + __all__.append('Float32') +except(PrecisionError): + pass +try: + Float64 = _lookup(_code_table, 'Float', 64) + __all__.append('Float64') +except(PrecisionError): + pass +try: + Float128 = _lookup(_code_table, 'Float', 128) + __all__.append('Float128') +except(PrecisionError): + pass +Float = 'd' + +try: + Complex0 = _lookup(_code_table, 'Complex', 0) + __all__.append('Complex0') +except(PrecisionError): + pass +try: + Complex8 = _lookup(_code_table, 'Complex', 16) + __all__.append('Complex8') +except(PrecisionError): + pass +try: + Complex16 = _lookup(_code_table, 'Complex', 32) + __all__.append('Complex16') +except(PrecisionError): + pass +try: + Complex32 = _lookup(_code_table, 'Complex', 64) + __all__.append('Complex32') +except(PrecisionError): + pass +try: + Complex64 = _lookup(_code_table, 'Complex', 128) + __all__.append('Complex64') +except(PrecisionError): + pass +try: + Complex128 = _lookup(_code_table, 'Complex', 256) + __all__.append('Complex128') +except(PrecisionError): + pass +Complex = 'D' + +PyObject = 'O' Added: trunk/numpy/oldnumeric/typeconv.py =================================================================== --- trunk/numpy/oldnumeric/typeconv.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/typeconv.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,28 @@ + +__all__ = ['oldtype2dtype', 'convtypecode'] + +import numpy as N + +oldtype2dtype = {'1': N.dtype(N.byte), + 's': N.dtype(N.short), + 'i': N.dtype(N.intc), + 'l': N.dtype(int), + 'b': N.dtype(N.ubyte), + 'w': N.dtype(N.ushort), + 'u': N.dtype(N.uintc), + 'f': N.dtype(N.single), + 'd': N.dtype(float), + 'F': N.dtype(N.csingle), + 'D': N.dtype(complex), + 'O': N.dtype(object), + 'c': N.dtype('c'), + None:N.dtype(int) + } + +def convtypecode(typecode, dtype=None): + if dtype is None: + try: + dtype = oldtype2dtype[typecode] + except: + dtype = N.dtype(typecode) + return dtype Added: trunk/numpy/oldnumeric/ufuncs.py =================================================================== --- trunk/numpy/oldnumeric/ufuncs.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/ufuncs.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,18 @@ +__all__ = ['less', 'cosh', 'arcsinh', 'add', 'ceil', 'arctan2', 'floor_divide', + 'fmod', 'hypot', 'logical_and', 'power', 'sinh', 'remainder', 'cos', + 'equal', 'arccos', 'less_equal', 'divide', 'bitwise_or', 'bitwise_and', + 'logical_xor', 'log', 'subtract', 'invert', 'negative', 'log10', 'arcsin', + 'arctanh', 'logical_not', 'not_equal', 'tanh', 'true_divide', 'maximum', + 'arccosh', 'logical_or', 'minimum', 'conjugate', 'tan', 'greater', 'bitwise_xor', + 'fabs', 'floor', 'sqrt', 'arctan', 'right_shift', 'absolute', 'sin', + 'multiply', 'greater_equal', 'left_shift', 'exp'] + +from numpy import less, cosh, arcsinh, add, ceil, arctan2, floor_divide, \ + fmod, hypot, logical_and, power, sinh, remainder, cos, \ + equal, arccos, less_equal, divide, bitwise_or, bitwise_and, \ + logical_xor, log, subtract, invert, negative, log10, arcsin, \ + arctanh, logical_not, not_equal, tanh, true_divide, maximum, \ + arccosh, logical_or, minimum, conjugate, tan, greater, bitwise_xor, \ + fabs, floor, sqrt, arctan, right_shift, absolute, sin, \ + multiply, greater_equal, left_shift, exp + Added: trunk/numpy/oldnumeric/user_array.py =================================================================== --- trunk/numpy/oldnumeric/user_array.py 2006-08-04 23:38:27 UTC (rev 2956) +++ trunk/numpy/oldnumeric/user_array.py 2006-08-05 01:20:56 UTC (rev 2957) @@ -0,0 +1,9 @@ + + +from numpy.oldnumeric import * +from numpy.lib.user_array import container as UserArray + +import numpy.oldnumeric as nold +__all__ = nold.__all__ +__all__ += ['UserArray'] +del nold From numpy-svn at scipy.org Fri Aug 4 21:52:58 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 20:52:58 -0500 (CDT) Subject: [Numpy-svn] r2958 - trunk/numpy/oldnumeric Message-ID: <20060805015258.D7F9D39C014@new.scipy.org> Author: oliphant Date: 2006-08-04 20:52:55 -0500 (Fri, 04 Aug 2006) New Revision: 2958 Modified: trunk/numpy/oldnumeric/compat.py trunk/numpy/oldnumeric/functions.py trunk/numpy/oldnumeric/misc.py Log: Fix-up oldnumeric compatibility layer. Modified: trunk/numpy/oldnumeric/compat.py =================================================================== --- trunk/numpy/oldnumeric/compat.py 2006-08-05 01:20:56 UTC (rev 2957) +++ trunk/numpy/oldnumeric/compat.py 2006-08-05 01:52:55 UTC (rev 2958) @@ -5,7 +5,7 @@ 'LittleEndian', 'sarray', 'arrayrange', 'cross_correlate', 'matrixmultiply', 'outerproduct', 'innerproduct', - 'cross_product', 'array_constructor', + 'cross_product', 'array_constructor', 'pickle_array', 'DumpArray', 'LoadArray', 'multiarray', 'divide_safe', # from cPickle 'dump', 'dumps' @@ -70,4 +70,11 @@ else: return x - +def pickle_array(a): + if a.dtype.hasobject: + return (array_constructor, + a.shape, a.dtype.char, a.tolist(), LittleEndian) + else: + return (array_constructor, + (a.shape, a.dtype.char, a.tostring(), LittleEndian)) + Modified: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-05 01:20:56 UTC (rev 2957) +++ trunk/numpy/oldnumeric/functions.py 2006-08-05 01:52:55 UTC (rev 2958) @@ -1,4 +1,4 @@ -# Functions that should behave the same as Numeric +# Functions that should behave the same as Numeric and need changing import numpy as N import numpy.core.multiarray as mu @@ -7,7 +7,9 @@ __all__ = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', 'cumsum', 'cumproduct'] -__all__ += ['ones', 'empty', 'identity', 'zeros'] +__all__ += ['ones', 'empty', 'identity', 'zeros', 'array', 'asarray', 'nonzero', + 'reshape', 'arange', 'fromstring', 'ravel', 'trace', 'indices', + 'where'] def take(a, indicies, axis=0): return N.take(a, indicies, axis) @@ -60,3 +62,33 @@ dtype = convtypecode(typecode, dtype) return mu.empty(shape, dtype, order) + +def array(sequence, typecode=None, copy=1, savespace=0): + pass + +def asarray(a, typecode=None): + pass + +def nonzero(a): + pass + +def reshape(a, shape): + pass + +def arange(start, stop=None, step=1, typecode=None): + pass + +def fromstring(string, typecode='l', count=-1): + pass + +def ravel(m): + pass + +def trace(a, offset=0, axis1=0, axis2=1): + pass + +def indices(dimensions, typecode=None): + pass + +def where(condition, x, y): + pass Modified: trunk/numpy/oldnumeric/misc.py =================================================================== --- trunk/numpy/oldnumeric/misc.py 2006-08-05 01:20:56 UTC (rev 2957) +++ trunk/numpy/oldnumeric/misc.py 2006-08-05 01:52:55 UTC (rev 2958) @@ -1,3 +1,40 @@ +# Functions that already have the correct syntax or miscellaneous functions -__all__ = ['load', 'sort', 'copy_reg', 'clip', 'putmask', 'Unpickler', 'rank', 'sign', 'shape', 'types', 'array', 'allclose', 'size', 'nonzero', 'asarray', 'reshape', 'argmax', 'choose', 'swapaxes', 'array_str', 'pi', 'ravel', 'math', 'compress', 'concatenate', 'pickle_array', 'around', 'trace', 'vdot', 'transpose', 'array2string', 'diagonal', 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', 'array_repr', 'e', 'argmin', 'StringIO', 'pickle', 'average', 'arange', 'argsort', 'convolve', 'fromstring', 'indices', 'loads', 'Pickler', 'where', 'dot'] +__all__ = ['load', 'sort', 'copy_reg', 'clip', 'putmask', 'Unpickler', 'rank', + 'sign', 'shape', 'types', + 'argmax', 'choose', 'swapaxes', 'array_str', + 'pi', 'math', 'compress', 'concatenate' + 'around', 'vdot', 'transpose', 'array2string', 'diagonal', + 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', + 'array_repr', 'e', 'argmin', 'StringIO', 'pickle', 'average', + 'argsort', 'convolve', 'loads', + 'Pickler', 'dot'] + +import types +import StringIO +import pickle +import math +import copy +import copy_reg +from pickle import load, loads + +from numpy import sort, clip, putmask, rank, sign, shape, allclose, size,\ + argmax, choose, swapaxes, array_str, array_repr, argmin, e, pi, \ + fromfunction, resize, around, compress, concatenate, vdot, transpose, \ + diagonal, searchsorted, put, average, argsort, convolve, dot + +from array_printer import array2string + + +class Unpickler(pickle.Unpickler): + def __init__(self, *args, **kwds): + raise NotImplemented + def load_array(self): + raise NotImplemented + +class Pickler(pickle.Pickler): + def __init__(self, *args, **kwds): + raise NotImplemented + def save_array(self, object): + raise NotImplemented From numpy-svn at scipy.org Fri Aug 4 22:00:46 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 21:00:46 -0500 (CDT) Subject: [Numpy-svn] r2959 - in trunk/numpy: core oldnumeric Message-ID: <20060805020046.8B61B39C014@new.scipy.org> Author: oliphant Date: 2006-08-04 21:00:43 -0500 (Fri, 04 Aug 2006) New Revision: 2959 Modified: trunk/numpy/core/fromnumeric.py trunk/numpy/oldnumeric/functions.py Log: Final fixes to oldnumeric Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-05 01:52:55 UTC (rev 2958) +++ trunk/numpy/core/fromnumeric.py 2006-08-05 02:00:43 UTC (rev 2959) @@ -239,11 +239,7 @@ res = _wrapit(a, 'nonzero') else: res = nonzero() - - if len(res) == 1: - return res[0] - else: - raise ValueError, "Input argument must be 1d" + return res def shape(a): Modified: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-05 01:52:55 UTC (rev 2958) +++ trunk/numpy/oldnumeric/functions.py 2006-08-05 02:00:43 UTC (rev 2959) @@ -34,7 +34,6 @@ def cumproduct(x, axis=0): return N.cumproduct(x, axis) - def ones(shape, typecode='l', savespace=0, dtype=None): """ones(shape, dtype=int) returns an array of the given @@ -62,33 +61,41 @@ dtype = convtypecode(typecode, dtype) return mu.empty(shape, dtype, order) +def array(sequence, typecode=None, copy=1, savespace=0, dtype=None): + dtype = convtypecode(typecode, dtype) + return mu.array(sequence, dtype, copy=copy) -def array(sequence, typecode=None, copy=1, savespace=0): - pass +def asarray(a, typecode=None, dtype=None): + dtype = convtypecode(typecode, dtype) + return mu.array(a, dtype, copy=0) -def asarray(a, typecode=None): - pass - def nonzero(a): - pass + res = N.nonzero(a) + if len(res) == 1: + return res[0] + else: + raise ValueError, "Input argument must be 1d" def reshape(a, shape): - pass + return N.reshape(a, shape) -def arange(start, stop=None, step=1, typecode=None): - pass +def arange(start, stop=None, step=1, typecode=None, dtype=None): + dtype = convtypecode(typecode, dtype) + return mu.arange(start, stop, step, dtype) -def fromstring(string, typecode='l', count=-1): - pass +def fromstring(string, typecode='l', count=-1, dtype=None): + dtype = convtypecode(typecode, dtype) + return mu.fromstring(string, dtype, count=count) def ravel(m): - pass + return N.ravel(m) def trace(a, offset=0, axis1=0, axis2=1): - pass + return N.trace(a, offset=0, axis1=0, axis2=1) -def indices(dimensions, typecode=None): - pass +def indices(dimensions, typecode=None, dtype=None): + dtype = convtypecode(typecode, dtype) + return N.indices(dimensions, dtype) def where(condition, x, y): - pass + return N.where(condition, x, y) From numpy-svn at scipy.org Fri Aug 4 22:01:28 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 21:01:28 -0500 (CDT) Subject: [Numpy-svn] r2960 - trunk/numpy/core Message-ID: <20060805020128.012EE39C014@new.scipy.org> Author: oliphant Date: 2006-08-04 21:01:26 -0500 (Fri, 04 Aug 2006) New Revision: 2960 Modified: trunk/numpy/core/fromnumeric.py Log: Final fixes to oldnumeric Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-05 02:00:43 UTC (rev 2959) +++ trunk/numpy/core/fromnumeric.py 2006-08-05 02:01:26 UTC (rev 2960) @@ -239,7 +239,7 @@ res = _wrapit(a, 'nonzero') else: res = nonzero() - return res + return res[0] def shape(a): From numpy-svn at scipy.org Fri Aug 4 22:04:32 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 4 Aug 2006 21:04:32 -0500 (CDT) Subject: [Numpy-svn] r2961 - trunk/numpy/core Message-ID: <20060805020432.20CA139C014@new.scipy.org> Author: oliphant Date: 2006-08-04 21:04:29 -0500 (Fri, 04 Aug 2006) New Revision: 2961 Modified: trunk/numpy/core/fromnumeric.py Log: Redo nonzero change --- head for the hills... Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-05 02:01:26 UTC (rev 2960) +++ trunk/numpy/core/fromnumeric.py 2006-08-05 02:04:29 UTC (rev 2961) @@ -239,7 +239,7 @@ res = _wrapit(a, 'nonzero') else: res = nonzero() - return res[0] + return res def shape(a): From numpy-svn at scipy.org Sat Aug 5 02:44:26 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 01:44:26 -0500 (CDT) Subject: [Numpy-svn] r2962 - in trunk/numpy: fft oldnumeric Message-ID: <20060805064426.050CF39C06A@new.scipy.org> Author: oliphant Date: 2006-08-05 01:44:20 -0500 (Sat, 05 Aug 2006) New Revision: 2962 Added: trunk/numpy/oldnumeric/fft.py Removed: trunk/numpy/fft/old.py Modified: trunk/numpy/oldnumeric/__init__.py trunk/numpy/oldnumeric/functions.py trunk/numpy/oldnumeric/ma.py trunk/numpy/oldnumeric/matrix.py trunk/numpy/oldnumeric/misc.py trunk/numpy/oldnumeric/mlab.py trunk/numpy/oldnumeric/precision.py trunk/numpy/oldnumeric/typeconv.py trunk/numpy/oldnumeric/ufuncs.py Log: Fixes for the recent change to oldnumeric Deleted: trunk/numpy/fft/old.py =================================================================== --- trunk/numpy/fft/old.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/fft/old.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -1,19 +0,0 @@ - -__all__ = ['fft', 'fft2d', 'fftnd', 'hermite_fft', 'inverse_fft', 'inverse_fft2d', - 'inverse_fftnd', 'inverse_hermite_fft', 'inverse_real_fft', 'inverse_real_fft2d', - 'inverse_real_fftnd', 'real_fft', 'real_fft2d', 'real_fftnd'] - -from fftpack import fft -from fftpack import fft2 as fft2d -from fftpack import fftn as fftnd -from fftpack import hfft as hermite_fft -from fftpack import ifft as inverse_fft -from fftpack import ifft2 as inverse_fft2d -from fftpack import ifftn as inverse_fftnd -from fftpack import ihfft as inverse_hermite_fft -from fftpack import irfft as inverse_real_fft -from fftpack import irfft2 as inverse_real_fft2d -from fftpack import irfftn as inverse_real_fftnd -from fftpack import rfft as real_fft -from fftpack import rfft2 as real_fft2d -from fftpack import rfftn as real_fftnd Modified: trunk/numpy/oldnumeric/__init__.py =================================================================== --- trunk/numpy/oldnumeric/__init__.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/__init__.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -1,5 +1,5 @@ -# Don't add these to the __all__ variable +# Don't add these to the __all__ variable though from numpy import * def _move_axis_to_0(a, axis): @@ -16,6 +16,7 @@ from functions import * from precision import * from ufuncs import * +from misc import * import compat import precision Added: trunk/numpy/oldnumeric/fft.py =================================================================== --- trunk/numpy/oldnumeric/fft.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/fft.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -0,0 +1,21 @@ + +__all__ = ['fft', 'fft2d', 'fftnd', 'hermite_fft', 'inverse_fft', + 'inverse_fft2d', 'inverse_fftnd', + 'inverse_hermite_fft', 'inverse_real_fft', + 'inverse_real_fft2d', 'inverse_real_fftnd', + 'real_fft', 'real_fft2d', 'real_fftnd'] + +from numpy.fft import fft +from numpy.fft import fft2 as fft2d +from numpy.fft import fftn as fftnd +from numpy.fft import hfft as hermite_fft +from numpy.fft import ifft as inverse_fft +from numpy.fft import ifft2 as inverse_fft2d +from numpy.fft import ifftn as inverse_fftnd +from numpy.fft import ihfft as inverse_hermite_fft +from numpy.fft import irfft as inverse_real_fft +from numpy.fft import irfft2 as inverse_real_fft2d +from numpy.fft import irfftn as inverse_real_fftnd +from numpy.fft import rfft as real_fft +from numpy.fft import rfft2 as real_fft2d +from numpy.fft import rfftn as real_fftnd Modified: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/functions.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -3,19 +3,19 @@ import numpy as N import numpy.core.multiarray as mu import numpy.core.numeric as nn -from typeconv import convtypecode +from typeconv import convtypecode, convtypecode2 __all__ = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', - 'cumsum', 'cumproduct'] -__all__ += ['ones', 'empty', 'identity', 'zeros', 'array', 'asarray', 'nonzero', - 'reshape', 'arange', 'fromstring', 'ravel', 'trace', 'indices', - 'where'] + 'cumsum', 'cumproduct', + 'ones', 'empty', 'identity', 'zeros', 'array', 'asarray', + 'nonzero', 'reshape', 'arange', 'fromstring', 'ravel', 'trace', + 'indices', 'where'] def take(a, indicies, axis=0): return N.take(a, indicies, axis) def repeat(a, repeats, axis=0): - return N.repeats(a, repeats, axis) + return N.repeat(a, repeats, axis) def sum(x, axis=0): return N.sum(x, axis) @@ -62,11 +62,11 @@ return mu.empty(shape, dtype, order) def array(sequence, typecode=None, copy=1, savespace=0, dtype=None): - dtype = convtypecode(typecode, dtype) + dtype = convtypecode2(typecode, dtype) return mu.array(sequence, dtype, copy=copy) def asarray(a, typecode=None, dtype=None): - dtype = convtypecode(typecode, dtype) + dtype = convtypecode2(typecode, dtype) return mu.array(a, dtype, copy=0) def nonzero(a): @@ -80,7 +80,7 @@ return N.reshape(a, shape) def arange(start, stop=None, step=1, typecode=None, dtype=None): - dtype = convtypecode(typecode, dtype) + dtype = convtypecode2(typecode, dtype) return mu.arange(start, stop, step, dtype) def fromstring(string, typecode='l', count=-1, dtype=None): Modified: trunk/numpy/oldnumeric/ma.py =================================================================== --- trunk/numpy/oldnumeric/ma.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/ma.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -1,11 +1,5 @@ +# Incompatibility in that getmask and a.mask returns nomask +# instead of None -from numpy.core.ma import getmask as _getmask, nomask as _nomask from numpy.core.ma import * -del getmask, nomask - -def getmask(a): - res = _getmask(a) - if res is _nomask: - return None - return res Modified: trunk/numpy/oldnumeric/matrix.py =================================================================== --- trunk/numpy/oldnumeric/matrix.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/matrix.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -4,14 +4,12 @@ import string import types -import numpy.oldnumeric as Numeric from user_array import UserArray, asarray +import numpy.oldnumeric as Numeric from numpy.oldnumeric import dot, identity, multiply -from mlab import squeeze import linear_algebra as LinearAlgebra +from numpy import matrix as Matrix, squeeze -from numpy import matrix as Matrix - # Hidden names that will be the same. _table = [None]*256 Modified: trunk/numpy/oldnumeric/misc.py =================================================================== --- trunk/numpy/oldnumeric/misc.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/misc.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -2,9 +2,9 @@ __all__ = ['load', 'sort', 'copy_reg', 'clip', 'putmask', 'Unpickler', 'rank', - 'sign', 'shape', 'types', + 'sign', 'shape', 'types', 'allclose', 'size', 'argmax', 'choose', 'swapaxes', 'array_str', - 'pi', 'math', 'compress', 'concatenate' + 'pi', 'math', 'compress', 'concatenate', 'around', 'vdot', 'transpose', 'array2string', 'diagonal', 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', 'array_repr', 'e', 'argmin', 'StringIO', 'pickle', 'average', Modified: trunk/numpy/oldnumeric/mlab.py =================================================================== --- trunk/numpy/oldnumeric/mlab.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/mlab.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -1,11 +1,7 @@ # This module is for compatibility only. All functions are defined elsewhere. -from numpy.oldnumeric import * +__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] -__all__ = numpy.oldnumeric.__all__ - -__all__ += ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] - import linear_algebra as LinearAlgebra import random_array as RandomArray from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \ @@ -69,4 +65,32 @@ def corrcoef(x, y=None): return _Ncorrcoef(x,y,0,0) +from compat import * +from functions import * +from precision import * +from ufuncs import * +from misc import * +import compat +import precision +import functions +import misc +import ufuncs + +import numpy +__version__ = numpy.__version__ +del numpy + +__all__ += ['__version__'] +__all__ += compat.__all__ +__all__ += precision.__all__ +__all__ += functions.__all__ +__all__ += ufuncs.__all__ +__all__ += misc.__all__ + +del compat +del functions +del precision +del ufuncs +del misc + Modified: trunk/numpy/oldnumeric/precision.py =================================================================== --- trunk/numpy/oldnumeric/precision.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/precision.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -1,14 +1,16 @@ -# Lifted from Precision.py. This is for compatibility only. Notice that the -# capitalized names have their old character strings +# Lifted from Precision.py. This is for compatibility only. +# +# The character strings are still for "new" NumPy +# which is the only Incompatibility with Numeric __all__ = ['Character', 'Complex', 'Float', 'PrecisionError', 'PyObject', 'Int', 'UInt', 'UnsignedInteger', 'string', 'typecodes', 'zeros'] import string -from olddefaults import zeros +from functions import zeros -typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', 'Float':'fd', 'Complex':'FD'} +typecodes = {'Character':'c', 'Integer':'bhil', 'UnsignedInteger':'BHI', 'Float':'fd', 'Complex':'FD'} def _get_precisions(typecodes): lst = [] Modified: trunk/numpy/oldnumeric/typeconv.py =================================================================== --- trunk/numpy/oldnumeric/typeconv.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/typeconv.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -1,5 +1,5 @@ -__all__ = ['oldtype2dtype', 'convtypecode'] +__all__ = ['oldtype2dtype', 'convtypecode', 'convtypecode2'] import numpy as N @@ -22,7 +22,15 @@ def convtypecode(typecode, dtype=None): if dtype is None: try: - dtype = oldtype2dtype[typecode] + return oldtype2dtype[typecode] except: - dtype = N.dtype(typecode) - return dtype + return N.dtype(typecode) + +def convtypecode2(typecode, dtype=None): + if typecode is None and dtype is None: + return None + elif dtype is None: + try: + return oldtype2dtype[typecode] + except: + return N.dtype(typecode) Modified: trunk/numpy/oldnumeric/ufuncs.py =================================================================== --- trunk/numpy/oldnumeric/ufuncs.py 2006-08-05 02:04:29 UTC (rev 2961) +++ trunk/numpy/oldnumeric/ufuncs.py 2006-08-05 06:44:20 UTC (rev 2962) @@ -1,11 +1,12 @@ __all__ = ['less', 'cosh', 'arcsinh', 'add', 'ceil', 'arctan2', 'floor_divide', 'fmod', 'hypot', 'logical_and', 'power', 'sinh', 'remainder', 'cos', - 'equal', 'arccos', 'less_equal', 'divide', 'bitwise_or', 'bitwise_and', - 'logical_xor', 'log', 'subtract', 'invert', 'negative', 'log10', 'arcsin', - 'arctanh', 'logical_not', 'not_equal', 'tanh', 'true_divide', 'maximum', - 'arccosh', 'logical_or', 'minimum', 'conjugate', 'tan', 'greater', 'bitwise_xor', - 'fabs', 'floor', 'sqrt', 'arctan', 'right_shift', 'absolute', 'sin', - 'multiply', 'greater_equal', 'left_shift', 'exp'] + 'equal', 'arccos', 'less_equal', 'divide', 'bitwise_or', + 'bitwise_and', 'logical_xor', 'log', 'subtract', 'invert', + 'negative', 'log10', 'arcsin', 'arctanh', 'logical_not', + 'not_equal', 'tanh', 'true_divide', 'maximum', 'arccosh', + 'logical_or', 'minimum', 'conjugate', 'tan', 'greater', + 'bitwise_xor', 'fabs', 'floor', 'sqrt', 'arctan', 'right_shift', + 'absolute', 'sin', 'multiply', 'greater_equal', 'left_shift', 'exp'] from numpy import less, cosh, arcsinh, add, ceil, arctan2, floor_divide, \ fmod, hypot, logical_and, power, sinh, remainder, cos, \ From numpy-svn at scipy.org Sat Aug 5 03:01:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 02:01:56 -0500 (CDT) Subject: [Numpy-svn] r2963 - trunk/numpy/oldnumeric Message-ID: <20060805070156.69F7D39C06B@new.scipy.org> Author: oliphant Date: 2006-08-05 02:01:54 -0500 (Sat, 05 Aug 2006) New Revision: 2963 Modified: trunk/numpy/oldnumeric/typeconv.py Log: Alter typeconv to ignore 'b' Modified: trunk/numpy/oldnumeric/typeconv.py =================================================================== --- trunk/numpy/oldnumeric/typeconv.py 2006-08-05 06:44:20 UTC (rev 2962) +++ trunk/numpy/oldnumeric/typeconv.py 2006-08-05 07:01:54 UTC (rev 2963) @@ -5,32 +5,40 @@ oldtype2dtype = {'1': N.dtype(N.byte), 's': N.dtype(N.short), - 'i': N.dtype(N.intc), - 'l': N.dtype(int), - 'b': N.dtype(N.ubyte), +# 'i': N.dtype(N.intc), +# 'l': N.dtype(int), +# 'b': N.dtype(N.ubyte), 'w': N.dtype(N.ushort), 'u': N.dtype(N.uintc), - 'f': N.dtype(N.single), - 'd': N.dtype(float), - 'F': N.dtype(N.csingle), - 'D': N.dtype(complex), - 'O': N.dtype(object), - 'c': N.dtype('c'), +# 'f': N.dtype(N.single), +# 'd': N.dtype(float), +# 'F': N.dtype(N.csingle), +# 'D': N.dtype(complex), +# 'O': N.dtype(object), +# 'c': N.dtype('c'), None:N.dtype(int) } +# converts typecode=None to int def convtypecode(typecode, dtype=None): if dtype is None: try: return oldtype2dtype[typecode] except: return N.dtype(typecode) + else: + return dtype +#if both typecode and dtype are None +# return None def convtypecode2(typecode, dtype=None): - if typecode is None and dtype is None: - return None - elif dtype is None: - try: - return oldtype2dtype[typecode] - except: - return N.dtype(typecode) + if dtype is None: + if typecode is None: + return None + else: + try: + return oldtype2dtype[typecode] + except: + return N.dtype(typecode) + else: + return dtype From numpy-svn at scipy.org Sat Aug 5 03:48:54 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 02:48:54 -0500 (CDT) Subject: [Numpy-svn] r2964 - in trunk/numpy: core core/tests lib linalg Message-ID: <20060805074854.C13FF39C06B@new.scipy.org> Author: oliphant Date: 2006-08-05 02:48:48 -0500 (Sat, 05 Aug 2006) New Revision: 2964 Modified: trunk/numpy/core/fromnumeric.py trunk/numpy/core/ma.py trunk/numpy/core/tests/test_ma.py trunk/numpy/lib/convertnumericA.py trunk/numpy/lib/function_base.py trunk/numpy/lib/polynomial.py trunk/numpy/linalg/linalg.py Log: Fix uses of nonzero and add flatnonzero Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-05 07:01:54 UTC (rev 2963) +++ trunk/numpy/core/fromnumeric.py 2006-08-05 07:48:48 UTC (rev 2964) @@ -230,8 +230,7 @@ return a.ravel(order) def nonzero(a): - """nonzero(a) returns the indices of the elements of a which are not zero, - a must be 1d + """nonzero(a) returns the indices of the elements of a which are not zero """ try: nonzero = a.nonzero @@ -241,7 +240,6 @@ res = nonzero() return res - def shape(a): """shape(a) returns the shape of a (as a function call which also works on nested sequences). Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-05 07:01:54 UTC (rev 2963) +++ trunk/numpy/core/ma.py 2006-08-05 07:48:48 UTC (rev 2964) @@ -445,9 +445,8 @@ negative = masked_unary_operation(umath.negative) def nonzero(a): - """returns the indices of the elements of a which are not zero and not masked - - a must be 1d + """returns the indices of the elements of a which are not zero + and not masked """ return asarray(filled(a, 0).nonzero()) Modified: trunk/numpy/core/tests/test_ma.py =================================================================== --- trunk/numpy/core/tests/test_ma.py 2006-08-05 07:01:54 UTC (rev 2963) +++ trunk/numpy/core/tests/test_ma.py 2006-08-05 07:48:48 UTC (rev 2964) @@ -306,7 +306,7 @@ def check_testMaPut(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1] - i = numpy.nonzero(m) + i = numpy.nonzero(m)[0] putmask(xm, m, z) assert take(xm, i) == z put(ym, i, zm) Modified: trunk/numpy/lib/convertnumericA.py =================================================================== --- trunk/numpy/lib/convertnumericA.py 2006-08-05 07:01:54 UTC (rev 2963) +++ trunk/numpy/lib/convertnumericA.py 2006-08-05 07:48:48 UTC (rev 2964) @@ -13,6 +13,9 @@ * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] * Replace xxx.spacesaver() with True * Convert xx.savespace(?) to pass + ## xx.savespace(?) + + * Converts uses of 'b' to 'B' in the typecode-position of + functions and methods """ __all__ = ['fromfile', 'fromstr'] Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-05 07:01:54 UTC (rev 2963) +++ trunk/numpy/lib/function_base.py 2006-08-05 07:48:48 UTC (rev 2964) @@ -7,7 +7,8 @@ 'nanargmin', 'nanmin', 'vectorize', 'asarray_chkfinite', 'average', 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', - 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid' + 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', + 'flatnonzero' ] import types @@ -530,7 +531,7 @@ Equivalent to compress(ravel(condition), ravel(arr)). """ - return _nx.take(ravel(arr), nonzero(ravel(condition))) + return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def insert(arr, mask, vals): """Similar to putmask arr[mask] = vals but the 1D array vals has the @@ -997,3 +998,11 @@ y = y.reshape(numRows,1) Y = y.repeat(numCols, axis=1) return X, Y + +def flatnonzero(a): + """Return indicies that are not-zero in flattened version of a + + Equivalent to a.ravel().nonzero()[0] + """ + return a.ravel().nonzero()[0] + Modified: trunk/numpy/lib/polynomial.py =================================================================== --- trunk/numpy/lib/polynomial.py 2006-08-05 07:01:54 UTC (rev 2963) +++ trunk/numpy/lib/polynomial.py 2006-08-05 07:48:48 UTC (rev 2964) @@ -90,7 +90,7 @@ raise ValueError,"Input must be a rank-1 array." # find non-zero array entries - non_zero = NX.nonzero(NX.ravel(p)) + non_zero = NX.nonzero(NX.ravel(p))[0] # find the number of trailing zeros -- this is the number of roots at 0. trailing_zeros = len(p) - non_zero[-1] - 1 Modified: trunk/numpy/linalg/linalg.py =================================================================== --- trunk/numpy/linalg/linalg.py 2006-08-05 07:01:54 UTC (rev 2963) +++ trunk/numpy/linalg/linalg.py 2006-08-05 07:48:48 UTC (rev 2964) @@ -313,7 +313,7 @@ else: w = wr+1j*wi v = array(vr, w.dtype) - ind = nonzero(wi != 0.0) # indices of complex e-vals + ind = nonzero(wi != 0.0)[0] # indices of complex e-vals for i in range(len(ind)/2): v[ind[2*i]] = vr[ind[2*i]] + 1j*vr[ind[2*i+1]] v[ind[2*i+1]] = vr[ind[2*i]] - 1j*vr[ind[2*i+1]] From numpy-svn at scipy.org Sat Aug 5 03:50:54 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 02:50:54 -0500 (CDT) Subject: [Numpy-svn] r2965 - in trunk/numpy: core lib linalg Message-ID: <20060805075054.7759F39C06B@new.scipy.org> Author: oliphant Date: 2006-08-05 02:50:50 -0500 (Sat, 05 Aug 2006) New Revision: 2965 Modified: trunk/numpy/core/numeric.py trunk/numpy/lib/function_base.py trunk/numpy/linalg/linalg.py Log: Move location of flatnonzero Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-05 07:48:48 UTC (rev 2964) +++ trunk/numpy/core/numeric.py 2006-08-05 07:50:50 UTC (rev 2965) @@ -16,7 +16,7 @@ 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', 'ones', 'identity', 'allclose', 'seterr', 'geterr', 'setbufsize', 'getbufsize', - 'seterrcall', 'geterrcall', + 'seterrcall', 'geterrcall', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', 'nan', 'NaN', 'False_', 'True_'] @@ -178,6 +178,13 @@ """ return transpose(a.nonzero()) +def flatnonzero(a): + """Return indicies that are not-zero in flattened version of a + + Equivalent to a.ravel().nonzero()[0] + """ + return a.ravel().nonzero()[0] + _mode_from_name_dict = {'v': 0, 's' : 1, 'f' : 2} Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-05 07:48:48 UTC (rev 2964) +++ trunk/numpy/lib/function_base.py 2006-08-05 07:50:50 UTC (rev 2965) @@ -8,7 +8,6 @@ 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', - 'flatnonzero' ] import types @@ -998,11 +997,4 @@ y = y.reshape(numRows,1) Y = y.repeat(numCols, axis=1) return X, Y - -def flatnonzero(a): - """Return indicies that are not-zero in flattened version of a - - Equivalent to a.ravel().nonzero()[0] - """ - return a.ravel().nonzero()[0] Modified: trunk/numpy/linalg/linalg.py =================================================================== --- trunk/numpy/linalg/linalg.py 2006-08-05 07:48:48 UTC (rev 2964) +++ trunk/numpy/linalg/linalg.py 2006-08-05 07:50:50 UTC (rev 2965) @@ -18,7 +18,7 @@ from numpy.core import array, asarray, zeros, empty, transpose, \ intc, single, double, csingle, cdouble, inexact, complexfloating, \ newaxis, ravel, all, Inf, dot, add, multiply, identity, sqrt, \ - maximum, nonzero, diagonal, arange, fastCopyAndTranspose, sum, \ + maximum, flatnonzero, diagonal, arange, fastCopyAndTranspose, sum, \ argsort from numpy.lib import triu from numpy.linalg import lapack_lite @@ -313,7 +313,7 @@ else: w = wr+1j*wi v = array(vr, w.dtype) - ind = nonzero(wi != 0.0)[0] # indices of complex e-vals + ind = flatnonzero(wi != 0.0) # indices of complex e-vals for i in range(len(ind)/2): v[ind[2*i]] = vr[ind[2*i]] + 1j*vr[ind[2*i+1]] v[ind[2*i+1]] = vr[ind[2*i]] - 1j*vr[ind[2*i+1]] From numpy-svn at scipy.org Sat Aug 5 04:05:13 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 03:05:13 -0500 (CDT) Subject: [Numpy-svn] r2966 - trunk/numpy/oldnumeric Message-ID: <20060805080513.765A239C072@new.scipy.org> Author: oliphant Date: 2006-08-05 03:05:11 -0500 (Sat, 05 Aug 2006) New Revision: 2966 Modified: trunk/numpy/oldnumeric/mlab.py Log: Update eye and tri to take dtype in mlab Modified: trunk/numpy/oldnumeric/mlab.py =================================================================== --- trunk/numpy/oldnumeric/mlab.py 2006-08-05 07:50:50 UTC (rev 2965) +++ trunk/numpy/oldnumeric/mlab.py 2006-08-05 08:05:11 UTC (rev 2966) @@ -13,23 +13,23 @@ from numpy.linalg import eig, svd from numpy.random import rand, randn -from typeconv import oldtype2dtype as o2d +from typeconv import convtypecode -def eye(N, M=None, k=0, typecode=None): +def eye(N, M=None, k=0, typecode=None, dtype=None): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros. """ - dtype = o2d[typecode] + dtype = convtypecode(typecode, dtype) if M is None: M = N m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) -def tri(N, M=None, k=0, typecode=None): +def tri(N, M=None, k=0, typecode=None, dtype=None): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. """ - dtype = o2d[typecode] + dtype = convtypecode(typecode, dtype) if M is None: M = N m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) if m.dtype != dtype: From numpy-svn at scipy.org Sat Aug 5 04:59:45 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 03:59:45 -0500 (CDT) Subject: [Numpy-svn] r2967 - trunk/numpy/lib Message-ID: <20060805085945.A8C5A39C06B@new.scipy.org> Author: oliphant Date: 2006-08-05 03:59:42 -0500 (Sat, 05 Aug 2006) New Revision: 2967 Modified: trunk/numpy/lib/convertnumericA.py trunk/numpy/lib/convertnumericB.py Log: Fix convertnumericA.py to fix transition from 'b' to 'B' Modified: trunk/numpy/lib/convertnumericA.py =================================================================== --- trunk/numpy/lib/convertnumericA.py 2006-08-05 08:05:11 UTC (rev 2966) +++ trunk/numpy/lib/convertnumericA.py 2006-08-05 08:59:42 UTC (rev 2967) @@ -15,7 +15,13 @@ * Convert xx.savespace(?) to pass + ## xx.savespace(?) * Converts uses of 'b' to 'B' in the typecode-position of - functions and methods + functions: + eye, tri (in position 4) + ones, zeros, identity, empty, array, asarray, arange, + fromstring, indices, array_constructor (in position 2) + + and methods: + astype --- only argument """ __all__ = ['fromfile', 'fromstr'] @@ -24,6 +30,31 @@ import re import glob + +_func4 = ['eye', 'tri'] +_meth1 = ['astype'] +_func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', + 'empty', 'array', 'asarray', 'arange', 'array_constructor'] + +func_re = {} + +for name in _func2: + _astr = r"""(%s\s*[(][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +for name in _func4: + _astr = r"""(%s\s*[(][^,]*?[,][^,]*?[,][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +for name in _meth1: + _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +def fixtypechars(fstr): + for name in _func2 + _func4 + _meth1: + fstr = func2_re[name].sub('\\1B\\2',fstr) + return fstr + flatindex_re = re.compile('([.]flat(\s*?[[=]))') def changeimports(fstr, name, newname): @@ -74,7 +105,7 @@ import datetime def fromstr(filestr): - #filestr = replacetypechars(filestr) + filestr = fixtypechars(filestr) filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'multiarray','numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') Modified: trunk/numpy/lib/convertnumericB.py =================================================================== --- trunk/numpy/lib/convertnumericB.py 2006-08-05 08:05:11 UTC (rev 2966) +++ trunk/numpy/lib/convertnumericB.py 2006-08-05 08:59:42 UTC (rev 2967) @@ -3,20 +3,26 @@ with numpy Makes the following changes: - * Converts typecharacters + * Converts typecharacters '1swu' to 'bhHI' respectively + when used as typecodes * Changes import statements * Change typecode= to dtype= - * Eliminates savespace=xxx + * Eliminates savespace=xxx keyword arguments + * Removes it when keyword is not given as well * replaces matrixmultiply with dot * converts functions that don't give axis= keyword that have changed * converts functions that don't give typecode= keyword that have changed * converts use of capitalized type-names + * converts old function names in oldnumeric.linear_algebra, + oldnumeric.random_array, and oldnumeric.fft - * converts old function names in linalg.old, random.old, dft.old - """ -__all__ = ['fromfile', 'fromstr'] +#__all__ = ['fromfile', 'fromstr'] +__all__ = [] +import warnings +warnings.warn("convetnumericB is not finished yet.") + import sys import os import re From numpy-svn at scipy.org Sat Aug 5 13:00:11 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 12:00:11 -0500 (CDT) Subject: [Numpy-svn] r2968 - in trunk/numpy: lib numarray oldnumeric Message-ID: <20060805170011.6154A39C0B6@new.scipy.org> Author: oliphant Date: 2006-08-05 12:00:03 -0500 (Sat, 05 Aug 2006) New Revision: 2968 Added: trunk/numpy/numarray/alter_code1.py trunk/numpy/numarray/alter_code2.py trunk/numpy/oldnumeric/alter_code1.py trunk/numpy/oldnumeric/alter_code2.py Removed: trunk/numpy/lib/convertnumericA.py trunk/numpy/lib/convertnumericB.py Log: Move converting code Deleted: trunk/numpy/lib/convertnumericA.py =================================================================== --- trunk/numpy/lib/convertnumericA.py 2006-08-05 08:59:42 UTC (rev 2967) +++ trunk/numpy/lib/convertnumericA.py 2006-08-05 17:00:03 UTC (rev 2968) @@ -1,173 +0,0 @@ -""" -This module converts code written for Numeric to run with numpy - -Makes the following changes: - * Changes import statements (warns of use of from Numeric import *) - * Changes import statements (using numerix) ... - * Makes search and replace changes to: - - .typecode() - - .iscontiguous() - - .byteswapped() - - .itemsize() - - .toscalar() - * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] - * Replace xxx.spacesaver() with True - * Convert xx.savespace(?) to pass + ## xx.savespace(?) - - * Converts uses of 'b' to 'B' in the typecode-position of - functions: - eye, tri (in position 4) - ones, zeros, identity, empty, array, asarray, arange, - fromstring, indices, array_constructor (in position 2) - - and methods: - astype --- only argument -""" -__all__ = ['fromfile', 'fromstr'] - -import sys -import os -import re -import glob - - -_func4 = ['eye', 'tri'] -_meth1 = ['astype'] -_func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', - 'empty', 'array', 'asarray', 'arange', 'array_constructor'] - -func_re = {} - -for name in _func2: - _astr = r"""(%s\s*[(][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name - func_re[name] = re.compile(_astr, re.DOTALL) - -for name in _func4: - _astr = r"""(%s\s*[(][^,]*?[,][^,]*?[,][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name - func_re[name] = re.compile(_astr, re.DOTALL) - -for name in _meth1: - _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name - func_re[name] = re.compile(_astr, re.DOTALL) - -def fixtypechars(fstr): - for name in _func2 + _func4 + _meth1: - fstr = func2_re[name].sub('\\1B\\2',fstr) - return fstr - -flatindex_re = re.compile('([.]flat(\s*?[[=]))') - -def changeimports(fstr, name, newname): - importstr = 'import %s' % name - importasstr = 'import %s as ' % name - fromstr = 'from %s import ' % name - fromall=0 - - fstr = fstr.replace(importasstr, 'import %s as ' % newname) - fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) - - ind = 0 - Nlen = len(fromstr) - Nlen2 = len("from %s import " % newname) - while 1: - found = fstr.find(fromstr,ind) - if (found < 0): - break - ind = found + Nlen - if fstr[ind] == '*': - continue - fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) - ind += Nlen2 - Nlen - return fstr, fromall - -def replaceattr(astr): - astr = astr.replace(".typecode()",".dtype.char") - astr = astr.replace(".iscontiguous()",".flags.contiguous") - astr = astr.replace(".byteswapped()",".byteswap()") - astr = astr.replace(".toscalar()", ".item()") - astr = astr.replace(".itemsize()",".itemsize") - # preserve uses of flat that should be o.k. - tmpstr = flatindex_re.sub(r"@@@@\2",astr) - # replace other uses of flat - tmpstr = tmpstr.replace(".flat",".ravel()") - # put back .flat where it was valid - astr = tmpstr.replace("@@@@", ".flat") - return astr - -svspc2 = re.compile(r'([^,(\s]+[.]spacesaver[(][)])') -svspc3 = re.compile(r'(\S+[.]savespace[(].*[)])') -#shpe = re.compile(r'(\S+\s*)[.]shape\s*=[^=]\s*(.+)') -def replaceother(astr): - astr = svspc2.sub('True',astr) - astr = svspc3.sub(r'pass ## \1', astr) - #astr = shpe.sub('\\1=\\1.reshape(\\2)', astr) - return astr - -import datetime -def fromstr(filestr): - filestr = fixtypechars(filestr) - filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'multiarray','numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric.precision') - filestr, fromall1 = changeimports(filestr, 'UserArray', 'numpy.oldnumeric.user_array') - filestr, fromall1 = changeimports(filestr, 'ArrayPrinter', 'numpy.oldnumeric.array_printer') - filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy.oldnumeric') - filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy.oldnumeric') - filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') - filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.oldnumeric.mlab') - filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.oldnumeric.linear_algebra') - filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.oldnumeric.rng') - filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.oldnumeric.rng_stats') - filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.oldnumeric.random_array') - filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.oldnumeric.fft') - filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.oldnumeric.ma') - fromall = fromall1 or fromall2 or fromall3 - filestr = replaceattr(filestr) - filestr = replaceother(filestr) - today = datetime.date.today().strftime('%b %d, %Y') - name = os.path.split(sys.argv[0])[-1] - filestr = '## Automatically adapted for '\ - 'numpy.oldnumeric %s by %s\n\n%s' % (today, name, filestr) - return filestr - -def makenewfile(name, filestr): - fid = file(name, 'w') - fid.write(filestr) - fid.close() - -def getandcopy(name): - fid = file(name) - filestr = fid.read() - fid.close() - base, ext = os.path.splitext(name) - makenewfile(base+'.orig', filestr) - return filestr - -def convertfile(filename): - """Convert the filename given from using Numeric to using NumPy - - Copies the file to filename.orig and then over-writes the file - with the updated code - """ - filestr = getandcopy(filename) - filestr = fromstr(filestr) - makenewfile(filename, filestr) - -def fromargs(args): - filename = args[1] - convertfile(filename) - -def convertall(direc=os.path.curdir): - """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given - - For each file, a backup of .py is made as - .py.orig. A new file named .py - is then written with the updated code. - """ - files = glob.glob(os.path.join(direc,'*.py')) - for afile in files: - convertfile(afile) - -if __name__ == '__main__': - fromargs(sys.argv) Deleted: trunk/numpy/lib/convertnumericB.py =================================================================== --- trunk/numpy/lib/convertnumericB.py 2006-08-05 08:59:42 UTC (rev 2967) +++ trunk/numpy/lib/convertnumericB.py 2006-08-05 17:00:03 UTC (rev 2968) @@ -1,135 +0,0 @@ -""" -This module converts code written for numpy.oldnumeric to work -with numpy - -Makes the following changes: - * Converts typecharacters '1swu' to 'bhHI' respectively - when used as typecodes - * Changes import statements - * Change typecode= to dtype= - * Eliminates savespace=xxx keyword arguments - * Removes it when keyword is not given as well - * replaces matrixmultiply with dot - * converts functions that don't give axis= keyword that have changed - * converts functions that don't give typecode= keyword that have changed - * converts use of capitalized type-names - * converts old function names in oldnumeric.linear_algebra, - oldnumeric.random_array, and oldnumeric.fft - -""" -#__all__ = ['fromfile', 'fromstr'] -__all__ = [] - -import warnings -warnings.warn("convetnumericB is not finished yet.") - -import sys -import os -import re -import glob - -# To convert typecharacters we need to -# Not very safe. Disabled for now.. -def replacetypechars(astr): - astr = astr.replace("'s'","'h'") - astr = astr.replace("'b'","'B'") - astr = astr.replace("'1'","'b'") - astr = astr.replace("'w'","'H'") - astr = astr.replace("'u'","'I'") - return astr - -def changeimports(fstr, name, newname): - importstr = 'import %s' % name - importasstr = 'import %s as ' % name - fromstr = 'from %s import ' % name - fromall=0 - - fstr = fstr.replace(importasstr, 'import %s as ' % newname) - fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) - - ind = 0 - Nlen = len(fromstr) - Nlen2 = len("from %s import " % newname) - while 1: - found = fstr.find(fromstr,ind) - if (found < 0): - break - ind = found + Nlen - if fstr[ind] == '*': - continue - fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) - ind += Nlen2 - Nlen - return fstr, fromall - -def replaceattr(astr): - astr = astr.replace("matrixmultiply","dot") - return astr - -def replaceother(astr): - astr = re.sub(r'typecode\s*=', 'dtype=', astr) - astr = astr.replace('ArrayType', 'ndarray') - astr = astr.replace('NewAxis', 'newaxis') - return astr - -import datetime -def fromstr(filestr): - #filestr = replacetypechars(filestr) - filestr, fromall1 = changeimports(filestr, 'numpy.oldnumeric', 'numpy') - filestr, fromall1 = changeimports(filestr, 'numpy.core.multiarray', 'numpy') - filestr, fromall1 = changeimports(filestr, 'numpy.core.umath', 'numpy') - filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', - 'numpy.linalg.old') - filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') - filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') - filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') - filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.fft.old') - filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') - fromall = fromall1 or fromall2 or fromall3 - filestr = replaceattr(filestr) - filestr = replaceother(filestr) - today = datetime.date.today().strftime('%b %d, %Y') - name = os.path.split(sys.argv[0])[-1] - filestr = '## Automatically adapted for '\ - 'numpy %s by %s\n\n%s' % (today, name, filestr) - return filestr - -def makenewfile(name, filestr): - fid = file(name, 'w') - fid.write(filestr) - fid.close() - -def getandcopy(name): - fid = file(name) - filestr = fid.read() - fid.close() - base, ext = os.path.splitext(name) - makenewfile(base+'.orig', filestr) - return filestr - -def convertfile(filename): - """Convert the filename given from using Numeric to using NumPy - - Copies the file to filename.orig and then over-writes the file - with the updated code - """ - filestr = getandcopy(filename) - filestr = fromstr(filestr) - makenewfile(filename, filestr) - -def fromargs(args): - filename = args[1] - convertfile(filename) - -def convertall(direc=os.path.curdir): - """Convert all .py files to use NumPy (from Numeric) in the directory given - - For each file, a backup of .py is made as - .py.orig. A new file named .py - is then written with the updated code. - """ - files = glob.glob(os.path.join(direc,'*.py')) - for afile in files: - convertfile(afile) - -if __name__ == '__main__': - fromargs(sys.argv) Added: trunk/numpy/numarray/alter_code1.py =================================================================== --- trunk/numpy/numarray/alter_code1.py 2006-08-05 08:59:42 UTC (rev 2967) +++ trunk/numpy/numarray/alter_code1.py 2006-08-05 17:00:03 UTC (rev 2968) @@ -0,0 +1,173 @@ +""" +This module converts code written for Numeric to run with numpy + +Makes the following changes: + * Changes import statements (warns of use of from Numeric import *) + * Changes import statements (using numerix) ... + * Makes search and replace changes to: + - .typecode() + - .iscontiguous() + - .byteswapped() + - .itemsize() + - .toscalar() + * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] + * Replace xxx.spacesaver() with True + * Convert xx.savespace(?) to pass + ## xx.savespace(?) + + * Converts uses of 'b' to 'B' in the typecode-position of + functions: + eye, tri (in position 4) + ones, zeros, identity, empty, array, asarray, arange, + fromstring, indices, array_constructor (in position 2) + + and methods: + astype --- only argument +""" +__all__ = ['fromfile', 'fromstr'] + +import sys +import os +import re +import glob + + +_func4 = ['eye', 'tri'] +_meth1 = ['astype'] +_func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', + 'empty', 'array', 'asarray', 'arange', 'array_constructor'] + +func_re = {} + +for name in _func2: + _astr = r"""(%s\s*[(][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +for name in _func4: + _astr = r"""(%s\s*[(][^,]*?[,][^,]*?[,][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +for name in _meth1: + _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +def fixtypechars(fstr): + for name in _func2 + _func4 + _meth1: + fstr = func2_re[name].sub('\\1B\\2',fstr) + return fstr + +flatindex_re = re.compile('([.]flat(\s*?[[=]))') + +def changeimports(fstr, name, newname): + importstr = 'import %s' % name + importasstr = 'import %s as ' % name + fromstr = 'from %s import ' % name + fromall=0 + + fstr = fstr.replace(importasstr, 'import %s as ' % newname) + fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) + + ind = 0 + Nlen = len(fromstr) + Nlen2 = len("from %s import " % newname) + while 1: + found = fstr.find(fromstr,ind) + if (found < 0): + break + ind = found + Nlen + if fstr[ind] == '*': + continue + fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) + ind += Nlen2 - Nlen + return fstr, fromall + +def replaceattr(astr): + astr = astr.replace(".typecode()",".dtype.char") + astr = astr.replace(".iscontiguous()",".flags.contiguous") + astr = astr.replace(".byteswapped()",".byteswap()") + astr = astr.replace(".toscalar()", ".item()") + astr = astr.replace(".itemsize()",".itemsize") + # preserve uses of flat that should be o.k. + tmpstr = flatindex_re.sub(r"@@@@\2",astr) + # replace other uses of flat + tmpstr = tmpstr.replace(".flat",".ravel()") + # put back .flat where it was valid + astr = tmpstr.replace("@@@@", ".flat") + return astr + +svspc2 = re.compile(r'([^,(\s]+[.]spacesaver[(][)])') +svspc3 = re.compile(r'(\S+[.]savespace[(].*[)])') +#shpe = re.compile(r'(\S+\s*)[.]shape\s*=[^=]\s*(.+)') +def replaceother(astr): + astr = svspc2.sub('True',astr) + astr = svspc3.sub(r'pass ## \1', astr) + #astr = shpe.sub('\\1=\\1.reshape(\\2)', astr) + return astr + +import datetime +def fromstr(filestr): + filestr = fixtypechars(filestr) + filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'multiarray','numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric.precision') + filestr, fromall1 = changeimports(filestr, 'UserArray', 'numpy.oldnumeric.user_array') + filestr, fromall1 = changeimports(filestr, 'ArrayPrinter', 'numpy.oldnumeric.array_printer') + filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy.oldnumeric') + filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy.oldnumeric') + filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') + filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.oldnumeric.mlab') + filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.oldnumeric.linear_algebra') + filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.oldnumeric.rng') + filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.oldnumeric.rng_stats') + filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.oldnumeric.random_array') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.oldnumeric.fft') + filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.oldnumeric.ma') + fromall = fromall1 or fromall2 or fromall3 + filestr = replaceattr(filestr) + filestr = replaceother(filestr) + today = datetime.date.today().strftime('%b %d, %Y') + name = os.path.split(sys.argv[0])[-1] + filestr = '## Automatically adapted for '\ + 'numpy.oldnumeric %s by %s\n\n%s' % (today, name, filestr) + return filestr + +def makenewfile(name, filestr): + fid = file(name, 'w') + fid.write(filestr) + fid.close() + +def getandcopy(name): + fid = file(name) + filestr = fid.read() + fid.close() + base, ext = os.path.splitext(name) + makenewfile(base+'.orig', filestr) + return filestr + +def convertfile(filename): + """Convert the filename given from using Numeric to using NumPy + + Copies the file to filename.orig and then over-writes the file + with the updated code + """ + filestr = getandcopy(filename) + filestr = fromstr(filestr) + makenewfile(filename, filestr) + +def fromargs(args): + filename = args[1] + convertfile(filename) + +def convertall(direc=os.path.curdir): + """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given + + For each file, a backup of .py is made as + .py.orig. A new file named .py + is then written with the updated code. + """ + files = glob.glob(os.path.join(direc,'*.py')) + for afile in files: + convertfile(afile) + +if __name__ == '__main__': + fromargs(sys.argv) Added: trunk/numpy/numarray/alter_code2.py =================================================================== --- trunk/numpy/numarray/alter_code2.py 2006-08-05 08:59:42 UTC (rev 2967) +++ trunk/numpy/numarray/alter_code2.py 2006-08-05 17:00:03 UTC (rev 2968) @@ -0,0 +1,135 @@ +""" +This module converts code written for numpy.oldnumeric to work +with numpy + +Makes the following changes: + * Converts typecharacters '1swu' to 'bhHI' respectively + when used as typecodes + * Changes import statements + * Change typecode= to dtype= + * Eliminates savespace=xxx keyword arguments + * Removes it when keyword is not given as well + * replaces matrixmultiply with dot + * converts functions that don't give axis= keyword that have changed + * converts functions that don't give typecode= keyword that have changed + * converts use of capitalized type-names + * converts old function names in oldnumeric.linear_algebra, + oldnumeric.random_array, and oldnumeric.fft + +""" +#__all__ = ['fromfile', 'fromstr'] +__all__ = [] + +import warnings +warnings.warn("convetnumericB is not finished yet.") + +import sys +import os +import re +import glob + +# To convert typecharacters we need to +# Not very safe. Disabled for now.. +def replacetypechars(astr): + astr = astr.replace("'s'","'h'") + astr = astr.replace("'b'","'B'") + astr = astr.replace("'1'","'b'") + astr = astr.replace("'w'","'H'") + astr = astr.replace("'u'","'I'") + return astr + +def changeimports(fstr, name, newname): + importstr = 'import %s' % name + importasstr = 'import %s as ' % name + fromstr = 'from %s import ' % name + fromall=0 + + fstr = fstr.replace(importasstr, 'import %s as ' % newname) + fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) + + ind = 0 + Nlen = len(fromstr) + Nlen2 = len("from %s import " % newname) + while 1: + found = fstr.find(fromstr,ind) + if (found < 0): + break + ind = found + Nlen + if fstr[ind] == '*': + continue + fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) + ind += Nlen2 - Nlen + return fstr, fromall + +def replaceattr(astr): + astr = astr.replace("matrixmultiply","dot") + return astr + +def replaceother(astr): + astr = re.sub(r'typecode\s*=', 'dtype=', astr) + astr = astr.replace('ArrayType', 'ndarray') + astr = astr.replace('NewAxis', 'newaxis') + return astr + +import datetime +def fromstr(filestr): + #filestr = replacetypechars(filestr) + filestr, fromall1 = changeimports(filestr, 'numpy.oldnumeric', 'numpy') + filestr, fromall1 = changeimports(filestr, 'numpy.core.multiarray', 'numpy') + filestr, fromall1 = changeimports(filestr, 'numpy.core.umath', 'numpy') + filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', + 'numpy.linalg.old') + filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') + filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') + filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.fft.old') + filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') + fromall = fromall1 or fromall2 or fromall3 + filestr = replaceattr(filestr) + filestr = replaceother(filestr) + today = datetime.date.today().strftime('%b %d, %Y') + name = os.path.split(sys.argv[0])[-1] + filestr = '## Automatically adapted for '\ + 'numpy %s by %s\n\n%s' % (today, name, filestr) + return filestr + +def makenewfile(name, filestr): + fid = file(name, 'w') + fid.write(filestr) + fid.close() + +def getandcopy(name): + fid = file(name) + filestr = fid.read() + fid.close() + base, ext = os.path.splitext(name) + makenewfile(base+'.orig', filestr) + return filestr + +def convertfile(filename): + """Convert the filename given from using Numeric to using NumPy + + Copies the file to filename.orig and then over-writes the file + with the updated code + """ + filestr = getandcopy(filename) + filestr = fromstr(filestr) + makenewfile(filename, filestr) + +def fromargs(args): + filename = args[1] + convertfile(filename) + +def convertall(direc=os.path.curdir): + """Convert all .py files to use NumPy (from Numeric) in the directory given + + For each file, a backup of .py is made as + .py.orig. A new file named .py + is then written with the updated code. + """ + files = glob.glob(os.path.join(direc,'*.py')) + for afile in files: + convertfile(afile) + +if __name__ == '__main__': + fromargs(sys.argv) Added: trunk/numpy/oldnumeric/alter_code1.py =================================================================== --- trunk/numpy/oldnumeric/alter_code1.py 2006-08-05 08:59:42 UTC (rev 2967) +++ trunk/numpy/oldnumeric/alter_code1.py 2006-08-05 17:00:03 UTC (rev 2968) @@ -0,0 +1,173 @@ +""" +This module converts code written for Numeric to run with numpy + +Makes the following changes: + * Changes import statements (warns of use of from Numeric import *) + * Changes import statements (using numerix) ... + * Makes search and replace changes to: + - .typecode() + - .iscontiguous() + - .byteswapped() + - .itemsize() + - .toscalar() + * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] + * Replace xxx.spacesaver() with True + * Convert xx.savespace(?) to pass + ## xx.savespace(?) + + * Converts uses of 'b' to 'B' in the typecode-position of + functions: + eye, tri (in position 4) + ones, zeros, identity, empty, array, asarray, arange, + fromstring, indices, array_constructor (in position 2) + + and methods: + astype --- only argument +""" +__all__ = ['fromfile', 'fromstr'] + +import sys +import os +import re +import glob + + +_func4 = ['eye', 'tri'] +_meth1 = ['astype'] +_func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', + 'empty', 'array', 'asarray', 'arange', 'array_constructor'] + +func_re = {} + +for name in _func2: + _astr = r"""(%s\s*[(][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +for name in _func4: + _astr = r"""(%s\s*[(][^,]*?[,][^,]*?[,][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +for name in _meth1: + _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name + func_re[name] = re.compile(_astr, re.DOTALL) + +def fixtypechars(fstr): + for name in _func2 + _func4 + _meth1: + fstr = func2_re[name].sub('\\1B\\2',fstr) + return fstr + +flatindex_re = re.compile('([.]flat(\s*?[[=]))') + +def changeimports(fstr, name, newname): + importstr = 'import %s' % name + importasstr = 'import %s as ' % name + fromstr = 'from %s import ' % name + fromall=0 + + fstr = fstr.replace(importasstr, 'import %s as ' % newname) + fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) + + ind = 0 + Nlen = len(fromstr) + Nlen2 = len("from %s import " % newname) + while 1: + found = fstr.find(fromstr,ind) + if (found < 0): + break + ind = found + Nlen + if fstr[ind] == '*': + continue + fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) + ind += Nlen2 - Nlen + return fstr, fromall + +def replaceattr(astr): + astr = astr.replace(".typecode()",".dtype.char") + astr = astr.replace(".iscontiguous()",".flags.contiguous") + astr = astr.replace(".byteswapped()",".byteswap()") + astr = astr.replace(".toscalar()", ".item()") + astr = astr.replace(".itemsize()",".itemsize") + # preserve uses of flat that should be o.k. + tmpstr = flatindex_re.sub(r"@@@@\2",astr) + # replace other uses of flat + tmpstr = tmpstr.replace(".flat",".ravel()") + # put back .flat where it was valid + astr = tmpstr.replace("@@@@", ".flat") + return astr + +svspc2 = re.compile(r'([^,(\s]+[.]spacesaver[(][)])') +svspc3 = re.compile(r'(\S+[.]savespace[(].*[)])') +#shpe = re.compile(r'(\S+\s*)[.]shape\s*=[^=]\s*(.+)') +def replaceother(astr): + astr = svspc2.sub('True',astr) + astr = svspc3.sub(r'pass ## \1', astr) + #astr = shpe.sub('\\1=\\1.reshape(\\2)', astr) + return astr + +import datetime +def fromstr(filestr): + filestr = fixtypechars(filestr) + filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'multiarray','numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') + filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric.precision') + filestr, fromall1 = changeimports(filestr, 'UserArray', 'numpy.oldnumeric.user_array') + filestr, fromall1 = changeimports(filestr, 'ArrayPrinter', 'numpy.oldnumeric.array_printer') + filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy.oldnumeric') + filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy.oldnumeric') + filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') + filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.oldnumeric.mlab') + filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.oldnumeric.linear_algebra') + filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.oldnumeric.rng') + filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.oldnumeric.rng_stats') + filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.oldnumeric.random_array') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.oldnumeric.fft') + filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.oldnumeric.ma') + fromall = fromall1 or fromall2 or fromall3 + filestr = replaceattr(filestr) + filestr = replaceother(filestr) + today = datetime.date.today().strftime('%b %d, %Y') + name = os.path.split(sys.argv[0])[-1] + filestr = '## Automatically adapted for '\ + 'numpy.oldnumeric %s by %s\n\n%s' % (today, name, filestr) + return filestr + +def makenewfile(name, filestr): + fid = file(name, 'w') + fid.write(filestr) + fid.close() + +def getandcopy(name): + fid = file(name) + filestr = fid.read() + fid.close() + base, ext = os.path.splitext(name) + makenewfile(base+'.orig', filestr) + return filestr + +def convertfile(filename): + """Convert the filename given from using Numeric to using NumPy + + Copies the file to filename.orig and then over-writes the file + with the updated code + """ + filestr = getandcopy(filename) + filestr = fromstr(filestr) + makenewfile(filename, filestr) + +def fromargs(args): + filename = args[1] + convertfile(filename) + +def convertall(direc=os.path.curdir): + """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given + + For each file, a backup of .py is made as + .py.orig. A new file named .py + is then written with the updated code. + """ + files = glob.glob(os.path.join(direc,'*.py')) + for afile in files: + convertfile(afile) + +if __name__ == '__main__': + fromargs(sys.argv) Added: trunk/numpy/oldnumeric/alter_code2.py =================================================================== --- trunk/numpy/oldnumeric/alter_code2.py 2006-08-05 08:59:42 UTC (rev 2967) +++ trunk/numpy/oldnumeric/alter_code2.py 2006-08-05 17:00:03 UTC (rev 2968) @@ -0,0 +1,135 @@ +""" +This module converts code written for numpy.oldnumeric to work +with numpy + +Makes the following changes: + * Converts typecharacters '1swu' to 'bhHI' respectively + when used as typecodes + * Changes import statements + * Change typecode= to dtype= + * Eliminates savespace=xxx keyword arguments + * Removes it when keyword is not given as well + * replaces matrixmultiply with dot + * converts functions that don't give axis= keyword that have changed + * converts functions that don't give typecode= keyword that have changed + * converts use of capitalized type-names + * converts old function names in oldnumeric.linear_algebra, + oldnumeric.random_array, and oldnumeric.fft + +""" +#__all__ = ['fromfile', 'fromstr'] +__all__ = [] + +import warnings +warnings.warn("convetnumericB is not finished yet.") + +import sys +import os +import re +import glob + +# To convert typecharacters we need to +# Not very safe. Disabled for now.. +def replacetypechars(astr): + astr = astr.replace("'s'","'h'") + astr = astr.replace("'b'","'B'") + astr = astr.replace("'1'","'b'") + astr = astr.replace("'w'","'H'") + astr = astr.replace("'u'","'I'") + return astr + +def changeimports(fstr, name, newname): + importstr = 'import %s' % name + importasstr = 'import %s as ' % name + fromstr = 'from %s import ' % name + fromall=0 + + fstr = fstr.replace(importasstr, 'import %s as ' % newname) + fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) + + ind = 0 + Nlen = len(fromstr) + Nlen2 = len("from %s import " % newname) + while 1: + found = fstr.find(fromstr,ind) + if (found < 0): + break + ind = found + Nlen + if fstr[ind] == '*': + continue + fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:]) + ind += Nlen2 - Nlen + return fstr, fromall + +def replaceattr(astr): + astr = astr.replace("matrixmultiply","dot") + return astr + +def replaceother(astr): + astr = re.sub(r'typecode\s*=', 'dtype=', astr) + astr = astr.replace('ArrayType', 'ndarray') + astr = astr.replace('NewAxis', 'newaxis') + return astr + +import datetime +def fromstr(filestr): + #filestr = replacetypechars(filestr) + filestr, fromall1 = changeimports(filestr, 'numpy.oldnumeric', 'numpy') + filestr, fromall1 = changeimports(filestr, 'numpy.core.multiarray', 'numpy') + filestr, fromall1 = changeimports(filestr, 'numpy.core.umath', 'numpy') + filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', + 'numpy.linalg.old') + filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.random.oldrng') + filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.random.oldrngstats') + filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.random.oldrandomarray') + filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.fft.old') + filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.core.ma') + fromall = fromall1 or fromall2 or fromall3 + filestr = replaceattr(filestr) + filestr = replaceother(filestr) + today = datetime.date.today().strftime('%b %d, %Y') + name = os.path.split(sys.argv[0])[-1] + filestr = '## Automatically adapted for '\ + 'numpy %s by %s\n\n%s' % (today, name, filestr) + return filestr + +def makenewfile(name, filestr): + fid = file(name, 'w') + fid.write(filestr) + fid.close() + +def getandcopy(name): + fid = file(name) + filestr = fid.read() + fid.close() + base, ext = os.path.splitext(name) + makenewfile(base+'.orig', filestr) + return filestr + +def convertfile(filename): + """Convert the filename given from using Numeric to using NumPy + + Copies the file to filename.orig and then over-writes the file + with the updated code + """ + filestr = getandcopy(filename) + filestr = fromstr(filestr) + makenewfile(filename, filestr) + +def fromargs(args): + filename = args[1] + convertfile(filename) + +def convertall(direc=os.path.curdir): + """Convert all .py files to use NumPy (from Numeric) in the directory given + + For each file, a backup of .py is made as + .py.orig. A new file named .py + is then written with the updated code. + """ + files = glob.glob(os.path.join(direc,'*.py')) + for afile in files: + convertfile(afile) + +if __name__ == '__main__': + fromargs(sys.argv) From numpy-svn at scipy.org Sat Aug 5 14:02:37 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 13:02:37 -0500 (CDT) Subject: [Numpy-svn] r2969 - trunk/numpy/oldnumeric Message-ID: <20060805180237.89ED139C0B6@new.scipy.org> Author: oliphant Date: 2006-08-05 13:02:33 -0500 (Sat, 05 Aug 2006) New Revision: 2969 Modified: trunk/numpy/oldnumeric/alter_code1.py trunk/numpy/oldnumeric/compat.py trunk/numpy/oldnumeric/functions.py trunk/numpy/oldnumeric/misc.py trunk/numpy/oldnumeric/ufuncs.py Log: Un-deprecate some names in Numeric. Modified: trunk/numpy/oldnumeric/alter_code1.py =================================================================== --- trunk/numpy/oldnumeric/alter_code1.py 2006-08-05 17:00:03 UTC (rev 2968) +++ trunk/numpy/oldnumeric/alter_code1.py 2006-08-05 18:02:33 UTC (rev 2969) @@ -22,6 +22,11 @@ and methods: astype --- only argument + -- converts uses of '1', 's', 'w', and 'u' to + -- 'b', 'h', 'H', and 'I' + + * Converts uses of type(...) is + isinstance(..., ) """ __all__ = ['fromfile', 'fromstr'] @@ -36,7 +41,10 @@ _func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', 'empty', 'array', 'asarray', 'arange', 'array_constructor'] +_chars = {'1':'b','s':'h','w':'H','u':'I'} + func_re = {} +meth_re = {} for name in _func2: _astr = r"""(%s\s*[(][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name @@ -50,9 +58,15 @@ _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name func_re[name] = re.compile(_astr, re.DOTALL) +for char in _chars.keys(): + _astr = r"""(.astype\s*[(][^'"]*?['"])%s(['"][^)]*?[)])"""%char + meth_re[char] = re.compile(_astr, re.DOTALL) + def fixtypechars(fstr): for name in _func2 + _func4 + _meth1: fstr = func2_re[name].sub('\\1B\\2',fstr) + for char in _chars.keys(): + fstr = meth_re[char].sub('\\1%s\\2'%_chars[char], fstr) return fstr flatindex_re = re.compile('([.]flat(\s*?[[=]))') @@ -80,6 +94,17 @@ ind += Nlen2 - Nlen return fstr, fromall +istest_re = {} +_types = ['float', 'int', 'complex', 'ArrayType', 'FloatType', + 'IntType', 'ComplexType'] +for name in _types: + _astr = r'type\s*[(]([^)]*)[)]\s+(?:is|==)\s+(.*?%s)'%name + istest_re[name] = re.compile(_astr) +def fixistesting(astr): + for name in _types: + astr = istest_re[name].sub('isinstance(\\1, \\2)', astr) + return astr + def replaceattr(astr): astr = astr.replace(".typecode()",".dtype.char") astr = astr.replace(".iscontiguous()",".flags.contiguous") @@ -106,6 +131,7 @@ import datetime def fromstr(filestr): filestr = fixtypechars(filestr) + filestr = fixistesting(filestr) filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'multiarray','numpy.oldnumeric') filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') Modified: trunk/numpy/oldnumeric/compat.py =================================================================== --- trunk/numpy/oldnumeric/compat.py 2006-08-05 17:00:03 UTC (rev 2968) +++ trunk/numpy/oldnumeric/compat.py 2006-08-05 18:02:33 UTC (rev 2969) @@ -2,11 +2,9 @@ __all__ = ['NewAxis', 'UFuncType', 'UfuncType', 'ArrayType', 'arraytype', - 'LittleEndian', - 'sarray', 'arrayrange', 'cross_correlate', - 'matrixmultiply', 'outerproduct', 'innerproduct', - 'cross_product', 'array_constructor', 'pickle_array', - 'DumpArray', 'LoadArray', 'multiarray', 'divide_safe', + 'LittleEndian', 'arrayrange', 'matrixmultiply', + 'array_constructor', 'pickle_array', + 'DumpArray', 'LoadArray', 'multiarray', # from cPickle 'dump', 'dumps' ] @@ -15,15 +13,13 @@ import numpy.core.umath as um from numpy.core.numeric import array, correlate, outer, cross from numpy.core.umath import sign, absolute, multiply +import functions import sys import types from cPickle import dump, dumps -def sarray(a, dtype=None, copy=False): - return array(a, dtype, copy) - mu = multiarray #Use this to add a new axis to an array @@ -41,17 +37,11 @@ from numpy import deprecate # backward compatibility -arrayrange = deprecate(mu.arange, 'arrayrange', 'arange') -cross_correlate = deprecate(correlate, 'cross_correlate', 'correlate') -cross_product = deprecate(cross, 'cross_product', 'cross') -divide_safe = deprecate(um.divide, 'divide_safe', 'divide') +arrayrange = deprecate(functions.arange, 'arrayrange', 'arange') # deprecated names matrixmultiply = deprecate(mu.dot, 'matrixmultiply', 'dot') -outerproduct = deprecate(outer, 'outerproduct', 'outer') -innerproduct = deprecate(mu.inner, 'innerproduct', 'inner') - def DumpArray(m, fp): m.dump(fp) Modified: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-05 17:00:03 UTC (rev 2968) +++ trunk/numpy/oldnumeric/functions.py 2006-08-05 18:02:33 UTC (rev 2969) @@ -9,7 +9,7 @@ 'cumsum', 'cumproduct', 'ones', 'empty', 'identity', 'zeros', 'array', 'asarray', 'nonzero', 'reshape', 'arange', 'fromstring', 'ravel', 'trace', - 'indices', 'where'] + 'indices', 'where','sarray','cross_product'] def take(a, indicies, axis=0): return N.take(a, indicies, axis) @@ -65,6 +65,10 @@ dtype = convtypecode2(typecode, dtype) return mu.array(sequence, dtype, copy=copy) +def sarray(a, typecode=None, copy=False, dtype=None): + dtype = convtypecode2(typecode, dtype) + return mu.array(a, dtype, copy) + def asarray(a, typecode=None, dtype=None): dtype = convtypecode2(typecode, dtype) return mu.array(a, dtype, copy=0) @@ -99,3 +103,6 @@ def where(condition, x, y): return N.where(condition, x, y) + +def cross_product(a, b, axis1=-1, axis2=-1): + return N.cross(a, b, axis1, axis2) Modified: trunk/numpy/oldnumeric/misc.py =================================================================== --- trunk/numpy/oldnumeric/misc.py 2006-08-05 17:00:03 UTC (rev 2968) +++ trunk/numpy/oldnumeric/misc.py 2006-08-05 18:02:33 UTC (rev 2969) @@ -8,8 +8,8 @@ 'around', 'vdot', 'transpose', 'array2string', 'diagonal', 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', 'array_repr', 'e', 'argmin', 'StringIO', 'pickle', 'average', - 'argsort', 'convolve', 'loads', - 'Pickler', 'dot'] + 'argsort', 'convolve', 'loads', 'cross_correlate', + 'Pickler', 'dot', 'outerproduct', 'innerproduct'] import types import StringIO @@ -22,7 +22,8 @@ from numpy import sort, clip, putmask, rank, sign, shape, allclose, size,\ argmax, choose, swapaxes, array_str, array_repr, argmin, e, pi, \ fromfunction, resize, around, compress, concatenate, vdot, transpose, \ - diagonal, searchsorted, put, average, argsort, convolve, dot + diagonal, searchsorted, put, average, argsort, convolve, dot, \ + outer as outerproduct, inner as innerproduct, correlate as cross_correlate from array_printer import array2string Modified: trunk/numpy/oldnumeric/ufuncs.py =================================================================== --- trunk/numpy/oldnumeric/ufuncs.py 2006-08-05 17:00:03 UTC (rev 2968) +++ trunk/numpy/oldnumeric/ufuncs.py 2006-08-05 18:02:33 UTC (rev 2969) @@ -6,7 +6,8 @@ 'not_equal', 'tanh', 'true_divide', 'maximum', 'arccosh', 'logical_or', 'minimum', 'conjugate', 'tan', 'greater', 'bitwise_xor', 'fabs', 'floor', 'sqrt', 'arctan', 'right_shift', - 'absolute', 'sin', 'multiply', 'greater_equal', 'left_shift', 'exp'] + 'absolute', 'sin', 'multiply', 'greater_equal', 'left_shift', + 'exp', 'divide_safe'] from numpy import less, cosh, arcsinh, add, ceil, arctan2, floor_divide, \ fmod, hypot, logical_and, power, sinh, remainder, cos, \ @@ -15,5 +16,5 @@ arctanh, logical_not, not_equal, tanh, true_divide, maximum, \ arccosh, logical_or, minimum, conjugate, tan, greater, bitwise_xor, \ fabs, floor, sqrt, arctan, right_shift, absolute, sin, \ - multiply, greater_equal, left_shift, exp + multiply, greater_equal, left_shift, exp, divide as divide_safe From numpy-svn at scipy.org Sat Aug 5 16:25:01 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 15:25:01 -0500 (CDT) Subject: [Numpy-svn] r2970 - in trunk/numpy: lib numarray Message-ID: <20060805202501.1E27739C0B6@new.scipy.org> Author: oliphant Date: 2006-08-05 15:24:55 -0500 (Sat, 05 Aug 2006) New Revision: 2970 Added: trunk/numpy/numarray/convolve.py trunk/numpy/numarray/image.py trunk/numpy/numarray/nd_image.py Modified: trunk/numpy/lib/utils.py trunk/numpy/numarray/alter_code1.py Log: Move source, info, and who to NumPy Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-05 18:02:33 UTC (rev 2969) +++ trunk/numpy/lib/utils.py 2006-08-05 20:24:55 UTC (rev 2970) @@ -1,10 +1,15 @@ import sys, os +import inspect +import types +import pydoc from numpy.core.numerictypes import obj2sctype from numpy.core.multiarray import dtype +from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', 'issubdtype', 'deprecate', 'get_numarray_include', - 'get_include', 'ctypes_load_library'] + 'get_include', 'ctypes_load_library', 'info', + 'source', 'who'] def issubclass_(arg1, arg2): try: @@ -107,7 +112,276 @@ newfunc.__dict__.update(d) return newfunc - get_numpy_include = deprecate(get_include, 'get_numpy_include', 'get_include') +#----------------------------------------------------------------------------- +# Function for output and information on the variables used. +#----------------------------------------------------------------------------- + + +def who(vardict=None): + """Print the scipy arrays in the given dictionary (or globals() if None). + """ + if vardict is None: + frame = sys._getframe().f_back + vardict = frame.f_globals + sta = [] + cache = {} + for name in vardict.keys(): + if isinstance(vardict[name],ndarray): + var = vardict[name] + idv = id(var) + if idv in cache.keys(): + namestr = name + " (%s)" % cache[idv] + original=0 + else: + cache[idv] = name + namestr = name + original=1 + shapestr = " x ".join(map(str, var.shape)) + bytestr = str(var.itemsize*product(var.shape)) + sta.append([namestr, shapestr, bytestr, var.dtype.name, + original]) + + maxname = 0 + maxshape = 0 + maxbyte = 0 + totalbytes = 0 + for k in range(len(sta)): + val = sta[k] + if maxname < len(val[0]): + maxname = len(val[0]) + if maxshape < len(val[1]): + maxshape = len(val[1]) + if maxbyte < len(val[2]): + maxbyte = len(val[2]) + if val[4]: + totalbytes += int(val[2]) + + if len(sta) > 0: + sp1 = max(10,maxname) + sp2 = max(10,maxshape) + sp3 = max(10,maxbyte) + prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ') + print prval + "\n" + "="*(len(prval)+5) + "\n" + + for k in range(len(sta)): + val = sta[k] + print "%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4), + val[1], ' '*(sp2-len(val[1])+5), + val[2], ' '*(sp3-len(val[2])+5), + val[3]) + print "\nUpper bound on total bytes = %d" % totalbytes + return + +#----------------------------------------------------------------------------- + + +# NOTE: pydoc defines a help function which works simliarly to this +# except it uses a pager to take over the screen. + +# combine name and arguments and split to multiple lines of +# width characters. End lines on a comma and begin argument list +# indented with the rest of the arguments. +def _split_line(name, arguments, width): + firstwidth = len(name) + k = firstwidth + newstr = name + sepstr = ", " + arglist = arguments.split(sepstr) + for argument in arglist: + if k == firstwidth: + addstr = "" + else: + addstr = sepstr + k = k + len(argument) + len(addstr) + if k > width: + k = firstwidth + 1 + len(argument) + newstr = newstr + ",\n" + " "*(firstwidth+2) + argument + else: + newstr = newstr + addstr + argument + return newstr + +_namedict = None +_dictlist = None + +# Traverse all module directories underneath globals +# to see if something is defined +def _makenamedict(module='numpy'): + module = __import__(module, globals(), locals(), []) + thedict = {module.__name__:module.__dict__} + dictlist = [module.__name__] + totraverse = [module.__dict__] + while 1: + if len(totraverse) == 0: + break + thisdict = totraverse.pop(0) + for x in thisdict.keys(): + if isinstance(thisdict[x],types.ModuleType): + modname = thisdict[x].__name__ + if modname not in dictlist: + moddict = thisdict[x].__dict__ + dictlist.append(modname) + totraverse.append(moddict) + thedict[modname] = moddict + return thedict, dictlist + + +def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): + """Get help information for a function, class, or module. + + Example: + >>> from numpy import * + >>> info(polyval) + polyval(p, x) + + Evaluate the polymnomial p at x. + + Description: + If p is of length N, this function returns the value: + p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] + """ + global _namedict, _dictlist + + if hasattr(object,'_ppimport_importer') or \ + hasattr(object, '_ppimport_module'): + object = object._ppimport_module + elif hasattr(object, '_ppimport_attr'): + object = object._ppimport_attr + + if object is None: + info(info) + elif isinstance(object, types.StringType): + if _namedict is None: + _namedict, _dictlist = _makenamedict(toplevel) + numfound = 0 + objlist = [] + for namestr in _dictlist: + try: + obj = _namedict[namestr][object] + if id(obj) in objlist: + print >> output, "\n *** Repeat reference found in %s *** " % namestr + else: + objlist.append(id(obj)) + print >> output, " *** Found in %s ***" % namestr + info(obj) + print >> output, "-"*maxwidth + numfound += 1 + except KeyError: + pass + if numfound == 0: + print >> output, "Help for %s not found." % object + else: + print >> output, "\n *** Total of %d references found. ***" % numfound + + elif inspect.isfunction(object): + name = object.func_name + arguments = apply(inspect.formatargspec, inspect.getargspec(object)) + + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + print >> output, inspect.getdoc(object) + + elif inspect.isclass(object): + name = object.__name__ + if hasattr(object, '__init__'): + arguments = apply(inspect.formatargspec, inspect.getargspec(object.__init__.im_func)) + arglist = arguments.split(', ') + if len(arglist) > 1: + arglist[1] = "("+arglist[1] + arguments = ", ".join(arglist[1:]) + else: + arguments = "()" + else: + arguments = "()" + + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + doc1 = inspect.getdoc(object) + if doc1 is None: + if hasattr(object,'__init__'): + print >> output, inspect.getdoc(object.__init__) + else: + print >> output, inspect.getdoc(object) + + methods = pydoc.allmethods(object) + if methods != []: + print >> output, "\n\nMethods:\n" + for meth in methods: + if meth[0] == '_': + continue + thisobj = getattr(object, meth, None) + if thisobj is not None: + methstr, other = pydoc.splitdoc(inspect.getdoc(thisobj) or "None") + print >> output, " %s -- %s" % (meth, methstr) + + elif type(object) is types.InstanceType: ## check for __call__ method + print >> output, "Instance of class: ", object.__class__.__name__ + print >> output + if hasattr(object, '__call__'): + arguments = apply(inspect.formatargspec, inspect.getargspec(object.__call__.im_func)) + arglist = arguments.split(', ') + if len(arglist) > 1: + arglist[1] = "("+arglist[1] + arguments = ", ".join(arglist[1:]) + else: + arguments = "()" + + if hasattr(object,'name'): + name = "%s" % object.name + else: + name = "" + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + doc = inspect.getdoc(object.__call__) + if doc is not None: + print >> output, inspect.getdoc(object.__call__) + print >> output, inspect.getdoc(object) + + else: + print >> output, inspect.getdoc(object) + + elif inspect.ismethod(object): + name = object.__name__ + arguments = apply(inspect.formatargspec, inspect.getargspec(object.im_func)) + arglist = arguments.split(', ') + if len(arglist) > 1: + arglist[1] = "("+arglist[1] + arguments = ", ".join(arglist[1:]) + else: + arguments = "()" + + if len(name+arguments) > maxwidth: + argstr = _split_line(name, arguments, maxwidth) + else: + argstr = name + arguments + + print >> output, " " + argstr + "\n" + print >> output, inspect.getdoc(object) + + elif hasattr(object, '__doc__'): + print >> output, inspect.getdoc(object) + + +def source(object, output=sys.stdout): + """Write source for this object to output. + """ + try: + print >> output, "In file: %s\n" % inspect.getsourcefile(object) + print >> output, inspect.getsource(object) + except: + print >> output, "Not available for this object." + Modified: trunk/numpy/numarray/alter_code1.py =================================================================== --- trunk/numpy/numarray/alter_code1.py 2006-08-05 18:02:33 UTC (rev 2969) +++ trunk/numpy/numarray/alter_code1.py 2006-08-05 20:24:55 UTC (rev 2970) @@ -2,26 +2,46 @@ This module converts code written for Numeric to run with numpy Makes the following changes: - * Changes import statements (warns of use of from Numeric import *) - * Changes import statements (using numerix) ... - * Makes search and replace changes to: - - .typecode() - - .iscontiguous() - - .byteswapped() - - .itemsize() - - .toscalar() - * Converts .flat to .ravel() except for .flat = xxx or .flat[xxx] - * Replace xxx.spacesaver() with True - * Convert xx.savespace(?) to pass + ## xx.savespace(?) + * Changes import statements - * Converts uses of 'b' to 'B' in the typecode-position of - functions: - eye, tri (in position 4) - ones, zeros, identity, empty, array, asarray, arange, - fromstring, indices, array_constructor (in position 2) + Stubs for + convolve --> numarray.convolve + image --> numarray.image + nd_image --> numarray.nd_image - and methods: - astype --- only argument + * Makes search and replace changes to: + - .imaginary --> .imag + - .flat --> .ravel() (most of the time) + - .byteswapped() --> .byteswap(False) + - .byteswap() --> .byteswap(True) + - .info() --> numarray.info(self) + - .isaligned() --> .flags.aligned + - .isbyteswapped() --> (not .dtype.isnative) + - .typecode() --> .dtype.char + - .iscontiguous() --> .flags.contiguous + - .is_c_array() --> .flags.carray and .dtype.isnative + - .is_fortran_contiguous() --> .flags.fortran + - .is_f_array() --> .dtype.isnative and .flags.farray + - .itemsize() --> .itemsize + - .nelements() --> .size + - self.new(None) --> emtpy_like(self) + - self.new(type) --> empty(self.shape, type) + - .repeat(r) --> .repeat(r, axis=0) + - .size() --> .size + - .type() -- numarray.type(self.dtype) + - .typecode() --> .dtype.char + - .stddev() --> .std() + - .togglebyteorder() --> self.dtype=self.dtype.newbyteorder() + - .getshape() --> .shape + - .setshape(obj) --> .shape=obj + - .getflat() --> .ravel() + - .getreal() --> .real + - .setreal() --> .real = + - .getimag() --> .imag + - .setimag() --> .imag = + - .getimaginary() --> .imag + - .setimaginary() --> .imag + """ __all__ = ['fromfile', 'fromstr'] Added: trunk/numpy/numarray/convolve.py =================================================================== --- trunk/numpy/numarray/convolve.py 2006-08-05 18:02:33 UTC (rev 2969) +++ trunk/numpy/numarray/convolve.py 2006-08-05 20:24:55 UTC (rev 2970) @@ -0,0 +1,14 @@ +try: + from stsci.convolve import * +except ImportError: + try: + from scipy.stsci.convolve import * + except ImportError: + msg = \ +"""The convolve package is not installed. + +It can be downloaded by checking out the latest source from +http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and +installing all of SciPy from http://www.scipy.org. +""" + raise ImportError(msg) Added: trunk/numpy/numarray/image.py =================================================================== --- trunk/numpy/numarray/image.py 2006-08-05 18:02:33 UTC (rev 2969) +++ trunk/numpy/numarray/image.py 2006-08-05 20:24:55 UTC (rev 2970) @@ -0,0 +1,15 @@ +try: + from stsci.image import * +except ImportError: + try: + from scipy.stsci.image import * + except ImportError: + msg = \ +"""The image package is not installed + +It can be downloaded by checking out the latest source from +http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and +installing all of SciPy from http://www.scipy.org. +""" + raise ImportError(msg) + Added: trunk/numpy/numarray/nd_image.py =================================================================== --- trunk/numpy/numarray/nd_image.py 2006-08-05 18:02:33 UTC (rev 2969) +++ trunk/numpy/numarray/nd_image.py 2006-08-05 20:24:55 UTC (rev 2970) @@ -0,0 +1,14 @@ +try: + from ndimage import * +except ImportError: + try: + from scipy.ndimage import * + except ImportError: + msg = \ +"""The nd_image package is not installed + +It can be downloaded by checking out the latest source from +http://svn.scipy.org/svn/scipy/trunk/Lib/ndimage or by downloading and +installing all of SciPy from http://www.scipy.org. +""" + raise ImportError(msg) From numpy-svn at scipy.org Sat Aug 5 16:36:42 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 15:36:42 -0500 (CDT) Subject: [Numpy-svn] r2971 - in trunk/numpy: numarray oldnumeric Message-ID: <20060805203642.247D039C0B6@new.scipy.org> Author: oliphant Date: 2006-08-05 15:36:39 -0500 (Sat, 05 Aug 2006) New Revision: 2971 Modified: trunk/numpy/numarray/alter_code2.py trunk/numpy/oldnumeric/alter_code2.py Log: Minor changes to alter_code scripts Modified: trunk/numpy/numarray/alter_code2.py =================================================================== --- trunk/numpy/numarray/alter_code2.py 2006-08-05 20:24:55 UTC (rev 2970) +++ trunk/numpy/numarray/alter_code2.py 2006-08-05 20:36:39 UTC (rev 2971) @@ -1,29 +1,16 @@ """ -This module converts code written for numpy.oldnumeric to work +This module converts code written for numpy.numarray to work with numpy -Makes the following changes: - * Converts typecharacters '1swu' to 'bhHI' respectively - when used as typecodes - * Changes import statements - * Change typecode= to dtype= - * Eliminates savespace=xxx keyword arguments - * Removes it when keyword is not given as well - * replaces matrixmultiply with dot - * converts functions that don't give axis= keyword that have changed - * converts functions that don't give typecode= keyword that have changed - * converts use of capitalized type-names - * converts old function names in oldnumeric.linear_algebra, - oldnumeric.random_array, and oldnumeric.fft - """ #__all__ = ['fromfile', 'fromstr'] __all__ = [] import warnings -warnings.warn("convetnumericB is not finished yet.") - +warnings.warn("numpy.numarray.alter_code2 is not ready yet.") import sys + + import os import re import glob Modified: trunk/numpy/oldnumeric/alter_code2.py =================================================================== --- trunk/numpy/oldnumeric/alter_code2.py 2006-08-05 20:24:55 UTC (rev 2970) +++ trunk/numpy/oldnumeric/alter_code2.py 2006-08-05 20:36:39 UTC (rev 2971) @@ -21,7 +21,7 @@ __all__ = [] import warnings -warnings.warn("convetnumericB is not finished yet.") +warnings.warn("numpy.oldnumeric.alter_code2 is not ready yet.") import sys import os From numpy-svn at scipy.org Sat Aug 5 18:25:58 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 17:25:58 -0500 (CDT) Subject: [Numpy-svn] r2972 - trunk/numpy/core Message-ID: <20060805222558.C4F6939C0C7@new.scipy.org> Author: oliphant Date: 2006-08-05 17:25:56 -0500 (Sat, 05 Aug 2006) New Revision: 2972 Modified: trunk/numpy/core/numerictypes.py Log: Add complex types correctly. Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-05 20:36:39 UTC (rev 2971) +++ trunk/numpy/core/numerictypes.py 2006-08-05 22:25:56 UTC (rev 2972) @@ -301,7 +301,7 @@ for bytes in fbytes: bits = 8*bytes _add_array_type('float', bits) - _add_array_type('complex', bits) + _add_array_type('complex', 2*bits) _gi = dtype('p') if _gi.type not in sctypes['int']: sctypes['int'].append(_gi.type) From numpy-svn at scipy.org Sat Aug 5 18:29:49 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 5 Aug 2006 17:29:49 -0500 (CDT) Subject: [Numpy-svn] r2973 - trunk/numpy/lib Message-ID: <20060805222949.111AE39C0C7@new.scipy.org> Author: oliphant Date: 2006-08-05 17:29:46 -0500 (Sat, 05 Aug 2006) New Revision: 2973 Modified: trunk/numpy/lib/function_base.py Log: Fix adding docstrings of digitize, bincount, and add_docstring so it doesn't happen twice. Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-05 22:25:56 UTC (rev 2972) +++ trunk/numpy/lib/function_base.py 2006-08-05 22:29:46 UTC (rev 2973) @@ -394,39 +394,48 @@ else: return a[slice1]-a[slice2] -add_docstring(digitize, - r"""digitize(x,bins) +try: + add_docstring(digitize, +r"""digitize(x,bins) - Return the index of the bin to which each value of x belongs. - - Each index i returned is such that bins[i-1] <= x < bins[i] if - bins is monotonically increasing, or bins [i-1] > x >= bins[i] if - bins is monotonically decreasing. +Return the index of the bin to which each value of x belongs. + +Each index i returned is such that bins[i-1] <= x < bins[i] if +bins is monotonically increasing, or bins [i-1] > x >= bins[i] if +bins is monotonically decreasing. - Beyond the bounds of the bins 0 or len(bins) is returned as appropriate. - """) +Beyond the bounds of the bins 0 or len(bins) is returned as appropriate. +""") +except RuntimeError: + pass -add_docstring(bincount, - r"""bincount(x,weights=None) - - Return the number of occurrences of each value in x. +try: + add_docstring(bincount, +r"""bincount(x,weights=None) + +Return the number of occurrences of each value in x. - x must be a list of non-negative integers. The output, b[i], - represents the number of times that i is found in x. If weights - is specified, every occurrence of i at a position p contributes - weights[p] instead of 1. +x must be a list of non-negative integers. The output, b[i], +represents the number of times that i is found in x. If weights +is specified, every occurrence of i at a position p contributes +weights[p] instead of 1. - See also: histogram, digitize, unique. - """) +See also: histogram, digitize, unique. +""") +except RuntimeError: + pass -add_docstring(add_docstring, - r"""docstring(obj, docstring) +try: + add_docstring(add_docstring, +r"""docstring(obj, docstring) - Add a docstring to a built-in obj if possible. - If the obj already has a docstring raise a RuntimeError - If this routine does not know how to add a docstring to the object - raise a TypeError - """) +Add a docstring to a built-in obj if possible. +If the obj already has a docstring raise a RuntimeError +If this routine does not know how to add a docstring to the object +raise a TypeError +""") +except RuntimeError: + pass def angle(z, deg=0): """Return the angle of the complex argument z. From numpy-svn at scipy.org Tue Aug 8 01:13:08 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 8 Aug 2006 00:13:08 -0500 (CDT) Subject: [Numpy-svn] r2974 - in trunk/numpy: core/src numarray Message-ID: <20060808051308.15E3A39C080@new.scipy.org> Author: oliphant Date: 2006-08-08 00:13:02 -0500 (Tue, 08 Aug 2006) New Revision: 2974 Modified: trunk/numpy/core/src/arraymethods.c trunk/numpy/numarray/alter_code1.py Log: Fix segfault in Ticket #238 Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-05 22:29:46 UTC (rev 2973) +++ trunk/numpy/core/src/arraymethods.c 2006-08-08 05:13:02 UTC (rev 2974) @@ -359,6 +359,12 @@ 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); Modified: trunk/numpy/numarray/alter_code1.py =================================================================== --- trunk/numpy/numarray/alter_code1.py 2006-08-05 22:29:46 UTC (rev 2973) +++ trunk/numpy/numarray/alter_code1.py 2006-08-08 05:13:02 UTC (rev 2974) @@ -5,9 +5,9 @@ * Changes import statements Stubs for - convolve --> numarray.convolve - image --> numarray.image - nd_image --> numarray.nd_image + numarray.convolve --> numpy.numarray.convolve + numarray.image --> numarray.image + numarray.nd_image --> numarray.nd_image * Makes search and replace changes to: - .imaginary --> .imag @@ -50,7 +50,11 @@ import re import glob +import warnings +warnings.warn("numarray.alter_code1 is not working yet") + + _func4 = ['eye', 'tri'] _meth1 = ['astype'] _func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', From numpy-svn at scipy.org Tue Aug 8 03:49:16 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 8 Aug 2006 02:49:16 -0500 (CDT) Subject: [Numpy-svn] r2975 - in trunk/numpy: core/src numarray Message-ID: <20060808074916.0F96239C0FE@new.scipy.org> Author: oliphant Date: 2006-08-08 02:49:10 -0500 (Tue, 08 Aug 2006) New Revision: 2975 Added: trunk/numpy/numarray/compat.py trunk/numpy/numarray/functions.py trunk/numpy/numarray/ufuncs.py Removed: trunk/numpy/numarray/numclass.py Modified: trunk/numpy/core/src/multiarraymodule.c trunk/numpy/numarray/__init__.py trunk/numpy/numarray/alter_code1.py trunk/numpy/numarray/numerictypes.py Log: Add numarray compatibility. Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-08 07:49:10 UTC (rev 2975) @@ -4377,12 +4377,13 @@ } return PY_SUCCEED; } - else goto fail; /*{ + 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; /* Modified: trunk/numpy/numarray/__init__.py =================================================================== --- trunk/numpy/numarray/__init__.py 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/numarray/__init__.py 2006-08-08 07:49:10 UTC (rev 2975) @@ -1,5 +1,22 @@ from util import * -from numclass import * +from numerictypes import * +from functions import * +from ufuncs import * +import util +import numerictypes +import functions +import ufuncs +import compat + __all__ = util.__all__ -__all__ += numclass.__all__ +__all__ += numerictypes.__all__ +__all__ += functions.__all__ +__all__ += ufuncs.__all__ +__all__ += compat.__all__ + +del util +del numerictypes +del functions +del ufuncs +del compat Modified: trunk/numpy/numarray/alter_code1.py =================================================================== --- trunk/numpy/numarray/alter_code1.py 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/numarray/alter_code1.py 2006-08-08 07:49:10 UTC (rev 2975) @@ -28,7 +28,7 @@ - self.new(type) --> empty(self.shape, type) - .repeat(r) --> .repeat(r, axis=0) - .size() --> .size - - .type() -- numarray.type(self.dtype) + - .type() -- numarray.typefrom(self) - .typecode() --> .dtype.char - .stddev() --> .std() - .togglebyteorder() --> self.dtype=self.dtype.newbyteorder() Added: trunk/numpy/numarray/compat.py =================================================================== --- trunk/numpy/numarray/compat.py 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/numarray/compat.py 2006-08-08 07:49:10 UTC (rev 2975) @@ -0,0 +1,6 @@ + +__all__ = ['NewAxis'] + +from numpy import newaxis + +NewAxis = newaxis Added: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/numarray/functions.py 2006-08-08 07:49:10 UTC (rev 2975) @@ -0,0 +1,86 @@ + +# missing Numarray defined names (in from numarray import *) +##__all__ = ['ArrayType', 'CLIP', 'ClassicUnpickler', 'Complex32_fromtype', +## 'Complex64_fromtype', 'ComplexArray', 'EarlyEOFError', 'Error', +## 'FileSeekWarning', 'MAX_ALIGN', 'MAX_INT_SIZE', 'MAX_LINE_WIDTH', +## 'MathDomainError', 'NDArray', 'NewArray', 'NewAxis', 'NumArray', +## 'NumError', 'NumOverflowError', 'PRECISION', 'Py2NumType', +## 'PyINT_TYPES', 'PyLevel2Type', 'PyNUMERIC_TYPES', 'PyREAL_TYPES', +## 'RAISE', 'SLOPPY', 'STRICT', 'SUPPRESS_SMALL', 'SizeMismatchError', +## 'SizeMismatchWarning', 'SuitableBuffer', 'USING_BLAS', +## 'UnderflowError', 'UsesOpPriority', 'WARN', 'WRAP', 'all', +## 'allclose', 'alltrue', 'and_', 'any', 'arange', 'argmax', +## 'argmin', 'argsort', 'around', 'array2list', 'array_equal', +## 'array_equiv', 'array_repr', 'array_str', 'arrayprint', +## 'arrayrange', 'average', 'choose', 'clip', +## 'codegenerator', 'compress', 'concatenate', 'conjugate', +## 'copy', 'copy_reg', 'diagonal', 'divide_remainder', +## 'dotblas', 'e', 'explicit_type', 'flush_caches', 'fromfile', +## 'fromfunction', 'fromlist', 'fromstring', 'generic', +## 'genericCoercions', 'genericPromotionExclusions', 'genericTypeRank', +## 'getShape', 'getTypeObject', 'handleError', 'identity', 'indices', +## 'info', 'innerproduct', 'inputarray', 'isBigEndian', +## 'kroneckerproduct', 'lexsort', 'libnumarray', 'libnumeric', +## 'load', 'make_ufuncs', 'math', 'memory', +## 'numarrayall', 'numarraycore', 'numerictypes', 'numinclude', +## 'operator', 'os', 'outerproduct', 'pi', 'put', 'putmask', +## 'pythonTypeMap', 'pythonTypeRank', 'rank', 'repeat', +## 'reshape', 'resize', 'round', 'safethread', 'save', 'scalarTypeMap', +## 'scalarTypes', 'searchsorted', 'session', 'shape', 'sign', 'size', +## 'sometrue', 'sort', 'swapaxes', 'sys', 'take', 'tcode', +## 'tensormultiply', 'tname', 'trace', 'transpose', 'typeDict', +## 'typecode', 'typecodes', 'typeconv', 'types', 'ufunc', +## 'ufuncFactory', 'value', ] + + +__all__ = ['asarray', 'ones', 'zeros', 'array', 'where'] +__all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices', + 'arange', 'concatenate'] + +from numpy import dot as matrixmultiply, dot, vdot, ravel + +def array(sequence=None, typecode=None, copy=1, savespace=0, + type=None, shape=None, dtype=None): + dtype = type2dtype(typecode, type, dtype) + if sequence is None: + if shape is None: + return None + if dtype is None: + dtype = 'l' + return N.empty(shape, dtype) + arr = N.array(sequence, dtype, copy=copy) + if shape is not None: + arr.shape = shape + return arr + +def asarray(seq, type=None, typecode=None, dtype=None): + if seq is None: + return None + dtype = type2dtype(typecode, type, dtype) + return N.array(seq, dtype, copy=0) + +def ones(shape, type=None, typecode=None, dtype=None): + dtype = type2dtype(typecode, type, dtype) + return N.ones(shape, dtype) + +def zeros(shape, type=None, typecode=None, dtype=None): + dtype = type2dtype(typecode, type, dtype) + return N.zeros(shape, dtype) + +def where(condition, x=None, y=None, out=None): + if x is None and y is None: + arr = N.where(condition) + else: + arr = N.where(condition, x, y) + if out is not None: + out[...] = arr + return out + return arr + +def indices(shape, type=None): + return N.indices(shape, type) + +def arange(a1, a2=None, stride=1, type=None, shape=None, + typecode=None, dtype=None): + dtype = type2dtype(typecode, type, dtype) + return N.arange(a1, a2, stride, dtype) Deleted: trunk/numpy/numarray/numclass.py =================================================================== --- trunk/numpy/numarray/numclass.py 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/numarray/numclass.py 2006-08-08 07:49:10 UTC (rev 2975) @@ -1,133 +0,0 @@ -from numpy.core.multiarray import ndarray -import numerictypes as _nt -import numpy as N -import sys as _sys - -__all__ = ['NumArray'] - -class NumArray(ndarray): - def __new__(klass, shape=None, type=None, buffer=None, - byteoffset=0, bytestride=None, byteorder=_sys.byteorder, - aligned=1, real=None, imag=None): - - type = _nt.getType(type) - dtype = N.dtype(type._dtype) - if byteorder in ['little', 'big']: - if byteorder is not _sys.byteorder: - dtype = dtype.newbyteorder() - else: - raise ValueError("byteorder must be 'little' or 'big'") - - if buffer is None: - self = ndarray.__new__(klass, shape, dtype) - else: - self = ndarray.__new__(klass, shape, dtype, buffer=buffer, - offset=byteoffset, strides=bytestride) - - self._type = type - - if real is not None: - self.real = real - - if imag is not None: - self.imag = imag - - self._byteorder = byteorder - - return self - - def argmax(self, axis=-1): - return ndarray.argmax(self, axis) - - def argmin(self, axis=-1): - return ndarray.argmax(self, axis) - - def argsort(self, axis=-1, kind='quicksort'): - return ndarray.argmax(self, axis, kind) - - def astype(self, type=None): - return self.astype(_getdtype(type)) - - def byteswap(self): - ndarray.byteswap(self, True) - - def byteswapped(self): - return ndarray.byteswap(self, False) - - def getdtypechar(self): - return self.dtype.char - - def getimag(self): - return self.imag - - getimaginary = getimag - - imaginary = property(getimaginary, None, "") - - def getreal(self): - return self.real - - def is_c_array(self): - return self.dtype.isnative and self.flags.carray - - def is_f_array(self): - return self.dtype.isnative and self.flags.farray - - def is_fortran_contiguous(self): - return self.flags.contiguous - - def new(self, type=None): - if type is not None: - dtype = _getdtype(type) - return N.empty(self.shape, dtype) - else: - return N.empty_like(self) - - def setimag(self, value): - self.imag = value - - setimaginary = setimag - - def setreal(self, value): - self.real = value - - def sinfo(self): - self.info() - - def sort(self, axis=-1, kind='quicksort'): - ndarray.sort(self, axis, kind) - - def spacesaver(self): - return False - - def stddev(self): - return self.std() - - def sum(self, type=None): - dtype = _getdtype(type) - return ndarray.sum(self, dtype=dtype) - - def togglebyteorder(self): - self.dtype = self.dtype.newbyteorder() - - def type(self): - return self._type - - def typecode(self): - return _numtypecode[self.dtype.char] - - dtypechar = property(getdtypechar, None, "") - - def info(self): - print "class: ", self.__class__ - print "shape: ", self.shape - print "strides: ", self.strides - print "byteoffset: 0" - print "bytestride: ", self.strides[0] - print "itemsize: ", self.itemsize - print "aligned: ", self.flags.isaligned - print "contiguous: ", self.flags.contiguous - print "buffer: ", self.data - print "data pointer:", self._as_paramater_ - print "byteorder: ", self._byteorder - print "byteswap: ", not self.dtype.isnative Modified: trunk/numpy/numarray/numerictypes.py =================================================================== --- trunk/numpy/numarray/numerictypes.py 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/numarray/numerictypes.py 2006-08-08 07:49:10 UTC (rev 2975) @@ -27,13 +27,25 @@ $Id: numerictypes.py,v 1.55 2005/12/01 16:22:03 jaytmiller Exp $ """ +__all__ = ['NumericType','HasUInt64','typeDict','IsType', + 'BooleanType', 'SignedType', 'UnsignedType', 'IntegralType', + 'SignedIntegralType', 'UnsignedIntegralType', 'FloatingType', + 'ComplexType', 'AnyType', 'ObjectType', 'Any', 'Object', + 'Bool', 'Int8', 'Int16', 'Int32', 'Int64', 'Float32', + 'Float64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', + 'Complex32', 'Complex64', 'Byte', 'Short', 'Int','Long', + 'Float', 'Complex', 'genericTypeRank', 'pythonTypeRank', + 'pythonTypeMap', 'scalarTypeMap', 'genericCoercions', + 'typecodes', 'genericPromotionExclusions','MaximumType', + 'getType','scalarTypes', 'typefrom'] + MAX_ALIGN = 8 MAX_INT_SIZE = 8 import numpy LP64 = numpy.intp(0).itemsize == 8 -HasUInt64 = 0 +HasUInt64 = 1 try: numpy.int64(0) except: @@ -182,6 +194,24 @@ Complex32 = ComplexType("Complex32", 8, complex(0.0), _tComplex32) Complex64 = ComplexType("Complex64", 16, complex(0.0), _tComplex64) +Object.dtype = 'O' +Bool.dtype = '?' +Int8.dtype = 'i1' +Int16.dtype = 'i2' +Int32.dtype = 'i4' +Int64.dtype = 'i8' + +UInt8.dtype = 'u1' +UInt16.dtype = 'u2' +UInt32.dtype = 'u4' +UInt64.dtype = 'u8' + +Float32.dtype = 'f4' +Float64.dtype = 'f8' + +Complex32.dtype = 'c8' +Complex64.dtype = 'c16' + # Aliases Byte = _register("Byte", Int8) @@ -192,10 +222,12 @@ if HasUInt64: _register("ULong", UInt64) MaybeLong = _register("MaybeLong", Int64) + __all__.append('MaybeLong') else: Long = _register("Long", Int32) _register("ULong", UInt32) - MaybeLong = _register("MaybeLong", Int32) + MaybeLong = _register("MaybeLong", Int32) + __all__.append('MaybeLong') _register("UByte", UInt8) @@ -280,10 +312,7 @@ 'Int32', 'UInt32', 'Int64', 'UInt64', 'Float32','Float64', 'Complex32', 'Complex64', 'Object'] -if _sys.version_info >= (2,3,0): - pythonTypeRank = [ bool, int, long, float, complex ] -else: - pythonTypeRank = [ int, long, float, complex ] +pythonTypeRank = [ bool, int, long, float, complex ] # The next line is not platform independent XXX Needs to be generalized if not LP64: @@ -311,9 +340,8 @@ float:"Float64", complex:"Complex64"} -if _sys.version_info >= (2,3,0): - pythonTypeMap.update({bool:("Bool","bool") }) - scalarTypeMap.update({bool:"Bool"}) +pythonTypeMap.update({bool:("Bool","bool") }) +scalarTypeMap.update({bool:"Bool"}) # Generate coercion matrix @@ -481,10 +509,7 @@ except KeyError: raise TypeError("Not a numeric type") -if _sys.version_info >= (2,3): - scalarTypes = (bool,int,long,float,complex) -else: - scalarTypes = (int,long,float,complex) +scalarTypes = (bool,int,long,float,complex) _scipy_dtypechar = { Int8 : 'b', @@ -505,4 +530,7 @@ for key,value in _scipy_dtypechar.items(): _scipy_dtypechar_inverse[value] = key - + +def typefrom(obj): + return _scipy_dtypechar_inverse[obj.dtype.char] + Added: trunk/numpy/numarray/ufuncs.py =================================================================== --- trunk/numpy/numarray/ufuncs.py 2006-08-08 05:13:02 UTC (rev 2974) +++ trunk/numpy/numarray/ufuncs.py 2006-08-08 07:49:10 UTC (rev 2975) @@ -0,0 +1,21 @@ + +__all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh', + 'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not', + 'bitwise_or', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'cumproduct', + 'cumsum', 'divide', 'equal', 'exp', 'fabs', 'floor', 'floor_divide', + 'fmod', 'greater', 'greater_equal', 'hypot', 'ieeemask', 'isnan', + 'less', 'less_equal', 'log', 'log10', 'logical_and', 'logical_not', + 'logical_or', 'logical_xor', 'lshift', 'maximum', 'minimum', + 'minus', 'multiply', 'negative', 'nonzero', 'not_equal', + 'power', 'product', 'remainder', 'rshift', 'sin', 'sinh', 'sqrt', + 'subtract', 'sum', 'tan', 'tanh', 'true_divide'] + +from numpy import abs, absolute, add, arccos, arccosh, arcsin, arcsinh, \ + arctan, arctan2, arctanh, bitwise_and, bitwise_not, bitwise_or, \ + bitwise_xor, ceil, cos, cosh, cumproduct, cumsum, divide, equal, \ + exp, fabs, floor, floor_divide, fmod, greater, greater_equal, hypot, \ + ieeemask, isnan, less, less_equal, log, log10, logical_and, \ + logical_not, logical_or, logical_xor, lshift, maximum, minimum, \ + minus, multiply, negative, nonzero, not_equal, power, product, \ + remainder, rshift, sin, sinh, sqrt, subtract, sum, tan, tanh, \ + true_divide From numpy-svn at scipy.org Tue Aug 8 11:48:43 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 8 Aug 2006 10:48:43 -0500 (CDT) Subject: [Numpy-svn] r2976 - trunk/numpy/numarray Message-ID: <20060808154843.2001B39C061@new.scipy.org> Author: oliphant Date: 2006-08-08 10:48:38 -0500 (Tue, 08 Aug 2006) New Revision: 2976 Modified: trunk/numpy/numarray/functions.py Log: Fix import problem Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-08 07:49:10 UTC (rev 2975) +++ trunk/numpy/numarray/functions.py 2006-08-08 15:48:38 UTC (rev 2976) @@ -37,7 +37,7 @@ __all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices', 'arange', 'concatenate'] -from numpy import dot as matrixmultiply, dot, vdot, ravel +from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate def array(sequence=None, typecode=None, copy=1, savespace=0, type=None, shape=None, dtype=None): From numpy-svn at scipy.org Tue Aug 8 12:06:02 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 8 Aug 2006 11:06:02 -0500 (CDT) Subject: [Numpy-svn] r2977 - trunk/numpy/numarray Message-ID: <20060808160602.3620F39C061@new.scipy.org> Author: oliphant Date: 2006-08-08 11:05:59 -0500 (Tue, 08 Aug 2006) New Revision: 2977 Modified: trunk/numpy/numarray/functions.py trunk/numpy/numarray/ufuncs.py Log: Fix numarray compatibility layer so it at least imports. It's not finished yet, but some functionality is there. Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-08 15:48:38 UTC (rev 2976) +++ trunk/numpy/numarray/functions.py 2006-08-08 16:05:59 UTC (rev 2977) @@ -30,7 +30,8 @@ ## 'sometrue', 'sort', 'swapaxes', 'sys', 'take', 'tcode', ## 'tensormultiply', 'tname', 'trace', 'transpose', 'typeDict', ## 'typecode', 'typecodes', 'typeconv', 'types', 'ufunc', -## 'ufuncFactory', 'value', ] +## 'ufuncFactory', 'value', 'ieeemask', 'cumproduct', 'cumsum', +## 'nonzero'] __all__ = ['asarray', 'ones', 'zeros', 'array', 'where'] Modified: trunk/numpy/numarray/ufuncs.py =================================================================== --- trunk/numpy/numarray/ufuncs.py 2006-08-08 15:48:38 UTC (rev 2976) +++ trunk/numpy/numarray/ufuncs.py 2006-08-08 16:05:59 UTC (rev 2977) @@ -1,21 +1,21 @@ __all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not', - 'bitwise_or', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'cumproduct', - 'cumsum', 'divide', 'equal', 'exp', 'fabs', 'floor', 'floor_divide', - 'fmod', 'greater', 'greater_equal', 'hypot', 'ieeemask', 'isnan', + 'bitwise_or', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide', + 'equal', 'exp', 'fabs', 'floor', 'floor_divide', + 'fmod', 'greater', 'greater_equal', 'hypot', 'isnan', 'less', 'less_equal', 'log', 'log10', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'lshift', 'maximum', 'minimum', - 'minus', 'multiply', 'negative', 'nonzero', 'not_equal', + 'minus', 'multiply', 'negative', 'not_equal', 'power', 'product', 'remainder', 'rshift', 'sin', 'sinh', 'sqrt', 'subtract', 'sum', 'tan', 'tanh', 'true_divide'] -from numpy import abs, absolute, add, arccos, arccosh, arcsin, arcsinh, \ - arctan, arctan2, arctanh, bitwise_and, bitwise_not, bitwise_or, \ - bitwise_xor, ceil, cos, cosh, cumproduct, cumsum, divide, equal, \ - exp, fabs, floor, floor_divide, fmod, greater, greater_equal, hypot, \ - ieeemask, isnan, less, less_equal, log, log10, logical_and, \ - logical_not, logical_or, logical_xor, lshift, maximum, minimum, \ - minus, multiply, negative, nonzero, not_equal, power, product, \ - remainder, rshift, sin, sinh, sqrt, subtract, sum, tan, tanh, \ - true_divide +from numpy import absolute as abs, absolute, add, arccos, arccosh, arcsin, \ + arcsinh, arctan, arctan2, arctanh, bitwise_and, invert as bitwise_not, \ + bitwise_or, bitwise_xor, ceil, cos, cosh, divide, \ + equal, exp, fabs, floor, floor_divide, fmod, greater, greater_equal, \ + hypot, isnan, less, less_equal, log, log10, logical_and, \ + logical_not, logical_or, logical_xor, left_shift as lshift, \ + maximum, minimum, negative as minus, multiply, negative, \ + not_equal, power, product, remainder, right_shift as rshift, sin, \ + sinh, sqrt, subtract, sum, tan, tanh, true_divide From numpy-svn at scipy.org Tue Aug 8 12:10:36 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 8 Aug 2006 11:10:36 -0500 (CDT) Subject: [Numpy-svn] r2978 - trunk/numpy/core Message-ID: <20060808161036.8B1A839C061@new.scipy.org> Author: oliphant Date: 2006-08-08 11:10:34 -0500 (Tue, 08 Aug 2006) New Revision: 2978 Modified: trunk/numpy/core/numeric.py Log: Add bitwise_not to numpy Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-08 16:05:59 UTC (rev 2977) +++ trunk/numpy/core/numeric.py 2006-08-08 16:10:34 UTC (rev 2978) @@ -18,7 +18,7 @@ 'seterr', 'geterr', 'setbufsize', 'getbufsize', 'seterrcall', 'geterrcall', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', - 'nan', 'NaN', 'False_', 'True_'] + 'nan', 'NaN', 'False_', 'True_', 'bitwise_not'] import sys import multiarray @@ -27,6 +27,8 @@ import numerictypes from numerictypes import * +bitwise_not = invert + # from Fernando Perez's IPython def zeros_like(a): """Return an array of zeros of the shape and typecode of a. From numpy-svn at scipy.org Tue Aug 8 17:16:06 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 8 Aug 2006 16:16:06 -0500 (CDT) Subject: [Numpy-svn] r2979 - trunk/numpy/distutils/fcompiler Message-ID: <20060808211606.8305439C08D@new.scipy.org> Author: cookedm Date: 2006-08-08 16:16:05 -0500 (Tue, 08 Aug 2006) New Revision: 2979 Modified: trunk/numpy/distutils/fcompiler/intel.py Log: fix #234: IntelVisualFCompiler is broken Modified: trunk/numpy/distutils/fcompiler/intel.py =================================================================== --- trunk/numpy/distutils/fcompiler/intel.py 2006-08-08 16:10:34 UTC (rev 2978) +++ trunk/numpy/distutils/fcompiler/intel.py 2006-08-08 21:16:05 UTC (rev 2979) @@ -128,9 +128,6 @@ ar_exe = 'lib.exe' fc_exe = 'ifl' - if sys.platform=='win32': - from distutils.msvccompiler import MSVCCompiler - ar_exe = MSVCCompiler().lib executables = { 'version_cmd' : [fc_exe, "-FI -V -c %(fname)s.f -o %(fname)s.o" \ From numpy-svn at scipy.org Wed Aug 9 20:14:44 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 9 Aug 2006 19:14:44 -0500 (CDT) Subject: [Numpy-svn] r2980 - in trunk/numpy/core: . src Message-ID: <20060810001444.DC44539C00C@new.scipy.org> Author: oliphant Date: 2006-08-09 19:14:42 -0500 (Wed, 09 Aug 2006) New Revision: 2980 Modified: trunk/numpy/core/_internal.py trunk/numpy/core/src/multiarraymodule.c Log: Fix byte-order problems in comma-string formats and size-specified fields. Modified: trunk/numpy/core/_internal.py =================================================================== --- trunk/numpy/core/_internal.py 2006-08-08 21:16:05 UTC (rev 2979) +++ trunk/numpy/core/_internal.py 2006-08-10 00:14:42 UTC (rev 2980) @@ -4,7 +4,13 @@ import re from multiarray import dtype, ndarray +import sys +if (sys.byteorder == 'little'): + _nbo = '<' +else: + _nbo = '>' + def _makenames_list(adict): allfields = [] fnames = adict.keys() @@ -141,10 +147,15 @@ return newlist -format_re = re.compile(r'(?P *[(]?[ ,0-9]*[)]? *)(?P[><|A-Za-z0-9.]*)') +format_re = re.compile(r'(?P[<>|=]?)(?P *[(]?[ ,0-9]*[)]? *)(?P[<>|=]?)(?P[A-Za-z0-9.]*)') # astr is a string (perhaps comma separated) +_convorder = {'=': _nbo, + '|': '|', + '>': '>', + '<': '<'} + def _commastring(astr): res = _split(astr) if (len(res)) < 1: @@ -153,10 +164,24 @@ for k,item in enumerate(res): # convert item try: - (repeats, dtype) = format_re.match(item).groups() + (order1, repeats, order2, dtype) = format_re.match(item).groups() except (TypeError, AttributeError): raise ValueError('format %s is not recognized' % item) + if order2 == '': + order = order1 + elif order1 == '': + order = order2 + else: + order1 = _convorder[order1] + order2 = _convorder[order2] + if (order1 != order2): + raise ValueError('in-consistent byte-order specification %s and %s' % (order1, order2)) + order = order1 + + if order in ['|', '=', _nbo]: + order = '' + dtype = '%s%s' % (order, dtype) if (repeats == ''): newitem = dtype else: Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-08 21:16:05 UTC (rev 2979) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-10 00:14:42 UTC (rev 2980) @@ -4193,13 +4193,19 @@ } static int -_could_be_commastring(char *type, int len) +_check_for_commastring(char *type, int len) { int i; - if (type[0] >= '1' && type[0] <= '9') return 1; + + if ((type[0] >= '0' && type[0] <= '9') || + ((len > 1) && (type[0] == '>' || type[0] == '<' || \ + type[0] == '|' || type[0] == '=') && \ + (type[1] >= '0' && type[1] <= '9'))) + return 1; for (i=1;i' || (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) { + + /* 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); - /* check for commas present - or first element a digit */ - if (_could_be_commastring(type, len)) { - /* see if it can be converted from - a comma-separated string */ - *at = _convert_from_commastring(obj, 0); - if (*at) return PY_SUCCEED; - else return PY_FAIL; - } if (elsize == 0) { check_num = PyArray_NOTYPE+10; } From numpy-svn at scipy.org Wed Aug 9 20:24:49 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 9 Aug 2006 19:24:49 -0500 (CDT) Subject: [Numpy-svn] r2981 - trunk/numpy/core/tests Message-ID: <20060810002449.E3F8039C00C@new.scipy.org> Author: oliphant Date: 2006-08-09 19:24:48 -0500 (Wed, 09 Aug 2006) New Revision: 2981 Modified: trunk/numpy/core/tests/test_numerictypes.py Log: Add unit-test for recent comma-string updates Modified: trunk/numpy/core/tests/test_numerictypes.py =================================================================== --- trunk/numpy/core/tests/test_numerictypes.py 2006-08-10 00:14:42 UTC (rev 2980) +++ trunk/numpy/core/tests/test_numerictypes.py 2006-08-10 00:24:48 UTC (rev 2981) @@ -331,6 +331,12 @@ multiple_rows = True _buffer = NbufferT +class test_empty_field(NumpyTestCase): + def check_assign(self): + a = numpy.arange(10, dtype=numpy.float32) + a.dtype = [("int", "<0i4"),("float", "<2f4")] + assert(a['int'].shape == (5,0)) + assert(a['float'].shape == (5,2)) if __name__ == "__main__": NumpyTest().run() From numpy-svn at scipy.org Thu Aug 10 07:55:44 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 06:55:44 -0500 (CDT) Subject: [Numpy-svn] r2982 - in trunk/numpy: core core/code_generators core/include/numpy core/src numarray Message-ID: <20060810115544.0C4E339C059@new.scipy.org> Author: oliphant Date: 2006-08-10 06:55:33 -0500 (Thu, 10 Aug 2006) New Revision: 2982 Added: trunk/numpy/numarray/session.py Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt trunk/numpy/core/defmatrix.py trunk/numpy/core/fromnumeric.py trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/include/numpy/ufuncobject.h trunk/numpy/core/numeric.py trunk/numpy/core/src/arraymethods.c trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/multiarraymodule.c trunk/numpy/core/src/scalartypes.inc.src trunk/numpy/core/src/ufuncobject.c trunk/numpy/numarray/__init__.py trunk/numpy/numarray/compat.py trunk/numpy/numarray/functions.py trunk/numpy/numarray/numerictypes.py trunk/numpy/numarray/ufuncs.py Log: Update C-API to add features needed for numarray compatibility. Output argument added for several functions and clipmode argument added for a few others. Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt =================================================================== --- trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-10 11:55:33 UTC (rev 2982) @@ -1,6 +1,6 @@ PyArray_Transpose -PyArray_Take -PyArray_Put +PyArray_TakeOut +PyArray_PutIn PyArray_PutMask PyArray_Repeat PyArray_Choose @@ -73,3 +73,5 @@ PyArray_InitArrFuncs PyArray_IntTupleFromIntp PyArray_TypeNumFromName +PyArray_ClipmodeConverter +PyArray_OutputConverter Modified: trunk/numpy/core/defmatrix.py =================================================================== --- trunk/numpy/core/defmatrix.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/defmatrix.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -234,45 +234,45 @@ raise ValueError, "unsupported axis" # To preserve orientation of result... - def sum(self, axis=None, dtype=None): + def sum(self, axis=None, dtype=None, out=None): """Sum the matrix over the given axis. If the axis is None, sum over all dimensions. This preserves the orientation of the result as a row or column. """ - return N.ndarray.sum(self, axis, dtype)._align(axis) + return N.ndarray.sum(self, axis, dtype, out=None)._align(axis) - def mean(self, axis=None): - return N.ndarray.mean(self, axis)._align(axis) + def mean(self, axis=None, out=None): + return N.ndarray.mean(self, axis, out)._align(axis) - def std(self, axis=None, dtype=None): - return N.ndarray.std(self, axis, dtype)._align(axis) + def std(self, axis=None, dtype=None, out=None): + return N.ndarray.std(self, axis, dtype, out)._align(axis) - def var(self, axis=None, dtype=None): - return N.ndarray.var(self, axis, dtype)._align(axis) + def var(self, axis=None, dtype=None, out=None): + return N.ndarray.var(self, axis, dtype, out)._align(axis) - def prod(self, axis=None, dtype=None): - return N.ndarray.prod(self, axis, dtype)._align(axis) + def prod(self, axis=None, dtype=None, out=None): + return N.ndarray.prod(self, axis, dtype, out)._align(axis) - def any(self, axis=None): - return N.ndarray.any(self, axis)._align(axis) + def any(self, axis=None, out=None): + return N.ndarray.any(self, axis, out)._align(axis) - def all(self, axis=None): - return N.ndarray.all(self, axis)._align(axis) + def all(self, axis=None, out=None): + return N.ndarray.all(self, axis, out)._align(axis) - def max(self, axis=None): - return N.ndarray.max(self, axis)._align(axis) + def max(self, axis=None, out=None): + return N.ndarray.max(self, axis, out)._align(axis) def argmax(self, axis=None): return N.ndarray.argmax(self, axis)._align(axis) - def min(self, axis=None): - return N.ndarray.min(self, axis)._align(axis) + def min(self, axis=None, out=None): + return N.ndarray.min(self, axis, out)._align(axis) def argmin(self, axis=None): return N.ndarray.argmin(self, axis)._align(axis) - def ptp(self, axis=None): - return N.ndarray.ptp(self, axis)._align(axis) + def ptp(self, axis=None, out=None): + return N.ndarray.ptp(self, axis, out)._align(axis) # Needed becase tolist method expects a[i] # to have dimension a.ndim-1 Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/fromnumeric.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -43,12 +43,12 @@ result = wrap(result) return result -def take(a, indices, axis=None): +def take(a, indices, axis=None, out=None, mode='raise'): try: take = a.take except AttributeError: - return _wrapit(a, 'take', indices, axis) - return take(indices, axis) + return _wrapit(a, 'take', indices, axis, out, mode) + return take(indices, axis, out, mode) # not deprecated --- copy if necessary, view otherwise def reshape(a, newshape, order='C'): @@ -61,12 +61,12 @@ return _wrapit(a, 'reshape', newshape, order=order) return reshape(newshape, order=order) -def choose(a, choices): +def choose(a, choices, out=None, mode='raise'): try: choose = a.choose except AttributeError: - return _wrapit(a, 'choose', choices) - return choose(choices) + return _wrapit(a, 'choose', choices, out=out, mode=mode) + return choose(choices, out=out, mode=mode) def repeat(a, repeats, axis=None): """repeat elements of a repeats times along axis @@ -82,7 +82,7 @@ return _wrapit(a, 'repeat', repeats, axis) return repeat(repeats, axis) -def put (a, ind, v): +def put (a, ind, v, mode='raise'): """put(a, ind, v) results in a[n] = v[n] for all n in ind If v is shorter than mask it will be repeated as necessary. In particular v can be a scalar or length 1 array. @@ -94,7 +94,7 @@ for i in ind: a.flat[i] = v[i] a must be a contiguous numpy array. """ - return a.put(v,ind) + return a.put(v,ind, mode) def putmask (a, mask, v): """putmask(a, mask, v) results in a = v for all places mask is true. @@ -124,22 +124,22 @@ return _wrapit(a, 'transpose', axes) return transpose(axes) -def sort(a, axis=-1): +def sort(a, axis=-1, kind='quicksort'): """sort(a,axis=-1) returns array with elements sorted along given axis. """ a = asanyarray(a).copy() - a.sort(axis) + a.sort(axis, kind) return a -def argsort(a, axis=-1): +def argsort(a, axis=-1, kind='quicksort'): """argsort(a,axis=-1) return the indices into a of the sorted array along the given axis. """ try: argsort = a.argsort except AttributeError: - return _wrapit(a, 'argsort', axis) - return argsort(axis) + return _wrapit(a, 'argsort', axis, kind) + return argsort(axis, kind) def argmax(a, axis=-1): """argmax(a,axis=-1) returns the indices to the maximum value of the @@ -215,11 +215,11 @@ """ return asarray(a).diagonal(offset, axis1, axis2) -def trace(a, offset=0, axis1=0, axis2=1, dtype=None): +def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals (defined by the last two dimenions) of the array. """ - return asarray(a).trace(offset, axis1, axis2, dtype) + return asarray(a).trace(offset, axis1, axis2, dtype, out) def ravel(m,order='C'): """ravel(m) returns a 1d array corresponding to all the elements of it's @@ -250,15 +250,15 @@ result = asarray(a).shape return result -def compress(condition, m, axis=-1): +def compress(condition, m, axis=-1, out=None): """compress(condition, x, axis=-1) = those elements of x corresponding to those elements of condition that are "true". condition must be the same size as the given dimension of x.""" try: compress = m.compress except AttributeError: - return _wrapit(m, 'compress', condition, axis) - return compress(condition, axis) + return _wrapit(m, 'compress', condition, axis, out) + return compress(condition, axis, out) def clip(m, m_min, m_max): """clip(m, m_min, m_max) = every entry in m that is less than m_min is @@ -271,7 +271,7 @@ return _wrapit(m, 'clip', m_min, m_max) return clip(m_min, m_max) -def sum(x, axis=None, dtype=None): +def sum(x, axis=None, dtype=None, out=None): """Sum the array over the given axis. The optional dtype argument is the data type for intermediate calculations. @@ -293,97 +293,100 @@ array([1, 5]) """ if isinstance(x, _gentype): - return _sum_(x) + res = _sum_(x) + if out is not None: + out[...] = res + return out try: sum = x.sum except AttributeError: - return _wrapit(x, 'sum', axis, dtype) - return sum(axis, dtype) + return _wrapit(x, 'sum', axis, dtype, out) + return sum(axis, dtype, out) -def product (x, axis=None, dtype=None): +def product (x, axis=None, dtype=None, out=None): """Product of the array elements over the given axis.""" try: prod = x.prod except AttributeError: - return _wrapit(x, 'prod', axis, dtype) - return prod(axis, dtype) + return _wrapit(x, 'prod', axis, dtype, out) + return prod(axis, dtype, out) -def sometrue (x, axis=None): +def sometrue (x, axis=None, out=None): """Perform a logical_or over the given axis.""" try: any = x.any except AttributeError: - return _wrapit(x, 'any', axis) - return any(axis) + return _wrapit(x, 'any', axis, out) + return any(axis, out) -def alltrue (x, axis=None): +def alltrue (x, axis=None, out=None): """Perform a logical_and over the given axis.""" try: all = x.all except AttributeError: - return _wrapit(x, 'all', axis) - return all(axis) + return _wrapit(x, 'all', axis, out) + return all(axis, out) -def any(x,axis=None): +def any(x,axis=None, out=None): """Return true if any elements of x are true: """ try: any = x.any except AttributeError: - return _wrapit(x, 'any', axis) - return any(axis) + return _wrapit(x, 'any', axis, out) + return any(axis, out) -def all(x,axis=None): +def all(x,axis=None, out=None): """Return true if all elements of x are true: """ try: all = x.all except AttributeError: - return _wrapit(x, 'all', axis) - return all(axis) + return _wrapit(x, 'all', axis, out) + return all(axis, out) -def cumsum (x, axis=None, dtype=None): +def cumsum (x, axis=None, dtype=None, out=None): """Sum the array over the given axis.""" try: cumsum = x.cumsum except AttributeError: - return _wrapit(x, 'cumsum', axis, dtype) - return cumsum(axis, dtype) + return _wrapit(x, 'cumsum', axis, dtype, out) + return cumsum(axis, dtype, out) -def cumproduct (x, axis=None, dtype=None): +def cumproduct (x, axis=None, dtype=None, out=None): """Sum the array over the given axis.""" try: cumprod = x.cumprod except AttributeError: - return _wrapit(x, 'cumprod', axis, dtype) - return cumprod(axis, dtype) + return _wrapit(x, 'cumprod', axis, dtype, out) + return cumprod(axis, dtype, out) -def ptp(a, axis=None): +def ptp(a, axis=None, out=None): """Return maximum - minimum along the the given dimension """ try: ptp = a.ptp except AttributeError: - return _wrapit(a, 'ptp', axis) - return ptp(axis) + return _wrapit(a, 'ptp', axis, out) + return ptp(axis, out) -def amax(a, axis=None): +def amax(a, axis=None, out=None): """Return the maximum of 'a' along dimension axis. """ try: max = a.max except AttributeError: - return _wrapit(a, 'max', axis) - return max(axis) + return _wrapit(a, 'max', axis, out) + return max(axis, out) -def amin(a, axis=None): +def amin(a, axis=None, out=None): """Return the minimum of a along dimension axis. """ try: min = a.min except AttributeError: - return _wrapit(a, 'min', axis) - return min(axis) + return _wrapit(a, 'min', axis, out) + return min(axis, out) def alen(a): """Return the length of a Python object interpreted as an array @@ -394,23 +397,23 @@ except TypeError: return len(array(a,ndmin=1)) -def prod(a, axis=None, dtype=None): +def prod(a, axis=None, dtype=None, out=None): """Return the product of the elements along the given axis """ try: prod = a.prod except AttributeError: - return _wrapit(a, 'prod', axis, dtype) - return prod(axis, dtype) + return _wrapit(a, 'prod', axis, dtype, out) + return prod(axis, dtype, out) -def cumprod(a, axis=None, dtype=None): +def cumprod(a, axis=None, dtype=None, out=None): """Return the cumulative product of the elments along the given axis """ try: cumprod = a.cumprod except AttributeError: - return _wrapit(a, 'cumprod', axis, dtype) - return cumprod(axis, dtype) + return _wrapit(a, 'cumprod', axis, dtype, out) + return cumprod(axis, dtype, out) def ndim(a): try: @@ -440,7 +443,7 @@ except AttributeError: return asarray(a).shape[axis] -def round_(a, decimals=0): +def round_(a, decimals=0, out=None): """Round 'a' to the given number of decimal places. Rounding behaviour is equivalent to Python. @@ -450,12 +453,12 @@ try: round = a.round except AttributeError: - return _wrapit(a, 'round', decimals) - return round(decimals) + return _wrapit(a, 'round', decimals, out) + return round(decimals, out) around = round_ -def mean(a, axis=None, dtype=None): +def mean(a, axis=None, dtype=None, out=None): """mean(a, axis=None, dtype=None) Return the arithmetic mean. @@ -466,10 +469,10 @@ try: mean = a.mean except AttributeError: - return _wrapit(a, 'mean', axis, dtype) - return mean(axis, dtype) + return _wrapit(a, 'mean', axis, dtype, out) + return mean(axis, dtype, out) -def std(a, axis=None, dtype=None): +def std(a, axis=None, dtype=None, out=None): """std(sample, axis=None, dtype=None) Return the standard deviation, a measure of the spread of a distribution. @@ -481,10 +484,10 @@ try: std = a.std except AttributeError: - return _wrapit(a, 'std', axis, dtype) - return std(axis, dtype) + return _wrapit(a, 'std', axis, dtype, out) + return std(axis, dtype, out) -def var(a, axis=None, dtype=None): +def var(a, axis=None, dtype=None, out=None): """var(sample, axis=None, dtype=None) Return the variance, a measure of the spread of a distribution. @@ -496,5 +499,5 @@ try: var = a.var except AttributeError: - return _wrapit(a, 'var', axis, dtype) - return var(axis, dtype) + return _wrapit(a, 'var', axis, dtype, out) + return var(axis, dtype, out) Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-10 11:55:33 UTC (rev 2982) @@ -37,7 +37,7 @@ #define NPY_SUCCEED 1 /* Helpful to distinguish what is installed */ -#define NPY_VERSION 0x01000000 +#define NPY_VERSION 0x01000001 /* Some platforms don't define bool, long long, or long double. Handle that here. @@ -207,6 +207,12 @@ } NPY_ORDER; +typedef enum { + NPY_CLIP=0, + NPY_WRAP=1, + NPY_RAISE=2 +} NPY_CLIPMODE; + /* Define bit-width array types and typedefs */ #define NPY_MAX_INT8 127 @@ -1526,6 +1532,12 @@ #define PyArray_Cast(mp, type_num) \ PyArray_CastToType(mp, PyArray_DescrFromType(type_num), 0) +#define PyArray_Take(ap, items, axis) \ + PyArray_TakeOut(ap, items, axis, NULL, NPY_RAISE) + +#define PyArray_Put(ap, items, values) \ + PyArray_PutIn(ap, items, values, NPY_RAISE) + /* Compatibility with old Numeric stuff -- don't use in new code */ #define PyArray_FromDimsAndData(nd, d, type, data) \ Modified: trunk/numpy/core/include/numpy/ufuncobject.h =================================================================== --- trunk/numpy/core/include/numpy/ufuncobject.h 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/include/numpy/ufuncobject.h 2006-08-10 11:55:33 UTC (rev 2982) @@ -158,6 +158,7 @@ PyObject *decref; int obj; + int retbase; } PyUFuncReduceObject; Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/numeric.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -11,14 +11,15 @@ 'array2string', 'get_printoptions', 'set_printoptions', 'array_repr', 'array_str', 'set_string_function', 'little_endian', 'require', - 'fromiter', + 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', 'ones', 'identity', 'allclose', 'seterr', 'geterr', 'setbufsize', 'getbufsize', 'seterrcall', 'geterrcall', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', - 'nan', 'NaN', 'False_', 'True_', 'bitwise_not'] + 'nan', 'NaN', 'False_', 'True_', 'bitwise_not', + 'CLIP', 'RAISE', 'WRAP', 'MAXDIMS', 'BUFSIZE', 'ALLOW_THREADS'] import sys import multiarray @@ -29,6 +30,14 @@ bitwise_not = invert +CLIP = multiarray.CLIP +WRAP = multiarray.WRAP +RAISE = multiarray.RAISE +MAXDIMS = multiarray.MAXDIMS +ALLOW_THREADS = multiarray.ALLOW_THREADS +BUFSIZE = multiarray.BUFSIZE + + # from Fernando Perez's IPython def zeros_like(a): """Return an array of zeros of the shape and typecode of a. @@ -475,7 +484,26 @@ return d.ravel().all() +def array_equal(a1, a2): + try: + a1, a2 = asarray(a1), asarray(a2) + except: + return 0 + if a1.shape != a2.shape: + return 0 + return logical_and.reduce(equal(a1,a2).ravel()) +def array_equiv(a1, a2): + try: + a1, a2 = asarray(a1), asarray(a2) + except: + return 0 + try: + return logical_and.reduce(equal(a1,a2).ravel()) + except ValueError: + return 0 + + _errdict = {"ignore":ERR_IGNORE, "warn":ERR_WARN, "raise":ERR_RAISE, Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/src/arraymethods.c 2006-08-10 11:55:33 UTC (rev 2982) @@ -10,15 +10,21 @@ { int dimension=MAX_DIMS; PyObject *indices; - static char *kwlist[] = {"indices", "axis", NULL}; + PyArrayObject *out=NULL; + NPY_CLIPMODE mode=NPY_RAISE; + static char *kwlist[] = {"indices", "axis", "out", "mode", NULL}; dimension=0; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O&", kwlist, &indices, PyArray_AxisConverter, - &dimension)) + &dimension, + PyArray_OutputConverter, + &out, + PyArray_ClipmodeConverter, + &mode)) return NULL; - return _ARET(PyArray_Take(self, indices, dimension)); + return _ARET(PyArray_TakeOut(self, indices, dimension, out, mode)); } static char doc_fill[] = "a.fill(value) places the scalar value at every "\ @@ -35,7 +41,7 @@ return Py_None; } -static char doc_put[] = "a.put(values, indices) sets a.flat[n] = v[n] "\ +static char doc_put[] = "a.put(values, indices, mode) sets a.flat[n] = v[n] "\ "for each n in indices. v can be scalar or shorter than indices, "\ "will repeat."; @@ -43,12 +49,15 @@ array_put(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *indices, *values; - static char *kwlist[] = {"values", "indices", NULL}; + NPY_CLIPMODE mode=NPY_RAISE; + static char *kwlist[] = {"values", "indices", "mode", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, - &values, &indices)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist, + &values, &indices, + PyArray_ClipmodeConverter, + &mode)) return NULL; - return PyArray_Put(self, values, indices); + return PyArray_PutIn(self, values, indices, mode); } static char doc_putmask[] = "a.putmask(values, mask) sets a.flat[n] = v[n] "\ @@ -185,14 +194,17 @@ array_max(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - static char *kwlist[] = {"axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, - &axis)) + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Max(self, axis); + return PyArray_Max(self, axis, out); } static char doc_ptp[] = "a.ptp(axis=None) a.max(axis)-a.min(axis)"; @@ -201,14 +213,17 @@ array_ptp(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - static char *kwlist[] = {"axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, - &axis)) + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Ptp(self, axis); + return PyArray_Ptp(self, axis, out); } @@ -218,14 +233,17 @@ array_min(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - static char *kwlist[] = {"axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, - &axis)) + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Min(self, axis); + return PyArray_Min(self, axis, out); } static char doc_swapaxes[] = "a.swapaxes(axis1, axis2) returns new view with axes swapped."; @@ -451,7 +469,7 @@ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ss", kwlist, &file, &sep, &format)) return NULL; - if (PyString_Check(file)) { + if (PyString_Check(file) || PyUnicode_Check(file)) { file = PyObject_CallFunction((PyObject *)&PyFile_Type, "Os", file, "wb"); if (file==NULL) return NULL; @@ -610,7 +628,7 @@ return PyArray_NewCopy(self, fortran); } -static char doc_resize[] = "self.resize(new_shape, refcheck=True, fortran=False). "\ +static char doc_resize[] = "self.resize(new_shape, refcheck=True, order=False). "\ "Change size and shape of self inplace.\n"\ "\n Array must own its own memory and not be referenced by other " \ "arrays\n Returns None."; @@ -633,7 +651,7 @@ return NULL; } } - ref = PyDict_GetItemString(kwds, "fortran"); + ref = PyDict_GetItemString(kwds, "order"); if (ref != NULL || (PyArray_OrderConverter(ref, &fortran) == PY_FAIL)) return NULL; @@ -678,7 +696,7 @@ return _ARET(PyArray_Repeat(self, repeats, axis)); } -static char doc_choose[] = "a.choose(b0, b1, ..., bn)\n"\ +static char doc_choose[] = "a.choose(b0, b1, ..., bn, out=None, mode='raise')\n"\ "\n" \ "Return an array that merges the b_i arrays together using 'a' as the index\n" "The b_i arrays and 'a' must all be broadcastable to the same shape.\n" @@ -687,10 +705,12 @@ "an integer array with entries from 0 to n+1."; static PyObject * -array_choose(PyArrayObject *self, PyObject *args) +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) { @@ -700,8 +720,18 @@ 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)); + return _ARET(PyArray_Choose(self, choices, out, clipmode)); } static char doc_sort[] = "a.sort(axis=-1,kind='quicksort') sorts in place along axis. Return is None and kind can be 'quicksort', 'mergesort', or 'heapsort'"; @@ -1254,14 +1284,17 @@ { int axis=MAX_DIMS; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"axis", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, - &dtype)) return NULL; + &dtype, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Mean(self, axis, _CHKTYPENUM(dtype)); + return PyArray_Mean(self, axis, _CHKTYPENUM(dtype), out); } static char doc_sum[] = "a.sum(axis=None, dtype=None)\n\n"\ @@ -1293,32 +1326,38 @@ { int axis=MAX_DIMS; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"axis", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, - &dtype)) return NULL; + &dtype, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Sum(self, axis, _CHKTYPENUM(dtype)); + return PyArray_Sum(self, axis, _CHKTYPENUM(dtype), out); } -static char doc_cumsum[] = "a.cumsum(axis=None, dtype=None)"; +static char doc_cumsum[] = "a.cumsum(axis=None, dtype=None, out=None)"; static PyObject * array_cumsum(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"axis", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, - &dtype)) return NULL; + &dtype, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_CumSum(self, axis, _CHKTYPENUM(dtype)); + return PyArray_CumSum(self, axis, _CHKTYPENUM(dtype), out); } static char doc_prod[] = "a.prod(axis=None, dtype=None)"; @@ -1328,14 +1367,17 @@ { int axis=MAX_DIMS; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"axis", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, - &dtype)) return NULL; + &dtype, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Prod(self, axis, _CHKTYPENUM(dtype)); + return PyArray_Prod(self, axis, _CHKTYPENUM(dtype), out); } @@ -1346,31 +1388,37 @@ { int axis=MAX_DIMS; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"axis", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, - &dtype)) return NULL; + &dtype, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_CumProd(self, axis, _CHKTYPENUM(dtype)); + return PyArray_CumProd(self, axis, _CHKTYPENUM(dtype), out); } -static char doc_any[] = "a.any(axis=None)"; +static char doc_any[] = "a.any(axis=None, out=None)"; static PyObject * array_any(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - static char *kwlist[] = {"axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, - &axis)) + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Any(self, axis); + return PyArray_Any(self, axis, out); } static char doc_all[] = "a.all(axis=None)"; @@ -1379,17 +1427,20 @@ array_all(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - static char *kwlist[] = {"axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, - &axis)) + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_All(self, axis); + return PyArray_All(self, axis, out); } -static char doc_stddev[] = "a.std(axis=None, dtype=None)\n" +static char doc_stddev[] = "a.std(axis=None, dtype=None, out=None)\n" "Return the standard deviation, a measure of the spread of a distribution.\n" "\n" "The standard deviation is the square root of the average of the squared\n" @@ -1402,14 +1453,17 @@ { int axis=MAX_DIMS; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"axis", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, - &dtype)) return NULL; + &dtype, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Std(self, axis, _CHKTYPENUM(dtype), 0); + return PyArray_Std(self, axis, _CHKTYPENUM(dtype), out, 0); } static char doc_variance[] = "a.var(axis=None, dtype=None)"; @@ -1419,30 +1473,36 @@ { int axis=MAX_DIMS; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"axis", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_DescrConverter2, - &dtype)) return NULL; + &dtype, + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Std(self, axis, _CHKTYPENUM(dtype), 1); + return PyArray_Std(self, axis, _CHKTYPENUM(dtype), out, 1); } -static char doc_compress[] = "a.compress(condition=, axis=None)"; +static char doc_compress[] = "a.compress(condition=, axis=None, out=None)"; static PyObject * array_compress(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyObject *condition; - static char *kwlist[] = {"condition", "axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"condition", "axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&", kwlist, &condition, PyArray_AxisConverter, - &axis)) return NULL; + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return _ARET(PyArray_Compress(self, condition, axis)); + return _ARET(PyArray_Compress(self, condition, axis, out)); } static char doc_nonzero[] = \ @@ -1465,7 +1525,7 @@ } -static char doc_trace[] = "a.trace(offset=0, axis1=0, axis2=1, dtype=None)\n"\ +static char doc_trace[] = "a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)\n"\ "return the sum along the offset diagonal of the arrays indicated\n" \ "axis1 and axis2."; @@ -1474,15 +1534,17 @@ { int axis1=0, axis2=1, offset=0; PyArray_Descr *dtype=NULL; - static char *kwlist[] = {"offset", "axis1", "axis2", "dtype", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"offset", "axis1", "axis2", "dtype", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiiO&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiiO&O&", kwlist, &offset, &axis1, &axis2, - PyArray_DescrConverter2, &dtype)) + PyArray_DescrConverter2, &dtype, + PyArray_OutputConverter, &out)) return NULL; return _ARET(PyArray_Trace(self, offset, axis1, axis2, - _CHKTYPENUM(dtype))); + _CHKTYPENUM(dtype), out)); } #undef _CHKTYPENUM @@ -1558,19 +1620,21 @@ return PyArray_Ravel(self, fortran); } -static char doc_round[] = "a.round(decimals=0)"; +static char doc_round[] = "a.round(decimals=0, out=None)"; static PyObject * array_round(PyArrayObject *self, PyObject *args, PyObject *kwds) { int decimals = 0; - static char *kwlist[] = {"decimals", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"decimals", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", kwlist, - &decimals)) - return NULL; - - return _ARET(PyArray_Round(self, decimals)); + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&", kwlist, + &decimals, PyArray_OutputConverter, + &out)) + return NULL; + + return _ARET(PyArray_Round(self, decimals, out)); } @@ -1702,7 +1766,7 @@ {"repeat", (PyCFunction)array_repeat, METH_VARARGS|METH_KEYWORDS, doc_repeat}, {"choose", (PyCFunction)array_choose, - METH_VARARGS, doc_choose}, + METH_VARARGS|METH_KEYWORDS, doc_choose}, {"sort", (PyCFunction)array_sort, METH_VARARGS|METH_KEYWORDS, doc_sort}, {"argsort", (PyCFunction)array_argsort, Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/src/arrayobject.c 2006-08-10 11:55:33 UTC (rev 2982) @@ -3218,55 +3218,70 @@ } 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); + } + } + return kwds; +} + +static PyObject * PyArray_GenericReduceFunction(PyArrayObject *m1, PyObject *op, int axis, - int rtype) + int rtype, PyArrayObject *out) { PyObject *args, *ret=NULL, *meth; + PyObject *kwds; if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } - if (rtype == PyArray_NOTYPE) - args = Py_BuildValue("(Oi)", m1, axis); - else { - PyArray_Descr *descr; - descr = PyArray_DescrFromType(rtype); - args = Py_BuildValue("(Oic)", m1, axis, descr->type); - Py_DECREF(descr); - } + 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, NULL); + ret = PyObject_Call(meth, args, kwds); } Py_DECREF(args); Py_DECREF(meth); + Py_XDECREF(kwds); return ret; } static PyObject * PyArray_GenericAccumulateFunction(PyArrayObject *m1, PyObject *op, int axis, - int rtype) + int rtype, PyArrayObject *out) { PyObject *args, *ret=NULL, *meth; + PyObject *kwds; if (op == NULL) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } - if (rtype == PyArray_NOTYPE) - args = Py_BuildValue("(Oi)", m1, axis); - else { - PyArray_Descr *descr; - descr = PyArray_DescrFromType(rtype); - args = Py_BuildValue("(Oic)", m1, axis, descr->type); - Py_DECREF(descr); - } + 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, NULL); + ret = PyObject_Call(meth, args, kwds); } Py_DECREF(args); Py_DECREF(meth); + Py_XDECREF(kwds); return ret; } Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-10 11:55:33 UTC (rev 2982) @@ -213,22 +213,36 @@ Round */ static PyObject * -PyArray_Round(PyArrayObject *a, int decimals) +PyArray_Round(PyArrayObject *a, int decimals, PyArrayObject *out) { - PyObject *f, *ret=NULL, *tmp; + PyObject *f, *ret=NULL, *tmp, *op1, *op2; + if (out && (!PyArray_SAMESHAPE(out, a) || + !PyArray_EquivTypes(a->descr, out->descr))) { + PyErr_SetString(PyExc_ValueError, + "output array must have the same shape" + "and type"); + return NULL; + } if (PyArray_ISCOMPLEX(a)) { PyObject *part; PyObject *round_part; PyObject *new; int res; - new = PyArray_Copy(a); - if (new == NULL) return NULL; + 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); + 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); @@ -239,7 +253,8 @@ part = PyObject_GetAttrString(new, "imag"); if (part == NULL) {Py_DECREF(new); return NULL;} part = PyArray_EnsureAnyArray(part); - round_part = PyArray_Round((PyArrayObject *)part, decimals); + 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); @@ -248,64 +263,50 @@ return new; } /* do the most common case first */ - if (decimals == 0) { + if (decimals >= 0) { if (PyArray_ISINTEGER(a)) { - Py_INCREF(a); - return (PyObject *)a; + if (out) { + if (PyArray_CopyInto(out, a) < 0) return NULL; + Py_INCREF(out); + return (PyObject *)out; + } + else { + Py_INCREF(a); + return (PyObject *)a; + } } - return PyArray_GenericUnaryFunction((PyAO *)a, n_ops.rint); - } - if (decimals > 0) { - if (PyArray_ISINTEGER(a)) { - Py_INCREF(a); - return (PyObject *)a; - } - f = PyFloat_FromDouble(power_of_ten(decimals)); - if (f==NULL) return NULL; - ret = PyNumber_Multiply((PyObject *)a, f); - if (ret==NULL) goto finish; - if (PyArray_IsScalar(ret, Generic)) { - /* array scalars cannot be modified inplace */ - tmp = PyObject_CallFunction(n_ops.rint, "O", ret); - Py_DECREF(ret); - if (tmp == NULL) {ret=NULL; goto finish;} - ret = PyObject_CallFunction(n_ops.divide, "OO", - tmp, f); - Py_DECREF(tmp); - } else { - 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(n_ops.divide, "OOO", ret, - f, ret); - if (tmp == NULL) {Py_DECREF(ret); ret=NULL; goto finish;} - Py_DECREF(tmp); - } - } - else { - /* remaining case: decimals < 0 */ - f = PyFloat_FromDouble(power_of_ten(-decimals)); - if (f==NULL) return NULL; - ret = PyNumber_Divide((PyObject *)a, f); - if (ret==NULL) goto finish; - if (PyArray_IsScalar(ret, Generic)) { - /* array scalars cannot be modified inplace */ - tmp = PyObject_CallFunction(n_ops.rint, "O", ret); - Py_DECREF(ret); - if (tmp == NULL) {ret=NULL; goto finish;} - ret = PyObject_CallFunction(n_ops.multiply, "OO", - tmp, f); - Py_DECREF(tmp); - } else { - 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(n_ops.multiply, "OOO", ret, - f, ret); - if (tmp==NULL) {Py_DECREF(ret); ret=NULL; goto finish;} - Py_DECREF(tmp); - } - } + 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.divide; + } + else { + op1 = n_ops.divide; + op2 = n_ops.multiply; + decimals = -decimals; + } + if (!out) { + Py_INCREF(a->descr); + out = (PyArrayObject *)PyArray_Empty(a->nd, a->dimensions, + a->descr, + PyArray_ISFORTRAN(a)); + if (out == NULL) return NULL; + } + 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); @@ -594,7 +595,7 @@ Mean */ static PyObject * -PyArray_Mean(PyArrayObject *self, int axis, int rtype) +PyArray_Mean(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *obj1=NULL, *obj2=NULL; PyObject *new, *ret; @@ -602,7 +603,7 @@ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; obj1 = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis, - rtype); + rtype, out); obj2 = PyFloat_FromDouble((double) PyArray_DIM(new,axis)); Py_DECREF(new); if (obj1 == NULL || obj2 == NULL) { @@ -610,10 +611,14 @@ Py_XDECREF(obj2); return NULL; } - - ret = PyNumber_Divide(obj1, obj2); - Py_DECREF(obj1); - Py_DECREF(obj2); + 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; } @@ -622,7 +627,8 @@ Std */ static PyObject * -PyArray_Std(PyArrayObject *self, int axis, int rtype, int variance) +PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out, + int variance) { PyObject *obj1=NULL, *obj2=NULL, *new=NULL; PyObject *ret=NULL, *newshape=NULL; @@ -630,9 +636,9 @@ 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)); + 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); @@ -660,7 +666,7 @@ /* Compute add.reduce(x*x,axis) */ obj1 = PyArray_GenericReduceFunction((PyAO *)obj2, n_ops.add, - axis, rtype); + axis, rtype, NULL); Py_DECREF(obj2); if (obj1 == NULL) {Py_DECREF(new); return NULL;} @@ -686,6 +692,15 @@ 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; + } return ret; } @@ -694,14 +709,14 @@ Sum */ static PyObject * -PyArray_Sum(PyArrayObject *self, int axis, int rtype) +PyArray_Sum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *new, *ret; if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis, - rtype); + rtype, out); Py_DECREF(new); return ret; } @@ -710,14 +725,14 @@ Prod */ static PyObject * -PyArray_Prod(PyArrayObject *self, int axis, int rtype) +PyArray_Prod(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *new, *ret; if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.multiply, axis, - rtype); + rtype, out); Py_DECREF(new); return ret; } @@ -726,14 +741,14 @@ CumSum */ static PyObject * -PyArray_CumSum(PyArrayObject *self, int axis, int rtype) +PyArray_CumSum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *new, *ret; if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; ret = PyArray_GenericAccumulateFunction((PyAO *)new, n_ops.add, axis, - rtype); + rtype, out); Py_DECREF(new); return ret; } @@ -742,7 +757,7 @@ CumProd */ static PyObject * -PyArray_CumProd(PyArrayObject *self, int axis, int rtype) +PyArray_CumProd(PyArrayObject *self, int axis, int rtype, PyArrayObject *out) { PyObject *new, *ret; @@ -750,7 +765,7 @@ ret = PyArray_GenericAccumulateFunction((PyAO *)new, n_ops.multiply, axis, - rtype); + rtype, out); Py_DECREF(new); return ret; } @@ -759,7 +774,7 @@ Any */ static PyObject * -PyArray_Any(PyArrayObject *self, int axis) +PyArray_Any(PyArrayObject *self, int axis, PyArrayObject *out) { PyObject *new, *ret; @@ -767,7 +782,7 @@ ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.logical_or, axis, - PyArray_BOOL); + PyArray_BOOL, out); Py_DECREF(new); return ret; } @@ -776,7 +791,7 @@ All */ static PyObject * -PyArray_All(PyArrayObject *self, int axis) +PyArray_All(PyArrayObject *self, int axis, PyArrayObject *out) { PyObject *new, *ret; @@ -784,7 +799,7 @@ ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.logical_and, axis, - PyArray_BOOL); + PyArray_BOOL, out); Py_DECREF(new); return ret; } @@ -794,7 +809,8 @@ Compress */ static PyObject * -PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis) +PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis, + PyArrayObject *out) { PyArrayObject *cond; PyObject *res, *ret; @@ -908,7 +924,7 @@ newtup = Py_BuildValue("(OOO)", (PyObject *)self, min, max); if (newtup == NULL) {Py_DECREF(selector); return NULL;} - ret = PyArray_Choose((PyAO *)selector, newtup); + ret = PyArray_Choose((PyAO *)selector, newtup, NULL, NPY_RAISE); Py_DECREF(selector); Py_DECREF(newtup); return ret; @@ -961,13 +977,13 @@ */ static PyObject * PyArray_Trace(PyArrayObject *self, int offset, int axis1, int axis2, -int rtype) + int rtype, PyArrayObject *out) { 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); + ret = PyArray_GenericReduceFunction((PyAO *)diag, n_ops.add, -1, rtype, out); Py_DECREF(diag); return ret; } @@ -1762,19 +1778,20 @@ } - /*MULTIARRAY_API */ static PyObject * -PyArray_Choose(PyArrayObject *ip, PyObject *op) +PyArray_Choose(PyArrayObject *ip, PyObject *op, PyArrayObject *ret, + NPY_CLIPMODE clipmode) { intp *sizes, offset; - int i,n,m,elsize; + int n, elsize; + intp i, m; char *ret_data; - PyArrayObject **mps, *ap, *ret; + PyArrayObject **mps, *ap; intp *self_data, mi; + int copyret=0; ap = NULL; - ret = NULL; /* Convert all inputs to arrays of a common type */ mps = PyArray_ConvertToCommonType(op, &n); @@ -1784,8 +1801,8 @@ if (sizes == NULL) goto fail; ap = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ip, - PyArray_INTP, - 0, 0); + PyArray_INTP, + 0, 0); if (ap == NULL) goto fail; /* Check the dimensions of the arrays */ @@ -1805,29 +1822,70 @@ sizes[i] = PyArray_NBYTES(mps[i]); } - Py_INCREF(mps[0]->descr); - ret = (PyArrayObject *)PyArray_NewFromDescr(ap->ob_type, - mps[0]->descr, - ap->nd, - ap->dimensions, - NULL, NULL, 0, - (PyObject *)ap); - if (ret == NULL) goto fail; - + Py_INCREF(mps[0]->descr); + if (!ret) { + ret = (PyArrayObject *)PyArray_NewFromDescr(ap->ob_type, + mps[0]->descr, + ap->nd, + ap->dimensions, + NULL, NULL, 0, + (PyObject *)ap); + if (ret == NULL) goto fail; + } + else { + PyArrayObject *obj; + int flags = NPY_CARRAY | NPY_UPDATEIFCOPY; + + if (!PyArray_SAMESHAPE(ap, ret)) { + PyErr_SetString(PyExc_TypeError, + "invalid shape for output array."); + ret = NULL; + Py_DECREF(mps[0]->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, mps[0]->descr, + flags); + if (obj != ret) copyret = 1; + ret = obj; + } + elsize = ret->descr->elsize; m = PyArray_SIZE(ret); self_data = (intp *)ap->data; - ret_data = ret->data; - + ret_data = ret->data; + for (i=0; i= n) { - PyErr_SetString(PyExc_ValueError, - "invalid entry in choice array"); - goto fail; - } - offset = i*elsize; - if (offset >= sizes[mi]) {offset = offset % sizes[mi]; } + 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; + } + } + offset = i*elsize; + if (offset >= sizes[mi]) {offset = offset % sizes[mi]; } memmove(ret_data, mps[mi]->data+offset, elsize); ret_data += elsize; self_data++; } @@ -1837,7 +1895,13 @@ 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: @@ -1845,7 +1909,7 @@ Py_XDECREF(ap); PyDataMem_FREE(mps); _pya_free(sizes); - Py_XDECREF(ret); + PyArray_XDECREF_ERR(ret); return NULL; } @@ -2984,7 +3048,7 @@ Max */ static PyObject * -PyArray_Max(PyArrayObject *ap, int axis) +PyArray_Max(PyArrayObject *ap, int axis, PyArrayObject *out) { PyArrayObject *arr; PyObject *ret; @@ -2992,7 +3056,7 @@ if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL) return NULL; ret = PyArray_GenericReduceFunction(arr, n_ops.maximum, axis, - arr->descr->type_num); + arr->descr->type_num, out); Py_DECREF(arr); return ret; } @@ -3001,7 +3065,7 @@ Min */ static PyObject * -PyArray_Min(PyArrayObject *ap, int axis) +PyArray_Min(PyArrayObject *ap, int axis, PyArrayObject *out) { PyArrayObject *arr; PyObject *ret; @@ -3009,7 +3073,7 @@ if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL) return NULL; ret = PyArray_GenericReduceFunction(arr, n_ops.minimum, axis, - arr->descr->type_num); + arr->descr->type_num, out); Py_DECREF(arr); return ret; } @@ -3018,7 +3082,7 @@ Ptp */ static PyObject * -PyArray_Ptp(PyArrayObject *ap, int axis) +PyArray_Ptp(PyArrayObject *ap, int axis, PyArrayObject *out) { PyArrayObject *arr; PyObject *ret; @@ -3026,12 +3090,17 @@ if ((arr=(PyArrayObject *)_check_axis(ap, &axis, 0))==NULL) return NULL; - obj1 = PyArray_Max(arr, axis); + obj1 = PyArray_Max(arr, axis, out); if (obj1 == NULL) goto fail; - obj2 = PyArray_Min(arr, axis); + obj2 = PyArray_Min(arr, axis, NULL); if (obj2 == NULL) goto fail; Py_DECREF(arr); - ret = PyNumber_Subtract(obj1, obj2); + 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; @@ -3132,12 +3201,14 @@ Take */ static PyObject * -PyArray_Take(PyArrayObject *self0, PyObject *indices0, int axis) +PyArray_TakeOut(PyArrayObject *self0, PyObject *indices0, int axis, + PyArrayObject *ret, NPY_CLIPMODE clipmode) { - PyArrayObject *self, *indices, *ret; + PyArrayObject *self, *indices; intp nd, i, j, n, m, max_item, tmp, chunk; intp shape[MAX_DIMS]; char *src, *dest; + int copyret=0; indices = ret = NULL; self = (PyAO *)_check_axis(self0, &axis, CARRAY); @@ -3165,45 +3236,111 @@ } } Py_INCREF(self->descr); - ret = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type, - self->descr, - nd, shape, - NULL, NULL, 0, - (PyObject *)self); + if (!ret) { + ret = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type, + self->descr, + nd, shape, + NULL, NULL, 0, + (PyObject *)self); + + 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; + } + + 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 (ret == NULL) goto fail; - max_item = self->dimensions[axis]; chunk = chunk * ret->descr->elsize; src = self->data; dest = ret->data; - - for(i=0; idata))[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; + + switch(clipmode) { + case NPY_RAISE: + for(i=0; idata))[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; } - memmove(dest, src+tmp*chunk, chunk); - dest += chunk; + src += chunk*max_item; } - src += chunk*max_item; + break; + case NPY_WRAP: + for(i=0; idata))[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; idata))[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); 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; fail: - Py_XDECREF(ret); + PyArray_XDECREF_ERR(ret); Py_XDECREF(indices); Py_XDECREF(self); return NULL; @@ -3213,28 +3350,40 @@ Put values into an array */ static PyObject * -PyArray_Put(PyArrayObject *self, PyObject* values0, PyObject *indices0) +PyArray_PutIn(PyArrayObject *self, PyObject* values0, PyObject *indices0, + NPY_CLIPMODE clipmode) { PyArrayObject *indices, *values; int i, chunk, ni, max_item, nv, tmp, thistype; char *src, *dest; + int copied = 0; indices = NULL; values = NULL; if (!PyArray_Check(self)) { - PyErr_SetString(PyExc_TypeError, "put: first argument must be an array"); + PyErr_SetString(PyExc_TypeError, + "put: first argument must be an array"); return NULL; } if (!PyArray_ISCONTIGUOUS(self)) { - PyErr_SetString(PyExc_ValueError, "put: first argument must be contiguous"); - return NULL; + 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; } max_item = PyArray_SIZE(self); dest = self->data; chunk = self->descr->elsize; - indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, PyArray_INTP, 0, 0); + indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, + PyArray_INTP, 0, 0); if (indices == NULL) goto fail; ni = PyArray_SIZE(indices); @@ -3244,44 +3393,107 @@ DEFAULT | FORCECAST, NULL); if (values == NULL) goto fail; nv = PyArray_SIZE(values); - if (nv > 0) { /* nv == 0 for a null array */ - if (self->descr->hasobject) { + if (nv <= 0) goto finish; + if (self->descr->hasobject) { + switch(clipmode) { + case NPY_RAISE: for(i=0; idata + 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"); + 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); + 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; idata + 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; idata + 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 { + } + else { + switch(clipmode) { + case NPY_RAISE: for(i=0; idata + 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"); + 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; idata + 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; idata + 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; fail: Py_XDECREF(indices); Py_XDECREF(values); + if (copied) { + PyArray_XDECREF_ERR(self); + } return NULL; } @@ -3289,11 +3501,12 @@ Put values into an array according to a mask. */ static PyObject * -PyArray_PutMask(PyArrayObject *self, PyObject* values0, PyObject* mask0) +PyArray_PutMask(PyArrayObject *self, PyObject* values0, PyObject* mask0) { PyArrayObject *mask, *values; int i, chunk, ni, max_item, nv, tmp, thistype; char *src, *dest; + int copied=0; mask = NULL; values = NULL; @@ -3305,9 +3518,13 @@ return NULL; } if (!PyArray_ISCONTIGUOUS(self)) { - PyErr_SetString(PyExc_ValueError, - "putmask: first argument must be contiguous"); - return NULL; + 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); @@ -3330,6 +3547,12 @@ PyArray_ContiguousFromAny(values0, thistype, 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 (nv > 0) { if (self->descr->hasobject) { for(i=0; i= (int) NPY_CLIP) + *val = (NPY_CLIPMODE) number; + else goto fail; + } + return PY_SUCCEED; + fail: + PyErr_SetString(PyExc_TypeError, + "clipmode not understood"); + return PY_FAIL; +} + + + /*MULTIARRAY_API Typestr converter */ @@ -5358,7 +5661,7 @@ if (type == NULL) type = PyArray_DescrFromType(PyArray_DEFAULT); - if (PyString_Check(file)) { + if (PyString_Check(file) || PyUnicode_Check(file)) { file = PyObject_CallFunction((PyObject *)&PyFile_Type, "Os", file, "rb"); if (file==NULL) return NULL; @@ -5901,7 +6204,7 @@ tup = Py_BuildValue("(OO)", y, x); if (tup == NULL) {Py_DECREF(obj); return NULL;} - ret = PyArray_Choose((PyAO *)obj, tup); + ret = PyArray_Choose((PyAO *)obj, tup, NULL, NPY_RAISE); Py_DECREF(obj); Py_DECREF(tup); @@ -6287,6 +6590,18 @@ PyDict_SetItemString(d, "BUFSIZE", s); Py_DECREF(s); + s = PyInt_FromLong(NPY_CLIP); + PyDict_SetItemString(d, "CLIP", s); + Py_DECREF(s); + + s = PyInt_FromLong(NPY_RAISE); + PyDict_SetItemString(d, "RAISE", s); + Py_DECREF(s); + + s = PyInt_FromLong(NPY_WRAP); + PyDict_SetItemString(d, "WRAP", s); + Py_DECREF(s); + s = PyInt_FromLong(NPY_MAXDIMS); PyDict_SetItemString(d, "MAXDIMS", s); Py_DECREF(s); Modified: trunk/numpy/core/src/scalartypes.inc.src =================================================================== --- trunk/numpy/core/src/scalartypes.inc.src 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/src/scalartypes.inc.src 2006-08-10 11:55:33 UTC (rev 2982) @@ -1071,7 +1071,7 @@ /**begin repeat -#name=tolist, item, tostring, astype, copy, __deepcopy__, choose, searchsorted, view, swapaxes, conj, conjugate, nonzero, flatten, ravel, fill, transpose, newbyteorder# +#name=tolist, item, tostring, astype, copy, __deepcopy__, searchsorted, view, swapaxes, conj, conjugate, nonzero, flatten, ravel, fill, transpose, newbyteorder# */ static PyObject * @@ -1130,7 +1130,7 @@ /**begin repeat -#name=take, getfield, put, putmask, repeat, tofile, mean, trace, diagonal, clip, std, var, sum, cumsum, prod, cumprod, compress, sort, argsort, round, argmax, argmin, max, min, ptp, any, all, resize, reshape# +#name=take, getfield, put, putmask, repeat, tofile, mean, trace, diagonal, clip, std, var, sum, cumsum, prod, cumprod, compress, sort, argsort, round, argmax, argmin, max, min, ptp, any, all, resize, reshape, choose# */ static PyObject * @@ -1344,7 +1344,7 @@ {"repeat", (PyCFunction)gentype_repeat, METH_VARARGS|METH_KEYWORDS, NULL}, {"choose", (PyCFunction)gentype_choose, - METH_VARARGS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"sort", (PyCFunction)gentype_sort, METH_VARARGS, NULL}, {"argsort", (PyCFunction)gentype_argsort, Modified: trunk/numpy/core/src/ufuncobject.c =================================================================== --- trunk/numpy/core/src/ufuncobject.c 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/core/src/ufuncobject.c 2006-08-10 11:55:33 UTC (rev 2982) @@ -1755,25 +1755,27 @@ } static PyUFuncReduceObject * -construct_reduce(PyUFuncObject *self, PyArrayObject **arr, int axis, - int otype, int operation, intp ind_size, char *str) +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]; + intp loop_i[MAX_DIMS], outsize; int arg_types[3] = {otype, otype, otype}; PyArray_SCALARKIND scalars[3] = {PyArray_NOSCALAR, PyArray_NOSCALAR, PyArray_NOSCALAR}; int i, j; int nd = (*arr)->nd; + int flags; /* Reduce type is the type requested of the input during reduction */ if ((loop = _pya_malloc(sizeof(PyUFuncReduceObject)))==NULL) { PyErr_NoMemory(); return loop; } - + + loop->retbase=0; loop->swap = 0; loop->index = 0; loop->ufunc = self; @@ -1853,6 +1855,7 @@ } /* Construct return array */ + flags = NPY_CARRAY | NPY_UPDATEIFCOPY | NPY_FORCECAST; switch(operation) { case UFUNC_REDUCE: for (j=0, i=0; idimensions[i]; } - loop->ret = (PyArrayObject *) \ - PyArray_New(aar->ob_type, aar->nd-1, loop_i, otype, - NULL, NULL, 0, 0, (PyObject *)aar); + 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: - loop->ret = (PyArrayObject *) \ - PyArray_New(aar->ob_type, aar->nd, aar->dimensions, - otype, NULL, NULL, 0, 0, (PyObject *)aar); + 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; - loop->ret = (PyArrayObject *)\ - PyArray_New(aar->ob_type, aar->nd, loop_i, otype, - NULL, NULL, 0, 0, (PyObject *)aar); - if (loop->ret == NULL) goto fail; + 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 = ZERODIM_REDUCELOOP; return loop; @@ -1885,6 +1903,19 @@ 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; @@ -1982,7 +2013,8 @@ */ static PyObject * -PyUFunc_Reduce(PyUFuncObject *self, PyArrayObject *arr, int axis, int otype) +PyUFunc_Reduce(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out, + int axis, int otype) { PyArrayObject *ret=NULL; PyUFuncReduceObject *loop; @@ -1991,7 +2023,7 @@ NPY_BEGIN_THREADS_DEF /* Construct loop object */ - loop = construct_reduce(self, &arr, axis, otype, UFUNC_REDUCE, 0, + loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_REDUCE, 0, "reduce"); if (!loop) return NULL; @@ -2108,8 +2140,9 @@ NPY_LOOP_END_THREADS - ret = loop->ret; /* 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; @@ -2123,8 +2156,8 @@ static PyObject * -PyUFunc_Accumulate(PyUFuncObject *self, PyArrayObject *arr, int axis, - int otype) +PyUFunc_Accumulate(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out, + int axis, int otype) { PyArrayObject *ret=NULL; PyUFuncReduceObject *loop; @@ -2133,7 +2166,7 @@ NPY_BEGIN_THREADS_DEF /* Construct loop object */ - loop = construct_reduce(self, &arr, axis, otype, UFUNC_ACCUMULATE, 0, + loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_ACCUMULATE, 0, "accumulate"); if (!loop) return NULL; @@ -2253,8 +2286,10 @@ } NPY_LOOP_END_THREADS - ret = loop->ret; + /* 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; @@ -2287,7 +2322,7 @@ static PyObject * PyUFunc_Reduceat(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *ind, - int axis, int otype) + PyArrayObject *out, int axis, int otype) { PyArrayObject *ret; PyUFuncReduceObject *loop; @@ -2310,7 +2345,7 @@ ptr = (intp *)ind->data; /* Construct loop object */ - loop = construct_reduce(self, &arr, axis, otype, UFUNC_REDUCEAT, nn, + loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_REDUCEAT, nn, "reduceat"); if (!loop) return NULL; @@ -2404,9 +2439,10 @@ } NPY_LOOP_END_THREADS - - ret = loop->ret; - /* 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; @@ -2434,8 +2470,9 @@ PyObject *obj_ind, *context; PyArrayObject *indices = NULL; PyArray_Descr *otype=NULL; - static char *kwlist1[] = {"array", "axis", "dtype", NULL}; - static char *kwlist2[] = {"array", "indices", "axis", "dtype", 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) { @@ -2460,19 +2497,23 @@ if (operation == UFUNC_REDUCEAT) { PyArray_Descr *indtype; indtype = PyArray_DescrFromType(PyArray_INTP); - if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO|iO&", kwlist2, + if(!PyArg_ParseTupleAndKeywords(args, kwds, "OO|iO&O&", kwlist2, &op, &obj_ind, &axis, PyArray_DescrConverter2, - &otype)) return NULL; + &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&", kwlist1, + if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|iO&O&", kwlist1, &op, &axis, PyArray_DescrConverter2, - &otype)) return NULL; + &otype, + PyArray_OutputConverter, + &out)) return NULL; } /* Ensure input is an array */ @@ -2511,7 +2552,14 @@ return NULL; } - /* Get default type to reduce over if not given */ + /* 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 --- makes sure at least a long is used */ @@ -2533,15 +2581,15 @@ switch(operation) { case UFUNC_REDUCE: - ret = (PyArrayObject *)PyUFunc_Reduce(self, mp, axis, + ret = (PyArrayObject *)PyUFunc_Reduce(self, mp, out, axis, otype->type_num); break; case UFUNC_ACCUMULATE: - ret = (PyArrayObject *)PyUFunc_Accumulate(self, mp, axis, + ret = (PyArrayObject *)PyUFunc_Accumulate(self, mp, out, axis, otype->type_num); break; case UFUNC_REDUCEAT: - ret = (PyArrayObject *)PyUFunc_Reduceat(self, mp, indices, + ret = (PyArrayObject *)PyUFunc_Reduceat(self, mp, indices, out, axis, otype->type_num); Py_DECREF(indices); break; Modified: trunk/numpy/numarray/__init__.py =================================================================== --- trunk/numpy/numarray/__init__.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/numarray/__init__.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -2,21 +2,24 @@ from numerictypes import * from functions import * from ufuncs import * +from session import * import util import numerictypes import functions import ufuncs import compat +import session -__all__ = util.__all__ +__all__ = ['session', 'numerictypes'] +__all__ += util.__all__ __all__ += numerictypes.__all__ __all__ += functions.__all__ __all__ += ufuncs.__all__ __all__ += compat.__all__ +__all__ += session.__all__ del util -del numerictypes del functions del ufuncs del compat Modified: trunk/numpy/numarray/compat.py =================================================================== --- trunk/numpy/numarray/compat.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/numarray/compat.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -1,6 +1,4 @@ -__all__ = ['NewAxis'] +__all__ = ['NewAxis', 'ArrayType'] -from numpy import newaxis - -NewAxis = newaxis +from numpy import newaxis as NewAxis, ndarray as ArrayType Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/numarray/functions.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -1,71 +1,80 @@ # missing Numarray defined names (in from numarray import *) -##__all__ = ['ArrayType', 'CLIP', 'ClassicUnpickler', 'Complex32_fromtype', -## 'Complex64_fromtype', 'ComplexArray', 'EarlyEOFError', 'Error', -## 'FileSeekWarning', 'MAX_ALIGN', 'MAX_INT_SIZE', 'MAX_LINE_WIDTH', -## 'MathDomainError', 'NDArray', 'NewArray', 'NewAxis', 'NumArray', -## 'NumError', 'NumOverflowError', 'PRECISION', 'Py2NumType', +##__all__ = ['ClassicUnpickler', 'Complex32_fromtype', +## 'Complex64_fromtype', 'ComplexArray', 'Error', +## 'MAX_ALIGN', 'MAX_INT_SIZE', 'MAX_LINE_WIDTH', +## 'NDArray', 'NewArray', 'NumArray', +## 'NumError', 'PRECISION', 'Py2NumType', ## 'PyINT_TYPES', 'PyLevel2Type', 'PyNUMERIC_TYPES', 'PyREAL_TYPES', -## 'RAISE', 'SLOPPY', 'STRICT', 'SUPPRESS_SMALL', 'SizeMismatchError', -## 'SizeMismatchWarning', 'SuitableBuffer', 'USING_BLAS', -## 'UnderflowError', 'UsesOpPriority', 'WARN', 'WRAP', 'all', -## 'allclose', 'alltrue', 'and_', 'any', 'arange', 'argmax', -## 'argmin', 'argsort', 'around', 'array2list', 'array_equal', -## 'array_equiv', 'array_repr', 'array_str', 'arrayprint', -## 'arrayrange', 'average', 'choose', 'clip', -## 'codegenerator', 'compress', 'concatenate', 'conjugate', -## 'copy', 'copy_reg', 'diagonal', 'divide_remainder', -## 'dotblas', 'e', 'explicit_type', 'flush_caches', 'fromfile', -## 'fromfunction', 'fromlist', 'fromstring', 'generic', -## 'genericCoercions', 'genericPromotionExclusions', 'genericTypeRank', -## 'getShape', 'getTypeObject', 'handleError', 'identity', 'indices', -## 'info', 'innerproduct', 'inputarray', 'isBigEndian', -## 'kroneckerproduct', 'lexsort', 'libnumarray', 'libnumeric', -## 'load', 'make_ufuncs', 'math', 'memory', -## 'numarrayall', 'numarraycore', 'numerictypes', 'numinclude', -## 'operator', 'os', 'outerproduct', 'pi', 'put', 'putmask', -## 'pythonTypeMap', 'pythonTypeRank', 'rank', 'repeat', -## 'reshape', 'resize', 'round', 'safethread', 'save', 'scalarTypeMap', -## 'scalarTypes', 'searchsorted', 'session', 'shape', 'sign', 'size', -## 'sometrue', 'sort', 'swapaxes', 'sys', 'take', 'tcode', -## 'tensormultiply', 'tname', 'trace', 'transpose', 'typeDict', -## 'typecode', 'typecodes', 'typeconv', 'types', 'ufunc', -## 'ufuncFactory', 'value', 'ieeemask', 'cumproduct', 'cumsum', -## 'nonzero'] +## 'SUPPRESS_SMALL', +## 'SuitableBuffer', 'USING_BLAS', +## 'UsesOpPriority', +## 'codegenerator', 'generic', 'libnumarray', 'libnumeric', +## 'make_ufuncs', 'memory', +## 'numarrayall', 'numarraycore', 'numinclude', 'safethread', +## 'typecode', 'typecodes', 'typeconv', 'ufunc', 'ufuncFactory', +## 'ieeemask'] - __all__ = ['asarray', 'ones', 'zeros', 'array', 'where'] __all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices', - 'arange', 'concatenate'] + 'arange', 'concatenate', 'all', 'allclose', 'alltrue', 'and_', + 'any', 'argmax', 'argmin', 'argsort', 'around', 'array_equal', + 'array_equiv', 'arrayrange', 'array_str', 'array_repr', + 'array2list', 'average', 'choose', 'CLIP', 'RAISE', 'WRAP', + 'clip', 'compress', 'concatenate', 'copy', 'copy_reg', + 'diagonal', 'divide_remainder', 'e', 'explicit_type', 'pi', + 'flush_caches', 'fromfile', 'os', 'sys', 'STRICT', + 'SLOPPY', 'WARN', 'EarlyEOFError', 'SizeMismatchError', + 'SizeMismatchWarning', 'FileSeekWarning', 'fromstring', + 'fromfunction', 'fromlist', 'getShape', 'getTypeObject', + 'identity', 'indices', 'info', 'innerproduct', 'inputarray', + 'isBigEndian', 'kroneckerproduct', 'lexsort', 'math', + 'operator', 'outerproduct', 'put', 'putmask', 'rank', + 'repeat', 'reshape', 'resize', 'round', 'searchsorted', + 'shape', 'size', 'sometrue', 'sort', 'swapaxes', 'take', + 'tcode', 'tname', 'tensormultiply', 'trace', 'transpose', + 'types', 'value', 'cumsum', 'cumproduct', 'nonzero' + ] -from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate +import copy, copy_reg, types +import os, sys, math, operator -def array(sequence=None, typecode=None, copy=1, savespace=0, - type=None, shape=None, dtype=None): - dtype = type2dtype(typecode, type, dtype) - if sequence is None: - if shape is None: - return None - if dtype is None: - dtype = 'l' - return N.empty(shape, dtype) - arr = N.array(sequence, dtype, copy=copy) - if shape is not None: - arr.shape = shape - return arr +from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\ + allclose, any, argmax, argmin, around, argsort, array_equal, array_equiv,\ + array_str, array_repr, average, CLIP, RAISE, WRAP, clip, concatenate, \ + diagonal, e, pi, fromfunction, indices, inner as innerproduct, nonzero, \ + outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \ + resize, searchsorted, shape, size, sort, swapaxes, trace, transpose +import numpy as N -def asarray(seq, type=None, typecode=None, dtype=None): - if seq is None: - return None - dtype = type2dtype(typecode, type, dtype) - return N.array(seq, dtype, copy=0) +from numerictypes import typefrom +isBigEndian = sys.byteorder != 'little' +value = tcode = 'f' +tname = 'Float32' + +# If dtype is not None, then it is used +# If type is not None, then it is used +# If typecode is not None then it is used +# If use_default is True, then the default +# data-type is returned if all are None +def type2dtype(typecode, type, dtype, use_default=True): + if dtype is None: + if type is None: + if use_default or typecode is not None: + dtype = N.dtype(typecode) + else: + dtype = N.dtype(type) + if use_default and dtype is None: + dtype = N.dtype(None) + return dtype + def ones(shape, type=None, typecode=None, dtype=None): - dtype = type2dtype(typecode, type, dtype) + dtype = type2dtype(typecode, type, dtype, 1) return N.ones(shape, dtype) def zeros(shape, type=None, typecode=None, dtype=None): - dtype = type2dtype(typecode, type, dtype) + dtype = type2dtype(typecode, type, dtype, 1) return N.zeros(shape, dtype) def where(condition, x=None, y=None, out=None): @@ -83,5 +92,349 @@ def arange(a1, a2=None, stride=1, type=None, shape=None, typecode=None, dtype=None): - dtype = type2dtype(typecode, type, dtype) + dtype = type2dtype(typecode, type, dtype, 0) return N.arange(a1, a2, stride, dtype) + +arrayrange = arange + +def alltrue(x, axis=0): + return N.alltrue(x, axis) + +def and_(a, b): + """Same as a & b + """ + return a & b + +def divide_remainder(a, b): + a, b = asarray(a), asarray(b) + return (a/b,a%b) + +def around(array, digits=0, output=None): + ret = N.around(array, digits, output) + if output is None: + return ret + return + +def array2list(arr): + return arr.tolist() + + +def choose(selector, population, outarr=None, clipmode=RAISE): + a = N.asarray(selector) + ret = a.choose(population, out=outarr, mode=clipmode) + if outarr is None: + return ret + return + +def compress(condition, a, axis=0): + return N.compress(condition, a, axis) + +# only returns a view +def explicit_type(a): + x = a.view() + return x + +# stub +def flush_caches(): + pass + + +class EarlyEOFError(Exception): + "Raised in fromfile() if EOF unexpectedly occurs." + pass + +class SizeMismatchError(Exception): + "Raised in fromfile() if file size does not match shape." + pass + +class SizeMismatchWarning(Warning): + "Issued in fromfile() if file size does not match shape." + pass + +class FileSeekWarning(Warning): + "Issued in fromfile() if there is unused data and seek() fails" + pass + + +STRICT, SLOPPY, WARN = range(3) + +_BLOCKSIZE=1024 + +# taken and adapted directly from numarray +def fromfile(infile, type=None, shape=None, sizing=STRICT, + typecode=None, dtype=None): + if isinstance(infile, (str, unicode)): + infile = open(infile, 'rb') + dtype = type2dtype(typecode, type, dtype, True) + if shape is None: + shape = (-1,) + if not isinstance(shape, tuple): + shape = (shape,) + + if (list(shape).count(-1)>1): + raise ValueError("At most one unspecified dimension in shape") + + if -1 not in shape: + if sizing != STRICT: + raise ValueError("sizing must be STRICT if size complete") + arr = N.empty(shape, dtype) + bytesleft=arr.nbytes + bytesread=0 + while(bytesleft > _BLOCKSIZE): + data = infile.read(_BLOCKSIZE) + if len(data) != _BLOCKSIZE: + raise EarlyEOFError("Unexpected EOF reading data for size complete array") + arr.data[bytesread:bytesread+_BLOCKSIZE]=data + bytesread += _BLOCKSIZE + bytesleft -= _BLOCKSIZE + if bytesleft > 0: + data = infile.read(bytesleft) + if len(data) != bytesleft: + raise EarlyEOFError("Unexpected EOF reading data for size complete array") + arr.data[bytesread:bytesread+bytesleft]=data + return arr + + + ##shape is incompletely specified + ##read until EOF + ##implementation 1: naively use memory blocks + ##problematic because memory allocation can be double what is + ##necessary (!) + + ##the most common case, namely reading in data from an unchanging + ##file whose size may be determined before allocation, should be + ##quick -- only one allocation will be needed. + + recsize = dtype.itemsize * N.product([i for i in shape if i != -1]) + blocksize = max(_BLOCKSIZE/recsize, 1)*recsize + + ##try to estimate file size + try: + curpos=infile.tell() + infile.seek(0,2) + endpos=infile.tell() + infile.seek(curpos) + except (AttributeError, IOError): + initsize=blocksize + else: + initsize=max(1,(endpos-curpos)/recsize)*recsize + + buf = N.newbuffer(initsize) + + bytesread=0 + while 1: + data=infile.read(blocksize) + if len(data) != blocksize: ##eof + break + ##do we have space? + if len(buf) < bytesread+blocksize: + buf=_resizebuf(buf,len(buf)+blocksize) + ## or rather a=resizebuf(a,2*len(a)) ? + assert len(buf) >= bytesread+blocksize + buf[bytesread:bytesread+blocksize]=data + bytesread += blocksize + + if len(data) % recsize != 0: + if sizing == STRICT: + raise SizeMismatchError("Filesize does not match specified shape") + if sizing == WARN: + _warnings.warn("Filesize does not match specified shape", + SizeMismatchWarning) + try: + infile.seek(-(len(data) % recsize),1) + except AttributeError: + _warnings.warn("Could not rewind (no seek support)", + FileSeekWarning) + except IOError: + _warnings.warn("Could not rewind (IOError in seek)", + FileSeekWarning) + datasize = (len(data)/recsize) * recsize + if len(buf) != bytesread+datasize: + buf=_resizebuf(buf,bytesread+datasize) + buf[bytesread:bytesread+datasize]=data[:datasize] + ##deduce shape from len(buf) + shape = list(shape) + uidx = shape.index(-1) + shape[uidx]=len(buf) / recsize + + a = N.ndarray(shape=shape, dtype=type, buffer=buf) + if a.dtype.char == '?': + N.not_equal(a, 0, a) + return a + +def fromstring(datastring, type=None, shape=None, typecode=None, dtype=None): + dtype = type2dtype(typecode, type, dtype, True) + if shape is None: + count = -1 + else: + count = N.product(shape)*dtype.itemsize + res = N.fromstring(datastring, count=count) + if shape is not None: + res.shape = shape + return res + + +# check_overflow is ignored +def fromlist(seq, type=None, shape=None, check_overflow=0, typecode=None, dtype=None): + dtype = type2dtype(typecode, type, dtype, False) + return N.array(seq, dtype) + +def array(sequence=None, typecode=None, copy=1, savespace=0, + type=None, shape=None, dtype=None): + dtype = type2dtype(typecode, type, dtype, 0) + if sequence is None: + if shape is None: + return None + if dtype is None: + dtype = 'l' + return N.empty(shape, dtype) + if isinstance(sequence, file): + return fromfile(sequence, dtype=dtype, shape=shape) + if isinstance(sequence, str): + return fromstring(sequence, dtype=dtype, shape=shape) + if isinstance(sequence, buffer): + arr = N.frombuffer(sequence, dtype=dtype) + else: + arr = N.array(sequence, dtype, copy=copy) + if shape is not None: + arr.shape = shape + return arr + +def asarray(seq, type=None, typecode=None, dtype=None): + if isinstance(seq, N.ndarray) and type is None and \ + typecode is None and dtype is None: + return seq + return array(seq, type=type, typecode=typecode, copy=0, dtype=dtype) + +inputarray = asarray + + +def getTypeObject(sequence, type): + if type is not None: + return type + try: + return typefrom(N.array(sequence)) + except: + raise TypeError("Can't determine a reasonable type from sequence") + +def getShape(shape, *args): + try: + if shape is () and not args: + return () + if len(args) > 0: + shape = (shape, ) + args + else: + shape = tuple(shape) + dummy = N.array(shape) + if not issubclass(dummy.dtype.type, N.integer): + raise TypeError + if len(dummy) > N.MAXDIMS: + raise TypeError + except: + raise TypeError("Shape must be a sequence of integers") + return shape + + +def identity(n, type=None, typecode=None, dtype=None): + dtype = type2dtype(typecode, type, dtype, True) + return N.identity(n, dtype) + +def info(obj): + print "class: ", type(obj) + print "shape: ", obj.shape + print "strides: ", obj.strides + print "byteoffset: 0" + print "bytestride: ", obj.strides[0] + print "itemsize: ", obj.itemsize + print "aligned: ", obj.flags.isaligned + print "contiguous: ", obj.flags.contiguous + print "buffer: ", obj.data + print "data pointer:", obj._as_paramater_, "(DEBUG ONLY)" + print "byteorder: ", + endian = obj.dtype.byteorder + if endian in ['|','=']: + print sys.byteorder + elif endian == '>': + print "big" + else: + print "little" + print "byteswap: ", not obj.dtype.isnative + print "type: ", typefrom(obj) + +#clipmode is ignored if axis is not 0 and array is not 1d +def put(array, indices, values, axis=0, clipmode=RAISE): + if not isinstance(array, N.ndarray): + raise TypeError("put only works on subclass of ndarray") + work = asarray(array) + if axis == 0: + if array.ndim == 1: + work.put(indices, values, clipmode) + else: + work[indices] = values + elif isinstance(axis, (int, long, N.integer)): + work = work.swapaxes(0, axis) + work[indices] = values + work = work.swapaxes(0, axis) + else: + def_axes = range(work.ndim) + for x in axis: + def_axes.remove(x) + axis = list(axis)+def_axes + work = work.transpose(axis) + work[indices] = values + work = work.transpose(axis) + +def repeat(array, repeats, axis=0): + return N.repeat(array, repeats, axis) + + +def reshape(array, shape, *args): + if len(args) > 0: + shape = (shape,) + args + return N.reshape(array, shape) + + +import warnings as _warnings +def round(*args, **keys): + _warnings.warn("round() is deprecated. Switch to around()", + DeprecationWarning) + return around(*args, **keys) + +def sometrue(array, axis=0): + return N.sometrue(array, axis) + +#clipmode is ignored if axis is not an integer +def take(array, indices, axis=0, outarr=None, clipmode=RAISE): + array = N.asarray(array) + if isinstance(axis, (int, long, N.integer)): + res = array.take(indices, axis, outarr, clipmode) + if outarr is None: + return res + return + else: + def_axes = range(array.ndim) + for x in axis: + def_axes.remove(x) + axis = list(axis) + def_axes + work = array.transpose(axis) + res = work[indices] + if outarr is None: + return res + out[...] = res + return + +def tensormultiply(a1, a2): + a1, a2 = N.asarray(a1), N.asarray(a2) + if (a1.shape[-1] != a2.shape[0]): + raise ValueError("Unmatched dimensions") + shape = a1.shape[:-1] + a2.shape[1:] + return N.reshape(dot(N.reshape(a1, (-1, a1.shape[-1])), + N.reshape(a2, (a2.shape[0],-1))), + shape) + +def cumsum(a1, axis=0, out=None, type=None, dim=0): + return N.asarray(a1).cumsum(axis,dtype=type,out=out) + +def cumproduct(a1, axis=0, out=None, type=None, dim=0): + return N.asarray(a1).cumprod(axis,dtype=type,out=out) + Modified: trunk/numpy/numarray/numerictypes.py =================================================================== --- trunk/numpy/numarray/numerictypes.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/numarray/numerictypes.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -530,7 +530,6 @@ for key,value in _scipy_dtypechar.items(): _scipy_dtypechar_inverse[value] = key - def typefrom(obj): return _scipy_dtypechar_inverse[obj.dtype.char] Added: trunk/numpy/numarray/session.py =================================================================== --- trunk/numpy/numarray/session.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/numarray/session.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -0,0 +1,349 @@ +""" This module contains a "session saver" which saves the state of a +NumPy session to a file. At a later time, a different Python +process can be started and the saved session can be restored using +load(). + +The session saver relies on the Python pickle protocol to save and +restore objects. Objects which are not themselves picklable (e.g. +modules) can sometimes be saved by "proxy", particularly when they +are global constants of some kind. If it's not known that proxying +will work, a warning is issued at save time. If a proxy fails to +reload properly (e.g. because it's not a global constant), a warning +is issued at reload time and that name is bound to a _ProxyFailure +instance which tries to identify what should have been restored. + +First, some unfortunate (probably unnecessary) concessions to doctest +to keep the test run free of warnings. + +>>> del _PROXY_ALLOWED +>>> del copy +>>> del __builtins__ + +By default, save() stores every variable in the caller's namespace: + +>>> import numpy as na +>>> a = na.arange(10) +>>> save() + +Alternately, save() can be passed a comma seperated string of variables: + +>>> save("a,na") + +Alternately, save() can be passed a dictionary, typically one you already +have lying around somewhere rather than created inline as shown here: + +>>> save(dictionary={"a":a,"na":na}) + +If both variables and a dictionary are specified, the variables to be +saved are taken from the dictionary. + +>>> save(variables="a,na",dictionary={"a":a,"na":na}) + +Remove names from the session namespace + +>>> del a, na + +By default, load() restores every variable/object in the session file +to the caller's namespace. + +>>> load() + +load() can be passed a comma seperated string of variables to be +restored from the session file to the caller's namespace: + +>>> load("a,na") + +load() can also be passed a dictionary to *restore to*: + +>>> d = {} +>>> load(dictionary=d) + +load can be passed both a list variables of variables to restore and a +dictionary to restore to: + +>>> load(variables="a,na", dictionary=d) + +>>> na.all(a == na.arange(10)) +1 +>>> na.__name__ +'numpy' + +NOTE: session saving is faked for modules using module proxy objects. +Saved modules are re-imported at load time but any "state" in the module +which is not restored by a simple import is lost. + +""" + +__all__ = ['load', 'save'] + +import copy +import sys +import pickle + +SAVEFILE="session.dat" +VERBOSE = False # global import-time override + +def _foo(): pass + +_PROXY_ALLOWED = (type(sys), # module + type(_foo), # function + type(None)) # None + +def _update_proxy_types(): + """Suppress warnings for known un-picklables with working proxies.""" + pass + +def _unknown(_type): + """returns True iff _type isn't known as OK to proxy""" + return (_type is not None) and (_type not in _PROXY_ALLOWED) + +# caller() from the following article with one extra f_back added. +# from http://www.python.org/search/hypermail/python-1994q1/0506.html +# SUBJECT: import ( how to put a symbol into caller's namespace ) +# SENDER: Steven D. Majewski (sdm7g at elvis.med.virginia.edu) +# DATE: Thu, 24 Mar 1994 15:38:53 -0500 + +def _caller(): + """caller() returns the frame object of the function's caller.""" + try: + 1 + '' # make an error happen + except: # and return the caller's caller's frame + return sys.exc_traceback.tb_frame.f_back.f_back.f_back + +def _callers_globals(): + """callers_globals() returns the global dictionary of the caller.""" + frame = _caller() + return frame.f_globals + +def _callers_modules(): + """returns a list containing the names of all the modules in the caller's + global namespace.""" + g = _callers_globals() + mods = [] + for k,v in g.items(): + if type(v) == type(sys): + mods.append(getattr(v,"__name__")) + return mods + +def _errout(*args): + for a in args: + print >>sys.stderr, a, + print >>sys.stderr + +def _verbose(*args): + if VERBOSE: + _errout(*args) + +class _ProxyingFailure: + """Object which is bound to a variable for a proxy pickle which failed to reload""" + def __init__(self, module, name, type=None): + self.module = module + self.name = name + self.type = type + def __repr__(self): + return "ProxyingFailure('%s','%s','%s')" % (self.module, self.name, self.type) + +class _ModuleProxy(object): + """Proxy object which fakes pickling a module""" + def __new__(_type, name, save=False): + if save: + _verbose("proxying module", name) + self = object.__new__(_type) + self.name = name + else: + _verbose("loading module proxy", name) + try: + self = _loadmodule(name) + except ImportError: + _errout("warning: module", name,"import failed.") + return self + + def __getnewargs__(self): + return (self.name,) + + def __getstate__(self): + return False + +def _loadmodule(module): + if not sys.modules.has_key(module): + modules = module.split(".") + s = "" + for i in range(len(modules)): + s = ".".join(modules[:i+1]) + exec "import " + s + return sys.modules[module] + +class _ObjectProxy(object): + """Proxy object which fakes pickling an arbitrary object. Only global + constants can really be proxied.""" + def __new__(_type, module, name, _type2, save=False): + if save: + if _unknown(_type2): + _errout("warning: proxying object", module + "." + name, + "of type", _type2, "because it wouldn't pickle...", + "it may not reload later.") + else: + _verbose("proxying object", module, name) + self = object.__new__(_type) + self.module, self.name, self.type = module, name, str(_type2) + else: + _verbose("loading object proxy", module, name) + try: + m = _loadmodule(module) + except (ImportError, KeyError): + _errout("warning: loading object proxy", module + "." + name, + "module import failed.") + return _ProxyingFailure(module,name,_type2) + try: + self = getattr(m, name) + except AttributeError: + _errout("warning: object proxy", module + "." + name, + "wouldn't reload from", m) + return _ProxyingFailure(module,name,_type2) + return self + + def __getnewargs__(self): + return (self.module, self.name, self.type) + + def __getstate__(self): + return False + + +class _SaveSession(object): + """Tag object which marks the end of a save session and holds the + saved session variable names as a list of strings in the same + order as the session pickles.""" + def __new__(_type, keys, save=False): + if save: + _verbose("saving session", keys) + else: + _verbose("loading session", keys) + self = object.__new__(_type) + self.keys = keys + return self + + def __getnewargs__(self): + return (self.keys,) + + def __getstate__(self): + return False + +class ObjectNotFound(RuntimeError): + pass + +def _locate(modules, object): + for mname in modules: + m = sys.modules[mname] + if m: + for k,v in m.__dict__.items(): + if v is object: + return m.__name__, k + else: + raise ObjectNotFound(k) + +def save(variables=None, file=SAVEFILE, dictionary=None, verbose=False): + + """saves variables from a numpy session to a file. Variables + which won't pickle are "proxied" if possible. + + 'variables' a string of comma seperated variables: e.g. "a,b,c" + Defaults to dictionary.keys(). + + 'file' a filename or file object for the session file. + + 'dictionary' the dictionary in which to look up the variables. + Defaults to the caller's globals() + + 'verbose' print additional debug output when True. + """ + + global VERBOSE + VERBOSE = verbose + + _update_proxy_types() + + if isinstance(file, str): + file = open(file, "wb") + + if dictionary is None: + dictionary = _callers_globals() + + if variables is None: + keys = dictionary.keys() + else: + keys = variables.split(",") + + source_modules = _callers_modules() + sys.modules.keys() + + p = pickle.Pickler(file, protocol=2) + + _verbose("variables:",keys) + for k in keys: + v = dictionary[k] + _verbose("saving", k, type(v)) + try: # Try to write an ordinary pickle + p.dump(v) + _verbose("pickled", k) + except (pickle.PicklingError, TypeError, SystemError): + # Use proxies for stuff that won't pickle + if isinstance(v, type(sys)): # module + proxy = _ModuleProxy(v.__name__, save=True) + else: + try: + module, name = _locate(source_modules, v) + except ObjectNotFound: + _errout("warning: couldn't find object",k, + "in any module... skipping.") + continue + else: + proxy = _ObjectProxy(module, name, type(v), save=True) + p.dump(proxy) + o = _SaveSession(keys, save=True) + p.dump(o) + file.close() + +def load(variables=None, file=SAVEFILE, dictionary=None, verbose=False): + + """load a numpy session from a file and store the specified + 'variables' into 'dictionary'. + + 'variables' a string of comma seperated variables: e.g. "a,b,c" + Defaults to dictionary.keys(). + + 'file' a filename or file object for the session file. + + 'dictionary' the dictionary in which to look up the variables. + Defaults to the caller's globals() + + 'verbose' print additional debug output when True. + """ + + global VERBOSE + VERBOSE = verbose + + if isinstance(file, str): + file = open(file, "rb") + if dictionary is None: + dictionary = _callers_globals() + values = [] + p = pickle.Unpickler(file) + while 1: + o = p.load() + if isinstance(o, _SaveSession): + session = dict(zip(o.keys, values)) + _verbose("updating dictionary with session variables.") + if variables is None: + keys = session.keys() + else: + keys = variables.split(",") + for k in keys: + dictionary[k] = session[k] + return None + else: + _verbose("unpickled object", str(o)) + values.append(o) + +def test(): + import doctest, numpy.numarray.session + return doctest.testmod(numpy.numarray.session) + Modified: trunk/numpy/numarray/ufuncs.py =================================================================== --- trunk/numpy/numarray/ufuncs.py 2006-08-10 00:24:48 UTC (rev 2981) +++ trunk/numpy/numarray/ufuncs.py 2006-08-10 11:55:33 UTC (rev 2982) @@ -8,7 +8,8 @@ 'logical_or', 'logical_xor', 'lshift', 'maximum', 'minimum', 'minus', 'multiply', 'negative', 'not_equal', 'power', 'product', 'remainder', 'rshift', 'sin', 'sinh', 'sqrt', - 'subtract', 'sum', 'tan', 'tanh', 'true_divide'] + 'subtract', 'sum', 'tan', 'tanh', 'true_divide', + 'conjugate', 'sign'] from numpy import absolute as abs, absolute, add, arccos, arccosh, arcsin, \ arcsinh, arctan, arctan2, arctanh, bitwise_and, invert as bitwise_not, \ @@ -18,4 +19,4 @@ logical_not, logical_or, logical_xor, left_shift as lshift, \ maximum, minimum, negative as minus, multiply, negative, \ not_equal, power, product, remainder, right_shift as rshift, sin, \ - sinh, sqrt, subtract, sum, tan, tanh, true_divide + sinh, sqrt, subtract, sum, tan, tanh, true_divide, conjugate, sign From numpy-svn at scipy.org Thu Aug 10 08:48:11 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 07:48:11 -0500 (CDT) Subject: [Numpy-svn] r2983 - in trunk/numpy: core core/blasdot core/include/numpy core/src numarray oldnumeric Message-ID: <20060810124811.B5BCE39C074@new.scipy.org> Author: oliphant Date: 2006-08-10 07:48:04 -0500 (Thu, 10 Aug 2006) New Revision: 2983 Modified: trunk/numpy/core/blasdot/_dotblas.c trunk/numpy/core/defmatrix.py trunk/numpy/core/fromnumeric.py trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/src/arraymethods.c trunk/numpy/core/src/multiarraymodule.c trunk/numpy/numarray/functions.py trunk/numpy/oldnumeric/functions.py trunk/numpy/oldnumeric/misc.py Log: Add output arguments to a few more functions for consistency Modified: trunk/numpy/core/blasdot/_dotblas.c =================================================================== --- trunk/numpy/core/blasdot/_dotblas.c 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/core/blasdot/_dotblas.c 2006-08-10 12:48:04 UTC (rev 2983) @@ -1005,7 +1005,7 @@ Py_DECREF(tmp2); } if (PyTypeNum_ISCOMPLEX(typenum)) { - op1 = PyArray_Conjugate(ap1); + op1 = PyArray_Conjugate(ap1, NULL); if (op1==NULL) goto fail; Py_DECREF(ap1); ap1 = (PyArrayObject *)op1; Modified: trunk/numpy/core/defmatrix.py =================================================================== --- trunk/numpy/core/defmatrix.py 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/core/defmatrix.py 2006-08-10 12:48:04 UTC (rev 2983) @@ -262,14 +262,14 @@ def max(self, axis=None, out=None): return N.ndarray.max(self, axis, out)._align(axis) - def argmax(self, axis=None): - return N.ndarray.argmax(self, axis)._align(axis) + def argmax(self, axis=None, out=None): + return N.ndarray.argmax(self, axis, out)._align(axis) def min(self, axis=None, out=None): return N.ndarray.min(self, axis, out)._align(axis) - def argmin(self, axis=None): - return N.ndarray.argmin(self, axis)._align(axis) + def argmin(self, axis=None, out=None): + return N.ndarray.argmin(self, axis, out)._align(axis) def ptp(self, axis=None, out=None): return N.ndarray.ptp(self, axis, out)._align(axis) Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/core/fromnumeric.py 2006-08-10 12:48:04 UTC (rev 2983) @@ -141,8 +141,8 @@ return _wrapit(a, 'argsort', axis, kind) return argsort(axis, kind) -def argmax(a, axis=-1): - """argmax(a,axis=-1) returns the indices to the maximum value of the +def argmax(a, axis=None): + """argmax(a,axis=None) returns the indices to the maximum value of the 1-D arrays along the given axis. """ try: @@ -151,8 +151,8 @@ return _wrapit(a, 'argmax', axis) return argmax(axis) -def argmin(a, axis=-1): - """argmin(a,axis=-1) returns the indices to the minimum value of the +def argmin(a, axis=None): + """argmin(a,axis=None) returns the indices to the minimum value of the 1-D arrays along the given axis. """ try: @@ -250,8 +250,8 @@ result = asarray(a).shape return result -def compress(condition, m, axis=-1, out=None): - """compress(condition, x, axis=-1) = those elements of x corresponding +def compress(condition, m, axis=None, out=None): + """compress(condition, x, axis=None) = those elements of x corresponding to those elements of condition that are "true". condition must be the same size as the given dimension of x.""" try: Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-10 12:48:04 UTC (rev 2983) @@ -37,7 +37,7 @@ #define NPY_SUCCEED 1 /* Helpful to distinguish what is installed */ -#define NPY_VERSION 0x01000001 +#define NPY_VERSION 0x01000002 /* Some platforms don't define bool, long long, or long double. Handle that here. Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/core/src/arraymethods.c 2006-08-10 12:48:04 UTC (rev 2983) @@ -156,36 +156,42 @@ return PyArray_View(self, type, NULL); } -static char doc_argmax[] = "a.argmax(axis=None)"; +static char doc_argmax[] = "a.argmax(axis=None, out=None)"; static PyObject * array_argmax(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - static char *kwlist[] = {"axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, - &axis)) + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return _ARET(PyArray_ArgMax(self, axis)); + return _ARET(PyArray_ArgMax(self, axis, out)); } -static char doc_argmin[] = "a.argmin(axis=None)"; +static char doc_argmin[] = "a.argmin(axis=None, out=None)"; static PyObject * array_argmin(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - static char *kwlist[] = {"axis", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"axis", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, - &axis)) + &axis, + PyArray_OutputConverter, + &out)) return NULL; - return _ARET(PyArray_ArgMin(self, axis)); + return _ARET(PyArray_ArgMin(self, axis, out)); } static char doc_max[] = "a.max(axis=None)"; @@ -1550,19 +1556,22 @@ #undef _CHKTYPENUM -static char doc_clip[] = "a.clip(min=, max=)"; +static char doc_clip[] = "a.clip(min=, max=, out=None)"; static PyObject * array_clip(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *min, *max; - static char *kwlist[] = {"min", "max", NULL}; + PyArrayObject *out=NULL; + static char *kwlist[] = {"min", "max", "out", NULL}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, - &min, &max)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist, + &min, &max, + PyArray_OutputConverter, + &out)) return NULL; - return _ARET(PyArray_Clip(self, min, max)); + return _ARET(PyArray_Clip(self, min, max, out)); } static char doc_conj[] = "a.conj()"; @@ -1573,9 +1582,12 @@ array_conjugate(PyArrayObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, "")) return NULL; + PyArrayObject *out=NULL; + if (!PyArg_ParseTuple(args, "|O&", + PyArray_OutputConverter, + &out)) return NULL; - return PyArray_Conjugate(self); + return PyArray_Conjugate(self, out); } Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-10 12:48:04 UTC (rev 2983) @@ -216,11 +216,9 @@ PyArray_Round(PyArrayObject *a, int decimals, PyArrayObject *out) { PyObject *f, *ret=NULL, *tmp, *op1, *op2; - if (out && (!PyArray_SAMESHAPE(out, a) || - !PyArray_EquivTypes(a->descr, out->descr))) { + if (out && (PyArray_SIZE(out) != PyArray_SIZE(a))) { PyErr_SetString(PyExc_ValueError, - "output array must have the same shape" - "and type"); + "invalid output shape"); return NULL; } if (PyArray_ISCOMPLEX(a)) { @@ -266,7 +264,7 @@ if (decimals >= 0) { if (PyArray_ISINTEGER(a)) { if (out) { - if (PyArray_CopyInto(out, a) < 0) return NULL; + if (PyArray_CopyAnyInto(out, a) < 0) return NULL; Py_INCREF(out); return (PyObject *)out; } @@ -897,7 +895,7 @@ Clip */ static PyObject * -PyArray_Clip(PyArrayObject *self, PyObject *min, PyObject *max) +PyArray_Clip(PyArrayObject *self, PyObject *min, PyObject *max, PyArrayObject *out) { PyObject *selector=NULL, *newtup=NULL, *ret=NULL; PyObject *res1=NULL, *res2=NULL, *res3=NULL; @@ -924,7 +922,7 @@ newtup = Py_BuildValue("(OOO)", (PyObject *)self, min, max); if (newtup == NULL) {Py_DECREF(selector); return NULL;} - ret = PyArray_Choose((PyAO *)selector, newtup, NULL, NPY_RAISE); + ret = PyArray_Choose((PyAO *)selector, newtup, out, NPY_RAISE); Py_DECREF(selector); Py_DECREF(newtup); return ret; @@ -934,14 +932,14 @@ Conjugate */ static PyObject * -PyArray_Conjugate(PyArrayObject *self) +PyArray_Conjugate(PyArrayObject *self, PyArrayObject *out) { if (PyArray_ISCOMPLEX(self)) { PyObject *new; intp size, i; /* Make a copy */ - new = PyArray_NewCopy(self, -1); - if (new==NULL) return NULL; + new = PyArray_NewCopy(self, -1); + if (new==NULL) return NULL; size = PyArray_SIZE(new); if (self->descr->type_num == PyArray_CFLOAT) { cfloat *dptr = (cfloat *) PyArray_DATA(new); @@ -964,11 +962,25 @@ dptr++; } } + if (out) { + if (PyArray_CopyAnyInto(out, (PyArrayObject *)new)<0) + return NULL; + Py_INCREF(out); + Py_DECREF(new); + return (PyObject *)out; + } return new; } else { - Py_INCREF(self); - return (PyObject *) self; + PyArrayObject *ret; + if (out) { + if (PyArray_CopyAnyInto(out, self)< 0) + return NULL; + ret = out; + } + else ret = self; + Py_INCREF(ret); + return (PyObject *)ret; } } @@ -1836,7 +1848,7 @@ PyArrayObject *obj; int flags = NPY_CARRAY | NPY_UPDATEIFCOPY; - if (!PyArray_SAMESHAPE(ap, ret)) { + if (PyArray_SIZE(ret) != PyArray_SIZE(ap)) { PyErr_SetString(PyExc_TypeError, "invalid shape for output array."); ret = NULL; @@ -3018,7 +3030,7 @@ ArgMin */ static PyObject * -PyArray_ArgMin(PyArrayObject *ap, int axis) +PyArray_ArgMin(PyArrayObject *ap, int axis, PyArrayObject *out) { PyObject *obj, *new, *ret; @@ -3039,7 +3051,7 @@ new = PyArray_EnsureAnyArray(PyNumber_Subtract(obj, (PyObject *)ap)); Py_DECREF(obj); if (new == NULL) return NULL; - ret = PyArray_ArgMax((PyArrayObject *)new, axis); + ret = PyArray_ArgMax((PyArrayObject *)new, axis, out); Py_DECREF(new); return ret; } @@ -3117,7 +3129,7 @@ ArgMax */ static PyObject * -PyArray_ArgMax(PyArrayObject *op, int axis) +PyArray_ArgMax(PyArrayObject *op, int axis, PyArrayObject *out) { PyArrayObject *ap=NULL, *rp=NULL; PyArray_ArgFunc* arg_func; @@ -3125,6 +3137,7 @@ intp *rptr; intp i, n, m; int elsize; + int copyret=0; NPY_BEGIN_THREADS_DEF @@ -3163,13 +3176,6 @@ goto fail; } - 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; - - elsize = ap->descr->elsize; m = ap->dimensions[ap->nd-1]; if (m == 0) { @@ -3178,6 +3184,28 @@ "of an empty sequence??"); goto fail; } + + if (!out) { + rp = (PyArrayObject *)PyArray_New(ap->ob_type, ap->nd-1, + ap->dimensions, PyArray_INTP, + NULL, NULL, 0, 0, + (PyObject *)ap); + if (rp == NULL) goto fail; + } + else { + if (PyArray_SIZE(out) != \ + PyArray_MultiplyList(ap->dimensions, ap->nd-1)) { + PyErr_SetString(PyExc_TypeError, + "invalid shape for output array."); + } + rp = (PyArrayObject *)\ + PyArray_FromArray(out, + PyArray_DescrFromType(PyArray_INTP), + NPY_CARRAY | NPY_UPDATEIFCOPY); + if (rp == NULL) goto fail; + if (rp != out) copyret = 1; + } + NPY_BEGIN_THREADS_DESCR(ap->descr) n = PyArray_SIZE(ap)/m; rptr = (intp *)rp->data; @@ -3188,6 +3216,13 @@ 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: Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/numarray/functions.py 2006-08-10 12:48:04 UTC (rev 2983) @@ -40,7 +40,7 @@ import os, sys, math, operator from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\ - allclose, any, argmax, argmin, around, argsort, array_equal, array_equiv,\ + allclose, any, around, argsort, array_equal, array_equiv,\ array_str, array_repr, average, CLIP, RAISE, WRAP, clip, concatenate, \ diagonal, e, pi, fromfunction, indices, inner as innerproduct, nonzero, \ outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \ @@ -438,3 +438,9 @@ def cumproduct(a1, axis=0, out=None, type=None, dim=0): return N.asarray(a1).cumprod(axis,dtype=type,out=out) +def argmax(x, axis=-1): + return N.argmax(x, axis) + +def argmin(x, axis=-1): + return N.argmin(x, axis) + Modified: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/oldnumeric/functions.py 2006-08-10 12:48:04 UTC (rev 2983) @@ -6,10 +6,10 @@ from typeconv import convtypecode, convtypecode2 __all__ = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', - 'cumsum', 'cumproduct', + 'cumsum', 'cumproduct', 'compress', 'ones', 'empty', 'identity', 'zeros', 'array', 'asarray', 'nonzero', 'reshape', 'arange', 'fromstring', 'ravel', 'trace', - 'indices', 'where','sarray','cross_product'] + 'indices', 'where','sarray','cross_product', 'argmax', 'argmin'] def take(a, indicies, axis=0): return N.take(a, indicies, axis) @@ -34,6 +34,15 @@ def cumproduct(x, axis=0): return N.cumproduct(x, axis) + +def argmax(x, axis=-1): + return N.argmax(x, axis) + +def argmin(x, axis=-1): + return N.argmax(x, axis) + +def compress(condition, m, axis=-1): + return N.compress(condition, m, axis) def ones(shape, typecode='l', savespace=0, dtype=None): """ones(shape, dtype=int) returns an array of the given Modified: trunk/numpy/oldnumeric/misc.py =================================================================== --- trunk/numpy/oldnumeric/misc.py 2006-08-10 11:55:33 UTC (rev 2982) +++ trunk/numpy/oldnumeric/misc.py 2006-08-10 12:48:04 UTC (rev 2983) @@ -3,11 +3,11 @@ __all__ = ['load', 'sort', 'copy_reg', 'clip', 'putmask', 'Unpickler', 'rank', 'sign', 'shape', 'types', 'allclose', 'size', - 'argmax', 'choose', 'swapaxes', 'array_str', - 'pi', 'math', 'compress', 'concatenate', + 'choose', 'swapaxes', 'array_str', + 'pi', 'math', 'concatenate', 'around', 'vdot', 'transpose', 'array2string', 'diagonal', 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', - 'array_repr', 'e', 'argmin', 'StringIO', 'pickle', 'average', + 'array_repr', 'e', 'StringIO', 'pickle', 'average', 'argsort', 'convolve', 'loads', 'cross_correlate', 'Pickler', 'dot', 'outerproduct', 'innerproduct'] @@ -20,8 +20,8 @@ from pickle import load, loads from numpy import sort, clip, putmask, rank, sign, shape, allclose, size,\ - argmax, choose, swapaxes, array_str, array_repr, argmin, e, pi, \ - fromfunction, resize, around, compress, concatenate, vdot, transpose, \ + choose, swapaxes, array_str, array_repr, e, pi, \ + fromfunction, resize, around, concatenate, vdot, transpose, \ diagonal, searchsorted, put, average, argsort, convolve, dot, \ outer as outerproduct, inner as innerproduct, correlate as cross_correlate From numpy-svn at scipy.org Thu Aug 10 09:03:59 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 08:03:59 -0500 (CDT) Subject: [Numpy-svn] r2984 - in trunk/numpy/core: code_generators include/numpy src Message-ID: <20060810130359.96FCB39C074@new.scipy.org> Author: oliphant Date: 2006-08-10 08:03:55 -0500 (Thu, 10 Aug 2006) New Revision: 2984 Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/src/arraymethods.c trunk/numpy/core/src/multiarraymodule.c Log: Change name of function -- no re-compile necessary. Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt =================================================================== --- trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-10 12:48:04 UTC (rev 2983) +++ trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-10 13:03:55 UTC (rev 2984) @@ -1,6 +1,6 @@ PyArray_Transpose -PyArray_TakeOut -PyArray_PutIn +PyArray_TakeFrom +PyArray_PutTo PyArray_PutMask PyArray_Repeat PyArray_Choose Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-10 12:48:04 UTC (rev 2983) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-10 13:03:55 UTC (rev 2984) @@ -1533,10 +1533,10 @@ PyArray_CastToType(mp, PyArray_DescrFromType(type_num), 0) #define PyArray_Take(ap, items, axis) \ - PyArray_TakeOut(ap, items, axis, NULL, NPY_RAISE) + PyArray_TakeFrom(ap, items, axis, NULL, NPY_RAISE) #define PyArray_Put(ap, items, values) \ - PyArray_PutIn(ap, items, values, NPY_RAISE) + PyArray_PutTo(ap, items, values, NPY_RAISE) /* Compatibility with old Numeric stuff -- don't use in new code */ Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-10 12:48:04 UTC (rev 2983) +++ trunk/numpy/core/src/arraymethods.c 2006-08-10 13:03:55 UTC (rev 2984) @@ -24,7 +24,7 @@ &mode)) return NULL; - return _ARET(PyArray_TakeOut(self, indices, dimension, out, mode)); + return _ARET(PyArray_TakeFrom(self, indices, dimension, out, mode)); } static char doc_fill[] = "a.fill(value) places the scalar value at every "\ @@ -57,7 +57,7 @@ PyArray_ClipmodeConverter, &mode)) return NULL; - return PyArray_PutIn(self, values, indices, mode); + return PyArray_PutTo(self, values, indices, mode); } static char doc_putmask[] = "a.putmask(values, mask) sets a.flat[n] = v[n] "\ Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-10 12:48:04 UTC (rev 2983) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-10 13:03:55 UTC (rev 2984) @@ -826,7 +826,8 @@ res = PyArray_Nonzero(cond); Py_DECREF(cond); if (res == NULL) return res; - ret = PyArray_Take(self, PyTuple_GET_ITEM(res, 0), axis); + ret = PyArray_TakeFrom(self, PyTuple_GET_ITEM(res, 0), axis, + out, NPY_RAISE); Py_DECREF(res); return ret; } @@ -3236,8 +3237,8 @@ Take */ static PyObject * -PyArray_TakeOut(PyArrayObject *self0, PyObject *indices0, int axis, - PyArrayObject *ret, NPY_CLIPMODE clipmode) +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; @@ -3385,7 +3386,7 @@ Put values into an array */ static PyObject * -PyArray_PutIn(PyArrayObject *self, PyObject* values0, PyObject *indices0, +PyArray_PutTo(PyArrayObject *self, PyObject* values0, PyObject *indices0, NPY_CLIPMODE clipmode) { PyArrayObject *indices, *values; From numpy-svn at scipy.org Thu Aug 10 09:33:48 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 08:33:48 -0500 (CDT) Subject: [Numpy-svn] r2985 - in trunk/numpy: core lib Message-ID: <20060810133348.9BB2E39C014@new.scipy.org> Author: oliphant Date: 2006-08-10 08:33:45 -0500 (Thu, 10 Aug 2006) New Revision: 2985 Modified: trunk/numpy/core/fromnumeric.py trunk/numpy/core/ma.py trunk/numpy/lib/utils.py Log: More fixes to masked array support of output arrays. Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-10 13:03:55 UTC (rev 2984) +++ trunk/numpy/core/fromnumeric.py 2006-08-10 13:33:45 UTC (rev 2985) @@ -374,19 +374,19 @@ """Return the maximum of 'a' along dimension axis. """ try: - max = a.max + amax = a.max except AttributeError: return _wrapit(a, 'max', axis, out) - return max(axis, out) + return amax(axis, out) def amin(a, axis=None, out=None): """Return the minimum of a along dimension axis. """ try: - min = a.min + amin = a.min except AttributeError: return _wrapit(a, 'min', axis, out) - return min(axis, out) + return amin(axis, out) def alen(a): """Return the length of a Python object interpreted as an array Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-10 13:03:55 UTC (rev 2984) +++ trunk/numpy/core/ma.py 2006-08-10 13:33:45 UTC (rev 2985) @@ -1728,7 +1728,7 @@ m = make_mask(mask_or(m, md), copy=0, flag=1) return masked_array(d, m) -def choose (indices, t): +def choose (indices, t, out=None, mode='raise'): "Returns array shaped like indices with elements chosen from t" def fmask (x): if x is masked: return 1 @@ -1856,7 +1856,7 @@ mask=numeric.swapaxes(m, axis1, axis2),) -def take (a, indices, axis=0): +def take (a, indices, axis=0, out=None, mode='raise'): "returns selection of items from a." m = getmask(a) # d = masked_array(a).raw_data() @@ -1878,7 +1878,7 @@ mask = numeric.transpose(m, axes)) -def put(a, indices, values): +def put(a, indices, values, mode='raise'): """sets storage-indexed locations to corresponding values. Values and indices are filled if necessary. @@ -1940,15 +1940,15 @@ """ return innerproduct(filled(a, 0), numeric.swapaxes(filled(b, 0), -1, -2)) -def compress(condition, x, dimension=-1): +def compress(condition, x, dimension=-1, out=None): """Select those parts of x for which condition is true. Masked values in condition are considered false. """ c = filled(condition, 0) m = getmask(x) if m is not nomask: - m = numeric.compress(c, m, dimension) - d = numeric.compress(c, filled(x), dimension) + m = numeric.compress(c, m, dimension, out) + d = numeric.compress(c, filled(x), dimension, m) return masked_array(d, m) class _minimum_operation: @@ -2077,13 +2077,13 @@ else: return masked_array(d, fromnumeric.diagonal(m, k, axis1, axis2)) -def trace (a, offset=0, axis1=0, axis2=1, dtype=None): +def trace (a, offset=0, axis1=0, axis2=1, dtype=None, out=None): """trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals (defined by the last two dimenions) of the array. """ - return diagonal(a, offset, axis1, axis2).sum(dtype=dtype) + return diagonal(a, offset, axis1, axis2).sum(dtype=dtype, out=out) -def argsort (x, axis = -1, fill_value=None): +def argsort (x, axis = -1, out=None, fill_value=None): """Treating masked values as if they have the value fill_value, return sort indices for sorting along given axis. if fill_value is None, use get_fill_value(x) @@ -2092,7 +2092,7 @@ d = filled(x, fill_value) return fromnumeric.argsort(d, axis) -def argmin (x, axis = -1, fill_value=None): +def argmin (x, axis = -1, out=None, fill_value=None): """Treating masked values as if they have the value fill_value, return indices for minimum values along given axis. if fill_value is None, use get_fill_value(x). @@ -2102,7 +2102,7 @@ d = filled(x, fill_value) return fromnumeric.argmin(d, axis) -def argmax (x, axis = -1, fill_value=None): +def argmax (x, axis = -1, out=None, fill_value=None): """Treating masked values as if they have the value fill_value, return sort indices for maximum along given axis. if fill_value is None, use -get_fill_value(x) if it exists. @@ -2158,7 +2158,7 @@ mask_or(getmask(a_min),getmask(a_max)))) array.clip = _m(_clip) -def _compress(self, cond, axis=None): +def _compress(self, cond, axis=None, out=None): return compress(cond, self, axis) array.compress = _m(_compress) del _compress @@ -2166,14 +2166,14 @@ array.conj = array.conjugate = _m(conjugate) array.copy = _m(not_implemented) -def _cumprod(self, axis=0, dtype=None): +def _cumprod(self, axis=0, dtype=None, out=None): m = self.mask if m is not nomask: m = umath.logical_or.accumulate(self.mask, axis) return MaskedArray(data = self.filled(1).cumprod(axis, dtype), mask=m) array.cumprod = _m(_cumprod) -def _cumsum(self, axis=0, dtype=None): +def _cumsum(self, axis=0, dtype=None, out=None): m = self.mask if m is not nomask: m = umath.logical_or.accumulate(self.mask, axis) @@ -2188,14 +2188,18 @@ array.flatten = _m(ravel) array.getfield = _m(not_implemented) -def _max(a, axis=None): +def _max(a, axis=None, out=None): + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") if axis is None: return maximum(a) else: return maximum.reduce(a, axis) array.max = _m(_max) del _max -def _min(a, axis=None): +def _min(a, axis=None, out=None): + if out is not None: + raise TypeError("Output arrays Unsupported for masked arrays") if axis is None: return minimum(a) else: @@ -2208,8 +2212,8 @@ array.nonzero = _m(nonzero) array.prod = _m(product) -def _ptp(a,axis=0): - return a.max(axis)-a.min(axis) +def _ptp(a,axis=0,out=None): + return a.max(axis,out)-a.min(axis) array.ptp = _m(_ptp) array.repeat = _m(repeat) array.resize = _m(resize) @@ -2238,7 +2242,7 @@ array.trace = _m(trace) array.transpose = _m(transpose) -def _var(self,axis=0,dtype=None): +def _var(self,axis=0,dtype=None, out=None): if axis is None: return asarray(self.compressed()).var() a = self.swapaxes(axis,0) @@ -2246,7 +2250,7 @@ a *= a a /= a.count(axis=0) return a.swapaxes(0,axis).sum(axis) -def _std(self,axis=0,dtype=None): +def _std(self,axis=0,dtype=None, out=None): return (self.var(axis,dtype))**0.5 array.var = _m(_var) array.std = _m(_std) Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-10 13:03:55 UTC (rev 2984) +++ trunk/numpy/lib/utils.py 2006-08-10 13:33:45 UTC (rev 2985) @@ -1,7 +1,6 @@ import sys, os import inspect import types -import pydoc from numpy.core.numerictypes import obj2sctype from numpy.core.multiarray import dtype from numpy.core import product, ndarray @@ -243,6 +242,7 @@ p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] """ global _namedict, _dictlist + import pydoc if hasattr(object,'_ppimport_importer') or \ hasattr(object, '_ppimport_module'): From numpy-svn at scipy.org Thu Aug 10 09:37:45 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 08:37:45 -0500 (CDT) Subject: [Numpy-svn] r2986 - trunk/numpy/core Message-ID: <20060810133745.99D0C39C014@new.scipy.org> Author: oliphant Date: 2006-08-10 08:37:43 -0500 (Thu, 10 Aug 2006) New Revision: 2986 Modified: trunk/numpy/core/ma.py Log: Don't use masked output values for output array Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-10 13:33:45 UTC (rev 2985) +++ trunk/numpy/core/ma.py 2006-08-10 13:37:43 UTC (rev 2986) @@ -1947,8 +1947,8 @@ c = filled(condition, 0) m = getmask(x) if m is not nomask: - m = numeric.compress(c, m, dimension, out) - d = numeric.compress(c, filled(x), dimension, m) + m = numeric.compress(c, m, dimension) + d = numeric.compress(c, filled(x), dimension) return masked_array(d, m) class _minimum_operation: @@ -2081,7 +2081,7 @@ """trace(a,offset=0, axis1=0, axis2=1) returns the sum along diagonals (defined by the last two dimenions) of the array. """ - return diagonal(a, offset, axis1, axis2).sum(dtype=dtype, out=out) + return diagonal(a, offset, axis1, axis2).sum(dtype=dtype) def argsort (x, axis = -1, out=None, fill_value=None): """Treating masked values as if they have the value fill_value, From numpy-svn at scipy.org Thu Aug 10 14:51:27 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 13:51:27 -0500 (CDT) Subject: [Numpy-svn] r2987 - trunk/numpy/core Message-ID: <20060810185127.CB7B739C012@new.scipy.org> Author: oliphant Date: 2006-08-10 13:51:25 -0500 (Thu, 10 Aug 2006) New Revision: 2987 Modified: trunk/numpy/core/ma.py Log: fix more argument lists for ma.py --- output arrays are ignored for masked arrays Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-10 13:37:43 UTC (rev 2986) +++ trunk/numpy/core/ma.py 2006-08-10 18:51:25 UTC (rev 2987) @@ -620,12 +620,14 @@ else: return self._data - def __array_wrap__ (self, array, context): + def __array_wrap__ (self, array, context=None): """Special hook for ufuncs. Wraps the numpy array and sets the mask according to context. """ + if context is None: + return MaskedArray(array, copy=False, mask=nomask) func, args = context[:2] domain = ufunc_domain[func] m = reduce(mask_or, [getmask(a) for a in args]) @@ -2146,12 +2148,12 @@ array.base = property(_m(not_implemented)) array.byteswap = _m(not_implemented) -def _choose(self, *args): +def _choose(self, *args, **kwds): return choose(self, args) array.choose = _m(_choose) del _choose -def _clip(self,a_min,a_max): +def _clip(self,a_min,a_max,out=None): return MaskedArray(data = self.data.clip(asarray(a_min).data, asarray(a_max).data), mask = mask_or(self.mask, From numpy-svn at scipy.org Thu Aug 10 15:38:52 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 14:38:52 -0500 (CDT) Subject: [Numpy-svn] r2988 - trunk/numpy/core/src Message-ID: <20060810193852.7117039C012@new.scipy.org> Author: oliphant Date: 2006-08-10 14:38:46 -0500 (Thu, 10 Aug 2006) New Revision: 2988 Modified: trunk/numpy/core/src/arrayobject.c Log: Fix ticket #239 Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-10 18:51:25 UTC (rev 2987) +++ trunk/numpy/core/src/arrayobject.c 2006-08-10 19:38:46 UTC (rev 2988) @@ -6933,8 +6933,8 @@ else obj = PyTuple_GET_ITEM(s, 0); nd = object_depth_and_dimension(obj, max-1, newdims); for (i=1; i Author: oliphant Date: 2006-08-10 16:07:31 -0500 (Thu, 10 Aug 2006) New Revision: 2989 Modified: trunk/README.txt trunk/numpy/numarray/alter_code1.py trunk/numpy/numarray/alter_code2.py trunk/numpy/numarray/functions.py trunk/numpy/oldnumeric/alter_code1.py trunk/numpy/oldnumeric/alter_code2.py Log: Finished up numpy.numarray.alter_code1 Modified: trunk/README.txt =================================================================== --- trunk/README.txt 2006-08-10 19:38:46 UTC (rev 2988) +++ trunk/README.txt 2006-08-10 21:07:31 UTC (rev 2989) @@ -1,6 +1,6 @@ -NumPy (previously called SciPy core) is a replacement of Numeric Python that -adds the features of numarray. To install: +NumPy is a replacement of Numeric Python that adds the features of numarray. +To install: python setup.py install @@ -9,7 +9,8 @@ If fast BLAS and LAPACK cannot be found, then a slower default version is used. -The current version is always available from a Subversion repostiory: +The most current development version is always available from a +subversion repostiory: http://svn.scipy.org/svn/numpy/trunk Modified: trunk/numpy/numarray/alter_code1.py =================================================================== --- trunk/numpy/numarray/alter_code1.py 2006-08-10 19:38:46 UTC (rev 2988) +++ trunk/numpy/numarray/alter_code1.py 2006-08-10 21:07:31 UTC (rev 2989) @@ -1,14 +1,24 @@ """ -This module converts code written for Numeric to run with numpy +This module converts code written for numarray to run with numpy Makes the following changes: * Changes import statements - Stubs for - numarray.convolve --> numpy.numarray.convolve - numarray.image --> numarray.image - numarray.nd_image --> numarray.nd_image + import numarray.package + --> import numpy.numarray.package as numarray_package + with all numarray.package in code changed to numarray_package + import numarray --> import numpy.numarray as numarray + import numarray.package as --> import numpy.numarray.package as + + from numarray import --> from numpy.numarray import + from numarray.package import + --> from numpy.numarray.package import + + package can be convolve, image, nd_image, mlab, linear_algebra, ma, + matrix, fft, random_array + + * Makes search and replace changes to: - .imaginary --> .imag - .flat --> .ravel() (most of the time) @@ -24,14 +34,13 @@ - .is_f_array() --> .dtype.isnative and .flags.farray - .itemsize() --> .itemsize - .nelements() --> .size - - self.new(None) --> emtpy_like(self) - - self.new(type) --> empty(self.shape, type) + - self.new(type) --> numarray.newobj(self, type) - .repeat(r) --> .repeat(r, axis=0) - .size() --> .size - - .type() -- numarray.typefrom(self) + - self.type() -- numarray.typefrom(self) - .typecode() --> .dtype.char - .stddev() --> .std() - - .togglebyteorder() --> self.dtype=self.dtype.newbyteorder() + - .togglebyteorder() --> numarray.togglebyteorder(self) - .getshape() --> .shape - .setshape(obj) --> .shape=obj - .getflat() --> .ravel() @@ -43,52 +52,29 @@ - .setimaginary() --> .imag """ -__all__ = ['fromfile', 'fromstr'] +__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] import sys import os import re import glob -import warnings -warnings.warn("numarray.alter_code1 is not working yet") - -_func4 = ['eye', 'tri'] -_meth1 = ['astype'] -_func2 = ['ones', 'zeros', 'identity', 'fromstring', 'indices', - 'empty', 'array', 'asarray', 'arange', 'array_constructor'] - -func_re = {} - -for name in _func2: - _astr = r"""(%s\s*[(][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name - func_re[name] = re.compile(_astr, re.DOTALL) - -for name in _func4: - _astr = r"""(%s\s*[(][^,]*?[,][^,]*?[,][^,]*?[,][^'"]*?['"])b(['"][^)]*?[)])"""%name - func_re[name] = re.compile(_astr, re.DOTALL) - -for name in _meth1: - _astr = r"""(.%s\s*[(][^'"]*?['"])b(['"][^)]*?[)])"""%name - func_re[name] = re.compile(_astr, re.DOTALL) - -def fixtypechars(fstr): - for name in _func2 + _func4 + _meth1: - fstr = func2_re[name].sub('\\1B\\2',fstr) - return fstr - -flatindex_re = re.compile('([.]flat(\s*?[[=]))') - def changeimports(fstr, name, newname): importstr = 'import %s' % name importasstr = 'import %s as ' % name fromstr = 'from %s import ' % name fromall=0 + name_ = name + if ('.' in name): + name_ = name.replace('.','_') + fstr = fstr.replace(importasstr, 'import %s as ' % newname) - fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name)) + fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name_)) + if (name_ != name): + fstr = fstr.replace(name, name_) ind = 0 Nlen = len(fromstr) @@ -104,12 +90,36 @@ ind += Nlen2 - Nlen return fstr, fromall +flatindex_re = re.compile('([.]flat(\s*?[[=]))') + + +def addimport(astr): + # find the first line with import on it + ind = astr.find('import') + start = astr.rfind(os.linesep, 0, ind) + astr = "%s%s%s%s" % (astr[:start], os.linesep, + "import numpy.numarray as numarray", + astr[start:]) + return astr + def replaceattr(astr): - astr = astr.replace(".typecode()",".dtype.char") + astr = astr.replace(".imaginary", ".imag") + astr = astr.replace(".byteswapped()",".byteswap(False)") + astr = astr.replace(".byteswap()", ".byteswap(True)") + astr = astr.replace(".isaligned()", ".flags.aligned") astr = astr.replace(".iscontiguous()",".flags.contiguous") - astr = astr.replace(".byteswapped()",".byteswap()") - astr = astr.replace(".toscalar()", ".item()") + astr = astr.replace(".is_fortran_contiguous()",".flags.fortran") astr = astr.replace(".itemsize()",".itemsize") + astr = astr.replace(".size()",".size") + astr = astr.replace(".nelements()",".size") + astr = astr.replace(".typecode()",".dtype.char") + astr = astr.replace(".stddev()",".std()") + astr = astr.replace(".getshape()", ".shape") + astr = astr.replace(".getflat()", ".ravel()") + astr = astr.replace(".getreal", ".real") + astr = astr.replace(".getimag", ".imag") + astr = astr.replace(".getimaginary", ".imag") + # preserve uses of flat that should be o.k. tmpstr = flatindex_re.sub(r"@@@@\2",astr) # replace other uses of flat @@ -118,41 +128,59 @@ astr = tmpstr.replace("@@@@", ".flat") return astr -svspc2 = re.compile(r'([^,(\s]+[.]spacesaver[(][)])') -svspc3 = re.compile(r'(\S+[.]savespace[(].*[)])') -#shpe = re.compile(r'(\S+\s*)[.]shape\s*=[^=]\s*(.+)') +info_re = re.compile(r'(\S+)\s*[.]\s*info\s*[(]\s*[)]') +new_re = re.compile(r'(\S+)\s*[.]\s*new\s*[(]\s*(\S+)\s*[)]') +toggle_re = re.compile(r'(\S+)\s*[.]\s*togglebyteorder\s*[(]\s*[)]') +type_re = re.compile(r'(\S+)\s*[.]\s*type\s*[(]\s*[)]') + +isbyte_re = re.compile(r'(\S+)\s*[.]\s*isbyteswapped\s*[(]\s*[)]') +iscarr_re = re.compile(r'(\S+)\s*[.]\s*is_c_array\s*[(]\s*[)]') +isfarr_re = re.compile(r'(\S+)\s*[.]\s*is_f_array\s*[(]\s*[)]') +repeat_re = re.compile(r'(\S+)\s*[.]\s*repeat\s*[(]\s*(\S+)\s*[)]') + +setshape_re = re.compile(r'(\S+)\s*[.]\s*setshape\s*[(]\s*(\S+)\s*[)]') +setreal_re = re.compile(r'(\S+)\s*[.]\s*setreal\s*[(]\s*(\S+)\s*[)]') +setimag_re = re.compile(r'(\S+)\s*[.]\s*setimag\s*[(]\s*(\S+)\s*[)]') +setimaginary_re = re.compile(r'(\S+)\s*[.]\s*setimaginary\s*[(]\s*(\S+)\s*[)]') def replaceother(astr): - astr = svspc2.sub('True',astr) - astr = svspc3.sub(r'pass ## \1', astr) - #astr = shpe.sub('\\1=\\1.reshape(\\2)', astr) + # self.info() --> numarray.info(self) + # self.new(type) --> numarray.newobj(self, type) + # self.togglebyteorder() --> numarray.togglebyteorder(self) + # self.type() --> numarray.typefrom(self) + (astr, n1) = info_re.subn('numarray.info(\\1)', astr) + (astr, n2) = new_re.subn('numarray.newobj(\\1, \\2)', astr) + (astr, n3) = toggle_re.subn('numarray.togglebyteorder(\\1)', astr) + (astr, n4) = type_re.subn('numarray.typefrom(\\1)', astr) + if (n1+n2+n3+n4 > 0): + astr = addimport(astr) + + astr = isbyte_re.sub('not \\1.dtype.isnative', astr) + astr = iscarr_re.sub('\\1.dtype.isnative and \\1.flags.carray', astr) + astr = isfarr_re.sub('\\1.dtype.isnative and \\1.flags.farray', astr) + astr = repeat_re.sub('\\1.repeat(\\2, axis=0)', astr) + astr = setshape_re.sub('\\1.shape = \\2', astr) + astr = setreal_re.sub('\\1.real = \\2', astr) + astr = setimag_re.sub('\\1.imag = \\2', astr) + astr = setimaginary_re.sub('\\1.imag = \\2', astr) return astr - + import datetime def fromstr(filestr): - filestr = fixtypechars(filestr) - filestr, fromall1 = changeimports(filestr, 'Numeric', 'numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'multiarray','numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'umath', 'numpy.oldnumeric') - filestr, fromall1 = changeimports(filestr, 'Precision', 'numpy.oldnumeric.precision') - filestr, fromall1 = changeimports(filestr, 'UserArray', 'numpy.oldnumeric.user_array') - filestr, fromall1 = changeimports(filestr, 'ArrayPrinter', 'numpy.oldnumeric.array_printer') - filestr, fromall2 = changeimports(filestr, 'numerix', 'numpy.oldnumeric') - filestr, fromall3 = changeimports(filestr, 'scipy_base', 'numpy.oldnumeric') - filestr, fromall3 = changeimports(filestr, 'Matrix', 'numpy.oldnumeric.matrix') - filestr, fromall3 = changeimports(filestr, 'MLab', 'numpy.oldnumeric.mlab') - filestr, fromall3 = changeimports(filestr, 'LinearAlgebra', 'numpy.oldnumeric.linear_algebra') - filestr, fromall3 = changeimports(filestr, 'RNG', 'numpy.oldnumeric.rng') - filestr, fromall3 = changeimports(filestr, 'RNG.Statistics', 'numpy.oldnumeric.rng_stats') - filestr, fromall3 = changeimports(filestr, 'RandomArray', 'numpy.oldnumeric.random_array') - filestr, fromall3 = changeimports(filestr, 'FFT', 'numpy.oldnumeric.fft') - filestr, fromall3 = changeimports(filestr, 'MA', 'numpy.oldnumeric.ma') - fromall = fromall1 or fromall2 or fromall3 + filestr, fromall = changeimports(filestr, 'numarray', 'numpy.numarray') + base = 'numarray' + newbase = 'numpy.numarray' + for sub in ['', 'convolve', 'image', 'nd_image', 'mlab', 'linear_algebra', + 'ma', 'matrix', 'fft', 'random_array']: + if sub != '': + sub = '.'+sub + filestr, fromall = changeimports(filestr, base+sub, newbase+sub) + filestr = replaceattr(filestr) filestr = replaceother(filestr) today = datetime.date.today().strftime('%b %d, %Y') name = os.path.split(sys.argv[0])[-1] filestr = '## Automatically adapted for '\ - 'numpy.oldnumeric %s by %s\n\n%s' % (today, name, filestr) + 'numpy.numarray %s by %s\n\n%s' % (today, name, filestr) return filestr def makenewfile(name, filestr): Modified: trunk/numpy/numarray/alter_code2.py =================================================================== --- trunk/numpy/numarray/alter_code2.py 2006-08-10 19:38:46 UTC (rev 2988) +++ trunk/numpy/numarray/alter_code2.py 2006-08-10 21:07:31 UTC (rev 2989) @@ -3,7 +3,7 @@ with numpy """ -#__all__ = ['fromfile', 'fromstr'] +#__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] __all__ = [] import warnings Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-10 19:38:46 UTC (rev 2988) +++ trunk/numpy/numarray/functions.py 2006-08-10 21:07:31 UTC (rev 2989) @@ -33,7 +33,8 @@ 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'swapaxes', 'take', 'tcode', 'tname', 'tensormultiply', 'trace', 'transpose', - 'types', 'value', 'cumsum', 'cumproduct', 'nonzero' + 'types', 'value', 'cumsum', 'cumproduct', 'nonzero', 'newobj', + 'togglebyteorder' ] import copy, copy_reg, types @@ -444,3 +445,11 @@ def argmin(x, axis=-1): return N.argmin(x, axis) +def newobj(self, type): + if type is None: + return N.empty_like(self) + else: + return N.empty(self.shape, type) + +def togglebyteorder(self): + self.dtype=self.dtype.newbyteorder() Modified: trunk/numpy/oldnumeric/alter_code1.py =================================================================== --- trunk/numpy/oldnumeric/alter_code1.py 2006-08-10 19:38:46 UTC (rev 2988) +++ trunk/numpy/oldnumeric/alter_code1.py 2006-08-10 21:07:31 UTC (rev 2989) @@ -28,7 +28,7 @@ * Converts uses of type(...) is isinstance(..., ) """ -__all__ = ['fromfile', 'fromstr'] +__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] import sys import os Modified: trunk/numpy/oldnumeric/alter_code2.py =================================================================== --- trunk/numpy/oldnumeric/alter_code2.py 2006-08-10 19:38:46 UTC (rev 2988) +++ trunk/numpy/oldnumeric/alter_code2.py 2006-08-10 21:07:31 UTC (rev 2989) @@ -17,7 +17,7 @@ oldnumeric.random_array, and oldnumeric.fft """ -#__all__ = ['fromfile', 'fromstr'] +#__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] __all__ = [] import warnings From numpy-svn at scipy.org Thu Aug 10 17:16:22 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 16:16:22 -0500 (CDT) Subject: [Numpy-svn] r2990 - in trunk/numpy/core: . code_generators Message-ID: <20060810211622.0362C39C00A@new.scipy.org> Author: cookedm Date: 2006-08-10 16:16:20 -0500 (Thu, 10 Aug 2006) New Revision: 2990 Modified: trunk/numpy/core/code_generators/genapi.py trunk/numpy/core/code_generators/generate_array_api.py trunk/numpy/core/code_generators/generate_ufunc_api.py trunk/numpy/core/setup.py Log: The code generators for the API now create a .txt file (in ReST format) with the API functions and the documentation comment from the source. Currently, this is put in the header file directory (`src./numpy/core/include` in the `build` directory). Also fixed up dependency checking: API changes should force a rebuild of all the C extensions using the API. Modified: trunk/numpy/core/code_generators/genapi.py =================================================================== --- trunk/numpy/core/code_generators/genapi.py 2006-08-10 21:07:31 UTC (rev 2989) +++ trunk/numpy/core/code_generators/genapi.py 2006-08-10 21:16:20 UTC (rev 2990) @@ -1,5 +1,6 @@ import sys, os, re import md5 +import textwrap API_FILES = ['arraymethods.c', 'arrayobject.c', @@ -11,6 +12,9 @@ THIS_DIR = os.path.dirname(__file__) API_FILES = [os.path.join(THIS_DIR, '..', 'src', a) for a in API_FILES] +def file_in_this_dir(filename): + return os.path.join(THIS_DIR, filename) + def remove_whitespace(s): return ''.join(s.split()) @@ -44,6 +48,21 @@ doccomment = '' return '%s%s %s(%s)' % (doccomment, self.return_type, self.name, argstr) + def to_ReST(self): + lines = ['::', '', ' ' + self.return_type] + argstr = ',\000'.join([self._format_arg(a) for a in self.args]) + name = ' %s' % (self.name,) + s = textwrap.wrap('(%s)' % (argstr,), width=72, + initial_indent=name, + subsequent_indent=' ' * (len(name)+1), + break_long_words=False) + for l in s: + lines.append(l.replace('\000', ' ').rstrip()) + lines.append('') + if self.doc: + lines.append(textwrap.dedent(self.doc)) + return '\n'.join(lines) + def api_hash(self): m = md5.new() m.update(remove_whitespace(self.return_type)) @@ -133,32 +152,36 @@ else: line = line.lstrip(' *') doclist.append(line) - elif state == STATE_RETTYPE: #first line of declaration with return type + elif state == STATE_RETTYPE: + # first line of declaration with return type m = re.match(r'static\s+(.*)$', line) if m: line = m.group(1) return_type = line state = STATE_NAME - elif state == STATE_NAME: # second line, with function name + elif state == STATE_NAME: + # second line, with function name m = re.match(r'(\w+)\s*\(', line) if m: function_name = m.group(1) else: - raise ParseError(filename, lineno+1, 'could not find function name') + raise ParseError(filename, lineno+1, + 'could not find function name') function_args.append(line[m.end():]) state = STATE_ARGS elif state == STATE_ARGS: - if line.startswith('{'): # finished + if line.startswith('{'): + # finished fargs_str = ' '.join(function_args).rstrip(' )') fargs = split_arguments(fargs_str) f = Function(function_name, return_type, fargs, - ' '.join(doclist)) + '\n'.join(doclist)) functions.append(f) return_type = None function_name = None function_args = [] doclist = [] - state = 0 + state = SCANNING else: function_args.append(line) except: @@ -181,7 +204,7 @@ def get_api_functions(tagname, order_file): if not os.path.exists(order_file): - order_file = os.path.join(THIS_DIR, order_file) + order_file = file_in_this_dir(order_file) order = read_order(order_file) functions = [] for f in API_FILES: @@ -195,7 +218,7 @@ def add_api_list(offset, APIname, api_list, module_list, extension_list, init_list): - """Add the API function declerations to the appropiate lists for use in + """Add the API function declarations to the appropiate lists for use in the headers. """ for k, func in enumerate(api_list): @@ -210,6 +233,15 @@ astr = " (void *) %s," % func.name init_list.append(astr) +def should_rebuild(targets, source_files): + from distutils.dep_util import newer_group + for t in targets: + if not os.path.exists(t): + return True + sources = API_FILES + list(source_files) + [__file__] + if newer_group(sources, targets[0], missing='newer'): + return True + return False def main(): tagname = sys.argv[1] Modified: trunk/numpy/core/code_generators/generate_array_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_array_api.py 2006-08-10 21:07:31 UTC (rev 2989) +++ trunk/numpy/core/code_generators/generate_array_api.py 2006-08-10 21:16:20 UTC (rev 2990) @@ -1,6 +1,9 @@ import os import genapi +OBJECT_API_ORDER = 'array_api_order.txt' +MULTIARRAY_API_ORDER = 'multiarray_api_order.txt' + types = ['Generic','Number','Integer','SignedInteger','UnsignedInteger', 'Inexact', 'Floating', 'ComplexFloating', 'Flexible', 'Character', @@ -113,11 +116,23 @@ }; """ -def generate_api(output_dir): +def generate_api(output_dir, force=False): + header_file = os.path.join(output_dir, '__multiarray_api.h') + c_file = os.path.join(output_dir,'__multiarray_api.c') + doc_file = os.path.join(output_dir, 'multiarray_api.txt') + + targets = (header_file, c_file, doc_file) + if (not force + and not genapi.should_rebuild(targets, + [OBJECT_API_ORDER, + MULTIARRAY_API_ORDER, + __file__])): + return targets + objectapi_list = genapi.get_api_functions('OBJECT_API', - 'array_api_order.txt') + OBJECT_API_ORDER) multiapi_list = genapi.get_api_functions('MULTIARRAY_API', - 'multiarray_api_order.txt') + MULTIARRAY_API_ORDER) # API fixes for __arrayobject_api.h fixed = 10 @@ -141,23 +156,48 @@ (types[k], num) extension_list.append(astr) - #setup object API + # set up object API genapi.add_api_list(numtypes, 'PyArray_API', objectapi_list, module_list, extension_list, init_list) - # setup multiarray module API + # set up multiarray module API genapi.add_api_list(numobject, 'PyArray_API', multiapi_list, module_list, extension_list, init_list) # Write to header - fid = open(os.path.join(output_dir, '__multiarray_api.h'),'w') + fid = open(header_file, 'w') s = h_template % ('\n'.join(module_list), '\n'.join(extension_list)) fid.write(s) fid.close() # Write to c-code - fid = open(os.path.join(output_dir,'__multiarray_api.c'),'w') + fid = open(c_file, 'w') s = c_template % '\n'.join(init_list) fid.write(s) fid.close() + + # write to documentation + fid = open(doc_file, 'w') + fid.write(''' +=========== +Numpy C-API +=========== + +Object API +========== +''') + for func in objectapi_list: + fid.write(func.to_ReST()) + fid.write('\n\n') + fid.write(''' + +Multiarray API +============== +''') + for func in multiapi_list: + fid.write(func.to_ReST()) + fid.write('\n\n') + fid.close() + + return targets Modified: trunk/numpy/core/code_generators/generate_ufunc_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_ufunc_api.py 2006-08-10 21:07:31 UTC (rev 2989) +++ trunk/numpy/core/code_generators/generate_ufunc_api.py 2006-08-10 21:16:20 UTC (rev 2990) @@ -1,6 +1,8 @@ import os import genapi +UFUNC_API_ORDER = 'ufunc_api_order.txt' + h_template = r""" #ifdef _UMATHMODULE @@ -64,10 +66,19 @@ }; """ -def generate_api(output_dir): - ufunc_api_list = genapi.get_api_functions('UFUNC_API', - 'ufunc_api_order.txt') +def generate_api(output_dir, force=False): + header_file = os.path.join(output_dir, '__ufunc_api.h') + c_file = os.path.join(output_dir, '__ufunc_api.c') + doc_file = os.path.join(output_dir, 'ufunc_api.txt') + targets = (header_file, c_file, doc_file) + if (not force + and not genapi.should_rebuild(targets, + [UFUNC_API_ORDER, __file__])): + return targets + + ufunc_api_list = genapi.get_api_functions('UFUNC_API', UFUNC_API_ORDER) + # API fixes for __arrayobject_api.h fixed = 1 @@ -78,18 +89,32 @@ extension_list = [] init_list = [] - #setup object API + # set up object API genapi.add_api_list(fixed, 'PyUFunc_API', ufunc_api_list, module_list, extension_list, init_list) # Write to header - fid = open(os.path.join(output_dir, '__ufunc_api.h'),'w') + fid = open(header_file, 'w') s = h_template % ('\n'.join(module_list), '\n'.join(extension_list)) fid.write(s) fid.close() # Write to c-code - fid = open(os.path.join(output_dir, '__ufunc_api.c'),'w') + fid = open(c_file, 'w') s = c_template % '\n'.join(init_list) fid.write(s) fid.close() + + # Write to documentation + fid = open(doc_file, 'w') + fid.write(''' +================= +Numpy Ufunc C-API +================= +''') + for func in ufunc_api_list: + fid.write(func.to_ReST()) + fid.write('\n\n') + fid.close() + + return targets Modified: trunk/numpy/core/setup.py =================================================================== --- trunk/numpy/core/setup.py 2006-08-10 21:07:31 UTC (rev 2989) +++ trunk/numpy/core/setup.py 2006-08-10 21:16:20 UTC (rev 2990) @@ -6,6 +6,19 @@ from glob import glob from distutils.dep_util import newer,newer_group +FUNCTIONS_TO_CHECK = [ + ('expl', 'HAVE_LONGDOUBLE_FUNCS'), + ('expf', 'HAVE_FLOAT_FUNCS'), + ('log1p', 'HAVE_LOG1P'), + ('expm1', 'HAVE_EXPM1'), + ('asinh', 'HAVE_INVERSE_HYPERBOLIC'), + ('atanhf', 'HAVE_INVERSE_HYPERBOLIC_FLOAT'), + ('atanhl', 'HAVE_INVERSE_HYPERBOLIC_LONGDOUBLE'), + ('isnan', 'HAVE_ISNAN'), + ('isinf', 'HAVE_ISINF'), + ('rint', 'HAVE_RINT'), + ] + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join from numpy.distutils.system_info import get_info, default_lib_dirs @@ -50,14 +63,14 @@ # are actually multiple CPUS? -- but # threaded code can be nice even on a single # CPU so that long-calculating code doesn't - # block. + # block. try: nosmp = os.environ['NPY_NOSMP'] nosmp = 1 except KeyError: nosmp = 0 if nosmp: moredefs = [('NPY_ALLOW_THREADS', '0')] - else: moredefs = [] + else: moredefs = [] # mathlibs = [] tc = testcode_mathlib() @@ -70,36 +83,24 @@ mathlibs = libs break else: - raise "math library missing; rerun setup.py after setting the MATHLIB env variable" + raise EnvironmentError("math library missing; rerun " + "setup.py after setting the " + "MATHLIB env variable") ext.libraries.extend(mathlibs) moredefs.append(('MATHLIB',','.join(mathlibs))) - libs = mathlibs - kws_args = {'libraries':libs,'decl':0,'headers':['math.h']} - if config_cmd.check_func('expl', **kws_args): - moredefs.append('HAVE_LONGDOUBLE_FUNCS') - if config_cmd.check_func('expf', **kws_args): - moredefs.append('HAVE_FLOAT_FUNCS') - if config_cmd.check_func('log1p', **kws_args): - moredefs.append('HAVE_LOG1P') - if config_cmd.check_func('expm1', **kws_args): - moredefs.append('HAVE_EXPM1') - if config_cmd.check_func('asinh', **kws_args): - moredefs.append('HAVE_INVERSE_HYPERBOLIC') - if config_cmd.check_func('atanhf', **kws_args): - moredefs.append('HAVE_INVERSE_HYPERBOLIC_FLOAT') - if config_cmd.check_func('atanhl', **kws_args): - moredefs.append('HAVE_INVERSE_HYPERBOLIC_LONGDOUBLE') - if config_cmd.check_func('isnan', **kws_args): - moredefs.append('HAVE_ISNAN') - if config_cmd.check_func('isinf', **kws_args): - moredefs.append('HAVE_ISINF') - if config_cmd.check_func('rint', **kws_args): - moredefs.append('HAVE_RINT') + def check_func(func_name): + return config_cmd.check_func(func_name, + libraries=mathlibs, decl=False, + headers=['math.h']) + for func_name, defsymbol in FUNCTIONS_TO_CHECK: + if check_func(func_name): + moredefs.append(defsymbol) + if sys.version[:3] < '2.4': kws_args['headers'].append('stdlib.h') - if config_cmd.check_func('strtod', **kws_args): + if check_func('strtod'): moredefs.append(('PyOS_ascii_strtod', 'strtod')) if moredefs: @@ -132,26 +133,23 @@ config.add_data_files((header_dir,target)) return target - def generate_api_func(header_file, module_name): - def generate_api(ext,build_dir): - target = join(build_dir, header_file) + def generate_api_func(module_name): + def generate_api(ext, build_dir): script = join(codegen_dir, module_name + '.py') - if newer(script, target): - sys.path.insert(0, codegen_dir) - try: - m = __import__(module_name) - print 'executing',script - m.generate_api(build_dir) - finally: - del sys.path[0] - config.add_data_files((header_dir,target)) - return target + sys.path.insert(0, codegen_dir) + try: + m = __import__(module_name) + print 'executing', script + h_file, c_file, doc_file = m.generate_api(build_dir) + finally: + del sys.path[0] + config.add_data_files((header_dir, h_file), + (header_dir, doc_file)) + return (h_file,) return generate_api - generate_array_api = generate_api_func('__multiarray_api.h', - 'generate_array_api') - generate_ufunc_api = generate_api_func('__ufunc_api.h', - 'generate_ufunc_api') + generate_array_api = generate_api_func('generate_array_api') + generate_ufunc_api = generate_api_func('generate_ufunc_api') def generate_umath_c(ext,build_dir): target = join(build_dir,'__umath_generated.c') From numpy-svn at scipy.org Thu Aug 10 18:45:36 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 17:45:36 -0500 (CDT) Subject: [Numpy-svn] r2991 - in trunk/numpy: linalg linalg/lapack_lite numarray Message-ID: <20060810224536.B9F4639C037@new.scipy.org> Author: oliphant Date: 2006-08-10 17:45:29 -0500 (Thu, 10 Aug 2006) New Revision: 2991 Added: trunk/numpy/numarray/fft.py trunk/numpy/numarray/linear_algebra.py trunk/numpy/numarray/ma.py trunk/numpy/numarray/matrix.py trunk/numpy/numarray/mlab.py trunk/numpy/numarray/random_array.py Modified: trunk/numpy/linalg/lapack_lite/wrapped_routines trunk/numpy/linalg/lapack_litemodule.c trunk/numpy/linalg/linalg.py Log: Add qr decomposition to linalg Modified: trunk/numpy/linalg/lapack_lite/wrapped_routines =================================================================== --- trunk/numpy/linalg/lapack_lite/wrapped_routines 2006-08-10 21:16:20 UTC (rev 2990) +++ trunk/numpy/linalg/lapack_lite/wrapped_routines 2006-08-10 22:45:29 UTC (rev 2991) @@ -12,6 +12,8 @@ zpotrf dgesdd zgesdd +dgeqrf +zgeqrf # need this b/c it's not properly declared as external in the BLAS source dcabs1 IGNORE: dlamch Modified: trunk/numpy/linalg/lapack_litemodule.c =================================================================== --- trunk/numpy/linalg/lapack_litemodule.c 2006-08-10 21:16:20 UTC (rev 2990) +++ trunk/numpy/linalg/lapack_litemodule.c 2006-08-10 22:45:29 UTC (rev 2991) @@ -16,11 +16,11 @@ typedef struct { double r, i; } f2c_doublecomplex; /* typedef long int (*L_fp)(); */ -extern void FNAME(dgeev)(char *jobvl, char *jobvr, int *n, +extern int FNAME(dgeev)(char *jobvl, char *jobvr, int *n, double a[], int *lda, double wr[], double wi[], double vl[], int *ldvl, double vr[], int *ldvr, double work[], int lwork[], int *info); -extern void FNAME(zgeev)(char *jobvl, char *jobvr, int *n, +extern int FNAME(zgeev)(char *jobvl, char *jobvr, int *n, f2c_doublecomplex a[], int *lda, f2c_doublecomplex w[], f2c_doublecomplex vl[], int *ldvl, @@ -28,54 +28,70 @@ f2c_doublecomplex work[], int *lwork, double rwork[], int *info); -extern void FNAME(dsyevd)(char *jobz, char *uplo, int *n, +extern int FNAME(dsyevd)(char *jobz, char *uplo, int *n, double a[], int *lda, double w[], double work[], int *lwork, int iwork[], int *liwork, int *info); -extern void FNAME(zheevd)(char *jobz, char *uplo, int *n, +extern int FNAME(zheevd)(char *jobz, char *uplo, int *n, f2c_doublecomplex a[], int *lda, double w[], f2c_doublecomplex work[], int *lwork, double rwork[], int *lrwork, int iwork[], int *liwork, int *info); -extern void FNAME(dgelsd)(int *m, int *n, int *nrhs, +extern int FNAME(dgelsd)(int *m, int *n, int *nrhs, double a[], int *lda, double b[], int *ldb, double s[], double *rcond, int *rank, double work[], int *lwork, int iwork[], int *info); -extern void FNAME(zgelsd)(int *m, int *n, int *nrhs, +extern int FNAME(zgelsd)(int *m, int *n, int *nrhs, f2c_doublecomplex a[], int *lda, f2c_doublecomplex b[], int *ldb, double s[], double *rcond, int *rank, f2c_doublecomplex work[], int *lwork, double rwork[], int iwork[], int *info); -extern void FNAME(dgesv)(int *n, int *nrhs, +extern int FNAME(dgesv)(int *n, int *nrhs, double a[], int *lda, int ipiv[], double b[], int *ldb, int *info); -extern void FNAME(zgesv)(int *n, int *nrhs, +extern int FNAME(zgesv)(int *n, int *nrhs, f2c_doublecomplex a[], int *lda, int ipiv[], f2c_doublecomplex b[], int *ldb, int *info); -extern void FNAME(dgetrf)(int *m, int *n, +extern int FNAME(dgetrf)(int *m, int *n, double a[], int *lda, int ipiv[], int *info); -extern void FNAME(zgetrf)(int *m, int *n, +extern int FNAME(zgetrf)(int *m, int *n, f2c_doublecomplex a[], int *lda, int ipiv[], int *info); -extern void FNAME(dpotrf)(char *uplo, int *n, double a[], int *lda, int *info); -extern void FNAME(zpotrf)(char *uplo, int *n, +extern int FNAME(dpotrf)(char *uplo, int *n, double a[], int *lda, int *info); +extern int FNAME(zpotrf)(char *uplo, int *n, f2c_doublecomplex a[], int *lda, int *info); -extern void FNAME(dgesdd)(char *jobz, int *m, int *n, +extern int FNAME(dgesdd)(char *jobz, int *m, int *n, double a[], int *lda, double s[], double u[], int *ldu, double vt[], int *ldvt, double work[], int *lwork, int iwork[], int *info); -extern void FNAME(zgesdd)(char *jobz, int *m, int *n, +extern int FNAME(zgesdd)(char *jobz, int *m, int *n, f2c_doublecomplex a[], int *lda, double s[], f2c_doublecomplex u[], int *ldu, f2c_doublecomplex vt[], int *ldvt, f2c_doublecomplex work[], int *lwork, double rwork[], int iwork[], int *info); +extern int FNAME(dgeqrf)(int *m, int *n, double a[], int *lda, + double tau[], double work[], + int *lwork, int *info); + +extern int FNAME(zgeqrf)(int *m, int *n, f2c_doublecomplex a[], int *lda, + f2c_doublecomplex tau[], f2c_doublecomplex work[], + int *lwork, int *info); + +extern int FNAME(dorgqr)(int *m, int *n, int *k, double a[], int *lda, + double tau[], double work[], + int *lwork, int *info); + +extern int FNAME(zungqr)(int *m, int *n, int *k, f2c_doublecomplex a[], + int *lda, f2c_doublecomplex tau[], + f2c_doublecomplex work[], int *lwork, int *info); + static PyObject *LapackError; #define TRY(E) if (!(E)) return NULL @@ -141,9 +157,10 @@ TRY(check_object(vr,PyArray_DOUBLE,"vr","PyArray_DOUBLE","dgeev")); TRY(check_object(work,PyArray_DOUBLE,"work","PyArray_DOUBLE","dgeev")); - lapack_lite_status__ = 0; - FNAME(dgeev)(&jobvl,&jobvr,&n,DDATA(a),&lda,DDATA(wr),DDATA(wi), - DDATA(vl),&ldvl,DDATA(vr),&ldvr,DDATA(work),&lwork,&info); + lapack_lite_status__ = \ + FNAME(dgeev)(&jobvl,&jobvr,&n,DDATA(a),&lda,DDATA(wr),DDATA(wi), + DDATA(vl),&ldvl,DDATA(vr),&ldvr,DDATA(work),&lwork, + &info); return Py_BuildValue("{s:i,s:c,s:c,s:i,s:i,s:i,s:i,s:i,s:i}","dgeev_", lapack_lite_status__,"jobvl",jobvl,"jobvr",jobvr, @@ -224,9 +241,9 @@ TRY(check_object(work,PyArray_DOUBLE,"work","PyArray_DOUBLE","dsyevd")); TRY(check_object(iwork,PyArray_INT,"iwork","PyArray_INT","dsyevd")); - lapack_lite_status__ = 0; - FNAME(dsyevd)(&jobz,&uplo,&n,DDATA(a),&lda,DDATA(w),DDATA(work), - &lwork,IDATA(iwork),&liwork,&info); + lapack_lite_status__ = \ + FNAME(dsyevd)(&jobz,&uplo,&n,DDATA(a),&lda,DDATA(w),DDATA(work), + &lwork,IDATA(iwork),&liwork,&info); return Py_BuildValue("{s:i,s:c,s:c,s:i,s:i,s:i,s:i,s:i}","dsyevd_", lapack_lite_status__,"jobz",jobz,"uplo",uplo, @@ -311,7 +328,7 @@ TRY(check_object(w,PyArray_DOUBLE,"rwork","PyArray_DOUBLE","zheevd")); TRY(check_object(iwork,PyArray_INT,"iwork","PyArray_INT","zheevd")); - lapack_lite_status__ = 0; + lapack_lite_status__ = \ FNAME(zheevd)(&jobz,&uplo,&n,ZDATA(a),&lda,DDATA(w),ZDATA(work), &lwork,DDATA(rwork),&lrwork,IDATA(iwork),&liwork,&info); @@ -349,10 +366,11 @@ TRY(check_object(work,PyArray_DOUBLE,"work","PyArray_DOUBLE","dgelsd")); TRY(check_object(iwork,PyArray_INT,"iwork","PyArray_INT","dgelsd")); - lapack_lite_status__ = 0; - FNAME(dgelsd)(&m,&n,&nrhs,DDATA(a),&lda,DDATA(b),&ldb, - DDATA(s),&rcond,&rank,DDATA(work),&lwork,IDATA(iwork),&info); - + lapack_lite_status__ = \ + FNAME(dgelsd)(&m,&n,&nrhs,DDATA(a),&lda,DDATA(b),&ldb, + DDATA(s),&rcond,&rank,DDATA(work),&lwork, + IDATA(iwork),&info); + return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i,s:d,s:i,s:i,s:i}","dgelsd_", lapack_lite_status__,"m",m,"n",n,"nrhs",nrhs, "lda",lda,"ldb",ldb,"rcond",rcond,"rank",rank, @@ -377,7 +395,7 @@ TRY(check_object(ipiv,PyArray_INT,"ipiv","PyArray_INT","dgesv")); TRY(check_object(b,PyArray_DOUBLE,"b","PyArray_DOUBLE","dgesv")); - lapack_lite_status__ = 0; + lapack_lite_status__ = \ FNAME(dgesv)(&n,&nrhs,DDATA(a),&lda,IDATA(ipiv),DDATA(b),&ldb,&info); return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i}","dgesv_", @@ -414,9 +432,10 @@ TRY(check_object(work,PyArray_DOUBLE,"work","PyArray_DOUBLE","dgesdd")); TRY(check_object(iwork,PyArray_INT,"iwork","PyArray_INT","dgesdd")); - lapack_lite_status__ = 0; - FNAME(dgesdd)(&jobz,&m,&n,DDATA(a),&lda,DDATA(s),DDATA(u),&ldu, - DDATA(vt),&ldvt,DDATA(work),&lwork,IDATA(iwork),&info); + lapack_lite_status__ = \ + FNAME(dgesdd)(&jobz,&m,&n,DDATA(a),&lda,DDATA(s),DDATA(u),&ldu, + DDATA(vt),&ldvt,DDATA(work),&lwork,IDATA(iwork), + &info); return Py_BuildValue("{s:i,s:c,s:i,s:i,s:i,s:i,s:i,s:i,s:i}","dgesdd_", lapack_lite_status__,"jobz",jobz,"m",m,"n",n, @@ -439,8 +458,8 @@ TRY(check_object(a,PyArray_DOUBLE,"a","PyArray_DOUBLE","dgetrf")); TRY(check_object(ipiv,PyArray_INT,"ipiv","PyArray_INT","dgetrf")); - lapack_lite_status__ = 0; - FNAME(dgetrf)(&m,&n,DDATA(a),&lda,IDATA(ipiv),&info); + lapack_lite_status__ = \ + FNAME(dgetrf)(&m,&n,DDATA(a),&lda,IDATA(ipiv),&info); return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i}","dgetrf_",lapack_lite_status__, "m",m,"n",n,"lda",lda,"info",info); @@ -459,14 +478,61 @@ TRY(PyArg_ParseTuple(args,"ciOii",&uplo,&n,&a,&lda,&info)); TRY(check_object(a,PyArray_DOUBLE,"a","PyArray_DOUBLE","dpotrf")); - lapack_lite_status__ = 0; - FNAME(dpotrf)(&uplo,&n,DDATA(a),&lda,&info); + lapack_lite_status__ = \ + FNAME(dpotrf)(&uplo,&n,DDATA(a),&lda,&info); return Py_BuildValue("{s:i,s:i,s:i,s:i}","dpotrf_",lapack_lite_status__, "n",n,"lda",lda,"info",info); } static PyObject * +lapack_lite_dgeqrf(PyObject *self, PyObject *args) +{ + int lapack_lite_status__; + int m, n, lwork; + PyObject *a, *tau, *work; + int lda; + int info; + + TRY(PyArg_ParseTuple(args,"llOlOOll",&m,&n,&a,&lda,&tau,&work,&lwork,&info)); + + /* check objects and convert to right storage order */ + TRY(check_object(a,PyArray_DOUBLE,"a","PyArray_DOUBLE","dgeqrf")); + TRY(check_object(tau,PyArray_DOUBLE,"tau","PyArray_DOUBLE","dgeqrf")); + TRY(check_object(work,PyArray_DOUBLE,"work","PyArray_DOUBLE","dgeqrf")); + + lapack_lite_status__ = \ + FNAME(dgeqrf)(&m, &n, DDATA(a), &lda, DDATA(tau), + DDATA(work), &lwork, &info); + + return Py_BuildValue("{s:l,s:l,s:l,s:l,s:l,s:l}","dgeqrf_", + lapack_lite_status__,"m",m,"n",n,"lda",lda, + "lwork",lwork,"info",info); +} + + +static PyObject * +lapack_lite_dorgqr(PyObject *self, PyObject *args) +{ + int lapack_lite_status__; + int m, n, k, lwork; + PyObject *a, *tau, *work; + int lda; + int info; + + TRY(PyArg_ParseTuple(args,"lllOlOOll", &m, &n, &k, &a, &lda, &tau, &work, &lwork, &info)); + TRY(check_object(a,PyArray_DOUBLE,"a","PyArray_DOUBLE","dorgqr")); + TRY(check_object(tau,PyArray_DOUBLE,"tau","PyArray_DOUBLE","dorgqr")); + TRY(check_object(work,PyArray_DOUBLE,"work","PyArray_DOUBLE","dorgqr")); + lapack_lite_status__ = \ + FNAME(dorgqr)(&m, &n, &k, DDATA(a), &lda, DDATA(tau), DDATA(work), &lwork, &info); + + return Py_BuildValue("{s:l,s:l}","dorgqr_",lapack_lite_status__, + "info",info); +} + + +static PyObject * lapack_lite_zgeev(PyObject *self, PyObject *args) { int lapack_lite_status__; @@ -495,9 +561,10 @@ TRY(check_object(work,PyArray_CDOUBLE,"work","PyArray_CDOUBLE","zgeev")); TRY(check_object(rwork,PyArray_DOUBLE,"rwork","PyArray_DOUBLE","zgeev")); - lapack_lite_status__ = 0; - FNAME(zgeev)(&jobvl,&jobvr,&n,ZDATA(a),&lda,ZDATA(w),ZDATA(vl),&ldvl, - ZDATA(vr),&ldvr,ZDATA(work),&lwork,DDATA(rwork),&info); + lapack_lite_status__ = \ + FNAME(zgeev)(&jobvl,&jobvr,&n,ZDATA(a),&lda,ZDATA(w),ZDATA(vl), + &ldvl,ZDATA(vr),&ldvr,ZDATA(work),&lwork, + DDATA(rwork),&info); return Py_BuildValue("{s:i,s:c,s:c,s:i,s:i,s:i,s:i,s:i,s:i}","zgeev_", lapack_lite_status__,"jobvl",jobvl,"jobvr",jobvr, @@ -535,7 +602,7 @@ TRY(check_object(rwork,PyArray_DOUBLE,"rwork","PyArray_DOUBLE","zgelsd")); TRY(check_object(iwork,PyArray_INT,"iwork","PyArray_INT","zgelsd")); - lapack_lite_status__ = 0; + lapack_lite_status__ = \ FNAME(zgelsd)(&m,&n,&nrhs,ZDATA(a),&lda,ZDATA(b),&ldb,DDATA(s),&rcond, &rank,ZDATA(work),&lwork,DDATA(rwork),IDATA(iwork),&info); @@ -562,7 +629,7 @@ TRY(check_object(ipiv,PyArray_INT,"ipiv","PyArray_INT","zgesv")); TRY(check_object(b,PyArray_CDOUBLE,"b","PyArray_CDOUBLE","zgesv")); - lapack_lite_status__ = 0; + lapack_lite_status__ = \ FNAME(zgesv)(&n,&nrhs,ZDATA(a),&lda,IDATA(ipiv),ZDATA(b),&ldb,&info); return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i,s:i}","zgesv_", @@ -601,7 +668,7 @@ TRY(check_object(rwork,PyArray_DOUBLE,"rwork","PyArray_DOUBLE","zgesdd")); TRY(check_object(iwork,PyArray_INT,"iwork","PyArray_INT","zgesdd")); - lapack_lite_status__ = 0; + lapack_lite_status__ = \ FNAME(zgesdd)(&jobz,&m,&n,ZDATA(a),&lda,DDATA(s),ZDATA(u),&ldu, ZDATA(vt),&ldvt,ZDATA(work),&lwork,DDATA(rwork), IDATA(iwork),&info); @@ -627,7 +694,7 @@ TRY(check_object(a,PyArray_CDOUBLE,"a","PyArray_CDOUBLE","zgetrf")); TRY(check_object(ipiv,PyArray_INT,"ipiv","PyArray_INT","zgetrf")); - lapack_lite_status__ = 0; + lapack_lite_status__ = \ FNAME(zgetrf)(&m,&n,ZDATA(a),&lda,IDATA(ipiv),&info); return Py_BuildValue("{s:i,s:i,s:i,s:i,s:i}","zgetrf_", @@ -646,13 +713,61 @@ TRY(PyArg_ParseTuple(args,"ciOii",&uplo,&n,&a,&lda,&info)); TRY(check_object(a,PyArray_CDOUBLE,"a","PyArray_CDOUBLE","zpotrf")); - lapack_lite_status__ = 0; + lapack_lite_status__ = \ FNAME(zpotrf)(&uplo,&n,ZDATA(a),&lda,&info); return Py_BuildValue("{s:i,s:i,s:i,s:i}","zpotrf_", lapack_lite_status__,"n",n,"lda",lda,"info",info); } +static PyObject * +lapack_lite_zgeqrf(PyObject *self, PyObject *args) +{ + int lapack_lite_status__; + int m, n, lwork; + PyObject *a, *tau, *work; + int lda; + int info; + + TRY(PyArg_ParseTuple(args,"llOlOOll",&m,&n,&a,&lda,&tau,&work,&lwork,&info)); + +/* check objects and convert to right storage order */ + TRY(check_object(a,PyArray_CDOUBLE,"a","PyArray_CDOUBLE","zgeqrf")); + TRY(check_object(tau,PyArray_CDOUBLE,"tau","PyArray_CDOUBLE","zgeqrf")); + TRY(check_object(work,PyArray_CDOUBLE,"work","PyArray_CDOUBLE","zgeqrf")); + + lapack_lite_status__ = \ + FNAME(zgeqrf)(&m, &n, ZDATA(a), &lda, ZDATA(tau), ZDATA(work), &lwork, &info); + + return Py_BuildValue("{s:l,s:l,s:l,s:l,s:l,s:l}","zgeqrf_",lapack_lite_status__,"m",m,"n",n,"lda",lda,"lwork",lwork,"info",info); +} + + +static PyObject * +lapack_lite_zungqr(PyObject *self, PyObject *args) +{ + int lapack_lite_status__; + int m, n, k, lwork; + PyObject *a, *tau, *work; + int lda; + int info; + + TRY(PyArg_ParseTuple(args,"lllOlOOll", &m, &n, &k, &a, &lda, &tau, &work, &lwork, &info)); + TRY(check_object(a,PyArray_CDOUBLE,"a","PyArray_CDOUBLE","zungqr")); + TRY(check_object(tau,PyArray_CDOUBLE,"tau","PyArray_CDOUBLE","zungqr")); + TRY(check_object(work,PyArray_CDOUBLE,"work","PyArray_CDOUBLE","zungqr")); + + + lapack_lite_status__ = \ + FNAME(zungqr)(&m, &n, &k, ZDATA(a), &lda, ZDATA(tau), ZDATA(work), + &lwork, &info); + + return Py_BuildValue("{s:l,s:l}","zungqr_",lapack_lite_status__, + "info",info); +} + + + #define STR(x) #x #define lameth(name) {STR(name), lapack_lite_##name, METH_VARARGS, NULL} static struct PyMethodDef lapack_lite_module_methods[] = { @@ -664,12 +779,16 @@ lameth(dgesdd), lameth(dgetrf), lameth(dpotrf), + lameth(dgeqrf), + lameth(dorgqr), lameth(zgeev), lameth(zgelsd), lameth(zgesv), lameth(zgesdd), lameth(zgetrf), lameth(zpotrf), + lameth(zgeqrf), + lameth(zungqr), { NULL,NULL,0} }; Modified: trunk/numpy/linalg/linalg.py =================================================================== --- trunk/numpy/linalg/linalg.py 2006-08-10 21:16:20 UTC (rev 2990) +++ trunk/numpy/linalg/linalg.py 2006-08-10 22:45:29 UTC (rev 2991) @@ -12,6 +12,7 @@ 'eigvalsh', 'pinv', 'det', 'svd', 'eig', 'eigh','lstsq', 'norm', + 'qr', 'LinAlgError' ] @@ -177,6 +178,95 @@ return s.astype(result_t) return s +# QR decompostion + +def qr(a, mode='full'): + """cacluates A=QR, Q orthonormal, R upper triangular + + mode: 'full' --> (Q,R) + 'r' --> R + 'economic' --> A2 where the diagonal + upper triangle + part of A2 is R. This is faster if you only need R + """ + _assertRank2(a) + t, result_t = _commonType(a) + a = _fastCopyAndTranspose(t, a) + m,n = a.shape + mn = min(m,n) + tau = zeros((mn,), t) + if isComplexType(t): + lapack_routine = lapack_lite.zgeqrf + routine_name = 'zgeqrf' + else: + lapack_routine = lapack_lite.dgeqrf + routine_name = 'dgeqrf' + + # calculate optimal size of work data 'work' + lwork = 1 + work = zeros((lwork,), t) + results=lapack_routine(m, n, a, m, tau, work, -1, 0) + if results['info'] > 0: + raise LinAlgError, '%s returns %d' % (routine_name, results['info']) + + # do qr decomposition + lwork = int(abs(work[0])) + work = zeros((lwork,),t) + results=lapack_routine(m, n, a, m, tau, work, lwork, 0) + + if results['info'] > 0: + raise LinAlgError, '%s returns %d' % (routine_name, results['info']) + + # atemp: convert fortrag storing order to num storing order + atemp = a.transpose() + + if atemp.dtype != result_t: + atemp = atemp.astype(result_t) + + # economic mode + if mode[0]=='e': + return atemp + + # generate r + r = zeros((mn,n), result_t) + for i in range(mn): + r[i, i:] = atemp[i, i:] + + # 'r'-mode, that is, calculate only r + if mode[0]=='r': + return r + + # from here on: build orthonormal matrix q from a + + if isComplexType(t): + lapack_routine = lapack_lite.zungqr + routine_name = 'zungqr' + else: + lapack_routine = lapack_lite.dorgqr + routine_name = 'dorgqr' + + # determine optimal lwork + lwork = 1 + work=zeros((lwork,), t) + results=lapack_routine(m,mn,mn, a, m, tau, work, -1, 0) + if results['info'] > 0: + raise LinAlgError, '%s returns %d' % (routine_name, results['info']) + + # compute q + lwork = int(abs(work[0])) + work=zeros((lwork,), t) + results=lapack_routine(m,mn,mn, a, m, tau, work, lwork, 0) + + if results['info'] > 0: + raise LinAlgError, '%s returns %d' % (routine_name, results['info']) + + q = a[:mn,:].transpose() + + if (q.dtype != result_t): + q = q.astype(result_t) + + return q,r + + # Eigenvalues def eigvals(a): _assertRank2(a) Added: trunk/numpy/numarray/fft.py =================================================================== Added: trunk/numpy/numarray/linear_algebra.py =================================================================== --- trunk/numpy/numarray/linear_algebra.py 2006-08-10 21:16:20 UTC (rev 2990) +++ trunk/numpy/numarray/linear_algebra.py 2006-08-10 22:45:29 UTC (rev 2991) @@ -0,0 +1,15 @@ + +from numpy.oldnumeric.linear_algebra import * + +import numpy.oldnumeric.linear_algebra as nol + +__all__ = nol.__all__ +__all__ += ['qr_decomposition'] + +from numpy.linalg import qr as _qr + +def qr_decomposition(a, mode='full'): + res = _qr(a, mode) + if mode == 'full': + return res + return (None, res) Added: trunk/numpy/numarray/ma.py =================================================================== Added: trunk/numpy/numarray/matrix.py =================================================================== Added: trunk/numpy/numarray/mlab.py =================================================================== Added: trunk/numpy/numarray/random_array.py =================================================================== From numpy-svn at scipy.org Thu Aug 10 19:06:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 18:06:56 -0500 (CDT) Subject: [Numpy-svn] r2992 - trunk/numpy/core/src Message-ID: <20060810230656.7F20B39C037@new.scipy.org> Author: oliphant Date: 2006-08-10 18:06:54 -0500 (Thu, 10 Aug 2006) New Revision: 2992 Modified: trunk/numpy/core/src/arraytypes.inc.src Log: Fix ticket #240 Modified: trunk/numpy/core/src/arraytypes.inc.src =================================================================== --- trunk/numpy/core/src/arraytypes.inc.src 2006-08-10 22:45:29 UTC (rev 2991) +++ trunk/numpy/core/src/arraytypes.inc.src 2006-08-10 23:06:54 UTC (rev 2992) @@ -1292,7 +1292,7 @@ b = a + 3; c=*a; *a++ = *b; *b-- = c; c=*a; *a++ = *b; *b-- = c; - a += 1; + a += 2; } } } @@ -1323,7 +1323,7 @@ b = a + 3; c=*a; *a++ = *b; *b-- = c; c=*a; *a++ = *b; *b-- = c; - a += 1; + a += 2; } } } From numpy-svn at scipy.org Thu Aug 10 19:31:57 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 18:31:57 -0500 (CDT) Subject: [Numpy-svn] r2993 - trunk/numpy/numarray Message-ID: <20060810233157.379FE39C037@new.scipy.org> Author: oliphant Date: 2006-08-10 18:31:53 -0500 (Thu, 10 Aug 2006) New Revision: 2993 Modified: trunk/numpy/numarray/fft.py trunk/numpy/numarray/ma.py trunk/numpy/numarray/matrix.py trunk/numpy/numarray/mlab.py trunk/numpy/numarray/random_array.py Log: Finish adding the rest of numarray compatibility Modified: trunk/numpy/numarray/fft.py =================================================================== --- trunk/numpy/numarray/fft.py 2006-08-10 23:06:54 UTC (rev 2992) +++ trunk/numpy/numarray/fft.py 2006-08-10 23:31:53 UTC (rev 2993) @@ -0,0 +1,7 @@ + +from numpy.oldnumeric.fft import * +import numpy.oldnumeric.fft as nof + +__all__ = nof.__all__ + +del nof Modified: trunk/numpy/numarray/ma.py =================================================================== --- trunk/numpy/numarray/ma.py 2006-08-10 23:06:54 UTC (rev 2992) +++ trunk/numpy/numarray/ma.py 2006-08-10 23:31:53 UTC (rev 2993) @@ -0,0 +1,2 @@ + +from numpy.oldnumeric.ma import * Modified: trunk/numpy/numarray/matrix.py =================================================================== --- trunk/numpy/numarray/matrix.py 2006-08-10 23:06:54 UTC (rev 2992) +++ trunk/numpy/numarray/matrix.py 2006-08-10 23:31:53 UTC (rev 2993) @@ -0,0 +1,8 @@ + +__all__ = ['Matrix'] + +from numpy import matrix as _matrix + +def Matrix(data, typecode=None, copy=1, savespace=0): + return _matrix(data, typecode, copy=copy) + Modified: trunk/numpy/numarray/mlab.py =================================================================== --- trunk/numpy/numarray/mlab.py 2006-08-10 23:06:54 UTC (rev 2992) +++ trunk/numpy/numarray/mlab.py 2006-08-10 23:31:53 UTC (rev 2993) @@ -0,0 +1,7 @@ + +from numpy.oldnumeric.mlab import * +import numpy.oldnumeric.mlab as nom + +__all__ = nom.__all__ + +del nom Modified: trunk/numpy/numarray/random_array.py =================================================================== --- trunk/numpy/numarray/random_array.py 2006-08-10 23:06:54 UTC (rev 2992) +++ trunk/numpy/numarray/random_array.py 2006-08-10 23:31:53 UTC (rev 2993) @@ -0,0 +1,9 @@ + +__all__ = ['ArgumentError', 'F', 'beta', 'binomial', 'chi_square', + 'exponential', 'gamma', 'get_seed', 'multinomial', + 'multivariate_normal', 'negative_binomial', 'noncentral_F', + 'noncentral_chi_square', 'normal', 'permutation', 'poisson', + 'randint', 'random', 'random_integers', 'standard_normal', + 'uniform', 'seed'] + +from numpy.oldnumeric.random_array import * From numpy-svn at scipy.org Thu Aug 10 21:58:49 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 20:58:49 -0500 (CDT) Subject: [Numpy-svn] r2994 - trunk/numpy/core Message-ID: <20060811015849.9B6A939C03A@new.scipy.org> Author: oliphant Date: 2006-08-10 20:58:47 -0500 (Thu, 10 Aug 2006) New Revision: 2994 Modified: trunk/numpy/core/defchararray.py Log: Fix silly mistake in chararray. Modified: trunk/numpy/core/defchararray.py =================================================================== --- trunk/numpy/core/defchararray.py 2006-08-10 23:31:53 UTC (rev 2993) +++ trunk/numpy/core/defchararray.py 2006-08-11 01:58:47 UTC (rev 2994) @@ -45,6 +45,7 @@ val = ndarray.__getitem__(self, obj) if isinstance(val, (string_, unicode_)): return val.rstrip() + return val def __add__(self, other): b = broadcast(self, other) From numpy-svn at scipy.org Thu Aug 10 22:12:24 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 10 Aug 2006 21:12:24 -0500 (CDT) Subject: [Numpy-svn] r2995 - trunk/numpy/core Message-ID: <20060811021224.6FB0839C083@new.scipy.org> Author: oliphant Date: 2006-08-10 21:12:22 -0500 (Thu, 10 Aug 2006) New Revision: 2995 Modified: trunk/numpy/core/records.py Log: Fix record class so that it returns chararrays and record arrays as needed as well. Modified: trunk/numpy/core/records.py =================================================================== --- trunk/numpy/core/records.py 2006-08-11 01:58:47 UTC (rev 2994) +++ trunk/numpy/core/records.py 2006-08-11 02:12:22 UTC (rev 2995) @@ -122,8 +122,16 @@ pass fielddict = nt.void.__getattribute__(self, 'dtype').fields res = fielddict.get(attr,None) - if res: - return self.getfield(*res[:2]) + if res: + obj = self.getfield(*res[:2]) + # if it has fields return a recarray, + # if it's a string return 'SU' return a chararray + # otherwise return a normal array + if obj.dtype.fields: + return obj.view(recarray) + if obj.dtype.char in 'SU': + return obj.view(chararray) + return obj else: raise AttributeError, "'record' object has no "\ "attribute '%s'" % attr From numpy-svn at scipy.org Fri Aug 11 03:09:39 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 11 Aug 2006 02:09:39 -0500 (CDT) Subject: [Numpy-svn] r2996 - trunk/numpy/core/src Message-ID: <20060811070939.DCE3739C01A@new.scipy.org> Author: oliphant Date: 2006-08-11 02:09:36 -0500 (Fri, 11 Aug 2006) New Revision: 2996 Modified: trunk/numpy/core/src/arrayobject.c Log: Rework meaning of isnative so it takes into account the fields. Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-11 02:12:22 UTC (rev 2995) +++ trunk/numpy/core/src/arrayobject.c 2006-08-11 07:09:36 UTC (rev 2996) @@ -10367,12 +10367,39 @@ 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, 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 Py_True if this data-type descriptor + has native byteorder if no fields are defined + + or if all sub-fields have native-byteorder if + fields are defined +*/ static PyObject * arraydescr_isnative_get(PyArray_Descr *self) { PyObject *ret; - - ret = (PyArray_ISNBO(self->byteorder) ? Py_True : Py_False); + int retval; + retval = _arraydescr_isnative(self); + if (retval == -1) return NULL; + ret = (retval ? Py_True : Py_False); Py_INCREF(ret); return ret; } From numpy-svn at scipy.org Fri Aug 11 16:16:45 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 11 Aug 2006 15:16:45 -0500 (CDT) Subject: [Numpy-svn] r2997 - trunk/numpy/core/src Message-ID: <20060811201645.E5C4C39C01E@new.scipy.org> Author: oliphant Date: 2006-08-11 15:16:43 -0500 (Fri, 11 Aug 2006) New Revision: 2997 Modified: trunk/numpy/core/src/arraymethods.c Log: Allow .astype method to work on data-types with fields. Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-11 07:09:36 UTC (rev 2996) +++ trunk/numpy/core/src/arraymethods.c 2006-08-11 20:16:43 UTC (rev 2997) @@ -530,6 +530,9 @@ Py_XDECREF(descr); return obj; } + if (descr->names != NULL) { + return PyArray_FromArray(self, descr, 0); + } return _ARET(PyArray_CastToType(self, descr, 0)); } From numpy-svn at scipy.org Fri Aug 11 16:46:40 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 11 Aug 2006 15:46:40 -0500 (CDT) Subject: [Numpy-svn] r2998 - trunk/numpy/core/src Message-ID: <20060811204640.B573D39C01E@new.scipy.org> Author: oliphant Date: 2006-08-11 15:46:36 -0500 (Fri, 11 Aug 2006) New Revision: 2998 Modified: trunk/numpy/core/src/arraymethods.c trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/multiarraymodule.c Log: Check for errors when casting from non-number types. Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-11 20:16:43 UTC (rev 2997) +++ trunk/numpy/core/src/arraymethods.c 2006-08-11 20:46:36 UTC (rev 2998) @@ -531,7 +531,7 @@ return obj; } if (descr->names != NULL) { - return PyArray_FromArray(self, descr, 0); + return PyArray_FromArray(self, descr, NPY_FORCECAST); } return _ARET(PyArray_CastToType(self, descr, 0)); } Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-11 20:16:43 UTC (rev 2997) +++ trunk/numpy/core/src/arrayobject.c 2006-08-11 20:46:36 UTC (rev 2998) @@ -7301,6 +7301,7 @@ } _pya_free(buffers[0]); _pya_free(buffers[1]); + if (!PyArray_ISNUMBER(in) && PyErr_Occurred()) return -1; return 0; } @@ -7354,7 +7355,7 @@ if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) { NPY_END_THREADS } #endif - return 0; + if (!PyArray_ISNUMBER(mp) && PyErr_Occurred()) return -1; } /* If the input or output is STRING, UNICODE, or VOID */ @@ -8209,8 +8210,9 @@ obj = PyArray_FromAny(op, descr, min_depth, max_depth, requires, context); + if (obj == NULL) return NULL; if ((requires & ELEMENTSTRIDES) && - (obj && !PyArray_ElementStrides(obj))) { + !PyArray_ElementStrides(obj)) { PyObject *new; new = PyArray_NewCopy((PyArrayObject *)obj, PyArray_ANYORDER); Py_DECREF(obj); Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-11 20:16:43 UTC (rev 2997) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-11 20:46:36 UTC (rev 2998) @@ -5013,8 +5013,7 @@ flags |= ENSUREARRAY; } - if ((ret = PyArray_CheckFromAny(op, type, 0, 0, flags, NULL)) == NULL) - return NULL; + ret = PyArray_CheckFromAny(op, type, 0, 0, flags, NULL); finish: if (!ret || (nd=PyArray_NDIM(ret)) >= ndmin) return ret; From numpy-svn at scipy.org Fri Aug 11 18:15:00 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 11 Aug 2006 17:15:00 -0500 (CDT) Subject: [Numpy-svn] r2999 - trunk/numpy/core/src Message-ID: <20060811221500.3BAEC39C0EB@new.scipy.org> Author: oliphant Date: 2006-08-11 17:14:56 -0500 (Fri, 11 Aug 2006) New Revision: 2999 Modified: trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/scalartypes.inc.src Log: Some fixes to array interface on Numpy side --- make sure descr pointer is NULL if not used and XDECREF it on interface free. Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-11 20:46:36 UTC (rev 2998) +++ trunk/numpy/core/src/arrayobject.c 2006-08-11 22:14:56 UTC (rev 2999) @@ -6087,6 +6087,7 @@ 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; @@ -6100,6 +6101,10 @@ */ 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); @@ -6114,6 +6119,7 @@ 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); } Modified: trunk/numpy/core/src/scalartypes.inc.src =================================================================== --- trunk/numpy/core/src/scalartypes.inc.src 2006-08-11 20:46:36 UTC (rev 2998) +++ trunk/numpy/core/src/scalartypes.inc.src 2006-08-11 22:14:56 UTC (rev 2999) @@ -730,11 +730,11 @@ static void gentype_struct_free(void *ptr, void *arg) { + PyArrayInterface *arrif = (PyArrayInterface *)ptr; Py_DECREF((PyObject *)arg); - if (((PyArrayInterface *)ptr)->shape != NULL) { - _pya_free(((PyArrayInterface *)ptr)->shape); - } - _pya_free(ptr); + Py_XDECREF(arrif->descr); + _pya_free(arrif->shape); + _pya_free(arrif); } static PyObject * @@ -753,6 +753,7 @@ inter->strides = NULL; inter->shape = NULL; inter->data = arr->data; + inter->descr = NULL; return PyCObject_FromVoidPtrAndDesc(inter, arr, gentype_struct_free); } From numpy-svn at scipy.org Sat Aug 12 14:27:07 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 12 Aug 2006 13:27:07 -0500 (CDT) Subject: [Numpy-svn] r3000 - trunk/numpy/core Message-ID: <20060812182707.F178239C00F@new.scipy.org> Author: cookedm Date: 2006-08-12 13:27:04 -0500 (Sat, 12 Aug 2006) New Revision: 3000 Modified: trunk/numpy/core/setup.py Log: numpy.core.setup: remove forgotten kws_args Modified: trunk/numpy/core/setup.py =================================================================== --- trunk/numpy/core/setup.py 2006-08-11 22:14:56 UTC (rev 2999) +++ trunk/numpy/core/setup.py 2006-08-12 18:27:04 UTC (rev 3000) @@ -99,7 +99,6 @@ moredefs.append(defsymbol) if sys.version[:3] < '2.4': - kws_args['headers'].append('stdlib.h') if check_func('strtod'): moredefs.append(('PyOS_ascii_strtod', 'strtod')) From numpy-svn at scipy.org Sat Aug 12 17:57:08 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 12 Aug 2006 16:57:08 -0500 (CDT) Subject: [Numpy-svn] r3001 - trunk/numpy/core/tests Message-ID: <20060812215708.C8CC939C058@new.scipy.org> Author: stefan Date: 2006-08-12 16:57:03 -0500 (Sat, 12 Aug 2006) New Revision: 3001 Modified: trunk/numpy/core/tests/test_regression.py Log: Add test for object array creation. Modified: trunk/numpy/core/tests/test_regression.py =================================================================== --- trunk/numpy/core/tests/test_regression.py 2006-08-12 18:27:04 UTC (rev 3000) +++ trunk/numpy/core/tests/test_regression.py 2006-08-12 21:57:03 UTC (rev 3001) @@ -338,6 +338,15 @@ x[0] = 'a ' x = x.rstrip() assert_equal(x[0], 'a') + + def check_object_array_shape(self,level=rlevel): + """Ticket #239""" + assert_equal(N.array([[1,2],3,4],dtype=object).shape, (3,)) + assert_equal(N.array([[1,2],[3,4]],dtype=object).shape, (2,2)) + #assert_equal(N.array([(1,2),(3,4)],dtype=object).shape, (2,)) + assert_equal(N.array([],dtype=object).shape, ()) + assert_equal(N.array([[],[],[]],dtype=object).shape, (3,)) + assert_equal(N.array([[3,4],[5,6],None],dtype=object).shape, (3,)) if __name__ == "__main__": NumpyTest().run() From numpy-svn at scipy.org Sat Aug 12 18:00:59 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 12 Aug 2006 17:00:59 -0500 (CDT) Subject: [Numpy-svn] r3002 - trunk/numpy/core/tests Message-ID: <20060812220059.F2CA739C058@new.scipy.org> Author: stefan Date: 2006-08-12 17:00:55 -0500 (Sat, 12 Aug 2006) New Revision: 3002 Modified: trunk/numpy/core/tests/test_regression.py Log: Minor change in test for ticket #239. Modified: trunk/numpy/core/tests/test_regression.py =================================================================== --- trunk/numpy/core/tests/test_regression.py 2006-08-12 21:57:03 UTC (rev 3001) +++ trunk/numpy/core/tests/test_regression.py 2006-08-12 22:00:55 UTC (rev 3002) @@ -343,7 +343,7 @@ """Ticket #239""" assert_equal(N.array([[1,2],3,4],dtype=object).shape, (3,)) assert_equal(N.array([[1,2],[3,4]],dtype=object).shape, (2,2)) - #assert_equal(N.array([(1,2),(3,4)],dtype=object).shape, (2,)) + assert_equal(N.array([(1,2),(3,4)],dtype=object).shape, (2,2)) assert_equal(N.array([],dtype=object).shape, ()) assert_equal(N.array([[],[],[]],dtype=object).shape, (3,)) assert_equal(N.array([[3,4],[5,6],None],dtype=object).shape, (3,)) From numpy-svn at scipy.org Sun Aug 13 03:15:59 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 13 Aug 2006 02:15:59 -0500 (CDT) Subject: [Numpy-svn] r3003 - in trunk/numpy: core core/tests lib numarray oldnumeric Message-ID: <20060813071559.33B8D39C077@new.scipy.org> Author: oliphant Date: 2006-08-13 02:15:52 -0500 (Sun, 13 Aug 2006) New Revision: 3003 Modified: trunk/numpy/core/ma.py trunk/numpy/core/tests/test_ma.py trunk/numpy/lib/function_base.py trunk/numpy/numarray/functions.py trunk/numpy/oldnumeric/functions.py trunk/numpy/oldnumeric/ma.py trunk/numpy/oldnumeric/misc.py Log: Change default axis argument of average and several masked array functions. Move old behaviors to compatibility layer. Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-12 22:00:55 UTC (rev 3002) +++ trunk/numpy/core/ma.py 2006-08-13 07:15:52 UTC (rev 3003) @@ -448,7 +448,7 @@ """returns the indices of the elements of a which are not zero and not masked """ - return asarray(filled(a, 0).nonzero()) + return numeric.asarray(filled(a, 0).nonzero()) around = masked_unary_operation(fromnumeric.round_) floor = masked_unary_operation(umath.floor) @@ -1532,7 +1532,7 @@ result.set_fill_value(get_fill_value(a)) return result -def repeat(a, repeats, axis=0): +def repeat(a, repeats, axis=None): """repeat elements of a repeats times along axis repeats is a sequence of length a.shape[axis] telling how many times to repeat each element. @@ -1603,8 +1603,8 @@ sum = add.reduce product = multiply.reduce -def average (a, axis=0, weights=None, returned = 0): - """average(a, axis=0, weights=None) +def average (a, axis=None, weights=None, returned = 0): + """average(a, axis=None, weights=None) Computes average along indicated axis. If axis is None, average over the entire array Inputs can be integer or floating types; result is of type float. @@ -1858,7 +1858,7 @@ mask=numeric.swapaxes(m, axis1, axis2),) -def take (a, indices, axis=0, out=None, mode='raise'): +def take (a, indices, axis=None, out=None, mode='raise'): "returns selection of items from a." m = getmask(a) # d = masked_array(a).raw_data() @@ -2168,14 +2168,14 @@ array.conj = array.conjugate = _m(conjugate) array.copy = _m(not_implemented) -def _cumprod(self, axis=0, dtype=None, out=None): +def _cumprod(self, axis=None, dtype=None, out=None): m = self.mask if m is not nomask: m = umath.logical_or.accumulate(self.mask, axis) return MaskedArray(data = self.filled(1).cumprod(axis, dtype), mask=m) array.cumprod = _m(_cumprod) -def _cumsum(self, axis=0, dtype=None, out=None): +def _cumsum(self, axis=None, dtype=None, out=None): m = self.mask if m is not nomask: m = umath.logical_or.accumulate(self.mask, axis) @@ -2214,7 +2214,7 @@ array.nonzero = _m(nonzero) array.prod = _m(product) -def _ptp(a,axis=0,out=None): +def _ptp(a,axis=None,out=None): return a.max(axis,out)-a.min(axis) array.ptp = _m(_ptp) array.repeat = _m(repeat) @@ -2244,15 +2244,15 @@ array.trace = _m(trace) array.transpose = _m(transpose) -def _var(self,axis=0,dtype=None, out=None): +def _var(self,axis=None,dtype=None, out=None): if axis is None: - return asarray(self.compressed()).var() + return numeric.asarray(self.compressed()).var() a = self.swapaxes(axis,0) a = a - a.mean(axis=0) a *= a a /= a.count(axis=0) return a.swapaxes(0,axis).sum(axis) -def _std(self,axis=0,dtype=None, out=None): +def _std(self,axis=None, dtype=None, out=None): return (self.var(axis,dtype))**0.5 array.var = _m(_var) array.std = _m(_std) Modified: trunk/numpy/core/tests/test_ma.py =================================================================== --- trunk/numpy/core/tests/test_ma.py 2006-08-12 22:00:55 UTC (rev 3002) +++ trunk/numpy/core/tests/test_ma.py 2006-08-13 07:15:52 UTC (rev 3003) @@ -267,9 +267,9 @@ y4 = resize(x4, (8,)) self.failUnless( eq(concatenate([x4,x4]), y4)) self.failUnless( eq(getmask(y4),[0,0,1,0,0,0,1,0])) - y5 = repeat(x4, (2,2,2,2)) + y5 = repeat(x4, (2,2,2,2), axis=0) self.failUnless( eq(y5, [0,0,1,1,2,2,3,3])) - y6 = repeat(x4, 2) + y6 = repeat(x4, 2, axis=0) self.failUnless( eq(y5, y6)) def check_testPut(self): @@ -523,10 +523,10 @@ ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) ott=ott.reshape(2,2) ott[:,1] = masked - self.failUnless(eq(average(ott), [2.0, 0.0])) + self.failUnless(eq(average(ott,axis=0), [2.0, 0.0])) self.failUnless(average(ott,axis=1)[0] is masked) - self.failUnless(eq([2.,0.], average(ott))) - result, wts = average(ott, returned=1) + self.failUnless(eq([2.,0.], average(ott, axis=0))) + result, wts = average(ott, axis=0, returned=1) self.failUnless(eq(wts, [1., 0.])) def check_testAverage2(self): @@ -534,8 +534,8 @@ w1 = [0,1,1,1,1,0] w2 = [[0,1,1,1,1,0],[1,0,0,0,0,1]] x=arange(6) - self.failUnless(allclose(average(x), 2.5)) - self.failUnless(allclose(average(x, weights=w1), 2.5)) + self.failUnless(allclose(average(x, axis=0), 2.5)) + self.failUnless(allclose(average(x, axis=0, weights=w1), 2.5)) y=array([arange(6), 2.0*arange(6)]) self.failUnless(allclose(average(y, None), numpy.add.reduce(numpy.arange(6))*3./12.)) self.failUnless(allclose(average(y, axis=0), numpy.arange(6) * 3./2.)) @@ -557,7 +557,7 @@ self.failUnless(allclose(average(z, None), 20./6.)) self.failUnless(allclose(average(z, axis=0), [0.,1.,99.,99.,4.0, 7.5])) self.failUnless(allclose(average(z, axis=1), [2.5, 5.0])) - self.failUnless(allclose( average(z,weights=w2), [0.,1., 99., 99., 4.0, 10.0])) + self.failUnless(allclose( average(z,axis=0, weights=w2), [0.,1., 99., 99., 4.0, 10.0])) a = arange(6) b = arange(6) * 3 @@ -572,9 +572,9 @@ self.failUnless(shape(w2) == shape(r2)) a2d = array([[1,2],[0,4]], float) a2dm = masked_array(a2d, [[0,0],[1,0]]) - a2da = average(a2d) + a2da = average(a2d, axis=0) self.failUnless(eq (a2da, [0.5, 3.0])) - a2dma = average(a2dm) + a2dma = average(a2dm, axis=0) self.failUnless(eq( a2dma, [1.0, 3.0])) a2dma = average(a2dm, axis=None) self.failUnless(eq(a2dma, 7./3.)) Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-12 22:00:55 UTC (rev 3002) +++ trunk/numpy/lib/function_base.py 2006-08-13 07:15:52 UTC (rev 3003) @@ -1,4 +1,3 @@ - __all__ = ['logspace', 'linspace', 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', #'base_repr', 'binary_repr', @@ -100,8 +99,8 @@ else: return n, bins -def average(a, axis=0, weights=None, returned=False): - """average(a, axis=0, weights=None, returned=False) +def average(a, axis=None, weights=None, returned=False): + """average(a, axis=None weights=None, returned=False) Average the array over the given axis. If the axis is None, average over all dimensions of the array. Equivalent to a.mean(axis), but Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-12 22:00:55 UTC (rev 3002) +++ trunk/numpy/numarray/functions.py 2006-08-13 07:15:52 UTC (rev 3003) @@ -42,7 +42,7 @@ from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\ allclose, any, around, argsort, array_equal, array_equiv,\ - array_str, array_repr, average, CLIP, RAISE, WRAP, clip, concatenate, \ + array_str, array_repr, CLIP, RAISE, WRAP, clip, concatenate, \ diagonal, e, pi, fromfunction, indices, inner as innerproduct, nonzero, \ outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \ resize, searchsorted, shape, size, sort, swapaxes, trace, transpose @@ -453,3 +453,6 @@ def togglebyteorder(self): self.dtype=self.dtype.newbyteorder() + +def average(a, axis=0, weights=None, returned=0): + return N.average(a, axis, weights, returned) Modified: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-12 22:00:55 UTC (rev 3002) +++ trunk/numpy/oldnumeric/functions.py 2006-08-13 07:15:52 UTC (rev 3003) @@ -9,7 +9,8 @@ 'cumsum', 'cumproduct', 'compress', 'ones', 'empty', 'identity', 'zeros', 'array', 'asarray', 'nonzero', 'reshape', 'arange', 'fromstring', 'ravel', 'trace', - 'indices', 'where','sarray','cross_product', 'argmax', 'argmin'] + 'indices', 'where','sarray','cross_product', 'argmax', 'argmin', + 'average'] def take(a, indicies, axis=0): return N.take(a, indicies, axis) @@ -115,3 +116,6 @@ def cross_product(a, b, axis1=-1, axis2=-1): return N.cross(a, b, axis1, axis2) + +def average(a, axis=0, weights=None, returned=False): + return N.average(a, axis, weights, returned) Modified: trunk/numpy/oldnumeric/ma.py =================================================================== --- trunk/numpy/oldnumeric/ma.py 2006-08-12 22:00:55 UTC (rev 3002) +++ trunk/numpy/oldnumeric/ma.py 2006-08-13 07:15:52 UTC (rev 3003) @@ -2,4 +2,14 @@ # instead of None from numpy.core.ma import * +import numpy.core.ma as nca +def repeat(a, repeats, axis=0): + return nca.repeat(a, repeats, axis) + +def average(a, axis=0, weights=None, returned=0): + return nca.average(a, axis, weights, returned) + +def take(a, indices, axis=0): + return nca.average(a, indices, axis=0) + Modified: trunk/numpy/oldnumeric/misc.py =================================================================== --- trunk/numpy/oldnumeric/misc.py 2006-08-12 22:00:55 UTC (rev 3002) +++ trunk/numpy/oldnumeric/misc.py 2006-08-13 07:15:52 UTC (rev 3003) @@ -7,7 +7,7 @@ 'pi', 'math', 'concatenate', 'around', 'vdot', 'transpose', 'array2string', 'diagonal', 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', - 'array_repr', 'e', 'StringIO', 'pickle', 'average', + 'array_repr', 'e', 'StringIO', 'pickle', 'argsort', 'convolve', 'loads', 'cross_correlate', 'Pickler', 'dot', 'outerproduct', 'innerproduct'] @@ -22,7 +22,7 @@ from numpy import sort, clip, putmask, rank, sign, shape, allclose, size,\ choose, swapaxes, array_str, array_repr, e, pi, \ fromfunction, resize, around, concatenate, vdot, transpose, \ - diagonal, searchsorted, put, average, argsort, convolve, dot, \ + diagonal, searchsorted, put, argsort, convolve, dot, \ outer as outerproduct, inner as innerproduct, correlate as cross_correlate from array_printer import array2string From numpy-svn at scipy.org Sun Aug 13 03:24:00 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 13 Aug 2006 02:24:00 -0500 (CDT) Subject: [Numpy-svn] r3004 - trunk/numpy/core/src Message-ID: <20060813072400.929C139C080@new.scipy.org> Author: oliphant Date: 2006-08-13 02:23:58 -0500 (Sun, 13 Aug 2006) New Revision: 3004 Modified: trunk/numpy/core/src/multiarraymodule.c Log: Fix ticket #243 Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-13 07:15:52 UTC (rev 3003) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-13 07:23:58 UTC (rev 3004) @@ -295,6 +295,7 @@ 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); @@ -308,6 +309,7 @@ finish: Py_DECREF(f); + Py_DECREF(out); return ret; } From numpy-svn at scipy.org Sun Aug 13 05:04:44 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 13 Aug 2006 04:04:44 -0500 (CDT) Subject: [Numpy-svn] r3005 - in trunk/numpy: core core/src lib Message-ID: <20060813090444.818A639C033@new.scipy.org> Author: oliphant Date: 2006-08-13 04:04:39 -0500 (Sun, 13 Aug 2006) New Revision: 3005 Modified: trunk/numpy/core/_internal.py trunk/numpy/core/src/arrayobject.c trunk/numpy/lib/utils.py Log: Remove _as_parameter_ attribute from arrays and add it to the ctypes object. Create an ndpointer class factory to return classes that check for specific array types. These can be used in argtypes list to ctypes functions. Modified: trunk/numpy/core/_internal.py =================================================================== --- trunk/numpy/core/_internal.py 2006-08-13 07:23:58 UTC (rev 3004) +++ trunk/numpy/core/_internal.py 2006-08-13 09:04:39 UTC (rev 3005) @@ -208,21 +208,30 @@ _getintp_ctype.cache = None # Used for .ctypes attribute of ndarray + +class _missing_ctypes(object): + def cast(self, num, obj): + return num + + def c_void_p(self, num): + return num + class _ctypes(object): - def __init__(self, array): + def __init__(self, array, ptr=None): try: import ctypes self._ctypes = ctypes except ImportError: - raise AttributeError, "ctypes not available" + self._ctypes = _missing_ctypes() self._arr = array + self._data = ptr if self._arr.ndim == 0: self._zerod = True else: self._zerod = False def data_as(self, obj): - return self._ctypes.cast(self._arr._as_parameter_, obj) + return self._ctypes.cast(self._data, obj) def shape_as(self, obj): if self._zerod: @@ -235,7 +244,7 @@ return (obj*self._arr.ndim)(*self._arr.strides) def get_data(self): - return self._ctypes.c_void_p(self._arr._as_parameter_) + return self._ctypes.c_void_p(self._data) def get_shape(self): if self._zerod: @@ -246,7 +255,11 @@ if self._zerod: return None return (_getintp_ctype()*self._arr.ndim)(*self._arr.strides) - + + def get_as_parameter(self): + return self._data + data = property(get_data, None, doc="c-types data") shape = property(get_shape, None, doc="c-types shape") strides = property(get_strides, None, doc="c-types strides") + _as_parameter_ = property(get_as_parameter, None, doc="_as parameter_") Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-13 07:23:58 UTC (rev 3004) +++ trunk/numpy/core/src/arrayobject.c 2006-08-13 09:04:39 UTC (rev 3005) @@ -5829,16 +5829,11 @@ array_ctypes_get(PyArrayObject *self) { return PyObject_CallMethod(_numpy_internal, "_ctypes", - "O", self); + "ON", self, + PyLong_FromVoidPtr(self->data)); } static PyObject * -array_as_parameter_get(PyArrayObject *self) -{ - return PyLong_FromVoidPtr(self->data); -} - -static PyObject * array_interface_get(PyArrayObject *self) { PyObject *dict; @@ -6413,9 +6408,6 @@ {"ctypes", (getter)array_ctypes_get, NULL, NULL}, - {"_as_parameter_", - (getter)array_as_parameter_get, - NULL, NULL}, {"T", (getter)array_transpose_get, NULL, NULL}, @@ -11062,11 +11054,11 @@ (reprfunc)arraydescr_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ - &descr_as_mapping, /* tp_as_mapping */ - 0, /* tp_hash */ + &descr_as_mapping, /* tp_as_mapping */ + (hashfunc)_Py_HashPointer, /* tp_hash */ 0, /* tp_call */ - (reprfunc)arraydescr_str, /* tp_str */ - 0, /* tp_getattro */ + (reprfunc)arraydescr_str, /* tp_str */ + 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ @@ -11075,8 +11067,8 @@ 0, /* tp_clear */ (richcmpfunc)arraydescr_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ + 0, /* tp_iter */ + 0, /* tp_iternext */ arraydescr_methods, /* tp_methods */ arraydescr_members, /* tp_members */ arraydescr_getsets, /* tp_getset */ Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-13 07:23:58 UTC (rev 3004) +++ trunk/numpy/lib/utils.py 2006-08-13 09:04:39 UTC (rev 3005) @@ -7,8 +7,8 @@ __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', 'issubdtype', 'deprecate', 'get_numarray_include', - 'get_include', 'ctypes_load_library', 'info', - 'source', 'who'] + 'get_include', 'ctypes_load_library', 'ndpointer', + 'info', 'source', 'who'] def issubclass_(arg1, arg2): try: @@ -76,7 +76,33 @@ libpath = os.path.join(libdir, libname) return ctypes.cdll[libpath] +class _ndptr(object): + def from_param(cls, obj): + if not isinstance(obj, ndarray): + raise TypeError("argument must be an ndarray") + if obj.dtype != cls._dtype_: + raise TypeError("array must have data type", cls._dtype_) + return obj.ctypes + from_param = classmethod(from_param) +# Factory for a type-checking object with from_param defined +_pointer_type_cache = {} +def ndpointer(datatype): + datatype = dtype(datatype) + try: + return _pointer_type_cache[datatype] + except KeyError: + pass + if datatype.names: + name = str(id(datatype)) + else: + name = datatype.str + klass = type("ndpointer_%s"%name, (_ndptr,), + {"_dtype_": datatype}) + _pointer_type_cache[datatype] = klass + return klass + + if sys.version_info < (2, 4): # Can't set __name__ in 2.3 import new From numpy-svn at scipy.org Sun Aug 13 06:03:15 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 13 Aug 2006 05:03:15 -0500 (CDT) Subject: [Numpy-svn] r3006 - trunk/numpy/lib Message-ID: <20060813100315.3FA7239C033@new.scipy.org> Author: oliphant Date: 2006-08-13 05:03:13 -0500 (Sun, 13 Aug 2006) New Revision: 3006 Modified: trunk/numpy/lib/utils.py Log: Improve ndpointer to allow shape and flags checking as well. Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-13 09:04:39 UTC (rev 3005) +++ trunk/numpy/lib/utils.py 2006-08-13 10:03:13 UTC (rev 3006) @@ -1,8 +1,8 @@ import sys, os import inspect import types -from numpy.core.numerictypes import obj2sctype -from numpy.core.multiarray import dtype +from numpy.core.numerictypes import obj2sctype, integer +from numpy.core.multiarray import dtype, _flagdict from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', @@ -76,30 +76,77 @@ libpath = os.path.join(libdir, libname) return ctypes.cdll[libpath] +def _num_fromflags(flaglist): + num = 0 + for val in flaglist: + num += _flagdict[val] + return num + +def _flags_fromnum(num): + res = [] + for key, value in _flagdict.items(): + if (num & value): + res.append(key) + return res + class _ndptr(object): def from_param(cls, obj): if not isinstance(obj, ndarray): raise TypeError("argument must be an ndarray") if obj.dtype != cls._dtype_: raise TypeError("array must have data type", cls._dtype_) + if cls._ndim_ and obj.ndim != cls._ndim_: + raise TypeError("array must have %d dimension(s)" % cls._ndim_) + if cls._shape_ and obj.shape != cls._shape_: + raise TypeError("array must have shape ", cls._shape_) + if cls._flags_ and ((obj.flags.num & cls._flags_) != cls._flags_): + raise TypeError("array must have flags ", + _flags_fromnum(cls._flags_)) return obj.ctypes from_param = classmethod(from_param) -# Factory for a type-checking object with from_param defined +# Factory for an array-checking object with from_param defined _pointer_type_cache = {} -def ndpointer(datatype): +def ndpointer(datatype, ndim=None, shape=None, flags=None): datatype = dtype(datatype) + num = None + if flags is not None: + if isinstance(flags, str): + flags = flags.split(',') + elif isinstance(flags, (int, integer)): + num = flags + flags = _flags_fromnum(flags) + if num is None: + flags = [x.strip().upper() for x in flags] + num = _num_fromflags(flags) try: - return _pointer_type_cache[datatype] + return _pointer_type_cache[(datatype, ndim, shape, num)] except KeyError: - pass + pass if datatype.names: name = str(id(datatype)) else: name = datatype.str + if ndim is not None: + name += "_%dd" % ndim + if shape is not None: + try: + strshape = [str(x) for x in shape] + except TypeError: + strshape = [str(shape)] + shape = (shape,) + shape = tuple(shape) + name += "_"+"x".join(strshape) + if flags is not None: + name += "_"+"_".join(flags) + else: + flags = [] klass = type("ndpointer_%s"%name, (_ndptr,), - {"_dtype_": datatype}) - _pointer_type_cache[datatype] = klass + {"_dtype_": datatype, + "_shape_" : shape, + "_ndim_" : ndim, + "_flags_" : num}) + _pointer_type_cache[datatype] = klass return klass From numpy-svn at scipy.org Sun Aug 13 06:06:50 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 13 Aug 2006 05:06:50 -0500 (CDT) Subject: [Numpy-svn] r3007 - trunk/numpy/lib Message-ID: <20060813100650.37BE439C033@new.scipy.org> Author: oliphant Date: 2006-08-13 05:06:48 -0500 (Sun, 13 Aug 2006) New Revision: 3007 Modified: trunk/numpy/lib/utils.py Log: Allow for type-less ndpointer. Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-13 10:03:13 UTC (rev 3006) +++ trunk/numpy/lib/utils.py 2006-08-13 10:06:48 UTC (rev 3007) @@ -93,7 +93,7 @@ def from_param(cls, obj): if not isinstance(obj, ndarray): raise TypeError("argument must be an ndarray") - if obj.dtype != cls._dtype_: + if cls._dtype_ and obj.dtype != cls._dtype_: raise TypeError("array must have data type", cls._dtype_) if cls._ndim_ and obj.ndim != cls._ndim_: raise TypeError("array must have %d dimension(s)" % cls._ndim_) @@ -107,8 +107,9 @@ # Factory for an array-checking object with from_param defined _pointer_type_cache = {} -def ndpointer(datatype, ndim=None, shape=None, flags=None): - datatype = dtype(datatype) +def ndpointer(datatype=None, ndim=None, shape=None, flags=None): + if datatype is not None: + datatype = dtype(datatype) num = None if flags is not None: if isinstance(flags, str): @@ -122,8 +123,10 @@ try: return _pointer_type_cache[(datatype, ndim, shape, num)] except KeyError: - pass - if datatype.names: + pass + if datatype is None: + name = 'any' + elif datatype.names: name = str(id(datatype)) else: name = datatype.str From numpy-svn at scipy.org Sun Aug 13 17:31:51 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 13 Aug 2006 16:31:51 -0500 (CDT) Subject: [Numpy-svn] r3008 - trunk/numpy/lib Message-ID: <20060813213151.1523339C0F1@new.scipy.org> Author: oliphant Date: 2006-08-13 16:31:47 -0500 (Sun, 13 Aug 2006) New Revision: 3008 Modified: trunk/numpy/lib/utils.py Log: datatype --> dtype in ndpointer and fix logic of from_param checks Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-13 10:06:48 UTC (rev 3007) +++ trunk/numpy/lib/utils.py 2006-08-13 21:31:47 UTC (rev 3008) @@ -2,7 +2,7 @@ import inspect import types from numpy.core.numerictypes import obj2sctype, integer -from numpy.core.multiarray import dtype, _flagdict +from numpy.core.multiarray import dtype as _dtype, _flagdict from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', @@ -20,7 +20,7 @@ return issubclass(obj2sctype(arg1), obj2sctype(arg2)) def issubdtype(arg1, arg2): - return issubclass(dtype(arg1).type, dtype(arg2).type) + return issubclass(_dtype(arg1).type, _dtype(arg2).type) def get_include(): """Return the directory in the package that contains the numpy/*.h header @@ -92,24 +92,29 @@ class _ndptr(object): def from_param(cls, obj): if not isinstance(obj, ndarray): - raise TypeError("argument must be an ndarray") - if cls._dtype_ and obj.dtype != cls._dtype_: - raise TypeError("array must have data type", cls._dtype_) - if cls._ndim_ and obj.ndim != cls._ndim_: - raise TypeError("array must have %d dimension(s)" % cls._ndim_) - if cls._shape_ and obj.shape != cls._shape_: - raise TypeError("array must have shape ", cls._shape_) - if cls._flags_ and ((obj.flags.num & cls._flags_) != cls._flags_): - raise TypeError("array must have flags ", - _flags_fromnum(cls._flags_)) + raise TypeError, "argument must be an ndarray" + if cls._dtype_ is not None \ + and obj.dtype != cls._dtype_: + raise TypeError, "array must have data type %s" % cls._dtype_ + if cls._ndim_ is not None \ + and obj.ndim != cls._ndim_: + raise TypeError, "array must have %d dimension(s)" % cls._ndim_ + if cls._shape_ is not None \ + and obj.shape != cls._shape_: + raise TypeError, "array must have shape %s" % cls._shape_ + if cls._flags_ is not None \ + and ((obj.flags.num & cls._flags_) != cls._flags_): + raise TypeError, "array must have flags %s" % \ + _flags_fromnum(cls._flags_) return obj.ctypes from_param = classmethod(from_param) -# Factory for an array-checking object with from_param defined +# Factory for an array-checking class with from_param defined for +# use with ctypes argtypes mechanism _pointer_type_cache = {} -def ndpointer(datatype=None, ndim=None, shape=None, flags=None): - if datatype is not None: - datatype = dtype(datatype) +def ndpointer(dtype=None, ndim=None, shape=None, flags=None): + if dtype is not None: + dtype = _dtype(dtype) num = None if flags is not None: if isinstance(flags, str): @@ -121,15 +126,15 @@ flags = [x.strip().upper() for x in flags] num = _num_fromflags(flags) try: - return _pointer_type_cache[(datatype, ndim, shape, num)] + return _pointer_type_cache[(dtype, ndim, shape, num)] except KeyError: pass - if datatype is None: + if dtype is None: name = 'any' - elif datatype.names: - name = str(id(datatype)) + elif dtype.names: + name = str(id(dtype)) else: - name = datatype.str + name = dtype.str if ndim is not None: name += "_%dd" % ndim if shape is not None: @@ -145,11 +150,11 @@ else: flags = [] klass = type("ndpointer_%s"%name, (_ndptr,), - {"_dtype_": datatype, + {"_dtype_": dtype, "_shape_" : shape, "_ndim_" : ndim, "_flags_" : num}) - _pointer_type_cache[datatype] = klass + _pointer_type_cache[dtype] = klass return klass From numpy-svn at scipy.org Sun Aug 13 19:08:45 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 13 Aug 2006 18:08:45 -0500 (CDT) Subject: [Numpy-svn] r3009 - trunk/numpy/oldnumeric Message-ID: <20060813230845.B4F4F39C0F3@new.scipy.org> Author: oliphant Date: 2006-08-13 18:08:42 -0500 (Sun, 13 Aug 2006) New Revision: 3009 Modified: trunk/numpy/oldnumeric/mlab.py Log: Restore numpy.oldnumeric.mlab.cov to MLab.cov behavior Modified: trunk/numpy/oldnumeric/mlab.py =================================================================== --- trunk/numpy/oldnumeric/mlab.py 2006-08-13 21:31:47 UTC (rev 3008) +++ trunk/numpy/oldnumeric/mlab.py 2006-08-13 23:08:42 UTC (rev 3009) @@ -8,7 +8,7 @@ angle, roots, ptp as _Nptp, kaiser, cumprod as _Ncumprod, \ diag, msort, prod as _Nprod, std as _Nstd, hamming, flipud, \ amax as _Nmax, amin as _Nmin, blackman, bartlett, corrcoef as _Ncorrcoef,\ - cov as _Ncov, squeeze, sinc, median, fliplr, mean as _Nmean + cov as _Ncov, squeeze, sinc, median, fliplr, mean as _Nmean, transpose from numpy.linalg import eig, svd from numpy.random import rand, randn @@ -59,11 +59,36 @@ def mean(x, axis=0): return _Nmean(x, axis) +# This is exactly the same cov function as in MLab def cov(m, y=None, rowvar=0, bias=0): - return _Ncov(m, y, rowvar, bias) + if y is None: + y = m + else: + y = y + if rowvar: + m = transpose(m) + y = transpose(y) + if (m.shape[0] == 1): + m = transpose(m) + if (y.shape[0] == 1): + y = transpose(y) + N = m.shape[0] + if (y.shape[0] != N): + raise ValueError, "x and y must have the same number "\ + "of observations" + m = m - _Nmean(m,axis=0) + y = y - _Nmean(y,axis=0) + if bias: + fact = N*1.0 + else: + fact = N-1.0 + return squeeze(dot(transpose(m), conjugate(y)) / fact) +from numpy import sqrt, multiply def corrcoef(x, y=None): - return _Ncorrcoef(x,y,0,0) + c = cov(x,y) + d = diag(c) + return c/sqrt(multiply.outer(d,d)) from compat import * from functions import * From numpy-svn at scipy.org Mon Aug 14 03:32:25 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 02:32:25 -0500 (CDT) Subject: [Numpy-svn] r3010 - trunk/numpy/oldnumeric Message-ID: <20060814073225.9737D39C042@new.scipy.org> Author: oliphant Date: 2006-08-14 02:32:22 -0500 (Mon, 14 Aug 2006) New Revision: 3010 Modified: trunk/numpy/oldnumeric/mlab.py Log: Remove un-needed functions. Modified: trunk/numpy/oldnumeric/mlab.py =================================================================== --- trunk/numpy/oldnumeric/mlab.py 2006-08-13 23:08:42 UTC (rev 3009) +++ trunk/numpy/oldnumeric/mlab.py 2006-08-14 07:32:22 UTC (rev 3010) @@ -7,8 +7,8 @@ from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \ angle, roots, ptp as _Nptp, kaiser, cumprod as _Ncumprod, \ diag, msort, prod as _Nprod, std as _Nstd, hamming, flipud, \ - amax as _Nmax, amin as _Nmin, blackman, bartlett, corrcoef as _Ncorrcoef,\ - cov as _Ncov, squeeze, sinc, median, fliplr, mean as _Nmean, transpose + amax as _Nmax, amin as _Nmin, blackman, bartlett, \ + squeeze, sinc, median, fliplr, mean as _Nmean, transpose from numpy.linalg import eig, svd from numpy.random import rand, randn From numpy-svn at scipy.org Mon Aug 14 03:33:20 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 02:33:20 -0500 (CDT) Subject: [Numpy-svn] r3011 - tags Message-ID: <20060814073320.C4E7E39C042@new.scipy.org> Author: oliphant Date: 2006-08-14 02:33:17 -0500 (Mon, 14 Aug 2006) New Revision: 3011 Added: tags/1.0b2/ Log: Tag tree for 1.0b2 release. Copied: tags/1.0b2 (from rev 3010, trunk) From numpy-svn at scipy.org Mon Aug 14 03:33:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 02:33:56 -0500 (CDT) Subject: [Numpy-svn] r3012 - trunk/numpy Message-ID: <20060814073356.D05BC39C042@new.scipy.org> Author: oliphant Date: 2006-08-14 02:33:54 -0500 (Mon, 14 Aug 2006) New Revision: 3012 Modified: trunk/numpy/version.py Log: Update version to 1.0b3 Modified: trunk/numpy/version.py =================================================================== --- trunk/numpy/version.py 2006-08-14 07:33:17 UTC (rev 3011) +++ trunk/numpy/version.py 2006-08-14 07:33:54 UTC (rev 3012) @@ -1,4 +1,4 @@ -version='1.0b2' +version='1.0b3' release=False if not release: From numpy-svn at scipy.org Mon Aug 14 03:34:34 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 02:34:34 -0500 (CDT) Subject: [Numpy-svn] r3013 - tags/1.0b2/numpy Message-ID: <20060814073434.1141C39C042@new.scipy.org> Author: oliphant Date: 2006-08-14 02:34:32 -0500 (Mon, 14 Aug 2006) New Revision: 3013 Modified: tags/1.0b2/numpy/version.py Log: Make it a release. Modified: tags/1.0b2/numpy/version.py =================================================================== --- tags/1.0b2/numpy/version.py 2006-08-14 07:33:54 UTC (rev 3012) +++ tags/1.0b2/numpy/version.py 2006-08-14 07:34:32 UTC (rev 3013) @@ -1,5 +1,5 @@ version='1.0b2' -release=False +release=True if not release: import os From numpy-svn at scipy.org Mon Aug 14 06:05:43 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 05:05:43 -0500 (CDT) Subject: [Numpy-svn] r3014 - in trunk/numpy: . core core/code_generators distutils distutils/command distutils/fcompiler f2py fft lib linalg numarray oldnumeric random testing Message-ID: <20060814100543.20BD539C101@new.scipy.org> Author: stefan Date: 2006-08-14 05:05:22 -0500 (Mon, 14 Aug 2006) New Revision: 3014 Modified: trunk/numpy/ trunk/numpy/core/ trunk/numpy/core/code_generators/ trunk/numpy/distutils/ trunk/numpy/distutils/command/ trunk/numpy/distutils/fcompiler/ trunk/numpy/f2py/ trunk/numpy/fft/ trunk/numpy/lib/ trunk/numpy/linalg/ trunk/numpy/numarray/ trunk/numpy/oldnumeric/ trunk/numpy/random/ trunk/numpy/testing/ Log: Ignore *.pyc files [for Albert Strasheim]. Property changes on: trunk/numpy ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/core ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/core/code_generators ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/distutils ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/distutils/command ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/distutils/fcompiler ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/f2py ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/fft ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/lib ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/linalg ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/numarray ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/oldnumeric ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/random ___________________________________________________________________ Name: svn:ignore + *.pyc Property changes on: trunk/numpy/testing ___________________________________________________________________ Name: svn:ignore + *.pyc From numpy-svn at scipy.org Mon Aug 14 06:11:02 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 05:11:02 -0500 (CDT) Subject: [Numpy-svn] r3015 - in trunk: . numpy/lib/tests Message-ID: <20060814101102.70C6A39C06D@new.scipy.org> Author: stefan Date: 2006-08-14 05:10:55 -0500 (Mon, 14 Aug 2006) New Revision: 3015 Modified: trunk/ trunk/numpy/lib/tests/ Log: Ignore build, dist, numpy.egg-info dirs [for Albert Strasheim]. Property changes on: trunk ___________________________________________________________________ Name: svn:ignore + dist build numpy.egg-info Property changes on: trunk/numpy/lib/tests ___________________________________________________________________ Name: svn:ignore + *.pyc From numpy-svn at scipy.org Mon Aug 14 16:01:25 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 15:01:25 -0500 (CDT) Subject: [Numpy-svn] r3016 - in trunk/numpy/core: . src Message-ID: <20060814200125.1A9FA39C045@new.scipy.org> Author: oliphant Date: 2006-08-14 15:01:12 -0500 (Mon, 14 Aug 2006) New Revision: 3016 Modified: trunk/numpy/core/defchararray.py trunk/numpy/core/numeric.py trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/multiarraymodule.c trunk/numpy/core/src/ufuncobject.c Log: Strip characters from chararrays during comparision Modified: trunk/numpy/core/defchararray.py =================================================================== --- trunk/numpy/core/defchararray.py 2006-08-14 10:10:55 UTC (rev 3015) +++ trunk/numpy/core/defchararray.py 2006-08-14 20:01:12 UTC (rev 3016) @@ -1,5 +1,5 @@ from numerictypes import string_, unicode_, integer, object_ -from numeric import ndarray, broadcast, empty +from numeric import ndarray, broadcast, empty, compare_chararrays from numeric import array as narray import sys @@ -12,7 +12,8 @@ # This adds + and * operations and methods of str and unicode types # which operate on an element-by-element basis -# It also strips white-space on element retrieval +# It also strips white-space on element retrieval and on +# comparisons class chararray(ndarray): def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, @@ -44,9 +45,31 @@ def __getitem__(self, obj): val = ndarray.__getitem__(self, obj) if isinstance(val, (string_, unicode_)): - return val.rstrip() + temp = val.rstrip() + if len(temp) == 0: + val = val[0] + else: + val = temp return val + def __eq__(self, other): + return compare_chararrays(self, other, '==', True) + + def __ne__(self, other): + return compare_chararrays(self, other, '!=', True) + + def __ge__(self, other): + return compare_chararrays(self, other, '>=', True) + + def __le__(self, other): + return compare_chararrays(self, other, '<=', True) + + def __gt__(self, other): + return compare_chararrays(self, other, '>', True) + + def __lt__(self, other): + return compare_chararrays(self, other, '<', True) + def __add__(self, other): b = broadcast(self, other) arr = b.iters[1].base Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-14 10:10:55 UTC (rev 3015) +++ trunk/numpy/core/numeric.py 2006-08-14 20:01:12 UTC (rev 3016) @@ -14,7 +14,7 @@ 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'load', 'loads', 'isscalar', 'binary_repr', 'base_repr', - 'ones', 'identity', 'allclose', + 'ones', 'identity', 'allclose', 'compare_chararrays', 'seterr', 'geterr', 'setbufsize', 'getbufsize', 'seterrcall', 'geterrcall', 'flatnonzero', 'Inf', 'inf', 'infty', 'Infinity', @@ -119,6 +119,7 @@ set_numeric_ops = multiarray.set_numeric_ops can_cast = multiarray.can_cast lexsort = multiarray.lexsort +compare_chararrays = multiarray.compare_chararrays def asarray(a, dtype=None, order=None): Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-14 10:10:55 UTC (rev 3015) +++ trunk/numpy/core/src/arrayobject.c 2006-08-14 20:01:12 UTC (rev 3016) @@ -4183,9 +4183,130 @@ return 0; } +/* Borrowed from Numarray */ + +#define SMALL_STRING 2048 + +#if defined(isspace) +#undef isspace +#define isspace(c) ((c==' ')||(c=='\t')||(c=='\n')||(c=='\r')||(c=='\v')||(c=='\f')) +#endif + +static void _rstripw(char *s, int n) +{ + int i; + for(i=strnlen(s,n)-1; i>=1; i--) /* Never strip to length 0. */ + { + 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. */ + { + PyArray_UCS4 c = s[i]; + if (!c || isspace(c)) + s[i] = 0; + else + break; + } +} + + +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; + } + } + memcpy(temp, original, nc); + _rstripw(temp, nc); + return temp; +} + +static void +_char_release(char *ptr, int nc) +{ + if (nc > SMALL_STRING) { + free(ptr); + } +} + +static char * +_uni_copy_n_strip(char *original, char *temp, int nc) +{ + if (nc*4 > SMALL_STRING) { + temp = malloc(nc); + if (!temp) { + PyErr_NoMemory(); + return NULL; + } + } + 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); + } +} + + +/* 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) \ + else _reg_loop(CMP) + static int _compare_strings(PyObject *result, PyArrayMultiIterObject *multi, - int cmp_op, void *func) + int cmp_op, void *func, int rstrip) { PyArrayIterObject *iself, *iother; Bool *dptr; @@ -4193,6 +4314,8 @@ 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); @@ -4204,43 +4327,48 @@ if ((void *)cmpfunc == (void *)_myunincmp) { N1 >>= 2; N2 >>= 2; + stripfunc = _uni_copy_n_strip; + relfunc = _uni_release; } - while(size--) { - val = cmpfunc((void *)iself->dataptr, (void *)iother->dataptr, - N1, N2); - switch (cmp_op) { - case Py_EQ: - *dptr = (val == 0); - break; - case Py_NE: - *dptr = (val != 0); - break; - case Py_LT: - *dptr = (val < 0); - break; - case Py_LE: - *dptr = (val <= 0); - break; - case Py_GT: - *dptr = (val > 0); - break; - case Py_GE: - *dptr = (val >= 0); - break; - default: - PyErr_SetString(PyExc_RuntimeError, - "bad comparison operator"); - return -1; - } - PyArray_ITER_NEXT(iself); - PyArray_ITER_NEXT(iother); - dptr += 1; + 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 +#undef _reg_loop +#undef _rstrip_loop +#undef SMALL_STRING + static PyObject * -_strings_richcompare(PyArrayObject *self, PyArrayObject *other, int cmp_op) +_strings_richcompare(PyArrayObject *self, PyArrayObject *other, int cmp_op, + int rstrip) { PyObject *result; PyArrayMultiIterObject *mit; @@ -4294,10 +4422,12 @@ if (result == NULL) goto finish; if (self->descr->type_num == PyArray_UNICODE) { - val = _compare_strings(result, mit, cmp_op, _myunincmp); + val = _compare_strings(result, mit, cmp_op, _myunincmp, + rstrip); } else { - val = _compare_strings(result, mit, cmp_op, _mystrncmp); + val = _compare_strings(result, mit, cmp_op, _mystrncmp, + rstrip); } if (val < 0) {Py_DECREF(result); result = NULL;} @@ -4361,7 +4491,7 @@ } else { /* compare as a string */ /* assumes self and other have same descr->type */ - return _strings_richcompare(self, other, cmp_op); + return _strings_richcompare(self, other, cmp_op, 0); } } @@ -4531,7 +4661,7 @@ if (PyArray_ISSTRING(self) && PyArray_ISSTRING(array_other)) { Py_DECREF(result); result = _strings_richcompare(self, (PyArrayObject *) - array_other, cmp_op); + array_other, cmp_op, 0); } Py_DECREF(array_other); } Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-14 10:10:55 UTC (rev 3015) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-14 20:01:12 UTC (rev 3016) @@ -6357,6 +6357,71 @@ return PyString_FromString(repr); } +static PyObject * +compare_chararrays(PyObject *dummy, PyObject *args, PyObject *kwds) +{ + PyObject *array; + PyObject *other; + PyArrayObject *newarr, *newoth; + int cmp_op; + Bool rstrip; + char *cmp_str; + Py_ssize_t strlen; + PyObject *res=NULL; + static char msg[] = \ + "comparision must be '==', '!=', '<', '>', '<=', '>='"; + + static char *kwlist[] = {"a1", "a2", "cmp", "rstrip", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOs#O&", kwlist, + &array, &other, + &cmp_str, &strlen, + PyArray_BoolConverter, &rstrip)) + 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; + } + else { + 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; + } + + if (PyArray_ISSTRING(newarr) && PyArray_ISSTRING(newoth)) { + res = _strings_richcompare(newarr, newoth, cmp_op, rstrip != 0); + } + else { + PyErr_SetString(PyExc_TypeError, + "comparison of non-string arrays"); + } + + Py_DECREF(newarr); + Py_DECREF(newoth); + return res; + + err: + PyErr_SetString(PyExc_ValueError, msg); + return NULL; +} + + + + static struct PyMethodDef array_module_methods[] = { {"_get_ndarray_c_version", (PyCFunction)array__get_ndarray_c_version, METH_VARARGS|METH_KEYWORDS, NULL}, @@ -6409,6 +6474,8 @@ 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}, {NULL, NULL, 0} /* sentinel */ }; Modified: trunk/numpy/core/src/ufuncobject.c =================================================================== --- trunk/numpy/core/src/ufuncobject.c 2006-08-14 10:10:55 UTC (rev 3015) +++ trunk/numpy/core/src/ufuncobject.c 2006-08-14 20:01:12 UTC (rev 3016) @@ -1761,7 +1761,7 @@ PyUFuncReduceObject *loop; PyArrayObject *idarr; PyArrayObject *aar; - intp loop_i[MAX_DIMS], outsize; + intp loop_i[MAX_DIMS], outsize=0; int arg_types[3] = {otype, otype, otype}; PyArray_SCALARKIND scalars[3] = {PyArray_NOSCALAR, PyArray_NOSCALAR, PyArray_NOSCALAR}; From numpy-svn at scipy.org Mon Aug 14 16:13:39 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 15:13:39 -0500 (CDT) Subject: [Numpy-svn] r3017 - in trunk/numpy/lib: . tests Message-ID: <20060814201339.7343839C045@new.scipy.org> Author: oliphant Date: 2006-08-14 15:13:33 -0500 (Mon, 14 Aug 2006) New Revision: 3017 Added: trunk/numpy/lib/tests/test_utils.py Modified: trunk/numpy/lib/utils.py Log: Fix ndpointer and add tests from ticket #245 Added: trunk/numpy/lib/tests/test_utils.py =================================================================== --- trunk/numpy/lib/tests/test_utils.py 2006-08-14 20:01:12 UTC (rev 3016) +++ trunk/numpy/lib/tests/test_utils.py 2006-08-14 20:13:33 UTC (rev 3017) @@ -0,0 +1,62 @@ +from numpy.testing import * +set_package_path() +import numpy as N +restore_path() + +class test_ndpointer(NumpyTestCase): + def check_dtype(self): + dt = N.intc + p = N.ndpointer(dtype=dt) + self.assert_(p.from_param(N.array([1], dt))) + dt = 'i4') + p = N.ndpointer(dtype=dt) + p.from_param(N.array([1], dt)) + self.assertRaises(TypeError, p.from_param, + N.array([1], dt.newbyteorder('swap'))) + dtnames = ['x', 'y'] + dtformats = [N.intc, N.float64] + dtdescr = {'names' : dtnames, 'formats' : dtformats} + dt = N.dtype(dtdescr) + p = N.ndpointer(dtype=dt) + self.assert_(p.from_param(N.zeros((10,), dt))) + samedt = N.dtype(dtdescr) + p = N.ndpointer(dtype=samedt) + self.assert_(p.from_param(N.zeros((10,), dt))) + dt2 = N.dtype(dtdescr, align=True) + if dt.itemsize != dt2.itemsize: + self.assertRaises(TypeError, p.from_param, N.zeros((10,), dt2)) + else: + self.assert_(p.from_param(N.zeros((10,), dt2))) + + def check_ndim(self): + p = N.ndpointer(ndim=0) + self.assert_(p.from_param(N.array(1))) + self.assertRaises(TypeError, p.from_param, N.array([1])) + p = N.ndpointer(ndim=1) + self.assertRaises(TypeError, p.from_param, N.array(1)) + self.assert_(p.from_param(N.array([1]))) + p = N.ndpointer(ndim=2) + self.assert_(p.from_param(N.array([[1]]))) + + def check_shape(self): + p = N.ndpointer(shape=(1,2)) + self.assert_(p.from_param(N.array([[1,2]]))) + self.assertRaises(TypeError, p.from_param, N.array([[1],[2]])) + p = N.ndpointer(shape=()) + self.assert_(p.from_param(N.array(1))) + + def check_flags(self): + x = N.array([[1,2,3]], order='F') + p = N.ndpointer(flags='FORTRAN') + self.assert_(p.from_param(x)) + p = N.ndpointer(flags='CONTIGUOUS') + self.assertRaises(TypeError, p.from_param, x) + p = N.ndpointer(flags=x.flags.num) + self.assert_(p.from_param(x)) + self.assertRaises(TypeError, p.from_param, N.array([[1,2,3]])) + +if __name__ == "__main__": + NumpyTest().run() Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-14 20:01:12 UTC (rev 3016) +++ trunk/numpy/lib/utils.py 2006-08-14 20:13:33 UTC (rev 3017) @@ -2,7 +2,7 @@ import inspect import types from numpy.core.numerictypes import obj2sctype, integer -from numpy.core.multiarray import dtype as _dtype, _flagdict +from numpy.core.multiarray import dtype as _dtype, _flagdict, flagsobj from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', @@ -101,7 +101,7 @@ raise TypeError, "array must have %d dimension(s)" % cls._ndim_ if cls._shape_ is not None \ and obj.shape != cls._shape_: - raise TypeError, "array must have shape %s" % cls._shape_ + raise TypeError, "array must have shape %s" % str(cls._shape_) if cls._flags_ is not None \ and ((obj.flags.num & cls._flags_) != cls._flags_): raise TypeError, "array must have flags %s" % \ @@ -121,9 +121,15 @@ flags = flags.split(',') elif isinstance(flags, (int, integer)): num = flags - flags = _flags_fromnum(flags) + flags = _flags_fromnum(num) + elif isinstance(flags, flagsobj): + num = flags.num + flags = _flags_fromnum(num) if num is None: - flags = [x.strip().upper() for x in flags] + try: + flags = [x.strip().upper() for x in flags] + except: + raise TypeError, "invalid flags specification" num = _num_fromflags(flags) try: return _pointer_type_cache[(dtype, ndim, shape, num)] From numpy-svn at scipy.org Mon Aug 14 16:21:05 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 15:21:05 -0500 (CDT) Subject: [Numpy-svn] r3018 - trunk/numpy/core/src Message-ID: <20060814202105.63B7039C045@new.scipy.org> Author: oliphant Date: 2006-08-14 15:20:56 -0500 (Mon, 14 Aug 2006) New Revision: 3018 Modified: trunk/numpy/core/src/ufuncobject.c Log: Fix == --> = error in ufuncobject.c Modified: trunk/numpy/core/src/ufuncobject.c =================================================================== --- trunk/numpy/core/src/ufuncobject.c 2006-08-14 20:13:33 UTC (rev 3017) +++ trunk/numpy/core/src/ufuncobject.c 2006-08-14 20:20:56 UTC (rev 3018) @@ -1870,7 +1870,7 @@ (PyObject *)aar); } else { - outsize == PyArray_MultiplyList(loop_i, aar->nd-1); + outsize = PyArray_MultiplyList(loop_i, aar->nd-1); } break; case UFUNC_ACCUMULATE: From numpy-svn at scipy.org Mon Aug 14 16:27:42 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 15:27:42 -0500 (CDT) Subject: [Numpy-svn] r3019 - trunk/numpy/linalg Message-ID: <20060814202742.98A0039C08E@new.scipy.org> Author: oliphant Date: 2006-08-14 15:27:39 -0500 (Mon, 14 Aug 2006) New Revision: 3019 Modified: trunk/numpy/linalg/linalg.py Log: Check for return value in linalg.det Modified: trunk/numpy/linalg/linalg.py =================================================================== --- trunk/numpy/linalg/linalg.py 2006-08-14 20:20:56 UTC (rev 3018) +++ trunk/numpy/linalg/linalg.py 2006-08-14 20:27:39 UTC (rev 3019) @@ -582,6 +582,11 @@ lapack_routine = lapack_lite.dgetrf pivots = zeros((n,), fortran_int) results = lapack_routine(n, n, a, n, pivots, 0) + info = results['info'] + if (info < 0): + raise TypeError, "Illegal input to Fortran routine" + elif (info > 0): + return 0.0 sign = add.reduce(pivots != arange(1, n+1)) % 2 return (1.-2.*sign)*multiply.reduce(diagonal(a),axis=-1) From numpy-svn at scipy.org Mon Aug 14 17:10:29 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 16:10:29 -0500 (CDT) Subject: [Numpy-svn] r3020 - trunk/numpy/core/src Message-ID: <20060814211029.EADFF39C052@new.scipy.org> Author: oliphant Date: 2006-08-14 16:10:27 -0500 (Mon, 14 Aug 2006) New Revision: 3020 Modified: trunk/numpy/core/src/arrayobject.c Log: Remove strnlen and fix unicode copy and strip Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-14 20:27:39 UTC (rev 3019) +++ trunk/numpy/core/src/arrayobject.c 2006-08-14 21:10:27 UTC (rev 3020) @@ -4195,7 +4195,7 @@ static void _rstripw(char *s, int n) { int i; - for(i=strnlen(s,n)-1; i>=1; i--) /* Never strip to length 0. */ + for(i=n-1; i>=1; i--) /* Never strip to length 0. */ { int c = s[i]; if (!c || isspace(c)) @@ -4245,8 +4245,8 @@ static char * _uni_copy_n_strip(char *original, char *temp, int nc) { - if (nc*4 > SMALL_STRING) { - temp = malloc(nc); + if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) { + temp = malloc(nc*sizeof(PyArray_UCS4)); if (!temp) { PyErr_NoMemory(); return NULL; From numpy-svn at scipy.org Mon Aug 14 17:30:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 16:30:56 -0500 (CDT) Subject: [Numpy-svn] r3021 - in trunk/numpy: . lib Message-ID: <20060814213056.EB47A39C044@new.scipy.org> Author: oliphant Date: 2006-08-14 16:30:52 -0500 (Mon, 14 Aug 2006) New Revision: 3021 Added: trunk/numpy/ctypeslib.py Modified: trunk/numpy/lib/utils.py Log: Move ctypes-related functions out of top-level Added: trunk/numpy/ctypeslib.py =================================================================== --- trunk/numpy/ctypeslib.py 2006-08-14 21:10:27 UTC (rev 3020) +++ trunk/numpy/ctypeslib.py 2006-08-14 21:30:52 UTC (rev 3021) @@ -0,0 +1,108 @@ +__all__ = ['ctypes_load_library', 'ndpointer'] + + +# Adapted from Albert Strasheim +def ctypes_load_library(libname, loader_path): + if '.' not in libname: + if sys.platform == 'win32': + libname = '%s.dll' % libname + elif sys.platform == 'darwin': + libname = '%s.dylib' % libname + else: + libname = '%s.so' % libname + loader_path = os.path.abspath(loader_path) + if not os.path.isdir(loader_path): + libdir = os.path.dirname(loader_path) + else: + libdir = loader_path + import ctypes + libpath = os.path.join(libdir, libname) + return ctypes.cdll[libpath] + +def _num_fromflags(flaglist): + num = 0 + for val in flaglist: + num += _flagdict[val] + return num + +def _flags_fromnum(num): + res = [] + for key, value in _flagdict.items(): + if (num & value): + res.append(key) + return res + +class _ndptr(object): + def from_param(cls, obj): + if not isinstance(obj, ndarray): + raise TypeError, "argument must be an ndarray" + if cls._dtype_ is not None \ + and obj.dtype != cls._dtype_: + raise TypeError, "array must have data type %s" % cls._dtype_ + if cls._ndim_ is not None \ + and obj.ndim != cls._ndim_: + raise TypeError, "array must have %d dimension(s)" % cls._ndim_ + if cls._shape_ is not None \ + and obj.shape != cls._shape_: + raise TypeError, "array must have shape %s" % str(cls._shape_) + if cls._flags_ is not None \ + and ((obj.flags.num & cls._flags_) != cls._flags_): + raise TypeError, "array must have flags %s" % \ + _flags_fromnum(cls._flags_) + return obj.ctypes + from_param = classmethod(from_param) + + +# Factory for an array-checking class with from_param defined for +# use with ctypes argtypes mechanism +_pointer_type_cache = {} +def ndpointer(dtype=None, ndim=None, shape=None, flags=None): + if dtype is not None: + dtype = _dtype(dtype) + num = None + if flags is not None: + if isinstance(flags, str): + flags = flags.split(',') + elif isinstance(flags, (int, integer)): + num = flags + flags = _flags_fromnum(num) + elif isinstance(flags, flagsobj): + num = flags.num + flags = _flags_fromnum(num) + if num is None: + try: + flags = [x.strip().upper() for x in flags] + except: + raise TypeError, "invalid flags specification" + num = _num_fromflags(flags) + try: + return _pointer_type_cache[(dtype, ndim, shape, num)] + except KeyError: + pass + if dtype is None: + name = 'any' + elif dtype.names: + name = str(id(dtype)) + else: + name = dtype.str + if ndim is not None: + name += "_%dd" % ndim + if shape is not None: + try: + strshape = [str(x) for x in shape] + except TypeError: + strshape = [str(shape)] + shape = (shape,) + shape = tuple(shape) + name += "_"+"x".join(strshape) + if flags is not None: + name += "_"+"_".join(flags) + else: + flags = [] + klass = type("ndpointer_%s"%name, (_ndptr,), + {"_dtype_": dtype, + "_shape_" : shape, + "_ndim_" : ndim, + "_flags_" : num}) + _pointer_type_cache[dtype] = klass + return klass Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-14 21:10:27 UTC (rev 3020) +++ trunk/numpy/lib/utils.py 2006-08-14 21:30:52 UTC (rev 3021) @@ -7,8 +7,7 @@ __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', 'issubdtype', 'deprecate', 'get_numarray_include', - 'get_include', 'ctypes_load_library', 'ndpointer', - 'info', 'source', 'who'] + 'get_include', 'info', 'source', 'who'] def issubclass_(arg1, arg2): try: @@ -58,112 +57,6 @@ return include_dirs + get_numpy_include_dirs() -# Adapted from Albert Strasheim -def ctypes_load_library(libname, loader_path): - if '.' not in libname: - if sys.platform == 'win32': - libname = '%s.dll' % libname - elif sys.platform == 'darwin': - libname = '%s.dylib' % libname - else: - libname = '%s.so' % libname - loader_path = os.path.abspath(loader_path) - if not os.path.isdir(loader_path): - libdir = os.path.dirname(loader_path) - else: - libdir = loader_path - import ctypes - libpath = os.path.join(libdir, libname) - return ctypes.cdll[libpath] - -def _num_fromflags(flaglist): - num = 0 - for val in flaglist: - num += _flagdict[val] - return num - -def _flags_fromnum(num): - res = [] - for key, value in _flagdict.items(): - if (num & value): - res.append(key) - return res - -class _ndptr(object): - def from_param(cls, obj): - if not isinstance(obj, ndarray): - raise TypeError, "argument must be an ndarray" - if cls._dtype_ is not None \ - and obj.dtype != cls._dtype_: - raise TypeError, "array must have data type %s" % cls._dtype_ - if cls._ndim_ is not None \ - and obj.ndim != cls._ndim_: - raise TypeError, "array must have %d dimension(s)" % cls._ndim_ - if cls._shape_ is not None \ - and obj.shape != cls._shape_: - raise TypeError, "array must have shape %s" % str(cls._shape_) - if cls._flags_ is not None \ - and ((obj.flags.num & cls._flags_) != cls._flags_): - raise TypeError, "array must have flags %s" % \ - _flags_fromnum(cls._flags_) - return obj.ctypes - from_param = classmethod(from_param) - -# Factory for an array-checking class with from_param defined for -# use with ctypes argtypes mechanism -_pointer_type_cache = {} -def ndpointer(dtype=None, ndim=None, shape=None, flags=None): - if dtype is not None: - dtype = _dtype(dtype) - num = None - if flags is not None: - if isinstance(flags, str): - flags = flags.split(',') - elif isinstance(flags, (int, integer)): - num = flags - flags = _flags_fromnum(num) - elif isinstance(flags, flagsobj): - num = flags.num - flags = _flags_fromnum(num) - if num is None: - try: - flags = [x.strip().upper() for x in flags] - except: - raise TypeError, "invalid flags specification" - num = _num_fromflags(flags) - try: - return _pointer_type_cache[(dtype, ndim, shape, num)] - except KeyError: - pass - if dtype is None: - name = 'any' - elif dtype.names: - name = str(id(dtype)) - else: - name = dtype.str - if ndim is not None: - name += "_%dd" % ndim - if shape is not None: - try: - strshape = [str(x) for x in shape] - except TypeError: - strshape = [str(shape)] - shape = (shape,) - shape = tuple(shape) - name += "_"+"x".join(strshape) - if flags is not None: - name += "_"+"_".join(flags) - else: - flags = [] - klass = type("ndpointer_%s"%name, (_ndptr,), - {"_dtype_": dtype, - "_shape_" : shape, - "_ndim_" : ndim, - "_flags_" : num}) - _pointer_type_cache[dtype] = klass - return klass - - if sys.version_info < (2, 4): # Can't set __name__ in 2.3 import new From numpy-svn at scipy.org Mon Aug 14 19:15:52 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 18:15:52 -0500 (CDT) Subject: [Numpy-svn] r3022 - in trunk/numpy: . core/include/numpy core/src lib/tests numarray oldnumeric testing tests Message-ID: <20060814231552.115D639C044@new.scipy.org> Author: oliphant Date: 2006-08-14 18:15:21 -0500 (Mon, 14 Aug 2006) New Revision: 3022 Added: trunk/numpy/tests/ trunk/numpy/tests/test_ctypeslib.py Removed: trunk/numpy/lib/tests/test_utils.py Modified: trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/multiarraymodule.c trunk/numpy/core/src/scalarmathmodule.c.src trunk/numpy/core/src/scalartypes.inc.src trunk/numpy/ctypeslib.py trunk/numpy/numarray/alter_code1.py trunk/numpy/numarray/alter_code2.py trunk/numpy/oldnumeric/alter_code1.py trunk/numpy/oldnumeric/alter_code2.py trunk/numpy/setup.py trunk/numpy/testing/numpytest.py Log: Fix Python 2.5 compatibility to work with new b3 release Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-14 23:15:21 UTC (rev 3022) @@ -644,8 +644,10 @@ #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define NPY_SSIZE_T_PYFMT "i" +#define constchar const char #else #define NPY_SSIZE_T_PYFMT "n" +#define constchar char #endif #if SIZEOF_PY_INTPTR_T == SIZEOF_INT Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/core/src/arrayobject.c 2006-08-14 23:15:21 UTC (rev 3022) @@ -3036,7 +3036,7 @@ } static Py_ssize_t -array_getcharbuf(PyArrayObject *self, Py_ssize_t segment, const char **ptrptr) +array_getcharbuf(PyArrayObject *self, Py_ssize_t segment, constchar **ptrptr) { if (self->descr->type_num == PyArray_STRING || \ self->descr->type_num == PyArray_UNICODE) @@ -3790,6 +3790,20 @@ PyArray_Copy(self)); } +#if PY_VERSION_HEX >= 0x02050000 +static PyObject * +array_index(PyArrayObject *v) +{ + if (PyArray_SIZE(v) != 1 || !PyArray_ISINTEGER(v)) { + PyErr_SetString(PyExc_TypeError, "only length-1 integer " \ + "arrays 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*/ @@ -3834,6 +3848,10 @@ (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 */ +#endif + }; /****************** End of Buffer Protocol *******************************/ Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-14 23:15:21 UTC (rev 3022) @@ -6118,7 +6118,7 @@ static unsigned int PyArray_GetNDArrayCVersion(void) { - return (unsigned int)NDARRAY_VERSION; + return (unsigned int)NPY_VERSION; } static PyObject * Modified: trunk/numpy/core/src/scalarmathmodule.c.src =================================================================== --- trunk/numpy/core/src/scalarmathmodule.c.src 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/core/src/scalarmathmodule.c.src 2006-08-14 23:15:21 UTC (rev 3022) @@ -712,8 +712,8 @@ /**end repeat**/ /**begin repeat - #name=(float,double,longdouble,cfloat,cdouble,clongdouble)*6# - #oper=lshift*6, rshift*6, and*6, or*6, xor*6, index*6# + #name=(float,double,longdouble,cfloat,cdouble,clongdouble)*5# + #oper=lshift*6, rshift*6, and*6, or*6, xor*6# **/ #define @name at _@oper@ NULL /**end repeat**/ @@ -819,21 +819,7 @@ /**end repeat**/ -#if PY_VERSION_HEX >= 0x02050000 /**begin repeat - #name=byte,ubyte,short,ushort,int,uint,long,ulong,longlong,ulonglong# - #Name=Byte, UByte, Short, UShort, Int, UInt, Long, ULong, LongLong, ULongLong# -**/ -static Py_ssize_t - at name@_index(PyObject *a) -{ - return PyArrayScalar_VAL(a, @Name@); -} -/**end repeat**/ -#endif - - -/**begin repeat #oper=le,ge,lt,gt,eq,ne# #op=<=,>=,<,>,==,!=# **/ @@ -937,7 +923,7 @@ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ #if PY_VERSION_HEX >= 0x02050000 - (lenfunc)@name at _index, /*nb_index*/ + (unaryfunc)NULL, /*nb_index*/ #endif }; /**end repeat**/ @@ -951,6 +937,9 @@ #name=byte,ubyte,short,ushort,int,uint,long,ulong,longlong,ulonglong,float,double,longdouble,cfloat,cdouble,clongdouble# #NAME=Byte, UByte, Short, UShort, Int, UInt, Long, ULong, LongLong, ULongLong, Float, Double, LongDouble, CFloat, CDouble, CLongDouble# **/ +#if PY_VERSION_HEX >= 0x02050000 + @name at _as_number.nb_index = Py at NAME@ArrType_Type.tp_as_number->nb_index; +#endif Py at NAME@ArrType_Type.tp_as_number = &(@name at _as_number); Py at NAME@ArrType_Type.tp_richcompare = @name at _richcompare; /**end repeat**/ Modified: trunk/numpy/core/src/scalartypes.inc.src =================================================================== --- trunk/numpy/core/src/scalartypes.inc.src 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/core/src/scalartypes.inc.src 2006-08-14 23:15:21 UTC (rev 3022) @@ -593,24 +593,7 @@ } /**end repeat**/ -#if PY_VERSION_HEX >= 0x02050000 -/* This needs a better implementation */ -static Py_ssize_t -gentype_index(PyObject *self) -{ - PyObject *obj; - if (!(PyArray_IsScalar(self, Integer))) { - PyErr_SetString(PyExc_TypeError, - "not an integer type."); - return -1; - } - obj = gentype_int(self); - if (obj == NULL) return -1; - return PyInt_AsSsize_t(obj); -} -#endif - static PyNumberMethods gentype_as_number = { (binaryfunc)gentype_add, /*nb_add*/ (binaryfunc)gentype_subtract, /*nb_subtract*/ @@ -651,7 +634,7 @@ 0, /*nb_inplace_floor_divide*/ 0, /*nb_inplace_true_divide*/ #if PY_VERSION_HEX >= 0x02050000 - (lenfunc)gentype_index, /* nb_index */ + (unaryfunc)NULL, /* nb_index */ #endif }; @@ -1641,7 +1624,7 @@ } static int -gentype_getcharbuf(PyObject *self, int segment, const char **ptrptr) +gentype_getcharbuf(PyObject *self, int segment, constchar **ptrptr) { if (PyArray_IsScalar(self, String) || \ PyArray_IsScalar(self, Unicode)) @@ -1795,6 +1778,26 @@ return a == PyArrayScalar_True; } +#if PY_VERSION_HEX >= 0x02050000 +/**begin repeat +#name=byte, short, int, long, ubyte, ushort, longlong, uint, ulong, ulonglong# +#Name=Byte, Short, Int, Long, UByte, UShort, LongLong, UInt, ULong, ULongLong# +#type=PyInt_FromLong*6, PyLong_FromLongLong*1, PyLong_FromUnsignedLong*2, PyLong_FromUnsignedLongLong# +*/ +static PyNumberMethods @name at _arrtype_as_number; +static PyObject * + at name@_index(PyObject *self) +{ + return @type@(PyArrayScalar_VAL(self, @Name@)); +} +/**end repeat**/ +static PyObject * +bool_index(PyObject *a) +{ + return PyInt_FromLong(PyArrayScalar_VAL(a, Bool)); +} +#endif + /* Arithmetic methods -- only so we can override &, |, ^. */ static PyNumberMethods bool_arrtype_as_number = { 0, /* nb_add */ @@ -2154,7 +2157,7 @@ static Py_ssize_t object_arrtype_getcharbuf(PyObjectScalarObject *self, Py_ssize_t segment, - const char **ptrptr) + constchar **ptrptr) { PyBufferProcs *pb = self->obval->ob_type->tp_as_buffer; @@ -2336,7 +2339,21 @@ PyGenericArrType_Type.tp_richcompare = gentype_richcompare; PyBoolArrType_Type.tp_as_number = &bool_arrtype_as_number; +#if PY_VERSION_HEX >= 0x02050000 + /* need to add dummy versions with filled-in nb_index + in-order for PyType_Ready to fill in .__index__() method + */ + /**begin repeat +#name=byte, short, int, long, longlong, ubyte, ushort, uint, ulong, ulonglong# +#NAME=Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, ULong, ULongLong# + */ + Py at NAME@ArrType_Type.tp_as_number = &@name at _arrtype_as_number; + Py at NAME@ArrType_Type.tp_as_number->nb_index = (unaryfunc)@name at _index; + /**end repeat**/ + PyBoolArrType_Type.tp_as_number->nb_index = (unaryfunc)bool_index; +#endif + PyStringArrType_Type.tp_alloc = NULL; PyStringArrType_Type.tp_free = NULL; Modified: trunk/numpy/ctypeslib.py =================================================================== --- trunk/numpy/ctypeslib.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/ctypeslib.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -1,5 +1,8 @@ __all__ = ['ctypes_load_library', 'ndpointer'] +import sys, os +from numpy import integer, product, ndarray, dtype as _dtype +from numpy.core.multiarray import _flagdict, flagsobj # Adapted from Albert Strasheim def ctypes_load_library(libname, loader_path): Deleted: trunk/numpy/lib/tests/test_utils.py =================================================================== --- trunk/numpy/lib/tests/test_utils.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/lib/tests/test_utils.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -1,62 +0,0 @@ -from numpy.testing import * -set_package_path() -import numpy as N -restore_path() - -class test_ndpointer(NumpyTestCase): - def check_dtype(self): - dt = N.intc - p = N.ndpointer(dtype=dt) - self.assert_(p.from_param(N.array([1], dt))) - dt = 'i4') - p = N.ndpointer(dtype=dt) - p.from_param(N.array([1], dt)) - self.assertRaises(TypeError, p.from_param, - N.array([1], dt.newbyteorder('swap'))) - dtnames = ['x', 'y'] - dtformats = [N.intc, N.float64] - dtdescr = {'names' : dtnames, 'formats' : dtformats} - dt = N.dtype(dtdescr) - p = N.ndpointer(dtype=dt) - self.assert_(p.from_param(N.zeros((10,), dt))) - samedt = N.dtype(dtdescr) - p = N.ndpointer(dtype=samedt) - self.assert_(p.from_param(N.zeros((10,), dt))) - dt2 = N.dtype(dtdescr, align=True) - if dt.itemsize != dt2.itemsize: - self.assertRaises(TypeError, p.from_param, N.zeros((10,), dt2)) - else: - self.assert_(p.from_param(N.zeros((10,), dt2))) - - def check_ndim(self): - p = N.ndpointer(ndim=0) - self.assert_(p.from_param(N.array(1))) - self.assertRaises(TypeError, p.from_param, N.array([1])) - p = N.ndpointer(ndim=1) - self.assertRaises(TypeError, p.from_param, N.array(1)) - self.assert_(p.from_param(N.array([1]))) - p = N.ndpointer(ndim=2) - self.assert_(p.from_param(N.array([[1]]))) - - def check_shape(self): - p = N.ndpointer(shape=(1,2)) - self.assert_(p.from_param(N.array([[1,2]]))) - self.assertRaises(TypeError, p.from_param, N.array([[1],[2]])) - p = N.ndpointer(shape=()) - self.assert_(p.from_param(N.array(1))) - - def check_flags(self): - x = N.array([[1,2,3]], order='F') - p = N.ndpointer(flags='FORTRAN') - self.assert_(p.from_param(x)) - p = N.ndpointer(flags='CONTIGUOUS') - self.assertRaises(TypeError, p.from_param, x) - p = N.ndpointer(flags=x.flags.num) - self.assert_(p.from_param(x)) - self.assertRaises(TypeError, p.from_param, N.array([[1,2,3]])) - -if __name__ == "__main__": - NumpyTest().run() Modified: trunk/numpy/numarray/alter_code1.py =================================================================== --- trunk/numpy/numarray/alter_code1.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/numarray/alter_code1.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -52,7 +52,7 @@ - .setimaginary() --> .imag """ -__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] +__all__ = ['convertfile', 'convertall'] import sys import os Modified: trunk/numpy/numarray/alter_code2.py =================================================================== --- trunk/numpy/numarray/alter_code2.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/numarray/alter_code2.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -3,7 +3,7 @@ with numpy """ -#__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] +#__all__ = ['convertfile', 'convertall'] __all__ = [] import warnings Modified: trunk/numpy/oldnumeric/alter_code1.py =================================================================== --- trunk/numpy/oldnumeric/alter_code1.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/oldnumeric/alter_code1.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -28,7 +28,7 @@ * Converts uses of type(...) is isinstance(..., ) """ -__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] +__all__ = ['convertfile', 'convertall'] import sys import os Modified: trunk/numpy/oldnumeric/alter_code2.py =================================================================== --- trunk/numpy/oldnumeric/alter_code2.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/oldnumeric/alter_code2.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -17,7 +17,7 @@ oldnumeric.random_array, and oldnumeric.fft """ -#__all__ = ['fromfile', 'fromstr', 'convertfile', 'convertall'] +#__all__ = ['convertfile', 'convertall'] __all__ = [] import warnings Modified: trunk/numpy/setup.py =================================================================== --- trunk/numpy/setup.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/setup.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -15,6 +15,7 @@ config.add_subpackage('linalg') config.add_subpackage('random') config.add_data_dir('doc') + config.add_data_dir('tests') config.make_config_py() # installs __config__.py return config Modified: trunk/numpy/testing/numpytest.py =================================================================== --- trunk/numpy/testing/numpytest.py 2006-08-14 21:30:52 UTC (rev 3021) +++ trunk/numpy/testing/numpytest.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -452,6 +452,8 @@ continue modules.append(module) + + self.test_files = [] suites = [] for module in modules: Copied: trunk/numpy/tests/test_ctypeslib.py (from rev 3019, trunk/numpy/lib/tests/test_utils.py) =================================================================== --- trunk/numpy/lib/tests/test_utils.py 2006-08-14 20:27:39 UTC (rev 3019) +++ trunk/numpy/tests/test_ctypeslib.py 2006-08-14 23:15:21 UTC (rev 3022) @@ -0,0 +1,63 @@ +from numpy.testing import * +set_package_path() +import numpy as N +from numpy.ctypeslib import ndpointer +restore_path() + +class test_ndpointer(NumpyTestCase): + def check_dtype(self): + dt = N.intc + p = ndpointer(dtype=dt) + self.assert_(p.from_param(N.array([1], dt))) + dt = 'i4') + p = ndpointer(dtype=dt) + p.from_param(N.array([1], dt)) + self.assertRaises(TypeError, p.from_param, + N.array([1], dt.newbyteorder('swap'))) + dtnames = ['x', 'y'] + dtformats = [N.intc, N.float64] + dtdescr = {'names' : dtnames, 'formats' : dtformats} + dt = N.dtype(dtdescr) + p = ndpointer(dtype=dt) + self.assert_(p.from_param(N.zeros((10,), dt))) + samedt = N.dtype(dtdescr) + p = ndpointer(dtype=samedt) + self.assert_(p.from_param(N.zeros((10,), dt))) + dt2 = N.dtype(dtdescr, align=True) + if dt.itemsize != dt2.itemsize: + self.assertRaises(TypeError, p.from_param, N.zeros((10,), dt2)) + else: + self.assert_(p.from_param(N.zeros((10,), dt2))) + + def check_ndim(self): + p = ndpointer(ndim=0) + self.assert_(p.from_param(N.array(1))) + self.assertRaises(TypeError, p.from_param, N.array([1])) + p = ndpointer(ndim=1) + self.assertRaises(TypeError, p.from_param, N.array(1)) + self.assert_(p.from_param(N.array([1]))) + p = ndpointer(ndim=2) + self.assert_(p.from_param(N.array([[1]]))) + + def check_shape(self): + p = ndpointer(shape=(1,2)) + self.assert_(p.from_param(N.array([[1,2]]))) + self.assertRaises(TypeError, p.from_param, N.array([[1],[2]])) + p = ndpointer(shape=()) + self.assert_(p.from_param(N.array(1))) + + def check_flags(self): + x = N.array([[1,2,3]], order='F') + p = ndpointer(flags='FORTRAN') + self.assert_(p.from_param(x)) + p = ndpointer(flags='CONTIGUOUS') + self.assertRaises(TypeError, p.from_param, x) + p = ndpointer(flags=x.flags.num) + self.assert_(p.from_param(x)) + self.assertRaises(TypeError, p.from_param, N.array([[1,2,3]])) + +if __name__ == "__main__": + NumpyTest().run() From numpy-svn at scipy.org Mon Aug 14 19:27:02 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 18:27:02 -0500 (CDT) Subject: [Numpy-svn] r3023 - trunk/numpy Message-ID: <20060814232702.C4AEC39C044@new.scipy.org> Author: oliphant Date: 2006-08-14 18:27:00 -0500 (Mon, 14 Aug 2006) New Revision: 3023 Modified: trunk/numpy/ctypeslib.py Log: Add a test function to the ctypeslib module. Modified: trunk/numpy/ctypeslib.py =================================================================== --- trunk/numpy/ctypeslib.py 2006-08-14 23:15:21 UTC (rev 3022) +++ trunk/numpy/ctypeslib.py 2006-08-14 23:27:00 UTC (rev 3023) @@ -1,4 +1,4 @@ -__all__ = ['ctypes_load_library', 'ndpointer'] +__all__ = ['ctypes_load_library', 'ndpointer', 'test'] import sys, os from numpy import integer, product, ndarray, dtype as _dtype @@ -109,3 +109,7 @@ "_flags_" : num}) _pointer_type_cache[dtype] = klass return klass + +def test(level=1, verbosity=1): + from numpy.testing import NumpyTest + return NumpyTest().test(level, verbosity) From numpy-svn at scipy.org Mon Aug 14 20:28:20 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 14 Aug 2006 19:28:20 -0500 (CDT) Subject: [Numpy-svn] r3024 - trunk/numpy/lib Message-ID: <20060815002820.F1DE839C016@new.scipy.org> Author: oliphant Date: 2006-08-14 19:28:18 -0500 (Mon, 14 Aug 2006) New Revision: 3024 Modified: trunk/numpy/lib/utils.py Log: Fix-up issubdtype to be more useful Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-14 23:27:00 UTC (rev 3023) +++ trunk/numpy/lib/utils.py 2006-08-15 00:28:18 UTC (rev 3024) @@ -1,7 +1,7 @@ import sys, os import inspect import types -from numpy.core.numerictypes import obj2sctype, integer +from numpy.core.numerictypes import obj2sctype, integer, generic from numpy.core.multiarray import dtype as _dtype, _flagdict, flagsobj from numpy.core import product, ndarray @@ -19,7 +19,14 @@ return issubclass(obj2sctype(arg1), obj2sctype(arg2)) def issubdtype(arg1, arg2): - return issubclass(_dtype(arg1).type, _dtype(arg2).type) + if issubclass_(arg2, generic): + return issubclass(_dtype(arg1).type, arg2) + mro = _dtype(arg2).type.mro() + if len(mro) > 1: + val = mro[1] + else: + val = mro[0] + return issubclass(_dtype(arg1).type, val) def get_include(): """Return the directory in the package that contains the numpy/*.h header From numpy-svn at scipy.org Tue Aug 15 02:25:55 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 15 Aug 2006 01:25:55 -0500 (CDT) Subject: [Numpy-svn] r3025 - trunk/numpy/core/src Message-ID: <20060815062555.0AFD839C010@new.scipy.org> Author: oliphant Date: 2006-08-15 01:25:51 -0500 (Tue, 15 Aug 2006) New Revision: 3025 Modified: trunk/numpy/core/src/arrayobject.c Log: Handle 0-d case in IterAllButAxis Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-15 00:28:18 UTC (rev 3024) +++ trunk/numpy/core/src/arrayobject.c 2006-08-15 06:25:51 UTC (rev 3025) @@ -8626,6 +8626,8 @@ it = (PyArrayIterObject *)PyArray_IterNew(obj); if (it == NULL) return NULL; + if (PyArray_NDIM(obj)==0) + return (PyObject *)it; if (*inaxis < 0) { int i, maxaxis=0; intp maxdim=PyArray_DIM(obj,0); From numpy-svn at scipy.org Tue Aug 15 05:37:48 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 15 Aug 2006 04:37:48 -0500 (CDT) Subject: [Numpy-svn] r3026 - trunk/numpy/core/tests Message-ID: <20060815093748.D643539C09B@new.scipy.org> Author: stefan Date: 2006-08-15 04:37:43 -0500 (Tue, 15 Aug 2006) New Revision: 3026 Modified: trunk/numpy/core/tests/test_regression.py Log: Test for lexsort. Modified: trunk/numpy/core/tests/test_regression.py =================================================================== --- trunk/numpy/core/tests/test_regression.py 2006-08-15 06:25:51 UTC (rev 3025) +++ trunk/numpy/core/tests/test_regression.py 2006-08-15 09:37:43 UTC (rev 3026) @@ -347,6 +347,11 @@ assert_equal(N.array([],dtype=object).shape, ()) assert_equal(N.array([[],[],[]],dtype=object).shape, (3,)) assert_equal(N.array([[3,4],[5,6],None],dtype=object).shape, (3,)) + + def check_lexsort(self,level=rlevel): + """Lexsort memory error""" + v = N.array([1,2,3,4,5,6,7,8,9,10]) + assert_equal(N.lexsort(v),0) if __name__ == "__main__": NumpyTest().run() From numpy-svn at scipy.org Tue Aug 15 05:53:53 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 15 Aug 2006 04:53:53 -0500 (CDT) Subject: [Numpy-svn] r3027 - trunk/numpy Message-ID: <20060815095353.1AE7139C010@new.scipy.org> Author: oliphant Date: 2006-08-15 04:53:49 -0500 (Tue, 15 Aug 2006) New Revision: 3027 Modified: trunk/numpy/__init__.py trunk/numpy/ctypeslib.py Log: import ctypeslib on numpy load and change name from ctypes_load_library to load_library Modified: trunk/numpy/__init__.py =================================================================== --- trunk/numpy/__init__.py 2006-08-15 09:37:43 UTC (rev 3026) +++ trunk/numpy/__init__.py 2006-08-15 09:53:49 UTC (rev 3027) @@ -39,12 +39,13 @@ import linalg import fft import random + import ctypeslib __all__ = ['__version__', 'pkgload', 'PackageLoader', 'ScipyTest', 'NumpyTest', 'show_config'] __all__ += core.__all__ __all__ += lib.__all__ - __all__ += ['linalg', 'fft', 'random'] + __all__ += ['linalg', 'fft', 'random', 'ctypeslib'] if __doc__ is not None: __doc__ += """ Modified: trunk/numpy/ctypeslib.py =================================================================== --- trunk/numpy/ctypeslib.py 2006-08-15 09:37:43 UTC (rev 3026) +++ trunk/numpy/ctypeslib.py 2006-08-15 09:53:49 UTC (rev 3027) @@ -1,11 +1,11 @@ -__all__ = ['ctypes_load_library', 'ndpointer', 'test'] +__all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library'] import sys, os -from numpy import integer, product, ndarray, dtype as _dtype +from numpy import integer, product, ndarray, dtype as _dtype, deprecate from numpy.core.multiarray import _flagdict, flagsobj # Adapted from Albert Strasheim -def ctypes_load_library(libname, loader_path): +def load_library(libname, loader_path): if '.' not in libname: if sys.platform == 'win32': libname = '%s.dll' % libname @@ -35,6 +35,8 @@ res.append(key) return res +ctypes_load_library = deprecate(load_library, 'ctypes_load_library', 'load_library') + class _ndptr(object): def from_param(cls, obj): if not isinstance(obj, ndarray): From numpy-svn at scipy.org Wed Aug 16 02:32:43 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 16 Aug 2006 01:32:43 -0500 (CDT) Subject: [Numpy-svn] r3028 - in branches/distutils-revamp: command fcompiler Message-ID: <20060816063243.340FB39C00A@new.scipy.org> Author: cookedm Date: 2006-08-16 01:32:39 -0500 (Wed, 16 Aug 2006) New Revision: 3028 Modified: branches/distutils-revamp/command/config_compiler.py branches/distutils-revamp/fcompiler/__init__.py Log: [distutils-rework] look in environment for more things (programs, flags) for Fortran compiler Modified: branches/distutils-revamp/command/config_compiler.py =================================================================== --- branches/distutils-revamp/command/config_compiler.py 2006-08-15 09:53:49 UTC (rev 3027) +++ branches/distutils-revamp/command/config_compiler.py 2006-08-16 06:32:39 UTC (rev 3028) @@ -31,11 +31,18 @@ ('f90exec=', None, "specify F90 compiler command"), ('f77flags=',None,"specify F77 compiler flags"), ('f90flags=',None,"specify F90 compiler flags"), + ('ldshared=',None,"shared-library linker command"), + ('ld=',None,"static library linker command"), + ('ar=',None,"archiver command (ar)"), + ('ranlib=',None,"ranlib command"), ('opt=',None,"specify optimization flags"), ('arch=',None,"specify architecture specific optimization flags"), ('debug','g',"compile with debugging information"), ('noopt',None,"compile without optimization"), ('noarch',None,"compile without arch-dependent optimization"), + ('fflags=',None,"extra flags for Fortran compiler"), + ('ldflags=',None,"linker flags"), + ('arflags=',None,"flags for ar"), ] help_options = [ @@ -51,11 +58,18 @@ self.f90exec = None self.f77flags = None self.f90flags = None + self.ldshared = None + self.ld = None + self.ar = None + self.ranlib = None self.opt = None self.arch = None self.debug = None self.noopt = None self.noarch = None + self.fflags = None + self.ldflags = None + self.arflags = None def finalize_options(self): fc = new_fcompiler(compiler=self.fcompiler, Modified: branches/distutils-revamp/fcompiler/__init__.py =================================================================== --- branches/distutils-revamp/fcompiler/__init__.py 2006-08-15 09:53:49 UTC (rev 3027) +++ branches/distutils-revamp/fcompiler/__init__.py 2006-08-16 06:32:39 UTC (rev 3028) @@ -81,10 +81,10 @@ compiler_f90 = ('exe.compiler_f90', 'F90', 'f90exec'), compiler_fix = ('exe.compiler_fix', 'F90', 'f90exec'), version_cmd = ('self.get_version_cmd', None, None), - linker_so = ('self.get_linker_so', 'LDSHARED', None), - linker_exe = ('self.get_linker_exe', 'LD', None), - archiver = (None, 'AR', None), - ranlib = (None, 'RANLIB', None), + linker_so = ('self.get_linker_so', 'LDSHARED', 'ldshared'), + linker_exe = ('self.get_linker_exe', 'LD', 'ld'), + archiver = (None, 'AR', 'ar'), + ranlib = (None, 'RANLIB', 'ranlib'), ) flag_vars = EnvironmentConfig( @@ -103,10 +103,10 @@ debug = ('flags.debug', 'FDEBUG', None, None), debug_f77 = ('flags.debug_f77', None, None), debug_f90 = ('flags.debug_f90', None, None), - flags = ('self.get_flags', 'FFLAGS', None), - linker_so = ('flags.linker_so', 'LDFLAGS', None), - linker_exe = ('flags.linker_exe', 'LDFLAGS', None), - ar = ('flags.ar', 'ARFLAGS', None), + flags = ('self.get_flags', 'FFLAGS', 'fflags'), + linker_so = ('flags.linker_so', 'LDFLAGS', 'ldflags'), + linker_exe = ('flags.linker_exe', 'LDFLAGS', 'ldflags'), + ar = ('flags.ar', 'ARFLAGS', 'arflags'), ) language_map = {'.f':'f77', From numpy-svn at scipy.org Wed Aug 16 10:50:20 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 16 Aug 2006 09:50:20 -0500 (CDT) Subject: [Numpy-svn] r3029 - trunk/numpy/oldnumeric Message-ID: <20060816145020.D0D8E39C05A@new.scipy.org> Author: oliphant Date: 2006-08-16 09:49:27 -0500 (Wed, 16 Aug 2006) New Revision: 3029 Modified: trunk/numpy/oldnumeric/functions.py Log: Fix error in oldnumeric.empty Modified: trunk/numpy/oldnumeric/functions.py =================================================================== --- trunk/numpy/oldnumeric/functions.py 2006-08-16 06:32:39 UTC (rev 3028) +++ trunk/numpy/oldnumeric/functions.py 2006-08-16 14:49:27 UTC (rev 3029) @@ -69,7 +69,7 @@ def empty(shape, typecode='l', dtype=None): dtype = convtypecode(typecode, dtype) - return mu.empty(shape, dtype, order) + return mu.empty(shape, dtype) def array(sequence, typecode=None, copy=1, savespace=0, dtype=None): dtype = convtypecode2(typecode, dtype) From numpy-svn at scipy.org Wed Aug 16 19:14:12 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 16 Aug 2006 18:14:12 -0500 (CDT) Subject: [Numpy-svn] r3030 - trunk/numpy/core/src Message-ID: <20060816231412.99F7639C02D@new.scipy.org> Author: oliphant Date: 2006-08-16 18:14:10 -0500 (Wed, 16 Aug 2006) New Revision: 3030 Modified: trunk/numpy/core/src/multiarraymodule.c Log: Allow titles to be used as 'meta-data' Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-16 14:49:27 UTC (rev 3029) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-16 23:14:10 UTC (rev 3030) @@ -4166,9 +4166,7 @@ if (PyTuple_GET_SIZE(name) != 2) goto fail; title = PyTuple_GET_ITEM(name, 0); name = PyTuple_GET_ITEM(name, 1); - if (!PyString_Check(name) || \ - (!PyString_Check(title) && \ - !PyUnicode_Check(title))) + if (!PyString_Check(name)) goto fail; } else goto fail; @@ -4199,7 +4197,9 @@ else goto fail; if (ret == PY_FAIL) goto fail; if ((PyDict_GetItem(fields, name) != NULL) || - (title && (PyDict_GetItem(fields, title) != 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; @@ -4209,10 +4209,15 @@ tup = PyTuple_New((title == NULL ? 2 : 3)); PyTuple_SET_ITEM(tup, 0, (PyObject *)conv); 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); - PyDict_SetItem(fields, title, tup); + if (PyString_Check(title) || PyUnicode_Check(title)) + PyDict_SetItem(fields, title, tup); } PyDict_SetItem(fields, name, tup); totalsize += conv->elsize; @@ -4370,7 +4375,10 @@ will be assumed and placed in the dictionary. "titles" --- Allows the use of an additional key - for the fields dictionary. + 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 @@ -4381,7 +4389,7 @@ 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. +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. @@ -4494,7 +4502,8 @@ PyDict_SetItem(fields, name, tup); Py_DECREF(name); if (len == 3) { - if (PyDict_GetItem(fields, item) != NULL) { + if ((PyString_Check(item) || PyUnicode_Check(item)) && \ + PyDict_GetItem(fields, item) != NULL) { PyErr_SetString(PyExc_ValueError, "title already used as a "\ "name or title."); From numpy-svn at scipy.org Wed Aug 16 21:01:19 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 16 Aug 2006 20:01:19 -0500 (CDT) Subject: [Numpy-svn] r3031 - in trunk/numpy/core: . src Message-ID: <20060817010119.853EC39C00D@new.scipy.org> Author: oliphant Date: 2006-08-16 20:01:14 -0500 (Wed, 16 Aug 2006) New Revision: 3031 Modified: trunk/numpy/core/_internal.py trunk/numpy/core/numerictypes.py trunk/numpy/core/records.py trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/multiarraymodule.c Log: Fix ambiguity of list data-type objects. Lists are always interpeted as array_descriptor format. Use a comma-separated string for the other approach. Add 'int', 'float', etc. to the sctypeDict so they can be interpreted in strings. Modified: trunk/numpy/core/_internal.py =================================================================== --- trunk/numpy/core/_internal.py 2006-08-16 23:14:10 UTC (rev 3030) +++ trunk/numpy/core/_internal.py 2006-08-17 01:01:14 UTC (rev 3031) @@ -120,7 +120,8 @@ newlist = [] hold = '' - for element in input.split(','): + listinput = input.split(',') + for element in listinput: if hold != '': item = hold + ',' + element else: Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-16 23:14:10 UTC (rev 3030) +++ trunk/numpy/core/numerictypes.py 2006-08-17 01:01:14 UTC (rev 3031) @@ -433,6 +433,19 @@ if val not in sctypeDict: sctypeDict[val] = key +# Add additional strings to the sctypeDict + +_toadd = ['int', 'float', 'complex', 'bool', 'object', 'string', ('str', allTypes['string_']), + 'unicode', 'object'] + +for name in _toadd: + if isinstance(name, tuple): + sctypeDict[name[0]] = name[1] + else: + sctypeDict[name] = allTypes['%s_' % name] + +del _toadd, name + # Now add the types we've determined to this module for key in allTypes: globals()[key] = allTypes[key] Modified: trunk/numpy/core/records.py =================================================================== --- trunk/numpy/core/records.py 2006-08-16 23:14:10 UTC (rev 3030) +++ trunk/numpy/core/records.py 2006-08-17 01:01:14 UTC (rev 3031) @@ -50,10 +50,14 @@ if formats is None: raise ValueError, "Need formats argument" + if isinstance(formats, list): + if len(formats) < 2: + formats.append('') + formats = ','.join(formats) dtype = sb.dtype(formats, aligned) fields = dtype.fields if fields is None: - dtype = sb.dtype([formats], aligned) + dtype = sb.dtype([('f1', dtype)], aligned) fields = dtype.fields keys = dtype.names self._f_formats = [fields[key][0] for key in keys] Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-16 23:14:10 UTC (rev 3030) +++ trunk/numpy/core/src/arrayobject.c 2006-08-17 01:01:14 UTC (rev 3031) @@ -10596,7 +10596,6 @@ {NULL, NULL, NULL, NULL}, }; -static PyArray_Descr *_convert_from_list(PyObject *obj, int align, int try_descr); static PyArray_Descr *_convert_from_dict(PyObject *obj, int align); static PyArray_Descr *_convert_from_commastring(PyObject *obj, int align); static PyArray_Descr *_convert_from_array_descr(PyObject *obj); @@ -10620,33 +10619,12 @@ if PyDict_Check(odescr) conv = _convert_from_dict(odescr, 1); else if PyList_Check(odescr) { - conv = _convert_from_list(odescr, 1, 0); - if (conv == NULL) { - /* There is an errror. Possibly it's - because we have an array_descriptor. - Try converting from an array_descriptor. - If that fails then raise the old error. - */ - PyObject *type, *value, *traceback; - PyArray_Descr *temp; - PyErr_Fetch(&type, &value, &traceback); - temp = _convert_from_array_descr(odescr); - if (!PyErr_Occurred()) { - Py_DECREF(temp); - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(traceback); - PyErr_SetString(PyExc_ValueError, - "align cannot be True" \ - " with array_descriptor " \ - "specification."); - } - else { - PyErr_Restore(type, value, traceback); - } - return NULL; - } - } + PyErr_SetString(PyExc_ValueError, + "align cannot be True" \ + " with array_descriptor " \ + "specification."); + return NULL; + } else if PyString_Check(odescr) conv = _convert_from_commastring(odescr, 1); else { @@ -10662,15 +10640,6 @@ return NULL; } - if PyList_Check(odescr) { - conv = _convert_from_array_descr(odescr); - if (!conv) { - PyErr_Clear(); - conv = _convert_from_list(odescr, 0, 0); - } - return (PyObject *)conv; - } - if (!PyArray_DescrConverter(odescr, &conv)) return NULL; /* Get a new copy of it unless it's already a copy */ Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-16 23:14:10 UTC (rev 3030) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-17 01:01:14 UTC (rev 3031) @@ -4246,7 +4246,7 @@ */ static PyArray_Descr * -_convert_from_list(PyObject *obj, int align, int try_descr) +_convert_from_list(PyObject *obj, int align) { int n, i; int totalsize; @@ -4260,6 +4260,11 @@ int hasobject=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); @@ -4304,16 +4309,7 @@ fail: Py_DECREF(nameslist); Py_DECREF(fields); - if (!try_descr) return NULL; - if (align) { - PyErr_SetString(PyExc_ValueError, - "failed to convert from list of formats "\ - "and align cannot be 1 for conversion from "\ - "array_descr structure"); - return NULL; - } - PyErr_Clear(); - return _convert_from_array_descr(obj); + return NULL; } @@ -4348,7 +4344,7 @@ } } else { - res = _convert_from_list(listobj, align, 0); + res = _convert_from_list(listobj, align); } Py_DECREF(listobj); if (!res && !PyErr_Occurred()) { @@ -4716,7 +4712,7 @@ } /* or a list */ else if (PyList_Check(obj)) { - *at = _convert_from_list(obj,0,1); + *at = _convert_from_array_descr(obj); if (*at == NULL) { if (PyErr_Occurred()) return PY_FAIL; goto fail; From numpy-svn at scipy.org Thu Aug 17 03:53:10 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 17 Aug 2006 02:53:10 -0500 (CDT) Subject: [Numpy-svn] r3032 - in trunk/numpy/core: . include/numpy src Message-ID: <20060817075310.1B4CC39C023@new.scipy.org> Author: oliphant Date: 2006-08-17 02:53:01 -0500 (Thu, 17 Aug 2006) New Revision: 3032 Modified: trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/numeric.py trunk/numpy/core/numerictypes.py trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/scalartypes.inc.src Log: Fix mismatch between tp_name and pickle name so that pickles of scalar types will work. Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-17 01:01:14 UTC (rev 3031) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-17 07:53:01 UTC (rev 3032) @@ -977,8 +977,8 @@ /* Size of internal buffers used for alignment */ /* Make BUFSIZE a multiple of sizeof(cdouble) -- ususally 16 */ /* So that ufunc buffers are aligned */ -#define NPY_MIN_BUFSIZE sizeof(cdouble) -#define NPY_MAX_BUFSIZE sizeof(cdouble)*1000000 +#define NPY_MIN_BUFSIZE ((int)sizeof(cdouble)) +#define NPY_MAX_BUFSIZE (((int)sizeof(cdouble))*1000000) #define NPY_BUFSIZE 10000 /* #define NPY_BUFSIZE 80*/ Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-17 01:01:14 UTC (rev 3031) +++ trunk/numpy/core/numeric.py 2006-08-17 07:53:01 UTC (rev 3032) @@ -328,7 +328,7 @@ if typeless and arr.size: return cName + "(%s)" % lst else: - typename=arr.dtype.type.__name__[:-6] + typename=arr.dtype.name lf = '' if issubclass(arr.dtype.type, flexible): typename = str(arr.dtype) Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-17 01:01:14 UTC (rev 3031) +++ trunk/numpy/core/numerictypes.py 2006-08-17 07:53:01 UTC (rev 3032) @@ -106,7 +106,7 @@ def bitname(obj): """Return a bit-width name for a given type object""" - name = obj.__name__[:-6] + name = obj.__name__ base = '' char = '' try: @@ -323,7 +323,7 @@ if g is None: return t t = g - name = t.__name__[:-6] + name = t.__name__ base, bits = _evalname(name) if bits == 0: return t @@ -334,7 +334,7 @@ float: 'float_', complex: 'complex_', bool: 'bool_', - str: 'string', + str: 'string_', unicode: 'unicode_', _types.BufferType: 'void', } Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-17 01:01:14 UTC (rev 3031) +++ trunk/numpy/core/src/arrayobject.c 2006-08-17 07:53:01 UTC (rev 3032) @@ -10441,18 +10441,30 @@ int len; PyTypeObject *typeobj = self->typeobj; PyObject *res; - static int suffix_len=0; + char *s; + static int prefix_len=0; if (PyTypeNum_ISUSERDEF(self->type_num)) { - res = PyString_FromString(typeobj->tp_name); + 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 (suffix_len == 0) - suffix_len = strlen("scalar"); - len = strlen(typeobj->tp_name) - suffix_len; - res = PyString_FromStringAndSize(typeobj->tp_name, len); + 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_ISEXTENDED(self->type_num) && self->elsize != 0) { + if (PyTypeNum_ISFLEXIBLE(self->type_num) && self->elsize != 0) { PyObject *p; p = PyString_FromFormat("%d", self->elsize * 8); PyString_ConcatAndDel(&res, p); Modified: trunk/numpy/core/src/scalartypes.inc.src =================================================================== --- trunk/numpy/core/src/scalartypes.inc.src 2006-08-17 01:01:14 UTC (rev 3031) +++ trunk/numpy/core/src/scalartypes.inc.src 2006-08-17 07:53:01 UTC (rev 3032) @@ -23,7 +23,7 @@ static PyTypeObject Py at NAME@ArrType_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "@name at scalar", /*tp_name*/ + "numpy. at name@", /*tp_name*/ sizeof(PyObject), /*tp_basicsize*/ }; /**end repeat**/ @@ -1652,7 +1652,7 @@ static PyTypeObject PyGenericArrType_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "genericscalar", /*tp_name*/ + "numpy.generic", /*tp_name*/ sizeof(PyObject), /*tp_basicsize*/ }; @@ -2195,7 +2195,7 @@ static PyTypeObject PyObjectArrType_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "objectscalar", /*tp_name*/ + "numpy.object_", /*tp_name*/ sizeof(PyObjectScalarObject), /*tp_basicsize*/ 0, /* tp_itemsize */ (destructor)object_arrtype_dealloc, /* tp_dealloc */ @@ -2219,11 +2219,12 @@ /**begin repeat #name=bool, string, unicode, void# #NAME=Bool, String, Unicode, Void# +#ex=_,_,_,# */ static PyTypeObject Py at NAME@ArrType_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "@name at scalar", /*tp_name*/ + "numpy. at name@@ex@", /*tp_name*/ sizeof(Py at NAME@ScalarObject), /*tp_basicsize*/ }; /**end repeat**/ @@ -2253,7 +2254,7 @@ static PyTypeObject Py at NAME@ArrType_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "@name@" _THIS_SIZE "scalar", /*tp_name*/ + "numpy. at name@" _THIS_SIZE, /*tp_name*/ sizeof(Py at NAME@ScalarObject), /*tp_basicsize*/ }; @@ -2290,7 +2291,7 @@ static PyTypeObject Py at NAME@ArrType_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ - "@name@" _THIS_SIZE1 "scalar", /*tp_name*/ + "numpy. at name@" _THIS_SIZE1, /*tp_name*/ sizeof(Py at NAME@ScalarObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ 0, /*tp_dealloc*/ From numpy-svn at scipy.org Thu Aug 17 14:19:29 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 17 Aug 2006 13:19:29 -0500 (CDT) Subject: [Numpy-svn] r3033 - trunk/numpy/core/src Message-ID: <20060817181929.ADEF739C047@new.scipy.org> Author: oliphant Date: 2006-08-17 13:19:27 -0500 (Thu, 17 Aug 2006) New Revision: 3033 Modified: trunk/numpy/core/src/multiarraymodule.c Log: Alter the naming of un-specified fields to start at 0 Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-17 07:53:01 UTC (rev 3032) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-17 18:19:27 UTC (rev 3033) @@ -4239,7 +4239,7 @@ /* a list specifying a data-type can just be a list of formats. The names for the fields - will default to f1, f2, f3, and so forth. + will default to f0, f1, f2, and so forth. or it can be an array_descr format string -- in which case align must be 0. @@ -4272,7 +4272,7 @@ fields = PyDict_New(); for (i=0; i Author: oliphant Date: 2006-08-17 17:03:38 -0500 (Thu, 17 Aug 2006) New Revision: 3034 Modified: trunk/numpy/oldnumeric/alter_code1.py Log: Fix ticket #252 Modified: trunk/numpy/oldnumeric/alter_code1.py =================================================================== --- trunk/numpy/oldnumeric/alter_code1.py 2006-08-17 18:19:27 UTC (rev 3033) +++ trunk/numpy/oldnumeric/alter_code1.py 2006-08-17 22:03:38 UTC (rev 3034) @@ -64,7 +64,7 @@ def fixtypechars(fstr): for name in _func2 + _func4 + _meth1: - fstr = func2_re[name].sub('\\1B\\2',fstr) + fstr = func_re[name].sub('\\1B\\2',fstr) for char in _chars.keys(): fstr = meth_re[char].sub('\\1%s\\2'%_chars[char], fstr) return fstr From numpy-svn at scipy.org Fri Aug 18 13:01:22 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 18 Aug 2006 12:01:22 -0500 (CDT) Subject: [Numpy-svn] r3035 - in trunk/numpy/core: . include/numpy Message-ID: <20060818170122.F415539C051@new.scipy.org> Author: oliphant Date: 2006-08-18 12:01:19 -0500 (Fri, 18 Aug 2006) New Revision: 3035 Modified: trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/include/numpy/noprefix.h trunk/numpy/core/ma.py Log: Fix ticket #254 and allow defining NPY_NO_PREFIX instead of including 'noprefix.h' Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-17 22:03:38 UTC (rev 3034) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-18 17:01:19 UTC (rev 3035) @@ -6,1550 +6,14 @@ long double is present on platform. CHAR_BIT -- number of bits in a char (usually 8) (should be in limits.h) + */ #ifndef Py_ARRAYOBJECT_H #define Py_ARRAYOBJECT_H -#ifdef __cplusplus -#define CONFUSE_EMACS { -#define CONFUSE_EMACS2 } -extern "C" CONFUSE_EMACS -#undef CONFUSE_EMACS -#undef CONFUSE_EMACS2 -/* ... otherwise a semi-smart idententer (like emacs) tries to indent - everything when you're typing */ +#include "ndarrayobject.h" +#ifdef NPY_NO_PREFIX +#include "noprefix.h" #endif -/* This is auto-generated by the installer */ -#include "config.h" - -/* There are several places in the code where an array of dimensions is */ -/* allocated statically. This is the size of that static allocation. */ -/* The array creation itself could have arbitrary dimensions but - * all the places where static allocation is used would need to - * be changed to dynamic (including inside of several structures) - */ - -#define NPY_MAXDIMS 32 -#define NPY_MAXARGS 32 - -/* Used for Converter Functions "O&" code in ParseTuple */ -#define NPY_FAIL 0 -#define NPY_SUCCEED 1 - - /* Helpful to distinguish what is installed */ -#define NPY_VERSION 0x01000002 - - /* Some platforms don't define bool, long long, or long double. - Handle that here. - */ - -#ifdef PY_LONG_LONG -typedef PY_LONG_LONG npy_longlong; -typedef unsigned PY_LONG_LONG npy_ulonglong; -# ifdef _MSC_VER -# define NPY_LONGLONG_FMT "I64d" -# define NPY_ULONGLONG_FMT "I64u" -# define NPY_LONGLONG_SUFFIX(x) (x##i64) -# define NPY_ULONGLONG_SUFFIX(x) (x##Ui64) -# else - /* #define LONGLONG_FMT "lld" Another possible variant - #define ULONGLONG_FMT "llu" - - #define LONGLONG_FMT "qd" -- BSD perhaps? - #define ULONGLONG_FMT "qu" - */ -# define NPY_LONGLONG_FMT "Ld" -# define NPY_ULONGLONG_FMT "Lu" -# define NPY_LONGLONG_SUFFIX(x) (x##LL) -# define NPY_ULONGLONG_SUFFIX(x) (x##ULL) -# endif -#else -typedef long npy_longlong; -typedef unsigned long npy_ulonglong; -# define NPY_LONGLONG_SUFFIX(x) (x##L) -# define NPY_ULONGLONG_SUFFIX(x) (x##UL) #endif - -typedef unsigned char npy_bool; -#define NPY_FALSE 0 -#define NPY_TRUE 1 - -#if SIZEOF_LONG_DOUBLE==SIZEOF_DOUBLE - typedef double npy_longdouble; - #define NPY_LONGDOUBLE_FMT "g" -#else - typedef long double npy_longdouble; - #define NPY_LONGDOUBLE_FMT "Lg" -#endif - -#ifndef Py_USING_UNICODE -#error Must use Python with unicode enabled. -#endif - - -typedef signed char npy_byte; -typedef unsigned char npy_ubyte; -typedef unsigned short npy_ushort; -typedef unsigned int npy_uint; -typedef unsigned long npy_ulong; - -/* These are for completeness */ -typedef float npy_float; -typedef double npy_double; -typedef short npy_short; -typedef int npy_int; -typedef long npy_long; - -typedef struct { float real, imag; } npy_cfloat; -typedef struct { double real, imag; } npy_cdouble; -typedef struct {npy_longdouble real, imag;} npy_clongdouble; - -enum NPY_TYPES { NPY_BOOL=0, - NPY_BYTE, NPY_UBYTE, - NPY_SHORT, NPY_USHORT, - NPY_INT, NPY_UINT, - NPY_LONG, NPY_ULONG, - NPY_LONGLONG, NPY_ULONGLONG, - NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE, - NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, - NPY_OBJECT=17, - NPY_STRING, NPY_UNICODE, - NPY_VOID, - NPY_NTYPES, - NPY_NOTYPE, - NPY_CHAR, /* special flag */ - NPY_USERDEF=256 /* leave room for characters */ -}; - -/* basetype array priority */ -#define NPY_PRIORITY 0.0 - -/* default subtype priority */ -#define NPY_SUBTYPE_PRIORITY 1.0 - -/* default scalar priority */ -#define NPY_SCALAR_PRIORITY -1000000.0 - -/* How many floating point types are there */ -#define NPY_NUM_FLOATTYPE 3 - -/* We need to match npy_intp to a signed integer of the same size as - a pointer variable. npy_uintp to the equivalent unsigned integer -*/ - - -/* These characters correspond to the array type and the - struct module */ - -/* except 'p' -- signed integer for pointer type */ - -enum NPY_TYPECHAR { NPY_BOOLLTR = '?', - NPY_BYTELTR = 'b', - NPY_UBYTELTR = 'B', - NPY_SHORTLTR = 'h', - NPY_USHORTLTR = 'H', - NPY_INTLTR = 'i', - NPY_UINTLTR = 'I', - NPY_LONGLTR = 'l', - NPY_ULONGLTR = 'L', - NPY_LONGLONGLTR = 'q', - NPY_ULONGLONGLTR = 'Q', - NPY_FLOATLTR = 'f', - NPY_DOUBLELTR = 'd', - NPY_LONGDOUBLELTR = 'g', - NPY_CFLOATLTR = 'F', - NPY_CDOUBLELTR = 'D', - NPY_CLONGDOUBLELTR = 'G', - NPY_OBJECTLTR = 'O', - NPY_STRINGLTR = 'S', - NPY_STRINGLTR2 = 'a', - NPY_UNICODELTR = 'U', - NPY_VOIDLTR = 'V', - NPY_CHARLTR = 'c', - - /* No Descriptor, just a define -- this let's - Python users specify an array of integers - large enough to hold a pointer on the platform*/ - NPY_INTPLTR = 'p', - NPY_UINTPLTR = 'P', - - NPY_GENBOOLLTR ='b', - NPY_SIGNEDLTR = 'i', - NPY_UNSIGNEDLTR = 'u', - NPY_FLOATINGLTR = 'f', - NPY_COMPLEXLTR = 'c' -}; - -typedef enum { - NPY_QUICKSORT=0, - NPY_HEAPSORT=1, - NPY_MERGESORT=2, -} NPY_SORTKIND; -#define NPY_NSORTS NPY_MERGESORT + 1 - - -typedef enum { - NPY_NOSCALAR=-1, - NPY_BOOL_SCALAR, - NPY_INTPOS_SCALAR, - NPY_INTNEG_SCALAR, - NPY_FLOAT_SCALAR, - NPY_COMPLEX_SCALAR, - NPY_OBJECT_SCALAR, -} NPY_SCALARKIND; -#define NPY_NSCALARKINDS NPY_OBJECT_SCALAR+1 - -typedef enum { - NPY_ANYORDER=-1, - NPY_CORDER=0, - NPY_FORTRANORDER=1 -} NPY_ORDER; - - -typedef enum { - NPY_CLIP=0, - NPY_WRAP=1, - NPY_RAISE=2 -} NPY_CLIPMODE; - - /* Define bit-width array types and typedefs */ - -#define NPY_MAX_INT8 127 -#define NPY_MIN_INT8 -128 -#define NPY_MAX_UINT8 255 -#define NPY_MAX_INT16 32767 -#define NPY_MIN_INT16 -32768 -#define NPY_MAX_UINT16 65535 -#define NPY_MAX_INT32 2147483647 -#define NPY_MIN_INT32 (-NPY_MAX_INT32 - 1) -#define NPY_MAX_UINT32 4294967295U -#define NPY_MAX_INT64 NPY_LONGLONG_SUFFIX(9223372036854775807) -#define NPY_MIN_INT64 (-NPY_MAX_INT64 - NPY_LONGLONG_SUFFIX(1)) -#define NPY_MAX_UINT64 NPY_ULONGLONG_SUFFIX(18446744073709551615) -#define NPY_MAX_INT128 NPY_LONGLONG_SUFFIX(85070591730234615865843651857942052864) -#define NPY_MIN_INT128 (-NPY_MAX_INT128 - NPY_LONGLONG_SUFFIX(1)) -#define NPY_MAX_UINT128 NPY_ULONGLONG_SUFFIX(170141183460469231731687303715884105728) -#define NPY_MAX_INT256 NPY_LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967) -#define NPY_MIN_INT256 (-NPY_MAX_INT256 - NPY_LONGLONG_SUFFIX(1)) -#define NPY_MAX_UINT256 NPY_ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935) - - /* Need to find the number of bits for each type and - make definitions accordingly. - - C states that sizeof(char) == 1 by definition - - So, just using the sizeof keyword won't help. - - It also looks like Python itself uses sizeof(char) quite a - bit, which by definition should be 1 all the time. - - Idea: Make Use of CHAR_BIT which should tell us how many - BITS per CHARACTER - */ - - /* Include platform definitions -- These are in the C89/90 standard */ -#include -#define NPY_MAX_BYTE SCHAR_MAX -#define NPY_MIN_BYTE SCHAR_MIN -#define NPY_MAX_UBYTE UCHAR_MAX -#define NPY_MAX_SHORT SHRT_MAX -#define NPY_MIN_SHORT SHRT_MIN -#define NPY_MAX_USHORT USHRT_MAX -#define NPY_MAX_INT INT_MAX -#ifndef INT_MIN -#define INT_MIN (-INT_MAX - 1) -#endif -#define NPY_MIN_INT INT_MIN -#define NPY_MAX_UINT UINT_MAX -#define NPY_MAX_LONG LONG_MAX -#define NPY_MIN_LONG LONG_MIN -#define NPY_MAX_ULONG ULONG_MAX - - -#define NPY_SIZEOF_LONG SIZEOF_LONG -#define NPY_SIZEOF_INT SIZEOF_INT -#define NPY_SIZEOF_SHORT SIZEOF_SHORT -#define NPY_SIZEOF_FLOAT SIZEOF_FLOAT -#define NPY_SIZEOF_DOUBLE SIZEOF_DOUBLE -#define NPY_SIZEOF_LONGDOUBLE SIZEOF_LONG_DOUBLE -#define NPY_SIZEOF_LONGLONG SIZEOF_LONG_LONG -#define NPY_BITSOF_BOOL sizeof(npy_bool)*CHAR_BIT -#define NPY_BITSOF_CHAR CHAR_BIT -#define NPY_BITSOF_SHORT (SIZEOF_SHORT*CHAR_BIT) -#define NPY_BITSOF_INT (SIZEOF_INT*CHAR_BIT) -#define NPY_BITSOF_LONG (SIZEOF_LONG*CHAR_BIT) -#define NPY_BITSOF_LONGLONG (NPY_SIZEOF_LONGLONG*CHAR_BIT) -#define NPY_BITSOF_FLOAT (SIZEOF_FLOAT*CHAR_BIT) -#define NPY_BITSOF_DOUBLE (SIZEOF_DOUBLE*CHAR_BIT) -#define NPY_BITSOF_LONGDOUBLE (NPY_SIZEOF_LONGDOUBLE*CHAR_BIT) - -#if NPY_BITSOF_LONG == 8 -#define NPY_INT8 NPY_LONG -#define NPY_UINT8 NPY_ULONG - typedef long npy_int8; - typedef unsigned long npy_uint8; -#elif NPY_BITSOF_LONG == 16 -#define NPY_INT16 NPY_LONG -#define NPY_UINT16 NPY_ULONG - typedef long npy_int16; - typedef unsigned long npy_uint16; -#elif NPY_BITSOF_LONG == 32 -#define NPY_INT32 NPY_LONG -#define NPY_UINT32 NPY_ULONG - typedef long npy_int32; - typedef unsigned long npy_uint32; - typedef unsigned long npy_ucs4; -#elif NPY_BITSOF_LONG == 64 -#define NPY_INT64 NPY_LONG -#define NPY_UINT64 NPY_ULONG - typedef long npy_int64; - typedef unsigned long npy_uint64; -#elif NPY_BITSOF_LONG == 128 -#define NPY_INT128 NPY_LONG -#define NPY_UINT128 NPY_ULONG - typedef long npy_int128; - typedef unsigned long npy_uint128; -#endif - -#if NPY_BITSOF_LONGLONG == 8 -# ifndef NPY_INT8 -# define NPY_INT8 NPY_LONGLONG -# define NPY_UINT8 NPY_ULONGLONG - typedef npy_longlong npy_int8; - typedef npy_ulonglong npy_uint8; -# endif -# define NPY_MAX_LONGLONG NPY_MAX_INT8 -# define NPY_MIN_LONGLONG NPY_MIN_INT8 -# define NPY_MAX_ULONGLONG NPY_MAX_UINT8 -#elif NPY_BITSOF_LONGLONG == 16 -# ifndef NPY_INT16 -# define NPY_INT16 NPY_LONGLONG -# define NPY_UINT16 NPY_ULONGLONG - typedef npy_longlong npy_int16; - typedef npy_ulonglong npy_uint16; -# endif -# define NPY_MAX_LONGLONG NPY_MAX_INT16 -# define NPY_MIN_LONGLONG NPY_MIN_INT16 -# define NPY_MAX_ULONGLONG NPY_MAX_UINT16 -#elif NPY_BITSOF_LONGLONG == 32 -# ifndef NPY_INT32 -# define NPY_INT32 NPY_LONGLONG -# define NPY_UINT32 NPY_ULONGLONG - typedef npy_longlong npy_int32; - typedef npy_ulonglong npy_uint32; - typedef npy_ulonglong npy_ucs4; -# endif -# define NPY_MAX_LONGLONG NPY_MAX_INT32 -# define NPY_MIN_LONGLONG NPY_MIN_INT32 -# define NPY_MAX_ULONGLONG NPY_MAX_UINT32 -#elif NPY_BITSOF_LONGLONG == 64 -# ifndef NPY_INT64 -# define NPY_INT64 NPY_LONGLONG -# define NPY_UINT64 NPY_ULONGLONG - typedef npy_longlong npy_int64; - typedef npy_ulonglong npy_uint64; -# endif -# define NPY_MAX_LONGLONG NPY_MAX_INT64 -# define NPY_MIN_LONGLONG NPY_MIN_INT64 -# define NPY_MAX_ULONGLONG NPY_MAX_UINT64 -#elif NPY_BITSOF_LONGLONG == 128 -# ifndef NPY_INT128 -# define NPY_INT128 NPY_LONGLONG -# define NPY_UINT128 NPY_ULONGLONG - typedef npy_longlong npy_int128; - typedef npy_ulonglong npy_uint128; -# endif -# define NPY_MAX_LONGLONG NPY_MAX_INT128 -# define NPY_MIN_LONGLONG NPY_MIN_INT128 -# define NPY_MAX_ULONGLONG NPY_MAX_UINT128 -#elif NPY_BITSOF_LONGLONG == 256 -# define NPY_INT256 NPY_LONGLONG -# define NPY_UINT256 NPY_ULONGLONG - typedef npy_longlong npy_int256; - typedef npy_ulonglong npy_uint256; -# define NPY_MAX_LONGLONG NPY_MAX_INT256 -# define NPY_MIN_LONGLONG NPY_MIN_INT256 -# define NPY_MAX_ULONGLONG NPY_MAX_UINT256 -#endif - -#if NPY_BITSOF_INT == 8 -#ifndef NPY_INT8 -#define NPY_INT8 NPY_INT -#define NPY_UINT8 NPY_UINT - typedef int npy_int8; - typedef unsigned int npy_uint8; -#endif -#elif NPY_BITSOF_INT == 16 -#ifndef NPY_INT16 -#define NPY_INT16 NPY_INT -#define NPY_UINT16 NPY_UINT - typedef int npy_int16; - typedef unsigned int npy_uint16; -#endif -#elif NPY_BITSOF_INT == 32 -#ifndef NPY_INT32 -#define NPY_INT32 NPY_INT -#define NPY_UINT32 NPY_UINT - typedef int npy_int32; - typedef unsigned int npy_uint32; - typedef unsigned int npy_ucs4; -#endif -#elif NPY_BITSOF_INT == 64 -#ifndef NPY_INT64 -#define NPY_INT64 NPY_INT -#define NPY_UINT64 NPY_UINT - typedef int npy_int64; - typedef unsigned int npy_uint64; -#endif -#elif NPY_BITSOF_INT == 128 -#ifndef NPY_INT128 -#define NPY_INT128 NPY_INT -#define NPY_UINT128 NPY_UINT - typedef int npy_int128; - typedef unsigned int npy_uint128; -#endif -#endif - -#if NPY_BITSOF_SHORT == 8 -#ifndef NPY_INT8 -#define NPY_INT8 NPY_SHORT -#define NPY_UINT8 NPY_USHORT - typedef short npy_int8; - typedef unsigned short npy_uint8; -#endif -#elif NPY_BITSOF_SHORT == 16 -#ifndef NPY_INT16 -#define NPY_INT16 NPY_SHORT -#define NPY_UINT16 NPY_USHORT - typedef short npy_int16; - typedef unsigned short npy_uint16; -#endif -#elif NPY_BITSOF_SHORT == 32 -#ifndef NPY_INT32 -#define NPY_INT32 NPY_SHORT -#define NPY_UINT32 NPY_USHORT - typedef short npy_int32; - typedef unsigned short npy_uint32; - typedef unsigned short npy_ucs4; -#endif -#elif NPY_BITSOF_SHORT == 64 -#ifndef NPY_INT64 -#define NPY_INT64 NPY_SHORT -#define NPY_UINT64 NPY_USHORT - typedef short npy_int64; - typedef unsigned short npy_uint64; -#endif -#elif NPY_BITSOF_SHORT == 128 -#ifndef NPY_INT128 -#define NPY_INT128 NPY_SHORT -#define NPY_UINT128 NPY_USHORT - typedef short npy_int128; - typedef unsigned short npy_uint128; -#endif -#endif - - -#if NPY_BITSOF_CHAR == 8 -#ifndef NPY_INT8 -#define NPY_INT8 NPY_BYTE -#define NPY_UINT8 NPY_UBYTE - typedef signed char npy_int8; - typedef unsigned char npy_uint8; -#endif -#elif NPY_BITSOF_CHAR == 16 -#ifndef NPY_INT16 -#define NPY_INT16 NPY_BYTE -#define NPY_UINT16 NPY_UBYTE - typedef signed char npy_int16; - typedef unsigned char npy_uint16; -#endif -#elif NPY_BITSOF_CHAR == 32 -#ifndef NPY_INT32 -#define NPY_INT32 NPY_BYTE -#define NPY_UINT32 NPY_UBYTE - typedef signed char npy_int32; - typedef unsigned char npy_uint32; - typedef unsigned char npy_ucs4; -#endif -#elif NPY_BITSOF_CHAR == 64 -#ifndef NPY_INT64 -#define NPY_INT64 NPY_BYTE -#define NPY_UINT64 NPY_UBYTE - typedef signed char npy_int64; - typedef unsigned char npy_uint64; -#endif -#elif NPY_BITSOF_CHAR == 128 -#ifndef NPY_INT128 -#define NPY_INT128 NPY_BYTE -#define NPY_UINT128 NPY_UBYTE - typedef signed char npy_int128; - typedef unsigned char npy_uint128; -#endif -#endif - - - -#if NPY_BITSOF_DOUBLE == 16 -#ifndef NPY_FLOAT16 -#define NPY_FLOAT16 NPY_DOUBLE -#define NPY_COMPLEX32 NPY_CDOUBLE - typedef double npy_float16; - typedef npy_cdouble npy_complex32; -#endif -#elif NPY_BITSOF_DOUBLE == 32 -#ifndef NPY_FLOAT32 -#define NPY_FLOAT32 NPY_DOUBLE -#define NPY_COMPLEX64 NPY_CDOUBLE - typedef double npy_float32; - typedef npy_cdouble npy_complex64; -#endif -#elif NPY_BITSOF_DOUBLE == 64 -#ifndef NPY_FLOAT64 -#define NPY_FLOAT64 NPY_DOUBLE -#define NPY_COMPLEX128 NPY_CDOUBLE - typedef double npy_float64; - typedef npy_cdouble npy_complex128; -#endif -#elif NPY_BITSOF_DOUBLE == 80 -#ifndef NPY_FLOAT80 -#define NPY_FLOAT80 NPY_DOUBLE -#define NPY_COMPLEX160 NPY_CDOUBLE - typedef double npy_float80; - typedef npy_cdouble npy_complex160; -#endif -#elif NPY_BITSOF_DOUBLE == 96 -#ifndef NPY_FLOAT96 -#define NPY_FLOAT96 NPY_DOUBLE -#define NPY_COMPLEX192 NPY_CDOUBLE - typedef double npy_float96; - typedef npy_cdouble npy_complex192; -#endif -#elif NPY_BITSOF_DOUBLE == 128 -#ifndef NPY_FLOAT128 -#define NPY_FLOAT128 NPY_DOUBLE -#define NPY_COMPLEX256 NPY_CDOUBLE - typedef double npy_float128; - typedef npy_cdouble npy_complex256; -#endif -#endif - - - -#if NPY_BITSOF_FLOAT == 16 -#ifndef NPY_FLOAT16 -#define NPY_FLOAT16 NPY_FLOAT -#define NPY_COMPLEX32 NPY_CFLOAT - typedef float npy_float16; - typedef npy_cfloat npy_complex32; -#endif -#elif NPY_BITSOF_FLOAT == 32 -#ifndef NPY_FLOAT32 -#define NPY_FLOAT32 NPY_FLOAT -#define NPY_COMPLEX64 NPY_CFLOAT - typedef float npy_float32; - typedef npy_cfloat npy_complex64; -#endif -#elif NPY_BITSOF_FLOAT == 64 -#ifndef NPY_FLOAT64 -#define NPY_FLOAT64 NPY_FLOAT -#define NPY_COMPLEX128 NPY_CFLOAT - typedef float npy_float64; - typedef npy_cfloat npy_complex128; -#endif -#elif NPY_BITSOF_FLOAT == 80 -#ifndef NPY_FLOAT80 -#define NPY_FLOAT80 NPY_FLOAT -#define NPY_COMPLEX160 NPY_CFLOAT - typedef float npy_float80; - typedef npy_cfloat npy_complex160; -#endif -#elif NPY_BITSOF_FLOAT == 96 -#ifndef NPY_FLOAT96 -#define NPY_FLOAT96 NPY_FLOAT -#define NPY_COMPLEX192 NPY_CFLOAT - typedef float npy_float96; - typedef npy_cfloat npy_complex192; -#endif -#elif NPY_BITSOF_FLOAT == 128 -#ifndef NPY_FLOAT128 -#define NPY_FLOAT128 NPY_FLOAT -#define NPY_COMPLEX256 NPY_CFLOAT - typedef float npy_float128; - typedef npy_cfloat npy_complex256; -#endif -#endif - - -#if NPY_BITSOF_LONGDOUBLE == 16 -#ifndef NPY_FLOAT16 -#define NPY_FLOAT16 NPY_LONGDOUBLE -#define NPY_COMPLEX32 NPY_CLONGDOUBLE - typedef npy_longdouble npy_float16; - typedef npy_clongdouble npy_complex32; -#endif -#elif NPY_BITSOF_LONGDOUBLE == 32 -#ifndef NPY_FLOAT32 -#define NPY_FLOAT32 NPY_LONGDOUBLE -#define NPY_COMPLEX64 NPY_CLONGDOUBLE - typedef npy_longdouble npy_float32; - typedef npy_clongdouble npy_complex64; -#endif -#elif NPY_BITSOF_LONGDOUBLE == 64 -#ifndef NPY_FLOAT64 -#define NPY_FLOAT64 NPY_LONGDOUBLE -#define NPY_COMPLEX128 NPY_CLONGDOUBLE - typedef npy_longdouble npy_float64; - typedef npy_clongdouble npy_complex128; -#endif -#elif NPY_BITSOF_LONGDOUBLE == 80 -#ifndef NPY_FLOAT80 -#define NPY_FLOAT80 NPY_LONGDOUBLE -#define NPY_COMPLEX160 NPY_CLONGDOUBLE - typedef npy_longdouble npy_float80; - typedef npy_clongdouble npy_complex160; -#endif -#elif NPY_BITSOF_LONGDOUBLE == 96 -#ifndef NPY_FLOAT96 -#define NPY_FLOAT96 NPY_LONGDOUBLE -#define NPY_COMPLEX192 NPY_CLONGDOUBLE - typedef npy_longdouble npy_float96; - typedef npy_clongdouble npy_complex192; -#endif -#elif NPY_BITSOF_LONGDOUBLE == 128 -#ifndef NPY_FLOAT128 -#define NPY_FLOAT128 NPY_LONGDOUBLE -#define NPY_COMPLEX256 NPY_CLONGDOUBLE - typedef npy_longdouble npy_float128; - typedef npy_clongdouble npy_complex256; -#endif -#elif NPY_BITSOF_LONGDOUBLE == 256 -#define NPY_FLOAT256 NPY_LONGDOUBLE -#define NPY_COMPLEX512 NPY_CLONGDOUBLE - typedef npy_longdouble npy_float256; - typedef npy_clongdouble npy_complex512; -#endif - - /* End of typedefs for numarray style bit-width names */ - -/* This is to typedef npy_intp to the appropriate pointer size for this platform. - * Py_intptr_t, Py_uintptr_t are defined in pyport.h. */ -typedef Py_intptr_t npy_intp; -typedef Py_uintptr_t npy_uintp; -#define NPY_SIZEOF_INTP SIZEOF_PY_INTPTR_T -#define NPY_SIZEOF_UINTP SIZEOF_PY_INTPTR_T - -#if (PY_VERSION_HEX < 0x02050000) -typedef int Py_ssize_t; -#define PY_SSIZE_T_MAX INT_MAX -#define PY_SSIZE_T_MIN INT_MIN -#define NPY_SSIZE_T_PYFMT "i" -#define constchar const char -#else -#define NPY_SSIZE_T_PYFMT "n" -#define constchar char -#endif - -#if SIZEOF_PY_INTPTR_T == SIZEOF_INT - #define NPY_INTP NPY_INT - #define NPY_UINTP NPY_UINT - #define PyIntpArrType_Type PyIntArrType_Type - #define PyUIntpArrType_Type PyUIntArrType_Type - #define NPY_MAX_INTP NPY_MAX_INT - #define NPY_MIN_INTP NPY_MIN_INT - #define NPY_MAX_UINTP NPY_MAX_UINT - #define NPY_INTP_FMT "d" -#elif SIZEOF_PY_INTPTR_T == SIZEOF_LONG - #define NPY_INTP NPY_LONG - #define NPY_UINTP NPY_ULONG - #define PyIntpArrType_Type PyLongArrType_Type - #define PyUIntpArrType_Type PyULongArrType_Type - #define NPY_MAX_INTP NPY_MAX_LONG - #define NPY_MIN_INTP MIN_LONG - #define NPY_MAX_UINTP NPY_MAX_ULONG - #define NPY_INTP_FMT "ld" -#elif defined(PY_LONG_LONG) && (SIZEOF_PY_INTPTR_T == SIZEOF_LONG_LONG) - #define NPY_INTP NPY_LONGLONG - #define NPY_UINTP NPY_ULONGLONG - #define PyIntpArrType_Type PyLongLongArrType_Type - #define PyUIntpArrType_Type PyULongLongArrType_Type - #define NPY_MAX_INTP NPY_MAX_LONGLONG - #define NPY_MIN_INTP NPY_MIN_LONGLONG - #define NPY_MAX_UINTP NPY_MAX_ULONGLONG - #define NPY_INTP_FMT "Ld" -#endif - -#define NPY_ERR(str) fprintf(stderr, #str); fflush(stderr); -#define NPY_ERR2(str) fprintf(stderr, str); fflush(stderr); - -#define NPY_STRINGIFY(x) #x -#define NPY_TOSTRING(x) NPY_STRINGIFY(x) - - /* Macros to define how array, and dimension/strides data is - allocated. - */ - - /* Data buffer */ -#define PyDataMem_NEW(size) ((char *)malloc(size)) - /* #define PyArrayMem_NEW(size) PyMem_NEW(char, size)*/ -#define PyDataMem_FREE(ptr) free(ptr) - /* #define PyArrayMem_FREE(ptr) PyMem_Free(ptr) */ -#define PyDataMem_RENEW(ptr,size) ((char *)realloc(ptr,size)) - -#define NPY_USE_PYMEM 0 - -#if NPY_USE_PYMEM == 1 -#define PyArray_malloc PyObject_Malloc -#define PyArray_free PyObject_Free -#define PyArray_realloc PyObject_Realloc -#else -#define PyArray_malloc malloc -#define PyArray_free free -#define PyArray_realloc realloc -#endif - -/* Dimensions and strides */ -#define PyDimMem_NEW(size) ((npy_intp *)PyArray_malloc(size*sizeof(npy_intp))) -#define PyDimMem_FREE(ptr) PyArray_free(ptr) -#define PyDimMem_RENEW(ptr,size) ((npy_intp *)PyArray_realloc(ptr,size*sizeof(npy_intp))) - - - /* These must deal with unaligned and swapped data if necessary */ -typedef PyObject * (PyArray_GetItemFunc) (void *, void *); -typedef int (PyArray_SetItemFunc)(PyObject *, void *, void *); - -typedef void (PyArray_CopySwapNFunc)(void *, npy_intp, void *, npy_intp, npy_intp, int, void *); -typedef void (PyArray_CopySwapFunc)(void *, void *, int, void *); -typedef npy_bool (PyArray_NonzeroFunc)(void *, void *); - - - /* These assume aligned and notswapped data -- a buffer will be - used before or contiguous data will be obtained - */ -typedef int (PyArray_CompareFunc)(const void *, const void *, void *); -typedef int (PyArray_ArgFunc)(void*, npy_intp, npy_intp*, void *); -typedef void (PyArray_DotFunc)(void *, npy_intp, void *, npy_intp, void *, npy_intp, - void *); -typedef void (PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *); -typedef int (PyArray_ScanFunc)(FILE *, void *, void *, void *); -typedef int (PyArray_FromStrFunc)(char *, void *, char **, void *); - -typedef int (PyArray_FillFunc)(void *, npy_intp, void *); - -typedef int (PyArray_SortFunc)(void *, npy_intp, void *); -typedef int (PyArray_ArgSortFunc)(void *, npy_intp *, npy_intp, void *); - -typedef int (PyArray_FillWithScalarFunc)(void *, npy_intp, void *, void *); - -typedef int (PyArray_ScalarKindFunc)(void *); - -typedef struct { - npy_intp *ptr; - int len; -} PyArray_Dims; - -typedef struct { - /* Functions to cast to all other standard types*/ - /* Can have some NULL entries */ - PyArray_VectorUnaryFunc *cast[NPY_NTYPES]; - - /* The next four functions *cannot* be NULL */ - - /* Functions to get and set items with standard - Python types -- not array scalars */ - PyArray_GetItemFunc *getitem; - PyArray_SetItemFunc *setitem; - - /* Copy and/or swap data. Memory areas may not overlap */ - /* Use memmove first if they might */ - PyArray_CopySwapNFunc *copyswapn; - PyArray_CopySwapFunc *copyswap; - - /* Function to compare items */ - /* Can be NULL - */ - PyArray_CompareFunc *compare; - - /* Function to select largest - Can be NULL - */ - PyArray_ArgFunc *argmax; - - /* Function to compute dot product */ - /* Can be NULL */ - PyArray_DotFunc *dotfunc; - - /* Function to scan an ASCII file and - place a single value plus possible separator - Can be NULL - */ - PyArray_ScanFunc *scanfunc; - - /* Function to read a single value from a string */ - /* and adjust the pointer; Can be NULL */ - PyArray_FromStrFunc *fromstr; - - /* Function to determine if data is zero or not */ - /* If NULL a default version is */ - /* used at Registration time. */ - PyArray_NonzeroFunc *nonzero; - - /* Used for arange. Can be NULL.*/ - PyArray_FillFunc *fill; - - /* Function to fill arrays with scalar values - Can be NULL*/ - PyArray_FillWithScalarFunc *fillwithscalar; - - /* Sorting functions; Can be NULL*/ - PyArray_SortFunc *sort[NPY_NSORTS]; - PyArray_ArgSortFunc *argsort[NPY_NSORTS]; - - /* Dictionary of additional casting functions - PyArray_VectorUnaryFuncs - which can be populated to support casting - to other registered types. Can be NULL*/ - PyObject *castdict; - - /* Functions useful for generalizing - the casting rules. Can be NULL; - */ - PyArray_ScalarKindFunc *scalarkind; - int **cancastscalarkindto; - int *cancastto; - - /* Set to 1 if you want pickles of this type - to go out as lists of _getitem objects - */ - int listpickle; - -} PyArray_ArrFuncs; - - -typedef struct { - PyObject_HEAD - PyTypeObject *typeobj; /* the type object representing an - instance of this type -- should not - be two type_numbers with the same type - object. */ - char kind; /* kind for this type */ - char type; /* unique-character representing this type */ - char byteorder; /* '>' (big), '<' (little), '|' - (not-applicable), or '=' (native). */ - char hasobject; /* non-zero if it has object arrays in fields */ - int type_num; /* number representing this type */ - int elsize; /* element size for this type */ - int alignment; /* alignment needed for this type */ - struct _arr_descr \ - *subarray; /* Non-NULL if this type is - is an array (C-contiguous) - of some other type - */ - PyObject *fields; /* The fields dictionary for this type */ - /* For statically defined descr this - is always Py_None */ - - PyObject *names; /* An ordered tuple of field names or NULL - if no fields are defined */ - - PyArray_ArrFuncs *f; /* a table of functions specific for each - basic data descriptor */ -} PyArray_Descr; - -typedef struct _arr_descr { - PyArray_Descr *base; - PyObject *shape; /* a tuple */ -} PyArray_ArrayDescr; - -/* - The main array object structure. It is recommended to use the macros - defined below (PyArray_DATA and friends) access fields here, instead - of the members themselves. - */ - -typedef struct PyArrayObject { - PyObject_HEAD - char *data; /* pointer to raw data buffer */ - int nd; /* number of dimensions, also called ndim */ - npy_intp *dimensions; /* size in each dimension */ - npy_intp *strides; /* bytes to jump to get to the - next element in each dimension */ - PyObject *base; /* This object should be decref'd - upon deletion of array */ - /* For views it points to the original array */ - /* For creation from buffer object it points - to an object that shold be decref'd on - deletion */ - /* For UPDATEIFCOPY flag this is an array - to-be-updated upon deletion of this one */ - PyArray_Descr *descr; /* Pointer to type structure */ - int flags; /* Flags describing array -- see below*/ - PyObject *weakreflist; /* For weakreferences */ -} PyArrayObject; - -#define NPY_AO PyArrayObject - -#define fortran fortran_ /* For some compilers */ - -/* Mirrors buffer object to ptr */ - -typedef struct { - PyObject_HEAD - PyObject *base; - void *ptr; - npy_intp len; - int flags; -} PyArray_Chunk; - -typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *); - -/* Means c-style contiguous (last index varies the fastest). The - data elements right after each other. */ -#define NPY_CONTIGUOUS 0x0001 -/* set if array is a contiguous Fortran array: the first index - varies the fastest in memory (strides array is reverse of - C-contiguous array)*/ -#define NPY_FORTRAN 0x0002 - -/* - Note: all 0-d arrays are CONTIGUOUS and FORTRAN contiguous. If a - 1-d array is CONTIGUOUS it is also FORTRAN contiguous -*/ - -/* If set, the array owns the data: it will be free'd when the array - is deleted. */ -#define NPY_OWNDATA 0x0004 - -/* An array never has the next four set; they're only used as parameter - flags to the the various FromAny functions */ - -/* Cause a cast to occur regardless of whether or not it is safe. */ -#define NPY_FORCECAST 0x0010 - -/* Always copy the array. Returned arrays are always CONTIGUOUS, ALIGNED, - and WRITEABLE. */ -#define NPY_ENSURECOPY 0x0020 - -/* Make sure the returned array is an ndarray or a bigndarray */ -#define NPY_ENSUREARRAY 0x0040 - -/* Make sure that the strides are in units of the element size - Needed for some operations with record-arrays. -*/ -#define NPY_ELEMENTSTRIDES 0x0080 - -/* Array data is aligned on the appropiate memory address for the - type stored according to how the compiler would align things - (e.g., an array of integers (4 bytes each) starts on - a memory address that's a multiple of 4) */ -#define NPY_ALIGNED 0x0100 -/* Array data has the native endianness */ -#define NPY_NOTSWAPPED 0x0200 -/* Array data is writeable */ -#define NPY_WRITEABLE 0x0400 -/* If this flag is set, then base contains a pointer to an array of - the same size that should be updated with the current contents of - this array when this array is deallocated -*/ -#define NPY_UPDATEIFCOPY 0x1000 - -/* This flag is for the array interface */ -#define NPY_ARR_HAS_DESCR 0x0800 - - -#define NPY_BEHAVED NPY_ALIGNED | NPY_WRITEABLE -#define NPY_BEHAVED_NS NPY_ALIGNED | NPY_WRITEABLE | NPY_NOTSWAPPED -#define NPY_CARRAY NPY_CONTIGUOUS | NPY_BEHAVED -#define NPY_CARRAY_RO NPY_CONTIGUOUS | NPY_ALIGNED -#define NPY_FARRAY NPY_FORTRAN | NPY_BEHAVED -#define NPY_FARRAY_RO NPY_FORTRAN | NPY_ALIGNED -#define NPY_DEFAULT NPY_CARRAY -#define NPY_IN_ARRAY NPY_CARRAY_RO -#define NPY_OUT_ARRAY NPY_CARRAY -#define NPY_INOUT_ARRAY NPY_CARRAY | NPY_UPDATEIFCOPY -#define NPY_IN_FARRAY NPY_FARRAY_RO -#define NPY_OUT_FARRAY NPY_FARRAY -#define NPY_INOUT_FARRAY NPY_FARRAY | NPY_UPDATEIFCOPY - -#define NPY_UPDATE_ALL NPY_CONTIGUOUS | NPY_FORTRAN | NPY_ALIGNED - - -/* Size of internal buffers used for alignment */ -/* Make BUFSIZE a multiple of sizeof(cdouble) -- ususally 16 */ -/* So that ufunc buffers are aligned */ -#define NPY_MIN_BUFSIZE ((int)sizeof(cdouble)) -#define NPY_MAX_BUFSIZE (((int)sizeof(cdouble))*1000000) -#define NPY_BUFSIZE 10000 -/* #define NPY_BUFSIZE 80*/ - -#define PyArray_MAX(a,b) (((a)>(b))?(a):(b)) -#define PyArray_MIN(a,b) (((a)<(b))?(a):(b)) - - -/* - * C API: consists of Macros and functions. The MACROS are defined here. - */ - - -#define PyArray_CHKFLAGS(m, FLAGS) \ - ((((PyArrayObject *)(m))->flags & (FLAGS)) == (FLAGS)) -#define PyArray_ISCONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_CONTIGUOUS) -#define PyArray_ISWRITEABLE(m) PyArray_CHKFLAGS(m, NPY_WRITEABLE) -#define PyArray_ISALIGNED(m) PyArray_CHKFLAGS(m, NPY_ALIGNED) - - -#if NPY_ALLOW_THREADS -#define NPY_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS -#define NPY_END_ALLOW_THREADS Py_END_ALLOW_THREADS -#define NPY_BEGIN_THREADS_DEF PyThreadState *_save=NULL; -#define NPY_BEGIN_THREADS _save = PyEval_SaveThread(); -#define NPY_END_THREADS if (_save) PyEval_RestoreThread(_save); -#define NPY_BEGIN_THREADS_DESCR(dtype) if (!((dtype)->hasobject)) NPY_BEGIN_THREADS -#define NPY_END_THREADS_DESCR(dtype) if (!((dtype)->hasobject)) NPY_END_THREADS -#define NPY_ALLOW_C_API_DEF PyGILState_STATE __save__; -#define NPY_ALLOW_C_API __save__ = PyGILState_Ensure(); -#define NPY_DISABLE_C_API PyGILState_Release(__save__); -#else -#define NPY_BEGIN_ALLOW_THREADS -#define NPY_END_ALLOW_THREADS -#define NPY_BEGIN_THREADS_DEF -#define NPY_BEGIN_THREADS -#define NPY_END_THREADS -#define NPY_BEGIN_THREADS_DESCR(dtype) -#define NPY_END_THREADS_DESCR(dtype) -#define NPY_ALLOW_C_API_DEF -#define NPY_ALLOW_C_API -#define NPY_DISABLE_C_API -#endif - -typedef struct { - PyObject_HEAD - int nd_m1; /* number of dimensions - 1 */ - npy_intp index, size; - npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */ - npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */ - npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */ - npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */ - npy_intp factors[NPY_MAXDIMS]; /* shape factors */ - PyArrayObject *ao; - char *dataptr; /* pointer to current item*/ - npy_bool contiguous; -} PyArrayIterObject; - - -/* Iterator API */ -#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type) - -#define PyArray_ITER_RESET(it) { \ - (it)->index = 0; \ - (it)->dataptr = (it)->ao->data; \ - memset((it)->coordinates, 0, ((it)->nd_m1+1)*sizeof(npy_intp)); \ -} - -#define _PyArray_ITER_NEXT1(it) { \ - (it)->dataptr += (it)->strides[0]; \ - (it)->coordinates[0]++; \ - } - -#define _PyArray_ITER_NEXT2(it) { \ - if ((it)->coordinates[1] < (it)->dims_m1[1]) { \ - (it)->coordinates[1]++; \ - (it)->dataptr += (it)->strides[1]; \ - } \ - else { \ - (it)->coordinates[1] = 0; \ - (it)->coordinates[0]++; \ - (it)->dataptr += (it)->strides[0] - \ - (it)->backstrides[1]; \ - } \ - } - -#define PyArray_ITER_NEXT(it) { \ - (it)->index++; \ - if ((it)->nd_m1 == 0) { \ - _PyArray_ITER_NEXT1(it); \ - } \ - else if ((it)->contiguous) (it)->dataptr += (it)->ao->descr->elsize; \ - else if ((it)->nd_m1 == 1) { \ - _PyArray_ITER_NEXT2(it); \ - } \ - else { \ - int __npy_i; \ - for (__npy_i = (it)->nd_m1; __npy_i >= 0; __npy_i--) { \ - if ((it)->coordinates[__npy_i] < \ - (it)->dims_m1[__npy_i]) { \ - (it)->coordinates[__npy_i]++; \ - (it)->dataptr += (it)->strides[__npy_i]; \ - break; \ - } \ - else { \ - (it)->coordinates[__npy_i] = 0; \ - (it)->dataptr -= (it)->backstrides[__npy_i]; \ - } \ - } \ - } \ -} - -#define PyArray_ITER_GOTO(it, destination) { \ - int __npy_i; \ - (it)->index = 0; \ - (it)->dataptr = (it)->ao->data; \ - for (__npy_i = (it)->nd_m1; __npy_i>=0; __npy_i--) { \ - if (destination[__npy_i] < 0) { \ - destination[__npy_i] += (it)->dims_m1[__npy_i]+1; \ - } \ - (it)->dataptr += destination[__npy_i] * \ - (it)->strides[__npy_i]; \ - (it)->coordinates[__npy_i] = destination[__npy_i]; \ - (it)->index += destination[__npy_i] * \ - ( __npy_i==(it)->nd_m1 ? 1 : \ - (it)->dims_m1[__npy_i+1]+1) ; \ - } \ - } - -#define PyArray_ITER_GOTO1D(it, ind) { \ - int __npy_i; \ - npy_intp __npy_ind = (npy_intp) (ind); \ - if (__npy_ind < 0) __npy_ind += (it)->size; \ - (it)->index = __npy_ind; \ - if ((it)->nd_m1 == 0) { \ - (it)->dataptr = (it)->ao->data + __npy_ind * \ - (it)->strides[0]; \ - } \ - else if ((it)->contiguous) \ - (it)->dataptr = (it)->ao->data + __npy_ind * \ - (it)->ao->descr->elsize; \ - else { \ - (it)->dataptr = (it)->ao->data; \ - for (__npy_i = 0; __npy_i<=(it)->nd_m1; __npy_i++) { \ - (it)->dataptr += (__npy_ind / (it)->factors[__npy_i]) \ - * (it)->strides[__npy_i]; \ - __npy_ind %= (it)->factors[__npy_i]; \ - } \ - } \ -} - -#define PyArray_ITER_DATA(it) ((PyArrayIterObject *)it)->dataptr - - -/* - Any object passed to PyArray_Broadcast must be binary compatible with - this structure. -*/ - -typedef struct { - PyObject_HEAD - int numiter; /* number of iters */ - npy_intp size; /* broadcasted size */ - npy_intp index; /* current index */ - int nd; /* number of dims */ - npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ - PyArrayIterObject *iters[NPY_MAXARGS]; /* iterators */ -} PyArrayMultiIterObject; - -#define PyArray_MultiIter_RESET(multi) { \ - int __npy_mi; \ - PyArrayMultiIterObject *__npy_mul = (multi); \ - __npy_mul->index = 0; \ - for (__npy_mi = 0; __npy_mi < __npy_mul->numiter; __npy_mi++) { \ - PyArray_ITER_RESET(__npy_mul->iters[__npy_mi]); \ - } \ - } - -#define PyArray_MultiIter_NEXT(multi) { \ - int __npy_mi; \ - PyArrayMultiIterObject *__npy_mul = (multi); \ - __npy_mul->index += 1; \ - for (__npy_mi=0; __npy_mi<__npy_mul->numiter; __npy_mi++) { \ - PyArray_ITER_NEXT(__npy_mul->iters[__npy_mi]); \ - } \ - } - -#define PyArray_MultiIter_GOTO(multi, dest) { \ - int __npy_mi; \ - PyArrayMultiIterObject *__npy_mul = (multi); \ - for (__npy_mi=0; __npy_mi<__npy_mul->numiter; __npy_mi++) { \ - PyArray_ITER_GOTO(__npy_mul->iters[__npy_mi], dest); \ - } \ - __npy_mul->index = __npy_mul->iters[0]->index; \ - } - -#define PyArray_MultiIter_GOTO1D(multi, ind) { \ - int __npy_mi; \ - PyArrayMultiIterObject *__npy_mul = (multi); \ - for (__npy_mi=0; __npy_mi<__npy_mul->numiter; __npy_mi++) { \ - PyArray_ITER_GOTO1D(__npy_mul->iters[__npy_mi], ind); \ - } \ - __npy_mul->index = __npy_mul->iters[0]->index; \ - } - -#define PyArray_MultiIter_DATA(multi, i) \ - (((PyArrayMultiIterObject *)multi)->iters[i]->dataptr) - -#define PyArray_MultiIter_SIZE(multi) \ - ((PyArrayMultiIterObject *)multi)->size - -#define PyArray_MultiIter_NEXTi(multi, i) \ - PyArray_ITER_NEXT(((PyArrayMultiIterObject *)multi)->iters[i]) - -/* Store the information needed for fancy-indexing over an array */ - -typedef struct { - PyObject_HEAD - /* Multi-iterator portion --- needs to be present in this order to - work with PyArray_Broadcast */ - - int numiter; /* number of index-array - iterators */ - npy_intp size; /* size of broadcasted - result */ - npy_intp index; /* current index */ - int nd; /* number of dims */ - npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ - PyArrayIterObject *iters[NPY_MAXDIMS]; /* index object - iterators */ - PyArrayIterObject *ait; /* flat Iterator for - underlying array */ - - /* flat iterator for subspace (when numiter < nd) */ - PyArrayIterObject *subspace; - - /* if subspace iteration, then this is the array of - axes in the underlying array represented by the - index objects */ - int iteraxes[NPY_MAXDIMS]; - /* if subspace iteration, the these are the coordinates - to the start of the subspace. - */ - npy_intp bscoord[NPY_MAXDIMS]; - - PyObject *indexobj; /* creating obj */ - int view; - int consec; - char *dataptr; - -} PyArrayMapIterObject; - -/* The default array type - */ -#define NPY_DEFAULT_TYPE NPY_DOUBLE -#define PyArray_DEFAULT NPY_DEFAULT_TYPE -/* All sorts of useful ways to look into a PyArrayObject. - These are the recommended over casting to PyArrayObject and accessing - the members directly. - */ - -#define PyArray_NDIM(obj) (((PyArrayObject *)(obj))->nd) -#define PyArray_ISONESEGMENT(m) (PyArray_NDIM(m) == 0 || PyArray_CHKFLAGS(m, NPY_CONTIGUOUS) || \ - PyArray_CHKFLAGS(m, NPY_FORTRAN)) -#define PyArray_ISFORTRAN(m) (PyArray_CHKFLAGS(m, NPY_FORTRAN) && (PyArray_NDIM(m) > 1)) -#define PyArray_FORTRAN_IF(m) ((PyArray_CHKFLAGS(m, NPY_FORTRAN) ? NPY_FORTRAN : 0)) -#define FORTRAN_IF PyArray_FORTRAN_IF -#define PyArray_DATA(obj) ((void *)(((PyArrayObject *)(obj))->data)) -#define PyArray_BYTES(obj) (((PyArrayObject *)(obj))->data) -#define PyArray_DIMS(obj) (((PyArrayObject *)(obj))->dimensions) -#define PyArray_STRIDES(obj) (((PyArrayObject *)(obj))->strides) -#define PyArray_DIM(obj,n) (PyArray_DIMS(obj)[n]) -#define PyArray_STRIDE(obj,n) (PyArray_STRIDES(obj)[n]) -#define PyArray_BASE(obj) (((PyArrayObject *)(obj))->base) -#define PyArray_DESCR(obj) (((PyArrayObject *)(obj))->descr) -#define PyArray_FLAGS(obj) (((PyArrayObject *)(obj))->flags) -#define PyArray_ITEMSIZE(obj) (((PyArrayObject *)(obj))->descr->elsize) -#define PyArray_TYPE(obj) (((PyArrayObject *)(obj))->descr->type_num) -#define PyArray_GETITEM(obj,itemptr) \ - ((PyArrayObject *)(obj))->descr->f->getitem((char *)itemptr, \ - (PyArrayObject *)obj); -#define PyArray_SETITEM(obj,itemptr,v) \ - (obj)->descr->f->setitem((PyObject *)v,(char *)(itemptr), \ - (PyArrayObject *)(obj)); - - -#define PyTypeNum_ISBOOL(type) (type == NPY_BOOL) -#define PyTypeNum_ISUNSIGNED(type) ((type == NPY_UBYTE) || \ - (type == NPY_USHORT) || \ - (type == NPY_UINT) || \ - (type == NPY_ULONG) || \ - (type == NPY_ULONGLONG)) - -#define PyTypeNum_ISSIGNED(type) ((type == NPY_BYTE) || \ - (type == NPY_SHORT) || \ - (type == NPY_INT) || \ - (type == NPY_LONG) || \ - (type == NPY_LONGLONG)) - -#define PyTypeNum_ISINTEGER(type) ((type >= NPY_BYTE) && \ - (type <= NPY_ULONGLONG)) - -#define PyTypeNum_ISFLOAT(type) ((type >= NPY_FLOAT) && \ - (type <= NPY_LONGDOUBLE)) - -#define PyTypeNum_ISNUMBER(type) (type <= NPY_CLONGDOUBLE) - -#define PyTypeNum_ISSTRING(type) ((type == NPY_STRING) || \ - (type == NPY_UNICODE)) - -#define PyTypeNum_ISCOMPLEX(type) ((type >= NPY_CFLOAT) && \ - (type <= NPY_CLONGDOUBLE)) - -#define PyTypeNum_ISPYTHON(type) ((type == NPY_LONG) || \ - (type == NPY_DOUBLE) || \ - (type == NPY_CDOUBLE) || \ - (type == NPY_BOOL) || \ - (type == NPY_OBJECT )) - -#define PyTypeNum_ISFLEXIBLE(type) ((type>=NPY_STRING) && \ - (type<=NPY_VOID)) - -#define PyTypeNum_ISUSERDEF(type) ((type >= NPY_USERDEF) && \ - (type < NPY_USERDEF+\ - NPY_NUMUSERTYPES)) - -#define PyTypeNum_ISEXTENDED(type) (PyTypeNum_ISFLEXIBLE(type) || \ - PyTypeNum_ISUSERDEF(type)) - -#define PyTypeNum_ISOBJECT(type) ((type) == NPY_OBJECT) - - -#define PyDataType_ISBOOL(obj) PyTypeNum_ISBOOL(_PyADt(obj)) -#define PyDataType_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISSIGNED(obj) PyTypeNum_ISSIGNED(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISINTEGER(obj) PyTypeNum_ISINTEGER(((PyArray_Descr*)obj)->type_num ) -#define PyDataType_ISFLOAT(obj) PyTypeNum_ISFLOAT(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISNUMBER(obj) PyTypeNum_ISNUMBER(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISSTRING(obj) PyTypeNum_ISSTRING(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISPYTHON(obj) PyTypeNum_ISPYTHON(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(((PyArray_Descr*)obj)->type_num) -#define PyDataType_ISOBJECT(obj) PyTypeNum_ISOBJECT(((PyArray_Descr*)obj)->type_num) -#define PyDataType_HASFIELDS(obj) (((PyArray_Descr *)obj)->names) - -#define PyArray_ISBOOL(obj) PyTypeNum_ISBOOL(PyArray_TYPE(obj)) -#define PyArray_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(PyArray_TYPE(obj)) -#define PyArray_ISSIGNED(obj) PyTypeNum_ISSIGNED(PyArray_TYPE(obj)) -#define PyArray_ISINTEGER(obj) PyTypeNum_ISINTEGER(PyArray_TYPE(obj)) -#define PyArray_ISFLOAT(obj) PyTypeNum_ISFLOAT(PyArray_TYPE(obj)) -#define PyArray_ISNUMBER(obj) PyTypeNum_ISNUMBER(PyArray_TYPE(obj)) -#define PyArray_ISSTRING(obj) PyTypeNum_ISSTRING(PyArray_TYPE(obj)) -#define PyArray_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(PyArray_TYPE(obj)) -#define PyArray_ISPYTHON(obj) PyTypeNum_ISPYTHON(PyArray_TYPE(obj)) -#define PyArray_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj)) -#define PyArray_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(PyArray_TYPE(obj)) -#define PyArray_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(PyArray_TYPE(obj)) -#define PyArray_ISOBJECT(obj) PyTypeNum_ISOBJECT(PyArray_TYPE(obj)) -#define PyArray_HASFIELDS(obj) PyDataType_HASFIELDS(PyArray_DESCR(obj)) - -#define NPY_LITTLE '<' -#define NPY_BIG '>' -#define NPY_NATIVE '=' -#define NPY_SWAP 's' -#define NPY_IGNORE '|' - -#ifdef WORDS_BIGENDIAN -#define NPY_NATBYTE NPY_BIG -#define NPY_OPPBYTE NPY_LITTLE -#else -#define NPY_NATBYTE NPY_LITTLE -#define NPY_OPPBYTE NPY_BIG -#endif - -#define PyArray_ISNBO(arg) ((arg) != NPY_OPPBYTE) -#define PyArray_IsNativeByteOrder PyArray_ISNBO -#define PyArray_ISNOTSWAPPED(m) PyArray_ISNBO(PyArray_DESCR(m)->byteorder) -#define PyArray_ISBYTESWAPPED(m) (!PyArray_ISNOTSWAPPED(m)) - -#define PyArray_FLAGSWAP(m, flags) (PyArray_CHKFLAGS(m, flags) && \ - PyArray_ISNOTSWAPPED(m)) -#define PyArray_ISCARRAY(m) PyArray_FLAGSWAP(m, NPY_CARRAY) -#define PyArray_ISCARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_CARRAY_RO) -#define PyArray_ISFARRAY(m) PyArray_FLAGSWAP(m, NPY_FARRAY) -#define PyArray_ISFARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_FARRAY_RO) -#define PyArray_ISBEHAVED(m) PyArray_FLAGSWAP(m, NPY_BEHAVED) -#define PyArray_ISBEHAVED_RO(m) PyArray_FLAGSWAP(m, NPY_ALIGNED) - - - -/* This is the form of the struct that's returned pointed by the - PyCObject attribute of an array __array_struct__. See - http://numeric.scipy.org/array_interface.html for the full - documentation. */ -typedef struct { - int two; /* contains the integer 2 as a sanity check */ - int nd; /* number of dimensions */ - char typekind; /* kind in array --- character code of typestr */ - int itemsize; /* size of each element */ - int flags; /* how should be data interpreted. Valid - flags are CONTIGUOUS (1), FORTRAN (2), - ALIGNED (0x100), NOTSWAPPED (0x200), and - WRITEABLE (0x400). - ARR_HAS_DESCR (0x800) states that arrdescr - field is present in structure */ - npy_intp *shape; /* A length-nd array of shape information */ - npy_intp *strides; /* A length-nd array of stride information */ - void *data; /* A pointer to the first element of the array */ - PyObject *descr; /* A list of fields or NULL (ignored if flags - does not have ARR_HAS_DESCR flag set) */ -} PyArrayInterface; - -/* Includes the "function" C-API -- these are all stored in a - list of pointers --- one for each file - The two lists are concatenated into one in multiarray. - - They are available as import_array() -*/ - - -#include "__multiarray_api.h" - - -/* C-API that requries previous API to be defined */ - -#define PyArray_DescrCheck(op) ((op)->ob_type == &PyArrayDescr_Type) - -#define PyArray_Check(op) ((op)->ob_type == &PyArray_Type || \ - PyObject_TypeCheck((op), &PyArray_Type)) -#define PyArray_CheckExact(op) ((op)->ob_type == &PyArray_Type) - -#define PyArray_IsZeroDim(op) (PyArray_Check(op) && (PyArray_NDIM(op) == 0)) -#define PyArray_IsScalar(obj, cls) \ - (PyObject_TypeCheck((obj), &Py##cls##ArrType_Type)) -#define PyArray_CheckScalar(m) (PyArray_IsScalar(m, Generic) || \ - PyArray_IsZeroDim(m)) -#define PyArray_IsPythonNumber(obj) \ - (PyInt_Check(obj) || PyFloat_Check(obj) || PyComplex_Check(obj) || \ - PyLong_Check(obj) || PyBool_Check(obj)) -#define PyArray_IsPythonScalar(obj) \ - (PyArray_IsPythonNumber(obj) || PyString_Check(obj) || \ - PyUnicode_Check(obj)) -#define PyArray_IsAnyScalar(obj) \ - (PyArray_IsScalar(obj, Generic) || PyArray_IsPythonScalar(obj)) -#define PyArray_CheckAnyScalar(obj) (PyArray_IsPythonScalar(obj) || \ - PyArray_CheckScalar(obj)) - -#define PyArray_GETCONTIGUOUS(m) (PyArray_ISCONTIGUOUS(m) ? Py_INCREF(m), m : \ - (PyArrayObject *)(PyArray_Copy(m))) - -#define PyArray_SAMESHAPE(a1,a2) ((PyArray_NDIM(a1) == PyArray_NDIM(a2)) && \ - PyArray_CompareLists(PyArray_DIMS(a1), \ - PyArray_DIMS(a2), \ - PyArray_NDIM(a1))) -#define PyArray_SIZE(m) PyArray_MultiplyList(PyArray_DIMS(m), PyArray_NDIM(m)) -#define PyArray_NBYTES(m) (PyArray_ITEMSIZE(m) * PyArray_SIZE(m)) -#define PyArray_FROM_O(m) PyArray_FromAny(m, NULL, 0, 0, 0, NULL) -#define PyArray_FROM_OF(m,flags) PyArray_CheckFromAny(m, NULL, 0, 0, flags, NULL) -#define PyArray_FROM_OT(m,type) PyArray_FromAny(m, PyArray_DescrFromType(type), \ - 0, 0, 0, NULL); -#define PyArray_FROM_OTF(m, type, flags) \ - PyArray_FromAny(m, PyArray_DescrFromType(type), 0, 0, \ - (((flags) & NPY_ENSURECOPY) ? \ - ((flags) | NPY_DEFAULT) : (flags)), NULL) -#define PyArray_FROMANY(m, type, min, max, flags) \ - PyArray_FromAny(m, PyArray_DescrFromType(type), min, max, \ - (((flags) & NPY_ENSURECOPY) ? \ - (flags) | NPY_DEFAULT : (flags)), NULL) -#define PyArray_ZEROS(m, dims, type, fortran) \ - PyArray_Zeros(m, dims, PyArray_DescrFromType(type), fortran) -#define PyArray_EMPTY(m, dims, type, fortran) \ - PyArray_Empty(m, dims, PyArray_DescrFromType(type), fortran) - -#define PyArray_FILLWBYTE(obj, val) memset(PyArray_DATA(obj), (val), PyArray_NBYTES(obj)) - -#define PyArray_REFCOUNT(obj) (((PyObject *)(obj))->ob_refcnt) -#define NPY_REFCOUNT PyArray_REFCOUNT -#define NPY_MAX_ELSIZE 2*SIZEOF_LONGDOUBLE - -#define PyArray_ContiguousFromAny(op, type, min_depth, max_depth) \ - PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ - max_depth, NPY_DEFAULT, NULL) - -#define PyArray_EquivArrTypes(a1, a2) \ - PyArray_EquivTypes(PyArray_DESCR(a1), PyArray_DESCR(a2)) - -#define PyArray_EquivByteorders(b1, b2) \ - (((b1) == (b2)) || (PyArray_ISNBO(b1) == PyArray_ISNBO(b2))) - -#define PyArray_SimpleNew(nd, dims, typenum) \ - PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, NULL, 0, 0, NULL) -#define PyArray_SimpleNewFromData(nd, dims, typenum, data) \ - PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, data, 0, NPY_CARRAY, NULL) -#define PyArray_SimpleNewFromDescr(nd, dims, descr) \ - PyArray_NewFromDescr(&PyArray_Type, descr, nd, dims, NULL, NULL, 0, NULL) - -#define PyArray_ToScalar(data, arr) \ - PyArray_Scalar(data, PyArray_DESCR(arr), (PyObject *)arr) - -/* These might be faster without the dereferencing of obj - going on inside -- of course an optimizing compiler should - inline the constants inside a for loop making it a moot point -*/ - -#define PyArray_GETPTR1(obj, i) (void *)(PyArray_BYTES(obj) + \ - i*PyArray_STRIDES(obj)[0]) - -#define PyArray_GETPTR2(obj, i, j) (void *)(PyArray_BYTES(obj) + \ - i*PyArray_STRIDES(obj)[0] + \ - j*PyArray_STRIDES(obj)[1]) - -#define PyArray_GETPTR3(obj, i, j, k) (void *)(PyArray_BYTES(obj) + \ - i*PyArray_STRIDES(obj)[0] + \ - j*PyArray_STRIDES(obj)[1] + \ - k*PyArray_STRIDES(obj)[2]) \ - -#define PyArray_GETPTR4(obj, i, j, k, l) (void *)(PyArray_BYTES(obj) + \ - i*PyArray_STRIDES(obj)[0] + \ - j*PyArray_STRIDES(obj)[1] + \ - k*PyArray_STRIDES(obj)[2] + \ - l*PyArray_STRIDES(obj)[3]) - -#define PyArray_XDECREF_ERR(obj) \ - if (obj && (PyArray_FLAGS(obj) & NPY_UPDATEIFCOPY)) { \ - PyArray_FLAGS(PyArray_BASE(obj)) |= NPY_WRITEABLE; \ - PyArray_FLAGS(obj) &= ~NPY_UPDATEIFCOPY; \ - }\ - Py_XDECREF(obj) - -#define PyArray_DESCR_REPLACE(descr) do { \ - PyArray_Descr *_new_; \ - _new_ = PyArray_DescrNew(descr); \ - Py_XDECREF(descr); \ - descr = _new_; \ - } while(0) - -/* Copy should always return contiguous array */ -#define PyArray_Copy(obj) PyArray_NewCopy(obj, NPY_CORDER) - -#define PyArray_FromObject(op, type, min_depth, max_depth) \ - PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ - max_depth, NPY_BEHAVED | NPY_ENSUREARRAY, NULL) - -#define PyArray_ContiguousFromObject(op, type, min_depth, max_depth) \ - PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ - max_depth, NPY_DEFAULT | NPY_ENSUREARRAY, NULL) - -#define PyArray_CopyFromObject(op, type, min_depth, max_depth) \ - PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ - max_depth, NPY_ENSURECOPY | NPY_DEFAULT | NPY_ENSUREARRAY, NULL) - -#define PyArray_Cast(mp, type_num) \ - PyArray_CastToType(mp, PyArray_DescrFromType(type_num), 0) - -#define PyArray_Take(ap, items, axis) \ - PyArray_TakeFrom(ap, items, axis, NULL, NPY_RAISE) - -#define PyArray_Put(ap, items, values) \ - PyArray_PutTo(ap, items, values, NPY_RAISE) - -/* Compatibility with old Numeric stuff -- don't use in new code */ - -#define PyArray_FromDimsAndData(nd, d, type, data) \ - PyArray_FromDimsAndDataAndDescr(nd, d, PyArray_DescrFromType(type), \ - data) - -#include "old_defines.h" - -#ifdef __cplusplus -} -#endif - -#endif /* !Py_ARRAYOBJECT_H */ Modified: trunk/numpy/core/include/numpy/noprefix.h =================================================================== --- trunk/numpy/core/include/numpy/noprefix.h 2006-08-17 22:03:38 UTC (rev 3034) +++ trunk/numpy/core/include/numpy/noprefix.h 2006-08-18 17:01:19 UTC (rev 3035) @@ -1,7 +1,11 @@ #ifndef NPY_NOPREFIX_H #define NPY_NOPREFIX_H -#include "arrayobject.h" +/* You can directly include noprefix.h as a backward +compatibility measure*/ +#ifndef NPY_NO_PREFIX +#include "ndarrayobject.h" +#endif #define MAX_DIMS NPY_MAXDIMS Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-17 22:03:38 UTC (rev 3034) +++ trunk/numpy/core/ma.py 2006-08-18 17:01:19 UTC (rev 3035) @@ -376,6 +376,10 @@ d1 = filled(a, self.fillx) d2 = filled(b, self.filly) result = self.f(d1, d2, *args, **kwargs) + if isinstance(result, ndarray) \ + and m.ndim != 0 \ + and m.shape != result.shape: + m = mask_or(getmaskarray(a), getmaskarray(b)) return masked_array(result, m) def reduce (self, target, axis=0, dtype=None): @@ -678,7 +682,7 @@ return masked_array(self._data.real, mask=nomask, fill_value = self.fill_value()) else: - return masked_array(self._data.real, mask=self._mask.ravel(), + return masked_array(self._data.real, mask=self._mask, fill_value = self.fill_value()) def _set_real (self, value): @@ -692,7 +696,7 @@ return masked_array(self._data.imag, mask=nomask, fill_value = self.fill_value()) else: - return masked_array(self._data.imag, mask=self._mask.ravel(), + return masked_array(self._data.imag, mask=self._mask, fill_value = self.fill_value()) def _set_imaginary (self, value): From numpy-svn at scipy.org Fri Aug 18 13:06:13 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 18 Aug 2006 12:06:13 -0500 (CDT) Subject: [Numpy-svn] r3036 - trunk/numpy/core/include/numpy Message-ID: <20060818170613.51DAC39C051@new.scipy.org> Author: oliphant Date: 2006-08-18 12:06:11 -0500 (Fri, 18 Aug 2006) New Revision: 3036 Added: trunk/numpy/core/include/numpy/ndarrayobject.h Log: Add ndarrayobject.h file and fix ticket #255 Added: trunk/numpy/core/include/numpy/ndarrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-18 17:01:19 UTC (rev 3035) +++ trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-18 17:06:11 UTC (rev 3036) @@ -0,0 +1,1549 @@ +/* DON'T INCLUDE THIS DIRECTLY. + */ + +#ifndef NPY_NDARRAYOBJECT_H +#define NPY_NDARRAYOBJECT_H +#ifdef __cplusplus +#define CONFUSE_EMACS { +#define CONFUSE_EMACS2 } +extern "C" CONFUSE_EMACS +#undef CONFUSE_EMACS +#undef CONFUSE_EMACS2 +/* ... otherwise a semi-smart idententer (like emacs) tries to indent + everything when you're typing */ +#endif +/* This is auto-generated by the installer */ +#include "config.h" + +/* There are several places in the code where an array of dimensions is */ +/* allocated statically. This is the size of that static allocation. */ +/* The array creation itself could have arbitrary dimensions but + * all the places where static allocation is used would need to + * be changed to dynamic (including inside of several structures) + */ + +#define NPY_MAXDIMS 32 +#define NPY_MAXARGS 32 + +/* Used for Converter Functions "O&" code in ParseTuple */ +#define NPY_FAIL 0 +#define NPY_SUCCEED 1 + + /* Helpful to distinguish what is installed */ +#define NPY_VERSION 0x01000002 + + /* Some platforms don't define bool, long long, or long double. + Handle that here. + */ + +#ifdef PY_LONG_LONG +typedef PY_LONG_LONG npy_longlong; +typedef unsigned PY_LONG_LONG npy_ulonglong; +# ifdef _MSC_VER +# define NPY_LONGLONG_FMT "I64d" +# define NPY_ULONGLONG_FMT "I64u" +# define NPY_LONGLONG_SUFFIX(x) (x##i64) +# define NPY_ULONGLONG_SUFFIX(x) (x##Ui64) +# else + /* #define LONGLONG_FMT "lld" Another possible variant + #define ULONGLONG_FMT "llu" + + #define LONGLONG_FMT "qd" -- BSD perhaps? + #define ULONGLONG_FMT "qu" + */ +# define NPY_LONGLONG_FMT "Ld" +# define NPY_ULONGLONG_FMT "Lu" +# define NPY_LONGLONG_SUFFIX(x) (x##LL) +# define NPY_ULONGLONG_SUFFIX(x) (x##ULL) +# endif +#else +typedef long npy_longlong; +typedef unsigned long npy_ulonglong; +# define NPY_LONGLONG_SUFFIX(x) (x##L) +# define NPY_ULONGLONG_SUFFIX(x) (x##UL) +#endif + + +typedef unsigned char npy_bool; +#define NPY_FALSE 0 +#define NPY_TRUE 1 + +#if SIZEOF_LONG_DOUBLE==SIZEOF_DOUBLE + typedef double npy_longdouble; + #define NPY_LONGDOUBLE_FMT "g" +#else + typedef long double npy_longdouble; + #define NPY_LONGDOUBLE_FMT "Lg" +#endif + +#ifndef Py_USING_UNICODE +#error Must use Python with unicode enabled. +#endif + + +typedef signed char npy_byte; +typedef unsigned char npy_ubyte; +typedef unsigned short npy_ushort; +typedef unsigned int npy_uint; +typedef unsigned long npy_ulong; + +/* These are for completeness */ +typedef float npy_float; +typedef double npy_double; +typedef short npy_short; +typedef int npy_int; +typedef long npy_long; + +typedef struct { float real, imag; } npy_cfloat; +typedef struct { double real, imag; } npy_cdouble; +typedef struct {npy_longdouble real, imag;} npy_clongdouble; + +enum NPY_TYPES { NPY_BOOL=0, + NPY_BYTE, NPY_UBYTE, + NPY_SHORT, NPY_USHORT, + NPY_INT, NPY_UINT, + NPY_LONG, NPY_ULONG, + NPY_LONGLONG, NPY_ULONGLONG, + NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE, + NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, + NPY_OBJECT=17, + NPY_STRING, NPY_UNICODE, + NPY_VOID, + NPY_NTYPES, + NPY_NOTYPE, + NPY_CHAR, /* special flag */ + NPY_USERDEF=256 /* leave room for characters */ +}; + +/* basetype array priority */ +#define NPY_PRIORITY 0.0 + +/* default subtype priority */ +#define NPY_SUBTYPE_PRIORITY 1.0 + +/* default scalar priority */ +#define NPY_SCALAR_PRIORITY -1000000.0 + +/* How many floating point types are there */ +#define NPY_NUM_FLOATTYPE 3 + +/* We need to match npy_intp to a signed integer of the same size as + a pointer variable. npy_uintp to the equivalent unsigned integer +*/ + + +/* These characters correspond to the array type and the + struct module */ + +/* except 'p' -- signed integer for pointer type */ + +enum NPY_TYPECHAR { NPY_BOOLLTR = '?', + NPY_BYTELTR = 'b', + NPY_UBYTELTR = 'B', + NPY_SHORTLTR = 'h', + NPY_USHORTLTR = 'H', + NPY_INTLTR = 'i', + NPY_UINTLTR = 'I', + NPY_LONGLTR = 'l', + NPY_ULONGLTR = 'L', + NPY_LONGLONGLTR = 'q', + NPY_ULONGLONGLTR = 'Q', + NPY_FLOATLTR = 'f', + NPY_DOUBLELTR = 'd', + NPY_LONGDOUBLELTR = 'g', + NPY_CFLOATLTR = 'F', + NPY_CDOUBLELTR = 'D', + NPY_CLONGDOUBLELTR = 'G', + NPY_OBJECTLTR = 'O', + NPY_STRINGLTR = 'S', + NPY_STRINGLTR2 = 'a', + NPY_UNICODELTR = 'U', + NPY_VOIDLTR = 'V', + NPY_CHARLTR = 'c', + + /* No Descriptor, just a define -- this let's + Python users specify an array of integers + large enough to hold a pointer on the platform*/ + NPY_INTPLTR = 'p', + NPY_UINTPLTR = 'P', + + NPY_GENBOOLLTR ='b', + NPY_SIGNEDLTR = 'i', + NPY_UNSIGNEDLTR = 'u', + NPY_FLOATINGLTR = 'f', + NPY_COMPLEXLTR = 'c' +}; + +typedef enum { + NPY_QUICKSORT=0, + NPY_HEAPSORT=1, + NPY_MERGESORT=2, +} NPY_SORTKIND; +#define NPY_NSORTS NPY_MERGESORT + 1 + + +typedef enum { + NPY_NOSCALAR=-1, + NPY_BOOL_SCALAR, + NPY_INTPOS_SCALAR, + NPY_INTNEG_SCALAR, + NPY_FLOAT_SCALAR, + NPY_COMPLEX_SCALAR, + NPY_OBJECT_SCALAR, +} NPY_SCALARKIND; +#define NPY_NSCALARKINDS NPY_OBJECT_SCALAR+1 + +typedef enum { + NPY_ANYORDER=-1, + NPY_CORDER=0, + NPY_FORTRANORDER=1 +} NPY_ORDER; + + +typedef enum { + NPY_CLIP=0, + NPY_WRAP=1, + NPY_RAISE=2 +} NPY_CLIPMODE; + + /* Define bit-width array types and typedefs */ + +#define NPY_MAX_INT8 127 +#define NPY_MIN_INT8 -128 +#define NPY_MAX_UINT8 255 +#define NPY_MAX_INT16 32767 +#define NPY_MIN_INT16 -32768 +#define NPY_MAX_UINT16 65535 +#define NPY_MAX_INT32 2147483647 +#define NPY_MIN_INT32 (-NPY_MAX_INT32 - 1) +#define NPY_MAX_UINT32 4294967295U +#define NPY_MAX_INT64 NPY_LONGLONG_SUFFIX(9223372036854775807) +#define NPY_MIN_INT64 (-NPY_MAX_INT64 - NPY_LONGLONG_SUFFIX(1)) +#define NPY_MAX_UINT64 NPY_ULONGLONG_SUFFIX(18446744073709551615) +#define NPY_MAX_INT128 NPY_LONGLONG_SUFFIX(85070591730234615865843651857942052864) +#define NPY_MIN_INT128 (-NPY_MAX_INT128 - NPY_LONGLONG_SUFFIX(1)) +#define NPY_MAX_UINT128 NPY_ULONGLONG_SUFFIX(170141183460469231731687303715884105728) +#define NPY_MAX_INT256 NPY_LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967) +#define NPY_MIN_INT256 (-NPY_MAX_INT256 - NPY_LONGLONG_SUFFIX(1)) +#define NPY_MAX_UINT256 NPY_ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935) + + /* Need to find the number of bits for each type and + make definitions accordingly. + + C states that sizeof(char) == 1 by definition + + So, just using the sizeof keyword won't help. + + It also looks like Python itself uses sizeof(char) quite a + bit, which by definition should be 1 all the time. + + Idea: Make Use of CHAR_BIT which should tell us how many + BITS per CHARACTER + */ + + /* Include platform definitions -- These are in the C89/90 standard */ +#include +#define NPY_MAX_BYTE SCHAR_MAX +#define NPY_MIN_BYTE SCHAR_MIN +#define NPY_MAX_UBYTE UCHAR_MAX +#define NPY_MAX_SHORT SHRT_MAX +#define NPY_MIN_SHORT SHRT_MIN +#define NPY_MAX_USHORT USHRT_MAX +#define NPY_MAX_INT INT_MAX +#ifndef INT_MIN +#define INT_MIN (-INT_MAX - 1) +#endif +#define NPY_MIN_INT INT_MIN +#define NPY_MAX_UINT UINT_MAX +#define NPY_MAX_LONG LONG_MAX +#define NPY_MIN_LONG LONG_MIN +#define NPY_MAX_ULONG ULONG_MAX + + +#define NPY_SIZEOF_LONG SIZEOF_LONG +#define NPY_SIZEOF_INT SIZEOF_INT +#define NPY_SIZEOF_SHORT SIZEOF_SHORT +#define NPY_SIZEOF_FLOAT SIZEOF_FLOAT +#define NPY_SIZEOF_DOUBLE SIZEOF_DOUBLE +#define NPY_SIZEOF_LONGDOUBLE SIZEOF_LONG_DOUBLE +#define NPY_SIZEOF_LONGLONG SIZEOF_LONG_LONG +#define NPY_BITSOF_BOOL sizeof(npy_bool)*CHAR_BIT +#define NPY_BITSOF_CHAR CHAR_BIT +#define NPY_BITSOF_SHORT (SIZEOF_SHORT*CHAR_BIT) +#define NPY_BITSOF_INT (SIZEOF_INT*CHAR_BIT) +#define NPY_BITSOF_LONG (SIZEOF_LONG*CHAR_BIT) +#define NPY_BITSOF_LONGLONG (NPY_SIZEOF_LONGLONG*CHAR_BIT) +#define NPY_BITSOF_FLOAT (SIZEOF_FLOAT*CHAR_BIT) +#define NPY_BITSOF_DOUBLE (SIZEOF_DOUBLE*CHAR_BIT) +#define NPY_BITSOF_LONGDOUBLE (NPY_SIZEOF_LONGDOUBLE*CHAR_BIT) + +#if NPY_BITSOF_LONG == 8 +#define NPY_INT8 NPY_LONG +#define NPY_UINT8 NPY_ULONG + typedef long npy_int8; + typedef unsigned long npy_uint8; +#elif NPY_BITSOF_LONG == 16 +#define NPY_INT16 NPY_LONG +#define NPY_UINT16 NPY_ULONG + typedef long npy_int16; + typedef unsigned long npy_uint16; +#elif NPY_BITSOF_LONG == 32 +#define NPY_INT32 NPY_LONG +#define NPY_UINT32 NPY_ULONG + typedef long npy_int32; + typedef unsigned long npy_uint32; + typedef unsigned long npy_ucs4; +#elif NPY_BITSOF_LONG == 64 +#define NPY_INT64 NPY_LONG +#define NPY_UINT64 NPY_ULONG + typedef long npy_int64; + typedef unsigned long npy_uint64; +#elif NPY_BITSOF_LONG == 128 +#define NPY_INT128 NPY_LONG +#define NPY_UINT128 NPY_ULONG + typedef long npy_int128; + typedef unsigned long npy_uint128; +#endif + +#if NPY_BITSOF_LONGLONG == 8 +# ifndef NPY_INT8 +# define NPY_INT8 NPY_LONGLONG +# define NPY_UINT8 NPY_ULONGLONG + typedef npy_longlong npy_int8; + typedef npy_ulonglong npy_uint8; +# endif +# define NPY_MAX_LONGLONG NPY_MAX_INT8 +# define NPY_MIN_LONGLONG NPY_MIN_INT8 +# define NPY_MAX_ULONGLONG NPY_MAX_UINT8 +#elif NPY_BITSOF_LONGLONG == 16 +# ifndef NPY_INT16 +# define NPY_INT16 NPY_LONGLONG +# define NPY_UINT16 NPY_ULONGLONG + typedef npy_longlong npy_int16; + typedef npy_ulonglong npy_uint16; +# endif +# define NPY_MAX_LONGLONG NPY_MAX_INT16 +# define NPY_MIN_LONGLONG NPY_MIN_INT16 +# define NPY_MAX_ULONGLONG NPY_MAX_UINT16 +#elif NPY_BITSOF_LONGLONG == 32 +# ifndef NPY_INT32 +# define NPY_INT32 NPY_LONGLONG +# define NPY_UINT32 NPY_ULONGLONG + typedef npy_longlong npy_int32; + typedef npy_ulonglong npy_uint32; + typedef npy_ulonglong npy_ucs4; +# endif +# define NPY_MAX_LONGLONG NPY_MAX_INT32 +# define NPY_MIN_LONGLONG NPY_MIN_INT32 +# define NPY_MAX_ULONGLONG NPY_MAX_UINT32 +#elif NPY_BITSOF_LONGLONG == 64 +# ifndef NPY_INT64 +# define NPY_INT64 NPY_LONGLONG +# define NPY_UINT64 NPY_ULONGLONG + typedef npy_longlong npy_int64; + typedef npy_ulonglong npy_uint64; +# endif +# define NPY_MAX_LONGLONG NPY_MAX_INT64 +# define NPY_MIN_LONGLONG NPY_MIN_INT64 +# define NPY_MAX_ULONGLONG NPY_MAX_UINT64 +#elif NPY_BITSOF_LONGLONG == 128 +# ifndef NPY_INT128 +# define NPY_INT128 NPY_LONGLONG +# define NPY_UINT128 NPY_ULONGLONG + typedef npy_longlong npy_int128; + typedef npy_ulonglong npy_uint128; +# endif +# define NPY_MAX_LONGLONG NPY_MAX_INT128 +# define NPY_MIN_LONGLONG NPY_MIN_INT128 +# define NPY_MAX_ULONGLONG NPY_MAX_UINT128 +#elif NPY_BITSOF_LONGLONG == 256 +# define NPY_INT256 NPY_LONGLONG +# define NPY_UINT256 NPY_ULONGLONG + typedef npy_longlong npy_int256; + typedef npy_ulonglong npy_uint256; +# define NPY_MAX_LONGLONG NPY_MAX_INT256 +# define NPY_MIN_LONGLONG NPY_MIN_INT256 +# define NPY_MAX_ULONGLONG NPY_MAX_UINT256 +#endif + +#if NPY_BITSOF_INT == 8 +#ifndef NPY_INT8 +#define NPY_INT8 NPY_INT +#define NPY_UINT8 NPY_UINT + typedef int npy_int8; + typedef unsigned int npy_uint8; +#endif +#elif NPY_BITSOF_INT == 16 +#ifndef NPY_INT16 +#define NPY_INT16 NPY_INT +#define NPY_UINT16 NPY_UINT + typedef int npy_int16; + typedef unsigned int npy_uint16; +#endif +#elif NPY_BITSOF_INT == 32 +#ifndef NPY_INT32 +#define NPY_INT32 NPY_INT +#define NPY_UINT32 NPY_UINT + typedef int npy_int32; + typedef unsigned int npy_uint32; + typedef unsigned int npy_ucs4; +#endif +#elif NPY_BITSOF_INT == 64 +#ifndef NPY_INT64 +#define NPY_INT64 NPY_INT +#define NPY_UINT64 NPY_UINT + typedef int npy_int64; + typedef unsigned int npy_uint64; +#endif +#elif NPY_BITSOF_INT == 128 +#ifndef NPY_INT128 +#define NPY_INT128 NPY_INT +#define NPY_UINT128 NPY_UINT + typedef int npy_int128; + typedef unsigned int npy_uint128; +#endif +#endif + +#if NPY_BITSOF_SHORT == 8 +#ifndef NPY_INT8 +#define NPY_INT8 NPY_SHORT +#define NPY_UINT8 NPY_USHORT + typedef short npy_int8; + typedef unsigned short npy_uint8; +#endif +#elif NPY_BITSOF_SHORT == 16 +#ifndef NPY_INT16 +#define NPY_INT16 NPY_SHORT +#define NPY_UINT16 NPY_USHORT + typedef short npy_int16; + typedef unsigned short npy_uint16; +#endif +#elif NPY_BITSOF_SHORT == 32 +#ifndef NPY_INT32 +#define NPY_INT32 NPY_SHORT +#define NPY_UINT32 NPY_USHORT + typedef short npy_int32; + typedef unsigned short npy_uint32; + typedef unsigned short npy_ucs4; +#endif +#elif NPY_BITSOF_SHORT == 64 +#ifndef NPY_INT64 +#define NPY_INT64 NPY_SHORT +#define NPY_UINT64 NPY_USHORT + typedef short npy_int64; + typedef unsigned short npy_uint64; +#endif +#elif NPY_BITSOF_SHORT == 128 +#ifndef NPY_INT128 +#define NPY_INT128 NPY_SHORT +#define NPY_UINT128 NPY_USHORT + typedef short npy_int128; + typedef unsigned short npy_uint128; +#endif +#endif + + +#if NPY_BITSOF_CHAR == 8 +#ifndef NPY_INT8 +#define NPY_INT8 NPY_BYTE +#define NPY_UINT8 NPY_UBYTE + typedef signed char npy_int8; + typedef unsigned char npy_uint8; +#endif +#elif NPY_BITSOF_CHAR == 16 +#ifndef NPY_INT16 +#define NPY_INT16 NPY_BYTE +#define NPY_UINT16 NPY_UBYTE + typedef signed char npy_int16; + typedef unsigned char npy_uint16; +#endif +#elif NPY_BITSOF_CHAR == 32 +#ifndef NPY_INT32 +#define NPY_INT32 NPY_BYTE +#define NPY_UINT32 NPY_UBYTE + typedef signed char npy_int32; + typedef unsigned char npy_uint32; + typedef unsigned char npy_ucs4; +#endif +#elif NPY_BITSOF_CHAR == 64 +#ifndef NPY_INT64 +#define NPY_INT64 NPY_BYTE +#define NPY_UINT64 NPY_UBYTE + typedef signed char npy_int64; + typedef unsigned char npy_uint64; +#endif +#elif NPY_BITSOF_CHAR == 128 +#ifndef NPY_INT128 +#define NPY_INT128 NPY_BYTE +#define NPY_UINT128 NPY_UBYTE + typedef signed char npy_int128; + typedef unsigned char npy_uint128; +#endif +#endif + + + +#if NPY_BITSOF_DOUBLE == 16 +#ifndef NPY_FLOAT16 +#define NPY_FLOAT16 NPY_DOUBLE +#define NPY_COMPLEX32 NPY_CDOUBLE + typedef double npy_float16; + typedef npy_cdouble npy_complex32; +#endif +#elif NPY_BITSOF_DOUBLE == 32 +#ifndef NPY_FLOAT32 +#define NPY_FLOAT32 NPY_DOUBLE +#define NPY_COMPLEX64 NPY_CDOUBLE + typedef double npy_float32; + typedef npy_cdouble npy_complex64; +#endif +#elif NPY_BITSOF_DOUBLE == 64 +#ifndef NPY_FLOAT64 +#define NPY_FLOAT64 NPY_DOUBLE +#define NPY_COMPLEX128 NPY_CDOUBLE + typedef double npy_float64; + typedef npy_cdouble npy_complex128; +#endif +#elif NPY_BITSOF_DOUBLE == 80 +#ifndef NPY_FLOAT80 +#define NPY_FLOAT80 NPY_DOUBLE +#define NPY_COMPLEX160 NPY_CDOUBLE + typedef double npy_float80; + typedef npy_cdouble npy_complex160; +#endif +#elif NPY_BITSOF_DOUBLE == 96 +#ifndef NPY_FLOAT96 +#define NPY_FLOAT96 NPY_DOUBLE +#define NPY_COMPLEX192 NPY_CDOUBLE + typedef double npy_float96; + typedef npy_cdouble npy_complex192; +#endif +#elif NPY_BITSOF_DOUBLE == 128 +#ifndef NPY_FLOAT128 +#define NPY_FLOAT128 NPY_DOUBLE +#define NPY_COMPLEX256 NPY_CDOUBLE + typedef double npy_float128; + typedef npy_cdouble npy_complex256; +#endif +#endif + + + +#if NPY_BITSOF_FLOAT == 16 +#ifndef NPY_FLOAT16 +#define NPY_FLOAT16 NPY_FLOAT +#define NPY_COMPLEX32 NPY_CFLOAT + typedef float npy_float16; + typedef npy_cfloat npy_complex32; +#endif +#elif NPY_BITSOF_FLOAT == 32 +#ifndef NPY_FLOAT32 +#define NPY_FLOAT32 NPY_FLOAT +#define NPY_COMPLEX64 NPY_CFLOAT + typedef float npy_float32; + typedef npy_cfloat npy_complex64; +#endif +#elif NPY_BITSOF_FLOAT == 64 +#ifndef NPY_FLOAT64 +#define NPY_FLOAT64 NPY_FLOAT +#define NPY_COMPLEX128 NPY_CFLOAT + typedef float npy_float64; + typedef npy_cfloat npy_complex128; +#endif +#elif NPY_BITSOF_FLOAT == 80 +#ifndef NPY_FLOAT80 +#define NPY_FLOAT80 NPY_FLOAT +#define NPY_COMPLEX160 NPY_CFLOAT + typedef float npy_float80; + typedef npy_cfloat npy_complex160; +#endif +#elif NPY_BITSOF_FLOAT == 96 +#ifndef NPY_FLOAT96 +#define NPY_FLOAT96 NPY_FLOAT +#define NPY_COMPLEX192 NPY_CFLOAT + typedef float npy_float96; + typedef npy_cfloat npy_complex192; +#endif +#elif NPY_BITSOF_FLOAT == 128 +#ifndef NPY_FLOAT128 +#define NPY_FLOAT128 NPY_FLOAT +#define NPY_COMPLEX256 NPY_CFLOAT + typedef float npy_float128; + typedef npy_cfloat npy_complex256; +#endif +#endif + + +#if NPY_BITSOF_LONGDOUBLE == 16 +#ifndef NPY_FLOAT16 +#define NPY_FLOAT16 NPY_LONGDOUBLE +#define NPY_COMPLEX32 NPY_CLONGDOUBLE + typedef npy_longdouble npy_float16; + typedef npy_clongdouble npy_complex32; +#endif +#elif NPY_BITSOF_LONGDOUBLE == 32 +#ifndef NPY_FLOAT32 +#define NPY_FLOAT32 NPY_LONGDOUBLE +#define NPY_COMPLEX64 NPY_CLONGDOUBLE + typedef npy_longdouble npy_float32; + typedef npy_clongdouble npy_complex64; +#endif +#elif NPY_BITSOF_LONGDOUBLE == 64 +#ifndef NPY_FLOAT64 +#define NPY_FLOAT64 NPY_LONGDOUBLE +#define NPY_COMPLEX128 NPY_CLONGDOUBLE + typedef npy_longdouble npy_float64; + typedef npy_clongdouble npy_complex128; +#endif +#elif NPY_BITSOF_LONGDOUBLE == 80 +#ifndef NPY_FLOAT80 +#define NPY_FLOAT80 NPY_LONGDOUBLE +#define NPY_COMPLEX160 NPY_CLONGDOUBLE + typedef npy_longdouble npy_float80; + typedef npy_clongdouble npy_complex160; +#endif +#elif NPY_BITSOF_LONGDOUBLE == 96 +#ifndef NPY_FLOAT96 +#define NPY_FLOAT96 NPY_LONGDOUBLE +#define NPY_COMPLEX192 NPY_CLONGDOUBLE + typedef npy_longdouble npy_float96; + typedef npy_clongdouble npy_complex192; +#endif +#elif NPY_BITSOF_LONGDOUBLE == 128 +#ifndef NPY_FLOAT128 +#define NPY_FLOAT128 NPY_LONGDOUBLE +#define NPY_COMPLEX256 NPY_CLONGDOUBLE + typedef npy_longdouble npy_float128; + typedef npy_clongdouble npy_complex256; +#endif +#elif NPY_BITSOF_LONGDOUBLE == 256 +#define NPY_FLOAT256 NPY_LONGDOUBLE +#define NPY_COMPLEX512 NPY_CLONGDOUBLE + typedef npy_longdouble npy_float256; + typedef npy_clongdouble npy_complex512; +#endif + + /* End of typedefs for numarray style bit-width names */ + +/* This is to typedef npy_intp to the appropriate pointer size for this platform. + * Py_intptr_t, Py_uintptr_t are defined in pyport.h. */ +typedef Py_intptr_t npy_intp; +typedef Py_uintptr_t npy_uintp; +#define NPY_SIZEOF_INTP SIZEOF_PY_INTPTR_T +#define NPY_SIZEOF_UINTP SIZEOF_PY_INTPTR_T + +#if (PY_VERSION_HEX < 0x02050000) +typedef int Py_ssize_t; +#define PY_SSIZE_T_MAX INT_MAX +#define PY_SSIZE_T_MIN INT_MIN +#define NPY_SSIZE_T_PYFMT "i" +#define constchar const char +#else +#define NPY_SSIZE_T_PYFMT "n" +#define constchar char +#endif + +#if SIZEOF_PY_INTPTR_T == SIZEOF_INT + #define NPY_INTP NPY_INT + #define NPY_UINTP NPY_UINT + #define PyIntpArrType_Type PyIntArrType_Type + #define PyUIntpArrType_Type PyUIntArrType_Type + #define NPY_MAX_INTP NPY_MAX_INT + #define NPY_MIN_INTP NPY_MIN_INT + #define NPY_MAX_UINTP NPY_MAX_UINT + #define NPY_INTP_FMT "d" +#elif SIZEOF_PY_INTPTR_T == SIZEOF_LONG + #define NPY_INTP NPY_LONG + #define NPY_UINTP NPY_ULONG + #define PyIntpArrType_Type PyLongArrType_Type + #define PyUIntpArrType_Type PyULongArrType_Type + #define NPY_MAX_INTP NPY_MAX_LONG + #define NPY_MIN_INTP MIN_LONG + #define NPY_MAX_UINTP NPY_MAX_ULONG + #define NPY_INTP_FMT "ld" +#elif defined(PY_LONG_LONG) && (SIZEOF_PY_INTPTR_T == SIZEOF_LONG_LONG) + #define NPY_INTP NPY_LONGLONG + #define NPY_UINTP NPY_ULONGLONG + #define PyIntpArrType_Type PyLongLongArrType_Type + #define PyUIntpArrType_Type PyULongLongArrType_Type + #define NPY_MAX_INTP NPY_MAX_LONGLONG + #define NPY_MIN_INTP NPY_MIN_LONGLONG + #define NPY_MAX_UINTP NPY_MAX_ULONGLONG + #define NPY_INTP_FMT "Ld" +#endif + +#define NPY_ERR(str) fprintf(stderr, #str); fflush(stderr); +#define NPY_ERR2(str) fprintf(stderr, str); fflush(stderr); + +#define NPY_STRINGIFY(x) #x +#define NPY_TOSTRING(x) NPY_STRINGIFY(x) + + /* Macros to define how array, and dimension/strides data is + allocated. + */ + + /* Data buffer */ +#define PyDataMem_NEW(size) ((char *)malloc(size)) + /* #define PyArrayMem_NEW(size) PyMem_NEW(char, size)*/ +#define PyDataMem_FREE(ptr) free(ptr) + /* #define PyArrayMem_FREE(ptr) PyMem_Free(ptr) */ +#define PyDataMem_RENEW(ptr,size) ((char *)realloc(ptr,size)) + +#define NPY_USE_PYMEM 0 + +#if NPY_USE_PYMEM == 1 +#define PyArray_malloc PyObject_Malloc +#define PyArray_free PyObject_Free +#define PyArray_realloc PyObject_Realloc +#else +#define PyArray_malloc malloc +#define PyArray_free free +#define PyArray_realloc realloc +#endif + +/* Dimensions and strides */ +#define PyDimMem_NEW(size) ((npy_intp *)PyArray_malloc(size*sizeof(npy_intp))) +#define PyDimMem_FREE(ptr) PyArray_free(ptr) +#define PyDimMem_RENEW(ptr,size) ((npy_intp *)PyArray_realloc(ptr,size*sizeof(npy_intp))) + + + /* These must deal with unaligned and swapped data if necessary */ +typedef PyObject * (PyArray_GetItemFunc) (void *, void *); +typedef int (PyArray_SetItemFunc)(PyObject *, void *, void *); + +typedef void (PyArray_CopySwapNFunc)(void *, npy_intp, void *, npy_intp, npy_intp, int, void *); +typedef void (PyArray_CopySwapFunc)(void *, void *, int, void *); +typedef npy_bool (PyArray_NonzeroFunc)(void *, void *); + + + /* These assume aligned and notswapped data -- a buffer will be + used before or contiguous data will be obtained + */ +typedef int (PyArray_CompareFunc)(const void *, const void *, void *); +typedef int (PyArray_ArgFunc)(void*, npy_intp, npy_intp*, void *); +typedef void (PyArray_DotFunc)(void *, npy_intp, void *, npy_intp, void *, npy_intp, + void *); +typedef void (PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *); +typedef int (PyArray_ScanFunc)(FILE *, void *, void *, void *); +typedef int (PyArray_FromStrFunc)(char *, void *, char **, void *); + +typedef int (PyArray_FillFunc)(void *, npy_intp, void *); + +typedef int (PyArray_SortFunc)(void *, npy_intp, void *); +typedef int (PyArray_ArgSortFunc)(void *, npy_intp *, npy_intp, void *); + +typedef int (PyArray_FillWithScalarFunc)(void *, npy_intp, void *, void *); + +typedef int (PyArray_ScalarKindFunc)(void *); + +typedef struct { + npy_intp *ptr; + int len; +} PyArray_Dims; + +typedef struct { + /* Functions to cast to all other standard types*/ + /* Can have some NULL entries */ + PyArray_VectorUnaryFunc *cast[NPY_NTYPES]; + + /* The next four functions *cannot* be NULL */ + + /* Functions to get and set items with standard + Python types -- not array scalars */ + PyArray_GetItemFunc *getitem; + PyArray_SetItemFunc *setitem; + + /* Copy and/or swap data. Memory areas may not overlap */ + /* Use memmove first if they might */ + PyArray_CopySwapNFunc *copyswapn; + PyArray_CopySwapFunc *copyswap; + + /* Function to compare items */ + /* Can be NULL + */ + PyArray_CompareFunc *compare; + + /* Function to select largest + Can be NULL + */ + PyArray_ArgFunc *argmax; + + /* Function to compute dot product */ + /* Can be NULL */ + PyArray_DotFunc *dotfunc; + + /* Function to scan an ASCII file and + place a single value plus possible separator + Can be NULL + */ + PyArray_ScanFunc *scanfunc; + + /* Function to read a single value from a string */ + /* and adjust the pointer; Can be NULL */ + PyArray_FromStrFunc *fromstr; + + /* Function to determine if data is zero or not */ + /* If NULL a default version is */ + /* used at Registration time. */ + PyArray_NonzeroFunc *nonzero; + + /* Used for arange. Can be NULL.*/ + PyArray_FillFunc *fill; + + /* Function to fill arrays with scalar values + Can be NULL*/ + PyArray_FillWithScalarFunc *fillwithscalar; + + /* Sorting functions; Can be NULL*/ + PyArray_SortFunc *sort[NPY_NSORTS]; + PyArray_ArgSortFunc *argsort[NPY_NSORTS]; + + /* Dictionary of additional casting functions + PyArray_VectorUnaryFuncs + which can be populated to support casting + to other registered types. Can be NULL*/ + PyObject *castdict; + + /* Functions useful for generalizing + the casting rules. Can be NULL; + */ + PyArray_ScalarKindFunc *scalarkind; + int **cancastscalarkindto; + int *cancastto; + + /* Set to 1 if you want pickles of this type + to go out as lists of _getitem objects + */ + int listpickle; + +} PyArray_ArrFuncs; + + +typedef struct { + PyObject_HEAD + PyTypeObject *typeobj; /* the type object representing an + instance of this type -- should not + be two type_numbers with the same type + object. */ + char kind; /* kind for this type */ + char type; /* unique-character representing this type */ + char byteorder; /* '>' (big), '<' (little), '|' + (not-applicable), or '=' (native). */ + char hasobject; /* non-zero if it has object arrays in fields */ + int type_num; /* number representing this type */ + int elsize; /* element size for this type */ + int alignment; /* alignment needed for this type */ + struct _arr_descr \ + *subarray; /* Non-NULL if this type is + is an array (C-contiguous) + of some other type + */ + PyObject *fields; /* The fields dictionary for this type */ + /* For statically defined descr this + is always Py_None */ + + PyObject *names; /* An ordered tuple of field names or NULL + if no fields are defined */ + + PyArray_ArrFuncs *f; /* a table of functions specific for each + basic data descriptor */ +} PyArray_Descr; + +typedef struct _arr_descr { + PyArray_Descr *base; + PyObject *shape; /* a tuple */ +} PyArray_ArrayDescr; + +/* + The main array object structure. It is recommended to use the macros + defined below (PyArray_DATA and friends) access fields here, instead + of the members themselves. + */ + +typedef struct PyArrayObject { + PyObject_HEAD + char *data; /* pointer to raw data buffer */ + int nd; /* number of dimensions, also called ndim */ + npy_intp *dimensions; /* size in each dimension */ + npy_intp *strides; /* bytes to jump to get to the + next element in each dimension */ + PyObject *base; /* This object should be decref'd + upon deletion of array */ + /* For views it points to the original array */ + /* For creation from buffer object it points + to an object that shold be decref'd on + deletion */ + /* For UPDATEIFCOPY flag this is an array + to-be-updated upon deletion of this one */ + PyArray_Descr *descr; /* Pointer to type structure */ + int flags; /* Flags describing array -- see below*/ + PyObject *weakreflist; /* For weakreferences */ +} PyArrayObject; + +#define NPY_AO PyArrayObject + +#define fortran fortran_ /* For some compilers */ + +/* Mirrors buffer object to ptr */ + +typedef struct { + PyObject_HEAD + PyObject *base; + void *ptr; + npy_intp len; + int flags; +} PyArray_Chunk; + +typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *); + +/* Means c-style contiguous (last index varies the fastest). The + data elements right after each other. */ +#define NPY_CONTIGUOUS 0x0001 +/* set if array is a contiguous Fortran array: the first index + varies the fastest in memory (strides array is reverse of + C-contiguous array)*/ +#define NPY_FORTRAN 0x0002 + +/* + Note: all 0-d arrays are CONTIGUOUS and FORTRAN contiguous. If a + 1-d array is CONTIGUOUS it is also FORTRAN contiguous +*/ + +/* If set, the array owns the data: it will be free'd when the array + is deleted. */ +#define NPY_OWNDATA 0x0004 + +/* An array never has the next four set; they're only used as parameter + flags to the the various FromAny functions */ + +/* Cause a cast to occur regardless of whether or not it is safe. */ +#define NPY_FORCECAST 0x0010 + +/* Always copy the array. Returned arrays are always CONTIGUOUS, ALIGNED, + and WRITEABLE. */ +#define NPY_ENSURECOPY 0x0020 + +/* Make sure the returned array is an ndarray or a bigndarray */ +#define NPY_ENSUREARRAY 0x0040 + +/* Make sure that the strides are in units of the element size + Needed for some operations with record-arrays. +*/ +#define NPY_ELEMENTSTRIDES 0x0080 + +/* Array data is aligned on the appropiate memory address for the + type stored according to how the compiler would align things + (e.g., an array of integers (4 bytes each) starts on + a memory address that's a multiple of 4) */ +#define NPY_ALIGNED 0x0100 +/* Array data has the native endianness */ +#define NPY_NOTSWAPPED 0x0200 +/* Array data is writeable */ +#define NPY_WRITEABLE 0x0400 +/* If this flag is set, then base contains a pointer to an array of + the same size that should be updated with the current contents of + this array when this array is deallocated +*/ +#define NPY_UPDATEIFCOPY 0x1000 + +/* This flag is for the array interface */ +#define NPY_ARR_HAS_DESCR 0x0800 + + +#define NPY_BEHAVED NPY_ALIGNED | NPY_WRITEABLE +#define NPY_BEHAVED_NS NPY_ALIGNED | NPY_WRITEABLE | NPY_NOTSWAPPED +#define NPY_CARRAY NPY_CONTIGUOUS | NPY_BEHAVED +#define NPY_CARRAY_RO NPY_CONTIGUOUS | NPY_ALIGNED +#define NPY_FARRAY NPY_FORTRAN | NPY_BEHAVED +#define NPY_FARRAY_RO NPY_FORTRAN | NPY_ALIGNED +#define NPY_DEFAULT NPY_CARRAY +#define NPY_IN_ARRAY NPY_CARRAY_RO +#define NPY_OUT_ARRAY NPY_CARRAY +#define NPY_INOUT_ARRAY NPY_CARRAY | NPY_UPDATEIFCOPY +#define NPY_IN_FARRAY NPY_FARRAY_RO +#define NPY_OUT_FARRAY NPY_FARRAY +#define NPY_INOUT_FARRAY NPY_FARRAY | NPY_UPDATEIFCOPY + +#define NPY_UPDATE_ALL NPY_CONTIGUOUS | NPY_FORTRAN | NPY_ALIGNED + + +/* Size of internal buffers used for alignment */ +/* Make BUFSIZE a multiple of sizeof(cdouble) -- ususally 16 */ +/* So that ufunc buffers are aligned */ +#define NPY_MIN_BUFSIZE ((int)sizeof(cdouble)) +#define NPY_MAX_BUFSIZE (((int)sizeof(cdouble))*1000000) +#define NPY_BUFSIZE 10000 +/* #define NPY_BUFSIZE 80*/ + +#define PyArray_MAX(a,b) (((a)>(b))?(a):(b)) +#define PyArray_MIN(a,b) (((a)<(b))?(a):(b)) + + +/* + * C API: consists of Macros and functions. The MACROS are defined here. + */ + + +#define PyArray_CHKFLAGS(m, FLAGS) \ + ((((PyArrayObject *)(m))->flags & (FLAGS)) == (FLAGS)) +#define PyArray_ISCONTIGUOUS(m) PyArray_CHKFLAGS(m, NPY_CONTIGUOUS) +#define PyArray_ISWRITEABLE(m) PyArray_CHKFLAGS(m, NPY_WRITEABLE) +#define PyArray_ISALIGNED(m) PyArray_CHKFLAGS(m, NPY_ALIGNED) + + +#if NPY_ALLOW_THREADS +#define NPY_BEGIN_ALLOW_THREADS Py_BEGIN_ALLOW_THREADS +#define NPY_END_ALLOW_THREADS Py_END_ALLOW_THREADS +#define NPY_BEGIN_THREADS_DEF PyThreadState *_save=NULL; +#define NPY_BEGIN_THREADS _save = PyEval_SaveThread(); +#define NPY_END_THREADS if (_save) PyEval_RestoreThread(_save); +#define NPY_BEGIN_THREADS_DESCR(dtype) if (!((dtype)->hasobject)) NPY_BEGIN_THREADS +#define NPY_END_THREADS_DESCR(dtype) if (!((dtype)->hasobject)) NPY_END_THREADS +#define NPY_ALLOW_C_API_DEF PyGILState_STATE __save__; +#define NPY_ALLOW_C_API __save__ = PyGILState_Ensure(); +#define NPY_DISABLE_C_API PyGILState_Release(__save__); +#else +#define NPY_BEGIN_ALLOW_THREADS +#define NPY_END_ALLOW_THREADS +#define NPY_BEGIN_THREADS_DEF +#define NPY_BEGIN_THREADS +#define NPY_END_THREADS +#define NPY_BEGIN_THREADS_DESCR(dtype) +#define NPY_END_THREADS_DESCR(dtype) +#define NPY_ALLOW_C_API_DEF +#define NPY_ALLOW_C_API +#define NPY_DISABLE_C_API +#endif + +typedef struct { + PyObject_HEAD + int nd_m1; /* number of dimensions - 1 */ + npy_intp index, size; + npy_intp coordinates[NPY_MAXDIMS];/* N-dimensional loop */ + npy_intp dims_m1[NPY_MAXDIMS]; /* ao->dimensions - 1 */ + npy_intp strides[NPY_MAXDIMS]; /* ao->strides or fake */ + npy_intp backstrides[NPY_MAXDIMS];/* how far to jump back */ + npy_intp factors[NPY_MAXDIMS]; /* shape factors */ + PyArrayObject *ao; + char *dataptr; /* pointer to current item*/ + npy_bool contiguous; +} PyArrayIterObject; + + +/* Iterator API */ +#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type) + +#define PyArray_ITER_RESET(it) { \ + (it)->index = 0; \ + (it)->dataptr = (it)->ao->data; \ + memset((it)->coordinates, 0, ((it)->nd_m1+1)*sizeof(npy_intp)); \ +} + +#define _PyArray_ITER_NEXT1(it) { \ + (it)->dataptr += (it)->strides[0]; \ + (it)->coordinates[0]++; \ + } + +#define _PyArray_ITER_NEXT2(it) { \ + if ((it)->coordinates[1] < (it)->dims_m1[1]) { \ + (it)->coordinates[1]++; \ + (it)->dataptr += (it)->strides[1]; \ + } \ + else { \ + (it)->coordinates[1] = 0; \ + (it)->coordinates[0]++; \ + (it)->dataptr += (it)->strides[0] - \ + (it)->backstrides[1]; \ + } \ + } + +#define PyArray_ITER_NEXT(it) { \ + (it)->index++; \ + if ((it)->nd_m1 == 0) { \ + _PyArray_ITER_NEXT1(it); \ + } \ + else if ((it)->contiguous) (it)->dataptr += (it)->ao->descr->elsize; \ + else if ((it)->nd_m1 == 1) { \ + _PyArray_ITER_NEXT2(it); \ + } \ + else { \ + int __npy_i; \ + for (__npy_i = (it)->nd_m1; __npy_i >= 0; __npy_i--) { \ + if ((it)->coordinates[__npy_i] < \ + (it)->dims_m1[__npy_i]) { \ + (it)->coordinates[__npy_i]++; \ + (it)->dataptr += (it)->strides[__npy_i]; \ + break; \ + } \ + else { \ + (it)->coordinates[__npy_i] = 0; \ + (it)->dataptr -= (it)->backstrides[__npy_i]; \ + } \ + } \ + } \ +} + +#define PyArray_ITER_GOTO(it, destination) { \ + int __npy_i; \ + (it)->index = 0; \ + (it)->dataptr = (it)->ao->data; \ + for (__npy_i = (it)->nd_m1; __npy_i>=0; __npy_i--) { \ + if (destination[__npy_i] < 0) { \ + destination[__npy_i] += (it)->dims_m1[__npy_i]+1; \ + } \ + (it)->dataptr += destination[__npy_i] * \ + (it)->strides[__npy_i]; \ + (it)->coordinates[__npy_i] = destination[__npy_i]; \ + (it)->index += destination[__npy_i] * \ + ( __npy_i==(it)->nd_m1 ? 1 : \ + (it)->dims_m1[__npy_i+1]+1) ; \ + } \ + } + +#define PyArray_ITER_GOTO1D(it, ind) { \ + int __npy_i; \ + npy_intp __npy_ind = (npy_intp) (ind); \ + if (__npy_ind < 0) __npy_ind += (it)->size; \ + (it)->index = __npy_ind; \ + if ((it)->nd_m1 == 0) { \ + (it)->dataptr = (it)->ao->data + __npy_ind * \ + (it)->strides[0]; \ + } \ + else if ((it)->contiguous) \ + (it)->dataptr = (it)->ao->data + __npy_ind * \ + (it)->ao->descr->elsize; \ + else { \ + (it)->dataptr = (it)->ao->data; \ + for (__npy_i = 0; __npy_i<=(it)->nd_m1; __npy_i++) { \ + (it)->dataptr += (__npy_ind / (it)->factors[__npy_i]) \ + * (it)->strides[__npy_i]; \ + __npy_ind %= (it)->factors[__npy_i]; \ + } \ + } \ +} + +#define PyArray_ITER_DATA(it) ((PyArrayIterObject *)it)->dataptr + + +/* + Any object passed to PyArray_Broadcast must be binary compatible with + this structure. +*/ + +typedef struct { + PyObject_HEAD + int numiter; /* number of iters */ + npy_intp size; /* broadcasted size */ + npy_intp index; /* current index */ + int nd; /* number of dims */ + npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ + PyArrayIterObject *iters[NPY_MAXARGS]; /* iterators */ +} PyArrayMultiIterObject; + +#define PyArray_MultiIter_RESET(multi) { \ + int __npy_mi; \ + PyArrayMultiIterObject *__npy_mul = (multi); \ + __npy_mul->index = 0; \ + for (__npy_mi = 0; __npy_mi < __npy_mul->numiter; __npy_mi++) { \ + PyArray_ITER_RESET(__npy_mul->iters[__npy_mi]); \ + } \ + } + +#define PyArray_MultiIter_NEXT(multi) { \ + int __npy_mi; \ + PyArrayMultiIterObject *__npy_mul = (multi); \ + __npy_mul->index += 1; \ + for (__npy_mi=0; __npy_mi<__npy_mul->numiter; __npy_mi++) { \ + PyArray_ITER_NEXT(__npy_mul->iters[__npy_mi]); \ + } \ + } + +#define PyArray_MultiIter_GOTO(multi, dest) { \ + int __npy_mi; \ + PyArrayMultiIterObject *__npy_mul = (multi); \ + for (__npy_mi=0; __npy_mi<__npy_mul->numiter; __npy_mi++) { \ + PyArray_ITER_GOTO(__npy_mul->iters[__npy_mi], dest); \ + } \ + __npy_mul->index = __npy_mul->iters[0]->index; \ + } + +#define PyArray_MultiIter_GOTO1D(multi, ind) { \ + int __npy_mi; \ + PyArrayMultiIterObject *__npy_mul = (multi); \ + for (__npy_mi=0; __npy_mi<__npy_mul->numiter; __npy_mi++) { \ + PyArray_ITER_GOTO1D(__npy_mul->iters[__npy_mi], ind); \ + } \ + __npy_mul->index = __npy_mul->iters[0]->index; \ + } + +#define PyArray_MultiIter_DATA(multi, i) \ + (((PyArrayMultiIterObject *)multi)->iters[i]->dataptr) + +#define PyArray_MultiIter_SIZE(multi) \ + ((PyArrayMultiIterObject *)multi)->size + +#define PyArray_MultiIter_NEXTi(multi, i) \ + PyArray_ITER_NEXT(((PyArrayMultiIterObject *)multi)->iters[i]) + +/* Store the information needed for fancy-indexing over an array */ + +typedef struct { + PyObject_HEAD + /* Multi-iterator portion --- needs to be present in this order to + work with PyArray_Broadcast */ + + int numiter; /* number of index-array + iterators */ + npy_intp size; /* size of broadcasted + result */ + npy_intp index; /* current index */ + int nd; /* number of dims */ + npy_intp dimensions[NPY_MAXDIMS]; /* dimensions */ + PyArrayIterObject *iters[NPY_MAXDIMS]; /* index object + iterators */ + PyArrayIterObject *ait; /* flat Iterator for + underlying array */ + + /* flat iterator for subspace (when numiter < nd) */ + PyArrayIterObject *subspace; + + /* if subspace iteration, then this is the array of + axes in the underlying array represented by the + index objects */ + int iteraxes[NPY_MAXDIMS]; + /* if subspace iteration, the these are the coordinates + to the start of the subspace. + */ + npy_intp bscoord[NPY_MAXDIMS]; + + PyObject *indexobj; /* creating obj */ + int view; + int consec; + char *dataptr; + +} PyArrayMapIterObject; + +/* The default array type + */ +#define NPY_DEFAULT_TYPE NPY_DOUBLE +#define PyArray_DEFAULT NPY_DEFAULT_TYPE +/* All sorts of useful ways to look into a PyArrayObject. + These are the recommended over casting to PyArrayObject and accessing + the members directly. + */ + +#define PyArray_NDIM(obj) (((PyArrayObject *)(obj))->nd) +#define PyArray_ISONESEGMENT(m) (PyArray_NDIM(m) == 0 || PyArray_CHKFLAGS(m, NPY_CONTIGUOUS) || \ + PyArray_CHKFLAGS(m, NPY_FORTRAN)) +#define PyArray_ISFORTRAN(m) (PyArray_CHKFLAGS(m, NPY_FORTRAN) && (PyArray_NDIM(m) > 1)) +#define PyArray_FORTRAN_IF(m) ((PyArray_CHKFLAGS(m, NPY_FORTRAN) ? NPY_FORTRAN : 0)) +#define FORTRAN_IF PyArray_FORTRAN_IF +#define PyArray_DATA(obj) ((void *)(((PyArrayObject *)(obj))->data)) +#define PyArray_BYTES(obj) (((PyArrayObject *)(obj))->data) +#define PyArray_DIMS(obj) (((PyArrayObject *)(obj))->dimensions) +#define PyArray_STRIDES(obj) (((PyArrayObject *)(obj))->strides) +#define PyArray_DIM(obj,n) (PyArray_DIMS(obj)[n]) +#define PyArray_STRIDE(obj,n) (PyArray_STRIDES(obj)[n]) +#define PyArray_BASE(obj) (((PyArrayObject *)(obj))->base) +#define PyArray_DESCR(obj) (((PyArrayObject *)(obj))->descr) +#define PyArray_FLAGS(obj) (((PyArrayObject *)(obj))->flags) +#define PyArray_ITEMSIZE(obj) (((PyArrayObject *)(obj))->descr->elsize) +#define PyArray_TYPE(obj) (((PyArrayObject *)(obj))->descr->type_num) +#define PyArray_GETITEM(obj,itemptr) \ + ((PyArrayObject *)(obj))->descr->f->getitem((char *)itemptr, \ + (PyArrayObject *)obj); +#define PyArray_SETITEM(obj,itemptr,v) \ + ((PyArrayObject *)(obj))->descr->f->setitem((PyObject *)v, \ + (char *)(itemptr), \ + (PyArrayObject *)(obj)); + + +#define PyTypeNum_ISBOOL(type) (type == NPY_BOOL) +#define PyTypeNum_ISUNSIGNED(type) ((type == NPY_UBYTE) || \ + (type == NPY_USHORT) || \ + (type == NPY_UINT) || \ + (type == NPY_ULONG) || \ + (type == NPY_ULONGLONG)) + +#define PyTypeNum_ISSIGNED(type) ((type == NPY_BYTE) || \ + (type == NPY_SHORT) || \ + (type == NPY_INT) || \ + (type == NPY_LONG) || \ + (type == NPY_LONGLONG)) + +#define PyTypeNum_ISINTEGER(type) ((type >= NPY_BYTE) && \ + (type <= NPY_ULONGLONG)) + +#define PyTypeNum_ISFLOAT(type) ((type >= NPY_FLOAT) && \ + (type <= NPY_LONGDOUBLE)) + +#define PyTypeNum_ISNUMBER(type) (type <= NPY_CLONGDOUBLE) + +#define PyTypeNum_ISSTRING(type) ((type == NPY_STRING) || \ + (type == NPY_UNICODE)) + +#define PyTypeNum_ISCOMPLEX(type) ((type >= NPY_CFLOAT) && \ + (type <= NPY_CLONGDOUBLE)) + +#define PyTypeNum_ISPYTHON(type) ((type == NPY_LONG) || \ + (type == NPY_DOUBLE) || \ + (type == NPY_CDOUBLE) || \ + (type == NPY_BOOL) || \ + (type == NPY_OBJECT )) + +#define PyTypeNum_ISFLEXIBLE(type) ((type>=NPY_STRING) && \ + (type<=NPY_VOID)) + +#define PyTypeNum_ISUSERDEF(type) ((type >= NPY_USERDEF) && \ + (type < NPY_USERDEF+\ + NPY_NUMUSERTYPES)) + +#define PyTypeNum_ISEXTENDED(type) (PyTypeNum_ISFLEXIBLE(type) || \ + PyTypeNum_ISUSERDEF(type)) + +#define PyTypeNum_ISOBJECT(type) ((type) == NPY_OBJECT) + + +#define PyDataType_ISBOOL(obj) PyTypeNum_ISBOOL(_PyADt(obj)) +#define PyDataType_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISSIGNED(obj) PyTypeNum_ISSIGNED(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISINTEGER(obj) PyTypeNum_ISINTEGER(((PyArray_Descr*)obj)->type_num ) +#define PyDataType_ISFLOAT(obj) PyTypeNum_ISFLOAT(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISNUMBER(obj) PyTypeNum_ISNUMBER(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISSTRING(obj) PyTypeNum_ISSTRING(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISPYTHON(obj) PyTypeNum_ISPYTHON(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(((PyArray_Descr*)obj)->type_num) +#define PyDataType_ISOBJECT(obj) PyTypeNum_ISOBJECT(((PyArray_Descr*)obj)->type_num) +#define PyDataType_HASFIELDS(obj) (((PyArray_Descr *)obj)->names) + +#define PyArray_ISBOOL(obj) PyTypeNum_ISBOOL(PyArray_TYPE(obj)) +#define PyArray_ISUNSIGNED(obj) PyTypeNum_ISUNSIGNED(PyArray_TYPE(obj)) +#define PyArray_ISSIGNED(obj) PyTypeNum_ISSIGNED(PyArray_TYPE(obj)) +#define PyArray_ISINTEGER(obj) PyTypeNum_ISINTEGER(PyArray_TYPE(obj)) +#define PyArray_ISFLOAT(obj) PyTypeNum_ISFLOAT(PyArray_TYPE(obj)) +#define PyArray_ISNUMBER(obj) PyTypeNum_ISNUMBER(PyArray_TYPE(obj)) +#define PyArray_ISSTRING(obj) PyTypeNum_ISSTRING(PyArray_TYPE(obj)) +#define PyArray_ISCOMPLEX(obj) PyTypeNum_ISCOMPLEX(PyArray_TYPE(obj)) +#define PyArray_ISPYTHON(obj) PyTypeNum_ISPYTHON(PyArray_TYPE(obj)) +#define PyArray_ISFLEXIBLE(obj) PyTypeNum_ISFLEXIBLE(PyArray_TYPE(obj)) +#define PyArray_ISUSERDEF(obj) PyTypeNum_ISUSERDEF(PyArray_TYPE(obj)) +#define PyArray_ISEXTENDED(obj) PyTypeNum_ISEXTENDED(PyArray_TYPE(obj)) +#define PyArray_ISOBJECT(obj) PyTypeNum_ISOBJECT(PyArray_TYPE(obj)) +#define PyArray_HASFIELDS(obj) PyDataType_HASFIELDS(PyArray_DESCR(obj)) + +#define NPY_LITTLE '<' +#define NPY_BIG '>' +#define NPY_NATIVE '=' +#define NPY_SWAP 's' +#define NPY_IGNORE '|' + +#ifdef WORDS_BIGENDIAN +#define NPY_NATBYTE NPY_BIG +#define NPY_OPPBYTE NPY_LITTLE +#else +#define NPY_NATBYTE NPY_LITTLE +#define NPY_OPPBYTE NPY_BIG +#endif + +#define PyArray_ISNBO(arg) ((arg) != NPY_OPPBYTE) +#define PyArray_IsNativeByteOrder PyArray_ISNBO +#define PyArray_ISNOTSWAPPED(m) PyArray_ISNBO(PyArray_DESCR(m)->byteorder) +#define PyArray_ISBYTESWAPPED(m) (!PyArray_ISNOTSWAPPED(m)) + +#define PyArray_FLAGSWAP(m, flags) (PyArray_CHKFLAGS(m, flags) && \ + PyArray_ISNOTSWAPPED(m)) +#define PyArray_ISCARRAY(m) PyArray_FLAGSWAP(m, NPY_CARRAY) +#define PyArray_ISCARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_CARRAY_RO) +#define PyArray_ISFARRAY(m) PyArray_FLAGSWAP(m, NPY_FARRAY) +#define PyArray_ISFARRAY_RO(m) PyArray_FLAGSWAP(m, NPY_FARRAY_RO) +#define PyArray_ISBEHAVED(m) PyArray_FLAGSWAP(m, NPY_BEHAVED) +#define PyArray_ISBEHAVED_RO(m) PyArray_FLAGSWAP(m, NPY_ALIGNED) + + + +/* This is the form of the struct that's returned pointed by the + PyCObject attribute of an array __array_struct__. See + http://numeric.scipy.org/array_interface.html for the full + documentation. */ +typedef struct { + int two; /* contains the integer 2 as a sanity check */ + int nd; /* number of dimensions */ + char typekind; /* kind in array --- character code of typestr */ + int itemsize; /* size of each element */ + int flags; /* how should be data interpreted. Valid + flags are CONTIGUOUS (1), FORTRAN (2), + ALIGNED (0x100), NOTSWAPPED (0x200), and + WRITEABLE (0x400). + ARR_HAS_DESCR (0x800) states that arrdescr + field is present in structure */ + npy_intp *shape; /* A length-nd array of shape information */ + npy_intp *strides; /* A length-nd array of stride information */ + void *data; /* A pointer to the first element of the array */ + PyObject *descr; /* A list of fields or NULL (ignored if flags + does not have ARR_HAS_DESCR flag set) */ +} PyArrayInterface; + +/* Includes the "function" C-API -- these are all stored in a + list of pointers --- one for each file + The two lists are concatenated into one in multiarray. + + They are available as import_array() +*/ + + +#include "__multiarray_api.h" + + +/* C-API that requries previous API to be defined */ + +#define PyArray_DescrCheck(op) ((op)->ob_type == &PyArrayDescr_Type) + +#define PyArray_Check(op) ((op)->ob_type == &PyArray_Type || \ + PyObject_TypeCheck((op), &PyArray_Type)) +#define PyArray_CheckExact(op) ((op)->ob_type == &PyArray_Type) + +#define PyArray_IsZeroDim(op) (PyArray_Check(op) && (PyArray_NDIM(op) == 0)) +#define PyArray_IsScalar(obj, cls) \ + (PyObject_TypeCheck((obj), &Py##cls##ArrType_Type)) +#define PyArray_CheckScalar(m) (PyArray_IsScalar(m, Generic) || \ + PyArray_IsZeroDim(m)) +#define PyArray_IsPythonNumber(obj) \ + (PyInt_Check(obj) || PyFloat_Check(obj) || PyComplex_Check(obj) || \ + PyLong_Check(obj) || PyBool_Check(obj)) +#define PyArray_IsPythonScalar(obj) \ + (PyArray_IsPythonNumber(obj) || PyString_Check(obj) || \ + PyUnicode_Check(obj)) +#define PyArray_IsAnyScalar(obj) \ + (PyArray_IsScalar(obj, Generic) || PyArray_IsPythonScalar(obj)) +#define PyArray_CheckAnyScalar(obj) (PyArray_IsPythonScalar(obj) || \ + PyArray_CheckScalar(obj)) + +#define PyArray_GETCONTIGUOUS(m) (PyArray_ISCONTIGUOUS(m) ? Py_INCREF(m), m : \ + (PyArrayObject *)(PyArray_Copy(m))) + +#define PyArray_SAMESHAPE(a1,a2) ((PyArray_NDIM(a1) == PyArray_NDIM(a2)) && \ + PyArray_CompareLists(PyArray_DIMS(a1), \ + PyArray_DIMS(a2), \ + PyArray_NDIM(a1))) +#define PyArray_SIZE(m) PyArray_MultiplyList(PyArray_DIMS(m), PyArray_NDIM(m)) +#define PyArray_NBYTES(m) (PyArray_ITEMSIZE(m) * PyArray_SIZE(m)) +#define PyArray_FROM_O(m) PyArray_FromAny(m, NULL, 0, 0, 0, NULL) +#define PyArray_FROM_OF(m,flags) PyArray_CheckFromAny(m, NULL, 0, 0, flags, NULL) +#define PyArray_FROM_OT(m,type) PyArray_FromAny(m, PyArray_DescrFromType(type), \ + 0, 0, 0, NULL); +#define PyArray_FROM_OTF(m, type, flags) \ + PyArray_FromAny(m, PyArray_DescrFromType(type), 0, 0, \ + (((flags) & NPY_ENSURECOPY) ? \ + ((flags) | NPY_DEFAULT) : (flags)), NULL) +#define PyArray_FROMANY(m, type, min, max, flags) \ + PyArray_FromAny(m, PyArray_DescrFromType(type), min, max, \ + (((flags) & NPY_ENSURECOPY) ? \ + (flags) | NPY_DEFAULT : (flags)), NULL) +#define PyArray_ZEROS(m, dims, type, fortran) \ + PyArray_Zeros(m, dims, PyArray_DescrFromType(type), fortran) +#define PyArray_EMPTY(m, dims, type, fortran) \ + PyArray_Empty(m, dims, PyArray_DescrFromType(type), fortran) + +#define PyArray_FILLWBYTE(obj, val) memset(PyArray_DATA(obj), (val), PyArray_NBYTES(obj)) + +#define PyArray_REFCOUNT(obj) (((PyObject *)(obj))->ob_refcnt) +#define NPY_REFCOUNT PyArray_REFCOUNT +#define NPY_MAX_ELSIZE 2*SIZEOF_LONGDOUBLE + +#define PyArray_ContiguousFromAny(op, type, min_depth, max_depth) \ + PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ + max_depth, NPY_DEFAULT, NULL) + +#define PyArray_EquivArrTypes(a1, a2) \ + PyArray_EquivTypes(PyArray_DESCR(a1), PyArray_DESCR(a2)) + +#define PyArray_EquivByteorders(b1, b2) \ + (((b1) == (b2)) || (PyArray_ISNBO(b1) == PyArray_ISNBO(b2))) + +#define PyArray_SimpleNew(nd, dims, typenum) \ + PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, NULL, 0, 0, NULL) +#define PyArray_SimpleNewFromData(nd, dims, typenum, data) \ + PyArray_New(&PyArray_Type, nd, dims, typenum, NULL, data, 0, NPY_CARRAY, NULL) +#define PyArray_SimpleNewFromDescr(nd, dims, descr) \ + PyArray_NewFromDescr(&PyArray_Type, descr, nd, dims, NULL, NULL, 0, NULL) + +#define PyArray_ToScalar(data, arr) \ + PyArray_Scalar(data, PyArray_DESCR(arr), (PyObject *)arr) + +/* These might be faster without the dereferencing of obj + going on inside -- of course an optimizing compiler should + inline the constants inside a for loop making it a moot point +*/ + +#define PyArray_GETPTR1(obj, i) (void *)(PyArray_BYTES(obj) + \ + i*PyArray_STRIDES(obj)[0]) + +#define PyArray_GETPTR2(obj, i, j) (void *)(PyArray_BYTES(obj) + \ + i*PyArray_STRIDES(obj)[0] + \ + j*PyArray_STRIDES(obj)[1]) + +#define PyArray_GETPTR3(obj, i, j, k) (void *)(PyArray_BYTES(obj) + \ + i*PyArray_STRIDES(obj)[0] + \ + j*PyArray_STRIDES(obj)[1] + \ + k*PyArray_STRIDES(obj)[2]) \ + +#define PyArray_GETPTR4(obj, i, j, k, l) (void *)(PyArray_BYTES(obj) + \ + i*PyArray_STRIDES(obj)[0] + \ + j*PyArray_STRIDES(obj)[1] + \ + k*PyArray_STRIDES(obj)[2] + \ + l*PyArray_STRIDES(obj)[3]) + +#define PyArray_XDECREF_ERR(obj) \ + if (obj && (PyArray_FLAGS(obj) & NPY_UPDATEIFCOPY)) { \ + PyArray_FLAGS(PyArray_BASE(obj)) |= NPY_WRITEABLE; \ + PyArray_FLAGS(obj) &= ~NPY_UPDATEIFCOPY; \ + }\ + Py_XDECREF(obj) + +#define PyArray_DESCR_REPLACE(descr) do { \ + PyArray_Descr *_new_; \ + _new_ = PyArray_DescrNew(descr); \ + Py_XDECREF(descr); \ + descr = _new_; \ + } while(0) + +/* Copy should always return contiguous array */ +#define PyArray_Copy(obj) PyArray_NewCopy(obj, NPY_CORDER) + +#define PyArray_FromObject(op, type, min_depth, max_depth) \ + PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ + max_depth, NPY_BEHAVED | NPY_ENSUREARRAY, NULL) + +#define PyArray_ContiguousFromObject(op, type, min_depth, max_depth) \ + PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ + max_depth, NPY_DEFAULT | NPY_ENSUREARRAY, NULL) + +#define PyArray_CopyFromObject(op, type, min_depth, max_depth) \ + PyArray_FromAny(op, PyArray_DescrFromType(type), min_depth, \ + max_depth, NPY_ENSURECOPY | NPY_DEFAULT | NPY_ENSUREARRAY, NULL) + +#define PyArray_Cast(mp, type_num) \ + PyArray_CastToType(mp, PyArray_DescrFromType(type_num), 0) + +#define PyArray_Take(ap, items, axis) \ + PyArray_TakeFrom(ap, items, axis, NULL, NPY_RAISE) + +#define PyArray_Put(ap, items, values) \ + PyArray_PutTo(ap, items, values, NPY_RAISE) + +/* Compatibility with old Numeric stuff -- don't use in new code */ + +#define PyArray_FromDimsAndData(nd, d, type, data) \ + PyArray_FromDimsAndDataAndDescr(nd, d, PyArray_DescrFromType(type), \ + data) + +#include "old_defines.h" + +#ifdef __cplusplus +} +#endif + +#endif /* NPY_NDARRAYOBJECT_H */ From numpy-svn at scipy.org Fri Aug 18 15:09:12 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 18 Aug 2006 14:09:12 -0500 (CDT) Subject: [Numpy-svn] r3037 - trunk/numpy/core Message-ID: <20060818190912.071EF39C050@new.scipy.org> Author: oliphant Date: 2006-08-18 14:09:11 -0500 (Fri, 18 Aug 2006) New Revision: 3037 Modified: trunk/numpy/core/setup.py Log: Fix logic for using THREADS Modified: trunk/numpy/core/setup.py =================================================================== --- trunk/numpy/core/setup.py 2006-08-18 17:06:11 UTC (rev 3036) +++ trunk/numpy/core/setup.py 2006-08-18 19:09:11 UTC (rev 3037) @@ -102,16 +102,15 @@ if check_func('strtod'): moredefs.append(('PyOS_ascii_strtod', 'strtod')) - if moredefs: - target_f = open(target,'a') - for d in moredefs: - if isinstance(d,str): - target_f.write('#define %s\n' % (d)) - else: - target_f.write('#define %s %s\n' % (d[0],d[1])) - if not nosmp: # default is to use WITH_THREAD - target_f.write('#ifdef WITH_THREAD\n#define NPY_ALLOW_THREADS 1\n#else\n#define NPY_ALLOW_THREADS 0\n#endif\n') - target_f.close() + target_f = open(target,'a') + for d in moredefs: + if isinstance(d,str): + target_f.write('#define %s\n' % (d)) + else: + target_f.write('#define %s %s\n' % (d[0],d[1])) + if not nosmp: # default is to use WITH_THREAD + target_f.write('#ifdef WITH_THREAD\n#define NPY_ALLOW_THREADS 1\n#else\n#define NPY_ALLOW_THREADS 0\n#endif\n') + target_f.close() else: mathlibs = [] target_f = open(target) From numpy-svn at scipy.org Fri Aug 18 15:18:19 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 18 Aug 2006 14:18:19 -0500 (CDT) Subject: [Numpy-svn] r3038 - trunk/numpy/core Message-ID: <20060818191819.C849F39C050@new.scipy.org> Author: oliphant Date: 2006-08-18 14:18:18 -0500 (Fri, 18 Aug 2006) New Revision: 3038 Modified: trunk/numpy/core/numerictypes.py Log: Fix missing bool8 Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-18 19:09:11 UTC (rev 3037) +++ trunk/numpy/core/numerictypes.py 2006-08-18 19:18:18 UTC (rev 3038) @@ -110,7 +110,11 @@ base = '' char = '' try: - info = typeinfo[name.upper()] + if name[-1] == '_': + newname = name[:-1] + else: + newname = name + info = typeinfo[newname.upper()] assert(info[-1] == obj) # sanity check bits = info[2] @@ -118,19 +122,19 @@ base, bits = _evalname(name) char = base[0] - if name == 'bool': + if name == 'bool_': char = 'b' base = 'bool' - elif name=='string': + elif name=='string_': char = 'S' base = 'string' - elif name=='unicode': + elif name=='unicode_': char = 'U' base = 'unicode' elif name=='void': char = 'V' base = 'void' - elif name=='object': + elif name=='object_': char = 'O' base = 'object' bits = 0 From numpy-svn at scipy.org Fri Aug 18 17:30:35 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 18 Aug 2006 16:30:35 -0500 (CDT) Subject: [Numpy-svn] r3039 - trunk/numpy/core Message-ID: <20060818213035.2CF3239C105@new.scipy.org> Author: oliphant Date: 2006-08-18 16:29:36 -0500 (Fri, 18 Aug 2006) New Revision: 3039 Modified: trunk/numpy/core/numerictypes.py Log: Fix missing numeric type issues. Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-18 19:18:18 UTC (rev 3038) +++ trunk/numpy/core/numerictypes.py 2006-08-18 21:29:36 UTC (rev 3039) @@ -76,9 +76,9 @@ """ # we add more at the bottom -__all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes', 'ScalarType', 'obj2sctype', - 'cast', 'nbytes', 'sctype2char', 'maximum_sctype', 'issctype', - 'typecodes'] +__all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes', + 'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char', + 'maximum_sctype', 'issctype', 'typecodes'] from multiarray import typeinfo, ndarray, array, empty, dtype import types as _types @@ -187,6 +187,7 @@ na_name = "%s%d" % (base.capitalize(), bit) sctypeDict[na_name] = typeobj sctypeNA[na_name] = typeobj + sctypeDict[na_name] = typeobj sctypeNA[typeobj] = na_name sctypeNA[typeinfo[a][0]] = na_name if char != '': From numpy-svn at scipy.org Sat Aug 19 02:04:17 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 19 Aug 2006 01:04:17 -0500 (CDT) Subject: [Numpy-svn] r3040 - in trunk/numpy/core: . include/numpy src Message-ID: <20060819060417.E052E39C134@new.scipy.org> Author: oliphant Date: 2006-08-19 01:01:10 -0500 (Sat, 19 Aug 2006) New Revision: 3040 Modified: trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/include/numpy/ndarrayobject.h trunk/numpy/core/include/numpy/noprefix.h trunk/numpy/core/include/numpy/old_defines.h trunk/numpy/core/include/numpy/oldnumeric.h trunk/numpy/core/include/numpy/ufuncobject.h trunk/numpy/core/numerictypes.py trunk/numpy/core/src/_isnan.c trunk/numpy/core/src/_signbit.c trunk/numpy/core/src/_sortmodule.c.src trunk/numpy/core/src/arraymethods.c trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/arraytypes.inc.src trunk/numpy/core/src/multiarraymodule.c trunk/numpy/core/src/scalarmathmodule.c.src trunk/numpy/core/src/scalartypes.inc.src trunk/numpy/core/src/ucsnarrow.c trunk/numpy/core/src/ufuncobject.c trunk/numpy/core/src/umathmodule.c.src Log: Fix white-space issues. Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-19 06:01:10 UTC (rev 3040) @@ -6,7 +6,7 @@ long double is present on platform. CHAR_BIT -- number of bits in a char (usually 8) (should be in limits.h) - + */ #ifndef Py_ARRAYOBJECT_H @@ -15,5 +15,13 @@ #ifdef NPY_NO_PREFIX #include "noprefix.h" #endif + + +/* Add signal handling macros */ + +#define NPY_SIG_ON +#define NPY_SIG_OFF +#define NPY_SIG_CHECK + + #endif - Modified: trunk/numpy/core/include/numpy/ndarrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-19 06:01:10 UTC (rev 3040) @@ -77,7 +77,7 @@ #endif #ifndef Py_USING_UNICODE -#error Must use Python with unicode enabled. +#error Must use Python with unicode enabled. #endif @@ -205,7 +205,7 @@ NPY_WRAP=1, NPY_RAISE=2 } NPY_CLIPMODE; - + /* Define bit-width array types and typedefs */ #define NPY_MAX_INT8 127 @@ -684,17 +684,15 @@ /* Data buffer */ #define PyDataMem_NEW(size) ((char *)malloc(size)) - /* #define PyArrayMem_NEW(size) PyMem_NEW(char, size)*/ #define PyDataMem_FREE(ptr) free(ptr) - /* #define PyArrayMem_FREE(ptr) PyMem_Free(ptr) */ #define PyDataMem_RENEW(ptr,size) ((char *)realloc(ptr,size)) -#define NPY_USE_PYMEM 0 +#define NPY_USE_PYMEM 1 #if NPY_USE_PYMEM == 1 -#define PyArray_malloc PyObject_Malloc -#define PyArray_free PyObject_Free -#define PyArray_realloc PyObject_Realloc +#define PyArray_malloc PyMem_Malloc +#define PyArray_free PyMem_Free +#define PyArray_realloc PyMem_Realloc #else #define PyArray_malloc malloc #define PyArray_free free @@ -759,11 +757,11 @@ PyArray_CopySwapFunc *copyswap; /* Function to compare items */ - /* Can be NULL + /* Can be NULL */ PyArray_CompareFunc *compare; - /* Function to select largest + /* Function to select largest Can be NULL */ PyArray_ArgFunc *argmax; @@ -773,8 +771,8 @@ PyArray_DotFunc *dotfunc; /* Function to scan an ASCII file and - place a single value plus possible separator - Can be NULL + place a single value plus possible separator + Can be NULL */ PyArray_ScanFunc *scanfunc; @@ -790,7 +788,7 @@ /* Used for arange. Can be NULL.*/ PyArray_FillFunc *fill; - /* Function to fill arrays with scalar values + /* Function to fill arrays with scalar values Can be NULL*/ PyArray_FillWithScalarFunc *fillwithscalar; @@ -958,7 +956,7 @@ #define NPY_FARRAY_RO NPY_FORTRAN | NPY_ALIGNED #define NPY_DEFAULT NPY_CARRAY #define NPY_IN_ARRAY NPY_CARRAY_RO -#define NPY_OUT_ARRAY NPY_CARRAY +#define NPY_OUT_ARRAY NPY_CARRAY #define NPY_INOUT_ARRAY NPY_CARRAY | NPY_UPDATEIFCOPY #define NPY_IN_FARRAY NPY_FARRAY_RO #define NPY_OUT_FARRAY NPY_FARRAY @@ -972,7 +970,7 @@ /* So that ufunc buffers are aligned */ #define NPY_MIN_BUFSIZE ((int)sizeof(cdouble)) #define NPY_MAX_BUFSIZE (((int)sizeof(cdouble))*1000000) -#define NPY_BUFSIZE 10000 +#define NPY_BUFSIZE 10000 /* #define NPY_BUFSIZE 80*/ #define PyArray_MAX(a,b) (((a)>(b))?(a):(b)) @@ -1003,8 +1001,8 @@ #define NPY_ALLOW_C_API __save__ = PyGILState_Ensure(); #define NPY_DISABLE_C_API PyGILState_Release(__save__); #else -#define NPY_BEGIN_ALLOW_THREADS -#define NPY_END_ALLOW_THREADS +#define NPY_BEGIN_ALLOW_THREADS +#define NPY_END_ALLOW_THREADS #define NPY_BEGIN_THREADS_DEF #define NPY_BEGIN_THREADS #define NPY_END_THREADS @@ -1376,7 +1374,7 @@ int flags; /* how should be data interpreted. Valid flags are CONTIGUOUS (1), FORTRAN (2), ALIGNED (0x100), NOTSWAPPED (0x200), and - WRITEABLE (0x400). + WRITEABLE (0x400). ARR_HAS_DESCR (0x800) states that arrdescr field is present in structure */ npy_intp *shape; /* A length-nd array of shape information */ Modified: trunk/numpy/core/include/numpy/noprefix.h =================================================================== --- trunk/numpy/core/include/numpy/noprefix.h 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/include/numpy/noprefix.h 2006-08-19 06:01:10 UTC (rev 3040) @@ -1,7 +1,7 @@ #ifndef NPY_NOPREFIX_H #define NPY_NOPREFIX_H -/* You can directly include noprefix.h as a backward +/* You can directly include noprefix.h as a backward compatibility measure*/ #ifndef NPY_NO_PREFIX #include "ndarrayobject.h" @@ -58,10 +58,10 @@ #define SIZEOF_INTP NPY_SIZEOF_INTP #define SIZEOF_UINTP NPY_SIZEOF_UINTP -#define LONGLONG_FMT NPY_LONGLONG_FMT -#define ULONGLONG_FMT NPY_ULONGLONG_FMT +#define LONGLONG_FMT NPY_LONGLONG_FMT +#define ULONGLONG_FMT NPY_ULONGLONG_FMT #define LONGLONG_SUFFIX NPY_LONGLONG_SUFFIX -#define ULONGLONG_SUFFIX NPY_ULONGLONG_SUFFIX(x) +#define ULONGLONG_SUFFIX NPY_ULONGLONG_SUFFIX(x) #define MAX_INT8 127 #define MIN_INT8 -128 @@ -99,16 +99,16 @@ #define MAX_ULONGLONG NPY_MAX_ULONGLONG #define SIZEOF_LONGDOUBLE NPY_SIZEOF_LONGDOUBLE -#define SIZEOF_LONGLONG NPY_SIZEOF_LONGLONG -#define BITSOF_BOOL NPY_BITSOF_BOOL -#define BITSOF_CHAR NPY_BITSOF_CHAR -#define BITSOF_SHORT NPY_BITSOF_SHORT -#define BITSOF_INT NPY_BITSOF_INT -#define BITSOF_LONG NPY_BITSOF_LONG -#define BITSOF_LONGLONG NPY_BITSOF_LONGLONG -#define BITSOF_FLOAT NPY_BITSOF_FLOAT -#define BITSOF_DOUBLE NPY_BITSOF_DOUBLE -#define BITSOF_LONGDOUBLE NPY_BITSOF_LONGDOUBLE +#define SIZEOF_LONGLONG NPY_SIZEOF_LONGLONG +#define BITSOF_BOOL NPY_BITSOF_BOOL +#define BITSOF_CHAR NPY_BITSOF_CHAR +#define BITSOF_SHORT NPY_BITSOF_SHORT +#define BITSOF_INT NPY_BITSOF_INT +#define BITSOF_LONG NPY_BITSOF_LONG +#define BITSOF_LONGLONG NPY_BITSOF_LONGLONG +#define BITSOF_FLOAT NPY_BITSOF_FLOAT +#define BITSOF_DOUBLE NPY_BITSOF_DOUBLE +#define BITSOF_LONGDOUBLE NPY_BITSOF_LONGDOUBLE #define PyArray_UCS4 npy_ucs4 #define _pya_malloc PyArray_malloc @@ -116,11 +116,11 @@ #define _pya_realloc PyArray_realloc #define BEGIN_THREADS_DEF NPY_BEGIN_THREADS_DEF -#define BEGIN_THREADS NPY_BEGIN_THREADS -#define END_THREADS NPY_END_THREADS -#define ALLOW_C_API_DEF NPY_ALLOW_C_API_DEF -#define ALLOW_C_API NPY_ALLOW_C_API -#define DISABLE_C_API NPY_DISABLE_C_API +#define BEGIN_THREADS NPY_BEGIN_THREADS +#define END_THREADS NPY_END_THREADS +#define ALLOW_C_API_DEF NPY_ALLOW_C_API_DEF +#define ALLOW_C_API NPY_ALLOW_C_API +#define DISABLE_C_API NPY_DISABLE_C_API #define PY_FAIL NPY_FAIL #define PY_SUCCEED NPY_SUCCEED @@ -136,31 +136,31 @@ #define LONGDOUBLE_FMT NPY_LONGDOUBLE_FMT #define CONTIGUOUS NPY_CONTIGUOUS -#define FORTRAN NPY_FORTRAN -#define OWNDATA NPY_OWNDATA -#define FORCECAST NPY_FORCECAST -#define ENSURECOPY NPY_ENSURECOPY -#define ENSUREARRAY NPY_ENSUREARRAY -#define ELEMENTSTRIDES NPY_ELEMENTSTRIDES -#define ALIGNED NPY_ALIGNED -#define NOTSWAPPED NPY_NOTSWAPPED -#define WRITEABLE NPY_WRITEABLE -#define UPDATEIFCOPY NPY_UPDATEIFCOPY -#define ARR_HAS_DESCR NPY_ARR_HAS_DESCR -#define BEHAVED NPY_BEHAVED -#define BEHAVED_NS NPY_BEHAVED_NS -#define CARRAY NPY_CARRAY -#define CARRAY_RO NPY_CARRAY_RO -#define FARRAY NPY_FARRAY -#define FARRAY_RO NPY_FARRAY_RO -#define DEFAULT NPY_DEFAULT -#define IN_ARRAY NPY_IN_ARRAY -#define OUT_ARRAY NPY_OUT_ARRAY -#define INOUT_ARRAY NPY_INOUT_ARRAY -#define IN_FARRAY NPY_IN_FARRAY -#define OUT_FARRAY NPY_OUT_FARRAY -#define INOUT_FARRAY NPY_INOUT_FARRAY -#define UPDATE_ALL NPY_UPDATE_ALL +#define FORTRAN NPY_FORTRAN +#define OWNDATA NPY_OWNDATA +#define FORCECAST NPY_FORCECAST +#define ENSURECOPY NPY_ENSURECOPY +#define ENSUREARRAY NPY_ENSUREARRAY +#define ELEMENTSTRIDES NPY_ELEMENTSTRIDES +#define ALIGNED NPY_ALIGNED +#define NOTSWAPPED NPY_NOTSWAPPED +#define WRITEABLE NPY_WRITEABLE +#define UPDATEIFCOPY NPY_UPDATEIFCOPY +#define ARR_HAS_DESCR NPY_ARR_HAS_DESCR +#define BEHAVED NPY_BEHAVED +#define BEHAVED_NS NPY_BEHAVED_NS +#define CARRAY NPY_CARRAY +#define CARRAY_RO NPY_CARRAY_RO +#define FARRAY NPY_FARRAY +#define FARRAY_RO NPY_FARRAY_RO +#define DEFAULT NPY_DEFAULT +#define IN_ARRAY NPY_IN_ARRAY +#define OUT_ARRAY NPY_OUT_ARRAY +#define INOUT_ARRAY NPY_INOUT_ARRAY +#define IN_FARRAY NPY_IN_FARRAY +#define OUT_FARRAY NPY_OUT_FARRAY +#define INOUT_FARRAY NPY_INOUT_FARRAY +#define UPDATE_ALL NPY_UPDATE_ALL #define OWN_DATA NPY_OWNDATA #define BEHAVED_FLAGS NPY_BEHAVED @@ -186,4 +186,4 @@ #define REFCOUNT PyArray_REFCOUNT #define MAX_ELSIZE NPY_MAX_ELSIZE -#endif +#endif Modified: trunk/numpy/core/include/numpy/old_defines.h =================================================================== --- trunk/numpy/core/include/numpy/old_defines.h 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/include/numpy/old_defines.h 2006-08-19 06:01:10 UTC (rev 3040) @@ -13,45 +13,45 @@ #define PyArray_TYPES NPY_TYPES #define PyArray_BOOL NPY_BOOL -#define PyArray_BYTE NPY_BYTE -#define PyArray_UBYTE NPY_UBYTE -#define PyArray_SHORT NPY_SHORT -#define PyArray_USHORT NPY_USHORT -#define PyArray_INT NPY_INT -#define PyArray_UINT NPY_UINT -#define PyArray_LONG NPY_LONG -#define PyArray_ULONG NPY_ULONG -#define PyArray_LONGLONG NPY_LONGLONG -#define PyArray_ULONGLONG NPY_ULONGLONG -#define PyArray_FLOAT NPY_FLOAT -#define PyArray_DOUBLE NPY_DOUBLE -#define PyArray_LONGDOUBLE NPY_LONGDOUBLE -#define PyArray_CFLOAT NPY_CFLOAT -#define PyArray_CDOUBLE NPY_CDOUBLE -#define PyArray_CLONGDOUBLE NPY_CLONGDOUBLE -#define PyArray_OBJECT NPY_OBJECT -#define PyArray_STRING NPY_STRING -#define PyArray_UNICODE NPY_UNICODE -#define PyArray_VOID NPY_VOID -#define PyArray_NTYPES NPY_NTYPES -#define PyArray_NOTYPE NPY_NOTYPE -#define PyArray_CHAR NPY_CHAR -#define PyArray_USERDEF NPY_USERDEF +#define PyArray_BYTE NPY_BYTE +#define PyArray_UBYTE NPY_UBYTE +#define PyArray_SHORT NPY_SHORT +#define PyArray_USHORT NPY_USHORT +#define PyArray_INT NPY_INT +#define PyArray_UINT NPY_UINT +#define PyArray_LONG NPY_LONG +#define PyArray_ULONG NPY_ULONG +#define PyArray_LONGLONG NPY_LONGLONG +#define PyArray_ULONGLONG NPY_ULONGLONG +#define PyArray_FLOAT NPY_FLOAT +#define PyArray_DOUBLE NPY_DOUBLE +#define PyArray_LONGDOUBLE NPY_LONGDOUBLE +#define PyArray_CFLOAT NPY_CFLOAT +#define PyArray_CDOUBLE NPY_CDOUBLE +#define PyArray_CLONGDOUBLE NPY_CLONGDOUBLE +#define PyArray_OBJECT NPY_OBJECT +#define PyArray_STRING NPY_STRING +#define PyArray_UNICODE NPY_UNICODE +#define PyArray_VOID NPY_VOID +#define PyArray_NTYPES NPY_NTYPES +#define PyArray_NOTYPE NPY_NOTYPE +#define PyArray_CHAR NPY_CHAR +#define PyArray_USERDEF NPY_USERDEF #define PyArray_NUMUSERTYPES NPY_NUMUSERTYPES #define PyArray_INTP NPY_INTP #define PyArray_UINTP NPY_UINTP -#define PyArray_INT8 NPY_INT8 -#define PyArray_UINT8 NPY_UINT8 -#define PyArray_INT16 NPY_INT16 -#define PyArray_UINT16 NPY_UINT16 -#define PyArray_INT32 NPY_INT32 -#define PyArray_UINT32 NPY_UINT32 +#define PyArray_INT8 NPY_INT8 +#define PyArray_UINT8 NPY_UINT8 +#define PyArray_INT16 NPY_INT16 +#define PyArray_UINT16 NPY_UINT16 +#define PyArray_INT32 NPY_INT32 +#define PyArray_UINT32 NPY_UINT32 #ifdef NPY_INT64 -#define PyArray_INT64 NPY_INT64 -#define PyArray_UINT64 NPY_UINT64 +#define PyArray_INT64 NPY_INT64 +#define PyArray_UINT64 NPY_UINT64 #endif #ifdef NPY_INT128 @@ -86,36 +86,36 @@ #define PyArray_TYPECHAR NPY_TYPECHAR -#define PyArray_BOOLLTR NPY_BOOLLTR -#define PyArray_BYTELTR NPY_BYTELTR -#define PyArray_UBYTELTR NPY_UBYTELTR -#define PyArray_SHORTLTR NPY_SHORTLTR -#define PyArray_USHORTLTR NPY_USHORTLTR -#define PyArray_INTLTR NPY_INTLTR -#define PyArray_UINTLTR NPY_UINTLTR -#define PyArray_LONGLTR NPY_LONGLTR -#define PyArray_ULONGLTR NPY_ULONGLTR -#define PyArray_LONGLONGLTR NPY_LONGLONGLTR -#define PyArray_ULONGLONGLTR NPY_ULONGLONGLTR -#define PyArray_FLOATLTR NPY_FLOATLTR -#define PyArray_DOUBLELTR NPY_DOUBLELTR -#define PyArray_LONGDOUBLELTR NPY_LONGDOUBLELTR -#define PyArray_CFLOATLTR NPY_CFLOATLTR -#define PyArray_CDOUBLELTR NPY_CDOUBLELTR -#define PyArray_CLONGDOUBLELTR NPY_CLONGDOUBLELTR -#define PyArray_OBJECTLTR NPY_OBJECTLTR -#define PyArray_STRINGLTR NPY_STRINGLTR -#define PyArray_STRINGLTR2 NPY_STRINGLTR2 -#define PyArray_UNICODELTR NPY_UNICODELTR -#define PyArray_VOIDLTR NPY_VOIDLTR -#define PyArray_CHARLTR NPY_CHARLTR -#define PyArray_INTPLTR NPY_INTPLTR -#define PyArray_UINTPLTR NPY_UINTPLTR -#define PyArray_GENBOOLLTR NPY_GENBOOLLTR -#define PyArray_SIGNEDLTR NPY_SIGNEDLTR -#define PyArray_UNSIGNEDLTR NPY_UNSIGNEDLTR -#define PyArray_FLOATINGLTR NPY_FLOATINGLTR -#define PyArray_COMPLEXLTR NPY_COMPLEXLTR +#define PyArray_BOOLLTR NPY_BOOLLTR +#define PyArray_BYTELTR NPY_BYTELTR +#define PyArray_UBYTELTR NPY_UBYTELTR +#define PyArray_SHORTLTR NPY_SHORTLTR +#define PyArray_USHORTLTR NPY_USHORTLTR +#define PyArray_INTLTR NPY_INTLTR +#define PyArray_UINTLTR NPY_UINTLTR +#define PyArray_LONGLTR NPY_LONGLTR +#define PyArray_ULONGLTR NPY_ULONGLTR +#define PyArray_LONGLONGLTR NPY_LONGLONGLTR +#define PyArray_ULONGLONGLTR NPY_ULONGLONGLTR +#define PyArray_FLOATLTR NPY_FLOATLTR +#define PyArray_DOUBLELTR NPY_DOUBLELTR +#define PyArray_LONGDOUBLELTR NPY_LONGDOUBLELTR +#define PyArray_CFLOATLTR NPY_CFLOATLTR +#define PyArray_CDOUBLELTR NPY_CDOUBLELTR +#define PyArray_CLONGDOUBLELTR NPY_CLONGDOUBLELTR +#define PyArray_OBJECTLTR NPY_OBJECTLTR +#define PyArray_STRINGLTR NPY_STRINGLTR +#define PyArray_STRINGLTR2 NPY_STRINGLTR2 +#define PyArray_UNICODELTR NPY_UNICODELTR +#define PyArray_VOIDLTR NPY_VOIDLTR +#define PyArray_CHARLTR NPY_CHARLTR +#define PyArray_INTPLTR NPY_INTPLTR +#define PyArray_UINTPLTR NPY_UINTPLTR +#define PyArray_GENBOOLLTR NPY_GENBOOLLTR +#define PyArray_SIGNEDLTR NPY_SIGNEDLTR +#define PyArray_UNSIGNEDLTR NPY_UNSIGNEDLTR +#define PyArray_FLOATINGLTR NPY_FLOATINGLTR +#define PyArray_COMPLEXLTR NPY_COMPLEXLTR #define PyArray_QUICKSORT NPY_QUICKSORT #define PyArray_HEAPSORT NPY_HEAPSORT @@ -123,35 +123,35 @@ #define PyArray_SORTKIND NPY_SORTKIND #define PyArray_NSORTS NPY_NSORTS -#define PyArray_NOSCALAR NPY_NOSCALAR -#define PyArray_BOOL_SCALAR NPY_BOOL_SCALAR -#define PyArray_INTPOS_SCALAR NPY_INTPOS_SCALAR -#define PyArray_INTNEG_SCALAR NPY_INTNEG_SCALAR -#define PyArray_FLOAT_SCALAR NPY_FLOAT_SCALAR -#define PyArray_COMPLEX_SCALAR NPY_COMPLEX_SCALAR -#define PyArray_OBJECT_SCALAR NPY_OBJECT_SCALAR -#define PyArray_SCALARKIND NPY_SCALARKIND -#define PyArray_NSCALARKINDS NPY_NSCALARKINDS +#define PyArray_NOSCALAR NPY_NOSCALAR +#define PyArray_BOOL_SCALAR NPY_BOOL_SCALAR +#define PyArray_INTPOS_SCALAR NPY_INTPOS_SCALAR +#define PyArray_INTNEG_SCALAR NPY_INTNEG_SCALAR +#define PyArray_FLOAT_SCALAR NPY_FLOAT_SCALAR +#define PyArray_COMPLEX_SCALAR NPY_COMPLEX_SCALAR +#define PyArray_OBJECT_SCALAR NPY_OBJECT_SCALAR +#define PyArray_SCALARKIND NPY_SCALARKIND +#define PyArray_NSCALARKINDS NPY_NSCALARKINDS -#define PyArray_ANYORDER NPY_ANYORDER +#define PyArray_ANYORDER NPY_ANYORDER #define PyArray_CORDER NPY_CORDER -#define PyArray_FORTRANORDER NPY_FORTRANORDER -#define PyArray_ORDER NPY_ORDER +#define PyArray_FORTRANORDER NPY_FORTRANORDER +#define PyArray_ORDER NPY_ORDER -#define PyDescr_ISBOOL PyDataType_ISBOOL -#define PyDescr_ISUNSIGNED PyDataType_ISUNSIGNED -#define PyDescr_ISSIGNED PyDataType_ISSIGNED -#define PyDescr_ISINTEGER PyDataType_ISINTEGER -#define PyDescr_ISFLOAT PyDataType_ISFLOAT -#define PyDescr_ISNUMBER PyDataType_ISNUMBER -#define PyDescr_ISSTRING PyDataType_ISSTRING -#define PyDescr_ISCOMPLEX PyDataType_ISCOMPLEX -#define PyDescr_ISPYTHON PyDataType_ISPYTHON -#define PyDescr_ISFLEXIBLE PyDataType_ISFLEXIBLE -#define PyDescr_ISUSERDEF PyDataType_ISUSERDEF -#define PyDescr_ISEXTENDED PyDataType_ISEXTENDED -#define PyDescr_ISOBJECT PyDataType_ISOBJECT -#define PyDescr_HASFIELDS PyDataType_HASFIELDS +#define PyDescr_ISBOOL PyDataType_ISBOOL +#define PyDescr_ISUNSIGNED PyDataType_ISUNSIGNED +#define PyDescr_ISSIGNED PyDataType_ISSIGNED +#define PyDescr_ISINTEGER PyDataType_ISINTEGER +#define PyDescr_ISFLOAT PyDataType_ISFLOAT +#define PyDescr_ISNUMBER PyDataType_ISNUMBER +#define PyDescr_ISSTRING PyDataType_ISSTRING +#define PyDescr_ISCOMPLEX PyDataType_ISCOMPLEX +#define PyDescr_ISPYTHON PyDataType_ISPYTHON +#define PyDescr_ISFLEXIBLE PyDataType_ISFLEXIBLE +#define PyDescr_ISUSERDEF PyDataType_ISUSERDEF +#define PyDescr_ISEXTENDED PyDataType_ISEXTENDED +#define PyDescr_ISOBJECT PyDataType_ISOBJECT +#define PyDescr_HASFIELDS PyDataType_HASFIELDS #define PyArray_LITTLE NPY_LITTLE #define PyArray_BIG NPY_BIG @@ -163,6 +163,6 @@ #define PyArray_OPPBYTE NPY_OPPBYTE #define NPY_REFCOUNT PyArray_REFCOUNT -#define PyArray_MAX_ELSIZE NPY_MAX_ELSIZE +#define PyArray_MAX_ELSIZE NPY_MAX_ELSIZE #define PyArray_USE_PYMEM NPY_USE_PYMEM Modified: trunk/numpy/core/include/numpy/oldnumeric.h =================================================================== --- trunk/numpy/core/include/numpy/oldnumeric.h 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/include/numpy/oldnumeric.h 2006-08-19 06:01:10 UTC (rev 3040) @@ -16,7 +16,3 @@ #define OWN_DATA NPY_OWNDATA #define SAVESPACE 0 #define SAVESPACEBIT 0 - - - - Modified: trunk/numpy/core/include/numpy/ufuncobject.h =================================================================== --- trunk/numpy/core/include/numpy/ufuncobject.h 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/include/numpy/ufuncobject.h 2006-08-19 06:01:10 UTC (rev 3040) @@ -38,7 +38,7 @@ #define UFUNC_SHIFT_DIVIDEBYZERO 0 #define UFUNC_SHIFT_OVERFLOW 2 #define UFUNC_SHIFT_UNDERFLOW 4 -#define UFUNC_SHIFT_INVALID 6 +#define UFUNC_SHIFT_INVALID 6 /* platform-dependent code translates floating point @@ -48,28 +48,28 @@ #define UFUNC_FPE_OVERFLOW 2 #define UFUNC_FPE_UNDERFLOW 4 #define UFUNC_FPE_INVALID 8 - + #define UFUNC_ERR_DEFAULT 0 /* Default error mode */ /* Only internal -- not exported, yet*/ typedef struct { - /* Multi-iterator portion --- needs to be present in this order + /* Multi-iterator portion --- needs to be present in this order to work with PyArray_Broadcast */ PyObject_HEAD int numiter; npy_intp size; npy_intp index; int nd; - npy_intp dimensions[NPY_MAXDIMS]; + npy_intp dimensions[NPY_MAXDIMS]; PyArrayIterObject *iters[NPY_MAXARGS]; /* End of Multi-iterator portion */ /* The ufunc */ PyUFuncObject *ufunc; - + /* The error handling */ int errormask; /* Integer showing desired error handling */ - PyObject *errobj; /* currently a tuple with + PyObject *errobj; /* currently a tuple with (string, func or None) */ @@ -85,7 +85,7 @@ int leftover; int ninnerloops; int lastdim; - + /* Whether or not to swap */ int swap[NPY_MAXARGS]; @@ -102,16 +102,16 @@ /* usually points to buffer but when a cast is to be done it switches for that argument to castbuf. */ - char *bufptr[NPY_MAXARGS]; + char *bufptr[NPY_MAXARGS]; /* Steps filled in from iters or sizeof(item) - depending on loop method. + depending on loop method. */ npy_intp steps[NPY_MAXARGS]; int obj; /* This loop uses object arrays */ - int notimplemented; /* The loop caused notimplemented */ - int objfunc; /* This loop calls object functions + int notimplemented; /* The loop caused notimplemented */ + int objfunc; /* This loop calls object functions (an inner-loop function with argument types */ } PyUFuncLoopObject; @@ -218,9 +218,9 @@ | ((IEEE_STATUS_UNF & fpstatus) ? UFUNC_FPE_UNDERFLOW : 0) \ | ((IEEE_STATUS_INV & fpstatus) ? UFUNC_FPE_INVALID : 0); \ } - + /* MS Windows -----------------------------------------------------*/ -#elif defined(_MSC_VER) +#elif defined(_MSC_VER) #include @@ -237,11 +237,11 @@ #define isinf(x) ((_fpclass((double)(x)) == _FPCLASS_PINF) || \ (_fpclass((double)(x)) == _FPCLASS_NINF)) #define isfinite(x) (_finite((double) x)) - + /* Solaris --------------------------------------------------------*/ /* --------ignoring SunOS ieee_flags approach, someone else can ** deal with that! */ -#elif defined(sun) || defined(__BSD__) || defined(__OpenBSD__) +#elif defined(sun) || defined(__BSD__) || defined(__OpenBSD__) #include #define UFUNC_CHECK_STATUS(ret) { \ @@ -254,7 +254,7 @@ | ((FP_X_INV & fpstatus) ? UFUNC_FPE_INVALID : 0); \ (void) fpsetsticky(0); \ } - + #elif defined(linux) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__MINGW32__) #if defined(__GLIBC__) || defined(__APPLE__) || defined(__MINGW32__) @@ -276,7 +276,7 @@ #define generate_divbyzero_error() feraiseexcept(FE_DIVBYZERO) #define generate_overflow_error() feraiseexcept(FE_OVERFLOW) - + #elif defined(_AIX) #include @@ -298,7 +298,7 @@ #else -#define NO_FLOATING_POINT_SUPPORT +#define NO_FLOATING_POINT_SUPPORT #define UFUNC_CHECK_STATUS(ret) { \ ret = 0; \ } @@ -319,7 +319,7 @@ return; else /* should never be called */ numeric_zero2 += 1; - return; + return; } #endif Modified: trunk/numpy/core/numerictypes.py =================================================================== --- trunk/numpy/core/numerictypes.py 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/numerictypes.py 2006-08-19 06:01:10 UTC (rev 3040) @@ -374,11 +374,14 @@ return _python_type(rep) if isinstance(rep, ndarray): return rep.dtype.type - res = sctypeDict.get(rep, default) - return res + try: + res = dtype(rep) + except: + return default + return res.type -# This dictionary allows look up based on any alias for an array type +# This dictionary allows look up based on any alias for an array data-type class _typedict(dict): def __getitem__(self, obj): return dict.__getitem__(self, obj2sctype(obj)) Modified: trunk/numpy/core/src/_isnan.c =================================================================== --- trunk/numpy/core/src/_isnan.c 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/_isnan.c 2006-08-19 06:01:10 UTC (rev 3040) @@ -1,6 +1,6 @@ /* Adapted from cephes */ -static int +static int isnan(double x) { union @@ -9,7 +9,7 @@ unsigned short s[4]; unsigned int i[2]; } u; - + u.d = x; #if SIZEOF_INT == 4 @@ -39,9 +39,8 @@ return 1; } #endif - + #endif /* SIZEOF_INT */ - + return 0; } - Modified: trunk/numpy/core/src/_signbit.c =================================================================== --- trunk/numpy/core/src/_signbit.c 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/_signbit.c 2006-08-19 06:01:10 UTC (rev 3040) @@ -1,6 +1,6 @@ /* Adapted from cephes */ -static int +static int signbit(double x) { union @@ -9,7 +9,7 @@ short s[4]; int i[2]; } u; - + u.d = x; #if SIZEOF_INT == 4 @@ -27,6 +27,6 @@ #else return u.s[3] < 0; #endif - + #endif /* SIZEOF_INT */ } Modified: trunk/numpy/core/src/_sortmodule.c.src =================================================================== --- trunk/numpy/core/src/_sortmodule.c.src 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/_sortmodule.c.src 2006-08-19 06:01:10 UTC (rev 3040) @@ -2,12 +2,12 @@ /* The purpose of this module is to add faster sort functions that are type-specific. This is done by altering the - function table for the builtin descriptors. + function table for the builtin descriptors. - These sorting functions are copied almost directly from numarray - with a few modifications (complex comparisons compare the imaginary + These sorting functions are copied almost directly from numarray + with a few modifications (complex comparisons compare the imaginary part if the real parts are equal, for example), and the names - are changed. + are changed. The original sorting code is due to Charles R. Harris who wrote it for numarray. @@ -15,13 +15,13 @@ /* Quick sort is usually the fastest, but the worst case scenario can be slower than the merge and heap sorts. The merge sort requires - extra memory and so for large arrays may not be useful. - + extra memory and so for large arrays may not be useful. + The merge sort is *stable*, meaning that equal components are unmoved from their entry versions, so it can be used to - implement lexigraphic sorting on multiple keys. + implement lexigraphic sorting on multiple keys. - The heap sort is included for completeness. + The heap sort is included for completeness. */ @@ -159,7 +159,7 @@ static int @TYPE at _heapsort(@type@ *start, intp n, void *unused) { - + @type@ tmp, *a; intp i,j,l; @@ -287,7 +287,7 @@ pl = start; pr = pl + num - 1; pw = (@type@ *) PyDataMem_NEW(((1+num/2))*sizeof(@type@)); - + if (!pw) { PyErr_NoMemory(); return -1; @@ -298,7 +298,7 @@ return 0; } -static void +static void @TYPE at _amergesort0(intp *pl, intp *pr, @type@ *v, intp *pw) { @type@ vp; @@ -345,7 +345,7 @@ pl = tosort; pr = pl + num - 1; pw = PyDimMem_NEW((1+num/2)); - + if (!pw) { PyErr_NoMemory(); return -1; @@ -362,7 +362,7 @@ #comp=strncmp,PyArray_CompareUCS4# #type=char *, PyArray_UCS4 *# */ -static void +static void @TYPE at _amergesort0(intp *pl, intp *pr, @type@*v, intp *pw, int elsize) { @type@ vp; @@ -413,7 +413,7 @@ pl = tosort; pr = pl + num - 1; pw = PyDimMem_NEW((1+num/2)); - + if (!pw) { PyErr_NoMemory(); return -1; @@ -424,8 +424,8 @@ return 0; } /**end repeat**/ - -static void + +static void add_sortfuncs(void) { PyArray_Descr *descr; @@ -465,7 +465,7 @@ PyObject *m; m = Py_InitModule("_sort", methods); - + import_array(); add_sortfuncs(); } Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/arraymethods.c 2006-08-19 06:01:10 UTC (rev 3040) @@ -6,16 +6,16 @@ "in indices from array a along the given axis."; static PyObject * -array_take(PyArrayObject *self, PyObject *args, PyObject *kwds) +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}; - + dimension=0; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O&", kwlist, + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&O&", kwlist, &indices, PyArray_AxisConverter, &dimension, PyArray_OutputConverter, @@ -23,7 +23,7 @@ PyArray_ClipmodeConverter, &mode)) return NULL; - + return _ARET(PyArray_TakeFrom(self, indices, dimension, out, mode)); } @@ -46,12 +46,12 @@ "will repeat."; static PyObject * -array_put(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_put(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *indices, *values; NPY_CLIPMODE mode=NPY_RAISE; static char *kwlist[] = {"values", "indices", "mode", NULL}; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist, &values, &indices, PyArray_ClipmodeConverter, @@ -64,12 +64,12 @@ "for each n where mask.flat[n] is TRUE. v can be scalar."; static PyObject * -array_putmask(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_putmask(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *mask, *values; static char *kwlist[] = {"values", "mask", NULL}; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, &values, &mask)) return NULL; @@ -77,20 +77,20 @@ } static char doc_reshape[] = \ - "self.reshape(d1, d2, ..., dn, order='C') \n" - "Return a new array from this one. \n" - "\n The new array must have the same number of elements as self. " + "self.reshape(d1, d2, ..., dn, order='C') \n" + "Return a new array from this one. \n" + "\n The new array must have the same number of elements as self. " "Also\n always returns a view or raises a ValueError if that is \n" "impossible."; static PyObject * -array_reshape(PyArrayObject *self, PyObject *args, PyObject *kwds) +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"); @@ -101,15 +101,15 @@ n = PyTuple_Size(args); if (n <= 1) { - if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter, + if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter, &newshape)) return NULL; } else { if (!PyArray_IntpConverter(args, &newshape)) { if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "invalid shape"); - } + } goto fail; } } @@ -143,13 +143,13 @@ if (otype) { if (PyType_Check(otype) && \ - PyType_IsSubtype((PyTypeObject *)otype, + PyType_IsSubtype((PyTypeObject *)otype, &PyArray_Type)) { - return PyArray_View(self, NULL, + return PyArray_View(self, NULL, (PyTypeObject *)otype); } else { - if (PyArray_DescrConverter(otype, &type) == PY_FAIL) + if (PyArray_DescrConverter(otype, &type) == PY_FAIL) return NULL; } } @@ -159,76 +159,76 @@ static char doc_argmax[] = "a.argmax(axis=None, out=None)"; static PyObject * -array_argmax(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_argmax(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArrayObject *out=NULL; static char *kwlist[] = {"axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) - return NULL; - + return NULL; + return _ARET(PyArray_ArgMax(self, axis, out)); } static char doc_argmin[] = "a.argmin(axis=None, out=None)"; static PyObject * -array_argmin(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_argmin(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArrayObject *out=NULL; static char *kwlist[] = {"axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) - return NULL; - + return NULL; + return _ARET(PyArray_ArgMin(self, axis, out)); } static char doc_max[] = "a.max(axis=None)"; static PyObject * -array_max(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_max(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArrayObject *out=NULL; static char *kwlist[] = {"axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) - return NULL; - + return NULL; + return PyArray_Max(self, axis, out); } static char doc_ptp[] = "a.ptp(axis=None) a.max(axis)-a.min(axis)"; static PyObject * -array_ptp(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_ptp(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArrayObject *out=NULL; static char *kwlist[] = {"axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) - return NULL; - + return NULL; + return PyArray_Ptp(self, axis, out); } @@ -236,19 +236,19 @@ static char doc_min[] = "a.min(axis=None)"; static PyObject * -array_min(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_min(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArrayObject *out=NULL; static char *kwlist[] = {"axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) - return NULL; - + return NULL; + return PyArray_Min(self, axis, out); } @@ -286,15 +286,15 @@ Py_DECREF(typed); return NULL; } - ret = PyArray_NewFromDescr(self->ob_type, + ret = PyArray_NewFromDescr(self->ob_type, typed, self->nd, self->dimensions, - self->strides, + self->strides, self->data + offset, self->flags, (PyObject *)self); if (ret == NULL) return NULL; Py_INCREF(self); - ((PyArrayObject *)ret)->base = (PyObject *)self; + ((PyArrayObject *)ret)->base = (PyObject *)self; PyArray_UpdateFlags((PyArrayObject *)ret, UPDATE_ALL); return ret; @@ -307,11 +307,11 @@ 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; - + return _ARET(PyArray_GetField(self, dtype, offset)); } @@ -328,7 +328,7 @@ { 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 " \ @@ -337,7 +337,7 @@ Py_DECREF(dtype); return -1; } - ret = PyArray_NewFromDescr(self->ob_type, + ret = PyArray_NewFromDescr(self->ob_type, dtype, self->nd, self->dimensions, self->strides, self->data + offset, self->flags, (PyObject *)self); @@ -345,7 +345,7 @@ Py_INCREF(self); ((PyArrayObject *)ret)->base = (PyObject *)self; - PyArray_UpdateFlags((PyArrayObject *)ret, UPDATE_ALL); + PyArray_UpdateFlags((PyArrayObject *)ret, UPDATE_ALL); retval = PyArray_CopyObject((PyArrayObject *)ret, val); Py_DECREF(ret); return retval; @@ -358,7 +358,7 @@ 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; @@ -406,13 +406,13 @@ } Py_DECREF(it); } - + Py_INCREF(self); return (PyObject *)self; } else { PyObject *new; - if ((ret = (PyArrayObject *)PyArray_NewCopy(self,-1)) == NULL) + if ((ret = (PyArrayObject *)PyArray_NewCopy(self,-1)) == NULL) return NULL; new = PyArray_Byteswap(ret, TRUE); Py_DECREF(new); @@ -425,13 +425,13 @@ " is TRUE, byteswap in-place and return a reference to self."; static PyObject * -array_byteswap(PyArrayObject *self, PyObject *args) +array_byteswap(PyArrayObject *self, PyObject *args) { Bool inplace=FALSE; - + if (!PyArg_ParseTuple(args, "|O&", PyArray_BoolConverter, &inplace)) return NULL; - + return PyArray_Byteswap(self, inplace); } @@ -439,9 +439,9 @@ " to a hierarchical python list and return that list."; static PyObject * -array_tolist(PyArrayObject *self, PyObject *args) +array_tolist(PyArrayObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, "")) return NULL; + if (!PyArg_ParseTuple(args, "")) return NULL; return PyArray_ToList(self); } @@ -453,7 +453,7 @@ { NPY_ORDER order=NPY_CORDER; static char *kwlist[] = {"order", NULL}; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&", kwlist, PyArray_OrderConverter, &order)) return NULL; @@ -471,8 +471,8 @@ char *sep=""; char *format=""; static char *kwlist[] = {"file", "sep", "format", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ss", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ss", kwlist, &file, &sep, &format)) return NULL; if (PyString_Check(file) || PyUnicode_Check(file)) { @@ -503,7 +503,7 @@ static PyObject * array_toscalar(PyArrayObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, "")) return NULL; - if (self->nd == 0 || PyArray_SIZE(self) == 1) + 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" \ @@ -517,14 +517,14 @@ " object of type int, float, or complex."; static PyObject * -array_cast(PyArrayObject *self, PyObject *args) +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,0)); Py_XDECREF(descr); @@ -534,7 +534,7 @@ return PyArray_FromArray(self, descr, NPY_FORCECAST); } return _ARET(PyArray_CastToType(self, descr, 0)); -} +} /* default sub-type implementation */ @@ -546,7 +546,7 @@ { PyObject *arr; PyObject *ret; - + if (PyTuple_Size(args) < 1) { PyErr_SetString(PyExc_TypeError, "only accepts 1 argument"); @@ -557,13 +557,13 @@ PyErr_SetString(PyExc_TypeError, "can only be called with ndarray object"); return NULL; - } + } Py_INCREF(PyArray_DESCR(arr)); - ret = PyArray_NewFromDescr(self->ob_type, + ret = PyArray_NewFromDescr(self->ob_type, PyArray_DESCR(arr), PyArray_NDIM(arr), - PyArray_DIMS(arr), + PyArray_DIMS(arr), PyArray_STRIDES(arr), PyArray_DATA(arr), PyArray_FLAGS(arr), (PyObject *)self); if (ret == NULL) return NULL; @@ -576,14 +576,14 @@ static char doc_array_getarray[] = "m.__array__(|dtype) just returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array."; static PyObject * -array_getarray(PyArrayObject *self, PyObject *args) +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; @@ -592,13 +592,13 @@ if (!PyType_IsSubtype(self->ob_type, &PyArray_Type)) { subtype = &PyArray_Type; } - + Py_INCREF(PyArray_DESCR(self)); - new = PyArray_NewFromDescr(subtype, + new = PyArray_NewFromDescr(subtype, PyArray_DESCR(self), PyArray_NDIM(self), - PyArray_DIMS(self), - PyArray_STRIDES(self), + PyArray_DIMS(self), + PyArray_STRIDES(self), PyArray_DATA(self), PyArray_FLAGS(self), NULL); if (new == NULL) return NULL; @@ -609,7 +609,7 @@ else { Py_INCREF(self); } - + if ((newtype == NULL) || \ PyArray_EquivTypes(self->descr, newtype)) { return (PyObject *)self; @@ -628,12 +628,12 @@ "only if m is already in fortran order."; static PyObject * -array_copy(PyArrayObject *self, PyObject *args) +array_copy(PyArrayObject *self, PyObject *args) { PyArray_ORDER fortran=PyArray_CORDER; if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter, &fortran)) return NULL; - + return PyArray_NewCopy(self, fortran); } @@ -643,14 +643,14 @@ "arrays\n Returns None."; static PyObject * -array_resize(PyArrayObject *self, PyObject *args, PyObject *kwds) +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"); @@ -661,24 +661,24 @@ } } ref = PyDict_GetItemString(kwds, "order"); - if (ref != NULL || + if (ref != NULL || (PyArray_OrderConverter(ref, &fortran) == PY_FAIL)) return NULL; } n = PyTuple_Size(args); if (n <= 1) { - if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter, + if (!PyArg_ParseTuple(args, "O&", PyArray_IntpConverter, &newshape)) return NULL; } else { if (!PyArray_IntpConverter(args, &newshape)) { if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "invalid shape"); - } - return NULL; + } + return NULL; } - } + } ret = PyArray_Resize(self, &newshape, refcheck, fortran); PyDimMem_FREE(newshape.ptr); if (ret == NULL) return NULL; @@ -697,11 +697,11 @@ PyObject *repeats; int axis=MAX_DIMS; static char *kwlist[] = {"repeats", "axis", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist, &repeats, PyArray_AxisConverter, &axis)) return NULL; - + return _ARET(PyArray_Repeat(self, repeats, axis)); } @@ -714,13 +714,13 @@ "an integer array with entries from 0 to n+1."; static PyObject * -array_choose(PyArrayObject *self, PyObject *args, PyObject *kwds) +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)) @@ -730,33 +730,33 @@ choices = args; } if (kwds && PyDict_Check(kwds)) { - if (PyArray_OutputConverter(PyDict_GetItemString(kwds, + if (PyArray_OutputConverter(PyDict_GetItemString(kwds, "out"), &out) == PY_FAIL) return NULL; - if (PyArray_ClipmodeConverter(PyDict_GetItemString(kwds, - "mode"), + if (PyArray_ClipmodeConverter(PyDict_GetItemString(kwds, + "mode"), &clipmode) == PY_FAIL) return NULL; } - + return _ARET(PyArray_Choose(self, choices, out, clipmode)); } static char doc_sort[] = "a.sort(axis=-1,kind='quicksort') sorts in place along axis. Return is None and kind can be 'quicksort', 'mergesort', or 'heapsort'"; static PyObject * -array_sort(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_sort(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=-1; int val; PyArray_SORTKIND which=PyArray_QUICKSORT; static char *kwlist[] = {"axis", "kind", NULL}; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&", kwlist, &axis, PyArray_SortkindConverter, &which)) return NULL; - + val = PyArray_Sort(self, axis, which); if (val < 0) return NULL; Py_INCREF(Py_None); @@ -768,16 +768,16 @@ " given axis; kind can be 'quicksort', 'mergesort', or 'heapsort'"; static PyObject * -array_argsort(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_argsort(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=-1; PyArray_SORTKIND which=PyArray_QUICKSORT; static char *kwlist[] = {"axis", "kind", NULL}; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO&", kwlist, &axis, PyArray_SortkindConverter, &which)) return NULL; - + return _ARET(PyArray_ArgSort(self, axis, which)); } @@ -790,12 +790,12 @@ " in ascending order."; static PyObject * -array_searchsorted(PyArrayObject *self, PyObject *args) +array_searchsorted(PyArrayObject *self, PyObject *args) { PyObject *values; - + if (!PyArg_ParseTuple(args, "O", &values)) return NULL; - + return _ARET(PyArray_SearchSorted(self, values)); } @@ -811,7 +811,7 @@ otemp = (PyObject **)optr; Py_XINCREF(*itemp); /* call deepcopy on this argument */ - res = PyObject_CallFunctionObjArgs(deepcopy, + res = PyObject_CallFunctionObjArgs(deepcopy, *itemp, visit, NULL); Py_XDECREF(*itemp); Py_XDECREF(*otemp); @@ -822,7 +822,7 @@ PyArray_Descr *new; int offset, pos=0; while (PyDict_Next(dtype->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) return; _deepcopy_call(iptr + offset, optr + offset, new, deepcopy, visit); @@ -833,7 +833,7 @@ static char doc_deepcopy[] = "Used if copy.deepcopy is called on an array."; static PyObject * -array_deepcopy(PyArrayObject *self, PyObject *args) +array_deepcopy(PyArrayObject *self, PyObject *args) { PyObject* visit; char *optr; @@ -929,15 +929,15 @@ obj = PyObject_GetAttrString(mod, "_reconstruct"); Py_DECREF(mod); PyTuple_SET_ITEM(ret, 0, obj); - PyTuple_SET_ITEM(ret, 1, + 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 + + /* Now fill in object's state. This is a tuple with 5 arguments 1) an integer with the pickle version. @@ -947,7 +947,7 @@ 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 + Notice because Python does not describe a mechanism to write raw data to the pickle, this performs a copy to a string first */ @@ -956,7 +956,7 @@ Py_DECREF(ret); return NULL; } PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version)); - PyTuple_SET_ITEM(state, 1, PyObject_GetAttrString((PyObject *)self, + PyTuple_SET_ITEM(state, 1, PyObject_GetAttrString((PyObject *)self, "shape")); descr = self->descr; Py_INCREF(descr); @@ -986,12 +986,12 @@ 1) a Tuple giving the shape 2) a PyArray_Descr Object 3) a Bool stating if Fortran or not - 4) a binary string with the data (or a list if Object array) + 4) a binary string with the data (or a list if Object array) */ static size_t _array_fill_strides(intp *, intp *, int, size_t, int, int *); -static int _IsAligned(PyArrayObject *); +static int _IsAligned(PyArrayObject *); static PyArray_Descr * _array_typedescr_fromstr(char *); @@ -1007,7 +1007,7 @@ int 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. */ @@ -1017,7 +1017,7 @@ PyErr_Clear(); version = 0; if (!PyArg_ParseTuple(args, "(O!O!iO)", &PyTuple_Type, - &shape, &PyArrayDescr_Type, &typecode, + &shape, &PyArrayDescr_Type, &typecode, &fortran, &rawdata)) { return NULL; } @@ -1050,14 +1050,14 @@ if (typecode->hasobject || typecode->f->listpickle) { if (!PyList_Check(rawdata)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "object pickle not returning list"); return NULL; } } else { if (!PyString_Check(rawdata)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "pickle not returning string"); return NULL; } @@ -1066,7 +1066,7 @@ return NULL; if ((len != (self->descr->elsize * size))) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "buffer size does not" \ " match array size"); return NULL; @@ -1083,7 +1083,7 @@ self->flags &= ~UPDATEIFCOPY; if (self->dimensions != NULL) { - PyDimMem_FREE(self->dimensions); + PyDimMem_FREE(self->dimensions); self->dimensions = NULL; } @@ -1096,7 +1096,7 @@ 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, + (size_t) self->descr->elsize, (fortran ? FORTRAN : CONTIGUOUS), &(self->flags)); } @@ -1122,7 +1122,7 @@ } else { self->descr = PyArray_DescrNew(typecode); - if (self->descr->byteorder == PyArray_BIG) + if (self->descr->byteorder == PyArray_BIG) self->descr->byteorder = PyArray_LITTLE; else if (self->descr->byteorder == PyArray_LITTLE) self->descr->byteorder = PyArray_BIG; @@ -1142,7 +1142,7 @@ } else { self->data = PyDataMem_NEW(PyArray_NBYTES(self)); - if (self->data == NULL) { + if (self->data == NULL) { self->nd = 0; self->data = PyDataMem_NEW(self->descr->elsize); if (self->dimensions) PyDimMem_FREE(self->dimensions); @@ -1151,14 +1151,14 @@ if (self->descr->hasobject) memset(self->data, 0, PyArray_NBYTES(self)); self->flags |= OWNDATA; self->base = NULL; - if (_setlist_pkl(self, rawdata) < 0) + if (_setlist_pkl(self, rawdata) < 0) return NULL; } PyArray_UpdateFlags(self, UPDATE_ALL); - + Py_INCREF(Py_None); - return Py_None; + return Py_None; } /*OBJECT_API*/ @@ -1177,7 +1177,7 @@ if (file==NULL) return -1; } else Py_INCREF(file); - ret = PyObject_CallMethod(cpick, "dump", "OOi", self, + ret = PyObject_CallMethod(cpick, "dump", "OOi", self, file, protocol); Py_XDECREF(ret); Py_DECREF(file); @@ -1251,7 +1251,7 @@ ; static PyObject * -array_transpose(PyArrayObject *self, PyObject *args) +array_transpose(PyArrayObject *self, PyObject *args) { PyObject *shape=Py_None; int n; @@ -1261,7 +1261,7 @@ 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 { @@ -1269,7 +1269,7 @@ ret = PyArray_Transpose(self, &permute); PyDimMem_FREE(permute.ptr); } - + return _ARET(ret); } @@ -1289,15 +1289,15 @@ #define _CHKTYPENUM(typ) ((typ) ? (typ)->type_num : PyArray_NOTYPE) static PyObject * -array_mean(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_mean(PyArrayObject *self, PyObject *args, PyObject *kwds) { 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, + PyArray_AxisConverter, &axis, PyArray_DescrConverter2, &dtype, PyArray_OutputConverter, @@ -1331,20 +1331,20 @@ "array([1, 5])"; static PyObject * -array_sum(PyArrayObject *self, PyObject *args, PyObject *kwds) +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}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, - PyArray_AxisConverter, + 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); } @@ -1352,40 +1352,40 @@ static char doc_cumsum[] = "a.cumsum(axis=None, dtype=None, out=None)"; static PyObject * -array_cumsum(PyArrayObject *self, PyObject *args, PyObject *kwds) +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}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, - PyArray_AxisConverter, + + 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); } static char doc_prod[] = "a.prod(axis=None, dtype=None)"; static PyObject * -array_prod(PyArrayObject *self, PyObject *args, PyObject *kwds) +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}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, - PyArray_AxisConverter, + + 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); } @@ -1393,20 +1393,20 @@ static char doc_cumprod[] = "a.cumprod(axis=None, dtype=None)"; static PyObject * -array_cumprod(PyArrayObject *self, PyObject *args, PyObject *kwds) +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}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, - PyArray_AxisConverter, + + 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); } @@ -1414,37 +1414,37 @@ static char doc_any[] = "a.any(axis=None, out=None)"; static PyObject * -array_any(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_any(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArrayObject *out=NULL; static char *kwlist[] = {"axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) - return NULL; - + return NULL; + return PyArray_Any(self, axis, out); } static char doc_all[] = "a.all(axis=None)"; static PyObject * -array_all(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_all(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; PyArrayObject *out=NULL; static char *kwlist[] = {"axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&", kwlist, PyArray_AxisConverter, &axis, PyArray_OutputConverter, &out)) - return NULL; + return NULL; return PyArray_All(self, axis, out); } @@ -1458,54 +1458,54 @@ "For multidimensional arrays, std is computed by default along the first axis.\n"; static PyObject * -array_stddev(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_stddev(PyArrayObject *self, PyObject *args, PyObject *kwds) { 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, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, + PyArray_AxisConverter, &axis, PyArray_DescrConverter2, &dtype, PyArray_OutputConverter, &out)) return NULL; - + return PyArray_Std(self, axis, _CHKTYPENUM(dtype), out, 0); } static char doc_variance[] = "a.var(axis=None, dtype=None)"; static PyObject * -array_variance(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_variance(PyArrayObject *self, PyObject *args, PyObject *kwds) { 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, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&O&O&", kwlist, + PyArray_AxisConverter, &axis, PyArray_DescrConverter2, &dtype, PyArray_OutputConverter, &out)) return NULL; - + return PyArray_Std(self, axis, _CHKTYPENUM(dtype), out, 1); } static char doc_compress[] = "a.compress(condition=, axis=None, out=None)"; static PyObject * -array_compress(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_compress(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis=MAX_DIMS; - PyObject *condition; + PyObject *condition; PyArrayObject *out=NULL; static char *kwlist[] = {"condition", "axis", "out", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&", kwlist, &condition, PyArray_AxisConverter, &axis, PyArray_OutputConverter, @@ -1539,20 +1539,20 @@ "axis1 and axis2."; static PyObject * -array_trace(PyArrayObject *self, PyObject *args, PyObject *kwds) +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}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiiO&O&", kwlist, + + 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, + + return _ARET(PyArray_Trace(self, offset, axis1, axis2, _CHKTYPENUM(dtype), out)); } @@ -1562,18 +1562,18 @@ static char doc_clip[] = "a.clip(min=, max=, out=None)"; static PyObject * -array_clip(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_clip(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *min, *max; PyArrayObject *out=NULL; static char *kwlist[] = {"min", "max", "out", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O&", kwlist, - &min, &max, + &min, &max, PyArray_OutputConverter, - &out)) + &out)) return NULL; - + return _ARET(PyArray_Clip(self, min, max, out)); } @@ -1582,14 +1582,14 @@ static char doc_conjugate[] = "a.conjugate()"; static PyObject * -array_conjugate(PyArrayObject *self, PyObject *args) +array_conjugate(PyArrayObject *self, PyObject *args) { PyArrayObject *out=NULL; if (!PyArg_ParseTuple(args, "|O&", PyArray_OutputConverter, &out)) return NULL; - + return PyArray_Conjugate(self, out); } @@ -1597,15 +1597,15 @@ static char doc_diagonal[] = "a.diagonal(offset=0, axis1=0, axis2=1)"; static PyObject * -array_diagonal(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_diagonal(PyArrayObject *self, PyObject *args, PyObject *kwds) { int axis1=0, axis2=1, offset=0; static char *kwlist[] = {"offset", "axis1", "axis2", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iii", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iii", kwlist, &offset, &axis1, &axis2)) return NULL; - + return _ARET(PyArray_Diagonal(self, offset, axis1, axis2)); } @@ -1616,9 +1616,9 @@ { PyArray_ORDER fortran=PyArray_CORDER; - if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter, + if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter, &fortran)) return NULL; - + return PyArray_Flatten(self, fortran); } @@ -1628,8 +1628,8 @@ array_ravel(PyArrayObject *self, PyObject *args) { PyArray_ORDER fortran=PyArray_CORDER; - - if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter, + + if (!PyArg_ParseTuple(args, "|O&", PyArray_OrderConverter, &fortran)) return NULL; return PyArray_Ravel(self, fortran); @@ -1638,7 +1638,7 @@ static char doc_round[] = "a.round(decimals=0, out=None)"; static PyObject * -array_round(PyArrayObject *self, PyObject *args, PyObject *kwds) +array_round(PyArrayObject *self, PyObject *args, PyObject *kwds) { int decimals = 0; PyArrayObject *out=NULL; @@ -1648,7 +1648,7 @@ &decimals, PyArray_OutputConverter, &out)) return NULL; - + return _ARET(PyArray_Round(self, decimals, out)); } @@ -1666,7 +1666,7 @@ PyObject *align=Py_None; PyObject *uic=Py_None; int flagback = self->flags; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO", kwlist, &write, &align, &uic)) return NULL; @@ -1675,17 +1675,17 @@ if (PyObject_Not(align)) self->flags &= ~ALIGNED; else if (_IsAligned(self)) self->flags |= ALIGNED; else { - PyErr_SetString(PyExc_ValueError, + 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, + PyErr_SetString(PyExc_ValueError, "cannot set UPDATEIFCOPY" \ "flag to True"); return NULL; @@ -1696,15 +1696,15 @@ self->base = NULL; } } - + if (write != Py_None) { - if (PyObject_IsTrue(write)) + if (PyObject_IsTrue(write)) if (_IsWriteable(self)) { self->flags |= WRITEABLE; } else { self->flags = flagback; - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "cannot set WRITEABLE " \ "flag to True of this " \ "array"); \ @@ -1713,7 +1713,7 @@ else self->flags &= ~WRITEABLE; } - + Py_INCREF(Py_None); return Py_None; } @@ -1722,11 +1722,11 @@ " to a.view(a.dtype.newbytorder())\n"; static PyObject * -array_newbyteorder(PyArrayObject *self, PyObject *args) +array_newbyteorder(PyArrayObject *self, PyObject *args) { char endian = PyArray_SWAP; PyArray_Descr *new; - + if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter, &endian)) return NULL; @@ -1739,30 +1739,30 @@ static PyMethodDef array_methods[] = { {"tolist", (PyCFunction)array_tolist, 1, doc_tolist}, {"item", (PyCFunction)array_toscalar, METH_VARARGS, doc_toscalar}, - {"tofile", (PyCFunction)array_tofile, + {"tofile", (PyCFunction)array_tofile, METH_VARARGS | METH_KEYWORDS, doc_tofile}, - {"tostring", (PyCFunction)array_tostring, + {"tostring", (PyCFunction)array_tostring, METH_VARARGS | METH_KEYWORDS, doc_tostring}, {"byteswap", (PyCFunction)array_byteswap, 1, doc_byteswap}, {"astype", (PyCFunction)array_cast, 1, doc_cast}, - {"getfield", (PyCFunction)array_getfield, + {"getfield", (PyCFunction)array_getfield, METH_VARARGS | METH_KEYWORDS, doc_getfield}, - {"setfield", (PyCFunction)array_setfield, + {"setfield", (PyCFunction)array_setfield, METH_VARARGS | METH_KEYWORDS, doc_setfield}, - {"copy", (PyCFunction)array_copy, 1, doc_copy}, - {"resize", (PyCFunction)array_resize, - METH_VARARGS | METH_KEYWORDS, doc_resize}, + {"copy", (PyCFunction)array_copy, 1, doc_copy}, + {"resize", (PyCFunction)array_resize, + METH_VARARGS | METH_KEYWORDS, doc_resize}, /* for subtypes */ {"__array__", (PyCFunction)array_getarray, 1, doc_array_getarray}, {"__array_wrap__", (PyCFunction)array_wraparray, 1, doc_wraparray}, - + /* for the copy module */ - {"__copy__", (PyCFunction)array_copy, 1, doc_copy}, - {"__deepcopy__", (PyCFunction)array_deepcopy, 1, doc_deepcopy}, - + {"__copy__", (PyCFunction)array_copy, 1, doc_copy}, + {"__deepcopy__", (PyCFunction)array_deepcopy, 1, doc_deepcopy}, + /* for Pickling */ - {"__reduce__", (PyCFunction) array_reduce, 1, doc_reduce}, + {"__reduce__", (PyCFunction) array_reduce, 1, doc_reduce}, {"__setstate__", (PyCFunction) array_setstate, 1, doc_setstate}, {"dumps", (PyCFunction) array_dumps, 1, doc_dumps}, {"dump", (PyCFunction) array_dump, 1, doc_dump}, @@ -1770,33 +1770,33 @@ /* Extended methods added 2005 */ {"fill", (PyCFunction)array_fill, METH_VARARGS, doc_fill}, - {"transpose", (PyCFunction)array_transpose, + {"transpose", (PyCFunction)array_transpose, METH_VARARGS, doc_transpose}, - {"take", (PyCFunction)array_take, + {"take", (PyCFunction)array_take, METH_VARARGS|METH_KEYWORDS, doc_take}, - {"put", (PyCFunction)array_put, + {"put", (PyCFunction)array_put, METH_VARARGS|METH_KEYWORDS, doc_put}, - {"putmask", (PyCFunction)array_putmask, + {"putmask", (PyCFunction)array_putmask, METH_VARARGS|METH_KEYWORDS, doc_putmask}, - {"repeat", (PyCFunction)array_repeat, + {"repeat", (PyCFunction)array_repeat, METH_VARARGS|METH_KEYWORDS, doc_repeat}, - {"choose", (PyCFunction)array_choose, - METH_VARARGS|METH_KEYWORDS, doc_choose}, - {"sort", (PyCFunction)array_sort, + {"choose", (PyCFunction)array_choose, + METH_VARARGS|METH_KEYWORDS, doc_choose}, + {"sort", (PyCFunction)array_sort, METH_VARARGS|METH_KEYWORDS, doc_sort}, - {"argsort", (PyCFunction)array_argsort, + {"argsort", (PyCFunction)array_argsort, METH_VARARGS|METH_KEYWORDS, doc_argsort}, - {"searchsorted", (PyCFunction)array_searchsorted, - METH_VARARGS, doc_searchsorted}, - {"argmax", (PyCFunction)array_argmax, + {"searchsorted", (PyCFunction)array_searchsorted, + METH_VARARGS, doc_searchsorted}, + {"argmax", (PyCFunction)array_argmax, METH_VARARGS|METH_KEYWORDS, doc_argmax}, {"argmin", (PyCFunction)array_argmin, METH_VARARGS|METH_KEYWORDS, doc_argmin}, - {"reshape", (PyCFunction)array_reshape, + {"reshape", (PyCFunction)array_reshape, METH_VARARGS|METH_KEYWORDS, doc_reshape}, {"squeeze", (PyCFunction)array_squeeze, METH_VARARGS, doc_squeeze}, - {"view", (PyCFunction)array_view, + {"view", (PyCFunction)array_view, METH_VARARGS, doc_view}, {"swapaxes", (PyCFunction)array_swapaxes, METH_VARARGS, doc_swapaxes}, @@ -1852,5 +1852,3 @@ }; #undef _ARET - - Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/arrayobject.c 2006-08-19 06:01:10 UTC (rev 3040) @@ -164,7 +164,7 @@ PyArray_Descr *new; int offset, pos=0; while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) return; PyArray_Item_INCREF(data + offset, new); } @@ -191,7 +191,7 @@ PyArray_Descr *new; int offset, pos=0; while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) return; PyArray_Item_XDECREF(data + offset, new); } @@ -212,9 +212,9 @@ intp i, n; PyObject **data, **temp; PyArrayIterObject *it; - + if (mp->descr->hasobject == 0) return 0; - + if (mp->descr->type_num != PyArray_OBJECT) { it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp); if (it == NULL) return -1; @@ -265,7 +265,7 @@ PyArrayIterObject *it; if (mp->descr->hasobject == 0) return 0; - + if (mp->descr->type_num != PyArray_OBJECT) { it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp); if (it == NULL) return -1; @@ -304,7 +304,7 @@ } static void -_strided_byte_copy(char *dst, intp outstrides, char *src, intp instrides, +_strided_byte_copy(char *dst, intp outstrides, char *src, intp instrides, intp N, int elsize) { intp i, j; @@ -318,7 +318,7 @@ tout += outstrides; \ } \ return - + switch(elsize) { case 8: _FAST_MOVE(Float64); @@ -335,7 +335,7 @@ tin += instrides; tout += outstrides; } - return; + return; default: for (i=0; i 0) return mp->data; - + if (i>0 && i < dim0) { return mp->data+i*mp->strides[0]; } @@ -713,7 +713,7 @@ } static int -_copy_from0d(PyArrayObject *dest, PyArrayObject *src, int usecopy, int swap) +_copy_from0d(PyArrayObject *dest, PyArrayObject *src, int usecopy, int swap) { char *aligned=NULL; char *sptr; @@ -753,16 +753,16 @@ intp dstride; dptr = dest->data; - if (dest->nd == 1) + if (dest->nd == 1) dstride = dest->strides[0]; - else + else dstride = nbytes; PyArray_XDECREF(dest); - NPY_BEGIN_THREADS - + NPY_BEGIN_THREADS + myfunc(dptr, dstride, sptr, 0, numcopies, (int) nbytes); - if (swap) + if (swap) _strided_byte_swap(dptr, dstride, numcopies, (int) nbytes); NPY_END_THREADS @@ -776,30 +776,30 @@ PyArray_IterAllButAxis((PyObject *)dest, &axis); if (dit == NULL) goto finish; PyArray_XDECREF(dest); - NPY_BEGIN_THREADS + 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, + if (swap) + _strided_byte_swap(dit->dataptr, PyArray_STRIDE(dest, axis), PyArray_DIM(dest, axis), nbytes); PyArray_ITER_NEXT(dit); } - NPY_END_THREADS + NPY_END_THREADS PyArray_INCREF(dest); Py_DECREF(dit); } retval = 0; finish: if (aligned != NULL) free(aligned); - return retval; + return retval; } -/* Special-case of PyArray_CopyInto when dst is 1-d - and contiguous (and aligned). - PyArray_CopyInto requires broadcastable arrays while +/* 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) { @@ -810,14 +810,14 @@ int elsize; intp nbytes; NPY_BEGIN_THREADS_DEF - + if (PyArray_NDIM(src) == 0) { PyArray_XDECREF((PyArrayObject *)dst); - NPY_BEGIN_THREADS + NPY_BEGIN_THREADS memcpy(PyArray_BYTES(dst), PyArray_BYTES(src), PyArray_ITEMSIZE(src)); - NPY_END_THREADS + NPY_END_THREADS PyArray_INCREF((PyArrayObject *)dst); return 0; } @@ -843,7 +843,7 @@ elsize = PyArray_ITEMSIZE(dst); nbytes = elsize * PyArray_DIM(src, axis); PyArray_XDECREF((PyArrayObject *)dst); - NPY_BEGIN_THREADS + NPY_BEGIN_THREADS while(it->index < it->size) { myfunc(dptr, elsize, it->dataptr, PyArray_STRIDE(src,axis), @@ -851,7 +851,7 @@ dptr += nbytes; PyArray_ITER_NEXT(it); } - NPY_END_THREADS + NPY_END_THREADS PyArray_INCREF((PyArrayObject *)dst); Py_DECREF(it); @@ -860,7 +860,7 @@ static int -_copy_from_same_shape(PyArrayObject *dest, PyArrayObject *src, +_copy_from_same_shape(PyArrayObject *dest, PyArrayObject *src, void (*myfunc)(char *, intp, char *, intp, intp, int), int swap) { @@ -873,9 +873,9 @@ PyArray_IterAllButAxis((PyObject *)dest, &maxaxis); sit = (PyArrayIterObject *) \ PyArray_IterAllButAxis((PyObject *)src, &maxaxis); - + maxdim = dest->dimensions[maxaxis]; - + if ((dit == NULL) || (sit == NULL)) { Py_XDECREF(dit); Py_XDECREF(sit); @@ -885,14 +885,14 @@ 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, + _strided_byte_swap(dit->dataptr, dest->strides[maxaxis], dest->dimensions[maxaxis], elsize); @@ -900,16 +900,16 @@ PyArray_ITER_NEXT(dit); PyArray_ITER_NEXT(sit); } - NPY_END_THREADS + NPY_END_THREADS Py_DECREF(sit); Py_DECREF(dit); - PyArray_INCREF(dest); + PyArray_INCREF(dest); return 0; } static int -_broadcast_copy(PyArrayObject *dest, PyArrayObject *src, +_broadcast_copy(PyArrayObject *dest, PyArrayObject *src, void (*myfunc)(char *, intp, char *, intp, intp, int), int swap) { @@ -942,11 +942,11 @@ PyArray_XDECREF(dest); - NPY_BEGIN_THREADS + NPY_BEGIN_THREADS while(multi->index < multi->size) { - myfunc(multi->iters[0]->dataptr, + myfunc(multi->iters[0]->dataptr, multi->iters[0]->strides[maxaxis], - multi->iters[1]->dataptr, + multi->iters[1]->dataptr, multi->iters[1]->strides[maxaxis], maxdim, elsize); if (swap) { @@ -964,7 +964,7 @@ } /* If destination is not the right type, then src - will be cast to destination -- this requires + will be cast to destination -- this requires src and dest to have the same shape */ @@ -995,9 +995,9 @@ } same = PyArray_SAMESHAPE(dest, src); - simple = same && ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) || + simple = same && ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) || (PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest))); - + if (simple) { PyArray_XDECREF(dest); NPY_BEGIN_THREADS @@ -1021,12 +1021,12 @@ } else if (usecopy) { myfunc = _unaligned_strided_byte_copy; - } + } else { myfunc = _unaligned_strided_byte_move; } - - /* Could combine these because _broadcasted_copy would work as well. + + /* 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) { @@ -1050,28 +1050,28 @@ int elsize, simple; PyArrayIterObject *idest, *isrc; void (*myfunc)(char *, intp, char *, intp, intp, int); - NPY_BEGIN_THREADS_DEF + 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 ((size=PyArray_SIZE(dest)) != PyArray_SIZE(src)) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "arrays must have the same number of elements" " for copy"); return -1; } - - simple = ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) || + + simple = ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) || (PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest))); - + if (simple) { PyArray_XDECREF(dest); NPY_BEGIN_THREADS @@ -1114,7 +1114,7 @@ } /*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) @@ -1153,7 +1153,7 @@ n_old = PyString_Size(src_object); if (n_new > n_old) { new_string = (char *)malloc(n_new); - memmove(new_string, + memmove(new_string, PyString_AS_STRING(src_object), n_old); memset(new_string+n_old, ' ', n_new-n_old); @@ -1162,7 +1162,7 @@ src_object = tmp; } } - + if (PyArray_Check(src_object)) { dtype = NULL; } @@ -1170,11 +1170,11 @@ dtype = dest->descr; Py_INCREF(dtype); } - src = (PyArrayObject *)PyArray_FromAny(src_object, dtype, 0, + 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; @@ -1235,7 +1235,7 @@ */ if (ret && (PyArray_DESCR(ret)->type_num != PyArray_OBJECT)) { memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret)); - } + } return ret; } @@ -1249,7 +1249,7 @@ PyArray_NewCopy(PyArrayObject *m1, NPY_ORDER fortran) { PyArrayObject *ret; - if (fortran == PyArray_ANYORDER) + if (fortran == PyArray_ANYORDER) fortran = PyArray_ISFORTRAN(m1); Py_INCREF(m1->descr); @@ -1355,7 +1355,7 @@ alloc = 1; memcpy(buffer, data, itemsize); if (!PyArray_ISNOTSWAPPED(base)) { - byte_swap_vector(buffer, + byte_swap_vector(buffer, itemsize >> 2, 4); } } @@ -1364,7 +1364,7 @@ /* Allocated enough for 2-characters per itemsize. Now convert from the data-buffer */ - length = PyUCS2Buffer_FromUCS4(uni->str, + length = PyUCS2Buffer_FromUCS4(uni->str, (PyArray_UCS4 *)buffer, itemsize >> 2); if (alloc) _pya_free(buffer); @@ -1497,7 +1497,7 @@ } /* - Given a string return the type-number for + Given a string return the type-number for the data-type with that string as the type-object name. Returns PyArray_NOTYPE without setting an error if no type can be found. Only works for user-defined data-types. @@ -1516,7 +1516,7 @@ if (strcmp(descr->typeobj->tp_name, str) == 0) return descr->type_num; } - + return PyArray_NOTYPE; } @@ -1535,7 +1535,7 @@ PyArray_Descr *descr2; int typenum; int i; - PyArray_ArrFuncs *f; + PyArray_ArrFuncs *f; /* See if this type is already registered */ for (i=0; inonzero == NULL) { f->nonzero = _default_nonzero; } - if (f->copyswap == NULL || f->getitem == NULL || + if (f->copyswap == NULL || f->getitem == NULL || f->copyswapn == NULL || f->setitem == NULL) { PyErr_SetString(PyExc_ValueError, "a required array function" \ " is missing."); @@ -1575,12 +1575,12 @@ } /*MULTIARRAY_API - Register Casting Function + Register Casting Function Replaces any function currently stored. */ -static int -PyArray_RegisterCastFunc(PyArray_Descr *descr, int totype, - PyArray_VectorUnaryFunc *castfunc) +static int +PyArray_RegisterCastFunc(PyArray_Descr *descr, int totype, + PyArray_VectorUnaryFunc *castfunc) { PyObject *cobj, *key; int ret; @@ -1625,17 +1625,17 @@ */ static int PyArray_RegisterCanCast(PyArray_Descr *descr, int totype, - NPY_SCALARKIND scalar) + NPY_SCALARKIND scalar) { if (scalar == PyArray_NOSCALAR) { /* register with cancastto */ - /* These lists won't be freed once created + /* 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, + descr->f->cancastto = _append_new(descr->f->cancastto, totype); } else { @@ -1747,7 +1747,7 @@ if (strobj == NULL) {Py_DECREF(it); return -1;} } NPY_BEGIN_ALLOW_THREADS - n=fwrite(PyString_AS_STRING(strobj), 1, + n=fwrite(PyString_AS_STRING(strobj), 1, n2=PyString_GET_SIZE(strobj), fp); NPY_END_ALLOW_THREADS if (n < n2) { @@ -1760,7 +1760,7 @@ return -1; } /* write separator for all but last one */ - if (it->index != it->size-1) + if (it->index != it->size-1) if (fwrite(sep, 1, n3, fp) < n3) { PyErr_Format(PyExc_IOError, "problem writing "\ @@ -1890,7 +1890,7 @@ 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, + if (PyArray_CopyAnyInto((PyArrayObject *)self->base, self) < 0) { PyErr_Print(); PyErr_Clear(); @@ -2267,14 +2267,14 @@ /* arr might not have the right number of dimensions and need to be reshaped first by pre-pending ones */ - arr = *ret; + 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; ind-arr->nd; i++) { permute.ptr[i] = 1; - } + } new = PyArray_Newshape(arr, &permute, PyArray_ANYORDER); Py_DECREF(arr); *ret = (PyArrayObject *)new; @@ -2398,8 +2398,8 @@ if (arr == NULL) return -1; } } - + if ((it = (PyArrayIterObject *)PyArray_IterNew(arr))==NULL) { Py_DECREF(arr); return -1; @@ -2589,7 +2589,7 @@ static PyObject * -array_subscript_simple(PyArrayObject *self, PyObject *op) +array_subscript_simple(PyArrayObject *self, PyObject *op) { intp dimensions[MAX_DIMS], strides[MAX_DIMS]; intp offset; @@ -2602,7 +2602,7 @@ return array_big_item(self, value); } PyErr_Clear(); - + /* Standard (view-based) Indexing */ if ((nd = parse_index(self, op, dimensions, strides, &offset)) == -1) return NULL; @@ -2616,12 +2616,12 @@ self->flags, (PyObject *)self)) == NULL) return NULL; - + other->base = (PyObject *)self; Py_INCREF(self); - + PyArray_UpdateFlags(other, UPDATE_ALL); - + return (PyObject *)other; } @@ -2680,7 +2680,7 @@ return NULL; } - if (PyInt_Check(op) || PyArray_IsScalar(op, Integer) || + if (PyInt_Check(op) || PyArray_IsScalar(op, Integer) || PyLong_Check(op)) { intp value; value = PyArray_PyIntAsIntp(op); @@ -2693,7 +2693,7 @@ fancy = fancy_indexing_check(op); if (fancy != SOBJ_NOTFANCY) { - oned = ((self->nd == 1) && + oned = ((self->nd == 1) && !(PyTuple_Check(op) && PyTuple_GET_SIZE(op) > 1)); /* wrap arguments into a mapiter object */ @@ -2716,7 +2716,7 @@ return (PyObject *)other; } - return array_subscript_simple(self, op); + return array_subscript_simple(self, op); } @@ -2743,7 +2743,7 @@ return array_ass_big_item(self, value, op); } PyErr_Clear(); - + /* Rest of standard (view-based) indexing */ if (PyArray_CheckExact(self)) { @@ -2755,14 +2755,14 @@ tmp0 = PyObject_GetItem((PyObject *)self, index); if (tmp0 == NULL) return -1; if (!PyArray_Check(tmp0)) { - PyErr_SetString(PyExc_RuntimeError, + 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); } @@ -2792,7 +2792,7 @@ return -1; } - if (PyInt_Check(index) || PyArray_IsScalar(index, Integer) || + if (PyInt_Check(index) || PyArray_IsScalar(index, Integer) || PyLong_Check(index)) { intp value; value = PyArray_PyIntAsIntp(index); @@ -2860,7 +2860,7 @@ fancy = fancy_indexing_check(index); if (fancy != SOBJ_NOTFANCY) { - oned = ((self->nd == 1) && + oned = ((self->nd == 1) && !(PyTuple_Check(index) && PyTuple_GET_SIZE(index) > 1)); mit = (PyArrayMapIterObject *) \ @@ -2909,7 +2909,7 @@ } } /* optimization for a tuple of integers */ - if (self->nd > 1 && PyTuple_Check(op) && + if (self->nd > 1 && PyTuple_Check(op) && (PyTuple_GET_SIZE(op) == self->nd) && PyArray_IntpFromSequence(op, vals, self->nd) == self->nd) { int i; @@ -2932,7 +2932,7 @@ mp = (PyArrayObject *)array_subscript(self, op); /* The following is just a copy of PyArray_Return with an - additional logic in the nd == 0 case. + additional logic in the nd == 0 case. */ if (mp == NULL) return NULL; @@ -2941,7 +2941,7 @@ Py_XDECREF(mp); return NULL; } - + if (mp->nd == 0) { Bool noellipses = TRUE; if (op == Py_Ellipsis) @@ -2953,7 +2953,7 @@ i=0; while (iob_type->tp_as_number->nb_float(o2); if (temp != NULL) { @@ -3390,13 +3390,13 @@ static PyObject * fast_scalar_power(PyArrayObject *a1, PyObject *o2, int inplace) { double exp; - if (PyArray_Check(a1) && (PyArray_ISFLOAT(a1) || + if (PyArray_Check(a1) && (PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1))) { if (array_power_is_scalar(o2, &exp)) { PyObject *fastop = NULL; if (exp == 1.0) { - /* we have to do this one special, as the - "copy" method of array objects isn't set + /* 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. */ @@ -3418,10 +3418,10 @@ return NULL; } if (inplace) { - return PyArray_GenericInplaceUnaryFunction(a1, + return PyArray_GenericInplaceUnaryFunction(a1, fastop); } else { - return PyArray_GenericUnaryFunction(a1, + return PyArray_GenericUnaryFunction(a1, fastop); } } @@ -3850,7 +3850,7 @@ #if PY_VERSION_HEX >= 0x02050000 (unaryfunc)array_index, /* nb_index */ -#endif +#endif }; @@ -3867,7 +3867,7 @@ static PyObject * -array_slice(PyArrayObject *self, Py_ssize_t ilow, +array_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh) { PyArrayObject *r; @@ -3909,7 +3909,7 @@ static int -array_ass_slice(PyArrayObject *self, Py_ssize_t ilow, +array_ass_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { int ret; PyArrayObject *tmp; @@ -3940,8 +3940,8 @@ PyObject *res; int ret; - - res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self, + + res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self, el, Py_EQ)); if (res == NULL) return -1; ret = array_any_nonzero((PyArrayObject *)res); @@ -4143,7 +4143,7 @@ } /* This also handles possibly mis-aligned data */ -/* Compare s1 and s2 which are not necessarily NULL-terminated. +/* Compare s1 and s2 which are not necessarily NULL-terminated. s1 is of length len1 s2 is of length len2 If they are NULL terminated, then stop comparison. @@ -4165,14 +4165,14 @@ 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;} else {sptr = s1t+len2; val = 1;} if (*sptr != 0) goto finish; val = 0; - + finish: if (s1t != s1) free(s1t); if (s2t != s2) free(s2t); @@ -4182,7 +4182,7 @@ -/* Compare s1 and s2 which are not necessarily NULL-terminated. +/* Compare s1 and s2 which are not necessarily NULL-terminated. s1 is of length len1 s2 is of length len2 If they are NULL terminated, then stop comparison. @@ -4323,7 +4323,7 @@ else _reg_loop(CMP) static int -_compare_strings(PyObject *result, PyArrayMultiIterObject *multi, +_compare_strings(PyObject *result, PyArrayMultiIterObject *multi, int cmp_op, void *func, int rstrip) { PyArrayIterObject *iself, *iother; @@ -4334,7 +4334,7 @@ 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]; @@ -4358,7 +4358,7 @@ break; case Py_NE: _loop(!=) - break; + break; case Py_LT: _loop(<) break; @@ -4376,7 +4376,7 @@ "bad comparison operator"); return -1; } - return 0; + return 0; } #undef _loop @@ -4392,14 +4392,14 @@ PyArrayMultiIterObject *mit; int val; - /* Cast arrays to a common type */ + /* Cast arrays to a common type */ if (self->descr->type != other->descr->type) { 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, + new = PyArray_FromAny((PyObject *)self, other->descr, 0, 0, 0, NULL); if (new == NULL) return NULL; self = (PyArrayObject *)new; @@ -4408,19 +4408,19 @@ other->descr->type_num == PyArray_STRING) { Py_INCREF(self); Py_INCREF(self->descr); - new = PyArray_FromAny((PyObject *)other, 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, + PyErr_SetString(PyExc_TypeError, "invalid string data-types " "in comparison"); return NULL; } } - else { + else { Py_INCREF(self); Py_INCREF(other); } @@ -4430,27 +4430,27 @@ 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, NULL, 0, NULL); if (result == NULL) goto finish; if (self->descr->type_num == PyArray_UNICODE) { - val = _compare_strings(result, mit, cmp_op, _myunincmp, + val = _compare_strings(result, mit, cmp_op, _myunincmp, rstrip); } else { - val = _compare_strings(result, mit, cmp_op, _mystrncmp, + val = _compare_strings(result, mit, cmp_op, _mystrncmp, rstrip); } - + if (val < 0) {Py_DECREF(result); result = NULL;} - - finish: + + finish: Py_DECREF(mit); return result; } @@ -4461,7 +4461,7 @@ 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 + VOID-type arrays without fields are compared for equality by comparing their memory at each location directly (using string-code). */ @@ -4469,7 +4469,7 @@ static PyObject * -_void_compare(PyArrayObject *self, PyArrayObject *other, int cmp_op) +_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" \ @@ -4563,11 +4563,11 @@ result = PyArray_GenericBinaryFunction(self, array_other, n_ops.equal); - if ((result == Py_NotImplemented) && + if ((result == Py_NotImplemented) && (self->descr->type_num == PyArray_VOID)) { int _res; _res = PyObject_RichCompareBool \ - ((PyObject *)self->descr, + ((PyObject *)self->descr, (PyObject *)\ PyArray_DESCR(array_other), Py_EQ); @@ -4579,7 +4579,7 @@ if (_res) { Py_DECREF(result); result = _void_compare\ - (self, + (self, (PyArrayObject *)array_other, cmp_op); Py_DECREF(array_other); @@ -4629,11 +4629,11 @@ result = PyArray_GenericBinaryFunction(self, array_other, n_ops.not_equal); - if ((result == Py_NotImplemented) && + if ((result == Py_NotImplemented) && (self->descr->type_num == PyArray_VOID)) { int _res; _res = PyObject_RichCompareBool\ - ((PyObject *)self->descr, + ((PyObject *)self->descr, (PyObject *)\ PyArray_DESCR(array_other), Py_EQ); @@ -4645,8 +4645,8 @@ if (_res) { Py_DECREF(result); result = _void_compare\ - (self, - (PyArrayObject *)array_other, + (self, + (PyArrayObject *)array_other, cmp_op); Py_DECREF(array_other); } @@ -4938,7 +4938,7 @@ if (_IsAligned(ret)) ret->flags |= ALIGNED; else ret->flags &= ~ALIGNED; } - /* This is not checked by default WRITEABLE is not + /* This is not checked by default WRITEABLE is not part of UPDATE_ALL */ if (flagmask & WRITEABLE) { if (_IsWriteable(ret)) ret->flags |= WRITEABLE; @@ -5207,7 +5207,7 @@ return NULL; } } - + self = (PyArrayObject *) subtype->tp_alloc(subtype, 0); if (self == NULL) { Py_DECREF(descr); @@ -5216,7 +5216,7 @@ self->nd = nd; self->dimensions = NULL; self->data = NULL; - if (data == NULL) { + if (data == NULL) { self->flags = DEFAULT; if (flags) { self->flags |= FORTRAN; @@ -5256,7 +5256,7 @@ /* Allocate something even for zero-space arrays e.g. shape=(0,) -- otherwise buffer exposure (a.data) doesn't work as it should. */ - + if (sd==0) sd = descr->elsize; if ((data = PyDataMem_NEW(sd))==NULL) { @@ -5292,7 +5292,7 @@ /* call the __array_finalize__ method if a subtype. - If obj is NULL, then call method with Py_None + If obj is NULL, then call method with Py_None */ if ((subtype != &PyArray_Type)) { PyObject *res, *func, *args; @@ -5303,7 +5303,7 @@ } func = PyObject_GetAttr((PyObject *)self, str); if (func && func != Py_None) { - if (strides != NULL) { /* did not allocate own data + if (strides != NULL) { /* did not allocate own data or funny strides */ /* update flags before finalize function */ PyArray_UpdateFlags(self, UPDATE_ALL); @@ -5328,7 +5328,7 @@ } else Py_XDECREF(func); } - + return (PyObject *)self; fail: @@ -5353,7 +5353,7 @@ PyArray_Descr *new; int offset, pos=0; while (PyDict_Next(dtype->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) return; _putzero(optr + offset, zero, new); } @@ -5389,16 +5389,16 @@ "resize only works on single-segment arrays"); return NULL; } - + if (self->descr->hasobject) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "cannot resize an object-array like this"); return NULL; } if (fortran == PyArray_ANYORDER) fortran = PyArray_CORDER; - + if (self->descr->elsize == 0) { PyErr_SetString(PyExc_ValueError, "Bad data-type size."); return NULL; @@ -5408,7 +5408,7 @@ for (k=0; khasobject) { - if ((obj == Py_None) || + 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, NULL, NULL, 0, NULL); if (arr!=NULL) dtype->f->setitem(obj, optr, arr); @@ -5529,7 +5529,7 @@ PyArray_Descr *new; int offset, pos=0; while (PyDict_Next(dtype->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) return; _fillobject(optr + offset, obj, new); } @@ -5633,7 +5633,7 @@ static PyObject * array_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { - static char *kwlist[] = {"shape", "dtype", "buffer", + static char *kwlist[] = {"shape", "dtype", "buffer", "offset", "strides", "order", NULL}; PyArray_Descr *descr=NULL; @@ -5679,15 +5679,15 @@ itemsize = descr->elsize; if (itemsize == 0) { - PyErr_SetString(PyExc_ValueError, + 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, + PyErr_SetString(PyExc_ValueError, "strides, if given, must be " \ "the same length as shape"); goto fail; @@ -5701,19 +5701,19 @@ nb = buffer.len; off = (intp) offset; } - - if (!PyArray_CheckStrides(itemsize, dims.len, + + if (!PyArray_CheckStrides(itemsize, dims.len, nb, off, dims.ptr, strides.ptr)) { - PyErr_SetString(PyExc_ValueError, + 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, @@ -5811,7 +5811,7 @@ if (ret == NULL) return -1; if (PyArray_DATA(ret) != PyArray_DATA(self)) { Py_DECREF(ret); - PyErr_SetString(PyExc_AttributeError, + PyErr_SetString(PyExc_AttributeError, "incompatible shape for a non-contiguous array"); return -1; } @@ -5977,7 +5977,7 @@ array_ctypes_get(PyArrayObject *self) { return PyObject_CallMethod(_numpy_internal, "_ctypes", - "ON", self, + "ON", self, PyLong_FromVoidPtr(self->data)); } @@ -5988,7 +5988,7 @@ PyObject *obj; dict = PyDict_New(); if (dict == NULL) return NULL; - + /* dataptr */ obj = array_dataptr_get(self); PyDict_SetItemString(dict, "data", obj); @@ -6005,7 +6005,7 @@ 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); @@ -6149,7 +6149,7 @@ } if (newtype->elsize == 0) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "data-type must not be 0-sized"); Py_DECREF(newtype); return -1; @@ -6239,7 +6239,7 @@ /* reset unused flags */ inter->flags &= ~(UPDATEIFCOPY | OWNDATA); if (PyArray_ISNOTSWAPPED(self)) inter->flags |= NOTSWAPPED; - /* Copy shape and strides over since these can be reset + /* Copy shape and strides over since these can be reset when the array is "reshaped". */ if (self->nd > 0) { @@ -6329,7 +6329,7 @@ self->strides, self->data, 0, - self->flags, + self->flags, (PyObject *)self); if (ret == NULL) {Py_DECREF(new); return -1;} ret->flags &= ~CONTIGUOUS; @@ -6379,7 +6379,7 @@ type, PyArray_ISFORTRAN(self)); ret->flags &= ~WRITEABLE; - if (PyArray_CheckExact(self)) + if (PyArray_CheckExact(self)) return (PyObject *)ret; else { PyObject *newret; @@ -6496,8 +6496,8 @@ return PyArray_Transpose(self, NULL); } -/* If this is None, no function call is made - --- default sub-class behavior +/* If this is None, no function call is made + --- default sub-class behavior */ static PyObject * array_finalize_get(PyArrayObject *self) @@ -6674,7 +6674,7 @@ if (PyDict_Check(e)) { PyObject *new; new = PyDict_GetItemString(e, "shape"); - if (new && PyTuple_Check(new)) + if (new && PyTuple_Check(new)) d = PyTuple_GET_SIZE(new); } Py_DECREF(e); @@ -6694,7 +6694,7 @@ if (d > -1) return d; } else PyErr_Clear(); - + if (PySequence_Length(s) == 0) return 1; if ((e=PySequence_GetItem(s,0)) == NULL) return -1; @@ -7051,7 +7051,7 @@ Otherwise: run object_depth_and_dimension on all the elements - and make sure the returned shape and size + and make sure the returned shape and size is the same for each element */ @@ -7066,7 +7066,7 @@ islist = PyList_Check(s); if (!(islist || PyTuple_Check(s)) || - ((size = PySequence_Size(s)) == 0)) + ((size = PySequence_Size(s)) == 0)) return 0; if (max < 2) { if (max < 1) return 0; @@ -7082,13 +7082,13 @@ 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) || + 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); @@ -7107,12 +7107,12 @@ if (nd < 0) return NULL; if (nd == 0) return Array_FromPyScalar(s, typecode); - + 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); @@ -7139,7 +7139,7 @@ int type = typecode->type_num; int itemsize = typecode->elsize; - if (isobject) + if (isobject) return ObjectArray_FromNestedList(s, typecode, fortran); stop_at_string = ((type == PyArray_OBJECT) || \ @@ -7277,9 +7277,9 @@ } /*OBJECT_API - Get a cast function to cast from the input descriptor to the + 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. + Returns NULL if un-successful. */ static PyArray_VectorUnaryFunc * PyArray_GetCastFunc(PyArray_Descr *descr, int type_num) @@ -7306,13 +7306,13 @@ PyErr_SetString(PyExc_ValueError, "No cast function available."); - return NULL; + return NULL; } /* Reference counts: copyswapn is used which increases and decreases reference counts for OBJECT arrays. - All that needs to happen is for any reference counts in the buffers to be - decreased when completely finished with the buffers. + All that needs to happen is for any reference counts in the buffers to be + decreased when completely finished with the buffers. buffers[0] is the destination buffers[1] is the source @@ -7343,9 +7343,9 @@ while(N > 0) { int newN; newN = MIN(N, bufsize); - _strided_buffered_cast(dptr+i*dstride, dstride, delsize, + _strided_buffered_cast(dptr+i*dstride, dstride, delsize, dswap, dcopyfunc, - sptr+i*sstride, sstride, selsize, + sptr+i*sstride, sstride, selsize, sswap, scopyfunc, newN, buffers, bufsize, castfunc, dest, src); i += newN; @@ -7354,15 +7354,15 @@ return; } -static int -_broadcast_cast(PyArrayObject *out, PyArrayObject *in, +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; + PyArray_CopySwapNFunc *ocopyfunc, *icopyfunc; char *obptr; NPY_BEGIN_THREADS_DEF @@ -7379,7 +7379,7 @@ Py_DECREF(multi); return -1; } - + icopyfunc = in->descr->f->copyswapn; ocopyfunc = out->descr->f->copyswapn; maxaxis = PyArray_RemoveLargest(multi); @@ -7407,14 +7407,14 @@ PyErr_NoMemory(); return -1; } - if (out->descr->hasobject) + if (out->descr->hasobject) memset(buffers[0], 0, N*delsize); - if (in->descr->hasobject) + if (in->descr->hasobject) memset(buffers[1], 0, N*selsize); -#if NPY_ALLOW_THREADS +#if NPY_ALLOW_THREADS if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) { - NPY_BEGIN_THREADS + NPY_BEGIN_THREADS } #endif @@ -7422,7 +7422,7 @@ _strided_buffered_cast(multi->iters[0]->dataptr, ostrides, delsize, oswap, ocopyfunc, - multi->iters[1]->dataptr, + multi->iters[1]->dataptr, istrides, selsize, iswap, icopyfunc, maxdim, buffers, N, @@ -7431,7 +7431,7 @@ } #if NPY_ALLOW_THREADS if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) { - NPY_END_THREADS + NPY_END_THREADS } #endif Py_DECREF(multi); @@ -7442,7 +7442,7 @@ } if (out->descr->hasobject) { obptr = buffers[0]; - for (i=0; idescr); } _pya_free(buffers[0]); @@ -7453,10 +7453,10 @@ -/* Must be broadcastable. +/* Must be broadcastable. This code is very similar to PyArray_CopyInto/PyArray_MoveInto - except casting is done --- PyArray_BUFSIZE is used - as the size of the casting buffer. + except casting is done --- PyArray_BUFSIZE is used + as the size of the casting buffer. */ /*OBJECT_API @@ -7471,7 +7471,7 @@ PyArray_VectorUnaryFunc *castfunc=NULL; int mpsize = PyArray_SIZE(mp); int iswap, oswap; - + NPY_BEGIN_THREADS_DEF if (mpsize == 0) return 0; @@ -7486,7 +7486,7 @@ same = PyArray_SAMESHAPE(out, mp); - simple = same && ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) || + simple = same && ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) || (PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out))); if (simple) { @@ -7510,13 +7510,13 @@ iswap = PyArray_ISBYTESWAPPED(mp) && !PyArray_ISFLEXIBLE(mp); oswap = PyArray_ISBYTESWAPPED(out) && !PyArray_ISFLEXIBLE(out); - + return _broadcast_cast(out, mp, castfunc, iswap, oswap); } static int -_bufferedcast(PyArrayObject *out, PyArrayObject *in, +_bufferedcast(PyArrayObject *out, PyArrayObject *in, PyArray_VectorUnaryFunc *castfunc) { char *inbuffer, *bptr, *optr; @@ -7612,7 +7612,7 @@ /*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. + Only requirement is they have the same number of elements. */ static int PyArray_CastAnyTo(PyArrayObject *out, PyArrayObject *mp) @@ -7634,14 +7634,14 @@ " elements for the cast."); return -1; } - + castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num); if (castfunc == NULL) return -1; - - - simple = ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(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; @@ -7650,7 +7650,7 @@ if (PyArray_SAMESHAPE(out, mp)) { int iswap, oswap; iswap = PyArray_ISBYTESWAPPED(mp) && !PyArray_ISFLEXIBLE(mp); - oswap = PyArray_ISBYTESWAPPED(out) && !PyArray_ISFLEXIBLE(out); + oswap = PyArray_ISBYTESWAPPED(out) && !PyArray_ISFLEXIBLE(out); return _broadcast_cast(out, mp, castfunc, iswap, oswap); } @@ -7988,7 +7988,7 @@ 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))) { @@ -8120,7 +8120,7 @@ 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, + if (typecode == NULL) new = PyObject_CallFunction(array_meth, NULL); else new = PyObject_CallFunction(array_meth, "O", typecode); } @@ -8135,12 +8135,12 @@ } } else { - new = PyObject_CallFunction(array_meth, "OO", + new = PyObject_CallFunction(array_meth, "OO", typecode, context); if (new == NULL && \ PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); - new = PyObject_CallFunction(array_meth, "O", + new = PyObject_CallFunction(array_meth, "O", typecode); } } @@ -8191,7 +8191,7 @@ PyObject *new; if (r == NULL) {Py_XDECREF(newtype); return NULL;} if (newtype != NULL || flags != 0) { - new = PyArray_FromArray((PyArrayObject *)r, newtype, + new = PyArray_FromArray((PyArrayObject *)r, newtype, flags); Py_DECREF(r); r = new; @@ -8215,7 +8215,7 @@ min_depth, max_depth, isobject); if (r == NULL && \ ((thiserr = PyErr_Occurred()) && \ - !PyErr_GivenExceptionMatches(thiserr, + !PyErr_GivenExceptionMatches(thiserr, PyExc_MemoryError))) { /* It wasn't really a sequence after all. * Try interpreting it as a scalar */ @@ -8259,7 +8259,7 @@ err: Py_XDECREF(newtype); - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "UPDATEIFCOPY used for non-array input."); return NULL; } @@ -8357,7 +8357,7 @@ obj = PyArray_FromAny(op, descr, min_depth, max_depth, requires, context); if (obj == NULL) return NULL; - if ((requires & ELEMENTSTRIDES) && + if ((requires & ELEMENTSTRIDES) && !PyArray_ElementStrides(obj)) { PyObject *new; new = PyArray_NewCopy((PyArrayObject *)obj, PyArray_ANYORDER); @@ -8385,7 +8385,7 @@ if (op == NULL) return NULL; if (PyArray_CheckExact(op)) return op; - + if (PyArray_Check(op)) { new = PyArray_View((PyArrayObject *)op, NULL, &PyArray_Type); Py_DECREF(op); @@ -8425,7 +8425,7 @@ 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 + /* cancastto is a PyArray_NOTYPE terminated C-int-array of types that the data-type can be cast to safely. */ if (from->f->cancastto) { @@ -8559,9 +8559,9 @@ fromtype = _typenum_fromtypeobj((PyObject *)from, 0); totype = _typenum_fromtypeobj((PyObject *)to, 0); - if (fromtype == PyArray_NOTYPE || totype == PyArray_NOTYPE) + if (fromtype == PyArray_NOTYPE || totype == PyArray_NOTYPE) return FALSE; - return (Bool) PyArray_CanCastSafely(fromtype, totype); + return (Bool) PyArray_CanCastSafely(fromtype, totype); } @@ -8626,7 +8626,7 @@ it = (PyArrayIterObject *)PyArray_IterNew(obj); if (it == NULL) return NULL; - if (PyArray_NDIM(obj)==0) + if (PyArray_NDIM(obj)==0) return (PyObject *)it; if (*inaxis < 0) { int i, maxaxis=0; @@ -8658,9 +8658,9 @@ adjusted */ /*OBJECT_API - Adjusts previously broadcasted iterators so that the largest axis - is not iterated over. - Returns dimension which is largest in the range [0,multi->nd). + Adjusts previously broadcasted iterators so that the largest axis + is not iterated over. + Returns dimension which is largest in the range [0,multi->nd). A -1 is returned if multi->nd == 0. */ static int @@ -8672,7 +8672,7 @@ intp longest; if (multi->nd == 0) return -1; - + longest = multi->dimensions[0]; /* Find longest dimension */ for (i=1; ind; i++) { @@ -8681,14 +8681,14 @@ longest = multi->dimensions[i]; } } - + for (i=0; inumiter; 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; + it->backstrides[axis] = 0; } multi->size = multi->iters[0]->size; @@ -8742,7 +8742,7 @@ } index = ind->dimensions[0]; if (index > self->size) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "too many boolean indices"); return NULL; } @@ -9256,7 +9256,7 @@ NULL, NULL, 0, (PyObject *)it->ao); if (r==NULL) return NULL; - if (_flat_copyinto(r, (PyObject *)it->ao, + if (_flat_copyinto(r, (PyObject *)it->ao, PyArray_CORDER) < 0) { Py_DECREF(r); return NULL; @@ -9324,7 +9324,7 @@ static PyGetSetDef iter_getsets[] = { {"coords", (getter)iter_coords_get, - NULL, + NULL, NULL}, {NULL, NULL, NULL, NULL}, }; @@ -9706,11 +9706,11 @@ /* 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, + PyErr_SetString(PyExc_ValueError, "invalid index into a 0-size array"); goto fail; } - + for (i=0; inumiter; i++) { intp indval; it = mit->iters[i]; @@ -9934,7 +9934,7 @@ PyInt_FromLong(0)); } else { /* we need to grow the - new indexing object and fill + new indexing object and fill it with 0s for each of the iterators produced */ int k; @@ -10457,7 +10457,7 @@ else { if (prefix_len == 0) prefix_len = strlen("numpy."); - + len = strlen(typeobj->tp_name); if (*(typeobj->tp_name + (len-1)) == '_') len-=1; @@ -10529,8 +10529,8 @@ return PyInt_FromLong(val); } -static int -_arraydescr_isnative(PyArray_Descr *self) +static int +_arraydescr_isnative(PyArray_Descr *self) { if (self->names == NULL) { return PyArray_ISNBO(self->byteorder); @@ -10550,8 +10550,8 @@ /* return Py_True if this data-type descriptor has native byteorder if no fields are defined - - or if all sub-fields have native-byteorder if + + or if all sub-fields have native-byteorder if fields are defined */ static PyObject * @@ -10752,7 +10752,7 @@ PyArray_Descr *new; int offset, pos=0; while (PyDict_Next(self->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) { PyErr_Clear(); return 0; @@ -10778,14 +10778,14 @@ char endian; PyObject *subarray, *fields, *names=NULL; int incref_names = 1; - + if (self->fields == Py_None) {Py_INCREF(Py_None); return Py_None;} - + if (!PyArg_ParseTuple(args, "(icOOOii)", &version, &endian, &subarray, &names, &fields, &elsize, &alignment)) { PyErr_Clear(); - if (!PyArg_ParseTuple(args, "(icOOii)", &version, &endian, - &subarray, &fields, &elsize, + if (!PyArg_ParseTuple(args, "(icOOii)", &version, &endian, + &subarray, &fields, &elsize, &alignment)) { PyErr_Clear(); version = 0; @@ -10812,7 +10812,7 @@ } version = 2; } - + /* If we ever need another pickle format, increment the version number. But we should still be able to handle the old versions. */ @@ -10822,14 +10822,14 @@ version); 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 = '='; @@ -11061,25 +11061,25 @@ result = Py_False; break; case Py_EQ: - if (PyArray_EquivTypes(self, new)) + if (PyArray_EquivTypes(self, new)) result = Py_True; else result = Py_False; break; case Py_NE: - if (PyArray_EquivTypes(self, new)) + 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)) + 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)) + if (PyArray_CanCastTo(new, self)) result = Py_True; else result = Py_False; @@ -11100,10 +11100,10 @@ static Py_ssize_t descr_length(PyObject *self0) { - + PyArray_Descr *self = (PyArray_Descr *)self0; - if (self->names) + if (self->names) return PyDict_Size(self->fields); else return 0; } @@ -11284,13 +11284,13 @@ arrayflags_forc_get(PyArrayFlagsObject *self) { PyObject *item; - + if (((self->flags & FORTRAN) == FORTRAN) || ((self->flags & CONTIGUOUS) == CONTIGUOUS)) item = Py_True; else item = Py_False; - + Py_INCREF(item); return item; } @@ -11299,13 +11299,13 @@ arrayflags_fnc_get(PyArrayFlagsObject *self) { PyObject *item; - + if (((self->flags & FORTRAN) == FORTRAN) && !((self->flags & CONTIGUOUS) == CONTIGUOUS)) item = Py_True; else item = Py_False; - + Py_INCREF(item); return item; } @@ -11314,14 +11314,14 @@ arrayflags_farray_get(PyArrayFlagsObject *self) { PyObject *item; - + 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; } @@ -11341,7 +11341,7 @@ PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars."); return -1; } - res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, Py_None, + 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); @@ -11356,7 +11356,7 @@ PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars."); return -1; } - res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, + res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, (PyObject_IsTrue(obj) ? Py_True : Py_False), Py_None); if (res == NULL) return -1; @@ -11372,7 +11372,7 @@ PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars."); return -1; } - res = PyObject_CallMethod(self->arr, "setflags", "OOO", + res = PyObject_CallMethod(self->arr, "setflags", "OOO", (PyObject_IsTrue(obj) ? Py_True : Py_False), Py_None, Py_None); if (res == NULL) return -1; @@ -11492,7 +11492,7 @@ if (strncmp(key,"ALIGNED",n)==0) return arrayflags_aligned_get(self); break; - case 9: + case 9: if (strncmp(key,"WRITEABLE",n)==0) return arrayflags_writeable_get(self); break; @@ -11513,7 +11513,7 @@ static int arrayflags_setitem(PyArrayFlagsObject *self, PyObject *ind, PyObject *item) -{ +{ char *key; int n; if (!PyString_Check(ind)) goto fail; @@ -11522,12 +11522,12 @@ 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)) || + 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); + return arrayflags_updateifcopy_set(self, item); fail: PyErr_SetString(PyExc_KeyError, "Unknown flag"); @@ -11538,14 +11538,14 @@ _torf_(int flags, int val) { if ((flags & val) == val) return "True"; - else return "False"; + else return "False"; } static PyObject * arrayflags_print(PyArrayFlagsObject *self) { int fl = self->flags; - + return PyString_FromFormat(" %s : %s\n %s : %s\n %s : %s\n"\ " %s : %s\n %s : %s\n %s : %s", "CONTIGUOUS", _torf_(fl, CONTIGUOUS), Modified: trunk/numpy/core/src/arraytypes.inc.src =================================================================== --- trunk/numpy/core/src/arraytypes.inc.src 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/arraytypes.inc.src 2006-08-19 06:01:10 UTC (rev 3040) @@ -24,13 +24,13 @@ /**end repeat**/ -static double +static double _getNAN(void) { #ifdef NAN return NAN; #else static double nan=0; - + if (nan == 0) { double mul = 1e100; double tmp = 0.0; @@ -51,7 +51,7 @@ MyPyFloat_AsDouble(PyObject *obj) { if (obj == Py_None) return _getNAN(); - return PyFloat_AsDouble(obj); + return PyFloat_AsDouble(obj); } @@ -67,7 +67,7 @@ #kind=Bool, Byte, UByte, Short, UShort, Int, Long, UInt, ULong, LongLong, ULongLong, Float, Double# */ -static PyObject * +static PyObject * @TYP at _getitem(char *ip, PyArrayObject *ap) { @typ@ t1; @@ -82,7 +82,7 @@ } } -static int +static int @TYP at _setitem(PyObject *op, char *ov, PyArrayObject *ap) { @typ@ temp; /* ensures alignment */ @@ -93,31 +93,31 @@ temp = (@typ@)@func2@(op); } if (PyErr_Occurred()) return -1; - if (ap == NULL || PyArray_ISBEHAVED(ap)) + if (ap == NULL || PyArray_ISBEHAVED(ap)) *((@typ@ *)ov)=temp; else { - ap->descr->f->copyswap(ov, &temp, !PyArray_ISNOTSWAPPED(ap), + ap->descr->f->copyswap(ov, &temp, !PyArray_ISNOTSWAPPED(ap), ap); } - + return 0; } /**end repeat**/ -/**begin repeat +/**begin repeat #TYP=CFLOAT,CDOUBLE# #typ=float, double# */ -static PyObject * +static PyObject * @TYP at _getitem(char *ip, PyArrayObject *ap) { @typ@ t1, t2; - if ((ap==NULL) || PyArray_ISBEHAVED_RO(ap)) { - return PyComplex_FromDoubles((double)((@typ@ *)ip)[0], + if ((ap==NULL) || PyArray_ISBEHAVED_RO(ap)) { + return PyComplex_FromDoubles((double)((@typ@ *)ip)[0], (double)((@typ@ *)ip)[1]); } else { @@ -130,27 +130,27 @@ } /**end repeat**/ -/**begin repeat +/**begin repeat #TYP=CFLOAT, CDOUBLE, CLONGDOUBLE# #typ=float, double, longdouble# #kind=CFloat, CDouble, CLongDouble# */ -static int - at TYP@_setitem(PyObject *op, char *ov, PyArrayObject *ap) +static int + at TYP@_setitem(PyObject *op, char *ov, PyArrayObject *ap) { Py_complex oop; PyObject *op2; c at typ@ temp; int rsize; - + if (!(PyArray_IsScalar(op, @kind@))) { if (PyArray_Check(op) && (PyArray_NDIM(op)==0)) { op2 = ((PyArrayObject *)op)->descr->f->getitem \ - (((PyArrayObject *)op)->data, + (((PyArrayObject *)op)->data, (PyArrayObject *)op); } - else { + else { op2 = op; Py_INCREF(op); } if (op2 == Py_None) { @@ -162,16 +162,16 @@ Py_DECREF(op2); if (PyErr_Occurred()) return -1; temp.real = (@typ@) oop.real; - temp.imag = (@typ@) oop.imag; + temp.imag = (@typ@) oop.imag; } else { temp = ((Py at kind@ScalarObject *)op)->obval; } - + memcpy(ov, &temp, ap->descr->elsize); if (!PyArray_ISNOTSWAPPED(ap)) byte_swap_vector(ov, 2, sizeof(@typ@)); - + rsize = sizeof(@typ@); copy_and_swap(ov, &temp, rsize, 2, rsize, !PyArray_ISNOTSWAPPED(ap)); return 0; @@ -204,16 +204,16 @@ return 0; } -static PyObject * -CLONGDOUBLE_getitem(char *ip, PyArrayObject *ap) +static PyObject * +CLONGDOUBLE_getitem(char *ip, PyArrayObject *ap) { return PyArray_Scalar(ip, ap->descr, NULL); } /* UNICODE */ -static PyObject * -UNICODE_getitem(char *ip, PyArrayObject *ap) +static PyObject * +UNICODE_getitem(char *ip, PyArrayObject *ap) { PyObject *obj; int mysize; @@ -241,7 +241,7 @@ /* create new empty unicode object of length mysize*2 */ obj = MyPyUnicode_New(mysize*2); if (obj == NULL) {if (alloc) _pya_free(buffer); return obj;} - mysize = PyUCS2Buffer_FromUCS4(((PyUnicodeObject *)obj)->str, + mysize = PyUCS2Buffer_FromUCS4(((PyUnicodeObject *)obj)->str, (PyArray_UCS4 *)buffer, mysize); /* reset length of unicode object to ucs2size */ if (MyPyUnicode_Resize((PyUnicodeObject *)obj, mysize) < 0) { @@ -251,19 +251,19 @@ } #endif if (alloc) _pya_free(buffer); - + return obj; } -static int -UNICODE_setitem(PyObject *op, char *ov, PyArrayObject *ap) +static int +UNICODE_setitem(PyObject *op, char *ov, PyArrayObject *ap) { PyObject *temp; Py_UNICODE *ptr; int datalen; #ifndef Py_UNICODE_WIDE char *buffer; -#endif +#endif if ((temp=PyObject_Unicode(op)) == NULL) return -1; ptr = PyUnicode_AS_UNICODE(temp); @@ -285,7 +285,7 @@ } } else buffer = ov; - datalen = PyUCS2Buffer_AsUCS4(ptr, (PyArray_UCS4 *)buffer, + datalen = PyUCS2Buffer_AsUCS4(ptr, (PyArray_UCS4 *)buffer, datalen >> 1, ap->descr->elsize >> 2); datalen <<= 2; @@ -298,16 +298,16 @@ if (ap->descr->elsize > datalen) { memset(ov + datalen, 0, (ap->descr->elsize - datalen)); } - - if (!PyArray_ISNOTSWAPPED(ap)) + + if (!PyArray_ISNOTSWAPPED(ap)) byte_swap_vector(ov, ap->descr->elsize >> 2, 4); Py_DECREF(temp); return 0; } /* STRING -- can handle both NULL-terminated and not NULL-terminated cases */ -static PyObject * -STRING_getitem(char *ip, PyArrayObject *ap) +static PyObject * +STRING_getitem(char *ip, PyArrayObject *ap) { if (ip[ap->descr->elsize-1]) return PyString_FromStringAndSize(ip,ap->descr->elsize); @@ -315,15 +315,15 @@ return PyString_FromString(ip); } -static int -STRING_setitem(PyObject *op, char *ov, PyArrayObject *ap) +static int +STRING_setitem(PyObject *op, char *ov, PyArrayObject *ap) { char *ptr; int len; PyObject *temp=PyObject_Str(op); - + if (temp == NULL) return -1; - + if (PyString_AsStringAndSize(temp, &ptr, &len) == -1) { Py_DECREF(temp); return -1; @@ -338,8 +338,8 @@ /* OBJECT */ -static PyObject * -OBJECT_getitem(char *ip, PyArrayObject *ap) +static PyObject * +OBJECT_getitem(char *ip, PyArrayObject *ap) { if (PyArray_ISALIGNED(ap)) { Py_INCREF(*(PyObject **)ip); @@ -354,8 +354,8 @@ } -static int -OBJECT_setitem(PyObject *op, char *ov, PyArrayObject *ap) +static int +OBJECT_setitem(PyObject *op, char *ov, PyArrayObject *ap) { Py_INCREF(op); if (PyArray_ISALIGNED(ap)) { @@ -400,9 +400,9 @@ for (i=0; ifields, key); - if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { - Py_DECREF(ret); + Py_DECREF(ret); ap->descr = descr; return NULL; } @@ -426,10 +426,10 @@ /* return an array of the basic type */ PyArray_Dims shape={NULL,-1}; PyObject *ret; - if (!(PyArray_IntpConverter(descr->subarray->shape, + if (!(PyArray_IntpConverter(descr->subarray->shape, &shape))) { PyDimMem_FREE(shape.ptr); - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "invalid shape in fixed-type tuple."); return NULL; } @@ -448,7 +448,7 @@ finish: if (descr->hasobject) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "tried to get void-array with object" " members as buffer."); return NULL; @@ -463,8 +463,8 @@ /* default is to return buffer object pointing to current item */ /* a view of it */ - return u; - + return u; + fail: return NULL; } @@ -494,7 +494,7 @@ names = descr->names; n = PyTuple_GET_SIZE(names); if (PyTuple_GET_SIZE(op) != n) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "size of tuple must match "\ "number of fields."); return -1; @@ -503,7 +503,7 @@ for (i=0; ifields, key); - if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(tup, "Oi|O", &new, &offset, &title)) { ap->descr = descr; return -1; @@ -529,10 +529,10 @@ /* copy into an array of the same basic type */ PyArray_Dims shape={NULL,-1}; PyObject *ret; - if (!(PyArray_IntpConverter(descr->subarray->shape, + if (!(PyArray_IntpConverter(descr->subarray->shape, &shape))) { PyDimMem_FREE(shape.ptr); - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "invalid shape in fixed-type tuple."); return -1; } @@ -556,7 +556,7 @@ const void *buffer; Py_ssize_t buflen; if (descr->hasobject) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "tried to set void-array with object" " members using buffer."); return -1; @@ -568,11 +568,11 @@ return 0; fail: - return -1; + return -1; } -/****************** XXX_to_YYY *******************************/ +/****************** XXX_to_YYY *******************************/ /* Assumes contiguous, and aligned, from and to */ @@ -584,9 +584,9 @@ #fromtyp=byte*13, ubyte*13, short*13, ushort*13, int*13, uint*13, long*13, ulong*13, longlong*13, ulonglong*13, float*13, double*13, longdouble*13, float*13, double*13, longdouble*13# #incr= ip++*169,ip+=2*39# */ -static void - at from@_to_ at to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, - PyArrayObject *aip, PyArrayObject *aop) +static void + at from@_to_ at to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, + PyArrayObject *aip, PyArrayObject *aop) { while (n--) { *op++ = (@totyp@)*ip; @@ -599,9 +599,9 @@ #from=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE# #fromtyp=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble# */ -static void - at from@_to_BOOL(register @fromtyp@ *ip, register Bool *op, register intp n, - PyArrayObject *aip, PyArrayObject *aop) +static void + at from@_to_BOOL(register @fromtyp@ *ip, register Bool *op, register intp n, + PyArrayObject *aip, PyArrayObject *aop) { while (n--) { *op++ = (Bool)(*ip++ != FALSE); @@ -613,9 +613,9 @@ #from=CFLOAT, CDOUBLE, CLONGDOUBLE# #fromtyp=cfloat, cdouble, clongdouble# */ -static void - at from@_to_BOOL(register @fromtyp@ *ip, register Bool *op, register intp n, - PyArrayObject *aip, PyArrayObject *aop) +static void + at from@_to_BOOL(register @fromtyp@ *ip, register Bool *op, register intp n, + PyArrayObject *aip, PyArrayObject *aop) { while (n--) { *op = (Bool)(((*ip).real != FALSE) || ((*ip).imag != FALSE)); @@ -628,9 +628,9 @@ #to=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE# #totyp=byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble# */ -static void -BOOL_to_ at to@(register Bool *ip, register @totyp@ *op, register intp n, - PyArrayObject *aip, PyArrayObject *aop) +static void +BOOL_to_ at to@(register Bool *ip, register @totyp@ *op, register intp n, + PyArrayObject *aip, PyArrayObject *aop) { while (n--) { *op++ = (@totyp@)(*ip++ != FALSE); @@ -645,10 +645,10 @@ #fromtyp=Bool*3,byte*3, ubyte*3, short*3, ushort*3, int*3, uint*3, long*3, ulong*3, longlong*3, ulonglong*3, float*3, double*3, longdouble*3# #totyp= (float, double, longdouble)*14# */ -static void - at from@_to_ at to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, - PyArrayObject *aip, PyArrayObject *aop) -{ +static void + at from@_to_ at to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, + PyArrayObject *aip, PyArrayObject *aop) +{ while (n--) { *op++ = (@totyp@)*ip++; *op++ = 0.0; @@ -657,16 +657,16 @@ } /**end repeat**/ -/**begin repeat +/**begin repeat #to=(CFLOAT,CDOUBLE,CLONGDOUBLE)*3# #from=CFLOAT*3,CDOUBLE*3,CLONGDOUBLE*3# #totyp=(float, double, longdouble)*3# #fromtyp=float*3, double*3, longdouble*3# */ -static void - at from@_to_ at to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, - PyArrayObject *aip, PyArrayObject *aop) +static void + at from@_to_ at to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, + PyArrayObject *aip, PyArrayObject *aop) { n <<= 1; while (n--) { @@ -676,17 +676,17 @@ } /**end repeat**/ -/**begin repeat +/**begin repeat #from=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE,CFLOAT,CDOUBLE,CLONGDOUBLE, STRING, UNICODE, VOID, OBJECT# #fromtyp=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble, cfloat, cdouble, clongdouble, char, char, char, PyObject *# #skip= 1*17, aip->descr->elsize*3, 1# */ -static void +static void @from at _to_OBJECT(@fromtyp@ *ip, PyObject **op, intp n, PyArrayObject *aip, PyArrayObject *aop) { - register intp i; + register intp i; int skip=@skip@; for(i=0;idescr->elsize*3# */ -static void +static void OBJECT_to_ at to@(PyObject **ip, @totyp@ *op, intp n, PyArrayObject *aip, PyArrayObject *aop) { - register intp i; + register intp i; int skip=@skip@; for(i=0;idescr; while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) {arr->descr=descr;return;} arr->descr = new; new->f->copyswapn(dst+offset, dstride, src+offset, sstride, n, swap, arr); @@ -1239,7 +1239,7 @@ return; } if (src != NULL) { - memcpy(dst, src, itemsize * n); + memcpy(dst, src, itemsize * n); } return; } @@ -1254,7 +1254,7 @@ int offset, pos=0; descr = arr->descr; /* Save it */ while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) {arr->descr=descr;return;} arr->descr = new; new->f->copyswap(dst+offset, src+offset, swap, arr); @@ -1270,7 +1270,7 @@ static void -UNICODE_copyswapn (char *dst, intp dstride, char *src, intp sstride, +UNICODE_copyswapn (char *dst, intp dstride, char *src, intp sstride, intp n, int swap, PyArrayObject *arr) { int itemsize; @@ -1280,10 +1280,10 @@ if (dstride == itemsize && sstride == itemsize) memcpy(dst, src, n * itemsize); else - _unaligned_strided_byte_copy(dst, dstride, src, + _unaligned_strided_byte_copy(dst, dstride, src, sstride, n, itemsize); } - + n *= itemsize; if (swap) { register char *a, *b, c; @@ -1303,7 +1303,7 @@ { if (src != NULL && arr != NULL) { memcpy(dst, src, arr->descr->elsize); - } + } } static void @@ -1315,7 +1315,7 @@ if (src != NULL) { memcpy(dst, src, itemsize); } - + if (swap) { register char *a, *b, c; itemsize >>= 2; @@ -1335,7 +1335,7 @@ #fname=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# */ -static Bool +static Bool @fname at _nonzero (@type@ *ip, PyArrayObject *ap) { @type@ t1; @@ -1354,7 +1354,7 @@ #fname=CFLOAT,CDOUBLE,CLONGDOUBLE# #type=cfloat, cdouble, clongdouble# */ -static Bool +static Bool @fname at _nonzero (@type@ *ip, PyArrayObject *ap) { @type@ t1; @@ -1374,17 +1374,17 @@ #define WHITELEN 6 static Bool -Py_STRING_ISSPACE(char ch) +Py_STRING_ISSPACE(char ch) { char white[] = WHITESPACE; int j; Bool space=FALSE; - for (j=0; jdescr->elsize >> 2; int i; Bool nonz = FALSE; - char *buffer=NULL; + char *buffer=NULL; if ((!PyArray_ISNOTSWAPPED(ap)) || \ (!PyArray_ISALIGNED(ap))) { @@ -1446,7 +1446,7 @@ static Bool OBJECT_nonzero (PyObject **ip, PyArrayObject *ap) { - + if (PyArray_ISALIGNED(ap)) { return (Bool) PyObject_IsTrue(*ip); } @@ -1473,7 +1473,7 @@ descr = ap->descr; savedflags = ap->flags; while (PyDict_Next(descr->fields, &pos, &key, &value)) { - if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, + if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset, &title)) {PyErr_Clear(); continue;} ap->descr = new; ap->flags = savedflags; @@ -1518,7 +1518,7 @@ */ static int - at fname@_compare (@type@ *ip1, @type@ *ip2, PyArrayObject *ap) + at fname@_compare (@type@ *ip1, @type@ *ip2, PyArrayObject *ap) { return *ip1 < *ip2 ? -1 : *ip1 == *ip2 ? 0 : 1; } @@ -1526,13 +1526,13 @@ /**end repeat**/ /* compare imaginary part first, then complex if equal imaginary */ -/**begin repeat +/**begin repeat #fname=CFLOAT, CDOUBLE, CLONGDOUBLE# #type= float, double, longdouble# */ static int - at fname@_compare (@type@ *ip1, @type@ *ip2, PyArrayObject *ap) + at fname@_compare (@type@ *ip1, @type@ *ip2, PyArrayObject *ap) { if (*ip1 == *ip2) { return ip1[1]descr->elsize); } /* taken from Python */ -static int -UNICODE_compare(register PyArray_UCS4 *ip1, register PyArray_UCS4 *ip2, +static int +UNICODE_compare(register PyArray_UCS4 *ip1, register PyArray_UCS4 *ip2, PyArrayObject *ap) { register int itemsize=ap->descr->elsize; register PyArray_UCS4 c1, c2; if (itemsize < 0) return 0; - + while(itemsize-- > 0) { c1 = *ip1++; c2 = *ip2++; - - if (c1 != c2) + + if (c1 != c2) return (c1 < c2) ? -1 : 1; } return 0; } /* possibly redefine compare in terms of fields and subarrays if any */ -/* this would have to properly align data (if needed for the type) - before passing on to the _compare function of sub-fields +/* this would have to properly align data (if needed for the type) + before passing on to the _compare function of sub-fields - More importantly, it's unclear what is meant by < and > so we really - can't implement it correctly. + More importantly, it's unclear what is meant by < and > so we really + can't implement it correctly. */ static int -VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) +VOID_compare(char *ip1, char *ip2, PyArrayObject *ap) { return STRING_compare(ip1, ip2, ap); } @@ -1616,18 +1616,18 @@ /**end repeat**/ -static int -OBJECT_argmax(PyObject **ip, intp n, intp *max_ind, PyArrayObject *aip) +static int +OBJECT_argmax(PyObject **ip, intp n, intp *max_ind, PyArrayObject *aip) { - register intp i; + register intp i; PyObject *mp=ip[0]; *max_ind=0; - for(i=1; i 0) { - mp = *ip; + if (PyObject_Compare(*ip,mp) > 0) { + mp = *ip; *max_ind=i; - } - } + } + } return 0; } @@ -1637,23 +1637,23 @@ #type= char, PyArray_UCS4# */ -static int - at fname@_argmax(@type@ *ip, intp n, intp *max_ind, PyArrayObject *aip) +static int + at fname@_argmax(@type@ *ip, intp n, intp *max_ind, PyArrayObject *aip) { - register intp i; + register intp i; int elsize = aip->descr->elsize; @type@ *mp = (@type@ *)_pya_malloc(elsize); - + if (mp==NULL) return 0; memcpy(mp, ip, elsize); *max_ind = 0; - for(i=1; i 0) { + if (@fname at _compare(ip,mp,aip) > 0) { memcpy(mp, ip, elsize); *max_ind=i; - } - } + } + } _pya_free(mp); return 0; } @@ -1663,17 +1663,17 @@ #define VOID_argmax NULL static void -BOOL_dot(char *ip1, intp is1, char *ip2, intp is2, char *op, intp n, +BOOL_dot(char *ip1, intp is1, char *ip2, intp is2, char *op, intp n, void *ignore) { register Bool tmp=FALSE; register intp i; - for(i=0;i= PyArray_NTYPES) ret = NULL; @@ -2080,8 +2080,8 @@ ret = _builtin_descrs[num]; } if (ret==NULL) { - PyErr_SetString(PyExc_ValueError, - "Invalid data-type for array"); + PyErr_SetString(PyExc_ValueError, + "Invalid data-type for array"); } else Py_INCREF(ret); return ret; @@ -2118,7 +2118,7 @@ #define BITSOF_INTP CHAR_BIT*SIZEOF_PY_INTPTR_T #define BITSOF_BYTE CHAR_BIT -/**begin repeat +/**begin repeat #name=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,INTP,UINTP,LONG,ULONG,LONGLONG,ULONGLONG# #uname=BOOL,BYTE*2,SHORT*2,INT*2,INTP*2,LONG*2,LONGLONG*2# @@ -2129,15 +2129,15 @@ #cx=i*6,N,N,N,l,N,N,N# #cn=i*7,N,i,l,i,N,i# */ - PyDict_SetItemString(infodict, "@name@", - s=Py_BuildValue("ciii at cx@@cn at O", - PyArray_ at name@LTR, + PyDict_SetItemString(infodict, "@name@", + s=Py_BuildValue("ciii at cx@@cn at O", + PyArray_ at name@LTR, PyArray_ at name@, BITSOF_ at uname@, _ALIGN(@type@), @max@, @min@, (PyObject *)&Py at Name@ArrType_Type)); - Py_DECREF(s); + Py_DECREF(s); /**end repeat**/ #define BITSOF_CFLOAT 2*BITSOF_FLOAT @@ -2150,43 +2150,43 @@ #name=FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE, CLONGDOUBLE# #Name=Float,Double,LongDouble,CFloat,CDouble,CLongDouble# */ - PyDict_SetItemString(infodict, "@name@", - s=Py_BuildValue("ciiiO", PyArray_ at name@LTR, + PyDict_SetItemString(infodict, "@name@", + s=Py_BuildValue("ciiiO", PyArray_ at name@LTR, PyArray_ at name@, BITSOF_ at name@, _ALIGN(@type@), (PyObject *)\ &Py at Name@ArrType_Type)); Py_DECREF(s); /**end repeat**/ - - PyDict_SetItemString(infodict, "OBJECT", - s=Py_BuildValue("ciiiO", PyArray_OBJECTLTR, - PyArray_OBJECT, + + PyDict_SetItemString(infodict, "OBJECT", + s=Py_BuildValue("ciiiO", PyArray_OBJECTLTR, + PyArray_OBJECT, sizeof(PyObject *)*CHAR_BIT, _ALIGN(PyObject *), (PyObject *)\ &PyObjectArrType_Type)); Py_DECREF(s); - PyDict_SetItemString(infodict, "STRING", - s=Py_BuildValue("ciiiO", PyArray_STRINGLTR, + PyDict_SetItemString(infodict, "STRING", + s=Py_BuildValue("ciiiO", PyArray_STRINGLTR, PyArray_STRING, 0, _ALIGN(char), (PyObject *)\ &PyStringArrType_Type)); Py_DECREF(s); - PyDict_SetItemString(infodict, "UNICODE", - s=Py_BuildValue("ciiiO", PyArray_UNICODELTR, + PyDict_SetItemString(infodict, "UNICODE", + s=Py_BuildValue("ciiiO", PyArray_UNICODELTR, PyArray_UNICODE, 0, _ALIGN(PyArray_UCS4), (PyObject *)\ - &PyUnicodeArrType_Type)); + &PyUnicodeArrType_Type)); Py_DECREF(s); - PyDict_SetItemString(infodict, "VOID", - s=Py_BuildValue("ciiiO", PyArray_VOIDLTR, + PyDict_SetItemString(infodict, "VOID", + s=Py_BuildValue("ciiiO", PyArray_VOIDLTR, PyArray_VOID, 0, _ALIGN(char), (PyObject *)\ - &PyVoidArrType_Type)); + &PyVoidArrType_Type)); Py_DECREF(s); #define SETTYPE(name) \ @@ -2205,7 +2205,7 @@ SETTYPE(Flexible) SETTYPE(Character) -#undef SETTYPE +#undef SETTYPE PyDict_SetItemString(dict, "typeinfo", infodict); Py_DECREF(infodict); @@ -2213,4 +2213,3 @@ } #undef _MAX_LETTER - Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-19 06:01:10 UTC (rev 3040) @@ -2,13 +2,13 @@ Python Multiarray Module -- A useful collection of functions for creating and using ndarrays - Original file + Original file Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin at mit.edu - Modified extensively for numpy in 2005 + Modified extensively for numpy in 2005 Travis E. Oliphant - oliphant at ee.byu.edu + oliphant at ee.byu.edu */ /* $Id: multiarraymodule.c,v 1.36 2005/09/14 00:14:00 teoliphant Exp $ */ @@ -36,7 +36,7 @@ PyObject *dtypedescr; PyArray_Descr *new; int ret; - + dtypedescr = PyObject_GetAttrString(obj, "dtype"); PyErr_Clear(); if (dtypedescr) { @@ -51,14 +51,14 @@ /* Including this file is the only way I know how to declare functions static in each file, and store the pointers from functions in both - arrayobject.c and multiarraymodule.c for the C-API + arrayobject.c and multiarraymodule.c for the C-API Declarying an external pointer-containing variable in arrayobject.c and trying to copy it to PyArray_API, did not work. Think about two modules with a common api that import each other... - This file would just be the module calls. + This file would just be the module calls. */ #include "arrayobject.c" @@ -71,7 +71,7 @@ Multiply a List of ints */ static int -PyArray_MultiplyIntList(register int *l1, register int n) +PyArray_MultiplyIntList(register int *l1, register int n) { register int s=1; while (n--) s *= (*l1++); @@ -81,8 +81,8 @@ /*MULTIARRAY_API Multiply a List */ -static intp -PyArray_MultiplyList(register intp *l1, register int n) +static intp +PyArray_MultiplyList(register intp *l1, register int n) { register intp s=1; while (n--) s *= (*l1++); @@ -98,7 +98,7 @@ register int n = obj->nd; register intp *strides = obj->strides; register char *dptr = obj->data; - + while (n--) dptr += (*strides++) * (*ind++); return (void *)dptr; } @@ -106,7 +106,7 @@ /*MULTIARRAY_API Get axis from an object (possibly None) -- a converter function, */ -static int +static int PyArray_AxisConverter(PyObject *obj, int *axis) { if (obj == Py_None) { @@ -124,13 +124,13 @@ /*MULTIARRAY_API Compare Lists */ -static int -PyArray_CompareLists(intp *l1, intp *l2, int n) +static int +PyArray_CompareLists(intp *l1, intp *l2, int n) { int i; for(i=0;iob_type; - + Py_INCREF(self->descr); new = PyArray_NewFromDescr(subtype, self->descr, @@ -154,11 +154,11 @@ 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) { @@ -168,7 +168,7 @@ } Py_DECREF(type); } - return new; + return new; } /*MULTIARRAY_API @@ -180,18 +180,18 @@ PyArray_Dims newdim = {NULL,1}; intp val[1] = {-1}; - 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); + 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); } static double @@ -217,7 +217,7 @@ { PyObject *f, *ret=NULL, *tmp, *op1, *op2; if (out && (PyArray_SIZE(out) != PyArray_SIZE(a))) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "invalid output shape"); return NULL; } @@ -239,7 +239,7 @@ part = PyObject_GetAttrString(new, "real"); if (part == NULL) {Py_DECREF(new); return NULL;} part = PyArray_EnsureAnyArray(part); - round_part = PyArray_Round((PyArrayObject *)part, + round_part = PyArray_Round((PyArrayObject *)part, decimals, NULL); Py_DECREF(part); if (round_part == NULL) {Py_DECREF(new); return NULL;} @@ -250,8 +250,8 @@ /* 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, + part = PyArray_EnsureAnyArray(part); + round_part = PyArray_Round((PyArrayObject *)part, decimals, NULL); Py_DECREF(part); if (round_part == NULL) {Py_DECREF(new); return NULL;} @@ -275,7 +275,7 @@ } if (decimals == 0) { if (out) { - return PyObject_CallFunction(n_ops.rint, "OO", + return PyObject_CallFunction(n_ops.rint, "OO", a, out); } return PyObject_CallFunction(n_ops.rint, "O", a); @@ -290,8 +290,8 @@ } if (!out) { Py_INCREF(a->descr); - out = (PyArrayObject *)PyArray_Empty(a->nd, a->dimensions, - a->descr, + out = (PyArrayObject *)PyArray_Empty(a->nd, a->dimensions, + a->descr, PyArray_ISFORTRAN(a)); if (out == NULL) return NULL; } @@ -311,7 +311,7 @@ Py_DECREF(f); Py_DECREF(out); return ret; - + } @@ -324,7 +324,7 @@ PyObject *ret; intp size; - if (order == PyArray_ANYORDER) + if (order == PyArray_ANYORDER) order = PyArray_ISFORTRAN(a); size = PyArray_SIZE(a); @@ -335,7 +335,7 @@ NULL, NULL, 0, (PyObject *)a); - + if (ret== NULL) return NULL; if (_flat_copyinto(ret, (PyObject *)a, order) < 0) { Py_DECREF(ret); @@ -353,7 +353,7 @@ Reshape an array */ static PyObject * -PyArray_Reshape(PyArrayObject *self, PyObject *shape) +PyArray_Reshape(PyArrayObject *self, PyObject *shape) { PyObject *ret; PyArray_Dims newdims; @@ -400,19 +400,19 @@ intp *dimensions; intp i_unknown, s_known; int i, n; - static char msg[] = "total size of new array must be unchanged"; - + static char msg[] = "total size of new array must be unchanged"; + dimensions = newshape->ptr; - n = newshape->len; + n = newshape->len; s_known = 1; i_unknown = -1; - + for(i=0; i= 0) { if ((s_known == 0) || (s_original % s_known != 0)) { PyErr_SetString(PyExc_ValueError, msg); @@ -437,19 +437,19 @@ return 0; } -/* Returns a new array +/* Returns a new array with the new shape from the data in the old array --- order-perspective depends on fortran argument. copy-if-necessary (currently if not contiguous or fortran-contiguous) - perhaps a more general-purpose strategy for determining this can + perhaps a more general-purpose strategy for determining this can be worked out */ /*MULTIARRAY_API New shape for an array */ -static PyObject * -PyArray_Newshape(PyArrayObject *self, PyArray_Dims *newdims, +static PyObject * +PyArray_Newshape(PyArrayObject *self, PyArray_Dims *newdims, NPY_ORDER fortran) { intp i; @@ -462,31 +462,31 @@ 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 && idescr->elsize; for (i=1; idescr); ret = (PyAO *)PyArray_NewFromDescr(self->ob_type, self->descr, @@ -530,15 +530,15 @@ strides, self->data, self->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; @@ -546,7 +546,7 @@ -/* return a new view of the array object with all of its unit-length +/* return a new view of the array object with all of its unit-length dimensions squeezed out if needed, otherwise return the same array. */ @@ -575,12 +575,12 @@ strides[j++] = self->strides[i]; } } - + Py_INCREF(self->descr); - ret = PyArray_NewFromDescr(self->ob_type, + ret = PyArray_NewFromDescr(self->ob_type, self->descr, - newnd, dimensions, - strides, self->data, + newnd, dimensions, + strides, self->data, self->flags, (PyObject *)self); if (ret == NULL) return NULL; @@ -627,7 +627,7 @@ Std */ static PyObject * -PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out, +PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out, int variance) { PyObject *obj1=NULL, *obj2=NULL, *new=NULL; @@ -639,7 +639,7 @@ /* Compute and reshape mean */ obj1 = PyArray_EnsureArray(PyArray_Mean((PyAO *)new, axis, rtype, NULL)); - if (obj1 == NULL) {Py_DECREF(new); return 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;} @@ -652,12 +652,12 @@ 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)); @@ -681,7 +681,7 @@ if (!variance) { obj1 = PyArray_EnsureArray(ret); - + /* sqrt() */ ret = PyArray_GenericUnaryFunction((PyAO *)obj1, n_ops.sqrt); Py_DECREF(obj1); @@ -715,7 +715,7 @@ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; - ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis, + ret = PyArray_GenericReduceFunction((PyAO *)new, n_ops.add, axis, rtype, out); Py_DECREF(new); return ret; @@ -763,7 +763,7 @@ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; - ret = PyArray_GenericAccumulateFunction((PyAO *)new, + ret = PyArray_GenericAccumulateFunction((PyAO *)new, n_ops.multiply, axis, rtype, out); Py_DECREF(new); @@ -780,8 +780,8 @@ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; - ret = PyArray_GenericReduceFunction((PyAO *)new, - n_ops.logical_or, axis, + ret = PyArray_GenericReduceFunction((PyAO *)new, + n_ops.logical_or, axis, PyArray_BOOL, out); Py_DECREF(new); return ret; @@ -797,8 +797,8 @@ if ((new = _check_axis(self, &axis, 0))==NULL) return NULL; - ret = PyArray_GenericReduceFunction((PyAO *)new, - n_ops.logical_and, axis, + ret = PyArray_GenericReduceFunction((PyAO *)new, + n_ops.logical_and, axis, PyArray_BOOL, out); Py_DECREF(new); return ret; @@ -809,7 +809,7 @@ Compress */ static PyObject * -PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis, +PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis, PyArrayObject *out) { PyArrayObject *cond; @@ -817,10 +817,10 @@ cond = (PyAO *)PyArray_FROM_O(condition); if (cond == NULL) return NULL; - + if (cond->nd != 1) { Py_DECREF(cond); - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "condition must be 1-d array"); return NULL; } @@ -828,7 +828,7 @@ res = PyArray_Nonzero(cond); Py_DECREF(cond); if (res == NULL) return res; - ret = PyArray_TakeFrom(self, PyTuple_GET_ITEM(res, 0), axis, + ret = PyArray_TakeFrom(self, PyTuple_GET_ITEM(res, 0), axis, out, NPY_RAISE); Py_DECREF(res); return ret; @@ -857,9 +857,9 @@ PyArray_ITER_RESET(it); ret = PyTuple_New(n); - if (ret == NULL) goto fail; + if (ret == NULL) goto fail; for (j=0; job_type, 1, &count, + item = PyArray_New(self->ob_type, 1, &count, PyArray_INTP, NULL, NULL, 0, 0, (PyObject *)self); if (item == NULL) goto fail; @@ -868,17 +868,17 @@ } if (n==1) { for (i=0; idescr->f->nonzero(it->dataptr, self)) + 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; idescr->f->nonzero(it->dataptr, self)) - for (j=0; jdescr->f->nonzero(it->dataptr, self)) + for (j=0; jcoordinates[j]; PyArray_ITER_NEXT(it); } @@ -891,7 +891,7 @@ Py_XDECREF(ret); Py_XDECREF(it); return NULL; - + } /*MULTIARRAY_API @@ -914,8 +914,8 @@ return NULL; } res3 = PyNumber_Multiply(two, res1); - Py_DECREF(two); - Py_DECREF(res1); + Py_DECREF(two); + Py_DECREF(res1); if (res3 == NULL) return NULL; selector = PyArray_EnsureAnyArray(PyNumber_Add(res2, res3)); @@ -963,10 +963,10 @@ for (i=0; iimag = -dptr->imag; dptr++; - } - } + } + } if (out) { - if (PyArray_CopyAnyInto(out, (PyArrayObject *)new)<0) + if (PyArray_CopyAnyInto(out, (PyArrayObject *)new)<0) return NULL; Py_INCREF(out); Py_DECREF(new); @@ -991,7 +991,7 @@ Trace */ static PyObject * -PyArray_Trace(PyArrayObject *self, int offset, int axis1, int axis2, +PyArray_Trace(PyArrayObject *self, int offset, int axis1, int axis2, int rtype, PyArrayObject *out) { PyObject *diag=NULL, *ret=NULL; @@ -1013,11 +1013,11 @@ PyObject *new; PyArray_Dims newaxes; intp dims[MAX_DIMS]; - int i, pos; + int i, pos; newaxes.ptr = dims; if (n < 2) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "array.ndim must be >= 2"); return NULL; } @@ -1030,7 +1030,7 @@ axis1, axis2, n); return NULL; } - + newaxes.len = n; /* insert at the end */ newaxes.ptr[n-2] = axis1; @@ -1043,7 +1043,7 @@ 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; @@ -1059,11 +1059,11 @@ 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, + + indices = PyArray_New(&PyArray_Type, 1, &count, PyArray_INTP, NULL, NULL, 0, 0, NULL); if (indices == NULL) { Py_DECREF(self); return NULL; @@ -1077,15 +1077,15 @@ 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) - */ + return array (my_diagonal) + */ PyObject *mydiagonal=NULL, *new=NULL, *ret=NULL, *sel=NULL; intp i, n1; int res; @@ -1128,13 +1128,13 @@ } } -/* 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 +/* 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. 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. + 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*/ @@ -1142,7 +1142,7 @@ Simulat a C-array */ static int -PyArray_AsCArray(PyObject **op, void *ptr, intp *dims, int nd, +PyArray_AsCArray(PyObject **op, void *ptr, intp *dims, int nd, PyArray_Descr* typedescr) { PyArrayObject *ap; @@ -1171,7 +1171,7 @@ ptr2[i] = ap->data + i*ap->strides[0]; } *((char ***)ptr) = ptr2; - break; + break; case 3: n = ap->dimensions[0]; m = ap->dimensions[1]; @@ -1200,15 +1200,15 @@ /*MULTIARRAY_API Convert to a 1D C-array */ -static int -PyArray_As1D(PyObject **op, char **ptr, int *d1, int typecode) +static int +PyArray_As1D(PyObject **op, char **ptr, int *d1, int typecode) { intp newd1; PyArray_Descr *descr; - descr = PyArray_DescrFromType(typecode); + descr = PyArray_DescrFromType(typecode); if (PyArray_AsCArray(op, (void *)ptr, &newd1, 1, descr) == -1) - return -1; + return -1; *d1 = (int) newd1; return 0; } @@ -1216,13 +1216,13 @@ /*MULTIARRAY_API Convert to a 2D C-array */ -static int -PyArray_As2D(PyObject **op, char ***ptr, int *d1, int *d2, int typecode) +static int +PyArray_As2D(PyObject **op, char ***ptr, int *d1, int *d2, int typecode) { intp newdims[2]; PyArray_Descr *descr; - descr = PyArray_DescrFromType(typecode); + descr = PyArray_DescrFromType(typecode); if (PyArray_AsCArray(op, (void *)ptr, newdims, 2, descr) == -1) return -1; @@ -1236,12 +1236,12 @@ /*MULTIARRAY_API Free pointers created if As2D is called */ -static int -PyArray_Free(PyObject *op, void *ptr) +static int +PyArray_Free(PyObject *op, void *ptr) { PyArrayObject *ap = (PyArrayObject *)op; - - if ((ap->nd < 1) || (ap->nd > 3)) + + if ((ap->nd < 1) || (ap->nd > 3)) return -1; if (ap->nd >= 2) { _pya_free(ptr); @@ -1276,28 +1276,28 @@ arr = PyArray_SwapAxes((PyArrayObject *)otmp, axis, 0); Py_DECREF(otmp); return arr; - + fail: Py_DECREF(newtup); return NULL; } /*op is a python object supporting the sequence interface. - Its elements will be concatenated together to form a single + Its elements will be concatenated together to form a single multidimensional array.*/ -/* If axis is MAX_DIMS or bigger, then each sequence object will - be flattened before concatenation +/* If axis is MAX_DIMS or bigger, then each sequence object will + be flattened before concatenation */ /*MULTIARRAY_API Concatenate an arbitrary Python sequence into an array. */ static PyObject * -PyArray_Concatenate(PyObject *op, int axis) +PyArray_Concatenate(PyObject *op, int axis) { PyArrayObject *ret, **mps; PyObject *otmp; int i, n, tmp, nd=0, new_dim; - char *data; + char *data; PyTypeObject *subtype; double prior1, prior2; intp numbytes; @@ -1307,7 +1307,7 @@ return NULL; } if (n == 0) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "concatenation of zero-length sequences is "\ "impossible"); return NULL; @@ -1315,13 +1315,13 @@ 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; @@ -1339,59 +1339,59 @@ } } } - + new_dim = 0; for(i=0; ind; else { if (nd != mps[i]->nd) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "arrays must have same "\ "number of dimensions"); goto fail; } - if (!PyArray_CompareLists(mps[0]->dimensions+1, - mps[i]->dimensions+1, + if (!PyArray_CompareLists(mps[0]->dimensions+1, + mps[i]->dimensions+1, nd-1)) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "array dimensions must "\ "agree except for d_0"); goto fail; } } if (nd == 0) { - PyErr_SetString(PyExc_ValueError, + 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, + ret = (PyArrayObject *)PyArray_NewFromDescr(subtype, mps[0]->descr, nd, - mps[0]->dimensions, + mps[0]->dimensions, NULL, NULL, 0, (PyObject *)ret); mps[0]->dimensions[0] = tmp; - + if (ret == NULL) goto fail; - + data = ret->data; for(i=0; idata, numbytes); data += numbytes; } - + PyArray_INCREF(ret); for(i=0; ind; if (n <= 1) { Py_INCREF(ap); @@ -1424,12 +1424,12 @@ if (a1 < 0) a1 += n; if (a2 < 0) a2 += n; if ((a1 < 0) || (a1 >= n)) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "bad axis1 argument to swapaxes"); return NULL; } if ((a2 < 0) || (a2 >= n)) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "bad axis2 argument to swapaxes"); return NULL; } @@ -1466,7 +1466,7 @@ n = permute->len; axes = permute->ptr; if (n != ap->nd) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "axes don't match array"); return NULL; } @@ -1477,7 +1477,7 @@ axis = axes[i]; if (axis < 0) axis = ap->nd+axis; if (axis < 0 || axis >= ap->nd) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "invalid axis for this array"); return NULL; } @@ -1492,29 +1492,29 @@ for (i=0; idata. */ Py_INCREF(ap->descr); ret = (PyArrayObject *)\ - PyArray_NewFromDescr(ap->ob_type, - ap->descr, - n, permutation, + PyArray_NewFromDescr(ap->ob_type, + ap->descr, + n, permutation, 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); - + for(i=0; idimensions[i] = ap->dimensions[permutation[i]]; ret->strides[i] = ap->strides[permutation[i]]; } - PyArray_UpdateFlags(ret, CONTIGUOUS | FORTRAN); + PyArray_UpdateFlags(ret, CONTIGUOUS | FORTRAN); - return (PyObject *)ret; + return (PyObject *)ret; } /*MULTIARRAY_API @@ -1550,16 +1550,16 @@ n = aop->dimensions[axis]; if (aop->dimensions[axis] != n) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "a.shape[axis] != len(repeats)"); goto fail; } - - if (nd == 0) + + if (nd == 0) total = counts[0]*n; else { - + total = 0; for(j=0; jdimensions[axis] = total; Py_INCREF(aop->descr); - ret = (PyArrayObject *)PyArray_NewFromDescr(aop->ob_type, + 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; ind; i++) { chunk *= aop->dimensions[i]; } - + n_outer = 1; for(i=0; idimensions[i]; @@ -1610,7 +1610,7 @@ PyArray_INCREF(ret); Py_XDECREF(aop); return (PyObject *)ret; - + fail: Py_DECREF(repeats); Py_XDECREF(aop); @@ -1635,14 +1635,14 @@ (byteorder == PyArray_NATIVE && PyArray_ISNBO(PyArray_LITTLE)))) ptr += elsize-1; - - return ((*ptr & bitmask) != 0); + + return ((*ptr & bitmask) != 0); } /*OBJECT_API*/ static NPY_SCALARKIND -PyArray_ScalarKind(int typenum, PyArrayObject **arr) +PyArray_ScalarKind(int typenum, PyArrayObject **arr) { if (PyTypeNum_ISSIGNED(typenum)) { if (arr && _signbit_set(*arr)) return PyArray_INTNEG_SCALAR; @@ -1657,9 +1657,9 @@ NPY_SCALARKIND retval; PyArray_Descr* descr; descr = PyArray_DescrFromType(typenum); - if (descr->f->scalarkind) + if (descr->f->scalarkind) retval = descr->f->scalarkind((arr ? *arr : NULL)); - else + else retval = PyArray_NOSCALAR; Py_DECREF(descr); return retval; @@ -1668,10 +1668,10 @@ } /*OBJECT_API*/ -static int -PyArray_CanCoerceScalar(int thistype, int neededtype, - NPY_SCALARKIND scalar) -{ +static int +PyArray_CanCoerceScalar(int thistype, int neededtype, + NPY_SCALARKIND scalar) +{ PyArray_Descr* from; int *castlist; @@ -1679,9 +1679,9 @@ return PyArray_CanCastSafely(thistype, neededtype); } from = PyArray_DescrFromType(thistype); - if (from->f->cancastscalarkindto && + if (from->f->cancastscalarkindto && (castlist = from->f->cancastscalarkindto[scalar])) { - while (*castlist != PyArray_NOTYPE) + while (*castlist != PyArray_NOTYPE) if (*castlist++ == neededtype) return 1; } switch(scalar) { @@ -1712,25 +1712,25 @@ static PyArrayObject ** PyArray_ConvertToCommonType(PyObject *op, int *retn) { - int i, n, allscalars=0; + int i, n, allscalars=0; PyArrayObject **mps=NULL; PyObject *otmp; PyArray_Descr *intype=NULL, *stype=NULL; PyArray_Descr *newtype=NULL; NPY_SCALARKIND scalarkind; - + *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(); } - + for(i=0; itype_num, + scalarkind = PyArray_ScalarKind(newtype->type_num, NULL); if (intype && \ !PyArray_CanCoerceScalar(newtype->type_num, - intype->type_num, + intype->type_num, scalarkind)) { Py_XDECREF(intype); intype = stype; @@ -1766,7 +1766,7 @@ /* Make sure all arrays are actual array objects. */ for(i=0; ind < mps[i]->nd) { - PyErr_SetString(PyExc_ValueError, + 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, + PyErr_SetString(PyExc_ValueError, "array dimensions must agree"); goto fail; } sizes[i] = PyArray_NBYTES(mps[i]); } - + Py_INCREF(mps[0]->descr); if (!ret) { - ret = (PyArrayObject *)PyArray_NewFromDescr(ap->ob_type, + ret = (PyArrayObject *)PyArray_NewFromDescr(ap->ob_type, mps[0]->descr, ap->nd, - ap->dimensions, + ap->dimensions, NULL, NULL, 0, (PyObject *)ap); if (ret == NULL) goto fail; @@ -1852,7 +1852,7 @@ int flags = NPY_CARRAY | NPY_UPDATEIFCOPY; if (PyArray_SIZE(ret) != PyArray_SIZE(ap)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "invalid shape for output array."); ret = NULL; Py_DECREF(mps[0]->descr); @@ -1861,27 +1861,27 @@ 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 + before the error is called */ flags |= NPY_ENSURECOPY; } - obj = (PyArrayObject *)PyArray_FromArray(ret, mps[0]->descr, + obj = (PyArrayObject *)PyArray_FromArray(ret, mps[0]->descr, flags); if (obj != ret) copyret = 1; ret = obj; } - + elsize = ret->descr->elsize; m = PyArray_SIZE(ret); self_data = (intp *)ap->data; - ret_data = ret->data; + ret_data = ret->data; for (i=0; i= n) { switch(clipmode) { case NPY_RAISE: - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "invalid entry in choice "\ "array"); goto fail; @@ -1904,7 +1904,7 @@ memmove(ret_data, mps[mi]->data+offset, elsize); ret_data += elsize; self_data++; } - + PyArray_INCREF(ret); for(i=0; ibase; Py_INCREF(obj); - Py_DECREF(ret); + Py_DECREF(ret); ret = (PyArrayObject *)obj; } return (PyObject *)ret; - + fail: for(i=0; idataptr, + _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, + + _unaligned_strided_byte_copy(it->dataptr, astride, buffer, (intp) elsize, N, elsize); PyArray_ITER_NEXT(it); } @@ -1987,10 +1987,10 @@ if (sort(it->dataptr, N, op) < 0) goto fail; PyArray_ITER_NEXT(it); } - } - + } + END_THREADS - + Py_DECREF(it); return 0; @@ -2002,7 +2002,7 @@ } static PyObject* -_new_argsort(PyArrayObject *op, int axis, NPY_SORTKIND which) +_new_argsort(PyArrayObject *op, int axis, NPY_SORTKIND which) { PyArrayIterObject *it=NULL; @@ -2013,7 +2013,7 @@ int elsize, swap; intp astride, rstride, *iptr; PyArray_ArgSortFunc *argsort; - BEGIN_THREADS_DEF + BEGIN_THREADS_DEF ret = PyArray_New(op->ob_type, op->nd, op->dimensions, PyArray_INTP, @@ -2037,7 +2037,7 @@ needcopy = swap || !(op->flags & ALIGNED) || (astride != (intp) elsize) || \ (rstride != sizeof(intp)); - + if (needcopy) { char *valbuffer, *indbuffer; valbuffer = PyDataMem_NEW(N*elsize); @@ -2049,11 +2049,11 @@ iptr = (intp *)indbuffer; for (i=0; idataptr, rstride, indbuffer, + _unaligned_strided_byte_copy(rit->dataptr, rstride, indbuffer, sizeof(intp), N, sizeof(intp)); PyArray_ITER_NEXT(it); PyArray_ITER_NEXT(rit); @@ -2065,13 +2065,13 @@ while (size--) { iptr = (intp *)rit->dataptr; for (i=0; idataptr, (intp *)rit->dataptr, + if (argsort(it->dataptr, (intp *)rit->dataptr, N, op) < 0) goto fail; PyArray_ITER_NEXT(it); PyArray_ITER_NEXT(rit); } } - + END_THREADS Py_DECREF(it); @@ -2093,8 +2093,8 @@ static PyArrayObject *global_obj; -static int -qsortCompare (const void *a, const void *b) +static int +qsortCompare (const void *a, const void *b) { return global_obj->descr->f->compare(a,b,global_obj); } @@ -2102,7 +2102,7 @@ /* Consumes reference to ap (op gets it) op contains a version of the array with axes swapped if local variable axis is not the last dimension. - orign must be defined locally. + orign must be defined locally. */ #define SWAPAXES(op, ap) { \ @@ -2116,9 +2116,9 @@ } /* 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. + 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) { \ @@ -2152,7 +2152,7 @@ Sort an array in-place */ static int -PyArray_Sort(PyArrayObject *op, int axis, NPY_SORTKIND which) +PyArray_Sort(PyArrayObject *op, int axis, NPY_SORTKIND which) { PyArrayObject *ap=NULL, *store_arr=NULL; char *ip; @@ -2163,12 +2163,12 @@ if (axis < 0) axis += n; if ((axis < 0) || (axis >= n)) { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "axis(=%d) out of bounds", axis); return -1; } if (!PyArray_ISWRITEABLE(op)) { - PyErr_SetString(PyExc_RuntimeError, + PyErr_SetString(PyExc_RuntimeError, "attempted sort on unwriteable array."); return -1; } @@ -2180,18 +2180,18 @@ if ((which != PyArray_QUICKSORT) || \ op->descr->f->compare == NULL) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "desired sort not supported for this type"); return -1; } SWAPAXES2(op); - ap = (PyArrayObject *)PyArray_FromAny((PyObject *)op, - NULL, 1, 0, - DEFAULT | UPDATEIFCOPY, NULL); + 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; @@ -2199,15 +2199,15 @@ n = PyArray_SIZE(ap)/m; /* Store global -- allows re-entry -- restore before leaving*/ - store_arr = global_obj; + store_arr = global_obj; global_obj = ap; - + for (ip=ap->data, i=0; idescr->elsize; const intp *ipa = ip1; - const intp *ipb = ip2; + const intp *ipb = ip2; return global_obj->descr->f->compare(global_data + (isize * *ipa), - global_data + (isize * *ipb), + global_data + (isize * *ipb), global_obj); } @@ -2238,7 +2238,7 @@ ArgSort an array */ static PyObject * -PyArray_ArgSort(PyArrayObject *op, int axis, NPY_SORTKIND which) +PyArray_ArgSort(PyArrayObject *op, int axis, NPY_SORTKIND which) { PyArrayObject *ap=NULL, *ret=NULL, *store; intp *ip; @@ -2249,9 +2249,9 @@ n = op->nd; if ((n==0) || (PyArray_SIZE(op)==1)) { ret = (PyArrayObject *)PyArray_New(op->ob_type, op->nd, - op->dimensions, + op->dimensions, PyArray_INTP, - NULL, NULL, 0, 0, + NULL, NULL, 0, 0, (PyObject *)op); if (ret == NULL) return NULL; *((intp *)ret->data) = 0; @@ -2259,7 +2259,7 @@ } if (axis < 0) axis += n; if ((axis < 0) || (axis >= n)) { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "axis(=%d) out of bounds", axis); return NULL; } @@ -2270,25 +2270,25 @@ } if ((which != PyArray_QUICKSORT) || op->descr->f->compare == NULL) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "requested sort not available for type"); goto fail; } SWAPAXES(ap, op); - op = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ap, + op = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)ap, PyArray_NOTYPE, 1, 0); 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]; @@ -2318,7 +2318,7 @@ Py_XDECREF(ret); return NULL; -} +} /*MULTIARRAY_API @@ -2326,11 +2326,11 @@ 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) +PyArray_LexSort(PyObject *sort_keys, int axis) { PyArrayObject **mps; PyArrayIterObject **its; @@ -2349,7 +2349,7 @@ if (!PySequence_Check(sort_keys) || \ ((n=PySequence_Size(sort_keys)) <= 0)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "need sequence of keys with len > 0 in lexsort"); return NULL; } @@ -2375,7 +2375,7 @@ } } if (!mps[i]->descr->f->argsort[PyArray_MERGESORT]) { - PyErr_Format(PyExc_TypeError, + PyErr_Format(PyExc_TypeError, "merge sort not available for item %d", i); goto fail; } @@ -2388,7 +2388,7 @@ nd = mps[0]->nd; if ((nd==0) || (PyArray_SIZE(mps[0])==1)) { ret = (PyArrayObject *)PyArray_New(&PyArray_Type, mps[0]->nd, - mps[0]->dimensions, + mps[0]->dimensions, PyArray_INTP, NULL, NULL, 0, 0, NULL); if (ret == NULL) return NULL; @@ -2397,7 +2397,7 @@ } if (axis < 0) axis += nd; if ((axis < 0) || (axis >= nd)) { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "axis(=%d) out of bounds", axis); goto fail; } @@ -2425,7 +2425,7 @@ needcopy = PyArray_ISBYTESWAPPED(mps[j]) || \ !(mps[j]->flags & ALIGNED) || \ (mps[j]->strides[axis] != (intp)mps[j]->descr->elsize); - if (mps[j]->descr->elsize > maxelsize) + if (mps[j]->descr->elsize > maxelsize) maxelsize = mps[j]->descr->elsize; } @@ -2441,14 +2441,14 @@ for (i=0; idescr->elsize; - astride = mps[j]->strides[axis]; + astride = mps[j]->strides[axis]; argsort = mps[j]->descr->f->argsort[PyArray_MERGESORT]; - _unaligned_strided_byte_copy(valbuffer, (intp) elsize, + _unaligned_strided_byte_copy(valbuffer, (intp) elsize, its[j]->dataptr, astride, N, elsize); - if (swaps[j]) + 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(valbuffer); PyDataMem_FREE(indbuffer); free(swaps); goto fail; @@ -2479,7 +2479,7 @@ NPY_END_THREADS - for (i=0; idescr->f->compare; intp min_i, max_i, i, j; int location, elsize = ap1->descr->elsize; @@ -2540,43 +2540,43 @@ Numeric.searchsorted(a,v) */ static PyObject * -PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2) +PyArray_SearchSorted(PyArrayObject *op1, PyObject *op2) { PyArrayObject *ap1=NULL, *ap2=NULL, *ret=NULL; int typenum = 0; NPY_BEGIN_THREADS_DEF - + typenum = PyArray_ObjectType((PyObject *)op1, 0); typenum = PyArray_ObjectType(op2, typenum); ret = NULL; - ap1 = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)op1, - typenum, + ap1 = (PyArrayObject *)PyArray_ContiguousFromAny((PyObject *)op1, + typenum, 1, 1); if (ap1 == NULL) return NULL; - ap2 = (PyArrayObject *)PyArray_ContiguousFromAny(op2, typenum, + ap2 = (PyArrayObject *)PyArray_ContiguousFromAny(op2, typenum, 0, 0); if (ap2 == NULL) goto fail; - - ret = (PyArrayObject *)PyArray_New(ap2->ob_type, ap2->nd, + + ret = (PyArrayObject *)PyArray_New(ap2->ob_type, ap2->nd, ap2->dimensions, PyArray_INTP, NULL, NULL, 0, 0, (PyObject *)ap2); if (ret == NULL) goto fail; if (ap2->descr->f->compare == NULL) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "compare not supported for type"); goto fail; } NPY_BEGIN_THREADS_DESCR(ap2->descr) - local_where(ap1, ap2, ret); + local_where(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); @@ -2595,7 +2595,7 @@ PyArrayObject *ret; PyTypeObject *subtype; double prior1, prior2; - /* Need to choose an output array that can hold a sum + /* Need to choose an output array that can hold a sum -- use priority to determine which subtype. */ if (ap2->ob_type != ap1->ob_type) { @@ -2608,21 +2608,21 @@ subtype = ap1->ob_type; } - ret = (PyArrayObject *)PyArray_New(subtype, nd, dimensions, - typenum, NULL, NULL, 0, 0, + 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 +/* Could perhaps be redone to not make contiguous arrays */ /*MULTIARRAY_API Numeric.innerproduct(a,v) */ static PyObject * -PyArray_InnerProduct(PyObject *op1, PyObject *op2) +PyArray_InnerProduct(PyObject *op1, PyObject *op2) { PyArrayObject *ap1, *ap2, *ret=NULL; PyArrayIterObject *it1, *it2; @@ -2636,18 +2636,18 @@ NPY_BEGIN_THREADS_DEF - typenum = PyArray_ObjectType(op1, 0); + 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, + 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->\ @@ -2656,14 +2656,14 @@ 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; ind-1; i++) { @@ -2674,21 +2674,21 @@ } - /* Need to choose an output array that can hold a sum + /* 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, + PyErr_SetString(PyExc_ValueError, "dot not available for this type"); goto fail; } - - is1 = ap1->strides[ap1->nd-1]; + + is1 = ap1->strides[ap1->nd-1]; is2 = ap2->strides[ap2->nd-1]; op = ret->data; os = ret->descr->elsize; @@ -2699,7 +2699,7 @@ it2 = (PyArrayIterObject *)\ PyArray_IterAllButAxis((PyObject *)ap2, &axis); - NPY_BEGIN_THREADS_DESCR(ap2->descr) + NPY_BEGIN_THREADS_DESCR(ap2->descr) while(1) { while(it2->index < it2->size) { dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret); @@ -2715,12 +2715,12 @@ Py_DECREF(it2); if (PyErr_Occurred()) goto fail; - - + + Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; - + fail: Py_XDECREF(ap1); Py_XDECREF(ap2); @@ -2734,7 +2734,7 @@ Numeric.matrixproduct(a,v) */ static PyObject * -PyArray_MatrixProduct(PyObject *op1, PyObject *op2) +PyArray_MatrixProduct(PyObject *op1, PyObject *op2) { PyArrayObject *ap1, *ap2, *ret=NULL; PyArrayIterObject *it1, *it2; @@ -2748,18 +2748,18 @@ NPY_BEGIN_THREADS_DEF - typenum = PyArray_ObjectType(op1, 0); - typenum = PyArray_ObjectType(op2, typenum); - + 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, + 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->\ @@ -2768,7 +2768,7 @@ Py_DECREF(ap2); return (PyObject *)ret; } - + l = ap1->dimensions[ap1->nd-1]; if (ap2->nd > 1) { matchDim = ap2->nd - 2; @@ -2781,7 +2781,7 @@ PyErr_SetString(PyExc_ValueError, "objects are not aligned"); goto fail; } - + nd = ap1->nd+ap2->nd-2; j = 0; for(i=0; ind-1; i++) { @@ -2795,9 +2795,9 @@ } /* fprintf(stderr, "nd=%d dimensions=", nd); - for(i=0; istrides[ap1->nd-1]; is2 = ap2->strides[matchDim]; @@ -2817,11 +2817,11 @@ dot = ret->descr->f->dotfunc; if (dot == NULL) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "dot not available for this type"); goto fail; } - + op = ret->data; os = ret->descr->elsize; axis = ap1->nd-1; @@ -2830,7 +2830,7 @@ it2 = (PyArrayIterObject *)\ PyArray_IterAllButAxis((PyObject *)ap2, &matchDim); - NPY_BEGIN_THREADS_DESCR(ap2->descr) + NPY_BEGIN_THREADS_DESCR(ap2->descr) while(1) { while(it2->index < it2->size) { dot(it1->dataptr, is1, it2->dataptr, is2, op, l, ret); @@ -2849,7 +2849,7 @@ Py_DECREF(ap1); Py_DECREF(ap2); return (PyObject *)ret; - + fail: Py_XDECREF(ap1); Py_XDECREF(ap2); @@ -2861,7 +2861,7 @@ Fast Copy and Transpose */ static PyObject * -PyArray_CopyAndTranspose(PyObject *op) +PyArray_CopyAndTranspose(PyObject *op) { PyObject *ret, *arr; int nd; @@ -2877,11 +2877,11 @@ if (nd == 1) { /* we will give in to old behavior */ ret = PyArray_Copy((PyArrayObject *)arr); Py_DECREF(arr); - return ret; + return ret; } else if (nd != 2) { Py_DECREF(arr); - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "only 2-d arrays are allowed"); return NULL; } @@ -2890,11 +2890,11 @@ 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, + ret = PyArray_NewFromDescr(arr->ob_type, PyArray_DESCR(arr), - 2, dims, + 2, dims, NULL, NULL, 0, arr); if (ret == NULL) { @@ -2918,12 +2918,12 @@ Py_DECREF(arr); return ret; } - + /*MULTIARRAY_API Numeric.correlate(a1,a2,mode) */ static PyObject * -PyArray_Correlate(PyObject *op1, PyObject *op2, int mode) +PyArray_Correlate(PyObject *op1, PyObject *op2, int mode) { PyArrayObject *ap1, *ap2, *ret=NULL; intp length; @@ -2935,10 +2935,10 @@ PyArray_Descr *typec; NPY_BEGIN_THREADS_DEF - - typenum = PyArray_ObjectType(op1, 0); + + 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, @@ -2947,18 +2947,18 @@ 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; + 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: + case 0: length = length-n+1; n_left = n_right = 0; break; @@ -2972,20 +2972,20 @@ length = length+n-1; break; default: - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "mode must be 0, 1, or 2"); goto fail; } - /* Need to choose an output array that can hold a sum + /* 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, + PyErr_SetString(PyExc_ValueError, "function not available for this data type"); goto fail; } @@ -2994,7 +2994,7 @@ 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; idescr->type_num, out); Py_DECREF(arr); - return ret; + return ret; } /*MULTIARRAY_API @@ -3090,7 +3090,7 @@ ret = PyArray_GenericReduceFunction(arr, n_ops.minimum, axis, arr->descr->type_num, out); Py_DECREF(arr); - return ret; + return ret; } /*MULTIARRAY_API @@ -3132,7 +3132,7 @@ ArgMax */ static PyObject * -PyArray_ArgMax(PyArrayObject *op, int axis, PyArrayObject *out) +PyArray_ArgMax(PyArrayObject *op, int axis, PyArrayObject *out) { PyArrayObject *ap=NULL, *rp=NULL; PyArray_ArgFunc* arg_func; @@ -3143,7 +3143,7 @@ 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. @@ -3167,12 +3167,12 @@ } ap = (PyArrayObject *)\ - PyArray_ContiguousFromAny((PyObject *)op, + 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"); @@ -3182,7 +3182,7 @@ elsize = ap->descr->elsize; m = ap->dimensions[ap->nd-1]; if (m == 0) { - PyErr_SetString(MultiArrayError, + PyErr_SetString(MultiArrayError, "attempt to get argmax/argmin "\ "of an empty sequence??"); goto fail; @@ -3191,18 +3191,18 @@ if (!out) { rp = (PyArrayObject *)PyArray_New(ap->ob_type, ap->nd-1, ap->dimensions, PyArray_INTP, - NULL, NULL, 0, 0, + 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, + PyErr_SetString(PyExc_TypeError, "invalid shape for output array."); } rp = (PyArrayObject *)\ - PyArray_FromArray(out, + PyArray_FromArray(out, PyArray_DescrFromType(PyArray_INTP), NPY_CARRAY | NPY_UPDATEIFCOPY); if (rp == NULL) goto fail; @@ -3227,19 +3227,19 @@ rp = obj; } return (PyObject *)rp; - + fail: Py_DECREF(ap); Py_XDECREF(rp); return NULL; -} +} /*MULTIARRAY_API Take */ static PyObject * -PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, +PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, PyArrayObject *ret, NPY_CLIPMODE clipmode) { PyArrayObject *self, *indices; @@ -3247,16 +3247,16 @@ intp shape[MAX_DIMS]; char *src, *dest; int copyret=0; - + indices = ret = NULL; self = (PyAO *)_check_axis(self0, &axis, CARRAY); if (self == NULL) return NULL; - - indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, - PyArray_INTP, + + 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++) { @@ -3275,21 +3275,21 @@ } Py_INCREF(self->descr); if (!ret) { - ret = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type, + ret = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type, self->descr, - nd, shape, - NULL, NULL, 0, + nd, shape, + NULL, NULL, 0, (PyObject *)self); - + if (ret == NULL) goto fail; } else { PyArrayObject *obj; int flags = NPY_CARRAY | NPY_UPDATEIFCOPY; - if ((ret->nd != nd) || + if ((ret->nd != nd) || !PyArray_CompareLists(ret->dimensions, shape, nd)) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "bad shape in output array"); ret = NULL; Py_DECREF(self->descr); @@ -3299,16 +3299,16 @@ 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 + before the error is called */ flags |= NPY_ENSURECOPY; } obj = (PyArrayObject *)PyArray_FromArray(ret, self->descr, flags); if (obj != ret) copyret = 1; - ret = obj; + ret = obj; } - + max_item = self->dimensions[axis]; chunk = chunk * ret->descr->elsize; src = self->data; @@ -3321,7 +3321,7 @@ tmp = ((intp *)(indices->data))[j]; if (tmp < 0) tmp = tmp+max_item; if ((tmp < 0) || (tmp >= max_item)) { - PyErr_SetString(PyExc_IndexError, + PyErr_SetString(PyExc_IndexError, "index out of range "\ "for array"); goto fail; @@ -3338,7 +3338,7 @@ tmp = ((intp *)(indices->data))[j]; if (tmp < 0) while (tmp < 0) tmp += max_item; else if (tmp >= max_item) - while (tmp >= max_item) + while (tmp >= max_item) tmp -= max_item; memmove(dest, src+tmp*chunk, chunk); dest += chunk; @@ -3350,9 +3350,9 @@ for(i=0; idata))[j]; - if (tmp < 0) + if (tmp < 0) tmp = 0; - else if (tmp >= max_item) + else if (tmp >= max_item) tmp = max_item-1; memmove(dest, src+tmp*chunk, chunk); dest += chunk; @@ -3370,13 +3370,13 @@ PyObject *obj; obj = ret->base; Py_INCREF(obj); - Py_DECREF(ret); + Py_DECREF(ret); ret = (PyArrayObject *)obj; } return (PyObject *)ret; - - + + fail: PyArray_XDECREF_ERR(ret); Py_XDECREF(indices); @@ -3392,7 +3392,7 @@ NPY_CLIPMODE clipmode) { PyArrayObject *indices, *values; - int i, chunk, ni, max_item, nv, tmp, thistype; + int i, chunk, ni, max_item, nv, tmp, thistype; char *src, *dest; int copied = 0; @@ -3400,7 +3400,7 @@ values = NULL; if (!PyArray_Check(self)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "put: first argument must be an array"); return NULL; } @@ -3411,7 +3411,7 @@ flags |= NPY_ENSURECOPY; } Py_INCREF(self->descr); - obj = (PyArrayObject *)PyArray_FromArray(self, + obj = (PyArrayObject *)PyArray_FromArray(self, self->descr, flags); if (obj != self) copied = 1; self = obj; @@ -3420,19 +3420,19 @@ dest = self->data; chunk = self->descr->elsize; - indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, + indices = (PyArrayObject *)PyArray_ContiguousFromAny(indices0, PyArray_INTP, 0, 0); if (indices == NULL) goto fail; ni = PyArray_SIZE(indices); thistype = self->descr->type_num; - Py_INCREF(self->descr); - values = (PyArrayObject *)PyArray_FromAny(values0, self->descr, 0, 0, - DEFAULT | FORCECAST, NULL); + 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 (self->descr->hasobject) { + if (self->descr->hasobject) { switch(clipmode) { case NPY_RAISE: for(i=0; idata))[i]; if (tmp < 0) tmp = tmp+max_item; if ((tmp < 0) || (tmp >= max_item)) { - PyErr_SetString(PyExc_IndexError, + PyErr_SetString(PyExc_IndexError, "index out of " \ "range for array"); goto fail; @@ -3455,7 +3455,7 @@ 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) + else if (tmp >= max_item) while(tmp >= max_item) tmp -= max_item; PyArray_Item_INCREF(src, self->descr); @@ -3485,7 +3485,7 @@ tmp = ((intp *)(indices->data))[i]; if (tmp < 0) tmp = tmp+max_item; if ((tmp < 0) || (tmp >= max_item)) { - PyErr_SetString(PyExc_IndexError, + PyErr_SetString(PyExc_IndexError, "index out of " \ "range for array"); goto fail; @@ -3498,7 +3498,7 @@ 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) + else if (tmp >= max_item) while(tmp >= max_item) tmp -= max_item; memmove(dest + tmp * chunk, src, chunk); @@ -3517,7 +3517,7 @@ } } - finish: + finish: Py_XDECREF(values); Py_XDECREF(indices); if (copied) { @@ -3525,7 +3525,7 @@ } Py_INCREF(Py_None); return Py_None; - + fail: Py_XDECREF(indices); Py_XDECREF(values); @@ -3550,7 +3550,7 @@ values = NULL; if (!PyArray_Check(self)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "putmask: first argument must "\ "be an array"); return NULL; @@ -3559,7 +3559,7 @@ PyArrayObject *obj; int flags = NPY_CARRAY | NPY_UPDATEIFCOPY; Py_INCREF(self->descr); - obj = (PyArrayObject *)PyArray_FromArray(self, + obj = (PyArrayObject *)PyArray_FromArray(self, self->descr, flags); if (obj != self) copied = 1; self = obj; @@ -3574,7 +3574,7 @@ if (mask == NULL) goto fail; ni = PyArray_SIZE(mask); if (ni != max_item) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "putmask: mask and data must be "\ "the same size"); goto fail; @@ -3619,7 +3619,7 @@ } Py_INCREF(Py_None); return Py_None; - + fail: Py_XDECREF(mask); Py_XDECREF(values); @@ -3632,18 +3632,18 @@ /* This conversion function can be used with the "O&" argument for PyArg_ParseTuple. It will immediately return an object of array type - or will convert to a CARRAY any other object. + or will convert to a CARRAY any other object. If you use PyArray_Converter, you must DECREF the array when finished as you get a new reference to it. */ - + /*MULTIARRAY_API Useful to pass as converter function for O& processing in PyArgs_ParseTuple. */ -static int -PyArray_Converter(PyObject *object, PyObject **address) +static int +PyArray_Converter(PyObject *object, PyObject **address) { if (PyArray_Check(object)) { *address = object; @@ -3661,8 +3661,8 @@ Useful to pass as converter function for O& processing in PyArgs_ParseTuple for output arrays */ -static int -PyArray_OutputConverter(PyObject *object, PyArrayObject **address) +static int +PyArray_OutputConverter(PyObject *object, PyArrayObject **address) { if (object == NULL || object == Py_None) { *address = NULL; @@ -3673,7 +3673,7 @@ return PY_SUCCEED; } else { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "output must be an array"); *address = NULL; return PY_FAIL; @@ -3686,7 +3686,7 @@ */ static int PyArray_BoolConverter(PyObject *object, Bool *val) -{ +{ if (PyObject_IsTrue(object)) *val=TRUE; else *val=FALSE; @@ -3717,7 +3717,7 @@ else { str = PyString_AS_STRING(object); if (str[0] == 'C' || str[0] == 'c') { - *val = PyArray_CORDER; + *val = PyArray_CORDER; } else if (str[0] == 'F' || str[0] == 'f') { *val = PyArray_FORTRANORDER; @@ -3726,7 +3726,7 @@ *val = PyArray_ANYORDER; } else { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "order not understood"); return PY_FAIL; } @@ -3747,7 +3747,7 @@ char *str; str = PyString_AS_STRING(object); if (str[0] == 'C' || str[0] == 'c') { - *val = NPY_CLIP; + *val = NPY_CLIP; } else if (str[0] == 'W' || str[0] == 'w') { *val = NPY_WRAP; @@ -3769,7 +3769,7 @@ number >= (int) NPY_CLIP) *val = (NPY_CLIPMODE) number; else goto fail; - } + } return PY_SUCCEED; fail: @@ -3787,11 +3787,11 @@ PyArray_TypestrConvert(int itemsize, int gentype) { register int newtype = gentype; - + if (gentype == PyArray_GENBOOLLTR) { if (itemsize == 1) newtype = PyArray_BOOL; - else + else newtype = PyArray_NOTYPE; } else if (gentype == PyArray_SIGNEDLTR) { @@ -3859,7 +3859,7 @@ case 12: newtype = PyArray_FLOAT96; break; -#endif +#endif #ifdef PyArray_FLOAT128 case 16: newtype = PyArray_FLOAT128; @@ -3867,9 +3867,9 @@ #endif default: newtype = PyArray_NOTYPE; - } + } } - + else if (gentype == PyArray_COMPLEXLTR) { switch(itemsize) { case 8: @@ -3885,9 +3885,9 @@ #endif #ifdef PyArray_FLOAT96 case 24: - newtype = PyArray_COMPLEX192; + newtype = PyArray_COMPLEX192; break; -#endif +#endif #ifdef PyArray_FLOAT128 case 32: newtype = PyArray_COMPLEX256; @@ -3895,7 +3895,7 @@ #endif default: newtype = PyArray_NOTYPE; - } + } } return newtype; @@ -3904,7 +3904,7 @@ /* this function takes a Python object which exposes the (single-segment) buffer interface and returns a pointer to the data segment - + You should increment the reference count by one of buf->base if you will hang on to a reference @@ -3931,17 +3931,17 @@ if (PyObject_AsWriteBuffer(obj, &(buf->ptr), &buflen) < 0) { PyErr_Clear(); buf->flags &= ~WRITEABLE; - if (PyObject_AsReadBuffer(obj, (const void **)&(buf->ptr), + 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; - - return PY_SUCCEED; + + return PY_SUCCEED; } @@ -3969,7 +3969,7 @@ if (PyNumber_Check(obj)) len = 1; } if (len < 0) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "expected sequence object with len >= 0"); return PY_FAIL; } @@ -3996,26 +3996,26 @@ } -/* A tuple type would be either (generic typeobject, typesize) - or (fixed-length data-type, shape) +/* A tuple type would be either (generic typeobject, typesize) + or (fixed-length data-type, shape) or (inheriting data-type, new-data-type) The new data-type must have the same itemsize as the inheriting data-type - unless the latter is 0 - + unless the latter is 0 + Thus (int32, {'real':(int16,0),'imag',(int16,2)}) - is one way to specify a descriptor that will give + is one way to specify a descriptor that will give a['real'] and a['imag'] to an int32 array. */ /* leave type reference alone */ static PyArray_Descr * -_use_inherit(PyArray_Descr *type, PyObject *newobj, int *errflag) +_use_inherit(PyArray_Descr *type, PyObject *newobj, int *errflag) { PyArray_Descr *new; PyArray_Descr *conv; - + *errflag = 0; if (!PyArray_DescrConverter(newobj, &conv)) { return NULL; @@ -4025,7 +4025,7 @@ if (new == NULL) goto fail; if (new->elsize && new->elsize != conv->elsize) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "mismatch in size of old "\ "and new data-descriptor"); goto fail; @@ -4050,15 +4050,15 @@ } static PyArray_Descr * -_convert_from_tuple(PyObject *obj) +_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)) + 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 */ @@ -4077,28 +4077,28 @@ int itemsize; itemsize = PyArray_PyIntAsInt(PyTuple_GET_ITEM(obj,1)); if (error_converting(itemsize)) { - PyErr_SetString(PyExc_ValueError, + 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; + 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. + 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)) || + if (!(PyArray_IntpConverter(val, &shape)) || (shape.len > MAX_DIMS)) { PyDimMem_FREE(shape.ptr); - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "invalid shape in fixed-type tuple."); goto fail; } @@ -4111,7 +4111,7 @@ newdescr = PyArray_DescrNewFromType(PyArray_VOID); if (newdescr == NULL) {PyDimMem_FREE(shape.ptr); goto fail;} newdescr->elsize = type->elsize; - newdescr->elsize *= PyArray_MultiplyList(shape.ptr, + newdescr->elsize *= PyArray_MultiplyList(shape.ptr, shape.len); PyDimMem_FREE(shape.ptr); newdescr->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr)); @@ -4134,7 +4134,7 @@ /* obj is a list. Each item is a tuple with -(field-name, data-type (either a list or a string), and an optional +(field-name, data-type (either a list or a string), and an optional shape parameter). */ static PyArray_Descr * @@ -4148,8 +4148,8 @@ PyArray_Descr *new; PyArray_Descr *conv; int hasobject=0; - - n = PyList_GET_SIZE(obj); + + n = PyList_GET_SIZE(obj); nameslist = PyTuple_New(n); if (!nameslist) return NULL; totalsize = 0; @@ -4171,7 +4171,7 @@ } else goto fail; if (PyString_GET_SIZE(name)==0) { - if (title==NULL) + if (title==NULL) name = PyString_FromFormat("f%d", i); else { name = title; @@ -4183,9 +4183,9 @@ } PyTuple_SET_ITEM(nameslist, i, name); if (PyTuple_GET_SIZE(item) == 2) { - ret = PyArray_DescrConverter(PyTuple_GET_ITEM(item, 1), + ret = PyArray_DescrConverter(PyTuple_GET_ITEM(item, 1), &conv); - if (ret == PY_FAIL) + if (ret == PY_FAIL) PyObject_Print(PyTuple_GET_ITEM(item,1), stderr, 0); } @@ -4197,8 +4197,8 @@ else goto fail; if (ret == PY_FAIL) goto fail; if ((PyDict_GetItem(fields, name) != NULL) || - (title && - (PyString_Check(title) || PyUnicode_Check(title)) && + (title && + (PyString_Check(title) || PyUnicode_Check(title)) && (PyDict_GetItem(fields, title) != NULL))) { PyErr_SetString(PyExc_ValueError, "two fields with the same name"); @@ -4213,10 +4213,10 @@ /* Title can be "meta-data". Only insert it into the fields dictionary if it is a string */ - if (title != NULL) { + if (title != NULL) { Py_INCREF(title); PyTuple_SET_ITEM(tup, 2, title); - if (PyString_Check(title) || PyUnicode_Check(title)) + if (PyString_Check(title) || PyUnicode_Check(title)) PyDict_SetItem(fields, title, tup); } PyDict_SetItem(fields, name, tup); @@ -4229,7 +4229,7 @@ new->elsize = totalsize; new->hasobject=hasobject; return new; - + fail: Py_DECREF(fields); Py_DECREF(nameslist); @@ -4242,7 +4242,7 @@ will default to f0, f1, f2, and so forth. or it can be an array_descr format string -- in which case - align must be 0. + align must be 0. */ static PyArray_Descr * @@ -4258,13 +4258,13 @@ int ret; int maxalign=0; int hasobject=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.*/ + /* End ignore code.*/ totalsize = 0; if (n==0) return NULL; nameslist = PyTuple_New(n); @@ -4280,7 +4280,7 @@ goto fail; } if (!hasobject && conv->hasobject) - hasobject=1; + hasobject=1; PyTuple_SET_ITEM(tup, 0, (PyObject *)conv); if (align) { int _align; @@ -4316,9 +4316,9 @@ /* comma-separated string */ /* this is the format developed by the numarray records module */ /* and implemented by the format parser in that module */ -/* this is an alternative implementation found in the _internal.py - file patterned after that one -- the approach is to try to convert - to a list (with tuples if any repeat information is present) +/* this is an alternative implementation found in the _internal.py + file patterned after that one -- the approach is to try to convert + to a list (with tuples if any repeat information is present) and then call the _convert_from_list) */ @@ -4360,42 +4360,42 @@ must have at least two and up to four keys These must all be sequences of the same length. - "names" --- field names + "names" --- field names "formats" --- the data-type descriptors for the field. - + Optional: - "offsets" --- integers indicating the offset into the + "offsets" --- integers indicating the offset into the record of the start of the field. - if not given, then "consecutive offsets" + 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 + 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 + 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. So, the notion of what is a name and what is a title is really quite -arbitrary. +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. +then it will be checked for conformity and used directly. */ static PyArray_Descr * _use_fields_dict(PyObject *obj, int align) { - return (PyArray_Descr *)PyObject_CallMethod(_numpy_internal, - "_usefields", + return (PyArray_Descr *)PyObject_CallMethod(_numpy_internal, + "_usefields", "Oi", obj, align); } @@ -4409,10 +4409,10 @@ int totalsize; int maxalign=0; int hasobject=0; - + fields = PyDict_New(); if (fields == NULL) return (PyArray_Descr *)PyErr_NoMemory(); - + names = PyDict_GetItemString(obj, "names"); descrs = PyDict_GetItemString(obj, "formats"); @@ -4484,7 +4484,7 @@ name = PyObject_GetItem(names, index); Py_DECREF(index); if (!(PyString_Check(name) || PyUnicode_Check(name))) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "field names must be strings"); ret = PY_FAIL; } @@ -4500,7 +4500,7 @@ if (len == 3) { if ((PyString_Check(item) || PyUnicode_Check(item)) && \ PyDict_GetItem(fields, item) != NULL) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "title already used as a "\ "name or title."); ret=PY_FAIL; @@ -4543,25 +4543,25 @@ { int i; - if ((type[0] >= '0' && type[0] <= '9') || + if ((type[0] >= '0' && type[0] <= '9') || ((len > 1) && (type[0] == '>' || type[0] == '<' || \ type[0] == '|' || type[0] == '=') && \ (type[1] >= '0' && type[1] <= '9'))) return 1; for (i=1;i= size computed from fields - - The .fields attribute must return a convertible dictionary if + + The .fields attribute must return a convertible dictionary if present. Result inherits from PyArray_VOID. */ @@ -4579,13 +4579,13 @@ else return PyArray_DescrConverter(obj, at); } -/* This function takes a Python object representing a type and converts it +/* This function takes a Python object representing a type and converts it to a the correct PyArray_Descr * structure to describe the type. - + Many objects can be used to represent a data-type which in NumPy is - quite a flexible concept. + quite a flexible concept. - This is the central code that converts Python objects to + This is the central code that converts Python objects to Type-descriptor objects that are used throughout numpy. */ @@ -4604,21 +4604,21 @@ 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, + if (PyType_IsSubtype((PyTypeObject *)obj, &PyGenericArrType_Type)) { *at = PyArray_DescrFromTypeObject(obj); if (*at) return PY_SUCCEED; @@ -4629,9 +4629,9 @@ check_num = PyArray_LONG; else if (obj == (PyObject *)(&PyLong_Type)) check_num = PyArray_LONGLONG; - else if (obj == (PyObject *)(&PyFloat_Type)) + else if (obj == (PyObject *)(&PyFloat_Type)) check_num = PyArray_DOUBLE; - else if (obj == (PyObject *)(&PyComplex_Type)) + else if (obj == (PyObject *)(&PyComplex_Type)) check_num = PyArray_CDOUBLE; else if (obj == (PyObject *)(&PyBool_Type)) check_num = PyArray_BOOL; @@ -4656,7 +4656,7 @@ len = PyString_GET_SIZE(obj); if (len <= 0) goto fail; - /* check for commas present + /* check for commas present or first (or second) element a digit */ if (_check_for_commastring(type, len)) { *at = _convert_from_commastring(obj, 0); @@ -4678,7 +4678,7 @@ check_num = PyArray_NOTYPE+10; } /* When specifying length of UNICODE - the number of characters is given to match + 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. @@ -4686,7 +4686,7 @@ else if (check_num == PyArray_UNICODELTR) { elsize <<= 2; } - /* Support for generic processing + /* Support for generic processing c4, i4, f8, etc... */ else if ((check_num != PyArray_STRINGLTR) && \ @@ -4752,27 +4752,27 @@ } goto fail; } - + if (((*at)->elsize == 0) && (elsize != 0)) { PyArray_DESCR_REPLACE(*at); (*at)->elsize = elsize; } - if (endian != '=' && PyArray_ISNBO(endian)) endian = '='; - + 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, + PyErr_SetString(PyExc_TypeError, "data type not understood"); *at=NULL; return PY_FAIL; -} +} /*MULTIARRAY_API Convert object to endian @@ -4785,7 +4785,7 @@ str = PyString_AsString(obj); if (!str) return PY_FAIL; if (strlen(str) < 1) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "Byteorder string must be at least length 1"); return PY_FAIL; } @@ -4803,7 +4803,7 @@ else if (str[0] == 's' || str[0] == 'S') *endian = PyArray_SWAP; else { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "%s is an unrecognized byteorder", str); return PY_FAIL; @@ -4813,7 +4813,7 @@ } /*MULTIARRAY_API - Convert object to sort kind + Convert object to sort kind */ static int PyArray_SortkindConverter(PyObject *obj, NPY_SORTKIND *sortkind) @@ -4823,7 +4823,7 @@ str = PyString_AsString(obj); if (!str) return PY_FAIL; if (strlen(str) < 1) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "Sort kind string must be at least length 1"); return PY_FAIL; } @@ -4834,7 +4834,7 @@ else if (str[0] == 'm' || str[0] == 'M') *sortkind = PyArray_MERGESORT; else { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "%s is an unrecognized kind of sort", str); return PY_FAIL; @@ -4844,14 +4844,14 @@ /* compare the field dictionary for two types - return 1 if the same or 0 if not + return 1 if the same or 0 if not */ static int _equivalent_fields(PyObject *field1, PyObject *field2) { int same, val; - + if (field1 == field2) return 1; if (field1 == NULL || field2 == NULL) return 0; val = PyObject_Compare(field1, field2); @@ -4861,7 +4861,7 @@ return same; } -/* This function returns true if the two typecodes are +/* This function returns true if the two typecodes are equivalent (same basic kind and same itemsize). */ @@ -4881,7 +4881,7 @@ if (typenum1 == PyArray_VOID || \ typenum2 == PyArray_VOID) { - return ((typenum1 == typenum2) && + return ((typenum1 == typenum2) && (typ1->typeobj == typ2->typeobj) && _equivalent_fields(typ1->fields, typ2->fields)); } @@ -4945,7 +4945,7 @@ _array_fromobject(PyObject *ignored, PyObject *args, PyObject *kws) { PyObject *op, *ret=NULL; - static char *kwd[]= {"object", "dtype", "copy", "order", "subok", + static char *kwd[]= {"object", "dtype", "copy", "order", "subok", "ndmin", NULL}; Bool subok=FALSE; Bool copy=TRUE; @@ -4956,22 +4956,22 @@ int flags=0; if (PyTuple_GET_SIZE(args) > 2) { - PyErr_SetString(PyExc_ValueError, + 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, + if(!PyArg_ParseTupleAndKeywords(args, kws, "O|O&O&O&O&i", kwd, &op, PyArray_DescrConverter2, - &type, - PyArray_BoolConverter, ©, + &type, + PyArray_BoolConverter, ©, PyArray_OrderConverter, &order, - PyArray_BoolConverter, &subok, - &ndmin)) + PyArray_BoolConverter, &subok, + &ndmin)) return NULL; /* fast exit if simple call */ - if ((subok && PyArray_Check(op)) || + if ((subok && PyArray_Check(op)) || (!subok && PyArray_CheckExact(op))) { if (type==NULL) { if (!copy && STRIDING_OK(op, order)) { @@ -4980,7 +4980,7 @@ goto finish; } else { - ret = PyArray_NewCopy((PyArrayObject*)op, + ret = PyArray_NewCopy((PyArrayObject*)op, order); goto finish; } @@ -5011,7 +5011,7 @@ if (order == PyArray_CORDER) { flags |= CONTIGUOUS; } - else if ((order == PyArray_FORTRANORDER) || + else if ((order == PyArray_FORTRANORDER) || /* order == PyArray_ANYORDER && */ (PyArray_Check(op) && PyArray_ISFORTRAN(op))) { flags |= FORTRAN; @@ -5038,14 +5038,14 @@ PyArray_Empty(int nd, intp *dims, PyArray_Descr *type, int fortran) { PyArrayObject *ret; - + if (!type) type = PyArray_DescrFromType(PyArray_DEFAULT); - ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, - type, nd, dims, + ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, + type, nd, dims, NULL, NULL, fortran, NULL); if (ret == NULL) return NULL; - + if (type->hasobject) { PyArray_FillObjectArray(ret, Py_None); if (PyErr_Occurred()) {Py_DECREF(ret); return NULL;} @@ -5054,28 +5054,28 @@ } static PyObject * -array_empty(PyObject *ignored, PyObject *args, PyObject *kwds) +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; + NPY_ORDER order = PyArray_CORDER; Bool fortran; PyObject *ret=NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&", kwlist, PyArray_IntpConverter, - &shape, + &shape, PyArray_DescrConverter, - &typecode, - PyArray_OrderConverter, &order)) + &typecode, + PyArray_OrderConverter, &order)) goto fail; if (order == PyArray_FORTRANORDER) fortran = TRUE; else fortran = FALSE; - ret = PyArray_Empty(shape.len, shape.ptr, typecode, fortran); + ret = PyArray_Empty(shape.len, shape.ptr, typecode, fortran); PyDimMem_FREE(shape.ptr); return ret; @@ -5085,9 +5085,9 @@ } static PyObject * -array_scalar(PyObject *ignored, PyObject *args, PyObject *kwds) +array_scalar(PyObject *ignored, PyObject *args, PyObject *kwds) { - + static char *kwlist[] = {"dtype","obj", NULL}; PyArray_Descr *typecode; PyObject *obj=NULL; @@ -5095,13 +5095,13 @@ void *dptr; PyObject *ret; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|O", - kwlist, &PyArrayDescr_Type, + kwlist, &PyArrayDescr_Type, &typecode, - &obj)) + &obj)) return NULL; - + if (typecode->elsize == 0) { PyErr_SetString(PyExc_ValueError, \ "itemsize cannot be zero"); @@ -5123,7 +5123,7 @@ } else { if (!PyString_Check(obj)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "initializing object must "\ "be a string"); return NULL; @@ -5139,7 +5139,7 @@ } ret = PyArray_Scalar(dptr, typecode, NULL); - + /* free dptr which contains zeros */ if (alloc) _pya_free(dptr); return ret; @@ -5158,13 +5158,13 @@ intp n; if (!type) type = PyArray_DescrFromType(PyArray_DEFAULT); - ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, + ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, type, - nd, dims, - NULL, NULL, + nd, dims, + NULL, NULL, fortran, NULL); if (ret == NULL) return NULL; - + if (type->hasobject) { PyObject *zero = PyInt_FromLong(0); PyArray_FillObjectArray(ret, zero); @@ -5180,22 +5180,22 @@ } static PyObject * -array_zeros(PyObject *ignored, PyObject *args, PyObject *kwds) +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; + Bool fortran = FALSE; PyObject *ret=NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&", kwlist, PyArray_IntpConverter, - &shape, + &shape, PyArray_DescrConverter, - &typecode, + &typecode, PyArray_OrderConverter, - &order)) + &order)) goto fail; if (order == PyArray_FORTRANORDER) fortran = TRUE; @@ -5238,7 +5238,7 @@ /* steals a reference to dtype -- accepts NULL */ /*OBJECT_API*/ static PyObject * -PyArray_FromString(char *data, intp slen, PyArray_Descr *dtype, +PyArray_FromString(char *data, intp slen, PyArray_Descr *dtype, intp n, char *sep) { int itemsize; @@ -5250,13 +5250,13 @@ dtype=PyArray_DescrFromType(PyArray_DEFAULT); if (dtype->hasobject) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "Cannot create an object array from" \ " a string"); Py_DECREF(dtype); return NULL; - } - + } + itemsize = dtype->elsize; if (itemsize == 0) { PyErr_SetString(PyExc_ValueError, "zero-valued itemsize"); @@ -5264,12 +5264,12 @@ return NULL; } - binary = ((sep == NULL) || (strlen(sep) == 0)); + binary = ((sep == NULL) || (strlen(sep) == 0)); if (binary) { if (n < 0 ) { if (slen % itemsize != 0) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "string size must be a "\ "multiple of element size"); Py_DECREF(dtype); @@ -5278,24 +5278,24 @@ n = slen/itemsize; } else { if (slen < n*itemsize) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "string is smaller than " \ "requested size"); Py_DECREF(dtype); return NULL; } } - + if ((ret = (PyArrayObject *)\ PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &n, NULL, NULL, 0, NULL)) == NULL) - return NULL; + return NULL; memcpy(ret->data, data, n*dtype->elsize); return (PyObject *)ret; } else { /* read from character-based string */ - char *ptr; + char *ptr; PyArray_FromStrFunc *fromstr; char *dptr; intp nread=0; @@ -5303,7 +5303,7 @@ fromstr = dtype->f->fromstr; if (fromstr == NULL) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "don't know how to read " \ "character strings for given " \ "array type"); @@ -5325,19 +5325,19 @@ break; nread += 1; dptr += dtype->elsize; - if (_skip_sep(&ptr, sep) < 0) + if (_skip_sep(&ptr, sep) < 0) break; } if (nread < n) { fprintf(stderr, "%ld items requested but "\ - "only %ld read\n", + "only %ld read\n", (long) n, (long) nread); ret->data = \ - PyDataMem_RENEW(ret->data, + PyDataMem_RENEW(ret->data, nread * \ ret->descr->elsize); PyArray_DIM(ret,0) = nread; - + } NPY_END_ALLOW_THREADS } @@ -5351,10 +5351,10 @@ int val; ret = (PyArrayObject *)\ - PyArray_NewFromDescr(&PyArray_Type, + PyArray_NewFromDescr(&PyArray_Type, dtype, - 1, &size, - NULL, NULL, + 1, &size, + NULL, NULL, 0, NULL); if (ret==NULL) return NULL; NPY_BEGIN_ALLOW_THREADS @@ -5372,14 +5372,14 @@ dptr += dtype->elsize; if (thisbuf == size) { totalbytes += bytes; - ret->data = PyDataMem_RENEW(ret->data, + ret->data = PyDataMem_RENEW(ret->data, totalbytes); dptr = ret->data + \ (totalbytes - bytes); thisbuf = 0; } } - ret->data = PyDataMem_RENEW(ret->data, + ret->data = PyDataMem_RENEW(ret->data, nread*ret->descr->elsize); PyArray_DIM(ret,0) = nread; #undef _FILEBUFNUM @@ -5399,9 +5399,9 @@ 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, + if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&" + NPY_SSIZE_T_PYFMT "s", kwlist, + &data, &s, PyArray_DescrConverter, &descr, &nin, &sep)) { return NULL; @@ -5426,9 +5426,9 @@ elcount = (count < 0) ? 0 : count; elsize = dtype->elsize; - + /* We would need to alter the memory RENEW code to decrement any - reference counts before just throwing away the memory. + reference counts before just throwing away the memory. */ if (dtype->hasobject) { PyErr_SetString(PyExc_ValueError, "cannot create "\ @@ -5441,11 +5441,11 @@ dtype = NULL; if (ret == NULL) goto done; - for (i = 0; (i < count || count == -1) && + 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 ... @@ -5456,7 +5456,7 @@ else new_data = NULL; if (new_data == NULL) { - PyErr_SetString(PyExc_MemoryError, + PyErr_SetString(PyExc_MemoryError, "cannot allocate array memory"); Py_DECREF(value); goto done; @@ -5508,9 +5508,9 @@ static char *kwlist[] = {"iter", "dtype", "count", NULL}; PyArray_Descr *descr=NULL; - if (!PyArg_ParseTupleAndKeywords(args, keywds, - "OO&|" NPY_SSIZE_T_PYFMT, - kwlist, + if (!PyArg_ParseTupleAndKeywords(args, keywds, + "OO&|" NPY_SSIZE_T_PYFMT, + kwlist, &iter, PyArray_DescrConverter, &descr, &nin)) { @@ -5523,10 +5523,10 @@ -/* This needs an open file object and reads it in directly. +/* This needs an open file object and reads it in directly. memory-mapped files handled differently through buffer interface. -file pointer number in resulting 1d array +file pointer number in resulting 1d array (can easily reshape later, -1 for to end of file) type of array sep is a separator string for character-based data (or NULL for binary) @@ -5566,19 +5566,19 @@ numbytes -= start; if (fseek(fp, start, SEEK_SET) < 0) fail=1; if (fail) { - PyErr_SetString(PyExc_IOError, + PyErr_SetString(PyExc_IOError, "could not seek in file"); Py_DECREF(typecode); return NULL; } num = numbytes / typecode->elsize; } - + if (binary) { /* binary data */ - r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, + r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, typecode, - 1, &num, - NULL, NULL, + 1, &num, + NULL, NULL, 0, NULL); if (r==NULL) return NULL; NPY_BEGIN_ALLOW_THREADS @@ -5592,7 +5592,7 @@ scan = typecode->f->scanfunc; if (scan == NULL) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "don't know how to read " \ "character files with that " \ "array type"); @@ -5602,13 +5602,13 @@ if (num != -1) { /* number to read is known */ r = (PyArrayObject *)\ - PyArray_NewFromDescr(&PyArray_Type, - typecode, - 1, &num, - NULL, NULL, + PyArray_NewFromDescr(&PyArray_Type, + typecode, + 1, &num, + NULL, NULL, 0, NULL); if (r==NULL) return NULL; - NPY_BEGIN_ALLOW_THREADS + NPY_BEGIN_ALLOW_THREADS dptr = r->data; for (i=0; i < num; i++) { if (done) break; @@ -5617,13 +5617,13 @@ nread += 1; dptr += r->descr->elsize; } - NPY_END_ALLOW_THREADS + NPY_END_ALLOW_THREADS if (PyErr_Occurred()) { Py_DECREF(r); return NULL; } } - else { /* we have to watch for the end of the file and + else { /* we have to watch for the end of the file and reallocate at the end */ #define _FILEBUFNUM 4096 intp thisbuf=0; @@ -5632,19 +5632,19 @@ intp totalbytes; r = (PyArrayObject *)\ - PyArray_NewFromDescr(&PyArray_Type, + PyArray_NewFromDescr(&PyArray_Type, typecode, - 1, &size, - NULL, NULL, + 1, &size, + NULL, NULL, 0, NULL); if (r==NULL) return NULL; - NPY_BEGIN_ALLOW_THREADS + NPY_BEGIN_ALLOW_THREADS totalbytes = bytes = size * typecode->elsize; dptr = r->data; while (!done) { done = scan(fp, dptr, sep, NULL); - /* end of file reached trying to + /* end of file reached trying to scan value. done is 1 or 2 if end of file reached trying to scan separator. Still good value. @@ -5655,7 +5655,7 @@ dptr += r->descr->elsize; if (!done && thisbuf == size) { totalbytes += bytes; - r->data = PyDataMem_RENEW(r->data, + r->data = PyDataMem_RENEW(r->data, totalbytes); dptr = r->data + (totalbytes - bytes); thisbuf = 0; @@ -5674,7 +5674,7 @@ } if (((intp) nread) < num) { - fprintf(stderr, "%ld items requested but only %ld read\n", + fprintf(stderr, "%ld items requested but only %ld read\n", (long) num, (long) nread); r->data = PyDataMem_RENEW(r->data, nread * r->descr->elsize); PyArray_DIM(r,0) = nread; @@ -5691,10 +5691,10 @@ 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, + + if (!PyArg_ParseTupleAndKeywords(args, keywds, + "O|O&" NPY_SSIZE_T_PYFMT "s", + kwlist, &file, PyArray_DescrConverter, &type, &nin, &sep)) { @@ -5713,7 +5713,7 @@ } fp = PyFile_AsFile(file); if (fp == NULL) { - PyErr_SetString(PyExc_IOError, + PyErr_SetString(PyExc_IOError, "first argument must be an open file"); Py_DECREF(file); return NULL; @@ -5725,8 +5725,8 @@ /*OBJECT_API*/ static PyObject * -PyArray_FromBuffer(PyObject *buf, PyArray_Descr *type, - intp count, intp offset) +PyArray_FromBuffer(PyObject *buf, PyArray_Descr *type, + intp count, intp offset) { PyArrayObject *ret; char *data; @@ -5737,17 +5737,17 @@ if (type->hasobject) { - PyErr_SetString(PyExc_ValueError, + 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, + PyErr_SetString(PyExc_ValueError, "itemsize cannot be zero in type"); Py_DECREF(type); - return NULL; + return NULL; } if (buf->ob_type->tp_as_buffer == NULL || \ @@ -5769,7 +5769,7 @@ return NULL; } } - + if ((offset < 0) || (offset >= ts)) { PyErr_Format(PyExc_ValueError, "offset must be positive and smaller than %" @@ -5780,10 +5780,10 @@ s = (intp)ts - offset; n = (intp)count; itemsize = type->elsize; - + if (n < 0 ) { if (s % itemsize != 0) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "buffer size must be a multiple"\ " of element size"); Py_DECREF(buf); @@ -5793,7 +5793,7 @@ n = s/itemsize; } else { if (s < n*itemsize) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "buffer is smaller than requested"\ " size"); Py_DECREF(buf); @@ -5801,17 +5801,17 @@ return NULL; } } - - if ((ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, - type, - 1, &n, - NULL, data, + + 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 */ @@ -5829,8 +5829,8 @@ PyArray_Descr *type=NULL; if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|O&" - NPY_SSIZE_T_PYFMT - NPY_SSIZE_T_PYFMT, kwlist, + NPY_SSIZE_T_PYFMT + NPY_SSIZE_T_PYFMT, kwlist, &obj, PyArray_DescrConverter, &type, &nin, &offset)) { @@ -5838,17 +5838,17 @@ } if (type==NULL) type = PyArray_DescrFromType(PyArray_DEFAULT); - + return PyArray_FromBuffer(obj, type, (intp)nin, (intp)offset); } static PyObject * -array_concatenate(PyObject *dummy, PyObject *args, PyObject *kwds) +array_concatenate(PyObject *dummy, PyObject *args, PyObject *kwds) { PyObject *a0; int axis=0; static char *kwlist[] = {"seq", "axis", NULL}; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&", kwlist, &a0, PyArray_AxisConverter, &axis)) @@ -5858,25 +5858,25 @@ static PyObject *array_innerproduct(PyObject *dummy, PyObject *args) { PyObject *b0, *a0; - + if (!PyArg_ParseTuple(args, "OO", &a0, &b0)) return NULL; - + return _ARET(PyArray_InnerProduct(a0, b0)); } static PyObject *array_matrixproduct(PyObject *dummy, PyObject *args) { PyObject *v, *a; - + if (!PyArg_ParseTuple(args, "OO", &a, &v)) return NULL; - + return _ARET(PyArray_MatrixProduct(a, v)); } static PyObject *array_fastCopyAndTranspose(PyObject *dummy, PyObject *args) { PyObject *a0; - + if (!PyArg_ParseTuple(args, "O", &a0)) return NULL; - + return _ARET(PyArray_CopyAndTranspose(a0)); } @@ -5884,16 +5884,16 @@ PyObject *shape, *a0; int mode=0; static char *kwlist[] = {"a", "v", "mode", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist, &a0, &shape, &mode)) return NULL; - + return PyArray_Correlate(a0, shape, mode); } /*MULTIARRAY_API - Arange, + Arange, */ static PyObject * PyArray_Arange(double start, double stop, double step, int type_num) @@ -5905,18 +5905,18 @@ int ret; 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); } - range = PyArray_New(&PyArray_Type, 1, &length, type_num, + 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 */ @@ -5928,7 +5928,7 @@ if (length == 1) return range; obj = PyFloat_FromDouble(start + step); - ret = funcs->setitem(obj, PyArray_BYTES(range)+PyArray_ITEMSIZE(range), + ret = funcs->setitem(obj, PyArray_BYTES(range)+PyArray_ITEMSIZE(range), (PyArrayObject *)range); Py_DECREF(obj); if (ret < 0) goto fail; @@ -5941,7 +5941,7 @@ } funcs->fill(PyArray_DATA(range), length, (PyArrayObject *)range); if (PyErr_Occurred()) goto fail; - + return range; fail: @@ -5949,7 +5949,7 @@ return NULL; } -/* the formula is +/* the formula is len = (intp) ceil((start - stop) / step); */ static intp @@ -5958,7 +5958,7 @@ intp len; PyObject *val; double value; - + *next = PyNumber_Subtract(stop, start); if (!(*next)) return -1; val = PyNumber_TrueDivide(*next, step); @@ -5979,7 +5979,7 @@ if (error_converting(value)) return -1; len = (intp) ceil(value); } - + if (len > 0) { *next = PyNumber_Add(start, step); if (!next) return -1; @@ -5992,7 +5992,7 @@ ArangeObj, */ static PyObject * -PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype) +PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype) { PyObject *range; PyArray_ArrFuncs *funcs; @@ -6035,7 +6035,7 @@ else Py_INCREF(start); /* calculate the length and next = start + step*/ - length = _calc_length(start, stop, step, &next, + length = _calc_length(start, stop, step, &next, PyTypeNum_ISCOMPLEX(dtype->type_num)); if (PyErr_Occurred()) {Py_DECREF(dtype); goto fail;} @@ -6068,7 +6068,7 @@ 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), + if (funcs->setitem(next, PyArray_BYTES(range)+PyArray_ITEMSIZE(range), (PyArrayObject *)range) < 0) goto fail; if (length == 2) goto finish; @@ -6093,7 +6093,7 @@ Py_DECREF(step); Py_DECREF(next); return range; - + fail: Py_DECREF(start); Py_DECREF(step); @@ -6106,18 +6106,18 @@ 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, + &o_stop, &o_step, PyArray_DescrConverter2, - &typecode)) + &typecode)) return NULL; return PyArray_ArangeObj(o_start, o_stop, o_step, typecode); } /* -Included at the very first so not auto-grabbed and thus not +Included at the very first so not auto-grabbed and thus not labeled. */ static unsigned int @@ -6127,35 +6127,35 @@ } static PyObject * -array__get_ndarray_c_version(PyObject *dummy, PyObject *args, PyObject *kwds) +array__get_ndarray_c_version(PyObject *dummy, PyObject *args, PyObject *kwds) { static char *kwlist[] = {NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwds, "", kwlist )) return NULL; - + return PyInt_FromLong( (long) PyArray_GetNDArrayCVersion() ); } static PyObject * -array__reconstruct(PyObject *dummy, PyObject *args) +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, + if (!PyArg_ParseTuple(args, "O!O&O&", &PyType_Type, &subtype, PyArray_IntpConverter, &shape, - PyArray_DescrConverter, &dtype)) + PyArray_DescrConverter, &dtype)) goto fail; if (!PyType_IsSubtype(subtype, &PyArray_Type)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "_reconstruct: First argument must be " \ "a sub-type of ndarray"); goto fail; } - - ret = PyArray_NewFromDescr(subtype, dtype, + + ret = PyArray_NewFromDescr(subtype, dtype, (int)shape.len, shape.ptr, NULL, NULL, 0, NULL); if (shape.ptr) PyDimMem_FREE(shape.ptr); @@ -6168,16 +6168,16 @@ } static PyObject * -array_set_string_function(PyObject *dummy, PyObject *args, PyObject *kwds) +array_set_string_function(PyObject *dummy, PyObject *args, PyObject *kwds) { PyObject *op; int repr=1; static char *kwlist[] = {"f", "repr", NULL}; - if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|i", kwlist, - &op, &repr)) return NULL; + if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|i", kwlist, + &op, &repr)) return NULL; if (!PyCallable_Check(op)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "Argument must be callable."); return NULL; } @@ -6187,19 +6187,19 @@ } static PyObject * -array_set_ops_function(PyObject *self, PyObject *args, PyObject *kwds) +array_set_ops_function(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *oldops=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 + later when use is attempted */ if (kwds && PyArray_SetNumericOps(kwds) == -1) { Py_DECREF(oldops); - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "one or more objects not callable"); return NULL; } @@ -6237,7 +6237,7 @@ zero = PyInt_FromLong((long) 0); - obj = PyArray_EnsureAnyArray(PyArray_GenericBinaryFunction(arr, zero, + obj = PyArray_EnsureAnyArray(PyArray_GenericBinaryFunction(arr, zero, n_ops.not_equal)); Py_DECREF(zero); Py_DECREF(arr); @@ -6257,7 +6257,7 @@ array_where(PyObject *ignored, PyObject *args) { PyObject *obj=NULL, *x=NULL, *y=NULL; - + if (!PyArg_ParseTuple(args, "O|OO", &obj, &x, &y)) return NULL; return PyArray_Where(obj, x, y); @@ -6269,10 +6269,10 @@ int axis=-1; PyObject *obj; static char *kwlist[] = {"keys", "axis", NULL}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i", kwlist, + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i", kwlist, &obj, &axis)) return NULL; - + return _ARET(PyArray_LexSort(obj, axis)); } @@ -6287,17 +6287,17 @@ PyObject *retobj; static char *kwlist[] = {"from", "to", NULL}; - if(!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&", kwlist, + 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, + 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); @@ -6311,7 +6311,7 @@ if(!PyArg_ParseTuple(args, "i", &size)) return NULL; - + return PyBuffer_New(size); } @@ -6322,16 +6322,16 @@ 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, + 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); + return PyBuffer_FromObject(obj, offset, size); } else return PyBuffer_FromReadWriteObject(obj, offset, size); @@ -6379,7 +6379,7 @@ static char *kwlist[] = {"a1", "a2", "cmp", "rstrip", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOs#O&", kwlist, - &array, &other, + &array, &other, &cmp_str, &strlen, PyArray_BoolConverter, &rstrip)) return NULL; @@ -6398,20 +6398,20 @@ 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; - } - + } + if (PyArray_ISSTRING(newarr) && PyArray_ISSTRING(newoth)) { res = _strings_richcompare(newarr, newoth, cmp_op, rstrip != 0); } else { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "comparison of non-string arrays"); } @@ -6428,24 +6428,24 @@ static struct PyMethodDef array_module_methods[] = { - {"_get_ndarray_c_version", (PyCFunction)array__get_ndarray_c_version, + {"_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, + {"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, + {"array", (PyCFunction)_array_fromobject, METH_VARARGS|METH_KEYWORDS, NULL}, - {"arange", (PyCFunction)array_arange, + {"arange", (PyCFunction)array_arange, METH_VARARGS|METH_KEYWORDS, NULL}, - {"zeros", (PyCFunction)array_zeros, + {"zeros", (PyCFunction)array_zeros, METH_VARARGS|METH_KEYWORDS, NULL}, - {"empty", (PyCFunction)array_empty, + {"empty", (PyCFunction)array_empty, METH_VARARGS|METH_KEYWORDS, NULL}, {"scalar", (PyCFunction)array_scalar, METH_VARARGS|METH_KEYWORDS, NULL}, @@ -6457,15 +6457,15 @@ METH_VARARGS|METH_KEYWORDS, NULL}, {"fromiter",(PyCFunction)array_fromIter, METH_VARARGS|METH_KEYWORDS, NULL}, - {"concatenate", (PyCFunction)array_concatenate, + {"concatenate", (PyCFunction)array_concatenate, METH_VARARGS|METH_KEYWORDS, NULL}, - {"inner", (PyCFunction)array_innerproduct, + {"inner", (PyCFunction)array_innerproduct, METH_VARARGS, NULL}, - {"dot", (PyCFunction)array_matrixproduct, + {"dot", (PyCFunction)array_matrixproduct, METH_VARARGS, NULL}, - {"_fastCopyAndTranspose", (PyCFunction)array_fastCopyAndTranspose, + {"_fastCopyAndTranspose", (PyCFunction)array_fastCopyAndTranspose, METH_VARARGS, NULL}, - {"correlate", (PyCFunction)array_correlate, + {"correlate", (PyCFunction)array_correlate, METH_VARARGS | METH_KEYWORDS, NULL}, {"frombuffer", (PyCFunction)array_frombuffer, METH_VARARGS | METH_KEYWORDS, NULL}, @@ -6490,11 +6490,11 @@ /* For dual inheritance we need to make sure that the objects being inherited from have the tp->mro object initialized. This is - not necessarily true for the basic type objects of Python (it is + not necessarily true for the basic type objects of Python (it is checked for single inheritance but not dual in PyType_Ready). Thus, we call PyType_Ready on the standard Python Types, here. -*/ +*/ static int setup_scalartypes(PyObject *dict) { @@ -6517,7 +6517,7 @@ #child); \ return -1; \ } - + if (PyType_Ready(&PyGenericArrType_Type) < 0) return -1; @@ -6530,7 +6530,7 @@ 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 = \ @@ -6596,9 +6596,9 @@ DUAL_INHERIT2(String, String, Character); DUAL_INHERIT2(Unicode, Unicode, Character); - + SINGLE_INHERIT(Void, Flexible); - + SINGLE_INHERIT(Object, Generic); return 0; @@ -6618,7 +6618,7 @@ { PyObject *s; PyObject *newd; - + newd = PyDict_New(); PyDict_SetItemString(newd, "OWNDATA", s=PyInt_FromLong(OWNDATA)); @@ -6634,7 +6634,7 @@ Py_DECREF(s); PyDict_SetItemString(newd, "WRITEABLE", s=PyInt_FromLong(WRITEABLE)); Py_DECREF(s); - + PyDict_SetItemString(d, "_flagdict", newd); Py_DECREF(newd); return; @@ -6655,7 +6655,7 @@ /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); - if (!d) goto err; + if (!d) goto err; if (PyType_Ready(&PyArray_Type) < 0) return; @@ -6665,10 +6665,10 @@ PyArrayIter_Type.tp_iter = PyObject_SelfIter; PyArrayMultiIter_Type.tp_iter = PyObject_SelfIter; if (PyType_Ready(&PyArrayIter_Type) < 0) - return; - + return; + if (PyType_Ready(&PyArrayMapIter_Type) < 0) - return; + return; if (PyType_Ready(&PyArrayMultiIter_Type) < 0) return; @@ -6687,7 +6687,7 @@ MultiArrayError = PyString_FromString ("multiarray.error"); PyDict_SetItemString (d, "error", MultiArrayError); - + s = PyString_FromString("3.0"); PyDict_SetItemString(d, "__version__", s); Py_DECREF(s); @@ -6720,7 +6720,7 @@ Py_INCREF(&PyArrayIter_Type); PyDict_SetItemString(d, "flatiter", (PyObject *)&PyArrayIter_Type); Py_INCREF(&PyArrayMultiIter_Type); - PyDict_SetItemString(d, "broadcast", + PyDict_SetItemString(d, "broadcast", (PyObject *)&PyArrayMultiIter_Type); Py_INCREF(&PyArrayDescr_Type); PyDict_SetItemString(d, "dtype", (PyObject *)&PyArrayDescr_Type); @@ -6736,11 +6736,10 @@ PyImport_ImportModule("numpy.core._internal"); if (_numpy_internal != NULL) return; - err: + err: if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_RuntimeError, + PyErr_SetString(PyExc_RuntimeError, "cannot load multiarray module."); } return; } - Modified: trunk/numpy/core/src/scalarmathmodule.c.src =================================================================== --- trunk/numpy/core/src/scalarmathmodule.c.src 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/scalarmathmodule.c.src 2006-08-19 06:01:10 UTC (rev 3040) @@ -1,9 +1,9 @@ /* -*- c -*- */ /* The purpose of this module is to add faster math for array scalars - that does not go through the ufunc machinery + that does not go through the ufunc machinery - but still supports error-modes. + but still supports error-modes. */ #include "Python.h" @@ -105,7 +105,7 @@ BINARY: -add, subtract, multiply, divide, remainder, divmod, power, +add, subtract, multiply, divide, remainder, divmod, power, floor_divide, true_divide lshift, rshift, and, or, xor (integers only) @@ -173,7 +173,7 @@ #if @neg@ if (temp > MAX_ at NAME@ || temp < MIN_ at NAME@) #else - if (temp > MAX_ at NAME@) + if (temp > MAX_ at NAME@) #endif generate_overflow_error(); return; @@ -336,14 +336,14 @@ /**begin repeat #name=float,double,longdouble# **/ -static void - at name@_ctype_remainder(@name@ a, @name@ b, @name@ *out) { +static void + at name@_ctype_remainder(@name@ a, @name@ b, @name@ *out) { @name@ mod; mod = _basic_ at name@_fmod(a, b); if (mod && (((b < 0) != (mod < 0)))) mod += b; *out = mod; -} -/**end repeat**/ +} +/**end repeat**/ @@ -402,8 +402,8 @@ } /**end repeat**/ -/* Get the nc_powf, nc_pow, and nc_powl functions from - the data area of the power ufunc in umathmodule. +/* Get the nc_powf, nc_pow, and nc_powl functions from + the data area of the power ufunc in umathmodule. */ /**begin repeat @@ -465,7 +465,7 @@ 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 +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. @@ -474,18 +474,18 @@ 6) Construct and return the output scalar. */ - + /**begin repeat #name=byte,ubyte,short,ushort,int,uint,long,ulong,longlong,ulonglong,float,double,longdouble,cfloat,cdouble,clongdouble# #Name=Byte, UByte, Short, UShort, Int, UInt, Long, ULong, LongLong, ULongLong, Float, Double, LongDouble, CFloat, CDouble, CLongDouble# #NAME=BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONGLONG, FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE, CLONGDOUBLE# -**/ +**/ static int _ at name@_convert_to_ctype(PyObject *a, @name@ *arg1) { - PyObject *temp; + PyObject *temp; if (PyArray_IsScalar(a, @Name@)) { *arg1 = PyArrayScalar_VAL(a, @Name@); @@ -511,10 +511,10 @@ return retval; } return -2; -} +} static int -_ at name@_convert2_to_ctypes(PyObject *a, @name@ *arg1, +_ at name@_convert2_to_ctypes(PyObject *a, @name@ *arg1, PyObject *b, @name@ *arg2) { int ret; @@ -550,7 +550,7 @@ #if @fperr@ int retstatus; -#endif +#endif switch(_ at name@_convert2_to_ctypes(a, &arg1, b, &arg2)) { case 0: @@ -581,8 +581,8 @@ if (retstatus) { int bufsize, errmask; PyObject *errobj; - if (PyUFunc_GetPyValues("@name at _scalars", &bufsize, &errmask, - &errobj) < 0) + if (PyUFunc_GetPyValues("@name at _scalars", &bufsize, &errmask, + &errobj) < 0) return NULL; if (PyUFunc_handlefperr(errmask, errobj, retstatus)) return NULL; @@ -634,11 +634,11 @@ @name@ out = 0; @otyp@ out1=0; #endif - + switch(_ at name@_convert2_to_ctypes(a, &arg1, b, &arg2)) { case 0: break; - case -1: /* can't cast both safely + case -1: /* can't cast both safely mixed-types? */ return PyArray_Type.tp_as_number->nb_power(a,b,NULL); case -2: /* use default handling */ @@ -658,7 +658,7 @@ #else if (arg2 == 0) { out1 = out = 1; - } + } #endif #if @isint@ else if (arg2 < 0) { @@ -675,8 +675,8 @@ if (retstatus) { int bufsize, errmask; PyObject *errobj; - if (PyUFunc_GetPyValues("@name at _scalars", &bufsize, &errmask, - &errobj) < 0) + if (PyUFunc_GetPyValues("@name at _scalars", &bufsize, &errmask, + &errobj) < 0) return NULL; if (PyUFunc_handlefperr(errmask, errobj, retstatus)) return NULL; @@ -698,7 +698,7 @@ if (ret==NULL) return NULL; PyArrayScalar_ASSIGN(ret, @Name@, out); #endif - + return ret; } /**end repeat**/ @@ -731,7 +731,7 @@ @name@ arg1; @otyp@ out; PyObject *ret; - + switch(_ at name@_convert_to_ctype(a, &arg1)) { case 0: break; @@ -770,21 +770,21 @@ { int ret; @name@ arg1; - + if (_ at name@_convert_to_ctype(a, &arg1) < 0) { if (PyErr_Occurred()) return -1; return PyGenericArrType_Type.tp_as_number->nb_nonzero(a); } - + /* here we do the actual calculation with arg1 and arg2 */ /* make it a function call. */ #if @simp@ ret = (arg1 != 0); -#else +#else ret = ((arg1.real != 0) || (arg1.imag != 0)); #endif - + return ret; } /**end repeat**/ @@ -838,7 +838,7 @@ { @name@ arg1, arg2; int out=0; - + switch(_ at name@_convert2_to_ctypes(self, &arg1, other, &arg2)) { case 0: break; @@ -869,7 +869,7 @@ out = @simp at _cmp_gt(arg1, arg2); break; } - + if (out) { PyArrayScalar_RETURN_TRUE; } @@ -963,17 +963,17 @@ char *signatures; int i, j; int ret = -1; - + /* Get the nc_pow functions */ /* Get the pow functions */ mm = PyImport_ImportModule("numpy.core.umath"); if (mm == NULL) return -1; - + obj = PyObject_GetAttrString(mm, "power"); if (obj == NULL) goto fail; funcdata = ((PyUFuncObject *)obj)->data; signatures = ((PyUFuncObject *)obj)->types; - + i = 0; j = 0; while(signatures[i] != PyArray_FLOAT) {i+=3; j++;} @@ -1058,9 +1058,9 @@ PyComplex_Type.tp_compare = PyCDoubleArrType_Type.tp_compare; PyComplex_Type.tp_richcompare = \ PyCDoubleArrType_Type.tp_richcompare; - } + } else { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } @@ -1092,9 +1092,9 @@ 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, + PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } @@ -1126,9 +1126,9 @@ 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, + PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } @@ -1160,9 +1160,9 @@ 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, + PyErr_SetString(PyExc_ValueError, "arguments must be int, float, or complex"); return NULL; } @@ -1187,10 +1187,10 @@ PyObject *m; m = Py_InitModule("scalarmath", methods); - - import_array(); - import_umath(); + import_array(); + import_umath(); + if (get_functions() < 0) return; add_scalarmath(); Modified: trunk/numpy/core/src/scalartypes.inc.src =================================================================== --- trunk/numpy/core/src/scalartypes.inc.src 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/scalartypes.inc.src 2006-08-19 06:01:10 UTC (rev 3040) @@ -868,7 +868,7 @@ if (PyArray_IsScalar(self, ComplexFloating)) { typecode = _realdescr_fromcomplexscalar(self, &typenum); - ret = PyArray_Scalar(scalar_value(self, NULL), + ret = PyArray_Scalar(scalar_value(self, NULL), typecode, NULL); Py_DECREF(typecode); return ret; @@ -1782,7 +1782,7 @@ /**begin repeat #name=byte, short, int, long, ubyte, ushort, longlong, uint, ulong, ulonglong# #Name=Byte, Short, Int, Long, UByte, UShort, LongLong, UInt, ULong, ULongLong# -#type=PyInt_FromLong*6, PyLong_FromLongLong*1, PyLong_FromUnsignedLong*2, PyLong_FromUnsignedLongLong# +#type=PyInt_FromLong*6, PyLong_FromLongLong*1, PyLong_FromUnsignedLong*2, PyLong_FromUnsignedLongLong# */ static PyNumberMethods @name at _arrtype_as_number; static PyObject * Modified: trunk/numpy/core/src/ucsnarrow.c =================================================================== --- trunk/numpy/core/src/ucsnarrow.c 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/ucsnarrow.c 2006-08-19 06:01:10 UTC (rev 3040) @@ -1,16 +1,16 @@ -/* Functions only needed on narrow builds of Python - for converting back and forth between the NumPy Unicode data-type +/* Functions only needed on narrow builds of Python + for converting back and forth between the NumPy Unicode data-type (always 4-byte) - and the Python Unicode scalar (2-bytes on a narrow build). + and the Python Unicode scalar (2-bytes on a narrow build). */ /* the ucs2 buffer must be large enough to hold 2*ucs4length characters - due to the use of surrogate pairs. + due to the use of surrogate pairs. The return value is the number of ucs2 bytes used-up which - is ucs4length + number of surrogate pairs found. + is ucs4length + number of surrogate pairs found. - values above 0xffff are converted to surrogate pairs. + values above 0xffff are converted to surrogate pairs. */ static int PyUCS2Buffer_FromUCS4(Py_UNICODE *ucs2, PyArray_UCS4 *ucs4, int ucs4length) @@ -41,7 +41,7 @@ It returns the number of characters converted which can be less than ucslen if there are surrogate pairs in ucs2. - The return value is the actual size of the used part of the ucs4 buffer. + The return value is the actual size of the used part of the ucs4 buffer. */ static int @@ -92,9 +92,9 @@ static int MyPyUnicode_Resize(PyUnicodeObject *uni, int length) -{ +{ void *oldstr; - + oldstr = uni->str; PyMem_RESIZE(uni->str, Py_UNICODE, length+1); if (!uni->str) { Modified: trunk/numpy/core/src/ufuncobject.c =================================================================== --- trunk/numpy/core/src/ufuncobject.c 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/ufuncobject.c 2006-08-19 06:01:10 UTC (rev 3040) @@ -1,17 +1,17 @@ /* - Python Universal Functions Object -- Math for all types, plus fast + Python Universal Functions Object -- Math for all types, plus fast arrays math - + Full description - + This supports mathematical (and Boolean) functions on arrays and other python objects. Math on large arrays of basic C types is rather efficient. Travis E. Oliphant (2005-2006), oliphant at ee.byu.edu (oliphant.travis at ieee.org) - based on the + based on the - Original Implementation: + Original Implementation: Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin at mit.edu with inspiration and code from @@ -20,7 +20,7 @@ J. Todd Miller Perry Greenfield Rick White - + */ @@ -43,7 +43,7 @@ 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; inin, nout=data->nout; int ntot; - PyObject *tocall = data->callable; + PyObject *tocall = data->callable; char *ptrs[NPY_MAXARGS]; PyObject *arglist, *result; PyObject *in, **op; @@ -423,7 +423,7 @@ 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; @@ -456,20 +456,20 @@ /* ---------------------------------------------------------------- */ -/* fpstatus is the ufunc_formatted hardware status +/* fpstatus is the ufunc_formatted hardware status errmask is the handling mask specified by the user. errobj is a Python object with (string, callable object or None) or NULL */ /* - 2. for each of the flags + 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 -*/ +*/ static int _error_handler(int method, PyObject *errobj, char *errtype, int retstatus) @@ -488,7 +488,7 @@ if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0) goto fail; break; case UFUNC_ERR_RAISE: - PyErr_Format(PyExc_FloatingPointError, + PyErr_Format(PyExc_FloatingPointError, "%s encountered in %s", errtype, name); goto fail; @@ -496,13 +496,13 @@ pyfunc = PyTuple_GET_ITEM(errobj, 1); if (pyfunc == Py_None) { - PyErr_Format(PyExc_NameError, + PyErr_Format(PyExc_NameError, "python callback specified for %s (in " \ - " %s) but no function found.", + " %s) but no function found.", errtype, name); goto fail; } - args = Py_BuildValue("NN", PyString_FromString(errtype), + args = Py_BuildValue("NN", PyString_FromString(errtype), PyInt_FromLong((long) retstatus)); if (args == NULL) goto fail; ret = PyObject_CallObject(pyfunc, args); @@ -515,9 +515,9 @@ DISABLE_C_API return 0; - fail: + fail: DISABLE_C_API - return -1; + return -1; } @@ -548,7 +548,7 @@ HANDLEIT(OVERFLOW, "overflow"); HANDLEIT(UNDERFLOW, "underflow"); HANDLEIT(INVALID, "invalid"); - } + } return 0; } @@ -618,8 +618,8 @@ /* Called to determine coercion */ -static int -select_types(PyUFuncObject *self, int *arg_types, +static int +select_types(PyUFuncObject *self, int *arg_types, PyUFuncGenericFunction *function, void **data, PyArray_SCALARKIND *scalars) { @@ -635,18 +635,18 @@ } } } - + if (userdef > 0) { PyObject *key, *obj; int *this_types=NULL; - + 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, + PyErr_SetString(PyExc_TypeError, "user-defined type used in ufunc" \ " with no registered loops"); return -1; @@ -669,7 +669,7 @@ PyCObject_AsVoidPtr(obj); *data = NULL; } - + if (this_types == NULL) { for (i=1; inargs; i++) { arg_types[i] = userdef; @@ -685,7 +685,7 @@ } start_type = arg_types[0]; - /* If the first argument is a scalar we need to place + /* 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) { @@ -693,12 +693,12 @@ } i = 0; - while (intypes && start_type > self->types[i*self->nargs]) + while (intypes && start_type > self->types[i*self->nargs]) i++; for(;intypes; i++) { for(j=0; jnin; j++) { - if (!PyArray_CanCoerceScalar(arg_types[j], + if (!PyArray_CanCoerceScalar(arg_types[j], self->types[i*self->nargs+j], scalars[j])) break; @@ -706,17 +706,17 @@ if (j == self->nin) break; } if(i>=self->ntypes) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "function not supported for these types, "\ "and can't coerce safely to supported types"); return -1; } - for(j=0; jnargs; j++) + for(j=0; jnargs; j++) arg_types[j] = self->types[i*self->nargs+j]; if (self->data) *data = self->data[i]; - else + else *data = NULL; *function = self->functions[i]; @@ -788,19 +788,19 @@ *errmask); return -1; } - + retval = PyList_GET_ITEM(ref, 2); if (retval != Py_None && !PyCallable_Check(retval)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "callback function must be callable"); return -1; } - *errobj = Py_BuildValue("NO", + *errobj = Py_BuildValue("NO", PyString_FromString(name), retval); if (*errobj == NULL) return -1; - + return 0; } @@ -816,7 +816,7 @@ int i; intp size; PyObject *new; - PyArray_Descr *ntype; + PyArray_Descr *ntype; PyArray_Descr *atype; for (i=0; inin) || (nargs > self->nargs)) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "invalid number of arguments"); return -1; } @@ -914,7 +914,7 @@ object = 1; } /* - fprintf(stderr, "array %d has reference %d\n", i, + fprintf(stderr, "array %d has reference %d\n", i, (mps[i])->ob_refcnt); */ @@ -940,15 +940,15 @@ scalars[i] = PyArray_NOSCALAR; } } - + /* Select an appropriate function for these argument types. */ - if (select_types(loop->ufunc, arg_types, &(loop->function), + if (select_types(loop->ufunc, arg_types, &(loop->function), &(loop->funcdata), scalars) == -1) return -1; - /* FAIL with NotImplemented if the other object has - the __r__ method and has __array_priority__ as - an attribute (signalling it can handle ndarray's) + /* FAIL with NotImplemented if the other object has + the __r__ method and has __array_priority__ as + an attribute (signalling it can handle ndarray's) and is not already an ndarray or bigndarray */ if ((arg_types[1] == PyArray_OBJECT) && \ @@ -961,22 +961,22 @@ return nargs; } } - + /* Create copies for some of the arrays if appropriate */ if (_create_copies(loop, arg_types, mps) < 0) return -1; - + /* Create Iterators for the Inputs */ for (i=0; inin; 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; ind != loop->nd || - !PyArray_CompareLists(mps[i]->dimensions, + !PyArray_CompareLists(mps[i]->dimensions, loop->dimensions, loop->nd)) { - PyErr_SetString(PyExc_ValueError, + 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, + PyErr_SetString(PyExc_ValueError, "return array is not writeable"); Py_DECREF(mps[i]); mps[i] = NULL; @@ -1021,21 +1021,21 @@ } /* construct any missing return arrays and make output iterators */ - + for (i=self->nin; inargs; i++) { PyArray_Descr *ntype; if (mps[i] == NULL) { mps[i] = (PyArrayObject *)PyArray_New(subtype, - loop->nd, + loop->nd, loop->dimensions, - arg_types[i], + arg_types[i], NULL, NULL, 0, 0, NULL); if (mps[i] == NULL) return -1; } - /* reset types for outputs that are equivalent + /* reset types for outputs that are equivalent -- no sense casting uselessly */ else { @@ -1048,13 +1048,13 @@ } 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 + /* Copy the array to a temporary copy and set the UPDATEIFCOPY flag */ ntype = PyArray_DescrFromType(arg_types[i]); @@ -1068,7 +1068,7 @@ } } } - + loop->iters[i] = (PyArrayIterObject *) \ PyArray_IterNew((PyObject *)mps[i]); if (loop->iters[i] == NULL) return -1; @@ -1090,7 +1090,7 @@ maxsize = 0; for (i=0; inargs; i++) { loop->needbuffer[i] = 0; - if (arg_types[i] != mps[i]->descr->type_num || + if (arg_types[i] != mps[i]->descr->type_num || !PyArray_ISBEHAVED_RO(mps[i])) { loop->meth = BUFFER_UFUNCLOOP; loop->needbuffer[i] = 1; @@ -1099,9 +1099,9 @@ loop->obj = 1; } } - + if (loop->meth == NO_UFUNCLOOP) { - + loop->meth = ONE_UFUNCLOOP; /* All correct type and BEHAVED */ @@ -1136,7 +1136,7 @@ /* Fix iterators */ /* Find the **largest** dimension */ - + maxdim = -1; for (i=loop->nd - 1; i>=0; i--) { if (loop->dimensions[i] > maxdim) { @@ -1149,9 +1149,9 @@ 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 + /* 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) */ @@ -1163,16 +1163,16 @@ it->backstrides[ldim] = 0; /* (won't fix factors because we - don't use PyArray_ITER_GOTO1D + 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 + /* 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... + values -- if step size is already zero that is not changed... */ if (loop->meth == BUFFER_UFUNCLOOP) { loop->leftover = maxdim % loop->bufsize; @@ -1193,10 +1193,10 @@ 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) { @@ -1275,7 +1275,7 @@ loop->bufptr[i] = loop->buffer[i]; } if (!loop->objfunc && loop->obj) { - if (arg_types[i] == PyArray_OBJECT) { + if (arg_types[i] == PyArray_OBJECT) { loop->objfunc = 1; } } @@ -1303,7 +1303,7 @@ ufuncloop_dealloc(PyUFuncLoopObject *self) { int i; - + if (self->ufunc != NULL) { for (i=0; iufunc->nargs; i++) Py_XDECREF(self->iters[i]); @@ -1319,7 +1319,7 @@ { PyUFuncLoopObject *loop; int i; - + if (self == NULL) { PyErr_SetString(PyExc_ValueError, "function not supported"); return NULL; @@ -1327,7 +1327,7 @@ if ((loop = _pya_malloc(sizeof(PyUFuncLoopObject)))==NULL) { PyErr_NoMemory(); return loop; } - + loop->index = 0; loop->ufunc = self; Py_INCREF(self); @@ -1340,9 +1340,9 @@ loop->notimplemented = 0; if (PyUFunc_GetPyValues((self->name ? self->name : ""), - &(loop->bufsize), &(loop->errormask), + &(loop->bufsize), &(loop->errormask), &(loop->errobj)) < 0) goto fail; - + /* Setup the matrices */ if (construct_matrices(loop, args, mps) < 0) goto fail; @@ -1356,51 +1356,51 @@ } -/* +/* static void -_printbytebuf(PyUFuncLoopObject *loop, int bufnum) -{ +_printbytebuf(PyUFuncLoopObject *loop, int bufnum) +{ int i; - + fprintf(stderr, "Printing byte buffer %d\n", bufnum); for (i=0; ibufcnt; i++) { fprintf(stderr, " %d\n", *(((byte *)(loop->buffer[bufnum]))+i)); - } + } } static void -_printlongbuf(PyUFuncLoopObject *loop, int bufnum) -{ +_printlongbuf(PyUFuncLoopObject *loop, int bufnum) +{ int i; - + fprintf(stderr, "Printing long buffer %d\n", bufnum); for (i=0; ibufcnt; i++) { fprintf(stderr, " %ld\n", *(((long *)(loop->buffer[bufnum]))+i)); - } + } } static void -_printlongbufptr(PyUFuncLoopObject *loop, int bufnum) -{ +_printlongbufptr(PyUFuncLoopObject *loop, int bufnum) +{ int i; - + fprintf(stderr, "Printing long buffer %d\n", bufnum); for (i=0; ibufcnt; i++) { fprintf(stderr, " %ld\n", *(((long *)(loop->bufptr[bufnum]))+i)); - } + } } - + static void -_printcastbuf(PyUFuncLoopObject *loop, int bufnum) -{ +_printcastbuf(PyUFuncLoopObject *loop, int bufnum) +{ int i; - + fprintf(stderr, "Printing long buffer %d\n", bufnum); for (i=0; ibufcnt; i++) { fprintf(stderr, " %ld\n", *(((long *)(loop->castbuf[bufnum]))+i)); - } + } } */ @@ -1410,7 +1410,7 @@ /* currently generic ufuncs cannot be built for use on flexible arrays. - The cast functions in the generic loop would need to be fixed to pass + The cast functions in the generic loop would need to be fixed to pass in something besides NULL, NULL. Also the underlying ufunc loops would not know the element-size unless @@ -1419,14 +1419,14 @@ */ /* This generic function is called with the ufunc object, the arguments to it, - and an array of (pointers to) PyArrayObjects which are NULL. The + and an array of (pointers to) PyArrayObjects which are NULL. The arguments are parsed and placed in mps in construct_loop (construct_matrices) */ /*UFUNC_API*/ -static int -PyUFunc_GenericFunction(PyUFuncObject *self, PyObject *args, - PyArrayObject **mps) +static int +PyUFunc_GenericFunction(PyUFuncObject *self, PyObject *args, + PyArrayObject **mps) { PyUFuncLoopObject *loop; int i; @@ -1442,20 +1442,20 @@ /* 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. + increment moves through the entire array. */ /*fprintf(stderr, "ONE...%d\n", loop->size);*/ - loop->function((char **)loop->bufptr, &(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 + /* 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; inargs; i++) + for (i=0; inargs; i++) loop->bufptr[i] = loop->iters[i]->dataptr; loop->function((char **)loop->bufptr, &(loop->bufcnt), @@ -1492,7 +1492,7 @@ int i, j, k, stopcondition; char *myptr1, *myptr2; - + for (i=0; inargs; i++) { copyswapn[i] = mps[i]->descr->f->copyswapn; mpselsize[i] = mps[i]->descr->elsize; @@ -1503,25 +1503,25 @@ else fastmemcpy[i] = 1; } /* Do generic buffered looping here (works for any kind of - arrays -- some need buffers, some don't. + 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 + 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 + + 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 + remainder. + + So, the code looks very similar to NOBUFFER_LOOP except the inner-most loop is replaced with... - + for(i=0; isize, + /* fprintf(stderr, "BUFFER...%d,%d,%d\n", loop->size, loop->ninnerloops, loop->leftover); */ /* for (i=0; inargs; i++) { - fprintf(stderr, "iters[%d]->dataptr = %p, %p of size %d\n", i, + fprintf(stderr, "iters[%d]->dataptr = %p, %p of size %d\n", i, iters[i], iters[i]->ao->data, PyArray_NBYTES(iters[i]->ao)); } */ @@ -1572,10 +1572,10 @@ copysizes[i] = datasize[i] * mpselsize[i]; } } - + for (i=0; inin; i++) { if (!needbuffer[i]) continue; - if (fastmemcpy[i]) + if (fastmemcpy[i]) memcpy(buffer[i], tptr[i], copysizes[i]); else { @@ -1587,7 +1587,7 @@ myptr2 += laststrides[i]; } } - + /* swap the buffer if necessary */ if (swap[i]) { /* fprintf(stderr, "swapping...\n");*/ @@ -1603,10 +1603,10 @@ NULL, NULL); } } - + bufcnt = (intp) bufsize; loop->function((char **)dptr, &bufcnt, steps, loop->funcdata); - + for (i=self->nin; inargs; i++) { if (!needbuffer[i]) continue; if (loop->cast[i]) { @@ -1617,7 +1617,7 @@ } if (swap[i]) { copyswapn[i](buffer[i], mpselsize[i], NULL, -1, - (intp) datasize[i], 1, + (intp) datasize[i], 1, mps[i]); } /* copy back to output arrays */ @@ -1629,13 +1629,13 @@ myptr1 += laststrides[i]; } } - if (fastmemcpy[i]) + if (fastmemcpy[i]) memcpy(tptr[i], buffer[i], copysizes[i]); else { myptr2 = buffer[i]; myptr1 = tptr[i]; for (j=0; jleftover; - + for (j=0; jnargs; i++) { PyArray_ITER_NEXT(loop->iters[i]); } @@ -1684,9 +1684,9 @@ } } } - + NPY_LOOP_END_THREADS - + ufuncloop_dealloc(loop); return 0; @@ -1702,9 +1702,9 @@ { PyObject *obj, *arr; PyArray_Descr *typecode; - + if (self->identity == PyUFunc_None) { - PyErr_Format(PyExc_ValueError, + PyErr_Format(PyExc_ValueError, "zero-size array to ufunc.%s " \ "without identity", str); return NULL; @@ -1715,7 +1715,7 @@ obj = PyInt_FromLong((long) 0); } - typecode = PyArray_DescrFromType(otype); + typecode = PyArray_DescrFromType(otype); arr = PyArray_FromAny(obj, typecode, 0, 0, CARRAY, NULL); Py_DECREF(obj); return (PyArrayObject *)arr; @@ -1727,14 +1727,14 @@ 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), + new = PyArray_FromAny((PyObject *)(*arr), ntype, 0, 0, FORCECAST | ALIGNED, NULL); if (new == NULL) return -1; @@ -1745,17 +1745,17 @@ /* 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 + on deallocation of the loop structure by setting loop->decref. */ - + return 0; } static PyUFuncReduceObject * -construct_reduce(PyUFuncObject *self, PyArrayObject **arr, PyArrayObject *out, +construct_reduce(PyUFuncObject *self, PyArrayObject **arr, PyArrayObject *out, int axis, int otype, int operation, intp ind_size, char *str) { PyUFuncReduceObject *loop; @@ -1763,14 +1763,14 @@ PyArrayObject *aar; intp loop_i[MAX_DIMS], outsize=0; int arg_types[3] = {otype, otype, otype}; - PyArray_SCALARKIND scalars[3] = {PyArray_NOSCALAR, PyArray_NOSCALAR, + PyArray_SCALARKIND scalars[3] = {PyArray_NOSCALAR, PyArray_NOSCALAR, PyArray_NOSCALAR}; int i, j; int nd = (*arr)->nd; int flags; - /* Reduce type is the type requested of the input + /* Reduce type is the type requested of the input during reduction */ - + if ((loop = _pya_malloc(sizeof(PyUFuncReduceObject)))==NULL) { PyErr_NoMemory(); return loop; } @@ -1786,34 +1786,34 @@ loop->it = NULL; loop->rit = NULL; loop->errobj = NULL; - loop->decref=NULL; + 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) == -1) goto fail; - - /* output type may change -- if it does - reduction is forced into that type + if (select_types(loop->ufunc, arg_types, &(loop->function), + &(loop->funcdata), scalars) == -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) == -1) - goto fail; + if (select_types(loop->ufunc, arg_types, &(loop->function), + &(loop->funcdata), scalars) == -1) + goto fail; } - + /* get looping parameters from Python */ - if (PyUFunc_GetPyValues(str, &(loop->bufsize), &(loop->errormask), + 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; + if (_create_reduce_copy(loop, arr, otype) < 0) goto fail; aar = *arr; - + if (loop->N == 0) { loop->meth = ZERODIM_REDUCELOOP; } @@ -1843,7 +1843,7 @@ idarr = _getidentity(self, otype, str); if (idarr == NULL) goto fail; if (idarr->descr->elsize > UFUNC_MAXIDENTITY) { - PyErr_Format(PyExc_RuntimeError, + PyErr_Format(PyExc_RuntimeError, "UFUNC_MAXIDENTITY (%d)" \ " is too small (needs to be at least %d)", UFUNC_MAXIDENTITY, idarr->descr->elsize); @@ -1853,20 +1853,20 @@ 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; idimensions[i]; - + } if (out == NULL) { loop->ret = (PyArrayObject *) \ - PyArray_New(aar->ob_type, aar->nd-1, loop_i, - otype, NULL, NULL, 0, 0, + PyArray_New(aar->ob_type, aar->nd-1, loop_i, + otype, NULL, NULL, 0, 0, (PyObject *)aar); } else { @@ -1876,7 +1876,7 @@ case UFUNC_ACCUMULATE: if (out == NULL) { loop->ret = (PyArrayObject *) \ - PyArray_New(aar->ob_type, aar->nd, aar->dimensions, + PyArray_New(aar->ob_type, aar->nd, aar->dimensions, otype, NULL, NULL, 0, 0, (PyObject *)aar); } else { @@ -1886,7 +1886,7 @@ case UFUNC_REDUCEAT: memcpy(loop_i, aar->dimensions, nd*sizeof(intp)); /* Index is 1-d array */ - loop_i[axis] = ind_size; + loop_i[axis] = ind_size; if (out == NULL) { loop->ret = (PyArrayObject *) \ PyArray_New(aar->ob_type, aar->nd, loop_i, otype, @@ -1905,12 +1905,12 @@ } if (out) { if (PyArray_SIZE(out) != outsize) { - PyErr_SetString(PyExc_ValueError, + PyErr_SetString(PyExc_ValueError, "wrong shape for output"); goto fail; } loop->ret = (PyArrayObject *) \ - PyArray_FromArray(out, PyArray_DescrFromType(otype), + PyArray_FromArray(out, PyArray_DescrFromType(otype), flags); if (loop->ret && loop->ret != out) { loop->retbase = 1; @@ -1930,13 +1930,13 @@ if (loop->it == NULL) return NULL; if (loop->meth == ONEDIM_REDUCELOOP) { - loop->size = loop->it->size; + loop->size = loop->it->size; return loop; } /* 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; @@ -1951,11 +1951,11 @@ else { loop->rit = (PyArrayIterObject *) \ PyArray_IterNew((PyObject *)(loop->ret)); - if (loop->rit == NULL) return NULL; + 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; @@ -1963,13 +1963,13 @@ if (operation == UFUNC_ACCUMULATE) loop->steps[1] = loop->ret->strides[axis]; - else + else loop->steps[1] = 0; } loop->steps[2] = loop->steps[1]; loop->bufptr[2] = loop->bufptr[1] + loop->steps[2]; - + if (loop->meth == BUFFER_UFUNCLOOP) { int _size; loop->steps[0] = loop->outsize; @@ -2000,7 +2000,7 @@ fail: ufuncreduce_dealloc(loop); - return NULL; + return NULL; } @@ -2013,7 +2013,7 @@ */ static PyObject * -PyUFunc_Reduce(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out, +PyUFunc_Reduce(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out, int axis, int otype) { PyArrayObject *ret=NULL; @@ -2021,7 +2021,7 @@ intp i, n; char *dptr; NPY_BEGIN_THREADS_DEF - + /* Construct loop object */ loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_REDUCE, 0, "reduce"); @@ -2040,26 +2040,26 @@ case ONEDIM_REDUCELOOP: /*fprintf(stderr, "ONEDIM..%d\n", loop->size); */ while(loop->index < loop->size) { - if (loop->obj) + if (loop->obj) Py_INCREF(*((PyObject **)loop->it->dataptr)); - memmove(loop->bufptr[1], loop->it->dataptr, + memmove(loop->bufptr[1], loop->it->dataptr, loop->outsize); PyArray_ITER_NEXT(loop->it); loop->bufptr[1] += 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) + if (loop->obj) Py_INCREF(*((PyObject **)loop->it->dataptr)); - memmove(loop->bufptr[1], loop->it->dataptr, + memmove(loop->bufptr[1], loop->it->dataptr, loop->outsize); /* Adjust input pointer */ loop->bufptr[0] = loop->it->dataptr+loop->steps[0]; - loop->function((char **)loop->bufptr, + loop->function((char **)loop->bufptr, &(loop->N), loop->steps, loop->funcdata); UFUNC_CHECK_ERROR(loop); @@ -2067,24 +2067,24 @@ PyArray_ITER_NEXT(loop->it) loop->bufptr[1] += loop->outsize; loop->bufptr[2] = loop->bufptr[1]; - loop->index++; + loop->index++; } break; - case BUFFER_UFUNCLOOP: + 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 + 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, + /* fprintf(stderr, "BUFFERED..%d %d\n", loop->size, loop->swap); */ while(loop->index < loop->size) { - loop->inptr = loop->it->dataptr; + loop->inptr = loop->it->dataptr; /* Copy (cast) First term over to output */ if (loop->cast) { /* A little tricky because we need to @@ -2095,20 +2095,20 @@ NULL); loop->cast(loop->buffer, loop->castbuf, 1, NULL, NULL); - if (loop->obj) + if (loop->obj) Py_INCREF(*((PyObject **)loop->castbuf)); memcpy(loop->bufptr[1], loop->castbuf, loop->outsize); } else { /* Simple copy */ - arr->descr->f->copyswap(loop->bufptr[1], + arr->descr->f->copyswap(loop->bufptr[1], loop->inptr, loop->swap, NULL); } loop->inptr += loop->instrides; n = 1; while(n < loop->N) { - /* Copy up to loop->bufsize elements to + /* Copy up to loop->bufsize elements to buffer */ dptr = loop->buffer; for (i=0; ibufsize; i++, n++) { @@ -2125,15 +2125,15 @@ loop->castbuf, i, NULL, NULL); loop->function((char **)loop->bufptr, - &i, + &i, loop->steps, loop->funcdata); loop->bufptr[1] += loop->steps[1]*i; loop->bufptr[2] += loop->steps[2]*i; UFUNC_CHECK_ERROR(loop); - } + } PyArray_ITER_NEXT(loop->it); loop->bufptr[1] += loop->outsize; - loop->bufptr[2] = loop->bufptr[1]; + loop->bufptr[2] = loop->bufptr[1]; loop->index++; } } @@ -2156,7 +2156,7 @@ static PyObject * -PyUFunc_Accumulate(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out, +PyUFunc_Accumulate(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *out, int axis, int otype) { PyArrayObject *ret=NULL; @@ -2164,7 +2164,7 @@ intp i, n; char *dptr; NPY_BEGIN_THREADS_DEF - + /* Construct loop object */ loop = construct_reduce(self, &arr, out, axis, otype, UFUNC_ACCUMULATE, 0, "accumulate"); @@ -2175,35 +2175,35 @@ case ZERODIM_REDUCELOOP: /* Accumulate */ /* fprintf(stderr, "ZERO..%d\n", loop->size); */ for(i=0; isize; i++) { - if (loop->obj) + if (loop->obj) Py_INCREF(*((PyObject **)loop->idptr)); memcpy(loop->bufptr[1], loop->idptr, loop->outsize); loop->bufptr[1] += loop->outsize; - } + } break; case ONEDIM_REDUCELOOP: /* Accumulate */ /* fprintf(stderr, "ONEDIM..%d\n", loop->size); */ while(loop->index < loop->size) { - if (loop->obj) + if (loop->obj) Py_INCREF(*((PyObject **)loop->it->dataptr)); - memcpy(loop->bufptr[1], loop->it->dataptr, + memcpy(loop->bufptr[1], loop->it->dataptr, loop->outsize); PyArray_ITER_NEXT(loop->it); loop->bufptr[1] += 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) + if (loop->obj) Py_INCREF(*((PyObject **)loop->it->dataptr)); - memcpy(loop->bufptr[1], loop->it->dataptr, + memcpy(loop->bufptr[1], loop->it->dataptr, loop->outsize); /* Adjust input pointer */ loop->bufptr[0] = loop->it->dataptr+loop->steps[0]; - loop->function((char **)loop->bufptr, + loop->function((char **)loop->bufptr, &(loop->N), loop->steps, loop->funcdata); UFUNC_CHECK_ERROR(loop); @@ -2217,19 +2217,19 @@ 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 + 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, + /* fprintf(stderr, "BUFFERED..%d %p\n", loop->size, loop->cast); */ while(loop->index < loop->size) { - loop->inptr = loop->it->dataptr; + loop->inptr = loop->it->dataptr; /* Copy (cast) First term over to output */ if (loop->cast) { /* A little tricky because we need to @@ -2240,13 +2240,13 @@ NULL); loop->cast(loop->buffer, loop->castbuf, 1, NULL, NULL); - if (loop->obj) + if (loop->obj) Py_INCREF(*((PyObject **)loop->castbuf)); memcpy(loop->bufptr[1], loop->castbuf, loop->outsize); } else { /* Simple copy */ - arr->descr->f->copyswap(loop->bufptr[1], + arr->descr->f->copyswap(loop->bufptr[1], loop->inptr, loop->swap, NULL); @@ -2254,7 +2254,7 @@ loop->inptr += loop->instrides; n = 1; while(n < loop->N) { - /* Copy up to loop->bufsize elements to + /* Copy up to loop->bufsize elements to buffer */ dptr = loop->buffer; for (i=0; ibufsize; i++, n++) { @@ -2271,12 +2271,12 @@ loop->castbuf, i, NULL, NULL); loop->function((char **)loop->bufptr, - &i, + &i, loop->steps, loop->funcdata); loop->bufptr[1] += loop->steps[1]*i; loop->bufptr[2] += loop->steps[2]*i; UFUNC_CHECK_ERROR(loop); - } + } PyArray_ITER_NEXT(loop->it); PyArray_ITER_NEXT(loop->rit); loop->bufptr[1] = loop->rit->dataptr; @@ -2304,11 +2304,11 @@ /* 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.reduce(array[indices[i]:indices[i+1]] for i=0..end with an implicit indices[i+1]=len(array) 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 @@ -2321,28 +2321,28 @@ */ static PyObject * -PyUFunc_Reduceat(PyUFuncObject *self, PyArrayObject *arr, PyArrayObject *ind, +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 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 */ + /* Check for out-of-bounds values in indices array */ for (i=0; i mm)) { - PyErr_Format(PyExc_IndexError, + 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, @@ -2363,7 +2363,7 @@ for (i=0; ibufptr[0] = loop->it->dataptr + \ (*ptr)*loop->instrides; - if (loop->obj) + if (loop->obj) Py_INCREF(*((PyObject **)loop->bufptr[0])); memcpy(loop->bufptr[1], loop->bufptr[0], loop->outsize); @@ -2376,7 +2376,7 @@ &mm, loop->steps, loop->funcdata); UFUNC_CHECK_ERROR(loop); - } + } loop->bufptr[1] += loop->ret->strides[axis]; ptr++; } @@ -2387,15 +2387,15 @@ } break; - /* BUFFER -- misbehaved array or different types */ + /* 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; iobj) + if (loop->obj) Py_INCREF(*((PyObject **)loop->idptr)); - memcpy(loop->bufptr[1], loop->idptr, + memcpy(loop->bufptr[1], loop->idptr, loop->outsize); n = 0; mm = (i==nn-1 ? arr->dimensions[axis] - *ptr :\ @@ -2426,7 +2426,7 @@ loop->funcdata); UFUNC_CHECK_ERROR(loop); loop->bufptr[1] += j*loop->steps[1]; - } + } loop->bufptr[1] += loop->ret->strides[axis]; ptr++; } @@ -2440,13 +2440,13 @@ 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; - + fail: NPY_LOOP_END_THREADS @@ -2455,33 +2455,33 @@ } -/* 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) +/* 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) */ -static PyObject * -PyUFunc_GenericReduction(PyUFuncObject *self, PyObject *args, - PyObject *kwds, int operation) +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; + 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 *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, + PyErr_Format(PyExc_ValueError, "%s only supported for binary functions", _reduce_type[operation]); return NULL; @@ -2497,26 +2497,26 @@ 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, + 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, + 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, + &op, &axis, + PyArray_DescrConverter2, &otype, PyArray_OutputConverter, &out)) return NULL; } - - /* Ensure input is an array */ + + /* Ensure input is an array */ if (!PyArray_Check(op) && !PyArray_IsScalar(op, Generic)) { context = Py_BuildValue("O(O)i", self, op, 0); } @@ -2532,13 +2532,13 @@ PyErr_Format(PyExc_TypeError, "cannot %s on a scalar", _reduce_type[operation]); Py_DECREF(mp); - return NULL; + return NULL; } /* Check to see that type (and otype) is not FLEXIBLE */ - if (PyArray_ISFLEXIBLE(mp) || + if (PyArray_ISFLEXIBLE(mp) || (otype && PyTypeNum_ISFLEXIBLE(otype->type_num))) { - PyErr_Format(PyExc_TypeError, + PyErr_Format(PyExc_TypeError, "cannot perform %s with flexible type", _reduce_type[operation]); Py_DECREF(mp); @@ -2561,7 +2561,7 @@ } if (otype == NULL) { - /* For integer types --- makes sure at + /* For integer types --- makes sure at least a long is used */ int typenum = PyArray_TYPE(mp); if (PyTypeNum_ISINTEGER(typenum) && \ @@ -2581,15 +2581,15 @@ switch(operation) { case UFUNC_REDUCE: - ret = (PyArrayObject *)PyUFunc_Reduce(self, mp, out, axis, + ret = (PyArrayObject *)PyUFunc_Reduce(self, mp, out, axis, otype->type_num); break; case UFUNC_ACCUMULATE: - ret = (PyArrayObject *)PyUFunc_Accumulate(self, mp, out, axis, + ret = (PyArrayObject *)PyUFunc_Accumulate(self, mp, out, axis, otype->type_num); break; case UFUNC_REDUCEAT: - ret = (PyArrayObject *)PyUFunc_Reduceat(self, mp, indices, out, + ret = (PyArrayObject *)PyUFunc_Reduceat(self, mp, indices, out, axis, otype->type_num); Py_DECREF(indices); break; @@ -2604,30 +2604,30 @@ else { Py_DECREF(ret); return res; - } + } } return PyArray_Return(ret); - + } /* This function analyzes the input arguments and determines an appropriate __array_wrap__ function to call - for the outputs. + for the outputs. - If an output argument is provided, then it is wrapped + If an output argument is provided, then it is wrapped with its own __array_wrap__ not with the one determined by - the input arguments. + the input arguments. if the provided output argument is already an array, the wrapping function is None (which means no wrapping will - be done --- not even PyArray_Return). + be done --- not even PyArray_Return). 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) +_find_array_wrap(PyObject *args, PyObject **output_wrap, int nin, int nout) { int nargs, i; int np = 0; @@ -2659,11 +2659,11 @@ } if (np >= 2) { wrap = wraps[0]; - maxpriority = PyArray_GetPriority(with_wrap[0], + maxpriority = PyArray_GetPriority(with_wrap[0], PyArray_SUBTYPE_PRIORITY); for (i = 1; i < np; ++i) { priority = \ - PyArray_GetPriority(with_wrap[i], + PyArray_GetPriority(with_wrap[i], PyArray_SUBTYPE_PRIORITY); if (priority > maxpriority) { maxpriority = priority; @@ -2676,18 +2676,18 @@ } /* Here wrap is the wrapping function determined from the - input arrays (could be NULL). + 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. + exact ndarray so that no PyArray_Return is + done in that case. */ for (i=0; inargs; i++) mps[i] = NULL; - + errval = PyUFunc_GenericFunction(self, args, mps); if (errval < 0) { for(i=0; inargs; i++) { @@ -2751,40 +2751,40 @@ return Py_NotImplemented; } } - + for(i=0; inin; i++) Py_DECREF(mps[i]); - /* Use __array_wrap__ on all outputs + /* 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 + use __array_wrap__ of input object with largest __array_priority__ (default = 0.0) */ - /* Exception: we should not wrap outputs for items already + /* 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 + 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. + method --- the __array_wrap__ method to call. */ _find_array_wrap(args, wraparr, self->nin, self->nout); - + /* wrap outputs */ for (i=0; inout; 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 + /* 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 + Py_DECREF(mps[j]); /* should trigger the copy back into old */ mps[j] = (PyArrayObject *)old; } @@ -2800,8 +2800,8 @@ if (res == NULL && \ PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); - res = PyObject_CallFunctionObjArgs(wrap, - mps[j], + res = PyObject_CallFunctionObjArgs(wrap, + mps[j], NULL); } Py_DECREF(wrap); @@ -2816,10 +2816,10 @@ /* default behavior */ retobj[i] = PyArray_Return(mps[j]); } - - if (self->nout == 1) { + + if (self->nout == 1) { return retobj[0]; - } else { + } else { ret = (PyTupleObject *)PyTuple_New(self->nout); for(i=0; inout; i++) { PyTuple_SET_ITEM(ret, i, retobj[i]); @@ -2836,9 +2836,9 @@ { PyObject *thedict; PyObject *res; - + if (!PyArg_ParseTuple(args, "")) return NULL; - + if (PyUFunc_PYVALS_NAME == NULL) { PyUFunc_PYVALS_NAME = PyString_InternFromString(UFUNC_PYVALS_NAME); } @@ -2861,26 +2861,26 @@ } #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. */ -static int +static int ufunc_update_use_defaults(void) { PyObject *errobj; int errmask, bufsize; int res; - + PyUFunc_NUM_NODEFAULTS += 1; - res = PyUFunc_GetPyValues("test", &bufsize, &errmask, + res = PyUFunc_GetPyValues("test", &bufsize, &errmask, &errobj); PyUFunc_NUM_NODEFAULTS -= 1; - + if (res < 0) return -1; - + if ((errmask != UFUNC_ERR_DEFAULT) || \ (bufsize != PyArray_BUFSIZE) || \ (PyTuple_GET_ITEM(errobj, 1) != Py_None)) { @@ -2900,9 +2900,9 @@ 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; @@ -2927,13 +2927,13 @@ static PyUFuncGenericFunction pyfunc_functions[] = {PyUFunc_On_Om}; -static char +static char doc_frompyfunc[] = "frompyfunc(func, nin, nout) take an arbitrary python function that takes nin objects as input and returns nout objects and return a universal function (ufunc). This ufunc always returns PyObject arrays"; static PyObject * ufunc_frompyfunc(PyObject *dummy, PyObject *args, PyObject *kwds) { /* Keywords are ignored for now */ - + PyObject *function, *pyname=NULL; int nin, nout, i; PyUFunc_PyFuncData *fdata; @@ -2948,7 +2948,7 @@ 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); @@ -2957,7 +2957,7 @@ self->nin = nin; self->nout = nout; self->nargs = nin+nout; - self->identity = PyUFunc_None; + self->identity = PyUFunc_None; self->functions = pyfunc_functions; self->ntypes = 1; @@ -2966,12 +2966,12 @@ 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); @@ -3002,45 +3002,45 @@ fdata->nin = nin; fdata->nout = nout; fdata->callable = function; - + self->data = (void **)(((char *)self->ptr) + offset[0]); self->data[0] = (void *)fdata; - + self->types = (char *)self->data + sizeof(void *); for (i=0; inargs; i++) self->types[i] = PyArray_OBJECT; str = self->types + offset[1]; memcpy(str, fname, fname_len); memcpy(str+fname_len, " (vectorized)", 14); - + self->name = str; /* Do a better job someday */ self->doc = "dynamic ufunc based on a python function"; - - + + return (PyObject *)self; } /*UFUNC_API*/ static PyObject * -PyUFunc_FromFuncAndData(PyUFuncGenericFunction *func, void **data, +PyUFunc_FromFuncAndData(PyUFuncGenericFunction *func, void **data, char *types, int ntypes, - int nin, int nout, int identity, - char *name, char *doc, int check_return) + int nin, int nout, int identity, + char *name, char *doc, int check_return) { PyUFuncObject *self; 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->functions = func; self->data = data; self->types = types; @@ -3049,19 +3049,19 @@ self->ptr = NULL; self->obj = NULL; self->userloops=NULL; - + if (name == NULL) self->name = "?"; else self->name = name; - + if (doc == NULL) self->doc = "NULL"; else self->doc = doc; - + return (PyObject *)self; } /*UFUNC_API*/ static int -PyUFunc_RegisterLoopForType(PyUFuncObject *ufunc, +PyUFunc_RegisterLoopForType(PyUFuncObject *ufunc, int usertype, PyUFuncGenericFunction function, int *arg_types, @@ -3069,16 +3069,16 @@ { PyArray_Descr *descr; PyObject *key, *cobj; - int ret; - + int ret; + descr=PyArray_DescrFromType(usertype); if ((usertype < PyArray_USERDEF) || (descr==NULL)) { - PyErr_SetString(PyExc_TypeError, + PyErr_SetString(PyExc_TypeError, "unknown user-defined type"); return -1; } Py_DECREF(descr); - + if (ufunc->userloops == NULL) { ufunc->userloops = PyDict_New(); } @@ -3114,7 +3114,7 @@ cobj3 = PyCObject_FromVoidPtr(data, NULL); if (cobj3 == NULL) { Py_DECREF(cobj2); - Py_DECREF(cobj); + Py_DECREF(cobj); Py_DECREF(key); return -1; } @@ -3140,9 +3140,9 @@ ufunc_repr(PyUFuncObject *self) { char buf[100]; - + sprintf(buf, "", self->name); - + return PyString_FromString(buf); } @@ -3156,7 +3156,7 @@ */ static PyObject * -ufunc_outer(PyUFuncObject *self, PyObject *args) +ufunc_outer(PyUFuncObject *self, PyObject *args) { int i; PyObject *ret; @@ -3170,20 +3170,20 @@ "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); @@ -3193,28 +3193,28 @@ /* Construct new shape tuple */ shape1 = PyTuple_New(ap1->nd); if (shape1 == NULL) goto fail; - for (i=0; ind; i++) - PyTuple_SET_ITEM(shape1, i, + for (i=0; ind; i++) + PyTuple_SET_ITEM(shape1, i, PyLong_FromLongLong((longlong)ap1-> \ dimensions[i])); - + shape2 = PyTuple_New(ap2->nd); - for (i=0; ind; i++) + for (i=0; ind; 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); + Py_DECREF(ap_new); ret = ufunc_generic_call(self, new_args); Py_DECREF(new_args); return ret; @@ -3229,32 +3229,32 @@ static PyObject * -ufunc_reduce(PyUFuncObject *self, PyObject *args, PyObject *kwds) +ufunc_reduce(PyUFuncObject *self, PyObject *args, PyObject *kwds) { - + return PyUFunc_GenericReduction(self, args, kwds, UFUNC_REDUCE); } static PyObject * -ufunc_accumulate(PyUFuncObject *self, PyObject *args, PyObject *kwds) +ufunc_accumulate(PyUFuncObject *self, PyObject *args, PyObject *kwds) { - + return PyUFunc_GenericReduction(self, args, kwds, UFUNC_ACCUMULATE); } static PyObject * -ufunc_reduceat(PyUFuncObject *self, PyObject *args, PyObject *kwds) -{ +ufunc_reduceat(PyUFuncObject *self, PyObject *args, PyObject *kwds) +{ 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, + {"accumulate", (PyCFunction)ufunc_accumulate, METH_VARARGS | METH_KEYWORDS}, - {"reduceat", (PyCFunction)ufunc_reduceat, - METH_VARARGS | METH_KEYWORDS}, + {"reduceat", (PyCFunction)ufunc_reduceat, + METH_VARARGS | METH_KEYWORDS}, {"outer", (PyCFunction)ufunc_outer, METH_VARARGS}, {NULL, NULL} /* sentinel */ }; @@ -3265,7 +3265,7 @@ y1,y2,...,yn */ static PyObject * -_makeargs(int num, char *ltr) +_makeargs(int num, char *ltr) { PyObject *str; int i; @@ -3286,12 +3286,12 @@ _typecharfromnum(int num) { PyArray_Descr *descr; char ret; - + descr = PyArray_DescrFromType(num); ret = descr->type; Py_DECREF(descr); return ret; -} +} static PyObject * ufunc_get_doc(PyUFuncObject *self) @@ -3300,15 +3300,15 @@ /* 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 + /* 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", + doc = PyString_FromFormat("%s = %s(%s) %s", PyString_AS_STRING(outargs), - self->name, + self->name, PyString_AS_STRING(inargs), self->doc); Py_DECREF(outargs); @@ -3372,7 +3372,7 @@ } _pya_free(t); return list; - + } static PyObject * @@ -3396,7 +3396,7 @@ #undef _typecharfromnum -static char Ufunctype__doc__[] = +static char Ufunctype__doc__[] = "Optimized functions make it possible to implement arithmetic "\ "with arrays efficiently"; Modified: trunk/numpy/core/src/umathmodule.c.src =================================================================== --- trunk/numpy/core/src/umathmodule.c.src 2006-08-18 21:29:36 UTC (rev 3039) +++ trunk/numpy/core/src/umathmodule.c.src 2006-08-19 06:01:10 UTC (rev 3040) @@ -244,21 +244,21 @@ #ifndef HAVE_RINT -static double +static double rint (double x) { double y, r; - + y = floor(x); r = x - y; - + 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: + rndup: y+=1.0; } } @@ -1191,7 +1191,7 @@ char *i1 = args[0], *op = args[1]; c at typ@ *x, *y; @typ@ xr, xi, xmag2; - + for (i = 0; i < n; i++, i1 += is1, op += os) { x = (c at typ@ *)i1; y = (c at typ@ *)op; From numpy-svn at scipy.org Mon Aug 21 14:52:10 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 13:52:10 -0500 (CDT) Subject: [Numpy-svn] r3041 - in trunk/numpy/core: code_generators include/numpy src Message-ID: <20060821185210.3A1F639C00B@new.scipy.org> Author: oliphant Date: 2006-08-21 13:52:06 -0500 (Mon, 21 Aug 2006) New Revision: 3041 Modified: trunk/numpy/core/code_generators/ufunc_api_order.txt trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/src/ufuncobject.c Log: Add simple function to replace Ufunc Modified: trunk/numpy/core/code_generators/ufunc_api_order.txt =================================================================== --- trunk/numpy/core/code_generators/ufunc_api_order.txt 2006-08-19 06:01:10 UTC (rev 3040) +++ trunk/numpy/core/code_generators/ufunc_api_order.txt 2006-08-21 18:52:06 UTC (rev 3041) @@ -27,3 +27,4 @@ PyUFunc_clearfperr PyUFunc_getfperr PyUFunc_handlefperr +PyUFunc_ReplaceLoopBySignature \ No newline at end of file Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-19 06:01:10 UTC (rev 3040) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-21 18:52:06 UTC (rev 3041) @@ -16,12 +16,6 @@ #include "noprefix.h" #endif - -/* Add signal handling macros */ - -#define NPY_SIG_ON -#define NPY_SIG_OFF -#define NPY_SIG_CHECK - - +#ifndef NPY_NO_SIGNAL +#include "npy_interrupt.h" #endif Modified: trunk/numpy/core/src/ufuncobject.c =================================================================== --- trunk/numpy/core/src/ufuncobject.c 2006-08-19 06:01:10 UTC (rev 3040) +++ trunk/numpy/core/src/ufuncobject.c 2006-08-21 18:52:06 UTC (rev 3041) @@ -3022,7 +3022,31 @@ return (PyObject *)self; } +/*UFUNC_API*/ +static int +PyUFunc_ReplaceLoopBySignature(PyUFuncObject *func, + PyUFuncGenericFunction *newfunc, + int *signature, + PyUFuncGenericFunction *oldfunc) +{ + int i,j; + /* Find the location of the matching signature */ + for (i=0; intypes; i++) { + for (j=0; jnargs; j++) { + if (signature[j] == func->types[i*self->nargs+j]) + break; + } + if (j >= func->nargs) return -1; + + if (oldfunc != NULL) { + *oldfunc = func->functions[i]; + } + func->functions[i] = newfunc; + } + return -1; +} + /*UFUNC_API*/ static PyObject * PyUFunc_FromFuncAndData(PyUFuncGenericFunction *func, void **data, From numpy-svn at scipy.org Mon Aug 21 15:03:30 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 14:03:30 -0500 (CDT) Subject: [Numpy-svn] r3042 - trunk/numpy/core/include/numpy Message-ID: <20060821190330.1581339C00B@new.scipy.org> Author: oliphant Date: 2006-08-21 14:03:29 -0500 (Mon, 21 Aug 2006) New Revision: 3042 Added: trunk/numpy/core/include/numpy/npy_interrupt.h Log: Include interrupt stub. Added: trunk/numpy/core/include/numpy/npy_interrupt.h =================================================================== --- trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-21 18:52:06 UTC (rev 3041) +++ trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-21 19:03:29 UTC (rev 3042) @@ -0,0 +1,24 @@ + +/* Signal handling: + +In your C-extension: + +Around a block of code you want to be interruptable + +NPY_SIG_ON +[code] +NPY_SIG_OFF + +*/ + +/* Add signal handling macros */ + +#ifndef NPY_INTERRUPT_H +#define NPY_INTERRUPT_H + +#define NPY_SIG_ON +#define NPY_SIG_OFF +#define NPY_SIG_CHECK + + +#endif /* NPY_INTERRUPT_H */ From numpy-svn at scipy.org Mon Aug 21 15:04:26 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 14:04:26 -0500 (CDT) Subject: [Numpy-svn] r3043 - trunk/numpy/core/include/numpy Message-ID: <20060821190426.B254D39C00B@new.scipy.org> Author: oliphant Date: 2006-08-21 14:04:25 -0500 (Mon, 21 Aug 2006) New Revision: 3043 Modified: trunk/numpy/core/include/numpy/arrayobject.h Log: Fix missing #endif Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-21 19:03:29 UTC (rev 3042) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-21 19:04:25 UTC (rev 3043) @@ -19,3 +19,5 @@ #ifndef NPY_NO_SIGNAL #include "npy_interrupt.h" #endif + +#endif From numpy-svn at scipy.org Mon Aug 21 15:55:43 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 14:55:43 -0500 (CDT) Subject: [Numpy-svn] r3044 - in trunk/numpy: core/code_generators core/src f2py lib numarray/numpy Message-ID: <20060821195543.DC2DC39C05A@new.scipy.org> Author: oliphant Date: 2006-08-21 14:55:37 -0500 (Mon, 21 Aug 2006) New Revision: 3044 Modified: trunk/numpy/core/code_generators/generate_array_api.py trunk/numpy/core/code_generators/generate_ufunc_api.py trunk/numpy/core/src/ufuncobject.c trunk/numpy/f2py/rules.py trunk/numpy/lib/function_base.py trunk/numpy/numarray/numpy/libnumarray.h Log: Remove usage of FatalError and fix linspace to end at stop if endpoint is True Modified: trunk/numpy/core/code_generators/generate_array_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_array_api.py 2006-08-21 19:04:25 UTC (rev 3043) +++ trunk/numpy/core/code_generators/generate_array_api.py 2006-08-21 19:55:37 UTC (rev 3044) @@ -88,7 +88,7 @@ return 0; } -#define import_array() { if (_import_array() < 0) {PyErr_Print(); Py_FatalError("numpy.core.multiarray failed to import... exiting.\n"); } } +#define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return; } } #endif Modified: trunk/numpy/core/code_generators/generate_ufunc_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_ufunc_api.py 2006-08-21 19:04:25 UTC (rev 3043) +++ trunk/numpy/core/code_generators/generate_ufunc_api.py 2006-08-21 19:55:37 UTC (rev 3044) @@ -48,7 +48,7 @@ return 0; } -#define import_umath() { if (_import_umath() < 0) {PyErr_Print(); Py_FatalError("numpy.core.umath failed to import... exiting.\n"); }} +#define import_umath() { if (_import_umath() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.umath failed to import\n"); return; }} #define import_ufunc import_umath Modified: trunk/numpy/core/src/ufuncobject.c =================================================================== --- trunk/numpy/core/src/ufuncobject.c 2006-08-21 19:04:25 UTC (rev 3043) +++ trunk/numpy/core/src/ufuncobject.c 2006-08-21 19:55:37 UTC (rev 3044) @@ -3025,7 +3025,7 @@ /*UFUNC_API*/ static int PyUFunc_ReplaceLoopBySignature(PyUFuncObject *func, - PyUFuncGenericFunction *newfunc, + PyUFuncGenericFunction newfunc, int *signature, PyUFuncGenericFunction *oldfunc) { @@ -3033,7 +3033,7 @@ /* Find the location of the matching signature */ for (i=0; intypes; i++) { for (j=0; jnargs; j++) { - if (signature[j] == func->types[i*self->nargs+j]) + if (signature[j] == func->types[i*func->nargs+j]) break; } if (j >= func->nargs) return -1; Modified: trunk/numpy/f2py/rules.py =================================================================== --- trunk/numpy/f2py/rules.py 2006-08-21 19:04:25 UTC (rev 3043) +++ trunk/numpy/f2py/rules.py 2006-08-21 19:55:37 UTC (rev 3044) @@ -173,8 +173,8 @@ \tm = #modulename#_module = Py_InitModule(\"#modulename#\", f2py_module_methods); \tPyFortran_Type.ob_type = &PyType_Type; \timport_array(); -\tif (PyErr_Occurred()) -\t\tPy_FatalError(\"can't initialize module #modulename# (failed to import numpy)\"); +\tif (PyErr_Occurred()) +\t\t{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return;} \td = PyModule_GetDict(m); \ts = PyString_FromString(\"$R"""+"""evision: $\"); \tPyDict_SetItemString(d, \"__version__\", s); Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-21 19:04:25 UTC (rev 3043) +++ trunk/numpy/lib/function_base.py 2006-08-21 19:55:37 UTC (rev 3044) @@ -42,6 +42,8 @@ else: step = (stop-start)/float(num) y = _nx.arange(0, num) * step + start + if endpoint: + y[-1] = stop if retstep: return y, step else: Modified: trunk/numpy/numarray/numpy/libnumarray.h =================================================================== --- trunk/numpy/numarray/numpy/libnumarray.h 2006-08-21 19:04:25 UTC (rev 3043) +++ trunk/numpy/numarray/numpy/libnumarray.h 2006-08-21 19:55:37 UTC (rev 3044) @@ -56,7 +56,7 @@ } \ } -#define import_libnumarray() _import_libnumarray(); if (PyErr_Occurred()) { PyErr_Print(); Py_FatalError("numpy.numarray._capi failed to import... exiting.\n"); } +#define import_libnumarray() _import_libnumarray(); if (PyErr_Occurred()) { PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.numarray._capi failed to import.\n"); return; } #endif From numpy-svn at scipy.org Mon Aug 21 16:45:04 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 15:45:04 -0500 (CDT) Subject: [Numpy-svn] r3045 - trunk/numpy/lib Message-ID: <20060821204504.450EC39C01B@new.scipy.org> Author: oliphant Date: 2006-08-21 15:45:00 -0500 (Mon, 21 Aug 2006) New Revision: 3045 Modified: trunk/numpy/lib/function_base.py Log: Re-factor fix to linspace Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-21 19:55:37 UTC (rev 3044) +++ trunk/numpy/lib/function_base.py 2006-08-21 20:45:00 UTC (rev 3045) @@ -39,11 +39,11 @@ if num == 1: return array([float(start)]) step = (stop-start)/float((num-1)) + y = _nx.arange(0, num) * step + start + y[-1] = stop else: step = (stop-start)/float(num) - y = _nx.arange(0, num) * step + start - if endpoint: - y[-1] = stop + y = _nx.arange(0, num) * step + start if retstep: return y, step else: From numpy-svn at scipy.org Mon Aug 21 16:55:35 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 15:55:35 -0500 (CDT) Subject: [Numpy-svn] r3046 - trunk/numpy/core/src Message-ID: <20060821205535.E5FBF39C01B@new.scipy.org> Author: oliphant Date: 2006-08-21 15:55:33 -0500 (Mon, 21 Aug 2006) New Revision: 3046 Modified: trunk/numpy/core/src/arrayobject.c Log: Fix shape attributes of data-types with no shape Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-21 20:45:00 UTC (rev 3045) +++ trunk/numpy/core/src/arrayobject.c 2006-08-21 20:55:33 UTC (rev 3046) @@ -10487,7 +10487,7 @@ arraydescr_shape_get(PyArray_Descr *self) { if (self->subarray == NULL) { - return Py_BuildValue("(N)", PyInt_FromLong(1)); + return PyTuple_New(0); } Py_INCREF(self->subarray->shape); return (PyObject *)(self->subarray->shape); From numpy-svn at scipy.org Mon Aug 21 17:05:05 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 16:05:05 -0500 (CDT) Subject: [Numpy-svn] r3047 - tags Message-ID: <20060821210505.B2D8739C01B@new.scipy.org> Author: oliphant Date: 2006-08-21 16:05:01 -0500 (Mon, 21 Aug 2006) New Revision: 3047 Added: tags/1.0b3/ Log: Tag the tree for 1.0b3 release Copied: tags/1.0b3 (from rev 3046, trunk) From numpy-svn at scipy.org Mon Aug 21 17:05:36 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 16:05:36 -0500 (CDT) Subject: [Numpy-svn] r3048 - trunk/numpy Message-ID: <20060821210536.4AAEB39C01B@new.scipy.org> Author: oliphant Date: 2006-08-21 16:05:33 -0500 (Mon, 21 Aug 2006) New Revision: 3048 Modified: trunk/numpy/version.py Log: Make trunk 1.0b4.dev release Modified: trunk/numpy/version.py =================================================================== --- trunk/numpy/version.py 2006-08-21 21:05:01 UTC (rev 3047) +++ trunk/numpy/version.py 2006-08-21 21:05:33 UTC (rev 3048) @@ -1,4 +1,4 @@ -version='1.0b3' +version='1.0b4444' release=False if not release: From numpy-svn at scipy.org Mon Aug 21 17:06:25 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 16:06:25 -0500 (CDT) Subject: [Numpy-svn] r3049 - tags/1.0b3/numpy Message-ID: <20060821210625.7AAD539C01B@new.scipy.org> Author: oliphant Date: 2006-08-21 16:06:24 -0500 (Mon, 21 Aug 2006) New Revision: 3049 Modified: tags/1.0b3/numpy/version.py Log: Make release 1.0b3 a release Modified: tags/1.0b3/numpy/version.py =================================================================== --- tags/1.0b3/numpy/version.py 2006-08-21 21:05:33 UTC (rev 3048) +++ tags/1.0b3/numpy/version.py 2006-08-21 21:06:24 UTC (rev 3049) @@ -1,5 +1,5 @@ version='1.0b3' -release=False +release=True if not release: import os From numpy-svn at scipy.org Mon Aug 21 17:22:06 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 21 Aug 2006 16:22:06 -0500 (CDT) Subject: [Numpy-svn] r3050 - trunk/numpy Message-ID: <20060821212206.7D27A39C01B@new.scipy.org> Author: oliphant Date: 2006-08-21 16:22:03 -0500 (Mon, 21 Aug 2006) New Revision: 3050 Modified: trunk/numpy/version.py Log: Fix silly version number Modified: trunk/numpy/version.py =================================================================== --- trunk/numpy/version.py 2006-08-21 21:06:24 UTC (rev 3049) +++ trunk/numpy/version.py 2006-08-21 21:22:03 UTC (rev 3050) @@ -1,4 +1,4 @@ -version='1.0b4444' +version='1.0b4' release=False if not release: From numpy-svn at scipy.org Tue Aug 22 12:02:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 22 Aug 2006 11:02:56 -0500 (CDT) Subject: [Numpy-svn] r3051 - trunk/numpy/core/src Message-ID: <20060822160256.6CD3839C0C8@new.scipy.org> Author: oliphant Date: 2006-08-22 11:02:52 -0500 (Tue, 22 Aug 2006) New Revision: 3051 Modified: trunk/numpy/core/src/arrayobject.c Log: Fix real and imag attributes for byte-swapped arrays. Fixes ticket #265 Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-21 21:22:03 UTC (rev 3050) +++ trunk/numpy/core/src/arrayobject.c 2006-08-22 16:02:52 UTC (rev 3051) @@ -6280,27 +6280,51 @@ } } +/* Create a view of a complex array with an equivalent data-type + except it is real instead of complex. +*/ +static PyArrayObject * +_get_part(PyArrayObject *self, int imag) +{ + 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; +} + static PyObject * array_real_get(PyArrayObject *self) { PyArrayObject *ret; if (PyArray_ISCOMPLEX(self)) { - ret = (PyArrayObject *)PyArray_New(self->ob_type, - self->nd, - self->dimensions, - self->descr->type_num - \ - PyArray_NUM_FLOATTYPE, - self->strides, - self->data, - 0, - self->flags, (PyObject *)self); - if (ret == NULL) return NULL; - ret->flags &= ~CONTIGUOUS; - ret->flags &= ~FORTRAN; - Py_INCREF(self); - ret->base = (PyObject *)self; + ret = _get_part(self, 0); return (PyObject *)ret; } else { @@ -6317,30 +6341,16 @@ PyArrayObject *new; int rint; - new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL); - if (new == NULL) return -1; - if (PyArray_ISCOMPLEX(self)) { - ret = (PyArrayObject *)PyArray_New(self->ob_type, - self->nd, - self->dimensions, - self->descr->type_num - \ - PyArray_NUM_FLOATTYPE, - self->strides, - self->data, - 0, - self->flags, - (PyObject *)self); - if (ret == NULL) {Py_DECREF(new); return -1;} - ret->flags &= ~CONTIGUOUS; - ret->flags &= ~FORTRAN; - Py_INCREF(self); - ret->base = (PyObject *)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); @@ -6354,21 +6364,7 @@ PyArray_Descr *type; if (PyArray_ISCOMPLEX(self)) { - type = PyArray_DescrFromType(self->descr->type_num - - PyArray_NUM_FLOATTYPE); - ret = (PyArrayObject *) \ - PyArray_NewFromDescr(self->ob_type, - type, - self->nd, - self->dimensions, - self->strides, - self->data + type->elsize, - self->flags, (PyObject *)self); - if (ret == NULL) return NULL; - ret->flags &= ~CONTIGUOUS; - ret->flags &= ~FORTRAN; - Py_INCREF(self); - ret->base = (PyObject *)self; + ret = _get_part(self, 1); return (PyObject *) ret; } else { @@ -6398,34 +6394,18 @@ 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) return -1; - ret = (PyArrayObject *)PyArray_New(self->ob_type, - self->nd, - self->dimensions, - self->descr->type_num - \ - PyArray_NUM_FLOATTYPE, - self->strides, - self->data + \ - (self->descr->elsize >> 1), - 0, - self->flags, (PyObject *)self); - if (ret == NULL) { - Py_DECREF(new); - return -1; - } - ret->flags &= ~CONTIGUOUS; - ret->flags &= ~FORTRAN; - Py_INCREF(self); - ret->base = (PyObject *)self; + 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, "does not have imaginary " \ - "part to set"); + PyErr_SetString(PyExc_TypeError, "array does not have "\ + "imaginary part to set"); return -1; } } From numpy-svn at scipy.org Tue Aug 22 12:30:14 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 22 Aug 2006 11:30:14 -0500 (CDT) Subject: [Numpy-svn] r3052 - in trunk/numpy/core: src tests Message-ID: <20060822163014.BACD439C08A@new.scipy.org> Author: oliphant Date: 2006-08-22 11:30:10 -0500 (Tue, 22 Aug 2006) New Revision: 3052 Modified: trunk/numpy/core/src/arraytypes.inc.src trunk/numpy/core/tests/test_regression.py Log: Fix copyswapn for complex data-types Modified: trunk/numpy/core/src/arraytypes.inc.src =================================================================== --- trunk/numpy/core/src/arraytypes.inc.src 2006-08-22 16:02:52 UTC (rev 3051) +++ trunk/numpy/core/src/arraytypes.inc.src 2006-08-22 16:30:10 UTC (rev 3052) @@ -1041,7 +1041,8 @@ } if (swap) { - _strided_byte_swap(dst, dstride, n, sizeof(@type@)); + _strided_byte_swap(dst, dstride, n, SIZEOF_ at fsize@); + _strided_byte_swap(dst + SIZEOF_ at fsize@, dstride, n, SIZEOF_ at fsize@); } } Modified: trunk/numpy/core/tests/test_regression.py =================================================================== --- trunk/numpy/core/tests/test_regression.py 2006-08-22 16:02:52 UTC (rev 3051) +++ trunk/numpy/core/tests/test_regression.py 2006-08-22 16:30:10 UTC (rev 3052) @@ -353,5 +353,12 @@ v = N.array([1,2,3,4,5,6,7,8,9,10]) assert_equal(N.lexsort(v),0) + def check_swap_real(self, level=rlevel): + """Ticket #265""" + assert_equal(N.arange(4,dtype='>c8').imag.max(),0.0) + assert_equal(N.arange(4,dtype=' Author: cookedm Date: 2006-08-22 19:37:52 -0500 (Tue, 22 Aug 2006) New Revision: 3053 Modified: trunk/numpy/doc/CAPI.txt Log: Fix a formatting bug in CAPI.txt Modified: trunk/numpy/doc/CAPI.txt =================================================================== --- trunk/numpy/doc/CAPI.txt 2006-08-22 16:30:10 UTC (rev 3052) +++ trunk/numpy/doc/CAPI.txt 2006-08-23 00:37:52 UTC (rev 3053) @@ -6,29 +6,29 @@ :Discussions to: scipy-dev at scipy.org :Created: October 2005 -The CAPI of NumPy is (mostly) backward compatible with Numeric. +The C API of NumPy is (mostly) backward compatible with Numeric. There are a few non-standard Numeric usages (that were not really part of the API) that will need to be changed: - * If you used any of the function pointers in the ``PyArray_Descr`` - structure you will have to modify your usage of those. First, - the pointers are all under the member named ``f``. So ``descr->cast`` - is now ``descr->f->cast``. In addition, the - casting functions have eliminated the strides argument (use - ``PyArray_CastTo`` if you need strided casting). All functions have - one or two ``PyArrayObject *`` arguments at the end. This allows the - flexible arrays and mis-behaved arrays to be handled. +* If you used any of the function pointers in the ``PyArray_Descr`` + structure you will have to modify your usage of those. First, + the pointers are all under the member named ``f``. So ``descr->cast`` + is now ``descr->f->cast``. In addition, the + casting functions have eliminated the strides argument (use + ``PyArray_CastTo`` if you need strided casting). All functions have + one or two ``PyArrayObject *`` arguments at the end. This allows the + flexible arrays and mis-behaved arrays to be handled. - * The ``descr->zero`` and ``descr->one`` constants have been replaced with - function calls, ``PyArray_Zero``, and ``PyArray_One`` (be sure to read the - code and free the resulting memory if you use these calls). +* The ``descr->zero`` and ``descr->one`` constants have been replaced with + function calls, ``PyArray_Zero``, and ``PyArray_One`` (be sure to read the + code and free the resulting memory if you use these calls). - * If you passed ``array->dimensions`` and ``array->strides`` around - to functions, you will need to fix some code. These are now - ``npy_intp*`` pointers. On 32-bit systems there won't be a problem. - However, on 64-bit systems, you will need to make changes to avoid - errors and segfaults. +* If you passed ``array->dimensions`` and ``array->strides`` around + to functions, you will need to fix some code. These are now + ``npy_intp*`` pointers. On 32-bit systems there won't be a problem. + However, on 64-bit systems, you will need to make changes to avoid + errors and segfaults. The header files ``arrayobject.h`` and ``ufuncobject.h`` contain many defines @@ -37,10 +37,9 @@ their function signatures. All of these headers are installed to +``/site-packages/numpy/core/include`` -/site-packages/numpy/core/include - Getting arrays in C-code ========================= From numpy-svn at scipy.org Wed Aug 23 15:56:35 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 23 Aug 2006 14:56:35 -0500 (CDT) Subject: [Numpy-svn] r3054 - in trunk/numpy/core: code_generators include/numpy src Message-ID: <20060823195635.AC0B639C084@new.scipy.org> Author: oliphant Date: 2006-08-23 14:56:28 -0500 (Wed, 23 Aug 2006) New Revision: 3054 Modified: trunk/numpy/core/code_generators/generate_umath.py trunk/numpy/core/include/numpy/arrayobject.h trunk/numpy/core/include/numpy/npy_interrupt.h trunk/numpy/core/src/umathmodule.c.src Log: Move complex multiply and divide from the generic interface to the specific interface --- saves about 10% speed increase. Modified: trunk/numpy/core/code_generators/generate_umath.py =================================================================== --- trunk/numpy/core/code_generators/generate_umath.py 2006-08-23 00:37:52 UTC (rev 3053) +++ trunk/numpy/core/code_generators/generate_umath.py 2006-08-23 19:56:28 UTC (rev 3054) @@ -101,6 +101,7 @@ nobool = all[1:] nobool_or_obj = all[1:-1] intflt = ints+flts +intfltcmplx = nobool_or_obj nocmplx = bints+flts nocmplxO = nocmplx+O nocmplxM = nocmplx+M @@ -122,22 +123,19 @@ 'multiply' : Ufunc(2, 1, One, 'multiplies the arguments elementwise.', - TD(nocmplx), - TD(cmplx, f='prod'), + TD(noobj), TD(O, f='PyNumber_Multiply'), ), 'divide' : Ufunc(2, 1, One, 'divides the arguments elementwise.', - TD(intflt), - TD(cmplx, f='quot'), + TD(intfltcmplx), TD(O, f='PyNumber_Divide'), ), 'floor_divide' : Ufunc(2, 1, One, 'floor divides the arguments elementwise.', - TD(intflt), - TD(cmplx, f='floor_quot'), + TD(intfltcmplx), TD(O, f='PyNumber_FloorDivide'), ), 'true_divide' : @@ -145,8 +143,7 @@ 'true divides the arguments elementwise.', TD('bBhH', out='f'), TD('iIlLqQ', out='d'), - TD(flts), - TD(cmplx, f='quot'), + TD(flts+cmplx), TD(O, f='PyNumber_TrueDivide'), ), 'conjugate' : Modified: trunk/numpy/core/include/numpy/arrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/arrayobject.h 2006-08-23 00:37:52 UTC (rev 3053) +++ trunk/numpy/core/include/numpy/arrayobject.h 2006-08-23 19:56:28 UTC (rev 3054) @@ -16,8 +16,6 @@ #include "noprefix.h" #endif -#ifndef NPY_NO_SIGNAL #include "npy_interrupt.h" -#endif #endif Modified: trunk/numpy/core/include/numpy/npy_interrupt.h =================================================================== --- trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-23 00:37:52 UTC (rev 3053) +++ trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-23 19:56:28 UTC (rev 3054) @@ -1,14 +1,88 @@ /* Signal handling: -In your C-extension: +This header file defines macros that allow your code to handle +interrupts received during processing. Interrupts that +could reasonably be handled: -Around a block of code you want to be interruptable +SIGINT, SIGABRT, SIGALRM, SIGSEGV -NPY_SIG_ON +****Warning*************** + +Do not allow code that creates temporary memory or increases reference +counts of Python objects to be interrupted unless you handle decrementing +the reference counts and freeing any allocated memory in the clean-up code. + +************************** + +The mechanism for handling interrupts is conceptually simple: + + - replace the signal handler with our own home-grown version + and store the old one. + - run the code to be interrupted -- if an interrupt occurs + the handler should basically just cause a return to the + calling function for clean-up work. + - restore the old signal handler + +Of course, every code that allows interrupts must account for +returning via the interrupt and handle clean-up correctly. But, +even still, the simple paradigm is complicated by at least three +factors. + + 1) platform portability (i.e. Microsoft says not to use longjmp + to return from signal handling. They have a __try and __except + extension to C instead but what about mingw?). + 2) how to handle threads + a) apparently whether signals are delivered to every thread of + the process or the "invoking" thread is platform dependent. + b) if we use global variables to save state, then how is this + to be done in a thread-safe way. + 3) A general-purpose facility must allow for the possibility of + re-entrance (i.e. during execution of the code that is allowed + to interrupt, we might call back into this very section of code + serially). + +Ideas: + + 1) Start by implementing an approach that works on platforms that + can use setjmp and longjmp functionality and does nothing + on other platforms. Initially only catch SIGINT. + + 2) Handle threads by storing global information in a linked-list + with a process-id key. Then use a call-back function that longjmps + only to the correct buffer. + + 3) Store a local copy of the global information and restore it on clean-up + so that re-entrance works. + + +Interface: + +In your C-extension. around a block of code you want to be interruptable + +NPY_SIG_TRY { [code] -NPY_SIG_OFF +} +NPY_SIG_EXCEPT(sigval) { +[signal return] +} +NPY_SIG_ELSE +[normal return] +sigval is a local variable that will receive what +signal was received. You can use it to perform different +actions based on the signal received. + +Default actions (setting of specific Python errors) +can be obtained with + +NPY_SIG_TRY { +[code] +NPY_SIG_EXCEPT_GOTO(label) +[normal return] + +label: + [error return] */ /* Add signal handling macros */ @@ -16,9 +90,16 @@ #ifndef NPY_INTERRUPT_H #define NPY_INTERRUPT_H +#ifdef NPY_NO_SIGNAL + #define NPY_SIG_ON #define NPY_SIG_OFF -#define NPY_SIG_CHECK +#else +#define NPY_SIG_ON +#define NPY_SIG_OFF + +#endif /* NPY_NO_SIGNAL */ + #endif /* NPY_INTERRUPT_H */ Modified: trunk/numpy/core/src/umathmodule.c.src =================================================================== --- trunk/numpy/core/src/umathmodule.c.src 2006-08-23 00:37:52 UTC (rev 3053) +++ trunk/numpy/core/src/umathmodule.c.src 2006-08-23 19:56:28 UTC (rev 3054) @@ -593,16 +593,6 @@ } static void -nc_floor_quot at c@(c at typ@ *a, c at typ@ *b, c at 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 = floor at c@((ar*br + ai*bi)/d); - r->imag = 0; - return; -} - -static void nc_sqrt at c@(c at typ@ *x, c at typ@ *r) { @typ@ s,d; @@ -979,8 +969,67 @@ } /**end repeat**/ + /**begin repeat +#TYP= CFLOAT, CDOUBLE, CLONGDOUBLE# +#typ= float, double, longdouble# +#c=f,,l# +*/ +static void + at 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; ireal, \ + ai=((c at typ@ *)i1)->imag, \ + br=((c at typ@ *)i2)->real, \ + bi=((c at typ@ *)i2)->imag; + ((c at typ@ *)op)->real = ar*br - ai*bi; + ((c at typ@ *)op)->imag = ar*bi + ai*br; + } +} +static void + at 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; ireal, \ + ai=((c at typ@ *)i1)->imag, \ + br=((c at typ@ *)i2)->real, \ + bi=((c at typ@ *)i2)->imag; + register @typ@ d = br*br + bi*bi; + ((c at typ@ *)op)->real = (ar*br + ai*bi)/d; + ((c at typ@ *)op)->imag = (ai*br - ar*bi)/d; + } +} + +static void + at 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; ireal, \ + ai=((c at typ@ *)i1)->imag, \ + br=((c at typ@ *)i2)->real, \ + bi=((c at typ@ *)i2)->imag; + register @typ@ d = br*br + bi*bi; + ((c at typ@ *)op)->real = floor at c@((ar*br + ai*bi)/d); + ((c at typ@ *)op)->imag = 0; + } +} + +#define @TYP at _true_divide @TYP at _divide +/**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# @@ -1020,13 +1069,11 @@ /**end repeat**/ /**begin repeat - -#TYP=(FLOAT,DOUBLE,LONGDOUBLE)*2# -#typ=(float,double,longdouble)*2# -#kind=divide*3, true_divide*3# +#TYP=FLOAT,DOUBLE,LONGDOUBLE# +#typ=float,double,longdouble# */ static void - at TYP@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) + at 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]; @@ -1034,6 +1081,7 @@ *((@typ@ *)op)=*((@typ@ *)i1) / *((@typ@ *)i2); } } +#define @TYP at _true_divide @TYP at _divide /**end repeat**/ /**begin repeat From numpy-svn at scipy.org Wed Aug 23 19:39:47 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 23 Aug 2006 18:39:47 -0500 (CDT) Subject: [Numpy-svn] r3055 - in trunk/numpy/core: . src Message-ID: <20060823233947.9355039C033@new.scipy.org> Author: cookedm Date: 2006-08-23 18:39:42 -0500 (Wed, 23 Aug 2006) New Revision: 3055 Modified: trunk/numpy/core/ma.py trunk/numpy/core/src/arraymethods.c Log: add .abs() as a method on the array object Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-23 19:56:28 UTC (rev 3054) +++ trunk/numpy/core/ma.py 2006-08-23 23:39:42 UTC (rev 3055) @@ -2144,6 +2144,7 @@ return MethodType(f, None, array) def not_implemented(*args, **kwds): raise NotImplementedError, "not yet implemented for numpy.ma arrays" +array.abs = array.__abs__ array.all = _m(alltrue) array.any = _m(sometrue) array.argmax = _m(argmax) Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-23 19:56:28 UTC (rev 3054) +++ trunk/numpy/core/src/arraymethods.c 2006-08-23 23:39:42 UTC (rev 3055) @@ -252,6 +252,8 @@ return PyArray_Min(self, axis, out); } +static char doc_abs[] = "a.abs() returns abs(a)"; + static char doc_swapaxes[] = "a.swapaxes(axis1, axis2) returns new view with axes swapped."; static PyObject * @@ -1806,6 +1808,8 @@ METH_VARARGS|METH_KEYWORDS, doc_min}, {"ptp", (PyCFunction)array_ptp, METH_VARARGS|METH_KEYWORDS, doc_ptp}, + {"abs", (PyCFunction)array_absolute, + METH_VARARGS, doc_abs}, {"mean", (PyCFunction)array_mean, METH_VARARGS|METH_KEYWORDS, doc_mean}, {"trace", (PyCFunction)array_trace, From numpy-svn at scipy.org Thu Aug 24 04:36:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 03:36:56 -0500 (CDT) Subject: [Numpy-svn] r3056 - in trunk/numpy/core: . code_generators include/numpy src Message-ID: <20060824083656.E7C9339C03E@new.scipy.org> Author: oliphant Date: 2006-08-24 03:36:48 -0500 (Thu, 24 Aug 2006) New Revision: 3056 Modified: trunk/numpy/core/code_generators/generate_array_api.py trunk/numpy/core/fromnumeric.py trunk/numpy/core/include/numpy/ndarrayobject.h trunk/numpy/core/include/numpy/npy_interrupt.h trunk/numpy/core/ma.py trunk/numpy/core/numeric.py trunk/numpy/core/src/arraymethods.c trunk/numpy/core/src/multiarraymodule.c Log: Add rudimentary interrupt handliNG. Add max, min, round, abs to the numpy space. Modified: trunk/numpy/core/code_generators/generate_array_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_array_api.py 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/code_generators/generate_array_api.py 2006-08-24 08:36:48 UTC (rev 3056) @@ -20,6 +20,7 @@ npy_bool obval; } PyBoolScalarObject; + static unsigned int PyArray_GetNDArrayCVersion (void); static PyTypeObject PyBigArray_Type; static PyTypeObject PyArray_Type; Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/fromnumeric.py 2006-08-24 08:36:48 UTC (rev 3056) @@ -379,6 +379,8 @@ return _wrapit(a, 'max', axis, out) return amax(axis, out) +max = amax + def amin(a, axis=None, out=None): """Return the minimum of a along dimension axis. """ @@ -388,6 +390,8 @@ return _wrapit(a, 'min', axis, out) return amin(axis, out) +min = amin + def alen(a): """Return the length of a Python object interpreted as an array of at least 1 dimension. @@ -458,6 +462,8 @@ around = round_ +round = round_ + def mean(a, axis=None, dtype=None, out=None): """mean(a, axis=None, dtype=None) Return the arithmetic mean. Modified: trunk/numpy/core/include/numpy/ndarrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-24 08:36:48 UTC (rev 3056) @@ -1384,6 +1384,7 @@ does not have ARR_HAS_DESCR flag set) */ } PyArrayInterface; + /* Includes the "function" C-API -- these are all stored in a list of pointers --- one for each file The two lists are concatenated into one in multiarray. Modified: trunk/numpy/core/include/numpy/npy_interrupt.h =================================================================== --- trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-24 08:36:48 UTC (rev 3056) @@ -10,8 +10,8 @@ ****Warning*************** Do not allow code that creates temporary memory or increases reference -counts of Python objects to be interrupted unless you handle decrementing -the reference counts and freeing any allocated memory in the clean-up code. +counts of Python objects to be interrupted unless you handle it +differently. ************************** @@ -21,7 +21,7 @@ and store the old one. - run the code to be interrupted -- if an interrupt occurs the handler should basically just cause a return to the - calling function for clean-up work. + calling function for finish work. - restore the old signal handler Of course, every code that allows interrupts must account for @@ -32,74 +32,90 @@ 1) platform portability (i.e. Microsoft says not to use longjmp to return from signal handling. They have a __try and __except extension to C instead but what about mingw?). - 2) how to handle threads - a) apparently whether signals are delivered to every thread of - the process or the "invoking" thread is platform dependent. - b) if we use global variables to save state, then how is this - to be done in a thread-safe way. - 3) A general-purpose facility must allow for the possibility of - re-entrance (i.e. during execution of the code that is allowed - to interrupt, we might call back into this very section of code - serially). + 2) how to handle threads: apparently whether signals are delivered to + every thread of the process or the "invoking" thread is platform + dependent. --- we don't handle threads for now. + + 3) do we need to worry about re-entrance. For now, assume the + code will not call-back into itself. + Ideas: 1) Start by implementing an approach that works on platforms that can use setjmp and longjmp functionality and does nothing - on other platforms. Initially only catch SIGINT. + on other platforms. - 2) Handle threads by storing global information in a linked-list - with a process-id key. Then use a call-back function that longjmps - only to the correct buffer. + 2) Ignore threads --- i.e. do not mix interrupt handling and threads - 3) Store a local copy of the global information and restore it on clean-up - so that re-entrance works. + 3) Add a default signal_handler function to the C-API but have the rest + use macros. -Interface: +Simple Interface: -In your C-extension. around a block of code you want to be interruptable -NPY_SIG_TRY { +In your C-extension: around a block of code you want to be interruptable +with a SIGINT + +NPY_SIGINT_ON [code] -} -NPY_SIG_EXCEPT(sigval) { -[signal return] -} -NPY_SIG_ELSE -[normal return] +NPY_SIGINT_OFF -sigval is a local variable that will receive what -signal was received. You can use it to perform different -actions based on the signal received. +In order for this to work correctly, the +[code] block must not allocate any memory or alter the reference count of any +Python objects. In other words [code] must be interruptible so that continuation +after NPY_SIGINT_OFF will only be "missing some computations" -Default actions (setting of specific Python errors) -can be obtained with +Interrupt handling does not work well with threads. -NPY_SIG_TRY { -[code] -NPY_SIG_EXCEPT_GOTO(label) -[normal return] - -label: - [error return] */ /* Add signal handling macros */ #ifndef NPY_INTERRUPT_H #define NPY_INTERRUPT_H + +#ifndef NPY_NO_SIGNAL -#ifdef NPY_NO_SIGNAL +#ifndef sigsetjmp -#define NPY_SIG_ON -#define NPY_SIG_OFF +#define SIGSETJMP(arg1, arg2) setjmp(arg1) +#define SIGLONGJMP(arg1, arg2) longjmp(arg1, arg2) +#define SIGJMP_BUF jmp_buf #else -#define NPY_SIG_ON -#define NPY_SIG_OFF +#define SIGSETJMP(arg1, arg2) sigsetjmp(arg1, arg2) +#define SIGLONGJMP(arg1, arg2) siglongjmp(arg1, arg2) +#define SIGJMP_BUF sigjmp_buf -#endif /* NPY_NO_SIGNAL */ +#endif +SIGJMP_BUF _NPY_SIGINT_BUF; + +static void +_npy_sighandler(int signum) +{ + PyOS_setsig(signum, SIG_IGN); + SIGLONGJMP(_NPY_SIGINT_BUF, signum); +} + + +# define NPY_SIGINT_ON { \ + PyOS_sighandler_t _npy_sig_save; \ + _npy_sig_save = PyOS_setsig(SIGINT, _npy_sighandler); \ + if (SIGSETJMP(_NPY_SIGINT_BUF, 1) == 0) { \ + +# define NPY_SIGINT_OFF } \ + PyOS_setsig(SIGINT, _npy_sig_save); \ + } + +#else /* NPY_NO_SIGNAL */ + +# define NPY_SIGINT_ON +# define NPY_SIGINT_OFF + +#endif /* HAVE_SIGSETJMP */ + #endif /* NPY_INTERRUPT_H */ Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/ma.py 2006-08-24 08:36:48 UTC (rev 3056) @@ -2144,7 +2144,6 @@ return MethodType(f, None, array) def not_implemented(*args, **kwds): raise NotImplementedError, "not yet implemented for numpy.ma arrays" -array.abs = array.__abs__ array.all = _m(alltrue) array.any = _m(sometrue) array.argmax = _m(argmax) Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/numeric.py 2006-08-24 08:36:48 UTC (rev 3056) @@ -95,6 +95,8 @@ extend_all(umath) extend_all(numerictypes) +abs = absolute + newaxis = None ndarray = multiarray.ndarray Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/src/arraymethods.c 2006-08-24 08:36:48 UTC (rev 3056) @@ -252,8 +252,6 @@ return PyArray_Min(self, axis, out); } -static char doc_abs[] = "a.abs() returns abs(a)"; - static char doc_swapaxes[] = "a.swapaxes(axis1, axis2) returns new view with axes swapped."; static PyObject * @@ -1808,8 +1806,6 @@ METH_VARARGS|METH_KEYWORDS, doc_min}, {"ptp", (PyCFunction)array_ptp, METH_VARARGS|METH_KEYWORDS, doc_ptp}, - {"abs", (PyCFunction)array_absolute, - METH_VARARGS, doc_abs}, {"mean", (PyCFunction)array_mean, METH_VARARGS|METH_KEYWORDS, doc_mean}, {"trace", (PyCFunction)array_trace, Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-23 23:39:42 UTC (rev 3055) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-24 08:36:48 UTC (rev 3056) @@ -21,7 +21,8 @@ */ #define _MULTIARRAYMODULE -#include "numpy/noprefix.h" +#define NPY_NO_PREFIX +#include "numpy/arrayobject.h" #define PyAO PyArrayObject @@ -931,6 +932,10 @@ return ret; } +/* Why doesn't this just call the ufunc? + All we need to do is add it to the list of needed ufuncs. + */ + /*MULTIARRAY_API Conjugate */ @@ -6427,6 +6432,24 @@ +#ifndef NPY_NO_SIGNAL + +static PyObject * +test_interrupt(PyObject *self) +{ + int a = 0; + NPY_SIGINT_ON + + while(1) { + a += 1; + } + + NPY_SIGINT_OFF + + return PyInt_FromLong(a); +} +#endif + static struct PyMethodDef array_module_methods[] = { {"_get_ndarray_c_version", (PyCFunction)array__get_ndarray_c_version, METH_VARARGS|METH_KEYWORDS, NULL}, @@ -6481,6 +6504,10 @@ METH_VARARGS | METH_KEYWORDS, NULL}, {"compare_chararrays", (PyCFunction)compare_chararrays, METH_VARARGS | METH_KEYWORDS, NULL}, +#ifndef NPY_NO_SIGNAL + {"test_interrupt", (PyCFunction)test_interrupt, + METH_NOARGS, NULL}, +#endif {NULL, NULL, 0} /* sentinel */ }; @@ -6680,7 +6707,6 @@ return; c_api = PyCObject_FromVoidPtr((void *)PyArray_API, NULL); - if (PyErr_Occurred()) goto err; PyDict_SetItemString(d, "_ARRAY_API", c_api); Py_DECREF(c_api); if (PyErr_Occurred()) goto err; From numpy-svn at scipy.org Thu Aug 24 11:55:21 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 10:55:21 -0500 (CDT) Subject: [Numpy-svn] r3057 - in trunk/numpy/core: include/numpy src Message-ID: <20060824155521.B12FF39C08B@new.scipy.org> Author: oliphant Date: 2006-08-24 10:55:15 -0500 (Thu, 24 Aug 2006) New Revision: 3057 Modified: trunk/numpy/core/include/numpy/npy_interrupt.h trunk/numpy/core/src/arraytypes.inc.src trunk/numpy/core/src/multiarraymodule.c Log: Fixed issues with ticket #267 Modified: trunk/numpy/core/include/numpy/npy_interrupt.h =================================================================== --- trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-24 08:36:48 UTC (rev 3056) +++ trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-24 15:55:15 UTC (rev 3057) @@ -78,6 +78,8 @@ #ifndef NPY_NO_SIGNAL +#include + #ifndef sigsetjmp #define SIGSETJMP(arg1, arg2) setjmp(arg1) Modified: trunk/numpy/core/src/arraytypes.inc.src =================================================================== --- trunk/numpy/core/src/arraytypes.inc.src 2006-08-24 08:36:48 UTC (rev 3056) +++ trunk/numpy/core/src/arraytypes.inc.src 2006-08-24 15:55:15 UTC (rev 3057) @@ -1035,14 +1035,16 @@ memcpy(dst, src, n*sizeof(@type@)); } else { - _unaligned_strided_byte_copy(dst, dstride, src, sstride, - n, sizeof(@type@)); + _unaligned_strided_byte_copy(dst, dstride, src, + sstride, n, + sizeof(@type@)); } } if (swap) { _strided_byte_swap(dst, dstride, n, SIZEOF_ at fsize@); - _strided_byte_swap(dst + SIZEOF_ at fsize@, dstride, n, SIZEOF_ at fsize@); + _strided_byte_swap(((char *)dst + SIZEOF_ at fsize@), dstride, + n, SIZEOF_ at fsize@); } } Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-24 08:36:48 UTC (rev 3056) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-24 15:55:15 UTC (rev 3057) @@ -5456,7 +5456,7 @@ 50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ... */ elcount = (i >> 1) + (i < 4 ? 4 : 2) + i; - if (elcount <= ((~(size_t)0) / elsize)) + if (elcount <= (intp)((~(size_t)0) / elsize)) new_data = PyDataMem_RENEW(ret->data, elcount * elsize); else new_data = NULL; @@ -6430,8 +6430,6 @@ } - - #ifndef NPY_NO_SIGNAL static PyObject * From numpy-svn at scipy.org Thu Aug 24 12:13:02 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 11:13:02 -0500 (CDT) Subject: [Numpy-svn] r3058 - trunk/numpy/core/src Message-ID: <20060824161302.ADB8E39C0DF@new.scipy.org> Author: oliphant Date: 2006-08-24 11:12:59 -0500 (Thu, 24 Aug 2006) New Revision: 3058 Modified: trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/multiarraymodule.c Log: Remove automatic setting of tp_free and tp_hash when it could be a Python function Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-24 15:55:15 UTC (rev 3057) +++ trunk/numpy/core/src/arrayobject.c 2006-08-24 16:12:59 UTC (rev 3058) @@ -6620,7 +6620,7 @@ (initproc)0, /* tp_init */ array_alloc, /* tp_alloc */ (newfunc)array_new, /* tp_new */ - _pya_free, /* tp_free */ + 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ @@ -10289,7 +10289,7 @@ (initproc)0, /* tp_init */ 0, /* tp_alloc */ arraymultiter_new, /* tp_new */ - _pya_free, /* tp_free */ + 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ @@ -11166,7 +11166,7 @@ 0, /* tp_as_number */ 0, /* tp_as_sequence */ &descr_as_mapping, /* tp_as_mapping */ - (hashfunc)_Py_HashPointer, /* tp_hash */ + 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)arraydescr_str, /* tp_str */ 0, /* tp_getattro */ Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-24 15:55:15 UTC (rev 3057) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-24 16:12:59 UTC (rev 3058) @@ -6435,7 +6435,7 @@ static PyObject * test_interrupt(PyObject *self) { - int a = 0; + npy_ulonglong a = 0; NPY_SIGINT_ON while(1) { @@ -6444,7 +6444,7 @@ NPY_SIGINT_OFF - return PyInt_FromLong(a); + return PyLong_FromUnsignedLongLong(a); } #endif @@ -6682,22 +6682,25 @@ d = PyModule_GetDict(m); if (!d) goto err; + PyArray_Type.tp_free = _pya_free; if (PyType_Ready(&PyArray_Type) < 0) - return; + 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; if (PyType_Ready(&PyArrayMapIter_Type) < 0) - return; + return; if (PyType_Ready(&PyArrayMultiIter_Type) < 0) return; + PyArrayDescr_Type.tp_hash = (hashfunc)_Py_HashPointer; if (PyType_Ready(&PyArrayDescr_Type) < 0) return; @@ -6739,11 +6742,11 @@ PyDict_SetItemString(d, "MAXDIMS", s); Py_DECREF(s); - Py_INCREF(&PyArray_Type); + Py_INCREF(&PyArray_Type); PyDict_SetItemString(d, "ndarray", (PyObject *)&PyArray_Type); - Py_INCREF(&PyArrayIter_Type); + Py_INCREF(&PyArrayIter_Type); PyDict_SetItemString(d, "flatiter", (PyObject *)&PyArrayIter_Type); - Py_INCREF(&PyArrayMultiIter_Type); + Py_INCREF(&PyArrayMultiIter_Type); PyDict_SetItemString(d, "broadcast", (PyObject *)&PyArrayMultiIter_Type); Py_INCREF(&PyArrayDescr_Type); @@ -6752,7 +6755,7 @@ Py_INCREF(&PyArrayFlags_Type); PyDict_SetItemString(d, "flagsobj", (PyObject *)&PyArrayFlags_Type); - set_flaginfo(d); + set_flaginfo(d); if (set_typeinfo(d) != 0) goto err; From numpy-svn at scipy.org Thu Aug 24 12:35:11 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 11:35:11 -0500 (CDT) Subject: [Numpy-svn] r3059 - trunk/numpy/core/src Message-ID: <20060824163511.6F26D39C094@new.scipy.org> Author: oliphant Date: 2006-08-24 11:35:08 -0500 (Thu, 24 Aug 2006) New Revision: 3059 Modified: trunk/numpy/core/src/multiarraymodule.c Log: Make sure test_interrupt ends at some point. Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-24 16:12:59 UTC (rev 3058) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-24 16:35:08 UTC (rev 3059) @@ -6430,23 +6430,20 @@ } -#ifndef NPY_NO_SIGNAL - static PyObject * test_interrupt(PyObject *self) { - npy_ulonglong a = 0; + int a = 0; NPY_SIGINT_ON - while(1) { + while(a>=0) { a += 1; } NPY_SIGINT_OFF - return PyLong_FromUnsignedLongLong(a); + return PyInt_FromLong(a); } -#endif static struct PyMethodDef array_module_methods[] = { {"_get_ndarray_c_version", (PyCFunction)array__get_ndarray_c_version, @@ -6502,10 +6499,8 @@ METH_VARARGS | METH_KEYWORDS, NULL}, {"compare_chararrays", (PyCFunction)compare_chararrays, METH_VARARGS | METH_KEYWORDS, NULL}, -#ifndef NPY_NO_SIGNAL {"test_interrupt", (PyCFunction)test_interrupt, METH_NOARGS, NULL}, -#endif {NULL, NULL, 0} /* sentinel */ }; From numpy-svn at scipy.org Thu Aug 24 12:38:03 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 11:38:03 -0500 (CDT) Subject: [Numpy-svn] r3060 - trunk/numpy/core/include/numpy Message-ID: <20060824163803.6D22139C094@new.scipy.org> Author: oliphant Date: 2006-08-24 11:38:00 -0500 (Thu, 24 Aug 2006) New Revision: 3060 Modified: trunk/numpy/core/include/numpy/npy_interrupt.h Log: Also include signal.h Modified: trunk/numpy/core/include/numpy/npy_interrupt.h =================================================================== --- trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-24 16:35:08 UTC (rev 3059) +++ trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-24 16:38:00 UTC (rev 3060) @@ -79,6 +79,7 @@ #ifndef NPY_NO_SIGNAL #include +#include #ifndef sigsetjmp From numpy-svn at scipy.org Thu Aug 24 16:08:01 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 15:08:01 -0500 (CDT) Subject: [Numpy-svn] r3061 - trunk/numpy/distutils/fcompiler Message-ID: <20060824200801.1C0F939C0A5@new.scipy.org> Author: oliphant Date: 2006-08-24 15:07:59 -0500 (Thu, 24 Aug 2006) New Revision: 3061 Modified: trunk/numpy/distutils/fcompiler/g95.py Log: update g95 version pattern Modified: trunk/numpy/distutils/fcompiler/g95.py =================================================================== --- trunk/numpy/distutils/fcompiler/g95.py 2006-08-24 16:38:00 UTC (rev 3060) +++ trunk/numpy/distutils/fcompiler/g95.py 2006-08-24 20:07:59 UTC (rev 3061) @@ -9,11 +9,15 @@ class G95FCompiler(FCompiler): compiler_type = 'g95' - version_pattern = r'G95 \((GCC (?P[\d.]+)|.*?) \(g95!\) (?P.*)\).*' - +# version_pattern = r'G95 \((GCC (?P[\d.]+)|.*?) \(g95!\) (?P.*)\).*' # $ g95 --version # G95 (GCC 4.0.3 (g95!) May 22 2006) + version_pattern = r'G95 \((GCC (?P[\d.]+)|.*?) \(g95 (?P.*)!\) (?P.*)\).*' + # $ g95 --version + # G95 (GCC 4.0.3 (g95 0.90!) Aug 22 2006) + + executables = { 'version_cmd' : ["g95", "--version"], 'compiler_f77' : ["g95", "-ffixed-form"], From numpy-svn at scipy.org Thu Aug 24 18:40:05 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 17:40:05 -0500 (CDT) Subject: [Numpy-svn] r3062 - trunk/numpy/core/src Message-ID: <20060824224005.B219939C063@new.scipy.org> Author: oliphant Date: 2006-08-24 17:39:57 -0500 (Thu, 24 Aug 2006) New Revision: 3062 Modified: trunk/numpy/core/src/multiarraymodule.c Log: Add an example of using PyOS_InterruptOccurred() to the test_interuppt function. Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-24 20:07:59 UTC (rev 3061) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-24 22:39:57 UTC (rev 3062) @@ -6431,16 +6431,30 @@ static PyObject * -test_interrupt(PyObject *self) +test_interrupt(PyObject *self, PyObject *args) { + int kind=0; int a = 0; - NPY_SIGINT_ON - while(a>=0) { - a += 1; + if (!PyArg_ParseTuple(args, "|i", &kind)) return NULL; + + if (kind) { + while (a>=0) { + if ((a % 1000 == 0) && + PyOS_InterruptOccurred()) break; + a+=1; + } } + else { - NPY_SIGINT_OFF + NPY_SIGINT_ON + + while(a>=0) { + a += 1; + } + + NPY_SIGINT_OFF + } return PyInt_FromLong(a); } @@ -6500,7 +6514,7 @@ {"compare_chararrays", (PyCFunction)compare_chararrays, METH_VARARGS | METH_KEYWORDS, NULL}, {"test_interrupt", (PyCFunction)test_interrupt, - METH_NOARGS, NULL}, + METH_VARARGS, NULL}, {NULL, NULL, 0} /* sentinel */ }; From numpy-svn at scipy.org Thu Aug 24 18:50:29 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 17:50:29 -0500 (CDT) Subject: [Numpy-svn] r3063 - trunk/numpy/numarray Message-ID: <20060824225029.C530939C02F@new.scipy.org> Author: oliphant Date: 2006-08-24 17:50:26 -0500 (Thu, 24 Aug 2006) New Revision: 3063 Modified: trunk/numpy/numarray/_capi.c Log: Fix NA_NewAllFromBuffer when shape is given Modified: trunk/numpy/numarray/_capi.c =================================================================== --- trunk/numpy/numarray/_capi.c 2006-08-24 22:39:57 UTC (rev 3062) +++ trunk/numpy/numarray/_capi.c 2006-08-24 22:50:26 UTC (rev 3063) @@ -2738,40 +2738,49 @@ int byteorder, int aligned, int writeable) { PyArrayObject *self = NULL; - PyArray_Descr *dtype; + PyArray_Descr *dtype; if (type == tAny) type = tDefault; - dtype = PyArray_DescrFromType(type); - if (dtype == NULL) return NULL; + dtype = PyArray_DescrFromType(type); + if (dtype == NULL) return NULL; - if (byteorder != NA_ByteOrder()) { - PyArray_Descr *temp; - temp = PyArray_DescrNewByteorder(dtype, PyArray_SWAP); - Py_DECREF(dtype); - if (temp == NULL) return NULL; - dtype = temp; - } + if (byteorder != NA_ByteOrder()) { + PyArray_Descr *temp; + temp = PyArray_DescrNewByteorder(dtype, PyArray_SWAP); + Py_DECREF(dtype); + if (temp == NULL) return NULL; + dtype = temp; + } - if (bufferObject == Py_None || bufferObject == NULL) { - self = (PyArrayObject *) \ + if (bufferObject == Py_None || bufferObject == NULL) { + self = (PyArrayObject *) \ PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, shape, NULL, NULL, 0, NULL); - } - else { - npy_intp size = dtype->elsize; - int i; - for(i=0; ind; i++) { - size *= self->dimensions[i]; + } + else { + npy_intp size = 1; + int i; + PyArrayObject *newself; + PyArray_Dims newdims; + for(i=0; i Author: oliphant Date: 2006-08-24 18:39:18 -0500 (Thu, 24 Aug 2006) New Revision: 3064 Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt trunk/numpy/core/include/numpy/ndarrayobject.h trunk/numpy/core/include/numpy/npy_interrupt.h trunk/numpy/core/src/multiarraymodule.c Log: Move signal handler and global variable getter to C-API Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt =================================================================== --- trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-24 22:50:26 UTC (rev 3063) +++ trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-24 23:39:18 UTC (rev 3064) @@ -75,3 +75,5 @@ PyArray_TypeNumFromName PyArray_ClipmodeConverter PyArray_OutputConverter +_PyArray_SigintHandler +_PyArray_GetSigintBuf \ No newline at end of file Modified: trunk/numpy/core/include/numpy/ndarrayobject.h =================================================================== --- trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-24 22:50:26 UTC (rev 3063) +++ trunk/numpy/core/include/numpy/ndarrayobject.h 2006-08-24 23:39:18 UTC (rev 3064) @@ -1392,7 +1392,6 @@ They are available as import_array() */ - #include "__multiarray_api.h" Modified: trunk/numpy/core/include/numpy/npy_interrupt.h =================================================================== --- trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-24 22:50:26 UTC (rev 3063) +++ trunk/numpy/core/include/numpy/npy_interrupt.h 2006-08-24 23:39:18 UTC (rev 3064) @@ -71,7 +71,9 @@ */ -/* Add signal handling macros */ +/* Add signal handling macros + Make the global variable and signal handler part of the C-API +*/ #ifndef NPY_INTERRUPT_H #define NPY_INTERRUPT_H @@ -94,28 +96,19 @@ #define SIGJMP_BUF sigjmp_buf #endif - -SIGJMP_BUF _NPY_SIGINT_BUF; - -static void -_npy_sighandler(int signum) -{ - PyOS_setsig(signum, SIG_IGN); - SIGLONGJMP(_NPY_SIGINT_BUF, signum); -} - # define NPY_SIGINT_ON { \ - PyOS_sighandler_t _npy_sig_save; \ - _npy_sig_save = PyOS_setsig(SIGINT, _npy_sighandler); \ - if (SIGSETJMP(_NPY_SIGINT_BUF, 1) == 0) { \ - + PyOS_sighandler_t _npy_sig_save; \ + _npy_sig_save = PyOS_setsig(SIGINT, _PyArray_SigintHandler); \ + if (SIGSETJMP(*((SIGJMP_BUF *)_PyArray_GetSigintBuf()), \ + 1) == 0) { \ + # define NPY_SIGINT_OFF } \ PyOS_setsig(SIGINT, _npy_sig_save); \ } - + #else /* NPY_NO_SIGNAL */ - + # define NPY_SIGINT_ON # define NPY_SIGINT_OFF Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-24 22:50:26 UTC (rev 3063) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-24 23:39:18 UTC (rev 3064) @@ -6430,6 +6430,44 @@ } +#ifndef NPY_NO_SIGNAL + +SIGJMP_BUF _NPY_SIGINT_BUF; + +/*MULTIARRAY_API +*/ +static void +_PyArray_SigintHandler(int signum) +{ + PyOS_setsig(signum, SIG_IGN); + SIGLONGJMP(_NPY_SIGINT_BUF, signum); +} + +/*MULTIARRAY_API +*/ +static void* +_PyArray_GetSigintBuf(void) +{ + return (void *)&_NPY_SIGINT_BUF; +} + +#else + +static void +_PyArray_SigintHandler(int signum) +{ + return; +} + +static void* +_PyArray_GetSigintBuf(void) +{ + return NULL; +} + +#endif + + static PyObject * test_interrupt(PyObject *self, PyObject *args) { From numpy-svn at scipy.org Thu Aug 24 20:10:25 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 19:10:25 -0500 (CDT) Subject: [Numpy-svn] r3065 - trunk/numpy/core/src Message-ID: <20060825001025.6A71039C02F@new.scipy.org> Author: oliphant Date: 2006-08-24 19:10:24 -0500 (Thu, 24 Aug 2006) New Revision: 3065 Modified: trunk/numpy/core/src/multiarraymodule.c Log: Add allow threads code Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-24 23:39:18 UTC (rev 3064) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-25 00:10:24 UTC (rev 3065) @@ -6477,11 +6477,13 @@ 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 { From numpy-svn at scipy.org Thu Aug 24 22:39:53 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 21:39:53 -0500 (CDT) Subject: [Numpy-svn] r3066 - trunk/numpy/core Message-ID: <20060825023953.1126C39C040@new.scipy.org> Author: oliphant Date: 2006-08-24 21:39:50 -0500 (Thu, 24 Aug 2006) New Revision: 3066 Modified: trunk/numpy/core/setup.py Log: Don't use LONGJMP on windows. Modified: trunk/numpy/core/setup.py =================================================================== --- trunk/numpy/core/setup.py 2006-08-25 00:10:24 UTC (rev 3065) +++ trunk/numpy/core/setup.py 2006-08-25 02:39:50 UTC (rev 3066) @@ -98,6 +98,9 @@ if check_func(func_name): moredefs.append(defsymbol) + if sys.platform == 'win32': + moredefs.append('NPY_NO_SIGNAL') + if sys.version[:3] < '2.4': if check_func('strtod'): moredefs.append(('PyOS_ascii_strtod', 'strtod')) From numpy-svn at scipy.org Thu Aug 24 23:44:26 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 22:44:26 -0500 (CDT) Subject: [Numpy-svn] r3067 - trunk/numpy/numarray Message-ID: <20060825034426.3B33039C07F@new.scipy.org> Author: oliphant Date: 2006-08-24 22:44:22 -0500 (Thu, 24 Aug 2006) New Revision: 3067 Modified: trunk/numpy/numarray/_capi.c Log: Fix warning... Modified: trunk/numpy/numarray/_capi.c =================================================================== --- trunk/numpy/numarray/_capi.c 2006-08-25 02:39:50 UTC (rev 3066) +++ trunk/numpy/numarray/_capi.c 2006-08-25 03:44:22 UTC (rev 3067) @@ -2775,7 +2775,8 @@ if (self == NULL) return self; newdims.len = ndim; newdims.ptr = shape; - newself = PyArray_Newshape(self, &newdims, PyArray_CORDER); + newself = (PyArrayObject *)\ + PyArray_Newshape(self, &newdims, PyArray_CORDER); Py_DECREF(self); self = newself; } From numpy-svn at scipy.org Fri Aug 25 00:00:00 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 24 Aug 2006 23:00:00 -0500 (CDT) Subject: [Numpy-svn] r3068 - trunk/numpy/core/src Message-ID: <20060825040000.7B3F439C07F@new.scipy.org> Author: oliphant Date: 2006-08-24 22:59:57 -0500 (Thu, 24 Aug 2006) New Revision: 3068 Modified: trunk/numpy/core/src/arrayobject.c Log: Fix coercion in multiarray to be like ufunc coercion. Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-25 03:44:22 UTC (rev 3067) +++ trunk/numpy/core/src/arrayobject.c 2006-08-25 03:59:57 UTC (rev 3068) @@ -6751,11 +6751,24 @@ _array_small_type(PyArray_Descr *chktype, PyArray_Descr* mintype) { PyArray_Descr *outtype; - - if (chktype->type_num > mintype->type_num) outtype = chktype; - else outtype = mintype; - - Py_INCREF(outtype); + int outtype_num, save_num; + + if (chktype->type_num > mintype->type_num) + outtype_num = chktype->type_num; + else + 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); + } + else { + outtype = PyArray_DescrFromType(outtype_num); + } if (PyTypeNum_ISEXTENDED(outtype->type_num) && \ (PyTypeNum_ISEXTENDED(mintype->type_num) || \ mintype->type_num==0)) { From numpy-svn at scipy.org Fri Aug 25 16:21:31 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 25 Aug 2006 15:21:31 -0500 (CDT) Subject: [Numpy-svn] r3069 - trunk/numpy/lib Message-ID: <20060825202131.E876039C08D@new.scipy.org> Author: oliphant Date: 2006-08-25 15:21:29 -0500 (Fri, 25 Aug 2006) New Revision: 3069 Modified: trunk/numpy/lib/function_base.py Log: Added a delete function Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-25 03:59:57 UTC (rev 3068) +++ trunk/numpy/lib/function_base.py 2006-08-25 20:21:29 UTC (rev 3069) @@ -7,13 +7,14 @@ 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', + 'delete' ] import types import numpy.core.numeric as _nx from numpy.core.numeric import ones, zeros, arange, concatenate, array, \ asarray, asanyarray, empty, empty_like, asanyarray, ndarray -from numpy.core.numeric import ScalarType, dot, where, newaxis +from numpy.core.numeric import ScalarType, dot, where, newaxis, intp from numpy.core.umath import pi, multiply, add, arctan2, \ frompyfunc, isnan, cos, less_equal, sqrt, sin, mod, exp from numpy.core.fromnumeric import ravel, nonzero, choose, sort @@ -22,6 +23,7 @@ from numpy.lib.twodim_base import diag from _compiled_base import _insert, add_docstring from _compiled_base import digitize, bincount +from arraysetops import setdiff1d #end Fernando's utilities @@ -1007,4 +1009,43 @@ y = y.reshape(numRows,1) Y = y.repeat(numCols, axis=1) return X, Y + +def delete(arr, obj, axis=-1): + """Delete sub-arrays from an axis + + Return a new array with the sub-arrays (i.e. rows or columns) + deleted along the given axis as specified by obj + + obj may be a slice_object (s_[3:5:2]) or an integer + or an array of integers indicated which sub-arrays to + remove. + + Example: + >>> arr = [[3,4,5], + [1,2,3], + [6,7,8]] + + >>> delete(arr, 1) + array([[3,5], + [1,3], + [6,8]) + >>> delete(arr, 1, 0) + array([[3,4,5], + [6,7,8]]) + """ + arr = asarray(arr) + ndim = arr.ndim + slobj = [slice(None)]*ndim + N = arr.shape[axis] + if isinstance(obj, slice): + obj = arange(obj.start or 0, obj.stop or N, + obj.step or 1, dtype=intp) + else: + obj = array(obj, dtype=intp, copy=0, ndmin=1) + + all = arange(N, dtype=intp) + obj = setdiff1d(all, obj) + slobj[axis] = obj + slobj = tuple(slobj) + return arr[slobj] From numpy-svn at scipy.org Fri Aug 25 16:52:41 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 25 Aug 2006 15:52:41 -0500 (CDT) Subject: [Numpy-svn] r3070 - trunk/numpy/core/code_generators Message-ID: <20060825205241.B14F439C055@new.scipy.org> Author: oliphant Date: 2006-08-25 15:52:39 -0500 (Fri, 25 Aug 2006) New Revision: 3070 Modified: trunk/numpy/core/code_generators/generate_array_api.py Log: Revert import_array so that it doesn't return anything Modified: trunk/numpy/core/code_generators/generate_array_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_array_api.py 2006-08-25 20:21:29 UTC (rev 3069) +++ trunk/numpy/core/code_generators/generate_array_api.py 2006-08-25 20:52:39 UTC (rev 3070) @@ -89,8 +89,14 @@ return 0; } -#define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return; } } +#define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } } +#define import_array0() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ; } } + +#define import_array1(ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ret; } } + +#define import_array2(msg, ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, msg); return ret; } } + #endif #endif From numpy-svn at scipy.org Fri Aug 25 17:33:46 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 25 Aug 2006 16:33:46 -0500 (CDT) Subject: [Numpy-svn] r3071 - in trunk/numpy/core: code_generators include/numpy Message-ID: <20060825213346.1D21E39C021@new.scipy.org> Author: oliphant Date: 2006-08-25 16:33:42 -0500 (Fri, 25 Aug 2006) New Revision: 3071 Modified: trunk/numpy/core/code_generators/generate_array_api.py trunk/numpy/core/code_generators/generate_ufunc_api.py trunk/numpy/core/include/numpy/oldnumeric.h Log: Add more import_array possibilities so it can be used inside a function. Modified: trunk/numpy/core/code_generators/generate_array_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_array_api.py 2006-08-25 20:52:39 UTC (rev 3070) +++ trunk/numpy/core/code_generators/generate_array_api.py 2006-08-25 21:33:42 UTC (rev 3071) @@ -89,10 +89,8 @@ return 0; } -#define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } } +#define import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return; } } -#define import_array0() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ; } } - #define import_array1(ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); return ret; } } #define import_array2(msg, ret) {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, msg); return ret; } } Modified: trunk/numpy/core/code_generators/generate_ufunc_api.py =================================================================== --- trunk/numpy/core/code_generators/generate_ufunc_api.py 2006-08-25 20:52:39 UTC (rev 3070) +++ trunk/numpy/core/code_generators/generate_ufunc_api.py 2006-08-25 21:33:42 UTC (rev 3071) @@ -48,10 +48,15 @@ return 0; } -#define import_umath() { if (_import_umath() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.umath failed to import\n"); return; }} +#define import_umath() { if (_import_umath() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.umath failed to import"); return; }} -#define import_ufunc import_umath +#define import_umath1(ret) { if (_import_umath() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.umath failed to import"); return ret; }} +#define import_umath2(msg, ret) { if (_import_umath() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, msg); return ret; }} + +#define import_ufunc() { if (_import_umath() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.umath failed to import"); }} + + #endif """ Modified: trunk/numpy/core/include/numpy/oldnumeric.h =================================================================== --- trunk/numpy/core/include/numpy/oldnumeric.h 2006-08-25 20:52:39 UTC (rev 3070) +++ trunk/numpy/core/include/numpy/oldnumeric.h 2006-08-25 21:33:42 UTC (rev 3071) @@ -16,3 +16,7 @@ #define OWN_DATA NPY_OWNDATA #define SAVESPACE 0 #define SAVESPACEBIT 0 + +#undef import_array() +#define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } } + From numpy-svn at scipy.org Fri Aug 25 18:14:12 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 25 Aug 2006 17:14:12 -0500 (CDT) Subject: [Numpy-svn] r3072 - in trunk/numpy: core/include/numpy oldnumeric Message-ID: <20060825221412.9BDCC39C021@new.scipy.org> Author: oliphant Date: 2006-08-25 17:14:06 -0500 (Fri, 25 Aug 2006) New Revision: 3072 Modified: trunk/numpy/core/include/numpy/old_defines.h trunk/numpy/core/include/numpy/oldnumeric.h trunk/numpy/oldnumeric/random_array.py trunk/numpy/oldnumeric/user_array.py Log: Fix a problem with __all__ not being copied in oldnumeric. Modified: trunk/numpy/core/include/numpy/old_defines.h =================================================================== --- trunk/numpy/core/include/numpy/old_defines.h 2006-08-25 21:33:42 UTC (rev 3071) +++ trunk/numpy/core/include/numpy/old_defines.h 2006-08-25 22:14:06 UTC (rev 3072) @@ -162,7 +162,6 @@ #define PyArray_NATBYTE NPY_NATBYTE #define PyArray_OPPBYTE NPY_OPPBYTE -#define NPY_REFCOUNT PyArray_REFCOUNT #define PyArray_MAX_ELSIZE NPY_MAX_ELSIZE #define PyArray_USE_PYMEM NPY_USE_PYMEM Modified: trunk/numpy/core/include/numpy/oldnumeric.h =================================================================== --- trunk/numpy/core/include/numpy/oldnumeric.h 2006-08-25 21:33:42 UTC (rev 3071) +++ trunk/numpy/core/include/numpy/oldnumeric.h 2006-08-25 22:14:06 UTC (rev 3072) @@ -1,7 +1,9 @@ #include "arrayobject.h" -#define REFCOUNT NPY_REFCOUNT -#define MAX_ELSIZE 16 +#ifndef REFCOUNT +# define REFCOUNT NPY_REFCOUNT +# define MAX_ELSIZE 16 +#endif #define PyArray_UNSIGNED_TYPES #define PyArray_SBYTE PyArray_BYTE @@ -17,6 +19,6 @@ #define SAVESPACE 0 #define SAVESPACEBIT 0 -#undef import_array() +#undef import_array #define import_array() { if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } } Modified: trunk/numpy/oldnumeric/random_array.py =================================================================== --- trunk/numpy/oldnumeric/random_array.py 2006-08-25 21:33:42 UTC (rev 3071) +++ trunk/numpy/oldnumeric/random_array.py 2006-08-25 22:14:06 UTC (rev 3072) @@ -1,9 +1,11 @@ # Backward compatible module for RandomArray -__all__ = ['ArgumentError','F','beta','binomial','chi_square', 'exponential', 'gamma', 'get_seed', - 'mean_var_test', 'multinomial', 'multivariate_normal', 'negative_binomial', - 'noncentral_F', 'noncentral_chi_square', 'normal', 'permutation', 'poisson', 'randint', - 'random', 'random_integers', 'seed', 'standard_normal', 'uniform'] +__all__ = ['ArgumentError','F','beta','binomial','chi_square', 'exponential', + 'gamma', 'get_seed', 'mean_var_test', 'multinomial', + 'multivariate_normal', 'negative_binomial', 'noncentral_F', + 'noncentral_chi_square', 'normal', 'permutation', 'poisson', + 'randint', 'random', 'random_integers', 'seed', 'standard_normal', + 'uniform'] ArgumentError = ValueError Modified: trunk/numpy/oldnumeric/user_array.py =================================================================== --- trunk/numpy/oldnumeric/user_array.py 2006-08-25 21:33:42 UTC (rev 3071) +++ trunk/numpy/oldnumeric/user_array.py 2006-08-25 22:14:06 UTC (rev 3072) @@ -4,6 +4,6 @@ from numpy.lib.user_array import container as UserArray import numpy.oldnumeric as nold -__all__ = nold.__all__ +__all__ = nold.__all__[:] __all__ += ['UserArray'] del nold From numpy-svn at scipy.org Fri Aug 25 20:49:34 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 25 Aug 2006 19:49:34 -0500 (CDT) Subject: [Numpy-svn] r3073 - in trunk/numpy: core/src lib Message-ID: <20060826004934.AB82D39C00C@new.scipy.org> Author: oliphant Date: 2006-08-25 19:49:30 -0500 (Fri, 25 Aug 2006) New Revision: 3073 Modified: trunk/numpy/core/src/arrayobject.c trunk/numpy/core/src/multiarraymodule.c trunk/numpy/lib/function_base.py Log: Add deletefrom, insertinto, and appendonto Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-25 22:14:06 UTC (rev 3072) +++ trunk/numpy/core/src/arrayobject.c 2006-08-26 00:49:30 UTC (rev 3073) @@ -4693,9 +4693,16 @@ int n = arr->nd; if ((*axis >= MAX_DIMS) || (n==0)) { - temp = PyArray_Ravel(arr,0); - if (temp) *axis = PyArray_NDIM(temp)-1; - else *axis = 0; + if (n != 1) { + temp = PyArray_Ravel(arr,0); + if (temp) *axis = PyArray_NDIM(temp)-1; + else *axis = 0; + } + else { + temp = (PyObject *)arr; + Py_INCREF(temp); + *axis = 0; + } return temp; } else { Modified: trunk/numpy/core/src/multiarraymodule.c =================================================================== --- trunk/numpy/core/src/multiarraymodule.c 2006-08-25 22:14:06 UTC (rev 3072) +++ trunk/numpy/core/src/multiarraymodule.c 2006-08-26 00:49:30 UTC (rev 3073) @@ -172,6 +172,8 @@ return new; } +/* Returns a contiguous array */ + /*MULTIARRAY_API Ravel */ Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-25 22:14:06 UTC (rev 3072) +++ trunk/numpy/lib/function_base.py 2006-08-26 00:49:30 UTC (rev 3073) @@ -7,14 +7,15 @@ 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', - 'delete' + 'deletefrom', 'insertinto', 'appendonto' ] import types import numpy.core.numeric as _nx from numpy.core.numeric import ones, zeros, arange, concatenate, array, \ asarray, asanyarray, empty, empty_like, asanyarray, ndarray -from numpy.core.numeric import ScalarType, dot, where, newaxis, intp +from numpy.core.numeric import ScalarType, dot, where, newaxis, intp, \ + integer from numpy.core.umath import pi, multiply, add, arctan2, \ frompyfunc, isnan, cos, less_equal, sqrt, sin, mod, exp from numpy.core.fromnumeric import ravel, nonzero, choose, sort @@ -551,7 +552,7 @@ """ return _insert(arr, mask, vals) -def nansum(a, axis=-1): +def nansum(a, axis=None): """Sum the array over the given axis, treating NaNs as 0. """ y = array(a) @@ -559,7 +560,7 @@ y[isnan(a)] = 0 return y.sum(axis) -def nanmin(a, axis=-1): +def nanmin(a, axis=None): """Find the minimium over the given axis, ignoring NaNs. """ y = array(a) @@ -567,7 +568,7 @@ y[isnan(a)] = _nx.inf return y.min(axis) -def nanargmin(a, axis=-1): +def nanargmin(a, axis=None): """Find the indices of the minimium over the given axis ignoring NaNs. """ y = array(a) @@ -575,7 +576,7 @@ y[isnan(a)] = _nx.inf return y.argmin(axis) -def nanmax(a, axis=-1): +def nanmax(a, axis=None): """Find the maximum over the given axis ignoring NaNs. """ y = array(a) @@ -583,7 +584,7 @@ y[isnan(a)] = -_nx.inf return y.max(axis) -def nanargmax(a, axis=-1): +def nanargmax(a, axis=None): """Find the maximum over the given axis ignoring NaNs. """ y = array(a) @@ -1010,9 +1011,8 @@ Y = y.repeat(numCols, axis=1) return X, Y - -def delete(arr, obj, axis=-1): - """Delete sub-arrays from an axis +def deletefrom(arr, obj, axis=None): + """Return a new array with sub-arrays along an axis deleted. Return a new array with the sub-arrays (i.e. rows or columns) deleted along the given axis as specified by obj @@ -1021,31 +1021,146 @@ or an array of integers indicated which sub-arrays to remove. + If axis is None, then ravel the array first. + Example: >>> arr = [[3,4,5], [1,2,3], [6,7,8]] - >>> delete(arr, 1) + >>> deletefrom(arr, 1, 1) array([[3,5], [1,3], [6,8]) - >>> delete(arr, 1, 0) + >>> deletefrom(arr, 1) array([[3,4,5], [6,7,8]]) """ arr = asarray(arr) ndim = arr.ndim - slobj = [slice(None)]*ndim + if axis is None: + if ndim != 1: + arr = arr.ravel() + axis = 0 + if ndim == 0: + return arr.copy() + slobj = [slice(None)]*ndim N = arr.shape[axis] - if isinstance(obj, slice): - obj = arange(obj.start or 0, obj.stop or N, - obj.step or 1, dtype=intp) - else: - obj = array(obj, dtype=intp, copy=0, ndmin=1) - + newshape = list(arr.shape) + if isinstance(obj, (int, long, integer)): + if (obj < 0): obj += N + if (obj < 0 or obj >=N): + raise ValueError, "invalid entry" + newshape[axis]-=1; + new = empty(newshape, arr.dtype, arr.flags.fnc) + slobj[axis] = slice(None, obj) + new[slobj] = arr[slobj] + slobj[axis] = slice(obj,None) + slobj2 = [slice(None)]*ndim + slobj[axis] = slice(ojb+1,None) + new[slobj] = arr[slobj2] + return new + elif isinstance(obj, slice): + start, stop, step = obj.indices(N) + numtodel = len(xrange(start, stop, step)) + if numtodel <= 0: + return arr.copy() + newshape[axis] -= numtodel + new = empty(newshape, arr.dtype, arr.flags.fnc) + # copy initial chunk + if start == 0: + pass + else: + slobj[axis] = slice(None, start) + new[slobj] = arr[slobj] + # copy end chunck + if stop == N: + pass + else: + slobj[axis] = slice(stop-numtodel,None) + slobj2 = [slice(None)]*ndim + slobj2[axis] = slice(stop, None) + new[slobj] = arr[slobj2] + # copy middle pieces + if step == 1: + pass + else: # use array indexing. + obj = arange(start, stop, step, dtype=intp) + all = arange(N, dtype=intp) + obj = setdiff1d(all, obj) + slobj[axis] = slice(start, stop-numtodel) + slobj2 = [slice(None)]*ndim + slobj2[axis] = obj + new[slobj] = arr[slobj2] + return new + + # default behavior + obj = array(obj, dtype=intp, copy=0, ndmin=1) all = arange(N, dtype=intp) - obj = setdiff1d(all, obj) + obj = setdiff1d(all, obj) slobj[axis] = obj slobj = tuple(slobj) return arr[slobj] + +def insertinto(arr, obj, values, axis=None): + """Return a new array with values inserted along the given axis + before the given indices + + If axis is None, then ravel the array first. + """ + arr = asarray(arr) + ndim = arr.ndim + if axis is None: + if ndim != 1: + arr = arr.ravel() + axis = 0 + if (ndim == 0): + arr = arr.copy() + arr[...] = values + return arr + slobj = [slice(None)]*ndim + N = arr.shape[axis] + newshape = list(arr.shape) + if isinstance(obj, (int, long, integer)): + if (obj < 0): obj += N + if (obj < 0 or obj >=N): + raise ValueError, "invalid entry" + newshape[axis] += 1; + new = empty(newshape, arr.dtype, arr.flags.fnc) + slobj[axis] = slice(None, obj) + new[slobj] = arr[slobj] + slobj[axis] = obj + new[slobj] = values + slobj[axis] = slice(obj+1,None) + slobj2 = [slice(None)]*ndim + slobj2[axis] = slice(obj,None) + new[slobj] = arr[slobj2] + return new + elif isinstance(obj, slice): + # turn it into a range object + obj = arange(*obj.indices(N),**{'dtype':intp}) + + # default behavior + # FIXME: this is too slow + obj = array(obj, dtype=intp, copy=0, ndmin=1) + try: + if len(values) != len(obj): + raise TypeError + except TypeError: + values = [values]*len(obj) + new = arr + k = 0 + for item, val in zip(obj, values): + new = insertinto(new, item+k, val, axis=axis) + return new + +def appendonto(arr, obj, axis=None): + """Append to the end of an array along axis (ravel first if None) + """ + arr = asarray(arr) + if axis is None: + if arr.ndim != 1: + arr = arr.ravel() + obj = ravel(obj) + axis = 0 + return concatenate((arr, obj), axis=axis) From numpy-svn at scipy.org Sat Aug 26 03:50:57 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 26 Aug 2006 02:50:57 -0500 (CDT) Subject: [Numpy-svn] r3074 - in trunk/numpy: core/code_generators core/src lib Message-ID: <20060826075057.F3AD539C07D@new.scipy.org> Author: oliphant Date: 2006-08-26 02:50:53 -0500 (Sat, 26 Aug 2006) New Revision: 3074 Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt trunk/numpy/core/src/arraymethods.c trunk/numpy/core/src/arrayobject.c trunk/numpy/lib/function_base.py Log: Fix broadcast-copy on fancy set-item. Modified: trunk/numpy/core/code_generators/multiarray_api_order.txt =================================================================== --- trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-26 00:49:30 UTC (rev 3073) +++ trunk/numpy/core/code_generators/multiarray_api_order.txt 2006-08-26 07:50:53 UTC (rev 3074) @@ -75,5 +75,6 @@ PyArray_TypeNumFromName PyArray_ClipmodeConverter PyArray_OutputConverter +PyArray_BroadcastToShape _PyArray_SigintHandler -_PyArray_GetSigintBuf \ No newline at end of file +_PyArray_GetSigintBuf Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-26 00:49:30 UTC (rev 3073) +++ trunk/numpy/core/src/arraymethods.c 2006-08-26 07:50:53 UTC (rev 3074) @@ -2,8 +2,8 @@ /* Should only be used if x is known to be an nd-array */ #define _ARET(x) PyArray_Return((PyArrayObject *)(x)) -static char doc_take[] = "a.take(indices, axis=None). Selects the elements "\ - "in indices from array a along the given axis."; +static char doc_take[] = "a.take(indices, axis=None, out=None, mode='raise')."\ + "Selects the elements in indices from array a along the given axis."; static PyObject * array_take(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -41,9 +41,9 @@ return Py_None; } -static char doc_put[] = "a.put(values, indices, mode) sets a.flat[n] = v[n] "\ - "for each n in indices. v can be scalar or shorter than indices, "\ - "will repeat."; +static char doc_put[] = "a.put(values, indices, mode) sets a.flat[n] = "\ + "values[n] for\n" "each n in indices. v can be scalar or shorter "\ + "than indices,\n" "and it will repeat."; static PyObject * array_put(PyArrayObject *self, PyObject *args, PyObject *kwds) Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-26 00:49:30 UTC (rev 3073) +++ trunk/numpy/core/src/arrayobject.c 2006-08-26 07:50:53 UTC (rev 3074) @@ -2399,8 +2399,11 @@ } } - - if ((it = (PyArrayIterObject *)PyArray_IterNew(arr))==NULL) { + /* 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; } @@ -2408,7 +2411,6 @@ 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 */ @@ -2421,8 +2423,6 @@ copyswap(mit->dataptr, NULL, swap, arr); PyArray_MapIterNext(mit); PyArray_ITER_NEXT(it); - if (it->index == it->size) - PyArray_ITER_RESET(it); } Py_DECREF(arr); Py_DECREF(it); @@ -2434,8 +2434,6 @@ copyswap(mit->dataptr, NULL, swap, arr); PyArray_MapIterNext(mit); PyArray_ITER_NEXT(it); - if (it->index == it->size) - PyArray_ITER_RESET(it); } Py_DECREF(arr); Py_DECREF(it); @@ -2703,7 +2701,8 @@ if (oned) { PyArrayIterObject *it; PyObject *rval; - it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self); + it = (PyArrayIterObject *)\ + PyArray_IterNew((PyObject *)self); if (it == NULL) {Py_DECREF(mit); return NULL;} rval = iter_subscript(it, mit->indexobj); Py_DECREF(it); @@ -8592,28 +8591,94 @@ nd = ao->nd; PyArray_UpdateFlags(ao, CONTIGUOUS); - it->contiguous = 0; 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] = it->ao->dimensions[i] - 1; - it->strides[i] = it->ao->strides[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; +} + +/*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; ind; i++, j++) { + if (ao->dimensions[i] == 1) continue; + if (ao->dimensions[i] != dims[j]) { + compat = 0; + break; + } + } + if (!compat) goto err; + + it = (PyArrayIterObject *)_pya_malloc(sizeof(PyArrayIterObject)); + PyObject_Init((PyObject *)it, &PyArrayIter_Type); + + 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[i]; + } + it->backstrides[i] = it->strides[i] * \ + it->dims_m1[i]; + if (i > 0) + it->factors[nd-i-1] = it->factors[nd-i] * \ it->ao->dimensions[nd-i]; } PyArray_ITER_RESET(it); return (PyObject *)it; + + err: + PyErr_SetString(PyExc_ValueError, "array is not broadcastable to "\ + "correct shape"); + return NULL; } + + + /*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. Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-26 00:49:30 UTC (rev 3073) +++ trunk/numpy/lib/function_base.py 2006-08-26 07:50:53 UTC (rev 3074) @@ -1106,7 +1106,22 @@ """Return a new array with values inserted along the given axis before the given indices - If axis is None, then ravel the array first. + If axis is None, then ravel the array first. + + The obj argument can be an integer, a slice, or a sequence of + integers. + + Example: + >>> a = array([[1,2,3], + [4,5,6], + [7,8,9]]) + + >>> insertinto(a, [1,2], [[4],[5]], axis=0) + array([[1,2,3], + [4,4,4], + [4,5,6], + [5,5,5], + [7,8,9]) """ arr = asarray(arr) ndim = arr.ndim @@ -1139,28 +1154,32 @@ elif isinstance(obj, slice): # turn it into a range object obj = arange(*obj.indices(N),**{'dtype':intp}) - - # default behavior - # FIXME: this is too slow - obj = array(obj, dtype=intp, copy=0, ndmin=1) - try: - if len(values) != len(obj): - raise TypeError - except TypeError: - values = [values]*len(obj) - new = arr - k = 0 - for item, val in zip(obj, values): - new = insertinto(new, item+k, val, axis=axis) + + # get two sets of indices + # one is the indices which will hold the new stuff + # two is the indices where arr will be copied over + + obj = asarray(obj, dtype=intp) + numnew = len(obj) + index1 = obj + arange(numnew) + index2 = setdiff1d(arange(numnew+N),index1) + newshape[axis] += numnew + new = empty(newshape, arr.dtype, arr.flags.fnc) + slobj2 = [slice(None)]*ndim + slobj[axis] = index1 + slobj2[axis] = index2 + new[slobj] = values + new[slobj2] = arr + return new -def appendonto(arr, obj, axis=None): +def appendonto(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ arr = asarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() - obj = ravel(obj) + values = ravel(values) axis = 0 - return concatenate((arr, obj), axis=axis) + return concatenate((arr, values), axis=axis) From numpy-svn at scipy.org Sat Aug 26 04:28:22 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 26 Aug 2006 03:28:22 -0500 (CDT) Subject: [Numpy-svn] r3075 - trunk/numpy/lib Message-ID: <20060826082822.2136C39C07D@new.scipy.org> Author: oliphant Date: 2006-08-26 03:28:20 -0500 (Sat, 26 Aug 2006) New Revision: 3075 Modified: trunk/numpy/lib/function_base.py Log: Fix how deletefrom and insertinto handle objects with __array_wrap__ defined. Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-26 07:50:53 UTC (rev 3074) +++ trunk/numpy/lib/function_base.py 2006-08-26 08:28:20 UTC (rev 3075) @@ -1036,14 +1036,23 @@ array([[3,4,5], [6,7,8]]) """ + try: + wrap = arr.__array_wrap__ + except AttributeError: + wrap = None + arr = asarray(arr) ndim = arr.ndim if axis is None: if ndim != 1: arr = arr.ravel() - axis = 0 + ndim = arr.ndim; + axis = ndim-1; if ndim == 0: - return arr.copy() + if wrap: + return wrap(arr) + else: + return arr.copy() slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) @@ -1059,12 +1068,18 @@ slobj2 = [slice(None)]*ndim slobj[axis] = slice(ojb+1,None) new[slobj] = arr[slobj2] + if wrap: + return wrap(new) return new + elif isinstance(obj, slice): start, stop, step = obj.indices(N) numtodel = len(xrange(start, stop, step)) if numtodel <= 0: - return arr.copy() + if wrap: + return wrap(new) + else: + return arr.copy() newshape[axis] -= numtodel new = empty(newshape, arr.dtype, arr.flags.fnc) # copy initial chunk @@ -1092,15 +1107,21 @@ slobj2 = [slice(None)]*ndim slobj2[axis] = obj new[slobj] = arr[slobj2] + if wrap: + return wrap(new) return new # default behavior - obj = array(obj, dtype=intp, copy=0, ndmin=1) + obj = array(obj, dtype=intp, copy=0, ndmin=1) all = arange(N, dtype=intp) obj = setdiff1d(all, obj) slobj[axis] = obj slobj = tuple(slobj) - return arr[slobj] + new = arr[slobj] + if wrap: + return wrap(new) + else: + return new def insertinto(arr, obj, values, axis=None): """Return a new array with values inserted along the given axis @@ -1123,16 +1144,25 @@ [5,5,5], [7,8,9]) """ + try: + wrap = arr.__array_wrap__ + except AttributeError: + wrap = None + arr = asarray(arr) - ndim = arr.ndim + ndim = arr.ndim if axis is None: if ndim != 1: arr = arr.ravel() - axis = 0 + ndim = arr.ndim + axis = ndim-1 if (ndim == 0): arr = arr.copy() arr[...] = values - return arr + if wrap: + return wrap(arr) + else: + return arr slobj = [slice(None)]*ndim N = arr.shape[axis] newshape = list(arr.shape) @@ -1150,6 +1180,8 @@ slobj2 = [slice(None)]*ndim slobj2[axis] = slice(obj,None) new[slobj] = arr[slobj2] + if wrap: + return wrap(new) return new elif isinstance(obj, slice): # turn it into a range object @@ -1170,16 +1202,18 @@ slobj2[axis] = index2 new[slobj] = values new[slobj2] = arr - + + if wrap: + return wrap(new) return new def appendonto(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ - arr = asarray(arr) + arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) - axis = 0 + axis = arr.ndim-1 return concatenate((arr, values), axis=axis) From numpy-svn at scipy.org Sat Aug 26 04:50:32 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 26 Aug 2006 03:50:32 -0500 (CDT) Subject: [Numpy-svn] r3076 - trunk/numpy/lib Message-ID: <20060826085032.DA7E139C016@new.scipy.org> Author: oliphant Date: 2006-08-26 03:50:30 -0500 (Sat, 26 Aug 2006) New Revision: 3076 Modified: trunk/numpy/lib/function_base.py Log: Fixes to the deletefrom, insertinto, functions... Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-26 08:28:20 UTC (rev 3075) +++ trunk/numpy/lib/function_base.py 2006-08-26 08:50:30 UTC (rev 3076) @@ -1032,15 +1032,18 @@ array([[3,5], [1,3], [6,8]) - >>> deletefrom(arr, 1) + >>> deletefrom(arr, 1, 0) array([[3,4,5], [6,7,8]]) """ - try: - wrap = arr.__array_wrap__ - except AttributeError: - wrap = None + wrap = None + if type(arr) is not ndarray: + try: + wrap = arr.__array_wrap__ + except AttributeError: + pass + arr = asarray(arr) ndim = arr.ndim if axis is None: @@ -1066,12 +1069,8 @@ new[slobj] = arr[slobj] slobj[axis] = slice(obj,None) slobj2 = [slice(None)]*ndim - slobj[axis] = slice(ojb+1,None) - new[slobj] = arr[slobj2] - if wrap: - return wrap(new) - return new - + slobj2[axis] = slice(obj+1,None) + new[slobj] = arr[slobj2] elif isinstance(obj, slice): start, stop, step = obj.indices(N) numtodel = len(xrange(start, stop, step)) @@ -1101,23 +1100,18 @@ pass else: # use array indexing. obj = arange(start, stop, step, dtype=intp) - all = arange(N, dtype=intp) + all = arange(start, stop, dtype=intp) obj = setdiff1d(all, obj) slobj[axis] = slice(start, stop-numtodel) slobj2 = [slice(None)]*ndim slobj2[axis] = obj new[slobj] = arr[slobj2] - if wrap: - return wrap(new) - return new - - # default behavior - obj = array(obj, dtype=intp, copy=0, ndmin=1) - all = arange(N, dtype=intp) - obj = setdiff1d(all, obj) - slobj[axis] = obj - slobj = tuple(slobj) - new = arr[slobj] + else: # default behavior + obj = array(obj, dtype=intp, copy=0, ndmin=1) + all = arange(N, dtype=intp) + obj = setdiff1d(all, obj) + slobj[axis] = obj + new = arr[slobj] if wrap: return wrap(new) else: @@ -1144,10 +1138,12 @@ [5,5,5], [7,8,9]) """ - try: - wrap = arr.__array_wrap__ - except AttributeError: - wrap = None + wrap = None + if type(arr) is not ndarray: + try: + wrap = arr.__array_wrap__ + except AttributeError: + pass arr = asarray(arr) ndim = arr.ndim @@ -1169,7 +1165,8 @@ if isinstance(obj, (int, long, integer)): if (obj < 0): obj += N if (obj < 0 or obj >=N): - raise ValueError, "invalid entry" + raise ValueError, "index (%d) out of range (0<=index<=%d) "\ + "in dimension %d" % (obj, N, axis) newshape[axis] += 1; new = empty(newshape, arr.dtype, arr.flags.fnc) slobj[axis] = slice(None, obj) @@ -1182,7 +1179,8 @@ new[slobj] = arr[slobj2] if wrap: return wrap(new) - return new + return new + elif isinstance(obj, slice): # turn it into a range object obj = arange(*obj.indices(N),**{'dtype':intp}) From numpy-svn at scipy.org Sat Aug 26 05:15:34 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 26 Aug 2006 04:15:34 -0500 (CDT) Subject: [Numpy-svn] r3077 - tags Message-ID: <20060826091534.CB16939C016@new.scipy.org> Author: oliphant Date: 2006-08-26 04:15:31 -0500 (Sat, 26 Aug 2006) New Revision: 3077 Added: tags/1.0b4/ Log: Create 1.0b4 tag Copied: tags/1.0b4 (from rev 3076, trunk) From numpy-svn at scipy.org Sat Aug 26 05:16:04 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 26 Aug 2006 04:16:04 -0500 (CDT) Subject: [Numpy-svn] r3078 - trunk/numpy Message-ID: <20060826091604.84A3139C016@new.scipy.org> Author: oliphant Date: 2006-08-26 04:16:02 -0500 (Sat, 26 Aug 2006) New Revision: 3078 Modified: trunk/numpy/version.py Log: Up version of trunk. Modified: trunk/numpy/version.py =================================================================== --- trunk/numpy/version.py 2006-08-26 09:15:31 UTC (rev 3077) +++ trunk/numpy/version.py 2006-08-26 09:16:02 UTC (rev 3078) @@ -1,4 +1,4 @@ -version='1.0b4' +version='1.0b5' release=False if not release: From numpy-svn at scipy.org Sat Aug 26 05:16:43 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 26 Aug 2006 04:16:43 -0500 (CDT) Subject: [Numpy-svn] r3079 - tags/1.0b4/numpy Message-ID: <20060826091643.BEE6F39C016@new.scipy.org> Author: oliphant Date: 2006-08-26 04:16:41 -0500 (Sat, 26 Aug 2006) New Revision: 3079 Modified: tags/1.0b4/numpy/version.py Log: Make tagged tree a release. Modified: tags/1.0b4/numpy/version.py =================================================================== --- tags/1.0b4/numpy/version.py 2006-08-26 09:16:02 UTC (rev 3078) +++ tags/1.0b4/numpy/version.py 2006-08-26 09:16:41 UTC (rev 3079) @@ -1,5 +1,5 @@ version='1.0b4' -release=False +release=True if not release: import os From numpy-svn at scipy.org Sun Aug 27 03:43:45 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 27 Aug 2006 02:43:45 -0500 (CDT) Subject: [Numpy-svn] r3080 - in tags/1.0b4/numpy: lib lib/tests oldnumeric Message-ID: <20060827074345.3F90839C00D@new.scipy.org> Author: oliphant Date: 2006-08-27 02:43:37 -0500 (Sun, 27 Aug 2006) New Revision: 3080 Modified: tags/1.0b4/numpy/lib/function_base.py tags/1.0b4/numpy/lib/tests/test_function_base.py tags/1.0b4/numpy/oldnumeric/misc.py Log: Fix up names. insert ==> place, deletefrom ==> delete, insertinto ==> insert, appendonto ==> append Modified: tags/1.0b4/numpy/lib/function_base.py =================================================================== --- tags/1.0b4/numpy/lib/function_base.py 2006-08-26 09:16:41 UTC (rev 3079) +++ tags/1.0b4/numpy/lib/function_base.py 2006-08-27 07:43:37 UTC (rev 3080) @@ -2,12 +2,12 @@ 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', #'base_repr', 'binary_repr', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', - 'unique', 'extract', 'insert', 'nansum', 'nanmax', 'nanargmax', + 'unique', 'extract', 'place', 'nansum', 'nanmax', 'nanargmax', 'nanargmin', 'nanmin', 'vectorize', 'asarray_chkfinite', 'average', 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', - 'deletefrom', 'insertinto', 'appendonto' + 'delete', 'insert', 'append' ] import types @@ -545,7 +545,7 @@ """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) -def insert(arr, mask, vals): +def place(arr, mask, vals): """Similar to putmask arr[mask] = vals but the 1D array vals has the same number of elements as the non-zero values of mask. Inverse of extract. @@ -1011,7 +1011,7 @@ Y = y.repeat(numCols, axis=1) return X, Y -def deletefrom(arr, obj, axis=None): +def delete(arr, obj, axis=None): """Return a new array with sub-arrays along an axis deleted. Return a new array with the sub-arrays (i.e. rows or columns) @@ -1117,7 +1117,7 @@ else: return new -def insertinto(arr, obj, values, axis=None): +def insert(arr, obj, values, axis=None): """Return a new array with values inserted along the given axis before the given indices @@ -1205,7 +1205,7 @@ return wrap(new) return new -def appendonto(arr, values, axis=None): +def append(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ arr = asanyarray(arr) Modified: tags/1.0b4/numpy/lib/tests/test_function_base.py =================================================================== --- tags/1.0b4/numpy/lib/tests/test_function_base.py 2006-08-26 09:16:41 UTC (rev 3079) +++ tags/1.0b4/numpy/lib/tests/test_function_base.py 2006-08-27 07:43:37 UTC (rev 3080) @@ -237,17 +237,17 @@ a = array([1,3,2,1,2,3,3]) b = extract(a>1,a) assert_array_equal(b,[3,2,2,3,3]) - def check_insert(self): + def check_place(self): a = array([1,4,3,2,5,8,7]) - insert(a,[0,1,0,1,0,1,0],[2,4,6]) + place(a,[0,1,0,1,0,1,0],[2,4,6]) assert_array_equal(a,[1,2,3,4,5,6,7]) def check_both(self): a = rand(10) mask = a > 0.5 ac = a.copy() c = extract(mask, a) - insert(a,mask,0) - insert(a,mask,c) + place(a,mask,0) + place(a,mask,c) assert_array_equal(a,ac) class test_vectorize(NumpyTestCase): Modified: tags/1.0b4/numpy/oldnumeric/misc.py =================================================================== --- tags/1.0b4/numpy/oldnumeric/misc.py 2006-08-26 09:16:41 UTC (rev 3079) +++ tags/1.0b4/numpy/oldnumeric/misc.py 2006-08-27 07:43:37 UTC (rev 3080) @@ -9,7 +9,7 @@ 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', 'array_repr', 'e', 'StringIO', 'pickle', 'argsort', 'convolve', 'loads', 'cross_correlate', - 'Pickler', 'dot', 'outerproduct', 'innerproduct'] + 'Pickler', 'dot', 'outerproduct', 'innerproduct', 'insert'] import types import StringIO @@ -23,7 +23,8 @@ choose, swapaxes, array_str, array_repr, e, pi, \ fromfunction, resize, around, concatenate, vdot, transpose, \ diagonal, searchsorted, put, argsort, convolve, dot, \ - outer as outerproduct, inner as innerproduct, correlate as cross_correlate + outer as outerproduct, inner as innerproduct, correlate as cross_correlate, \ + place as insert from array_printer import array2string From numpy-svn at scipy.org Sun Aug 27 04:02:22 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 27 Aug 2006 03:02:22 -0500 (CDT) Subject: [Numpy-svn] r3081 - tags/1.0b4/numpy/lib Message-ID: <20060827080222.4AA7D39C00D@new.scipy.org> Author: oliphant Date: 2006-08-27 03:02:19 -0500 (Sun, 27 Aug 2006) New Revision: 3081 Modified: tags/1.0b4/numpy/lib/function_base.py Log: Add tensordot placeholder. Modified: tags/1.0b4/numpy/lib/function_base.py =================================================================== --- tags/1.0b4/numpy/lib/function_base.py 2006-08-27 07:43:37 UTC (rev 3080) +++ tags/1.0b4/numpy/lib/function_base.py 2006-08-27 08:02:19 UTC (rev 3081) @@ -1,4 +1,4 @@ -__all__ = ['logspace', 'linspace', +u__all__ = ['logspace', 'linspace', 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', #'base_repr', 'binary_repr', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', @@ -7,7 +7,7 @@ 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', - 'delete', 'insert', 'append' + 'delete', 'insert', 'append', 'tensordot' ] import types @@ -1215,3 +1215,12 @@ values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axis) + +def tensordot(arr1, arr2, axes1=-1, axes2=0): + """tensordot returns the product for any (ndim >= 1) arrays. + + r_{xxx, yyy} = \sum_k arr1_{xxx,k} arr2_{k,yyy} where + the axes of k + """ + #FIXME + pass From numpy-svn at scipy.org Sun Aug 27 14:08:30 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 27 Aug 2006 13:08:30 -0500 (CDT) Subject: [Numpy-svn] r3082 - in trunk/numpy: . core core/src Message-ID: <20060827180830.5DE5A39C09C@new.scipy.org> Author: charris Date: 2006-08-27 13:08:18 -0500 (Sun, 27 Aug 2006) New Revision: 3082 Modified: trunk/numpy/add_newdocs.py trunk/numpy/core/fromnumeric.py trunk/numpy/core/src/arraymethods.c Log: Move the documentation of the sort, argsort, and searchsorted methods into add_newdocs. Rewrite the documentation of sort and argsort. Replace the documentation of these functions in fromnumeric with the new documentation. Modified: trunk/numpy/add_newdocs.py =================================================================== --- trunk/numpy/add_newdocs.py 2006-08-27 08:02:19 UTC (rev 3081) +++ trunk/numpy/add_newdocs.py 2006-08-27 18:08:18 UTC (rev 3082) @@ -46,16 +46,16 @@ ndarray.__new__(subtype, shape=, dtype=float, buffer=None, offset=0, strides=None, order=None) - + There are two modes of creating an array using __new__: - 1) If buffer is None, then only shape, dtype, and order + 1) If buffer is None, then only shape, dtype, and order are used 2) If buffer is an object exporting the buffer interface, then all keywords are interpreted. - The dtype parameter can be any object that can be interpreted + The dtype parameter can be any object that can be interpreted as a numpy.dtype object. - - No __init__ method is needed because the array is fully + + No __init__ method is needed because the array is fully initialized after the __new__ method. """ ) @@ -82,7 +82,7 @@ ('__array_priority__', 'Array priority'), ('__array_finalize__', 'None') ] - ) + ) add_newdoc('numpy.core', 'flatiter', @@ -108,20 +108,20 @@ add_newdoc('numpy.core.multiarray','array', """array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0) - + Return an array from object with the specified date-type. Inputs: - object - an array, any object exposing the array interface, any - object whose __array__ method returns an array, or any + object - an array, any object exposing the array interface, any + object whose __array__ method returns an array, or any (nested) sequence. dtype - The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only - be used to 'upcast' the array. For downcasting, use the + be used to 'upcast' the array. For downcasting, use the .astype(t) method. copy - If true, then force a copy. Otherwise a copy will only occur - if __array__ returns a copy, obj is a nested sequence, or + if __array__ returns a copy, obj is a nested sequence, or a copy is needed to satisfy any of the other requirements order - Specify the order of the array. If order is 'C', then the array will be in C-contiguous order (last-index varies the @@ -232,9 +232,9 @@ The tuple of sequences (a1, a2, ...) are joined along the given axis (default is the first one) into a single numpy array. - + Example: - + >>> concatenate( ([0,1,2], [5,6,7]) ) array([0, 1, 2, 5, 6, 7]) @@ -313,7 +313,7 @@ To group the indices by element, rather than dimension, use transpose(where(condition, | x, y)) - + instead. This always results in a 2d array, with a row of indices for each element that satisfies the condition. @@ -357,4 +357,81 @@ """) +add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', +"""a.sort(axis=-1, kind='quicksort') -> None. Sort a along the given axis. +Keyword arguments: + +axis -- axis to be sorted (default -1) +kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. + +Returns: None. + +This method sorts a in place along the given axis using the algorithm +specified by the kind keyword. + +The various sorts may characterized by average speed, worst case +performance, need for work space, and whether they are stable. A stable +sort keeps items with the same key in the same relative order and is most +useful when used with argsort where the key might differ from the items +being sorted. The three available algorithms have the following properties: + +|------------------------------------------------------| +| kind | speed | worst case | work space | stable| +|------------------------------------------------------| +|'quicksort'| 1 | o(n) | 0 | no | +|'mergesort'| 2 | o(n*log(n)) | ~n/2 | yes | +|'heapsort' | 3 | o(n*log(n)) | 0 | no | +|------------------------------------------------------| + +All the sort algorithms make temporary copies of the data when the sort is +not along the last axis. Consequently, sorts along the last axis are faster +and use less space than sorts along other axis. + +""")) + +add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort', +"""a.sort(axis=-1, kind='quicksort') -> indices that sort a along given axis. + +Keyword arguments: + +axis -- axis to be indirectly sorted (default -1) +kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + +Returns: array of indices that sort a along the specified axis. + +This method executes an indirect sort along the given axis using the +algorithm specified by the kind keyword. It returns an array of indices of +the same shape as a that index data along the given axis in sorted order. + +The various sorts are characterized by average speed, worst case +performance, need for work space, and whether they are stable. A stable +sort keeps items with the same key in the same relative order. The three +available algorithms have the following properties: + +|------------------------------------------------------| +| kind | speed | worst case | work space | stable| +|------------------------------------------------------| +|'quicksort'| 1 | o(n^2) | 0 | no | +|'mergesort'| 2 | o(n*log(n)) | ~n/2 | yes | +|'heapsort' | 3 | o(n*log(n)) | 0 | no | +|------------------------------------------------------| + +All the sort algorithms make temporary copies of the data when the sort is not +along the last axis. Consequently, sorts along the last axis are faster and use +less space than sorts along other axis. + +""")) + +add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted', +"""a.searchsorted(v) + + Assuming that a is a 1-D array, in ascending order and represents + bin boundaries, then a.searchsorted(values) gives an array of bin + numbers, giving the bin into which each value would be placed. + This method is helpful for histograming. Note: No warning is + given if the boundaries, in a, are not in ascending order.; + +""")) Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-27 08:02:19 UTC (rev 3081) +++ trunk/numpy/core/fromnumeric.py 2006-08-27 18:08:18 UTC (rev 3082) @@ -125,15 +125,74 @@ return transpose(axes) def sort(a, axis=-1, kind='quicksort'): - """sort(a,axis=-1) returns array with elements sorted along given axis. + """Return copy of array sorted along the given axis. + + Keyword arguments: + + axis -- axis to be sorted (default -1) + kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. + + Returns: None. + + This method sorts a in place along the given axis using the algorithm + specified by the kind keyword. + + The various sorts may characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order and is most + useful when used with argsort where the key might differ from the items + being sorted. The three available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | o(n) | 0 | no | + |'mergesort'| 2 | o(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | o(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is + not along the last axis. Consequently, sorts along the last axis are faster + and use less space than sorts along other axis. + """ a = asanyarray(a).copy() a.sort(axis, kind) return a def argsort(a, axis=-1, kind='quicksort'): - """argsort(a,axis=-1) return the indices into a of the sorted array - along the given axis. + """Return array of indices that index a in sorted order. + + Keyword arguments: + + axis -- axis to be indirectly sorted (default -1) + kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort' + + Returns: array of indices that sort a along the specified axis. + + This method executes an indirect sort along the given axis using the + algorithm specified by the kind keyword. It returns an array of indices of + the same shape as a that index data along the given axis in sorted order. + + The various sorts are characterized by average speed, worst case + performance, need for work space, and whether they are stable. A stable + sort keeps items with the same key in the same relative order. The three + available algorithms have the following properties: + + |------------------------------------------------------| + | kind | speed | worst case | work space | stable| + |------------------------------------------------------| + |'quicksort'| 1 | o(n^2) | 0 | no | + |'mergesort'| 2 | o(n*log(n)) | ~n/2 | yes | + |'heapsort' | 3 | o(n*log(n)) | 0 | no | + |------------------------------------------------------| + + All the sort algorithms make temporary copies of the data when the sort is not + along the last axis. Consequently, sorts along the last axis are faster and use + less space than sorts along other axis. + """ try: argsort = a.argsort @@ -160,7 +219,7 @@ except AttributeError: return _wrapit(a, 'argmin', axis) return argmin(axis) - + def searchsorted(a, v): """searchsorted(a, v) """ @@ -239,7 +298,7 @@ else: res = nonzero() return res - + def shape(a): """shape(a) returns the shape of a (as a function call which also works on nested sequences). @@ -328,7 +387,7 @@ return all(axis, out) def any(x,axis=None, out=None): - """Return true if any elements of x are true: + """Return true if any elements of x are true: """ try: any = x.any @@ -337,7 +396,7 @@ return any(axis, out) def all(x,axis=None, out=None): - """Return true if all elements of x are true: + """Return true if all elements of x are true: """ try: all = x.all @@ -467,9 +526,9 @@ def mean(a, axis=None, dtype=None, out=None): """mean(a, axis=None, dtype=None) Return the arithmetic mean. - - The mean is the sum of the elements divided by the number of elements. - + + The mean is the sum of the elements divided by the number of elements. + See also: average """ try: @@ -484,7 +543,7 @@ The standard deviation is the square root of the average of the squared deviations from the mean, i.e. std = sqrt(mean((x - x.mean())**2)). - + See also: var """ try: @@ -499,7 +558,7 @@ The variance is the average of the squared deviations from the mean, i.e. var = mean((x - x.mean())**2). - + See also: std """ try: Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-27 08:02:19 UTC (rev 3081) +++ trunk/numpy/core/src/arraymethods.c 2006-08-27 18:08:18 UTC (rev 3082) @@ -743,8 +743,6 @@ return _ARET(PyArray_Choose(self, choices, out, clipmode)); } -static char doc_sort[] = "a.sort(axis=-1,kind='quicksort') sorts in place along axis. Return is None and kind can be 'quicksort', 'mergesort', or 'heapsort'"; - static PyObject * array_sort(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -763,10 +761,6 @@ return Py_None; } -static char doc_argsort[] = "a.argsort(axis=-1,kind='quicksort')\n"\ - " Return the indexes into a that would sort it along the"\ - " given axis; kind can be 'quicksort', 'mergesort', or 'heapsort'"; - static PyObject * array_argsort(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -781,14 +775,6 @@ return _ARET(PyArray_ArgSort(self, axis, which)); } -static char doc_searchsorted[] = "a.searchsorted(v)\n"\ - " Assuming that a is a 1-D array, in ascending order and\n"\ - " represents bin boundaries, then a.searchsorted(values) gives an\n"\ - " array of bin numbers, giving the bin into which each value would\n"\ - " be placed. This method is helpful for histograming. \n"\ - " Note: No warning is given if the boundaries, in a, are not \n"\ - " in ascending order."; - static PyObject * array_searchsorted(PyArrayObject *self, PyObject *args) { @@ -1783,11 +1769,11 @@ {"choose", (PyCFunction)array_choose, METH_VARARGS|METH_KEYWORDS, doc_choose}, {"sort", (PyCFunction)array_sort, - METH_VARARGS|METH_KEYWORDS, doc_sort}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"argsort", (PyCFunction)array_argsort, - METH_VARARGS|METH_KEYWORDS, doc_argsort}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"searchsorted", (PyCFunction)array_searchsorted, - METH_VARARGS, doc_searchsorted}, + METH_VARARGS, NULL}, {"argmax", (PyCFunction)array_argmax, METH_VARARGS|METH_KEYWORDS, doc_argmax}, {"argmin", (PyCFunction)array_argmin, From numpy-svn at scipy.org Sun Aug 27 20:37:17 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 27 Aug 2006 19:37:17 -0500 (CDT) Subject: [Numpy-svn] r3083 - in trunk/numpy: . core/src Message-ID: <20060828003717.1852539C0D0@new.scipy.org> Author: charris Date: 2006-08-27 19:37:14 -0500 (Sun, 27 Aug 2006) New Revision: 3083 Modified: trunk/numpy/add_newdocs.py trunk/numpy/core/src/arraymethods.c Log: Move most of the remaining documentation from arraymethods to add_newdocs. The formatting is still very crude and the docs need expansion. Modified: trunk/numpy/add_newdocs.py =================================================================== --- trunk/numpy/add_newdocs.py 2006-08-27 18:08:18 UTC (rev 3082) +++ trunk/numpy/add_newdocs.py 2006-08-28 00:37:14 UTC (rev 3083) @@ -35,56 +35,6 @@ ] ) -add_newdoc('numpy.core', 'ndarray', -"""An array object represents a multidimensional, homogeneous array -of fixed-size items. An associated data-type-descriptor object -details the data-type in an array (including byteorder and any -fields). An array can be constructed using the numpy.array -command. Arrays are sequence, mapping and numeric objects. -More information is available in the numpy module and by looking -at the methods and attributes of an array. - -ndarray.__new__(subtype, shape=, dtype=float, buffer=None, - offset=0, strides=None, order=None) - - There are two modes of creating an array using __new__: - 1) If buffer is None, then only shape, dtype, and order - are used - 2) If buffer is an object exporting the buffer interface, then - all keywords are interpreted. - The dtype parameter can be any object that can be interpreted - as a numpy.dtype object. - - No __init__ method is needed because the array is fully - initialized after the __new__ method. -""" - ) - -add_newdoc('numpy.core', 'ndarray', - [('ndim', 'number of array dimensions'), - ('flags', 'special object providing array flags'), - ('shape', 'tuple of array dimensions'), - ('strides', 'tuple of bytes to step in each dimension'), - ('data', 'buffer object pointing to the start of the data'), - ('itemsize', 'length of one element in bytes'), - ('size', 'number of elements in the array'), - ('nbytes', 'number of bytes in the array'), - ('base', 'base object if memory is from some other object'), - ('dtype', 'data-type for the array'), - ('real', 'real part of the array'), - ('imag', 'imaginary part of the array'), - ('flat', 'a 1-d flat iterator'), - ('ctypes', 'a ctypes interface object'), - ('_as_parameter_', 'allow the array to be interpreted as a ctypes object by returning the data-memory location as an integer'), - ('T', 'equivalent to self.transpose() except self is returned for self.ndim < 2'), - ('__array_interface__', 'Array protocol: Python side'), - ('__array_struct__', 'Array protocol: C-struct side'), - ('__array_priority__', 'Array priority'), - ('__array_finalize__', 'None') - ] - ) - - add_newdoc('numpy.core', 'flatiter', [('__array__', """__array__(type=None) @@ -357,42 +307,99 @@ """) -add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', -"""a.sort(axis=-1, kind='quicksort') -> None. Sort a along the given axis. +############################################################################## +# +# Documentation for ndarray attributes and methods +# +# Todo: +# +# break out attributes separately +# +# Attributes and module documentation are still defined elsewhere, +# so don't show up yet. +# +# expand and reformat other documentation. +# +# all methods prior to Extended methods added 2005 +# +############################################################################## -Keyword arguments: -axis -- axis to be sorted (default -1) -kind -- sorting algorithm (default 'quicksort') - Possible values: 'quicksort', 'mergesort', or 'heapsort'. +add_newdoc('numpy.core.multiarray', 'ndarray', +"""An array object represents a multidimensional, homogeneous array +of fixed-size items. An associated data-type-descriptor object +details the data-type in an array (including byteorder and any +fields). An array can be constructed using the numpy.array +command. Arrays are sequence, mapping and numeric objects. +More information is available in the numpy module and by looking +at the methods and attributes of an array. -Returns: None. +ndarray.__new__(subtype, shape=, dtype=float, buffer=None, + offset=0, strides=None, order=None) -This method sorts a in place along the given axis using the algorithm -specified by the kind keyword. + There are two modes of creating an array using __new__: + 1) If buffer is None, then only shape, dtype, and order + are used + 2) If buffer is an object exporting the buffer interface, then + all keywords are interpreted. + The dtype parameter can be any object that can be interpreted + as a numpy.dtype object. -The various sorts may characterized by average speed, worst case -performance, need for work space, and whether they are stable. A stable -sort keeps items with the same key in the same relative order and is most -useful when used with argsort where the key might differ from the items -being sorted. The three available algorithms have the following properties: + No __init__ method is needed because the array is fully + initialized after the __new__ method. +""") -|------------------------------------------------------| -| kind | speed | worst case | work space | stable| -|------------------------------------------------------| -|'quicksort'| 1 | o(n) | 0 | no | -|'mergesort'| 2 | o(n*log(n)) | ~n/2 | yes | -|'heapsort' | 3 | o(n*log(n)) | 0 | no | -|------------------------------------------------------| -All the sort algorithms make temporary copies of the data when the sort is -not along the last axis. Consequently, sorts along the last axis are faster -and use less space than sorts along other axis. +add_newdoc('numpy.core.multiarray', 'ndarray', + [('ndim', 'number of array dimensions'), + ('flags', 'special object providing array flags'), + ('shape', 'tuple of array dimensions'), + ('strides', 'tuple of bytes to step in each dimension'), + ('data', 'buffer object pointing to the start of the data'), + ('itemsize', 'length of one element in bytes'), + ('size', 'number of elements in the array'), + ('nbytes', 'number of bytes in the array'), + ('base', 'base object if memory is from some other object'), + ('dtype', 'data-type for the array'), + ('real', 'real part of the array'), + ('imag', 'imaginary part of the array'), + ('flat', 'a 1-d flat iterator'), + ('ctypes', 'a ctypes interface object'), + ('_as_parameter_', 'allow the array to be interpreted as a ctypes object by returning the data-memory location as an integer'), + ('T', 'equivalent to self.transpose() except self is returned for self.ndim < 2'), + ('__array_interface__', 'Array protocol: Python side'), + ('__array_struct__', 'Array protocol: C-struct side'), + ('__array_priority__', 'Array priority'), + ('__array_finalize__', 'None') + ]) + +add_newdoc('numpy.core.multiarray', 'ndarray', ('all', +""" a.all(axis=None) + """)) + +add_newdoc('numpy.core.multiarray', 'ndarray', ('any', +""" a.any(axis=None, out=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('argmax', +""" a.argmax(axis=None, out=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('argmin', +""" a.argmin(axis=None, out=None) + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort', -"""a.sort(axis=-1, kind='quicksort') -> indices that sort a along given axis. +"""a.argsort(axis=-1, kind='quicksort') -> indices that sort a along given axis. Keyword arguments: @@ -425,6 +432,176 @@ """)) + +add_newdoc('numpy.core.multiarray', 'ndarray', ('choose', +""" a.choose(b0, b1, ..., bn, out=None, mode='raise') + +Return an array that merges the b_i arrays together using 'a' as +the index The b_i arrays and 'a' must all be broadcastable to the +same shape. The output at a particular position is the input +array b_i at that position depending on the value of 'a' at that +position. Therefore, 'a' must be an integer array with entries +from 0 to n+1.; + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('clip', +"""a.clip(min=, max=, out=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('compress', +"""a.compress(condition=, axis=None, out=None) +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('conj', +"""a.conj() +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate', +"""a.conjugate() +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('cumprod', +"""a.cumprod(axis=None, dtype=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('cumsum', +"""a.cumsum(axis=None, dtype=None, out=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal', +"""a.diagonal(offset=0, axis1=0, axis2=1) +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('fill', +"""a.fill(value) -> None. Fill the array with the scalar value. +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten', +"""a.flatten([fortran]) return a 1-d array (always copy) +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('max', +"""a.max(axis=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('mean', +"""a.mean(axis=None, dtype=None) + + Average the array over the given axis. If the axis is None, + average over all dimensions of the array. If an integer axis + is given, this equals: + a.sum(axis, dtype) * 1.0 / len(a). + If axis is None, this equals: + a.sum(axis, dtype) * 1.0 / product(a.shape) + The optional dtype argument is the data type for intermediate + calculations in the sum.; + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('min', +"""a.min(axis=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('newbyteorder', +"""a.newbyteorder() is equivalent to +a.view(a.dtype.newbytorder()) +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero', +"""a.nonzero() returns a tuple of arrays + +Returns a tuple of arrays, one for each dimension of a, +containing the indices of the non-zero elements in that +dimension. The corresponding non-zero values can be obtained +with + a[a.nonzero()]. + +To group the indices by element, rather than dimension, use + transpose(a.nonzero()) +instead. The result of this is always a 2d array, with a row for +each non-zero element.; + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('prod', +""" a.prod(axis=None, dtype=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp', +"""a.ptp(axis=None) a.max(axis)-a.min(axis) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('put', +"""a.put(values, indices, mode) sets a.flat[n] = values[n] for +each n in indices. v can be scalar or shorter than indices, and +it will repeat. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('putmask', +"""a.putmask(values, mask) sets a.flat[n] = v[n] for each n where +mask.flat[n] is true. v can be scalar. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('ravel', +"""a.ravel([fortran]) return a 1-d array (copy only if needed) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat', +"""a.repeat(repeats=, axis=none) + +copy elements of a, repeats times. the repeats argument must +be a sequence of length a.shape[axis] or a scalar.; + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape', +"""a.reshape(d1, d2, ..., dn, order='c') + +Return a new array from this one. The new array must have the +same number of elements as self. Also always returns a view or +raises a ValueError if that is impossible.; + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('round', +"""a.round(decimals=0, out=None) + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted', """a.searchsorted(v) @@ -435,3 +612,160 @@ given if the boundaries, in a, are not in ascending order.; """)) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags', +"""a.setflags(write=None, align=None, uic=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('sort', +"""a.sort(axis=-1, kind='quicksort') -> None. Sort a along the given axis. + +Keyword arguments: + +axis -- axis to be sorted (default -1) +kind -- sorting algorithm (default 'quicksort') + Possible values: 'quicksort', 'mergesort', or 'heapsort'. + +Returns: None. + +This method sorts a in place along the given axis using the algorithm +specified by the kind keyword. + +The various sorts may characterized by average speed, worst case +performance, need for work space, and whether they are stable. A stable +sort keeps items with the same key in the same relative order and is most +useful when used with argsort where the key might differ from the items +being sorted. The three available algorithms have the following properties: + +|------------------------------------------------------| +| kind | speed | worst case | work space | stable| +|------------------------------------------------------| +|'quicksort'| 1 | o(n) | 0 | no | +|'mergesort'| 2 | o(n*log(n)) | ~n/2 | yes | +|'heapsort' | 3 | o(n*log(n)) | 0 | no | +|------------------------------------------------------| + +All the sort algorithms make temporary copies of the data when the sort is +not along the last axis. Consequently, sorts along the last axis are faster +and use less space than sorts along other axis. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('squeeze', +"""m.squeeze() eliminate all length-1 dimensions + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('std', +"""a.std(axis=None, dtype=None, out=None) -> standard deviation. + +The standard deviation isa measure of the spread of a +distribution. + +The standard deviation is the square root of the average of the +squared deviations from the mean, i.e. + std = sqrt(mean((x - x.mean())**2)). + +For multidimensional arrays, std is computed by default along the +first axis. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('sum', +"""a.sum(axis=None, dtype=None) -> Sum of array over given axis. + +Sum the array over the given axis. If the axis is None, sum over +all dimensions of the array. + +The optional dtype argument is the data type for the returned +value and intermediate calculations. The default is to upcast +(promote) smaller integer types to the platform-dependent int. +For example, on 32-bit platforms: + + a.dtype default sum() dtype + --------------------------------------------------- + bool, int8, int16, int32 int32 + +Examples: + +>>> array([0.5, 1.5]).sum() +2.0 +>>> array([0.5, 1.5]).sum(dtype=int32) +1 +>>> array([[0, 1], [0, 5]]).sum(axis=0) +array([0, 6]) +>>> array([[0, 1], [0, 5]]).sum(axis=1) +array([1, 5]) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('swapaxes', +"""a.swapaxes(axis1, axis2) -> new view with axes swapped. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('take', +"""a.take(indices, axis=None, out=None, mode='raise') -> new array. + +The new array is formed from the elements of a indexed by indices along the +given axis. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('trace', +"""a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) +return the sum along the offset diagonal of the arrays indicated +axis1 and axis2. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose', +"""a.transpose(*axes) + +Returns a view of 'a' with axes transposed. If no axes are given, +or None is passed, switches the order of the axes. For a 2-d +array, this is the usual matrix transpose. If axes are given, +they describe how the axes are permuted. + +Example: +>>> a = array([[1,2],[3,4]]) +>>> a +array([[1, 2], + [3, 4]]) +>>> a.transpose() +array([[1, 3], + [2, 4]]) +>>> a.transpose((1,0)) +array([[1, 3], + [2, 4]]) +>>> a.transpose(1,0) +array([[1, 3], + [2, 4]]) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('var', +"""a.var(axis=None, dtype=None) + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('view', +"""a.view() -> new view of array with same data. + +Type can be either a new sub-type object or a data-descriptor object + +""")) + + Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-27 18:08:18 UTC (rev 3082) +++ trunk/numpy/core/src/arraymethods.c 2006-08-28 00:37:14 UTC (rev 3083) @@ -2,9 +2,6 @@ /* Should only be used if x is known to be an nd-array */ #define _ARET(x) PyArray_Return((PyArrayObject *)(x)) -static char doc_take[] = "a.take(indices, axis=None, out=None, mode='raise')."\ - "Selects the elements in indices from array a along the given axis."; - static PyObject * array_take(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -27,9 +24,6 @@ return _ARET(PyArray_TakeFrom(self, indices, dimension, out, mode)); } -static char doc_fill[] = "a.fill(value) places the scalar value at every "\ - "position in the array."; - static PyObject * array_fill(PyArrayObject *self, PyObject *args) { @@ -41,10 +35,6 @@ return Py_None; } -static char doc_put[] = "a.put(values, indices, mode) sets a.flat[n] = "\ - "values[n] for\n" "each n in indices. v can be scalar or shorter "\ - "than indices,\n" "and it will repeat."; - static PyObject * array_put(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -60,9 +50,6 @@ return PyArray_PutTo(self, values, indices, mode); } -static char doc_putmask[] = "a.putmask(values, mask) sets a.flat[n] = v[n] "\ - "for each n where mask.flat[n] is TRUE. v can be scalar."; - static PyObject * array_putmask(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -76,13 +63,6 @@ return PyArray_PutMask(self, values, mask); } -static char doc_reshape[] = \ - "self.reshape(d1, d2, ..., dn, order='C') \n" - "Return a new array from this one. \n" - "\n The new array must have the same number of elements as self. " - "Also\n always returns a view or raises a ValueError if that is \n" - "impossible."; - static PyObject * array_reshape(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -122,8 +102,6 @@ return NULL; } -static char doc_squeeze[] = "m.squeeze() eliminate all length-1 dimensions"; - static PyObject * array_squeeze(PyArrayObject *self, PyObject *args) { @@ -131,8 +109,6 @@ return PyArray_Squeeze(self); } -static char doc_view[] = "a.view() return a new view of array with same data. type can be either a new sub-type object or a data-descriptor object"; - static PyObject * array_view(PyArrayObject *self, PyObject *args) { @@ -156,8 +132,6 @@ return PyArray_View(self, type, NULL); } -static char doc_argmax[] = "a.argmax(axis=None, out=None)"; - static PyObject * array_argmax(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -175,8 +149,6 @@ return _ARET(PyArray_ArgMax(self, axis, out)); } -static char doc_argmin[] = "a.argmin(axis=None, out=None)"; - static PyObject * array_argmin(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -194,8 +166,6 @@ return _ARET(PyArray_ArgMin(self, axis, out)); } -static char doc_max[] = "a.max(axis=None)"; - static PyObject * array_max(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -213,8 +183,6 @@ return PyArray_Max(self, axis, out); } -static char doc_ptp[] = "a.ptp(axis=None) a.max(axis)-a.min(axis)"; - static PyObject * array_ptp(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -233,8 +201,6 @@ } -static char doc_min[] = "a.min(axis=None)"; - static PyObject * array_min(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -252,8 +218,6 @@ return PyArray_Min(self, axis, out); } -static char doc_swapaxes[] = "a.swapaxes(axis1, axis2) returns new view with axes swapped."; - static PyObject * array_swapaxes(PyArrayObject *self, PyObject *args) { @@ -687,11 +651,6 @@ return Py_None; } -static char doc_repeat[] = "a.repeat(repeats=, axis=None)\n"\ - "\n"\ - " Copy elements of a, repeats times. The repeats argument must\n"\ - " be a sequence of length a.shape[axis] or a scalar."; - static PyObject * array_repeat(PyArrayObject *self, PyObject *args, PyObject *kwds) { PyObject *repeats; @@ -705,14 +664,6 @@ return _ARET(PyArray_Repeat(self, repeats, axis)); } -static char doc_choose[] = "a.choose(b0, b1, ..., bn, out=None, mode='raise')\n"\ - "\n" \ - "Return an array that merges the b_i arrays together using 'a' as the index\n" - "The b_i arrays and 'a' must all be broadcastable to the same shape.\n" - "The output at a particular position is the input array b_i at that position\n" - "depending on the value of 'a' at that position. Therefore, 'a' must be\n" - "an integer array with entries from 0 to n+1."; - static PyObject * array_choose(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1215,27 +1166,6 @@ } -static char doc_transpose[] = "a.transpose(*axes)\n\n" -"Returns a view of `a` with axes transposed. If no axes are given,\n" -"or None is passed, switches the order of the axes (for a 2-d array,\n" -"this is the usual matrix transpose). If axes are given, they\n" -"describe how the axes are permuted.\n\n" -"Example:\n" -">>> a = array([[1,2],[3,4]])\n" -">>> a\n" -"array([[1, 2],\n" -" [3, 4]])\n" -">>> a.transpose()\n" -"array([[1, 3],\n" -" [2, 4]])\n" -">>> a.transpose((1,0))\n" -"array([[1, 3],\n" -" [2, 4]])\n" -">>> a.transpose(1,0)\n" -"array([[1, 3],\n" -" [2, 4]])\n" -; - static PyObject * array_transpose(PyArrayObject *self, PyObject *args) { @@ -1259,19 +1189,6 @@ return _ARET(ret); } -static char doc_mean[] = "a.mean(axis=None, dtype=None)\n\n"\ - "Average the array over the given axis. If the axis is None, average\n"\ - "over all dimensions of the array.\n"\ - "\n"\ - "If an integer axis is given, this equals:\n"\ - " a.sum(axis, dtype) * 1.0 / len(a)\n"\ - "\n"\ - "If axis is None, this equals:\n"\ - " a.sum(axis, dtype) * 1.0 / product(a.shape)\n"\ - "\n"\ - "The optional dtype argument is the data type for intermediate\n"\ - "calculations in the sum."; - #define _CHKTYPENUM(typ) ((typ) ? (typ)->type_num : PyArray_NOTYPE) static PyObject * @@ -1292,30 +1209,6 @@ return PyArray_Mean(self, axis, _CHKTYPENUM(dtype), out); } -static char doc_sum[] = "a.sum(axis=None, dtype=None)\n\n"\ - "Sum the array over the given axis. If the axis is None, sum over all\n"\ - "dimensions of the array.\n"\ - "\n"\ - "The optional dtype argument is the data type for the returned value\n"\ - "and intermediate calculations. The default is to upcast (promote)\n"\ - "smaller integer types to the platform-dependent int. For example, on\n"\ - "32-bit platforms:\n"\ - "\n"\ - " a.dtype default sum() dtype\n"\ - " ---------------------------------------------------\n"\ - " bool, int8, int16, int32 int32\n"\ - "\n"\ - "Examples:\n"\ - "\n"\ - ">>> array([0.5, 1.5]).sum()\n"\ - "2.0\n"\ - ">>> array([0.5, 1.5]).sum(dtype=int32)\n"\ - "1\n"\ - ">>> array([[0, 1], [0, 5]]).sum(axis=0)\n"\ - "array([0, 6])\n"\ - ">>> array([[0, 1], [0, 5]]).sum(axis=1)\n"\ - "array([1, 5])"; - static PyObject * array_sum(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1335,8 +1228,6 @@ } -static char doc_cumsum[] = "a.cumsum(axis=None, dtype=None, out=None)"; - static PyObject * array_cumsum(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1355,8 +1246,6 @@ return PyArray_CumSum(self, axis, _CHKTYPENUM(dtype), out); } -static char doc_prod[] = "a.prod(axis=None, dtype=None)"; - static PyObject * array_prod(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1375,9 +1264,6 @@ return PyArray_Prod(self, axis, _CHKTYPENUM(dtype), out); } - -static char doc_cumprod[] = "a.cumprod(axis=None, dtype=None)"; - static PyObject * array_cumprod(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1397,8 +1283,6 @@ } -static char doc_any[] = "a.any(axis=None, out=None)"; - static PyObject * array_any(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1416,7 +1300,6 @@ return PyArray_Any(self, axis, out); } -static char doc_all[] = "a.all(axis=None)"; static PyObject * array_all(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -1435,13 +1318,6 @@ return PyArray_All(self, axis, out); } -static char doc_stddev[] = "a.std(axis=None, dtype=None, out=None)\n" -"Return the standard deviation, a measure of the spread of a distribution.\n" -"\n" -"The standard deviation is the square root of the average of the squared\n" -"deviations from the mean, i.e. std = sqrt(mean((x - x.mean())**2)).\n" -"\n" -"For multidimensional arrays, std is computed by default along the first axis.\n"; static PyObject * array_stddev(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -1461,7 +1337,6 @@ return PyArray_Std(self, axis, _CHKTYPENUM(dtype), out, 0); } -static char doc_variance[] = "a.var(axis=None, dtype=None)"; static PyObject * array_variance(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -1481,7 +1356,6 @@ return PyArray_Std(self, axis, _CHKTYPENUM(dtype), out, 1); } -static char doc_compress[] = "a.compress(condition=, axis=None, out=None)"; static PyObject * array_compress(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -1500,16 +1374,6 @@ return _ARET(PyArray_Compress(self, condition, axis, out)); } -static char doc_nonzero[] = \ - "a.nonzero() returns a tuple of arrays, one for each dimension of a,\n"\ - "containing the indices of the non-zero elements in that dimension.\n"\ - "The corresponding non-zero values can be obtained with\n"\ - " a[a.nonzero()].\n" - "\n"\ - "To group the indices by element, rather than dimension, use\n"\ - " transpose(a.nonzero())\n"\ - "instead. The result of this is always a 2d array, with a row for each\n"\ - "non-zero element."; static PyObject * array_nonzero(PyArrayObject *self, PyObject *args) @@ -1520,10 +1384,6 @@ } -static char doc_trace[] = "a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)\n"\ - "return the sum along the offset diagonal of the arrays indicated\n" \ - "axis1 and axis2."; - static PyObject * array_trace(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1545,8 +1405,6 @@ #undef _CHKTYPENUM -static char doc_clip[] = "a.clip(min=, max=, out=None)"; - static PyObject * array_clip(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1563,10 +1421,7 @@ return _ARET(PyArray_Clip(self, min, max, out)); } -static char doc_conj[] = "a.conj()"; -static char doc_conjugate[] = "a.conjugate()"; - static PyObject * array_conjugate(PyArrayObject *self, PyObject *args) { @@ -1580,8 +1435,6 @@ } -static char doc_diagonal[] = "a.diagonal(offset=0, axis1=0, axis2=1)"; - static PyObject * array_diagonal(PyArrayObject *self, PyObject *args, PyObject *kwds) { @@ -1595,7 +1448,6 @@ return _ARET(PyArray_Diagonal(self, offset, axis1, axis2)); } -static char doc_flatten[] = "a.flatten([fortran]) return a 1-d array (always copy)"; static PyObject * array_flatten(PyArrayObject *self, PyObject *args) @@ -1608,7 +1460,6 @@ return PyArray_Flatten(self, fortran); } -static char doc_ravel[] = "a.ravel([fortran]) return a 1-d array (copy only if needed)"; static PyObject * array_ravel(PyArrayObject *self, PyObject *args) @@ -1621,7 +1472,6 @@ return PyArray_Ravel(self, fortran); } -static char doc_round[] = "a.round(decimals=0, out=None)"; static PyObject * array_round(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -1639,7 +1489,6 @@ } -static char doc_setflags[] = "a.setflags(write=None, align=None, uic=None)"; static int _IsAligned(PyArrayObject *); static Bool _IsWriteable(PyArrayObject *); @@ -1704,8 +1553,6 @@ return Py_None; } -static char doc_newbyteorder[] = "a.newbyteorder() is equivalent\n" \ - " to a.view(a.dtype.newbytorder())\n"; static PyObject * array_newbyteorder(PyArrayObject *self, PyObject *args) @@ -1754,86 +1601,86 @@ {"dump", (PyCFunction) array_dump, 1, doc_dump}, /* Extended methods added 2005 */ - {"fill", (PyCFunction)array_fill, - METH_VARARGS, doc_fill}, - {"transpose", (PyCFunction)array_transpose, - METH_VARARGS, doc_transpose}, - {"take", (PyCFunction)array_take, - METH_VARARGS|METH_KEYWORDS, doc_take}, - {"put", (PyCFunction)array_put, - METH_VARARGS|METH_KEYWORDS, doc_put}, - {"putmask", (PyCFunction)array_putmask, - METH_VARARGS|METH_KEYWORDS, doc_putmask}, - {"repeat", (PyCFunction)array_repeat, - METH_VARARGS|METH_KEYWORDS, doc_repeat}, - {"choose", (PyCFunction)array_choose, - METH_VARARGS|METH_KEYWORDS, doc_choose}, - {"sort", (PyCFunction)array_sort, + {"all", (PyCFunction)array_all, METH_VARARGS|METH_KEYWORDS, NULL}, - {"argsort", (PyCFunction)array_argsort, + {"any", (PyCFunction)array_any, METH_VARARGS|METH_KEYWORDS, NULL}, - {"searchsorted", (PyCFunction)array_searchsorted, - METH_VARARGS, NULL}, {"argmax", (PyCFunction)array_argmax, - METH_VARARGS|METH_KEYWORDS, doc_argmax}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"argmin", (PyCFunction)array_argmin, - METH_VARARGS|METH_KEYWORDS, doc_argmin}, - {"reshape", (PyCFunction)array_reshape, - METH_VARARGS|METH_KEYWORDS, doc_reshape}, - {"squeeze", (PyCFunction)array_squeeze, - METH_VARARGS, doc_squeeze}, - {"view", (PyCFunction)array_view, - METH_VARARGS, doc_view}, - {"swapaxes", (PyCFunction)array_swapaxes, - METH_VARARGS, doc_swapaxes}, - {"max", (PyCFunction)array_max, - METH_VARARGS|METH_KEYWORDS, doc_max}, - {"min", (PyCFunction)array_min, - METH_VARARGS|METH_KEYWORDS, doc_min}, - {"ptp", (PyCFunction)array_ptp, - METH_VARARGS|METH_KEYWORDS, doc_ptp}, - {"mean", (PyCFunction)array_mean, - METH_VARARGS|METH_KEYWORDS, doc_mean}, - {"trace", (PyCFunction)array_trace, - METH_VARARGS|METH_KEYWORDS, doc_trace}, - {"diagonal", (PyCFunction)array_diagonal, - METH_VARARGS|METH_KEYWORDS, doc_diagonal}, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"argsort", (PyCFunction)array_argsort, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"choose", (PyCFunction)array_choose, + METH_VARARGS|METH_KEYWORDS, NULL}, {"clip", (PyCFunction)array_clip, - METH_VARARGS|METH_KEYWORDS, doc_clip}, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"compress", (PyCFunction)array_compress, + METH_VARARGS|METH_KEYWORDS, NULL}, {"conj", (PyCFunction)array_conjugate, - METH_VARARGS, doc_conj}, + METH_VARARGS, NULL}, {"conjugate", (PyCFunction)array_conjugate, - METH_VARARGS, doc_conjugate}, - {"nonzero", (PyCFunction)array_nonzero, - METH_VARARGS, doc_nonzero}, - {"std", (PyCFunction)array_stddev, - METH_VARARGS|METH_KEYWORDS, doc_stddev}, - {"var", (PyCFunction)array_variance, - METH_VARARGS|METH_KEYWORDS, doc_variance}, - {"sum", (PyCFunction)array_sum, - METH_VARARGS|METH_KEYWORDS, doc_sum}, - {"cumsum", (PyCFunction)array_cumsum, - METH_VARARGS|METH_KEYWORDS, doc_cumsum}, - {"prod", (PyCFunction)array_prod, - METH_VARARGS|METH_KEYWORDS, doc_prod}, + METH_VARARGS, NULL}, {"cumprod", (PyCFunction)array_cumprod, - METH_VARARGS|METH_KEYWORDS, doc_cumprod}, - {"all", (PyCFunction)array_all, - METH_VARARGS|METH_KEYWORDS, doc_all}, - {"any", (PyCFunction)array_any, - METH_VARARGS|METH_KEYWORDS, doc_any}, - {"compress", (PyCFunction)array_compress, - METH_VARARGS|METH_KEYWORDS, doc_compress}, + 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, doc_flatten}, + 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}, + {"putmask", (PyCFunction)array_putmask, + METH_VARARGS|METH_KEYWORDS, NULL}, {"ravel", (PyCFunction)array_ravel, - METH_VARARGS, doc_ravel}, + METH_VARARGS, NULL}, + {"repeat", (PyCFunction)array_repeat, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"reshape", (PyCFunction)array_reshape, + METH_VARARGS|METH_KEYWORDS, NULL}, {"round", (PyCFunction)array_round, - METH_VARARGS|METH_KEYWORDS, doc_round}, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"searchsorted", (PyCFunction)array_searchsorted, + METH_VARARGS, NULL}, {"setflags", (PyCFunction)array_setflags, - METH_VARARGS|METH_KEYWORDS, doc_setflags}, - {"newbyteorder", (PyCFunction)array_newbyteorder, - METH_VARARGS, doc_newbyteorder}, + 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}, + {"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 */ }; From numpy-svn at scipy.org Mon Aug 28 01:56:56 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 28 Aug 2006 00:56:56 -0500 (CDT) Subject: [Numpy-svn] r3084 - in trunk/numpy: . core/src Message-ID: <20060828055656.C774339C035@new.scipy.org> Author: charris Date: 2006-08-28 00:56:49 -0500 (Mon, 28 Aug 2006) New Revision: 3084 Modified: trunk/numpy/add_newdocs.py trunk/numpy/core/src/arraymethods.c Log: Break up the documentation of ndarray attributes into separate calls. Modified: trunk/numpy/add_newdocs.py =================================================================== --- trunk/numpy/add_newdocs.py 2006-08-28 00:37:14 UTC (rev 3083) +++ trunk/numpy/add_newdocs.py 2006-08-28 05:56:49 UTC (rev 3084) @@ -313,14 +313,16 @@ # # Todo: # -# break out attributes separately +# expand and reformat documentation. # -# Attributes and module documentation are still defined elsewhere, -# so don't show up yet. +# do all methods prior to Extended methods added 2005 # -# expand and reformat other documentation. +############################################################################## + + +############################################################################## # -# all methods prior to Extended methods added 2005 +# ndarray object # ############################################################################## @@ -347,33 +349,104 @@ No __init__ method is needed because the array is fully initialized after the __new__ method. + """) -add_newdoc('numpy.core.multiarray', 'ndarray', - [('ndim', 'number of array dimensions'), - ('flags', 'special object providing array flags'), - ('shape', 'tuple of array dimensions'), - ('strides', 'tuple of bytes to step in each dimension'), - ('data', 'buffer object pointing to the start of the data'), - ('itemsize', 'length of one element in bytes'), - ('size', 'number of elements in the array'), - ('nbytes', 'number of bytes in the array'), - ('base', 'base object if memory is from some other object'), - ('dtype', 'data-type for the array'), - ('real', 'real part of the array'), - ('imag', 'imaginary part of the array'), - ('flat', 'a 1-d flat iterator'), - ('ctypes', 'a ctypes interface object'), - ('_as_parameter_', 'allow the array to be interpreted as a ctypes object by returning the data-memory location as an integer'), - ('T', 'equivalent to self.transpose() except self is returned for self.ndim < 2'), - ('__array_interface__', 'Array protocol: Python side'), - ('__array_struct__', 'Array protocol: C-struct side'), - ('__array_priority__', 'Array priority'), - ('__array_finalize__', 'None') - ]) +############################################################################## +# +# ndarray attributes +# +############################################################################## +add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_interface__', +"""Array protocol: Python side.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_finalize__', +"""None.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_priority__', +"""Array priority.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_struct__', +"""Array protocol: C-struct side.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('_as_parameter_', +"""Allow the array to be interpreted as a ctypes object by returning the +data-memory location as an integer""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('base', +"""Base object if memory is from some other object.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('ctypes', +"""A ctypes interface object.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('data', +"""Buffer object pointing to the start of the data.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('dtype', +"""Data-type for the array.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('imag', +"""Imaginary part of the array.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('itemsize', +"""Length of one element in bytes.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('flags', +"""Special object providing array flags.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('flat', +"""A 1-d flat iterator.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('nbytes', +"""Number of bytes in the array.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('ndim', +"""Number of array dimensions.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('real', +"""Real part of the array.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('shape', +"""Tuple of array dimensions.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('size', +"""Number of elements in the array.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('strides', +"""Tuple of bytes to step in each dimension.""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('T', +"""Equivalent to self.transpose() except self is returned for self.ndim < 2.""")) + + +############################################################################## +# +# ndarray methods +# +############################################################################## + add_newdoc('numpy.core.multiarray', 'ndarray', ('all', """ a.all(axis=None) Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-28 00:37:14 UTC (rev 3083) +++ trunk/numpy/core/src/arraymethods.c 2006-08-28 05:56:49 UTC (rev 3084) @@ -229,8 +229,8 @@ } static char doc_getfield[] = "m.getfield(dtype, offset) returns a field "\ - " of the given array as a certain type. A field is a view of "\ - " the array's data with each itemsize determined by the given type"\ + " of the given array as a certain type. \nA field is a view of "\ + " the array's data with each itemsize determined by the\ngiven type"\ " and the offset into the current array."; /* steals typed reference */ From numpy-svn at scipy.org Mon Aug 28 15:42:31 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 28 Aug 2006 14:42:31 -0500 (CDT) Subject: [Numpy-svn] r3085 - in tags/1.0b4/numpy: core lib Message-ID: <20060828194231.CB35D39C013@new.scipy.org> Author: oliphant Date: 2006-08-28 14:42:27 -0500 (Mon, 28 Aug 2006) New Revision: 3085 Modified: tags/1.0b4/numpy/core/numeric.py tags/1.0b4/numpy/lib/function_base.py Log: Update tensordot. Modified: tags/1.0b4/numpy/core/numeric.py =================================================================== --- tags/1.0b4/numpy/core/numeric.py 2006-08-28 05:56:49 UTC (rev 3084) +++ tags/1.0b4/numpy/core/numeric.py 2006-08-28 19:42:27 UTC (rev 3085) @@ -7,7 +7,7 @@ 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', - 'alterdot', 'restoredot', 'cross', + 'alterdot', 'restoredot', 'cross', 'tensordot', 'array2string', 'get_printoptions', 'set_printoptions', 'array_repr', 'array_str', 'set_string_function', 'little_endian', 'require', @@ -252,7 +252,48 @@ def restoredot(): pass +def tensordot(a, b, axes=(-1,0)) + """tensordot returns the product for any (ndim >= 1) arrays. + r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where + + the axes to be summed over are given by the axes argument. + the first element of the sequence determines the axis or axes + in arr1 to sum over and the second element in axes argument sequence + """ + axes_a, axes_b = axes + try: + na = len(axes_a) + except TypeError: + axes_a = [axes_a] + na = 1 + try: + nb = len(axes_b) + except TypeError: + axes_b = [axes_b] + nb = 1 + + a, b = asarray(a), asarray(b) + as = a.shape + bs = b.shape + equal = 1 + if (na != nb): equal = 0 + for k in xrange(na): + if as[axes_a[k]] != bs[axes_b[k]]: + equal = 0 + break + + if not equal: + raise ValueError, "shape-mismatch for sum" + + olda = [ for k in aa if k not in axes_a] + oldb = [k for k in bs if k not in axes_b] + + at = a.reshape(nd1, nd2) + res = dot(at, bt) + return res.reshape(olda + oldb) + + def _move_axis_to_0(a, axis): if axis == 0: return a Modified: tags/1.0b4/numpy/lib/function_base.py =================================================================== --- tags/1.0b4/numpy/lib/function_base.py 2006-08-28 05:56:49 UTC (rev 3084) +++ tags/1.0b4/numpy/lib/function_base.py 2006-08-28 19:42:27 UTC (rev 3085) @@ -7,7 +7,7 @@ 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', - 'delete', 'insert', 'append', 'tensordot' + 'delete', 'insert', 'append' ] import types @@ -1216,11 +1216,3 @@ axis = arr.ndim-1 return concatenate((arr, values), axis=axis) -def tensordot(arr1, arr2, axes1=-1, axes2=0): - """tensordot returns the product for any (ndim >= 1) arrays. - - r_{xxx, yyy} = \sum_k arr1_{xxx,k} arr2_{k,yyy} where - the axes of k - """ - #FIXME - pass From numpy-svn at scipy.org Mon Aug 28 15:46:13 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 28 Aug 2006 14:46:13 -0500 (CDT) Subject: [Numpy-svn] r3086 - in trunk/numpy: core lib lib/tests oldnumeric Message-ID: <20060828194613.E284139C013@new.scipy.org> Author: oliphant Date: 2006-08-28 14:46:08 -0500 (Mon, 28 Aug 2006) New Revision: 3086 Modified: trunk/numpy/core/numeric.py trunk/numpy/lib/function_base.py trunk/numpy/lib/tests/test_function_base.py trunk/numpy/oldnumeric/misc.py Log: Merge changes mistakenly added to 1.0b4 tag to the main trunk Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-28 19:42:27 UTC (rev 3085) +++ trunk/numpy/core/numeric.py 2006-08-28 19:46:08 UTC (rev 3086) @@ -7,7 +7,7 @@ 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', - 'alterdot', 'restoredot', 'cross', + 'alterdot', 'restoredot', 'cross', 'tensordot', 'array2string', 'get_printoptions', 'set_printoptions', 'array_repr', 'array_str', 'set_string_function', 'little_endian', 'require', @@ -252,7 +252,48 @@ def restoredot(): pass +def tensordot(a, b, axes=(-1,0)) + """tensordot returns the product for any (ndim >= 1) arrays. + r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where + + the axes to be summed over are given by the axes argument. + the first element of the sequence determines the axis or axes + in arr1 to sum over and the second element in axes argument sequence + """ + axes_a, axes_b = axes + try: + na = len(axes_a) + except TypeError: + axes_a = [axes_a] + na = 1 + try: + nb = len(axes_b) + except TypeError: + axes_b = [axes_b] + nb = 1 + + a, b = asarray(a), asarray(b) + as = a.shape + bs = b.shape + equal = 1 + if (na != nb): equal = 0 + for k in xrange(na): + if as[axes_a[k]] != bs[axes_b[k]]: + equal = 0 + break + + if not equal: + raise ValueError, "shape-mismatch for sum" + + olda = [ for k in aa if k not in axes_a] + oldb = [k for k in bs if k not in axes_b] + + at = a.reshape(nd1, nd2) + res = dot(at, bt) + return res.reshape(olda + oldb) + + def _move_axis_to_0(a, axis): if axis == 0: return a Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-28 19:42:27 UTC (rev 3085) +++ trunk/numpy/lib/function_base.py 2006-08-28 19:46:08 UTC (rev 3086) @@ -1,13 +1,13 @@ -__all__ = ['logspace', 'linspace', +u__all__ = ['logspace', 'linspace', 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', #'base_repr', 'binary_repr', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', - 'unique', 'extract', 'insert', 'nansum', 'nanmax', 'nanargmax', + 'unique', 'extract', 'place', 'nansum', 'nanmax', 'nanargmax', 'nanargmin', 'nanmin', 'vectorize', 'asarray_chkfinite', 'average', 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', - 'deletefrom', 'insertinto', 'appendonto' + 'delete', 'insert', 'append' ] import types @@ -545,7 +545,7 @@ """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) -def insert(arr, mask, vals): +def place(arr, mask, vals): """Similar to putmask arr[mask] = vals but the 1D array vals has the same number of elements as the non-zero values of mask. Inverse of extract. @@ -1011,7 +1011,7 @@ Y = y.repeat(numCols, axis=1) return X, Y -def deletefrom(arr, obj, axis=None): +def delete(arr, obj, axis=None): """Return a new array with sub-arrays along an axis deleted. Return a new array with the sub-arrays (i.e. rows or columns) @@ -1117,7 +1117,7 @@ else: return new -def insertinto(arr, obj, values, axis=None): +def insert(arr, obj, values, axis=None): """Return a new array with values inserted along the given axis before the given indices @@ -1205,7 +1205,7 @@ return wrap(new) return new -def appendonto(arr, values, axis=None): +def append(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ arr = asanyarray(arr) @@ -1215,3 +1215,4 @@ values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axis) + Modified: trunk/numpy/lib/tests/test_function_base.py =================================================================== --- trunk/numpy/lib/tests/test_function_base.py 2006-08-28 19:42:27 UTC (rev 3085) +++ trunk/numpy/lib/tests/test_function_base.py 2006-08-28 19:46:08 UTC (rev 3086) @@ -237,17 +237,17 @@ a = array([1,3,2,1,2,3,3]) b = extract(a>1,a) assert_array_equal(b,[3,2,2,3,3]) - def check_insert(self): + def check_place(self): a = array([1,4,3,2,5,8,7]) - insert(a,[0,1,0,1,0,1,0],[2,4,6]) + place(a,[0,1,0,1,0,1,0],[2,4,6]) assert_array_equal(a,[1,2,3,4,5,6,7]) def check_both(self): a = rand(10) mask = a > 0.5 ac = a.copy() c = extract(mask, a) - insert(a,mask,0) - insert(a,mask,c) + place(a,mask,0) + place(a,mask,c) assert_array_equal(a,ac) class test_vectorize(NumpyTestCase): Modified: trunk/numpy/oldnumeric/misc.py =================================================================== --- trunk/numpy/oldnumeric/misc.py 2006-08-28 19:42:27 UTC (rev 3085) +++ trunk/numpy/oldnumeric/misc.py 2006-08-28 19:46:08 UTC (rev 3086) @@ -9,7 +9,7 @@ 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', 'array_repr', 'e', 'StringIO', 'pickle', 'argsort', 'convolve', 'loads', 'cross_correlate', - 'Pickler', 'dot', 'outerproduct', 'innerproduct'] + 'Pickler', 'dot', 'outerproduct', 'innerproduct', 'insert'] import types import StringIO @@ -23,7 +23,8 @@ choose, swapaxes, array_str, array_repr, e, pi, \ fromfunction, resize, around, concatenate, vdot, transpose, \ diagonal, searchsorted, put, argsort, convolve, dot, \ - outer as outerproduct, inner as innerproduct, correlate as cross_correlate + outer as outerproduct, inner as innerproduct, correlate as cross_correlate, \ + place as insert from array_printer import array2string From numpy-svn at scipy.org Mon Aug 28 15:53:00 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 28 Aug 2006 14:53:00 -0500 (CDT) Subject: [Numpy-svn] r3087 - in tags/1.0b4/numpy: core lib lib/tests oldnumeric Message-ID: <20060828195300.7336339C013@new.scipy.org> Author: oliphant Date: 2006-08-28 14:52:55 -0500 (Mon, 28 Aug 2006) New Revision: 3087 Modified: tags/1.0b4/numpy/core/numeric.py tags/1.0b4/numpy/lib/function_base.py tags/1.0b4/numpy/lib/tests/test_function_base.py tags/1.0b4/numpy/oldnumeric/misc.py Log: Undoing changes mistakenly made on tag 1.0b4 Modified: tags/1.0b4/numpy/core/numeric.py =================================================================== --- tags/1.0b4/numpy/core/numeric.py 2006-08-28 19:46:08 UTC (rev 3086) +++ tags/1.0b4/numpy/core/numeric.py 2006-08-28 19:52:55 UTC (rev 3087) @@ -7,7 +7,7 @@ 'asarray', 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'isfortran', 'empty_like', 'zeros_like', 'correlate', 'convolve', 'inner', 'dot', 'outer', 'vdot', - 'alterdot', 'restoredot', 'cross', 'tensordot', + 'alterdot', 'restoredot', 'cross', 'array2string', 'get_printoptions', 'set_printoptions', 'array_repr', 'array_str', 'set_string_function', 'little_endian', 'require', @@ -252,48 +252,7 @@ def restoredot(): pass -def tensordot(a, b, axes=(-1,0)) - """tensordot returns the product for any (ndim >= 1) arrays. - r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where - - the axes to be summed over are given by the axes argument. - the first element of the sequence determines the axis or axes - in arr1 to sum over and the second element in axes argument sequence - """ - axes_a, axes_b = axes - try: - na = len(axes_a) - except TypeError: - axes_a = [axes_a] - na = 1 - try: - nb = len(axes_b) - except TypeError: - axes_b = [axes_b] - nb = 1 - - a, b = asarray(a), asarray(b) - as = a.shape - bs = b.shape - equal = 1 - if (na != nb): equal = 0 - for k in xrange(na): - if as[axes_a[k]] != bs[axes_b[k]]: - equal = 0 - break - - if not equal: - raise ValueError, "shape-mismatch for sum" - - olda = [ for k in aa if k not in axes_a] - oldb = [k for k in bs if k not in axes_b] - - at = a.reshape(nd1, nd2) - res = dot(at, bt) - return res.reshape(olda + oldb) - - def _move_axis_to_0(a, axis): if axis == 0: return a Modified: tags/1.0b4/numpy/lib/function_base.py =================================================================== --- tags/1.0b4/numpy/lib/function_base.py 2006-08-28 19:46:08 UTC (rev 3086) +++ tags/1.0b4/numpy/lib/function_base.py 2006-08-28 19:52:55 UTC (rev 3087) @@ -1,13 +1,13 @@ -u__all__ = ['logspace', 'linspace', +__all__ = ['logspace', 'linspace', 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', #'base_repr', 'binary_repr', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', - 'unique', 'extract', 'place', 'nansum', 'nanmax', 'nanargmax', + 'unique', 'extract', 'insert', 'nansum', 'nanmax', 'nanargmax', 'nanargmin', 'nanmin', 'vectorize', 'asarray_chkfinite', 'average', 'histogram', 'bincount', 'digitize', 'cov', 'corrcoef', 'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring', 'meshgrid', - 'delete', 'insert', 'append' + 'deletefrom', 'insertinto', 'appendonto' ] import types @@ -545,7 +545,7 @@ """ return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) -def place(arr, mask, vals): +def insert(arr, mask, vals): """Similar to putmask arr[mask] = vals but the 1D array vals has the same number of elements as the non-zero values of mask. Inverse of extract. @@ -1011,7 +1011,7 @@ Y = y.repeat(numCols, axis=1) return X, Y -def delete(arr, obj, axis=None): +def deletefrom(arr, obj, axis=None): """Return a new array with sub-arrays along an axis deleted. Return a new array with the sub-arrays (i.e. rows or columns) @@ -1117,7 +1117,7 @@ else: return new -def insert(arr, obj, values, axis=None): +def insertinto(arr, obj, values, axis=None): """Return a new array with values inserted along the given axis before the given indices @@ -1205,7 +1205,7 @@ return wrap(new) return new -def append(arr, values, axis=None): +def appendonto(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ arr = asanyarray(arr) @@ -1215,4 +1215,3 @@ values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axis) - Modified: tags/1.0b4/numpy/lib/tests/test_function_base.py =================================================================== --- tags/1.0b4/numpy/lib/tests/test_function_base.py 2006-08-28 19:46:08 UTC (rev 3086) +++ tags/1.0b4/numpy/lib/tests/test_function_base.py 2006-08-28 19:52:55 UTC (rev 3087) @@ -237,17 +237,17 @@ a = array([1,3,2,1,2,3,3]) b = extract(a>1,a) assert_array_equal(b,[3,2,2,3,3]) - def check_place(self): + def check_insert(self): a = array([1,4,3,2,5,8,7]) - place(a,[0,1,0,1,0,1,0],[2,4,6]) + insert(a,[0,1,0,1,0,1,0],[2,4,6]) assert_array_equal(a,[1,2,3,4,5,6,7]) def check_both(self): a = rand(10) mask = a > 0.5 ac = a.copy() c = extract(mask, a) - place(a,mask,0) - place(a,mask,c) + insert(a,mask,0) + insert(a,mask,c) assert_array_equal(a,ac) class test_vectorize(NumpyTestCase): Modified: tags/1.0b4/numpy/oldnumeric/misc.py =================================================================== --- tags/1.0b4/numpy/oldnumeric/misc.py 2006-08-28 19:46:08 UTC (rev 3086) +++ tags/1.0b4/numpy/oldnumeric/misc.py 2006-08-28 19:52:55 UTC (rev 3087) @@ -9,7 +9,7 @@ 'searchsorted', 'put', 'fromfunction', 'copy', 'resize', 'array_repr', 'e', 'StringIO', 'pickle', 'argsort', 'convolve', 'loads', 'cross_correlate', - 'Pickler', 'dot', 'outerproduct', 'innerproduct', 'insert'] + 'Pickler', 'dot', 'outerproduct', 'innerproduct'] import types import StringIO @@ -23,8 +23,7 @@ choose, swapaxes, array_str, array_repr, e, pi, \ fromfunction, resize, around, concatenate, vdot, transpose, \ diagonal, searchsorted, put, argsort, convolve, dot, \ - outer as outerproduct, inner as innerproduct, correlate as cross_correlate, \ - place as insert + outer as outerproduct, inner as innerproduct, correlate as cross_correlate from array_printer import array2string From numpy-svn at scipy.org Mon Aug 28 16:01:38 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 28 Aug 2006 15:01:38 -0500 (CDT) Subject: [Numpy-svn] r3088 - in trunk/numpy: core lib Message-ID: <20060828200138.A134539C051@new.scipy.org> Author: oliphant Date: 2006-08-28 15:01:34 -0500 (Mon, 28 Aug 2006) New Revision: 3088 Modified: trunk/numpy/core/fromnumeric.py trunk/numpy/core/numeric.py trunk/numpy/lib/function_base.py Log: Fix sundry errors. Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2006-08-28 19:52:55 UTC (rev 3087) +++ trunk/numpy/core/fromnumeric.py 2006-08-28 20:01:34 UTC (rev 3088) @@ -356,6 +356,7 @@ if out is not None: out[...] = res return out + return res try: sum = x.sum except AttributeError: Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-28 19:52:55 UTC (rev 3087) +++ trunk/numpy/core/numeric.py 2006-08-28 20:01:34 UTC (rev 3088) @@ -252,7 +252,7 @@ def restoredot(): pass -def tensordot(a, b, axes=(-1,0)) +def tensordot(a, b, axes=(-1,0)): """tensordot returns the product for any (ndim >= 1) arrays. r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where @@ -286,7 +286,7 @@ if not equal: raise ValueError, "shape-mismatch for sum" - olda = [ for k in aa if k not in axes_a] + olda = [k for k in aa if k not in axes_a] oldb = [k for k in bs if k not in axes_b] at = a.reshape(nd1, nd2) Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-28 19:52:55 UTC (rev 3087) +++ trunk/numpy/lib/function_base.py 2006-08-28 20:01:34 UTC (rev 3088) @@ -1,4 +1,4 @@ -u__all__ = ['logspace', 'linspace', +__all__ = ['logspace', 'linspace', 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', #'base_repr', 'binary_repr', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', From numpy-svn at scipy.org Mon Aug 28 16:56:27 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 28 Aug 2006 15:56:27 -0500 (CDT) Subject: [Numpy-svn] r3089 - trunk/numpy/core/src Message-ID: <20060828205627.5F14139C013@new.scipy.org> Author: oliphant Date: 2006-08-28 15:56:23 -0500 (Mon, 28 Aug 2006) New Revision: 3089 Modified: trunk/numpy/core/src/scalartypes.inc.src Log: Fix flags on numpy array scalars for array interface. Modified: trunk/numpy/core/src/scalartypes.inc.src =================================================================== --- trunk/numpy/core/src/scalartypes.inc.src 2006-08-28 20:01:34 UTC (rev 3088) +++ trunk/numpy/core/src/scalartypes.inc.src 2006-08-28 20:56:23 UTC (rev 3089) @@ -731,6 +731,8 @@ inter->two = 2; inter->nd = 0; inter->flags = arr->flags; + inter->flags &= ~(UPDATEIFCOPY | OWNDATA); + inter->flags |= NPY_NOTSWAPPED; inter->typekind = arr->descr->kind; inter->itemsize = arr->descr->elsize; inter->strides = NULL; From numpy-svn at scipy.org Mon Aug 28 22:47:45 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 28 Aug 2006 21:47:45 -0500 (CDT) Subject: [Numpy-svn] r3090 - in trunk/numpy: . core core/src Message-ID: <20060829024745.CF0E339C022@new.scipy.org> Author: oliphant Date: 2006-08-28 21:47:39 -0500 (Mon, 28 Aug 2006) New Revision: 3090 Modified: trunk/numpy/__init__.py trunk/numpy/core/numeric.py trunk/numpy/core/src/arrayobject.c Log: Add float, int, etc. to numpy name-space. Flesh out tensordot. Fix-up getcharbuf to allow all 8-bit types to be returned as a charbuf. Modified: trunk/numpy/__init__.py =================================================================== --- trunk/numpy/__init__.py 2006-08-28 20:56:23 UTC (rev 3089) +++ trunk/numpy/__init__.py 2006-08-29 02:47:39 UTC (rev 3090) @@ -36,6 +36,10 @@ from core import * import lib from lib import * + # Make these accessible from numpy name-space + # but not imported in from numpy import * + from __builtin__ import bool, int, long, float, complex, \ + object, unicode, str import linalg import fft import random Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2006-08-28 20:56:23 UTC (rev 3089) +++ trunk/numpy/core/numeric.py 2006-08-29 02:47:39 UTC (rev 3090) @@ -190,7 +190,7 @@ is a sequence of indices into a. This sequence must be converted to a tuple in order to be used to index into a. """ - return transpose(a.nonzero()) + return asarray(a.nonzero()).T def flatnonzero(a): """Return indicies that are not-zero in flattened version of a @@ -252,6 +252,7 @@ def restoredot(): pass + def tensordot(a, b, axes=(-1,0)): """tensordot returns the product for any (ndim >= 1) arrays. @@ -259,37 +260,67 @@ the axes to be summed over are given by the axes argument. the first element of the sequence determines the axis or axes - in arr1 to sum over and the second element in axes argument sequence + in arr1 to sum over, and the second element in axes argument sequence + determines the axis or axes in arr2 to sum over. + + When there is more than one axis to sum over, the corresponding + arguments to axes should be sequences of the same length with the first + axis to sum over given first in both sequences, the second axis second, + and so forth. """ axes_a, axes_b = axes try: na = len(axes_a) + axes_a = list(axes_a) except TypeError: axes_a = [axes_a] na = 1 try: nb = len(axes_b) + axes_b = list(axes_b) except TypeError: axes_b = [axes_b] nb = 1 a, b = asarray(a), asarray(b) as = a.shape + nda = len(a.shape) bs = b.shape + ndb = len(b.shape) equal = 1 if (na != nb): equal = 0 - for k in xrange(na): - if as[axes_a[k]] != bs[axes_b[k]]: - equal = 0 - break - + else: + for k in xrange(na): + if as[axes_a[k]] != bs[axes_b[k]]: + equal = 0 + break + if axes_a[k] < 0: + axes_a[k] += nda + if axes_b[k] < 0: + axes_b[k] += ndb if not equal: - raise ValueError, "shape-mismatch for sum" - - olda = [k for k in aa if k not in axes_a] - oldb = [k for k in bs if k not in axes_b] + raise ValueError, "shape-mismatch for sum" - at = a.reshape(nd1, nd2) + # Move the axes to sum over to the end of "a" + # and to the front of "b" + notin = [k for k in range(nda) if k not in axes_a] + newaxes_a = notin + axes_a + N2 = 1 + for axis in axes_a: + N2 *= as[axis] + newshape_a = (-1, N2) + olda = [as[axis] for axis in notin] + + notin = [k for k in range(ndb) if k not in axes_b] + newaxes_b = axes_b + notin + N2 = 1 + for axis in axes_b: + N2 *= bs[axis] + newshape_b = (N2, -1) + oldb = [bs[axis] for axis in notin] + + at = a.transpose(newaxes_a).reshape(newshape_a) + bt = b.transpose(newaxes_b).reshape(newshape_b) res = dot(at, bt) return res.reshape(olda + oldb) Modified: trunk/numpy/core/src/arrayobject.c =================================================================== --- trunk/numpy/core/src/arrayobject.c 2006-08-28 20:56:23 UTC (rev 3089) +++ trunk/numpy/core/src/arrayobject.c 2006-08-29 02:47:39 UTC (rev 3090) @@ -3038,12 +3038,13 @@ 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->type_num == PyArray_UNICODE || \ + self->descr->elsize == 1) return array_getreadbuf(self, segment, (void **) ptrptr); else { PyErr_SetString(PyExc_TypeError, - "non-character array cannot be interpreted "\ - "as character buffer"); + "non-character (or 8-bit) array cannot be "\ + "interpreted as character buffer"); return -1; } } From numpy-svn at scipy.org Tue Aug 29 02:02:17 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 29 Aug 2006 01:02:17 -0500 (CDT) Subject: [Numpy-svn] r3091 - in trunk/numpy: . core/src Message-ID: <20060829060217.93A3439C023@new.scipy.org> Author: charris Date: 2006-08-29 01:02:10 -0500 (Tue, 29 Aug 2006) New Revision: 3091 Modified: trunk/numpy/add_newdocs.py trunk/numpy/core/src/arraymethods.c Log: Move more documentation from arraymethods to add_newdocs. Modified: trunk/numpy/add_newdocs.py =================================================================== --- trunk/numpy/add_newdocs.py 2006-08-29 02:47:39 UTC (rev 3090) +++ trunk/numpy/add_newdocs.py 2006-08-29 06:02:10 UTC (rev 3091) @@ -447,6 +447,30 @@ # ############################################################################## + +add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__', +"""a.__copy__(|order) -> copy, possibly with different order. + +Return a copy of the array. + +Argument: + order -- Order of returned copy (default 'C') + If order is 'C' (False) then the result is contiguous (default). + If order is 'Fortran' (True) then the result has fortran order. + If order is 'Any' (None) then the result has fortran order + only if m is already in fortran order.; + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('__deepcopy__', +"""a.__deepcopy__() -> Deep copy of array. + +Used if copy.deepcopy is called on an array. + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('all', """ a.all(axis=None) @@ -506,6 +530,24 @@ """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('astype', +"""a.astype(t) -> Copy of array cast to type t. + +Cast array m to type t. t can be either a string representing a typecode, +or a python type object of type int, float, or complex. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('byteswap', +"""a.byteswap(False) -> View or copy. Swap the bytes in the array. + +Swap the bytes in the array. Return the byteswapped array. If the first +argument is TRUE, byteswap in-place and return a reference to self. + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('choose', """ a.choose(b0, b1, ..., bn, out=None, mode='raise') @@ -540,6 +582,21 @@ """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('copy', +"""a.copy(|order) -> copy, possibly with different order. + +Return a copy of the array. + +Argument: + order -- Order of returned copy (default 'C') + If order is 'C' (False) then the result is contiguous (default). + If order is 'Fortran' (True) then the result has fortran order. + If order is 'Any' (None) then the result has fortran order + only if m is already in fortran order.; + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('cumprod', """a.cumprod(axis=None, dtype=None) @@ -567,6 +624,25 @@ """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('getfield', +"""a.getfield(dtype, offset) -> field of array as given type. + +Returns a field of the given array as a certain type. A field is a view of +the array's data with each itemsize determined by the given type and the +offset into the current array. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('item', +"""a.item() -> copy of first array item as Python scalar. + +Copy the first element of array to a standard Python scalar and return +it. The array must be of size one. + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('max', """a.max(axis=None) @@ -653,8 +729,8 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat', """a.repeat(repeats=, axis=none) -copy elements of a, repeats times. the repeats argument must -be a sequence of length a.shape[axis] or a scalar.; +copy elements of a, repeats times. the repeats argument must be a sequence +of length a.shape[axis] or a scalar. """)) @@ -662,13 +738,22 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape', """a.reshape(d1, d2, ..., dn, order='c') -Return a new array from this one. The new array must have the -same number of elements as self. Also always returns a view or -raises a ValueError if that is impossible.; +Return a new array from this one. The new array must have the same number +of elements as self. Also always returns a view or raises a ValueError if +that is impossible.; """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('resize', +"""a.resize(new_shape, refcheck=True, order=False) -> None. Change array shape. + +Change size and shape of self inplace. Array must own its own memory and +not be referenced by other arrays. Returns None. + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('round', """a.round(decimals=0, out=None) @@ -678,15 +763,22 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted', """a.searchsorted(v) - Assuming that a is a 1-D array, in ascending order and represents - bin boundaries, then a.searchsorted(values) gives an array of bin - numbers, giving the bin into which each value would be placed. - This method is helpful for histograming. Note: No warning is - given if the boundaries, in a, are not in ascending order.; + Assuming that a is a 1-D array, in ascending order and represents bin + boundaries, then a.searchsorted(values) gives an array of bin numbers, + giving the bin into which each value would be placed. This method is + helpful for histograming. Note: No warning is given if the boundaries, in + a, are not in ascending order. """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('setfield', +"""m.setfield(value, dtype, offset) -> None. +places val into field of the given array defined by the data type and offset. + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags', """a.setflags(write=None, align=None, uic=None) @@ -794,9 +886,32 @@ """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile', +"""a.tofile(fid, sep="") -> None. Write the data to a file. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist', +"""a.tolist() -> Array as hierarchical list. + +Copy the data portion of the array to a hierarchical python list and return +that list. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', +"""a.tostring(order='C') -> binary array data as Python string. + +Construct a Python string containing the raw bytes in the array. + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('trace', """a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) -return the sum along the offset diagonal of the arrays indicated +return the sum along the offset diagonal of the array's indicated axis1 and axis2. """)) @@ -840,5 +955,3 @@ Type can be either a new sub-type object or a data-descriptor object """)) - - Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-29 02:47:39 UTC (rev 3090) +++ trunk/numpy/core/src/arraymethods.c 2006-08-29 06:02:10 UTC (rev 3091) @@ -228,10 +228,6 @@ return PyArray_SwapAxes(self, axis1, axis2); } -static char doc_getfield[] = "m.getfield(dtype, offset) returns a field "\ - " of the given array as a certain type. \nA field is a view of "\ - " the array's data with each itemsize determined by the\ngiven type"\ - " and the offset into the current array."; /* steals typed reference */ /*OBJECT_API @@ -280,9 +276,6 @@ } -static char doc_setfield[] = "m.setfield(value, dtype, offset) places val "\ - "into field of the given array defined by the data type and offset."; - /*OBJECT_API Set a subset of bytes from each element of the array */ @@ -384,9 +377,6 @@ } } -static char doc_byteswap[] = "m.byteswap(False) Swap the bytes in"\ - " the array. Return the byteswapped array. If the first argument"\ - " is TRUE, byteswap in-place and return a reference to self."; static PyObject * array_byteswap(PyArrayObject *self, PyObject *args) @@ -399,9 +389,6 @@ return PyArray_Byteswap(self, inplace); } -static char doc_tolist[] = "m.tolist(). Copy the data portion of the array"\ - " to a hierarchical python list and return that list."; - static PyObject * array_tolist(PyArrayObject *self, PyObject *args) { @@ -409,8 +396,6 @@ return PyArray_ToList(self); } -static char doc_tostring[] = "m.tostring(order='C') Construct a Python string "\ - "containing the raw bytes in the array"; static PyObject * array_tostring(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -424,7 +409,6 @@ return PyArray_ToString(self, order); } -static char doc_tofile[] = "m.tofile(fid, sep="") write the data to a file."; static PyObject * array_tofile(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -461,8 +445,6 @@ return Py_None; } -static char doc_toscalar[] = "m.item(). Copy the first data point of "\ - "the array to a standard Python scalar and return it."; static PyObject * array_toscalar(PyArrayObject *self, PyObject *args) { @@ -476,9 +458,6 @@ } } -static char doc_cast[] = "m.astype(t). Cast array m to type t. \n\n"\ - "t can be either a string representing a typecode, or a python type"\ - " object of type int, float, or complex."; static PyObject * array_cast(PyArrayObject *self, PyObject *args) @@ -585,11 +564,6 @@ } } -static char doc_copy[] = "m.copy(|order). Return a copy of the array.\n"\ - "If order is 'C' (False) then the result is contiguous (default). \n"\ - "If order is 'Fortran' (True) then the result has fortran order. \n"\ - "If order is 'Any' (None) then the result has fortran order \n"\ - "only if m is already in fortran order."; static PyObject * array_copy(PyArrayObject *self, PyObject *args) @@ -601,10 +575,6 @@ return PyArray_NewCopy(self, fortran); } -static char doc_resize[] = "self.resize(new_shape, refcheck=True, order=False). "\ - "Change size and shape of self inplace.\n"\ - "\n Array must own its own memory and not be referenced by other " \ - "arrays\n Returns None."; static PyObject * array_resize(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -767,7 +737,6 @@ } } -static char doc_deepcopy[] = "Used if copy.deepcopy is called on an array."; static PyObject * array_deepcopy(PyArrayObject *self, PyObject *args) @@ -1570,117 +1539,130 @@ } static PyMethodDef array_methods[] = { - {"tolist", (PyCFunction)array_tolist, 1, doc_tolist}, - {"item", (PyCFunction)array_toscalar, METH_VARARGS, doc_toscalar}, + {"astype", (PyCFunction)array_cast, + 1, NULL}, + {"byteswap", (PyCFunction)array_byteswap, + 1, NULL}, + {"copy", (PyCFunction)array_copy, + 1, NULL}, + {"getfield", (PyCFunction)array_getfield, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"item", (PyCFunction)array_toscalar, + METH_VARARGS, NULL}, {"tofile", (PyCFunction)array_tofile, - METH_VARARGS | METH_KEYWORDS, doc_tofile}, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"tolist", (PyCFunction)array_tolist, + 1, NULL}, {"tostring", (PyCFunction)array_tostring, - METH_VARARGS | METH_KEYWORDS, doc_tostring}, - {"byteswap", (PyCFunction)array_byteswap, 1, doc_byteswap}, - {"astype", (PyCFunction)array_cast, 1, doc_cast}, - {"getfield", (PyCFunction)array_getfield, - METH_VARARGS | METH_KEYWORDS, doc_getfield}, - {"setfield", (PyCFunction)array_setfield, - METH_VARARGS | METH_KEYWORDS, doc_setfield}, - {"copy", (PyCFunction)array_copy, 1, doc_copy}, + METH_VARARGS | METH_KEYWORDS, NULL}, {"resize", (PyCFunction)array_resize, - METH_VARARGS | METH_KEYWORDS, doc_resize}, + METH_VARARGS | METH_KEYWORDS, NULL}, + {"setfield", (PyCFunction)array_setfield, + METH_VARARGS | METH_KEYWORDS, NULL}, /* for subtypes */ - {"__array__", (PyCFunction)array_getarray, 1, doc_array_getarray}, - {"__array_wrap__", (PyCFunction)array_wraparray, 1, doc_wraparray}, + {"__array__", (PyCFunction)array_getarray, + 1, doc_array_getarray}, + {"__array_wrap__", (PyCFunction)array_wraparray, + 1, doc_wraparray}, /* for the copy module */ - {"__copy__", (PyCFunction)array_copy, 1, doc_copy}, - {"__deepcopy__", (PyCFunction)array_deepcopy, 1, doc_deepcopy}, + {"__copy__", (PyCFunction)array_copy, + 1, NULL}, + {"__deepcopy__", (PyCFunction)array_deepcopy, + 1, NULL}, /* for Pickling */ - {"__reduce__", (PyCFunction) array_reduce, 1, doc_reduce}, - {"__setstate__", (PyCFunction) array_setstate, 1, doc_setstate}, - {"dumps", (PyCFunction) array_dumps, 1, doc_dumps}, - {"dump", (PyCFunction) array_dump, 1, doc_dump}, + {"__reduce__", (PyCFunction) array_reduce, + 1, doc_reduce}, + {"__setstate__", (PyCFunction) array_setstate, + 1, doc_setstate}, + {"dumps", (PyCFunction) array_dumps, + 1, doc_dumps}, + {"dump", (PyCFunction) array_dump, + 1, doc_dump}, /* Extended methods added 2005 */ - {"all", (PyCFunction)array_all, - METH_VARARGS|METH_KEYWORDS, NULL}, + {"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}, - {"choose", (PyCFunction)array_choose, - METH_VARARGS|METH_KEYWORDS, NULL}, + 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}, + {"choose", (PyCFunction)array_choose, + METH_VARARGS|METH_KEYWORDS, NULL}, {"clip", (PyCFunction)array_clip, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"compress", (PyCFunction)array_compress, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"conj", (PyCFunction)array_conjugate, - METH_VARARGS, NULL}, + METH_VARARGS, NULL}, {"conjugate", (PyCFunction)array_conjugate, - METH_VARARGS, NULL}, + METH_VARARGS, NULL}, {"cumprod", (PyCFunction)array_cumprod, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"cumsum", (PyCFunction)array_cumsum, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"diagonal", (PyCFunction)array_diagonal, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"fill", (PyCFunction)array_fill, - METH_VARARGS, NULL}, + METH_VARARGS, NULL}, {"flatten", (PyCFunction)array_flatten, - METH_VARARGS, NULL}, + METH_VARARGS, NULL}, {"max", (PyCFunction)array_max, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"mean", (PyCFunction)array_mean, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"min", (PyCFunction)array_min, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"newbyteorder", (PyCFunction)array_newbyteorder, - METH_VARARGS, NULL}, + METH_VARARGS, NULL}, {"nonzero", (PyCFunction)array_nonzero, - METH_VARARGS, NULL}, + METH_VARARGS, NULL}, {"prod", (PyCFunction)array_prod, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"ptp", (PyCFunction)array_ptp, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"put", (PyCFunction)array_put, - METH_VARARGS|METH_KEYWORDS, NULL}, - {"putmask", (PyCFunction)array_putmask, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"putmask", (PyCFunction)array_putmask, + 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}, + METH_VARARGS, NULL}, + {"repeat", (PyCFunction)array_repeat, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"reshape", (PyCFunction)array_reshape, + METH_VARARGS|METH_KEYWORDS, NULL}, {"round", (PyCFunction)array_round, - METH_VARARGS|METH_KEYWORDS, NULL}, - {"searchsorted", (PyCFunction)array_searchsorted, - METH_VARARGS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"searchsorted", (PyCFunction)array_searchsorted, + METH_VARARGS, 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}, + 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}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"sum", (PyCFunction)array_sum, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS|METH_KEYWORDS, NULL}, {"swapaxes", (PyCFunction)array_swapaxes, - METH_VARARGS, NULL}, - {"take", (PyCFunction)array_take, - METH_VARARGS|METH_KEYWORDS, NULL}, + METH_VARARGS, NULL}, + {"take", (PyCFunction)array_take, + METH_VARARGS|METH_KEYWORDS, NULL}, {"trace", (PyCFunction)array_trace, - METH_VARARGS|METH_KEYWORDS, NULL}, - {"transpose", (PyCFunction)array_transpose, - METH_VARARGS, NULL}, + 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}, + METH_VARARGS|METH_KEYWORDS, NULL}, + {"view", (PyCFunction)array_view, + METH_VARARGS, NULL}, {NULL, NULL} /* sentinel */ }; From numpy-svn at scipy.org Tue Aug 29 02:52:37 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 29 Aug 2006 01:52:37 -0500 (CDT) Subject: [Numpy-svn] r3092 - trunk/numpy/lib Message-ID: <20060829065237.0ACD039C03C@new.scipy.org> Author: oliphant Date: 2006-08-29 01:52:33 -0500 (Tue, 29 Aug 2006) New Revision: 3092 Modified: trunk/numpy/lib/arraysetops.py trunk/numpy/lib/shape_base.py Log: Add axis argument to usages of take Modified: trunk/numpy/lib/arraysetops.py =================================================================== --- trunk/numpy/lib/arraysetops.py 2006-08-29 06:02:10 UTC (rev 3091) +++ trunk/numpy/lib/arraysetops.py 2006-08-29 06:52:33 UTC (rev 3092) @@ -66,7 +66,7 @@ if retindx: ar = numpy.array(ar1).ravel() perm = ar.argsort() - aux = ar.take(perm) + aux = ar.take(perm,0) flag = ediff1d( aux, 1 ) != 0 return perm.compress(flag), aux.compress(flag) else: @@ -113,8 +113,8 @@ tt = concat( (zlike( ar1 ), zlike( ar2 ) + 1) ) perm = ar.argsort() - aux = ar.take(perm) - aux2 = tt.take(perm) + aux = ar.take(perm,0) + aux2 = tt.take(perm,0) flag = ediff1d( aux, 1 ) == 0 ii = numpy.where( flag * aux2 )[0] @@ -124,7 +124,7 @@ indx = perm.argsort()[:len( ar1 )] - return flag.take( indx ) + return flag.take( indx , 0) ## # 03.11.2005, c Modified: trunk/numpy/lib/shape_base.py =================================================================== --- trunk/numpy/lib/shape_base.py 2006-08-29 06:02:10 UTC (rev 3091) +++ trunk/numpy/lib/shape_base.py 2006-08-29 06:52:33 UTC (rev 3092) @@ -25,7 +25,7 @@ indlist = range(nd) indlist.remove(axis) i[axis] = slice(None,None) - outshape = asarray(arr.shape).take(indlist) + outshape = asarray(arr.shape).take(indlist,0) i.put(ind, indlist) res = func1d(arr[tuple(i.tolist())],*args) # if res is a number, then we have a smaller output array From numpy-svn at scipy.org Tue Aug 29 05:37:49 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 29 Aug 2006 04:37:49 -0500 (CDT) Subject: [Numpy-svn] r3093 - trunk/numpy/lib Message-ID: <20060829093749.E1F3F39C03C@new.scipy.org> Author: oliphant Date: 2006-08-29 04:37:47 -0500 (Tue, 29 Aug 2006) New Revision: 3093 Modified: trunk/numpy/lib/arraysetops.py trunk/numpy/lib/shape_base.py Log: Restore un-needed axis arguments Modified: trunk/numpy/lib/arraysetops.py =================================================================== --- trunk/numpy/lib/arraysetops.py 2006-08-29 06:52:33 UTC (rev 3092) +++ trunk/numpy/lib/arraysetops.py 2006-08-29 09:37:47 UTC (rev 3093) @@ -66,7 +66,7 @@ if retindx: ar = numpy.array(ar1).ravel() perm = ar.argsort() - aux = ar.take(perm,0) + aux = ar.take(perm) flag = ediff1d( aux, 1 ) != 0 return perm.compress(flag), aux.compress(flag) else: @@ -113,8 +113,8 @@ tt = concat( (zlike( ar1 ), zlike( ar2 ) + 1) ) perm = ar.argsort() - aux = ar.take(perm,0) - aux2 = tt.take(perm,0) + aux = ar.take(perm) + aux2 = tt.take(perm) flag = ediff1d( aux, 1 ) == 0 ii = numpy.where( flag * aux2 )[0] @@ -124,7 +124,7 @@ indx = perm.argsort()[:len( ar1 )] - return flag.take( indx , 0) + return flag.take( indx ) ## # 03.11.2005, c Modified: trunk/numpy/lib/shape_base.py =================================================================== --- trunk/numpy/lib/shape_base.py 2006-08-29 06:52:33 UTC (rev 3092) +++ trunk/numpy/lib/shape_base.py 2006-08-29 09:37:47 UTC (rev 3093) @@ -25,7 +25,7 @@ indlist = range(nd) indlist.remove(axis) i[axis] = slice(None,None) - outshape = asarray(arr.shape).take(indlist,0) + outshape = asarray(arr.shape).take(indlist) i.put(ind, indlist) res = func1d(arr[tuple(i.tolist())],*args) # if res is a number, then we have a smaller output array From numpy-svn at scipy.org Tue Aug 29 06:28:29 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 29 Aug 2006 05:28:29 -0500 (CDT) Subject: [Numpy-svn] r3094 - in trunk/numpy: . core core/tests f2py/tests/array_from_pyobj/tests fft lib lib/tests linalg numarray oldnumeric Message-ID: <20060829102829.8269639C023@new.scipy.org> Author: oliphant Date: 2006-08-29 05:28:11 -0500 (Tue, 29 Aug 2006) New Revision: 3094 Modified: trunk/numpy/add_newdocs.py trunk/numpy/core/ma.py trunk/numpy/core/tests/test_ma.py trunk/numpy/core/tests/test_numeric.py trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py trunk/numpy/fft/fftpack.py trunk/numpy/lib/arraysetops.py trunk/numpy/lib/function_base.py trunk/numpy/lib/shape_base.py trunk/numpy/lib/tests/test_function_base.py trunk/numpy/lib/tests/test_type_check.py trunk/numpy/lib/utils.py trunk/numpy/linalg/linalg.py trunk/numpy/numarray/functions.py trunk/numpy/oldnumeric/random_array.py trunk/numpy/oldnumeric/rng_stats.py Log: Add axis arguments to various functions so as not to rely on the defaults. Modified: trunk/numpy/add_newdocs.py =================================================================== --- trunk/numpy/add_newdocs.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/add_newdocs.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -657,7 +657,7 @@ is given, this equals: a.sum(axis, dtype) * 1.0 / len(a). If axis is None, this equals: - a.sum(axis, dtype) * 1.0 / product(a.shape) + a.sum(axis, dtype) * 1.0 / product(a.shape,axis=0) The optional dtype argument is the data type for intermediate calculations in the sum.; @@ -834,7 +834,7 @@ The standard deviation is the square root of the average of the squared deviations from the mean, i.e. - std = sqrt(mean((x - x.mean())**2)). + std = sqrt(mean((x - x.mean())**2,axis=0)). For multidimensional arrays, std is computed by default along the first axis. @@ -853,7 +853,7 @@ (promote) smaller integer types to the platform-dependent int. For example, on 32-bit platforms: - a.dtype default sum() dtype + a.dtype default sum dtype --------------------------------------------------- bool, int8, int16, int32 int32 Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/core/ma.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -1613,7 +1613,7 @@ If axis is None, average over the entire array Inputs can be integer or floating types; result is of type float. - If weights are given, result is sum(a*weights)/(sum(weights)*1.0) + If weights are given, result is sum(a*weights,axis=0)/(sum(weights,axis=0)*1.0) weights must have a's shape or be the 1-d with length the size of a in the given axis. Modified: trunk/numpy/core/tests/test_ma.py =================================================================== --- trunk/numpy/core/tests/test_ma.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/core/tests/test_ma.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -167,14 +167,14 @@ (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d self.failUnless (eq(numpy.add.reduce(x), add.reduce(x))) self.failUnless (eq(numpy.add.accumulate(x), add.accumulate(x))) - self.failUnless (eq(4, sum(array(4)))) + self.failUnless (eq(4, sum(array(4),axis=0))) self.failUnless (eq(4, sum(array(4), axis=0))) - self.failUnless (eq(numpy.sum(x), sum(x))) - self.failUnless (eq(numpy.sum(filled(xm,0)), sum(xm))) + self.failUnless (eq(numpy.sum(x,axis=0), sum(x,axis=0))) + self.failUnless (eq(numpy.sum(filled(xm,0),axis=0), sum(xm,axis=0))) self.failUnless (eq(numpy.sum(x,0), sum(x,0))) - self.failUnless (eq(numpy.product(x), product(x))) + self.failUnless (eq(numpy.product(x,axis=0), product(x,axis=0))) self.failUnless (eq(numpy.product(x,0), product(x,0))) - self.failUnless (eq(numpy.product(filled(xm,1)), product(xm))) + self.failUnless (eq(numpy.product(filled(xm,1),axis=0), product(xm,axis=0))) if len(s) > 1: self.failUnless (eq(numpy.concatenate((x,y),1), concatenate((xm,ym),1))) self.failUnless (eq(numpy.add.reduce(x,1), add.reduce(x,1))) @@ -308,9 +308,9 @@ m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1] i = numpy.nonzero(m)[0] putmask(xm, m, z) - assert take(xm, i) == z + assert take(xm, i,axis=0) == z put(ym, i, zm) - assert take(ym, i) == zm + assert take(ym, i,axis=0) == zm def check_testOddFeatures(self): "Test of other odd features" @@ -513,13 +513,13 @@ def check_testAverage1(self): "Test of average." ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) - self.failUnless(eq(2.0, average(ott))) + self.failUnless(eq(2.0, average(ott,axis=0))) self.failUnless(eq(2.0, average(ott, weights=[1., 1., 2., 1.]))) result, wts = average(ott, weights=[1.,1.,2.,1.], returned=1) self.failUnless(eq(2.0, result)) self.failUnless(wts == 4.0) ott[:] = masked - self.failUnless(average(ott) is masked) + self.failUnless(average(ott,axis=0) is masked) ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) ott=ott.reshape(2,2) ott[:,1] = masked @@ -539,20 +539,20 @@ y=array([arange(6), 2.0*arange(6)]) self.failUnless(allclose(average(y, None), numpy.add.reduce(numpy.arange(6))*3./12.)) self.failUnless(allclose(average(y, axis=0), numpy.arange(6) * 3./2.)) - self.failUnless(allclose(average(y, axis=1), [average(x), average(x) * 2.0])) + self.failUnless(allclose(average(y, axis=1), [average(x,axis=0), average(x,axis=0) * 2.0])) self.failUnless(allclose(average(y, None, weights=w2), 20./6.)) self.failUnless(allclose(average(y, axis=0, weights=w2), [0.,1.,2.,3.,4.,10.])) - self.failUnless(allclose(average(y, axis=1), [average(x), average(x) * 2.0])) + self.failUnless(allclose(average(y, axis=1), [average(x,axis=0), average(x,axis=0) * 2.0])) m1 = zeros(6) m2 = [0,0,1,1,0,0] m3 = [[0,0,1,1,0,0],[0,1,1,1,1,0]] m4 = ones(6) m5 = [0, 1, 1, 1, 1, 1] - self.failUnless(allclose(average(masked_array(x, m1)), 2.5)) - self.failUnless(allclose(average(masked_array(x, m2)), 2.5)) - self.failUnless(average(masked_array(x, m4)) is masked) - self.assertEqual(average(masked_array(x, m5)), 0.0) - self.assertEqual(count(average(masked_array(x, m4))), 0) + self.failUnless(allclose(average(masked_array(x, m1),axis=0), 2.5)) + self.failUnless(allclose(average(masked_array(x, m2),axis=0), 2.5)) + self.failUnless(average(masked_array(x, m4),axis=0) is masked) + self.assertEqual(average(masked_array(x, m5),axis=0), 0.0) + self.assertEqual(count(average(masked_array(x, m4),axis=0)), 0) z = masked_array(y, m3) self.failUnless(allclose(average(z, None), 20./6.)) self.failUnless(allclose(average(z, axis=0), [0.,1.,99.,99.,4.0, 7.5])) @@ -678,10 +678,10 @@ def test_reduce(self): a = self.d[0] - self.failIf(alltrue(a)) - self.failUnless(sometrue(a)) - self.failUnlessEqual(sum(a[:3]), 0) - self.failUnlessEqual(product(a), 0) + self.failIf(alltrue(a,axis=0)) + self.failUnless(sometrue(a,axis=0)) + self.failUnlessEqual(sum(a[:3],axis=0), 0) + self.failUnlessEqual(product(a,axis=0), 0) def test_minmax(self): a = arange(1,13).reshape(3,4) @@ -738,7 +738,7 @@ mXdiag = mX.diagonal() self.assertEqual(mX.trace(), mX.diagonal().compressed().sum()) self.failUnless(eq(mX.trace(), - X.trace() - sum(mXdiag.mask*X.diagonal()))) + X.trace() - sum(mXdiag.mask*X.diagonal(),axis=0))) def test_clip(self): (x,X,XX,m,mx,mX,mXX,) = self.d Modified: trunk/numpy/core/tests/test_numeric.py =================================================================== --- trunk/numpy/core/tests/test_numeric.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/core/tests/test_numeric.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -228,8 +228,8 @@ expected = array(list(self.makegen())) a = fromiter(self.makegen(), int) a20 = fromiter(self.makegen(), int, 20) - self.failUnless(alltrue(a == expected)) - self.failUnless(alltrue(a20 == expected[:20])) + self.failUnless(alltrue(a == expected,axis=0)) + self.failUnless(alltrue(a20 == expected[:20],axis=0)) class test_index(NumpyTestCase): def test_boolean(self): Modified: trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py =================================================================== --- trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -222,7 +222,7 @@ if arr1.shape != arr2.shape: return False s = arr1==arr2 - return alltrue(s.flatten()) + return alltrue(s.flatten(),axis=0) def __str__(self): return str(self.arr) Modified: trunk/numpy/fft/fftpack.py =================================================================== --- trunk/numpy/fft/fftpack.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/fft/fftpack.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -200,7 +200,7 @@ if axes == None: s = list(a.shape) else: - s = take(a.shape, axes) + s = take(a.shape, axes,axis=0) else: shapeless = 0 s = list(s) Modified: trunk/numpy/lib/arraysetops.py =================================================================== --- trunk/numpy/lib/arraysetops.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/lib/arraysetops.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -179,7 +179,7 @@ dt1s.append( dt1 ) dt2s.append( dt2 ) - assert numpy.alltrue( b == c ) + assert numpy.alltrue( b == c) print nItems Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/lib/function_base.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -108,17 +108,16 @@ """average(a, axis=None weights=None, returned=False) Average the array over the given axis. If the axis is None, average - over all dimensions of the array. Equivalent to a.mean(axis), but - with a default axis of 0 instead of None. + over all dimensions of the array. Equivalent to a.mean(axis) If an integer axis is given, this equals: a.sum(axis) * 1.0 / len(a) If axis is None, this equals: - a.sum(axis) * 1.0 / product(a.shape) + a.sum(axis) * 1.0 / product(a.shape,axis=0) If weights are given, result is: - sum(a * weights) / sum(weights), + sum(a * weights,axis) / sum(weights,axis), where the weights must have a's shape or be 1D with length the size of a in the given axis. Integer weights are converted to Float. Not specifying weights is equivalent to specifying @@ -541,9 +540,9 @@ """Return the elements of ravel(arr) where ravel(condition) is True (in 1D). - Equivalent to compress(ravel(condition), ravel(arr)). + Equivalent to compress(ravel(condition), ravel(arr),0). """ - return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) + return _nx.take(ravel(arr), nonzero(ravel(condition))[0],axis=0) def place(arr, mask, vals): """Similar to putmask arr[mask] = vals but the 1D array vals has the Modified: trunk/numpy/lib/shape_base.py =================================================================== --- trunk/numpy/lib/shape_base.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/lib/shape_base.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -32,7 +32,7 @@ if isscalar(res): outarr = zeros(outshape,asarray(res).dtype) outarr[ind] = res - Ntot = product(outshape) + Ntot = product(outshape,axis=0) k = 1 while k < Ntot: # increment the index @@ -48,7 +48,7 @@ k += 1 return outarr else: - Ntot = product(outshape) + Ntot = product(outshape,axis=0) holdshape = outshape outshape = list(arr.shape) outshape[axis] = len(res) @@ -326,12 +326,7 @@ Caveats: Currently, the default for axis is 0. This means a 2D array is divided into multiple groups - of rows. This seems like the appropriate default, but - we've agreed most other functions should default to - axis=-1. Perhaps we should use axis=-1 for consistency. - However, we could also make the argument that NumPy - works on "rows" by default. sum() sums up rows of - values. split() will split data into rows. Opinions? + of rows. This seems like the appropriate default, """ try: Ntotal = ary.shape[axis] @@ -391,12 +386,7 @@ Caveats: Currently, the default for axis is 0. This means a 2D array is divided into multiple groups - of rows. This seems like the appropriate default, but - we've agreed most other functions should default to - axis=-1. Perhaps we should use axis=-1 for consistency. - However, we could also make the argument that NumPy - works on "rows" by default. sum() sums up rows of - values. split() will split data into rows. Opinions? + of rows. This seems like the appropriate default """ try: len(indices_or_sections) except TypeError: Modified: trunk/numpy/lib/tests/test_function_base.py =================================================================== --- trunk/numpy/lib/tests/test_function_base.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/lib/tests/test_function_base.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -42,11 +42,11 @@ class test_average(NumpyTestCase): def check_basic(self): y1 = array([1,2,3]) - assert(average(y1) == 2.) + assert(average(y1,axis=0) == 2.) y2 = array([1.,2.,3.]) - assert(average(y2) == 2.) + assert(average(y2,axis=0) == 2.) y3 = [0.,0.,0.] - assert(average(y3) == 0.) + assert(average(y3,axis=0) == 0.) y4 = ones((4,4)) y4[0,1] = 0 @@ -117,7 +117,7 @@ class test_ptp(NumpyTestCase): def check_basic(self): a = [3,4,5,10,-3,-5,6.0] - assert_equal(ptp(a),15.0) + assert_equal(ptp(a,axis=0),15.0) b = [[3,6.0, 9.0], [4,10.0,5.0], [8,3.0,2.0]] @@ -132,7 +132,7 @@ float32,float64,complex64,complex128]: a = array(ba,ctype) a2 = array(ba2,ctype) - assert_array_equal(cumsum(a), array([1,3,13,24,30,35,39],ctype)) + assert_array_equal(cumsum(a,axis=0), array([1,3,13,24,30,35,39],ctype)) assert_array_equal(cumsum(a2,axis=0), array([[1,2,3,4],[6,8,10,13], [16,11,14,18]],ctype)) assert_array_equal(cumsum(a2,axis=1), @@ -153,7 +153,7 @@ self.failUnlessRaises(ArithmeticError, prod, a2, 1) self.failUnlessRaises(ArithmeticError, prod, a) else: - assert_equal(prod(a),26400) + assert_equal(prod(a,axis=0),26400) assert_array_equal(prod(a2,axis=0), array([50,36,84,180],ctype)) assert_array_equal(prod(a2,axis=-1),array([24, 1890, 600],ctype)) @@ -305,35 +305,35 @@ w=hanning(10) assert_array_almost_equal(w,flipud(w),7) #check known value - assert_almost_equal(sum(w),4.500,4) + assert_almost_equal(sum(w,axis=0),4.500,4) def check_hamming(self): #check symmetry w=hamming(10) assert_array_almost_equal(w,flipud(w),7) #check known value - assert_almost_equal(sum(w),4.9400,4) + assert_almost_equal(sum(w,axis=0),4.9400,4) def check_bartlett(self): #check symmetry w=bartlett(10) assert_array_almost_equal(w,flipud(w),7) #check known value - assert_almost_equal(sum(w),4.4444,4) + assert_almost_equal(sum(w,axis=0),4.4444,4) def check_blackman(self): #check symmetry w=blackman(10) assert_array_almost_equal(w,flipud(w),7) #check known value - assert_almost_equal(sum(w),3.7800,4) + assert_almost_equal(sum(w,axis=0),3.7800,4) class test_trapz(NumpyTestCase): def check_simple(self): r=trapz(exp(-1.0/2*(arange(-10,10,.1))**2)/sqrt(2*pi),dx=0.1) #check integral of normal equals 1 - assert_almost_equal(sum(r),1,7) + assert_almost_equal(sum(r,axis=0),1,7) class test_sinc(NumpyTestCase): def check_simple(self): @@ -348,7 +348,7 @@ v=rand(n) (a,b)=histogram(v) #check if the sum of the bins equals the number of samples - assert(sum(a)==n) + assert(sum(a,axis=0)==n) #check that the bin counts are evenly spaced when the data is from a linear function (a,b)=histogram(linspace(0,10,100)) assert(all(a==10)) Modified: trunk/numpy/lib/tests/test_type_check.py =================================================================== --- trunk/numpy/lib/tests/test_type_check.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/lib/tests/test_type_check.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -91,7 +91,7 @@ def check_fail(self): z = array([-1,0,1]) res = iscomplex(z) - assert(not sometrue(res)) + assert(not sometrue(res,axis=0)) def check_pass(self): z = array([-1j,1,0]) res = iscomplex(z) @@ -125,7 +125,7 @@ def check_goodvalues(self): z = array((-1.,0.,1.)) res = isnan(z) == 0 - assert_all(alltrue(res)) + assert_all(alltrue(res,axis=0)) def check_posinf(self): assert_all(isnan(array((1.,))/0.) == 0) def check_neginf(self): @@ -145,7 +145,7 @@ def check_goodvalues(self): z = array((-1.,0.,1.)) res = isfinite(z) == 1 - assert_all(alltrue(res)) + assert_all(alltrue(res,axis=0)) def check_posinf(self): assert_all(isfinite(array((1.,))/0.) == 0) def check_neginf(self): @@ -165,7 +165,7 @@ def check_goodvalues(self): z = array((-1.,0.,1.)) res = isinf(z) == 0 - assert_all(alltrue(res)) + assert_all(alltrue(res,axis=0)) def check_posinf(self): assert_all(isinf(array((1.,))/0.) == 1) def check_posinf_scalar(self): Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/lib/utils.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -126,7 +126,7 @@ namestr = name original=1 shapestr = " x ".join(map(str, var.shape)) - bytestr = str(var.itemsize*product(var.shape)) + bytestr = str(var.itemsize*product(var.shape,axis=0)) sta.append([namestr, shapestr, bytestr, var.dtype.name, original]) Modified: trunk/numpy/linalg/linalg.py =================================================================== --- trunk/numpy/linalg/linalg.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/linalg/linalg.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -661,11 +661,11 @@ if one_eq: x = array(ravel(bstar)[:n], dtype=result_t, copy=True) if results['rank']==n and m>n: - resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t) + resids = array([sum((ravel(bstar)[n:])**2,axis=0)], dtype=result_t) else: x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True) if results['rank']==n and m>n: - resids = sum((transpose(bstar)[n:,:])**2).astype(result_t) + resids = sum((transpose(bstar)[n:,:])**2,axis=0).astype(result_t) st = s[:min(n,m)].copy().astype(_realType(result_t)) return wrap(x), resids, results['rank'], st @@ -687,7 +687,7 @@ For vectors ord can be any real number including Inf or -Inf. ord = Inf, computes the maximum of the magnitudes ord = -Inf, computes minimum of the magnitudes - ord is finite, computes sum(abs(x)**ord)**(1.0/ord) + ord is finite, computes sum(abs(x)**ord,axis=0)**(1.0/ord) For matrices ord can only be one of the following values: ord = 2 computes the largest singular value @@ -696,7 +696,7 @@ ord = -1 computes the smallest column sum of absolute values ord = Inf computes the largest row sum of absolute values ord = -Inf computes the smallest row sum of absolute values - ord = 'fro' computes the frobenius norm sqrt(sum(diag(X.H * X))) + ord = 'fro' computes the frobenius norm sqrt(sum(diag(X.H * X),axis=0)) For values ord < 0, the result is, strictly speaking, not a mathematical 'norm', but it may still be useful for numerical purposes. Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/numarray/functions.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -206,7 +206,7 @@ ##file whose size may be determined before allocation, should be ##quick -- only one allocation will be needed. - recsize = dtype.itemsize * N.product([i for i in shape if i != -1]) + recsize = dtype.itemsize * N.product([i for i in shape if i != -1],axis=0) blocksize = max(_BLOCKSIZE/recsize, 1)*recsize ##try to estimate file size @@ -268,7 +268,7 @@ if shape is None: count = -1 else: - count = N.product(shape)*dtype.itemsize + count = N.product(shape,axis=0)*dtype.itemsize res = N.fromstring(datastring, count=count) if shape is not None: res.shape = shape Modified: trunk/numpy/oldnumeric/random_array.py =================================================================== --- trunk/numpy/oldnumeric/random_array.py 2006-08-29 09:37:47 UTC (rev 3093) +++ trunk/numpy/oldnumeric/random_array.py 2006-08-29 10:28:11 UTC (rev 3094) @@ -166,7 +166,7 @@ trials is the number of trials in each multinomial distribution. probs is a one dimensional array. There are len(prob)+1 events. prob[i] is the probability of the i-th event, 0<=i Author: charris Date: 2006-08-29 12:20:29 -0500 (Tue, 29 Aug 2006) New Revision: 3096 Modified: trunk/numpy/add_newdocs.py trunk/numpy/core/src/arraymethods.c Log: Finish moving comments from arraymethods to add_newdocs. Replace hardcoded 1 by METH_VARARGS in arraymethods. Modified: trunk/numpy/add_newdocs.py =================================================================== --- trunk/numpy/add_newdocs.py 2006-08-29 17:15:31 UTC (rev 3095) +++ trunk/numpy/add_newdocs.py 2006-08-29 17:20:29 UTC (rev 3096) @@ -448,6 +448,22 @@ ############################################################################## +add_newdoc('numpy.core.multiarray', 'ndarray', ('__array__', +""" a.__array__(|dtype) -> reference if type unchanged, copy otherwise. + +Returns either a new reference to self if dtype is not given or a new array +of provided data type if dtype is different from the current dtype of the +array. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_wrap__', +"""a.__array_wrap__(obj) -> Object of same type as a from ndarray obj. + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__', """a.__copy__(|order) -> copy, possibly with different order. @@ -471,6 +487,29 @@ """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('__reduce__', +"""a.__reduce__() + +For pickling. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__', +"""a.__setstate__(version, shape, typecode, isfortran, rawdata) + +For unpickling. + +Arguments: + version -- optional pickle version. If omitted defaults to 0. + shape -- a tuple giving the shape + typecode -- a typecode + isFortran -- a bool stating if Fortran or no + rawdata -- a binary string with the data (or a list if Object array) + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('all', """ a.all(axis=None) @@ -569,16 +608,19 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('compress', """a.compress(condition=, axis=None, out=None) + """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('conj', """a.conj() + """)) add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate', """a.conjugate() + """)) @@ -611,9 +653,25 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal', """a.diagonal(offset=0, axis1=0, axis2=1) + """)) +add_newdoc('numpy.core.multiarray', 'ndarray', ('dump', +"""a.dump(file) Dump to specified file. + +Arguments: + file -- string naming the dump file. + +""")) + + +add_newdoc('numpy.core.multiarray', 'ndarray', ('dumps', +"""a.dumps() -> string containing the dump? + +""")) + + add_newdoc('numpy.core.multiarray', 'ndarray', ('fill', """a.fill(value) -> None. Fill the array with the scalar value. """)) Modified: trunk/numpy/core/src/arraymethods.c =================================================================== --- trunk/numpy/core/src/arraymethods.c 2006-08-29 17:15:31 UTC (rev 3095) +++ trunk/numpy/core/src/arraymethods.c 2006-08-29 17:20:29 UTC (rev 3096) @@ -481,8 +481,6 @@ /* default sub-type implementation */ -static char doc_wraparray[] = "m.__array_wrap__(obj) returns an object of "\ - "type m from the ndarray object obj"; static PyObject * array_wraparray(PyArrayObject *self, PyObject *args) @@ -516,8 +514,6 @@ } -static char doc_array_getarray[] = "m.__array__(|dtype) just returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array."; - static PyObject * array_getarray(PyArrayObject *self, PyObject *args) { @@ -811,7 +807,6 @@ return 0; } -static char doc_reduce[] = "a.__reduce__() for pickling."; static PyObject * array_reduce(PyArrayObject *self, PyObject *args) @@ -886,14 +881,7 @@ return ret; } -static char doc_setstate[] = "a.__setstate__(tuple) for unpickling."; -/* - 1) a Tuple giving the shape - 2) a PyArray_Descr Object - 3) a Bool stating if Fortran or not - 4) a binary string with the data (or a list if Object array) -*/ static size_t _array_fill_strides(intp *, intp *, int, size_t, int, int *); @@ -1108,8 +1096,6 @@ } -static char doc_dump[] = "m.dump(file)"; - static PyObject * array_dump(PyArrayObject *self, PyObject *args) { @@ -1124,7 +1110,6 @@ return Py_None; } -static char doc_dumps[] = "m.dumps()"; static PyObject * array_dumps(PyArrayObject *self, PyObject *args) @@ -1539,50 +1524,30 @@ } static PyMethodDef array_methods[] = { - {"astype", (PyCFunction)array_cast, - 1, NULL}, - {"byteswap", (PyCFunction)array_byteswap, - 1, NULL}, - {"copy", (PyCFunction)array_copy, - 1, NULL}, - {"getfield", (PyCFunction)array_getfield, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"item", (PyCFunction)array_toscalar, - METH_VARARGS, NULL}, - {"tofile", (PyCFunction)array_tofile, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"tolist", (PyCFunction)array_tolist, - 1, NULL}, - {"tostring", (PyCFunction)array_tostring, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"resize", (PyCFunction)array_resize, - METH_VARARGS | METH_KEYWORDS, NULL}, - {"setfield", (PyCFunction)array_setfield, - METH_VARARGS | METH_KEYWORDS, NULL}, /* for subtypes */ {"__array__", (PyCFunction)array_getarray, - 1, doc_array_getarray}, + METH_VARARGS, NULL}, {"__array_wrap__", (PyCFunction)array_wraparray, - 1, doc_wraparray}, + METH_VARARGS, NULL}, /* for the copy module */ {"__copy__", (PyCFunction)array_copy, - 1, NULL}, + METH_VARARGS, NULL}, {"__deepcopy__", (PyCFunction)array_deepcopy, - 1, NULL}, + METH_VARARGS, NULL}, /* for Pickling */ {"__reduce__", (PyCFunction) array_reduce, - 1, doc_reduce}, + METH_VARARGS, NULL}, {"__setstate__", (PyCFunction) array_setstate, - 1, doc_setstate}, + METH_VARARGS, NULL}, {"dumps", (PyCFunction) array_dumps, - 1, doc_dumps}, + METH_VARARGS, NULL}, {"dump", (PyCFunction) array_dump, - 1, doc_dump}, + METH_VARARGS, NULL}, - /* Extended methods added 2005 */ + /* Original and Extended methods added 2005 */ {"all", (PyCFunction)array_all, METH_VARARGS|METH_KEYWORDS, NULL}, {"any", (PyCFunction)array_any, @@ -1593,6 +1558,10 @@ 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, @@ -1603,6 +1572,8 @@ 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, @@ -1613,6 +1584,10 @@ 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}, {"max", (PyCFunction)array_max, METH_VARARGS|METH_KEYWORDS, NULL}, {"mean", (PyCFunction)array_mean, @@ -1637,10 +1612,14 @@ 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, NULL}, + {"setfield", (PyCFunction)array_setfield, + METH_VARARGS | METH_KEYWORDS, NULL}, {"setflags", (PyCFunction)array_setflags, METH_VARARGS|METH_KEYWORDS, NULL}, {"sort", (PyCFunction)array_sort, @@ -1655,6 +1634,12 @@ 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, From numpy-svn at scipy.org Tue Aug 29 13:56:34 2006 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 29 Aug 2006 12:56:34 -0500 (CDT) Subject: [Numpy-svn] r3097 - in trunk/numpy: core f2py/tests/array_from_pyobj/tests fft lib linalg numarray oldnumeric Message-ID: <20060829175634.BBA2D39C08B@new.scipy.org> Author: oliphant Date: 2006-08-29 12:56:21 -0500 (Tue, 29 Aug 2006) New Revision: 3097 Modified: trunk/numpy/core/ma.py trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py trunk/numpy/fft/fftpack.py trunk/numpy/lib/arraysetops.py trunk/numpy/lib/function_base.py trunk/numpy/lib/shape_base.py trunk/numpy/lib/utils.py trunk/numpy/linalg/linalg.py trunk/numpy/numarray/functions.py trunk/numpy/oldnumeric/random_array.py Log: Clean-up some un-needed default axes. Fix default axes of ma.sum and ma.product Modified: trunk/numpy/core/ma.py =================================================================== --- trunk/numpy/core/ma.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/core/ma.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -1604,9 +1604,18 @@ """ return array(a, mask=mask, copy=0, fill_value=fill_value) -sum = add.reduce -product = multiply.reduce +def sum (target, axis=None, dtype=None): + if axis is None: + target = ravel(target) + axis = 0 + return add.reduce(target, axis, dtype) +def product (target, axis=None, dtype=None): + if axis is None: + target = ravel(target) + axis = 0 + return multiply.reduce(target, axis, dtype) + def average (a, axis=None, weights=None, returned = 0): """average(a, axis=None, weights=None) Computes average along indicated axis. Modified: trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py =================================================================== --- trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/f2py/tests/array_from_pyobj/tests/test_array_from_pyobj.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -222,7 +222,7 @@ if arr1.shape != arr2.shape: return False s = arr1==arr2 - return alltrue(s.flatten(),axis=0) + return alltrue(s.flatten()) def __str__(self): return str(self.arr) Modified: trunk/numpy/fft/fftpack.py =================================================================== --- trunk/numpy/fft/fftpack.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/fft/fftpack.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -200,7 +200,7 @@ if axes == None: s = list(a.shape) else: - s = take(a.shape, axes,axis=0) + s = take(a.shape, axes) else: shapeless = 0 s = list(s) Modified: trunk/numpy/lib/arraysetops.py =================================================================== --- trunk/numpy/lib/arraysetops.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/lib/arraysetops.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -179,7 +179,7 @@ dt1s.append( dt1 ) dt2s.append( dt2 ) - assert numpy.alltrue( b == c) + assert numpy.alltrue( b == c ) print nItems Modified: trunk/numpy/lib/function_base.py =================================================================== --- trunk/numpy/lib/function_base.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/lib/function_base.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -540,9 +540,9 @@ """Return the elements of ravel(arr) where ravel(condition) is True (in 1D). - Equivalent to compress(ravel(condition), ravel(arr),0). + Equivalent to compress(ravel(condition), ravel(arr)). """ - return _nx.take(ravel(arr), nonzero(ravel(condition))[0],axis=0) + return _nx.take(ravel(arr), nonzero(ravel(condition))[0]) def place(arr, mask, vals): """Similar to putmask arr[mask] = vals but the 1D array vals has the Modified: trunk/numpy/lib/shape_base.py =================================================================== --- trunk/numpy/lib/shape_base.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/lib/shape_base.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -32,7 +32,7 @@ if isscalar(res): outarr = zeros(outshape,asarray(res).dtype) outarr[ind] = res - Ntot = product(outshape,axis=0) + Ntot = product(outshape) k = 1 while k < Ntot: # increment the index @@ -48,7 +48,7 @@ k += 1 return outarr else: - Ntot = product(outshape,axis=0) + Ntot = product(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = len(res) Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/lib/utils.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -126,7 +126,7 @@ namestr = name original=1 shapestr = " x ".join(map(str, var.shape)) - bytestr = str(var.itemsize*product(var.shape,axis=0)) + bytestr = str(var.itemsize*product(var.shape)) sta.append([namestr, shapestr, bytestr, var.dtype.name, original]) Modified: trunk/numpy/linalg/linalg.py =================================================================== --- trunk/numpy/linalg/linalg.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/linalg/linalg.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -661,7 +661,7 @@ if one_eq: x = array(ravel(bstar)[:n], dtype=result_t, copy=True) if results['rank']==n and m>n: - resids = array([sum((ravel(bstar)[n:])**2,axis=0)], dtype=result_t) + resids = array([sum((ravel(bstar)[n:])**2)], dtype=result_t) else: x = array(transpose(bstar)[:n,:], dtype=result_t, copy=True) if results['rank']==n and m>n: Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/numarray/functions.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -206,7 +206,7 @@ ##file whose size may be determined before allocation, should be ##quick -- only one allocation will be needed. - recsize = dtype.itemsize * N.product([i for i in shape if i != -1],axis=0) + recsize = dtype.itemsize * N.product([i for i in shape if i != -1]) blocksize = max(_BLOCKSIZE/recsize, 1)*recsize ##try to estimate file size @@ -268,7 +268,7 @@ if shape is None: count = -1 else: - count = N.product(shape,axis=0)*dtype.itemsize + count = N.product(shape)*dtype.itemsize res = N.fromstring(datastring, count=count) if shape is not None: res.shape = shape Modified: trunk/numpy/oldnumeric/random_array.py =================================================================== --- trunk/numpy/oldnumeric/random_array.py 2006-08-29 17:20:29 UTC (rev 3096) +++ trunk/numpy/oldnumeric/random_array.py 2006-08-29 17:56:21 UTC (rev 3097) @@ -166,7 +166,7 @@ trials is the number of trials in each multinomial distribution. probs is a one dimensional array. There are len(prob)+1 events. prob[i] is the probability of the i-th event, 0<=i Author: oliphant Date: 2006-08-29 13:29:53 -0500 (Tue, 29 Aug 2006) New Revision: 3098 Added: trunk/numpy/oldnumeric/fix_default_axis.py Log: Add a module/script to fix the default axis issue for code already converted to NumPy Added: trunk/numpy/oldnumeric/fix_default_axis.py =================================================================== --- trunk/numpy/oldnumeric/fix_default_axis.py 2006-08-29 17:56:21 UTC (rev 3097) +++ trunk/numpy/oldnumeric/fix_default_axis.py 2006-08-29 18:29:53 UTC (rev 3098) @@ -0,0 +1,292 @@ +""" +This module adds the default axis argument to code which did not specify it +for the functions where the default was changed in NumPy. + +The functions changed are + +add -1 ( all second argument) +====== +nansum +nanmax +nanmin +nanargmax +nanargmin +argmax +argmin +compress 3 + + +add 0 +====== +take 3 +repeat 3 +sum # might cause problems with builtin. +product +sometrue +alltrue +cumsum +cumproduct +average +ptp +cumprod +prod +std +mean +""" +__all__ = ['convertfile', 'convertall', 'converttree', + 'convertfile2','convertall2', 'converttree2'] + +import sys +import os +import re +import glob + + +_args3 = ['compress', 'take', 'repeat'] +_funcm1 = ['nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', + 'argmax', 'argmin', 'compress'] +_func0 = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', + 'cumsum', 'cumproduct', 'average', 'ptp', 'cumprod', 'prod', + 'std', 'mean'] + +_all = _func0 + _funcm1 +func_re = {} + +for name in _all: + _astr = r"""%s\s*[(]"""%name + func_re[name] = re.compile(_astr) + + +import string +disallowed = '_' + string.uppercase + string.lowercase + string.digits + +def _add_axis(fstr, name, repl): + alter = 0 + if name in _args3: + allowed_comma = 1 + else: + allowed_comma = 0 + newcode = "" + last = 0 + for obj in func_re[name].finditer(fstr): + nochange = 0 + start, end = obj.span() + if fstr[start-1] in disallowed: + continue + if fstr[start-1] == '.' \ + and fstr[start-6:start-1] != 'numpy' \ + and fstr[start-2:start-1] != 'N' \ + and fstr[start-9:start-1] != 'numarray' \ + and fstr[start-8:start-1] != 'numerix' \ + and fstr[start-8:start-1] != 'Numeric': + continue + if fstr[start-1] in ['\t',' ']: + k = start-2 + while fstr[k] in ['\t',' ']: + k -= 1 + if fstr[k-2:k+1] == 'def' or \ + fstr[k-4:k+1] == 'class': + continue + k = end + stack = 1 + ncommas = 0 + N = len(fstr) + while stack: + if k>=N: + nochange =1 + break + if fstr[k] == ')': + stack -= 1 + elif fstr[k] == '(': + stack += 1 + elif stack == 1 and fstr[k] == ',': + ncommas += 1 + if ncommas > allowed_comma: + nochange = 1 + break + k += 1 + if nochange: + continue + alter += 1 + newcode = "%s%s,%s)" % (newcode, fstr[last:k-1], repl) + last = k + if not alter: + newcode = fstr + else: + newcode = "%s%s" % (newcode, fstr[last:]) + return newcode, alter + +def _import_change(fstr, names): + # Four possibilities + # 1.) import numpy with subsequent use of numpy. + # change this to import numpy.oldnumeric as numpy + # 2.) import numpy as XXXX with subsequent use of + # XXXX. ==> import numpy.oldnumeric as XXXX + # 3.) from numpy import * + # with subsequent use of one of the names + # 4.) from numpy import ..., , ... (could span multiple + # lines. ==> remove all names from list and + # add from numpy.oldnumeric import + + num = 0 + # case 1 + importstr = "import numpy" + ind = fstr.find(importstr) + if (ind > 0): + found = 0 + for name in names: + ind2 = fstr.find("numpy.%s" % name, ind) + if (ind2 > 0): + found = 1 + break + if found: + fstr = "%s%s%s" % (fstr[:ind], "import numpy.oldnumeric as numpy", + fstr[ind+len(importstr):]) + num += 1 + + # case 2 + importre = re.compile("""import numpy as ([A-Za-z0-9_]+)""") + modules = importre.findall(fstr) + if len(modules) > 0: + for module in modules: + found = 0 + for name in names: + ind2 = fstr.find("%s.%s" % (module, name)) + if (ind2 > 0): + found = 1 + break + if found: + importstr = "import numpy as %s" % module + ind = fstr.find(importstr) + fstr = "%s%s%s" % (fstr[:ind], + "import numpy.oldnumeric as %s" % module, + fstr[ind+len(importstr):]) + num += 1 + + # case 3 + importstr = "from numpy import *" + ind = fstr.find(importstr) + if (ind > 0): + found = 0 + for name in names: + ind2 = fstr.find(name, ind) + if (ind2 > 0) and fstr[ind2-1] not in disallowed: + found = 1 + break + if found: + fstr = "%s%s%s" % (fstr[:ind], + "from numpy.oldnumeric import *", + fstr[ind+len(importstr):]) + num += 1 + + # case 4 + ind = 0 + importstr = "from numpy import" + N = len(importstr) + while 1: + ind = fstr.find(importstr, ind) + if (ind < 0): + break + ind += N + ptr = ind+1 + stack = 1 + while stack: + if fstr[ptr] == '\\': + stack += 1 + elif fstr[ptr] == '\n': + stack -= 1 + ptr += 1 + substr = fstr[ind:ptr] + found = 0 + substr = substr.replace('\n',' ') + substr = substr.replace('\\','') + importnames = [x.strip() for x in substr.split(',')] + # determine if any of names are in importnames + addnames = [] + for name in names: + if name in importnames: + importnames.remove(name) + addnames.append(name) + if len(addnames) > 0: + fstr = "%s%s\n%s\n%s" % \ + (fstr[:ind], + "from numpy import %s" % \ + ", ".join(importnames), + "from numpy.oldnumeric import %s" % \ + ", ".join(addnames), + fstr[ptr:]) + num += 1 + + return fstr, num + +def add_axis(fstr, import_change=False): + total = 0 + if not import_change: + for name in _funcm1: + fstr, num = _add_axis(fstr, name, 'axis=-1') + total += num + for name in _func0: + fstr, num = _add_axis(fstr, name, 'axis=0') + total += num + return fstr, total + else: + fstr, num = _import_change(fstr, _funcm1+_func0) + return fstr, num + + +def makenewfile(name, filestr): + fid = file(name, 'w') + fid.write(filestr) + fid.close() + +def getfile(name): + fid = file(name) + filestr = fid.read() + fid.close() + return filestr + +def copyfile(name, fstr): + base, ext = os.path.splitext(name) + makenewfile(base+'.orig', fstr) + return + +def convertfile(filename, import_change=False): + """Convert the filename given from using Numeric to using NumPy + + Copies the file to filename.orig and then over-writes the file + with the updated code + """ + filestr = getfile(filename) + newstr, total = add_axis(filestr, import_change) + if total > 0: + print "Changing ", filename + copyfile(filename, filestr) + makenewfile(filename, newstr) + sys.stdout.flush() + +def fromargs(args): + filename = args[1] + convertfile(filename) + +def convertall(direc=os.path.curdir, import_change=False): + """Convert all .py files in the directory given + + For each file, a backup of .py is made as + .py.orig. A new file named .py + is then written with the updated code. + """ + files = glob.glob(os.path.join(direc,'*.py')) + for afile in files: + convertfile(afile, import_change) + +def _func(arg, dirname, fnames): + convertall(dirname, import_change=arg) + +def converttree(direc=os.path.curdir, import_change=False): + """Convert all .py files in the tree given + + """ + os.path.walk(direc, _func, import_change) + +if __name__ == '__main__': + fromargs(sys.argv)