diff options
412 files changed, 1518 insertions, 1057 deletions
diff --git a/.travis.yml b/.travis.yml index 6cf83d8f9..6949be4bc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,8 +10,12 @@ matrix: include: - python: 2.7 env: NPY_SEPARATE_COMPILATION=0 - - python: 3.2 + - python: 3.3 env: NPY_SEPARATE_COMPILATION=0 + - python: 2.7 + env: NPY_RELAXED_STRIDES_CHECKING=1 + - python: 3.3 + env: NPY_RELAXED_STRIDES_CHECKING=1 before_install: - uname -a - free -m diff --git a/doc/cdoc/numpyfilter.py b/doc/cdoc/numpyfilter.py index 4a93141dd..60bee1b51 100755 --- a/doc/cdoc/numpyfilter.py +++ b/doc/cdoc/numpyfilter.py @@ -6,7 +6,7 @@ Interpret C comments as ReStructuredText, and replace them by the HTML output. Also, add Doxygen /** and /**< syntax automatically where appropriate. """ -from __future__ import division +from __future__ import division, absolute_import import sys import re diff --git a/doc/cython/run_test.py b/doc/cython/run_test.py index 64918ed9c..986016c7a 100755 --- a/doc/cython/run_test.py +++ b/doc/cython/run_test.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import from numpyx import test test() diff --git a/doc/example.py b/doc/example.py index 5c9d3d27e..e01640948 100644 --- a/doc/example.py +++ b/doc/example.py @@ -8,7 +8,7 @@ extend over multiple lines, the closing three quotation marks must be on a line by itself, preferably preceeded by a blank line. """ -from __future__ import division +from __future__ import division, absolute_import import os # standard library imports first diff --git a/doc/neps/missing-data.rst b/doc/neps/missing-data.rst index 6f124890b..338a8da96 100644 --- a/doc/neps/missing-data.rst +++ b/doc/neps/missing-data.rst @@ -320,7 +320,7 @@ A manual loop through a masked array like:: >>> a[3] = np.NA >>> a array([ 0., 1., 2., NA, 4.], maskna=True) - >>> for i in xrange(len(a)): + >>> for i in range(len(a)): ... a[i] = np.log(a[i]) ... __main__:2: RuntimeWarning: divide by zero encountered in log diff --git a/doc/newdtype_example/example.py b/doc/newdtype_example/example.py index b9ccc465b..f6251c0b9 100644 --- a/doc/newdtype_example/example.py +++ b/doc/newdtype_example/example.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import floatint.floatint as ff import numpy as np diff --git a/doc/newdtype_example/floatint/__init__.py b/doc/newdtype_example/floatint/__init__.py index 5c6aac4d6..b4895eb4c 100644 --- a/doc/newdtype_example/floatint/__init__.py +++ b/doc/newdtype_example/floatint/__init__.py @@ -1,3 +1,3 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/doc/numpybook/comparison/ctypes/filter.py b/doc/numpybook/comparison/ctypes/filter.py index ebc274f31..16acec04b 100644 --- a/doc/numpybook/comparison/ctypes/filter.py +++ b/doc/numpybook/comparison/ctypes/filter.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['filter2d'] diff --git a/doc/numpybook/comparison/ctypes/interface.py b/doc/numpybook/comparison/ctypes/interface.py index ab1b14731..651ee9439 100644 --- a/doc/numpybook/comparison/ctypes/interface.py +++ b/doc/numpybook/comparison/ctypes/interface.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['add', 'filter2d'] diff --git a/doc/numpybook/comparison/timing.py b/doc/numpybook/comparison/timing.py index 18004855e..59978ba35 100644 --- a/doc/numpybook/comparison/timing.py +++ b/doc/numpybook/comparison/timing.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import timeit diff --git a/doc/numpybook/comparison/weave/filter.py b/doc/numpybook/comparison/weave/filter.py index 519a54c5b..9fa726a79 100644 --- a/doc/numpybook/comparison/weave/filter.py +++ b/doc/numpybook/comparison/weave/filter.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from scipy import weave, zeros_like diff --git a/doc/numpybook/comparison/weave/inline.py b/doc/numpybook/comparison/weave/inline.py index 1f98b7a62..9c134b231 100644 --- a/doc/numpybook/comparison/weave/inline.py +++ b/doc/numpybook/comparison/weave/inline.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from scipy import weave from numpy import rand, zeros_like diff --git a/doc/numpybook/runcode.py b/doc/numpybook/runcode.py index 92784d34e..66c74cd74 100644 --- a/doc/numpybook/runcode.py +++ b/doc/numpybook/runcode.py @@ -14,7 +14,7 @@ Options: -n name of code section (default MyCode) """ -from __future__ import division +from __future__ import division, absolute_import import sys import optparse diff --git a/doc/postprocess.py b/doc/postprocess.py index 512070193..195ab9d96 100755 --- a/doc/postprocess.py +++ b/doc/postprocess.py @@ -6,7 +6,7 @@ Post-processes HTML and Latex files output by Sphinx. MODE is either 'html' or 'tex'. """ -from __future__ import division +from __future__ import division, absolute_import import re, optparse diff --git a/doc/pyrex/run_test.py b/doc/pyrex/run_test.py index 64918ed9c..986016c7a 100755 --- a/doc/pyrex/run_test.py +++ b/doc/pyrex/run_test.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import from numpyx import test test() diff --git a/doc/release/1.8.0-notes.rst b/doc/release/1.8.0-notes.rst index f41c8e716..1750b5d14 100644 --- a/doc/release/1.8.0-notes.rst +++ b/doc/release/1.8.0-notes.rst @@ -37,6 +37,13 @@ compiler, then it's possible you will encounter problems. If so, please file a bug and as a temporary workaround you can re-enable the old build system by exporting the shell variable NPY_SEPARATE_COMPILATION=0. +For the AdvancedNew iterator the ``oa_ndim`` flag should now be -1 to indicate +that no ``op_axes`` and ``itershape`` are passed in. The ``oa_ndim == 0`` +case, now indicates a 0-D iteration and ``op_axes`` being NULL and the old +usage is deprecated. This does not effect the ``NpyIter_New`` or +``NpyIter_MultiNew`` functions. + + New features ============ diff --git a/doc/source/conf.py b/doc/source/conf.py index f22505f97..8b29316cb 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -from __future__ import division +from __future__ import division, absolute_import import sys, os, re diff --git a/doc/source/reference/arrays.classes.rst b/doc/source/reference/arrays.classes.rst index b35e36545..5cdadd40e 100644 --- a/doc/source/reference/arrays.classes.rst +++ b/doc/source/reference/arrays.classes.rst @@ -340,7 +340,7 @@ The default iterator of an ndarray object is the default Python iterator of a sequence type. Thus, when the array object itself is used as an iterator. The default behavior is equivalent to:: - for i in xrange(arr.shape[0]): + for i in range(arr.shape[0]): val = arr[i] This default iterator selects a sub-array of dimension :math:`N-1` diff --git a/doc/source/reference/c-api.iterator.rst b/doc/source/reference/c-api.iterator.rst index 7e2900bcc..1e3565bc1 100644 --- a/doc/source/reference/c-api.iterator.rst +++ b/doc/source/reference/c-api.iterator.rst @@ -634,12 +634,12 @@ Construction and Destruction Extends :cfunc:`NpyIter_MultiNew` with several advanced options providing more control over broadcasting and buffering. - If 0/NULL values are passed to ``oa_ndim``, ``op_axes``, ``itershape``, + If -1/NULL values are passed to ``oa_ndim``, ``op_axes``, ``itershape``, and ``buffersize``, it is equivalent to :cfunc:`NpyIter_MultiNew`. - The parameter ``oa_ndim``, when non-zero, specifies the number of + The parameter ``oa_ndim``, when not zero or -1, specifies the number of dimensions that will be iterated with customized broadcasting. - If it is provided, ``op_axes`` and/or ``itershape`` must also be provided. + If it is provided, ``op_axes`` must and ``itershape`` can also be provided. The ``op_axes`` parameter let you control in detail how the axes of the operand arrays get matched together and iterated. In ``op_axes``, you must provide an array of ``nop`` pointers @@ -649,6 +649,11 @@ Construction and Destruction -1 which means ``newaxis``. Within each ``op_axes[j]`` array, axes may not be repeated. The following example is how normal broadcasting applies to a 3-D array, a 2-D array, a 1-D array and a scalar. + + **Note**: Before NumPy 1.8 ``oa_ndim == 0` was used for signalling that + that ``op_axes`` and ``itershape`` are unused. This is deprecated and + should be replaced with -1. Better backward compatibility may be + achieved by using :cfunc:`NpyIter_MultiNew` for this case. .. code-block:: c diff --git a/doc/sphinxext/numpydoc/__init__.py b/doc/sphinxext/numpydoc/__init__.py index 68dbbb00a..9fa06e37c 100644 --- a/doc/sphinxext/numpydoc/__init__.py +++ b/doc/sphinxext/numpydoc/__init__.py @@ -1 +1,3 @@ +from __future__ import division, absolute_import + from .numpydoc import setup diff --git a/doc/sphinxext/numpydoc/comment_eater.py b/doc/sphinxext/numpydoc/comment_eater.py index 0e205072e..74d0d4768 100644 --- a/doc/sphinxext/numpydoc/comment_eater.py +++ b/doc/sphinxext/numpydoc/comment_eater.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys if sys.version_info[0] >= 3: diff --git a/doc/sphinxext/numpydoc/compiler_unparse.py b/doc/sphinxext/numpydoc/compiler_unparse.py index 56da748d1..bb76f7ea3 100644 --- a/doc/sphinxext/numpydoc/compiler_unparse.py +++ b/doc/sphinxext/numpydoc/compiler_unparse.py @@ -10,7 +10,7 @@ fixme: We may want to move to using _ast trees because the compiler for them is about 6 times faster than compiler.compile. """ -from __future__ import division +from __future__ import division, absolute_import import sys from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add diff --git a/doc/sphinxext/numpydoc/docscrape.py b/doc/sphinxext/numpydoc/docscrape.py index 0fe259447..af76b86e5 100644 --- a/doc/sphinxext/numpydoc/docscrape.py +++ b/doc/sphinxext/numpydoc/docscrape.py @@ -1,7 +1,7 @@ """Extract reference documentation from the NumPy source tree. """ -from __future__ import division +from __future__ import division, absolute_import import sys import inspect diff --git a/doc/sphinxext/numpydoc/docscrape_sphinx.py b/doc/sphinxext/numpydoc/docscrape_sphinx.py index 14d766d84..1248253b3 100644 --- a/doc/sphinxext/numpydoc/docscrape_sphinx.py +++ b/doc/sphinxext/numpydoc/docscrape_sphinx.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import re, inspect, textwrap, pydoc import sphinx diff --git a/doc/sphinxext/numpydoc/linkcode.py b/doc/sphinxext/numpydoc/linkcode.py index 58361e8c3..986f39384 100644 --- a/doc/sphinxext/numpydoc/linkcode.py +++ b/doc/sphinxext/numpydoc/linkcode.py @@ -9,7 +9,7 @@ :license: BSD, see LICENSE for details. """ -from __future__ import division +from __future__ import division, absolute_import import warnings import collections diff --git a/doc/sphinxext/numpydoc/numpydoc.py b/doc/sphinxext/numpydoc/numpydoc.py index 0243d23c4..d95d476ef 100644 --- a/doc/sphinxext/numpydoc/numpydoc.py +++ b/doc/sphinxext/numpydoc/numpydoc.py @@ -15,7 +15,7 @@ It will: .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt """ -from __future__ import division +from __future__ import division, absolute_import import sphinx import collections diff --git a/doc/sphinxext/numpydoc/phantom_import.py b/doc/sphinxext/numpydoc/phantom_import.py index 6308f492d..855068834 100644 --- a/doc/sphinxext/numpydoc/phantom_import.py +++ b/doc/sphinxext/numpydoc/phantom_import.py @@ -14,7 +14,7 @@ without needing to rebuild the documented module. .. [1] http://code.google.com/p/pydocweb """ -from __future__ import division +from __future__ import division, absolute_import import imp, sys, compiler, types, os, inspect, re diff --git a/doc/sphinxext/numpydoc/plot_directive.py b/doc/sphinxext/numpydoc/plot_directive.py index 7547642a2..9e92acabb 100644 --- a/doc/sphinxext/numpydoc/plot_directive.py +++ b/doc/sphinxext/numpydoc/plot_directive.py @@ -74,7 +74,7 @@ TODO to make them appear side-by-side, or in floats. """ -from __future__ import division +from __future__ import division, absolute_import import sys, os, glob, shutil, imp, warnings, re, textwrap, traceback import sphinx diff --git a/doc/sphinxext/numpydoc/tests/test_docscrape.py b/doc/sphinxext/numpydoc/tests/test_docscrape.py index 90e8345d4..877d33980 100644 --- a/doc/sphinxext/numpydoc/tests/test_docscrape.py +++ b/doc/sphinxext/numpydoc/tests/test_docscrape.py @@ -1,5 +1,5 @@ # -*- encoding:utf-8 -*- -from __future__ import division +from __future__ import division, absolute_import import sys, textwrap diff --git a/doc/sphinxext/numpydoc/tests/test_linkcode.py b/doc/sphinxext/numpydoc/tests/test_linkcode.py index 45de6b70d..b0c863dd6 100644 --- a/doc/sphinxext/numpydoc/tests/test_linkcode.py +++ b/doc/sphinxext/numpydoc/tests/test_linkcode.py @@ -1,3 +1,5 @@ +from __future__ import division, absolute_import + import numpydoc.linkcode # No tests at the moment... diff --git a/doc/sphinxext/numpydoc/tests/test_phantom_import.py b/doc/sphinxext/numpydoc/tests/test_phantom_import.py index b9ee76fc6..337db377a 100644 --- a/doc/sphinxext/numpydoc/tests/test_phantom_import.py +++ b/doc/sphinxext/numpydoc/tests/test_phantom_import.py @@ -1,3 +1,5 @@ +from __future__ import division, absolute_import + import numpydoc.phantom_import # No tests at the moment... diff --git a/doc/sphinxext/numpydoc/tests/test_plot_directive.py b/doc/sphinxext/numpydoc/tests/test_plot_directive.py index 3496d2c29..738166424 100644 --- a/doc/sphinxext/numpydoc/tests/test_plot_directive.py +++ b/doc/sphinxext/numpydoc/tests/test_plot_directive.py @@ -1,3 +1,5 @@ +from __future__ import division, absolute_import + import numpydoc.plot_directive # No tests at the moment... diff --git a/doc/sphinxext/numpydoc/tests/test_traitsdoc.py b/doc/sphinxext/numpydoc/tests/test_traitsdoc.py index 99b1600fb..882d6f796 100644 --- a/doc/sphinxext/numpydoc/tests/test_traitsdoc.py +++ b/doc/sphinxext/numpydoc/tests/test_traitsdoc.py @@ -1,3 +1,5 @@ +from __future__ import division, absolute_import + import numpydoc.traitsdoc # No tests at the moment... diff --git a/doc/sphinxext/numpydoc/traitsdoc.py b/doc/sphinxext/numpydoc/traitsdoc.py index 784c4fc2f..74c226ab4 100644 --- a/doc/sphinxext/numpydoc/traitsdoc.py +++ b/doc/sphinxext/numpydoc/traitsdoc.py @@ -13,7 +13,7 @@ for Traits is required. .. [2] http://code.enthought.com/projects/traits/ """ -from __future__ import division +from __future__ import division, absolute_import import inspect import os diff --git a/doc/summarize.py b/doc/summarize.py index d953bd642..d72fcef61 100755 --- a/doc/summarize.py +++ b/doc/summarize.py @@ -5,7 +5,7 @@ summarize.py Show a summary about which Numpy functions are documented and which are not. """ -from __future__ import division +from __future__ import division, absolute_import import os, glob, re, sys, inspect, optparse import collections diff --git a/doc/swig/test/testArray.py b/doc/swig/test/testArray.py index b25aff85a..433dfb1bd 100755 --- a/doc/swig/test/testArray.py +++ b/doc/swig/test/testArray.py @@ -1,5 +1,5 @@ #! /usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # System imports from distutils.util import get_platform diff --git a/doc/swig/test/testFarray.py b/doc/swig/test/testFarray.py index 184fd2564..c0699b07d 100755 --- a/doc/swig/test/testFarray.py +++ b/doc/swig/test/testFarray.py @@ -1,5 +1,5 @@ #! /usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # System imports from distutils.util import get_platform diff --git a/doc/swig/test/testFortran.py b/doc/swig/test/testFortran.py index 56bc03eae..499f6a439 100644 --- a/doc/swig/test/testFortran.py +++ b/doc/swig/test/testFortran.py @@ -1,5 +1,5 @@ #! /usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # System imports from distutils.util import get_platform diff --git a/doc/swig/test/testMatrix.py b/doc/swig/test/testMatrix.py index 68259de3e..187cd7214 100755 --- a/doc/swig/test/testMatrix.py +++ b/doc/swig/test/testMatrix.py @@ -1,5 +1,5 @@ #! /usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # System imports from distutils.util import get_platform diff --git a/doc/swig/test/testTensor.py b/doc/swig/test/testTensor.py index 41b037811..cd9cada46 100755 --- a/doc/swig/test/testTensor.py +++ b/doc/swig/test/testTensor.py @@ -1,5 +1,5 @@ #! /usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # System imports from distutils.util import get_platform diff --git a/doc/swig/test/testVector.py b/doc/swig/test/testVector.py index 2ad00b856..29a77d281 100755 --- a/doc/swig/test/testVector.py +++ b/doc/swig/test/testVector.py @@ -1,5 +1,5 @@ #! /usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # System imports from distutils.util import get_platform diff --git a/numpy/__init__.py b/numpy/__init__.py index 03e2afe6e..9cae9d388 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -104,7 +104,7 @@ available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. Exceptions to this rule are documented. """ -from __future__ import division +from __future__ import division, absolute_import # We first need to detect if we're being called as part of the numpy setup # procedure itself in a reliable manner. @@ -126,43 +126,43 @@ else: its source directory; please exit the numpy source tree, and relaunch your python intepreter from there.""" raise ImportError(msg) - from version import git_revision as __git_revision__ - from version import version as __version__ + from .version import git_revision as __git_revision__ + from .version import version as __version__ - from _import_tools import PackageLoader + from ._import_tools import PackageLoader def pkgload(*packages, **options): loader = PackageLoader(infunc=True) return loader(*packages, **options) - import add_newdocs + from . import add_newdocs __all__ = ['add_newdocs'] pkgload.__doc__ = PackageLoader.__call__.__doc__ - from testing import Tester + from .testing import Tester test = Tester().test bench = Tester().bench - import core - from core import * - import compat - import lib - from lib import * - import linalg - import fft - import polynomial - import random - import ctypeslib - import ma - import matrixlib as _mat - from matrixlib import * + from . import core + from .core import * + from . import compat + from . import lib + from .lib import * + from . import linalg + from . import fft + from . import polynomial + from . import random + from . import ctypeslib + from . import ma + from . import matrixlib as _mat + from .matrixlib import * # Make these accessible from numpy name-space # but not imported in from numpy import * from __builtin__ import bool, int, long, float, complex, \ object, unicode, str - from core import round, abs, max, min + from .core import round, abs, max, min __all__.extend(['__version__', 'pkgload', 'PackageLoader', 'show_config']) diff --git a/numpy/_import_tools.py b/numpy/_import_tools.py index ecf29975b..b5939cd0a 100644 --- a/numpy/_import_tools.py +++ b/numpy/_import_tools.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index 9486bbc7f..a534e852c 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -8,7 +8,7 @@ NOTE: Many of the methods of ndarray have corresponding functions. core/fromnumeric.py, core/defmatrix.py up-to-date. """ -from __future__ import division +from __future__ import division, absolute_import from numpy.lib import add_newdoc @@ -5403,7 +5403,7 @@ add_newdoc('numpy.core', 'ufunc', ('reduce', :: r = op.identity # op = ufunc - for i in xrange(len(A)): + for i in range(len(A)): r = op(r, A[i]) return r @@ -5484,7 +5484,7 @@ add_newdoc('numpy.core', 'ufunc', ('accumulate', r = np.empty(len(A)) t = op.identity # op = the ufunc being applied to A's elements - for i in xrange(len(A)): + for i in range(len(A)): t = op(t, A[i]) r[i] = t return r @@ -5664,8 +5664,8 @@ add_newdoc('numpy.core', 'ufunc', ('outer', For `A` and `B` one-dimensional, this is equivalent to:: r = empty(len(A),len(B)) - for i in xrange(len(A)): - for j in xrange(len(B)): + for i in range(len(A)): + for j in range(len(B)): r[i,j] = op(A[i], B[j]) # op = ufunc in question Parameters diff --git a/numpy/build_utils/__init__.py b/numpy/build_utils/__init__.py index b06eaf1a4..52119d5cd 100644 --- a/numpy/build_utils/__init__.py +++ b/numpy/build_utils/__init__.py @@ -1 +1 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/build_utils/common.py b/numpy/build_utils/common.py index eba509084..50d2f59bc 100644 --- a/numpy/build_utils/common.py +++ b/numpy/build_utils/common.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys import copy diff --git a/numpy/build_utils/waf.py b/numpy/build_utils/waf.py index ee28c0ee6..09f1943ea 100644 --- a/numpy/build_utils/waf.py +++ b/numpy/build_utils/waf.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import re @@ -7,7 +7,7 @@ import waflib.Configure import waflib.Tools.c_config from waflib import Logs, Utils -from common \ +from .common \ import \ LONG_DOUBLE_REPRESENTATION_SRC, pyod, \ long_double_representation diff --git a/numpy/compat/__init__.py b/numpy/compat/__init__.py index 930be5a90..bb40fdbe9 100644 --- a/numpy/compat/__init__.py +++ b/numpy/compat/__init__.py @@ -8,12 +8,12 @@ extensions, which may be included for the following reasons: * we may only need a small subset of the copied library/module """ -from __future__ import division +from __future__ import division, absolute_import -import _inspect -import py3k -from _inspect import getargspec, formatargspec -from py3k import * +from . import _inspect +from . import py3k +from ._inspect import getargspec, formatargspec +from .py3k import * __all__ = [] __all__.extend(_inspect.__all__) diff --git a/numpy/compat/_inspect.py b/numpy/compat/_inspect.py index cb9717ced..902d609a9 100644 --- a/numpy/compat/_inspect.py +++ b/numpy/compat/_inspect.py @@ -5,7 +5,7 @@ significanly contributes to numpy import times. Importing this copy has almost no overhead. """ -from __future__ import division +from __future__ import division, absolute_import import types diff --git a/numpy/compat/py3k.py b/numpy/compat/py3k.py index 594acc1e0..7d853d84b 100644 --- a/numpy/compat/py3k.py +++ b/numpy/compat/py3k.py @@ -2,7 +2,7 @@ Python 3 compatibility tools. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar', 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested', diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index 011e356b2..f055d289e 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -1,36 +1,36 @@ -from __future__ import division +from __future__ import division, absolute_import -from info import __doc__ +from .info import __doc__ from numpy.version import version as __version__ -import multiarray -import umath -import _internal # for freeze programs -import numerictypes as nt +from . import multiarray +from . import umath +from . import _internal # for freeze programs +from . import numerictypes as nt multiarray.set_typeDict(nt.sctypeDict) -import numeric -from numeric import * -import fromnumeric -from fromnumeric import * -import defchararray as char -import records as rec -from records import * -from memmap import * -from defchararray import chararray -import scalarmath -import function_base -from function_base import * -import machar -from machar import * -import getlimits -from getlimits import * -import shape_base -from shape_base import * +from . import numeric +from .numeric import * +from . import fromnumeric +from .fromnumeric import * +from . import defchararray as char +from . import records as rec +from .records import * +from .memmap import * +from .defchararray import chararray +from . import scalarmath +from . import function_base +from .function_base import * +from . import machar +from .machar import * +from . import getlimits +from .getlimits import * +from . import shape_base +from .shape_base import * del nt -from fromnumeric import amax as max, amin as min, \ +from .fromnumeric import amax as max, amin as min, \ round_ as round -from numeric import absolute as abs +from .numeric import absolute as abs __all__ = ['char','rec','memmap'] __all__ += numeric.__all__ diff --git a/numpy/core/_internal.py b/numpy/core/_internal.py index 7ba28f993..ae7a81ca8 100644 --- a/numpy/core/_internal.py +++ b/numpy/core/_internal.py @@ -4,7 +4,7 @@ A place for code to be called from core C-code. Some things are more easily handled Python. """ -from __future__ import division +from __future__ import division, absolute_import import re import sys @@ -18,7 +18,7 @@ else: _nbo = asbytes('>') def _makenames_list(adict, align): - from multiarray import dtype + from .multiarray import dtype allfields = [] fnames = adict.keys() for fname in fnames: @@ -52,7 +52,7 @@ def _makenames_list(adict, align): # a dictionary without "names" and "formats" # fields is used as a data-type descriptor. def _usefields(adict, align): - from multiarray import dtype + from .multiarray import dtype try: names = adict[-1] except KeyError: @@ -130,7 +130,7 @@ def _array_descr(descriptor): # so don't remove the name here, or you'll # break backward compatibilty. def _reconstruct(subtype, shape, dtype): - from multiarray import ndarray + from .multiarray import ndarray return ndarray.__new__(subtype, shape, dtype) @@ -194,7 +194,7 @@ def _commastring(astr): return result def _getintp_ctype(): - from multiarray import dtype + from .multiarray import dtype val = _getintp_ctype.cache if val is not None: return val @@ -290,7 +290,7 @@ def _newnames(datatype, order): # Given an array with fields and a sequence of field names # construct a new array with just those fields copied over def _index_fields(ary, fields): - from multiarray import empty, dtype, array + from .multiarray import empty, dtype, array dt = ary.dtype names = [name for name in fields if name in dt.names] @@ -414,7 +414,7 @@ def _dtype_from_pep3118(spec, byteorder='@', is_subdtype=False): itemsize = 1 if spec[0].isdigit(): j = 1 - for j in xrange(1, len(spec)): + for j in range(1, len(spec)): if not spec[j].isdigit(): break itemsize = int(spec[:j]) diff --git a/numpy/core/_methods.py b/numpy/core/_methods.py index a7f9ccd44..358d35ef1 100644 --- a/numpy/core/_methods.py +++ b/numpy/core/_methods.py @@ -3,7 +3,7 @@ Array methods which are called by the both the C-code for the method and the Python code for the NumPy-namespace function """ -from __future__ import division +from __future__ import division, absolute_import from numpy.core import multiarray as mu from numpy.core import umath as um @@ -35,7 +35,7 @@ def _all(a, axis=None, dtype=None, out=None, keepdims=False): def _count_reduce_items(arr, axis): if axis is None: - axis = tuple(xrange(arr.ndim)) + axis = tuple(range(arr.ndim)) if not isinstance(axis, tuple): axis = (axis,) items = 1 diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 17eeef0b3..6e53dca00 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -3,7 +3,7 @@ $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ["array2string", "set_printoptions", "get_printoptions"] __docformat__ = 'restructuredtext' @@ -16,10 +16,10 @@ __docformat__ = 'restructuredtext' # and by Travis Oliphant 2005-8-22 for numpy import sys -import numerictypes as _nt -from umath import maximum, minimum, absolute, not_equal, isnan, isinf -from multiarray import format_longfloat, datetime_as_string, datetime_data -from fromnumeric import ravel +from . import numerictypes as _nt +from .umath import maximum, minimum, absolute, not_equal, isnan, isinf +from .multiarray import format_longfloat, datetime_as_string, datetime_data +from .fromnumeric import ravel def product(x, y): return x*y @@ -197,7 +197,7 @@ def get_printoptions(): return d def _leading_trailing(a): - import numeric as _nc + from . import numeric as _nc if a.ndim == 1: if len(a) > 2*_summaryEdgeItems: b = _nc.concatenate((a[:_summaryEdgeItems], @@ -324,7 +324,7 @@ def _array2string(a, max_line_width, precision, suppress_small, separator=' ', return lst def _convert_arrays(obj): - import numeric as _nc + from . import numeric as _nc newtup = [] for k in obj: if isinstance(k, _nc.ndarray): @@ -481,14 +481,14 @@ def _formatArray(a, format_function, rank, max_line_len, if rank == 1: s = "" line = next_line_prefix - for i in xrange(leading_items): + for i in range(leading_items): word = format_function(a[i]) + separator s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) if summary_insert1: s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix) - for i in xrange(trailing_items, 1, -1): + for i in range(trailing_items, 1, -1): word = format_function(a[-i]) + separator s, line = _extendLine(s, line, word, max_line_len, next_line_prefix) @@ -499,7 +499,7 @@ def _formatArray(a, format_function, rank, max_line_len, else: s = '[' sep = separator.rstrip() - for i in xrange(leading_items): + for i in range(leading_items): if i > 0: s += next_line_prefix s += _formatArray(a[i], format_function, rank-1, max_line_len, @@ -510,7 +510,7 @@ def _formatArray(a, format_function, rank, max_line_len, if summary_insert1: s += next_line_prefix + summary_insert1 + "\n" - for i in xrange(trailing_items, 1, -1): + for i in range(trailing_items, 1, -1): if leading_items or i != trailing_items: s += next_line_prefix s += _formatArray(a[-i], format_function, rank-1, max_line_len, @@ -540,7 +540,7 @@ class FloatFormat(object): pass def fillFormat(self, data): - import numeric as _nc + from . import numeric as _nc errstate = _nc.seterr(all='ignore') try: special = isnan(data) | isinf(data) @@ -593,7 +593,7 @@ class FloatFormat(object): self.format = format def __call__(self, x, strip_zeros=True): - import numeric as _nc + from . import numeric as _nc err = _nc.seterr(invalid='ignore') try: if isnan(x): diff --git a/numpy/core/bscript b/numpy/core/bscript index 3d9b84018..3a2bb2340 100644 --- a/numpy/core/bscript +++ b/numpy/core/bscript @@ -31,6 +31,7 @@ from setup_common \ MANDATORY_FUNCS, C_ABI_VERSION, C_API_VERSION ENABLE_SEPARATE_COMPILATION = (os.environ.get('NPY_SEPARATE_COMPILATION', "1") != "0") +NPY_RELAXED_STRIDES_CHECKING = (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', "0") != "0") NUMPYCONFIG_SYM = [] @@ -39,6 +40,12 @@ if ENABLE_SEPARATE_COMPILATION: NUMPYCONFIG_SYM.append(('DEFINE_NPY_ENABLE_SEPARATE_COMPILATION', '#define NPY_ENABLE_SEPARATE_COMPILATION 1')) else: NUMPYCONFIG_SYM.append(('DEFINE_NPY_ENABLE_SEPARATE_COMPILATION', '')) + +if NPY_RELAXED_STRIDES_CHECKING: + NUMPYCONFIG_SYM.append(('DEFINE_NPY_RELAXED_STRIDES_CHECKING', '#define NPY_RELAXED_STRIDES_CHECKING 1')) +else: + NUMPYCONFIG_SYM.append(('DEFINE_NPY_RELAXED_STRIDES_CHECKING', '')) + NUMPYCONFIG_SYM.append(('VISIBILITY_HIDDEN', '__attribute__((visibility("hidden")))')) NUMPYCONFIG_SYM.append(('NPY_ABI_VERSION', '0x%.8X' % C_ABI_VERSION)) diff --git a/numpy/core/code_generators/__init__.py b/numpy/core/code_generators/__init__.py index b06eaf1a4..52119d5cd 100644 --- a/numpy/core/code_generators/__init__.py +++ b/numpy/core/code_generators/__init__.py @@ -1 +1 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/core/code_generators/cversions.py b/numpy/core/code_generators/cversions.py index 161dae8d9..9f8a8fb34 100644 --- a/numpy/core/code_generators/cversions.py +++ b/numpy/core/code_generators/cversions.py @@ -3,12 +3,12 @@ The API has is defined by numpy_api_order and ufunc_api_order. """ -from __future__ import division +from __future__ import division, absolute_import from os.path import dirname -from genapi import fullapi_hash -import numpy_api +from .genapi import fullapi_hash +from . import numpy_api if __name__ == '__main__': diff --git a/numpy/core/code_generators/genapi.py b/numpy/core/code_generators/genapi.py index 164232e6e..3855d5a3d 100644 --- a/numpy/core/code_generators/genapi.py +++ b/numpy/core/code_generators/genapi.py @@ -6,7 +6,7 @@ See ``find_function`` for how functions should be formatted, and specified. """ -from __future__ import division +from __future__ import division, absolute_import import sys, os, re try: @@ -203,7 +203,7 @@ def find_functions(filename, tag='API'): function_name = None function_args = [] doclist = [] - SCANNING, STATE_DOC, STATE_RETTYPE, STATE_NAME, STATE_ARGS = range(5) + SCANNING, STATE_DOC, STATE_RETTYPE, STATE_NAME, STATE_ARGS = list(range(5)) state = SCANNING tagcomment = '/*' + tag for lineno, line in enumerate(fo): diff --git a/numpy/core/code_generators/numpy_api.py b/numpy/core/code_generators/numpy_api.py index 4a9c747ea..35c8ab496 100644 --- a/numpy/core/code_generators/numpy_api.py +++ b/numpy/core/code_generators/numpy_api.py @@ -12,7 +12,7 @@ When adding a function, make sure to use the next integer not used as an index exception, so it should hopefully not get unnoticed). """ -from __future__ import division +from __future__ import division, absolute_import multiarray_global_vars = { 'NPY_NUMUSERTYPES': 7, diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index 1ef8e997c..b990e81ea 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -9,7 +9,7 @@ for the ufuncs in numpy.core at the C level when the ufuncs are created at compile time. """ -from __future__ import division +from __future__ import division, absolute_import docdict = {} diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index c85d95c49..3f0a730ad 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -15,12 +15,12 @@ available in your version of Python. The preferred alias for `defchararray` is `numpy.char`. """ -from __future__ import division +from __future__ import division, absolute_import import sys -from numerictypes import string_, unicode_, integer, object_, bool_, character -from numeric import ndarray, compare_chararrays -from numeric import array as narray +from .numerictypes import string_, unicode_, integer, object_, bool_, character +from .numeric import ndarray, compare_chararrays +from .numeric import array as narray from numpy.core.multiarray import _vec_string from numpy.compat import asbytes import numpy diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index da1048134..e7211cede 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -1,7 +1,7 @@ """Module containing non-deprecated functions borrowed from Numeric. """ -from __future__ import division +from __future__ import division, absolute_import __docformat__ = "restructuredtext en" @@ -16,11 +16,11 @@ __all__ = ['take', 'reshape', 'choose', 'repeat', 'put', 'amax', 'amin', ] -import multiarray as mu -import umath as um -import numerictypes as nt -from numeric import asarray, array, asanyarray, concatenate -import _methods +from . import multiarray as mu +from . import umath as um +from . import numerictypes as nt +from .numeric import asarray, array, asanyarray, concatenate +from . import _methods _dt_ = nt.sctype2char import types diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index fa6732077..4a757b931 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -1,9 +1,9 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['logspace', 'linspace'] -import numeric as _nx -from numeric import array +from . import numeric as _nx +from .numeric import array def linspace(start, stop, num=50, endpoint=True, retstep=False): """ diff --git a/numpy/core/getlimits.py b/numpy/core/getlimits.py index 7b94346c7..606038677 100644 --- a/numpy/core/getlimits.py +++ b/numpy/core/getlimits.py @@ -1,14 +1,14 @@ """Machine limits for Float32 and Float64 and (long double) if available... """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['finfo','iinfo'] -from machar import MachAr -import numeric -import numerictypes as ntypes -from numeric import array +from .machar import MachAr +from . import numeric +from . import numerictypes as ntypes +from .numeric import array def _frz(a): """fix rank-0 --> rank-1""" diff --git a/numpy/core/include/numpy/ndarraytypes.h b/numpy/core/include/numpy/ndarraytypes.h index 05bac8a1f..7cc37bff8 100644 --- a/numpy/core/include/numpy/ndarraytypes.h +++ b/numpy/core/include/numpy/ndarraytypes.h @@ -753,9 +753,15 @@ typedef int (PyArray_FinalizeFunc)(PyArrayObject *, PyObject *); #define NPY_ARRAY_F_CONTIGUOUS 0x0002 /* - * Note: all 0-d arrays are C_CONTIGUOUS and F_CONTIGUOUS. An N-d - * array that is C_CONTIGUOUS is also F_CONTIGUOUS if only - * one axis has a dimension different from one (ie. a 1x3x1 array). + * Note: all 0-d arrays are C_CONTIGUOUS and F_CONTIGUOUS. If a + * 1-d array is C_CONTIGUOUS it is also F_CONTIGUOUS. Arrays with + * more then one dimension can be C_CONTIGUOUS and F_CONTIGUOUS + * at the same time if they have either zero or one element. + * If NPY_RELAXED_STRIDES_CHECKING is set, a higher dimensional + * array is always C_CONTIGUOUS and F_CONTIGUOUS if it has zero elements + * and the array is contiguous if ndarray.squeeze() is contiguous. + * I.e. dimensions for which `ndarray.shape[dimension] == 1` are + * ignored. */ /* diff --git a/numpy/core/info.py b/numpy/core/info.py index f56b2d395..7152e4aca 100644 --- a/numpy/core/info.py +++ b/numpy/core/info.py @@ -81,7 +81,7 @@ More Functions: arccosh arcsinh arctanh """ -from __future__ import division +from __future__ import division, absolute_import depends = ['testing'] global_symbols = ['*'] diff --git a/numpy/core/machar.py b/numpy/core/machar.py index b7e64290e..1053570f8 100644 --- a/numpy/core/machar.py +++ b/numpy/core/machar.py @@ -5,7 +5,7 @@ floating-point arithmetic system Author: Pearu Peterson, September 2003 """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['MachAr'] @@ -123,7 +123,7 @@ class MachAr(object): # Do we really need to do this? Aren't they 2 and 2.0? # Determine ibeta and beta a = one - for _ in xrange(max_iterN): + for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a @@ -132,7 +132,7 @@ class MachAr(object): else: raise RuntimeError(msg % (_, one.dtype)) b = one - for _ in xrange(max_iterN): + for _ in range(max_iterN): b = b + b temp = a + b itemp = int_conv(temp-a) @@ -146,7 +146,7 @@ class MachAr(object): # Determine it and irnd it = -1 b = one - for _ in xrange(max_iterN): + for _ in range(max_iterN): it = it + 1 b = b * beta temp = b + one @@ -158,7 +158,7 @@ class MachAr(object): betah = beta / two a = one - for _ in xrange(max_iterN): + for _ in range(max_iterN): a = a + a temp = a + one temp1 = temp - a @@ -182,7 +182,7 @@ class MachAr(object): for i in range(negep): a = a * betain b = a - for _ in xrange(max_iterN): + for _ in range(max_iterN): temp = one - a if any(temp-one != zero): break @@ -201,7 +201,7 @@ class MachAr(object): machep = - it - 3 a = b - for _ in xrange(max_iterN): + for _ in range(max_iterN): temp = one + a if any(temp-one != zero): break @@ -223,7 +223,7 @@ class MachAr(object): z = betain t = one + eps nxres = 0 - for _ in xrange(max_iterN): + for _ in range(max_iterN): y = z z = y*y a = z*one # Check here for underflow @@ -249,7 +249,7 @@ class MachAr(object): mx = iz + iz - 1 # Determine minexp and xmin - for _ in xrange(max_iterN): + for _ in range(max_iterN): xmin = y y = y * betain a = y * one diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index 5107e9b28..528951537 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -1,9 +1,9 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['memmap'] import warnings -from numeric import uint8, ndarray, dtype +from .numeric import uint8, ndarray, dtype import sys import numpy as np diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index a114e4bb5..25f977254 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 'arange', 'array', 'zeros', 'count_nonzero', @@ -26,11 +26,11 @@ __all__ = ['newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', import sys import warnings -import multiarray -import umath -from umath import * -import numerictypes -from numerictypes import * +from . import multiarray +from . import umath +from .umath import * +from . import numerictypes +from .numerictypes import * import collections @@ -911,7 +911,7 @@ def outer(a,b): try: # importing this changes the dot function for basic 4 types # to blas-optimized versions. - from _dotblas import dot, vdot, inner, alterdot, restoredot + from ._dotblas import dot, vdot, inner, alterdot, restoredot except ImportError: # docstrings are in add_newdocs.py inner = multiarray.inner @@ -1040,8 +1040,8 @@ def tensordot(a, b, axes=2): try: iter(axes) except: - axes_a = range(-axes,0) - axes_b = range(0,axes) + axes_a = list(range(-axes,0)) + axes_b = list(range(0,axes)) else: axes_a, axes_b = axes try: @@ -1065,7 +1065,7 @@ def tensordot(a, b, axes=2): equal = True if (na != nb): equal = False else: - for k in xrange(na): + for k in range(na): if as_[axes_a[k]] != bs[axes_b[k]]: equal = False break @@ -1153,15 +1153,19 @@ def roll(a, shift, axis=None): n = a.size reshape = True else: - n = a.shape[axis] + try: + n = a.shape[axis] + except IndexError: + raise ValueError('axis must be >= 0 and < %d' % a.ndim) reshape = False + if n == 0: + return a shift %= n - indexes = concatenate((arange(n-shift,n),arange(n-shift))) + indexes = concatenate((arange(n - shift, n), arange(n - shift))) res = a.take(indexes, axis) if reshape: - return res.reshape(a.shape) - else: - return res + res = res.reshape(a.shape) + return res def rollaxis(a, axis, start=0): """ @@ -1213,7 +1217,7 @@ def rollaxis(a, axis, start=0): start -= 1 if axis==start: return a - axes = range(0,n) + axes = list(range(0,n)) axes.remove(axis) axes.insert(start, axis) return a.transpose(axes) @@ -1364,7 +1368,7 @@ def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None): #Use numarray's printing function -from arrayprint import array2string, get_printoptions, set_printoptions +from .arrayprint import array2string, get_printoptions, set_printoptions _typelessdata = [int_, float_, complex_] if issubclass(intc, int): @@ -2591,6 +2595,6 @@ nan = NaN = NAN False_ = bool_(False) True_ = bool_(True) -import fromnumeric -from fromnumeric import * +from . import fromnumeric +from .fromnumeric import * extend_all(fromnumeric) diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index b069b5426..a1af9d80d 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -80,7 +80,7 @@ Exported symbols include: \\-> object_ (not used much) (kind=O) """ -from __future__ import division +from __future__ import division, absolute_import # we add more at the bottom __all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes', @@ -112,7 +112,7 @@ if sys.version_info[0] >= 3: # "import string" is costly to import! # Construct the translation tables directly # "A" = chr(65), "a" = chr(97) -_all_chars = map(chr, range(256)) +_all_chars = map(chr, list(range(256))) _ascii_upper = _all_chars[65:65+26] _ascii_lower = _all_chars[97:97+26] LOWER_TABLE="".join(_all_chars[:65] + _ascii_lower + _all_chars[65+26:]) diff --git a/numpy/core/records.py b/numpy/core/records.py index ff5d98d3a..385f9866d 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -34,14 +34,14 @@ Record arrays allow us to access fields as properties:: array([ 2., 2.]) """ -from __future__ import division +from __future__ import division, absolute_import # All of the functions allow formats to be a dtype __all__ = ['record', 'recarray', 'format_parser'] -import numeric as sb -from defchararray import chararray -import numerictypes as nt +from . import numeric as sb +from .defchararray import chararray +from . import numerictypes as nt import types import os import sys @@ -603,7 +603,7 @@ def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, nfields = len(recList[0]) if formats is None and dtype is None: # slower obj = sb.array(recList, dtype=object) - arrlist = [sb.array(obj[..., i].tolist()) for i in xrange(nfields)] + arrlist = [sb.array(obj[..., i].tolist()) for i in range(nfields)] return fromarrays(arrlist, formats=formats, shape=shape, names=names, titles=titles, aligned=aligned, byteorder=byteorder) @@ -622,7 +622,7 @@ def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, if len(shape) > 1: raise ValueError("Can only deal with 1-d array.") _array = recarray(shape, descr) - for k in xrange(_array.size): + for k in range(_array.size): _array[k] = tuple(recList[k]) return _array else: diff --git a/numpy/core/setup.py b/numpy/core/setup.py index 37f649e6b..c65012126 100644 --- a/numpy/core/setup.py +++ b/numpy/core/setup.py @@ -15,6 +15,9 @@ from setup_common import * # Set to True to enable multiple file compilations (experimental) ENABLE_SEPARATE_COMPILATION = (os.environ.get('NPY_SEPARATE_COMPILATION', "1") != "0") +# Set to True to enable relaxed strides checking. This (mostly) means +# that `strides[dim]` is ignored if `shape[dim] == 1` when setting flags. +NPY_RELAXED_STRIDES_CHECKING = (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', "0") != "0") # XXX: ugly, we use a class to avoid calling twice some expensive functions in # config.h/numpyconfig.h. I don't see a better way because distutils force @@ -435,6 +438,9 @@ def configuration(parent_package='',top_path=None): if ENABLE_SEPARATE_COMPILATION: moredefs.append(('ENABLE_SEPARATE_COMPILATION', 1)) + if NPY_RELAXED_STRIDES_CHECKING: + moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1)) + # Get long double representation if sys.platform != 'darwin': rep = check_long_double_representation(config_cmd) @@ -532,6 +538,9 @@ def configuration(parent_package='',top_path=None): if ENABLE_SEPARATE_COMPILATION: moredefs.append(('NPY_ENABLE_SEPARATE_COMPILATION', 1)) + if NPY_RELAXED_STRIDES_CHECKING: + moredefs.append(('NPY_RELAXED_STRIDES_CHECKING', 1)) + # Check wether we can use inttypes (C99) formats if config_cmd.check_decl('PRIdPTR', headers = ['inttypes.h']): moredefs.append(('NPY_USE_C99_FORMATS', 1)) diff --git a/numpy/core/setup_common.py b/numpy/core/setup_common.py index 8c4a22a44..53f3b76e1 100644 --- a/numpy/core/setup_common.py +++ b/numpy/core/setup_common.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import # Code common to build tools import sys diff --git a/numpy/core/shape_base.py b/numpy/core/shape_base.py index 4d5439249..d7e86f64e 100644 --- a/numpy/core/shape_base.py +++ b/numpy/core/shape_base.py @@ -1,9 +1,9 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack'] -import numeric as _nx -from numeric import array, asanyarray, newaxis +from . import numeric as _nx +from .numeric import array, asanyarray, newaxis def atleast_1d(*arys): """ diff --git a/numpy/core/src/multiarray/common.c b/numpy/core/src/multiarray/common.c index f27de491f..f0a6a761c 100644 --- a/numpy/core/src/multiarray/common.c +++ b/numpy/core/src/multiarray/common.c @@ -628,8 +628,20 @@ _IsAligned(PyArrayObject *ap) } ptr = (npy_intp) PyArray_DATA(ap); aligned = (ptr % alignment) == 0; + for (i = 0; i < PyArray_NDIM(ap); i++) { +#if NPY_RELAXED_STRIDES_CHECKING + if (PyArray_DIM(ap, i) > 1) { + /* if shape[i] == 1, the stride is never used */ + aligned &= ((PyArray_STRIDES(ap)[i] % alignment) == 0); + } + else if (PyArray_DIM(ap, i) == 0) { + /* an array with zero elements is always aligned */ + return 1; + } +#else /* not NPY_RELAXED_STRIDES_CHECKING */ aligned &= ((PyArray_STRIDES(ap)[i] % alignment) == 0); +#endif /* not NPY_RELAXED_STRIDES_CHECKING */ } return aligned != 0; } diff --git a/numpy/core/src/multiarray/ctors.c b/numpy/core/src/multiarray/ctors.c index bdf2e6e2b..f366a34b1 100644 --- a/numpy/core/src/multiarray/ctors.c +++ b/numpy/core/src/multiarray/ctors.c @@ -3560,6 +3560,7 @@ _array_fill_strides(npy_intp *strides, npy_intp *dims, int nd, size_t itemsize, int inflag, int *objflags) { int i; +#if NPY_RELAXED_STRIDES_CHECKING npy_bool not_cf_contig = 0; npy_bool nod = 0; /* A dim != 1 was found */ @@ -3573,6 +3574,7 @@ _array_fill_strides(npy_intp *strides, npy_intp *dims, int nd, size_t itemsize, nod = 1; } } +#endif /* NPY_RELAXED_STRIDES_CHECKING */ /* Only make Fortran strides if not contiguous as well */ if ((inflag & (NPY_ARRAY_F_CONTIGUOUS|NPY_ARRAY_C_CONTIGUOUS)) == @@ -3582,11 +3584,21 @@ _array_fill_strides(npy_intp *strides, npy_intp *dims, int nd, size_t itemsize, if (dims[i]) { itemsize *= dims[i]; } +#if NPY_RELAXED_STRIDES_CHECKING else { not_cf_contig = 0; } + if (dims[i] == 1) { + /* For testing purpose only */ + strides[i] = NPY_MAX_INTP; + } +#endif /* NPY_RELAXED_STRIDES_CHECKING */ } +#if NPY_RELAXED_STRIDES_CHECKING if (not_cf_contig) { +#else /* not NPY_RELAXED_STRIDES_CHECKING */ + if ((nd > 1) && ((strides[0] != strides[nd-1]) || (dims[nd-1] > 1))) { +#endif /* not NPY_RELAXED_STRIDES_CHECKING */ *objflags = ((*objflags)|NPY_ARRAY_F_CONTIGUOUS) & ~NPY_ARRAY_C_CONTIGUOUS; } @@ -3600,11 +3612,21 @@ _array_fill_strides(npy_intp *strides, npy_intp *dims, int nd, size_t itemsize, if (dims[i]) { itemsize *= dims[i]; } +#if NPY_RELAXED_STRIDES_CHECKING else { not_cf_contig = 0; } + if (dims[i] == 1) { + /* For testing purpose only */ + strides[i] = NPY_MAX_INTP; + } +#endif /* NPY_RELAXED_STRIDES_CHECKING */ } +#if NPY_RELAXED_STRIDES_CHECKING if (not_cf_contig) { +#else /* not NPY_RELAXED_STRIDES_CHECKING */ + if ((nd > 1) && ((strides[0] != strides[nd-1]) || (dims[0] > 1))) { +#endif /* not NPY_RELAXED_STRIDES_CHECKING */ *objflags = ((*objflags)|NPY_ARRAY_C_CONTIGUOUS) & ~NPY_ARRAY_F_CONTIGUOUS; } diff --git a/numpy/core/src/multiarray/flagsobject.c b/numpy/core/src/multiarray/flagsobject.c index ef04bdb20..0ad5c908a 100644 --- a/numpy/core/src/multiarray/flagsobject.c +++ b/numpy/core/src/multiarray/flagsobject.c @@ -90,8 +90,33 @@ PyArray_UpdateFlags(PyArrayObject *ret, int flagmask) * Check whether the given array is stored contiguously * in memory. And update the passed in ap flags apropriately. * - * A dimension == 1 stride is ignored for contiguous flags and a 0-sized array - * is always both C- and F-Contiguous. 0-strided arrays are not contiguous. + * The traditional rule is that for an array to be flagged as C contiguous, + * the following must hold: + * + * strides[-1] == itemsize + * strides[i] == shape[i+1] * strides[i + 1] + * + * And for an array to be flagged as F contiguous, the obvious reversal: + * + * strides[0] == itemsize + * strides[i] == shape[i - 1] * strides[i - 1] + * + * According to these rules, a 0- or 1-dimensional array is either both + * C- and F-contiguous, or neither; and an array with 2+ dimensions + * can be C- or F- contiguous, or neither, but not both. Though there + * there are exceptions for arrays with zero or one item, in the first + * case the check is relaxed up to and including the first dimension + * with shape[i] == 0. In the second case `strides == itemsize` will + * can be true for all dimensions and both flags are set. + * + * When NPY_RELAXED_STRIDES_CHECKING is set, we use a more accurate + * definition of C- and F-contiguity, in which all 0-sized arrays are + * contiguous (regardless of dimensionality), and if shape[i] == 1 + * then we ignore strides[i] (since it has no affect on memory layout). + * With these new rules, it is possible for e.g. a 10x1 array to be both + * C- and F-contiguous -- but, they break downstream code which assumes + * that for contiguous arrays strides[-1] (resp. strides[0]) always + * contains the itemsize. */ static void _UpdateContiguousFlags(PyArrayObject *ap) @@ -101,9 +126,10 @@ _UpdateContiguousFlags(PyArrayObject *ap) int i; npy_bool is_c_contig = 1; - sd = PyArray_DESCR(ap)->elsize; + sd = PyArray_ITEMSIZE(ap); for (i = PyArray_NDIM(ap) - 1; i >= 0; --i) { dim = PyArray_DIMS(ap)[i]; +#if NPY_RELAXED_STRIDES_CHECKING /* contiguous by definition */ if (dim == 0) { PyArray_ENABLEFLAGS(ap, NPY_ARRAY_C_CONTIGUOUS); @@ -116,6 +142,17 @@ _UpdateContiguousFlags(PyArrayObject *ap) } sd *= dim; } +#else /* not NPY_RELAXED_STRIDES_CHECKING */ + if (PyArray_STRIDES(ap)[i] != sd) { + is_c_contig = 0; + break; + } + /* contiguous, if it got this far */ + if (dim == 0) { + break; + } + sd *= dim; +#endif /* not NPY_RELAXED_STRIDES_CHECKING */ } if (is_c_contig) { PyArray_ENABLEFLAGS(ap, NPY_ARRAY_C_CONTIGUOUS); @@ -125,9 +162,10 @@ _UpdateContiguousFlags(PyArrayObject *ap) } /* check if fortran contiguous */ - sd = PyArray_DESCR(ap)->elsize; + sd = PyArray_ITEMSIZE(ap); for (i = 0; i < PyArray_NDIM(ap); ++i) { dim = PyArray_DIMS(ap)[i]; +#if NPY_RELAXED_STRIDES_CHECKING if (dim != 1) { if (PyArray_STRIDES(ap)[i] != sd) { PyArray_CLEARFLAGS(ap, NPY_ARRAY_F_CONTIGUOUS); @@ -135,6 +173,16 @@ _UpdateContiguousFlags(PyArrayObject *ap) } sd *= dim; } +#else /* not NPY_RELAXED_STRIDES_CHECKING */ + if (PyArray_STRIDES(ap)[i] != sd) { + PyArray_CLEARFLAGS(ap, NPY_ARRAY_F_CONTIGUOUS); + return; + } + if (dim == 0) { + break; + } + sd *= dim; +#endif /* not NPY_RELAXED_STRIDES_CHECKING */ } PyArray_ENABLEFLAGS(ap, NPY_ARRAY_F_CONTIGUOUS); return; diff --git a/numpy/core/src/multiarray/multiarraymodule.c b/numpy/core/src/multiarray/multiarraymodule.c index f8ade57da..dd6d44003 100644 --- a/numpy/core/src/multiarray/multiarraymodule.c +++ b/numpy/core/src/multiarray/multiarraymodule.c @@ -1510,20 +1510,31 @@ PyArray_EquivTypenums(int typenum1, int typenum2) } /*** END C-API FUNCTIONS **/ - +/* + * NPY_RELAXED_STRIDES_CHECKING: If the strides logic is changed, the + * order specific stride setting is not necessary. + */ static PyObject * -_prepend_ones(PyArrayObject *arr, int nd, int ndmin) +_prepend_ones(PyArrayObject *arr, int nd, int ndmin, NPY_ORDER order) { npy_intp newdims[NPY_MAXDIMS]; npy_intp newstrides[NPY_MAXDIMS]; + npy_intp newstride; int i, k, num; PyArrayObject *ret; PyArray_Descr *dtype; + if (order == NPY_FORTRANORDER || PyArray_ISFORTRAN(arr) || PyArray_NDIM(arr) == 0) { + newstride = PyArray_DESCR(arr)->elsize; + } + else { + newstride = PyArray_STRIDES(arr)[0] * PyArray_DIMS(arr)[0]; + } + num = ndmin - nd; for (i = 0; i < num; i++) { newdims[i] = 1; - newstrides[i] = PyArray_DESCR(arr)->elsize; + newstrides[i] = newstride; } for (i = num; i < ndmin; i++) { k = i - num; @@ -1664,7 +1675,7 @@ _array_fromobject(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kws) * create a new array from the same data with ones in the shape * steals a reference to ret */ - return _prepend_ones(ret, nd, ndmin); + return _prepend_ones(ret, nd, ndmin, order); clean_type: Py_XDECREF(type); diff --git a/numpy/core/src/multiarray/nditer_api.c b/numpy/core/src/multiarray/nditer_api.c index 09e572f10..40043648d 100644 --- a/numpy/core/src/multiarray/nditer_api.c +++ b/numpy/core/src/multiarray/nditer_api.c @@ -134,12 +134,10 @@ NpyIter_RemoveAxis(NpyIter *iter, int axis) axisdata = NIT_INDEX_AXISDATA(axisdata_del, 1); memmove(axisdata_del, axisdata, (ndim-1-xdim)*sizeof_axisdata); - /* If there is more than one dimension, shrink the iterator */ - if (ndim > 1) { - NIT_NDIM(iter) = ndim-1; - } - /* Otherwise convert it to a singleton dimension */ - else { + /* Shrink the iterator */ + NIT_NDIM(iter) = ndim - 1; + /* If it is now 0-d fill the singleton dimension */ + if (ndim == 1) { npy_intp *strides = NAD_STRIDES(axisdata_del); NAD_SHAPE(axisdata_del) = 1; for (iop = 0; iop < nop; ++iop) { @@ -642,6 +640,9 @@ NpyIter_GetIterIndex(NpyIter *iter) npy_intp sizeof_axisdata; iterindex = 0; + if (ndim == 0) { + return 0; + } sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); axisdata = NIT_INDEX_AXISDATA(NIT_AXISDATA(iter), ndim-1); @@ -1750,6 +1751,8 @@ npyiter_goto_iterindex(NpyIter *iter, npy_intp iterindex) NIT_ITERINDEX(iter) = iterindex; + ndim = ndim ? ndim : 1; + if (iterindex == 0) { dataptr = NIT_RESETDATAPTR(iter); @@ -2062,8 +2065,9 @@ npyiter_copy_to_buffers(NpyIter *iter, char **prev_dataptrs) /* If last time around, the reduce loop structure was full, we reuse it */ if (reuse_reduce_loops) { - npy_intp full_transfersize; + npy_intp full_transfersize, prev_reduce_outersize; + prev_reduce_outersize = NBF_REDUCE_OUTERSIZE(bufferdata); reduce_outerstrides = NBF_REDUCE_OUTERSTRIDES(bufferdata); reduce_outerptrs = NBF_REDUCE_OUTERPTRS(bufferdata); reduce_outerdim = NBF_REDUCE_OUTERDIM(bufferdata); @@ -2086,6 +2090,13 @@ npyiter_copy_to_buffers(NpyIter *iter, char **prev_dataptrs) else { transfersize = full_transfersize; } + if (prev_reduce_outersize < NBF_REDUCE_OUTERSIZE(bufferdata)) { + /* + * If the previous time around less data was copied it may not + * be safe to reuse the buffers even if the pointers match. + */ + reuse_reduce_loops = 0; + } NBF_BUFITEREND(bufferdata) = iterindex + reduce_innersize; NPY_IT_DBG_PRINT3("Reused reduce transfersize: %d innersize: %d " @@ -2184,6 +2195,11 @@ npyiter_copy_to_buffers(NpyIter *iter, char **prev_dataptrs) break; /* Just a copy */ case 0: + /* Do not reuse buffer if it did not exist */ + if (!(op_itflags[iop] & NPY_OP_ITFLAG_USINGBUFFER) && + (prev_dataptrs != NULL)) { + prev_dataptrs[iop] = NULL; + } /* * No copyswap or cast was requested, so all we're * doing is copying the data to fill the buffer and @@ -2227,6 +2243,11 @@ npyiter_copy_to_buffers(NpyIter *iter, char **prev_dataptrs) break; /* Just a copy, but with a reduction */ case NPY_OP_ITFLAG_REDUCE: + /* Do not reuse buffer if it did not exist */ + if (!(op_itflags[iop] & NPY_OP_ITFLAG_USINGBUFFER) && + (prev_dataptrs != NULL)) { + prev_dataptrs[iop] = NULL; + } if (ad_strides[iop] == 0) { strides[iop] = 0; /* It's all in one stride in the inner loop dimension */ @@ -2615,6 +2636,7 @@ npyiter_checkreducesize(NpyIter *iter, npy_intp count, */ if (count <= reducespace) { *reduce_innersize = count; + NIT_ITFLAGS(iter) |= NPY_ITFLAG_REUSE_REDUCE_LOOPS; return count; } else if (nonzerocoord) { @@ -2622,6 +2644,8 @@ npyiter_checkreducesize(NpyIter *iter, npy_intp count, count = reducespace; } *reduce_innersize = count; + /* NOTE: This is similar to the (coord != 0) case below. */ + NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_REUSE_REDUCE_LOOPS; return count; } else { @@ -2661,8 +2685,20 @@ npyiter_checkreducesize(NpyIter *iter, npy_intp count, return count; } - /* In this case, we can reuse the reduce loops */ - NIT_ITFLAGS(iter) |= NPY_ITFLAG_REUSE_REDUCE_LOOPS; + coord = NAD_INDEX(axisdata); + if (coord != 0) { + /* + * In this case, it is only safe to reuse the buffer if the amount + * of data copied is not more then the current axes, as is the + * case when reuse_reduce_loops was active already. + * It should be in principle OK when the idim loop returns immidiatly. + */ + NIT_ITFLAGS(iter) &= ~NPY_ITFLAG_REUSE_REDUCE_LOOPS; + } + else { + /* In this case, we can reuse the reduce loops */ + NIT_ITFLAGS(iter) |= NPY_ITFLAG_REUSE_REDUCE_LOOPS; + } *reduce_innersize = reducespace; count /= reducespace; @@ -2687,7 +2723,6 @@ npyiter_checkreducesize(NpyIter *iter, npy_intp count, "the outer loop? %d\n", iop, (int)stride0op[iop]); } shape = NAD_SHAPE(axisdata); - coord = NAD_INDEX(axisdata); reducespace += (shape-coord-1) * factor; factor *= shape; NIT_ADVANCE_AXISDATA(axisdata, 1); diff --git a/numpy/core/src/multiarray/nditer_constr.c b/numpy/core/src/multiarray/nditer_constr.c index cfbaea321..a40cbc7bc 100644 --- a/numpy/core/src/multiarray/nditer_constr.c +++ b/numpy/core/src/multiarray/nditer_constr.c @@ -54,8 +54,7 @@ static int npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itflags, char **op_dataptr, npy_uint32 *op_flags, int **op_axes, - npy_intp *itershape, - int output_scalars); + npy_intp *itershape); static void npyiter_replace_axisdata(NpyIter *iter, int iop, PyArrayObject *op, @@ -75,7 +74,7 @@ static PyArray_Descr * npyiter_get_common_dtype(int nop, PyArrayObject **op, npyiter_opitflags *op_itflags, PyArray_Descr **op_dtype, PyArray_Descr **op_request_dtypes, - int only_inputs, int output_scalars); + int only_inputs); static PyArrayObject * npyiter_new_temp_array(NpyIter *iter, PyTypeObject *subtype, npy_uint32 flags, npyiter_opitflags *op_itflags, @@ -86,7 +85,7 @@ npyiter_allocate_arrays(NpyIter *iter, npy_uint32 flags, PyArray_Descr **op_dtype, PyTypeObject *subtype, npy_uint32 *op_flags, npyiter_opitflags *op_itflags, - int **op_axes, int output_scalars); + int **op_axes); static void npyiter_get_priority_subtype(int nop, PyArrayObject **op, npyiter_opitflags *op_itflags, @@ -122,8 +121,7 @@ NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, npy_int8 *perm; NpyIter_BufferData *bufferdata = NULL; - int any_allocate = 0, any_missing_dtypes = 0, - output_scalars = 0, need_subtype = 0; + int any_allocate = 0, any_missing_dtypes = 0, need_subtype = 0; /* The subtype for automatically allocated outputs */ double subtype_priority = NPY_PRIORITY; @@ -158,6 +156,22 @@ NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, return NULL; } + /* + * Before 1.8, if `oa_ndim == 0`, this meant `op_axes != NULL` was an error. + * With 1.8, `oa_ndim == -1` takes this role, while op_axes in that case + * enforces a 0-d iterator. Using `oa_ndim == 0` with `op_axes == NULL` + * is thus deprecated with version 1.8. + */ + if ((oa_ndim == 0) && (op_axes == NULL)) { + char* mesg = "using `oa_ndim == 0` when `op_axes` is NULL is " + "deprecated. Use `oa_ndim == -1` or the MultiNew " + "iterator for NumPy <1.8 compatibility"; + if (DEPRECATE(mesg) < 0) { + return NULL; + } + oa_ndim = -1; + } + /* Error check 'oa_ndim' and 'op_axes', which must be used together */ if (!npyiter_check_op_axes(nop, oa_ndim, op_axes, itershape)) { return NULL; @@ -175,12 +189,6 @@ NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, /* Calculate how many dimensions the iterator should have */ ndim = npyiter_calculate_ndim(nop, op_in, oa_ndim); - /* If 'ndim' is zero, any outputs should be scalars */ - if (ndim == 0) { - output_scalars = 1; - ndim = 1; - } - NPY_IT_TIME_POINT(c_calculate_ndim); /* Allocate memory for the iterator */ @@ -231,8 +239,7 @@ NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, /* Fill in the AXISDATA arrays and set the ITERSIZE field */ if (!npyiter_fill_axisdata(iter, flags, op_itflags, op_dataptr, - op_flags, op_axes, itershape, - output_scalars)) { + op_flags, op_axes, itershape)) { NpyIter_Deallocate(iter); return NULL; } @@ -338,8 +345,7 @@ NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, dtype = npyiter_get_common_dtype(nop, op, op_itflags, op_dtype, op_request_dtypes, - only_inputs, - output_scalars); + only_inputs); if (dtype == NULL) { NpyIter_Deallocate(iter); return NULL; @@ -389,7 +395,7 @@ NpyIter_AdvancedNew(int nop, PyArrayObject **op_in, npy_uint32 flags, * done now using a memory layout matching the iterator. */ if (!npyiter_allocate_arrays(iter, flags, op_dtype, subtype, op_flags, - op_itflags, op_axes, output_scalars)) { + op_itflags, op_axes)) { NpyIter_Deallocate(iter); return NULL; } @@ -504,7 +510,7 @@ NpyIter_MultiNew(int nop, PyArrayObject **op_in, npy_uint32 flags, { return NpyIter_AdvancedNew(nop, op_in, flags, order, casting, op_flags, op_request_dtypes, - 0, NULL, NULL, 0); + -1, NULL, NULL, 0); } /*NUMPY_API @@ -521,7 +527,7 @@ NpyIter_New(PyArrayObject *op, npy_uint32 flags, return NpyIter_AdvancedNew(1, &op, flags, order, casting, &op_flags, &dtype, - 0, NULL, NULL, 0); + -1, NULL, NULL, 0); } /*NUMPY_API @@ -758,53 +764,60 @@ npyiter_check_op_axes(int nop, int oa_ndim, int **op_axes, char axes_dupcheck[NPY_MAXDIMS]; int iop, idim; - if (oa_ndim == 0 && (op_axes != NULL || itershape != NULL)) { - PyErr_Format(PyExc_ValueError, - "If 'op_axes' or 'itershape' is not NULL in the" - "iterator constructor, 'oa_ndim' must be greater than zero"); - return 0; - } - else if (oa_ndim > 0) { - if (oa_ndim > NPY_MAXDIMS) { + if (oa_ndim < 0) { + /* + * If `oa_ndim < 0`, `op_axes` and `itershape` are signalled to + * be unused and should be NULL. (Before NumPy 1.8 this was + * signalled by `oa_ndim == 0`.) + */ + if (op_axes != NULL || itershape != NULL) { PyErr_Format(PyExc_ValueError, + "If 'op_axes' or 'itershape' is not NULL in the iterator " + "constructor, 'oa_ndim' must be zero or greater"); + return 0; + } + return 1; + } + if (oa_ndim > NPY_MAXDIMS) { + PyErr_Format(PyExc_ValueError, "Cannot construct an iterator with more than %d dimensions " "(%d were requested for op_axes)", (int)NPY_MAXDIMS, oa_ndim); - return 0; - } - else if (op_axes == NULL) { - PyErr_Format(PyExc_ValueError, - "If 'oa_ndim' is greater than zero in the iterator " - "constructor, then op_axes cannot be NULL"); - return 0; - } + return 0; + } + if (op_axes == NULL) { + PyErr_Format(PyExc_ValueError, + "If 'oa_ndim' is zero or greater in the iterator " + "constructor, then op_axes cannot be NULL"); + return 0; + } - /* Check that there are no duplicates in op_axes */ - for (iop = 0; iop < nop; ++iop) { - int *axes = op_axes[iop]; - if (axes != NULL) { - memset(axes_dupcheck, 0, NPY_MAXDIMS); - for (idim = 0; idim < oa_ndim; ++idim) { - npy_intp i = axes[idim]; - if (i >= 0) { - if (i >= NPY_MAXDIMS) { - PyErr_Format(PyExc_ValueError, - "The 'op_axes' provided to the iterator " - "constructor for operand %d " - "contained invalid " - "values %d", (int)iop, (int)i); - return 0; - } else if(axes_dupcheck[i] == 1) { - PyErr_Format(PyExc_ValueError, - "The 'op_axes' provided to the iterator " - "constructor for operand %d " - "contained duplicate " - "value %d", (int)iop, (int)i); - return 0; - } - else { - axes_dupcheck[i] = 1; - } + /* Check that there are no duplicates in op_axes */ + for (iop = 0; iop < nop; ++iop) { + int *axes = op_axes[iop]; + if (axes != NULL) { + memset(axes_dupcheck, 0, NPY_MAXDIMS); + for (idim = 0; idim < oa_ndim; ++idim) { + npy_intp i = axes[idim]; + if (i >= 0) { + if (i >= NPY_MAXDIMS) { + PyErr_Format(PyExc_ValueError, + "The 'op_axes' provided to the iterator " + "constructor for operand %d " + "contained invalid " + "values %d", (int)iop, (int)i); + return 0; + } + else if (axes_dupcheck[i] == 1) { + PyErr_Format(PyExc_ValueError, + "The 'op_axes' provided to the iterator " + "constructor for operand %d " + "contained duplicate " + "value %d", (int)iop, (int)i); + return 0; + } + else { + axes_dupcheck[i] = 1; } } } @@ -819,7 +832,7 @@ npyiter_calculate_ndim(int nop, PyArrayObject **op_in, int oa_ndim) { /* If 'op_axes' is being used, force 'ndim' */ - if (oa_ndim > 0 ) { + if (oa_ndim >= 0 ) { return oa_ndim; } /* Otherwise it's the maximum 'ndim' from the operands */ @@ -1439,8 +1452,7 @@ static int npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itflags, char **op_dataptr, npy_uint32 *op_flags, int **op_axes, - npy_intp *itershape, - int output_scalars) + npy_intp *itershape) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); @@ -1540,6 +1552,13 @@ npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itf axisdata = NIT_AXISDATA(iter); sizeof_axisdata = NIT_AXISDATA_SIZEOF(itflags, ndim, nop); + if (ndim == 0) { + /* Need to fill the first axisdata, even if the iterator is 0-d */ + NAD_SHAPE(axisdata) = 1; + NAD_INDEX(axisdata) = 0; + memcpy(NAD_PTRS(axisdata), op_dataptr, NPY_SIZEOF_INTP*nop); + } + /* Now process the operands, filling in the axisdata */ for (idim = 0; idim < ndim; ++idim) { npy_intp bshape = broadcast_shape[ndim-idim-1]; @@ -1560,7 +1579,7 @@ npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itf ondim = PyArray_NDIM(op_cur); if (bshape == 1) { strides[iop] = 0; - if (idim >= ondim && !output_scalars && + if (idim >= ondim && (op_flags[iop] & NPY_ITER_NO_BROADCAST)) { goto operand_different_than_broadcast; } @@ -1681,8 +1700,8 @@ npyiter_fill_axisdata(NpyIter *iter, npy_uint32 flags, npyiter_opitflags *op_itf } /* Now fill in the ITERSIZE member */ - NIT_ITERSIZE(iter) = broadcast_shape[0]; - for (idim = 1; idim < ndim; ++idim) { + NIT_ITERSIZE(iter) = 1; + for (idim = 0; idim < ndim; ++idim) { NIT_ITERSIZE(iter) *= broadcast_shape[idim]; } /* The range defaults to everything */ @@ -2003,7 +2022,10 @@ npyiter_replace_axisdata(NpyIter *iter, int iop, NIT_RESETDATAPTR(iter)[iop] = op_dataptr; NIT_BASEOFFSETS(iter)[iop] = baseoffset; axisdata = axisdata0; - for (idim = 0; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { + /* Fill at least one axisdata, for the 0-d case */ + NAD_PTRS(axisdata)[iop] = op_dataptr; + NIT_ADVANCE_AXISDATA(axisdata, 1); + for (idim = 1; idim < ndim; ++idim, NIT_ADVANCE_AXISDATA(axisdata, 1)) { NAD_PTRS(axisdata)[iop] = op_dataptr; } } @@ -2029,7 +2051,7 @@ npyiter_compute_index_strides(NpyIter *iter, npy_uint32 flags) /* * If there is only one element being iterated, we just have * to touch the first AXISDATA because nothing will ever be - * incremented. + * incremented. This also initializes the data for the 0-d case. */ if (NIT_ITERSIZE(iter) == 1) { if (itflags & NPY_ITFLAG_HASINDEX) { @@ -2399,7 +2421,7 @@ static PyArray_Descr * npyiter_get_common_dtype(int nop, PyArrayObject **op, npyiter_opitflags *op_itflags, PyArray_Descr **op_dtype, PyArray_Descr **op_request_dtypes, - int only_inputs, int output_scalars) + int only_inputs) { int iop; npy_intp narrs = 0, ndtypes = 0; @@ -2698,7 +2720,7 @@ npyiter_allocate_arrays(NpyIter *iter, npy_uint32 flags, PyArray_Descr **op_dtype, PyTypeObject *subtype, npy_uint32 *op_flags, npyiter_opitflags *op_itflags, - int **op_axes, int output_scalars) + int **op_axes) { npy_uint32 itflags = NIT_ITFLAGS(iter); int idim, ndim = NIT_NDIM(iter); @@ -2729,7 +2751,7 @@ npyiter_allocate_arrays(NpyIter *iter, if (op[iop] == NULL) { PyArrayObject *out; PyTypeObject *op_subtype; - int ondim = output_scalars ? 0 : ndim; + int ondim = ndim; /* Check whether the subtype was disabled */ op_subtype = (op_flags[iop] & NPY_ITER_NO_SUBTYPE) ? @@ -2902,7 +2924,7 @@ npyiter_allocate_arrays(NpyIter *iter, if ((itflags & NPY_ITFLAG_BUFFER) && !(op_itflags[iop] & NPY_OP_ITFLAG_CAST)) { NpyIter_AxisData *axisdata = NIT_AXISDATA(iter); - if (ndim == 1) { + if (ndim <= 1) { op_itflags[iop] |= NPY_OP_ITFLAG_BUFNEVER; NBF_STRIDES(bufferdata)[iop] = NAD_STRIDES(axisdata)[iop]; } diff --git a/numpy/core/src/multiarray/nditer_impl.h b/numpy/core/src/multiarray/nditer_impl.h index 1251baa6e..ae24f46e6 100644 --- a/numpy/core/src/multiarray/nditer_impl.h +++ b/numpy/core/src/multiarray/nditer_impl.h @@ -294,7 +294,7 @@ struct NpyIter_AD { #define NIT_SIZEOF_ITERATOR(itflags, ndim, nop) ( \ sizeof(struct NpyIter_InternalOnly) + \ NIT_AXISDATA_OFFSET(itflags, ndim, nop) + \ - NIT_AXISDATA_SIZEOF(itflags, ndim, nop)*(ndim)) + NIT_AXISDATA_SIZEOF(itflags, ndim, nop)*(ndim ? ndim : 1)) /* Internal helper functions shared between implementation files */ NPY_NO_EXPORT void diff --git a/numpy/core/src/multiarray/nditer_pywrap.c b/numpy/core/src/multiarray/nditer_pywrap.c index 4621491a3..61f0c42b6 100644 --- a/numpy/core/src/multiarray/nditer_pywrap.c +++ b/numpy/core/src/multiarray/nditer_pywrap.c @@ -95,7 +95,6 @@ NpyIter_GlobalFlagsConverter(PyObject *flags_in, npy_uint32 *flags) npy_uint32 flag; if (flags_in == NULL || flags_in == Py_None) { - *flags = 0; return 1; } @@ -526,7 +525,7 @@ npyiter_convert_op_axes(PyObject *op_axes_in, npy_intp nop, return 0; } - *oa_ndim = 0; + *oa_ndim = -1; /* Copy the tuples into op_axes */ for (iop = 0; iop < nop; ++iop) { @@ -545,13 +544,8 @@ npyiter_convert_op_axes(PyObject *op_axes_in, npy_intp nop, Py_DECREF(a); return 0; } - if (*oa_ndim == 0) { + if (*oa_ndim == -1) { *oa_ndim = PySequence_Size(a); - if (*oa_ndim == 0) { - PyErr_SetString(PyExc_ValueError, - "op_axes must have at least one dimension"); - return 0; - } if (*oa_ndim > NPY_MAXDIMS) { PyErr_SetString(PyExc_ValueError, "Too many dimensions in op_axes"); @@ -575,7 +569,7 @@ npyiter_convert_op_axes(PyObject *op_axes_in, npy_intp nop, op_axes[iop][idim] = -1; } else { - op_axes[iop][idim] = PyInt_AsLong(v); + op_axes[iop][idim] = PyArray_PyIntAsInt(v); if (op_axes[iop][idim]==-1 && PyErr_Occurred()) { Py_DECREF(a); @@ -589,7 +583,7 @@ npyiter_convert_op_axes(PyObject *op_axes_in, npy_intp nop, } } - if (*oa_ndim == 0) { + if (*oa_ndim == -1) { PyErr_SetString(PyExc_ValueError, "If op_axes is provided, at least one list of axes " "must be contained within it"); @@ -726,7 +720,7 @@ npyiter_init(NewNpyArrayIterObject *self, PyObject *args, PyObject *kwds) NPY_CASTING casting = NPY_SAFE_CASTING; npy_uint32 op_flags[NPY_MAXARGS]; PyArray_Descr *op_request_dtypes[NPY_MAXARGS]; - int oa_ndim = 0; + int oa_ndim = -1; int op_axes_arrays[NPY_MAXARGS][NPY_MAXDIMS]; int *op_axes[NPY_MAXARGS]; PyArray_Dims itershape = {NULL, 0}; @@ -784,7 +778,7 @@ npyiter_init(NewNpyArrayIterObject *self, PyObject *args, PyObject *kwds) } if (itershape.len > 0) { - if (oa_ndim == 0) { + if (oa_ndim == -1) { oa_ndim = itershape.len; memset(op_axes, 0, sizeof(op_axes[0]) * nop); } @@ -800,10 +794,9 @@ npyiter_init(NewNpyArrayIterObject *self, PyObject *args, PyObject *kwds) itershape.ptr = NULL; } - self->iter = NpyIter_AdvancedNew(nop, op, flags, order, casting, op_flags, op_request_dtypes, - oa_ndim, oa_ndim > 0 ? op_axes : NULL, + oa_ndim, oa_ndim >= 0 ? op_axes : NULL, itershape.ptr, buffersize); @@ -860,7 +853,7 @@ NpyIter_NestedIters(PyObject *NPY_UNUSED(self), int iop, nop = 0, inest, nnest = 0; PyArrayObject *op[NPY_MAXARGS]; - npy_uint32 flags = 0, flags_inner = 0; + npy_uint32 flags = 0, flags_inner; NPY_ORDER order = NPY_KEEPORDER; NPY_CASTING casting = NPY_SAFE_CASTING; npy_uint32 op_flags[NPY_MAXARGS], op_flags_inner[NPY_MAXARGS]; diff --git a/numpy/core/src/multiarray/shape.c b/numpy/core/src/multiarray/shape.c index 4223e49f6..67ee4b04b 100644 --- a/numpy/core/src/multiarray/shape.c +++ b/numpy/core/src/multiarray/shape.c @@ -214,9 +214,11 @@ PyArray_Newshape(PyArrayObject *self, PyArray_Dims *newdims, * in order to get the right orientation and * because we can't just re-use the buffer with the * data in the order it is in. + * NPY_RELAXED_STRIDES_CHECKING: size check is unnecessary when set. */ - if ((order == NPY_CORDER && !PyArray_IS_C_CONTIGUOUS(self)) || - (order == NPY_FORTRANORDER && !PyArray_IS_F_CONTIGUOUS(self))) { + if ((PyArray_SIZE(self) > 1) && + ((order == NPY_CORDER && !PyArray_IS_C_CONTIGUOUS(self)) || + (order == NPY_FORTRANORDER && !PyArray_IS_F_CONTIGUOUS(self)))) { int success = 0; success = _attempt_nocopy_reshape(self, ndim, dimensions, newstrides, order); @@ -1102,7 +1104,9 @@ build_shape_string(npy_intp n, npy_intp *vals) * the array will point to invalid memory. The caller must * validate this! * If an axis flagged for removal has a shape larger then one, - * the arrays contiguous flags may require updating. + * the aligned flag (and in the future the contiguous flags), + * may need explicite update. + * (check also NPY_RELAXED_STRIDES_CHECKING) * * For example, this can be used to remove the reduction axes * from a reduction result once its computation is complete. @@ -1125,4 +1129,7 @@ PyArray_RemoveAxesInPlace(PyArrayObject *arr, npy_bool *flags) /* The final number of dimensions */ fa->nd = idim_out; + + /* May not be necessary for NPY_RELAXED_STRIDES_CHECKING (see comment) */ + PyArray_UpdateFlags(arr, NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); } diff --git a/numpy/core/src/multiarray/testcalcs.py b/numpy/core/src/multiarray/testcalcs.py index 78a875406..d4b39cb4a 100644 --- a/numpy/core/src/multiarray/testcalcs.py +++ b/numpy/core/src/multiarray/testcalcs.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from scipy import weave diff --git a/numpy/core/src/private/lowlevel_strided_loops.h b/numpy/core/src/private/lowlevel_strided_loops.h index 94c6a2121..c9fd1248f 100644 --- a/numpy/core/src/private/lowlevel_strided_loops.h +++ b/numpy/core/src/private/lowlevel_strided_loops.h @@ -256,6 +256,7 @@ PyArray_CastRawArrays(npy_intp count, * 'stransfer' with the provided dst_stride/src_stride and * dst_strides[0]/src_strides[0], so the caller can use those values to * specialize the function. + * Note that even if ndim == 0, everything needs to be set as if ndim == 1. * * The return value is the number of elements it couldn't copy. A return value * of 0 means all elements were copied, a larger value means the end of diff --git a/numpy/core/src/scalarmathmodule.c.src b/numpy/core/src/scalarmathmodule.c.src index 57c610b9e..b87d9b405 100644 --- a/numpy/core/src/scalarmathmodule.c.src +++ b/numpy/core/src/scalarmathmodule.c.src @@ -494,16 +494,25 @@ half_ctype_remainder(npy_half a, npy_half b, npy_half *out) { /**end repeat**/ /**begin repeat - * #name = half, float, double, longdouble# - * #type = npy_half, npy_float, npy_double, npy_longdouble# + * #name = float, double, longdouble# + * #type = npy_float, npy_double, npy_longdouble# */ static npy_@name@ (*_basic_@name@_pow)(@type@ a, @type@ b); static void -@name@_ctype_power(@type@ a, @type@ b, @type@ *out) { +@name@_ctype_power(@type@ a, @type@ b, @type@ *out) +{ *out = _basic_@name@_pow(a, b); } /**end repeat**/ +static void +half_ctype_power(npy_half a, npy_half b, npy_half *out) +{ + const npy_float af = npy_half_to_float(a); + const npy_float bf = npy_half_to_float(b); + const npy_float outf = _basic_float_pow(af,bf); + *out = npy_float_to_half(outf); +} /**begin repeat * #name = byte, ubyte, short, ushort, int, uint, @@ -1130,7 +1139,6 @@ static PyObject * int first; @type@ out = @zero@; - switch(_@name@_convert2_to_ctypes(a, &arg1, b, &arg2)) { case 0: break; @@ -1724,7 +1732,6 @@ get_functions(void) i += 3; j++; } - _basic_half_pow = funcdata[j - 1]; _basic_float_pow = funcdata[j]; _basic_double_pow = funcdata[j + 1]; _basic_longdouble_pow = funcdata[j + 2]; diff --git a/numpy/core/src/umath/reduction.c b/numpy/core/src/umath/reduction.c index e6ed04e99..f69aea2d0 100644 --- a/numpy/core/src/umath/reduction.c +++ b/numpy/core/src/umath/reduction.c @@ -513,7 +513,7 @@ PyUFunc_ReduceWrapper(PyArrayObject *operand, PyArrayObject *out, NPY_KEEPORDER, casting, op_flags, op_dtypes, - 0, NULL, NULL, buffersize); + -1, NULL, NULL, buffersize); if (iter == NULL) { goto fail; } diff --git a/numpy/core/src/umath/ufunc_object.c b/numpy/core/src/umath/ufunc_object.c index 124185bfd..9c499d322 100644 --- a/numpy/core/src/umath/ufunc_object.c +++ b/numpy/core/src/umath/ufunc_object.c @@ -1211,7 +1211,7 @@ iterator_loop(PyUFuncObject *ufunc, NPY_ITER_DELAY_BUFALLOC, order, NPY_UNSAFE_CASTING, op_flags, dtype, - 0, NULL, NULL, buffersize); + -1, NULL, NULL, buffersize); if (iter == NULL) { return -1; } @@ -1509,7 +1509,7 @@ execute_fancy_ufunc_loop(PyUFuncObject *ufunc, NPY_ITER_GROWINNER, order, NPY_UNSAFE_CASTING, op_flags, dtypes, - 0, NULL, NULL, buffersize); + -1, NULL, NULL, buffersize); if (iter == NULL) { return -1; } @@ -1976,18 +1976,6 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, NPY_ITER_NO_BROADCAST; } - /* - * If there are no iteration dimensions, create a fake one - * so that the scalar edge case works right. - */ - if (iter_ndim == 0) { - iter_ndim = 1; - iter_shape[0] = 1; - for (i = 0; i < nop; ++i) { - op_axes[i][0] = -1; - } - } - /* Create the iterator */ iter = NpyIter_AdvancedNew(nop, op, NPY_ITER_MULTI_INDEX| NPY_ITER_REFS_OK| diff --git a/numpy/core/tests/test_api.py b/numpy/core/tests/test_api.py index 484b6afbd..d93d6477a 100644 --- a/numpy/core/tests/test_api.py +++ b/numpy/core/tests/test_api.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys @@ -7,6 +7,9 @@ from numpy.testing import * from numpy.testing.utils import WarningManager import warnings +# Switch between new behaviour when NPY_RELAXED_STRIDES_CHECKING is set. +NPY_RELAXED_STRIDES_CHECKING = np.ones((10,1), order='C').flags.f_contiguous + def test_fastCopyAndTranspose(): # 0D array a = np.array(2) @@ -149,10 +152,13 @@ def test_copy_order(): assert_equal(x, y) assert_equal(res.flags.c_contiguous, ccontig) assert_equal(res.flags.f_contiguous, fcontig) - if strides: - assert_equal(x.strides, y.strides) - else: - assert_(x.strides != y.strides) + # This check is impossible only because + # NPY_RELAXED_STRIDES_CHECKING changes the strides actively + if not NPY_RELAXED_STRIDES_CHECKING: + if strides: + assert_equal(x.strides, y.strides) + else: + assert_(x.strides != y.strides) # Validate the initial state of a, b, and c assert_(a.flags.c_contiguous) @@ -206,7 +212,8 @@ def test_copy_order(): def test_contiguous_flags(): a = np.ones((4,4,1))[::2,:,:] - a.strides = a.strides[:2] + (-123,) + if NPY_RELAXED_STRIDES_CHECKING: + a.strides = a.strides[:2] + (-123,) b = np.ones((2,2,1,2,2)).swapaxes(3,4) def check_contig(a, ccontig, fcontig): @@ -216,8 +223,12 @@ def test_contiguous_flags(): # Check if new arrays are correct: check_contig(a, False, False) check_contig(b, False, False) - check_contig(np.empty((2,2,0,2,2)), True, True) - check_contig(np.array([[[1],[2]]], order='F'), True, True) + if NPY_RELAXED_STRIDES_CHECKING: + check_contig(np.empty((2,2,0,2,2)), True, True) + check_contig(np.array([[[1],[2]]], order='F'), True, True) + else: + check_contig(np.empty((2,2,0,2,2)), True, False) + check_contig(np.array([[[1],[2]]], order='F'), False, True) check_contig(np.empty((2,2)), True, False) check_contig(np.empty((2,2), order='F'), False, True) @@ -226,11 +237,18 @@ def test_contiguous_flags(): check_contig(np.array(a, copy=False, order='C'), True, False) check_contig(np.array(a, ndmin=4, copy=False, order='F'), False, True) - # Check slicing update of flags and : - check_contig(a[0], True, True) - check_contig(a[None,::4,...,None], True, True) - check_contig(b[0,0,...], False, True) - check_contig(b[:,:,0:0,:,:], True, True) + if NPY_RELAXED_STRIDES_CHECKING: + # Check slicing update of flags and : + check_contig(a[0], True, True) + check_contig(a[None,::4,...,None], True, True) + check_contig(b[0,0,...], False, True) + check_contig(b[:,:,0:0,:,:], True, True) + else: + # Check slicing update of flags: + check_contig(a[0], True, False) + # Would be nice if this was C-Contiguous: + check_contig(a[None,0,...,None], False, False) + check_contig(b[0,0,0,...], False, True) # Test ravel and squeeze. check_contig(a.ravel(), True, True) diff --git a/numpy/core/tests/test_arrayprint.py b/numpy/core/tests/test_arrayprint.py index a61aa5161..e286aea07 100644 --- a/numpy/core/tests/test_arrayprint.py +++ b/numpy/core/tests/test_arrayprint.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -*- coding: utf-8 -*- -from __future__ import division +from __future__ import division, absolute_import import sys import numpy as np diff --git a/numpy/core/tests/test_blasdot.py b/numpy/core/tests/test_blasdot.py index ec80840c5..1dd56fddd 100644 --- a/numpy/core/tests/test_blasdot.py +++ b/numpy/core/tests/test_blasdot.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import sys @@ -49,7 +49,7 @@ def test_dot_3args(): v = np.random.random_sample((16, 32)) r = np.empty((1024, 32)) - for i in xrange(12): + for i in range(12): np.dot(f,v,r) assert_equal(sys.getrefcount(r), 2) r2 = np.dot(f,v,out=None) diff --git a/numpy/core/tests/test_datetime.py b/numpy/core/tests/test_datetime.py index 03ee20b09..eecbfe75b 100644 --- a/numpy/core/tests/test_datetime.py +++ b/numpy/core/tests/test_datetime.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os, pickle import numpy diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py index ed928bce1..d75955075 100644 --- a/numpy/core/tests/test_defchararray.py +++ b/numpy/core/tests/test_defchararray.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy.core import * diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index c7cc9d413..6a248b5cf 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -3,7 +3,7 @@ Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. """ -from __future__ import division +from __future__ import division, absolute_import import sys import warnings diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py index a08cf4851..804c1cf2c 100644 --- a/numpy/core/tests/test_dtype.py +++ b/numpy/core/tests/test_dtype.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys import numpy as np diff --git a/numpy/core/tests/test_einsum.py b/numpy/core/tests/test_einsum.py index 4fba533db..aa0328a8b 100644 --- a/numpy/core/tests/test_einsum.py +++ b/numpy/core/tests/test_einsum.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from decimal import Decimal @@ -241,6 +241,7 @@ class TestEinSum(TestCase): assert_equal(np.einsum(a, [0,0]), np.trace(a).astype(dtype)) # multiply(a, b) + assert_equal(np.einsum("..., ...", 3, 4), 12) # scalar case for n in range(1,17): a = np.arange(3*n, dtype=dtype).reshape(3,n) b = np.arange(2*3*n, dtype=dtype).reshape(2,3,n) diff --git a/numpy/core/tests/test_errstate.py b/numpy/core/tests/test_errstate.py index c7c5a13ce..04acafbc9 100644 --- a/numpy/core/tests/test_errstate.py +++ b/numpy/core/tests/test_errstate.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import platform diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py index 914ffbb14..345e326c2 100644 --- a/numpy/core/tests/test_function_base.py +++ b/numpy/core/tests/test_function_base.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy import logspace, linspace diff --git a/numpy/core/tests/test_getlimits.py b/numpy/core/tests/test_getlimits.py index 5d5d9bc44..794d9d0b7 100644 --- a/numpy/core/tests/test_getlimits.py +++ b/numpy/core/tests/test_getlimits.py @@ -1,7 +1,7 @@ """ Test functions for limits module. """ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py index ed1b3e5dd..a6a3cd05c 100644 --- a/numpy/core/tests/test_half.py +++ b/numpy/core/tests/test_half.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import platform diff --git a/numpy/core/tests/test_indexerrors.py b/numpy/core/tests/test_indexerrors.py index 2d74d2ef3..5ab9b5aef 100644 --- a/numpy/core/tests/test_indexerrors.py +++ b/numpy/core/tests/test_indexerrors.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import TestCase, run_module_suite, assert_raises, assert_equal, assert_ diff --git a/numpy/core/tests/test_indexing.py b/numpy/core/tests/test_indexing.py index 6b8b7b8a8..530fd5583 100644 --- a/numpy/core/tests/test_indexing.py +++ b/numpy/core/tests/test_indexing.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.compat import asbytes diff --git a/numpy/core/tests/test_item_selection.py b/numpy/core/tests/test_item_selection.py index 6da27175b..d2282e52a 100644 --- a/numpy/core/tests/test_item_selection.py +++ b/numpy/core/tests/test_item_selection.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import * @@ -47,7 +47,7 @@ class TestTake(TestCase): def test_refcounting(self): - objects = [object() for i in xrange(10)] + objects = [object() for i in range(10)] for mode in ('raise', 'clip', 'wrap'): a = np.array(objects) b = np.array([2, 2, 4, 5, 3, 5]) diff --git a/numpy/core/tests/test_machar.py b/numpy/core/tests/test_machar.py index 1d2c42110..659902d84 100644 --- a/numpy/core/tests/test_machar.py +++ b/numpy/core/tests/test_machar.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py index 5daeaa279..01c804933 100644 --- a/numpy/core/tests/test_memmap.py +++ b/numpy/core/tests/test_memmap.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from tempfile import NamedTemporaryFile, mktemp diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 25cc8ced8..bca255f21 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import tempfile import sys @@ -579,7 +579,7 @@ class TestMethods(TestCase): # test object array sorts. a = np.empty((101,), dtype=np.object) - a[:] = range(101) + a[:] = list(range(101)) b = a[::-1] for kind in ['q', 'h', 'm'] : msg = "object sort, kind=%s" % kind @@ -729,7 +729,7 @@ class TestMethods(TestCase): # test object array argsorts. a = np.empty((101,), dtype=np.object) - a[:] = range(101) + a[:] = list(range(101)) b = a[::-1] r = np.arange(101) rr = r[::-1] @@ -1059,7 +1059,7 @@ class TestMethods(TestCase): # Regression test for a bug that crept in at one point a = np.zeros((100, 100)) assert_(sys.getrefcount(a) < 50) - for i in xrange(100): + for i in range(100): a.diagonal() assert_(sys.getrefcount(a) < 50) @@ -1311,10 +1311,10 @@ class TestArgmax(TestCase): def test_all(self): a = np.random.normal(0,1,(4,5,6,7,8)) - for i in xrange(a.ndim): + for i in range(a.ndim): amax = a.max(i) aargmax = a.argmax(i) - axes = range(a.ndim) + axes = list(range(a.ndim)) axes.remove(i) assert_(all(amax == aargmax.choose(*a.transpose(i,*axes)))) @@ -1379,10 +1379,10 @@ class TestArgmin(TestCase): def test_all(self): a = np.random.normal(0,1,(4,5,6,7,8)) - for i in xrange(a.ndim): + for i in range(a.ndim): amin = a.min(i) aargmin = a.argmin(i) - axes = range(a.ndim) + axes = list(range(a.ndim)) axes.remove(i) assert_(all(amin == aargmin.choose(*a.transpose(i,*axes)))) @@ -1541,7 +1541,7 @@ class TestPutmask(object): class TestTake(object): def tst_basic(self,x): - ind = range(x.shape[0]) + ind = list(range(x.shape[0])) assert_array_equal(x.take(ind, axis=0), x) def test_ip_types(self): @@ -2109,7 +2109,7 @@ class TestDot(TestCase): v = np.random.random_sample((16, 32)) r = np.empty((1024, 32)) - for i in xrange(12): + for i in range(12): dot(f,v,r) assert_equal(sys.getrefcount(r), 2) r2 = dot(f,v,out=None) @@ -2532,7 +2532,7 @@ if sys.version_info >= (2, 6): def test_native_padding(self): align = np.dtype('i').alignment - for j in xrange(8): + for j in range(8): if j == 0: s = 'bi' else: @@ -2764,7 +2764,9 @@ if sys.version_info >= (2, 6): assert_equal(y.format, 'T{b:a:=h:b:i:c:l:d:^q:dx:B:e:@H:f:=I:g:L:h:^Q:hx:=f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') else: assert_equal(y.format, 'T{b:a:=h:b:i:c:q:d:^q:dx:B:e:@H:f:=I:g:Q:h:^Q:hx:=f:i:d:j:^g:k:=Zf:ix:Zd:jx:^Zg:kx:4s:l:=4w:m:3x:n:?:o:@e:p:}') - assert_equal(y.strides, (sz,)) + # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides + if not (np.ones(1).strides[0] == np.iinfo(np.intp).max): + assert_equal(y.strides, (sz,)) assert_equal(y.itemsize, sz) def test_export_subarray(self): @@ -2793,7 +2795,7 @@ if sys.version_info >= (2, 6): assert_equal(y.format, '<i') def test_padding(self): - for j in xrange(8): + for j in range(8): x = np.array([(1,),(2,)], dtype={'f0': (int, j)}) self._check_roundtrip(x) diff --git a/numpy/core/tests/test_multiarray_assignment.py b/numpy/core/tests/test_multiarray_assignment.py index 555de8c4a..c47979b4d 100644 --- a/numpy/core/tests/test_multiarray_assignment.py +++ b/numpy/core/tests/test_multiarray_assignment.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import TestCase @@ -45,7 +45,7 @@ def _indices(ndims): # no itertools.product available in Py2.4 res = [[]] - for i in xrange(ndims): + for i in range(ndims): newres = [] for elem in ind: for others in res: diff --git a/numpy/core/tests/test_nditer.py b/numpy/core/tests/test_nditer.py index d537e4921..ec5f63c5e 100644 --- a/numpy/core/tests/test_nditer.py +++ b/numpy/core/tests/test_nditer.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy import array, arange, nditer, all @@ -1435,32 +1435,32 @@ def test_iter_iterindex(): a = arange(24).reshape(4,3,2) for flags in ([], ['buffered']): i = nditer(a, flags, buffersize=buffersize) - assert_equal(iter_iterindices(i), range(24)) + assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 2 - assert_equal(iter_iterindices(i), range(2,24)) + assert_equal(iter_iterindices(i), list(range(2,24))) i = nditer(a, flags, order='F', buffersize=buffersize) - assert_equal(iter_iterindices(i), range(24)) + assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 5 - assert_equal(iter_iterindices(i), range(5,24)) + assert_equal(iter_iterindices(i), list(range(5,24))) i = nditer(a[::-1], flags, order='F', buffersize=buffersize) - assert_equal(iter_iterindices(i), range(24)) + assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 9 - assert_equal(iter_iterindices(i), range(9,24)) + assert_equal(iter_iterindices(i), list(range(9,24))) i = nditer(a[::-1,::-1], flags, order='C', buffersize=buffersize) - assert_equal(iter_iterindices(i), range(24)) + assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 13 - assert_equal(iter_iterindices(i), range(13,24)) + assert_equal(iter_iterindices(i), list(range(13,24))) i = nditer(a[::1,::-1], flags, buffersize=buffersize) - assert_equal(iter_iterindices(i), range(24)) + assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 23 - assert_equal(iter_iterindices(i), range(23,24)) + assert_equal(iter_iterindices(i), list(range(23,24))) i.reset() i.iterindex = 2 - assert_equal(iter_iterindices(i), range(2,24)) + assert_equal(iter_iterindices(i), list(range(2,24))) def test_iter_iterrange(): # Make sure getting and resetting the iterrange works @@ -1572,7 +1572,7 @@ def test_iter_buffering_delayed_alloc(): assert_equal(i[0], 0) i[1] = 1 assert_equal(i[0:2], [0,1]) - assert_equal([[x[0][()],x[1][()]] for x in i], zip(range(6), [1]*6)) + assert_equal([[x[0][()],x[1][()]] for x in i], zip(list(range(6)), [1]*6)) def test_iter_buffered_cast_simple(): # Test that buffering can handle a simple cast @@ -1804,7 +1804,7 @@ def test_iter_buffered_cast_subarray(): casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) - for x, count in zip(i, range(6)): + for x, count in zip(i, list(range(6))): assert_(np.all(x['a'] == count)) # one element -> many -> back (copies it to all) @@ -2017,6 +2017,57 @@ def test_iter_buffering_growinner(): # Should end up with just one inner loop here assert_equal(i[0].size, a.size) + +@dec.slow +def test_iter_buffered_reduce_reuse(): + # large enough array for all views, including negative strides. + a = np.arange(2*3**5)[3**5:3**5+1] + flags = ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok', 'refs_ok'] + op_flags = [('readonly',), ('readwrite','allocate')] + op_axes_list = [[(0,1,2), (0,1,-1)], [(0,1,2), (0,-1,-1)]] + # wrong dtype to force buffering + op_dtypes = [np.float, a.dtype] + + def get_params(): + for xs in xrange(-3**2, 3**2 + 1): + for ys in xrange(xs, 3**2 + 1): + for op_axes in op_axes_list: + # last stride is reduced and because of that not + # important for this test, as it is the inner stride. + strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize) + arr = np.lib.stride_tricks.as_strided(a, (3,3,3), strides) + + for skip in [0, 1]: + yield arr, op_axes, skip + + for arr, op_axes, skip in get_params(): + nditer2 = np.nditer([arr.copy(), None], + op_axes=op_axes, flags=flags, op_flags=op_flags, + op_dtypes=op_dtypes) + nditer2.operands[-1][...] = 0 + nditer2.reset() + nditer2.iterindex = skip + + for (a2_in, b2_in) in nditer2: + b2_in += a2_in.astype(np.int_) + + comp_res = nditer2.operands[-1] + + for bufsize in xrange(0, 3**3): + nditer1 = np.nditer([arr, None], + op_axes=op_axes, flags=flags, op_flags=op_flags, + buffersize=bufsize, op_dtypes=op_dtypes) + nditer1.operands[-1][...] = 0 + nditer1.reset() + nditer1.iterindex = skip + + for (a1_in, b1_in) in nditer1: + b1_in += a1_in.astype(np.int_) + + res = nditer1.operands[-1] + assert_array_equal(res, comp_res) + + def test_iter_no_broadcast(): # Test that the no_broadcast flag works a = np.arange(24).reshape(2,3,4) @@ -2472,5 +2523,59 @@ def test_iter_allocated_array_dtypes(): c[1,1] = a / b assert_equal(it.operands[2], [[8, 12], [20, 5]]) + +def test_0d_iter(): + # Basic test for iteration of 0-d arrays: + i = nditer([2, 3], ['multi_index'], [['readonly']]*2) + assert_equal(i.ndim, 0) + assert_equal(i.next(), (2, 3)) + assert_equal(i.multi_index, ()) + assert_equal(i.iterindex, 0) + assert_raises(StopIteration, i.next) + # test reset: + i.reset() + assert_equal(i.next(), (2, 3)) + assert_raises(StopIteration, i.next) + + # test forcing to 0-d + i = nditer(np.arange(5), ['multi_index'], [['readonly']], op_axes=[()]) + assert_equal(i.ndim, 0) + assert_equal(len(i), 1) + # note that itershape=(), still behaves like None due to the conversions + + # Test a more complex buffered casting case (same as another test above) + sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2,3)), ('d', 'O')] + a = np.array(0.5, dtype='f4') + i = nditer(a, ['buffered','refs_ok'], ['readonly'], + casting='unsafe', op_dtypes=sdt) + vals = i.next() + assert_equal(vals['a'], 0.5) + assert_equal(vals['b'], 0) + assert_equal(vals['c'], [[(0.5)]*3]*2) + assert_equal(vals['d'], 0.5) + + +def test_0d_nested_iter(): + a = np.arange(12).reshape(2,3,2) + i, j = np.nested_iters(a, [[],[1,0,2]]) + vals = [] + for x in i: + vals.append([y for y in j]) + assert_equal(vals, [[0,1,2,3,4,5,6,7,8,9,10,11]]) + + i, j = np.nested_iters(a, [[1,0,2],[]]) + vals = [] + for x in i: + vals.append([y for y in j]) + assert_equal(vals, [[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11]]) + + i, j, k = np.nested_iters(a, [[2,0], [] ,[1]]) + vals = [] + for x in i: + for y in j: + vals.append([z for z in k]) + assert_equal(vals, [[0,2,4],[1,3,5],[6,8,10],[7,9,11]]) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index 6d0ca4efc..f5953955b 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys import platform @@ -520,7 +520,7 @@ class TestTypes(TestCase): class TestFromiter(TestCase): def makegen(self): - for x in xrange(24): + for x in range(24): yield x**2 def test_types(self): @@ -1504,5 +1504,27 @@ class TestStringFunction(object): np.set_string_function(None, repr=False) assert_equal(str(a), "[1]") +class TestRoll(TestCase): + def test_roll1d(self): + x = np.arange(10) + xr = np.roll(x, 2) + assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])) + + def test_roll2d(self): + x2 = np.reshape(np.arange(10), (2,5)) + x2r = np.roll(x2, 1) + assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]])) + + x2r = np.roll(x2, 1, axis=0) + assert_equal(x2r, np.array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]])) + + x2r = np.roll(x2, 1, axis=1) + assert_equal(x2r, np.array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]])) + + def test_roll_empty(self): + x = np.array([]) + assert_equal(np.roll(x, 1), np.array([])) + + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py index f00aee453..77fe2daf2 100644 --- a/numpy/core/tests/test_numerictypes.py +++ b/numpy/core/tests/test_numerictypes.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * diff --git a/numpy/core/tests/test_print.py b/numpy/core/tests/test_print.py index 3b9025d10..67021c20e 100644 --- a/numpy/core/tests/test_print.py +++ b/numpy/core/tests/test_print.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import * diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py index 5c7cba936..fa5877538 100644 --- a/numpy/core/tests/test_records.py +++ b/numpy/core/tests/test_records.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from os import path import numpy as np @@ -54,11 +54,11 @@ class TestFromrecords(TestCase): b = np.zeros(count, dtype='f8') c = np.zeros(count, dtype='f8') for i in range(len(a)): - a[i] = range(1, 10) + a[i] = list(range(1, 10)) mine = np.rec.fromarrays([a, b, c], names='date,data1,data2') for i in range(len(a)): - assert_((mine.date[i] == range(1, 10))) + assert_((mine.date[i] == list(range(1, 10)))) assert_((mine.data1[i] == 0.0)) assert_((mine.data2[i] == 0.0)) @@ -81,7 +81,7 @@ class TestFromrecords(TestCase): names='c1, c2, c3, c4') assert_(ra.dtype == pa.dtype) assert_(ra.shape == pa.shape) - for k in xrange(len(ra)): + for k in range(len(ra)): assert_(ra[k].item() == pa[k].item()) def test_recarray_conflict_fields(self): diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 95df4a113..4fa554b12 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import pickle import sys @@ -240,7 +240,7 @@ class TestRegression(TestCase): def test_argmax(self,level=rlevel): """Ticket #119""" a = np.random.normal(0,1,(4,5,6,7,8)) - for i in xrange(a.ndim): + for i in range(a.ndim): aargmax = a.argmax(i) def test_mem_divmod(self,level=rlevel): @@ -547,6 +547,9 @@ class TestRegression(TestCase): a = np.ones((0,2)) a.shape = (-1,2) + # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. + # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous. + @dec.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max) def test_reshape_trailing_ones_strides(self): # Github issue gh-2949, bad strides for trailing ones of new shape a = np.zeros(12, dtype=np.int32)[::2] # not contiguous @@ -675,7 +678,7 @@ class TestRegression(TestCase): def test_arr_transpose(self, level=rlevel): """Ticket #516""" x = np.random.rand(*(2,)*16) - y = x.transpose(range(16)) + y = x.transpose(list(range(16))) def test_string_mergesort(self, level=rlevel): """Ticket #540""" @@ -799,6 +802,10 @@ class TestRegression(TestCase): """Ticket #658""" np.indices((0,3,4)).T.reshape(-1,3) + # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides. + # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous, + # 0-sized reshape itself is tested elsewhere. + @dec.skipif(np.ones(1).strides[0] == np.iinfo(np.intp).max) def test_copy_detection_corner_case2(self, level=rlevel): """Ticket #771: strides are not set correctly when reshaping 0-sized arrays""" @@ -1188,7 +1195,7 @@ class TestRegression(TestCase): """Ticket #950""" for m in [0, 1, 2]: for n in [0, 1, 2]: - for k in xrange(3): + for k in range(3): # Try to ensure that x->data contains non-zero floats x = np.array([123456789e199], dtype=np.float64) x.resize((m, 0)) @@ -1229,8 +1236,8 @@ class TestRegression(TestCase): def test_fromiter_bytes(self): """Ticket #1058""" - a = np.fromiter(range(10), dtype='b') - b = np.fromiter(range(10), dtype='B') + a = np.fromiter(list(range(10)), dtype='b') + b = np.fromiter(list(range(10)), dtype='B') assert_(np.alltrue(a == np.array([0,1,2,3,4,5,6,7,8,9]))) assert_(np.alltrue(b == np.array([0,1,2,3,4,5,6,7,8,9]))) @@ -1413,8 +1420,8 @@ class TestRegression(TestCase): assert_(np.isfinite(np.log1p(np.exp2(-53)))) def test_fromiter_comparison(self, level=rlevel): - a = np.fromiter(range(10), dtype='b') - b = np.fromiter(range(10), dtype='B') + a = np.fromiter(list(range(10)), dtype='b') + b = np.fromiter(list(range(10)), dtype='B') assert_(np.alltrue(a == np.array([0,1,2,3,4,5,6,7,8,9]))) assert_(np.alltrue(b == np.array([0,1,2,3,4,5,6,7,8,9]))) @@ -1550,7 +1557,7 @@ class TestRegression(TestCase): assert_equal(int(np.uint64(x)), x) def test_duplicate_field_names_assign(self): - ra = np.fromiter(((i*3, i*2) for i in xrange(10)), dtype='i8,f8') + ra = np.fromiter(((i*3, i*2) for i in range(10)), dtype='i8,f8') ra.dtype.names = ('f1', 'f2') rep = repr(ra) # should not cause a segmentation fault assert_raises(ValueError, setattr, ra.dtype, 'names', ('f1', 'f1')) diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 03b90af79..75137411c 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * @@ -46,7 +46,7 @@ class TestTypes(TestCase): class TestPower(TestCase): def test_small_types(self): - for t in [np.int8, np.int16]: + for t in [np.int8, np.int16, np.float16]: a = t(3) b = a ** 4 assert_(b == 81, "error with %r: got %r" % (t,b)) @@ -60,7 +60,21 @@ class TestPower(TestCase): assert_(b == 6765201, msg) else: assert_almost_equal(b, 6765201, err_msg=msg) - + def test_mixed_types(self): + typelist = [np.int8,np.int16,np.float16, + np.float32,np.float64,np.int8, + np.int16,np.int32,np.int64] + for t1 in typelist: + for t2 in typelist: + a = t1(3) + b = t2(2) + result = a**b + msg = ("error with %r and %r:" + "got %r, expected %r") % (t1, t2, result, 9) + if np.issubdtype(np.dtype(result), np.integer): + assert_(result == 9, msg) + else: + assert_almost_equal(result, 9, err_msg=msg) class TestComplexDivision(TestCase): def test_zero_division(self): diff --git a/numpy/core/tests/test_scalarprint.py b/numpy/core/tests/test_scalarprint.py index 3f791e12d..80f5ab622 100644 --- a/numpy/core/tests/test_scalarprint.py +++ b/numpy/core/tests/test_scalarprint.py @@ -2,7 +2,7 @@ """ Test printing of scalar types. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import TestCase, assert_, run_module_suite diff --git a/numpy/core/tests/test_shape_base.py b/numpy/core/tests/test_shape_base.py index ccfb18ef7..cc2ff9d17 100644 --- a/numpy/core/tests/test_shape_base.py +++ b/numpy/core/tests/test_shape_base.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import warnings import numpy as np @@ -151,7 +151,7 @@ class TestVstack(TestCase): def test_concatenate_axis_None(): a = np.arange(4, dtype=np.float64).reshape((2,2)) - b = range(3) + b = list(range(3)) c = ['x'] r = np.concatenate((a, a), axis=None) assert_equal(r.dtype, a.dtype) diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py index a0fbb4bba..16ae9f50c 100644 --- a/numpy/core/tests/test_ufunc.py +++ b/numpy/core/tests/test_ufunc.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys @@ -449,7 +449,7 @@ class TestUfunc(TestCase): ret = () base = permute_n(n-1) for perm in base: - for i in xrange(n): + for i in range(n): new = perm + [n-1] new[n-1] = new[i] new[i] = n-1 diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index 78aa32234..cbad84bfc 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys import platform @@ -158,9 +158,9 @@ class TestPower(TestCase): assert_complex_equal(np.power(zero, -p), cnan) assert_complex_equal(np.power(zero, -1+0.2j), cnan) - def test_fast_power(self): - x=np.array([1,2,3], np.int16) - assert (x**2.00001).dtype is (x**2.0).dtype + def test_fast_power(self): + x = np.array([1,2,3], np.int16) + assert_((x**2.00001).dtype is (x**2.0).dtype) class TestLog2(TestCase): def test_log2_values(self) : diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py index 9500056bc..a1368bccd 100644 --- a/numpy/core/tests/test_umath_complex.py +++ b/numpy/core/tests/test_umath_complex.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys import platform @@ -400,7 +400,7 @@ class TestCpow(TestCase): def test_scalar(self): x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan]) y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3]) - lx = range(len(x)) + lx = list(range(len(x))) # Compute the values for complex type in python p_r = [complex(x[i]) ** complex(y[i]) for i in lx] # Substitute a result allowed by C99 standard @@ -413,7 +413,7 @@ class TestCpow(TestCase): def test_array(self): x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan]) y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3]) - lx = range(len(x)) + lx = list(range(len(x))) # Compute the values for complex type in python p_r = [complex(x[i]) ** complex(y[i]) for i in lx] # Substitute a result allowed by C99 standard diff --git a/numpy/core/tests/test_unicode.py b/numpy/core/tests/test_unicode.py index 8941f8e82..17a3c386b 100644 --- a/numpy/core/tests/test_unicode.py +++ b/numpy/core/tests/test_unicode.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py index e111fdb83..aa49de34b 100644 --- a/numpy/ctypeslib.py +++ b/numpy/ctypeslib.py @@ -49,7 +49,7 @@ Then, we're ready to call ``foo_func``: >>> _lib.foo_func(out, len(out)) #doctest: +SKIP """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library', 'c_intp', 'as_ctypes', 'as_array'] @@ -122,15 +122,16 @@ else: else: libdir = loader_path - # Need to save exception when using Python 3k, see PEP 3110. - exc = None for ln in libname_ext: - try: - libpath = os.path.join(libdir, ln) - return ctypes.cdll[libpath] - except OSError as e: - exc = e - raise exc + libpath = os.path.join(libdir, ln) + if os.path.exists(libpath): + try: + return ctypes.cdll[libpath] + except OSError: + ## defective lib file + raise + ## if no successful return in the libname_ext loop: + raise OSError("no file with expected extension") ctypes_load_library = deprecate(load_library, 'ctypes_load_library', 'load_library') diff --git a/numpy/distutils/__init__.py b/numpy/distutils/__init__.py index 5b68de74f..2a99ef8ad 100644 --- a/numpy/distutils/__init__.py +++ b/numpy/distutils/__init__.py @@ -1,16 +1,16 @@ -from __future__ import division +from __future__ import division, absolute_import import sys if sys.version_info[0] < 3: - from __version__ import version as __version__ + from .__version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. - import ccompiler - import unixccompiler + from . import ccompiler + from . import unixccompiler - from info import __doc__ - from npy_pkg_config import * + from .info import __doc__ + from .npy_pkg_config import * try: import __config__ diff --git a/numpy/distutils/__version__.py b/numpy/distutils/__version__.py index c9af8cdb1..e1bc8d30f 100644 --- a/numpy/distutils/__version__.py +++ b/numpy/distutils/__version__.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import major = 0 minor = 4 diff --git a/numpy/distutils/ccompiler.py b/numpy/distutils/ccompiler.py index 4478154f8..247eead42 100644 --- a/numpy/distutils/ccompiler.py +++ b/numpy/distutils/ccompiler.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import re import os @@ -165,7 +165,7 @@ def CCompiler_compile(self, sources, output_dir=None, macros=None, return [] # FIXME:RELATIVE_IMPORT if sys.version_info[0] < 3: - from fcompiler import FCompiler + from .fcompiler import FCompiler else: from numpy.distutils.fcompiler import FCompiler if isinstance(self, FCompiler): diff --git a/numpy/distutils/command/__init__.py b/numpy/distutils/command/__init__.py index 09fe78d22..4c4ddbf1f 100644 --- a/numpy/distutils/command/__init__.py +++ b/numpy/distutils/command/__init__.py @@ -4,7 +4,7 @@ Package containing implementation of all the standard Distutils commands. """ -from __future__ import division +from __future__ import division, absolute_import def test_na_writable_attributes_deletion(): a = np.NA(2) diff --git a/numpy/distutils/command/autodist.py b/numpy/distutils/command/autodist.py index 2e31fe22a..3d71bb68e 100644 --- a/numpy/distutils/command/autodist.py +++ b/numpy/distutils/command/autodist.py @@ -1,7 +1,7 @@ """This module implements additional tests ala autoconf which can be useful. """ -from __future__ import division +from __future__ import division, absolute_import # We put them here since they could be easily reused outside numpy.distutils diff --git a/numpy/distutils/command/bdist_rpm.py b/numpy/distutils/command/bdist_rpm.py index 302c6fdd2..004f67b9d 100644 --- a/numpy/distutils/command/bdist_rpm.py +++ b/numpy/distutils/command/bdist_rpm.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/distutils/command/build.py b/numpy/distutils/command/build.py index 239cafe1e..f0755373b 100644 --- a/numpy/distutils/command/build.py +++ b/numpy/distutils/command/build.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/distutils/command/build_clib.py b/numpy/distutils/command/build_clib.py index 99144d7b5..87005e05f 100644 --- a/numpy/distutils/command/build_clib.py +++ b/numpy/distutils/command/build_clib.py @@ -1,6 +1,6 @@ """ Modified version of build_clib that handles fortran source files. """ -from __future__ import division +from __future__ import division, absolute_import import os from glob import glob diff --git a/numpy/distutils/command/build_ext.py b/numpy/distutils/command/build_ext.py index 2245661a5..d1092a85b 100644 --- a/numpy/distutils/command/build_ext.py +++ b/numpy/distutils/command/build_ext.py @@ -1,7 +1,7 @@ """ Modified version of build_ext that handles fortran source files. """ -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/distutils/command/build_py.py b/numpy/distutils/command/build_py.py index e8c7b8f83..655e56b87 100644 --- a/numpy/distutils/command/build_py.py +++ b/numpy/distutils/command/build_py.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from distutils.command.build_py import build_py as old_build_py from numpy.distutils.misc_util import is_string diff --git a/numpy/distutils/command/build_scripts.py b/numpy/distutils/command/build_scripts.py index 1a3d26d58..17cc6aaed 100644 --- a/numpy/distutils/command/build_scripts.py +++ b/numpy/distutils/command/build_scripts.py @@ -1,7 +1,7 @@ """ Modified version of build_scripts that handles building scripts from functions. """ -from __future__ import division +from __future__ import division, absolute_import from distutils.command.build_scripts import build_scripts as old_build_scripts from numpy.distutils import log diff --git a/numpy/distutils/command/build_src.py b/numpy/distutils/command/build_src.py index cacfc472b..d9a9023b0 100644 --- a/numpy/distutils/command/build_src.py +++ b/numpy/distutils/command/build_src.py @@ -1,6 +1,6 @@ """ Build swig, f2py, pyrex sources. """ -from __future__ import division +from __future__ import division, absolute_import import os import re diff --git a/numpy/distutils/command/config.py b/numpy/distutils/command/config.py index 78207895b..470ca07c9 100644 --- a/numpy/distutils/command/config.py +++ b/numpy/distutils/command/config.py @@ -2,7 +2,7 @@ # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson -from __future__ import division +from __future__ import division, absolute_import import os, signal import warnings diff --git a/numpy/distutils/command/config_compiler.py b/numpy/distutils/command/config_compiler.py index 6894b4552..3303d3469 100644 --- a/numpy/distutils/command/config_compiler.py +++ b/numpy/distutils/command/config_compiler.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from distutils.core import Command from numpy.distutils import log diff --git a/numpy/distutils/command/develop.py b/numpy/distutils/command/develop.py index 8328effcf..17661e0bd 100644 --- a/numpy/distutils/command/develop.py +++ b/numpy/distutils/command/develop.py @@ -3,7 +3,7 @@ generated files (from build_src or build_scripts) are properly converted to real files with filenames. """ -from __future__ import division +from __future__ import division, absolute_import from setuptools.command.develop import develop as old_develop diff --git a/numpy/distutils/command/egg_info.py b/numpy/distutils/command/egg_info.py index 33c64b0e4..3a908f602 100644 --- a/numpy/distutils/command/egg_info.py +++ b/numpy/distutils/command/egg_info.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from setuptools.command.egg_info import egg_info as _egg_info diff --git a/numpy/distutils/command/install.py b/numpy/distutils/command/install.py index d9b84fc08..37523c8e4 100644 --- a/numpy/distutils/command/install.py +++ b/numpy/distutils/command/install.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys if 'setuptools' in sys.modules: diff --git a/numpy/distutils/command/install_clib.py b/numpy/distutils/command/install_clib.py index 8845cedab..7753020e5 100644 --- a/numpy/distutils/command/install_clib.py +++ b/numpy/distutils/command/install_clib.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os from distutils.core import Command diff --git a/numpy/distutils/command/install_data.py b/numpy/distutils/command/install_data.py index d99d656db..afdc98013 100644 --- a/numpy/distutils/command/install_data.py +++ b/numpy/distutils/command/install_data.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys have_setuptools = ('setuptools' in sys.modules) diff --git a/numpy/distutils/command/install_headers.py b/numpy/distutils/command/install_headers.py index 548c3c643..c6c01e35b 100644 --- a/numpy/distutils/command/install_headers.py +++ b/numpy/distutils/command/install_headers.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os from distutils.command.install_headers import install_headers as old_install_headers diff --git a/numpy/distutils/command/sdist.py b/numpy/distutils/command/sdist.py index 3e07f7a01..a4e2158ce 100644 --- a/numpy/distutils/command/sdist.py +++ b/numpy/distutils/command/sdist.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys if 'setuptools' in sys.modules: diff --git a/numpy/distutils/compat.py b/numpy/distutils/compat.py index 55b9627d5..bd4184dcd 100644 --- a/numpy/distutils/compat.py +++ b/numpy/distutils/compat.py @@ -2,7 +2,7 @@ numpy.distutils """ -from __future__ import division +from __future__ import division, absolute_import import sys diff --git a/numpy/distutils/conv_template.py b/numpy/distutils/conv_template.py index 6b969cef3..77e2eb5e1 100644 --- a/numpy/distutils/conv_template.py +++ b/numpy/distutils/conv_template.py @@ -78,7 +78,7 @@ Example: 3, 3, jim """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['process_str', 'process_file'] diff --git a/numpy/distutils/core.py b/numpy/distutils/core.py index f450b1564..711d5a223 100644 --- a/numpy/distutils/core.py +++ b/numpy/distutils/core.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from distutils.core import * diff --git a/numpy/distutils/cpuinfo.py b/numpy/distutils/cpuinfo.py index 86a18993a..1e2d9379c 100644 --- a/numpy/distutils/cpuinfo.py +++ b/numpy/distutils/cpuinfo.py @@ -12,7 +12,7 @@ NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['cpu'] diff --git a/numpy/distutils/environment.py b/numpy/distutils/environment.py index 015815cbe..1360d82fe 100644 --- a/numpy/distutils/environment.py +++ b/numpy/distutils/environment.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os from distutils.dist import Distribution diff --git a/numpy/distutils/exec_command.py b/numpy/distutils/exec_command.py index f05b56429..923486158 100644 --- a/numpy/distutils/exec_command.py +++ b/numpy/distutils/exec_command.py @@ -44,7 +44,7 @@ Known bugs: - Tests, that send messages to stderr, fail when executed from MSYS prompt because the messages are lost at some point. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['exec_command','find_executable'] @@ -141,6 +141,19 @@ def _update_environment( **env ): for name,value in env.items(): os.environ[name] = value or '' +def _supports_fileno(stream): + """ + Returns True if 'stream' supports the file descriptor and allows fileno(). + """ + if hasattr(stream, 'fileno'): + try: + r = stream.fileno() + return True + except IOError: + return False + else: + return False + def exec_command( command, execute_in='', use_shell=None, use_tee = None, _with_python = 1, @@ -195,7 +208,8 @@ def exec_command( command, # _exec_command_posix uses os.system and is faster # but not on all platforms os.system will return # a correct status. - if _with_python and sys.stdout.fileno() == -1: + if (_with_python and _supports_fileno(sys.stdout) and + sys.stdout.fileno() == -1): st = _exec_command_python(command, exec_command_dir = exec_dir, **env) @@ -349,12 +363,16 @@ def _exec_command( command, use_shell=None, use_tee = None, **env ): argv = [os.environ['COMSPEC'],'/C'] + argv using_command = 1 - so_fileno = sys.stdout.fileno() - se_fileno = sys.stderr.fileno() + _so_has_fileno = _supports_fileno(sys.stdout) + _se_has_fileno = _supports_fileno(sys.stderr) so_flush = sys.stdout.flush se_flush = sys.stderr.flush - so_dup = os.dup(so_fileno) - se_dup = os.dup(se_fileno) + if _so_has_fileno: + so_fileno = sys.stdout.fileno() + so_dup = os.dup(so_fileno) + if _se_has_fileno: + se_fileno = sys.stderr.fileno() + se_dup = os.dup(se_fileno) outfile = temp_file_name() fout = open(outfile,'w') @@ -371,13 +389,16 @@ def _exec_command( command, use_shell=None, use_tee = None, **env ): so_flush() se_flush() - os.dup2(fout.fileno(),so_fileno) - if using_command: - #XXX: disabled for now as it does not work from cmd under win32. - # Tests fail on msys - os.dup2(ferr.fileno(),se_fileno) - else: - os.dup2(fout.fileno(),se_fileno) + if _so_has_fileno: + os.dup2(fout.fileno(),so_fileno) + + if _se_has_fileno: + if using_command: + #XXX: disabled for now as it does not work from cmd under win32. + # Tests fail on msys + os.dup2(ferr.fileno(),se_fileno) + else: + os.dup2(fout.fileno(),se_fileno) try: status = spawn_command(os.P_WAIT,argv0,argv,os.environ) except OSError: @@ -387,8 +408,10 @@ def _exec_command( command, use_shell=None, use_tee = None, **env ): so_flush() se_flush() - os.dup2(so_dup,so_fileno) - os.dup2(se_dup,se_fileno) + if _so_has_fileno: + os.dup2(so_dup,so_fileno) + if _se_has_fileno: + os.dup2(se_dup,se_fileno) fout.close() fout = open_latin1(outfile,'r') diff --git a/numpy/distutils/extension.py b/numpy/distutils/extension.py index 95213644f..f58b27780 100644 --- a/numpy/distutils/extension.py +++ b/numpy/distutils/extension.py @@ -6,7 +6,7 @@ modules in setup scripts. Overridden to support f2py. """ -from __future__ import division +from __future__ import division, absolute_import __revision__ = "$Id: extension.py,v 1.1 2005/04/09 19:29:34 pearu Exp $" diff --git a/numpy/distutils/fcompiler/__init__.py b/numpy/distutils/fcompiler/__init__.py index 510a38a58..c0b587fed 100644 --- a/numpy/distutils/fcompiler/__init__.py +++ b/numpy/distutils/fcompiler/__init__.py @@ -13,7 +13,7 @@ should be a list. But note that FCompiler.executables is actually a dictionary of commands. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['FCompiler','new_fcompiler','show_fcompilers', 'dummy_fortran_file'] diff --git a/numpy/distutils/fcompiler/absoft.py b/numpy/distutils/fcompiler/absoft.py index 7c06d70a3..2fb579e35 100644 --- a/numpy/distutils/fcompiler/absoft.py +++ b/numpy/distutils/fcompiler/absoft.py @@ -5,7 +5,7 @@ # Notes: # - when using -g77 then use -DUNDERSCORE_G77 to compile f2py # generated extension modules (works for f2py v2.45.241_1936 and up) -from __future__ import division +from __future__ import division, absolute_import import os diff --git a/numpy/distutils/fcompiler/compaq.py b/numpy/distutils/fcompiler/compaq.py index d67c1f24e..16f3a0e54 100644 --- a/numpy/distutils/fcompiler/compaq.py +++ b/numpy/distutils/fcompiler/compaq.py @@ -1,6 +1,6 @@ #http://www.compaq.com/fortran/docs/ -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/distutils/fcompiler/g95.py b/numpy/distutils/fcompiler/g95.py index 478f48f3e..41b781010 100644 --- a/numpy/distutils/fcompiler/g95.py +++ b/numpy/distutils/fcompiler/g95.py @@ -1,5 +1,5 @@ # http://g95.sourceforge.net/ -from __future__ import division +from __future__ import division, absolute_import from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/gnu.py b/numpy/distutils/fcompiler/gnu.py index c26e81fcd..80dbf48c6 100644 --- a/numpy/distutils/fcompiler/gnu.py +++ b/numpy/distutils/fcompiler/gnu.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import re import os diff --git a/numpy/distutils/fcompiler/hpux.py b/numpy/distutils/fcompiler/hpux.py index 44bfbe1c2..250159107 100644 --- a/numpy/distutils/fcompiler/hpux.py +++ b/numpy/distutils/fcompiler/hpux.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/ibm.py b/numpy/distutils/fcompiler/ibm.py index b3126b558..09001c500 100644 --- a/numpy/distutils/fcompiler/ibm.py +++ b/numpy/distutils/fcompiler/ibm.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import re diff --git a/numpy/distutils/fcompiler/intel.py b/numpy/distutils/fcompiler/intel.py index 53ea7af05..b975d1f1b 100644 --- a/numpy/distutils/fcompiler/intel.py +++ b/numpy/distutils/fcompiler/intel.py @@ -1,5 +1,5 @@ # http://developer.intel.com/software/products/compilers/flin/ -from __future__ import division +from __future__ import division, absolute_import import sys diff --git a/numpy/distutils/fcompiler/lahey.py b/numpy/distutils/fcompiler/lahey.py index 06c4c6f56..208f09a27 100644 --- a/numpy/distutils/fcompiler/lahey.py +++ b/numpy/distutils/fcompiler/lahey.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os diff --git a/numpy/distutils/fcompiler/mips.py b/numpy/distutils/fcompiler/mips.py index 6cd2fdfac..433f053e3 100644 --- a/numpy/distutils/fcompiler/mips.py +++ b/numpy/distutils/fcompiler/mips.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/nag.py b/numpy/distutils/fcompiler/nag.py index 11253c4be..8cbd15f60 100644 --- a/numpy/distutils/fcompiler/nag.py +++ b/numpy/distutils/fcompiler/nag.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/none.py b/numpy/distutils/fcompiler/none.py index e99c2ab35..ee7e6dee9 100644 --- a/numpy/distutils/fcompiler/none.py +++ b/numpy/distutils/fcompiler/none.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/pathf95.py b/numpy/distutils/fcompiler/pathf95.py index c9bd58c62..3b3c31e00 100644 --- a/numpy/distutils/fcompiler/pathf95.py +++ b/numpy/distutils/fcompiler/pathf95.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/pg.py b/numpy/distutils/fcompiler/pg.py index e0f5e0d44..959f86d68 100644 --- a/numpy/distutils/fcompiler/pg.py +++ b/numpy/distutils/fcompiler/pg.py @@ -1,5 +1,5 @@ # http://www.pgroup.com -from __future__ import division +from __future__ import division, absolute_import from numpy.distutils.fcompiler import FCompiler from sys import platform diff --git a/numpy/distutils/fcompiler/sun.py b/numpy/distutils/fcompiler/sun.py index 7deeac29a..bff37a543 100644 --- a/numpy/distutils/fcompiler/sun.py +++ b/numpy/distutils/fcompiler/sun.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/vast.py b/numpy/distutils/fcompiler/vast.py index bddc1be91..2d6d164a1 100644 --- a/numpy/distutils/fcompiler/vast.py +++ b/numpy/distutils/fcompiler/vast.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os diff --git a/numpy/distutils/from_template.py b/numpy/distutils/from_template.py index 99f36e371..dc933dd6a 100644 --- a/numpy/distutils/from_template.py +++ b/numpy/distutils/from_template.py @@ -45,7 +45,7 @@ process_file(filename) <ctypereal=float,double,\\0,\\1> """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['process_str','process_file'] diff --git a/numpy/distutils/info.py b/numpy/distutils/info.py index 4d8b847bd..de3dc4f48 100644 --- a/numpy/distutils/info.py +++ b/numpy/distutils/info.py @@ -1,6 +1,6 @@ """ Enhanced distutils with Fortran compilers support and more. """ -from __future__ import division +from __future__ import division, absolute_import postpone_import = True diff --git a/numpy/distutils/intelccompiler.py b/numpy/distutils/intelccompiler.py index 8c3af0957..58208647d 100644 --- a/numpy/distutils/intelccompiler.py +++ b/numpy/distutils/intelccompiler.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from distutils.unixccompiler import UnixCCompiler from numpy.distutils.exec_command import find_executable diff --git a/numpy/distutils/lib2def.py b/numpy/distutils/lib2def.py index 0e98e17ef..b2c4f1f28 100644 --- a/numpy/distutils/lib2def.py +++ b/numpy/distutils/lib2def.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import re import sys diff --git a/numpy/distutils/line_endings.py b/numpy/distutils/line_endings.py index f18850716..93f5421c0 100644 --- a/numpy/distutils/line_endings.py +++ b/numpy/distutils/line_endings.py @@ -1,7 +1,7 @@ """ Functions for converting from DOS to UNIX line endings """ -from __future__ import division +from __future__ import division, absolute_import import sys, re, os diff --git a/numpy/distutils/log.py b/numpy/distutils/log.py index a3f4cb9ff..41c9a56da 100644 --- a/numpy/distutils/log.py +++ b/numpy/distutils/log.py @@ -1,5 +1,5 @@ # Colored log, requires Python 2.3 or up. -from __future__ import division +from __future__ import division, absolute_import import sys from distutils.log import * @@ -7,7 +7,7 @@ from distutils.log import Log as old_Log from distutils.log import _global_log if sys.version_info[0] < 3: - from misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string + from .misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string else: from numpy.distutils.misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string diff --git a/numpy/distutils/mingw32ccompiler.py b/numpy/distutils/mingw32ccompiler.py index 34a874933..af613e551 100644 --- a/numpy/distutils/mingw32ccompiler.py +++ b/numpy/distutils/mingw32ccompiler.py @@ -7,7 +7,7 @@ Support code for building Python extensions on Windows. # 3. Force windows to use g77 """ -from __future__ import division +from __future__ import division, absolute_import import os import subprocess @@ -19,7 +19,7 @@ import re import numpy.distutils.ccompiler if sys.version_info[0] < 3: - import log + from . import log else: from numpy.distutils import log # NT stuff diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index a082a6dae..48bbcf005 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import re @@ -1047,7 +1047,7 @@ class Configuration(object): pattern_list = allpath(d).split(os.sep) pattern_list.reverse() # /a/*//b/ -> /a/*/b - rl = range(len(pattern_list)-1); rl.reverse() + rl = list(range(len(pattern_list)-1)); rl.reverse() for i in rl: if not pattern_list[i]: del pattern_list[i] @@ -1990,7 +1990,7 @@ class Configuration(object): Return information (from system_info.get_info) for all of the names in the argument list in a single dictionary. """ - from system_info import get_info, dict_append + from .system_info import get_info, dict_append info_dict = {} for a in names: dict_append(info_dict,**get_info(a)) diff --git a/numpy/distutils/npy_pkg_config.py b/numpy/distutils/npy_pkg_config.py index 6f3072885..2dacbbc70 100644 --- a/numpy/distutils/npy_pkg_config.py +++ b/numpy/distutils/npy_pkg_config.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys if sys.version_info[0] < 3: diff --git a/numpy/distutils/numpy_distribution.py b/numpy/distutils/numpy_distribution.py index 276f81398..353e18a51 100644 --- a/numpy/distutils/numpy_distribution.py +++ b/numpy/distutils/numpy_distribution.py @@ -1,5 +1,5 @@ # XXX: Handle setuptools ? -from __future__ import division +from __future__ import division, absolute_import from distutils.core import Distribution diff --git a/numpy/distutils/pathccompiler.py b/numpy/distutils/pathccompiler.py index 2e5b76a53..e847e7d0a 100644 --- a/numpy/distutils/pathccompiler.py +++ b/numpy/distutils/pathccompiler.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from distutils.unixccompiler import UnixCCompiler diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index 869bd6bd1..68ad926e3 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -110,7 +110,7 @@ this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. """ -from __future__ import division +from __future__ import division, absolute_import import sys import os @@ -929,7 +929,7 @@ class mkl_info(system_info): if mklroot is None: system_info.__init__(self) else: - from cpuinfo import cpu + from .cpuinfo import cpu l = 'mkl' # use shared library if cpu.is_Itanium(): plt = '64' diff --git a/numpy/distutils/tests/f2py_ext/__init__.py b/numpy/distutils/tests/f2py_ext/__init__.py index b06eaf1a4..52119d5cd 100644 --- a/numpy/distutils/tests/f2py_ext/__init__.py +++ b/numpy/distutils/tests/f2py_ext/__init__.py @@ -1 +1 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/distutils/tests/f2py_ext/tests/test_fib2.py b/numpy/distutils/tests/f2py_ext/tests/test_fib2.py index 696ee41d8..149256d72 100644 --- a/numpy/distutils/tests/f2py_ext/tests/test_fib2.py +++ b/numpy/distutils/tests/f2py_ext/tests/test_fib2.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * diff --git a/numpy/distutils/tests/f2py_f90_ext/__init__.py b/numpy/distutils/tests/f2py_f90_ext/__init__.py index b06eaf1a4..52119d5cd 100644 --- a/numpy/distutils/tests/f2py_f90_ext/__init__.py +++ b/numpy/distutils/tests/f2py_f90_ext/__init__.py @@ -1 +1 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py b/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py index 3fa7b3730..d68981c04 100644 --- a/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py +++ b/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * diff --git a/numpy/distutils/tests/gen_ext/__init__.py b/numpy/distutils/tests/gen_ext/__init__.py index b06eaf1a4..52119d5cd 100644 --- a/numpy/distutils/tests/gen_ext/__init__.py +++ b/numpy/distutils/tests/gen_ext/__init__.py @@ -1 +1 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/distutils/tests/gen_ext/tests/test_fib3.py b/numpy/distutils/tests/gen_ext/tests/test_fib3.py index 3fa72036e..0f194255d 100644 --- a/numpy/distutils/tests/gen_ext/tests/test_fib3.py +++ b/numpy/distutils/tests/gen_ext/tests/test_fib3.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * diff --git a/numpy/distutils/tests/pyrex_ext/__init__.py b/numpy/distutils/tests/pyrex_ext/__init__.py index b06eaf1a4..52119d5cd 100644 --- a/numpy/distutils/tests/pyrex_ext/__init__.py +++ b/numpy/distutils/tests/pyrex_ext/__init__.py @@ -1 +1 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/distutils/tests/pyrex_ext/tests/test_primes.py b/numpy/distutils/tests/pyrex_ext/tests/test_primes.py index 96f73c426..a2bb091ea 100644 --- a/numpy/distutils/tests/pyrex_ext/tests/test_primes.py +++ b/numpy/distutils/tests/pyrex_ext/tests/test_primes.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * diff --git a/numpy/distutils/tests/swig_ext/__init__.py b/numpy/distutils/tests/swig_ext/__init__.py index b06eaf1a4..52119d5cd 100644 --- a/numpy/distutils/tests/swig_ext/__init__.py +++ b/numpy/distutils/tests/swig_ext/__init__.py @@ -1 +1 @@ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/distutils/tests/swig_ext/tests/test_example.py b/numpy/distutils/tests/swig_ext/tests/test_example.py index 5a4765fa7..419ca53d8 100644 --- a/numpy/distutils/tests/swig_ext/tests/test_example.py +++ b/numpy/distutils/tests/swig_ext/tests/test_example.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * diff --git a/numpy/distutils/tests/swig_ext/tests/test_example2.py b/numpy/distutils/tests/swig_ext/tests/test_example2.py index c3c4727c0..f876bad16 100644 --- a/numpy/distutils/tests/swig_ext/tests/test_example2.py +++ b/numpy/distutils/tests/swig_ext/tests/test_example2.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys from numpy.testing import * diff --git a/numpy/distutils/tests/test_exec_command.py b/numpy/distutils/tests/test_exec_command.py new file mode 100644 index 000000000..11f262369 --- /dev/null +++ b/numpy/distutils/tests/test_exec_command.py @@ -0,0 +1,87 @@ +from __future__ import division, absolute_import + +import os +import sys +import StringIO +from tempfile import TemporaryFile + +from numpy.distutils import exec_command + + +class redirect_stdout(object): + """Context manager to redirect stdout for exec_command test.""" + def __init__(self, stdout=None): + self._stdout = stdout or sys.stdout + + def __enter__(self): + self.old_stdout = sys.stdout + sys.stdout = self._stdout + + def __exit__(self, exc_type, exc_value, traceback): + self._stdout.flush() + sys.stdout = self.old_stdout + # note: closing sys.stdout won't close it. + self._stdout.close() + +class redirect_stderr(object): + """Context manager to redirect stderr for exec_command test.""" + def __init__(self, stderr=None): + self._stderr = stderr or sys.stderr + + def __enter__(self): + self.old_stderr = sys.stderr + sys.stderr = self._stderr + + def __exit__(self, exc_type, exc_value, traceback): + self._stderr.flush() + sys.stderr = self.old_stderr + # note: closing sys.stderr won't close it. + self._stderr.close() + +class emulate_nonposix(object): + """Context manager to emulate os.name != 'posix' """ + def __init__(self, osname='non-posix'): + self._new_name = osname + + def __enter__(self): + self._old_name = os.name + os.name = self._new_name + + def __exit__(self, exc_type, exc_value, traceback): + os.name = self._old_name + + +def test_exec_command_stdout(): + # Regression test for gh-2999 and gh-2915. + # There are several packages (nose, scipy.weave.inline, Sage inline + # Fortran) that replace stdout, in which case it doesn't have a fileno + # method. This is tested here, with a do-nothing command that fails if the + # presence of fileno() is assumed in exec_command. + + # The code has a special case for posix systems, so if we are on posix test + # both that the special case works and that the generic code works. + + # Test posix version: + with redirect_stdout(StringIO.StringIO()): + with redirect_stderr(TemporaryFile()): + exec_command.exec_command("cd '.'") + + if os.name == 'posix': + # Test general (non-posix) version: + with emulate_nonposix(): + with redirect_stdout(StringIO.StringIO()): + with redirect_stderr(TemporaryFile()): + exec_command.exec_command("cd '.'") + +def test_exec_command_stderr(): + # Test posix version: + with redirect_stdout(TemporaryFile(mode='w+')): + with redirect_stderr(StringIO.StringIO()): + exec_command.exec_command("cd '.'") + + if os.name == 'posix': + # Test general (non-posix) version: + with emulate_nonposix(): + with redirect_stdout(TemporaryFile()): + with redirect_stderr(StringIO.StringIO()): + exec_command.exec_command("cd '.'") diff --git a/numpy/distutils/tests/test_fcompiler_gnu.py b/numpy/distutils/tests/test_fcompiler_gnu.py index d3b38db23..09a7275f8 100644 --- a/numpy/distutils/tests/test_fcompiler_gnu.py +++ b/numpy/distutils/tests/test_fcompiler_gnu.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * diff --git a/numpy/distutils/tests/test_fcompiler_intel.py b/numpy/distutils/tests/test_fcompiler_intel.py index 4ebf1a0c0..8e3ba5fd3 100644 --- a/numpy/distutils/tests/test_fcompiler_intel.py +++ b/numpy/distutils/tests/test_fcompiler_intel.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * diff --git a/numpy/distutils/tests/test_misc_util.py b/numpy/distutils/tests/test_misc_util.py index 57fde8899..b19c09f81 100644 --- a/numpy/distutils/tests/test_misc_util.py +++ b/numpy/distutils/tests/test_misc_util.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy.distutils.misc_util import appendpath, minrelpath, gpaths, rel_path diff --git a/numpy/distutils/tests/test_npy_pkg_config.py b/numpy/distutils/tests/test_npy_pkg_config.py index d3568eb6b..e25f47d76 100644 --- a/numpy/distutils/tests/test_npy_pkg_config.py +++ b/numpy/distutils/tests/test_npy_pkg_config.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os from tempfile import mkstemp diff --git a/numpy/distutils/unixccompiler.py b/numpy/distutils/unixccompiler.py index 837ce5092..2825a899b 100644 --- a/numpy/distutils/unixccompiler.py +++ b/numpy/distutils/unixccompiler.py @@ -2,7 +2,7 @@ unixccompiler - can handle very long argument lists for ar. """ -from __future__ import division +from __future__ import division, absolute_import import os @@ -12,7 +12,7 @@ from numpy.distutils.ccompiler import replace_method from numpy.distutils.compat import get_exception if sys.version_info[0] < 3: - import log + from . import log else: from numpy.distutils import log diff --git a/numpy/doc/__init__.py b/numpy/doc/__init__.py index 19b3d87db..028d0c343 100644 --- a/numpy/doc/__init__.py +++ b/numpy/doc/__init__.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os diff --git a/numpy/doc/basics.py b/numpy/doc/basics.py index d50388282..b56d61380 100644 --- a/numpy/doc/basics.py +++ b/numpy/doc/basics.py @@ -136,5 +136,5 @@ value is inside an array or not. NumPy scalars also have many of the same methods arrays do. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/broadcasting.py b/numpy/doc/broadcasting.py index be6cde0bd..bbbd5bdcc 100644 --- a/numpy/doc/broadcasting.py +++ b/numpy/doc/broadcasting.py @@ -175,5 +175,5 @@ See `this article <http://www.scipy.org/EricsBroadcastingDoc>`_ for illustrations of broadcasting concepts. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/byteswapping.py b/numpy/doc/byteswapping.py index 395c858ed..df767f1bc 100644 --- a/numpy/doc/byteswapping.py +++ b/numpy/doc/byteswapping.py @@ -135,5 +135,5 @@ the previous operations: False """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/constants.py b/numpy/doc/constants.py index 10f41a7ba..5fe93fa2b 100644 --- a/numpy/doc/constants.py +++ b/numpy/doc/constants.py @@ -10,7 +10,7 @@ Numpy includes several constants: # # Note: the docstring is autogenerated. # -from __future__ import division +from __future__ import division, absolute_import import textwrap, re diff --git a/numpy/doc/creation.py b/numpy/doc/creation.py index f14b163e6..045b476e3 100644 --- a/numpy/doc/creation.py +++ b/numpy/doc/creation.py @@ -141,5 +141,5 @@ random values, and some utility functions to generate special matrices (e.g. diagonal). """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/glossary.py b/numpy/doc/glossary.py index 35adfc820..02b291b64 100644 --- a/numpy/doc/glossary.py +++ b/numpy/doc/glossary.py @@ -415,5 +415,5 @@ Glossary and f2py (which wraps Fortran). """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/howtofind.py b/numpy/doc/howtofind.py index 8e6793c48..e456a7422 100644 --- a/numpy/doc/howtofind.py +++ b/numpy/doc/howtofind.py @@ -7,5 +7,5 @@ How to Find Stuff How to find things in NumPy. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/indexing.py b/numpy/doc/indexing.py index 84f300dcd..821240efd 100644 --- a/numpy/doc/indexing.py +++ b/numpy/doc/indexing.py @@ -405,5 +405,5 @@ converted to an array as a list would be. As an example: :: 40 """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/internals.py b/numpy/doc/internals.py index d7b6d3c93..ed2991a32 100644 --- a/numpy/doc/internals.py +++ b/numpy/doc/internals.py @@ -160,5 +160,5 @@ when accessing elements of an array. Granted, it goes against the grain, but it is more in line with Python semantics and the natural order of the data. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/io.py b/numpy/doc/io.py index 4ee4c7c2f..a212b9697 100644 --- a/numpy/doc/io.py +++ b/numpy/doc/io.py @@ -7,5 +7,5 @@ Array I/O Placeholder for array I/O documentation. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/jargon.py b/numpy/doc/jargon.py index 3bf4d5070..684674816 100644 --- a/numpy/doc/jargon.py +++ b/numpy/doc/jargon.py @@ -7,5 +7,5 @@ Jargon Placeholder for computer science, engineering and other jargon. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/methods_vs_functions.py b/numpy/doc/methods_vs_functions.py index 902ec54d0..7090190c0 100644 --- a/numpy/doc/methods_vs_functions.py +++ b/numpy/doc/methods_vs_functions.py @@ -7,5 +7,5 @@ Methods vs. Functions Placeholder for Methods vs. Functions documentation. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/misc.py b/numpy/doc/misc.py index 9195ebb5a..a16698a20 100644 --- a/numpy/doc/misc.py +++ b/numpy/doc/misc.py @@ -226,5 +226,5 @@ Interfacing to C++: 5) SIP (used mainly in PyQT) """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/performance.py b/numpy/doc/performance.py index 711dd3153..e2ca2c53e 100644 --- a/numpy/doc/performance.py +++ b/numpy/doc/performance.py @@ -7,5 +7,5 @@ Performance Placeholder for Improving Performance documentation. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/structured_arrays.py b/numpy/doc/structured_arrays.py index eeb8a949f..cd308c1cf 100644 --- a/numpy/doc/structured_arrays.py +++ b/numpy/doc/structured_arrays.py @@ -221,5 +221,5 @@ You can find some more information on recarrays and structured arrays <http://www.scipy.org/Cookbook/Recarray>`_. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/subclassing.py b/numpy/doc/subclassing.py index 19bdd425f..8734a0567 100644 --- a/numpy/doc/subclassing.py +++ b/numpy/doc/subclassing.py @@ -557,5 +557,5 @@ how this can work, have a look at the ``memmap`` class in """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/doc/ufuncs.py b/numpy/doc/ufuncs.py index d566ee98a..a1de5681f 100644 --- a/numpy/doc/ufuncs.py +++ b/numpy/doc/ufuncs.py @@ -135,5 +135,5 @@ results in an error. There are two alternatives: a convenient way to apply these operators. """ -from __future__ import division +from __future__ import division, absolute_import diff --git a/numpy/dual.py b/numpy/dual.py index 15b175b92..481e42d0c 100644 --- a/numpy/dual.py +++ b/numpy/dual.py @@ -10,7 +10,7 @@ Numpy. .. _Scipy : http://www.scipy.org """ -from __future__ import division +from __future__ import division, absolute_import # This module should be used for functions both in numpy and scipy if # you want to use the numpy version if available but the scipy version diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py index 12add2153..951544588 100644 --- a/numpy/f2py/__init__.py +++ b/numpy/f2py/__init__.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import __all__ = ['run_main','compile','f2py_testing'] @@ -7,11 +7,11 @@ import os import sys import commands -import f2py2e -import f2py_testing -import diagnose +from . import f2py2e +from . import f2py_testing +from . import diagnose -from info import __doc__ +from .info import __doc__ run_main = f2py2e.run_main main = f2py2e.main diff --git a/numpy/f2py/__version__.py b/numpy/f2py/__version__.py index 2f842c89d..44791aa37 100644 --- a/numpy/f2py/__version__.py +++ b/numpy/f2py/__version__.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import major = 2 diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py index 0f68953ad..5b13747f1 100644 --- a/numpy/f2py/auxfuncs.py +++ b/numpy/f2py/auxfuncs.py @@ -14,17 +14,17 @@ $Date: 2005/07/24 19:01:55 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.65 $"[10:-1] -import __version__ +from . import __version__ f2py_version = __version__.version import pprint import sys import types -import cfuncs +from . import cfuncs errmess=sys.stderr.write @@ -522,7 +522,7 @@ def getcallprotoargument(rout,cb_map={}): if hascallstatement(rout): outmess('warning: callstatement is defined without callprotoargument\n') return - from capi_maps import getctype + from .capi_maps import getctype arg_types,arg_types2 = [],[] if l_and(isstringfunction,l_not(isfunction_wrap))(rout): arg_types.extend(['char*','size_t']) diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py index d82b2c3f5..117ea2233 100644 --- a/numpy/f2py/capi_maps.py +++ b/numpy/f2py/capi_maps.py @@ -11,20 +11,20 @@ $Date: 2005/05/06 10:57:33 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.60 $"[10:-1] -import __version__ +from . import __version__ f2py_version = __version__.version import copy import re import os import sys -from auxfuncs import * -from crackfortran import markoutercomma -import cb_rules +from .auxfuncs import * +from .crackfortran import markoutercomma +from . import cb_rules # Numarray and Numeric users should set this False using_newcore = True diff --git a/numpy/f2py/cb_rules.py b/numpy/f2py/cb_rules.py index 05404add2..bc565a904 100644 --- a/numpy/f2py/cb_rules.py +++ b/numpy/f2py/cb_rules.py @@ -13,11 +13,11 @@ $Date: 2005/07/20 11:27:58 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.53 $"[10:-1] -import __version__ +from . import __version__ f2py_version = __version__.version @@ -28,8 +28,8 @@ errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint -from auxfuncs import * -import cfuncs +from .auxfuncs import * +from . import cfuncs ################## Rules for callback function ############## @@ -416,7 +416,7 @@ def buildcallbacks(m): def buildcallback(rout,um): global cb_map - import capi_maps + from . import capi_maps outmess('\tConstructing call-back function "cb_%s_in_%s"\n'%(rout['name'],um)) args,depargs=getargs(rout) diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py index ccadd94e3..a0110c530 100644 --- a/numpy/f2py/cfuncs.py +++ b/numpy/f2py/cfuncs.py @@ -14,11 +14,11 @@ $Date: 2005/05/06 11:42:34 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.75 $"[10:-1] -import __version__ +from . import __version__ f2py_version = __version__.version import types @@ -1117,7 +1117,7 @@ capi_fail: """ def buildcfuncs(): - from capi_maps import c2capi_map + from .capi_maps import c2capi_map for k in c2capi_map.keys(): m='pyarr_from_p_%s1'%k cppmacros[m]='#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))'%(m,c2capi_map[k]) diff --git a/numpy/f2py/common_rules.py b/numpy/f2py/common_rules.py index db7a6ee6d..aec0ef1b1 100644 --- a/numpy/f2py/common_rules.py +++ b/numpy/f2py/common_rules.py @@ -13,11 +13,11 @@ $Date: 2005/05/06 10:57:33 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.19 $"[10:-1] -import __version__ +from . import __version__ f2py_version = __version__.version import pprint @@ -26,10 +26,10 @@ errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint -from auxfuncs import * -import capi_maps -import func2subr -from crackfortran import rmbadname +from .auxfuncs import * +from . import capi_maps +from . import func2subr +from .crackfortran import rmbadname ############## def findcommonblocks(block,top=1): diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 76e113a67..2a7f137d2 100755 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -138,11 +138,11 @@ TODO: The above may be solved by creating appropriate preprocessor program, for example. """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.177 $"[10:-1] import platform -import __version__ +from . import __version__ f2py_version = __version__.version # @@ -153,7 +153,7 @@ import re import pprint import os import copy -from auxfuncs import * +from .auxfuncs import * # Global flags: strictf77=1 # Ignore `!' comments unless line[0]=='!' @@ -292,7 +292,7 @@ def readfortrancode(ffile,dowithline=show,istop=1): mline_mark = re.compile(r".*?'''") if istop: dowithline('',-1) ll,l1='','' - spacedigits=[' ']+map(str,range(10)) + spacedigits=[' ']+map(str,list(range(10))) filepositiontext='' fin=fileinput.FileInput(ffile) while 1: diff --git a/numpy/f2py/diagnose.py b/numpy/f2py/diagnose.py index e7759b6dd..59ef5205b 100644 --- a/numpy/f2py/diagnose.py +++ b/numpy/f2py/diagnose.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/f2py/doc/collectinput.py b/numpy/f2py/doc/collectinput.py index 5e98c8350..078da8eeb 100755 --- a/numpy/f2py/doc/collectinput.py +++ b/numpy/f2py/doc/collectinput.py @@ -19,7 +19,7 @@ Usage: collectinput # in and out are stdin and stdout """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "0.0" diff --git a/numpy/f2py/docs/pytest.py b/numpy/f2py/docs/pytest.py index b49dc764a..40d6b0c5e 100644 --- a/numpy/f2py/docs/pytest.py +++ b/numpy/f2py/docs/pytest.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import #File: pytest.py import Numeric diff --git a/numpy/f2py/docs/usersguide/setup_example.py b/numpy/f2py/docs/usersguide/setup_example.py index 911dc3324..e80bc493b 100644 --- a/numpy/f2py/docs/usersguide/setup_example.py +++ b/numpy/f2py/docs/usersguide/setup_example.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # File: setup_example.py diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py index 235fcb75a..aee8afba0 100755 --- a/numpy/f2py/f2py2e.py +++ b/numpy/f2py/f2py2e.py @@ -14,9 +14,9 @@ $Date: 2005/05/06 08:31:19 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import -import __version__ +from . import __version__ f2py_version = __version__.version import sys @@ -28,12 +28,12 @@ errmess=sys.stderr.write #outmess=sys.stdout.write show=pprint.pprint -import crackfortran -import rules -import cb_rules -import auxfuncs -import cfuncs -import f90mod_rules +from . import crackfortran +from . import rules +from . import cb_rules +from . import auxfuncs +from . import cfuncs +from . import f90mod_rules outmess = auxfuncs.outmess diff --git a/numpy/f2py/f2py_testing.py b/numpy/f2py/f2py_testing.py index 73eb2caed..b0f396ad4 100644 --- a/numpy/f2py/f2py_testing.py +++ b/numpy/f2py/f2py_testing.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys import re diff --git a/numpy/f2py/f90mod_rules.py b/numpy/f2py/f90mod_rules.py index 3a80eb8f4..bc571371b 100644 --- a/numpy/f2py/f90mod_rules.py +++ b/numpy/f2py/f90mod_rules.py @@ -13,7 +13,7 @@ $Date: 2005/02/03 19:30:23 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.27 $"[10:-1] @@ -25,11 +25,11 @@ errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint -from auxfuncs import * +from .auxfuncs import * import numpy as np -import capi_maps -import func2subr -from crackfortran import undo_rmbadname, undo_rmbadname1 +from . import capi_maps +from . import func2subr +from .crackfortran import undo_rmbadname, undo_rmbadname1 options={} @@ -84,7 +84,7 @@ fgetdims2_sa="""\ def buildhooks(pymod): global fgetdims1,fgetdims2 - import rules + from . import rules ret = {'f90modhooks':[],'initf90modhooks':[],'body':[], 'need':['F_FUNC','arrayobject.h'], 'separatorsfor':{'includes0':'\n','includes':'\n'}, diff --git a/numpy/f2py/func2subr.py b/numpy/f2py/func2subr.py index eb72c76c9..7597e43ae 100644 --- a/numpy/f2py/func2subr.py +++ b/numpy/f2py/func2subr.py @@ -13,7 +13,7 @@ $Date: 2004/11/26 11:13:06 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.16 $"[10:-1] @@ -26,7 +26,7 @@ errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint -from auxfuncs import * +from .auxfuncs import * def var2fixfortran(vars,a,fa=None,f90mode=None): if fa is None: fa = a diff --git a/numpy/f2py/info.py b/numpy/f2py/info.py index b976fb2ea..07a750588 100644 --- a/numpy/f2py/info.py +++ b/numpy/f2py/info.py @@ -1,6 +1,6 @@ """Fortran to Python Interface Generator. """ -from __future__ import division +from __future__ import division, absolute_import postpone_import = True diff --git a/numpy/f2py/rules.py b/numpy/f2py/rules.py index b04f54e16..38c43b4ae 100644 --- a/numpy/f2py/rules.py +++ b/numpy/f2py/rules.py @@ -50,11 +50,11 @@ $Date: 2005/08/30 08:58:42 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.129 $"[10:-1] -import __version__ +from . import __version__ f2py_version = __version__.version import pprint @@ -66,14 +66,14 @@ errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint -from auxfuncs import * -import capi_maps -from capi_maps import * -import cfuncs -import common_rules -import use_rules -import f90mod_rules -import func2subr +from .auxfuncs import * +from . import capi_maps +from .capi_maps import * +from . import cfuncs +from . import common_rules +from . import use_rules +from . import f90mod_rules +from . import func2subr options={} sepdict={} diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index ff8c16cd1..586833e68 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import unittest import os diff --git a/numpy/f2py/tests/test_assumed_shape.py b/numpy/f2py/tests/test_assumed_shape.py index 728c034ec..19a557530 100644 --- a/numpy/f2py/tests/test_assumed_shape.py +++ b/numpy/f2py/tests/test_assumed_shape.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import math diff --git a/numpy/f2py/tests/test_callback.py b/numpy/f2py/tests/test_callback.py index f903fbcb4..51b1bb1b4 100644 --- a/numpy/f2py/tests/test_callback.py +++ b/numpy/f2py/tests/test_callback.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy import array diff --git a/numpy/f2py/tests/test_kind.py b/numpy/f2py/tests/test_kind.py index 56a747096..d24099b05 100644 --- a/numpy/f2py/tests/test_kind.py +++ b/numpy/f2py/tests/test_kind.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import math diff --git a/numpy/f2py/tests/test_mixed.py b/numpy/f2py/tests/test_mixed.py index dc29d2b5d..d62098ab4 100644 --- a/numpy/f2py/tests/test_mixed.py +++ b/numpy/f2py/tests/test_mixed.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import math diff --git a/numpy/f2py/tests/test_return_character.py b/numpy/f2py/tests/test_return_character.py index fd8355ac3..5a68bec72 100644 --- a/numpy/f2py/tests/test_return_character.py +++ b/numpy/f2py/tests/test_return_character.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy import array diff --git a/numpy/f2py/tests/test_return_complex.py b/numpy/f2py/tests/test_return_complex.py index 4cdc03993..00ba1cfe6 100644 --- a/numpy/f2py/tests/test_return_complex.py +++ b/numpy/f2py/tests/test_return_complex.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy import array diff --git a/numpy/f2py/tests/test_return_integer.py b/numpy/f2py/tests/test_return_integer.py index a1af6b932..6c55cc1b9 100644 --- a/numpy/f2py/tests/test_return_integer.py +++ b/numpy/f2py/tests/test_return_integer.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy import array diff --git a/numpy/f2py/tests/test_return_logical.py b/numpy/f2py/tests/test_return_logical.py index 1c8dce532..af35c50d1 100644 --- a/numpy/f2py/tests/test_return_logical.py +++ b/numpy/f2py/tests/test_return_logical.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy import array diff --git a/numpy/f2py/tests/test_return_real.py b/numpy/f2py/tests/test_return_real.py index 943a4972d..0ea4373fb 100644 --- a/numpy/f2py/tests/test_return_real.py +++ b/numpy/f2py/tests/test_return_real.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy import array diff --git a/numpy/f2py/tests/test_size.py b/numpy/f2py/tests/test_size.py index 72443b4f6..1a41ce972 100644 --- a/numpy/f2py/tests/test_size.py +++ b/numpy/f2py/tests/test_size.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import math diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py index 0584ae188..0da4bc310 100644 --- a/numpy/f2py/tests/util.py +++ b/numpy/f2py/tests/util.py @@ -5,7 +5,7 @@ Utility functions for - detecting if compilers are present """ -from __future__ import division +from __future__ import division, absolute_import import os import sys @@ -58,7 +58,7 @@ def get_module_dir(): def get_temp_module_name(): # Assume single-threaded, and the module dir usable only by this thread d = get_module_dir() - for j in xrange(5403, 9999999): + for j in range(5403, 9999999): name = "_test_ext_module_%d" % j fn = os.path.join(d, name) if name not in sys.modules and not os.path.isfile(fn+'.py'): diff --git a/numpy/f2py/use_rules.py b/numpy/f2py/use_rules.py index e47dfc6e5..c027baef8 100644 --- a/numpy/f2py/use_rules.py +++ b/numpy/f2py/use_rules.py @@ -15,7 +15,7 @@ $Date: 2000/09/10 12:35:43 $ Pearu Peterson """ -from __future__ import division +from __future__ import division, absolute_import __version__ = "$Revision: 1.3 $"[10:-1] @@ -27,7 +27,7 @@ errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint -from auxfuncs import * +from .auxfuncs import * ############## usemodule_rules={ diff --git a/numpy/fft/__init__.py b/numpy/fft/__init__.py index 6cfa535fb..001ac59b0 100644 --- a/numpy/fft/__init__.py +++ b/numpy/fft/__init__.py @@ -1,10 +1,10 @@ -from __future__ import division +from __future__ import division, absolute_import # To get sub-modules -from info import __doc__ +from .info import __doc__ -from fftpack import * -from helper import * +from .fftpack import * +from .helper import * from numpy.testing import Tester test = Tester().test diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index 54d071884..59ab5d9db 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -30,14 +30,14 @@ The underlying code for these functions is an f2c-translated and modified version of the FFTPACK routines. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['fft','ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn', 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn'] from numpy.core import asarray, zeros, swapaxes, shape, conjugate, \ take -import fftpack_lite as fftpack +from . import fftpack_lite as fftpack _fft_cache = {} _real_fft_cache = {} @@ -511,7 +511,7 @@ def _cook_nd_args(a, s=None, axes=None, invreal=0): shapeless = 0 s = list(s) if axes is None: - axes = range(-len(s), 0) + axes = list(range(-len(s), 0)) if len(s) != len(axes): raise ValueError("Shape and axes have different lengths.") if invreal and shapeless: @@ -522,7 +522,7 @@ def _cook_nd_args(a, s=None, axes=None, invreal=0): def _raw_fftnd(a, s=None, axes=None, function=fft): a = asarray(a) s, axes = _cook_nd_args(a, s, axes) - itl = range(len(axes)) + itl = list(range(len(axes))) itl.reverse() for ii in itl: a = function(a, n=s[ii], axis=axes[ii]) diff --git a/numpy/fft/fftpack_litemodule.c b/numpy/fft/fftpack_litemodule.c index 499c72828..6f6a6c9f3 100644 --- a/numpy/fft/fftpack_litemodule.c +++ b/numpy/fft/fftpack_litemodule.c @@ -45,10 +45,12 @@ fftpack_cfftf(PyObject *NPY_UNUSED(self), PyObject *args) nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_DATA(data); NPY_SIGINT_ON; + Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { cfftf(npts, dptr, wsave); dptr += npts*2; } + Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; @@ -96,10 +98,12 @@ fftpack_cfftb(PyObject *NPY_UNUSED(self), PyObject *args) nrepeats = PyArray_SIZE(data)/npts; dptr = (double *)PyArray_DATA(data); NPY_SIGINT_ON; + Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { cfftb(npts, dptr, wsave); dptr += npts*2; } + Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); return (PyObject *)data; @@ -131,7 +135,9 @@ fftpack_cffti(PyObject *NPY_UNUSED(self), PyObject *args) } NPY_SIGINT_ON; + Py_BEGIN_ALLOW_THREADS; cffti(n, (double *)PyArray_DATA((PyArrayObject*)op)); + Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; return (PyObject *)op; @@ -183,6 +189,7 @@ fftpack_rfftf(PyObject *NPY_UNUSED(self), PyObject *args) NPY_SIGINT_ON; + Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr+1), dptr, npts*sizeof(double)); rfftf(npts, rptr+1, wsave); @@ -191,6 +198,7 @@ fftpack_rfftf(PyObject *NPY_UNUSED(self), PyObject *args) rptr += rstep; dptr += npts; } + Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); @@ -245,6 +253,7 @@ fftpack_rfftb(PyObject *NPY_UNUSED(self), PyObject *args) dptr = (double *)PyArray_DATA(data); NPY_SIGINT_ON; + Py_BEGIN_ALLOW_THREADS; for (i = 0; i < nrepeats; i++) { memcpy((char *)(rptr + 1), (dptr + 2), (npts - 1)*sizeof(double)); rptr[0] = dptr[0]; @@ -252,6 +261,7 @@ fftpack_rfftb(PyObject *NPY_UNUSED(self), PyObject *args) rptr += npts; dptr += npts*2; } + Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; PyArray_Free(op2, (char *)wsave); Py_DECREF(data); @@ -285,7 +295,9 @@ fftpack_rffti(PyObject *NPY_UNUSED(self), PyObject *args) return NULL; } NPY_SIGINT_ON; + Py_BEGIN_ALLOW_THREADS; rffti(n, (double *)PyArray_DATA((PyArrayObject*)op)); + Py_END_ALLOW_THREADS; NPY_SIGINT_OFF; return (PyObject *)op; diff --git a/numpy/fft/helper.py b/numpy/fft/helper.py index 763d6684b..910ccc9a2 100644 --- a/numpy/fft/helper.py +++ b/numpy/fft/helper.py @@ -2,7 +2,7 @@ Discrete Fourier Transforms - helper.py """ -from __future__ import division +from __future__ import division, absolute_import # Created by Pearu Peterson, September 2002 @@ -60,7 +60,7 @@ def fftshift(x, axes=None): tmp = asarray(x) ndim = len(tmp.shape) if axes is None: - axes = range(ndim) + axes = list(range(ndim)) elif isinstance(axes, (int, nt.integer)): axes = (axes,) y = tmp @@ -108,7 +108,7 @@ def ifftshift(x, axes=None): tmp = asarray(x) ndim = len(tmp.shape) if axes is None: - axes = range(ndim) + axes = list(range(ndim)) elif isinstance(axes, (int, nt.integer)): axes = (axes,) y = tmp diff --git a/numpy/fft/info.py b/numpy/fft/info.py index 9fb98eda6..6b5a1db79 100644 --- a/numpy/fft/info.py +++ b/numpy/fft/info.py @@ -174,6 +174,6 @@ Examples For examples, see the various functions. """ -from __future__ import division +from __future__ import division, absolute_import depends = ['core'] diff --git a/numpy/fft/tests/test_fftpack.py b/numpy/fft/tests/test_fftpack.py index dceb3bd89..b592d788d 100644 --- a/numpy/fft/tests/test_fftpack.py +++ b/numpy/fft/tests/test_fftpack.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal diff --git a/numpy/fft/tests/test_helper.py b/numpy/fft/tests/test_helper.py index b20e6ddc3..a57cbd81a 100644 --- a/numpy/fft/tests/test_helper.py +++ b/numpy/fft/tests/test_helper.py @@ -4,7 +4,7 @@ Copied from fftpack.helper by Pearu Peterson, October 2005 """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 5679a2dc8..37c06c014 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -1,26 +1,26 @@ -from __future__ import division +from __future__ import division, absolute_import -from info import __doc__ +from .info import __doc__ from numpy.version import version as __version__ -from type_check import * -from index_tricks import * -from function_base import * -from shape_base import * -from stride_tricks import * -from twodim_base import * -from ufunclike import * +from .type_check import * +from .index_tricks import * +from .function_base import * +from .shape_base import * +from .stride_tricks import * +from .twodim_base import * +from .ufunclike import * -import scimath as emath -from polynomial import * +from . import scimath as emath +from .polynomial import * #import convertcode -from utils import * -from arraysetops import * -from npyio import * -from financial import * +from .utils import * +from .arraysetops import * +from .npyio import * +from .financial import * import math -from arrayterator import * -from arraypad import * +from .arrayterator import * +from .arraypad import * __all__ = ['emath','math'] __all__ += type_check.__all__ diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py index d5424e8d3..db97c5507 100644 --- a/numpy/lib/_datasource.py +++ b/numpy/lib/_datasource.py @@ -31,7 +31,7 @@ Example:: >>> fp.close() """ -from __future__ import division +from __future__ import division, absolute_import __docformat__ = "restructuredtext en" diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py index dc07c3cd9..8054c2662 100644 --- a/numpy/lib/_iotools.py +++ b/numpy/lib/_iotools.py @@ -1,7 +1,7 @@ """A collection of functions designed to help I/O with ascii files. """ -from __future__ import division +from __future__ import division, absolute_import __docformat__ = "restructuredtext en" diff --git a/numpy/lib/arraypad.py b/numpy/lib/arraypad.py index 042f587e0..31bf609f5 100644 --- a/numpy/lib/arraypad.py +++ b/numpy/lib/arraypad.py @@ -3,7 +3,7 @@ The arraypad module contains a group of functions to pad values onto the edges of an n-dimensional array. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np @@ -760,7 +760,7 @@ def pad(array, pad_width, mode=None, **kwargs): function = mode # Create a new padded array - rank = range(len(narray.shape)) + rank = list(range(len(narray.shape))) total_dim_increase = [np.sum(pad_width[i]) for i in rank] offset_slices = [slice(pad_width[i][0], pad_width[i][0] + narray.shape[i]) diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index 61bb81721..e3a39342f 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -24,7 +24,7 @@ To do: Optionally return indices analogously to unique for all functions. :Author: Robert Cimrman """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique', 'in1d'] diff --git a/numpy/lib/arrayterator.py b/numpy/lib/arrayterator.py index 6f6953a22..b71e9a123 100644 --- a/numpy/lib/arrayterator.py +++ b/numpy/lib/arrayterator.py @@ -7,7 +7,7 @@ an array object, and when iterated it will return sub-arrays with at most a user-specified number of elements. """ -from __future__ import division +from __future__ import division, absolute_import from operator import mul diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index 5887a9224..2a3295bfe 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -8,7 +8,7 @@ broadcasting and being able to be called with scalars or arrays (or other sequences). """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np diff --git a/numpy/lib/format.py b/numpy/lib/format.py index 724125f1d..a4e8495b5 100644 --- a/numpy/lib/format.py +++ b/numpy/lib/format.py @@ -134,7 +134,7 @@ The ``.npy`` format, including reasons for creating it and a comparison of alternatives, is described fully in the "npy-format" NEP. """ -from __future__ import division +from __future__ import division, absolute_import import cPickle diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 914d7b580..fdcb4977a 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __docformat__ = "restructuredtext en" __all__ = ['select', 'piecewise', 'trim_zeros', 'copy', 'iterable', @@ -26,11 +26,11 @@ from numpy.core.fromnumeric import ravel, nonzero, choose, sort, mean from numpy.core.numerictypes import typecodes, number from numpy.core import atleast_1d, atleast_2d from numpy.lib.twodim_base import diag -from _compiled_base import _insert, add_docstring -from _compiled_base import digitize, bincount, interp as compiled_interp -from arraysetops import setdiff1d -from utils import deprecate -from _compiled_base import add_newdoc_ufunc +from ._compiled_base import _insert, add_docstring +from ._compiled_base import digitize, bincount, interp as compiled_interp +from .arraysetops import setdiff1d +from .utils import deprecate +from ._compiled_base import add_newdoc_ufunc import numpy as np import collections @@ -2589,7 +2589,7 @@ def _chbevl(x, vals): b0 = vals[0] b1 = 0.0 - for i in xrange(1,len(vals)): + for i in range(1,len(vals)): b2 = b1 b1 = b0 b0 = x*b1 - b2 + vals[i] @@ -3467,7 +3467,7 @@ def delete(arr, obj, axis=None): new[slobj] = arr[slobj2] elif isinstance(obj, slice): start, stop, step = obj.indices(N) - numtodel = len(xrange(start, stop, step)) + numtodel = len(list(range(start, stop, step))) if numtodel <= 0: if wrap: return wrap(new) diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index c77424f71..06ec80d23 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['ravel_multi_index', 'unravel_index', @@ -16,9 +16,9 @@ from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod, from numpy.core.numerictypes import find_common_type import math -import function_base +from . import function_base import numpy.matrixlib as matrix -from function_base import diff +from .function_base import diff from numpy.lib._compiled_base import ravel_multi_index, unravel_index from numpy.lib.stride_tricks import as_strided makemat = matrix.matrix @@ -307,7 +307,7 @@ class AxisConcatenator(object): k2 = ndmin-tempobj.ndim if (trans1d < 0): trans1d += k2 + 1 - defaxes = range(ndmin) + defaxes = list(range(ndmin)) k1 = trans1d axes = defaxes[:k1] + defaxes[k2:] + \ defaxes[k1:k2] @@ -532,30 +532,7 @@ class ndindex(object): (2, 0, 0) (2, 1, 0) - """ - # This is a hack to handle 0-d arrays correctly. - # Fixing nditer would be more work but should be done eventually, - # and then this entire __new__ method can be removed. - def __new__(cls, *shape): - if len(shape) == 1 and isinstance(shape[0], tuple): - shape = shape[0] - if len(shape) == 0: - class zero_dim_iter(object): - def __init__(self): - self._N = 1 - def __iter__(self): - return self - def ndincr(self): - self.next() - def next(self): - if self._N > 0: - self._N -= 1 - return () - raise StopIteration - return zero_dim_iter() - else: - return super(ndindex, cls).__new__(cls) - + """ def __init__(self, *shape): if len(shape) == 1 and isinstance(shape[0], tuple): shape = shape[0] diff --git a/numpy/lib/info.py b/numpy/lib/info.py index 1a2154951..de94f0a19 100644 --- a/numpy/lib/info.py +++ b/numpy/lib/info.py @@ -145,7 +145,7 @@ setdiff1d Set difference of 1D arrays with unique elements. ================ =================== """ -from __future__ import division +from __future__ import division, absolute_import depends = ['core','testing'] global_symbols = ['*'] diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index b6ae7ba01..ede54ecc7 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -1,11 +1,11 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['savetxt', 'loadtxt', 'genfromtxt', 'ndfromtxt', 'mafromtxt', 'recfromtxt', 'recfromcsv', 'load', 'loads', 'save', 'savez', 'savez_compressed', 'packbits', 'unpackbits', 'fromregex', 'DataSource'] import numpy as np -import format +from . import format import sys import os import re @@ -16,10 +16,10 @@ import weakref from operator import itemgetter from cPickle import load as _cload, loads -from _datasource import DataSource -from _compiled_base import packbits, unpackbits +from ._datasource import DataSource +from ._compiled_base import packbits, unpackbits -from _iotools import LineSplitter, NameValidator, StringConverter, \ +from ._iotools import LineSplitter, NameValidator, StringConverter, \ ConverterError, ConverterLockError, ConversionWarning, \ _is_string_like, has_nested_fields, flatten_dtype, \ easy_dtype, _bytes_to_name @@ -780,7 +780,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, defconv = _getconv(dtype) # Skip the first `skiprows` lines - for i in xrange(skiprows): + for i in range(skiprows): fh.next() # Read until we find a line with some values, and use @@ -804,7 +804,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters = [_getconv(dt) for dt in dtype_types] else: # All fields have the same dtype - converters = [defconv for i in xrange(N)] + converters = [defconv for i in range(N)] if N > 1: packing = [(N, tuple)] @@ -1339,7 +1339,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None, DeprecationWarning) skip_header = skiprows # Skip the first `skip_header` rows - for i in xrange(skip_header): + for i in range(skip_header): fhd.next() # Keep on until we find the first valid values diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index 0720f7345..3f5593432 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -2,7 +2,7 @@ Functions to operate on polynomials. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd', 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d', diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index c72cf2059..9f0beff59 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -5,7 +5,7 @@ Most of these functions were initially implemented by John Hunter for matplotlib They have been rewritten and extended for convenience. """ -from __future__ import division +from __future__ import division, absolute_import import sys import itertools diff --git a/numpy/lib/scimath.py b/numpy/lib/scimath.py index 00fc4bccd..0457e120c 100644 --- a/numpy/lib/scimath.py +++ b/numpy/lib/scimath.py @@ -15,7 +15,7 @@ Similarly, `sqrt`, other base logarithms, `power` and trig functions are correctly handled. See their respective docstrings for specific examples. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['sqrt', 'log', 'log2', 'logn','log10', 'power', 'arccos', 'arcsin', 'arctanh'] diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index fcabbace4..4f14a0c40 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['column_stack','row_stack', 'dstack','array_split','split','hsplit', 'vsplit','dsplit','apply_over_axes','expand_dims', @@ -74,7 +74,7 @@ def apply_along_axis(func1d,axis,arr,*args): % (axis,nd)) ind = [0]*(nd-1) i = zeros(nd,'O') - indlist = range(nd) + indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None,None) outshape = asarray(arr.shape).take(indlist) @@ -752,7 +752,7 @@ def kron(a,b): nd = nda result = outer(a,b).reshape(as_+bs) axis = nd-1 - for _ in xrange(nd): + for _ in range(nd): result = concatenate(result, axis=axis) wrapper = get_array_prepare(a, b) if wrapper is not None: diff --git a/numpy/lib/stride_tricks.py b/numpy/lib/stride_tricks.py index b82537024..70457c19f 100644 --- a/numpy/lib/stride_tricks.py +++ b/numpy/lib/stride_tricks.py @@ -5,7 +5,7 @@ An explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index f025b947e..e784e4296 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os from tempfile import mkdtemp, mkstemp, NamedTemporaryFile diff --git a/numpy/lib/tests/test__iotools.py b/numpy/lib/tests/test__iotools.py index 6416b6d7a..ebb01ad3a 100644 --- a/numpy/lib/tests/test__iotools.py +++ b/numpy/lib/tests/test__iotools.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys diff --git a/numpy/lib/tests/test_arraypad.py b/numpy/lib/tests/test_arraypad.py index e70c06aeb..0a87acb36 100644 --- a/numpy/lib/tests/test_arraypad.py +++ b/numpy/lib/tests/test_arraypad.py @@ -1,7 +1,7 @@ """Tests for the pad functions. """ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import TestCase, run_module_suite, assert_array_equal from numpy.testing import assert_raises, assert_array_almost_equal diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py index cab7a86b1..b0a2e429d 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -1,7 +1,7 @@ """Test functions for 1D array set operations. """ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * import numpy as np diff --git a/numpy/lib/tests/test_arrayterator.py b/numpy/lib/tests/test_arrayterator.py index 5064ab496..28feb4824 100644 --- a/numpy/lib/tests/test_arrayterator.py +++ b/numpy/lib/tests/test_arrayterator.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from operator import mul diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py index e06c50ef6..56681dbb4 100644 --- a/numpy/lib/tests/test_financial.py +++ b/numpy/lib/tests/test_financial.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * import numpy as np @@ -124,15 +124,15 @@ class TestFinancial(TestCase): assert_almost_equal(np.nper(0.075,-2000,0,100000.,[0,1]), [ 21.5449442 , 20.76156441], 4) - assert_almost_equal(np.ipmt(0.1/12,range(5), 24, 2000), + assert_almost_equal(np.ipmt(0.1/12,list(range(5)), 24, 2000), [-17.29165168, -16.66666667, -16.03647345, -15.40102862, -14.76028842], 4) - assert_almost_equal(np.ppmt(0.1/12,range(5), 24, 2000), + assert_almost_equal(np.ppmt(0.1/12,list(range(5)), 24, 2000), [-74.998201 , -75.62318601, -76.25337923, -76.88882405, -77.52956425], 4) - assert_almost_equal(np.ppmt(0.1/12,range(5), 24, 2000, 0, + assert_almost_equal(np.ppmt(0.1/12,list(range(5)), 24, 2000, 0, [0,0,1,'end','begin']), [-74.998201 , -75.62318601, -75.62318601, -76.88882405, -76.88882405], 4) diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index 320cef3d2..5c07da1c3 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import r''' Test the .npy file format. diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 25c498312..406bad40b 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import warnings import numpy as np @@ -887,7 +887,7 @@ class TestHistogramdd(TestCase): assert_array_equal(H, answer) Z = np.zeros((5, 5, 5)) - Z[range(5), range(5), range(5)] = 1. + Z[list(range(5)), list(range(5)), list(range(5))] = 1. H, edges = histogramdd([np.arange(5), np.arange(5), np.arange(5)], 5) assert_array_equal(H, Z) diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py index 2b42fdc2c..02516cab7 100644 --- a/numpy/lib/tests/test_index_tricks.py +++ b/numpy/lib/tests/test_index_tricks.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * import numpy as np diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 9144138d1..ab990976e 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys import gzip @@ -160,7 +160,7 @@ class TestSavezLoad(RoundtripTest, TestCase): errors = [] threads = [threading.Thread(target=writer, args=(errors,)) - for j in xrange(3)] + for j in range(3)] for t in threads: t.start() for t in threads: diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py index fc2b49c81..4a110d58e 100644 --- a/numpy/lib/tests/test_polynomial.py +++ b/numpy/lib/tests/test_polynomial.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import ''' >>> p = np.poly1d([1.,2,3]) diff --git a/numpy/lib/tests/test_recfunctions.py b/numpy/lib/tests/test_recfunctions.py index 6a0ad1609..f38a6914c 100644 --- a/numpy/lib/tests/test_recfunctions.py +++ b/numpy/lib/tests/test_recfunctions.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py index e0a3a424d..9e303d2b1 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy.testing.utils import _assert_valid_refcount diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py index 70c4d33ac..9aaf3d086 100644 --- a/numpy/lib/tests/test_shape_base.py +++ b/numpy/lib/tests/test_shape_base.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy.lib import * diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py index 0ac1c279b..b6408fe19 100644 --- a/numpy/lib/tests/test_stride_tricks.py +++ b/numpy/lib/tests/test_stride_tricks.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import * diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py index 702f9a6f5..e2d24464a 100644 --- a/numpy/lib/tests/test_twodim_base.py +++ b/numpy/lib/tests/test_twodim_base.py @@ -1,7 +1,7 @@ """Test functions for matrix module """ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * @@ -191,7 +191,7 @@ class TestHistogram2d(TestCase): assert_array_equal(H.T, answer) H = histogram2d(x, y, xedges)[0] assert_array_equal(H.T, answer) - H,xedges,yedges = histogram2d(range(10),range(10)) + H,xedges,yedges = histogram2d(list(range(10)),list(range(10))) assert_array_equal(H, eye(10,10)) assert_array_equal(xedges, np.linspace(0,9,11)) assert_array_equal(yedges, np.linspace(0,9,11)) diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py index c4f4a6299..c1204cec4 100644 --- a/numpy/lib/tests/test_type_check.py +++ b/numpy/lib/tests/test_type_check.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy.lib import * diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py index 0f688b021..d4505266c 100644 --- a/numpy/lib/tests/test_ufunclike.py +++ b/numpy/lib/tests/test_ufunclike.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * import numpy.core as nx diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py index 534806ff2..4b386e0b1 100644 --- a/numpy/lib/tests/test_utils.py +++ b/numpy/lib/tests/test_utils.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * import numpy.lib.utils as utils diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index 92df5306d..b2e74e07a 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -1,7 +1,7 @@ """ Basic functions for manipulating 2d arrays """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['diag','diagflat','eye','fliplr','flipud','rot90','tri','triu', 'tril','vander','histogram2d','mask_indices', diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index 895c4d406..b59cf13aa 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -1,7 +1,7 @@ """Automatically adapted for numpy Sep 19, 2005 by convertcode.py """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['iscomplexobj','isrealobj','imag','iscomplex', 'isreal','nan_to_num','real','real_if_close', @@ -11,7 +11,7 @@ __all__ = ['iscomplexobj','isrealobj','imag','iscomplex', import numpy.core.numeric as _nx from numpy.core.numeric import asarray, asanyarray, array, isnan, \ obj2sctype, zeros -from ufunclike import isneginf, isposinf +from .ufunclike import isneginf, isposinf _typecodes_by_elsize = 'GDFgdfQqLlIiHhBb?' diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index 8b85ef770..a71dab0d0 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -3,7 +3,7 @@ Module of functions that are like ufuncs in acting on arrays and optionally storing results in an output array. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['fix', 'isneginf', 'isposinf'] diff --git a/numpy/lib/user_array.py b/numpy/lib/user_array.py index 51ab10520..e6871f489 100644 --- a/numpy/lib/user_array.py +++ b/numpy/lib/user_array.py @@ -4,7 +4,7 @@ Try to inherit from the ndarray instead of using this class as this is not complete. """ -from __future__ import division +from __future__ import division, absolute_import from numpy.core import array, asarray, absolute, add, subtract, multiply, \ divide, remainder, power, left_shift, right_shift, bitwise_and, \ diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index d7492def8..ee49b41d6 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/linalg/__init__.py b/numpy/linalg/__init__.py index ed281abee..d0a5de983 100644 --- a/numpy/linalg/__init__.py +++ b/numpy/linalg/__init__.py @@ -42,12 +42,12 @@ LinAlgError Indicates a failed linear algebra operation =============== ========================================================== """ -from __future__ import division +from __future__ import division, absolute_import # To get sub-modules -from info import __doc__ +from .info import __doc__ -from linalg import * +from .linalg import * from numpy.testing import Tester test = Tester().test diff --git a/numpy/linalg/info.py b/numpy/linalg/info.py index 45b91db18..14d9ab1f7 100644 --- a/numpy/linalg/info.py +++ b/numpy/linalg/info.py @@ -32,6 +32,6 @@ Exceptions: - LinAlgError Indicates a failed linear algebra operation """ -from __future__ import division +from __future__ import division, absolute_import depends = ['core'] diff --git a/numpy/linalg/lapack_lite/clapack_scrub.py b/numpy/linalg/lapack_lite/clapack_scrub.py index 10ee543b9..22f818e91 100644 --- a/numpy/linalg/lapack_lite/clapack_scrub.py +++ b/numpy/linalg/lapack_lite/clapack_scrub.py @@ -1,5 +1,5 @@ #!/usr/bin/env python2.4 -from __future__ import division +from __future__ import division, absolute_import import sys, os from cStringIO import StringIO diff --git a/numpy/linalg/lapack_lite/fortran.py b/numpy/linalg/lapack_lite/fortran.py index 6fff72312..6aad0ba8c 100644 --- a/numpy/linalg/lapack_lite/fortran.py +++ b/numpy/linalg/lapack_lite/fortran.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import re import itertools diff --git a/numpy/linalg/lapack_lite/make_lite.py b/numpy/linalg/lapack_lite/make_lite.py index 1fea7c049..7e48a5a37 100755 --- a/numpy/linalg/lapack_lite/make_lite.py +++ b/numpy/linalg/lapack_lite/make_lite.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import import sys, os import fortran diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index 167e733fd..c66ab8c3a 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -8,7 +8,7 @@ version only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', @@ -226,7 +226,7 @@ def tensorsolve(a, b, axes=None): an = a.ndim if axes is not None: - allaxes = range(0, an) + allaxes = list(range(0, an)) for k in axes: allaxes.remove(k) allaxes.insert(an, k) diff --git a/numpy/linalg/tests/test_build.py b/numpy/linalg/tests/test_build.py index 4a151d3f4..0e7dc3629 100644 --- a/numpy/linalg/tests/test_build.py +++ b/numpy/linalg/tests/test_build.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from subprocess import call, PIPE, Popen import sys diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py index fb8f89fe9..6750f059d 100644 --- a/numpy/linalg/tests/test_linalg.py +++ b/numpy/linalg/tests/test_linalg.py @@ -1,6 +1,6 @@ """ Test functions for linalg module """ -from __future__ import division +from __future__ import division, absolute_import import sys diff --git a/numpy/linalg/tests/test_regression.py b/numpy/linalg/tests/test_regression.py index 9ca56e9ff..c3e01c383 100644 --- a/numpy/linalg/tests/test_regression.py +++ b/numpy/linalg/tests/test_regression.py @@ -1,6 +1,6 @@ """ Test functions for linalg module """ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * diff --git a/numpy/ma/__init__.py b/numpy/ma/__init__.py index 7388a7ce3..3113e538c 100644 --- a/numpy/ma/__init__.py +++ b/numpy/ma/__init__.py @@ -36,18 +36,18 @@ may now proceed to calculate the mean of the other values: invalid operation. """ -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' -import core -from core import * +from . import core +from .core import * -import extras -from extras import * +from . import extras +from .extras import * __all__ = ['core', 'extras'] __all__ += core.__all__ diff --git a/numpy/ma/bench.py b/numpy/ma/bench.py index df6933eb9..7500245c3 100644 --- a/numpy/ma/bench.py +++ b/numpy/ma/bench.py @@ -1,6 +1,6 @@ #! python # encoding: utf-8 -from __future__ import division +from __future__ import division, absolute_import import timeit #import IPython.ipapi diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 5f3c33dcc..3c7206e1c 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -20,7 +20,7 @@ Released for unlimited redistribution. """ # pylint: disable-msg=E1002 -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant" diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index 279f1e7e4..a22152729 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -8,7 +8,7 @@ A collection of utilities for `numpy.ma`. :version: $Id: extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' @@ -38,8 +38,8 @@ __all__ = ['apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d', import itertools import warnings -import core as ma -from core import MaskedArray, MAError, add, array, asarray, concatenate, count, \ +from . import core as ma +from .core import MaskedArray, MAError, add, array, asarray, concatenate, count, \ filled, getmask, getmaskarray, make_mask_descr, masked, masked_array, \ mask_or, nomask, ones, sort, zeros #from core import * @@ -337,7 +337,7 @@ def apply_along_axis(func1d, axis, arr, *args, **kwargs): % (axis, nd)) ind = [0] * (nd - 1) i = np.zeros(nd, 'O') - indlist = range(nd) + indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None, None) outshape = np.asarray(arr.shape).take(indlist) @@ -729,7 +729,7 @@ def compress_rowcols(x, axis=None): if m.all(): return nxarray([]) # Builds a list of rows/columns indices - (idxr, idxc) = (range(len(x)), range(x.shape[1])) + (idxr, idxc) = (list(range(len(x))), list(range(x.shape[1]))) masked = m.nonzero() if not axis: for i in np.unique(masked[0]): diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py index 084859d07..ae31986bc 100644 --- a/numpy/ma/mrecords.py +++ b/numpy/ma/mrecords.py @@ -8,7 +8,7 @@ and the masking of individual fields. :author: Pierre Gerard-Marchant """ -from __future__ import division +from __future__ import division, absolute_import #!!!: * We should make sure that no field is called '_mask','mask','_fieldmask', #!!!: or whatever restricted keywords. diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py index cf8f1111d..383e4a907 100644 --- a/numpy/ma/tests/test_core.py +++ b/numpy/ma/tests/test_core.py @@ -4,7 +4,7 @@ :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu """ -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant" @@ -381,7 +381,7 @@ class TestMaskedArray(TestCase): def test_pickling_subbaseclass(self): "Test pickling w/ a subclass of ndarray" import cPickle - a = array(np.matrix(range(10)), mask=[1, 0, 1, 0, 0] * 2) + a = array(np.matrix(list(range(10))), mask=[1, 0, 1, 0, 0] * 2) a_pickled = cPickle.loads(a.dumps()) assert_equal(a_pickled._mask, a._mask) assert_equal(a_pickled, a) @@ -2983,11 +2983,11 @@ class TestMaskedArrayFunctions(TestCase): def test_masked_otherfunctions(self): - assert_equal(masked_inside(range(5), 1, 3), [0, 199, 199, 199, 4]) - assert_equal(masked_outside(range(5), 1, 3), [199, 1, 2, 3, 199]) - assert_equal(masked_inside(array(range(5), mask=[1, 0, 0, 0, 0]), 1, 3).mask, [1, 1, 1, 1, 0]) - assert_equal(masked_outside(array(range(5), mask=[0, 1, 0, 0, 0]), 1, 3).mask, [1, 1, 0, 0, 1]) - assert_equal(masked_equal(array(range(5), mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 0]) + assert_equal(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4]) + assert_equal(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199]) + assert_equal(masked_inside(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 1, 3).mask, [1, 1, 1, 1, 0]) + assert_equal(masked_outside(array(list(range(5)), mask=[0, 1, 0, 0, 0]), 1, 3).mask, [1, 1, 0, 0, 1]) + assert_equal(masked_equal(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 0]) assert_equal(masked_not_equal(array([2, 2, 1, 2, 1], mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 1]) diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py index 3f25ac21c..c32e689c3 100644 --- a/numpy/ma/tests/test_extras.py +++ b/numpy/ma/tests/test_extras.py @@ -7,7 +7,7 @@ Adapted from the original test_ma by Pierre Gerard-Marchant :version: $Id: test_extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py index 4e59b8e41..d6f8d9765 100644 --- a/numpy/ma/tests/test_mrecords.py +++ b/numpy/ma/tests/test_mrecords.py @@ -5,7 +5,7 @@ :contact: pierregm_at_uga_dot_edu """ -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __revision__ = "$Revision: 3473 $" diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py index c9dbe4d4a..41f7779d9 100644 --- a/numpy/ma/tests/test_old_ma.py +++ b/numpy/ma/tests/test_old_ma.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy import types @@ -388,13 +388,13 @@ class TestMa(TestCase): assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) assert_(eq(masked_where(equal(x, 2), x), masked_equal(x, 2))) assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) - assert_(eq(masked_inside(range(5), 1, 3), [0, 199, 199, 199, 4])) - assert_(eq(masked_outside(range(5), 1, 3), [199, 1, 2, 3, 199])) - assert_(eq(masked_inside(array(range(5), mask=[1, 0, 0, 0, 0]), 1, 3).mask, + assert_(eq(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4])) + assert_(eq(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])) + assert_(eq(masked_inside(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 1, 3).mask, [1, 1, 1, 1, 0])) - assert_(eq(masked_outside(array(range(5), mask=[0, 1, 0, 0, 0]), 1, 3).mask, + assert_(eq(masked_outside(array(list(range(5)), mask=[0, 1, 0, 0, 0]), 1, 3).mask, [1, 1, 0, 0, 1])) - assert_(eq(masked_equal(array(range(5), mask=[1, 0, 0, 0, 0]), 2).mask, + assert_(eq(masked_equal(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 0])) assert_(eq(masked_not_equal(array([2, 2, 1, 2, 1], mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 1])) diff --git a/numpy/ma/tests/test_regression.py b/numpy/ma/tests/test_regression.py index 85c290160..e5fea0c52 100644 --- a/numpy/ma/tests/test_regression.py +++ b/numpy/ma/tests/test_regression.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * import numpy as np diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py index ce3d8c889..6b8ff0769 100644 --- a/numpy/ma/tests/test_subclassing.py +++ b/numpy/ma/tests/test_subclassing.py @@ -6,7 +6,7 @@ :version: $Id: test_subclassing.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' diff --git a/numpy/ma/testutils.py b/numpy/ma/testutils.py index 3707dcc16..882db2b89 100644 --- a/numpy/ma/testutils.py +++ b/numpy/ma/testutils.py @@ -5,7 +5,7 @@ :version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $ """ -from __future__ import division +from __future__ import division, absolute_import __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = "1.0" @@ -21,7 +21,7 @@ import numpy.core.umath as umath from numpy.testing import * import numpy.testing.utils as utils -from core import mask_or, getmask, masked_array, nomask, masked, filled, \ +from .core import mask_or, getmask, masked_array, nomask, masked, filled, \ equal, less #------------------------------------------------------------------------------ diff --git a/numpy/ma/timer_comparison.py b/numpy/ma/timer_comparison.py index adc1fa22b..549448689 100644 --- a/numpy/ma/timer_comparison.py +++ b/numpy/ma/timer_comparison.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import timeit diff --git a/numpy/ma/version.py b/numpy/ma/version.py index 73281311d..cf9a95572 100644 --- a/numpy/ma/version.py +++ b/numpy/ma/version.py @@ -1,14 +1,14 @@ """Version number """ -from __future__ import division +from __future__ import division, absolute_import version = '1.00' release = False if not release: - import core - import extras + from . import core + from . import extras revision = [core.__revision__.split(':')[-1][:-1].strip(), extras.__revision__.split(':')[-1][:-1].strip(),] version += '.dev%04i' % max([int(rev) for rev in revision]) diff --git a/numpy/matlib.py b/numpy/matlib.py index ae053373b..df683573f 100644 --- a/numpy/matlib.py +++ b/numpy/matlib.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.matrixlib.defmatrix import matrix, asmatrix diff --git a/numpy/matrixlib/__init__.py b/numpy/matrixlib/__init__.py index dc9a6bca9..bb826cd39 100644 --- a/numpy/matrixlib/__init__.py +++ b/numpy/matrixlib/__init__.py @@ -1,9 +1,9 @@ """Sub-package containing the matrix class and related functions. """ -from __future__ import division +from __future__ import division, absolute_import -from defmatrix import * +from .defmatrix import * __all__ = defmatrix.__all__ diff --git a/numpy/matrixlib/defmatrix.py b/numpy/matrixlib/defmatrix.py index 3ad4c826f..4ecce483c 100644 --- a/numpy/matrixlib/defmatrix.py +++ b/numpy/matrixlib/defmatrix.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] diff --git a/numpy/matrixlib/tests/test_defmatrix.py b/numpy/matrixlib/tests/test_defmatrix.py index 74c379d77..c67b447b8 100644 --- a/numpy/matrixlib/tests/test_defmatrix.py +++ b/numpy/matrixlib/tests/test_defmatrix.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * from numpy.core import * @@ -211,13 +211,13 @@ class TestAlgebra(TestCase): mA = matrix(A) B = identity(2) - for i in xrange(6): + for i in range(6): assert_(allclose((mA ** i).A, B)) B = dot(B, A) Ainv = linalg.inv(A) B = identity(2) - for i in xrange(6): + for i in range(6): assert_(allclose((mA ** -i).A, B)) B = dot(B, Ainv) diff --git a/numpy/matrixlib/tests/test_multiarray.py b/numpy/matrixlib/tests/test_multiarray.py index 6247a1c48..d58adb3a2 100644 --- a/numpy/matrixlib/tests/test_multiarray.py +++ b/numpy/matrixlib/tests/test_multiarray.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import * diff --git a/numpy/matrixlib/tests/test_numeric.py b/numpy/matrixlib/tests/test_numeric.py index 5539dac0d..7b690fbef 100644 --- a/numpy/matrixlib/tests/test_numeric.py +++ b/numpy/matrixlib/tests/test_numeric.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import assert_equal, TestCase from numpy.core import ones diff --git a/numpy/matrixlib/tests/test_regression.py b/numpy/matrixlib/tests/test_regression.py index ae352f09c..da5131bc6 100644 --- a/numpy/matrixlib/tests/test_regression.py +++ b/numpy/matrixlib/tests/test_regression.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * import numpy as np diff --git a/numpy/numarray/__init__.py b/numpy/numarray/__init__.py index 964ee2baa..f7a487cdf 100644 --- a/numpy/numarray/__init__.py +++ b/numpy/numarray/__init__.py @@ -1,18 +1,18 @@ -from __future__ import division +from __future__ import division, absolute_import -from util import * -from numerictypes import * -from functions import * -from ufuncs import * -from compat import * -from session import * +from .util import * +from .numerictypes import * +from .functions import * +from .ufuncs import * +from .compat import * +from .session import * -import util -import numerictypes -import functions -import ufuncs -import compat -import session +from . import util +from . import numerictypes +from . import functions +from . import ufuncs +from . import compat +from . import session __all__ = ['session', 'numerictypes'] __all__ += util.__all__ diff --git a/numpy/numarray/alter_code1.py b/numpy/numarray/alter_code1.py index 2393aff5a..09370549d 100644 --- a/numpy/numarray/alter_code1.py +++ b/numpy/numarray/alter_code1.py @@ -52,7 +52,7 @@ Makes the following changes: - .setimaginary() --> .imag """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc'] diff --git a/numpy/numarray/alter_code2.py b/numpy/numarray/alter_code2.py index 4d76222da..df248a924 100644 --- a/numpy/numarray/alter_code2.py +++ b/numpy/numarray/alter_code2.py @@ -5,7 +5,7 @@ with numpy FIXME: finish this. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = [] diff --git a/numpy/numarray/compat.py b/numpy/numarray/compat.py index 794a2d591..24e20be17 100644 --- a/numpy/numarray/compat.py +++ b/numpy/numarray/compat.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['NewAxis', 'ArrayType'] diff --git a/numpy/numarray/convolve.py b/numpy/numarray/convolve.py index 14c16f008..af7330fc7 100644 --- a/numpy/numarray/convolve.py +++ b/numpy/numarray/convolve.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import try: from stsci.convolve import * diff --git a/numpy/numarray/fft.py b/numpy/numarray/fft.py index 158c8807e..4adf1d3bb 100644 --- a/numpy/numarray/fft.py +++ b/numpy/numarray/fft.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.oldnumeric.fft import * import numpy.oldnumeric.fft as nof diff --git a/numpy/numarray/functions.py b/numpy/numarray/functions.py index 7242f2870..2492d5f3f 100644 --- a/numpy/numarray/functions.py +++ b/numpy/numarray/functions.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import # missing Numarray defined names (in from numarray import *) @@ -40,7 +40,7 @@ from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\ resize, searchsorted, shape, size, sort, swapaxes, trace, transpose import numpy as np -from numerictypes import typefrom +from .numerictypes import typefrom if sys.version_info[0] >= 3: import copyreg as copy_reg @@ -155,7 +155,7 @@ class FileSeekWarning(Warning): pass -STRICT, SLOPPY, WARN = range(3) +STRICT, SLOPPY, WARN = list(range(3)) _BLOCKSIZE=1024 @@ -204,8 +204,8 @@ def fromfile(infile, type=None, shape=None, sizing=STRICT, ##file whose size may be determined before allocation, should be ##quick -- only one allocation will be needed. - recsize = dtype.itemsize * np.product([i for i in shape if i != -1]) - blocksize = max(_BLOCKSIZE/recsize, 1)*recsize + 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: @@ -216,7 +216,7 @@ def fromfile(infile, type=None, shape=None, sizing=STRICT, except (AttributeError, IOError): initsize=blocksize else: - initsize=max(1,(endpos-curpos)/recsize)*recsize + initsize=max(1,(endpos-curpos)//recsize)*recsize buf = np.newbuffer(initsize) @@ -247,20 +247,33 @@ def fromfile(infile, type=None, shape=None, sizing=STRICT, except IOError: _warnings.warn("Could not rewind (IOError in seek)", FileSeekWarning) - datasize = (len(data)/recsize) * recsize + 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 + 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: @@ -405,7 +418,7 @@ def put(array, indices, values, axis=0, clipmode=RAISE): work[indices] = values work = work.swapaxes(0, axis) else: - def_axes = range(work.ndim) + def_axes = list(range(work.ndim)) for x in axis: def_axes.remove(x) axis = list(axis)+def_axes @@ -441,7 +454,7 @@ def take(array, indices, axis=0, outarr=None, clipmode=RAISE): return res return else: - def_axes = range(array.ndim) + def_axes = list(range(array.ndim)) for x in axis: def_axes.remove(x) axis = list(axis) + def_axes diff --git a/numpy/numarray/image.py b/numpy/numarray/image.py index 112fdac9e..bcfa09afd 100644 --- a/numpy/numarray/image.py +++ b/numpy/numarray/image.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import try: from stsci.image import * diff --git a/numpy/numarray/linear_algebra.py b/numpy/numarray/linear_algebra.py index 1c716e05b..3b92d09d1 100644 --- a/numpy/numarray/linear_algebra.py +++ b/numpy/numarray/linear_algebra.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.oldnumeric.linear_algebra import * diff --git a/numpy/numarray/ma.py b/numpy/numarray/ma.py index 2b820a98d..f220362ae 100644 --- a/numpy/numarray/ma.py +++ b/numpy/numarray/ma.py @@ -1,3 +1,3 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.oldnumeric.ma import * diff --git a/numpy/numarray/matrix.py b/numpy/numarray/matrix.py index 723613c63..bd10f8278 100644 --- a/numpy/numarray/matrix.py +++ b/numpy/numarray/matrix.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['Matrix'] diff --git a/numpy/numarray/mlab.py b/numpy/numarray/mlab.py index 70ccf077a..d530c8a05 100644 --- a/numpy/numarray/mlab.py +++ b/numpy/numarray/mlab.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.oldnumeric.mlab import * import numpy.oldnumeric.mlab as nom diff --git a/numpy/numarray/nd_image.py b/numpy/numarray/nd_image.py index a9a7ee1f4..d73788ed3 100644 --- a/numpy/numarray/nd_image.py +++ b/numpy/numarray/nd_image.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import try: from ndimage import * diff --git a/numpy/numarray/numerictypes.py b/numpy/numarray/numerictypes.py index ef1ccb2a3..b51706ec3 100644 --- a/numpy/numarray/numerictypes.py +++ b/numpy/numarray/numerictypes.py @@ -27,7 +27,7 @@ Exported symbols include: $Id: numerictypes.py,v 1.55 2005/12/01 16:22:03 jaytmiller Exp $ """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['NumericType','HasUInt64','typeDict','IsType', diff --git a/numpy/numarray/random_array.py b/numpy/numarray/random_array.py index 654f58346..6f56e9cf9 100644 --- a/numpy/numarray/random_array.py +++ b/numpy/numarray/random_array.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['ArgumentError', 'F', 'beta', 'binomial', 'chi_square', 'exponential', 'gamma', 'get_seed', 'multinomial', diff --git a/numpy/numarray/session.py b/numpy/numarray/session.py index fab80a1e2..32a28cca0 100644 --- a/numpy/numarray/session.py +++ b/numpy/numarray/session.py @@ -72,7 +72,7 @@ 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 +from __future__ import division, absolute_import __all__ = ['load', 'save'] diff --git a/numpy/numarray/ufuncs.py b/numpy/numarray/ufuncs.py index 357972c79..a5b72c3fb 100644 --- a/numpy/numarray/ufuncs.py +++ b/numpy/numarray/ufuncs.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not', diff --git a/numpy/numarray/util.py b/numpy/numarray/util.py index 819987cbf..acdb18fc8 100644 --- a/numpy/numarray/util.py +++ b/numpy/numarray/util.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import numpy as np diff --git a/numpy/oldnumeric/__init__.py b/numpy/oldnumeric/__init__.py index 5fc8f7c76..ff8c00885 100644 --- a/numpy/oldnumeric/__init__.py +++ b/numpy/oldnumeric/__init__.py @@ -1,7 +1,7 @@ """Don't add these to the __all__ variable though """ -from __future__ import division +from __future__ import division, absolute_import from numpy import * @@ -11,21 +11,21 @@ def _move_axis_to_0(a, axis): n = len(a.shape) if axis < 0: axis += n - axes = range(1, axis+1) + [0,] + range(axis+1, 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 * - -import compat -import precision -import functions -import misc -import ufuncs +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__ diff --git a/numpy/oldnumeric/alter_code1.py b/numpy/oldnumeric/alter_code1.py index 5eb1c99f2..f970994e4 100644 --- a/numpy/oldnumeric/alter_code1.py +++ b/numpy/oldnumeric/alter_code1.py @@ -29,7 +29,7 @@ Makes the following changes: isinstance(..., <type>) """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc'] diff --git a/numpy/oldnumeric/alter_code2.py b/numpy/oldnumeric/alter_code2.py index 61f285f63..6d33efd60 100644 --- a/numpy/oldnumeric/alter_code2.py +++ b/numpy/oldnumeric/alter_code2.py @@ -19,7 +19,7 @@ Makes the following changes: oldnumeric.random_array, and oldnumeric.fft """ -from __future__ import division +from __future__ import division, absolute_import #__all__ = ['convertfile', 'convertall', 'converttree'] __all__ = [] diff --git a/numpy/oldnumeric/array_printer.py b/numpy/oldnumeric/array_printer.py index 7c0428c14..f14872821 100644 --- a/numpy/oldnumeric/array_printer.py +++ b/numpy/oldnumeric/array_printer.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['array2string'] diff --git a/numpy/oldnumeric/arrayfns.py b/numpy/oldnumeric/arrayfns.py index 1db219d4a..03f816db8 100644 --- a/numpy/oldnumeric/arrayfns.py +++ b/numpy/oldnumeric/arrayfns.py @@ -1,7 +1,7 @@ """Backward compatible with arrayfns from Numeric. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span', diff --git a/numpy/oldnumeric/compat.py b/numpy/oldnumeric/compat.py index 0c18917d0..46c3c727f 100644 --- a/numpy/oldnumeric/compat.py +++ b/numpy/oldnumeric/compat.py @@ -1,7 +1,7 @@ """Compatibility module containing deprecated names. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['NewAxis', 'UFuncType', 'UfuncType', 'ArrayType', 'arraytype', @@ -16,7 +16,7 @@ __all__ = ['NewAxis', import numpy.core.multiarray as multiarray import numpy.core.umath as um from numpy.core.numeric import array -import functions +from . import functions import sys from cPickle import dump, dumps @@ -78,7 +78,7 @@ def load(fp): return loads(fp.read()) def _LoadArray(fp): - import typeconv + from . import typeconv ln = fp.readline().split() if ln[0][0] == 'A': ln[0] = ln[0][1:] typecode = ln[0][0] diff --git a/numpy/oldnumeric/fft.py b/numpy/oldnumeric/fft.py index ace7d27d9..7ea554e4a 100644 --- a/numpy/oldnumeric/fft.py +++ b/numpy/oldnumeric/fft.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['fft', 'fft2d', 'fftnd', 'hermite_fft', 'inverse_fft', 'inverse_fft2d', 'inverse_fftnd', diff --git a/numpy/oldnumeric/fix_default_axis.py b/numpy/oldnumeric/fix_default_axis.py index 262f82859..cefa67239 100644 --- a/numpy/oldnumeric/fix_default_axis.py +++ b/numpy/oldnumeric/fix_default_axis.py @@ -34,7 +34,7 @@ std mean """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['convertfile', 'convertall', 'converttree'] diff --git a/numpy/oldnumeric/functions.py b/numpy/oldnumeric/functions.py index 1e4daef5d..50c11e32c 100644 --- a/numpy/oldnumeric/functions.py +++ b/numpy/oldnumeric/functions.py @@ -1,12 +1,12 @@ """Functions that should behave the same as Numeric and need changing """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.core.multiarray as mu import numpy.core.numeric as nn -from typeconv import convtypecode, convtypecode2 +from .typeconv import convtypecode, convtypecode2 __all__ = ['take', 'repeat', 'sum', 'product', 'sometrue', 'alltrue', 'cumsum', 'cumproduct', 'compress', 'fromfunction', diff --git a/numpy/oldnumeric/linear_algebra.py b/numpy/oldnumeric/linear_algebra.py index a8600c77d..e850cd792 100644 --- a/numpy/oldnumeric/linear_algebra.py +++ b/numpy/oldnumeric/linear_algebra.py @@ -6,7 +6,7 @@ only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, dpotrf. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['LinAlgError', 'solve_linear_equations', 'inverse', 'cholesky_decomposition', 'eigenvalues', diff --git a/numpy/oldnumeric/ma.py b/numpy/oldnumeric/ma.py index 46af041ba..b449d619c 100644 --- a/numpy/oldnumeric/ma.py +++ b/numpy/oldnumeric/ma.py @@ -9,7 +9,7 @@ Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois. """ -from __future__ import division +from __future__ import division, absolute_import import types, sys diff --git a/numpy/oldnumeric/matrix.py b/numpy/oldnumeric/matrix.py index 9be08e93c..e76f8935f 100644 --- a/numpy/oldnumeric/matrix.py +++ b/numpy/oldnumeric/matrix.py @@ -1,12 +1,12 @@ """This module is for compatibility only. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['UserArray', 'squeeze', 'Matrix', 'asarray', 'dot', 'k', 'Numeric', 'LinearAlgebra', 'identity', 'multiply', 'types', 'string'] import types -from user_array import UserArray, asarray +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 diff --git a/numpy/oldnumeric/misc.py b/numpy/oldnumeric/misc.py index 3871d8251..8f1e1ae96 100644 --- a/numpy/oldnumeric/misc.py +++ b/numpy/oldnumeric/misc.py @@ -1,7 +1,7 @@ """Functions that already have the correct syntax or miscellaneous functions """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['sort', 'copy_reg', 'clip', 'rank', 'sign', 'shape', 'types', 'allclose', 'size', @@ -35,4 +35,4 @@ from numpy import sort, clip, rank, sign, shape, putmask, allclose, size,\ correlate as cross_correlate, \ place as insert -from array_printer import array2string +from .array_printer import array2string diff --git a/numpy/oldnumeric/mlab.py b/numpy/oldnumeric/mlab.py index e2ea78c02..d4063f65e 100644 --- a/numpy/oldnumeric/mlab.py +++ b/numpy/oldnumeric/mlab.py @@ -1,7 +1,7 @@ """This module is for compatibility only. All functions are defined elsewhere. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', @@ -21,7 +21,7 @@ from numpy.linalg import eig, svd from numpy.random import rand, randn import numpy as np -from typeconv import convtypecode +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, @@ -98,17 +98,17 @@ def corrcoef(x, y=None): 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 * - -import compat -import precision -import functions -import misc -import ufuncs +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__ diff --git a/numpy/oldnumeric/precision.py b/numpy/oldnumeric/precision.py index c6579f302..7c85f21fc 100644 --- a/numpy/oldnumeric/precision.py +++ b/numpy/oldnumeric/precision.py @@ -6,13 +6,13 @@ The character strings are still for "new" NumPy which is the only Incompatibility with Numeric """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['Character', 'Complex', 'Float', 'PrecisionError', 'PyObject', 'Int', 'UInt', 'UnsignedInt', 'UnsignedInteger', 'string', 'typecodes', 'zeros'] -from functions import zeros +from .functions import zeros import string # for backwards compatibility typecodes = {'Character':'c', 'Integer':'bhil', 'UnsignedInteger':'BHIL', 'Float':'fd', 'Complex':'FD'} diff --git a/numpy/oldnumeric/random_array.py b/numpy/oldnumeric/random_array.py index a7f6c4112..4dcddda12 100644 --- a/numpy/oldnumeric/random_array.py +++ b/numpy/oldnumeric/random_array.py @@ -1,7 +1,7 @@ """Backward compatible module for RandomArray """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['ArgumentError','F','beta','binomial','chi_square', 'exponential', 'gamma', 'get_seed', 'mean_var_test', 'multinomial', diff --git a/numpy/oldnumeric/rng.py b/numpy/oldnumeric/rng.py index 28fb9d591..3ad0b4190 100644 --- a/numpy/oldnumeric/rng.py +++ b/numpy/oldnumeric/rng.py @@ -4,7 +4,7 @@ Replace import RNG with import numpy.oldnumeric.rng as RNG. It is for backwards compatibility only. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution', 'NormalDistribution', 'UniformDistribution', 'error', 'ranf', diff --git a/numpy/oldnumeric/rng_stats.py b/numpy/oldnumeric/rng_stats.py index 96e50f9a4..43d763046 100644 --- a/numpy/oldnumeric/rng_stats.py +++ b/numpy/oldnumeric/rng_stats.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['average', 'histogram', 'standardDeviation', 'variance'] diff --git a/numpy/oldnumeric/tests/test_oldnumeric.py b/numpy/oldnumeric/tests/test_oldnumeric.py index 58ccc710a..488b2b471 100644 --- a/numpy/oldnumeric/tests/test_oldnumeric.py +++ b/numpy/oldnumeric/tests/test_oldnumeric.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import unittest diff --git a/numpy/oldnumeric/tests/test_regression.py b/numpy/oldnumeric/tests/test_regression.py index dd221699d..d169d6f3f 100644 --- a/numpy/oldnumeric/tests/test_regression.py +++ b/numpy/oldnumeric/tests/test_regression.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import * diff --git a/numpy/oldnumeric/typeconv.py b/numpy/oldnumeric/typeconv.py index 014477950..c3a27f5a3 100644 --- a/numpy/oldnumeric/typeconv.py +++ b/numpy/oldnumeric/typeconv.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['oldtype2dtype', 'convtypecode', 'convtypecode2', 'oldtypecodes'] diff --git a/numpy/oldnumeric/ufuncs.py b/numpy/oldnumeric/ufuncs.py index 9ace30a91..7da0b5a93 100644 --- a/numpy/oldnumeric/ufuncs.py +++ b/numpy/oldnumeric/ufuncs.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['less', 'cosh', 'arcsinh', 'add', 'ceil', 'arctan2', 'floor_divide', 'fmod', 'hypot', 'logical_and', 'power', 'sinh', 'remainder', 'cos', diff --git a/numpy/oldnumeric/user_array.py b/numpy/oldnumeric/user_array.py index 08be8135b..8d2421f4a 100644 --- a/numpy/oldnumeric/user_array.py +++ b/numpy/oldnumeric/user_array.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.oldnumeric import * from numpy.lib.user_array import container as UserArray diff --git a/numpy/polynomial/__init__.py b/numpy/polynomial/__init__.py index 684720828..1e9919614 100644 --- a/numpy/polynomial/__init__.py +++ b/numpy/polynomial/__init__.py @@ -13,16 +13,16 @@ implemented as operations on the coefficients. Additional (module-specific) information can be found in the docstring for the module of interest. """ -from __future__ import division +from __future__ import division, absolute_import import warnings -from polynomial import Polynomial -from chebyshev import Chebyshev -from legendre import Legendre -from hermite import Hermite -from hermite_e import HermiteE -from laguerre import Laguerre +from .polynomial import Polynomial +from .chebyshev import Chebyshev +from .legendre import Legendre +from .hermite import Hermite +from .hermite_e import HermiteE +from .laguerre import Laguerre from numpy.testing import Tester test = Tester().test diff --git a/numpy/polynomial/chebyshev.py b/numpy/polynomial/chebyshev.py index 1c2a539bf..2c2070c62 100644 --- a/numpy/polynomial/chebyshev.py +++ b/numpy/polynomial/chebyshev.py @@ -85,13 +85,13 @@ References (preprint: http://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4) """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.linalg as la -import polyutils as pu +from . import polyutils as pu import warnings -from polytemplate import polytemplate +from .polytemplate import polytemplate __all__ = ['chebzero', 'chebone', 'chebx', 'chebdomain', 'chebline', 'chebadd', 'chebsub', 'chebmulx', 'chebmul', 'chebdiv', 'chebpow', @@ -416,7 +416,7 @@ def cheb2poly(c) : array([ -2., -8., 4., 12.]) """ - from polynomial import polyadd, polysub, polymulx + from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) diff --git a/numpy/polynomial/hermite.py b/numpy/polynomial/hermite.py index 5929ee016..f731817c0 100644 --- a/numpy/polynomial/hermite.py +++ b/numpy/polynomial/hermite.py @@ -57,13 +57,13 @@ See also `numpy.polynomial` """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.linalg as la -import polyutils as pu +from . import polyutils as pu import warnings -from polytemplate import polytemplate +from .polytemplate import polytemplate __all__ = ['hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd', 'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', @@ -160,7 +160,7 @@ def herm2poly(c) : array([ 0., 1., 2., 3.]) """ - from polynomial import polyadd, polysub, polymulx + from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) diff --git a/numpy/polynomial/hermite_e.py b/numpy/polynomial/hermite_e.py index e2edaa36d..3ecb3c58d 100644 --- a/numpy/polynomial/hermite_e.py +++ b/numpy/polynomial/hermite_e.py @@ -57,13 +57,13 @@ See also `numpy.polynomial` """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.linalg as la -import polyutils as pu +from . import polyutils as pu import warnings -from polytemplate import polytemplate +from .polytemplate import polytemplate __all__ = ['hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline', 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv', 'hermpow', @@ -160,7 +160,7 @@ def herme2poly(c) : array([ 0., 1., 2., 3.]) """ - from polynomial import polyadd, polysub, polymulx + from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) diff --git a/numpy/polynomial/laguerre.py b/numpy/polynomial/laguerre.py index f8604a6b4..a951567de 100644 --- a/numpy/polynomial/laguerre.py +++ b/numpy/polynomial/laguerre.py @@ -57,13 +57,13 @@ See also `numpy.polynomial` """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.linalg as la -import polyutils as pu +from . import polyutils as pu import warnings -from polytemplate import polytemplate +from .polytemplate import polytemplate __all__ = ['lagzero', 'lagone', 'lagx', 'lagdomain', 'lagline', 'lagadd', 'lagsub', 'lagmulx', 'lagmul', 'lagdiv', 'lagpow', @@ -159,7 +159,7 @@ def lag2poly(c) : array([ 0., 1., 2., 3.]) """ - from polynomial import polyadd, polysub, polymulx + from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) diff --git a/numpy/polynomial/legendre.py b/numpy/polynomial/legendre.py index 5a0a12cdb..45107f543 100644 --- a/numpy/polynomial/legendre.py +++ b/numpy/polynomial/legendre.py @@ -81,13 +81,13 @@ numpy.polynomial.hermite numpy.polynomial.hermite_e """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.linalg as la -import polyutils as pu +from . import polyutils as pu import warnings -from polytemplate import polytemplate +from .polytemplate import polytemplate __all__ = ['legzero', 'legone', 'legx', 'legdomain', 'legline', 'legadd', 'legsub', 'legmulx', 'legmul', 'legdiv', 'legpow', 'legval', @@ -191,7 +191,7 @@ def leg2poly(c) : """ - from polynomial import polyadd, polysub, polymulx + from .polynomial import polyadd, polysub, polymulx [c] = pu.as_series([c]) n = len(c) diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index c9e35c2ff..49678cbbc 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -52,7 +52,7 @@ See also `numpy.polynomial` """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', 'polyadd', 'polysub', 'polymulx', 'polymul', 'polydiv', 'polypow', @@ -62,9 +62,9 @@ __all__ = ['polyzero', 'polyone', 'polyx', 'polydomain', 'polyline', import numpy as np import numpy.linalg as la -import polyutils as pu +from . import polyutils as pu import warnings -from polytemplate import polytemplate +from .polytemplate import polytemplate polytrim = pu.trimcoef diff --git a/numpy/polynomial/polytemplate.py b/numpy/polynomial/polytemplate.py index 7d67c914c..adf32170f 100644 --- a/numpy/polynomial/polytemplate.py +++ b/numpy/polynomial/polytemplate.py @@ -9,21 +9,16 @@ creating additional specific polynomial classes (e.g., Legendre, Jacobi, etc.) in the future, such that all these classes will have a common API. """ -from __future__ import division +from __future__ import division, absolute_import import string import sys -if sys.version_info[0] >= 3: - rel_import = "from . import" -else: - rel_import = "import" - polytemplate = string.Template(''' -from __future__ import division +from __future__ import division, absolute_import import numpy as np import warnings -REL_IMPORT polyutils as pu +from . import polyutils as pu class $name(pu.PolyBase) : """A $name series class. @@ -918,4 +913,4 @@ class $name(pu.PolyBase) : """ return series.convert(domain, $name, window) -'''.replace('REL_IMPORT', rel_import)) +''') diff --git a/numpy/polynomial/polyutils.py b/numpy/polynomial/polyutils.py index d4490aafc..51caacebe 100644 --- a/numpy/polynomial/polyutils.py +++ b/numpy/polynomial/polyutils.py @@ -31,7 +31,7 @@ Functions - `mapparms` -- parameters of the linear map between domains. """ -from __future__ import division +from __future__ import division, absolute_import __all__ = ['RankWarning', 'PolyError', 'PolyDomainError', 'PolyBase', 'as_series', 'trimseq', 'trimcoef', 'getdomain', 'mapdomain', diff --git a/numpy/polynomial/tests/test_chebyshev.py b/numpy/polynomial/tests/test_chebyshev.py index 95da83631..2bf73d02b 100644 --- a/numpy/polynomial/tests/test_chebyshev.py +++ b/numpy/polynomial/tests/test_chebyshev.py @@ -1,7 +1,7 @@ """Tests for chebyshev module. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.polynomial.chebyshev as cheb @@ -265,7 +265,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = cheb.chebint(tgt, m=1, k=[k]) - res = cheb.chebint(pol, m=j, k=range(j)) + res = cheb.chebint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd @@ -275,7 +275,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = cheb.chebint(tgt, m=1, k=[k], lbnd=-1) - res = cheb.chebint(pol, m=j, k=range(j), lbnd=-1) + res = cheb.chebint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling @@ -285,7 +285,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = cheb.chebint(tgt, m=1, k=[k], scl=2) - res = cheb.chebint(pol, m=j, k=range(j), scl=2) + res = cheb.chebint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_chebint_axis(self): diff --git a/numpy/polynomial/tests/test_classes.py b/numpy/polynomial/tests/test_classes.py index fb0d359e0..2439fc8ad 100644 --- a/numpy/polynomial/tests/test_classes.py +++ b/numpy/polynomial/tests/test_classes.py @@ -3,7 +3,7 @@ This tests the convert and cast methods of all the polynomial classes. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.polynomial import ( diff --git a/numpy/polynomial/tests/test_hermite.py b/numpy/polynomial/tests/test_hermite.py index a0ef3b515..f9b936bbf 100644 --- a/numpy/polynomial/tests/test_hermite.py +++ b/numpy/polynomial/tests/test_hermite.py @@ -1,7 +1,7 @@ """Tests for hermite module. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.polynomial.hermite as herm @@ -255,7 +255,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = herm.hermint(tgt, m=1, k=[k]) - res = herm.hermint(pol, m=j, k=range(j)) + res = herm.hermint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd @@ -265,7 +265,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = herm.hermint(tgt, m=1, k=[k], lbnd=-1) - res = herm.hermint(pol, m=j, k=range(j), lbnd=-1) + res = herm.hermint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling @@ -275,7 +275,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = herm.hermint(tgt, m=1, k=[k], scl=2) - res = herm.hermint(pol, m=j, k=range(j), scl=2) + res = herm.hermint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_hermint_axis(self): diff --git a/numpy/polynomial/tests/test_hermite_e.py b/numpy/polynomial/tests/test_hermite_e.py index f6bfe5e5e..f7871fe99 100644 --- a/numpy/polynomial/tests/test_hermite_e.py +++ b/numpy/polynomial/tests/test_hermite_e.py @@ -1,7 +1,7 @@ """Tests for hermite_e module. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.polynomial.hermite_e as herme @@ -252,7 +252,7 @@ class TestIntegral(TestCase): tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k]) - res = herme.hermeint(pol, m=j, k=range(j)) + res = herme.hermeint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd @@ -262,7 +262,7 @@ class TestIntegral(TestCase): tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1) - res = herme.hermeint(pol, m=j, k=range(j), lbnd=-1) + res = herme.hermeint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling @@ -272,7 +272,7 @@ class TestIntegral(TestCase): tgt = pol[:] for k in range(j) : tgt = herme.hermeint(tgt, m=1, k=[k], scl=2) - res = herme.hermeint(pol, m=j, k=range(j), scl=2) + res = herme.hermeint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_hermeint_axis(self): diff --git a/numpy/polynomial/tests/test_laguerre.py b/numpy/polynomial/tests/test_laguerre.py index b6e0376a2..2aabda114 100644 --- a/numpy/polynomial/tests/test_laguerre.py +++ b/numpy/polynomial/tests/test_laguerre.py @@ -1,7 +1,7 @@ """Tests for laguerre module. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.polynomial.laguerre as lag @@ -250,7 +250,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = lag.lagint(tgt, m=1, k=[k]) - res = lag.lagint(pol, m=j, k=range(j)) + res = lag.lagint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd @@ -260,7 +260,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = lag.lagint(tgt, m=1, k=[k], lbnd=-1) - res = lag.lagint(pol, m=j, k=range(j), lbnd=-1) + res = lag.lagint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling @@ -270,7 +270,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = lag.lagint(tgt, m=1, k=[k], scl=2) - res = lag.lagint(pol, m=j, k=range(j), scl=2) + res = lag.lagint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_lagint_axis(self): diff --git a/numpy/polynomial/tests/test_legendre.py b/numpy/polynomial/tests/test_legendre.py index 3180db907..cd3db4e35 100644 --- a/numpy/polynomial/tests/test_legendre.py +++ b/numpy/polynomial/tests/test_legendre.py @@ -1,7 +1,7 @@ """Tests for legendre module. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.polynomial.legendre as leg @@ -254,7 +254,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k]) - res = leg.legint(pol, m=j, k=range(j)) + res = leg.legint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd @@ -264,7 +264,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k], lbnd=-1) - res = leg.legint(pol, m=j, k=range(j), lbnd=-1) + res = leg.legint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling @@ -274,7 +274,7 @@ class TestIntegral(TestCase) : tgt = pol[:] for k in range(j) : tgt = leg.legint(tgt, m=1, k=[k], scl=2) - res = leg.legint(pol, m=j, k=range(j), scl=2) + res = leg.legint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_legint_axis(self): diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py index bd09c07f6..c93421c7d 100644 --- a/numpy/polynomial/tests/test_polynomial.py +++ b/numpy/polynomial/tests/test_polynomial.py @@ -1,7 +1,7 @@ """Tests for polynomial module. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.polynomial.polynomial as poly @@ -253,7 +253,7 @@ class TestIntegral(TestCase): tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k]) - res = poly.polyint(pol, m=j, k=range(j)) + res = poly.polyint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd @@ -263,7 +263,7 @@ class TestIntegral(TestCase): tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k], lbnd=-1) - res = poly.polyint(pol, m=j, k=range(j), lbnd=-1) + res = poly.polyint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling @@ -273,7 +273,7 @@ class TestIntegral(TestCase): tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k], scl=2) - res = poly.polyint(pol, m=j, k=range(j), scl=2) + res = poly.polyint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt)) def test_polyint_axis(self): diff --git a/numpy/polynomial/tests/test_polyutils.py b/numpy/polynomial/tests/test_polyutils.py index 14bf8bb78..95a8f39bb 100644 --- a/numpy/polynomial/tests/test_polyutils.py +++ b/numpy/polynomial/tests/test_polyutils.py @@ -1,7 +1,7 @@ """Tests for polyutils module. """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.polynomial.polyutils as pu diff --git a/numpy/polynomial/tests/test_printing.py b/numpy/polynomial/tests/test_printing.py index 889966051..3974620a7 100644 --- a/numpy/polynomial/tests/test_printing.py +++ b/numpy/polynomial/tests/test_printing.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy.polynomial as poly from numpy.testing import TestCase, run_module_suite, assert_ diff --git a/numpy/random/__init__.py b/numpy/random/__init__.py index f005bc15a..fd401a32c 100644 --- a/numpy/random/__init__.py +++ b/numpy/random/__init__.py @@ -86,10 +86,10 @@ set_state Set state of generator. ==================== ========================================================= """ -from __future__ import division +from __future__ import division, absolute_import # To get sub-modules -from info import __doc__, __all__ +from .info import __doc__, __all__ import warnings from numpy.testing.utils import WarningManager @@ -98,7 +98,7 @@ warn_ctx = WarningManager() warn_ctx.__enter__() try: warnings.filterwarnings("ignore", message="numpy.ndarray size changed") - from mtrand import * + from .mtrand import * finally: warn_ctx.__exit__() diff --git a/numpy/random/info.py b/numpy/random/info.py index c886c565e..981c55046 100644 --- a/numpy/random/info.py +++ b/numpy/random/info.py @@ -82,7 +82,7 @@ set_state Set state of generator. ==================== ========================================================= """ -from __future__ import division +from __future__ import division, absolute_import depends = ['core'] diff --git a/numpy/random/mtrand/generate_mtrand_c.py b/numpy/random/mtrand/generate_mtrand_c.py index d6527e695..7bfda22eb 100644 --- a/numpy/random/mtrand/generate_mtrand_c.py +++ b/numpy/random/mtrand/generate_mtrand_c.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import import sys import re diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py index 410456ef4..27e7a3755 100644 --- a/numpy/random/tests/test_random.py +++ b/numpy/random/tests/test_random.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import TestCase, run_module_suite, assert_,\ assert_raises diff --git a/numpy/random/tests/test_regression.py b/numpy/random/tests/test_regression.py index a19974c47..530c45228 100644 --- a/numpy/random/tests/test_regression.py +++ b/numpy/random/tests/test_regression.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import from numpy.testing import TestCase, run_module_suite, assert_,\ assert_array_equal diff --git a/numpy/testing/__init__.py b/numpy/testing/__init__.py index 19b0d2052..cee2d6944 100644 --- a/numpy/testing/__init__.py +++ b/numpy/testing/__init__.py @@ -5,13 +5,13 @@ in a single location, so that test scripts can just import it and work right away. """ -from __future__ import division +from __future__ import division, absolute_import from unittest import TestCase -import decorators as dec -from utils import * -from numpytest import * -from nosetester import NoseTester as Tester -from nosetester import run_module_suite +from . import decorators as dec +from .utils import * +from .numpytest import * +from .nosetester import NoseTester as Tester +from .nosetester import run_module_suite test = Tester().test diff --git a/numpy/testing/decorators.py b/numpy/testing/decorators.py index eae9d93b0..6d3da95ed 100644 --- a/numpy/testing/decorators.py +++ b/numpy/testing/decorators.py @@ -13,7 +13,7 @@ function name, setup and teardown functions and so on - see ``nose.tools`` for more information. """ -from __future__ import division +from __future__ import division, absolute_import import warnings import sys @@ -210,7 +210,7 @@ def knownfailureif(fail_condition, msg=None): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose - from noseclasses import KnownFailureTest + from .noseclasses import KnownFailureTest def knownfailer(*args, **kwargs): if fail_val(): raise KnownFailureTest(msg) @@ -249,7 +249,7 @@ def deprecated(conditional=True): # Local import to avoid a hard nose dependency and only incur the # import time overhead at actual test-time. import nose - from noseclasses import KnownFailureTest + from .noseclasses import KnownFailureTest def _deprecated_imp(*args, **kwargs): # Poor man's replacement for the with statement diff --git a/numpy/testing/noseclasses.py b/numpy/testing/noseclasses.py index 96c779c2e..f3c15b39d 100644 --- a/numpy/testing/noseclasses.py +++ b/numpy/testing/noseclasses.py @@ -4,7 +4,7 @@ # Because this module imports nose directly, it should not # be used except by nosetester.py to avoid a general NumPy # dependency on nose. -from __future__ import division +from __future__ import division, absolute_import import os import doctest @@ -15,7 +15,7 @@ from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from nose.plugins.base import Plugin from nose.util import src import numpy -from nosetester import get_package_name +from .nosetester import get_package_name import inspect # Some of the classes in this module begin with 'Numpy' to clearly distinguish diff --git a/numpy/testing/nosetester.py b/numpy/testing/nosetester.py index 7f1292cd8..326c36cac 100644 --- a/numpy/testing/nosetester.py +++ b/numpy/testing/nosetester.py @@ -4,7 +4,7 @@ Nose test running. This module implements ``test()`` and ``bench()`` functions for NumPy modules. """ -from __future__ import division +from __future__ import division, absolute_import import os import sys @@ -216,7 +216,7 @@ class NoseTester(object): A return value of None means use the nose builtin doctest plugin """ - from noseclasses import NumpyDoctest + from .noseclasses import NumpyDoctest return NumpyDoctest() def prepare_test_args(self, label='fast', verbose=1, extra_argv=None, @@ -245,7 +245,7 @@ class NoseTester(object): '--cover-tests', '--cover-erase'] # construct list of plugins import nose.plugins.builtin - from noseclasses import KnownFailure, Unplugger + from .noseclasses import KnownFailure, Unplugger plugins = [KnownFailure()] plugins += [p() for p in nose.plugins.builtin.plugins] # add doctesting if required @@ -331,7 +331,7 @@ class NoseTester(object): # cap verbosity at 3 because nose becomes *very* verbose beyond that verbose = min(verbose, 3) - import utils + from . import utils utils.verbose = verbose if doctests: @@ -371,7 +371,7 @@ class NoseTester(object): warnings.filterwarnings("ignore", message="numpy.ufunc size changed") try: - from noseclasses import NumpyTestProgram + from .noseclasses import NumpyTestProgram argv, plugins = self.prepare_test_args(label, verbose, extra_argv, doctests, coverage) @@ -447,7 +447,7 @@ class NoseTester(object): nose = import_nose() # get plugin to disable doctests - from noseclasses import Unplugger + from .noseclasses import Unplugger add_plugins = [Unplugger('doctest')] return nose.run(argv=argv, addplugins=add_plugins) diff --git a/numpy/testing/nulltester.py b/numpy/testing/nulltester.py index e0c7531b3..0419f9436 100644 --- a/numpy/testing/nulltester.py +++ b/numpy/testing/nulltester.py @@ -6,7 +6,7 @@ below requirements. See pkgtester, nosetester modules """ -from __future__ import division +from __future__ import division, absolute_import class NullTester(object): diff --git a/numpy/testing/numpytest.py b/numpy/testing/numpytest.py index 5259ba773..4e2409e8d 100644 --- a/numpy/testing/numpytest.py +++ b/numpy/testing/numpytest.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import os import sys diff --git a/numpy/testing/print_coercion_tables.py b/numpy/testing/print_coercion_tables.py index 4982f5602..829ba0a16 100755 --- a/numpy/testing/print_coercion_tables.py +++ b/numpy/testing/print_coercion_tables.py @@ -2,7 +2,7 @@ """Prints type-coercion tables for the built-in NumPy types """ -from __future__ import division +from __future__ import division, absolute_import import numpy as np diff --git a/numpy/testing/tests/test_decorators.py b/numpy/testing/tests/test_decorators.py index e2dc2bd7d..0acf5a11a 100644 --- a/numpy/testing/tests/test_decorators.py +++ b/numpy/testing/tests/test_decorators.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np from numpy.testing import * @@ -88,7 +88,7 @@ def test_skip_functions_callable(): def test_skip_generators_hardcoded(): @dec.knownfailureif(True, "This test is known to fail") def g1(x): - for i in xrange(x): + for i in range(x): yield i try: @@ -102,7 +102,7 @@ def test_skip_generators_hardcoded(): @dec.knownfailureif(False, "This test is NOT known to fail") def g2(x): - for i in xrange(x): + for i in range(x): yield i raise DidntSkipException('FAIL') @@ -121,7 +121,7 @@ def test_skip_generators_callable(): @dec.knownfailureif(skip_tester, "This test is known to fail") def g1(x): - for i in xrange(x): + for i in range(x): yield i try: @@ -136,7 +136,7 @@ def test_skip_generators_callable(): @dec.knownfailureif(skip_tester, "This test is NOT known to fail") def g2(x): - for i in xrange(x): + for i in range(x): yield i raise DidntSkipException('FAIL') diff --git a/numpy/testing/tests/test_doctesting.py b/numpy/testing/tests/test_doctesting.py index 58f65aa45..798c0e7e7 100644 --- a/numpy/testing/tests/test_doctesting.py +++ b/numpy/testing/tests/test_doctesting.py @@ -1,7 +1,7 @@ """ Doctests for NumPy-specific nose/doctest modifications """ -from __future__ import division +from __future__ import division, absolute_import # try the #random directive on the output line def check_random_directive(): diff --git a/numpy/testing/tests/test_utils.py b/numpy/testing/tests/test_utils.py index 9722c583c..f08ca2b12 100644 --- a/numpy/testing/tests/test_utils.py +++ b/numpy/testing/tests/test_utils.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import warnings import sys @@ -378,7 +378,7 @@ class TestArrayAlmostEqualNulp(unittest.TestCase): @dec.knownfailureif(True, "Github issue #347") def test_simple(self): np.random.seed(12345) - for i in xrange(100): + for i in range(100): dev = np.random.randn(10) x = np.ones(10) y = x + dev * np.finfo(np.float64).eps diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index b0495af00..eb212cb14 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -2,7 +2,7 @@ Utility function to facilitate testing. """ -from __future__ import division +from __future__ import division, absolute_import import os import sys @@ -10,7 +10,7 @@ import re import operator import types import warnings -from nosetester import import_nose +from .nosetester import import_nose __all__ = ['assert_equal', 'assert_almost_equal','assert_approx_equal', 'assert_array_equal', 'assert_array_less', 'assert_string_equal', diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py index 9b53ed0c6..cbf8db6a3 100644 --- a/numpy/tests/test_ctypeslib.py +++ b/numpy/tests/test_ctypeslib.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import sys diff --git a/numpy/tests/test_matlib.py b/numpy/tests/test_matlib.py index 0ac49fed3..621563462 100644 --- a/numpy/tests/test_matlib.py +++ b/numpy/tests/test_matlib.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import numpy.matlib diff --git a/pavement.py b/pavement.py index 56fe5e714..444976238 100644 --- a/pavement.py +++ b/pavement.py @@ -55,7 +55,7 @@ TODO - fix bdist_mpkg: we build the same source twice -> how to make sure we use the same underlying python for egg install in venv and for bdist_mpkg """ -from __future__ import division +from __future__ import division, absolute_import # What need to be installed to build everything on mac os x: # - wine: python 2.6 and 2.5 + makensis + cpuid plugin + mingw, all in the PATH diff --git a/setupegg.py b/setupegg.py index 4269fd4c8..e2d1ad0b8 100755 --- a/setupegg.py +++ b/setupegg.py @@ -12,7 +12,7 @@ set wrong, with nose refusing to run any tests. To run the tests anyway, use:: >>> np.test(extra_argv=['--exe']) """ -from __future__ import division +from __future__ import division, absolute_import import sys from setuptools import setup diff --git a/tools/allocation_tracking/track_allocations.py b/tools/allocation_tracking/track_allocations.py index b37e8cd04..ddd0ffea0 100644 --- a/tools/allocation_tracking/track_allocations.py +++ b/tools/allocation_tracking/track_allocations.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import import numpy as np import inspect diff --git a/tools/c_coverage/c_coverage_report.py b/tools/c_coverage/c_coverage_report.py index e4522bd92..83fdd1998 100755 --- a/tools/c_coverage/c_coverage_report.py +++ b/tools/c_coverage/c_coverage_report.py @@ -4,7 +4,7 @@ A script to create C code-coverage reports based on the output of valgrind's callgrind tool. """ -from __future__ import division +from __future__ import division, absolute_import import optparse import os diff --git a/tools/commitstats.py b/tools/commitstats.py index d89c7a98e..73e995912 100644 --- a/tools/commitstats.py +++ b/tools/commitstats.py @@ -1,4 +1,4 @@ -from __future__ import division +from __future__ import division, absolute_import # Run svn log -l <some number> diff --git a/tools/osxbuild/build.py b/tools/osxbuild/build.py index ef6006fa1..7aa9312dd 100644 --- a/tools/osxbuild/build.py +++ b/tools/osxbuild/build.py @@ -10,6 +10,7 @@ built using sudo so file permissions are correct when installed on user system. Script will prompt for sudo pwd. """ +from __future__ import division import os import shutil diff --git a/tools/osxbuild/install_and_test.py b/tools/osxbuild/install_and_test.py index e9b34f5b0..651298b3f 100644 --- a/tools/osxbuild/install_and_test.py +++ b/tools/osxbuild/install_and_test.py @@ -1,5 +1,8 @@ #!/usr/bin/env python -"""Install the built package and run the tests.""" +"""Install the built package and run the tests. + +""" +from __future__ import division import os diff --git a/tools/py3tool.py b/tools/py3tool.py index 5e2ffbe58..656327450 100755 --- a/tools/py3tool.py +++ b/tools/py3tool.py @@ -18,7 +18,7 @@ When running py3tool again, only changed files are re-processed, which makes the test-bugfix cycle faster. """ -from __future__ import division +from __future__ import division, absolute_import from optparse import OptionParser import shutil @@ -37,10 +37,6 @@ TEMP = os.path.normpath(os.path.join(BASE, '_py3k')) SCRIPT_2TO3 = os.path.join(BASE, 'tools', '2to3.py') EXTRA_2TO3_FLAGS = { - '*/setup.py': '-x import', - 'numpy/core/code_generators/generate_umath.py': '-x import', - 'numpy/core/code_generators/generate_numpy_api.py': '-x import', - 'numpy/core/code_generators/generate_ufunc_api.py': '-x import', 'numpy/core/defchararray.py': '-x unicode', 'numpy/compat/py3k.py': '-x unicode', 'numpy/ma/timer_comparison.py': 'skip', @@ -79,7 +75,9 @@ FIXES_TO_SKIP = [ 'apply', 'input', 'raw_input', - 'xreadlines' + 'xreadlines', + 'xrange', + 'import' ] skip_fixes= [] @@ -171,38 +169,6 @@ except: # Run nosetests subprocess.call(['nosetests3', '-v', d], cwd=TEMP) -def custom_mangling(filename): - import_mangling = [ - os.path.join('core', '__init__.py'), - os.path.join('core', 'numeric.py'), - os.path.join('core', '_internal.py'), - os.path.join('core', 'arrayprint.py'), - os.path.join('core', 'fromnumeric.py'), - os.path.join('numpy', '__init__.py'), - os.path.join('lib', 'npyio.py'), - os.path.join('lib', 'function_base.py'), - os.path.join('fft', 'fftpack.py'), - os.path.join('random', '__init__.py'), - ] - - if any(filename.endswith(x) for x in import_mangling): - f = open(filename, 'r') - text = f.read() - f.close() - for mod in ['multiarray', 'scalarmath', 'umath', '_sort', - '_compiled_base', 'core', 'lib', 'testing', 'fft', - 'polynomial', 'random', 'ma', 'linalg', 'compat', - 'mtrand', '_dotblas', 'version']: - text = re.sub(r'^(\s*)import %s' % mod, - r'\1from . import %s' % mod, - text, flags=re.M) - text = re.sub(r'^(\s*)from %s import' % mod, - r'\1from .%s import' % mod, - text, flags=re.M) - text = text.replace('from matrixlib', 'from .matrixlib') - f = open(filename, 'w') - f.write(text) - f.close() def walk_sync(dir1, dir2, _seen=None): if _seen is None: @@ -312,10 +278,6 @@ def sync_2to3(src, dst, patchfile=None, clean=False): finally: sys.stdout = _old_stdout - for fn, dst_fn in to_convert: - # perform custom mangling - custom_mangling(dst_fn) - p.close() if __name__ == "__main__": diff --git a/tools/test-installed-numpy.py b/tools/test-installed-numpy.py index ac917b05f..41d64614f 100644 --- a/tools/test-installed-numpy.py +++ b/tools/test-installed-numpy.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -from __future__ import division +from __future__ import division, absolute_import # A simple script to test the installed version of numpy by calling # 'numpy.test()'. Key features: @@ -12,7 +12,7 @@ from __future__ import division # But, python2.4's -m switch only works with top-level modules, not modules # that are inside packages. So, once we drop 2.4 support, maybe... -import sys +import sys, os # In case we are run from the source directory, we don't want to import numpy # from there, we want to import the installed version: sys.path.pop(0) @@ -35,6 +35,17 @@ parser.add_option("-m", "--mode", (options, args) = parser.parse_args() import numpy + +# Check that NPY_RELAXED_STRIDES_CHECKING is active when set. +# The same flags check is also used in the tests to switch behavior. +if (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', "0") != "0"): + if not numpy.ones((10,1), order='C').flags.f_contiguous: + print('NPY_RELAXED_STRIDES_CHECKING set, but not active.') + sys.exit(1) +elif numpy.ones((10,1), order='C').flags.f_contiguous: + print('NPY_RELAXED_STRIDES_CHECKING not set, but active.') + sys.exit(1) + result = numpy.test(options.mode, verbose=options.verbose, extra_argv=args, diff --git a/tools/win32build/build.py b/tools/win32build/build.py index 4acb2e879..43d8a395d 100644 --- a/tools/win32build/build.py +++ b/tools/win32build/build.py @@ -1,11 +1,15 @@ """Python script to build windows binaries to be fed to the "superpack". The script is pretty dumb: it assumes python executables are installed the -standard way, and the location for blas/lapack/atlas is harcoded.""" +standard way, and the location for blas/lapack/atlas is harcoded. + +TODO: + - integrate the x86analysis script to check built binaries + - make the config configurable with a file + +""" +from __future__ import division -# TODO: -# - integrate the x86analysis script to check built binaries -# - make the config configurable with a file import sys import subprocess import os diff --git a/tools/win32build/doall.py b/tools/win32build/doall.py index eb07394ea..e9866122e 100644 --- a/tools/win32build/doall.py +++ b/tools/win32build/doall.py @@ -1,3 +1,5 @@ +from __future__ import division + import subprocess import os diff --git a/tools/win32build/misc/x86analysis.py b/tools/win32build/misc/x86analysis.py index bccf0171c..e5eb886b4 100644 --- a/tools/win32build/misc/x86analysis.py +++ b/tools/win32build/misc/x86analysis.py @@ -5,6 +5,7 @@ # checking the assembly for instructions specific to sse, etc... Obviously, # this won't work all the times (for example, if some instructions are used # only after proper detection of the running CPU, this will give false alarm). +from __future__ import division import sys import re @@ -57,7 +58,7 @@ SSE2_SET = ["addpd", "addsd", "andnpd", "andpd", "clflush", "cmppd", "cmpsd", "sqrtsd", "subpd", "subsd", "ucomisd", "unpckhpd", "unpcklpd", "xorpd"] SSE3_SET = [ "addsubpd", "addsubps", "haddpd", "haddps", "hsubpd", "hsubps", - "lddqu", "movddup", "movshdup", "movsldup", "fisttp"] + "lddqu", "movddup", "movshdup", "movsldup", "fisttp"] def get_vendor_string(): """Return the vendor string reading cpuinfo.""" diff --git a/tools/win32build/prepare_bootstrap.py b/tools/win32build/prepare_bootstrap.py index f1d8edbfb..d5822b83e 100644 --- a/tools/win32build/prepare_bootstrap.py +++ b/tools/win32build/prepare_bootstrap.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import subprocess import shutil |