summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
Diffstat (limited to 'numpy')
-rw-r--r--numpy/numarray/__init__.py38
-rw-r--r--numpy/numarray/_capi.c3441
-rw-r--r--numpy/numarray/alter_code1.py267
-rw-r--r--numpy/numarray/alter_code2.py68
-rw-r--r--numpy/numarray/compat.py5
-rw-r--r--numpy/numarray/convolve.py16
-rw-r--r--numpy/numarray/fft.py8
-rw-r--r--numpy/numarray/functions.py500
-rw-r--r--numpy/numarray/image.py16
-rw-r--r--numpy/numarray/include/numpy/arraybase.h71
-rw-r--r--numpy/numarray/include/numpy/cfunc.h77
-rw-r--r--numpy/numarray/include/numpy/ieeespecial.h123
-rw-r--r--numpy/numarray/include/numpy/libnumarray.h630
-rw-r--r--numpy/numarray/include/numpy/numcomplex.h252
-rw-r--r--numpy/numarray/include/numpy/nummacro.h447
-rw-r--r--numpy/numarray/linear_algebra.py16
-rw-r--r--numpy/numarray/ma.py3
-rw-r--r--numpy/numarray/matrix.py8
-rw-r--r--numpy/numarray/mlab.py8
-rw-r--r--numpy/numarray/nd_image.py16
-rw-r--r--numpy/numarray/numerictypes.py552
-rw-r--r--numpy/numarray/random_array.py10
-rw-r--r--numpy/numarray/session.py347
-rw-r--r--numpy/numarray/setup.py19
-rw-r--r--numpy/numarray/ufuncs.py23
-rw-r--r--numpy/numarray/util.py49
-rw-r--r--numpy/oldnumeric/__init__.py55
-rw-r--r--numpy/oldnumeric/alter_code1.py243
-rw-r--r--numpy/oldnumeric/alter_code2.py148
-rw-r--r--numpy/oldnumeric/array_printer.py17
-rw-r--r--numpy/oldnumeric/arrayfns.py99
-rw-r--r--numpy/oldnumeric/compat.py121
-rw-r--r--numpy/oldnumeric/fft.py22
-rw-r--r--numpy/oldnumeric/fix_default_axis.py294
-rw-r--r--numpy/oldnumeric/functions.py127
-rw-r--r--numpy/oldnumeric/linear_algebra.py85
-rw-r--r--numpy/oldnumeric/ma.py2296
-rw-r--r--numpy/oldnumeric/matrix.py70
-rw-r--r--numpy/oldnumeric/misc.py37
-rw-r--r--numpy/oldnumeric/mlab.py128
-rw-r--r--numpy/oldnumeric/precision.py174
-rw-r--r--numpy/oldnumeric/random_array.py269
-rw-r--r--numpy/oldnumeric/rng.py137
-rw-r--r--numpy/oldnumeric/rng_stats.py36
-rw-r--r--numpy/oldnumeric/setup.py11
-rw-r--r--numpy/oldnumeric/tests/test_oldnumeric.py96
-rw-r--r--numpy/oldnumeric/tests/test_regression.py11
-rw-r--r--numpy/oldnumeric/typeconv.py62
-rw-r--r--numpy/oldnumeric/ufuncs.py21
-rw-r--r--numpy/oldnumeric/user_array.py9
50 files changed, 0 insertions, 11578 deletions
diff --git a/numpy/numarray/__init__.py b/numpy/numarray/__init__.py
deleted file mode 100644
index 468324ced..000000000
--- a/numpy/numarray/__init__.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-import warnings
-from numpy import ModuleDeprecationWarning
-
-from .util import *
-from .numerictypes import *
-from .functions import *
-from .ufuncs import *
-from .compat import *
-from .session import *
-
-from . import util
-from . import numerictypes
-from . import functions
-from . import ufuncs
-from . import compat
-from . import session
-
-_msg = "The numarray module will be dropped in Numpy 1.9"
-warnings.warn(_msg, ModuleDeprecationWarning)
-
-__all__ = ['session', 'numerictypes']
-__all__ += util.__all__
-__all__ += numerictypes.__all__
-__all__ += functions.__all__
-__all__ += ufuncs.__all__
-__all__ += compat.__all__
-__all__ += session.__all__
-
-del util
-del functions
-del ufuncs
-del compat
-
-from numpy.testing import Tester
-test = Tester().test
-bench = Tester().bench
diff --git a/numpy/numarray/_capi.c b/numpy/numarray/_capi.c
deleted file mode 100644
index 91e3b4984..000000000
--- a/numpy/numarray/_capi.c
+++ /dev/null
@@ -1,3441 +0,0 @@
-#include <Python.h>
-
-#define NPY_NO_DEPRECATED_API NPY_API_VERSION
-#define _libnumarray_MODULE
-#include "include/numpy/libnumarray.h"
-#include "numpy/npy_3kcompat.h"
-#include <float.h>
-
-#if (defined(__unix__) || defined(unix)) && !defined(USG)
-#include <sys/param.h>
-#endif
-
-#if defined(__GLIBC__) || defined(__APPLE__) || defined(__MINGW32__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 502114))
-#include <fenv.h>
-#elif defined(__CYGWIN__)
-#include "numpy/fenv/fenv.h"
-#include "numpy/fenv/fenv.c"
-#endif
-
-static PyObject *pCfuncClass;
-static PyTypeObject CfuncType;
-static PyObject *pHandleErrorFunc;
-
-static int
-deferred_libnumarray_init(void)
-{
-static int initialized=0;
-
- if (initialized) return 0;
-
- pCfuncClass = (PyObject *) &CfuncType;
- Py_INCREF(pCfuncClass);
-
- pHandleErrorFunc =
- NA_initModuleGlobal("numpy.numarray.util", "handleError");
-
- if (!pHandleErrorFunc) goto _fail;
-
-
- /* _exit: */
- initialized = 1;
- return 0;
-
-_fail:
- initialized = 0;
- return -1;
-}
-
-
-
-/**********************************************************************/
-/* Buffer Utility Functions */
-/**********************************************************************/
-
-static PyObject *
-getBuffer( PyObject *obj)
-{
- if (!obj) return PyErr_Format(PyExc_RuntimeError,
- "NULL object passed to getBuffer()");
- if (((PyObject*)obj)->ob_type->tp_as_buffer == NULL) {
- return PyObject_CallMethod(obj, "__buffer__", NULL);
- } else {
- Py_INCREF(obj); /* Since CallMethod returns a new object when it
- succeeds, We'll need to DECREF later to free it.
- INCREF ordinary buffers here so we don't have to
- remember where the buffer came from at DECREF time.
- */
- return obj;
- }
-}
-
-/* Either it defines the buffer API, or it is an instance which returns
- a buffer when obj.__buffer__() is called */
-static int
-isBuffer (PyObject *obj)
-{
- PyObject *buf = getBuffer(obj);
- int ans = 0;
- if (buf) {
- ans = buf->ob_type->tp_as_buffer != NULL;
- Py_DECREF(buf);
- } else {
- PyErr_Clear();
- }
- return ans;
-}
-
-/**********************************************************************/
-
-static int
-getWriteBufferDataPtr(PyObject *buffobj, void **buff)
-{
-#if defined(NPY_PY3K)
- /* FIXME: XXX - needs implementation */
- PyErr_SetString(PyExc_RuntimeError,
- "XXX: getWriteBufferDataPtr is not implemented");
- return -1;
-#else
- int rval = -1;
- PyObject *buff2;
- if ((buff2 = getBuffer(buffobj)))
- {
- if (buff2->ob_type->tp_as_buffer->bf_getwritebuffer)
- rval = buff2->ob_type->tp_as_buffer->bf_getwritebuffer(buff2,
- 0, buff);
- Py_DECREF(buff2);
- }
- return rval;
-#endif
-}
-
-/**********************************************************************/
-
-static int
-isBufferWriteable (PyObject *buffobj)
-{
- void *ptr;
- int rval = -1;
- rval = getWriteBufferDataPtr(buffobj, &ptr);
- if (rval == -1)
- PyErr_Clear(); /* Since we're just "testing", it's not really an error */
- return rval != -1;
-}
-
-/**********************************************************************/
-
-static int
-getReadBufferDataPtr(PyObject *buffobj, void **buff)
-{
-#if defined(NPY_PY3K)
- /* FIXME: XXX - needs implementation */
- PyErr_SetString(PyExc_RuntimeError,
- "XXX: getWriteBufferDataPtr is not implemented");
- return -1;
-#else
- int rval = -1;
- PyObject *buff2;
- if ((buff2 = getBuffer(buffobj))) {
- if (buff2->ob_type->tp_as_buffer->bf_getreadbuffer)
- rval = buff2->ob_type->tp_as_buffer->bf_getreadbuffer(buff2,
- 0, buff);
- Py_DECREF(buff2);
- }
- return rval;
-#endif
-}
-
-/**********************************************************************/
-
-static int
-getBufferSize(PyObject *buffobj)
-{
-#if defined(NPY_PY3K)
- /* FIXME: XXX - needs implementation */
- PyErr_SetString(PyExc_RuntimeError,
- "XXX: getWriteBufferDataPtr is not implemented");
- return -1;
-#else
- Py_ssize_t size=0;
- PyObject *buff2;
- if ((buff2 = getBuffer(buffobj)))
- {
- (void) buff2->ob_type->tp_as_buffer->bf_getsegcount(buff2, &size);
- Py_DECREF(buff2);
- }
- else
- size = -1;
- return size;
-#endif
-}
-
-
-static double numarray_zero = 0.0;
-
-static double raiseDivByZero(void)
-{
- return 1.0/numarray_zero;
-}
-
-static double raiseNegDivByZero(void)
-{
- return -1.0/numarray_zero;
-}
-
-static double num_log(double x)
-{
- if (x == 0.0)
- return raiseNegDivByZero();
- else
- return log(x);
-}
-
-static double num_log10(double x)
-{
- if (x == 0.0)
- return raiseNegDivByZero();
- else
- return log10(x);
-}
-
-static double num_pow(double x, double y)
-{
- int z = (int) y;
- if ((x < 0.0) && (y != z))
- return raiseDivByZero();
- else
- return pow(x, y);
-}
-
-/* Inverse hyperbolic trig functions from Numeric */
-static double num_acosh(double x)
-{
- return log(x + sqrt((x-1.0)*(x+1.0)));
-}
-
-static double num_asinh(double xx)
-{
- double x;
- int sign;
- if (xx < 0.0) {
- sign = -1;
- x = -xx;
- }
- else {
- sign = 1;
- x = xx;
- }
- return sign*log(x + sqrt(x*x+1.0));
-}
-
-static double num_atanh(double x)
-{
- return 0.5*log((1.0+x)/(1.0-x));
-}
-
-/* NUM_CROUND (in numcomplex.h) also calls num_round */
-static double num_round(double x)
-{
- return (x >= 0) ? floor(x+0.5) : ceil(x-0.5);
-}
-
-
-/* The following routine is used in the event of a detected integer *
- ** divide by zero so that a floating divide by zero is generated. *
- ** This is done since numarray uses the floating point exception *
- ** sticky bits to detect errors. The last bit is an attempt to *
- ** prevent optimization of the divide by zero away, the input value *
- ** should always be 0 *
- */
-
-static int int_dividebyzero_error(long NPY_UNUSED(value), long NPY_UNUSED(unused)) {
- double dummy;
- dummy = 1./numarray_zero;
- if (dummy) /* to prevent optimizer from eliminating expression */
- return 0;
- else
- return 1;
-}
-
-/* Likewise for Integer overflows */
-#if defined(__GLIBC__) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__MINGW32__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 502114))
-static int int_overflow_error(Float64 value) { /* For x86_64 */
- feraiseexcept(FE_OVERFLOW);
- return (int) value;
-}
-#else
-static int int_overflow_error(Float64 value) {
- double dummy;
- dummy = pow(1.e10, fabs(value/2));
- if (dummy) /* to prevent optimizer from eliminating expression */
- return (int) value;
- else
- return 1;
-}
-#endif
-
-static int umult64_overflow(UInt64 a, UInt64 b)
-{
- UInt64 ah, al, bh, bl, w, x, y, z;
-
- ah = (a >> 32);
- al = (a & 0xFFFFFFFFL);
- bh = (b >> 32);
- bl = (b & 0xFFFFFFFFL);
-
- /* 128-bit product: z*2**64 + (x+y)*2**32 + w */
- w = al*bl;
- x = bh*al;
- y = ah*bl;
- z = ah*bh;
-
- /* *c = ((x + y)<<32) + w; */
- return z || (x>>32) || (y>>32) ||
- (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 32);
-}
-
-static int smult64_overflow(Int64 a0, Int64 b0)
-{
- UInt64 a, b;
- UInt64 ah, al, bh, bl, w, x, y, z;
-
- /* Convert to non-negative quantities */
- if (a0 < 0) { a = -a0; } else { a = a0; }
- if (b0 < 0) { b = -b0; } else { b = b0; }
-
- ah = (a >> 32);
- al = (a & 0xFFFFFFFFL);
- bh = (b >> 32);
- bl = (b & 0xFFFFFFFFL);
-
- w = al*bl;
- x = bh*al;
- y = ah*bl;
- z = ah*bh;
-
- /*
- UInt64 c = ((x + y)<<32) + w;
- if ((a0 < 0) ^ (b0 < 0))
- *c = -c;
- else
- *c = c
- */
-
- return z || (x>>31) || (y>>31) ||
- (((x & 0xFFFFFFFFL) + (y & 0xFFFFFFFFL) + (w >> 32)) >> 31);
-}
-
-
-static void
-NA_Done(void)
-{
- return;
-}
-
-static PyArrayObject *
-NA_NewAll(int ndim, maybelong *shape, NumarrayType type,
- void *buffer, maybelong byteoffset, maybelong bytestride,
- int byteorder, int aligned, int writeable)
-{
- PyArrayObject *result = NA_NewAllFromBuffer(
- ndim, shape, type, Py_None, byteoffset, bytestride,
- byteorder, aligned, writeable);
-
- if (result) {
- if (!NA_NumArrayCheck((PyObject *) result)) {
- PyErr_Format( PyExc_TypeError,
- "NA_NewAll: non-NumArray result");
- result = NULL;
- } else {
- if (buffer) {
- memcpy(PyArray_DATA(result), buffer, NA_NBYTES(result));
- } else {
- memset(PyArray_DATA(result), 0, NA_NBYTES(result));
- }
- }
- }
- return result;
-}
-
-static PyArrayObject *
-NA_NewAllStrides(int ndim, maybelong *shape, maybelong *strides,
- NumarrayType type, void *buffer, maybelong byteoffset,
- int byteorder, int aligned, int writeable)
-{
- int i;
- PyArrayObject *result = NA_NewAll(ndim, shape, type, buffer,
- byteoffset, 0,
- byteorder, aligned, writeable);
- for(i=0; i<ndim; i++)
- PyArray_STRIDES(result)[i] = strides[i];
- return result;
-}
-
-
-static PyArrayObject *
-NA_New(void *buffer, NumarrayType type, int ndim, ...)
-{
- int i;
- maybelong shape[MAXDIM];
- va_list ap;
- va_start(ap, ndim);
- for(i=0; i<ndim; i++)
- shape[i] = va_arg(ap, int);
- va_end(ap);
- return NA_NewAll(ndim, shape, type, buffer, 0, 0,
- NA_ByteOrder(), 1, 1);
-}
-
-static PyArrayObject *
-NA_Empty(int ndim, maybelong *shape, NumarrayType type)
-{
- return NA_NewAll(ndim, shape, type, NULL, 0, 0,
- NA_ByteOrder(), 1, 1);
-}
-
-
-/* Create a new numarray which is initially a C_array, or which
- references a C_array: aligned, !byteswapped, contiguous, ...
- Call with buffer==NULL to allocate storage.
- */
-static PyArrayObject *
-NA_vNewArray(void *buffer, NumarrayType type, int ndim, maybelong *shape)
-{
- return (PyArrayObject *) NA_NewAll(ndim, shape, type, buffer, 0, 0,
- NA_ByteOrder(), 1, 1);
-}
-
-static PyArrayObject *
-NA_NewArray(void *buffer, NumarrayType type, int ndim, ...)
-{
- int i;
- maybelong shape[MAXDIM];
- va_list ap;
- va_start(ap, ndim);
- for(i=0; i<ndim; i++)
- shape[i] = va_arg(ap, int); /* literals will still be ints */
- va_end(ap);
- return NA_vNewArray(buffer, type, ndim, shape);
-}
-
-
-static PyObject*
-NA_ReturnOutput(PyObject *out, PyArrayObject *shadow)
-{
- if ((out == Py_None) || (out == NULL)) {
- /* default behavior: return shadow array as the result */
- return (PyObject *) shadow;
- } else {
- PyObject *rval;
- /* specified output behavior: return None */
- /* del(shadow) --> out.copyFrom(shadow) */
- Py_DECREF(shadow);
- Py_INCREF(Py_None);
- rval = Py_None;
- return rval;
- }
-}
-
-static long NA_getBufferPtrAndSize(PyObject *buffobj, int readonly, void **ptr)
-{
- long rval;
- if (readonly)
- rval = getReadBufferDataPtr(buffobj, ptr);
- else
- rval = getWriteBufferDataPtr(buffobj, ptr);
- return rval;
-}
-
-
-static int NA_checkIo(char *name,
- int wantIn, int wantOut, int gotIn, int gotOut)
-{
- if (wantIn != gotIn) {
- PyErr_Format(_Error,
- "%s: wrong # of input buffers. Expected %d. Got %d.",
- name, wantIn, gotIn);
- return -1;
- }
- if (wantOut != gotOut) {
- PyErr_Format(_Error,
- "%s: wrong # of output buffers. Expected %d. Got %d.",
- name, wantOut, gotOut);
- return -1;
- }
- return 0;
-}
-
-static int NA_checkOneCBuffer(char *name, long niter,
- void *buffer, long bsize, size_t typesize)
-{
- Int64 lniter = niter, ltypesize = typesize;
-
- if (lniter*ltypesize > bsize) {
- PyErr_Format(_Error,
- "%s: access out of buffer. niter=%d typesize=%d bsize=%d",
- name, (int) niter, (int) typesize, (int) bsize);
- return -1;
- }
- if ((typesize <= sizeof(Float64)) && (((long) buffer) % typesize)) {
- PyErr_Format(_Error,
- "%s: buffer not aligned on %d byte boundary.",
- name, (int) typesize);
- return -1;
- }
- return 0;
-}
-
-
-static int NA_checkNCBuffers(char *name, int N, long niter,
- void **buffers, long *bsizes,
- Int8 *typesizes, Int8 *iters)
-{
- int i;
- for (i=0; i<N; i++)
- if (NA_checkOneCBuffer(name, iters[i] ? iters[i] : niter,
- buffers[i], bsizes[i], typesizes[i]))
- return -1;
- return 0;
-}
-
-static int NA_checkOneStriding(char *name, long dim, maybelong *shape,
- long offset, maybelong *stride, long buffersize, long itemsize,
- int align)
-{
- int i;
- long omin=offset, omax=offset;
- long alignsize = ((size_t)itemsize <= sizeof(Float64) ? (size_t)itemsize : sizeof(Float64));
-
- if (align && (offset % alignsize)) {
- PyErr_Format(_Error,
- "%s: buffer not aligned on %d byte boundary.",
- name, (int) alignsize);
- return -1;
- }
- for(i=0; i<dim; i++) {
- long strideN = stride[i] * (shape[i]-1);
- long tmax = omax + strideN;
- long tmin = omin + strideN;
- if (shape[i]-1 >= 0) { /* Skip dimension == 0. */
- omax = MAX(omax, tmax);
- omin = MIN(omin, tmin);
- if (align && (ABS(stride[i]) % alignsize)) {
- PyErr_Format(_Error,
- "%s: stride %d not aligned on %d byte boundary.",
- name, (int) stride[i], (int) alignsize);
- return -1;
- }
- if (omax + itemsize > buffersize) {
- PyErr_Format(_Error,
- "%s: access beyond buffer. offset=%d buffersize=%d",
- name, (int) (omax+itemsize-1), (int) buffersize);
- return -1;
- }
- if (omin < 0) {
- PyErr_Format(_Error,
- "%s: access before buffer. offset=%d buffersize=%d",
- name, (int) omin, (int) buffersize);
- return -1;
- }
- }
- }
- return 0;
-}
-
-/* Function to call standard C Ufuncs
- **
- ** The C Ufuncs expect contiguous 1-d data numarray, input and output numarray
- ** iterate with standard increments of one data element over all numarray.
- ** (There are some exceptions like arrayrangexxx which use one or more of
- ** the data numarray as parameter or other sources of information and do not
- ** iterate over every buffer).
- **
- ** Arguments:
- **
- ** Number of iterations (simple integer value).
- ** Number of input numarray.
- ** Number of output numarray.
- ** Tuple of tuples, one tuple per input/output array. Each of these
- ** tuples consists of a buffer object and a byte offset to start.
- **
- ** Returns None
- */
-
-
-static PyObject *
-NA_callCUFuncCore(PyObject *self,
- long niter, long ninargs, long noutargs,
- PyObject **BufferObj, long *offset)
-{
- CfuncObject *me = (CfuncObject *) self;
- char *buffers[MAXARGS];
- long bsizes[MAXARGS];
- long i, pnargs = ninargs + noutargs;
- UFUNC ufuncptr;
-
- if (pnargs > MAXARGS)
- return PyErr_Format(PyExc_RuntimeError, "NA_callCUFuncCore: too many parameters");
-
- if (!PyObject_IsInstance(self, (PyObject *) &CfuncType)
- || me->descr.type != CFUNC_UFUNC)
- return PyErr_Format(PyExc_TypeError,
- "NA_callCUFuncCore: problem with cfunc.");
-
- for (i=0; i<pnargs; i++) {
- int readonly = (i < ninargs);
- if (offset[i] < 0)
- return PyErr_Format(_Error,
- "%s: invalid negative offset:%d for buffer[%d]",
- me->descr.name, (int) offset[i], (int) i);
- if ((bsizes[i] = NA_getBufferPtrAndSize(BufferObj[i], readonly,
- (void *) &buffers[i])) < 0)
- return PyErr_Format(_Error,
- "%s: Problem with %s buffer[%d].",
- me->descr.name,
- readonly ? "read" : "write", (int) i);
- buffers[i] += offset[i];
- bsizes[i] -= offset[i]; /* "shorten" buffer size by offset. */
- }
-
- ufuncptr = (UFUNC) me->descr.fptr;
-
- /* If it's not a self-checking ufunc, check arg count match,
- buffer size, and alignment for all buffers */
- if (!me->descr.chkself &&
- (NA_checkIo(me->descr.name,
- me->descr.wantIn, me->descr.wantOut, ninargs, noutargs) ||
- NA_checkNCBuffers(me->descr.name, pnargs,
- niter, (void **) buffers, bsizes,
- me->descr.sizes, me->descr.iters)))
- return NULL;
-
- /* Since the parameters are valid, call the C Ufunc */
- if (!(*ufuncptr)(niter, ninargs, noutargs, (void **)buffers, bsizes)) {
- Py_INCREF(Py_None);
- return Py_None;
- } else {
- return NULL;
- }
-}
-
-static PyObject *
-callCUFunc(PyObject *self, PyObject *args) {
- PyObject *DataArgs, *ArgTuple;
- long pnargs, ninargs, noutargs, niter, i;
- CfuncObject *me = (CfuncObject *) self;
- PyObject *BufferObj[MAXARGS];
- long offset[MAXARGS];
-
- if (!PyArg_ParseTuple(args, "lllO",
- &niter, &ninargs, &noutargs, &DataArgs))
- return PyErr_Format(_Error,
- "%s: Problem with argument list", me->descr.name);
-
- /* check consistency of stated inputs/outputs and supplied buffers */
- pnargs = PyObject_Length(DataArgs);
- if ((pnargs != (ninargs+noutargs)) || (pnargs > MAXARGS))
- return PyErr_Format(_Error,
- "%s: wrong buffer count for function", me->descr.name);
-
- /* Unpack buffers and offsets, get data pointers */
- for (i=0; i<pnargs; i++) {
- ArgTuple = PySequence_GetItem(DataArgs, i);
- Py_DECREF(ArgTuple);
- if (!PyArg_ParseTuple(ArgTuple, "Ol", &BufferObj[i], &offset[i]))
- return PyErr_Format(_Error,
- "%s: Problem with buffer/offset tuple", me->descr.name);
- }
- return NA_callCUFuncCore(self, niter, ninargs, noutargs, BufferObj, offset);
-}
-
-static PyObject *
-callStrideConvCFunc(PyObject *self, PyObject *args) {
- PyObject *inbuffObj, *outbuffObj, *shapeObj;
- PyObject *inbstridesObj, *outbstridesObj;
- CfuncObject *me = (CfuncObject *) self;
- int nshape, ninbstrides, noutbstrides;
- maybelong shape[MAXDIM], inbstrides[MAXDIM],
- outbstrides[MAXDIM], *outbstrides1 = outbstrides;
- long inboffset, outboffset, nbytes=0;
-
- if (!PyArg_ParseTuple(args, "OOlOOlO|l",
- &shapeObj, &inbuffObj, &inboffset, &inbstridesObj,
- &outbuffObj, &outboffset, &outbstridesObj,
- &nbytes)) {
- return PyErr_Format(_Error,
- "%s: Problem with argument list",
- me->descr.name);
- }
-
- nshape = NA_maybeLongsFromIntTuple(MAXDIM, shape, shapeObj);
- if (nshape < 0) return NULL;
-
- ninbstrides = NA_maybeLongsFromIntTuple(MAXDIM, inbstrides, inbstridesObj);
- if (ninbstrides < 0) return NULL;
-
- noutbstrides= NA_maybeLongsFromIntTuple(MAXDIM, outbstrides, outbstridesObj);
- if (noutbstrides < 0) return NULL;
-
- if (nshape && (nshape != ninbstrides)) {
- return PyErr_Format(_Error,
- "%s: Missmatch between input iteration and strides tuples",
- me->descr.name);
- }
-
- if (nshape && (nshape != noutbstrides)) {
- if (noutbstrides < 1 ||
- outbstrides[ noutbstrides - 1 ])/* allow 0 for reductions. */
- return PyErr_Format(_Error,
- "%s: Missmatch between output "
- "iteration and strides tuples",
- me->descr.name);
- }
-
- return NA_callStrideConvCFuncCore(
- self, nshape, shape,
- inbuffObj, inboffset, ninbstrides, inbstrides,
- outbuffObj, outboffset, noutbstrides, outbstrides1, nbytes);
-}
-
-static int
-_NA_callStridingHelper(PyObject *aux, long dim,
- long nnumarray, PyArrayObject *numarray[], char *data[],
- CFUNC_STRIDED_FUNC f)
-{
- int i, j, status=0;
- dim -= 1;
- for(i=0; i<PyArray_DIMS(numarray[0])[dim]; i++) {
- for (j=0; j<nnumarray; j++)
- data[j] += PyArray_STRIDES(numarray[j])[dim]*i;
- if (dim == 0)
- status |= f(aux, nnumarray, numarray, data);
- else
- status |= _NA_callStridingHelper(
- aux, dim, nnumarray, numarray, data, f);
- for (j=0; j<nnumarray; j++)
- data[j] -= PyArray_STRIDES(numarray[j])[dim]*i;
- }
- return status;
-}
-
-
-static PyObject *
-callStridingCFunc(PyObject *self, PyObject *args) {
- CfuncObject *me = (CfuncObject *) self;
- PyObject *aux;
- PyArrayObject *numarray[MAXARRAYS];
- char *data[MAXARRAYS];
- CFUNC_STRIDED_FUNC f;
- int i;
-
- int nnumarray = PySequence_Length(args)-1;
- if ((nnumarray < 1) || (nnumarray > MAXARRAYS))
- return PyErr_Format(_Error, "%s, too many or too few numarray.",
- me->descr.name);
-
- aux = PySequence_GetItem(args, 0);
- if (!aux)
- return NULL;
-
- for(i=0; i<nnumarray; i++) {
- PyObject *otemp = PySequence_GetItem(args, i+1);
- if (!otemp)
- return PyErr_Format(_Error, "%s couldn't get array[%d]",
- me->descr.name, i);
- if (!NA_NDArrayCheck(otemp))
- return PyErr_Format(PyExc_TypeError,
- "%s arg[%d] is not an array.",
- me->descr.name, i);
- numarray[i] = (PyArrayObject *) otemp;
- data[i] = PyArray_DATA(numarray[i]);
- Py_DECREF(otemp);
- if (!NA_updateDataPtr(numarray[i]))
- return NULL;
- }
-
- /* Cast function pointer and perform stride operation */
- f = (CFUNC_STRIDED_FUNC) me->descr.fptr;
-
- if (_NA_callStridingHelper(aux, PyArray_NDIM(numarray[0]),
- nnumarray, numarray, data, f)) {
- return NULL;
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
-}
-
-/* Convert a standard C numeric value to a Python numeric value.
- **
- ** Handles both nonaligned and/or byteswapped C data.
- **
- ** Input arguments are:
- **
- ** Buffer object that contains the C numeric value.
- ** Offset (in bytes) into the buffer that the data is located at.
- ** The size of the C numeric data item in bytes.
- ** Flag indicating if the C data is byteswapped from the processor's
- ** natural representation.
- **
- ** Returns a Python numeric value.
- */
-
-static PyObject *
-NumTypeAsPyValue(PyObject *self, PyObject *args) {
- PyObject *bufferObj;
- long offset, itemsize, byteswap, i, buffersize;
- Py_complex temp; /* to hold copies of largest possible type */
- void *buffer;
- char *tempptr;
- CFUNCasPyValue funcptr;
- CfuncObject *me = (CfuncObject *) self;
-
- if (!PyArg_ParseTuple(args, "Olll",
- &bufferObj, &offset, &itemsize, &byteswap))
- return PyErr_Format(_Error,
- "NumTypeAsPyValue: Problem with argument list");
-
- if ((buffersize = NA_getBufferPtrAndSize(bufferObj, 1, &buffer)) < 0)
- return PyErr_Format(_Error,
- "NumTypeAsPyValue: Problem with array buffer");
-
- if (offset < 0)
- return PyErr_Format(_Error,
- "NumTypeAsPyValue: invalid negative offset: %d", (int) offset);
-
- /* Guarantee valid buffer pointer */
- if (offset+itemsize > buffersize)
- return PyErr_Format(_Error,
- "NumTypeAsPyValue: buffer too small for offset and itemsize.");
-
- /* Do byteswapping. Guarantee double alignment by using temp. */
- tempptr = (char *) &temp;
- if (!byteswap) {
- for (i=0; i<itemsize; i++)
- *(tempptr++) = *(((char *) buffer)+offset+i);
- } else {
- tempptr += itemsize-1;
- for (i=0; i<itemsize; i++)
- *(tempptr--) = *(((char *) buffer)+offset+i);
- }
-
- funcptr = (CFUNCasPyValue) me->descr.fptr;
-
- /* Call function to build PyObject. Bad parameters to this function
- may render call meaningless, but "temp" guarantees that its safe. */
- return (*funcptr)((void *)(&temp));
-}
-
-/* Convert a Python numeric value to a standard C numeric value.
- **
- ** Handles both nonaligned and/or byteswapped C data.
- **
- ** Input arguments are:
- **
- ** The Python numeric value to be converted.
- ** Buffer object to contain the C numeric value.
- ** Offset (in bytes) into the buffer that the data is to be copied to.
- ** The size of the C numeric data item in bytes.
- ** Flag indicating if the C data is byteswapped from the processor's
- ** natural representation.
- **
- ** Returns None
- */
-
-static PyObject *
-NumTypeFromPyValue(PyObject *self, PyObject *args) {
- PyObject *bufferObj, *valueObj;
- long offset, itemsize, byteswap, i, buffersize;
- Py_complex temp; /* to hold copies of largest possible type */
- void *buffer;
- char *tempptr;
- CFUNCfromPyValue funcptr;
- CfuncObject *me = (CfuncObject *) self;
-
- if (!PyArg_ParseTuple(args, "OOlll",
- &valueObj, &bufferObj, &offset, &itemsize, &byteswap))
- return PyErr_Format(_Error,
- "%s: Problem with argument list", me->descr.name);
-
- if ((buffersize = NA_getBufferPtrAndSize(bufferObj, 0, &buffer)) < 0)
- return PyErr_Format(_Error,
- "%s: Problem with array buffer (read only?)", me->descr.name);
-
- funcptr = (CFUNCfromPyValue) me->descr.fptr;
-
- /* Convert python object into "temp". Always safe. */
- if (!((*funcptr)(valueObj, (void *)( &temp))))
- return PyErr_Format(_Error,
- "%s: Problem converting value", me->descr.name);
-
- /* Check buffer offset. */
- if (offset < 0)
- return PyErr_Format(_Error,
- "%s: invalid negative offset: %d", me->descr.name, (int) offset);
-
- if (offset+itemsize > buffersize)
- return PyErr_Format(_Error,
- "%s: buffer too small(%d) for offset(%d) and itemsize(%d)",
- me->descr.name, (int) buffersize, (int) offset, (int) itemsize);
-
- /* Copy "temp" to array buffer. */
- tempptr = (char *) &temp;
- if (!byteswap) {
- for (i=0; i<itemsize; i++)
- *(((char *) buffer)+offset+i) = *(tempptr++);
- } else {
- tempptr += itemsize-1;
- for (i=0; i<itemsize; i++)
- *(((char *) buffer)+offset+i) = *(tempptr--);
- }
- Py_INCREF(Py_None);
- return Py_None;
-}
-
-/* Handle "calling" the cfunc object at the python level.
- Dispatch the call to the appropriate python-c wrapper based
- on the cfunc type. Do this dispatch to avoid having to
- check that python code didn't somehow create a mismatch between
- cfunc and wrapper.
- */
-static PyObject *
-cfunc_call(PyObject *self, PyObject *argsTuple, PyObject *NPY_UNUSED(argsDict))
-{
- CfuncObject *me = (CfuncObject *) self;
- switch(me->descr.type) {
- case CFUNC_UFUNC:
- return callCUFunc(self, argsTuple);
- break;
- case CFUNC_STRIDING:
- return callStrideConvCFunc(self, argsTuple);
- break;
- case CFUNC_NSTRIDING:
- return callStridingCFunc(self, argsTuple);
- case CFUNC_FROM_PY_VALUE:
- return NumTypeFromPyValue(self, argsTuple);
- break;
- case CFUNC_AS_PY_VALUE:
- return NumTypeAsPyValue(self, argsTuple);
- break;
- default:
- return PyErr_Format( _Error,
- "cfunc_call: Can't dispatch cfunc '%s' with type: %d.",
- me->descr.name, me->descr.type);
- }
-}
-
-static PyTypeObject CfuncType;
-
-static void
-cfunc_dealloc(PyObject* self)
-{
- PyObject_Del(self);
-}
-
-static PyObject *
-cfunc_repr(PyObject *self)
-{
- char buf[256];
- CfuncObject *me = (CfuncObject *) self;
- sprintf(buf, "<cfunc '%s' at %08lx check-self:%d align:%d io:(%d, %d)>",
- me->descr.name, (unsigned long ) me->descr.fptr,
- me->descr.chkself, me->descr.align,
- me->descr.wantIn, me->descr.wantOut);
- return PyUString_FromString(buf);
-}
-
-static PyTypeObject CfuncType = {
-#if defined(NPY_PY3K)
- PyVarObject_HEAD_INIT(0,0)
-#else
- PyObject_HEAD_INIT(0)
- 0, /* ob_size */
-#endif
- "Cfunc",
- sizeof(CfuncObject),
- 0,
- cfunc_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- cfunc_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- cfunc_call, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- 0, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
- 0, /* tp_is_gc */
- 0, /* tp_bases */
- 0, /* tp_mro */
- 0, /* tp_cache */
- 0, /* tp_subclasses */
- 0, /* tp_weaklist */
- 0, /* tp_del */
- 0, /* tp_version_tag */
- };
-
-/* CfuncObjects are created at the c-level only. They ensure that each
- cfunc is called via the correct python-c-wrapper as defined by its
- CfuncDescriptor. The wrapper, in turn, does conversions and buffer size
- and alignment checking. Allowing these to be created at the python level
- would enable them to be created *wrong* at the python level, and thereby
- enable python code to *crash* python.
- */
-static PyObject*
-NA_new_cfunc(CfuncDescriptor *cfd)
-{
- CfuncObject* cfunc;
-
- /* Should be done once at init.
- Do now since there is no init. */
- ((PyObject*)&CfuncType)->ob_type = &PyType_Type;
-
- cfunc = PyObject_New(CfuncObject, &CfuncType);
-
- if (!cfunc) {
- return PyErr_Format(_Error,
- "NA_new_cfunc: failed creating '%s'",
- cfd->name);
- }
-
- cfunc->descr = *cfd;
-
- return (PyObject*)cfunc;
-}
-
-static int NA_add_cfunc(PyObject *dict, char *keystr, CfuncDescriptor *descr)
-{
- PyObject *c = (PyObject *) NA_new_cfunc(descr);
- if (!c) return -1;
- return PyDict_SetItemString(dict, keystr, c);
-}
-
-static PyArrayObject*
-NA_InputArray(PyObject *a, NumarrayType t, int requires)
-{
- PyArray_Descr *descr;
- if (t == tAny) descr = NULL;
- else descr = PyArray_DescrFromType(t);
- return (PyArrayObject *) \
- PyArray_CheckFromAny(a, descr, 0, 0, requires, NULL);
-}
-
-/* satisfies ensures that 'a' meets a set of requirements and matches
- the specified type.
- */
-static int
-satisfies(PyArrayObject *a, int requirements, NumarrayType t)
-{
- int type_ok = (PyArray_DESCR(a)->type_num == t) || (t == tAny);
-
- if (PyArray_ISCARRAY(a))
- return type_ok;
- if (PyArray_ISBYTESWAPPED(a) && (requirements & NUM_NOTSWAPPED))
- return 0;
- if (!PyArray_ISALIGNED(a) && (requirements & NUM_ALIGNED))
- return 0;
- if (!PyArray_ISCONTIGUOUS(a) && (requirements & NUM_CONTIGUOUS))
- return 0;
- if (!PyArray_ISWRITABLE(a) && (requirements & NUM_WRITABLE))
- return 0;
- if (requirements & NUM_COPY)
- return 0;
- return type_ok;
-}
-
-
-static PyArrayObject *
-NA_OutputArray(PyObject *a, NumarrayType t, int requires)
-{
- PyArray_Descr *dtype;
- PyArrayObject *ret;
-
- if (!PyArray_Check(a)) {
- PyErr_Format(PyExc_TypeError,
- "NA_OutputArray: only arrays work for output.");
- return NULL;
- }
- if (PyArray_FailUnlessWriteable((PyArrayObject *)a, "output array") < 0) {
- return NULL;
- }
-
- if (satisfies((PyArrayObject *)a, requires, t)) {
- Py_INCREF(a);
- return (PyArrayObject *)a;
- }
- if (t == tAny) {
- dtype = PyArray_DESCR((PyArrayObject *)a);
- Py_INCREF(dtype);
- }
- else {
- dtype = PyArray_DescrFromType(t);
- }
- ret = (PyArrayObject *)PyArray_Empty(PyArray_NDIM((PyArrayObject *)a),
- PyArray_DIMS((PyArrayObject *)a),
- dtype, 0);
- Py_INCREF(a);
- if (PyArray_SetUpdateIfCopyBase(ret, (PyArrayObject *)a) < 0) {
- Py_DECREF(ret);
- return NULL;
- }
- return ret;
-}
-
-
-/* NA_IoArray is a combination of NA_InputArray and NA_OutputArray.
-
- Unlike NA_OutputArray, if a temporary is required it is initialized to a copy
- of the input array.
-
- Unlike NA_InputArray, deallocating any resulting temporary array results in a
- copy from the temporary back to the original.
- */
-static PyArrayObject *
-NA_IoArray(PyObject *a, NumarrayType t, int requires)
-{
- PyArrayObject *shadow = NA_InputArray(a, t,
- requires | NPY_ARRAY_UPDATEIFCOPY );
-
- if (!shadow) return NULL;
-
- /* Guard against non-writable, but otherwise satisfying requires.
- In this case, shadow == a.
- */
- if (!PyArray_FailUnlessWriteable(shadow, "input/output array")) {
- PyArray_XDECREF_ERR(shadow);
- return NULL;
- }
-
- return shadow;
-}
-
-/* NA_OptionalOutputArray works like NA_OutputArray, but handles the case
- where the output array 'optional' is omitted entirely at the python level,
- resulting in 'optional'==Py_None. When 'optional' is Py_None, the return
- value is cloned (but with NumarrayType 't') from 'master', typically an input
- array with the same shape as the output array.
- */
-static PyArrayObject *
-NA_OptionalOutputArray(PyObject *optional, NumarrayType t, int requires,
- PyArrayObject *master)
-{
- if ((optional == Py_None) || (optional == NULL)) {
- PyObject *rval;
- PyArray_Descr *descr;
- if (t == tAny) descr=NULL;
- else descr = PyArray_DescrFromType(t);
- rval = PyArray_FromArray(
- master, descr, NUM_C_ARRAY | NUM_COPY | NUM_WRITABLE);
- return (PyArrayObject *)rval;
- } else {
- return NA_OutputArray(optional, t, requires);
- }
-}
-
-Complex64 NA_get_Complex64(PyArrayObject *a, long offset)
-{
- Complex32 v0;
- Complex64 v;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tComplex32:
- v0 = NA_GETP(a, Complex32, (NA_PTR(a)+offset));
- v.r = v0.r;
- v.i = v0.i;
- break;
- case tComplex64:
- v = NA_GETP(a, Complex64, (NA_PTR(a)+offset));
- break;
- default:
- v.r = NA_get_Float64(a, offset);
- v.i = 0;
- break;
- }
- return v;
-}
-
-void NA_set_Complex64(PyArrayObject *a, long offset, Complex64 v)
-{
- Complex32 v0;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tComplex32:
- v0.r = v.r;
- v0.i = v.i;
- NA_SETP(a, Complex32, (NA_PTR(a)+offset), v0);
- break;
- case tComplex64:
- NA_SETP(a, Complex64, (NA_PTR(a)+offset), v);
- break;
- default:
- NA_set_Float64(a, offset, v.r);
- break;
- }
-}
-
-Int64 NA_get_Int64(PyArrayObject *a, long offset)
-{
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- return NA_GETP(a, Bool, (NA_PTR(a)+offset)) != 0;
- case tInt8:
- return NA_GETP(a, Int8, (NA_PTR(a)+offset));
- case tUInt8:
- return NA_GETP(a, UInt8, (NA_PTR(a)+offset));
- case tInt16:
- return NA_GETP(a, Int16, (NA_PTR(a)+offset));
- case tUInt16:
- return NA_GETP(a, UInt16, (NA_PTR(a)+offset));
- case tInt32:
- return NA_GETP(a, Int32, (NA_PTR(a)+offset));
- case tUInt32:
- return NA_GETP(a, UInt32, (NA_PTR(a)+offset));
- case tInt64:
- return NA_GETP(a, Int64, (NA_PTR(a)+offset));
- case tUInt64:
- return NA_GETP(a, UInt64, (NA_PTR(a)+offset));
- case tFloat32:
- return NA_GETP(a, Float32, (NA_PTR(a)+offset));
- case tFloat64:
- return NA_GETP(a, Float64, (NA_PTR(a)+offset));
- case tComplex32:
- return NA_GETP(a, Float32, (NA_PTR(a)+offset));
- case tComplex64:
- return NA_GETP(a, Float64, (NA_PTR(a)+offset));
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_get_Int64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- }
- return 0; /* suppress warning */
-}
-
-void NA_set_Int64(PyArrayObject *a, long offset, Int64 v)
-{
- Bool b;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- b = (v != 0);
- NA_SETP(a, Bool, (NA_PTR(a)+offset), b);
- break;
- case tInt8: NA_SETP(a, Int8, (NA_PTR(a)+offset), v);
- break;
- case tUInt8: NA_SETP(a, UInt8, (NA_PTR(a)+offset), v);
- break;
- case tInt16: NA_SETP(a, Int16, (NA_PTR(a)+offset), v);
- break;
- case tUInt16: NA_SETP(a, UInt16, (NA_PTR(a)+offset), v);
- break;
- case tInt32: NA_SETP(a, Int32, (NA_PTR(a)+offset), v);
- break;
- case tUInt32: NA_SETP(a, UInt32, (NA_PTR(a)+offset), v);
- break;
- case tInt64: NA_SETP(a, Int64, (NA_PTR(a)+offset), v);
- break;
- case tUInt64: NA_SETP(a, UInt64, (NA_PTR(a)+offset), v);
- break;
- case tFloat32:
- NA_SETP(a, Float32, (NA_PTR(a)+offset), v);
- break;
- case tFloat64:
- NA_SETP(a, Float64, (NA_PTR(a)+offset), v);
- break;
- case tComplex32:
- NA_SETP(a, Float32, (NA_PTR(a)+offset), v);
- NA_SETP(a, Float32, (NA_PTR(a)+offset+sizeof(Float32)), 0);
- break;
- case tComplex64:
- NA_SETP(a, Float64, (NA_PTR(a)+offset), v);
- NA_SETP(a, Float64, (NA_PTR(a)+offset+sizeof(Float64)), 0);
- break;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_set_Int64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- }
-}
-
-/* NA_get_offset computes the offset specified by the set of indices.
- If N > 0, the indices are taken from the outer dimensions of the array.
- If N < 0, the indices are taken from the inner dimensions of the array.
- If N == 0, the offset is 0.
- */
-long NA_get_offset(PyArrayObject *a, int N, ...)
-{
- int i;
- long offset = 0;
- va_list ap;
- va_start(ap, N);
- if (N > 0) { /* compute offset of "outer" indices. */
- for(i=0; i<N; i++)
- offset += va_arg(ap, long) * PyArray_STRIDES(a)[i];
- } else { /* compute offset of "inner" indices. */
- N = -N;
- for(i=0; i<N; i++)
- offset += va_arg(ap, long) * PyArray_STRIDES(a)[PyArray_NDIM(a)-N+i];
- }
- va_end(ap);
- return offset;
-}
-
-Float64 NA_get_Float64(PyArrayObject *a, long offset)
-{
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- return NA_GETP(a, Bool, (NA_PTR(a)+offset)) != 0;
- case tInt8:
- return NA_GETP(a, Int8, (NA_PTR(a)+offset));
- case tUInt8:
- return NA_GETP(a, UInt8, (NA_PTR(a)+offset));
- case tInt16:
- return NA_GETP(a, Int16, (NA_PTR(a)+offset));
- case tUInt16:
- return NA_GETP(a, UInt16, (NA_PTR(a)+offset));
- case tInt32:
- return NA_GETP(a, Int32, (NA_PTR(a)+offset));
- case tUInt32:
- return NA_GETP(a, UInt32, (NA_PTR(a)+offset));
- case tInt64:
- return NA_GETP(a, Int64, (NA_PTR(a)+offset));
-#if HAS_UINT64
- case tUInt64:
- return NA_GETP(a, UInt64, (NA_PTR(a)+offset));
-#endif
- case tFloat32:
- return NA_GETP(a, Float32, (NA_PTR(a)+offset));
- case tFloat64:
- return NA_GETP(a, Float64, (NA_PTR(a)+offset));
- case tComplex32: /* Since real value is first */
- return NA_GETP(a, Float32, (NA_PTR(a)+offset));
- case tComplex64: /* Since real value is first */
- return NA_GETP(a, Float64, (NA_PTR(a)+offset));
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_get_Float64",
- PyArray_DESCR(a)->type_num);
- }
- return 0; /* suppress warning */
-}
-
-void NA_set_Float64(PyArrayObject *a, long offset, Float64 v)
-{
- Bool b;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- b = (v != 0);
- NA_SETP(a, Bool, (NA_PTR(a)+offset), b);
- break;
- case tInt8: NA_SETP(a, Int8, (NA_PTR(a)+offset), v);
- break;
- case tUInt8: NA_SETP(a, UInt8, (NA_PTR(a)+offset), v);
- break;
- case tInt16: NA_SETP(a, Int16, (NA_PTR(a)+offset), v);
- break;
- case tUInt16: NA_SETP(a, UInt16, (NA_PTR(a)+offset), v);
- break;
- case tInt32: NA_SETP(a, Int32, (NA_PTR(a)+offset), v);
- break;
- case tUInt32: NA_SETP(a, UInt32, (NA_PTR(a)+offset), v);
- break;
- case tInt64: NA_SETP(a, Int64, (NA_PTR(a)+offset), v);
- break;
-#if HAS_UINT64
- case tUInt64: NA_SETP(a, UInt64, (NA_PTR(a)+offset), v);
- break;
-#endif
- case tFloat32:
- NA_SETP(a, Float32, (NA_PTR(a)+offset), v);
- break;
- case tFloat64:
- NA_SETP(a, Float64, (NA_PTR(a)+offset), v);
- break;
- case tComplex32: {
- NA_SETP(a, Float32, (NA_PTR(a)+offset), v);
- NA_SETP(a, Float32, (NA_PTR(a)+offset+sizeof(Float32)), 0);
- break;
- }
- case tComplex64: {
- NA_SETP(a, Float64, (NA_PTR(a)+offset), v);
- NA_SETP(a, Float64, (NA_PTR(a)+offset+sizeof(Float64)), 0);
- break;
- }
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_set_Float64",
- PyArray_DESCR(a)->type_num );
- PyErr_Print();
- }
-}
-
-
-Float64 NA_get1_Float64(PyArrayObject *a, long i)
-{
- long offset = i * PyArray_STRIDES(a)[0];
- return NA_get_Float64(a, offset);
-}
-
-Float64 NA_get2_Float64(PyArrayObject *a, long i, long j)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1];
- return NA_get_Float64(a, offset);
-}
-
-Float64 NA_get3_Float64(PyArrayObject *a, long i, long j, long k)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1]
- + k * PyArray_STRIDES(a)[2];
- return NA_get_Float64(a, offset);
-}
-
-void NA_set1_Float64(PyArrayObject *a, long i, Float64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0];
- NA_set_Float64(a, offset, v);
-}
-
-void NA_set2_Float64(PyArrayObject *a, long i, long j, Float64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1];
- NA_set_Float64(a, offset, v);
-}
-
-void NA_set3_Float64(PyArrayObject *a, long i, long j, long k, Float64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1]
- + k * PyArray_STRIDES(a)[2];
- NA_set_Float64(a, offset, v);
-}
-
-Complex64 NA_get1_Complex64(PyArrayObject *a, long i)
-{
- long offset = i * PyArray_STRIDES(a)[0];
- return NA_get_Complex64(a, offset);
-}
-
-Complex64 NA_get2_Complex64(PyArrayObject *a, long i, long j)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1];
- return NA_get_Complex64(a, offset);
-}
-
-Complex64 NA_get3_Complex64(PyArrayObject *a, long i, long j, long k)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1]
- + k * PyArray_STRIDES(a)[2];
- return NA_get_Complex64(a, offset);
-}
-
-void NA_set1_Complex64(PyArrayObject *a, long i, Complex64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0];
- NA_set_Complex64(a, offset, v);
-}
-
-void NA_set2_Complex64(PyArrayObject *a, long i, long j, Complex64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1];
- NA_set_Complex64(a, offset, v);
-}
-
-void NA_set3_Complex64(PyArrayObject *a, long i, long j, long k, Complex64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1]
- + k * PyArray_STRIDES(a)[2];
- NA_set_Complex64(a, offset, v);
-}
-
-Int64 NA_get1_Int64(PyArrayObject *a, long i)
-{
- long offset = i * PyArray_STRIDES(a)[0];
- return NA_get_Int64(a, offset);
-}
-
-Int64 NA_get2_Int64(PyArrayObject *a, long i, long j)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1];
- return NA_get_Int64(a, offset);
-}
-
-Int64 NA_get3_Int64(PyArrayObject *a, long i, long j, long k)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1]
- + k * PyArray_STRIDES(a)[2];
- return NA_get_Int64(a, offset);
-}
-
-void NA_set1_Int64(PyArrayObject *a, long i, Int64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0];
- NA_set_Int64(a, offset, v);
-}
-
-void NA_set2_Int64(PyArrayObject *a, long i, long j, Int64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1];
- NA_set_Int64(a, offset, v);
-}
-
-void NA_set3_Int64(PyArrayObject *a, long i, long j, long k, Int64 v)
-{
- long offset = i * PyArray_STRIDES(a)[0]
- + j * PyArray_STRIDES(a)[1]
- + k * PyArray_STRIDES(a)[2];
- NA_set_Int64(a, offset, v);
-}
-
-/* SET_CMPLX could be made faster by factoring it into 3 seperate loops.
-*/
-#define NA_SET_CMPLX(a, type, base, cnt, in) \
-{ \
- int i; \
- int stride = PyArray_STRIDES(a)[ PyArray_NDIM(a) - 1]; \
- NA_SET1D(a, type, base, cnt, in); \
- base = NA_PTR(a) + offset + sizeof(type); \
- for(i=0; i<cnt; i++) { \
- NA_SETP(a, Float32, base, 0); \
- base += stride; \
- } \
-}
-
-static int
-NA_get1D_Float64(PyArrayObject *a, long offset, int cnt, Float64*out)
-{
- char *base = NA_PTR(a) + offset;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- NA_GET1D(a, Bool, base, cnt, out);
- break;
- case tInt8:
- NA_GET1D(a, Int8, base, cnt, out);
- break;
- case tUInt8:
- NA_GET1D(a, UInt8, base, cnt, out);
- break;
- case tInt16:
- NA_GET1D(a, Int16, base, cnt, out);
- break;
- case tUInt16:
- NA_GET1D(a, UInt16, base, cnt, out);
- break;
- case tInt32:
- NA_GET1D(a, Int32, base, cnt, out);
- break;
- case tUInt32:
- NA_GET1D(a, UInt32, base, cnt, out);
- break;
- case tInt64:
- NA_GET1D(a, Int64, base, cnt, out);
- break;
-#if HAS_UINT64
- case tUInt64:
- NA_GET1D(a, UInt64, base, cnt, out);
- break;
-#endif
- case tFloat32:
- NA_GET1D(a, Float32, base, cnt, out);
- break;
- case tFloat64:
- NA_GET1D(a, Float64, base, cnt, out);
- break;
- case tComplex32:
- NA_GET1D(a, Float32, base, cnt, out);
- break;
- case tComplex64:
- NA_GET1D(a, Float64, base, cnt, out);
- break;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_get1D_Float64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- return -1;
- }
- return 0;
-}
-
-static Float64 *
-NA_alloc1D_Float64(PyArrayObject *a, long offset, int cnt)
-{
- Float64 *result = PyMem_New(Float64, (size_t)cnt);
- if (!result) return NULL;
- if (NA_get1D_Float64(a, offset, cnt, result) < 0) {
- PyMem_Free(result);
- return NULL;
- }
- return result;
-}
-
-static int
-NA_set1D_Float64(PyArrayObject *a, long offset, int cnt, Float64*in)
-{
- char *base = NA_PTR(a) + offset;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- NA_SET1D(a, Bool, base, cnt, in);
- break;
- case tInt8:
- NA_SET1D(a, Int8, base, cnt, in);
- break;
- case tUInt8:
- NA_SET1D(a, UInt8, base, cnt, in);
- break;
- case tInt16:
- NA_SET1D(a, Int16, base, cnt, in);
- break;
- case tUInt16:
- NA_SET1D(a, UInt16, base, cnt, in);
- break;
- case tInt32:
- NA_SET1D(a, Int32, base, cnt, in);
- break;
- case tUInt32:
- NA_SET1D(a, UInt32, base, cnt, in);
- break;
- case tInt64:
- NA_SET1D(a, Int64, base, cnt, in);
- break;
-#if HAS_UINT64
- case tUInt64:
- NA_SET1D(a, UInt64, base, cnt, in);
- break;
-#endif
- case tFloat32:
- NA_SET1D(a, Float32, base, cnt, in);
- break;
- case tFloat64:
- NA_SET1D(a, Float64, base, cnt, in);
- break;
- case tComplex32:
- NA_SET_CMPLX(a, Float32, base, cnt, in);
- break;
- case tComplex64:
- NA_SET_CMPLX(a, Float64, base, cnt, in);
- break;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_set1D_Float64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- return -1;
- }
- return 0;
-}
-
-static int
-NA_get1D_Int64(PyArrayObject *a, long offset, int cnt, Int64*out)
-{
- char *base = NA_PTR(a) + offset;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- NA_GET1D(a, Bool, base, cnt, out);
- break;
- case tInt8:
- NA_GET1D(a, Int8, base, cnt, out);
- break;
- case tUInt8:
- NA_GET1D(a, UInt8, base, cnt, out);
- break;
- case tInt16:
- NA_GET1D(a, Int16, base, cnt, out);
- break;
- case tUInt16:
- NA_GET1D(a, UInt16, base, cnt, out);
- break;
- case tInt32:
- NA_GET1D(a, Int32, base, cnt, out);
- break;
- case tUInt32:
- NA_GET1D(a, UInt32, base, cnt, out);
- break;
- case tInt64:
- NA_GET1D(a, Int64, base, cnt, out);
- break;
- case tUInt64:
- NA_GET1D(a, UInt64, base, cnt, out);
- break;
- case tFloat32:
- NA_GET1D(a, Float32, base, cnt, out);
- break;
- case tFloat64:
- NA_GET1D(a, Float64, base, cnt, out);
- break;
- case tComplex32:
- NA_GET1D(a, Float32, base, cnt, out);
- break;
- case tComplex64:
- NA_GET1D(a, Float64, base, cnt, out);
- break;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_get1D_Int64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- return -1;
- }
- return 0;
-}
-
-static Int64 *
-NA_alloc1D_Int64(PyArrayObject *a, long offset, int cnt)
-{
- Int64 *result = PyMem_New(Int64, (size_t)cnt);
- if (!result) return NULL;
- if (NA_get1D_Int64(a, offset, cnt, result) < 0) {
- PyMem_Free(result);
- return NULL;
- }
- return result;
-}
-
-static int
-NA_set1D_Int64(PyArrayObject *a, long offset, int cnt, Int64*in)
-{
- char *base = NA_PTR(a) + offset;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- NA_SET1D(a, Bool, base, cnt, in);
- break;
- case tInt8:
- NA_SET1D(a, Int8, base, cnt, in);
- break;
- case tUInt8:
- NA_SET1D(a, UInt8, base, cnt, in);
- break;
- case tInt16:
- NA_SET1D(a, Int16, base, cnt, in);
- break;
- case tUInt16:
- NA_SET1D(a, UInt16, base, cnt, in);
- break;
- case tInt32:
- NA_SET1D(a, Int32, base, cnt, in);
- break;
- case tUInt32:
- NA_SET1D(a, UInt32, base, cnt, in);
- break;
- case tInt64:
- NA_SET1D(a, Int64, base, cnt, in);
- break;
- case tUInt64:
- NA_SET1D(a, UInt64, base, cnt, in);
- break;
- case tFloat32:
- NA_SET1D(a, Float32, base, cnt, in);
- break;
- case tFloat64:
- NA_SET1D(a, Float64, base, cnt, in);
- break;
- case tComplex32:
- NA_SET_CMPLX(a, Float32, base, cnt, in);
- break;
- case tComplex64:
- NA_SET_CMPLX(a, Float64, base, cnt, in);
- break;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_set1D_Int64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- return -1;
- }
- return 0;
-}
-
-static int
-NA_get1D_Complex64(PyArrayObject *a, long offset, int cnt, Complex64*out)
-{
- char *base = NA_PTR(a) + offset;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tComplex64:
- NA_GET1D(a, Complex64, base, cnt, out);
- break;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unsupported type %d in NA_get1D_Complex64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- return -1;
- }
- return 0;
-}
-
-static int
-NA_set1D_Complex64(PyArrayObject *a, long offset, int cnt, Complex64*in)
-{
- char *base = NA_PTR(a) + offset;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tComplex64:
- NA_SET1D(a, Complex64, base, cnt, in);
- break;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unsupported type %d in NA_set1D_Complex64",
- PyArray_DESCR(a)->type_num);
- PyErr_Print();
- return -1;
- }
- return 0;
-}
-
-
-/* NA_ShapeEqual returns 1 if 'a' and 'b' have the same shape, 0 otherwise.
-*/
-static int
-NA_ShapeEqual(PyArrayObject *a, PyArrayObject *b)
-{
- int i;
-
- if (!NA_NDArrayCheck((PyObject *) a) ||
- !NA_NDArrayCheck((PyObject*) b)) {
- PyErr_Format(
- PyExc_TypeError,
- "NA_ShapeEqual: non-array as parameter.");
- return -1;
- }
- if (PyArray_NDIM(a) != PyArray_NDIM(b))
- return 0;
- for(i=0; i<PyArray_NDIM(a); i++)
- if (PyArray_DIMS(a)[i] != PyArray_DIMS(b)[i])
- return 0;
- return 1;
-}
-
-/* NA_ShapeLessThan returns 1 if a.shape[i] < b.shape[i] for all i, else 0.
- If they have a different number of dimensions, it compares the innermost
- overlapping dimensions of each.
- */
-static int
-NA_ShapeLessThan(PyArrayObject *a, PyArrayObject *b)
-{
- int i;
- int mindim, aoff, boff;
- if (!NA_NDArrayCheck((PyObject *) a) ||
- !NA_NDArrayCheck((PyObject *) b)) {
- PyErr_Format(PyExc_TypeError,
- "NA_ShapeLessThan: non-array as parameter.");
- return -1;
- }
- mindim = MIN(PyArray_NDIM(a), PyArray_NDIM(b));
- aoff = PyArray_NDIM(a) - mindim;
- boff = PyArray_NDIM(b) - mindim;
- for(i=0; i<mindim; i++)
- if (PyArray_DIMS(a)[i+aoff] >= PyArray_DIMS(b)[i+boff])
- return 0;
- return 1;
-}
-
-static int
-NA_ByteOrder(void)
-{
- unsigned long byteorder_test;
- byteorder_test = 1;
- if (*((char *) &byteorder_test))
- return NUM_LITTLE_ENDIAN;
- else
- return NUM_BIG_ENDIAN;
-}
-
-static Bool
-NA_IeeeSpecial32( Float32 *f, Int32 *mask)
-{
- return NA_IeeeMask32(*f, *mask);
-}
-
-static Bool
-NA_IeeeSpecial64( Float64 *f, Int32 *mask)
-{
- return NA_IeeeMask64(*f, *mask);
-}
-
-static PyArrayObject *
-NA_updateDataPtr(PyArrayObject *me)
-{
- return me;
-}
-
-
-#define ELEM(x) (sizeof(x)/sizeof(x[0]))
-
-typedef struct
-{
- char *name;
- int typeno;
-} NumarrayTypeNameMapping;
-
-static NumarrayTypeNameMapping NumarrayTypeNameMap[] = {
- {"Any", tAny},
- {"Bool", tBool},
- {"Int8", tInt8},
- {"UInt8", tUInt8},
- {"Int16", tInt16},
- {"UInt16", tUInt16},
- {"Int32", tInt32},
- {"UInt32", tUInt32},
- {"Int64", tInt64},
- {"UInt64", tUInt64},
- {"Float32", tFloat32},
- {"Float64", tFloat64},
- {"Complex32", tComplex32},
- {"Complex64", tComplex64},
- {"Object", tObject},
- {"Long", tLong},
-};
-
-
-/* Convert NumarrayType 'typeno' into the string of the type's name. */
-static char *
-NA_typeNoToName(int typeno)
-{
- size_t i;
- PyObject *typeObj;
- int typeno2;
-
- for(i=0; i<ELEM(NumarrayTypeNameMap); i++)
- if (typeno == NumarrayTypeNameMap[i].typeno)
- return NumarrayTypeNameMap[i].name;
-
- /* Handle Numeric typecodes */
- typeObj = NA_typeNoToTypeObject(typeno);
- if (!typeObj) return 0;
- typeno2 = NA_typeObjectToTypeNo(typeObj);
- Py_DECREF(typeObj);
-
- return NA_typeNoToName(typeno2);
-}
-
-/* Look up the NumarrayType which corresponds to typename */
-
-static int
-NA_nameToTypeNo(char *typename)
-{
- size_t i;
- for(i=0; i<ELEM(NumarrayTypeNameMap); i++)
- if (!strcmp(typename, NumarrayTypeNameMap[i].name))
- return NumarrayTypeNameMap[i].typeno;
- return -1;
-}
-
-static PyObject *
-getTypeObject(NumarrayType type)
-{
- return (PyObject *)PyArray_DescrFromType(type);
-}
-
-
-static PyObject *
-NA_typeNoToTypeObject(int typeno)
-{
- PyObject *o;
- o = getTypeObject(typeno);
- if (o) Py_INCREF(o);
- return o;
-}
-
-
-static PyObject *
-NA_intTupleFromMaybeLongs(int len, maybelong *Longs)
-{
- return PyArray_IntTupleFromIntp(len, Longs);
-}
-
-static long
-NA_maybeLongsFromIntTuple(int len, maybelong *arr, PyObject *sequence)
-{
- return PyArray_IntpFromSequence(sequence, arr, len);
-}
-
-
-static int
-NA_intTupleProduct(PyObject *shape, long *prod)
-{
- int i, nshape, rval = -1;
-
- if (!PySequence_Check(shape)) {
- PyErr_Format(PyExc_TypeError,
- "NA_intSequenceProduct: object is not a sequence.");
- goto _exit;
- }
- nshape = PySequence_Size(shape);
-
- for(i=0, *prod=1; i<nshape; i++) {
- PyObject *obj = PySequence_GetItem(shape, i);
- if (!obj || !(PyInt_Check(obj) || PyLong_Check(obj))) {
- PyErr_Format(PyExc_TypeError,
- "NA_intTupleProduct: non-integer in shape.");
- Py_XDECREF(obj);
- goto _exit;
- }
- *prod *= PyInt_AsLong(obj);
- Py_DECREF(obj);
- if (PyErr_Occurred())
- goto _exit;
- }
- rval = 0;
-_exit:
- return rval;
-}
-
-static long
-NA_isIntegerSequence(PyObject *sequence)
-{
- PyObject *o;
- long i, size, isInt = 1;
- if (!sequence) {
- isInt = -1;
- goto _exit;
- }
- if (!PySequence_Check(sequence)) {
- isInt = 0;
- goto _exit;
- }
- if ((size = PySequence_Length(sequence)) < 0) {
- isInt = -1;
- goto _exit;
- }
- for(i=0; i<size; i++) {
- o = PySequence_GetItem(sequence, i);
- if (!PyInt_Check(o) && !PyLong_Check(o)) {
- isInt = 0;
- Py_XDECREF(o);
- goto _exit;
- }
- Py_XDECREF(o);
- }
-_exit:
- return isInt;
-}
-
-static int
-getShape(PyObject *a, maybelong *shape, int dims)
-{
- long slen;
- if (PyBytes_Check(a)) {
- PyErr_Format(PyExc_TypeError,
- "getShape: numerical sequences can't contain strings.");
- return -1;
- }
-
- if (!PySequence_Check(a) ||
- (NA_NDArrayCheck(a) && (PyArray_NDIM(PyArray(a)) == 0)))
- return dims;
- slen = PySequence_Length(a);
- if (slen < 0) {
- PyErr_Format(_Error,
- "getShape: couldn't get sequence length.");
- return -1;
- }
- if (!slen) {
- *shape = 0;
- return dims+1;
- } else if (dims < MAXDIM) {
- PyObject *item0 = PySequence_GetItem(a, 0);
- if (item0) {
- *shape = PySequence_Length(a);
- dims = getShape(item0, ++shape, dims+1);
- Py_DECREF(item0);
- } else {
- PyErr_Format(_Error,
- "getShape: couldn't get sequence item.");
- return -1;
- }
- } else {
- PyErr_Format(_Error,
- "getShape: sequence object nested more than MAXDIM deep.");
- return -1;
- }
- return dims;
-}
-
-
-
-typedef enum {
- NOTHING,
- NUMBER,
- SEQUENCE
-} SequenceConstraint;
-
-static int
-setArrayFromSequence(PyArrayObject *a, PyObject *s, int dim, long offset)
-{
- SequenceConstraint mustbe = NOTHING;
- int i, seqlen=-1, slen = PySequence_Length(s);
-
- if (dim > PyArray_NDIM(a)) {
- PyErr_Format(PyExc_ValueError,
- "setArrayFromSequence: sequence/array dimensions mismatch.");
- return -1;
- }
-
- if (slen != PyArray_DIMS(a)[dim]) {
- PyErr_Format(PyExc_ValueError,
- "setArrayFromSequence: sequence/array shape mismatch.");
- return -1;
- }
-
- for(i=0; i<slen; i++) {
- PyObject *o = PySequence_GetItem(s, i);
- if (!o) {
- PyErr_SetString(_Error,
- "setArrayFromSequence: Can't get a sequence item");
- return -1;
- } else if ((NA_isPythonScalar(o) ||
- (NA_NumArrayCheck(o) && PyArray_NDIM(PyArray(o)) == 0)) &&
- ((mustbe == NOTHING) || (mustbe == NUMBER))) {
- if (NA_setFromPythonScalar(a, offset, o) < 0)
- return -2;
- mustbe = NUMBER;
- } else if (PyBytes_Check(o)) {
- PyErr_SetString( PyExc_ValueError,
- "setArrayFromSequence: strings can't define numeric numarray.");
- return -3;
- } else if (PySequence_Check(o)) {
-
- if ((mustbe == NOTHING) || (mustbe == SEQUENCE)) {
- if (mustbe == NOTHING) {
- mustbe = SEQUENCE;
- seqlen = PySequence_Length(o);
- } else if (PySequence_Length(o) != seqlen) {
- PyErr_SetString(
- PyExc_ValueError,
- "Nested sequences with different lengths.");
- return -5;
- }
- setArrayFromSequence(a, o, dim+1, offset);
- } else {
- PyErr_SetString(PyExc_ValueError,
- "Nested sequences with different lengths.");
- return -4;
- }
- } else {
- PyErr_SetString(PyExc_ValueError, "Invalid sequence.");
- return -6;
- }
- Py_DECREF(o);
- offset += PyArray_STRIDES(a)[dim];
- }
- return 0;
-}
-
-static PyObject *
-NA_setArrayFromSequence(PyArrayObject *a, PyObject *s)
-{
- maybelong shape[MAXDIM];
-
- if (!PySequence_Check(s))
- return PyErr_Format( PyExc_TypeError,
- "NA_setArrayFromSequence: (array, seq) expected.");
-
- if (getShape(s, shape, 0) < 0)
- return NULL;
-
- if (!NA_updateDataPtr(a))
- return NULL;
-
- if (setArrayFromSequence(a, s, 0, 0) < 0)
- return NULL;
-
- Py_INCREF(Py_None);
- return Py_None;
-}
-
-enum {
- BOOL_SCALAR,
- INT_SCALAR,
- LONG_SCALAR,
- FLOAT_SCALAR,
- COMPLEX_SCALAR
-};
-
-
-static int
-_NA_maxType(PyObject *seq, int limit)
-{
- if (limit > MAXDIM) {
- PyErr_Format( PyExc_ValueError,
- "NA_maxType: sequence nested too deep." );
- return -1;
- }
- if (NA_NumArrayCheck(seq)) {
- switch(PyArray_DESCR(PyArray(seq))->type_num) {
- case tBool:
- return BOOL_SCALAR;
- case tInt8:
- case tUInt8:
- case tInt16:
- case tUInt16:
- case tInt32:
- case tUInt32:
- return INT_SCALAR;
- case tInt64:
- case tUInt64:
- return LONG_SCALAR;
- case tFloat32:
- case tFloat64:
- return FLOAT_SCALAR;
- case tComplex32:
- case tComplex64:
- return COMPLEX_SCALAR;
- default:
- PyErr_Format(PyExc_TypeError,
- "Expecting a python numeric type, got something else.");
- return -1;
- }
- } else if (PySequence_Check(seq) && !PyBytes_Check(seq)) {
- long i, maxtype=BOOL_SCALAR, slen;
-
- slen = PySequence_Length(seq);
- if (slen < 0) return -1;
-
- if (slen == 0) return INT_SCALAR;
-
- for(i=0; i<slen; i++) {
- long newmax;
- PyObject *o = PySequence_GetItem(seq, i);
- if (!o) return -1;
- newmax = _NA_maxType(o, limit+1);
- if (newmax < 0)
- return -1;
- else if (newmax > maxtype) {
- maxtype = newmax;
- }
- Py_DECREF(o);
- }
- return maxtype;
- } else {
- if (PyBool_Check(seq))
- return BOOL_SCALAR;
- else
-#if defined(NPY_PY3K)
- if (PyInt_Check(seq))
- return INT_SCALAR;
- else if (PyLong_Check(seq))
-#else
- if (PyLong_Check(seq))
-#endif
- return LONG_SCALAR;
- else if (PyFloat_Check(seq))
- return FLOAT_SCALAR;
- else if (PyComplex_Check(seq))
- return COMPLEX_SCALAR;
- else {
- PyErr_Format(PyExc_TypeError,
- "Expecting a python numeric type, got something else.");
- return -1;
- }
- }
-}
-
-static int
-NA_maxType(PyObject *seq)
-{
- int rval;
- rval = _NA_maxType(seq, 0);
- return rval;
-}
-
-static int
-NA_isPythonScalar(PyObject *o)
-{
- int rval;
- rval = PyInt_Check(o) ||
- PyLong_Check(o) ||
- PyFloat_Check(o) ||
- PyComplex_Check(o) ||
- (PyBytes_Check(o) && (PyBytes_Size(o) == 1));
- return rval;
-}
-
-#if (NPY_SIZEOF_INTP == 8)
-#define PlatBigInt PyInt_FromLong
-#define PlatBigUInt PyLong_FromUnsignedLong
-#else
-#define PlatBigInt PyLong_FromLongLong
-#define PlatBigUInt PyLong_FromUnsignedLongLong
-#endif
-
-
-static PyObject *
-NA_getPythonScalar(PyArrayObject *a, long offset)
-{
- int type = PyArray_DESCR(a)->type_num;
- PyObject *rval = NULL;
-
- switch(type) {
- case tBool:
- case tInt8:
- case tUInt8:
- case tInt16:
- case tUInt16:
- case tInt32: {
- Int64 v = NA_get_Int64(a, offset);
- rval = PyInt_FromLong(v);
- break;
- }
- case tUInt32: {
- Int64 v = NA_get_Int64(a, offset);
- rval = PlatBigUInt(v);
- break;
- }
- case tInt64: {
- Int64 v = NA_get_Int64(a, offset);
- rval = PlatBigInt( v);
- break;
- }
- case tUInt64: {
- Int64 v = NA_get_Int64(a, offset);
- rval = PlatBigUInt( v);
- break;
- }
- case tFloat32:
- case tFloat64: {
- Float64 v = NA_get_Float64(a, offset);
- rval = PyFloat_FromDouble( v );
- break;
- }
- case tComplex32:
- case tComplex64:
- {
- Complex64 v = NA_get_Complex64(a, offset);
- rval = PyComplex_FromDoubles(v.r, v.i);
- break;
- }
- default:
- rval = PyErr_Format(PyExc_TypeError,
- "NA_getPythonScalar: bad type %d\n",
- type);
- }
- return rval;
-}
-
-static int
-NA_overflow(PyArrayObject *a, Float64 v)
-{
- if ((PyArray_FLAGS(a) & CHECKOVERFLOW) == 0) return 0;
-
- switch(PyArray_DESCR(a)->type_num) {
- case tBool:
- return 0;
- case tInt8:
- if ((v < -128) || (v > 127)) goto _fail;
- return 0;
- case tUInt8:
- if ((v < 0) || (v > 255)) goto _fail;
- return 0;
- case tInt16:
- if ((v < -32768) || (v > 32767)) goto _fail;
- return 0;
- case tUInt16:
- if ((v < 0) || (v > 65535)) goto _fail;
- return 0;
- case tInt32:
- if ((v < -2147483648.) ||
- (v > 2147483647.)) goto _fail;
- return 0;
- case tUInt32:
- if ((v < 0) || (v > 4294967295.)) goto _fail;
- return 0;
- case tInt64:
- if ((v < -9223372036854775808.) ||
- (v > 9223372036854775807.)) goto _fail;
- return 0;
-#if HAS_UINT64
- case tUInt64:
- if ((v < 0) ||
- (v > 18446744073709551615.)) goto _fail;
- return 0;
-#endif
- case tFloat32:
- if ((v < -FLT_MAX) || (v > FLT_MAX)) goto _fail;
- return 0;
- case tFloat64:
- return 0;
- case tComplex32:
- if ((v < -FLT_MAX) || (v > FLT_MAX)) goto _fail;
- return 0;
- case tComplex64:
- return 0;
- default:
- PyErr_Format( PyExc_TypeError,
- "Unknown type %d in NA_overflow",
- PyArray_DESCR(a)->type_num );
- PyErr_Print();
- return -1;
- }
-_fail:
- PyErr_Format(PyExc_OverflowError, "value out of range for array");
- return -1;
-}
-
-static int
-_setFromPythonScalarCore(PyArrayObject *a, long offset, PyObject*value, int entries)
-{
- Int64 v;
- if (entries >= 100) {
- PyErr_Format(PyExc_RuntimeError,
- "NA_setFromPythonScalar: __tonumtype__ conversion chain too long");
- return -1;
- } else if (PyInt_Check(value)) {
- v = PyInt_AsLong(value);
- if (NA_overflow(a, v) < 0)
- return -1;
- NA_set_Int64(a, offset, v);
- } else if (PyLong_Check(value)) {
- if (PyArray_DESCR(a)->type_num == tInt64) {
- v = (Int64) PyLong_AsLongLong( value );
- } else if (PyArray_DESCR(a)->type_num == tUInt64) {
- v = (UInt64) PyLong_AsUnsignedLongLong( value );
- } else if (PyArray_DESCR(a)->type_num == tUInt32) {
- v = PyLong_AsUnsignedLong(value);
- } else {
- v = PyLong_AsLongLong(value);
- }
- if (PyErr_Occurred())
- return -1;
- if (NA_overflow(a, v) < 0)
- return -1;
- NA_set_Int64(a, offset, v);
- } else if (PyFloat_Check(value)) {
- Float64 v = PyFloat_AsDouble(value);
- if (NA_overflow(a, v) < 0)
- return -1;
- NA_set_Float64(a, offset, v);
- } else if (PyComplex_Check(value)) {
- Complex64 vc;
- vc.r = PyComplex_RealAsDouble(value);
- vc.i = PyComplex_ImagAsDouble(value);
- if (NA_overflow(a, vc.r) < 0)
- return -1;
- if (NA_overflow(a, vc.i) < 0)
- return -1;
- NA_set_Complex64(a, offset, vc);
- } else if (PyObject_HasAttrString(value, "__tonumtype__")) {
- int rval;
- PyObject *type = NA_typeNoToTypeObject(PyArray_DESCR(a)->type_num);
- if (!type) return -1;
- value = PyObject_CallMethod(
- value, "__tonumtype__", "(N)", type);
- if (!value) return -1;
- rval = _setFromPythonScalarCore(a, offset, value, entries+1);
- Py_DECREF(value);
- return rval;
- } else if (PyBytes_Check(value)) {
- long size = PyBytes_Size(value);
- if ((size <= 0) || (size > 1)) {
- PyErr_Format( PyExc_ValueError,
- "NA_setFromPythonScalar: len(string) must be 1.");
- return -1;
- }
- NA_set_Int64(a, offset, *PyBytes_AsString(value));
- } else {
- PyErr_Format(PyExc_TypeError,
- "NA_setFromPythonScalar: bad value type.");
- return -1;
- }
- return 0;
-}
-
-static int
-NA_setFromPythonScalar(PyArrayObject *a, long offset, PyObject *value)
-{
- if (PyArray_FailUnlessWriteable(a, "array") < 0) {
- return -1;
- }
- return _setFromPythonScalarCore(a, offset, value, 0);
-}
-
-
-static int
-NA_NDArrayCheck(PyObject *obj) {
- return PyArray_Check(obj);
-}
-
-static int
-NA_NumArrayCheck(PyObject *obj) {
- return PyArray_Check(obj);
-}
-
-static int
-NA_ComplexArrayCheck(PyObject *a)
-{
- int rval = NA_NumArrayCheck(a);
- if (rval > 0) {
- PyArrayObject *arr = (PyArrayObject *) a;
- switch(PyArray_DESCR(arr)->type_num) {
- case tComplex64: case tComplex32:
- return 1;
- default:
- return 0;
- }
- }
- return rval;
-}
-
-static unsigned long
-NA_elements(PyArrayObject *a)
-{
- int i;
- unsigned long n = 1;
- for(i = 0; i<PyArray_NDIM(a); i++)
- n *= PyArray_DIMS(a)[i];
- return n;
-}
-
-static int
-NA_typeObjectToTypeNo(PyObject *typeObj)
-{
- PyArray_Descr *dtype;
- int i;
- if (PyArray_DescrConverter(typeObj, &dtype) == NPY_FAIL) i=-1;
- else i=dtype->type_num;
- return i;
-}
-
-static int
-NA_copyArray(PyArrayObject *to, const PyArrayObject *from)
-{
- return PyArray_CopyInto(to, (PyArrayObject *)from);
-}
-
-static PyArrayObject *
-NA_copy(PyArrayObject *from)
-{
- return (PyArrayObject *)PyArray_NewCopy(from, 0);
-}
-
-
-static PyObject *
-NA_getType( PyObject *type)
-{
- PyArray_Descr *typeobj = NULL;
- if (!type && PyArray_DescrConverter(type, &typeobj) == NPY_FAIL) {
- PyErr_Format(PyExc_ValueError, "NA_getType: unknown type.");
- typeobj = NULL;
- }
- return (PyObject *)typeobj;
-}
-
-
-/* Call a standard "stride" function
- **
- ** Stride functions always take one input and one output array.
- ** They can handle n-dimensional data with arbitrary strides (of
- ** either sign) for both the input and output numarray. Typically
- ** these functions are used to copy data, byteswap, or align data.
- **
- **
- ** It expects the following arguments:
- **
- ** Number of iterations for each dimension as a tuple
- ** Input Buffer Object
- ** Offset in bytes for input buffer
- ** Input strides (in bytes) for each dimension as a tuple
- ** Output Buffer Object
- ** Offset in bytes for output buffer
- ** Output strides (in bytes) for each dimension as a tuple
- ** An integer (Optional), typically the number of bytes to copy per
- * element.
- **
- ** Returns None
- **
- ** The arguments expected by the standard stride functions that this
- ** function calls are:
- **
- ** Number of dimensions to iterate over
- ** Long int value (from the optional last argument to
- ** callStrideConvCFunc)
- ** often unused by the C Function
- ** An array of long ints. Each is the number of iterations for each
- ** dimension. NOTE: the previous argument as well as the stride
- ** arguments are reversed in order with respect to how they are
- ** used in Python. Fastest changing dimension is the first element
- ** in the numarray!
- ** A void pointer to the input data buffer.
- ** The starting offset for the input data buffer in bytes (long int).
- ** An array of long int input strides (in bytes) [reversed as with
- ** the iteration array]
- ** A void pointer to the output data buffer.
- ** The starting offset for the output data buffer in bytes (long int).
- ** An array of long int output strides (in bytes) [also reversed]
- */
-
-
-static PyObject *
-NA_callStrideConvCFuncCore(
- PyObject *self, int nshape, maybelong *shape,
- PyObject *inbuffObj, long inboffset,
- int NPY_UNUSED(ninbstrides), maybelong *inbstrides,
- PyObject *outbuffObj, long outboffset,
- int NPY_UNUSED(noutbstrides), maybelong *outbstrides,
- long nbytes)
-{
- CfuncObject *me = (CfuncObject *) self;
- CFUNC_STRIDE_CONV_FUNC funcptr;
- void *inbuffer, *outbuffer;
- long inbsize, outbsize;
- maybelong i, lshape[MAXDIM], in_strides[MAXDIM], out_strides[MAXDIM];
- maybelong shape_0, inbstr_0, outbstr_0;
-
- if (nshape == 0) { /* handle rank-0 numarray. */
- nshape = 1;
- shape = &shape_0;
- inbstrides = &inbstr_0;
- outbstrides = &outbstr_0;
- shape[0] = 1;
- inbstrides[0] = outbstrides[0] = 0;
- }
-
- for(i=0; i<nshape; i++)
- lshape[i] = shape[nshape-1-i];
- for(i=0; i<nshape; i++)
- in_strides[i] = inbstrides[nshape-1-i];
- for(i=0; i<nshape; i++)
- out_strides[i] = outbstrides[nshape-1-i];
-
- if (!PyObject_IsInstance(self , (PyObject *) &CfuncType)
- || me->descr.type != CFUNC_STRIDING)
- return PyErr_Format(PyExc_TypeError,
- "NA_callStrideConvCFuncCore: problem with cfunc");
-
- if ((inbsize = NA_getBufferPtrAndSize(inbuffObj, 1, &inbuffer)) < 0)
- return PyErr_Format(_Error,
- "%s: Problem with input buffer", me->descr.name);
-
- if ((outbsize = NA_getBufferPtrAndSize(outbuffObj, 0, &outbuffer)) < 0)
- return PyErr_Format(_Error,
- "%s: Problem with output buffer (read only?)",
- me->descr.name);
-
- /* Check buffer alignment and bounds */
- if (NA_checkOneStriding(me->descr.name, nshape, lshape,
- inboffset, in_strides, inbsize,
- (me->descr.sizes[0] == -1) ?
- nbytes : me->descr.sizes[0],
- me->descr.align) ||
- NA_checkOneStriding(me->descr.name, nshape, lshape,
- outboffset, out_strides, outbsize,
- (me->descr.sizes[1] == -1) ?
- nbytes : me->descr.sizes[1],
- me->descr.align))
- return NULL;
-
- /* Cast function pointer and perform stride operation */
- funcptr = (CFUNC_STRIDE_CONV_FUNC) me->descr.fptr;
- if ((*funcptr)(nshape-1, nbytes, lshape,
- inbuffer, inboffset, in_strides,
- outbuffer, outboffset, out_strides) == 0) {
- Py_INCREF(Py_None);
- return Py_None;
- } else {
- return NULL;
- }
-}
-
-static void
-NA_stridesFromShape(int nshape, maybelong *shape, maybelong bytestride,
- maybelong *strides)
-{
- int i;
- if (nshape > 0) {
- for(i=0; i<nshape; i++)
- strides[i] = bytestride;
- for(i=nshape-2; i>=0; i--)
- strides[i] = strides[i+1]*shape[i+1];
- }
-}
-
-static int
-NA_OperatorCheck(PyObject *NPY_UNUSED(op)) {
- return 0;
-}
-
-static int
-NA_ConverterCheck(PyObject *NPY_UNUSED(op)) {
- return 0;
-}
-
-static int
-NA_UfuncCheck(PyObject *NPY_UNUSED(op)) {
- return 0;
-}
-
-static int
-NA_CfuncCheck(PyObject *op) {
- return PyObject_TypeCheck(op, &CfuncType);
-}
-
-static int
-NA_getByteOffset(PyArrayObject *NPY_UNUSED(array), int NPY_UNUSED(nindices),
- maybelong *NPY_UNUSED(indices), long *NPY_UNUSED(offset))
-{
- return 0;
-}
-
-static int
-NA_swapAxes(PyArrayObject *array, int x, int y)
-{
- long temp;
-
- if (((PyObject *) array) == Py_None) return 0;
-
- if (PyArray_NDIM(array) < 2) return 0;
-
- if (x < 0) x += PyArray_NDIM(array);
- if (y < 0) y += PyArray_NDIM(array);
-
- if ((x < 0) || (x >= PyArray_NDIM(array)) ||
- (y < 0) || (y >= PyArray_NDIM(array))) {
- PyErr_Format(PyExc_ValueError,
- "Specified dimension does not exist");
- return -1;
- }
-
- temp = PyArray_DIMS(array)[x];
- PyArray_DIMS(array)[x] = PyArray_DIMS(array)[y];
- PyArray_DIMS(array)[y] = temp;
-
- temp = PyArray_STRIDES(array)[x];
- PyArray_STRIDES(array)[x] = PyArray_STRIDES(array)[y];
- PyArray_STRIDES(array)[y] = temp;
-
- PyArray_UpdateFlags(array, NPY_ARRAY_UPDATE_ALL);
-
- return 0;
-}
-
-static PyObject *
-NA_initModuleGlobal(char *modulename, char *globalname)
-{
- PyObject *module, *dict, *global = NULL;
- module = PyImport_ImportModule(modulename);
- if (!module) {
- PyErr_Format(PyExc_RuntimeError,
- "Can't import '%s' module",
- modulename);
- goto _exit;
- }
- dict = PyModule_GetDict(module);
- global = PyDict_GetItemString(dict, globalname);
- if (!global) {
- PyErr_Format(PyExc_RuntimeError,
- "Can't find '%s' global in '%s' module.",
- globalname, modulename);
- goto _exit;
- }
- Py_DECREF(module);
- Py_INCREF(global);
-_exit:
- return global;
-}
-
- NumarrayType
-NA_NumarrayType(PyObject *seq)
-{
- int maxtype = NA_maxType(seq);
- int rval;
- switch(maxtype) {
- case BOOL_SCALAR:
- rval = tBool;
- goto _exit;
- case INT_SCALAR:
- case LONG_SCALAR:
- rval = tLong; /* tLong corresponds to C long int,
- not Python long int */
- goto _exit;
- case FLOAT_SCALAR:
- rval = tFloat64;
- goto _exit;
- case COMPLEX_SCALAR:
- rval = tComplex64;
- goto _exit;
- default:
- PyErr_Format(PyExc_TypeError,
- "expecting Python numeric scalar value; got something else.");
- rval = -1;
- }
-_exit:
- return rval;
-}
-
-/* ignores bytestride */
-static PyArrayObject *
-NA_NewAllFromBuffer(int ndim, maybelong *shape, NumarrayType type,
- PyObject *bufferObject, maybelong byteoffset,
- maybelong NPY_UNUSED(bytestride), int byteorder,
- int NPY_UNUSED(aligned), int NPY_UNUSED(writeable))
-{
- PyArrayObject *self = NULL;
- PyArray_Descr *dtype;
-
- if (type == tAny)
- type = tDefault;
-
- dtype = PyArray_DescrFromType(type);
- if (dtype == NULL) return NULL;
-
- if (byteorder != NA_ByteOrder()) {
- PyArray_Descr *temp;
- temp = PyArray_DescrNewByteorder(dtype, NPY_SWAP);
- Py_DECREF(dtype);
- if (temp == NULL) return NULL;
- dtype = temp;
- }
-
- if (bufferObject == Py_None || bufferObject == NULL) {
- self = (PyArrayObject *) \
- PyArray_NewFromDescr(&PyArray_Type, dtype,
- ndim, shape, NULL, NULL,
- 0, NULL);
- }
- else {
- npy_intp size = 1;
- int i;
- PyArrayObject *newself;
- PyArray_Dims newdims;
- for(i=0; i<ndim; i++) {
- size *= shape[i];
- }
- self = (PyArrayObject *)\
- PyArray_FromBuffer(bufferObject, dtype,
- size, byteoffset);
-
- if (self == NULL) return self;
- newdims.len = ndim;
- newdims.ptr = shape;
- newself = (PyArrayObject *)\
- PyArray_Newshape(self, &newdims, NPY_CORDER);
- Py_DECREF(self);
- self = newself;
- }
-
- return self;
-}
-
-static void
-NA_updateAlignment(PyArrayObject *self)
-{
- PyArray_UpdateFlags(self, NPY_ARRAY_ALIGNED);
-}
-
-static void
-NA_updateContiguous(PyArrayObject *self)
-{
- PyArray_UpdateFlags(self, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS);
-}
-
-
-static void
-NA_updateStatus(PyArrayObject *self)
-{
- PyArray_UpdateFlags(self, NPY_ARRAY_UPDATE_ALL);
-}
-
-static int
-NA_NumArrayCheckExact(PyObject *op) {
- return (op->ob_type == &PyArray_Type);
-}
-
-static int
-NA_NDArrayCheckExact(PyObject *op) {
- return (op->ob_type == &PyArray_Type);
-}
-
-static int
-NA_OperatorCheckExact(PyObject *NPY_UNUSED(op)) {
- return 0;
-}
-
-static int
-NA_ConverterCheckExact(PyObject *NPY_UNUSED(op)) {
- return 0;
-}
-
-static int
-NA_UfuncCheckExact(PyObject *NPY_UNUSED(op)) {
- return 0;
-}
-
-
-static int
-NA_CfuncCheckExact(PyObject *op) {
- return op->ob_type == &CfuncType;
-}
-
-static char *
-NA_getArrayData(PyArrayObject *obj)
-{
- if (!NA_NDArrayCheck((PyObject *) obj)) {
- PyErr_Format(PyExc_TypeError,
- "expected an NDArray");
- }
- return PyArray_DATA(obj);
-}
-
-/* Byteswap is not a flag of the array --- it is implicit in the data-type */
-static void
-NA_updateByteswap(PyArrayObject *NPY_UNUSED(self))
-{
- return;
-}
-
-static PyArray_Descr *
-NA_DescrFromType(int type)
-{
- if (type == tAny)
- type = tDefault;
- return PyArray_DescrFromType(type);
-}
-
-static PyObject *
-NA_Cast(PyArrayObject *a, int type)
-{
- return PyArray_Cast(a, type);
-}
-
-
-/* The following function has much platform dependent code since
- ** there is no platform-independent way of checking Floating Point
- ** status bits
- */
-
-/* OSF/Alpha (Tru64) ---------------------------------------------*/
-#if defined(__osf__) && defined(__alpha)
-
-static int
-NA_checkFPErrors(void)
-{
- unsigned long fpstatus;
- int retstatus;
-
-#include <machine/fpu.h> /* Should migrate to global scope */
-
- fpstatus = ieee_get_fp_control();
- /* clear status bits as well as disable exception mode if on */
- ieee_set_fp_control( 0 );
- retstatus =
- pyFPE_DIVIDE_BY_ZERO* (int)((IEEE_STATUS_DZE & fpstatus) != 0)
- + pyFPE_OVERFLOW * (int)((IEEE_STATUS_OVF & fpstatus) != 0)
- + pyFPE_UNDERFLOW * (int)((IEEE_STATUS_UNF & fpstatus) != 0)
- + pyFPE_INVALID * (int)((IEEE_STATUS_INV & fpstatus) != 0);
-
- return retstatus;
-}
-
-/* MS Windows -----------------------------------------------------*/
-#elif defined(_MSC_VER)
-
-#include <float.h>
-
-static int
-NA_checkFPErrors(void)
-{
- int fpstatus = (int) _clear87();
- int retstatus =
- pyFPE_DIVIDE_BY_ZERO * ((SW_ZERODIVIDE & fpstatus) != 0)
- + pyFPE_OVERFLOW * ((SW_OVERFLOW & fpstatus) != 0)
- + pyFPE_UNDERFLOW * ((SW_UNDERFLOW & fpstatus) != 0)
- + pyFPE_INVALID * ((SW_INVALID & fpstatus) != 0);
-
-
- return retstatus;
-}
-
-/* Solaris --------------------------------------------------------*/
-/* --------ignoring SunOS ieee_flags approach, someone else can
- ** deal with that! */
-#elif defined(sun)
-#include <ieeefp.h>
-
-static int
-NA_checkFPErrors(void)
-{
- int fpstatus;
- int retstatus;
-
- fpstatus = (int) fpgetsticky();
- retstatus = pyFPE_DIVIDE_BY_ZERO * ((FP_X_DZ & fpstatus) != 0)
- + pyFPE_OVERFLOW * ((FP_X_OFL & fpstatus) != 0)
- + pyFPE_UNDERFLOW * ((FP_X_UFL & fpstatus) != 0)
- + pyFPE_INVALID * ((FP_X_INV & fpstatus) != 0);
- (void) fpsetsticky(0);
-
- return retstatus;
-}
-
-#elif defined(__GLIBC__) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__MINGW32__) || (defined(__FreeBSD__) && (__FreeBSD_version >= 502114))
-
-static int
-NA_checkFPErrors(void)
-{
- int fpstatus = (int) fetestexcept(
- FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW | FE_INVALID);
- int retstatus =
- pyFPE_DIVIDE_BY_ZERO * ((FE_DIVBYZERO & fpstatus) != 0)
- + pyFPE_OVERFLOW * ((FE_OVERFLOW & fpstatus) != 0)
- + pyFPE_UNDERFLOW * ((FE_UNDERFLOW & fpstatus) != 0)
- + pyFPE_INVALID * ((FE_INVALID & fpstatus) != 0);
- (void) feclearexcept(FE_DIVBYZERO | FE_OVERFLOW |
- FE_UNDERFLOW | FE_INVALID);
- return retstatus;
-}
-
-#else
-
-static int
-NA_checkFPErrors(void)
-{
- return 0;
-}
-
-#endif
-
-static void
-NA_clearFPErrors()
-{
- NA_checkFPErrors();
-}
-
-/* Not supported yet */
-static int
-NA_checkAndReportFPErrors(char *name)
-{
- int error = NA_checkFPErrors();
- if (error) {
- PyObject *ans;
- char msg[128];
- strcpy(msg, " in ");
- strncat(msg, name, 100);
- ans = PyObject_CallFunction(pHandleErrorFunc, "(is)", error, msg);
- if (!ans) return -1;
- Py_DECREF(ans); /* Py_None */
- }
- return 0;
-
-}
-
-
-#define WITHIN32(v, f) (((v) >= f##_MIN32) && ((v) <= f##_MAX32))
-#define WITHIN64(v, f) (((v) >= f##_MIN64) && ((v) <= f##_MAX64))
-
-static Bool
-NA_IeeeMask32( Float32 f, Int32 mask)
-{
- Int32 category;
- UInt32 v = *(UInt32 *) &f;
-
- if (v & BIT(31)) {
- if (WITHIN32(v, NEG_NORMALIZED)) {
- category = MSK_NEG_NOR;
- } else if (WITHIN32(v, NEG_DENORMALIZED)) {
- category = MSK_NEG_DEN;
- } else if (WITHIN32(v, NEG_SIGNAL_NAN)) {
- category = MSK_NEG_SNAN;
- } else if (WITHIN32(v, NEG_QUIET_NAN)) {
- category = MSK_NEG_QNAN;
- } else if (v == NEG_INFINITY_MIN32) {
- category = MSK_NEG_INF;
- } else if (v == NEG_ZERO_MIN32) {
- category = MSK_NEG_ZERO;
- } else if (v == INDETERMINATE_MIN32) {
- category = MSK_INDETERM;
- } else {
- category = MSK_BUG;
- }
- } else {
- if (WITHIN32(v, POS_NORMALIZED)) {
- category = MSK_POS_NOR;
- } else if (WITHIN32(v, POS_DENORMALIZED)) {
- category = MSK_POS_DEN;
- } else if (WITHIN32(v, POS_SIGNAL_NAN)) {
- category = MSK_POS_SNAN;
- } else if (WITHIN32(v, POS_QUIET_NAN)) {
- category = MSK_POS_QNAN;
- } else if (v == POS_INFINITY_MIN32) {
- category = MSK_POS_INF;
- } else if (v == POS_ZERO_MIN32) {
- category = MSK_POS_ZERO;
- } else {
- category = MSK_BUG;
- }
- }
- return (category & mask) != 0;
-}
-
-static Bool
-NA_IeeeMask64( Float64 f, Int32 mask)
-{
- Int32 category;
- UInt64 v = *(UInt64 *) &f;
-
- if (v & BIT(63)) {
- if (WITHIN64(v, NEG_NORMALIZED)) {
- category = MSK_NEG_NOR;
- } else if (WITHIN64(v, NEG_DENORMALIZED)) {
- category = MSK_NEG_DEN;
- } else if (WITHIN64(v, NEG_SIGNAL_NAN)) {
- category = MSK_NEG_SNAN;
- } else if (WITHIN64(v, NEG_QUIET_NAN)) {
- category = MSK_NEG_QNAN;
- } else if (v == NEG_INFINITY_MIN64) {
- category = MSK_NEG_INF;
- } else if (v == NEG_ZERO_MIN64) {
- category = MSK_NEG_ZERO;
- } else if (v == INDETERMINATE_MIN64) {
- category = MSK_INDETERM;
- } else {
- category = MSK_BUG;
- }
- } else {
- if (WITHIN64(v, POS_NORMALIZED)) {
- category = MSK_POS_NOR;
- } else if (WITHIN64(v, POS_DENORMALIZED)) {
- category = MSK_POS_DEN;
- } else if (WITHIN64(v, POS_SIGNAL_NAN)) {
- category = MSK_POS_SNAN;
- } else if (WITHIN64(v, POS_QUIET_NAN)) {
- category = MSK_POS_QNAN;
- } else if (v == POS_INFINITY_MIN64) {
- category = MSK_POS_INF;
- } else if (v == POS_ZERO_MIN64) {
- category = MSK_POS_ZERO;
- } else {
- category = MSK_BUG;
- }
- }
- return (category & mask) != 0;
-}
-
-static PyArrayObject *
-NA_FromDimsStridesDescrAndData(int nd, maybelong *d, maybelong *s, PyArray_Descr *descr, char *data)
-{
- return (PyArrayObject *)\
- PyArray_NewFromDescr(&PyArray_Type, descr, nd, d,
- s, data, 0, NULL);
-}
-
-static PyArrayObject *
-NA_FromDimsTypeAndData(int nd, maybelong *d, int type, char *data)
-{
- PyArray_Descr *descr = NA_DescrFromType(type);
- return NA_FromDimsStridesDescrAndData(nd, d, NULL, descr, data);
-}
-
-static PyArrayObject *
-NA_FromDimsStridesTypeAndData(int nd, maybelong *shape, maybelong *strides,
- int type, char *data)
-{
- PyArray_Descr *descr = NA_DescrFromType(type);
- return NA_FromDimsStridesDescrAndData(nd, shape, strides, descr, data);
-}
-
-
-typedef struct
-{
- NumarrayType type_num;
- char suffix[5];
- int itemsize;
-} scipy_typestr;
-
-static scipy_typestr scipy_descriptors[ ] = {
- { tAny, "", 0},
-
- { tBool, "b1", 1},
-
- { tInt8, "i1", 1},
- { tUInt8, "u1", 1},
-
- { tInt16, "i2", 2},
- { tUInt16, "u2", 2},
-
- { tInt32, "i4", 4},
- { tUInt32, "u4", 4},
-
- { tInt64, "i8", 8},
- { tUInt64, "u8", 8},
-
- { tFloat32, "f4", 4},
- { tFloat64, "f8", 8},
-
- { tComplex32, "c8", 8},
- { tComplex64, "c16", 16}
-};
-
-
-static int
-NA_scipy_typestr(NumarrayType t, int byteorder, char *typestr)
-{
- size_t i;
- if (byteorder)
- strcpy(typestr, ">");
- else
- strcpy(typestr, "<");
- for(i=0; i<ELEM(scipy_descriptors); i++) {
- scipy_typestr *ts = &scipy_descriptors[i];
- if (ts->type_num == t) {
- strncat(typestr, ts->suffix, 4);
- return 0;
- }
- }
- return -1;
-}
-
-static PyArrayObject *
-NA_FromArrayStruct(PyObject *obj)
-{
- return (PyArrayObject *)PyArray_FromStructInterface(obj);
-}
-
-
-static PyObject *_Error;
-
-void *libnumarray_API[] = {
- (void*) getBuffer,
- (void*) isBuffer,
- (void*) getWriteBufferDataPtr,
- (void*) isBufferWriteable,
- (void*) getReadBufferDataPtr,
- (void*) getBufferSize,
- (void*) num_log,
- (void*) num_log10,
- (void*) num_pow,
- (void*) num_acosh,
- (void*) num_asinh,
- (void*) num_atanh,
- (void*) num_round,
- (void*) int_dividebyzero_error,
- (void*) int_overflow_error,
- (void*) umult64_overflow,
- (void*) smult64_overflow,
- (void*) NA_Done,
- (void*) NA_NewAll,
- (void*) NA_NewAllStrides,
- (void*) NA_New,
- (void*) NA_Empty,
- (void*) NA_NewArray,
- (void*) NA_vNewArray,
- (void*) NA_ReturnOutput,
- (void*) NA_getBufferPtrAndSize,
- (void*) NA_checkIo,
- (void*) NA_checkOneCBuffer,
- (void*) NA_checkNCBuffers,
- (void*) NA_checkOneStriding,
- (void*) NA_new_cfunc,
- (void*) NA_add_cfunc,
- (void*) NA_InputArray,
- (void*) NA_OutputArray,
- (void*) NA_IoArray,
- (void*) NA_OptionalOutputArray,
- (void*) NA_get_offset,
- (void*) NA_get_Float64,
- (void*) NA_set_Float64,
- (void*) NA_get_Complex64,
- (void*) NA_set_Complex64,
- (void*) NA_get_Int64,
- (void*) NA_set_Int64,
- (void*) NA_get1_Float64,
- (void*) NA_get2_Float64,
- (void*) NA_get3_Float64,
- (void*) NA_set1_Float64,
- (void*) NA_set2_Float64,
- (void*) NA_set3_Float64,
- (void*) NA_get1_Complex64,
- (void*) NA_get2_Complex64,
- (void*) NA_get3_Complex64,
- (void*) NA_set1_Complex64,
- (void*) NA_set2_Complex64,
- (void*) NA_set3_Complex64,
- (void*) NA_get1_Int64,
- (void*) NA_get2_Int64,
- (void*) NA_get3_Int64,
- (void*) NA_set1_Int64,
- (void*) NA_set2_Int64,
- (void*) NA_set3_Int64,
- (void*) NA_get1D_Float64,
- (void*) NA_set1D_Float64,
- (void*) NA_get1D_Int64,
- (void*) NA_set1D_Int64,
- (void*) NA_get1D_Complex64,
- (void*) NA_set1D_Complex64,
- (void*) NA_ShapeEqual,
- (void*) NA_ShapeLessThan,
- (void*) NA_ByteOrder,
- (void*) NA_IeeeSpecial32,
- (void*) NA_IeeeSpecial64,
- (void*) NA_updateDataPtr,
- (void*) NA_typeNoToName,
- (void*) NA_nameToTypeNo,
- (void*) NA_typeNoToTypeObject,
- (void*) NA_intTupleFromMaybeLongs,
- (void*) NA_maybeLongsFromIntTuple,
- (void*) NA_intTupleProduct,
- (void*) NA_isIntegerSequence,
- (void*) NA_setArrayFromSequence,
- (void*) NA_maxType,
- (void*) NA_isPythonScalar,
- (void*) NA_getPythonScalar,
- (void*) NA_setFromPythonScalar,
- (void*) NA_NDArrayCheck,
- (void*) NA_NumArrayCheck,
- (void*) NA_ComplexArrayCheck,
- (void*) NA_elements,
- (void*) NA_typeObjectToTypeNo,
- (void*) NA_copyArray,
- (void*) NA_copy,
- (void*) NA_getType,
- (void*) NA_callCUFuncCore,
- (void*) NA_callStrideConvCFuncCore,
- (void*) NA_stridesFromShape,
- (void*) NA_OperatorCheck,
- (void*) NA_ConverterCheck,
- (void*) NA_UfuncCheck,
- (void*) NA_CfuncCheck,
- (void*) NA_getByteOffset,
- (void*) NA_swapAxes,
- (void*) NA_initModuleGlobal,
- (void*) NA_NumarrayType,
- (void*) NA_NewAllFromBuffer,
- (void*) NA_alloc1D_Float64,
- (void*) NA_alloc1D_Int64,
- (void*) NA_updateAlignment,
- (void*) NA_updateContiguous,
- (void*) NA_updateStatus,
- (void*) NA_NumArrayCheckExact,
- (void*) NA_NDArrayCheckExact,
- (void*) NA_OperatorCheckExact,
- (void*) NA_ConverterCheckExact,
- (void*) NA_UfuncCheckExact,
- (void*) NA_CfuncCheckExact,
- (void*) NA_getArrayData,
- (void*) NA_updateByteswap,
- (void*) NA_DescrFromType,
- (void*) NA_Cast,
- (void*) NA_checkFPErrors,
- (void*) NA_clearFPErrors,
- (void*) NA_checkAndReportFPErrors,
- (void*) NA_IeeeMask32,
- (void*) NA_IeeeMask64,
- (void*) _NA_callStridingHelper,
- (void*) NA_FromDimsStridesDescrAndData,
- (void*) NA_FromDimsTypeAndData,
- (void*) NA_FromDimsStridesTypeAndData,
- (void*) NA_scipy_typestr,
- (void*) NA_FromArrayStruct
-};
-
-#if (!defined(METHOD_TABLE_EXISTS))
-static PyMethodDef _libnumarrayMethods[] = {
- {NULL, NULL, 0, NULL} /* Sentinel */
-};
-#endif
-
-/* boiler plate API init */
-#if defined(NPY_PY3K)
-
-#define RETVAL m
-
-static struct PyModuleDef moduledef = {
- PyModuleDef_HEAD_INIT,
- "_capi",
- NULL,
- -1,
- _libnumarrayMethods,
- NULL,
- NULL,
- NULL,
- NULL
-};
-
-PyMODINIT_FUNC PyInit__capi(void)
-#else
-
-#define RETVAL
-
-PyMODINIT_FUNC init_capi(void)
-#endif
-{
- PyObject *m;
- PyObject *c_api_object;
-
- _Error = PyErr_NewException("numpy.numarray._capi.error", NULL, NULL);
-
- /* Create a CObject containing the API pointer array's address */
-#if defined(NPY_PY3K)
- m = PyModule_Create(&moduledef);
-#else
- m = Py_InitModule("_capi", _libnumarrayMethods);
-#endif
-
-#if defined(NPY_PY3K)
- c_api_object = PyCapsule_New((void *)libnumarray_API, NULL, NULL);
- if (c_api_object == NULL) {
- PyErr_Clear();
- }
-#else
- c_api_object = PyCObject_FromVoidPtr((void *)libnumarray_API, NULL);
-#endif
-
- if (c_api_object != NULL) {
- /* Create a name for this object in the module's namespace */
- PyObject *d = PyModule_GetDict(m);
-
- PyDict_SetItemString(d, "_C_API", c_api_object);
- PyDict_SetItemString(d, "error", _Error);
- Py_DECREF(c_api_object);
- }
- else {
- return RETVAL;
- }
- if (PyModule_AddObject(m, "__version__", PyUString_FromString("0.9")) < 0) {
- return RETVAL;
- }
- if (_import_array() < 0) {
- return RETVAL;
- }
- deferred_libnumarray_init();
- return RETVAL;
-}
diff --git a/numpy/numarray/alter_code1.py b/numpy/numarray/alter_code1.py
deleted file mode 100644
index ff50d7c50..000000000
--- a/numpy/numarray/alter_code1.py
+++ /dev/null
@@ -1,267 +0,0 @@
-"""
-This module converts code written for numarray to run with numpy
-
-Makes the following changes:
- * Changes import statements
-
- 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 <yyy> --> import numpy.numarray.package as <yyy>
-
- from numarray import <xxx> --> from numpy.numarray import <xxx>
- from numarray.package import <xxx>
- --> from numpy.numarray.package import <xxx>
-
- 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)
- - .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(type) --> numarray.newobj(self, type)
- - .repeat(r) --> .repeat(r, axis=0)
- - .size() --> .size
- - self.type() -- numarray.typefrom(self)
- - .typecode() --> .dtype.char
- - .stddev() --> .std()
- - .togglebyteorder() --> numarray.togglebyteorder(self)
- - .getshape() --> .shape
- - .setshape(obj) --> .shape=obj
- - .getflat() --> .ravel()
- - .getreal() --> .real
- - .setreal() --> .real =
- - .getimag() --> .imag
- - .setimag() --> .imag =
- - .getimaginary() --> .imag
- - .setimaginary() --> .imag
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc']
-
-import sys
-import os
-import re
-import glob
-
-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 = re.sub(r'(import\s+[^,\n\r]+,\s*)(%s)' % name,
- "\\1%s as %s" % (newname, name), fstr)
- fstr = fstr.replace(importasstr, 'import %s as ' % newname)
- fstr = fstr.replace(importstr, 'import %s as %s' % (newname, name_))
- if (name_ != name):
- fstr = fstr.replace(name, name_)
-
- ind = 0
- Nlen = len(fromstr)
- Nlen2 = len("from %s import " % newname)
- while True:
- 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
-
-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(".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(".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
- tmpstr = tmpstr.replace(".flat", ".ravel()")
- # put back .flat where it was valid
- astr = tmpstr.replace("@@@@", ".flat")
- return astr
-
-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):
- # 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):
- savestr = filestr[:]
- 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)
- if savestr != filestr:
- name = os.path.split(sys.argv[0])[-1]
- today = datetime.date.today().strftime('%b %d, %Y')
- filestr = '## Automatically adapted for '\
- 'numpy.numarray %s by %s\n\n%s' % (today, name, filestr)
- return filestr, 1
- return filestr, 0
-
-def makenewfile(name, filestr):
- fid = file(name, 'w')
- fid.write(filestr)
- fid.close()
-
-def convertfile(filename, orig=1):
- """Convert the filename given from using Numarray to using NumPy
-
- Copies the file to filename.orig and then over-writes the file
- with the updated code
- """
- fid = open(filename)
- filestr = fid.read()
- fid.close()
- filestr, changed = fromstr(filestr)
- if changed:
- if orig:
- base, ext = os.path.splitext(filename)
- os.rename(filename, base+".orig")
- else:
- os.remove(filename)
- makenewfile(filename, filestr)
-
-def fromargs(args):
- filename = args[1]
- convertfile(filename)
-
-def convertall(direc=os.path.curdir, orig=1):
- """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given
-
- For each file, a backup of <usesnumeric>.py is made as
- <usesnumeric>.py.orig. A new file named <usesnumeric>.py
- is then written with the updated code.
- """
- files = glob.glob(os.path.join(direc, '*.py'))
- for afile in files:
- if afile[-8:] == 'setup.py': continue
- convertfile(afile, orig)
-
-header_re = re.compile(r'(numarray/libnumarray.h)')
-
-def convertsrc(direc=os.path.curdir, ext=None, orig=1):
- """Replace Numeric/arrayobject.h with numpy/oldnumeric.h in all files in the
- directory with extension give by list ext (if ext is None, then all files are
- replaced)."""
- if ext is None:
- files = glob.glob(os.path.join(direc, '*'))
- else:
- files = []
- for aext in ext:
- files.extend(glob.glob(os.path.join(direc, "*.%s" % aext)))
- for afile in files:
- fid = open(afile)
- fstr = fid.read()
- fid.close()
- fstr, n = header_re.subn(r'numpy/libnumarray.h', fstr)
- if n > 0:
- if orig:
- base, ext = os.path.splitext(afile)
- os.rename(afile, base+".orig")
- else:
- os.remove(afile)
- makenewfile(afile, fstr)
-
-def _func(arg, dirname, fnames):
- convertall(dirname, orig=0)
- convertsrc(dirname, ['h', 'c'], orig=0)
-
-def converttree(direc=os.path.curdir):
- """Convert all .py files in the tree given
-
- """
- os.path.walk(direc, _func, None)
-
-
-if __name__ == '__main__':
- converttree(sys.argv)
diff --git a/numpy/numarray/alter_code2.py b/numpy/numarray/alter_code2.py
deleted file mode 100644
index 5771a7285..000000000
--- a/numpy/numarray/alter_code2.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""
-This module converts code written for numpy.numarray to work
-with numpy
-
-FIXME: finish this.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = []
-
-import warnings
-warnings.warn("numpy.numarray.alter_code2 is not working yet.")
-import sys
-
-import os
-import glob
-
-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 <usesnumeric>.py is made as
- <usesnumeric>.py.orig. A new file named <usesnumeric>.py
- is then written with the updated code.
- """
- files = glob.glob(os.path.join(direc, '*.py'))
- for afile in files:
- convertfile(afile)
-
-def _func(arg, dirname, fnames):
- convertall(dirname)
-
-def converttree(direc=os.path.curdir):
- """Convert all .py files in the tree given
-
- """
- os.path.walk(direc, _func, None)
-
-
-if __name__ == '__main__':
- fromargs(sys.argv)
diff --git a/numpy/numarray/compat.py b/numpy/numarray/compat.py
deleted file mode 100644
index 2289af04c..000000000
--- a/numpy/numarray/compat.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['NewAxis', 'ArrayType']
-
-from numpy import newaxis as NewAxis, ndarray as ArrayType
diff --git a/numpy/numarray/convolve.py b/numpy/numarray/convolve.py
deleted file mode 100644
index b2ff3bd13..000000000
--- a/numpy/numarray/convolve.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-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)
diff --git a/numpy/numarray/fft.py b/numpy/numarray/fft.py
deleted file mode 100644
index 407ad7c5b..000000000
--- a/numpy/numarray/fft.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-from numpy.oldnumeric.fft import *
-import numpy.oldnumeric.fft as nof
-
-__all__ = nof.__all__
-
-del nof
diff --git a/numpy/numarray/functions.py b/numpy/numarray/functions.py
deleted file mode 100644
index f37e0f054..000000000
--- a/numpy/numarray/functions.py
+++ /dev/null
@@ -1,500 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-# missing Numarray defined names (in from numarray import *)
-
-__all__ = ['asarray', 'ones', 'zeros', 'array', 'where']
-__all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices',
- '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', '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', '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', 'newobj',
- 'togglebyteorder'
- ]
-
-import copy
-import types
-import os
-import sys
-import math
-import operator
-
-import numpy as np
-from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\
- allclose, any, argsort, array_equal, array_equiv,\
- array_str, array_repr, CLIP, RAISE, WRAP, clip, concatenate, \
- diagonal, e, pi, inner as innerproduct, nonzero, \
- outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \
- resize, searchsorted, shape, size, sort, swapaxes, trace, transpose
-from numpy.compat import long
-from .numerictypes import typefrom
-
-if sys.version_info[0] >= 3:
- import copyreg as copy_reg
-else:
- import copy_reg
-
-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 = np.dtype(typecode)
- else:
- dtype = np.dtype(type)
- if use_default and dtype is None:
- dtype = np.dtype('int')
- return dtype
-
-def fromfunction(shape, dimensions, type=None, typecode=None, dtype=None):
- dtype = type2dtype(typecode, type, dtype, 1)
- return np.fromfunction(shape, dimensions, dtype=dtype)
-def ones(shape, type=None, typecode=None, dtype=None):
- dtype = type2dtype(typecode, type, dtype, 1)
- return np.ones(shape, dtype)
-
-def zeros(shape, type=None, typecode=None, dtype=None):
- dtype = type2dtype(typecode, type, dtype, 1)
- return np.zeros(shape, dtype)
-
-def where(condition, x=None, y=None, out=None):
- if x is None and y is None:
- arr = np.where(condition)
- else:
- arr = np.where(condition, x, y)
- if out is not None:
- out[...] = arr
- return out
- return arr
-
-def indices(shape, type=None):
- return np.indices(shape, type)
-
-def arange(a1, a2=None, stride=1, type=None, shape=None,
- typecode=None, dtype=None):
- dtype = type2dtype(typecode, type, dtype, 0)
- return np.arange(a1, a2, stride, dtype)
-
-arrayrange = arange
-
-def alltrue(x, axis=0):
- return np.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 = np.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 = np.asarray(selector)
- ret = a.choose(population, out=outarr, mode=clipmode)
- if outarr is None:
- return ret
- return
-
-def compress(condition, a, axis=0):
- return np.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 = list(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 = np.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 = int(dtype.itemsize * np.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 = np.newbuffer(initsize)
-
- bytesread=0
- while True:
- 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 = np.ndarray(shape=shape, dtype=type, buffer=buf)
- if a.dtype.char == '?':
- np.not_equal(a, 0, a)
- return a
-
-
-# this function is referenced in the code above but not defined. adding
-# it back. - phensley
-def _resizebuf(buf, newsize):
- "Return a copy of BUF of size NEWSIZE."
- newbuf = np.newbuffer(newsize)
- if newsize > len(buf):
- newbuf[:len(buf)]=buf
- else:
- newbuf[:]=buf[:len(newbuf)]
- return newbuf
-
-
-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 = np.product(shape)
- res = np.fromstring(datastring, dtype=dtype, 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 np.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 np.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 = np.frombuffer(sequence, dtype=dtype)
- else:
- arr = np.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, np.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(np.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 = np.array(shape)
- if not issubclass(dummy.dtype.type, np.integer):
- raise TypeError
- if len(dummy) > np.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 np.identity(n, dtype)
-
-def info(obj, output=sys.stdout, numpy=0):
- if numpy:
- bp = lambda x: x
- else:
- bp = lambda x: int(x)
- cls = getattr(obj, '__class__', type(obj))
- if numpy:
- nm = getattr(cls, '__name__', cls)
- else:
- nm = cls
- print("class: ", nm, file=output)
- print("shape: ", obj.shape, file=output)
- strides = obj.strides
- print("strides: ", strides, file=output)
- if not numpy:
- print("byteoffset: 0", file=output)
- if len(strides) > 0:
- bs = obj.strides[0]
- else:
- bs = obj.itemsize
- print("bytestride: ", bs, file=output)
- print("itemsize: ", obj.itemsize, file=output)
- print("aligned: ", bp(obj.flags.aligned), file=output)
- print("contiguous: ", bp(obj.flags.contiguous), file=output)
- if numpy:
- print("fortran: ", obj.flags.fortran, file=output)
- if not numpy:
- print("buffer: ", repr(obj.data), file=output)
- if not numpy:
- extra = " (DEBUG ONLY)"
- tic = "'"
- else:
- extra = ""
- tic = ""
- print("data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra), file=output)
- print("byteorder: ", end=' ', file=output)
- endian = obj.dtype.byteorder
- if endian in ['|', '=']:
- print("%s%s%s" % (tic, sys.byteorder, tic), file=output)
- byteswap = False
- elif endian == '>':
- print("%sbig%s" % (tic, tic), file=output)
- byteswap = sys.byteorder != "big"
- else:
- print("%slittle%s" % (tic, tic), file=output)
- byteswap = sys.byteorder != "little"
- print("byteswap: ", bp(byteswap), file=output)
- if not numpy:
- print("type: ", typefrom(obj).name, file=output)
- else:
- print("type: %s" % obj.dtype, file=output)
-
-#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, np.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, np.integer)):
- work = work.swapaxes(0, axis)
- work[indices] = values
- work = work.swapaxes(0, axis)
- else:
- def_axes = list(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 np.repeat(array, repeats, axis)
-
-
-def reshape(array, shape, *args):
- if len(args) > 0:
- shape = (shape,) + args
- return np.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 np.sometrue(array, axis)
-
-#clipmode is ignored if axis is not an integer
-def take(array, indices, axis=0, outarr=None, clipmode=RAISE):
- array = np.asarray(array)
- if isinstance(axis, (int, long, np.integer)):
- res = array.take(indices, axis, outarr, clipmode)
- if outarr is None:
- return res
- return
- else:
- def_axes = list(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
- outarr[...] = res
- return
-
-def tensormultiply(a1, a2):
- a1, a2 = np.asarray(a1), np.asarray(a2)
- if (a1.shape[-1] != a2.shape[0]):
- raise ValueError("Unmatched dimensions")
- shape = a1.shape[:-1] + a2.shape[1:]
- return np.reshape(dot(np.reshape(a1, (-1, a1.shape[-1])),
- np.reshape(a2, (a2.shape[0], -1))),
- shape)
-
-def cumsum(a1, axis=0, out=None, type=None, dim=0):
- return np.asarray(a1).cumsum(axis, dtype=type, out=out)
-
-def cumproduct(a1, axis=0, out=None, type=None, dim=0):
- return np.asarray(a1).cumprod(axis, dtype=type, out=out)
-
-def argmax(x, axis=-1):
- return np.argmax(x, axis)
-
-def argmin(x, axis=-1):
- return np.argmin(x, axis)
-
-def newobj(self, type):
- if type is None:
- return np.empty_like(self)
- else:
- return np.empty(self.shape, type)
-
-def togglebyteorder(self):
- self.dtype=self.dtype.newbyteorder()
-
-def average(a, axis=0, weights=None, returned=0):
- return np.average(a, axis, weights, returned)
diff --git a/numpy/numarray/image.py b/numpy/numarray/image.py
deleted file mode 100644
index 063e51376..000000000
--- a/numpy/numarray/image.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-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)
diff --git a/numpy/numarray/include/numpy/arraybase.h b/numpy/numarray/include/numpy/arraybase.h
deleted file mode 100644
index 02430b08a..000000000
--- a/numpy/numarray/include/numpy/arraybase.h
+++ /dev/null
@@ -1,71 +0,0 @@
-#if !defined(__arraybase_h)
-#define _arraybase_h 1
-
-#define SZ_BUF 79
-#define MAXDIM NPY_MAXDIMS
-#define MAXARGS 18
-
-typedef npy_intp maybelong;
-typedef npy_bool Bool;
-typedef npy_int8 Int8;
-typedef npy_uint8 UInt8;
-typedef npy_int16 Int16;
-typedef npy_uint16 UInt16;
-typedef npy_int32 Int32;
-typedef npy_uint32 UInt32;
-typedef npy_int64 Int64;
-typedef npy_uint64 UInt64;
-typedef npy_float32 Float32;
-typedef npy_float64 Float64;
-
-typedef enum
-{
- tAny = -1,
- tBool = NPY_BOOL,
- tInt8 = NPY_INT8,
- tUInt8 = NPY_UINT8,
- tInt16 = NPY_INT16,
- tUInt16 = NPY_UINT16,
- tInt32 = NPY_INT32,
- tUInt32 = NPY_UINT32,
- tInt64 = NPY_INT64,
- tUInt64 = NPY_UINT64,
- tFloat32 = NPY_FLOAT32,
- tFloat64 = NPY_FLOAT64,
- tComplex32 = NPY_COMPLEX64,
- tComplex64 = NPY_COMPLEX128,
- tObject = NPY_OBJECT, /* placeholder... does nothing */
- tMaxType = NPY_NTYPES,
- tDefault = tFloat64,
-#if NPY_BITSOF_LONG == 64
- tLong = tInt64,
-#else
- tLong = tInt32,
-#endif
-} NumarrayType;
-
-#define nNumarrayType PyArray_NTYPES
-
-#define HAS_UINT64 1
-
-typedef enum
-{
- NUM_LITTLE_ENDIAN=0,
- NUM_BIG_ENDIAN = 1
-} NumarrayByteOrder;
-
-typedef struct { Float32 r, i; } Complex32;
-typedef struct { Float64 r, i; } Complex64;
-
-#define WRITABLE NPY_WRITEABLE
-#define CHECKOVERFLOW 0x800
-#define UPDATEDICT 0x1000
-#define FORTRAN_CONTIGUOUS NPY_FORTRAN
-#define IS_CARRAY (NPY_CONTIGUOUS | NPY_ALIGNED)
-
-#define PyArray(m) ((PyArrayObject *)(m))
-#define PyArray_ISFORTRAN_CONTIGUOUS(m) (((PyArray(m))->flags & FORTRAN_CONTIGUOUS) != 0)
-#define PyArray_ISWRITABLE PyArray_ISWRITEABLE
-
-
-#endif
diff --git a/numpy/numarray/include/numpy/cfunc.h b/numpy/numarray/include/numpy/cfunc.h
deleted file mode 100644
index 1c03c2100..000000000
--- a/numpy/numarray/include/numpy/cfunc.h
+++ /dev/null
@@ -1,77 +0,0 @@
-#if !defined(__cfunc__)
-#define __cfunc__ 1
-
-typedef PyObject *(*CFUNCasPyValue)(void *);
-typedef int (*UFUNC)(long, long, long, void **, long*);
-/* typedef void (*CFUNC_2ARG)(long, void *, void *); */
-/* typedef void (*CFUNC_3ARG)(long, void *, void *, void *); */
-typedef int (*CFUNCfromPyValue)(PyObject *, void *);
-typedef int (*CFUNC_STRIDE_CONV_FUNC)(long, long, maybelong *,
- void *, long, maybelong*, void *, long, maybelong *);
-
-typedef int (*CFUNC_STRIDED_FUNC)(PyObject *, long, PyArrayObject **,
- char **data);
-
-#define MAXARRAYS 16
-
-typedef enum {
- CFUNC_UFUNC,
- CFUNC_STRIDING,
- CFUNC_NSTRIDING,
- CFUNC_AS_PY_VALUE,
- CFUNC_FROM_PY_VALUE
-} eCfuncType;
-
-typedef struct {
- char *name;
- void *fptr; /* Pointer to "un-wrapped" c function */
- eCfuncType type; /* UFUNC, STRIDING, AsPyValue, FromPyValue */
- Bool chkself; /* CFUNC does own alignment/bounds checking */
- Bool align; /* CFUNC requires aligned buffer pointers */
- Int8 wantIn, wantOut; /* required input/output arg counts. */
- Int8 sizes[MAXARRAYS]; /* array of align/itemsizes. */
- Int8 iters[MAXARRAYS]; /* array of element counts. 0 --> niter. */
-} CfuncDescriptor;
-
-typedef struct {
- PyObject_HEAD
- CfuncDescriptor descr;
-} CfuncObject;
-
-#define SELF_CHECKED_CFUNC_DESCR(name, type) \
- static CfuncDescriptor name##_descr = { #name, (void *) name, type, 1 }
-
-#define CHECK_ALIGN 1
-
-#define CFUNC_DESCR(name, type, align, iargs, oargs, s1, s2, s3, i1, i2, i3) \
- static CfuncDescriptor name##_descr = \
- { #name, (void *)name, type, 0, align, iargs, oargs, {s1, s2, s3}, {i1, i2, i3} }
-
-#define UFUNC_DESCR1(name, s1) \
- CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 0, 1, s1, 0, 0, 0, 0, 0)
-
-#define UFUNC_DESCR2(name, s1, s2) \
- CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 1, 1, s1, s2, 0, 0, 0, 0)
-
-#define UFUNC_DESCR3(name, s1, s2, s3) \
- CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 2, 1, s1, s2, s3, 0, 0, 0)
-
-#define UFUNC_DESCR3sv(name, s1, s2, s3) \
- CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 2, 1, s1, s2, s3, 1, 0, 0)
-
-#define UFUNC_DESCR3vs(name, s1, s2, s3) \
- CFUNC_DESCR(name, CFUNC_UFUNC, CHECK_ALIGN, 2, 1, s1, s2, s3, 0, 1, 0)
-
-#define STRIDING_DESCR2(name, align, s1, s2) \
- CFUNC_DESCR(name, CFUNC_STRIDING, align, 1, 1, s1, s2, 0, 0, 0, 0)
-
-#define NSTRIDING_DESCR1(name) \
- CFUNC_DESCR(name, CFUNC_NSTRIDING, 0, 0, 1, 0, 0, 0, 0, 0, 0)
-
-#define NSTRIDING_DESCR2(name) \
- CFUNC_DESCR(name, CFUNC_NSTRIDING, 0, 1, 1, 0, 0, 0, 0, 0, 0)
-
-#define NSTRIDING_DESCR3(name) \
- CFUNC_DESCR(name, CFUNC_NSTRIDING, 0, 2, 1, 0, 0, 0, 0, 0, 0)
-
-#endif
diff --git a/numpy/numarray/include/numpy/ieeespecial.h b/numpy/numarray/include/numpy/ieeespecial.h
deleted file mode 100644
index 3d2afc0e1..000000000
--- a/numpy/numarray/include/numpy/ieeespecial.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/* 32-bit special value ranges */
-
-#if defined(_MSC_VER)
-#define MKINT(x) (x##UL)
-#define MKINT64(x) (x##Ui64)
-#define BIT(x) (1Ui64 << (x))
-#else
-#define MKINT(x) (x##U)
-#define MKINT64(x) (x##ULL)
-#define BIT(x) (1ULL << (x))
-#endif
-
-
-#define NEG_QUIET_NAN_MIN32 MKINT(0xFFC00001)
-#define NEG_QUIET_NAN_MAX32 MKINT(0xFFFFFFFF)
-
-#define INDETERMINATE_MIN32 MKINT(0xFFC00000)
-#define INDETERMINATE_MAX32 MKINT(0xFFC00000)
-
-#define NEG_SIGNAL_NAN_MIN32 MKINT(0xFF800001)
-#define NEG_SIGNAL_NAN_MAX32 MKINT(0xFFBFFFFF)
-
-#define NEG_INFINITY_MIN32 MKINT(0xFF800000)
-
-#define NEG_NORMALIZED_MIN32 MKINT(0x80800000)
-#define NEG_NORMALIZED_MAX32 MKINT(0xFF7FFFFF)
-
-#define NEG_DENORMALIZED_MIN32 MKINT(0x80000001)
-#define NEG_DENORMALIZED_MAX32 MKINT(0x807FFFFF)
-
-#define NEG_ZERO_MIN32 MKINT(0x80000000)
-#define NEG_ZERO_MAX32 MKINT(0x80000000)
-
-#define POS_ZERO_MIN32 MKINT(0x00000000)
-#define POS_ZERO_MAX32 MKINT(0x00000000)
-
-#define POS_DENORMALIZED_MIN32 MKINT(0x00000001)
-#define POS_DENORMALIZED_MAX32 MKINT(0x007FFFFF)
-
-#define POS_NORMALIZED_MIN32 MKINT(0x00800000)
-#define POS_NORMALIZED_MAX32 MKINT(0x7F7FFFFF)
-
-#define POS_INFINITY_MIN32 MKINT(0x7F800000)
-#define POS_INFINITY_MAX32 MKINT(0x7F800000)
-
-#define POS_SIGNAL_NAN_MIN32 MKINT(0x7F800001)
-#define POS_SIGNAL_NAN_MAX32 MKINT(0x7FBFFFFF)
-
-#define POS_QUIET_NAN_MIN32 MKINT(0x7FC00000)
-#define POS_QUIET_NAN_MAX32 MKINT(0x7FFFFFFF)
-
-/* 64-bit special value ranges */
-
-#define NEG_QUIET_NAN_MIN64 MKINT64(0xFFF8000000000001)
-#define NEG_QUIET_NAN_MAX64 MKINT64(0xFFFFFFFFFFFFFFFF)
-
-#define INDETERMINATE_MIN64 MKINT64(0xFFF8000000000000)
-#define INDETERMINATE_MAX64 MKINT64(0xFFF8000000000000)
-
-#define NEG_SIGNAL_NAN_MIN64 MKINT64(0xFFF7FFFFFFFFFFFF)
-#define NEG_SIGNAL_NAN_MAX64 MKINT64(0xFFF0000000000001)
-
-#define NEG_INFINITY_MIN64 MKINT64(0xFFF0000000000000)
-
-#define NEG_NORMALIZED_MIN64 MKINT64(0xFFEFFFFFFFFFFFFF)
-#define NEG_NORMALIZED_MAX64 MKINT64(0x8010000000000000)
-
-#define NEG_DENORMALIZED_MIN64 MKINT64(0x800FFFFFFFFFFFFF)
-#define NEG_DENORMALIZED_MAX64 MKINT64(0x8000000000000001)
-
-#define NEG_ZERO_MIN64 MKINT64(0x8000000000000000)
-#define NEG_ZERO_MAX64 MKINT64(0x8000000000000000)
-
-#define POS_ZERO_MIN64 MKINT64(0x0000000000000000)
-#define POS_ZERO_MAX64 MKINT64(0x0000000000000000)
-
-#define POS_DENORMALIZED_MIN64 MKINT64(0x0000000000000001)
-#define POS_DENORMALIZED_MAX64 MKINT64(0x000FFFFFFFFFFFFF)
-
-#define POS_NORMALIZED_MIN64 MKINT64(0x0010000000000000)
-#define POS_NORMALIZED_MAX64 MKINT64(0x7FEFFFFFFFFFFFFF)
-
-#define POS_INFINITY_MIN64 MKINT64(0x7FF0000000000000)
-#define POS_INFINITY_MAX64 MKINT64(0x7FF0000000000000)
-
-#define POS_SIGNAL_NAN_MIN64 MKINT64(0x7FF0000000000001)
-#define POS_SIGNAL_NAN_MAX64 MKINT64(0x7FF7FFFFFFFFFFFF)
-
-#define POS_QUIET_NAN_MIN64 MKINT64(0x7FF8000000000000)
-#define POS_QUIET_NAN_MAX64 MKINT64(0x7FFFFFFFFFFFFFFF)
-
-typedef enum
-{
- POS_QNAN_BIT,
- NEG_QNAN_BIT,
- POS_SNAN_BIT,
- NEG_SNAN_BIT,
- POS_INF_BIT,
- NEG_INF_BIT,
- POS_DEN_BIT,
- NEG_DEN_BIT,
- POS_NOR_BIT,
- NEG_NOR_BIT,
- POS_ZERO_BIT,
- NEG_ZERO_BIT,
- INDETERM_BIT,
- BUG_BIT
-} ieee_selects;
-
-#define MSK_POS_QNAN BIT(POS_QNAN_BIT)
-#define MSK_POS_SNAN BIT(POS_SNAN_BIT)
-#define MSK_POS_INF BIT(POS_INF_BIT)
-#define MSK_POS_DEN BIT(POS_DEN_BIT)
-#define MSK_POS_NOR BIT(POS_NOR_BIT)
-#define MSK_POS_ZERO BIT(POS_ZERO_BIT)
-#define MSK_NEG_QNAN BIT(NEG_QNAN_BIT)
-#define MSK_NEG_SNAN BIT(NEG_SNAN_BIT)
-#define MSK_NEG_INF BIT(NEG_INF_BIT)
-#define MSK_NEG_DEN BIT(NEG_DEN_BIT)
-#define MSK_NEG_NOR BIT(NEG_NOR_BIT)
-#define MSK_NEG_ZERO BIT(NEG_ZERO_BIT)
-#define MSK_INDETERM BIT(INDETERM_BIT)
-#define MSK_BUG BIT(BUG_BIT)
diff --git a/numpy/numarray/include/numpy/libnumarray.h b/numpy/numarray/include/numpy/libnumarray.h
deleted file mode 100644
index c69f10d8e..000000000
--- a/numpy/numarray/include/numpy/libnumarray.h
+++ /dev/null
@@ -1,630 +0,0 @@
-/* Compatibility with numarray. Do not use in new code.
- */
-
-#ifndef NUMPY_LIBNUMARRAY_H
-#define NUMPY_LIBNUMARRAY_H
-
-#include "numpy/arrayobject.h"
-#include "arraybase.h"
-#include "nummacro.h"
-#include "numcomplex.h"
-#include "ieeespecial.h"
-#include "cfunc.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Header file for libnumarray */
-
-#if !defined(_libnumarray_MODULE)
-
-/*
-Extensions constructed from seperate compilation units can access the
-C-API defined here by defining "libnumarray_UNIQUE_SYMBOL" to a global
-name unique to the extension. Doing this circumvents the requirement
-to import libnumarray into each compilation unit, but is nevertheless
-mildly discouraged as "outside the Python norm" and potentially
-leading to problems. Looking around at "existing Python art", most
-extension modules are monolithic C files, and likely for good reason.
-*/
-
-/* C API address pointer */
-#if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY)
-extern void **libnumarray_API;
-#else
-#if defined(libnumarray_UNIQUE_SYMBOL)
-void **libnumarray_API;
-#else
-static void **libnumarray_API;
-#endif
-#endif
-
-#if PY_VERSION_HEX >= 0x03000000
-#define _import_libnumarray() \
- { \
- PyObject *module = PyImport_ImportModule("numpy.numarray._capi"); \
- if (module != NULL) { \
- PyObject *module_dict = PyModule_GetDict(module); \
- PyObject *c_api_object = \
- PyDict_GetItemString(module_dict, "_C_API"); \
- if (c_api_object && PyCapsule_CheckExact(c_api_object)) { \
- libnumarray_API = (void **)PyCapsule_GetPointer(c_api_object, NULL); \
- } else { \
- PyErr_Format(PyExc_ImportError, \
- "Can't get API for module 'numpy.numarray._capi'"); \
- } \
- } \
- }
-
-#else
-#define _import_libnumarray() \
- { \
- PyObject *module = PyImport_ImportModule("numpy.numarray._capi"); \
- if (module != NULL) { \
- PyObject *module_dict = PyModule_GetDict(module); \
- PyObject *c_api_object = \
- PyDict_GetItemString(module_dict, "_C_API"); \
- if (c_api_object && PyCObject_Check(c_api_object)) { \
- libnumarray_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
- } else { \
- PyErr_Format(PyExc_ImportError, \
- "Can't get API for module 'numpy.numarray._capi'"); \
- } \
- } \
- }
-#endif
-
-#define import_libnumarray() _import_libnumarray(); if (PyErr_Occurred()) { PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.numarray._capi failed to import.\n"); return; }
-
-#endif
-
-
-#define libnumarray_FatalApiError (Py_FatalError("Call to API function without first calling import_libnumarray() in " __FILE__), NULL)
-
-
-/* Macros defining components of function prototypes */
-
-#ifdef _libnumarray_MODULE
- /* This section is used when compiling libnumarray */
-
-static PyObject *_Error;
-
-static PyObject* getBuffer (PyObject*o);
-
-static int isBuffer (PyObject*o);
-
-static int getWriteBufferDataPtr (PyObject*o,void**p);
-
-static int isBufferWriteable (PyObject*o);
-
-static int getReadBufferDataPtr (PyObject*o,void**p);
-
-static int getBufferSize (PyObject*o);
-
-static double num_log (double x);
-
-static double num_log10 (double x);
-
-static double num_pow (double x, double y);
-
-static double num_acosh (double x);
-
-static double num_asinh (double x);
-
-static double num_atanh (double x);
-
-static double num_round (double x);
-
-static int int_dividebyzero_error (long value, long unused);
-
-static int int_overflow_error (Float64 value);
-
-static int umult64_overflow (UInt64 a, UInt64 b);
-
-static int smult64_overflow (Int64 a0, Int64 b0);
-
-static void NA_Done (void);
-
-static PyArrayObject* NA_NewAll (int ndim, maybelong* shape, NumarrayType type, void* buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable);
-
-static PyArrayObject* NA_NewAllStrides (int ndim, maybelong* shape, maybelong* strides, NumarrayType type, void* buffer, maybelong byteoffset, int byteorder, int aligned, int writeable);
-
-static PyArrayObject* NA_New (void* buffer, NumarrayType type, int ndim,...);
-
-static PyArrayObject* NA_Empty (int ndim, maybelong* shape, NumarrayType type);
-
-static PyArrayObject* NA_NewArray (void* buffer, NumarrayType type, int ndim, ...);
-
-static PyArrayObject* NA_vNewArray (void* buffer, NumarrayType type, int ndim, maybelong *shape);
-
-static PyObject* NA_ReturnOutput (PyObject*,PyArrayObject*);
-
-static long NA_getBufferPtrAndSize (PyObject*,int,void**);
-
-static int NA_checkIo (char*,int,int,int,int);
-
-static int NA_checkOneCBuffer (char*,long,void*,long,size_t);
-
-static int NA_checkNCBuffers (char*,int,long,void**,long*,Int8*,Int8*);
-
-static int NA_checkOneStriding (char*,long,maybelong*,long,maybelong*,long,long,int);
-
-static PyObject* NA_new_cfunc (CfuncDescriptor*);
-
-static int NA_add_cfunc (PyObject*,char*,CfuncDescriptor*);
-
-static PyArrayObject* NA_InputArray (PyObject*,NumarrayType,int);
-
-static PyArrayObject* NA_OutputArray (PyObject*,NumarrayType,int);
-
-static PyArrayObject* NA_IoArray (PyObject*,NumarrayType,int);
-
-static PyArrayObject* NA_OptionalOutputArray (PyObject*,NumarrayType,int,PyArrayObject*);
-
-static long NA_get_offset (PyArrayObject*,int,...);
-
-static Float64 NA_get_Float64 (PyArrayObject*,long);
-
-static void NA_set_Float64 (PyArrayObject*,long,Float64);
-
-static Complex64 NA_get_Complex64 (PyArrayObject*,long);
-
-static void NA_set_Complex64 (PyArrayObject*,long,Complex64);
-
-static Int64 NA_get_Int64 (PyArrayObject*,long);
-
-static void NA_set_Int64 (PyArrayObject*,long,Int64);
-
-static Float64 NA_get1_Float64 (PyArrayObject*,long);
-
-static Float64 NA_get2_Float64 (PyArrayObject*,long,long);
-
-static Float64 NA_get3_Float64 (PyArrayObject*,long,long,long);
-
-static void NA_set1_Float64 (PyArrayObject*,long,Float64);
-
-static void NA_set2_Float64 (PyArrayObject*,long,long,Float64);
-
-static void NA_set3_Float64 (PyArrayObject*,long,long,long,Float64);
-
-static Complex64 NA_get1_Complex64 (PyArrayObject*,long);
-
-static Complex64 NA_get2_Complex64 (PyArrayObject*,long,long);
-
-static Complex64 NA_get3_Complex64 (PyArrayObject*,long,long,long);
-
-static void NA_set1_Complex64 (PyArrayObject*,long,Complex64);
-
-static void NA_set2_Complex64 (PyArrayObject*,long,long,Complex64);
-
-static void NA_set3_Complex64 (PyArrayObject*,long,long,long,Complex64);
-
-static Int64 NA_get1_Int64 (PyArrayObject*,long);
-
-static Int64 NA_get2_Int64 (PyArrayObject*,long,long);
-
-static Int64 NA_get3_Int64 (PyArrayObject*,long,long,long);
-
-static void NA_set1_Int64 (PyArrayObject*,long,Int64);
-
-static void NA_set2_Int64 (PyArrayObject*,long,long,Int64);
-
-static void NA_set3_Int64 (PyArrayObject*,long,long,long,Int64);
-
-static int NA_get1D_Float64 (PyArrayObject*,long,int,Float64*);
-
-static int NA_set1D_Float64 (PyArrayObject*,long,int,Float64*);
-
-static int NA_get1D_Int64 (PyArrayObject*,long,int,Int64*);
-
-static int NA_set1D_Int64 (PyArrayObject*,long,int,Int64*);
-
-static int NA_get1D_Complex64 (PyArrayObject*,long,int,Complex64*);
-
-static int NA_set1D_Complex64 (PyArrayObject*,long,int,Complex64*);
-
-static int NA_ShapeEqual (PyArrayObject*,PyArrayObject*);
-
-static int NA_ShapeLessThan (PyArrayObject*,PyArrayObject*);
-
-static int NA_ByteOrder (void);
-
-static Bool NA_IeeeSpecial32 (Float32*,Int32*);
-
-static Bool NA_IeeeSpecial64 (Float64*,Int32*);
-
-static PyArrayObject* NA_updateDataPtr (PyArrayObject*);
-
-static char* NA_typeNoToName (int);
-
-static int NA_nameToTypeNo (char*);
-
-static PyObject* NA_typeNoToTypeObject (int);
-
-static PyObject* NA_intTupleFromMaybeLongs (int,maybelong*);
-
-static long NA_maybeLongsFromIntTuple (int,maybelong*,PyObject*);
-
-static int NA_intTupleProduct (PyObject *obj, long *product);
-
-static long NA_isIntegerSequence (PyObject*);
-
-static PyObject* NA_setArrayFromSequence (PyArrayObject*,PyObject*);
-
-static int NA_maxType (PyObject*);
-
-static int NA_isPythonScalar (PyObject *obj);
-
-static PyObject* NA_getPythonScalar (PyArrayObject*,long);
-
-static int NA_setFromPythonScalar (PyArrayObject*,long,PyObject*);
-
-static int NA_NDArrayCheck (PyObject*);
-
-static int NA_NumArrayCheck (PyObject*);
-
-static int NA_ComplexArrayCheck (PyObject*);
-
-static unsigned long NA_elements (PyArrayObject*);
-
-static int NA_typeObjectToTypeNo (PyObject*);
-
-static int NA_copyArray (PyArrayObject* to, const PyArrayObject* from);
-
-static PyArrayObject* NA_copy (PyArrayObject*);
-
-static PyObject* NA_getType (PyObject *typeobj_or_name);
-
-static PyObject * NA_callCUFuncCore (PyObject *cfunc, long niter, long ninargs, long noutargs, PyObject **BufferObj, long *offset);
-
-static PyObject * NA_callStrideConvCFuncCore (PyObject *cfunc, int nshape, maybelong *shape, PyObject *inbuffObj, long inboffset, int nstrides0, maybelong *inbstrides, PyObject *outbuffObj, long outboffset, int nstrides1, maybelong *outbstrides, long nbytes);
-
-static void NA_stridesFromShape (int nshape, maybelong *shape, maybelong bytestride, maybelong *strides);
-
-static int NA_OperatorCheck (PyObject *obj);
-
-static int NA_ConverterCheck (PyObject *obj);
-
-static int NA_UfuncCheck (PyObject *obj);
-
-static int NA_CfuncCheck (PyObject *obj);
-
-static int NA_getByteOffset (PyArrayObject *array, int nindices, maybelong *indices, long *offset);
-
-static int NA_swapAxes (PyArrayObject *array, int x, int y);
-
-static PyObject * NA_initModuleGlobal (char *module, char *global);
-
-static NumarrayType NA_NumarrayType (PyObject *seq);
-
-static PyArrayObject * NA_NewAllFromBuffer (int ndim, maybelong *shape, NumarrayType type, PyObject *bufferObject, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable);
-
-static Float64 * NA_alloc1D_Float64 (PyArrayObject *a, long offset, int cnt);
-
-static Int64 * NA_alloc1D_Int64 (PyArrayObject *a, long offset, int cnt);
-
-static void NA_updateAlignment (PyArrayObject *self);
-
-static void NA_updateContiguous (PyArrayObject *self);
-
-static void NA_updateStatus (PyArrayObject *self);
-
-static int NA_NumArrayCheckExact (PyObject *op);
-
-static int NA_NDArrayCheckExact (PyObject *op);
-
-static int NA_OperatorCheckExact (PyObject *op);
-
-static int NA_ConverterCheckExact (PyObject *op);
-
-static int NA_UfuncCheckExact (PyObject *op);
-
-static int NA_CfuncCheckExact (PyObject *op);
-
-static char * NA_getArrayData (PyArrayObject *ap);
-
-static void NA_updateByteswap (PyArrayObject *ap);
-
-static PyArray_Descr * NA_DescrFromType (int type);
-
-static PyObject * NA_Cast (PyArrayObject *a, int type);
-
-static int NA_checkFPErrors (void);
-
-static void NA_clearFPErrors (void);
-
-static int NA_checkAndReportFPErrors (char *name);
-
-static Bool NA_IeeeMask32 (Float32,Int32);
-
-static Bool NA_IeeeMask64 (Float64,Int32);
-
-static int _NA_callStridingHelper (PyObject *aux, long dim, long nnumarray, PyArrayObject *numarray[], char *data[], CFUNC_STRIDED_FUNC f);
-
-static PyArrayObject * NA_FromDimsStridesDescrAndData (int nd, maybelong *dims, maybelong *strides, PyArray_Descr *descr, char *data);
-
-static PyArrayObject * NA_FromDimsTypeAndData (int nd, maybelong *dims, int type, char *data);
-
-static PyArrayObject * NA_FromDimsStridesTypeAndData (int nd, maybelong *dims, maybelong *strides, int type, char *data);
-
-static int NA_scipy_typestr (NumarrayType t, int byteorder, char *typestr);
-
-static PyArrayObject * NA_FromArrayStruct (PyObject *a);
-
-
-#else
- /* This section is used in modules that use libnumarray */
-
-#define getBuffer (libnumarray_API ? (*(PyObject* (*) (PyObject*o) ) libnumarray_API[ 0 ]) : (*(PyObject* (*) (PyObject*o) ) libnumarray_FatalApiError))
-
-#define isBuffer (libnumarray_API ? (*(int (*) (PyObject*o) ) libnumarray_API[ 1 ]) : (*(int (*) (PyObject*o) ) libnumarray_FatalApiError))
-
-#define getWriteBufferDataPtr (libnumarray_API ? (*(int (*) (PyObject*o,void**p) ) libnumarray_API[ 2 ]) : (*(int (*) (PyObject*o,void**p) ) libnumarray_FatalApiError))
-
-#define isBufferWriteable (libnumarray_API ? (*(int (*) (PyObject*o) ) libnumarray_API[ 3 ]) : (*(int (*) (PyObject*o) ) libnumarray_FatalApiError))
-
-#define getReadBufferDataPtr (libnumarray_API ? (*(int (*) (PyObject*o,void**p) ) libnumarray_API[ 4 ]) : (*(int (*) (PyObject*o,void**p) ) libnumarray_FatalApiError))
-
-#define getBufferSize (libnumarray_API ? (*(int (*) (PyObject*o) ) libnumarray_API[ 5 ]) : (*(int (*) (PyObject*o) ) libnumarray_FatalApiError))
-
-#define num_log (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 6 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError))
-
-#define num_log10 (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 7 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError))
-
-#define num_pow (libnumarray_API ? (*(double (*) (double x, double y) ) libnumarray_API[ 8 ]) : (*(double (*) (double x, double y) ) libnumarray_FatalApiError))
-
-#define num_acosh (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 9 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError))
-
-#define num_asinh (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 10 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError))
-
-#define num_atanh (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 11 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError))
-
-#define num_round (libnumarray_API ? (*(double (*) (double x) ) libnumarray_API[ 12 ]) : (*(double (*) (double x) ) libnumarray_FatalApiError))
-
-#define int_dividebyzero_error (libnumarray_API ? (*(int (*) (long value, long unused) ) libnumarray_API[ 13 ]) : (*(int (*) (long value, long unused) ) libnumarray_FatalApiError))
-
-#define int_overflow_error (libnumarray_API ? (*(int (*) (Float64 value) ) libnumarray_API[ 14 ]) : (*(int (*) (Float64 value) ) libnumarray_FatalApiError))
-
-#define umult64_overflow (libnumarray_API ? (*(int (*) (UInt64 a, UInt64 b) ) libnumarray_API[ 15 ]) : (*(int (*) (UInt64 a, UInt64 b) ) libnumarray_FatalApiError))
-
-#define smult64_overflow (libnumarray_API ? (*(int (*) (Int64 a0, Int64 b0) ) libnumarray_API[ 16 ]) : (*(int (*) (Int64 a0, Int64 b0) ) libnumarray_FatalApiError))
-
-#define NA_Done (libnumarray_API ? (*(void (*) (void) ) libnumarray_API[ 17 ]) : (*(void (*) (void) ) libnumarray_FatalApiError))
-
-#define NA_NewAll (libnumarray_API ? (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type, void* buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_API[ 18 ]) : (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type, void* buffer, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_FatalApiError))
-
-#define NA_NewAllStrides (libnumarray_API ? (*(PyArrayObject* (*) (int ndim, maybelong* shape, maybelong* strides, NumarrayType type, void* buffer, maybelong byteoffset, int byteorder, int aligned, int writeable) ) libnumarray_API[ 19 ]) : (*(PyArrayObject* (*) (int ndim, maybelong* shape, maybelong* strides, NumarrayType type, void* buffer, maybelong byteoffset, int byteorder, int aligned, int writeable) ) libnumarray_FatalApiError))
-
-#define NA_New (libnumarray_API ? (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim,...) ) libnumarray_API[ 20 ]) : (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim,...) ) libnumarray_FatalApiError))
-
-#define NA_Empty (libnumarray_API ? (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type) ) libnumarray_API[ 21 ]) : (*(PyArrayObject* (*) (int ndim, maybelong* shape, NumarrayType type) ) libnumarray_FatalApiError))
-
-#define NA_NewArray (libnumarray_API ? (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, ...) ) libnumarray_API[ 22 ]) : (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, ...) ) libnumarray_FatalApiError))
-
-#define NA_vNewArray (libnumarray_API ? (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, maybelong *shape) ) libnumarray_API[ 23 ]) : (*(PyArrayObject* (*) (void* buffer, NumarrayType type, int ndim, maybelong *shape) ) libnumarray_FatalApiError))
-
-#define NA_ReturnOutput (libnumarray_API ? (*(PyObject* (*) (PyObject*,PyArrayObject*) ) libnumarray_API[ 24 ]) : (*(PyObject* (*) (PyObject*,PyArrayObject*) ) libnumarray_FatalApiError))
-
-#define NA_getBufferPtrAndSize (libnumarray_API ? (*(long (*) (PyObject*,int,void**) ) libnumarray_API[ 25 ]) : (*(long (*) (PyObject*,int,void**) ) libnumarray_FatalApiError))
-
-#define NA_checkIo (libnumarray_API ? (*(int (*) (char*,int,int,int,int) ) libnumarray_API[ 26 ]) : (*(int (*) (char*,int,int,int,int) ) libnumarray_FatalApiError))
-
-#define NA_checkOneCBuffer (libnumarray_API ? (*(int (*) (char*,long,void*,long,size_t) ) libnumarray_API[ 27 ]) : (*(int (*) (char*,long,void*,long,size_t) ) libnumarray_FatalApiError))
-
-#define NA_checkNCBuffers (libnumarray_API ? (*(int (*) (char*,int,long,void**,long*,Int8*,Int8*) ) libnumarray_API[ 28 ]) : (*(int (*) (char*,int,long,void**,long*,Int8*,Int8*) ) libnumarray_FatalApiError))
-
-#define NA_checkOneStriding (libnumarray_API ? (*(int (*) (char*,long,maybelong*,long,maybelong*,long,long,int) ) libnumarray_API[ 29 ]) : (*(int (*) (char*,long,maybelong*,long,maybelong*,long,long,int) ) libnumarray_FatalApiError))
-
-#define NA_new_cfunc (libnumarray_API ? (*(PyObject* (*) (CfuncDescriptor*) ) libnumarray_API[ 30 ]) : (*(PyObject* (*) (CfuncDescriptor*) ) libnumarray_FatalApiError))
-
-#define NA_add_cfunc (libnumarray_API ? (*(int (*) (PyObject*,char*,CfuncDescriptor*) ) libnumarray_API[ 31 ]) : (*(int (*) (PyObject*,char*,CfuncDescriptor*) ) libnumarray_FatalApiError))
-
-#define NA_InputArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_API[ 32 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_FatalApiError))
-
-#define NA_OutputArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_API[ 33 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_FatalApiError))
-
-#define NA_IoArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_API[ 34 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int) ) libnumarray_FatalApiError))
-
-#define NA_OptionalOutputArray (libnumarray_API ? (*(PyArrayObject* (*) (PyObject*,NumarrayType,int,PyArrayObject*) ) libnumarray_API[ 35 ]) : (*(PyArrayObject* (*) (PyObject*,NumarrayType,int,PyArrayObject*) ) libnumarray_FatalApiError))
-
-#define NA_get_offset (libnumarray_API ? (*(long (*) (PyArrayObject*,int,...) ) libnumarray_API[ 36 ]) : (*(long (*) (PyArrayObject*,int,...) ) libnumarray_FatalApiError))
-
-#define NA_get_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_API[ 37 ]) : (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError))
-
-#define NA_set_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_API[ 38 ]) : (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_FatalApiError))
-
-#define NA_get_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_API[ 39 ]) : (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError))
-
-#define NA_set_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_API[ 40 ]) : (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_FatalApiError))
-
-#define NA_get_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_API[ 41 ]) : (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError))
-
-#define NA_set_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_API[ 42 ]) : (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_FatalApiError))
-
-#define NA_get1_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_API[ 43 ]) : (*(Float64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError))
-
-#define NA_get2_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long,long) ) libnumarray_API[ 44 ]) : (*(Float64 (*) (PyArrayObject*,long,long) ) libnumarray_FatalApiError))
-
-#define NA_get3_Float64 (libnumarray_API ? (*(Float64 (*) (PyArrayObject*,long,long,long) ) libnumarray_API[ 45 ]) : (*(Float64 (*) (PyArrayObject*,long,long,long) ) libnumarray_FatalApiError))
-
-#define NA_set1_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_API[ 46 ]) : (*(void (*) (PyArrayObject*,long,Float64) ) libnumarray_FatalApiError))
-
-#define NA_set2_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,Float64) ) libnumarray_API[ 47 ]) : (*(void (*) (PyArrayObject*,long,long,Float64) ) libnumarray_FatalApiError))
-
-#define NA_set3_Float64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,long,Float64) ) libnumarray_API[ 48 ]) : (*(void (*) (PyArrayObject*,long,long,long,Float64) ) libnumarray_FatalApiError))
-
-#define NA_get1_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_API[ 49 ]) : (*(Complex64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError))
-
-#define NA_get2_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long,long) ) libnumarray_API[ 50 ]) : (*(Complex64 (*) (PyArrayObject*,long,long) ) libnumarray_FatalApiError))
-
-#define NA_get3_Complex64 (libnumarray_API ? (*(Complex64 (*) (PyArrayObject*,long,long,long) ) libnumarray_API[ 51 ]) : (*(Complex64 (*) (PyArrayObject*,long,long,long) ) libnumarray_FatalApiError))
-
-#define NA_set1_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_API[ 52 ]) : (*(void (*) (PyArrayObject*,long,Complex64) ) libnumarray_FatalApiError))
-
-#define NA_set2_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,Complex64) ) libnumarray_API[ 53 ]) : (*(void (*) (PyArrayObject*,long,long,Complex64) ) libnumarray_FatalApiError))
-
-#define NA_set3_Complex64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,long,Complex64) ) libnumarray_API[ 54 ]) : (*(void (*) (PyArrayObject*,long,long,long,Complex64) ) libnumarray_FatalApiError))
-
-#define NA_get1_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_API[ 55 ]) : (*(Int64 (*) (PyArrayObject*,long) ) libnumarray_FatalApiError))
-
-#define NA_get2_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long,long) ) libnumarray_API[ 56 ]) : (*(Int64 (*) (PyArrayObject*,long,long) ) libnumarray_FatalApiError))
-
-#define NA_get3_Int64 (libnumarray_API ? (*(Int64 (*) (PyArrayObject*,long,long,long) ) libnumarray_API[ 57 ]) : (*(Int64 (*) (PyArrayObject*,long,long,long) ) libnumarray_FatalApiError))
-
-#define NA_set1_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_API[ 58 ]) : (*(void (*) (PyArrayObject*,long,Int64) ) libnumarray_FatalApiError))
-
-#define NA_set2_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,Int64) ) libnumarray_API[ 59 ]) : (*(void (*) (PyArrayObject*,long,long,Int64) ) libnumarray_FatalApiError))
-
-#define NA_set3_Int64 (libnumarray_API ? (*(void (*) (PyArrayObject*,long,long,long,Int64) ) libnumarray_API[ 60 ]) : (*(void (*) (PyArrayObject*,long,long,long,Int64) ) libnumarray_FatalApiError))
-
-#define NA_get1D_Float64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_API[ 61 ]) : (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_FatalApiError))
-
-#define NA_set1D_Float64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_API[ 62 ]) : (*(int (*) (PyArrayObject*,long,int,Float64*) ) libnumarray_FatalApiError))
-
-#define NA_get1D_Int64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_API[ 63 ]) : (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_FatalApiError))
-
-#define NA_set1D_Int64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_API[ 64 ]) : (*(int (*) (PyArrayObject*,long,int,Int64*) ) libnumarray_FatalApiError))
-
-#define NA_get1D_Complex64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_API[ 65 ]) : (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_FatalApiError))
-
-#define NA_set1D_Complex64 (libnumarray_API ? (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_API[ 66 ]) : (*(int (*) (PyArrayObject*,long,int,Complex64*) ) libnumarray_FatalApiError))
-
-#define NA_ShapeEqual (libnumarray_API ? (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_API[ 67 ]) : (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_FatalApiError))
-
-#define NA_ShapeLessThan (libnumarray_API ? (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_API[ 68 ]) : (*(int (*) (PyArrayObject*,PyArrayObject*) ) libnumarray_FatalApiError))
-
-#define NA_ByteOrder (libnumarray_API ? (*(int (*) (void) ) libnumarray_API[ 69 ]) : (*(int (*) (void) ) libnumarray_FatalApiError))
-
-#define NA_IeeeSpecial32 (libnumarray_API ? (*(Bool (*) (Float32*,Int32*) ) libnumarray_API[ 70 ]) : (*(Bool (*) (Float32*,Int32*) ) libnumarray_FatalApiError))
-
-#define NA_IeeeSpecial64 (libnumarray_API ? (*(Bool (*) (Float64*,Int32*) ) libnumarray_API[ 71 ]) : (*(Bool (*) (Float64*,Int32*) ) libnumarray_FatalApiError))
-
-#define NA_updateDataPtr (libnumarray_API ? (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_API[ 72 ]) : (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_FatalApiError))
-
-#define NA_typeNoToName (libnumarray_API ? (*(char* (*) (int) ) libnumarray_API[ 73 ]) : (*(char* (*) (int) ) libnumarray_FatalApiError))
-
-#define NA_nameToTypeNo (libnumarray_API ? (*(int (*) (char*) ) libnumarray_API[ 74 ]) : (*(int (*) (char*) ) libnumarray_FatalApiError))
-
-#define NA_typeNoToTypeObject (libnumarray_API ? (*(PyObject* (*) (int) ) libnumarray_API[ 75 ]) : (*(PyObject* (*) (int) ) libnumarray_FatalApiError))
-
-#define NA_intTupleFromMaybeLongs (libnumarray_API ? (*(PyObject* (*) (int,maybelong*) ) libnumarray_API[ 76 ]) : (*(PyObject* (*) (int,maybelong*) ) libnumarray_FatalApiError))
-
-#define NA_maybeLongsFromIntTuple (libnumarray_API ? (*(long (*) (int,maybelong*,PyObject*) ) libnumarray_API[ 77 ]) : (*(long (*) (int,maybelong*,PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_intTupleProduct (libnumarray_API ? (*(int (*) (PyObject *obj, long *product) ) libnumarray_API[ 78 ]) : (*(int (*) (PyObject *obj, long *product) ) libnumarray_FatalApiError))
-
-#define NA_isIntegerSequence (libnumarray_API ? (*(long (*) (PyObject*) ) libnumarray_API[ 79 ]) : (*(long (*) (PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_setArrayFromSequence (libnumarray_API ? (*(PyObject* (*) (PyArrayObject*,PyObject*) ) libnumarray_API[ 80 ]) : (*(PyObject* (*) (PyArrayObject*,PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_maxType (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 81 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_isPythonScalar (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 82 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError))
-
-#define NA_getPythonScalar (libnumarray_API ? (*(PyObject* (*) (PyArrayObject*,long) ) libnumarray_API[ 83 ]) : (*(PyObject* (*) (PyArrayObject*,long) ) libnumarray_FatalApiError))
-
-#define NA_setFromPythonScalar (libnumarray_API ? (*(int (*) (PyArrayObject*,long,PyObject*) ) libnumarray_API[ 84 ]) : (*(int (*) (PyArrayObject*,long,PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_NDArrayCheck (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 85 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_NumArrayCheck (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 86 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_ComplexArrayCheck (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 87 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_elements (libnumarray_API ? (*(unsigned long (*) (PyArrayObject*) ) libnumarray_API[ 88 ]) : (*(unsigned long (*) (PyArrayObject*) ) libnumarray_FatalApiError))
-
-#define NA_typeObjectToTypeNo (libnumarray_API ? (*(int (*) (PyObject*) ) libnumarray_API[ 89 ]) : (*(int (*) (PyObject*) ) libnumarray_FatalApiError))
-
-#define NA_copyArray (libnumarray_API ? (*(int (*) (PyArrayObject* to, const PyArrayObject* from) ) libnumarray_API[ 90 ]) : (*(int (*) (PyArrayObject* to, const PyArrayObject* from) ) libnumarray_FatalApiError))
-
-#define NA_copy (libnumarray_API ? (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_API[ 91 ]) : (*(PyArrayObject* (*) (PyArrayObject*) ) libnumarray_FatalApiError))
-
-#define NA_getType (libnumarray_API ? (*(PyObject* (*) (PyObject *typeobj_or_name) ) libnumarray_API[ 92 ]) : (*(PyObject* (*) (PyObject *typeobj_or_name) ) libnumarray_FatalApiError))
-
-#define NA_callCUFuncCore (libnumarray_API ? (*(PyObject * (*) (PyObject *cfunc, long niter, long ninargs, long noutargs, PyObject **BufferObj, long *offset) ) libnumarray_API[ 93 ]) : (*(PyObject * (*) (PyObject *cfunc, long niter, long ninargs, long noutargs, PyObject **BufferObj, long *offset) ) libnumarray_FatalApiError))
-
-#define NA_callStrideConvCFuncCore (libnumarray_API ? (*(PyObject * (*) (PyObject *cfunc, int nshape, maybelong *shape, PyObject *inbuffObj, long inboffset, int nstrides0, maybelong *inbstrides, PyObject *outbuffObj, long outboffset, int nstrides1, maybelong *outbstrides, long nbytes) ) libnumarray_API[ 94 ]) : (*(PyObject * (*) (PyObject *cfunc, int nshape, maybelong *shape, PyObject *inbuffObj, long inboffset, int nstrides0, maybelong *inbstrides, PyObject *outbuffObj, long outboffset, int nstrides1, maybelong *outbstrides, long nbytes) ) libnumarray_FatalApiError))
-
-#define NA_stridesFromShape (libnumarray_API ? (*(void (*) (int nshape, maybelong *shape, maybelong bytestride, maybelong *strides) ) libnumarray_API[ 95 ]) : (*(void (*) (int nshape, maybelong *shape, maybelong bytestride, maybelong *strides) ) libnumarray_FatalApiError))
-
-#define NA_OperatorCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 96 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError))
-
-#define NA_ConverterCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 97 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError))
-
-#define NA_UfuncCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 98 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError))
-
-#define NA_CfuncCheck (libnumarray_API ? (*(int (*) (PyObject *obj) ) libnumarray_API[ 99 ]) : (*(int (*) (PyObject *obj) ) libnumarray_FatalApiError))
-
-#define NA_getByteOffset (libnumarray_API ? (*(int (*) (PyArrayObject *array, int nindices, maybelong *indices, long *offset) ) libnumarray_API[ 100 ]) : (*(int (*) (PyArrayObject *array, int nindices, maybelong *indices, long *offset) ) libnumarray_FatalApiError))
-
-#define NA_swapAxes (libnumarray_API ? (*(int (*) (PyArrayObject *array, int x, int y) ) libnumarray_API[ 101 ]) : (*(int (*) (PyArrayObject *array, int x, int y) ) libnumarray_FatalApiError))
-
-#define NA_initModuleGlobal (libnumarray_API ? (*(PyObject * (*) (char *module, char *global) ) libnumarray_API[ 102 ]) : (*(PyObject * (*) (char *module, char *global) ) libnumarray_FatalApiError))
-
-#define NA_NumarrayType (libnumarray_API ? (*(NumarrayType (*) (PyObject *seq) ) libnumarray_API[ 103 ]) : (*(NumarrayType (*) (PyObject *seq) ) libnumarray_FatalApiError))
-
-#define NA_NewAllFromBuffer (libnumarray_API ? (*(PyArrayObject * (*) (int ndim, maybelong *shape, NumarrayType type, PyObject *bufferObject, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_API[ 104 ]) : (*(PyArrayObject * (*) (int ndim, maybelong *shape, NumarrayType type, PyObject *bufferObject, maybelong byteoffset, maybelong bytestride, int byteorder, int aligned, int writeable) ) libnumarray_FatalApiError))
-
-#define NA_alloc1D_Float64 (libnumarray_API ? (*(Float64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_API[ 105 ]) : (*(Float64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_FatalApiError))
-
-#define NA_alloc1D_Int64 (libnumarray_API ? (*(Int64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_API[ 106 ]) : (*(Int64 * (*) (PyArrayObject *a, long offset, int cnt) ) libnumarray_FatalApiError))
-
-#define NA_updateAlignment (libnumarray_API ? (*(void (*) (PyArrayObject *self) ) libnumarray_API[ 107 ]) : (*(void (*) (PyArrayObject *self) ) libnumarray_FatalApiError))
-
-#define NA_updateContiguous (libnumarray_API ? (*(void (*) (PyArrayObject *self) ) libnumarray_API[ 108 ]) : (*(void (*) (PyArrayObject *self) ) libnumarray_FatalApiError))
-
-#define NA_updateStatus (libnumarray_API ? (*(void (*) (PyArrayObject *self) ) libnumarray_API[ 109 ]) : (*(void (*) (PyArrayObject *self) ) libnumarray_FatalApiError))
-
-#define NA_NumArrayCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 110 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError))
-
-#define NA_NDArrayCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 111 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError))
-
-#define NA_OperatorCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 112 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError))
-
-#define NA_ConverterCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 113 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError))
-
-#define NA_UfuncCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 114 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError))
-
-#define NA_CfuncCheckExact (libnumarray_API ? (*(int (*) (PyObject *op) ) libnumarray_API[ 115 ]) : (*(int (*) (PyObject *op) ) libnumarray_FatalApiError))
-
-#define NA_getArrayData (libnumarray_API ? (*(char * (*) (PyArrayObject *ap) ) libnumarray_API[ 116 ]) : (*(char * (*) (PyArrayObject *ap) ) libnumarray_FatalApiError))
-
-#define NA_updateByteswap (libnumarray_API ? (*(void (*) (PyArrayObject *ap) ) libnumarray_API[ 117 ]) : (*(void (*) (PyArrayObject *ap) ) libnumarray_FatalApiError))
-
-#define NA_DescrFromType (libnumarray_API ? (*(PyArray_Descr * (*) (int type) ) libnumarray_API[ 118 ]) : (*(PyArray_Descr * (*) (int type) ) libnumarray_FatalApiError))
-
-#define NA_Cast (libnumarray_API ? (*(PyObject * (*) (PyArrayObject *a, int type) ) libnumarray_API[ 119 ]) : (*(PyObject * (*) (PyArrayObject *a, int type) ) libnumarray_FatalApiError))
-
-#define NA_checkFPErrors (libnumarray_API ? (*(int (*) (void) ) libnumarray_API[ 120 ]) : (*(int (*) (void) ) libnumarray_FatalApiError))
-
-#define NA_clearFPErrors (libnumarray_API ? (*(void (*) (void) ) libnumarray_API[ 121 ]) : (*(void (*) (void) ) libnumarray_FatalApiError))
-
-#define NA_checkAndReportFPErrors (libnumarray_API ? (*(int (*) (char *name) ) libnumarray_API[ 122 ]) : (*(int (*) (char *name) ) libnumarray_FatalApiError))
-
-#define NA_IeeeMask32 (libnumarray_API ? (*(Bool (*) (Float32,Int32) ) libnumarray_API[ 123 ]) : (*(Bool (*) (Float32,Int32) ) libnumarray_FatalApiError))
-
-#define NA_IeeeMask64 (libnumarray_API ? (*(Bool (*) (Float64,Int32) ) libnumarray_API[ 124 ]) : (*(Bool (*) (Float64,Int32) ) libnumarray_FatalApiError))
-
-#define _NA_callStridingHelper (libnumarray_API ? (*(int (*) (PyObject *aux, long dim, long nnumarray, PyArrayObject *numarray[], char *data[], CFUNC_STRIDED_FUNC f) ) libnumarray_API[ 125 ]) : (*(int (*) (PyObject *aux, long dim, long nnumarray, PyArrayObject *numarray[], char *data[], CFUNC_STRIDED_FUNC f) ) libnumarray_FatalApiError))
-
-#define NA_FromDimsStridesDescrAndData (libnumarray_API ? (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, PyArray_Descr *descr, char *data) ) libnumarray_API[ 126 ]) : (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, PyArray_Descr *descr, char *data) ) libnumarray_FatalApiError))
-
-#define NA_FromDimsTypeAndData (libnumarray_API ? (*(PyArrayObject * (*) (int nd, maybelong *dims, int type, char *data) ) libnumarray_API[ 127 ]) : (*(PyArrayObject * (*) (int nd, maybelong *dims, int type, char *data) ) libnumarray_FatalApiError))
-
-#define NA_FromDimsStridesTypeAndData (libnumarray_API ? (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, int type, char *data) ) libnumarray_API[ 128 ]) : (*(PyArrayObject * (*) (int nd, maybelong *dims, maybelong *strides, int type, char *data) ) libnumarray_FatalApiError))
-
-#define NA_scipy_typestr (libnumarray_API ? (*(int (*) (NumarrayType t, int byteorder, char *typestr) ) libnumarray_API[ 129 ]) : (*(int (*) (NumarrayType t, int byteorder, char *typestr) ) libnumarray_FatalApiError))
-
-#define NA_FromArrayStruct (libnumarray_API ? (*(PyArrayObject * (*) (PyObject *a) ) libnumarray_API[ 130 ]) : (*(PyArrayObject * (*) (PyObject *a) ) libnumarray_FatalApiError))
-
-#endif
-
- /* Total number of C API pointers */
-#define libnumarray_API_pointers 131
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* NUMPY_LIBNUMARRAY_H */
diff --git a/numpy/numarray/include/numpy/numcomplex.h b/numpy/numarray/include/numpy/numcomplex.h
deleted file mode 100644
index 7b4960e40..000000000
--- a/numpy/numarray/include/numpy/numcomplex.h
+++ /dev/null
@@ -1,252 +0,0 @@
-/* See numarray.h for Complex32, Complex64:
-
-typedef struct { Float32 r, i; } Complex32;
-typedef struct { Float64 r, i; } Complex64;
-
-*/
-typedef struct { Float32 a, theta; } PolarComplex32;
-typedef struct { Float64 a, theta; } PolarComplex64;
-
-#define NUM_SQ(x) ((x)*(x))
-
-#define NUM_CABSSQ(p) (NUM_SQ((p).r) + NUM_SQ((p).i))
-
-#define NUM_CABS(p) sqrt(NUM_CABSSQ(p))
-
-#define NUM_C_TO_P(c, p) (p).a = NUM_CABS(c); \
- (p).theta = atan2((c).i, (c).r);
-
-#define NUM_P_TO_C(p, c) (c).r = (p).a*cos((p).theta); \
- (c).i = (p).a*sin((p).theta);
-
-#define NUM_CASS(p, q) (q).r = (p).r, (q).i = (p).i
-
-#define NUM_CADD(p, q, s) (s).r = (p).r + (q).r, \
- (s).i = (p).i + (q).i
-
-#define NUM_CSUB(p, q, s) (s).r = (p).r - (q).r, \
- (s).i = (p).i - (q).i
-
-#define NUM_CMUL(p, q, s) \
- { Float64 rp = (p).r; \
- Float64 rq = (q).r; \
- (s).r = rp*rq - (p).i*(q).i; \
- (s).i = rp*(q).i + rq*(p).i; \
- }
-
-#define NUM_CDIV(p, q, s) \
- { \
- Float64 rp = (p).r; \
- Float64 ip = (p).i; \
- Float64 rq = (q).r; \
- if ((q).i != 0) { \
- Float64 temp = NUM_CABSSQ(q); \
- (s).r = (rp*rq+(p).i*(q).i)/temp; \
- (s).i = (rq*(p).i-(q).i*rp)/temp; \
- } else { \
- (s).r = rp/rq; \
- (s).i = ip/rq; \
- } \
- }
-
-#define NUM_CREM(p, q, s) \
- { Complex64 r; \
- NUM_CDIV(p, q, r); \
- r.r = floor(r.r); \
- r.i = 0; \
- NUM_CMUL(r, q, r); \
- NUM_CSUB(p, r, s); \
- }
-
-#define NUM_CMINUS(p, s) (s).r = -(p).r; (s).i = -(p).i;
-#define NUM_CNEG NUM_CMINUS
-
-#define NUM_CEQ(p, q) (((p).r == (q).r) && ((p).i == (q).i))
-#define NUM_CNE(p, q) (((p).r != (q).r) || ((p).i != (q).i))
-#define NUM_CLT(p, q) ((p).r < (q).r)
-#define NUM_CGT(p, q) ((p).r > (q).r)
-#define NUM_CLE(p, q) ((p).r <= (q).r)
-#define NUM_CGE(p, q) ((p).r >= (q).r)
-
-/* e**z = e**x * (cos(y)+ i*sin(y)) where z = x + i*y
- so e**z = e**x * cos(y) + i * e**x * sin(y)
-*/
-#define NUM_CEXP(p, s) \
- { Float64 ex = exp((p).r); \
- (s).r = ex * cos((p).i); \
- (s).i = ex * sin((p).i); \
- }
-
-/* e**w = z; w = u + i*v; z = r * e**(i*theta);
-
-e**u * e**(i*v) = r * e**(i*theta);
-
-log(z) = w; log(z) = log(r) + i*theta;
- */
-#define NUM_CLOG(p, s) \
- { PolarComplex64 temp; NUM_C_TO_P(p, temp); \
- (s).r = num_log(temp.a); \
- (s).i = temp.theta; \
- }
-
-#define NUM_LOG10_E 0.43429448190325182
-
-#define NUM_CLOG10(p, s) \
- { NUM_CLOG(p, s); \
- (s).r *= NUM_LOG10_E; \
- (s).i *= NUM_LOG10_E; \
- }
-
-/* s = p ** q */
-#define NUM_CPOW(p, q, s) { if (NUM_CABSSQ(p) == 0) { \
- if ((q).r == 0 && (q).i == 0) { \
- (s).r = (s).i = 1; \
- } else { \
- (s).r = (s).i = 0; \
- } \
- } else { \
- NUM_CLOG(p, s); \
- NUM_CMUL(s, q, s); \
- NUM_CEXP(s, s); \
- } \
- }
-
-#define NUM_CSQRT(p, s) { Complex64 temp; temp.r = 0.5; temp.i=0; \
- NUM_CPOW(p, temp, s); \
- }
-
-#define NUM_CSQR(p, s) { Complex64 temp; temp.r = 2.0; temp.i=0; \
- NUM_CPOW(p, temp, s); \
- }
-
-#define NUM_CSIN(p, s) { Float64 sp = sin((p).r); \
- Float64 cp = cos((p).r); \
- (s).r = cosh((p).i) * sp; \
- (s).i = sinh((p).i) * cp; \
- }
-
-#define NUM_CCOS(p, s) { Float64 sp = sin((p).r); \
- Float64 cp = cos((p).r); \
- (s).r = cosh((p).i) * cp; \
- (s).i = -sinh((p).i) * sp; \
- }
-
-#define NUM_CTAN(p, s) { Complex64 ss, cs; \
- NUM_CSIN(p, ss); \
- NUM_CCOS(p, cs); \
- NUM_CDIV(ss, cs, s); \
- }
-
-#define NUM_CSINH(p, s) { Float64 sp = sin((p).i); \
- Float64 cp = cos((p).i); \
- (s).r = sinh((p).r) * cp; \
- (s).i = cosh((p).r) * sp; \
- }
-
-#define NUM_CCOSH(p, s) { Float64 sp = sin((p).i); \
- Float64 cp = cos((p).i); \
- (s).r = cosh((p).r) * cp; \
- (s).i = sinh((p).r) * sp; \
- }
-
-#define NUM_CTANH(p, s) { Complex64 ss, cs; \
- NUM_CSINH(p, ss); \
- NUM_CCOSH(p, cs); \
- NUM_CDIV(ss, cs, s); \
- }
-
-#define NUM_CRPOW(p, v, s) { Complex64 cr; cr.r = v; cr.i = 0; \
- NUM_CPOW(p,cr,s); \
- }
-
-#define NUM_CRMUL(p, v, s) (s).r = (p).r * v; (s).i = (p).i * v;
-
-#define NUM_CIMUL(p, s) { Float64 temp = (s).r; \
- (s).r = -(p).i; (s).i = temp; \
- }
-
-/* asin(z) = -i * log(i*z + (1 - z**2)**0.5) */
-#define NUM_CASIN(p, s) { Complex64 p1; NUM_CASS(p, p1); \
- NUM_CIMUL(p, p1); \
- NUM_CMUL(p, p, s); \
- NUM_CNEG(s, s); \
- (s).r += 1; \
- NUM_CRPOW(s, 0.5, s); \
- NUM_CADD(p1, s, s); \
- NUM_CLOG(s, s); \
- NUM_CIMUL(s, s); \
- NUM_CNEG(s, s); \
- }
-
-/* acos(z) = -i * log(z + i*(1 - z**2)**0.5) */
-#define NUM_CACOS(p, s) { Complex64 p1; NUM_CASS(p, p1); \
- NUM_CMUL(p, p, s); \
- NUM_CNEG(s, s); \
- (s).r += 1; \
- NUM_CRPOW(s, 0.5, s); \
- NUM_CIMUL(s, s); \
- NUM_CADD(p1, s, s); \
- NUM_CLOG(s, s); \
- NUM_CIMUL(s, s); \
- NUM_CNEG(s, s); \
- }
-
-/* atan(z) = i/2 * log( (i+z) / (i - z) ) */
-#define NUM_CATAN(p, s) { Complex64 p1, p2; \
- NUM_CASS(p, p1); NUM_CNEG(p, p2); \
- p1.i += 1; \
- p2.i += 1; \
- NUM_CDIV(p1, p2, s); \
- NUM_CLOG(s, s); \
- NUM_CIMUL(s, s); \
- NUM_CRMUL(s, 0.5, s); \
- }
-
-/* asinh(z) = log( z + (z**2 + 1)**0.5 ) */
-#define NUM_CASINH(p, s) { Complex64 p1; NUM_CASS(p, p1); \
- NUM_CMUL(p, p, s); \
- (s).r += 1; \
- NUM_CRPOW(s, 0.5, s); \
- NUM_CADD(p1, s, s); \
- NUM_CLOG(s, s); \
- }
-
-/* acosh(z) = log( z + (z**2 - 1)**0.5 ) */
-#define NUM_CACOSH(p, s) { Complex64 p1; NUM_CASS(p, p1); \
- NUM_CMUL(p, p, s); \
- (s).r -= 1; \
- NUM_CRPOW(s, 0.5, s); \
- NUM_CADD(p1, s, s); \
- NUM_CLOG(s, s); \
- }
-
-/* atanh(z) = 1/2 * log( (1+z)/(1-z) ) */
-#define NUM_CATANH(p, s) { Complex64 p1, p2; \
- NUM_CASS(p, p1); NUM_CNEG(p, p2); \
- p1.r += 1; \
- p2.r += 1; \
- NUM_CDIV(p1, p2, s); \
- NUM_CLOG(s, s); \
- NUM_CRMUL(s, 0.5, s); \
- }
-
-
-#define NUM_CMIN(p, q) (NUM_CLE(p, q) ? p : q)
-#define NUM_CMAX(p, q) (NUM_CGE(p, q) ? p : q)
-
-#define NUM_CNZ(p) (((p).r != 0) || ((p).i != 0))
-#define NUM_CLAND(p, q) (NUM_CNZ(p) & NUM_CNZ(q))
-#define NUM_CLOR(p, q) (NUM_CNZ(p) | NUM_CNZ(q))
-#define NUM_CLXOR(p, q) (NUM_CNZ(p) ^ NUM_CNZ(q))
-#define NUM_CLNOT(p) (!NUM_CNZ(p))
-
-#define NUM_CFLOOR(p, s) (s).r = floor((p).r); (s).i = floor((p).i);
-#define NUM_CCEIL(p, s) (s).r = ceil((p).r); (s).i = ceil((p).i);
-
-#define NUM_CFABS(p, s) (s).r = fabs((p).r); (s).i = fabs((p).i);
-#define NUM_CROUND(p, s) (s).r = num_round((p).r); (s).i = num_round((p).i);
-#define NUM_CHYPOT(p, q, s) { Complex64 t; \
- NUM_CSQR(p, s); NUM_CSQR(q, t); \
- NUM_CADD(s, t, s); \
- NUM_CSQRT(s, s); \
- }
diff --git a/numpy/numarray/include/numpy/nummacro.h b/numpy/numarray/include/numpy/nummacro.h
deleted file mode 100644
index 0f87dfb84..000000000
--- a/numpy/numarray/include/numpy/nummacro.h
+++ /dev/null
@@ -1,447 +0,0 @@
-/* Primarily for compatibility with numarray C-API */
-
-#if !defined(_ndarraymacro)
-#define _ndarraymacro
-
-/* The structs defined here are private implementation details of numarray
-which are subject to change w/o notice.
-*/
-
-#define PY_BOOL_CHAR "b"
-#define PY_INT8_CHAR "b"
-#define PY_INT16_CHAR "h"
-#define PY_INT32_CHAR "i"
-#define PY_FLOAT32_CHAR "f"
-#define PY_FLOAT64_CHAR "d"
-#define PY_UINT8_CHAR "h"
-#define PY_UINT16_CHAR "i"
-#define PY_UINT32_CHAR "i" /* Unless longer int available */
-#define PY_COMPLEX64_CHAR "D"
-#define PY_COMPLEX128_CHAR "D"
-
-#define PY_LONG_CHAR "l"
-#define PY_LONG_LONG_CHAR "L"
-
-#define pyFPE_DIVIDE_BY_ZERO 1
-#define pyFPE_OVERFLOW 2
-#define pyFPE_UNDERFLOW 4
-#define pyFPE_INVALID 8
-
-#define isNonZERO(x) (x != 0) /* to convert values to boolean 1's or 0's */
-
-typedef enum
-{
- NUM_CONTIGUOUS=1,
- NUM_NOTSWAPPED=0x0200,
- NUM_ALIGNED=0x0100,
- NUM_WRITABLE=0x0400,
- NUM_COPY=0x0020,
-
- NUM_C_ARRAY = (NUM_CONTIGUOUS | NUM_ALIGNED | NUM_NOTSWAPPED),
- NUM_UNCONVERTED = 0
-} NumRequirements;
-
-#define UNCONVERTED 0
-#define C_ARRAY (NUM_CONTIGUOUS | NUM_NOTSWAPPED | NUM_ALIGNED)
-
-#define MUST_BE_COMPUTED 2
-
-#define NUM_FLOORDIVIDE(a,b,out) (out) = floor((a)/(b))
-
-#define NA_Begin() Py_Initialize(); import_libnumarray();
-#define NA_End() NA_Done(); Py_Finalize();
-
-#define NA_OFFSETDATA(num) ((void *) PyArray_DATA(num))
-
-/* unaligned NA_COPY functions */
-#define NA_COPY1(i, o) (*(o) = *(i))
-#define NA_COPY2(i, o) NA_COPY1(i, o), NA_COPY1(i+1, o+1)
-#define NA_COPY4(i, o) NA_COPY2(i, o), NA_COPY2(i+2, o+2)
-#define NA_COPY8(i, o) NA_COPY4(i, o), NA_COPY4(i+4, o+4)
-#define NA_COPY16(i, o) NA_COPY8(i, o), NA_COPY8(i+8, o+8)
-
-/* byteswapping macros: these fail if i==o */
-#define NA_SWAP1(i, o) NA_COPY1(i, o)
-#define NA_SWAP2(i, o) NA_SWAP1(i, o+1), NA_SWAP1(i+1, o)
-#define NA_SWAP4(i, o) NA_SWAP2(i, o+2), NA_SWAP2(i+2, o)
-#define NA_SWAP8(i, o) NA_SWAP4(i, o+4), NA_SWAP4(i+4, o)
-#define NA_SWAP16(i, o) NA_SWAP8(i, o+8), NA_SWAP8(i+8, o)
-
-/* complex byteswaps must swap each part (real, imag) independently */
-#define NA_COMPLEX_SWAP8(i, o) NA_SWAP4(i, o), NA_SWAP4(i+4, o+4)
-#define NA_COMPLEX_SWAP16(i, o) NA_SWAP8(i, o), NA_SWAP8(i+8, o+8)
-
-/* byteswapping macros: these work even if i == o */
-#define NA_TSWAP1(i, o, t) NA_COPY1(i, t), NA_SWAP1(t, o)
-#define NA_TSWAP2(i, o, t) NA_COPY2(i, t), NA_SWAP2(t, o)
-#define NA_TSWAP4(i, o, t) NA_COPY4(i, t), NA_SWAP4(t, o)
-#define NA_TSWAP8(i, o, t) NA_COPY8(i, t), NA_SWAP8(t, o)
-
-/* fast copy functions for %N aligned i and o */
-#define NA_ACOPY1(i, o) (((Int8 *)o)[0] = ((Int8 *)i)[0])
-#define NA_ACOPY2(i, o) (((Int16 *)o)[0] = ((Int16 *)i)[0])
-#define NA_ACOPY4(i, o) (((Int32 *)o)[0] = ((Int32 *)i)[0])
-#define NA_ACOPY8(i, o) (((Float64 *)o)[0] = ((Float64 *)i)[0])
-#define NA_ACOPY16(i, o) (((Complex64 *)o)[0] = ((Complex64 *)i)[0])
-
-/* from here down, type("ai") is NDInfo* */
-
-#define NA_PTR(ai) ((char *) NA_OFFSETDATA((ai)))
-#define NA_PTR1(ai, i) (NA_PTR(ai) + \
- (i)*PyArray_STRIDES(ai)[0])
-#define NA_PTR2(ai, i, j) (NA_PTR(ai) + \
- (i)*PyArray_STRIDES(ai)[0] + \
- (j)*PyArray_STRIDES(ai)[1])
-#define NA_PTR3(ai, i, j, k) (NA_PTR(ai) + \
- (i)*PyArray_STRIDES(ai)[0] + \
- (j)*PyArray_STRIDES(ai)[1] + \
- (k)*PyArray_STRIDES(ai)[2])
-
-#define NA_SET_TEMP(ai, type, v) (((type *) &__temp__)[0] = v)
-
-#define NA_SWAPComplex64 NA_COMPLEX_SWAP16
-#define NA_SWAPComplex32 NA_COMPLEX_SWAP8
-#define NA_SWAPFloat64 NA_SWAP8
-#define NA_SWAPFloat32 NA_SWAP4
-#define NA_SWAPInt64 NA_SWAP8
-#define NA_SWAPUInt64 NA_SWAP8
-#define NA_SWAPInt32 NA_SWAP4
-#define NA_SWAPUInt32 NA_SWAP4
-#define NA_SWAPInt16 NA_SWAP2
-#define NA_SWAPUInt16 NA_SWAP2
-#define NA_SWAPInt8 NA_SWAP1
-#define NA_SWAPUInt8 NA_SWAP1
-#define NA_SWAPBool NA_SWAP1
-
-#define NA_COPYComplex64 NA_COPY16
-#define NA_COPYComplex32 NA_COPY8
-#define NA_COPYFloat64 NA_COPY8
-#define NA_COPYFloat32 NA_COPY4
-#define NA_COPYInt64 NA_COPY8
-#define NA_COPYUInt64 NA_COPY8
-#define NA_COPYInt32 NA_COPY4
-#define NA_COPYUInt32 NA_COPY4
-#define NA_COPYInt16 NA_COPY2
-#define NA_COPYUInt16 NA_COPY2
-#define NA_COPYInt8 NA_COPY1
-#define NA_COPYUInt8 NA_COPY1
-#define NA_COPYBool NA_COPY1
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define _makeGetPb(type) \
-static type _NA_GETPb_##type(char *ptr) \
-{ \
- type temp; \
- NA_SWAP##type(ptr, (char *)&temp); \
- return temp; \
-}
-
-#define _makeGetPa(type) \
-static type _NA_GETPa_##type(char *ptr) \
-{ \
- type temp; \
- NA_COPY##type(ptr, (char *)&temp); \
- return temp; \
-}
-
-_makeGetPb(Complex64)
-_makeGetPb(Complex32)
-_makeGetPb(Float64)
-_makeGetPb(Float32)
-_makeGetPb(Int64)
-_makeGetPb(UInt64)
-_makeGetPb(Int32)
-_makeGetPb(UInt32)
-_makeGetPb(Int16)
-_makeGetPb(UInt16)
-_makeGetPb(Int8)
-_makeGetPb(UInt8)
-_makeGetPb(Bool)
-
-_makeGetPa(Complex64)
-_makeGetPa(Complex32)
-_makeGetPa(Float64)
-_makeGetPa(Float32)
-_makeGetPa(Int64)
-_makeGetPa(UInt64)
-_makeGetPa(Int32)
-_makeGetPa(UInt32)
-_makeGetPa(Int16)
-_makeGetPa(UInt16)
-_makeGetPa(Int8)
-_makeGetPa(UInt8)
-_makeGetPa(Bool)
-
-#undef _makeGetPb
-#undef _makeGetPa
-
-#define _makeSetPb(type) \
-static void _NA_SETPb_##type(char *ptr, type v) \
-{ \
- NA_SWAP##type(((char *)&v), ptr); \
- return; \
-}
-
-#define _makeSetPa(type) \
-static void _NA_SETPa_##type(char *ptr, type v) \
-{ \
- NA_COPY##type(((char *)&v), ptr); \
- return; \
-}
-
-_makeSetPb(Complex64)
-_makeSetPb(Complex32)
-_makeSetPb(Float64)
-_makeSetPb(Float32)
-_makeSetPb(Int64)
-_makeSetPb(UInt64)
-_makeSetPb(Int32)
-_makeSetPb(UInt32)
-_makeSetPb(Int16)
-_makeSetPb(UInt16)
-_makeSetPb(Int8)
-_makeSetPb(UInt8)
-_makeSetPb(Bool)
-
-_makeSetPa(Complex64)
-_makeSetPa(Complex32)
-_makeSetPa(Float64)
-_makeSetPa(Float32)
-_makeSetPa(Int64)
-_makeSetPa(UInt64)
-_makeSetPa(Int32)
-_makeSetPa(UInt32)
-_makeSetPa(Int16)
-_makeSetPa(UInt16)
-_makeSetPa(Int8)
-_makeSetPa(UInt8)
-_makeSetPa(Bool)
-
-#undef _makeSetPb
-#undef _makeSetPa
-
-#ifdef __cplusplus
- }
-#endif
-
-/* ========================== ptr get/set ================================ */
-
-/* byteswapping */
-#define NA_GETPb(ai, type, ptr) _NA_GETPb_##type(ptr)
-
-/* aligning */
-#define NA_GETPa(ai, type, ptr) _NA_GETPa_##type(ptr)
-
-/* fast (aligned, !byteswapped) */
-#define NA_GETPf(ai, type, ptr) (*((type *) (ptr)))
-
-#define NA_GETP(ai, type, ptr) \
- (PyArray_ISCARRAY(ai) ? NA_GETPf(ai, type, ptr) \
- : (PyArray_ISBYTESWAPPED(ai) ? \
- NA_GETPb(ai, type, ptr) \
- : NA_GETPa(ai, type, ptr)))
-
-/* NOTE: NA_SET* macros cannot be used as values. */
-
-/* byteswapping */
-#define NA_SETPb(ai, type, ptr, v) _NA_SETPb_##type(ptr, v)
-
-/* aligning */
-#define NA_SETPa(ai, type, ptr, v) _NA_SETPa_##type(ptr, v)
-
-/* fast (aligned, !byteswapped) */
-#define NA_SETPf(ai, type, ptr, v) ((*((type *) ptr)) = (v))
-
-#define NA_SETP(ai, type, ptr, v) \
- if (PyArray_ISCARRAY(ai)) { \
- NA_SETPf((ai), type, (ptr), (v)); \
- } else if (PyArray_ISBYTESWAPPED(ai)) { \
- NA_SETPb((ai), type, (ptr), (v)); \
- } else \
- NA_SETPa((ai), type, (ptr), (v))
-
-/* ========================== 1 index get/set ============================ */
-
-/* byteswapping */
-#define NA_GET1b(ai, type, i) NA_GETPb(ai, type, NA_PTR1(ai, i))
-/* aligning */
-#define NA_GET1a(ai, type, i) NA_GETPa(ai, type, NA_PTR1(ai, i))
-/* fast (aligned, !byteswapped) */
-#define NA_GET1f(ai, type, i) NA_GETPf(ai, type, NA_PTR1(ai, i))
-/* testing */
-#define NA_GET1(ai, type, i) NA_GETP(ai, type, NA_PTR1(ai, i))
-
-/* byteswapping */
-#define NA_SET1b(ai, type, i, v) NA_SETPb(ai, type, NA_PTR1(ai, i), v)
-/* aligning */
-#define NA_SET1a(ai, type, i, v) NA_SETPa(ai, type, NA_PTR1(ai, i), v)
-/* fast (aligned, !byteswapped) */
-#define NA_SET1f(ai, type, i, v) NA_SETPf(ai, type, NA_PTR1(ai, i), v)
-/* testing */
-#define NA_SET1(ai, type, i, v) NA_SETP(ai, type, NA_PTR1(ai, i), v)
-
-/* ========================== 2 index get/set ============================= */
-
-/* byteswapping */
-#define NA_GET2b(ai, type, i, j) NA_GETPb(ai, type, NA_PTR2(ai, i, j))
-/* aligning */
-#define NA_GET2a(ai, type, i, j) NA_GETPa(ai, type, NA_PTR2(ai, i, j))
-/* fast (aligned, !byteswapped) */
-#define NA_GET2f(ai, type, i, j) NA_GETPf(ai, type, NA_PTR2(ai, i, j))
-/* testing */
-#define NA_GET2(ai, type, i, j) NA_GETP(ai, type, NA_PTR2(ai, i, j))
-
-/* byteswapping */
-#define NA_SET2b(ai, type, i, j, v) NA_SETPb(ai, type, NA_PTR2(ai, i, j), v)
-/* aligning */
-#define NA_SET2a(ai, type, i, j, v) NA_SETPa(ai, type, NA_PTR2(ai, i, j), v)
-/* fast (aligned, !byteswapped) */
-#define NA_SET2f(ai, type, i, j, v) NA_SETPf(ai, type, NA_PTR2(ai, i, j), v)
-
-#define NA_SET2(ai, type, i, j, v) NA_SETP(ai, type, NA_PTR2(ai, i, j), v)
-
-/* ========================== 3 index get/set ============================= */
-
-/* byteswapping */
-#define NA_GET3b(ai, type, i, j, k) NA_GETPb(ai, type, NA_PTR3(ai, i, j, k))
-/* aligning */
-#define NA_GET3a(ai, type, i, j, k) NA_GETPa(ai, type, NA_PTR3(ai, i, j, k))
-/* fast (aligned, !byteswapped) */
-#define NA_GET3f(ai, type, i, j, k) NA_GETPf(ai, type, NA_PTR3(ai, i, j, k))
-/* testing */
-#define NA_GET3(ai, type, i, j, k) NA_GETP(ai, type, NA_PTR3(ai, i, j, k))
-
-/* byteswapping */
-#define NA_SET3b(ai, type, i, j, k, v) \
- NA_SETPb(ai, type, NA_PTR3(ai, i, j, k), v)
-/* aligning */
-#define NA_SET3a(ai, type, i, j, k, v) \
- NA_SETPa(ai, type, NA_PTR3(ai, i, j, k), v)
-/* fast (aligned, !byteswapped) */
-#define NA_SET3f(ai, type, i, j, k, v) \
- NA_SETPf(ai, type, NA_PTR3(ai, i, j, k), v)
-#define NA_SET3(ai, type, i, j, k, v) \
- NA_SETP(ai, type, NA_PTR3(ai, i, j, k), v)
-
-/* ========================== 1D get/set ================================== */
-
-#define NA_GET1Db(ai, type, base, cnt, out) \
- { int i, stride = PyArray_STRIDES(ai)[PyArray_NDIM(ai)-1]; \
- for(i=0; i<cnt; i++) { \
- out[i] = NA_GETPb(ai, type, base); \
- base += stride; \
- } \
- }
-
-#define NA_GET1Da(ai, type, base, cnt, out) \
- { int i, stride = PyArray_STRIDES(ai)[PyArray_NDIM(ai)-1]; \
- for(i=0; i<cnt; i++) { \
- out[i] = NA_GETPa(ai, type, base); \
- base += stride; \
- } \
- }
-
-#define NA_GET1Df(ai, type, base, cnt, out) \
- { int i, stride = PyArray_STRIDES(ai)[PyArray_NDIM(ai)-1]; \
- for(i=0; i<cnt; i++) { \
- out[i] = NA_GETPf(ai, type, base); \
- base += stride; \
- } \
- }
-
-#define NA_GET1D(ai, type, base, cnt, out) \
- if (PyArray_ISCARRAY(ai)) { \
- NA_GET1Df(ai, type, base, cnt, out); \
- } else if (PyArray_ISBYTESWAPPED(ai)) { \
- NA_GET1Db(ai, type, base, cnt, out); \
- } else { \
- NA_GET1Da(ai, type, base, cnt, out); \
- }
-
-#define NA_SET1Db(ai, type, base, cnt, in) \
- { int i, stride = PyArray_STRIDES(ai)[PyArray_NDIM(ai)-1]; \
- for(i=0; i<cnt; i++) { \
- NA_SETPb(ai, type, base, in[i]); \
- base += stride; \
- } \
- }
-
-#define NA_SET1Da(ai, type, base, cnt, in) \
- { int i, stride = PyArray_STRIDES(ai)[PyArray_NDIM(ai)-1]; \
- for(i=0; i<cnt; i++) { \
- NA_SETPa(ai, type, base, in[i]); \
- base += stride; \
- } \
- }
-
-#define NA_SET1Df(ai, type, base, cnt, in) \
- { int i, stride = PyArray_STRIDES(ai)[PyArray_NDIM(ai)-1]; \
- for(i=0; i<cnt; i++) { \
- NA_SETPf(ai, type, base, in[i]); \
- base += stride; \
- } \
- }
-
-#define NA_SET1D(ai, type, base, cnt, out) \
- if (PyArray_ISCARRAY(ai)) { \
- NA_SET1Df(ai, type, base, cnt, out); \
- } else if (PyArray_ISBYTESWAPPED(ai)) { \
- NA_SET1Db(ai, type, base, cnt, out); \
- } else { \
- NA_SET1Da(ai, type, base, cnt, out); \
- }
-
-/* ========================== utilities ================================== */
-
-#if !defined(MIN)
-#define MIN(x,y) (((x)<=(y)) ? (x) : (y))
-#endif
-
-#if !defined(MAX)
-#define MAX(x,y) (((x)>=(y)) ? (x) : (y))
-#endif
-
-#if !defined(ABS)
-#define ABS(x) (((x) >= 0) ? (x) : -(x))
-#endif
-
-#define ELEM(x) (sizeof(x)/sizeof(x[0]))
-
-#define BOOLEAN_BITWISE_NOT(x) ((x) ^ 1)
-
-#define NA_NBYTES(a) (PyArray_DESCR(a)->elsize * NA_elements(a))
-
-#if defined(NA_SMP)
-#define BEGIN_THREADS Py_BEGIN_ALLOW_THREADS
-#define END_THREADS Py_END_ALLOW_THREADS
-#else
-#define BEGIN_THREADS
-#define END_THREADS
-#endif
-
-#if !defined(NA_isnan)
-
-#define U32(u) (* (Int32 *) &(u) )
-#define U64(u) (* (Int64 *) &(u) )
-
-#define NA_isnan32(u) \
- ( (( U32(u) & 0x7f800000) == 0x7f800000) && ((U32(u) & 0x007fffff) != 0)) ? 1:0
-
-#if !defined(_MSC_VER)
-#define NA_isnan64(u) \
- ( (( U64(u) & 0x7ff0000000000000LL) == 0x7ff0000000000000LL) && ((U64(u) & 0x000fffffffffffffLL) != 0)) ? 1:0
-#else
-#define NA_isnan64(u) \
- ( (( U64(u) & 0x7ff0000000000000i64) == 0x7ff0000000000000i64) && ((U64(u) & 0x000fffffffffffffi64) != 0)) ? 1:0
-#endif
-
-#define NA_isnanC32(u) (NA_isnan32(((Complex32 *)&(u))->r) || NA_isnan32(((Complex32 *)&(u))->i))
-#define NA_isnanC64(u) (NA_isnan64(((Complex64 *)&(u))->r) || NA_isnan64(((Complex64 *)&(u))->i))
-
-#endif /* NA_isnan */
-
-
-#endif /* _ndarraymacro */
diff --git a/numpy/numarray/linear_algebra.py b/numpy/numarray/linear_algebra.py
deleted file mode 100644
index 6cf22329e..000000000
--- a/numpy/numarray/linear_algebra.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-from numpy.oldnumeric.linear_algebra import *
-
-import numpy.oldnumeric.linear_algebra as nol
-
-__all__ = list(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)
diff --git a/numpy/numarray/ma.py b/numpy/numarray/ma.py
deleted file mode 100644
index dbfd3d2f5..000000000
--- a/numpy/numarray/ma.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-from numpy.oldnumeric.ma import *
diff --git a/numpy/numarray/matrix.py b/numpy/numarray/matrix.py
deleted file mode 100644
index e88fc086f..000000000
--- a/numpy/numarray/matrix.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['Matrix']
-
-from numpy import matrix as _matrix
-
-def Matrix(data, typecode=None, copy=1, savespace=0):
- return _matrix(data, typecode, copy=copy)
diff --git a/numpy/numarray/mlab.py b/numpy/numarray/mlab.py
deleted file mode 100644
index c5b9194ee..000000000
--- a/numpy/numarray/mlab.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-from numpy.oldnumeric.mlab import *
-import numpy.oldnumeric.mlab as nom
-
-__all__ = nom.__all__
-
-del nom
diff --git a/numpy/numarray/nd_image.py b/numpy/numarray/nd_image.py
deleted file mode 100644
index 224d2ba23..000000000
--- a/numpy/numarray/nd_image.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-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)
diff --git a/numpy/numarray/numerictypes.py b/numpy/numarray/numerictypes.py
deleted file mode 100644
index 739b855a1..000000000
--- a/numpy/numarray/numerictypes.py
+++ /dev/null
@@ -1,552 +0,0 @@
-"""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 $
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import numpy
-from numpy.compat import long
-
-__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
-
-LP64 = numpy.intp(0).itemsize == 8
-
-HasUInt64 = 1
-try:
- numpy.int64(0)
-except:
- HasUInt64 = 0
-
-#from typeconv import typeConverters as _typeConverters
-#import numinclude
-#from _numerictype import _numerictype, typeDict
-
-# 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 rep in typeDict
-
-def _register(name, type, force=0):
- """Register the type object. Raise an exception if it is already registered
- unless force is true.
- """
- if name in typeDict 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 name in typeDict:
- 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(object):
- """Marker class used for signed type check"""
- pass
-
-class UnsignedType(object):
- """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)
-
-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)
-Short = _register("Short", Int16)
-Int = _register("Int", Int32)
-if LP64:
- Long = _register("Long", Int64)
- if HasUInt64:
- _register("ULong", UInt64)
- MaybeLong = _register("MaybeLong", Int64)
- __all__.append('MaybeLong')
-else:
- Long = _register("Long", Int32)
- _register("ULong", UInt32)
- MaybeLong = _register("MaybeLong", Int32)
- __all__.append('MaybeLong')
-
-
-_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']
-
-pythonTypeRank = [ bool, 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"}
-
-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")
-
-scalarTypes = (bool, 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
-
-_val = numpy.int_(0).itemsize
-if _val == 8:
- _scipy_dtypechar_inverse['l'] = Int64
- _scipy_dtypechar_inverse['L'] = UInt64
-elif _val == 4:
- _scipy_dtypechar_inverse['l'] = Int32
- _scipy_dtypechar_inverse['L'] = UInt32
-
-del _val
-
-if LP64:
- _scipy_dtypechar_inverse['p'] = Int64
- _scipy_dtypechar_inverse['P'] = UInt64
-else:
- _scipy_dtypechar_inverse['p'] = Int32
- _scipy_dtypechar_inverse['P'] = UInt32
-
-def typefrom(obj):
- return _scipy_dtypechar_inverse[obj.dtype.char]
diff --git a/numpy/numarray/random_array.py b/numpy/numarray/random_array.py
deleted file mode 100644
index 2edb171a2..000000000
--- a/numpy/numarray/random_array.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__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 *
diff --git a/numpy/numarray/session.py b/numpy/numarray/session.py
deleted file mode 100644
index 7e9c2f1fd..000000000
--- a/numpy/numarray/session.py
+++ /dev/null
@@ -1,347 +0,0 @@
-""" 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 __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.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['load', 'save']
-
-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@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 isinstance(v, type(sys)):
- mods.append(getattr(v, "__name__"))
- return mods
-
-def _errout(*args):
- for a in args:
- print(a, end=' ', file=sys.stderr)
- print(file=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 module not in sys.modules:
- 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 = list(dictionary.keys())
- else:
- keys = variables.split(",")
-
- source_modules = _callers_modules() + list(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 True:
- o = p.load()
- if isinstance(o, _SaveSession):
- session = dict(zip(o.keys, values))
- _verbose("updating dictionary with session variables.")
- if variables is None:
- keys = list(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)
diff --git a/numpy/numarray/setup.py b/numpy/numarray/setup.py
deleted file mode 100644
index 2c2b804c9..000000000
--- a/numpy/numarray/setup.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from __future__ import division, print_function
-
-from os.path import join
-
-def configuration(parent_package='',top_path=None):
- from numpy.distutils.misc_util import Configuration
- config = Configuration('numarray', parent_package, top_path)
-
- config.add_data_files('include/numpy/*')
-
- config.add_extension('_capi',
- sources=['_capi.c'],
- )
-
- return config
-
-if __name__ == '__main__':
- from numpy.distutils.core import setup
- setup(configuration=configuration)
diff --git a/numpy/numarray/ufuncs.py b/numpy/numarray/ufuncs.py
deleted file mode 100644
index 57fc58c54..000000000
--- a/numpy/numarray/ufuncs.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh',
- 'arctan', 'arctan2', 'arctanh', 'bitwise_and', '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', 'lshift', 'maximum', 'minimum',
- 'minus', 'multiply', 'negative', 'not_equal',
- 'power', 'product', 'remainder', 'rshift', 'sin', 'sinh', 'sqrt',
- '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, \
- 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, conjugate, sign
diff --git a/numpy/numarray/util.py b/numpy/numarray/util.py
deleted file mode 100644
index b8e37a28d..000000000
--- a/numpy/numarray/util.py
+++ /dev/null
@@ -1,49 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-import os
-import numpy as np
-
-__all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError',
- 'handleError', 'get_numarray_include_dirs']
-
-class MathDomainError(ArithmeticError):
- pass
-
-
-class UnderflowError(ArithmeticError):
- pass
-
-
-class NumOverflowError(OverflowError, ArithmeticError):
- pass
-
-
-def handleError(errorStatus, sourcemsg):
- """Take error status and use error mode to handle it."""
- modes = np.geterr()
- if errorStatus & np.FPE_INVALID:
- if modes['invalid'] == "warn":
- print("Warning: Encountered invalid numeric result(s)", sourcemsg)
- if modes['invalid'] == "raise":
- raise MathDomainError(sourcemsg)
- if errorStatus & np.FPE_DIVIDEBYZERO:
- if modes['dividebyzero'] == "warn":
- print("Warning: Encountered divide by zero(s)", sourcemsg)
- if modes['dividebyzero'] == "raise":
- raise ZeroDivisionError(sourcemsg)
- if errorStatus & np.FPE_OVERFLOW:
- if modes['overflow'] == "warn":
- print("Warning: Encountered overflow(s)", sourcemsg)
- if modes['overflow'] == "raise":
- raise NumOverflowError(sourcemsg)
- if errorStatus & np.FPE_UNDERFLOW:
- if modes['underflow'] == "warn":
- print("Warning: Encountered underflow(s)", sourcemsg)
- if modes['underflow'] == "raise":
- raise UnderflowError(sourcemsg)
-
-
-def get_numarray_include_dirs():
- base = os.path.dirname(np.__file__)
- newdirs = [os.path.join(base, 'numarray', 'include')]
- return newdirs
diff --git a/numpy/oldnumeric/__init__.py b/numpy/oldnumeric/__init__.py
deleted file mode 100644
index 86cdf55f7..000000000
--- a/numpy/oldnumeric/__init__.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Don't add these to the __all__ variable though
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import warnings
-
-from numpy import *
-
-_msg = "The oldnumeric module will be dropped in Numpy 1.9"
-warnings.warn(_msg, ModuleDeprecationWarning)
-
-
-def _move_axis_to_0(a, axis):
- if axis == 0:
- return a
- n = len(a.shape)
- if axis < 0:
- axis += n
- axes = list(range(1, axis+1)) + [0,] + list(range(axis+1, n))
- return transpose(a, axes)
-
-# Add these
-from .compat import *
-from .functions import *
-from .precision import *
-from .ufuncs import *
-from .misc import *
-
-from . import compat
-from . import precision
-from . import functions
-from . import misc
-from . 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
-
-from numpy.testing import Tester
-test = Tester().test
-bench = Tester().bench
diff --git a/numpy/oldnumeric/alter_code1.py b/numpy/oldnumeric/alter_code1.py
deleted file mode 100644
index 2d4e17106..000000000
--- a/numpy/oldnumeric/alter_code1.py
+++ /dev/null
@@ -1,243 +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
- -- converts uses of '1', 's', 'w', and 'u' to
- -- 'b', 'h', 'H', and 'I'
-
- * Converts uses of type(...) is <type>
- isinstance(..., <type>)
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc']
-
-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']
-
-_chars = {'1':'b','s':'h','w':'H','u':'I'}
-
-func_re = {}
-meth_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)
-
-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 = 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
-
-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 = re.sub(r'(import\s+[^,\n\r]+,\s*)(%s)' % name,
- "\\1%s as %s" % (newname, name), fstr)
- 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 True:
- 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
-
-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")
- 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):
- savestr = 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')
- 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)
- if savestr != 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, 1
- return filestr, 0
-
-def makenewfile(name, filestr):
- fid = file(name, 'w')
- fid.write(filestr)
- fid.close()
-
-def convertfile(filename, orig=1):
- """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
- """
- fid = open(filename)
- filestr = fid.read()
- fid.close()
- filestr, changed = fromstr(filestr)
- if changed:
- if orig:
- base, ext = os.path.splitext(filename)
- os.rename(filename, base+".orig")
- else:
- os.remove(filename)
- makenewfile(filename, filestr)
-
-def fromargs(args):
- filename = args[1]
- converttree(filename)
-
-def convertall(direc=os.path.curdir, orig=1):
- """Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given
-
- For each changed file, a backup of <usesnumeric>.py is made as
- <usesnumeric>.py.orig. A new file named <usesnumeric>.py
- is then written with the updated code.
- """
- files = glob.glob(os.path.join(direc, '*.py'))
- for afile in files:
- if afile[-8:] == 'setup.py': continue # skip these
- convertfile(afile, orig)
-
-header_re = re.compile(r'(Numeric/arrayobject.h)')
-
-def convertsrc(direc=os.path.curdir, ext=None, orig=1):
- """Replace Numeric/arrayobject.h with numpy/oldnumeric.h in all files in the
- directory with extension give by list ext (if ext is None, then all files are
- replaced)."""
- if ext is None:
- files = glob.glob(os.path.join(direc, '*'))
- else:
- files = []
- for aext in ext:
- files.extend(glob.glob(os.path.join(direc, "*.%s" % aext)))
- for afile in files:
- fid = open(afile)
- fstr = fid.read()
- fid.close()
- fstr, n = header_re.subn(r'numpy/oldnumeric.h', fstr)
- if n > 0:
- if orig:
- base, ext = os.path.splitext(afile)
- os.rename(afile, base+".orig")
- else:
- os.remove(afile)
- makenewfile(afile, fstr)
-
-def _func(arg, dirname, fnames):
- convertall(dirname, orig=0)
- convertsrc(dirname, ext=['h', 'c'], orig=0)
-
-def converttree(direc=os.path.curdir):
- """Convert all .py files and source code files in the tree given
- """
- os.path.walk(direc, _func, None)
-
-
-if __name__ == '__main__':
- fromargs(sys.argv)
diff --git a/numpy/oldnumeric/alter_code2.py b/numpy/oldnumeric/alter_code2.py
deleted file mode 100644
index 1ec15c855..000000000
--- a/numpy/oldnumeric/alter_code2.py
+++ /dev/null
@@ -1,148 +0,0 @@
-"""
-This module converts code written for numpy.oldnumeric to work
-with numpy
-
-FIXME: Flesh this out.
-
-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
-
-"""
-from __future__ import division, absolute_import, print_function
-
-#__all__ = ['convertfile', 'convertall', 'converttree']
-__all__ = []
-
-import warnings
-warnings.warn("numpy.oldnumeric.alter_code2 is not working 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 True:
- 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 <usesnumeric>.py is made as
- <usesnumeric>.py.orig. A new file named <usesnumeric>.py
- is then written with the updated code.
- """
- files = glob.glob(os.path.join(direc, '*.py'))
- for afile in files:
- convertfile(afile)
-
-def _func(arg, dirname, fnames):
- convertall(dirname)
-
-def converttree(direc=os.path.curdir):
- """Convert all .py files in the tree given
-
- """
- os.path.walk(direc, _func, None)
-
-if __name__ == '__main__':
- fromargs(sys.argv)
diff --git a/numpy/oldnumeric/array_printer.py b/numpy/oldnumeric/array_printer.py
deleted file mode 100644
index 9cccc5023..000000000
--- a/numpy/oldnumeric/array_printer.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__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)
diff --git a/numpy/oldnumeric/arrayfns.py b/numpy/oldnumeric/arrayfns.py
deleted file mode 100644
index 0eb97ae9c..000000000
--- a/numpy/oldnumeric/arrayfns.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""Backward compatible with arrayfns from Numeric.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask',
- 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span',
- 'to_corners', 'zmin_zmax']
-
-import numpy as np
-from numpy import asarray
-
-class error(Exception):
- pass
-
-def array_set(vals1, indices, vals2):
- indices = asarray(indices)
- if indices.ndim != 1:
- raise ValueError("index array must be 1-d")
- if not isinstance(vals1, np.ndarray):
- raise TypeError("vals1 must be an ndarray")
- vals1 = asarray(vals1)
- vals2 = asarray(vals2)
- if vals1.ndim != vals2.ndim or vals1.ndim < 1:
- raise error("vals1 and vals2 must have same number of dimensions (>=1)")
- vals1[indices] = vals2
-
-from numpy import digitize
-from numpy import bincount as histogram
-
-def index_sort(arr):
- return asarray(arr).argsort(kind='heap')
-
-def interp(y, x, z, typ=None):
- """y(z) interpolated by treating y(x) as piecewise function
- """
- res = np.interp(z, x, y)
- if typ is None or typ == 'd':
- return res
- if typ == 'f':
- return res.astype('f')
-
- raise error("incompatible typecode")
-
-def nz(x):
- x = asarray(x, dtype=np.ubyte)
- if x.ndim != 1:
- raise TypeError("intput must have 1 dimension.")
- indxs = np.flatnonzero(x != 0)
- return indxs[-1].item()+1
-
-def reverse(x, n):
- x = asarray(x, dtype='d')
- if x.ndim != 2:
- raise ValueError("input must be 2-d")
- y = np.empty_like(x)
- if n == 0:
- y[...] = x[::-1,:]
- elif n == 1:
- y[...] = x[:, ::-1]
- return y
-
-def span(lo, hi, num, d2=0):
- x = np.linspace(lo, hi, num)
- if d2 <= 0:
- return x
- else:
- ret = np.empty((d2, num), x.dtype)
- ret[...] = x
- return ret
-
-def zmin_zmax(z, ireg):
- z = asarray(z, dtype=float)
- ireg = asarray(ireg, dtype=int)
- if z.shape != ireg.shape or z.ndim != 2:
- raise ValueError("z and ireg must be the same shape and 2-d")
- ix, iy = np.nonzero(ireg)
- # Now, add more indices
- x1m = ix - 1
- y1m = iy-1
- i1 = x1m>=0
- i2 = y1m>=0
- i3 = i1 & i2
- nix = np.r_[ix, x1m[i1], x1m[i1], ix[i2] ]
- niy = np.r_[iy, iy[i1], y1m[i3], y1m[i2]]
- # remove any negative indices
- zres = z[nix, niy]
- return zres.min().item(), zres.max().item()
-
-
-def find_mask(fs, node_edges):
- raise NotImplementedError
-
-def to_corners(arr, nv, nvsum):
- raise NotImplementedError
-
-
-def construct3(mask, itype):
- raise NotImplementedError
diff --git a/numpy/oldnumeric/compat.py b/numpy/oldnumeric/compat.py
deleted file mode 100644
index 841052656..000000000
--- a/numpy/oldnumeric/compat.py
+++ /dev/null
@@ -1,121 +0,0 @@
-"""Compatibility module containing deprecated names.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import sys
-import copy
-import pickle
-from pickle import dump, dumps
-
-import numpy.core.multiarray as multiarray
-import numpy.core.umath as um
-from numpy.core.numeric import array
-from . import functions
-
-
-__all__ = ['NewAxis',
- 'UFuncType', 'UfuncType', 'ArrayType', 'arraytype',
- 'LittleEndian', 'arrayrange', 'matrixmultiply',
- 'array_constructor', 'pickle_array',
- 'DumpArray', 'LoadArray', 'multiarray',
- # from cPickle
- 'dump', 'dumps', 'load', 'loads',
- 'Unpickler', 'Pickler'
- ]
-
-
-mu = multiarray
-
-#Use this to add a new axis to an array
-#compatibility only
-NewAxis = None
-
-#deprecated
-UFuncType = type(um.sin)
-UfuncType = type(um.sin)
-ArrayType = mu.ndarray
-arraytype = mu.ndarray
-
-LittleEndian = (sys.byteorder == 'little')
-
-from numpy import deprecate
-
-# backward compatibility
-arrayrange = deprecate(functions.arange, 'arrayrange', 'arange')
-
-# deprecated names
-matrixmultiply = deprecate(mu.dot, 'matrixmultiply', 'dot')
-
-def DumpArray(m, fp):
- m.dump(fp)
-
-def LoadArray(fp):
- return pickle.load(fp)
-
-def array_constructor(shape, typecode, thestr, Endian=LittleEndian):
- if typecode == "O":
- x = array(thestr, "O")
- else:
- x = mu.fromstring(thestr, typecode)
- x.shape = shape
- if LittleEndian != Endian:
- return x.byteswap(True)
- 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))
-
-def loads(astr):
- arr = pickle.loads(astr.replace('Numeric', 'numpy.oldnumeric'))
- return arr
-
-def load(fp):
- return loads(fp.read())
-
-def _LoadArray(fp):
- from . import typeconv
- ln = fp.readline().split()
- if ln[0][0] == 'A': ln[0] = ln[0][1:]
- typecode = ln[0][0]
- endian = ln[0][1]
- itemsize = int(ln[0][2:])
- shape = [int(x) for x in ln[1:]]
- sz = itemsize
- for val in shape:
- sz *= val
- dstr = fp.read(sz)
- m = mu.fromstring(dstr, typeconv.convtypecode(typecode))
- m.shape = shape
-
- if (LittleEndian and endian == 'B') or (not LittleEndian and endian == 'L'):
- return m.byteswap(True)
- else:
- return m
-
-if sys.version_info[0] >= 3:
- class Unpickler(pickle.Unpickler):
- # XXX: should we implement this? It's not completely straightforward
- # to do.
- def __init__(self, *a, **kw):
- raise NotImplementedError(
- "numpy.oldnumeric.Unpickler is not supported on Python 3")
-else:
- class Unpickler(pickle.Unpickler):
- def load_array(self):
- self.stack.append(_LoadArray(self))
-
- dispatch = copy.copy(pickle.Unpickler.dispatch)
- dispatch['A'] = load_array
-
-class Pickler(pickle.Pickler):
- def __init__(self, *args, **kwds):
- raise NotImplementedError("Don't pickle new arrays with this")
- def save_array(self, object):
- raise NotImplementedError("Don't pickle new arrays with this")
diff --git a/numpy/oldnumeric/fft.py b/numpy/oldnumeric/fft.py
deleted file mode 100644
index 0fd3ae48e..000000000
--- a/numpy/oldnumeric/fft.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__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
diff --git a/numpy/oldnumeric/fix_default_axis.py b/numpy/oldnumeric/fix_default_axis.py
deleted file mode 100644
index d4235a94c..000000000
--- a/numpy/oldnumeric/fix_default_axis.py
+++ /dev/null
@@ -1,294 +0,0 @@
-"""
-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
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['convertfile', 'convertall', 'converttree']
-
-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.<name>
- # change this to import numpy.oldnumeric as numpy
- # 2.) import numpy as XXXX with subsequent use of
- # XXXX.<name> ==> import numpy.oldnumeric as XXXX
- # 3.) from numpy import *
- # with subsequent use of one of the names
- # 4.) from numpy import ..., <name>, ... (could span multiple
- # lines. ==> remove all names from list and
- # add from numpy.oldnumeric import <name>
-
- 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 True:
- 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 <usesnumeric>.py is made as
- <usesnumeric>.py.orig. A new file named <usesnumeric>.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)
diff --git a/numpy/oldnumeric/functions.py b/numpy/oldnumeric/functions.py
deleted file mode 100644
index 156a09a43..000000000
--- a/numpy/oldnumeric/functions.py
+++ /dev/null
@@ -1,127 +0,0 @@
-"""Functions that should behave the same as Numeric and need changing
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import numpy as np
-import numpy.core.multiarray as mu
-import numpy.core.numeric as nn
-from .typeconv import convtypecode, convtypecode2
-
-__all__ = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue',
- 'cumsum', 'cumproduct', 'compress', 'fromfunction',
- 'ones', 'empty', 'identity', 'zeros', 'array', 'asarray',
- 'nonzero', 'reshape', 'arange', 'fromstring', 'ravel', 'trace',
- 'indices', 'where', 'sarray', 'cross_product', 'argmax', 'argmin',
- 'average']
-
-def take(a, indicies, axis=0):
- return np.take(a, indicies, axis)
-
-def repeat(a, repeats, axis=0):
- return np.repeat(a, repeats, axis)
-
-def sum(x, axis=0):
- return np.sum(x, axis)
-
-def product(x, axis=0):
- return np.product(x, axis)
-
-def sometrue(x, axis=0):
- return np.sometrue(x, axis)
-
-def alltrue(x, axis=0):
- return np.alltrue(x, axis)
-
-def cumsum(x, axis=0):
- return np.cumsum(x, axis)
-
-def cumproduct(x, axis=0):
- return np.cumproduct(x, axis)
-
-def argmax(x, axis=-1):
- return np.argmax(x, axis)
-
-def argmin(x, axis=-1):
- return np.argmin(x, axis)
-
-def compress(condition, m, axis=-1):
- return np.compress(condition, m, axis)
-
-def fromfunction(args, dimensions):
- return np.fromfunction(args, dimensions, dtype=int)
-
-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)
-
-def array(sequence, typecode=None, copy=1, savespace=0, dtype=None):
- 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)
-
-def nonzero(a):
- res = np.nonzero(a)
- if len(res) == 1:
- return res[0]
- else:
- raise ValueError("Input argument must be 1d")
-
-def reshape(a, shape):
- return np.reshape(a, shape)
-
-def arange(start, stop=None, step=1, typecode=None, dtype=None):
- dtype = convtypecode2(typecode, dtype)
- return mu.arange(start, stop, step, dtype)
-
-def fromstring(string, typecode='l', count=-1, dtype=None):
- dtype = convtypecode(typecode, dtype)
- return mu.fromstring(string, dtype, count=count)
-
-def ravel(m):
- return np.ravel(m)
-
-def trace(a, offset=0, axis1=0, axis2=1):
- return np.trace(a, offset=0, axis1=0, axis2=1)
-
-def indices(dimensions, typecode=None, dtype=None):
- dtype = convtypecode(typecode, dtype)
- return np.indices(dimensions, dtype)
-
-def where(condition, x, y):
- return np.where(condition, x, y)
-
-def cross_product(a, b, axis1=-1, axis2=-1):
- return np.cross(a, b, axis1, axis2)
-
-def average(a, axis=0, weights=None, returned=False):
- return np.average(a, axis, weights, returned)
diff --git a/numpy/oldnumeric/linear_algebra.py b/numpy/oldnumeric/linear_algebra.py
deleted file mode 100644
index 8208637b8..000000000
--- a/numpy/oldnumeric/linear_algebra.py
+++ /dev/null
@@ -1,85 +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.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__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)
diff --git a/numpy/oldnumeric/ma.py b/numpy/oldnumeric/ma.py
deleted file mode 100644
index d41c68edc..000000000
--- a/numpy/oldnumeric/ma.py
+++ /dev/null
@@ -1,2296 +0,0 @@
-"""MA: a facility for dealing with missing observations
-
-MA is generally used as a numpy.array look-alike.
-by Paul F. Dubois.
-
-Copyright 1999, 2000, 2001 Regents of the University of California.
-Released for unlimited redistribution.
-Adapted for numpy_core 2005 by Travis Oliphant and
-(mainly) Paul Dubois.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import sys
-import types
-import warnings
-from functools import reduce
-
-import numpy.core.umath as umath
-import numpy.core.fromnumeric as fromnumeric
-import numpy.core.numeric as numeric
-from numpy.core.numeric import newaxis, ndarray, inf
-from numpy.core.fromnumeric import amax, amin
-from numpy.core.numerictypes import bool_, typecodes
-import numpy.core.numeric as numeric
-from numpy.compat import bytes, long
-
-if sys.version_info[0] >= 3:
- _MAXINT = sys.maxsize
- _MININT = -sys.maxsize - 1
-else:
- _MAXINT = sys.maxint
- _MININT = -sys.maxint - 1
-
-
-# Ufunc domain lookup for __array_wrap__
-ufunc_domain = {}
-# Ufunc fills lookup for __array__
-ufunc_fills = {}
-
-MaskType = bool_
-nomask = MaskType(0)
-divide_tolerance = 1.e-35
-
-class MAError (Exception):
- def __init__ (self, args=None):
- "Create an exception"
-
- # The .args attribute must be a tuple.
- if not isinstance(args, tuple):
- args = (args,)
- self.args = args
- def __str__(self):
- "Calculate the string representation"
- return str(self.args[0])
- __repr__ = __str__
-
-class _MaskedPrintOption:
- "One instance of this class, masked_print_option, is created."
- def __init__ (self, display):
- "Create the masked print option object."
- self.set_display(display)
- self._enabled = 1
-
- def display (self):
- "Show what prints for masked values."
- return self._display
-
- def set_display (self, s):
- "set_display(s) sets what prints for masked values."
- self._display = s
-
- def enabled (self):
- "Is the use of the display value enabled?"
- return self._enabled
-
- def enable(self, flag=1):
- "Set the enabling flag to flag."
- self._enabled = flag
-
- def __str__ (self):
- return str(self._display)
-
- __repr__ = __str__
-
-#if you single index into a masked location you get this object.
-masked_print_option = _MaskedPrintOption('--')
-
-# Use single element arrays or scalars.
-default_real_fill_value = 1.e20
-default_complex_fill_value = 1.e20 + 0.0j
-default_character_fill_value = '-'
-default_integer_fill_value = 999999
-default_object_fill_value = '?'
-
-def default_fill_value (obj):
- "Function to calculate default fill value for an object."
- if isinstance(obj, float):
- return default_real_fill_value
- elif isinstance(obj, int) or isinstance(obj, long):
- return default_integer_fill_value
- elif isinstance(obj, bytes):
- return default_character_fill_value
- elif isinstance(obj, complex):
- return default_complex_fill_value
- elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
- x = obj.dtype.char
- if x in typecodes['Float']:
- return default_real_fill_value
- if x in typecodes['Integer']:
- return default_integer_fill_value
- if x in typecodes['Complex']:
- return default_complex_fill_value
- if x in typecodes['Character']:
- return default_character_fill_value
- if x in typecodes['UnsignedInteger']:
- return umath.absolute(default_integer_fill_value)
- return default_object_fill_value
- else:
- return default_object_fill_value
-
-def minimum_fill_value (obj):
- "Function to calculate default fill value suitable for taking minima."
- if isinstance(obj, float):
- return numeric.inf
- elif isinstance(obj, int) or isinstance(obj, long):
- return _MAXINT
- elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
- x = obj.dtype.char
- if x in typecodes['Float']:
- return numeric.inf
- if x in typecodes['Integer']:
- return _MAXINT
- if x in typecodes['UnsignedInteger']:
- return _MAXINT
- else:
- raise TypeError('Unsuitable type for calculating minimum.')
-
-def maximum_fill_value (obj):
- "Function to calculate default fill value suitable for taking maxima."
- if isinstance(obj, float):
- return -inf
- elif isinstance(obj, int) or isinstance(obj, long):
- return -_MAXINT
- elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
- x = obj.dtype.char
- if x in typecodes['Float']:
- return -inf
- if x in typecodes['Integer']:
- return -_MAXINT
- if x in typecodes['UnsignedInteger']:
- return 0
- else:
- raise TypeError('Unsuitable type for calculating maximum.')
-
-def set_fill_value (a, fill_value):
- "Set fill value of a if it is a masked array."
- if isMaskedArray(a):
- a.set_fill_value (fill_value)
-
-def getmask (a):
- """Mask of values in a; could be nomask.
- Returns nomask if a is not a masked array.
- To get an array for sure use getmaskarray."""
- if isinstance(a, MaskedArray):
- return a.raw_mask()
- else:
- return nomask
-
-def getmaskarray (a):
- """Mask of values in a; an array of zeros if mask is nomask
- or not a masked array, and is a byte-sized integer.
- Do not try to add up entries, for example.
- """
- m = getmask(a)
- if m is nomask:
- return make_mask_none(shape(a))
- else:
- return m
-
-def is_mask (m):
- """Is m a legal mask? Does not check contents, only type.
- """
- try:
- return m.dtype.type is MaskType
- except AttributeError:
- return False
-
-def make_mask (m, copy=0, flag=0):
- """make_mask(m, copy=0, flag=0)
- return m as a mask, creating a copy if necessary or requested.
- Can accept any sequence of integers or nomask. Does not check
- that contents must be 0s and 1s.
- if flag, return nomask if m contains no true elements.
- """
- if m is nomask:
- return nomask
- elif isinstance(m, ndarray):
- if m.dtype.type is MaskType:
- if copy:
- result = numeric.array(m, dtype=MaskType, copy=copy)
- else:
- result = m
- else:
- result = m.astype(MaskType)
- else:
- result = filled(m, True).astype(MaskType)
-
- if flag and not fromnumeric.sometrue(fromnumeric.ravel(result)):
- return nomask
- else:
- return result
-
-def make_mask_none (s):
- "Return a mask of all zeros of shape s."
- result = numeric.zeros(s, dtype=MaskType)
- result.shape = s
- return result
-
-def mask_or (m1, m2):
- """Logical or of the mask candidates m1 and m2, treating nomask as false.
- Result may equal m1 or m2 if the other is nomask.
- """
- if m1 is nomask: return make_mask(m2)
- if m2 is nomask: return make_mask(m1)
- if m1 is m2 and is_mask(m1): return m1
- return make_mask(umath.logical_or(m1, m2))
-
-def filled (a, value = None):
- """a as a contiguous numeric array with any masked areas replaced by value
- if value is None or the special element "masked", get_fill_value(a)
- is used instead.
-
- If a is already a contiguous numeric array, a itself is returned.
-
- filled(a) can be used to be sure that the result is numeric when
- passing an object a to other software ignorant of MA, in particular to
- numeric itself.
- """
- if isinstance(a, MaskedArray):
- return a.filled(value)
- elif isinstance(a, ndarray) and a.flags['CONTIGUOUS']:
- return a
- elif isinstance(a, dict):
- return numeric.array(a, 'O')
- else:
- return numeric.array(a)
-
-def get_fill_value (a):
- """
- The fill value of a, if it has one; otherwise, the default fill value
- for that type.
- """
- if isMaskedArray(a):
- result = a.fill_value()
- else:
- result = default_fill_value(a)
- return result
-
-def common_fill_value (a, b):
- "The common fill_value of a and b, if there is one, or None"
- t1 = get_fill_value(a)
- t2 = get_fill_value(b)
- if t1 == t2: return t1
- return None
-
-# Domain functions return 1 where the argument(s) are not in the domain.
-class domain_check_interval:
- "domain_check_interval(a,b)(x) = true where x < a or y > b"
- def __init__(self, y1, y2):
- "domain_check_interval(a,b)(x) = true where x < a or y > b"
- self.y1 = y1
- self.y2 = y2
-
- def __call__ (self, x):
- "Execute the call behavior."
- return umath.logical_or(umath.greater (x, self.y2),
- umath.less(x, self.y1)
- )
-
-class domain_tan:
- "domain_tan(eps) = true where abs(cos(x)) < eps)"
- def __init__(self, eps):
- "domain_tan(eps) = true where abs(cos(x)) < eps)"
- self.eps = eps
-
- def __call__ (self, x):
- "Execute the call behavior."
- return umath.less(umath.absolute(umath.cos(x)), self.eps)
-
-class domain_greater:
- "domain_greater(v)(x) = true where x <= v"
- def __init__(self, critical_value):
- "domain_greater(v)(x) = true where x <= v"
- self.critical_value = critical_value
-
- def __call__ (self, x):
- "Execute the call behavior."
- return umath.less_equal (x, self.critical_value)
-
-class domain_greater_equal:
- "domain_greater_equal(v)(x) = true where x < v"
- def __init__(self, critical_value):
- "domain_greater_equal(v)(x) = true where x < v"
- self.critical_value = critical_value
-
- def __call__ (self, x):
- "Execute the call behavior."
- return umath.less (x, self.critical_value)
-
-class masked_unary_operation:
- def __init__ (self, aufunc, fill=0, domain=None):
- """ masked_unary_operation(aufunc, fill=0, domain=None)
- aufunc(fill) must be defined
- self(x) returns aufunc(x)
- with masked values where domain(x) is true or getmask(x) is true.
- """
- self.f = aufunc
- self.fill = fill
- self.domain = domain
- self.__doc__ = getattr(aufunc, "__doc__", str(aufunc))
- self.__name__ = getattr(aufunc, "__name__", str(aufunc))
- ufunc_domain[aufunc] = domain
- ufunc_fills[aufunc] = fill,
-
- def __call__ (self, a, *args, **kwargs):
- "Execute the call behavior."
-# numeric tries to return scalars rather than arrays when given scalars.
- m = getmask(a)
- d1 = filled(a, self.fill)
- if self.domain is not None:
- m = mask_or(m, self.domain(d1))
- result = self.f(d1, *args, **kwargs)
- return masked_array(result, m)
-
- def __str__ (self):
- return "Masked version of " + str(self.f)
-
-
-class domain_safe_divide:
- def __init__ (self, tolerance=divide_tolerance):
- self.tolerance = tolerance
- def __call__ (self, a, b):
- return umath.absolute(a) * self.tolerance >= umath.absolute(b)
-
-class domained_binary_operation:
- """Binary operations that have a domain, like divide. These are complicated
- so they are a separate class. They have no reduce, outer or accumulate.
- """
- def __init__ (self, abfunc, domain, fillx=0, filly=0):
- """abfunc(fillx, filly) must be defined.
- abfunc(x, filly) = x for all x to enable reduce.
- """
- self.f = abfunc
- self.domain = domain
- self.fillx = fillx
- self.filly = filly
- self.__doc__ = getattr(abfunc, "__doc__", str(abfunc))
- self.__name__ = getattr(abfunc, "__name__", str(abfunc))
- ufunc_domain[abfunc] = domain
- ufunc_fills[abfunc] = fillx, filly
-
- def __call__(self, a, b):
- "Execute the call behavior."
- ma = getmask(a)
- mb = getmask(b)
- d1 = filled(a, self.fillx)
- d2 = filled(b, self.filly)
- t = self.domain(d1, d2)
-
- if fromnumeric.sometrue(t, None):
- d2 = where(t, self.filly, d2)
- mb = mask_or(mb, t)
- m = mask_or(ma, mb)
- result = self.f(d1, d2)
- return masked_array(result, m)
-
- def __str__ (self):
- return "Masked version of " + str(self.f)
-
-class masked_binary_operation:
- def __init__ (self, abfunc, fillx=0, filly=0):
- """abfunc(fillx, filly) must be defined.
- abfunc(x, filly) = x for all x to enable reduce.
- """
- self.f = abfunc
- self.fillx = fillx
- self.filly = filly
- self.__doc__ = getattr(abfunc, "__doc__", str(abfunc))
- ufunc_domain[abfunc] = None
- ufunc_fills[abfunc] = fillx, filly
-
- def __call__ (self, a, b, *args, **kwargs):
- "Execute the call behavior."
- m = mask_or(getmask(a), getmask(b))
- 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):
- """Reduce target along the given axis with this function."""
- m = getmask(target)
- t = filled(target, self.filly)
- if t.shape == ():
- t = t.reshape(1)
- if m is not nomask:
- m = make_mask(m, copy=1)
- m.shape = (1,)
- if m is nomask:
- t = self.f.reduce(t, axis)
- else:
- t = masked_array (t, m)
- # XXX: "or t.dtype" below is a workaround for what appears
- # XXX: to be a bug in reduce.
- t = self.f.reduce(filled(t, self.filly), axis,
- dtype=dtype or t.dtype)
- m = umath.logical_and.reduce(m, axis)
- if isinstance(t, ndarray):
- return masked_array(t, m, get_fill_value(target))
- elif m:
- return masked
- else:
- return t
-
- def outer (self, a, b):
- "Return the function applied to the outer product of a and b."
- ma = getmask(a)
- mb = getmask(b)
- if ma is nomask and mb is nomask:
- m = nomask
- else:
- ma = getmaskarray(a)
- mb = getmaskarray(b)
- m = logical_or.outer(ma, mb)
- d = self.f.outer(filled(a, self.fillx), filled(b, self.filly))
- return masked_array(d, m)
-
- def accumulate (self, target, axis=0):
- """Accumulate target along axis after filling with y fill value."""
- t = filled(target, self.filly)
- return masked_array (self.f.accumulate (t, axis))
- def __str__ (self):
- return "Masked version of " + str(self.f)
-
-sqrt = masked_unary_operation(umath.sqrt, 0.0, domain_greater_equal(0.0))
-log = masked_unary_operation(umath.log, 1.0, domain_greater(0.0))
-log10 = masked_unary_operation(umath.log10, 1.0, domain_greater(0.0))
-exp = masked_unary_operation(umath.exp)
-conjugate = masked_unary_operation(umath.conjugate)
-sin = masked_unary_operation(umath.sin)
-cos = masked_unary_operation(umath.cos)
-tan = masked_unary_operation(umath.tan, 0.0, domain_tan(1.e-35))
-arcsin = masked_unary_operation(umath.arcsin, 0.0, domain_check_interval(-1.0, 1.0))
-arccos = masked_unary_operation(umath.arccos, 0.0, domain_check_interval(-1.0, 1.0))
-arctan = masked_unary_operation(umath.arctan)
-# Missing from numeric
-arcsinh = masked_unary_operation(umath.arcsinh)
-arccosh = masked_unary_operation(umath.arccosh, 1.0, domain_greater_equal(1.0))
-arctanh = masked_unary_operation(umath.arctanh, 0.0, domain_check_interval(-1.0+1e-15, 1.0-1e-15))
-sinh = masked_unary_operation(umath.sinh)
-cosh = masked_unary_operation(umath.cosh)
-tanh = masked_unary_operation(umath.tanh)
-absolute = masked_unary_operation(umath.absolute)
-fabs = masked_unary_operation(umath.fabs)
-negative = masked_unary_operation(umath.negative)
-
-def nonzero(a):
- """returns the indices of the elements of a which are not zero
- and not masked
- """
- return numeric.asarray(filled(a, 0).nonzero())
-
-around = masked_unary_operation(fromnumeric.round_)
-floor = masked_unary_operation(umath.floor)
-ceil = masked_unary_operation(umath.ceil)
-logical_not = masked_unary_operation(umath.logical_not)
-
-add = masked_binary_operation(umath.add)
-subtract = masked_binary_operation(umath.subtract)
-subtract.reduce = None
-multiply = masked_binary_operation(umath.multiply, 1, 1)
-divide = domained_binary_operation(umath.divide, domain_safe_divide(), 0, 1)
-true_divide = domained_binary_operation(umath.true_divide, domain_safe_divide(), 0, 1)
-floor_divide = domained_binary_operation(umath.floor_divide, domain_safe_divide(), 0, 1)
-remainder = domained_binary_operation(umath.remainder, domain_safe_divide(), 0, 1)
-fmod = domained_binary_operation(umath.fmod, domain_safe_divide(), 0, 1)
-hypot = masked_binary_operation(umath.hypot)
-arctan2 = masked_binary_operation(umath.arctan2, 0.0, 1.0)
-arctan2.reduce = None
-equal = masked_binary_operation(umath.equal)
-equal.reduce = None
-not_equal = masked_binary_operation(umath.not_equal)
-not_equal.reduce = None
-less_equal = masked_binary_operation(umath.less_equal)
-less_equal.reduce = None
-greater_equal = masked_binary_operation(umath.greater_equal)
-greater_equal.reduce = None
-less = masked_binary_operation(umath.less)
-less.reduce = None
-greater = masked_binary_operation(umath.greater)
-greater.reduce = None
-logical_and = masked_binary_operation(umath.logical_and)
-alltrue = masked_binary_operation(umath.logical_and, 1, 1).reduce
-logical_or = masked_binary_operation(umath.logical_or)
-sometrue = logical_or.reduce
-logical_xor = masked_binary_operation(umath.logical_xor)
-bitwise_and = masked_binary_operation(umath.bitwise_and)
-bitwise_or = masked_binary_operation(umath.bitwise_or)
-bitwise_xor = masked_binary_operation(umath.bitwise_xor)
-
-def rank (object):
- return fromnumeric.rank(filled(object))
-
-def shape (object):
- return fromnumeric.shape(filled(object))
-
-def size (object, axis=None):
- return fromnumeric.size(filled(object), axis)
-
-class MaskedArray (object):
- """Arrays with possibly masked values.
- Masked values of 1 exclude the corresponding element from
- any computation.
-
- Construction:
- x = array(data, dtype=None, copy=True, order=False,
- mask = nomask, fill_value=None)
-
- If copy=False, every effort is made not to copy the data:
- If data is a MaskedArray, and argument mask=nomask,
- then the candidate data is data.data and the
- mask used is data.mask. If data is a numeric array,
- it is used as the candidate raw data.
- If dtype is not None and
- is != data.dtype.char then a data copy is required.
- Otherwise, the candidate is used.
-
- If a data copy is required, raw data stored is the result of:
- numeric.array(data, dtype=dtype.char, copy=copy)
-
- If mask is nomask there are no masked values. Otherwise mask must
- be convertible to an array of booleans with the same shape as x.
-
- fill_value is used to fill in masked values when necessary,
- such as when printing and in method/function filled().
- The fill_value is not used for computation within this module.
- """
- __array_priority__ = 10.1
- def __init__(self, data, dtype=None, copy=True, order=False,
- mask=nomask, fill_value=None):
- """array(data, dtype=None, copy=True, order=False, mask=nomask, fill_value=None)
- If data already a numeric array, its dtype becomes the default value of dtype.
- """
- if dtype is None:
- tc = None
- else:
- tc = numeric.dtype(dtype)
- need_data_copied = copy
- if isinstance(data, MaskedArray):
- c = data.data
- if tc is None:
- tc = c.dtype
- elif tc != c.dtype:
- need_data_copied = True
- if mask is nomask:
- mask = data.mask
- elif mask is not nomask: #attempting to change the mask
- need_data_copied = True
-
- elif isinstance(data, ndarray):
- c = data
- if tc is None:
- tc = c.dtype
- elif tc != c.dtype:
- need_data_copied = True
- else:
- need_data_copied = False #because I'll do it now
- c = numeric.array(data, dtype=tc, copy=True, order=order)
- tc = c.dtype
-
- if need_data_copied:
- if tc == c.dtype:
- self._data = numeric.array(c, dtype=tc, copy=True, order=order)
- else:
- self._data = c.astype(tc)
- else:
- self._data = c
-
- if mask is nomask:
- self._mask = nomask
- self._shared_mask = 0
- else:
- self._mask = make_mask (mask)
- if self._mask is nomask:
- self._shared_mask = 0
- else:
- self._shared_mask = (self._mask is mask)
- nm = size(self._mask)
- nd = size(self._data)
- if nm != nd:
- if nm == 1:
- self._mask = fromnumeric.resize(self._mask, self._data.shape)
- self._shared_mask = 0
- elif nd == 1:
- self._data = fromnumeric.resize(self._data, self._mask.shape)
- self._data.shape = self._mask.shape
- else:
- raise MAError("Mask and data not compatible.")
- elif nm == 1 and shape(self._mask) != shape(self._data):
- self.unshare_mask()
- self._mask.shape = self._data.shape
-
- self.set_fill_value(fill_value)
-
- def __array__ (self, t=None, context=None):
- "Special hook for numeric. Converts to numeric if possible."
- if self._mask is not nomask:
- if fromnumeric.ravel(self._mask).any():
- if context is None:
- warnings.warn("Cannot automatically convert masked array to "\
- "numeric because data\n is masked in one or "\
- "more locations.");
- return self._data
- #raise MAError(
- # """Cannot automatically convert masked array to numeric because data
- # is masked in one or more locations.
- # """)
- else:
- func, args, i = context
- fills = ufunc_fills.get(func)
- if fills is None:
- raise MAError("%s not known to ma" % func)
- return self.filled(fills[i])
- else: # Mask is all false
- # Optimize to avoid future invocations of this section.
- self._mask = nomask
- self._shared_mask = 0
- if t:
- return self._data.astype(t)
- else:
- return self._data
-
- 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])
- if domain is not None:
- m = mask_or(m, domain(*[getattr(a, '_data', a)
- for a in args]))
- if m is not nomask:
- try:
- shape = array.shape
- except AttributeError:
- pass
- else:
- if m.shape != shape:
- m = reduce(mask_or, [getmaskarray(a) for a in args])
-
- return MaskedArray(array, copy=False, mask=m)
-
- def _get_shape(self):
- "Return the current shape."
- return self._data.shape
-
- def _set_shape (self, newshape):
- "Set the array's shape."
- self._data.shape = newshape
- if self._mask is not nomask:
- self._mask = self._mask.copy()
- self._mask.shape = newshape
-
- def _get_flat(self):
- """Calculate the flat value.
- """
- if self._mask is nomask:
- return masked_array(self._data.ravel(), mask=nomask,
- fill_value = self.fill_value())
- else:
- return masked_array(self._data.ravel(),
- mask=self._mask.ravel(),
- fill_value = self.fill_value())
-
- def _set_flat (self, value):
- "x.flat = value"
- y = self.ravel()
- y[:] = value
-
- def _get_real(self):
- "Get the real part of a complex array."
- if self._mask is nomask:
- return masked_array(self._data.real, mask=nomask,
- fill_value = self.fill_value())
- else:
- return masked_array(self._data.real, mask=self._mask,
- fill_value = self.fill_value())
-
- def _set_real (self, value):
- "x.real = value"
- y = self.real
- y[...] = value
-
- def _get_imaginary(self):
- "Get the imaginary part of a complex array."
- if self._mask is nomask:
- return masked_array(self._data.imag, mask=nomask,
- fill_value = self.fill_value())
- else:
- return masked_array(self._data.imag, mask=self._mask,
- fill_value = self.fill_value())
-
- def _set_imaginary (self, value):
- "x.imaginary = value"
- y = self.imaginary
- y[...] = value
-
- def __str__(self):
- """Calculate the str representation, using masked for fill if
- it is enabled. Otherwise fill with fill value.
- """
- if masked_print_option.enabled():
- f = masked_print_option
- # XXX: Without the following special case masked
- # XXX: would print as "[--]", not "--". Can we avoid
- # XXX: checks for masked by choosing a different value
- # XXX: for the masked singleton? 2005-01-05 -- sasha
- if self is masked:
- return str(f)
- m = self._mask
- if m is not nomask and m.shape == () and m:
- return str(f)
- # convert to object array to make filled work
- self = self.astype(object)
- else:
- f = self.fill_value()
- res = self.filled(f)
- return str(res)
-
- def __repr__(self):
- """Calculate the repr representation, using masked for fill if
- it is enabled. Otherwise fill with fill value.
- """
- with_mask = """\
-array(data =
- %(data)s,
- mask =
- %(mask)s,
- fill_value=%(fill)s)
-"""
- with_mask1 = """\
-array(data = %(data)s,
- mask = %(mask)s,
- fill_value=%(fill)s)
-"""
- without_mask = """array(
- %(data)s)"""
- without_mask1 = """array(%(data)s)"""
-
- n = len(self.shape)
- if self._mask is nomask:
- if n <= 1:
- return without_mask1 % {'data':str(self.filled())}
- return without_mask % {'data':str(self.filled())}
- else:
- if n <= 1:
- return with_mask % {
- 'data': str(self.filled()),
- 'mask': str(self._mask),
- 'fill': str(self.fill_value())
- }
- return with_mask % {
- 'data': str(self.filled()),
- 'mask': str(self._mask),
- 'fill': str(self.fill_value())
- }
- without_mask1 = """array(%(data)s)"""
- if self._mask is nomask:
- return without_mask % {'data':str(self.filled())}
- else:
- return with_mask % {
- 'data': str(self.filled()),
- 'mask': str(self._mask),
- 'fill': str(self.fill_value())
- }
-
- def __float__(self):
- "Convert self to float."
- self.unmask()
- if self._mask is not nomask:
- raise MAError('Cannot convert masked element to a Python float.')
- return float(self.data.item())
-
- def __int__(self):
- "Convert self to int."
- self.unmask()
- if self._mask is not nomask:
- raise MAError('Cannot convert masked element to a Python int.')
- return int(self.data.item())
-
- def __getitem__(self, i):
- "Get item described by i. Not a copy as in previous versions."
- self.unshare_mask()
- m = self._mask
- dout = self._data[i]
- if m is nomask:
- try:
- if dout.size == 1:
- return dout
- else:
- return masked_array(dout, fill_value=self._fill_value)
- except AttributeError:
- return dout
- mi = m[i]
- if mi.size == 1:
- if mi:
- return masked
- else:
- return dout
- else:
- return masked_array(dout, mi, fill_value=self._fill_value)
-
-# --------
-# setitem and setslice notes
-# note that if value is masked, it means to mask those locations.
-# setting a value changes the mask to match the value in those locations.
-
- def __setitem__(self, index, value):
- "Set item described by index. If value is masked, mask those locations."
- d = self._data
- if self is masked:
- raise MAError('Cannot alter masked elements.')
- if value is masked:
- if self._mask is nomask:
- self._mask = make_mask_none(d.shape)
- self._shared_mask = False
- else:
- self.unshare_mask()
- self._mask[index] = True
- return
- m = getmask(value)
- value = filled(value).astype(d.dtype)
- d[index] = value
- if m is nomask:
- if self._mask is not nomask:
- self.unshare_mask()
- self._mask[index] = False
- else:
- if self._mask is nomask:
- self._mask = make_mask_none(d.shape)
- self._shared_mask = True
- else:
- self.unshare_mask()
- self._mask[index] = m
-
- def __nonzero__(self):
- """returns true if any element is non-zero or masked
-
- """
- # XXX: This changes bool conversion logic from MA.
- # XXX: In MA bool(a) == len(a) != 0, but in numpy
- # XXX: scalars do not have len
- m = self._mask
- d = self._data
- return bool(m is not nomask and m.any()
- or d is not nomask and d.any())
-
- def __bool__(self):
- """returns true if any element is non-zero or masked
-
- """
- # XXX: This changes bool conversion logic from MA.
- # XXX: In MA bool(a) == len(a) != 0, but in numpy
- # XXX: scalars do not have len
- m = self._mask
- d = self._data
- return bool(m is not nomask and m.any()
- or d is not nomask and d.any())
-
- def __len__ (self):
- """Return length of first dimension. This is weird but Python's
- slicing behavior depends on it."""
- return len(self._data)
-
- def __and__(self, other):
- "Return bitwise_and"
- return bitwise_and(self, other)
-
- def __or__(self, other):
- "Return bitwise_or"
- return bitwise_or(self, other)
-
- def __xor__(self, other):
- "Return bitwise_xor"
- return bitwise_xor(self, other)
-
- __rand__ = __and__
- __ror__ = __or__
- __rxor__ = __xor__
-
- def __abs__(self):
- "Return absolute(self)"
- return absolute(self)
-
- def __neg__(self):
- "Return negative(self)"
- return negative(self)
-
- def __pos__(self):
- "Return array(self)"
- return array(self)
-
- def __add__(self, other):
- "Return add(self, other)"
- return add(self, other)
-
- __radd__ = __add__
-
- def __mod__ (self, other):
- "Return remainder(self, other)"
- return remainder(self, other)
-
- def __rmod__ (self, other):
- "Return remainder(other, self)"
- return remainder(other, self)
-
- def __lshift__ (self, n):
- return left_shift(self, n)
-
- def __rshift__ (self, n):
- return right_shift(self, n)
-
- def __sub__(self, other):
- "Return subtract(self, other)"
- return subtract(self, other)
-
- def __rsub__(self, other):
- "Return subtract(other, self)"
- return subtract(other, self)
-
- def __mul__(self, other):
- "Return multiply(self, other)"
- return multiply(self, other)
-
- __rmul__ = __mul__
-
- def __div__(self, other):
- "Return divide(self, other)"
- return divide(self, other)
-
- def __rdiv__(self, other):
- "Return divide(other, self)"
- return divide(other, self)
-
- def __truediv__(self, other):
- "Return divide(self, other)"
- return true_divide(self, other)
-
- def __rtruediv__(self, other):
- "Return divide(other, self)"
- return true_divide(other, self)
-
- def __floordiv__(self, other):
- "Return divide(self, other)"
- return floor_divide(self, other)
-
- def __rfloordiv__(self, other):
- "Return divide(other, self)"
- return floor_divide(other, self)
-
- def __pow__(self, other, third=None):
- "Return power(self, other, third)"
- return power(self, other, third)
-
- def __sqrt__(self):
- "Return sqrt(self)"
- return sqrt(self)
-
- def __iadd__(self, other):
- "Add other to self in place."
- t = self._data.dtype.char
- f = filled(other, 0)
- t1 = f.dtype.char
- if t == t1:
- pass
- elif t in typecodes['Integer']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Float']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Complex']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- elif t1 in typecodes['Complex']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- else:
- raise TypeError('Incorrect type for in-place operation.')
-
- if self._mask is nomask:
- self._data += f
- m = getmask(other)
- self._mask = m
- self._shared_mask = m is not nomask
- else:
- result = add(self, masked_array(f, mask=getmask(other)))
- self._data = result.data
- self._mask = result.mask
- self._shared_mask = 1
- return self
-
- def __imul__(self, other):
- "Add other to self in place."
- t = self._data.dtype.char
- f = filled(other, 0)
- t1 = f.dtype.char
- if t == t1:
- pass
- elif t in typecodes['Integer']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Float']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Complex']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- elif t1 in typecodes['Complex']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- else:
- raise TypeError('Incorrect type for in-place operation.')
-
- if self._mask is nomask:
- self._data *= f
- m = getmask(other)
- self._mask = m
- self._shared_mask = m is not nomask
- else:
- result = multiply(self, masked_array(f, mask=getmask(other)))
- self._data = result.data
- self._mask = result.mask
- self._shared_mask = 1
- return self
-
- def __isub__(self, other):
- "Subtract other from self in place."
- t = self._data.dtype.char
- f = filled(other, 0)
- t1 = f.dtype.char
- if t == t1:
- pass
- elif t in typecodes['Integer']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Float']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Complex']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- elif t1 in typecodes['Complex']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- else:
- raise TypeError('Incorrect type for in-place operation.')
-
- if self._mask is nomask:
- self._data -= f
- m = getmask(other)
- self._mask = m
- self._shared_mask = m is not nomask
- else:
- result = subtract(self, masked_array(f, mask=getmask(other)))
- self._data = result.data
- self._mask = result.mask
- self._shared_mask = 1
- return self
-
-
-
- def __idiv__(self, other):
- "Divide self by other in place."
- t = self._data.dtype.char
- f = filled(other, 0)
- t1 = f.dtype.char
- if t == t1:
- pass
- elif t in typecodes['Integer']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Float']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- elif t in typecodes['Complex']:
- if t1 in typecodes['Integer']:
- f = f.astype(t)
- elif t1 in typecodes['Float']:
- f = f.astype(t)
- elif t1 in typecodes['Complex']:
- f = f.astype(t)
- else:
- raise TypeError('Incorrect type for in-place operation.')
- else:
- raise TypeError('Incorrect type for in-place operation.')
- mo = getmask(other)
- result = divide(self, masked_array(f, mask=mo))
- self._data = result.data
- dm = result.raw_mask()
- if dm is not self._mask:
- self._mask = dm
- self._shared_mask = 1
- return self
-
- def __eq__(self, other):
- return equal(self, other)
-
- def __ne__(self, other):
- return not_equal(self, other)
-
- def __lt__(self, other):
- return less(self, other)
-
- def __le__(self, other):
- return less_equal(self, other)
-
- def __gt__(self, other):
- return greater(self, other)
-
- def __ge__(self, other):
- return greater_equal(self, other)
-
- def astype (self, tc):
- "return self as array of given type."
- d = self._data.astype(tc)
- return array(d, mask=self._mask)
-
- def byte_swapped(self):
- """Returns the raw data field, byte_swapped. Included for consistency
- with numeric but doesn't make sense in this context.
- """
- return self._data.byte_swapped()
-
- def compressed (self):
- "A 1-D array of all the non-masked data."
- d = fromnumeric.ravel(self._data)
- if self._mask is nomask:
- return array(d)
- else:
- m = 1 - fromnumeric.ravel(self._mask)
- c = fromnumeric.compress(m, d)
- return array(c, copy=0)
-
- def count (self, axis = None):
- "Count of the non-masked elements in a, or along a certain axis."
- m = self._mask
- s = self._data.shape
- ls = len(s)
- if m is nomask:
- if ls == 0:
- return 1
- if ls == 1:
- return s[0]
- if axis is None:
- return reduce(lambda x, y:x*y, s)
- else:
- n = s[axis]
- t = list(s)
- del t[axis]
- return ones(t) * n
- if axis is None:
- w = fromnumeric.ravel(m).astype(int)
- n1 = size(w)
- if n1 == 1:
- n2 = w[0]
- else:
- n2 = umath.add.reduce(w)
- return n1 - n2
- else:
- n1 = size(m, axis)
- n2 = sum(m.astype(int), axis)
- return n1 - n2
-
- def dot (self, other):
- "s.dot(other) = innerproduct(s, other)"
- return innerproduct(self, other)
-
- def fill_value(self):
- "Get the current fill value."
- return self._fill_value
-
- def filled (self, fill_value=None):
- """A numeric array with masked values filled. If fill_value is None,
- use self.fill_value().
-
- If mask is nomask, copy data only if not contiguous.
- Result is always a contiguous, numeric array.
-# Is contiguous really necessary now?
- """
- d = self._data
- m = self._mask
- if m is nomask:
- if d.flags['CONTIGUOUS']:
- return d
- else:
- return d.copy()
- else:
- if fill_value is None:
- value = self._fill_value
- else:
- value = fill_value
-
- if self is masked:
- result = numeric.array(value)
- else:
- try:
- result = numeric.array(d, dtype=d.dtype, copy=1)
- result[m] = value
- except (TypeError, AttributeError):
- #ok, can't put that value in here
- value = numeric.array(value, dtype=object)
- d = d.astype(object)
- result = fromnumeric.choose(m, (d, value))
- return result
-
- def ids (self):
- """Return the ids of the data and mask areas"""
- return (id(self._data), id(self._mask))
-
- def iscontiguous (self):
- "Is the data contiguous?"
- return self._data.flags['CONTIGUOUS']
-
- def itemsize(self):
- "Item size of each data item."
- return self._data.itemsize
-
-
- def outer(self, other):
- "s.outer(other) = outerproduct(s, other)"
- return outerproduct(self, other)
-
- def put (self, values):
- """Set the non-masked entries of self to filled(values).
- No change to mask
- """
- iota = numeric.arange(self.size)
- d = self._data
- if self._mask is nomask:
- ind = iota
- else:
- ind = fromnumeric.compress(1 - self._mask, iota)
- d[ind] = filled(values).astype(d.dtype)
-
- def putmask (self, values):
- """Set the masked entries of self to filled(values).
- Mask changed to nomask.
- """
- d = self._data
- if self._mask is not nomask:
- d[self._mask] = filled(values).astype(d.dtype)
- self._shared_mask = 0
- self._mask = nomask
-
- def ravel (self):
- """Return a 1-D view of self."""
- if self._mask is nomask:
- return masked_array(self._data.ravel())
- else:
- return masked_array(self._data.ravel(), self._mask.ravel())
-
- def raw_data (self):
- """ Obsolete; use data property instead.
- The raw data; portions may be meaningless.
- May be noncontiguous. Expert use only."""
- return self._data
- data = property(fget=raw_data,
- doc="The data, but values at masked locations are meaningless.")
-
- def raw_mask (self):
- """ Obsolete; use mask property instead.
- May be noncontiguous. Expert use only.
- """
- return self._mask
- mask = property(fget=raw_mask,
- doc="The mask, may be nomask. Values where mask true are meaningless.")
-
- def reshape (self, *s):
- """This array reshaped to shape s"""
- d = self._data.reshape(*s)
- if self._mask is nomask:
- return masked_array(d)
- else:
- m = self._mask.reshape(*s)
- return masked_array(d, m)
-
- def set_fill_value (self, v=None):
- "Set the fill value to v. Omit v to restore default."
- if v is None:
- v = default_fill_value (self.raw_data())
- self._fill_value = v
-
- def _get_ndim(self):
- return self._data.ndim
- ndim = property(_get_ndim, doc=numeric.ndarray.ndim.__doc__)
-
- def _get_size (self):
- return self._data.size
- size = property(fget=_get_size, doc="Number of elements in the array.")
-## CHECK THIS: signature of numeric.array.size?
-
- def _get_dtype(self):
- return self._data.dtype
- dtype = property(fget=_get_dtype, doc="type of the array elements.")
-
- def item(self, *args):
- "Return Python scalar if possible"
- if self._mask is not nomask:
- m = self._mask.item(*args)
- try:
- if m[0]:
- return masked
- except IndexError:
- return masked
- return self._data.item(*args)
-
- def itemset(self, *args):
- "Set Python scalar into array"
- item = args[-1]
- args = args[:-1]
- self[args] = item
-
- def tolist(self, fill_value=None):
- "Convert to list"
- return self.filled(fill_value).tolist()
-
- def tostring(self, fill_value=None):
- "Convert to string"
- return self.filled(fill_value).tostring()
-
- def unmask (self):
- "Replace the mask by nomask if possible."
- if self._mask is nomask: return
- m = make_mask(self._mask, flag=1)
- if m is nomask:
- self._mask = nomask
- self._shared_mask = 0
-
- def unshare_mask (self):
- "If currently sharing mask, make a copy."
- if self._shared_mask:
- self._mask = make_mask (self._mask, copy=1, flag=0)
- self._shared_mask = 0
-
- def _get_ctypes(self):
- return self._data.ctypes
-
- def _get_T(self):
- if (self.ndim < 2):
- return self
- return self.transpose()
-
- shape = property(_get_shape, _set_shape,
- doc = 'tuple giving the shape of the array')
-
- flat = property(_get_flat, _set_flat,
- doc = 'Access array in flat form.')
-
- real = property(_get_real, _set_real,
- doc = 'Access the real part of the array')
-
- imaginary = property(_get_imaginary, _set_imaginary,
- doc = 'Access the imaginary part of the array')
-
- imag = imaginary
-
- ctypes = property(_get_ctypes, None, doc="ctypes")
-
- T = property(_get_T, None, doc="get transpose")
-
-#end class MaskedArray
-
-array = MaskedArray
-
-def isMaskedArray (x):
- "Is x a masked array, that is, an instance of MaskedArray?"
- return isinstance(x, MaskedArray)
-
-isarray = isMaskedArray
-isMA = isMaskedArray #backward compatibility
-
-def allclose (a, b, fill_value=1, rtol=1.e-5, atol=1.e-8):
- """ Returns true if all components of a and b are equal
- subject to given tolerances.
- If fill_value is 1, masked values considered equal.
- If fill_value is 0, masked values considered unequal.
- The relative error rtol should be positive and << 1.0
- The absolute error atol comes into play for those elements
- of b that are very small or zero; it says how small a must be also.
- """
- m = mask_or(getmask(a), getmask(b))
- d1 = filled(a)
- d2 = filled(b)
- x = filled(array(d1, copy=0, mask=m), fill_value).astype(float)
- y = filled(array(d2, copy=0, mask=m), 1).astype(float)
- d = umath.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y))
- return fromnumeric.alltrue(fromnumeric.ravel(d))
-
-def allequal (a, b, fill_value=1):
- """
- True if all entries of a and b are equal, using
- fill_value as a truth value where either or both are masked.
- """
- m = mask_or(getmask(a), getmask(b))
- if m is nomask:
- x = filled(a)
- y = filled(b)
- d = umath.equal(x, y)
- return fromnumeric.alltrue(fromnumeric.ravel(d))
- elif fill_value:
- x = filled(a)
- y = filled(b)
- d = umath.equal(x, y)
- dm = array(d, mask=m, copy=0)
- return fromnumeric.alltrue(fromnumeric.ravel(filled(dm, 1)))
- else:
- return 0
-
-def masked_values (data, value, rtol=1.e-5, atol=1.e-8, copy=1):
- """
- masked_values(data, value, rtol=1.e-5, atol=1.e-8)
- Create a masked array; mask is nomask if possible.
- If copy==0, and otherwise possible, result
- may share data values with original array.
- Let d = filled(data, value). Returns d
- masked where abs(data-value)<= atol + rtol * abs(value)
- if d is of a floating point type. Otherwise returns
- masked_object(d, value, copy)
- """
- abs = umath.absolute
- d = filled(data, value)
- if issubclass(d.dtype.type, numeric.floating):
- m = umath.less_equal(abs(d-value), atol+rtol*abs(value))
- m = make_mask(m, flag=1)
- return array(d, mask = m, copy=copy,
- fill_value=value)
- else:
- return masked_object(d, value, copy=copy)
-
-def masked_object (data, value, copy=1):
- "Create array masked where exactly data equal to value"
- d = filled(data, value)
- dm = make_mask(umath.equal(d, value), flag=1)
- return array(d, mask=dm, copy=copy, fill_value=value)
-
-def arange(start, stop=None, step=1, dtype=None):
- """Just like range() except it returns a array whose type can be specified
- by the keyword argument dtype.
- """
- return array(numeric.arange(start, stop, step, dtype))
-
-arrayrange = arange
-
-def fromstring (s, t):
- "Construct a masked array from a string. Result will have no mask."
- return masked_array(numeric.fromstring(s, t))
-
-def left_shift (a, n):
- "Left shift n bits"
- m = getmask(a)
- if m is nomask:
- d = umath.left_shift(filled(a), n)
- return masked_array(d)
- else:
- d = umath.left_shift(filled(a, 0), n)
- return masked_array(d, m)
-
-def right_shift (a, n):
- "Right shift n bits"
- m = getmask(a)
- if m is nomask:
- d = umath.right_shift(filled(a), n)
- return masked_array(d)
- else:
- d = umath.right_shift(filled(a, 0), n)
- return masked_array(d, m)
-
-def resize (a, new_shape):
- """resize(a, new_shape) returns a new array with the specified shape.
- The original array's total size can be any size."""
- m = getmask(a)
- if m is not nomask:
- m = fromnumeric.resize(m, new_shape)
- result = array(fromnumeric.resize(filled(a), new_shape), mask=m)
- result.set_fill_value(get_fill_value(a))
- return result
-
-def new_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.
- """
- af = filled(a)
- if isinstance(repeats, int):
- if axis is None:
- num = af.size
- else:
- num = af.shape[axis]
- repeats = tuple([repeats]*num)
-
- m = getmask(a)
- if m is not nomask:
- m = fromnumeric.repeat(m, repeats, axis)
- d = fromnumeric.repeat(af, repeats, axis)
- result = masked_array(d, m)
- result.set_fill_value(get_fill_value(a))
- return result
-
-
-
-def identity(n):
- """identity(n) returns the identity matrix of shape n x n.
- """
- return array(numeric.identity(n))
-
-def indices (dimensions, dtype=None):
- """indices(dimensions,dtype=None) returns an array representing a grid
- of indices with row-only, and column-only variation.
- """
- return array(numeric.indices(dimensions, dtype))
-
-def zeros (shape, dtype=float):
- """zeros(n, dtype=float) =
- an array of all zeros of the given length or shape."""
- return array(numeric.zeros(shape, dtype))
-
-def ones (shape, dtype=float):
- """ones(n, dtype=float) =
- an array of all ones of the given length or shape."""
- return array(numeric.ones(shape, dtype))
-
-def count (a, axis = None):
- "Count of the non-masked elements in a, or along a certain axis."
- a = masked_array(a)
- return a.count(axis)
-
-def power (a, b, third=None):
- "a**b"
- if third is not None:
- raise MAError("3-argument power not supported.")
- ma = getmask(a)
- mb = getmask(b)
- m = mask_or(ma, mb)
- fa = filled(a, 1)
- fb = filled(b, 1)
- if fb.dtype.char in typecodes["Integer"]:
- return masked_array(umath.power(fa, fb), m)
- md = make_mask(umath.less(fa, 0), flag=1)
- m = mask_or(m, md)
- if m is nomask:
- return masked_array(umath.power(fa, fb))
- else:
- fa = numeric.where(m, 1, fa)
- return masked_array(umath.power(fa, fb), m)
-
-def masked_array (a, mask=nomask, fill_value=None):
- """masked_array(a, mask=nomask) =
- array(a, mask=mask, copy=0, fill_value=fill_value)
- """
- return array(a, mask=mask, copy=0, fill_value=fill_value)
-
-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 new_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.
-
- 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.
-
- If returned, return a tuple: the result and the sum of the weights
- or count of values. Results will have the same shape.
-
- masked values in the weights will be set to 0.0
- """
- a = masked_array(a)
- mask = a.mask
- ash = a.shape
- if ash == ():
- ash = (1,)
- if axis is None:
- if mask is nomask:
- if weights is None:
- n = add.reduce(a.raw_data().ravel())
- d = reduce(lambda x, y: x * y, ash, 1.0)
- else:
- w = filled(weights, 0.0).ravel()
- n = umath.add.reduce(a.raw_data().ravel() * w)
- d = umath.add.reduce(w)
- del w
- else:
- if weights is None:
- n = add.reduce(a.ravel())
- w = fromnumeric.choose(mask, (1.0, 0.0)).ravel()
- d = umath.add.reduce(w)
- del w
- else:
- w = array(filled(weights, 0.0), float, mask=mask).ravel()
- n = add.reduce(a.ravel() * w)
- d = add.reduce(w)
- del w
- else:
- if mask is nomask:
- if weights is None:
- d = ash[axis] * 1.0
- n = umath.add.reduce(a.raw_data(), axis)
- else:
- w = filled(weights, 0.0)
- wsh = w.shape
- if wsh == ():
- wsh = (1,)
- if wsh == ash:
- w = numeric.array(w, float, copy=0)
- n = add.reduce(a*w, axis)
- d = add.reduce(w, axis)
- del w
- elif wsh == (ash[axis],):
- r = [newaxis]*len(ash)
- r[axis] = slice(None, None, 1)
- w = eval ("w["+ repr(tuple(r)) + "] * ones(ash, float)")
- n = add.reduce(a*w, axis)
- d = add.reduce(w, axis)
- del w, r
- else:
- raise ValueError('average: weights wrong shape.')
- else:
- if weights is None:
- n = add.reduce(a, axis)
- w = numeric.choose(mask, (1.0, 0.0))
- d = umath.add.reduce(w, axis)
- del w
- else:
- w = filled(weights, 0.0)
- wsh = w.shape
- if wsh == ():
- wsh = (1,)
- if wsh == ash:
- w = array(w, float, mask=mask, copy=0)
- n = add.reduce(a*w, axis)
- d = add.reduce(w, axis)
- elif wsh == (ash[axis],):
- r = [newaxis]*len(ash)
- r[axis] = slice(None, None, 1)
- w = eval ("w["+ repr(tuple(r)) + "] * masked_array(ones(ash, float), mask)")
- n = add.reduce(a*w, axis)
- d = add.reduce(w, axis)
- else:
- raise ValueError('average: weights wrong shape.')
- del w
- #print n, d, repr(mask), repr(weights)
- if n is masked or d is masked: return masked
- result = divide (n, d)
- del n
-
- if isinstance(result, MaskedArray):
- result.unmask()
- if returned:
- if not isinstance(d, MaskedArray):
- d = masked_array(d)
- if not d.shape == result.shape:
- d = ones(result.shape, float) * d
- d.unmask()
- if returned:
- return result, d
- else:
- return result
-
-def where (condition, x, y):
- """where(condition, x, y) is x where condition is nonzero, y otherwise.
- condition must be convertible to an integer array.
- Answer is always the shape of condition.
- The type depends on x and y. It is integer if both x and y are
- the value masked.
- """
- fc = filled(not_equal(condition, 0), 0)
- xv = filled(x)
- xm = getmask(x)
- yv = filled(y)
- ym = getmask(y)
- d = numeric.choose(fc, (yv, xv))
- md = numeric.choose(fc, (ym, xm))
- m = getmask(condition)
- m = make_mask(mask_or(m, md), copy=0, flag=1)
- return masked_array(d, m)
-
-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
- return filled(x)
- def nmask (x):
- if x is masked: return 1
- m = getmask(x)
- if m is nomask: return 0
- return m
- c = filled(indices, 0)
- masks = [nmask(x) for x in t]
- a = [fmask(x) for x in t]
- d = numeric.choose(c, a)
- m = numeric.choose(c, masks)
- m = make_mask(mask_or(m, getmask(indices)), copy=0, flag=1)
- return masked_array(d, m)
-
-def masked_where(condition, x, copy=1):
- """Return x as an array masked where condition is true.
- Also masked where x or condition masked.
- """
- cm = filled(condition, 1)
- m = mask_or(getmask(x), cm)
- return array(filled(x), copy=copy, mask=m)
-
-def masked_greater(x, value, copy=1):
- "masked_greater(x, value) = x masked where x > value"
- return masked_where(greater(x, value), x, copy)
-
-def masked_greater_equal(x, value, copy=1):
- "masked_greater_equal(x, value) = x masked where x >= value"
- return masked_where(greater_equal(x, value), x, copy)
-
-def masked_less(x, value, copy=1):
- "masked_less(x, value) = x masked where x < value"
- return masked_where(less(x, value), x, copy)
-
-def masked_less_equal(x, value, copy=1):
- "masked_less_equal(x, value) = x masked where x <= value"
- return masked_where(less_equal(x, value), x, copy)
-
-def masked_not_equal(x, value, copy=1):
- "masked_not_equal(x, value) = x masked where x != value"
- d = filled(x, 0)
- c = umath.not_equal(d, value)
- m = mask_or(c, getmask(x))
- return array(d, mask=m, copy=copy)
-
-def masked_equal(x, value, copy=1):
- """masked_equal(x, value) = x masked where x == value
- For floating point consider masked_values(x, value) instead.
- """
- d = filled(x, 0)
- c = umath.equal(d, value)
- m = mask_or(c, getmask(x))
- return array(d, mask=m, copy=copy)
-
-def masked_inside(x, v1, v2, copy=1):
- """x with mask of all values of x that are inside [v1,v2]
- v1 and v2 can be given in either order.
- """
- if v2 < v1:
- t = v2
- v2 = v1
- v1 = t
- d = filled(x, 0)
- c = umath.logical_and(umath.less_equal(d, v2), umath.greater_equal(d, v1))
- m = mask_or(c, getmask(x))
- return array(d, mask = m, copy=copy)
-
-def masked_outside(x, v1, v2, copy=1):
- """x with mask of all values of x that are outside [v1,v2]
- v1 and v2 can be given in either order.
- """
- if v2 < v1:
- t = v2
- v2 = v1
- v1 = t
- d = filled(x, 0)
- c = umath.logical_or(umath.less(d, v1), umath.greater(d, v2))
- m = mask_or(c, getmask(x))
- return array(d, mask = m, copy=copy)
-
-def reshape (a, *newshape):
- "Copy of a with a new shape."
- m = getmask(a)
- d = filled(a).reshape(*newshape)
- if m is nomask:
- return masked_array(d)
- else:
- return masked_array(d, mask=numeric.reshape(m, *newshape))
-
-def ravel (a):
- "a as one-dimensional, may share data and mask"
- m = getmask(a)
- d = fromnumeric.ravel(filled(a))
- if m is nomask:
- return masked_array(d)
- else:
- return masked_array(d, mask=numeric.ravel(m))
-
-def concatenate (arrays, axis=0):
- "Concatenate the arrays along the given axis"
- d = []
- for x in arrays:
- d.append(filled(x))
- d = numeric.concatenate(d, axis)
- for x in arrays:
- if getmask(x) is not nomask: break
- else:
- return masked_array(d)
- dm = []
- for x in arrays:
- dm.append(getmaskarray(x))
- dm = numeric.concatenate(dm, axis)
- return masked_array(d, mask=dm)
-
-def swapaxes (a, axis1, axis2):
- m = getmask(a)
- d = masked_array(a).data
- if m is nomask:
- return masked_array(data=numeric.swapaxes(d, axis1, axis2))
- else:
- return masked_array(data=numeric.swapaxes(d, axis1, axis2),
- mask=numeric.swapaxes(m, axis1, axis2),)
-
-
-def new_take (a, indices, axis=None, out=None, mode='raise'):
- "returns selection of items from a."
- m = getmask(a)
- # d = masked_array(a).raw_data()
- d = masked_array(a).data
- if m is nomask:
- return masked_array(numeric.take(d, indices, axis))
- else:
- return masked_array(numeric.take(d, indices, axis),
- mask = numeric.take(m, indices, axis))
-
-def transpose(a, axes=None):
- "reorder dimensions per tuple axes"
- m = getmask(a)
- d = filled(a)
- if m is nomask:
- return masked_array(numeric.transpose(d, axes))
- else:
- return masked_array(numeric.transpose(d, axes),
- mask = numeric.transpose(m, axes))
-
-
-def put(a, indices, values, mode='raise'):
- """sets storage-indexed locations to corresponding values.
-
- Values and indices are filled if necessary.
-
- """
- d = a.raw_data()
- ind = filled(indices)
- v = filled(values)
- numeric.put (d, ind, v)
- m = getmask(a)
- if m is not nomask:
- a.unshare_mask()
- numeric.put(a.raw_mask(), ind, 0)
-
-def putmask(a, mask, values):
- "putmask(a, mask, values) sets a where mask is true."
- if mask is nomask:
- return
- numeric.putmask(a.raw_data(), mask, values)
- m = getmask(a)
- if m is nomask: return
- a.unshare_mask()
- numeric.putmask(a.raw_mask(), mask, 0)
-
-def inner(a, b):
- """inner(a,b) returns the dot product of two arrays, which has
- shape a.shape[:-1] + b.shape[:-1] with elements computed by summing the
- product of the elements from the last dimensions of a and b.
- Masked elements are replace by zeros.
- """
- fa = filled(a, 0)
- fb = filled(b, 0)
- if len(fa.shape) == 0: fa.shape = (1,)
- if len(fb.shape) == 0: fb.shape = (1,)
- return masked_array(numeric.inner(fa, fb))
-
-innerproduct = inner
-
-def outer(a, b):
- """outer(a,b) = {a[i]*b[j]}, has shape (len(a),len(b))"""
- fa = filled(a, 0).ravel()
- fb = filled(b, 0).ravel()
- d = numeric.outer(fa, fb)
- ma = getmask(a)
- mb = getmask(b)
- if ma is nomask and mb is nomask:
- return masked_array(d)
- ma = getmaskarray(a)
- mb = getmaskarray(b)
- m = make_mask(1-numeric.outer(1-ma, 1-mb), copy=0)
- return masked_array(d, m)
-
-outerproduct = outer
-
-def dot(a, b):
- """dot(a,b) returns matrix-multiplication between a and b. The product-sum
- is over the last dimension of a and the second-to-last dimension of b.
- Masked values are replaced by zeros. See also innerproduct.
- """
- return innerproduct(filled(a, 0), numeric.swapaxes(filled(b, 0), -1, -2))
-
-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)
- return masked_array(d, m)
-
-class _minimum_operation:
- "Object to calculate minima"
- def __init__ (self):
- """minimum(a, b) or minimum(a)
- In one argument case returns the scalar minimum.
- """
- pass
-
- def __call__ (self, a, b=None):
- "Execute the call behavior."
- if b is None:
- m = getmask(a)
- if m is nomask:
- d = amin(filled(a).ravel())
- return d
- ac = a.compressed()
- if len(ac) == 0:
- return masked
- else:
- return amin(ac.raw_data())
- else:
- return where(less(a, b), a, b)
-
- def reduce (self, target, axis=0):
- """Reduce target along the given axis."""
- m = getmask(target)
- if m is nomask:
- t = filled(target)
- return masked_array (umath.minimum.reduce (t, axis))
- else:
- t = umath.minimum.reduce(filled(target, minimum_fill_value(target)), axis)
- m = umath.logical_and.reduce(m, axis)
- return masked_array(t, m, get_fill_value(target))
-
- def outer (self, a, b):
- "Return the function applied to the outer product of a and b."
- ma = getmask(a)
- mb = getmask(b)
- if ma is nomask and mb is nomask:
- m = nomask
- else:
- ma = getmaskarray(a)
- mb = getmaskarray(b)
- m = logical_or.outer(ma, mb)
- d = umath.minimum.outer(filled(a), filled(b))
- return masked_array(d, m)
-
-minimum = _minimum_operation ()
-
-class _maximum_operation:
- "Object to calculate maxima"
- def __init__ (self):
- """maximum(a, b) or maximum(a)
- In one argument case returns the scalar maximum.
- """
- pass
-
- def __call__ (self, a, b=None):
- "Execute the call behavior."
- if b is None:
- m = getmask(a)
- if m is nomask:
- d = amax(filled(a).ravel())
- return d
- ac = a.compressed()
- if len(ac) == 0:
- return masked
- else:
- return amax(ac.raw_data())
- else:
- return where(greater(a, b), a, b)
-
- def reduce (self, target, axis=0):
- """Reduce target along the given axis."""
- m = getmask(target)
- if m is nomask:
- t = filled(target)
- return masked_array (umath.maximum.reduce (t, axis))
- else:
- t = umath.maximum.reduce(filled(target, maximum_fill_value(target)), axis)
- m = umath.logical_and.reduce(m, axis)
- return masked_array(t, m, get_fill_value(target))
-
- def outer (self, a, b):
- "Return the function applied to the outer product of a and b."
- ma = getmask(a)
- mb = getmask(b)
- if ma is nomask and mb is nomask:
- m = nomask
- else:
- ma = getmaskarray(a)
- mb = getmaskarray(b)
- m = logical_or.outer(ma, mb)
- d = umath.maximum.outer(filled(a), filled(b))
- return masked_array(d, m)
-
-maximum = _maximum_operation ()
-
-def sort (x, axis = -1, fill_value=None):
- """If x does not have a mask, return a masked array formed from the
- result of numeric.sort(x, axis).
- Otherwise, fill x with fill_value. Sort it.
- Set a mask where the result is equal to fill_value.
- Note that this may have unintended consequences if the data contains the
- fill value at a non-masked site.
-
- If fill_value is not given the default fill value for x's type will be
- used.
- """
- if fill_value is None:
- fill_value = default_fill_value (x)
- d = filled(x, fill_value)
- s = fromnumeric.sort(d, axis)
- if getmask(x) is nomask:
- return masked_array(s)
- return masked_values(s, fill_value, copy=0)
-
-def diagonal(a, k = 0, axis1=0, axis2=1):
- """diagonal(a,k=0,axis1=0, axis2=1) = the k'th diagonal of a"""
- d = fromnumeric.diagonal(filled(a), k, axis1, axis2)
- m = getmask(a)
- if m is nomask:
- return masked_array(d, m)
- else:
- return masked_array(d, fromnumeric.diagonal(m, k, axis1, axis2))
-
-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)
-
-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)
- Returns a numpy array.
- """
- d = filled(x, fill_value)
- return fromnumeric.argsort(d, axis)
-
-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).
- Returns a numpy array if x has more than one dimension.
- Otherwise, returns a scalar index.
- """
- d = filled(x, fill_value)
- return fromnumeric.argmin(d, axis)
-
-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.
- Returns a numpy array if x has more than one dimension.
- Otherwise, returns a scalar index.
- """
- if fill_value is None:
- fill_value = default_fill_value (x)
- try:
- fill_value = - fill_value
- except:
- pass
- d = filled(x, fill_value)
- return fromnumeric.argmax(d, axis)
-
-def fromfunction (f, s):
- """apply f to s to create array as in umath."""
- return masked_array(numeric.fromfunction(f, s))
-
-def asarray(data, dtype=None):
- """asarray(data, dtype) = array(data, dtype, copy=0)
- """
- if isinstance(data, MaskedArray) and \
- (dtype is None or dtype == data.dtype):
- return data
- return array(data, dtype=dtype, copy=0)
-
-# Add methods to support ndarray interface
-# XXX: I is better to to change the masked_*_operation adaptors
-# XXX: to wrap ndarray methods directly to create ma.array methods.
-
-def _m(f):
- return types.MethodType(f, None, array)
-
-def not_implemented(*args, **kwds):
- raise NotImplementedError("not yet implemented for numpy.ma arrays")
-
-array.all = _m(alltrue)
-array.any = _m(sometrue)
-array.argmax = _m(argmax)
-array.argmin = _m(argmin)
-array.argsort = _m(argsort)
-array.base = property(_m(not_implemented))
-array.byteswap = _m(not_implemented)
-
-def _choose(self, *args, **kwds):
- return choose(self, args)
-array.choose = _m(_choose)
-del _choose
-
-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,
- mask_or(getmask(a_min), getmask(a_max))))
-array.clip = _m(_clip)
-
-def _compress(self, cond, axis=None, out=None):
- return compress(cond, self, axis)
-array.compress = _m(_compress)
-del _compress
-
-array.conj = array.conjugate = _m(conjugate)
-array.copy = _m(not_implemented)
-
-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=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(0).cumsum(axis, dtype), mask=m)
-array.cumsum = _m(_cumsum)
-
-array.diagonal = _m(diagonal)
-array.dump = _m(not_implemented)
-array.dumps = _m(not_implemented)
-array.fill = _m(not_implemented)
-array.flags = property(_m(not_implemented))
-array.flatten = _m(ravel)
-array.getfield = _m(not_implemented)
-
-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, out=None):
- if out is not None:
- raise TypeError("Output arrays Unsupported for masked arrays")
- if axis is None:
- return minimum(a)
- else:
- return minimum.reduce(a, axis)
-array.min = _m(_min)
-del _min
-array.mean = _m(new_average)
-array.nbytes = property(_m(not_implemented))
-array.newbyteorder = _m(not_implemented)
-array.nonzero = _m(nonzero)
-array.prod = _m(product)
-
-def _ptp(a,axis=None,out=None):
- return a.max(axis, out)-a.min(axis)
-array.ptp = _m(_ptp)
-array.repeat = _m(new_repeat)
-array.resize = _m(resize)
-array.searchsorted = _m(not_implemented)
-array.setfield = _m(not_implemented)
-array.setflags = _m(not_implemented)
-array.sort = _m(not_implemented) # NB: ndarray.sort is inplace
-
-def _squeeze(self):
- try:
- result = MaskedArray(data = self.data.squeeze(),
- mask = self.mask.squeeze())
- except AttributeError:
- result = _wrapit(self, 'squeeze')
- return result
-array.squeeze = _m(_squeeze)
-
-array.strides = property(_m(not_implemented))
-array.sum = _m(sum)
-def _swapaxes(self, axis1, axis2):
- return MaskedArray(data = self.data.swapaxes(axis1, axis2),
- mask = self.mask.swapaxes(axis1, axis2))
-array.swapaxes = _m(_swapaxes)
-array.take = _m(new_take)
-array.tofile = _m(not_implemented)
-array.trace = _m(trace)
-array.transpose = _m(transpose)
-
-def _var(self,axis=None,dtype=None, out=None):
- if axis is None:
- 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=None, dtype=None, out=None):
- return (self.var(axis, dtype))**0.5
-array.var = _m(_var)
-array.std = _m(_std)
-
-array.view = _m(not_implemented)
-array.round = _m(around)
-del _m, not_implemented
-
-
-masked = MaskedArray(0, int, mask=1)
-
-def repeat(a, repeats, axis=0):
- return new_repeat(a, repeats, axis)
-
-def average(a, axis=0, weights=None, returned=0):
- return new_average(a, axis, weights, returned)
-
-def take(a, indices, axis=0):
- return new_take(a, indices, axis)
diff --git a/numpy/oldnumeric/matrix.py b/numpy/oldnumeric/matrix.py
deleted file mode 100644
index 35c795e9d..000000000
--- a/numpy/oldnumeric/matrix.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""This module is for compatibility only.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['UserArray', 'squeeze', 'Matrix', 'asarray', 'dot', 'k', 'Numeric', 'LinearAlgebra', 'identity', 'multiply', 'types', 'string']
-
-import types
-from .user_array import UserArray, asarray
-import numpy.oldnumeric as Numeric
-from numpy.oldnumeric import dot, identity, multiply
-import numpy.oldnumeric.linear_algebra as LinearAlgebra
-from numpy import matrix as Matrix, squeeze
-
-# Hidden names that will be the same.
-
-_table = [None]*256
-for k in range(256):
- _table[k] = chr(k)
-_table = ''.join(_table)
-
-_numchars = '0123456789.-+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:]
diff --git a/numpy/oldnumeric/misc.py b/numpy/oldnumeric/misc.py
deleted file mode 100644
index beaafd503..000000000
--- a/numpy/oldnumeric/misc.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""Functions that already have the correct syntax or miscellaneous functions
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['sort', 'copy_reg', 'clip', 'rank',
- 'sign', 'shape', 'types', 'allclose', 'size',
- 'choose', 'swapaxes', 'array_str',
- 'pi', 'math', 'concatenate', 'putmask', 'put',
- 'around', 'vdot', 'transpose', 'array2string', 'diagonal',
- 'searchsorted', 'copy', 'resize',
- 'array_repr', 'e', 'StringIO', 'pickle',
- 'argsort', 'convolve', 'cross_correlate',
- 'dot', 'outerproduct', 'innerproduct', 'insert']
-
-import types
-import pickle
-import math
-import copy
-import sys
-
-if sys.version_info[0] >= 3:
- import copyreg as copy_reg
- from io import BytesIO as StringIO
-else:
- import copy_reg
- from StringIO import StringIO
-
-from numpy import sort, clip, rank, sign, shape, putmask, allclose, size,\
- choose, swapaxes, array_str, array_repr, e, pi, put, \
- resize, around, concatenate, vdot, transpose, \
- diagonal, searchsorted, argsort, convolve, dot, \
- outer as outerproduct, inner as innerproduct, \
- correlate as cross_correlate, \
- place as insert
-
-from .array_printer import array2string
diff --git a/numpy/oldnumeric/mlab.py b/numpy/oldnumeric/mlab.py
deleted file mode 100644
index 2b357612c..000000000
--- a/numpy/oldnumeric/mlab.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""This module is for compatibility only. All functions are defined elsewhere.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__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 numpy.oldnumeric.linear_algebra as LinearAlgebra
-import numpy.oldnumeric.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, \
- squeeze, sinc, median, fliplr, mean as _Nmean, transpose
-
-from numpy.linalg import eig, svd
-from numpy.random import rand, randn
-import numpy as np
-
-from .typeconv import convtypecode
-
-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 = convtypecode(typecode, dtype)
- if M is None: M = N
- m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)), -k)
- if m.dtype != dtype:
- return m.astype(dtype)
-
-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 = convtypecode(typecode, dtype)
- if M is None: M = N
- m = np.greater_equal(np.subtract.outer(np.arange(N), np.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):
- N = asarray(x).shape[axis]
- return _Nstd(x, axis)*sqrt(N/(N-1.))
-
-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):
- 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):
- c = cov(x, y)
- d = diag(c)
- return c/sqrt(multiply.outer(d, d))
-
-from .compat import *
-from .functions import *
-from .precision import *
-from .ufuncs import *
-from .misc import *
-
-from . import compat
-from . import precision
-from . import functions
-from . import misc
-from . 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
diff --git a/numpy/oldnumeric/precision.py b/numpy/oldnumeric/precision.py
deleted file mode 100644
index d7b0344ee..000000000
--- a/numpy/oldnumeric/precision.py
+++ /dev/null
@@ -1,174 +0,0 @@
-"""
-
-Lifted from Precision.py. This is for compatibility only.
-
-The character strings are still for "new" NumPy
-which is the only Incompatibility with Numeric
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['Character', 'Complex', 'Float',
- 'PrecisionError', 'PyObject', 'Int', 'UInt',
- 'UnsignedInt', 'UnsignedInteger', 'string', 'typecodes', 'zeros']
-
-from .functions import zeros
-import string # for backwards compatibility
-
-typecodes = {'Character':'c', 'Integer':'bhil', 'UnsignedInteger':'BHIL', '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
-UInt = UnsignedInt = UnsignedInteger = 'u'
-
-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'
diff --git a/numpy/oldnumeric/random_array.py b/numpy/oldnumeric/random_array.py
deleted file mode 100644
index c43a49cdb..000000000
--- a/numpy/oldnumeric/random_array.py
+++ /dev/null
@@ -1,269 +0,0 @@
-"""Backward compatible module for RandomArray
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__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 np
-
-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, <min"""
- if not isinstance(minimum, int):
- raise ArgumentError("randint requires first argument integer")
- if maximum is None:
- maximum = minimum
- minimum = 0
- if not isinstance(maximum, int):
- raise ArgumentError("randint requires second argument integer")
- a = ((maximum-minimum)* random(shape))
- if isinstance(a, np.ndarray):
- return minimum + a.astype(np.int)
- else:
- return minimum + int(a)
-
-def random_integers(maximum, minimum=1, shape=[]):
- """random_integers(max, min=1, shape=[]) = random integers in range min-max inclusive"""
- return randint(minimum, maximum+1, shape)
-
-def permutation(n):
- "permutation(n) = a permutation of indices range(n)"
- return mt.permutation(n)
-
-def standard_normal(shape=[]):
- """standard_normal(n) or standard_normal([n, m, ...]) returns array of
- random numbers normally distributed with mean 0 and standard
- deviation 1"""
- if shape == []:
- shape = None
- return mt.standard_normal(shape)
-
-def normal(mean, std, shape=[]):
- """normal(mean, std, n) or normal(mean, std, [n, m, ...]) returns
- array of random numbers randomly distributed with specified mean and
- standard deviation"""
- if shape == []:
- shape = None
- return mt.normal(mean, std, shape)
-
-def multivariate_normal(mean, cov, shape=[]):
- """multivariate_normal(mean, cov) or multivariate_normal(mean, cov, [m, n, ...])
- returns an array containing multivariate normally distributed random numbers
- with specified mean and covariance.
-
- mean must be a 1 dimensional array. cov must be a square two dimensional
- array with the same number of rows and columns as mean has elements.
-
- The first form returns a single 1-D array containing a multivariate
- normal.
-
- The second form returns an array of shape (m, n, ..., cov.shape[0]).
- In this case, output[i,j,...,:] is a 1-D array containing a multivariate
- normal."""
- if shape == []:
- shape = None
- return mt.multivariate_normal(mean, cov, shape)
-
-def exponential(mean, shape=[]):
- """exponential(mean, n) or exponential(mean, [n, m, ...]) returns array
- of random numbers exponentially distributed with specified mean"""
- if shape == []:
- shape = None
- return mt.exponential(mean, shape)
-
-def beta(a, b, shape=[]):
- """beta(a, b) or beta(a, b, [n, m, ...]) returns array of beta distributed random numbers."""
- if shape == []:
- shape = None
- return mt.beta(a, b, shape)
-
-def gamma(a, r, shape=[]):
- """gamma(a, r) or gamma(a, r, [n, m, ...]) returns array of gamma distributed random numbers."""
- if shape == []:
- shape = None
- return mt.gamma(a, r, shape)
-
-def F(dfn, dfd, shape=[]):
- """F(dfn, dfd) or F(dfn, dfd, [n, m, ...]) returns array of F distributed random numbers with dfn degrees of freedom in the numerator and dfd degrees of freedom in the denominator."""
- if shape == []:
- shape = None
- return mt.f(dfn, dfd, shape)
-
-def noncentral_F(dfn, dfd, nconc, shape=[]):
- """noncentral_F(dfn, dfd, nonc) or noncentral_F(dfn, dfd, nonc, [n, m, ...]) returns array of noncentral F distributed random numbers with dfn degrees of freedom in the numerator and dfd degrees of freedom in the denominator, and noncentrality parameter nconc."""
- if shape == []:
- shape = None
- return mt.noncentral_f(dfn, dfd, nconc, shape)
-
-def chi_square(df, shape=[]):
- """chi_square(df) or chi_square(df, [n, m, ...]) returns array of chi squared distributed random numbers with df degrees of freedom."""
- if shape == []:
- shape = None
- return mt.chisquare(df, shape)
-
-def noncentral_chi_square(df, nconc, shape=[]):
- """noncentral_chi_square(df, nconc) or chi_square(df, nconc, [n, m, ...]) returns array of noncentral chi squared distributed random numbers with df degrees of freedom and noncentrality parameter."""
- if shape == []:
- shape = None
- return mt.noncentral_chisquare(df, nconc, shape)
-
-def binomial(trials, p, shape=[]):
- """binomial(trials, p) or binomial(trials, p, [n, m, ...]) returns array of binomially distributed random integers.
-
- trials is the number of trials in the binomial distribution.
- p is the probability of an event in each trial of the binomial distribution."""
- if shape == []:
- shape = None
- return mt.binomial(trials, p, shape)
-
-def negative_binomial(trials, p, shape=[]):
- """negative_binomial(trials, p) or negative_binomial(trials, p, [n, m, ...]) returns
- array of negative binomially distributed random integers.
-
- trials is the number of trials in the negative binomial distribution.
- p is the probability of an event in each trial of the negative binomial distribution."""
- if shape == []:
- shape = None
- return mt.negative_binomial(trials, p, shape)
-
-def multinomial(trials, probs, shape=[]):
- """multinomial(trials, probs) or multinomial(trials, probs, [n, m, ...]) returns
- array of multinomial distributed integer vectors.
-
- 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<len(prob).
- The probability of event len(prob) is 1.-np.sum(prob).
-
- The first form returns a single 1-D array containing one multinomially
- distributed vector.
-
- The second form returns an array of shape (m, n, ..., len(probs)).
- In this case, output[i,j,...,:] is a 1-D array containing a multinomially
- distributed integer 1-D array."""
- if shape == []:
- shape = None
- return mt.multinomial(trials, probs, shape)
-
-def poisson(mean, shape=[]):
- """poisson(mean) or poisson(mean, [n, m, ...]) returns array of poisson
- distributed random integers with specified mean."""
- if shape == []:
- shape = None
- return mt.poisson(mean, shape)
-
-
-def mean_var_test(x, type, mean, var, skew=[]):
- n = len(x) * 1.0
- x_mean = np.sum(x, axis=0)/n
- x_minus_mean = x - x_mean
- x_var = np.sum(x_minus_mean*x_minus_mean, axis=0)/(n-1.0)
- print("\nAverage of ", len(x), type)
- print("(should be about ", mean, "):", x_mean)
- print("Variance of those random numbers (should be about ", var, "):", x_var)
- if skew != []:
- x_skew = (np.sum(x_minus_mean*x_minus_mean*x_minus_mean, axis=0)/9998.)/x_var**(3./2.)
- print("Skewness of those random numbers (should be about ", skew, "):", x_skew)
-
-def test():
- obj = mt.get_state()
- mt.set_state(obj)
- obj2 = mt.get_state()
- if (obj2[1] - obj[1]).any():
- raise SystemExit("Failed seed test.")
- print("First random number is", random())
- print("Average of 10000 random numbers is", np.sum(random(10000), axis=0)/10000.)
- x = random([10, 1000])
- if len(x.shape) != 2 or x.shape[0] != 10 or x.shape[1] != 1000:
- raise SystemExit("random returned wrong shape")
- x.shape = (10000,)
- print("Average of 100 by 100 random numbers is", np.sum(x, axis=0)/10000.)
- y = uniform(0.5, 0.6, (1000, 10))
- if len(y.shape) !=2 or y.shape[0] != 1000 or y.shape[1] != 10:
- raise SystemExit("uniform returned wrong shape")
- y.shape = (10000,)
- if np.minimum.reduce(y) <= 0.5 or np.maximum.reduce(y) >= 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(np.array([10, 20]), np.array(([1, 2], [2, 4])))
- print("\nA multivariate normal", x)
- if x.shape != (2,): raise SystemExit("multivariate_normal returned wrong shape")
- x = multivariate_normal(np.array([10, 20]), np.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(np.array([-100, 0, 100]), np.array([[3, 2, 1], [2, 2, 1], [1, 1, 1]]), 10000)
- x_mean = np.sum(x, axis=0)/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(np.dot(np.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*np.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 = ", np.sum(x, axis=0)/8.)
-
-if __name__ == '__main__':
- test()
diff --git a/numpy/oldnumeric/rng.py b/numpy/oldnumeric/rng.py
deleted file mode 100644
index 06120798d..000000000
--- a/numpy/oldnumeric/rng.py
+++ /dev/null
@@ -1,137 +0,0 @@
-"""Re-create the RNG interface from Numeric.
-
-Replace import RNG with import numpy.oldnumeric.rng as RNG.
-It is for backwards compatibility only.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['CreateGenerator', 'ExponentialDistribution', 'LogNormalDistribution',
- 'NormalDistribution', 'UniformDistribution', 'error', 'ranf',
- 'default_distribution', 'random_sample', '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_*math.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*math.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*math.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)
diff --git a/numpy/oldnumeric/rng_stats.py b/numpy/oldnumeric/rng_stats.py
deleted file mode 100644
index dd450343d..000000000
--- a/numpy/oldnumeric/rng_stats.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__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, axis=0))**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)), axis=0)
- 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]))
diff --git a/numpy/oldnumeric/setup.py b/numpy/oldnumeric/setup.py
deleted file mode 100644
index 13c3e0d8d..000000000
--- a/numpy/oldnumeric/setup.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from __future__ import division, print_function
-
-def configuration(parent_package='',top_path=None):
- from numpy.distutils.misc_util import Configuration
- config = Configuration('oldnumeric', parent_package, top_path)
- config.add_data_dir('tests')
- return config
-
-if __name__ == '__main__':
- from numpy.distutils.core import setup
- setup(configuration=configuration)
diff --git a/numpy/oldnumeric/tests/test_oldnumeric.py b/numpy/oldnumeric/tests/test_oldnumeric.py
deleted file mode 100644
index 2c1a806ac..000000000
--- a/numpy/oldnumeric/tests/test_oldnumeric.py
+++ /dev/null
@@ -1,96 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-import unittest
-
-from numpy.testing import *
-
-from numpy import array
-from numpy.oldnumeric import *
-from numpy.core.numeric import float32, float64, complex64, complex128, int8, \
- int16, int32, int64, uint, uint8, uint16, uint32, uint64
-
-class test_oldtypes(unittest.TestCase):
- def test_oldtypes(self, level=1):
- a1 = array([0, 1, 0], Float)
- a2 = array([0, 1, 0], float)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Float8)
- a2 = array([0, 1, 0], float)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Float16)
- a2 = array([0, 1, 0], float)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Float32)
- a2 = array([0, 1, 0], float32)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Float64)
- a2 = array([0, 1, 0], float64)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Complex)
- a2 = array([0, 1, 0], complex)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Complex8)
- a2 = array([0, 1, 0], complex)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Complex16)
- a2 = array([0, 1, 0], complex)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Complex32)
- a2 = array([0, 1, 0], complex64)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Complex64)
- a2 = array([0, 1, 0], complex128)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Int)
- a2 = array([0, 1, 0], int)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Int8)
- a2 = array([0, 1, 0], int8)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Int16)
- a2 = array([0, 1, 0], int16)
- assert_array_equal(a1, a2)
- a1 = array([0, 1, 0], Int32)
- a2 = array([0, 1, 0], int32)
- assert_array_equal(a1, a2)
- try:
- a1 = array([0, 1, 0], Int64)
- a2 = array([0, 1, 0], int64)
- assert_array_equal(a1, a2)
- except NameError:
- # Not all systems have 64-bit integers.
- pass
- a1 = array([0, 1, 0], UnsignedInt)
- a2 = array([0, 1, 0], UnsignedInteger)
- a3 = array([0, 1, 0], uint)
- assert_array_equal(a1, a3)
- assert_array_equal(a2, a3)
- a1 = array([0, 1, 0], UInt8)
- a2 = array([0, 1, 0], UnsignedInt8)
- a3 = array([0, 1, 0], uint8)
- assert_array_equal(a1, a3)
- assert_array_equal(a2, a3)
- a1 = array([0, 1, 0], UInt16)
- a2 = array([0, 1, 0], UnsignedInt16)
- a3 = array([0, 1, 0], uint16)
- assert_array_equal(a1, a3)
- assert_array_equal(a2, a3)
- a1 = array([0, 1, 0], UInt32)
- a2 = array([0, 1, 0], UnsignedInt32)
- a3 = array([0, 1, 0], uint32)
- assert_array_equal(a1, a3)
- assert_array_equal(a2, a3)
- try:
- a1 = array([0, 1, 0], UInt64)
- a2 = array([0, 1, 0], UnsignedInt64)
- a3 = array([0, 1, 0], uint64)
- assert_array_equal(a1, a3)
- assert_array_equal(a2, a3)
- except NameError:
- # Not all systems have 64-bit integers.
- pass
-
-
-if __name__ == "__main__":
- import nose
- nose.main()
diff --git a/numpy/oldnumeric/tests/test_regression.py b/numpy/oldnumeric/tests/test_regression.py
deleted file mode 100644
index 272323b81..000000000
--- a/numpy/oldnumeric/tests/test_regression.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-from numpy.testing import *
-
-rlevel = 1
-
-class TestRegression(TestCase):
- def test_numeric_random(self, level=rlevel):
- """Ticket #552"""
- from numpy.oldnumeric.random_array import randint
- randint(0, 50, [2, 3])
diff --git a/numpy/oldnumeric/typeconv.py b/numpy/oldnumeric/typeconv.py
deleted file mode 100644
index c4a8c4385..000000000
--- a/numpy/oldnumeric/typeconv.py
+++ /dev/null
@@ -1,62 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__all__ = ['oldtype2dtype', 'convtypecode', 'convtypecode2', 'oldtypecodes']
-
-import numpy as np
-
-oldtype2dtype = {'1': np.dtype(np.byte),
- 's': np.dtype(np.short),
-# 'i': np.dtype(np.intc),
-# 'l': np.dtype(int),
-# 'b': np.dtype(np.ubyte),
- 'w': np.dtype(np.ushort),
- 'u': np.dtype(np.uintc),
-# 'f': np.dtype(np.single),
-# 'd': np.dtype(float),
-# 'F': np.dtype(np.csingle),
-# 'D': np.dtype(complex),
-# 'O': np.dtype(object),
-# 'c': np.dtype('c'),
- None: np.dtype(int)
- }
-
-# converts typecode=None to int
-def convtypecode(typecode, dtype=None):
- if dtype is None:
- try:
- return oldtype2dtype[typecode]
- except:
- return np.dtype(typecode)
- else:
- return dtype
-
-#if both typecode and dtype are None
-# return None
-def convtypecode2(typecode, dtype=None):
- if dtype is None:
- if typecode is None:
- return None
- else:
- try:
- return oldtype2dtype[typecode]
- except:
- return np.dtype(typecode)
- else:
- return dtype
-
-_changedtypes = {'B': 'b',
- 'b': '1',
- 'h': 's',
- 'H': 'w',
- 'I': 'u'}
-
-class _oldtypecodes(dict):
- def __getitem__(self, obj):
- char = np.dtype(obj).char
- try:
- return _changedtypes[char]
- except KeyError:
- return char
-
-
-oldtypecodes = _oldtypecodes()
diff --git a/numpy/oldnumeric/ufuncs.py b/numpy/oldnumeric/ufuncs.py
deleted file mode 100644
index 4ab43cb1f..000000000
--- a/numpy/oldnumeric/ufuncs.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-__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', 'divide_safe']
-
-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, divide as divide_safe
diff --git a/numpy/oldnumeric/user_array.py b/numpy/oldnumeric/user_array.py
deleted file mode 100644
index e5f3ecd01..000000000
--- a/numpy/oldnumeric/user_array.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-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