summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
authorDavid Cournapeau <cournape@gmail.com>2008-09-20 11:39:20 +0000
committerDavid Cournapeau <cournape@gmail.com>2008-09-20 11:39:20 +0000
commit99c765d3be1b7ce73e2a7def0f99af6ae7d6a522 (patch)
treec33d5d09196578dd46fb466a3dcadeccd0ab4607 /numpy
parent7e79e3909956beac477060543f569adc3e53661c (diff)
parent3060e39a4dc5ffc4852d7f7b2adc8f8d79bde0df (diff)
downloadnumpy-99c765d3be1b7ce73e2a7def0f99af6ae7d6a522.tar.gz
Merged revisions 5812-5843 via svnmerge from
http://svn.scipy.org/svn/numpy/trunk ........ r5821 | alan.mcintyre | 2008-09-14 03:04:57 +0900 (Sun, 14 Sep 2008) | 3 lines Removed unused imports. Standardize NumPy import as "import numpy as np". ........ r5822 | alan.mcintyre | 2008-09-14 03:10:48 +0900 (Sun, 14 Sep 2008) | 6 lines Rewrapped __all__ definition to conform to PEP8. Standardize NumPy import as "import numpy as np". Removed unused imports. Fixed undefined reference to ndarray (should be np.ndarray). Fixed undefined references to exp (should be math.exp). ........ r5823 | alan.mcintyre | 2008-09-14 03:15:38 +0900 (Sun, 14 Sep 2008) | 3 lines Removed unused imports. Fixed undefined reference to "getpackage" (from nose.util). ........ r5824 | pierregm | 2008-09-14 06:17:09 +0900 (Sun, 14 Sep 2008) | 1 line MaskedArray.__new__ : make sure that we inherit the _hardmask from data (if any) instead of reverting to default. ........ r5826 | alan.mcintyre | 2008-09-18 12:29:56 +0900 (Thu, 18 Sep 2008) | 4 lines Added documentation for doctests and using the skipif and knownfailureif decorators. Fixed indentation on the last sample snippet in the "__init__.py and setup.py" section. ........ r5827 | alan.mcintyre | 2008-09-18 12:33:15 +0900 (Thu, 18 Sep 2008) | 3 lines Rewrapped __all__ to conform with PEP8. Removed unused imports. ........ r5828 | alan.mcintyre | 2008-09-18 12:33:58 +0900 (Thu, 18 Sep 2008) | 2 lines Removed unused imports. ........ r5829 | alan.mcintyre | 2008-09-18 12:45:53 +0900 (Thu, 18 Sep 2008) | 3 lines Removed unused/redundant imports. PEP8 conformance (only one import per line). ........ r5830 | alan.mcintyre | 2008-09-18 12:57:47 +0900 (Thu, 18 Sep 2008) | 2 lines Removed redundant import. ........ r5831 | pierregm | 2008-09-19 02:51:55 +0900 (Fri, 19 Sep 2008) | 1 line median : fixed a bug in _median1D (there shouldn't have been an axis) ........ r5832 | jarrod.millman | 2008-09-19 03:53:53 +0900 (Fri, 19 Sep 2008) | 2 lines ReSTified an URL ........ r5833 | rkern | 2008-09-19 06:48:57 +0900 (Fri, 19 Sep 2008) | 1 line BUG: Override setuptools' install.run() method to correctly allow 'python setup.py install' to work. ........ r5834 | pierregm | 2008-09-19 12:33:40 +0900 (Fri, 19 Sep 2008) | 1 line * fixing view to recognize dtype and type parameters, for consistency with regular ndarrays. ........ r5835 | pierregm | 2008-09-20 04:43:05 +0900 (Sat, 20 Sep 2008) | 8 lines core: * add dtype to the repr of masked arrays w/ flexible type * prevent __getitem__ to return masked on flexible-type masked array * make sure __str__ returns something sensible for flexible dtype w/ masked fields * simplify the count method mrecords: * fixed a pb with fromrecords when the number of fields cannot be determined from the first element. ........
Diffstat (limited to 'numpy')
-rw-r--r--numpy/_import_tools.py2
-rw-r--r--numpy/core/records.py26
-rw-r--r--numpy/distutils/command/install.py37
-rw-r--r--numpy/f2py/auxfuncs.py2
-rw-r--r--numpy/f2py/cb_rules.py3
-rw-r--r--numpy/f2py/cfuncs.py4
-rw-r--r--numpy/f2py/common_rules.py4
-rwxr-xr-xnumpy/f2py/crackfortran.py1
-rwxr-xr-xnumpy/f2py/doc/collectinput.py1
-rwxr-xr-xnumpy/f2py/f2py2e.py7
-rw-r--r--numpy/f2py/f2py_testing.py3
-rw-r--r--numpy/f2py/f90mod_rules.py4
-rw-r--r--numpy/f2py/func2subr.py3
-rw-r--r--numpy/f2py/use_rules.py5
-rw-r--r--numpy/lib/index_tricks.py2
-rw-r--r--numpy/lib/twodim_base.py2
-rw-r--r--numpy/lib/utils.py4
-rw-r--r--numpy/linalg/linalg.py15
-rw-r--r--numpy/ma/bench.py6
-rw-r--r--numpy/ma/core.py73
-rw-r--r--numpy/ma/extras.py2
-rw-r--r--numpy/ma/mrecords.py46
-rw-r--r--numpy/ma/tests/test_core.py20
-rw-r--r--numpy/ma/tests/test_extras.py39
-rw-r--r--numpy/ma/tests/test_mrecords.py15
-rw-r--r--numpy/ma/testutils.py6
-rw-r--r--numpy/ma/timer_comparison.py76
-rw-r--r--numpy/oldnumeric/arrayfns.py27
-rw-r--r--numpy/oldnumeric/compat.py2
-rw-r--r--numpy/oldnumeric/mlab.py12
-rw-r--r--numpy/oldnumeric/rng.py12
-rw-r--r--numpy/testing/noseclasses.py15
32 files changed, 267 insertions, 209 deletions
diff --git a/numpy/_import_tools.py b/numpy/_import_tools.py
index 4bda26d87..38bf712fe 100644
--- a/numpy/_import_tools.py
+++ b/numpy/_import_tools.py
@@ -1,7 +1,5 @@
-
import os
import sys
-import imp
__all__ = ['PackageLoader']
diff --git a/numpy/core/records.py b/numpy/core/records.py
index 6f94c3e9f..1d5b85b97 100644
--- a/numpy/core/records.py
+++ b/numpy/core/records.py
@@ -448,16 +448,22 @@ class recarray(ndarray):
else:
return self.setfield(val, *res)
- def view(self, obj):
- try:
- if issubclass(obj, ndarray):
- return ndarray.view(self, obj)
- except TypeError:
- pass
- dtype = sb.dtype(obj)
- if dtype.fields is None:
- return self.__array__().view(dtype)
- return ndarray.view(self, obj)
+ def view(self, dtype=None, type=None):
+ if dtype is None:
+ return ndarray.view(self, type)
+ elif type is None:
+ try:
+ if issubclass(dtype, ndarray):
+ return ndarray.view(self, dtype)
+ except TypeError:
+ pass
+ dtype = sb.dtype(dtype)
+ if dtype.fields is None:
+ return self.__array__().view(dtype)
+ return ndarray.view(self, dtype)
+ else:
+ return ndarray.view(self, dtype, type)
+
def fromarrays(arrayList, dtype=None, shape=None, formats=None,
names=None, titles=None, aligned=False, byteorder=None):
diff --git a/numpy/distutils/command/install.py b/numpy/distutils/command/install.py
index 36e6b5a66..87b549da8 100644
--- a/numpy/distutils/command/install.py
+++ b/numpy/distutils/command/install.py
@@ -1,8 +1,10 @@
import sys
if 'setuptools' in sys.modules:
import setuptools.command.install as old_install_mod
+ have_setuptools = True
else:
import distutils.command.install as old_install_mod
+ have_setuptools = False
old_install = old_install_mod.install
from distutils.file_util import write_file
@@ -12,8 +14,41 @@ class install(old_install):
old_install.finalize_options(self)
self.install_lib = self.install_libbase
+ def setuptools_run(self):
+ """ The setuptools version of the .run() method.
+
+ We must pull in the entire code so we can override the level used in the
+ _getframe() call since we wrap this call by one more level.
+ """
+ # Explicit request for old-style install? Just do it
+ if self.old_and_unmanageable or self.single_version_externally_managed:
+ return old_install_mod._install.run(self)
+
+ # Attempt to detect whether we were called from setup() or by another
+ # command. If we were called by setup(), our caller will be the
+ # 'run_command' method in 'distutils.dist', and *its* caller will be
+ # the 'run_commands' method. If we were called any other way, our
+ # immediate caller *might* be 'run_command', but it won't have been
+ # called by 'run_commands'. This is slightly kludgy, but seems to
+ # work.
+ #
+ caller = sys._getframe(3)
+ caller_module = caller.f_globals.get('__name__','')
+ caller_name = caller.f_code.co_name
+
+ if caller_module != 'distutils.dist' or caller_name!='run_commands':
+ # We weren't called from the command line or setup(), so we
+ # should run in backward-compatibility mode to support bdist_*
+ # commands.
+ old_install_mod._install.run(self)
+ else:
+ self.do_egg_install()
+
def run(self):
- r = old_install.run(self)
+ if not have_setuptools:
+ r = old_install.run(self)
+ else:
+ r = self.setuptools_run()
if self.record:
# bdist_rpm fails when INSTALLED_FILES contains
# paths with spaces. Such paths must be enclosed
diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py
index fb82c28df..facbd0534 100644
--- a/numpy/f2py/auxfuncs.py
+++ b/numpy/f2py/auxfuncs.py
@@ -20,9 +20,7 @@ f2py_version = __version__.version
import pprint
import sys
-import time
import types
-import os
import cfuncs
diff --git a/numpy/f2py/cb_rules.py b/numpy/f2py/cb_rules.py
index 8f6ac101a..aeb0e7a11 100644
--- a/numpy/f2py/cb_rules.py
+++ b/numpy/f2py/cb_rules.py
@@ -21,16 +21,13 @@ f2py_version = __version__.version
import pprint
import sys
-import time
import types
-import copy
errmess=sys.stderr.write
outmess=sys.stdout.write
show=pprint.pprint
from auxfuncs import *
import capi_maps
-#from capi_maps import *
import cfuncs
################## Rules for callback function ##############
diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py
index a1e8ebff3..02462241c 100644
--- a/numpy/f2py/cfuncs.py
+++ b/numpy/f2py/cfuncs.py
@@ -19,7 +19,9 @@ __version__ = "$Revision: 1.75 $"[10:-1]
import __version__
f2py_version = __version__.version
-import types,sys,copy,os
+import types
+import sys
+import copy
errmess=sys.stderr.write
##################### Definitions ##################
diff --git a/numpy/f2py/common_rules.py b/numpy/f2py/common_rules.py
index c4a7b5dab..3295676ef 100644
--- a/numpy/f2py/common_rules.py
+++ b/numpy/f2py/common_rules.py
@@ -20,16 +20,12 @@ f2py_version = __version__.version
import pprint
import sys
-import time
-import types
-import copy
errmess=sys.stderr.write
outmess=sys.stdout.write
show=pprint.pprint
from auxfuncs import *
import capi_maps
-import cfuncs
import func2subr
from crackfortran import rmbadname
##############
diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py
index e8bd696bc..8e5f2882f 100755
--- a/numpy/f2py/crackfortran.py
+++ b/numpy/f2py/crackfortran.py
@@ -15,7 +15,6 @@ Pearu Peterson
__version__ = "$Revision: 1.177 $"[10:-1]
import __version__
-import string
f2py_version = __version__.version
"""
diff --git a/numpy/f2py/doc/collectinput.py b/numpy/f2py/doc/collectinput.py
index 54a908fcc..2e6c6c96b 100755
--- a/numpy/f2py/doc/collectinput.py
+++ b/numpy/f2py/doc/collectinput.py
@@ -23,7 +23,6 @@ __version__ = "0.0"
stdoutflag=0
import sys
-import os
import fileinput
import re
import commands
diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py
index eb0ae1889..2fd4f6caa 100755
--- a/numpy/f2py/f2py2e.py
+++ b/numpy/f2py/f2py2e.py
@@ -21,7 +21,6 @@ f2py_version = __version__.version
import sys
import os
import pprint
-import shutil
import types
import re
errmess=sys.stderr.write
@@ -31,11 +30,8 @@ show=pprint.pprint
import crackfortran
import rules
import cb_rules
-import common_rules
import auxfuncs
import cfuncs
-import capi_maps
-import func2subr
import f90mod_rules
outmess = auxfuncs.outmess
@@ -395,7 +391,7 @@ def run_compile():
"""
Do it all in one call!
"""
- import tempfile,os,shutil
+ import tempfile
i = sys.argv.index('-c')
del sys.argv[i]
@@ -547,6 +543,7 @@ def run_compile():
setup(ext_modules = [ext])
if remove_build_dir and os.path.exists(build_dir):
+ import shutil
outmess('Removing build directory %s\n'%(build_dir))
shutil.rmtree(build_dir)
diff --git a/numpy/f2py/f2py_testing.py b/numpy/f2py/f2py_testing.py
index aabf0c569..0c78f3594 100644
--- a/numpy/f2py/f2py_testing.py
+++ b/numpy/f2py/f2py_testing.py
@@ -1,4 +1,5 @@
-import os,sys,re,time
+import sys
+import re
from numpy.testing.utils import jiffies, memusage
diff --git a/numpy/f2py/f90mod_rules.py b/numpy/f2py/f90mod_rules.py
index f8ca508e0..f494d43c0 100644
--- a/numpy/f2py/f90mod_rules.py
+++ b/numpy/f2py/f90mod_rules.py
@@ -17,11 +17,8 @@ __version__ = "$Revision: 1.27 $"[10:-1]
f2py_version='See `f2py -v`'
-import copy
import pprint
import sys
-import time
-import types
errmess=sys.stderr.write
outmess=sys.stdout.write
show=pprint.pprint
@@ -29,7 +26,6 @@ show=pprint.pprint
from auxfuncs import *
import numpy as np
import capi_maps
-import cfuncs
import rules
import func2subr
from crackfortran import undo_rmbadname, undo_rmbadname1
diff --git a/numpy/f2py/func2subr.py b/numpy/f2py/func2subr.py
index b0421bb55..7ce30bc70 100644
--- a/numpy/f2py/func2subr.py
+++ b/numpy/f2py/func2subr.py
@@ -20,9 +20,6 @@ f2py_version='See `f2py -v`'
import pprint
import copy
import sys
-import time
-import types
-import copy
errmess=sys.stderr.write
outmess=sys.stdout.write
show=pprint.pprint
diff --git a/numpy/f2py/use_rules.py b/numpy/f2py/use_rules.py
index 25e52df0b..021d08601 100644
--- a/numpy/f2py/use_rules.py
+++ b/numpy/f2py/use_rules.py
@@ -21,16 +21,11 @@ f2py_version='See `f2py -v`'
import pprint
import sys
-import time
-import types
-import copy
errmess=sys.stderr.write
outmess=sys.stdout.write
show=pprint.pprint
from auxfuncs import *
-import capi_maps
-import cfuncs
##############
usemodule_rules={
diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py
index af87b24a6..02018c87e 100644
--- a/numpy/lib/index_tricks.py
+++ b/numpy/lib/index_tricks.py
@@ -7,7 +7,7 @@ __all__ = ['unravel_index',
import sys
import numpy.core.numeric as _nx
-from numpy.core.numeric import asarray, ScalarType, array, dtype
+from numpy.core.numeric import asarray, ScalarType, array
from numpy.core.numerictypes import find_common_type
import math
diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py
index d779009e7..69eecbd87 100644
--- a/numpy/lib/twodim_base.py
+++ b/numpy/lib/twodim_base.py
@@ -6,7 +6,7 @@ __all__ = ['diag','diagflat','eye','fliplr','flipud','rot90','tri','triu',
'tril','vander','histogram2d']
from numpy.core.numeric import asanyarray, equal, subtract, arange, \
- zeros, arange, greater_equal, multiply, ones, asarray
+ zeros, greater_equal, multiply, ones, asarray
def fliplr(m):
"""
diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py
index 684876591..1c88fb3f1 100644
--- a/numpy/lib/utils.py
+++ b/numpy/lib/utils.py
@@ -4,9 +4,7 @@ import pkgutil
import types
import re
-from numpy.core.numerictypes import obj2sctype, generic, issubclass_, \
- issubsctype, issubdtype
-from numpy.core.multiarray import dtype as _dtype
+from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype
from numpy.core import product, ndarray
__all__ = ['issubclass_', 'get_numpy_include', 'issubsctype',
diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py
index f9af033f0..c0bb95004 100644
--- a/numpy/linalg/linalg.py
+++ b/numpy/linalg/linalg.py
@@ -9,16 +9,9 @@ dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
"""
-__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv',
- 'inv', 'cholesky',
- 'eigvals',
- 'eigvalsh', 'pinv',
- 'det', 'svd',
- 'eig', 'eigh','lstsq', 'norm',
- 'qr',
- 'cond',
- 'LinAlgError'
- ]
+__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
+ 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'det', 'svd',
+ 'eig', 'eigh','lstsq', 'norm', 'qr', 'cond', 'LinAlgError']
from numpy.core import array, asarray, zeros, empty, transpose, \
intc, single, double, csingle, cdouble, inexact, complexfloating, \
@@ -27,7 +20,7 @@ from numpy.core import array, asarray, zeros, empty, transpose, \
isfinite, size
from numpy.lib import triu
from numpy.linalg import lapack_lite
-from numpy.core.defmatrix import matrix_power, matrix
+from numpy.core.defmatrix import matrix_power
fortran_int = intc
diff --git a/numpy/ma/bench.py b/numpy/ma/bench.py
index 19fbe9461..2cc8f6a80 100644
--- a/numpy/ma/bench.py
+++ b/numpy/ma/bench.py
@@ -6,9 +6,9 @@ import timeit
#ip = IPython.ipapi.get()
#from IPython import ipmagic
import numpy
-from numpy import ma
-from numpy.ma import filled
-from numpy.ma.testutils import assert_equal
+#from numpy import ma
+#from numpy.ma import filled
+#from numpy.ma.testutils import assert_equal
#####---------------------------------------------------------------------------
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index e76f8787b..8eb4b3161 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -57,17 +57,14 @@ __all__ = ['MAError', 'MaskType', 'MaskedArray',
'var', 'where',
'zeros']
-import sys
-import types
import cPickle
import operator
import numpy as np
-from numpy import ndarray, typecodes, amax, amin, iscomplexobj,\
- bool_, complex_, float_, int_, object_, str_
+from numpy import ndarray, amax, amin, iscomplexobj, bool_, complex_, float_,\
+ int_, object_
from numpy import array as narray
-
import numpy.core.umath as umath
import numpy.core.numerictypes as ntypes
from numpy import expand_dims as n_expand_dims
@@ -1237,7 +1234,7 @@ class MaskedArray(ndarray):
def __new__(cls, data=None, mask=nomask, dtype=None, copy=False,
subok=True, ndmin=0, fill_value=None,
- keep_mask=True, hard_mask=False, flag=None, shrink=True,
+ keep_mask=True, hard_mask=None, flag=None, shrink=True,
**options):
"""Create a new masked array from scratch.
@@ -1341,7 +1338,10 @@ class MaskedArray(ndarray):
if fill_value is not None:
_data._fill_value = _check_fill_value(fill_value, _data.dtype)
# Process extra options ..
- _data._hardmask = hard_mask
+ if hard_mask is None:
+ _data._hardmask = getattr(data, '_hardmask', False)
+ else:
+ _data._hardmask = hard_mask
_data._baseclass = _baseclass
return _data
#
@@ -1479,15 +1479,22 @@ class MaskedArray(ndarray):
# if getmask(indx) is not nomask:
# msg = "Masked arrays must be filled before they can be used as indices!"
# raise IndexError, msg
- dout = ndarray.__getitem__(self.view(ndarray), indx)
+ dout = ndarray.__getitem__(ndarray.view(self,ndarray), indx)
# We could directly use ndarray.__getitem__ on self...
# But then we would have to modify __array_finalize__ to prevent the
# mask of being reshaped if it hasn't been set up properly yet...
# So it's easier to stick to the current version
_mask = self._mask
if not getattr(dout,'ndim', False):
+ # A record ................
+ if isinstance(dout, np.void):
+ mask = _mask[indx]
+ if mask.view((bool,len(mask.dtype))).any():
+ dout = masked_array(dout, mask=mask)
+ else:
+ return dout
# Just a scalar............
- if _mask is not nomask and _mask[indx]:
+ elif _mask is not nomask and _mask[indx]:
return masked
else:
# Force dout to MA ........
@@ -1896,7 +1903,15 @@ class MaskedArray(ndarray):
res = self._data
else:
if m.shape == ():
- if m:
+ if m.dtype.names:
+ m = m.view((bool, len(m.dtype)))
+ if m.any():
+ r = np.array(self._data.tolist(), dtype=object)
+ np.putmask(r, m, f)
+ return str(tuple(r))
+ else:
+ return str(self._data)
+ elif m:
return str(f)
else:
return str(self._data)
@@ -1933,21 +1948,31 @@ masked_%(name)s(data = %(data)s,
mask = %(mask)s,
fill_value=%(fill)s)
"""
+ with_mask_flx = """\
+masked_%(name)s(data =
+ %(data)s,
+ mask =
+ %(mask)s,
+ fill_value=%(fill)s,
+ dtype=%(dtype)s)
+"""
+ with_mask1_flx = """\
+masked_%(name)s(data = %(data)s,
+ mask = %(mask)s,
+ fill_value=%(fill)s
+ dtype=%(dtype)s)
+"""
n = len(self.shape)
name = repr(self._data).split('(')[0]
- if n <= 1:
- return with_mask1 % {
- 'name': name,
- 'data': str(self),
- 'mask': str(self._mask),
- 'fill': str(self.fill_value),
- }
- return with_mask % {
- 'name': name,
- 'data': str(self),
- 'mask': str(self._mask),
- 'fill': str(self.fill_value),
- }
+ parameters = dict(name=name, data=str(self), mask=str(self._mask),
+ fill=str(self.fill_value), dtype=str(self.dtype))
+ if self.dtype.names:
+ if n<= 1:
+ return with_mask1_flx % parameters
+ return with_mask_flx % parameters
+ elif n <= 1:
+ return with_mask1 % parameters
+ return with_mask % parameters
#............................................
def __add__(self, other):
"Add other to self, and return a new masked array."
@@ -3509,6 +3534,8 @@ def concatenate(arrays, axis=0):
return data
def count(a, axis = None):
+ if isinstance(a, MaskedArray):
+ return a.count(axis)
return masked_array(a, copy=False).count(axis)
count.__doc__ = MaskedArray.count.__doc__
diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py
index f0e8a3fea..ded2d475f 100644
--- a/numpy/ma/extras.py
+++ b/numpy/ma/extras.py
@@ -415,7 +415,7 @@ def median(a, axis=None, out=None, overwrite_input=False):
"""
def _median1D(data):
- counts = filled(count(data, axis),0)
+ counts = filled(count(data),0)
(idx, rmd) = divmod(counts, 2)
if rmd:
choice = slice(idx, idx+1)
diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py
index e6735c015..24c62d81b 100644
--- a/numpy/ma/mrecords.py
+++ b/numpy/ma/mrecords.py
@@ -16,23 +16,21 @@ By comparison, mrecarrays support masking individual fields.
__author__ = "Pierre GF Gerard-Marchant"
import sys
-import types
import numpy as np
-from numpy import bool_, complex_, float_, int_, str_, object_, dtype, \
- chararray, ndarray, recarray, record, array as narray
+from numpy import bool_, dtype, \
+ ndarray, recarray, array as narray
import numpy.core.numerictypes as ntypes
-from numpy.core.records import find_duplicate, format_parser
from numpy.core.records import fromarrays as recfromarrays, \
- fromrecords as recfromrecords
+ fromrecords as recfromrecords
_byteorderconv = np.core.records._byteorderconv
_typestr = ntypes._typestr
import numpy.ma as ma
from numpy.ma import MAError, MaskedArray, masked, nomask, masked_array,\
- make_mask, mask_or, getdata, getmask, getmaskarray, filled, \
- default_fill_value, masked_print_option
+ getdata, getmaskarray, filled
+
_check_fill_value = ma.core._check_fill_value
import warnings
@@ -153,10 +151,9 @@ class MaskedRecords(MaskedArray, object):
return self
#......................................................
def __array_finalize__(self,obj):
- MaskedArray._update_from(self,obj)
# Make sure we have a _fieldmask by default ..
- _fieldmask = getattr(obj, '_fieldmask', None)
- if _fieldmask is None:
+ _mask = getattr(obj, '_mask', None)
+ if _mask is None:
objmask = getattr(obj, '_mask', nomask)
_dtype = ndarray.__getattribute__(self,'dtype')
if objmask is nomask:
@@ -165,15 +162,15 @@ class MaskedRecords(MaskedArray, object):
mdescr = ma.make_mask_descr(_dtype)
_mask = narray([tuple([m]*len(mdescr)) for m in objmask],
dtype=mdescr).view(recarray)
- else:
- _mask = _fieldmask
# Update some of the attributes
- _locdict = self.__dict__
- if _locdict['_baseclass'] == ndarray:
- _locdict['_baseclass'] = recarray
- _locdict.update(_mask=_mask, _fieldmask=_mask)
+ _dict = self.__dict__
+ _dict.update(_mask=_mask, _fieldmask=_mask)
+ self._update_from(obj)
+ if _dict['_baseclass'] == ndarray:
+ _dict['_baseclass'] = recarray
return
+
def _getdata(self):
"Returns the data as a recarray."
return ndarray.view(self,recarray)
@@ -250,7 +247,6 @@ class MaskedRecords(MaskedArray, object):
# Get the list of names ......
fielddict = ndarray.__getattribute__(self,'dtype').fields or {}
# Check the attribute
-##### _localdict = self.__dict__
if attr not in fielddict:
return ret
if newattr: # We just added this one
@@ -284,8 +280,8 @@ class MaskedRecords(MaskedArray, object):
"""Returns all the fields sharing the same fieldname base.
The fieldname base is either `_data` or `_mask`."""
_localdict = self.__dict__
- _mask = _localdict['_fieldmask']
- _data = self._data
+ _mask = ndarray.__getattribute__(self,'_mask')
+ _data = ndarray.view(self, _localdict['_baseclass'])
# We want a field ........
if isinstance(indx, basestring):
#!!!: Make sure _sharedmask is True to propagate back to _fieldmask
@@ -473,7 +469,7 @@ def fromarrays(arraylist, dtype=None, shape=None, formats=None,
dtype=dtype, shape=shape, formats=formats,
names=names, titles=titles, aligned=aligned,
byteorder=byteorder).view(mrecarray)
- _array._fieldmask.flat = zip(*masklist)
+ _array._mask.flat = zip(*masklist)
if fill_value is not None:
_array.fill_value = fill_value
return _array
@@ -507,13 +503,17 @@ def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None,
mask : {nomask, sequence}, optional.
External mask to apply on the data.
-*Notes*:
+ Notes
+ -----
Lists of tuples should be preferred over lists of lists for faster processing.
"""
# Grab the initial _fieldmask, if needed:
_fieldmask = getattr(reclist, '_fieldmask', None)
# Get the list of records.....
- nfields = len(reclist[0])
+ try:
+ nfields = len(reclist[0])
+ except TypeError:
+ nfields = len(reclist[0].dtype)
if isinstance(reclist, ndarray):
# Make sure we don't have some hidden mask
if isinstance(reclist,MaskedArray):
@@ -656,7 +656,7 @@ and `newfieldname` as name. If `newfieldname` is None, the new field name is
set to 'fi', where `i` is the number of existing fields.
"""
_data = mrecord._data
- _mask = mrecord._fieldmask
+ _mask = mrecord._mask
if newfieldname is None or newfieldname in reserved_fields:
newfieldname = 'f%i' % len(_data.dtype)
newfield = ma.array(newfield)
diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py
index 411fca516..de6a40e92 100644
--- a/numpy/ma/tests/test_core.py
+++ b/numpy/ma/tests/test_core.py
@@ -173,10 +173,12 @@ class TestMaskedArray(TestCase):
def test_asarray(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
xm.fill_value = -9999
+ xm._hardmask = True
xmm = asarray(xm)
assert_equal(xmm._data, xm._data)
assert_equal(xmm._mask, xm._mask)
assert_equal(xmm.fill_value, xm.fill_value)
+ assert_equal(xmm._hardmask, xm._hardmask)
def test_fix_invalid(self):
"Checks fix_invalid."
@@ -2370,7 +2372,23 @@ class TestMaskedFields(TestCase):
test = a.view((float,2), np.matrix)
assert_equal(test, data)
assert(isinstance(test, np.matrix))
-
+ #
+ def test_getitem(self):
+ ndtype = [('a',float), ('b',float)]
+ a = array(zip(np.random.rand(10),np.arange(10)), dtype=ndtype)
+ a.mask = np.array(zip([0,0,0,0,0,0,0,0,1,1],
+ [1,0,0,0,0,0,0,0,1,0]),
+ dtype=[('a',bool),('b',bool)])
+ # No mask
+ assert(isinstance(a[1], np.void))
+ # One element masked
+ assert(isinstance(a[0], MaskedArray))
+ assert_equal_records(a[0]._data, a._data[0])
+ assert_equal_records(a[0]._mask, a._mask[0])
+ # All element masked
+ assert(isinstance(a[-2], MaskedArray))
+ assert_equal_records(a[-2]._data, a._data[-2])
+ assert_equal_records(a[-2]._mask, a._mask[-2])
###############################################################################
#------------------------------------------------------------------------------
diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py
index f6105f843..0b670c348 100644
--- a/numpy/ma/tests/test_extras.py
+++ b/numpy/ma/tests/test_extras.py
@@ -11,7 +11,7 @@ __version__ = '1.0'
__revision__ = "$Revision: 3473 $"
__date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
-import numpy
+import numpy as np
from numpy.testing import TestCase, run_module_suite
from numpy.ma.testutils import *
from numpy.ma.core import *
@@ -332,25 +332,36 @@ class TestMedian(TestCase):
def test_2d(self):
"Tests median w/ 2D"
(n,p) = (101,30)
- x = masked_array(numpy.linspace(-1.,1.,n),)
+ x = masked_array(np.linspace(-1.,1.,n),)
x[:10] = x[-10:] = masked
- z = masked_array(numpy.empty((n,p), dtype=numpy.float_))
+ z = masked_array(np.empty((n,p), dtype=float))
z[:,0] = x[:]
- idx = numpy.arange(len(x))
+ idx = np.arange(len(x))
for i in range(1,p):
- numpy.random.shuffle(idx)
+ np.random.shuffle(idx)
z[:,i] = x[idx]
assert_equal(median(z[:,0]), 0)
- assert_equal(median(z), numpy.zeros((p,)))
+ assert_equal(median(z), 0)
+ assert_equal(median(z, axis=0), np.zeros(p))
+ assert_equal(median(z.T, axis=1), np.zeros(p))
+ #
+ def test_2d_waxis(self):
+ "Tests median w/ 2D arrays and different axis."
+ x = masked_array(np.arange(30).reshape(10,3))
+ x[:3] = x[-3:] = masked
+ assert_equal(median(x), 14.5)
+ assert_equal(median(x, axis=0), [13.5,14.5,15.5])
+ assert_equal(median(x,axis=1), [0,0,0,10,13,16,19,0,0,0])
+ assert_equal(median(x,axis=1).mask, [1,1,1,0,0,0,0,1,1,1])
#
def test_3d(self):
"Tests median w/ 3D"
- x = numpy.ma.arange(24).reshape(3,4,2)
+ x = np.ma.arange(24).reshape(3,4,2)
x[x%3==0] = masked
assert_equal(median(x,0), [[12,9],[6,15],[12,9],[18,15]])
x.shape = (4,3,2)
assert_equal(median(x,0),[[99,10],[11,99],[13,14]])
- x = numpy.ma.arange(24).reshape(4,3,2)
+ x = np.ma.arange(24).reshape(4,3,2)
x[x%5==0] = masked
assert_equal(median(x,0), [[12,10],[8,9],[16,17]])
@@ -483,9 +494,9 @@ class TestPolynomial(TestCase):
def test_polyfit(self):
"Tests polyfit"
# On ndarrays
- x = numpy.random.rand(10)
- y = numpy.random.rand(20).reshape(-1,2)
- assert_almost_equal(polyfit(x,y,3),numpy.polyfit(x,y,3))
+ x = np.random.rand(10)
+ y = np.random.rand(20).reshape(-1,2)
+ assert_almost_equal(polyfit(x,y,3),np.polyfit(x,y,3))
# ON 1D maskedarrays
x = x.view(MaskedArray)
x[0] = masked
@@ -493,17 +504,17 @@ class TestPolynomial(TestCase):
y[0,0] = y[-1,-1] = masked
#
(C,R,K,S,D) = polyfit(x,y[:,0],3,full=True)
- (c,r,k,s,d) = numpy.polyfit(x[1:], y[1:,0].compressed(), 3, full=True)
+ (c,r,k,s,d) = np.polyfit(x[1:], y[1:,0].compressed(), 3, full=True)
for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)):
assert_almost_equal(a, a_)
#
(C,R,K,S,D) = polyfit(x,y[:,-1],3,full=True)
- (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,-1], 3, full=True)
+ (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,-1], 3, full=True)
for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)):
assert_almost_equal(a, a_)
#
(C,R,K,S,D) = polyfit(x,y,3,full=True)
- (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
+ (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)):
assert_almost_equal(a, a_)
diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py
index 38758393c..52b9fd314 100644
--- a/numpy/ma/tests/test_mrecords.py
+++ b/numpy/ma/tests/test_mrecords.py
@@ -8,23 +8,19 @@ __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
__revision__ = "$Revision: 3473 $"
__date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
-import types
-
import numpy as np
from numpy import recarray
from numpy.core.records import fromrecords as recfromrecords, \
- fromarrays as recfromarrays
+ fromarrays as recfromarrays
import numpy.ma.testutils
from numpy.ma.testutils import *
import numpy.ma as ma
-from numpy.ma import masked, nomask, getdata, getmaskarray
+from numpy.ma import masked, nomask
-import numpy.ma.mrecords
-reload(numpy.ma.mrecords)
-from numpy.ma.mrecords import MaskedRecords, mrecarray,\
- fromarrays, fromtextfile, fromrecords, addfield
+from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \
+ fromtextfile, fromrecords, addfield
#..............................................................................
class TestMRecords(TestCase):
@@ -207,8 +203,8 @@ class TestMRecords(TestCase):
#
def test_set_elements(self):
base = self.base.copy()
- mbase = base.view(mrecarray)
# Set an element to mask .....................
+ mbase = base.view(mrecarray).copy()
mbase[-2] = masked
assert_equal(mbase._fieldmask.tolist(),
np.array([(0,0,0),(1,1,1),(0,0,0),(1,1,1),(1,1,1)],
@@ -432,7 +428,6 @@ class TestMRecordsImport(TestCase):
'strings',4,-1e-10,,,1
"""
import os
- from datetime import datetime
import tempfile
(tmp_fd,tmp_fl) = tempfile.mkstemp()
os.write(tmp_fd, fcontent)
diff --git a/numpy/ma/testutils.py b/numpy/ma/testutils.py
index 8de590be5..9dc9cf5c2 100644
--- a/numpy/ma/testutils.py
+++ b/numpy/ma/testutils.py
@@ -16,12 +16,10 @@ import numpy as np
from numpy import ndarray, float_
import numpy.core.umath as umath
from numpy.testing import *
-from numpy.testing.utils import build_err_msg, rand
import numpy.testing.utils as utils
-import core
-from core import mask_or, getmask, getmaskarray, masked_array, nomask, masked
-from core import fix_invalid, filled, equal, less
+from core import mask_or, getmask, masked_array, nomask, masked, filled, \
+ equal, less
#------------------------------------------------------------------------------
def approx (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8):
diff --git a/numpy/ma/timer_comparison.py b/numpy/ma/timer_comparison.py
index 45f0b22a6..282931494 100644
--- a/numpy/ma/timer_comparison.py
+++ b/numpy/ma/timer_comparison.py
@@ -1,16 +1,14 @@
-
import timeit
-import numpy
-from numpy import int_, float_, bool_
-import numpy.core.fromnumeric as fromnumeric
-
-from numpy.testing.utils import build_err_msg, rand
+import numpy as np
+from numpy import float_
+import np.core.fromnumeric as fromnumeric
+from np.testing.utils import build_err_msg
-numpy.seterr(all='ignore')
+np.seterr(all='ignore')
-pi = numpy.pi
+pi = np.pi
class moduletester:
#-----------------------------------
@@ -61,15 +59,15 @@ class moduletester:
y = self.filled(self.masked_array(yf, mask=m), fill_value)
if (x.dtype.char != "O"):
x = x.astype(float_)
- if isinstance(x, numpy.ndarray) and x.size > 1:
- x[numpy.isnan(x)] = 0
- elif numpy.isnan(x):
+ if isinstance(x, np.ndarray) and x.size > 1:
+ x[np.isnan(x)] = 0
+ elif np.isnan(x):
x = 0
if (y.dtype.char != "O"):
y = y.astype(float_)
- if isinstance(y, numpy.ndarray) and y.size > 1:
- y[numpy.isnan(y)] = 0
- elif numpy.isnan(y):
+ if isinstance(y, np.ndarray) and y.size > 1:
+ y[np.isnan(y)] = 0
+ elif np.isnan(y):
y = 0
try:
cond = (x.shape==() or y.shape==()) or x.shape == y.shape
@@ -110,23 +108,23 @@ class moduletester:
#----------------------------------
def test_0(self):
"Tests creation"
- x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+ x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
xm = self.masked_array(x, mask=m)
xm[0]
#----------------------------------
def test_1(self):
"Tests creation"
- x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
- y = numpy.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
+ x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+ y = np.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
a10 = 10.
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0 ,0, 1]
xm = self.masked_array(x, mask=m1)
ym = self.masked_array(y, mask=m2)
- z = numpy.array([-.5, 0., .5, .8])
+ z = np.array([-.5, 0., .5, .8])
zm = self.masked_array(z, mask=[0,1,0,0])
- xf = numpy.where(m1, 1.e+20, x)
+ xf = np.where(m1, 1.e+20, x)
xm.set_fill_value(1.e+20)
#.....
assert((xm-ym).filled(0).any())
@@ -146,13 +144,13 @@ class moduletester:
#----------------------------------
def test_2(self):
"Tests conversions and indexing"
- x1 = numpy.array([1,2,4,3])
+ x1 = np.array([1,2,4,3])
x2 = self.array(x1, mask=[1,0,0,0])
x3 = self.array(x1, mask=[0,1,0,1])
x4 = self.array(x1)
# test conversion to strings
junk, garbage = str(x2), repr(x2)
-# assert_equal(numpy.sort(x1), self.sort(x2, fill_value=0))
+# assert_equal(np.sort(x1), self.sort(x2, fill_value=0))
# tests of indexing
assert type(x2[1]) is type(x1[1])
assert x1[1] == x2[1]
@@ -178,12 +176,12 @@ class moduletester:
x4[:] = self.masked_array([1,2,3,4],[0,1,1,0])
# assert self.allequal(self.getmask(x4), self.array([0,1,1,0]))
# assert self.allequal(x4, self.array([1,2,3,4]))
- x1 = numpy.arange(5)*1.0
+ x1 = np.arange(5)*1.0
x2 = self.masked_values(x1, 3.0)
# assert self.allequal(x1,x2)
# assert self.allequal(self.array([0,0,0,1,0], self.MaskType), x2.mask)
x1 = self.array([1,'hello',2,3],object)
- x2 = numpy.array([1,'hello',2,3],object)
+ x2 = np.array([1,'hello',2,3],object)
s1 = x1[1]
s2 = x2[1]
assert x1[1:1].shape == (0,)
@@ -216,15 +214,15 @@ class moduletester:
def test_4(self):
"Test of take, transpose, inner, outer products"
x = self.arange(24)
- y = numpy.arange(24)
+ y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2,3,4)
y = y.reshape(2,3,4)
- assert self.allequal(numpy.transpose(y,(2,0,1)), self.transpose(x,(2,0,1)))
- assert self.allequal(numpy.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1))
- assert self.allequal(numpy.inner(self.filled(x,0), self.filled(y,0)),
+ assert self.allequal(np.transpose(y,(2,0,1)), self.transpose(x,(2,0,1)))
+ assert self.allequal(np.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1))
+ assert self.allequal(np.inner(self.filled(x,0), self.filled(y,0)),
self.inner(x, y))
- assert self.allequal(numpy.outer(self.filled(x,0), self.filled(y,0)),
+ assert self.allequal(np.outer(self.filled(x,0), self.filled(y,0)),
self.outer(x, y))
y = self.array(['abc', 1, 'def', 2, 3], object)
y[2] = self.masked
@@ -396,8 +394,8 @@ class moduletester:
self.assert_array_equal(self.average(x, axis=0), 2.5)
self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5)
y = self.array([self.arange(6), 2.0*self.arange(6)])
- self.assert_array_equal(self.average(y, None), numpy.add.reduce(numpy.arange(6))*3./12.)
- self.assert_array_equal(self.average(y, axis=0), numpy.arange(6) * 3./2.)
+ self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.)
+ self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.)
self.assert_array_equal(self.average(y, axis=1), [self.average(x,axis=0), self.average(x,axis=0) * 2.0])
self.assert_array_equal(self.average(y, None, weights=w2), 20./6.)
self.assert_array_equal(self.average(y, axis=0, weights=w2), [0.,1.,2.,3.,4.,10.])
@@ -420,7 +418,7 @@ class moduletester:
#------------------------
def test_A(self):
x = self.arange(24)
- y = numpy.arange(24)
+ y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2,3,4)
@@ -431,10 +429,10 @@ if __name__ == '__main__':
setup_base = "from __main__ import moduletester \n"\
"import numpy\n" \
"tester = moduletester(module)\n"
-# setup_new = "import numpy.ma.core_ini as module\n"+setup_base
- setup_cur = "import numpy.ma.core as module\n"+setup_base
-# setup_alt = "import numpy.ma.core_alt as module\n"+setup_base
-# setup_tmp = "import numpy.ma.core_tmp as module\n"+setup_base
+# setup_new = "import np.ma.core_ini as module\n"+setup_base
+ setup_cur = "import np.ma.core as module\n"+setup_base
+# setup_alt = "import np.ma.core_alt as module\n"+setup_base
+# setup_tmp = "import np.ma.core_tmp as module\n"+setup_base
(nrepeat, nloop) = (10, 10)
@@ -445,10 +443,10 @@ if __name__ == '__main__':
cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10)
# alt = timeit.Timer(func, setup_alt).repeat(nrepeat, nloop*10)
# tmp = timeit.Timer(func, setup_tmp).repeat(nrepeat, nloop*10)
-# new = numpy.sort(new)
- cur = numpy.sort(cur)
-# alt = numpy.sort(alt)
-# tmp = numpy.sort(tmp)
+# new = np.sort(new)
+ cur = np.sort(cur)
+# alt = np.sort(alt)
+# tmp = np.sort(tmp)
print "#%i" % i +50*'.'
print eval("moduletester.test_%i.__doc__" % i)
# print "core_ini : %.3f - %.3f" % (new[0], new[1])
diff --git a/numpy/oldnumeric/arrayfns.py b/numpy/oldnumeric/arrayfns.py
index 4c31a6827..dbb910770 100644
--- a/numpy/oldnumeric/arrayfns.py
+++ b/numpy/oldnumeric/arrayfns.py
@@ -1,10 +1,11 @@
"""Backward compatible with arrayfns from Numeric
"""
-__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort',
- 'interp', 'nz', 'reverse', 'span', 'to_corners', 'zmin_zmax']
+__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask',
+ 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span',
+ 'to_corners', 'zmin_zmax']
-import numpy as nx
+import numpy as np
from numpy import asarray
class error(Exception):
@@ -14,7 +15,7 @@ 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, ndarray):
+ if not isinstance(vals1, np.ndarray):
raise TypeError, "vals1 must be an ndarray"
vals1 = asarray(vals1)
vals2 = asarray(vals2)
@@ -31,7 +32,7 @@ def index_sort(arr):
def interp(y, x, z, typ=None):
"""y(z) interpolated by treating y(x) as piecewise function
"""
- res = numpy.interp(z, x, y)
+ res = np.interp(z, x, y)
if typ is None or typ == 'd':
return res
if typ == 'f':
@@ -40,17 +41,17 @@ def interp(y, x, z, typ=None):
raise error, "incompatible typecode"
def nz(x):
- x = asarray(x,dtype=nx.ubyte)
+ x = asarray(x,dtype=np.ubyte)
if x.ndim != 1:
raise TypeError, "intput must have 1 dimension."
- indxs = nx.flatnonzero(x != 0)
+ 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 = nx.empty_like(x)
+ y = np.empty_like(x)
if n == 0:
y[...] = x[::-1,:]
elif n == 1:
@@ -58,11 +59,11 @@ def reverse(x, n):
return y
def span(lo, hi, num, d2=0):
- x = linspace(lo, hi, num)
+ x = np.linspace(lo, hi, num)
if d2 <= 0:
return x
else:
- ret = empty((d2,num),x.dtype)
+ ret = np.empty((d2,num),x.dtype)
ret[...] = x
return ret
@@ -71,15 +72,15 @@ def zmin_zmax(z, ireg):
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 = nx.nonzero(ireg)
+ 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 = nx.r_[ix, x1m[i1], x1m[i1], ix[i2] ]
- niy = nx.r_[iy, iy[i1], y1m[i3], y1m[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()
diff --git a/numpy/oldnumeric/compat.py b/numpy/oldnumeric/compat.py
index 7f123fa69..3e1d53d0e 100644
--- a/numpy/oldnumeric/compat.py
+++ b/numpy/oldnumeric/compat.py
@@ -12,7 +12,7 @@ __all__ = ['NewAxis',
import numpy.core.multiarray as multiarray
import numpy.core.umath as um
-from numpy.core.numeric import array, correlate
+from numpy.core.numeric import array
import functions
import sys
diff --git a/numpy/oldnumeric/mlab.py b/numpy/oldnumeric/mlab.py
index 47be89e1b..c11e34c1f 100644
--- a/numpy/oldnumeric/mlab.py
+++ b/numpy/oldnumeric/mlab.py
@@ -1,6 +1,10 @@
# This module is for compatibility only. All functions are defined elsewhere.
-__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean']
+__all__ = ['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
@@ -12,7 +16,7 @@ from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \
from numpy.linalg import eig, svd
from numpy.random import rand, randn
-import numpy as nn
+import numpy as np
from typeconv import convtypecode
@@ -22,7 +26,7 @@ def eye(N, M=None, k=0, typecode=None, dtype=None):
"""
dtype = convtypecode(typecode, dtype)
if M is None: M = N
- m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k)
+ m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k)
if m.dtype != dtype:
return m.astype(dtype)
@@ -32,7 +36,7 @@ def tri(N, M=None, k=0, typecode=None, dtype=None):
"""
dtype = convtypecode(typecode, dtype)
if M is None: M = N
- m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k)
+ m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)),-k)
if m.dtype != dtype:
return m.astype(dtype)
diff --git a/numpy/oldnumeric/rng.py b/numpy/oldnumeric/rng.py
index fcf08bb37..b4c72a68c 100644
--- a/numpy/oldnumeric/rng.py
+++ b/numpy/oldnumeric/rng.py
@@ -4,9 +4,9 @@
# It is for backwards compatibility only.
-__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution','NormalDistribution',
- 'UniformDistribution', 'error', 'default_distribution', 'random_sample', 'ranf',
- 'standard_generator']
+__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution',
+ 'NormalDistribution', 'UniformDistribution', 'error', 'ranf',
+ 'default_distribution', 'random_sample', 'standard_generator']
import numpy.random.mtrand as mt
import math
@@ -44,7 +44,7 @@ class ExponentialDistribution(Distribution):
return 0.0
else:
lambda_ = self._args[0]
- return lambda_*exp(-lambda_*x)
+ return lambda_*math.exp(-lambda_*x)
class LogNormalDistribution(Distribution):
def __init__(self, m, s):
@@ -61,7 +61,7 @@ class LogNormalDistribution(Distribution):
def density(x):
m,s = self._args
y = (math.log(x)-self._mn)/self._sn
- return self._fac*exp(-0.5*y*y)/x
+ return self._fac*math.exp(-0.5*y*y)/x
class NormalDistribution(Distribution):
@@ -76,7 +76,7 @@ class NormalDistribution(Distribution):
def density(x):
m,s = self._args
y = (x-m)/s
- return self._fac*exp(-0.5*y*y)
+ return self._fac*math.exp(-0.5*y*y)
class UniformDistribution(Distribution):
def __init__(self, a, b):
diff --git a/numpy/testing/noseclasses.py b/numpy/testing/noseclasses.py
index 1cd03a8bf..d838a5f84 100644
--- a/numpy/testing/noseclasses.py
+++ b/numpy/testing/noseclasses.py
@@ -9,7 +9,7 @@ import doctest
from nose.plugins import doctests as npd
from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin
from nose.plugins.base import Plugin
-from nose.util import src, tolist
+from nose.util import src, getpackage
import numpy
from nosetester import get_package_name
import inspect
@@ -79,10 +79,11 @@ class NumpyDocTestFinder(doctest.DocTestFinder):
# doctests in extension modules.
# Local shorthands
- from inspect import isroutine, isclass, ismodule
+ from inspect import isroutine, isclass, ismodule, isfunction, \
+ ismethod
# Look for tests in a module's contained objects.
- if inspect.ismodule(obj) and self._recurse:
+ if ismodule(obj) and self._recurse:
for valname, val in obj.__dict__.items():
valname1 = '%s.%s' % (name, valname)
if ( (isroutine(val) or isclass(val))
@@ -93,7 +94,7 @@ class NumpyDocTestFinder(doctest.DocTestFinder):
# Look for tests in a class's contained objects.
- if inspect.isclass(obj) and self._recurse:
+ if isclass(obj) and self._recurse:
#print 'RECURSE into class:',obj # dbg
for valname, val in obj.__dict__.items():
#valname1 = '%s.%s' % (name, valname) # dbg
@@ -105,9 +106,8 @@ class NumpyDocTestFinder(doctest.DocTestFinder):
val = getattr(obj, valname).im_func
# Recurse to methods, properties, and nested classes.
- if ((inspect.isfunction(val) or inspect.isclass(val) or
- inspect.ismethod(val) or
- isinstance(val, property)) and
+ if ((isfunction(val) or isclass(val) or
+ ismethod(val) or isinstance(val, property)) and
self._from_module(module, val)):
valname = '%s.%s' % (name, valname)
self._find(tests, val, valname, module, source_lines,
@@ -175,7 +175,6 @@ class NumpyDoctest(npd.Doctest):
def configure(self, options, config):
Plugin.configure(self, options, config)
self.doctest_tests = True
-# self.extension = tolist(options.doctestExtension)
self.finder = NumpyDocTestFinder()
self.parser = doctest.DocTestParser()