summaryrefslogtreecommitdiff
path: root/numpy/lib
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/lib')
-rw-r--r--numpy/lib/__init__.py6
-rw-r--r--numpy/lib/function_base.py53
-rw-r--r--numpy/lib/histograms.py167
-rw-r--r--numpy/lib/npyio.py12
-rw-r--r--numpy/lib/tests/test__datasource.py8
-rw-r--r--numpy/lib/tests/test__iotools.py5
-rw-r--r--numpy/lib/tests/test__version.py6
-rw-r--r--numpy/lib/tests/test_arraypad.py4
-rw-r--r--numpy/lib/tests/test_arraysetops.py8
-rw-r--r--numpy/lib/tests/test_arrayterator.py4
-rw-r--r--numpy/lib/tests/test_financial.py9
-rw-r--r--numpy/lib/tests/test_format.py19
-rw-r--r--numpy/lib/tests/test_function_base.py57
-rw-r--r--numpy/lib/tests/test_histograms.py31
-rw-r--r--numpy/lib/tests/test_index_tricks.py145
-rw-r--r--numpy/lib/tests/test_io.py104
-rw-r--r--numpy/lib/tests/test_mixins.py8
-rw-r--r--numpy/lib/tests/test_nanfunctions.py8
-rw-r--r--numpy/lib/tests/test_packbits.py8
-rw-r--r--numpy/lib/tests/test_polynomial.py44
-rw-r--r--numpy/lib/tests/test_recfunctions.py11
-rw-r--r--numpy/lib/tests/test_regression.py8
-rw-r--r--numpy/lib/tests/test_shape_base.py7
-rw-r--r--numpy/lib/tests/test_stride_tricks.py11
-rw-r--r--numpy/lib/tests/test_twodim_base.py69
-rw-r--r--numpy/lib/tests/test_type_check.py6
-rw-r--r--numpy/lib/tests/test_ufunclike.py5
-rw-r--r--numpy/lib/tests/test_utils.py12
28 files changed, 426 insertions, 409 deletions
diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py
index cc05232a2..d764cdc7e 100644
--- a/numpy/lib/__init__.py
+++ b/numpy/lib/__init__.py
@@ -46,6 +46,6 @@ __all__ += financial.__all__
__all__ += nanfunctions.__all__
__all__ += histograms.__all__
-from numpy.testing import _numpy_tester
-test = _numpy_tester().test
-bench = _numpy_tester().bench
+from numpy.testing._private.pytesttester import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py
index 9ccbfafa2..a4516c276 100644
--- a/numpy/lib/function_base.py
+++ b/numpy/lib/function_base.py
@@ -145,7 +145,7 @@ def rot90(m, k=1, axes=(0,1)):
return flip(transpose(m, axes_list), axes[1])
-def flip(m, axis):
+def flip(m, axis=None):
"""
Reverse the order of elements in an array along the given axis.
@@ -157,9 +157,16 @@ def flip(m, axis):
----------
m : array_like
Input array.
- axis : integer
- Axis in array, which entries are reversed.
+ axis : None or int or tuple of ints, optional
+ Axis or axes along which to flip over. The default,
+ axis=None, will flip over all of the axes of the input array.
+ If axis is negative it counts from the last to the first axis.
+
+ If axis is a tuple of ints, flipping is performed on all of the axes
+ specified in the tuple.
+ .. versionchanged:: 1.15.0
+ None and tuples of axes are supported
Returns
-------
@@ -175,46 +182,60 @@ def flip(m, axis):
Notes
-----
flip(m, 0) is equivalent to flipud(m).
+
flip(m, 1) is equivalent to fliplr(m).
+
flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n.
+ flip(m) corresponds to ``m[::-1,::-1,...,::-1]`` with ``::-1`` at all
+ positions.
+
+ flip(m, (0, 1)) corresponds to ``m[::-1,::-1,...]`` with ``::-1`` at
+ position 0 and position 1.
+
Examples
--------
>>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
[2, 3]],
-
[[4, 5],
[6, 7]]])
-
>>> flip(A, 0)
array([[[4, 5],
[6, 7]],
-
[[0, 1],
[2, 3]]])
-
>>> flip(A, 1)
array([[[2, 3],
[0, 1]],
-
[[6, 7],
[4, 5]]])
-
+ >>> np.flip(A)
+ array([[[7, 6],
+ [5, 4]],
+ [[3, 2],
+ [1, 0]]])
+ >>> np.flip(A, (0, 2))
+ array([[[5, 4],
+ [7, 6]],
+ [[1, 0],
+ [3, 2]]])
>>> A = np.random.randn(3,4,5)
>>> np.all(flip(A,2) == A[:,:,::-1,...])
True
"""
if not hasattr(m, 'ndim'):
m = asarray(m)
- indexer = [slice(None)] * m.ndim
- try:
- indexer[axis] = slice(None, None, -1)
- except IndexError:
- raise ValueError("axis=%i is invalid for the %i-dimensional input array"
- % (axis, m.ndim))
- return m[tuple(indexer)]
+ if axis is None:
+ indexer = (np.s_[::-1],) * m.ndim
+ else:
+ axis = _nx.normalize_axis_tuple(axis, m.ndim)
+ indexer = [np.s_[:]] * m.ndim
+ for ax in axis:
+ indexer[ax] = np.s_[::-1]
+ indexer = tuple(indexer)
+ return m[indexer]
def iterable(y):
diff --git a/numpy/lib/histograms.py b/numpy/lib/histograms.py
index aa067a431..d2a398a0a 100644
--- a/numpy/lib/histograms.py
+++ b/numpy/lib/histograms.py
@@ -10,6 +10,10 @@ from numpy.compat.py3k import basestring
__all__ = ['histogram', 'histogramdd', 'histogram_bin_edges']
+# range is a keyword argument to many functions, so save the builtin so they can
+# use it.
+_range = range
+
def _hist_bin_sqrt(x):
"""
@@ -163,12 +167,22 @@ def _hist_bin_fd(x):
def _hist_bin_auto(x):
"""
Histogram bin estimator that uses the minimum width of the
- Freedman-Diaconis and Sturges estimators.
+ Freedman-Diaconis and Sturges estimators if the FD bandwidth is non zero
+ and the Sturges estimator if the FD bandwidth is 0.
The FD estimator is usually the most robust method, but its width
- estimate tends to be too large for small `x`. The Sturges estimator
- is quite good for small (<1000) datasets and is the default in the R
- language. This method gives good off the shelf behaviour.
+ estimate tends to be too large for small `x` and bad for data with limited
+ variance. The Sturges estimator is quite good for small (<1000) datasets
+ and is the default in the R language. This method gives good off the shelf
+ behaviour.
+
+ .. versionchanged:: 1.15.0
+ If there is limited variance the IQR can be 0, which results in the
+ FD bin width being 0 too. This is not a valid bin width, so
+ ``np.histogram_bin_edges`` chooses 1 bin instead, which may not be optimal.
+ If the IQR is 0, it's unlikely any variance based estimators will be of
+ use, so we revert to the sturges estimator, which only uses the size of the
+ dataset in its calculation.
Parameters
----------
@@ -184,10 +198,13 @@ def _hist_bin_auto(x):
--------
_hist_bin_fd, _hist_bin_sturges
"""
- # There is no need to check for zero here. If ptp is, so is IQR and
- # vice versa. Either both are zero or neither one is.
- return min(_hist_bin_fd(x), _hist_bin_sturges(x))
-
+ fd_bw = _hist_bin_fd(x)
+ sturges_bw = _hist_bin_sturges(x)
+ if fd_bw:
+ return min(fd_bw, sturges_bw)
+ else:
+ # limited variance, so we return a len dependent bw estimator
+ return sturges_bw
# Private dict initialized at module load time
_hist_bin_selectors = {'auto': _hist_bin_auto,
@@ -436,7 +453,7 @@ def histogram_bin_edges(a, bins=10, range=None, weights=None):
below, :math:`h` is the binwidth and :math:`n_h` is the number of
bins. All estimators that compute bin counts are recast to bin width
using the `ptp` of the data. The final bin count is obtained from
- ``np.round(np.ceil(range / h))`.
+ ``np.round(np.ceil(range / h))``.
'Auto' (maximum of the 'Sturges' and 'FD' estimators)
A compromise to get a good value. For small datasets the Sturges
@@ -693,7 +710,7 @@ def histogram(a, bins=10, range=None, normed=False, weights=None,
# large arrays, it is actually faster (for example for a 10^8 array it
# is 2x as fast) and it results in a memory footprint 3x lower in the
# limit of large arrays.
- for i in np.arange(0, len(a), BLOCK):
+ for i in _range(0, len(a), BLOCK):
tmp_a = a[i:i+BLOCK]
if weights is None:
tmp_w = None
@@ -741,12 +758,12 @@ def histogram(a, bins=10, range=None, normed=False, weights=None,
# Compute via cumulative histogram
cum_n = np.zeros(bin_edges.shape, ntype)
if weights is None:
- for i in np.arange(0, len(a), BLOCK):
+ for i in _range(0, len(a), BLOCK):
sa = np.sort(a[i:i+BLOCK])
cum_n += _search_sorted_inclusive(sa, bin_edges)
else:
zero = np.zeros(1, dtype=ntype)
- for i in np.arange(0, len(a), BLOCK):
+ for i in _range(0, len(a), BLOCK):
tmp_a = a[i:i+BLOCK]
tmp_w = weights[i:i+BLOCK]
sorting_index = np.argsort(tmp_a)
@@ -779,10 +796,18 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
Parameters
----------
- sample : array_like
- The data to be histogrammed. It must be an (N,D) array or data
- that can be converted to such. The rows of the resulting array
- are the coordinates of points in a D dimensional polytope.
+ sample : (N, D) array, or (D, N) array_like
+ The data to be histogrammed.
+
+ Note the unusual interpretation of sample when an array_like:
+
+ * When an array, each row is a coordinate in a D-dimensional space -
+ such as ``histogramgramdd(np.array([p1, p2, p3]))``.
+ * When an array_like, each element is the list of values for single
+ coordinate - such as ``histogramgramdd((X, Y, Z))``.
+
+ The first form should be preferred.
+
bins : sequence or int, optional
The bin specification:
@@ -791,9 +816,12 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
* The number of bins for all dimensions (nx=ny=...=bins).
range : sequence, optional
- A sequence of lower and upper bin edges to be used if the edges are
- not given explicitly in `bins`. Defaults to the minimum and maximum
- values along each dimension.
+ A sequence of length D, each an optional (lower, upper) tuple giving
+ the outer bin edges to be used if the edges are not given explicitly in
+ `bins`.
+ An entry of None in the sequence results in the minimum and maximum
+ values being used for the corresponding dimension.
+ The default, None, is equivalent to passing a tuple of D None values.
normed : bool, optional
If False, returns the number of samples in each bin. If True,
returns the bin density ``bin_count / sample_count / bin_volume``.
@@ -849,69 +877,54 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
# bins is an integer
bins = D*[bins]
- # Select range for each dimension
- # Used only if number of bins is given.
- if range is None:
- # Handle empty input. Range can't be determined in that case, use 0-1.
- if N == 0:
- smin = np.zeros(D)
- smax = np.ones(D)
- else:
- smin = np.atleast_1d(np.array(sample.min(0), float))
- smax = np.atleast_1d(np.array(sample.max(0), float))
- else:
- if not np.all(np.isfinite(range)):
- raise ValueError(
- 'range parameter must be finite.')
- smin = np.zeros(D)
- smax = np.zeros(D)
- for i in np.arange(D):
- smin[i], smax[i] = range[i]
-
- # Make sure the bins have a finite width.
- for i in np.arange(len(smin)):
- if smin[i] == smax[i]:
- smin[i] = smin[i] - .5
- smax[i] = smax[i] + .5
-
# avoid rounding issues for comparisons when dealing with inexact types
if np.issubdtype(sample.dtype, np.inexact):
edge_dt = sample.dtype
else:
edge_dt = float
+
+ # normalize the range argument
+ if range is None:
+ range = (None,) * D
+ elif len(range) != D:
+ raise ValueError('range argument must have one entry per dimension')
+
# Create edge arrays
- for i in np.arange(D):
- if np.isscalar(bins[i]):
+ for i in _range(D):
+ if np.ndim(bins[i]) == 0:
if bins[i] < 1:
raise ValueError(
- "Element at index %s in `bins` should be a positive "
- "integer." % i)
- nbin[i] = bins[i] + 2 # +2 for outlier bins
- edges[i] = np.linspace(smin[i], smax[i], nbin[i]-1, dtype=edge_dt)
- else:
+ '`bins[{}]` must be positive, when an integer'.format(i))
+ smin, smax = _get_outer_edges(sample[:,i], range[i])
+ edges[i] = np.linspace(smin, smax, bins[i] + 1, dtype=edge_dt)
+ elif np.ndim(bins[i]) == 1:
edges[i] = np.asarray(bins[i], edge_dt)
- nbin[i] = len(edges[i]) + 1 # +1 for outlier bins
- dedges[i] = np.diff(edges[i])
- if np.any(np.asarray(dedges[i]) <= 0):
+ # not just monotonic, due to the use of mindiff below
+ if np.any(edges[i][:-1] >= edges[i][1:]):
+ raise ValueError(
+ '`bins[{}]` must be strictly increasing, when an array'
+ .format(i))
+ else:
raise ValueError(
- "Found bin edge of size <= 0. Did you specify `bins` with"
- "non-monotonic sequence?")
+ '`bins[{}]` must be a scalar or 1d array'.format(i))
- nbin = np.asarray(nbin)
+ nbin[i] = len(edges[i]) + 1 # includes an outlier on each end
+ dedges[i] = np.diff(edges[i])
# Handle empty input.
if N == 0:
return np.zeros(nbin-2), edges
# Compute the bin number each sample falls into.
- Ncount = {}
- for i in np.arange(D):
- Ncount[i] = np.digitize(sample[:, i], edges[i])
+ Ncount = tuple(
+ np.digitize(sample[:, i], edges[i])
+ for i in _range(D)
+ )
# Using digitize, values that fall on an edge are put in the right bin.
# For the rightmost bin, we want values equal to the right edge to be
# counted in the last bin, and not as an outlier.
- for i in np.arange(D):
+ for i in _range(D):
# Rounding precision
mindiff = dedges[i].min()
if not np.isinf(mindiff):
@@ -921,35 +934,21 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
on_edge = (np.around(sample[:, i], decimal) ==
np.around(edges[i][-1], decimal))
# Shift these points one bin to the left.
- Ncount[i][np.nonzero(on_edge & not_smaller_than_edge)[0]] -= 1
-
- # Flattened histogram matrix (1D)
- # Reshape is used so that overlarge arrays
- # will raise an error.
- hist = np.zeros(nbin, float).reshape(-1)
+ Ncount[i][on_edge & not_smaller_than_edge] -= 1
# Compute the sample indices in the flattened histogram matrix.
- ni = nbin.argsort()
- xy = np.zeros(N, int)
- for i in np.arange(0, D-1):
- xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod()
- xy += Ncount[ni[-1]]
+ # This raises an error if the array is too large.
+ xy = np.ravel_multi_index(Ncount, nbin)
# Compute the number of repetitions in xy and assign it to the
# flattened histmat.
- if len(xy) == 0:
- return np.zeros(nbin-2, int), edges
-
- flatcount = np.bincount(xy, weights)
- a = np.arange(len(flatcount))
- hist[a] = flatcount
+ hist = np.bincount(xy, weights, minlength=nbin.prod())
# Shape into a proper matrix
- hist = hist.reshape(np.sort(nbin))
- for i in np.arange(nbin.size):
- j = ni.argsort()[i]
- hist = hist.swapaxes(i, j)
- ni[i], ni[j] = ni[j], ni[i]
+ hist = hist.reshape(nbin)
+
+ # This preserves the (bad) behavior observed in gh-7845, for now.
+ hist = hist.astype(float, casting='safe')
# Remove outliers (indices 0 and -1 for each dimension).
core = D*(slice(1, -1),)
@@ -958,7 +957,7 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
# Normalize if normed is True
if normed:
s = hist.sum()
- for i in np.arange(D):
+ for i in _range(D):
shape = np.ones(D, int)
shape[i] = nbin[i] - 2
hist = hist / dedges[i].reshape(shape)
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
index 0f338d781..29688f73d 100644
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -758,7 +758,7 @@ def _getconv(dtype):
elif issubclass(typ, np.floating):
return floatconv
elif issubclass(typ, complex):
- return lambda x: complex(asstr(x))
+ return lambda x: complex(asstr(x).replace('+-', '-'))
elif issubclass(typ, np.bytes_):
return asbytes
elif issubclass(typ, np.unicode_):
@@ -1377,7 +1377,8 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
for number in row:
row2.append(number.real)
row2.append(number.imag)
- fh.write(format % tuple(row2) + newline)
+ s = format % tuple(row2) + newline
+ fh.write(s.replace('+-', '-'))
else:
for row in X:
try:
@@ -1719,7 +1720,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
try:
while not first_values:
first_line = _decode_line(next(fhd), encoding)
- if names is True:
+ if (names is True) and (comments is not None):
if comments in first_line:
first_line = (
''.join(first_line.split(comments)[1:]))
@@ -1733,8 +1734,9 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
# Should we take the first values as names ?
if names is True:
fval = first_values[0].strip()
- if fval in comments:
- del first_values[0]
+ if comments is not None:
+ if fval in comments:
+ del first_values[0]
# Check the columns to use: make sure `usecols` is a list
if usecols is not None:
diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py
index a9cb157f3..32812990c 100644
--- a/numpy/lib/tests/test__datasource.py
+++ b/numpy/lib/tests/test__datasource.py
@@ -5,9 +5,7 @@ import sys
from tempfile import mkdtemp, mkstemp, NamedTemporaryFile
from shutil import rmtree
-from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_raises, SkipTest,
- )
+from numpy.testing import assert_, assert_equal, assert_raises, SkipTest
import numpy.lib._datasource as datasource
if sys.version_info[0] >= 3:
@@ -342,7 +340,3 @@ class TestOpenFunc(object):
fp = datasource.open(local_file)
assert_(fp)
fp.close()
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test__iotools.py b/numpy/lib/tests/test__iotools.py
index 54fac8da4..5f6c29a4d 100644
--- a/numpy/lib/tests/test__iotools.py
+++ b/numpy/lib/tests/test__iotools.py
@@ -6,7 +6,7 @@ from datetime import date
import numpy as np
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_allclose, assert_raises,
+ assert_, assert_equal, assert_allclose, assert_raises,
)
from numpy.lib._iotools import (
LineSplitter, NameValidator, StringConverter,
@@ -346,6 +346,3 @@ class TestMiscFunctions(object):
dt = np.dtype([(("a", "A"), "f8"), (("b", "B"), "f8")])
dt_flat = flatten_dtype(dt)
assert_equal(dt_flat, [float, float])
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test__version.py b/numpy/lib/tests/test__version.py
index 993c9d507..8e66a0c03 100644
--- a/numpy/lib/tests/test__version.py
+++ b/numpy/lib/tests/test__version.py
@@ -3,7 +3,7 @@
"""
from __future__ import division, absolute_import, print_function
-from numpy.testing import assert_, run_module_suite, assert_raises
+from numpy.testing import assert_, assert_raises
from numpy.lib import NumpyVersion
@@ -64,7 +64,3 @@ def test_dev0_a_b_rc_mixed():
def test_raises():
for ver in ['1.9', '1,9.0', '1.7.x']:
assert_raises(ValueError, NumpyVersion, ver)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_arraypad.py b/numpy/lib/tests/test_arraypad.py
index fce4c451d..8be49ce67 100644
--- a/numpy/lib/tests/test_arraypad.py
+++ b/numpy/lib/tests/test_arraypad.py
@@ -1090,7 +1090,3 @@ class TestTypeError1(object):
kwargs = dict(mode='mean', stat_length=(3, ))
assert_raises(TypeError, pad, arr, ((2, 3, 4), (3, 2)),
**kwargs)
-
-
-if __name__ == "__main__":
- np.testing.run_module_suite()
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
index 8286834a4..76c36c53e 100644
--- a/numpy/lib/tests/test_arraysetops.py
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -6,9 +6,7 @@ from __future__ import division, absolute_import, print_function
import numpy as np
import sys
-from numpy.testing import (
- run_module_suite, assert_array_equal, assert_equal, assert_raises,
- )
+from numpy.testing import assert_array_equal, assert_equal, assert_raises
from numpy.lib.arraysetops import (
ediff1d, intersect1d, setxor1d, union1d, setdiff1d, unique, in1d, isin
)
@@ -504,7 +502,3 @@ class TestUnique(object):
assert_array_equal(uniq[:, inv], data)
msg = "Unique's return_counts=True failed with axis=1"
assert_array_equal(cnt, np.array([2, 1, 1]), msg)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_arrayterator.py b/numpy/lib/tests/test_arrayterator.py
index 64ad7f4de..2ce4456a5 100644
--- a/numpy/lib/tests/test_arrayterator.py
+++ b/numpy/lib/tests/test_arrayterator.py
@@ -46,7 +46,3 @@ def test():
# Check that all elements are iterated correctly
assert_(list(c.flat) == list(d.flat))
-
-if __name__ == '__main__':
- from numpy.testing import run_module_suite
- run_module_suite()
diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py
index c5e92dbc0..524915041 100644
--- a/numpy/lib/tests/test_financial.py
+++ b/numpy/lib/tests/test_financial.py
@@ -4,9 +4,8 @@ from decimal import Decimal
import numpy as np
from numpy.testing import (
- run_module_suite, assert_, assert_almost_equal, assert_allclose,
- assert_equal, assert_raises
-)
+ assert_, assert_almost_equal, assert_allclose, assert_equal, assert_raises
+ )
class TestFinancial(object):
@@ -339,7 +338,3 @@ class TestFinancial(object):
Decimal('0'), [Decimal('0'), Decimal('0'), Decimal('1'), 'end', 'begin']),
[Decimal('-74.998201'), Decimal('-75.62318601'), Decimal('-75.62318601'),
Decimal('-76.88882405'), Decimal('-76.88882405')], 4)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py
index d3bd2cef7..38a9b8000 100644
--- a/numpy/lib/tests/test_format.py
+++ b/numpy/lib/tests/test_format.py
@@ -1,5 +1,6 @@
from __future__ import division, absolute_import, print_function
+# doctest
r''' Test the .npy file format.
Set up:
@@ -275,18 +276,17 @@ Test the header writing.
"v\x00{'descr': [('x', '>i4', (2,)), ('y', '>f8', (2, 2)), ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
"\x16\x02{'descr': [('x', '>i4', (2,)),\n ('Info',\n [('value', '>c16'),\n ('y2', '>f8'),\n ('Info2',\n [('name', '|S2'),\n ('value', '>c16', (2,)),\n ('y3', '>f8', (2,)),\n ('z3', '>u4', (2,))]),\n ('name', '|S2'),\n ('z2', '|b1')]),\n ('color', '|S2'),\n ('info', [('Name', '>U8'), ('Value', '>c16')]),\n ('y', '>f8', (2, 2)),\n ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
'''
-
import sys
import os
import shutil
import tempfile
import warnings
+import pytest
from io import BytesIO
import numpy as np
from numpy.testing import (
- run_module_suite, assert_, assert_array_equal, assert_raises, raises,
- dec, SkipTest
+ assert_, assert_array_equal, assert_raises, raises, SkipTest
)
from numpy.lib import format
@@ -477,7 +477,7 @@ def test_long_str():
assert_array_equal(long_str_arr, long_str_arr2)
-@dec.slow
+@pytest.mark.slow
def test_memmap_roundtrip():
# Fixme: test crashes nose on windows.
if not (sys.platform == 'win32' or sys.platform == 'cygwin'):
@@ -628,7 +628,7 @@ def test_version_2_0():
assert_raises(ValueError, format.write_array, f, d, (1, 0))
-@dec.slow
+@pytest.mark.slow
def test_version_2_0_memmap():
# requires more than 2 byte for header
dt = [(("%d" % i) * 100, float) for i in range(500)]
@@ -832,8 +832,9 @@ def test_large_file_support():
assert_array_equal(r, d)
-@dec.slow
-@dec.skipif(np.dtype(np.intp).itemsize < 8, "test requires 64-bit system")
+@pytest.mark.skipif(np.dtype(np.intp).itemsize < 8,
+ reason="test requires 64-bit system")
+@pytest.mark.slow
def test_large_archive():
# Regression test for product of saving arrays with dimensions of array
# having a product that doesn't fit in int32. See gh-7598 for details.
@@ -851,7 +852,3 @@ def test_large_archive():
new_a = np.load(f)["arr"]
assert_(a.shape == new_a.shape)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index c28257c6d..6653b5ba1 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -4,15 +4,16 @@ import operator
import warnings
import sys
import decimal
+import pytest
import numpy as np
from numpy import ma
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_array_equal,
- assert_almost_equal, assert_array_almost_equal, assert_raises,
- assert_allclose, assert_array_max_ulp, assert_warns, assert_raises_regex,
- dec, suppress_warnings,
-)
+ assert_, assert_equal, assert_array_equal, assert_almost_equal,
+ assert_array_almost_equal, assert_raises, assert_allclose,
+ assert_array_max_ulp, assert_warns, assert_raises_regex, suppress_warnings,
+ HAS_REFCOUNT,
+ )
import numpy.lib.function_base as nfb
from numpy.random import rand
from numpy.lib import (
@@ -21,7 +22,7 @@ from numpy.lib import (
histogram, histogramdd, i0, insert, interp, kaiser, meshgrid, msort,
piecewise, place, rot90, select, setxor1d, sinc, split, trapz, trim_zeros,
unwrap, unique, vectorize
-)
+ )
from numpy.compat import long
@@ -103,9 +104,10 @@ class TestRot90(object):
class TestFlip(object):
def test_axes(self):
- assert_raises(ValueError, np.flip, np.ones(4), axis=1)
- assert_raises(ValueError, np.flip, np.ones((4, 4)), axis=2)
- assert_raises(ValueError, np.flip, np.ones((4, 4)), axis=-3)
+ assert_raises(np.AxisError, np.flip, np.ones(4), axis=1)
+ assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=2)
+ assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=-3)
+ assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=(0, 3))
def test_basic_lr(self):
a = get_mat(4)
@@ -172,6 +174,35 @@ class TestFlip(object):
assert_equal(np.flip(a, i),
np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))
+ def test_default_axis(self):
+ a = np.array([[1, 2, 3],
+ [4, 5, 6]])
+ b = np.array([[6, 5, 4],
+ [3, 2, 1]])
+ assert_equal(np.flip(a), b)
+
+ def test_multiple_axes(self):
+ a = np.array([[[0, 1],
+ [2, 3]],
+ [[4, 5],
+ [6, 7]]])
+
+ assert_equal(np.flip(a, axis=()), a)
+
+ b = np.array([[[5, 4],
+ [7, 6]],
+ [[1, 0],
+ [3, 2]]])
+
+ assert_equal(np.flip(a, axis=(0, 2)), b)
+
+ c = np.array([[[3, 2],
+ [1, 0]],
+ [[7, 6],
+ [5, 4]]])
+
+ assert_equal(np.flip(a, axis=(1, 2)), c)
+
class TestAny(object):
@@ -2143,7 +2174,7 @@ class TestBincount(object):
"must not be negative",
lambda: np.bincount(x, minlength=-1))
- @dec._needs_refcount
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
def test_dtype_reference_leaks(self):
# gh-6805
intp_refcount = sys.getrefcount(np.dtype(np.intp))
@@ -2987,14 +3018,10 @@ class TestAdd_newdoc_ufunc(object):
class TestAdd_newdoc(object):
- @dec.skipif(sys.flags.optimize == 2)
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
def test_add_doc(self):
# test np.add_newdoc
tgt = "Current flat index into the array."
assert_equal(np.core.flatiter.index.__doc__[:len(tgt)], tgt)
assert_(len(np.core.ufunc.identity.__doc__) > 300)
assert_(len(np.lib.index_tricks.mgrid.__doc__) > 300)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_histograms.py b/numpy/lib/tests/test_histograms.py
index 4f7af214c..06daacbdc 100644
--- a/numpy/lib/tests/test_histograms.py
+++ b/numpy/lib/tests/test_histograms.py
@@ -4,11 +4,10 @@ import numpy as np
from numpy.lib.histograms import histogram, histogramdd, histogram_bin_edges
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_array_equal,
- assert_almost_equal, assert_array_almost_equal, assert_raises,
- assert_allclose, assert_array_max_ulp, assert_warns, assert_raises_regex,
- dec, suppress_warnings, HAS_REFCOUNT,
-)
+ assert_, assert_equal, assert_array_equal, assert_almost_equal,
+ assert_array_almost_equal, assert_raises, assert_allclose,
+ assert_array_max_ulp, assert_warns, assert_raises_regex, suppress_warnings,
+ )
class TestHistogram(object):
@@ -444,6 +443,24 @@ class TestHistogramOptimBinNums(object):
assert_equal(len(a), numbins, err_msg="{0} estimator, "
"No Variance test".format(estimator))
+ def test_limited_variance(self):
+ """
+ Check when IQR is 0, but variance exists, we return the sturges value
+ and not the fd value.
+ """
+ lim_var_data = np.ones(1000)
+ lim_var_data[:3] = 0
+ lim_var_data[-4:] = 100
+
+ edges_auto = histogram_bin_edges(lim_var_data, 'auto')
+ assert_equal(edges_auto, np.linspace(0, 100, 12))
+
+ edges_fd = histogram_bin_edges(lim_var_data, 'fd')
+ assert_equal(edges_fd, np.array([0, 100]))
+
+ edges_sturges = histogram_bin_edges(lim_var_data, 'sturges')
+ assert_equal(edges_sturges, np.linspace(0, 100, 12))
+
def test_outlier(self):
"""
Check the FD, Scott and Doane with outliers.
@@ -643,7 +660,3 @@ class TestHistogramdd(object):
range=[[0.0, 1.0], [0.25, 0.75], [0.25, np.inf]])
assert_raises(ValueError, histogramdd, vals,
range=[[0.0, 1.0], [np.nan, 0.75], [0.25, 0.5]])
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py
index 0520ce580..f934e952a 100644
--- a/numpy/lib/tests/test_index_tricks.py
+++ b/numpy/lib/tests/test_index_tricks.py
@@ -2,9 +2,8 @@ from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_array_equal,
- assert_almost_equal, assert_array_almost_equal, assert_raises,
- assert_raises_regex
+ assert_, assert_equal, assert_array_equal, assert_almost_equal,
+ assert_array_almost_equal, assert_raises, assert_raises_regex
)
from numpy.lib.index_tricks import (
mgrid, ndenumerate, fill_diagonal, diag_indices, diag_indices_from,
@@ -285,71 +284,77 @@ def test_c_():
assert_equal(a, [[1, 2, 3, 0, 0, 4, 5, 6]])
-def test_fill_diagonal():
- a = np.zeros((3, 3), int)
- fill_diagonal(a, 5)
- yield (assert_array_equal, a,
- np.array([[5, 0, 0],
- [0, 5, 0],
- [0, 0, 5]]))
-
- #Test tall matrix
- a = np.zeros((10, 3), int)
- fill_diagonal(a, 5)
- yield (assert_array_equal, a,
- np.array([[5, 0, 0],
- [0, 5, 0],
- [0, 0, 5],
- [0, 0, 0],
- [0, 0, 0],
- [0, 0, 0],
- [0, 0, 0],
- [0, 0, 0],
- [0, 0, 0],
- [0, 0, 0]]))
-
- #Test tall matrix wrap
- a = np.zeros((10, 3), int)
- fill_diagonal(a, 5, True)
- yield (assert_array_equal, a,
- np.array([[5, 0, 0],
- [0, 5, 0],
- [0, 0, 5],
- [0, 0, 0],
- [5, 0, 0],
- [0, 5, 0],
- [0, 0, 5],
- [0, 0, 0],
- [5, 0, 0],
- [0, 5, 0]]))
-
- #Test wide matrix
- a = np.zeros((3, 10), int)
- fill_diagonal(a, 5)
- yield (assert_array_equal, a,
- np.array([[5, 0, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 5, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 5, 0, 0, 0, 0, 0, 0, 0]]))
-
- # The same function can operate on a 4-d array:
- a = np.zeros((3, 3, 3, 3), int)
- fill_diagonal(a, 4)
- i = np.array([0, 1, 2])
- yield (assert_equal, np.where(a != 0), (i, i, i, i))
+class TestFillDiagonal(object):
+ def test_basic(self):
+ a = np.zeros((3, 3), int)
+ fill_diagonal(a, 5)
+ assert_array_equal(
+ a, np.array([[5, 0, 0],
+ [0, 5, 0],
+ [0, 0, 5]])
+ )
+
+ def test_tall_matrix(self):
+ a = np.zeros((10, 3), int)
+ fill_diagonal(a, 5)
+ assert_array_equal(
+ a, np.array([[5, 0, 0],
+ [0, 5, 0],
+ [0, 0, 5],
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0]])
+ )
+
+ def test_tall_matrix_wrap(self):
+ a = np.zeros((10, 3), int)
+ fill_diagonal(a, 5, True)
+ assert_array_equal(
+ a, np.array([[5, 0, 0],
+ [0, 5, 0],
+ [0, 0, 5],
+ [0, 0, 0],
+ [5, 0, 0],
+ [0, 5, 0],
+ [0, 0, 5],
+ [0, 0, 0],
+ [5, 0, 0],
+ [0, 5, 0]])
+ )
+
+ def test_wide_matrix(self):
+ a = np.zeros((3, 10), int)
+ fill_diagonal(a, 5)
+ assert_array_equal(
+ a, np.array([[5, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 5, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 5, 0, 0, 0, 0, 0, 0, 0]])
+ )
+
+ def test_operate_4d_array(self):
+ a = np.zeros((3, 3, 3, 3), int)
+ fill_diagonal(a, 4)
+ i = np.array([0, 1, 2])
+ assert_equal(np.where(a != 0), (i, i, i, i))
def test_diag_indices():
di = diag_indices(4)
a = np.array([[1, 2, 3, 4],
- [5, 6, 7, 8],
- [9, 10, 11, 12],
- [13, 14, 15, 16]])
+ [5, 6, 7, 8],
+ [9, 10, 11, 12],
+ [13, 14, 15, 16]])
a[di] = 100
- yield (assert_array_equal, a,
- np.array([[100, 2, 3, 4],
- [5, 100, 7, 8],
- [9, 10, 100, 12],
- [13, 14, 15, 100]]))
+ assert_array_equal(
+ a, np.array([[100, 2, 3, 4],
+ [5, 100, 7, 8],
+ [9, 10, 100, 12],
+ [13, 14, 15, 100]])
+ )
# Now, we create indices to manipulate a 3-d array:
d3 = diag_indices(2, 3)
@@ -357,12 +362,12 @@ def test_diag_indices():
# And use it to set the diagonal of a zeros array to 1:
a = np.zeros((2, 2, 2), int)
a[d3] = 1
- yield (assert_array_equal, a,
- np.array([[[1, 0],
- [0, 0]],
-
- [[0, 0],
- [0, 1]]]))
+ assert_array_equal(
+ a, np.array([[[1, 0],
+ [0, 0]],
+ [[0, 0],
+ [0, 1]]])
+ )
def test_diag_indices_from():
@@ -394,7 +399,3 @@ def test_ndindex():
# Make sure 0-sized ndindex works correctly
x = list(ndindex(*[0]))
assert_equal(x, [])
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index a0f256726..84aca9915 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -4,15 +4,16 @@ import sys
import gzip
import os
import threading
-from tempfile import NamedTemporaryFile
import time
import warnings
import gc
import io
+import re
+import pytest
+from tempfile import NamedTemporaryFile
from io import BytesIO, StringIO
from datetime import datetime
import locale
-import re
import numpy as np
import numpy.ma as ma
@@ -20,10 +21,10 @@ from numpy.lib._iotools import ConverterError, ConversionWarning
from numpy.compat import asbytes, bytes, unicode, Path
from numpy.ma.testutils import assert_equal
from numpy.testing import (
- run_module_suite, assert_warns, assert_, SkipTest,
- assert_raises_regex, assert_raises, assert_allclose,
- assert_array_equal, temppath, tempdir, dec, IS_PYPY, suppress_warnings,
-)
+ assert_warns, assert_, SkipTest, assert_raises_regex, assert_raises,
+ assert_allclose, assert_array_equal, temppath, tempdir, IS_PYPY,
+ HAS_REFCOUNT, suppress_warnings,
+ )
class TextIO(BytesIO):
@@ -156,7 +157,7 @@ class RoundtripTest(object):
a = np.array([1, 2, 3, 4], int)
self.roundtrip(a)
- @dec.knownfailureif(sys.platform == 'win32', "Fail on Win32")
+ @pytest.mark.skipif(sys.platform == 'win32', reason="Fails on Win32")
def test_mmap(self):
a = np.array([[1, 2.5], [4, 7.3]])
self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})
@@ -168,7 +169,7 @@ class RoundtripTest(object):
a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
self.check_roundtrips(a)
- @dec.slow
+ @pytest.mark.slow
def test_format_2_0(self):
dt = [(("%d" % i) * 100, float) for i in range(500)]
a = np.ones(1000, dtype=dt)
@@ -200,8 +201,8 @@ class TestSavezLoad(RoundtripTest):
self.arr_reloaded.fid.close()
os.remove(self.arr_reloaded.fid.name)
- @dec.skipif(not IS_64BIT, "Works only with 64bit systems")
- @dec.slow
+ @pytest.mark.skipif(not IS_64BIT, reason="Needs 64bit platform")
+ @pytest.mark.slow
def test_big_arrays(self):
L = (1 << 31) + 100000
a = np.empty(L, dtype=np.uint8)
@@ -277,7 +278,8 @@ class TestSavezLoad(RoundtripTest):
fp.seek(0)
assert_(not fp.closed)
- @dec.skipif(IS_PYPY, "context manager required on PyPy")
+ #FIXME: Is this still true?
+ @pytest.mark.skipif(IS_PYPY, reason="Missing context manager on PyPy")
def test_closing_fid(self):
# Test that issue #1517 (too many opened files) remains closed
# It might be a "weak" test since failed to get triggered on
@@ -466,6 +468,26 @@ class TestSaveTxt(object):
[b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n',
b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n'])
+ def test_complex_negative_exponent(self):
+ # Previous to 1.15, some formats generated x+-yj, gh 7895
+ ncols = 2
+ nrows = 2
+ a = np.zeros((ncols, nrows), dtype=np.complex128)
+ re = np.pi
+ im = np.e
+ a[:] = re - 1.0j * im
+ c = BytesIO()
+ np.savetxt(c, a, fmt='%.3e')
+ c.seek(0)
+ lines = c.readlines()
+ assert_equal(
+ lines,
+ [b' (3.142e+00-2.718e+00j) (3.142e+00-2.718e+00j)\n',
+ b' (3.142e+00-2.718e+00j) (3.142e+00-2.718e+00j)\n'])
+
+
+
+
def test_custom_writer(self):
class CustomWriter(list):
@@ -540,15 +562,17 @@ class LoadTxtBase(object):
assert_array_equal(res, wanted)
# Python2 .open does not support encoding
- @dec.skipif(MAJVER == 2)
+ @pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3")
def test_compressed_gzip(self):
self.check_compressed(gzip.open, ('.gz',))
- @dec.skipif(MAJVER == 2 or not HAS_BZ2)
+ @pytest.mark.skipif(not HAS_BZ2, reason="Needs bz2")
+ @pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3")
def test_compressed_gzip(self):
self.check_compressed(bz2.open, ('.bz2',))
- @dec.skipif(MAJVER == 2 or not HAS_LZMA)
+ @pytest.mark.skipif(not HAS_LZMA, reason="Needs lzma")
+ @pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3")
def test_compressed_gzip(self):
self.check_compressed(lzma.open, ('.xz', '.lzma'))
@@ -599,11 +623,11 @@ class LoadTxtBase(object):
class TestLoadTxt(LoadTxtBase):
loadfunc = staticmethod(np.loadtxt)
- def setUp(self):
+ def setup(self):
# lower chunksize for testing
self.orig_chunk = np.lib.npyio._loadtxt_chunksize
np.lib.npyio._loadtxt_chunksize = 1
- def tearDown(self):
+ def teardown(self):
np.lib.npyio._loadtxt_chunksize = self.orig_chunk
def test_record(self):
@@ -912,6 +936,26 @@ class TestLoadTxt(LoadTxtBase):
res = np.loadtxt(c, dtype=complex)
assert_equal(res, tgt)
+ def test_complex_misformatted(self):
+ # test for backward compatability
+ # some complex formats used to generate x+-yj
+ a = np.zeros((2, 2), dtype=np.complex128)
+ re = np.pi
+ im = np.e
+ a[:] = re - 1.0j * im
+ c = BytesIO()
+ np.savetxt(c, a, fmt='%.16e')
+ c.seek(0)
+ txt = c.read()
+ c.seek(0)
+ # misformat the sign on the imaginary part, gh 7895
+ txt_bad = txt.replace(b'e+00-', b'e00+-')
+ assert_(txt_bad != txt)
+ c.write(txt_bad)
+ c.seek(0)
+ res = np.loadtxt(c, dtype=complex)
+ assert_equal(res, a)
+
def test_universal_newline(self):
with temppath() as name:
with open(name, 'w') as f:
@@ -1007,7 +1051,8 @@ class TestLoadTxt(LoadTxtBase):
dt = np.dtype([('x', int), ('a', 'S10'), ('y', int)])
np.loadtxt(c, delimiter=',', dtype=dt, comments=None) # Should succeed
- @dec.skipif(locale.getpreferredencoding() == 'ANSI_X3.4-1968')
+ @pytest.mark.skipif(locale.getpreferredencoding() == 'ANSI_X3.4-1968',
+ reason="Wrong preferred encoding")
def test_binary_load(self):
butf8 = b"5,6,7,\xc3\x95scarscar\n\r15,2,3,hello\n\r"\
b"20,2,3,\xc3\x95scar\n\r"
@@ -1272,6 +1317,13 @@ M 33 21.99
assert_(w[0].category is np.VisibleDeprecationWarning)
assert_equal(test, ctrl)
+ def test_names_and_comments_none(self):
+ # Tests case when names is true but comments is None (gh-10780)
+ data = TextIO('col1 col2\n 1 2\n 3 4')
+ test = np.genfromtxt(data, dtype=(int, int), comments=None, names=True)
+ control = np.array([(1, 2), (3, 4)], dtype=[('col1', int), ('col2', int)])
+ assert_equal(test, control)
+
def test_autonames_and_usecols(self):
# Tests names and usecols
data = TextIO('A B C D\n aaaa 121 45 9.1')
@@ -1984,7 +2036,6 @@ M 33 21.99
# encoding of io.open. Will need to change this for PyTest, maybe
# using pytest.mark.xfail(raises=***).
try:
- import locale
encoding = locale.getpreferredencoding()
utf8.encode(encoding)
except (UnicodeError, ImportError):
@@ -2189,9 +2240,9 @@ M 33 21.99
assert_equal(test['f2'], 1024)
+@pytest.mark.skipif(Path is None, reason="No pathlib.Path")
class TestPathUsage(object):
# Test that pathlib.Path can be used
- @dec.skipif(Path is None, "No pathlib.Path")
def test_loadtxt(self):
with temppath(suffix='.txt') as path:
path = Path(path)
@@ -2200,7 +2251,6 @@ class TestPathUsage(object):
x = np.loadtxt(path)
assert_array_equal(x, a)
- @dec.skipif(Path is None, "No pathlib.Path")
def test_save_load(self):
# Test that pathlib.Path instances can be used with savez.
with temppath(suffix='.npy') as path:
@@ -2210,7 +2260,6 @@ class TestPathUsage(object):
data = np.load(path)
assert_array_equal(data, a)
- @dec.skipif(Path is None, "No pathlib.Path")
def test_savez_load(self):
# Test that pathlib.Path instances can be used with savez.
with temppath(suffix='.npz') as path:
@@ -2218,8 +2267,7 @@ class TestPathUsage(object):
np.savez(path, lab='place holder')
with np.load(path) as data:
assert_array_equal(data['lab'], 'place holder')
-
- @dec.skipif(Path is None, "No pathlib.Path")
+
def test_savez_compressed_load(self):
# Test that pathlib.Path instances can be used with savez.
with temppath(suffix='.npz') as path:
@@ -2229,7 +2277,6 @@ class TestPathUsage(object):
assert_array_equal(data['lab'], 'place holder')
data.close()
- @dec.skipif(Path is None, "No pathlib.Path")
def test_genfromtxt(self):
with temppath(suffix='.txt') as path:
path = Path(path)
@@ -2238,7 +2285,6 @@ class TestPathUsage(object):
data = np.genfromtxt(path)
assert_array_equal(a, data)
- @dec.skipif(Path is None, "No pathlib.Path")
def test_ndfromtxt(self):
# Test outputting a standard ndarray
with temppath(suffix='.txt') as path:
@@ -2250,7 +2296,6 @@ class TestPathUsage(object):
test = np.ndfromtxt(path, dtype=int)
assert_array_equal(test, control)
- @dec.skipif(Path is None, "No pathlib.Path")
def test_mafromtxt(self):
# From `test_fancy_dtype_alt` above
with temppath(suffix='.txt') as path:
@@ -2262,7 +2307,6 @@ class TestPathUsage(object):
control = ma.array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)])
assert_equal(test, control)
- @dec.skipif(Path is None, "No pathlib.Path")
def test_recfromtxt(self):
with temppath(suffix='.txt') as path:
path = Path(path)
@@ -2276,7 +2320,6 @@ class TestPathUsage(object):
assert_(isinstance(test, np.recarray))
assert_equal(test, control)
- @dec.skipif(Path is None, "No pathlib.Path")
def test_recfromcsv(self):
with temppath(suffix='.txt') as path:
path = Path(path)
@@ -2364,7 +2407,7 @@ def test_npzfile_dict():
assert_('x' in z.keys())
-@dec._needs_refcount
+@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
def test_load_refcount():
# Check that objects returned by np.load are directly freed based on
# their refcount, rather than needing the gc to collect them.
@@ -2384,6 +2427,3 @@ def test_load_refcount():
finally:
gc.enable()
assert_equal(n_objects_in_cycles, 0)
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_mixins.py b/numpy/lib/tests/test_mixins.py
index 94f06c336..f2d915502 100644
--- a/numpy/lib/tests/test_mixins.py
+++ b/numpy/lib/tests/test_mixins.py
@@ -5,9 +5,7 @@ import operator
import sys
import numpy as np
-from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_raises
- )
+from numpy.testing import assert_, assert_equal, assert_raises
PY2 = sys.version_info.major < 3
@@ -213,7 +211,3 @@ class TestNDArrayOperatorsMixin(object):
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py
index 3d362fc6e..1f403f7b8 100644
--- a/numpy/lib/tests/test_nanfunctions.py
+++ b/numpy/lib/tests/test_nanfunctions.py
@@ -4,8 +4,8 @@ import warnings
import numpy as np
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_almost_equal,
- assert_no_warnings, assert_raises, assert_array_equal, suppress_warnings
+ assert_, assert_equal, assert_almost_equal, assert_no_warnings,
+ assert_raises, assert_array_equal, suppress_warnings
)
@@ -886,7 +886,3 @@ class TestNanFunctions_Percentile(object):
megamat = np.ones((3, 4, 5, 6))
assert_equal(np.nanpercentile(megamat, perc, axis=(1, 2)).shape, (2, 3, 6))
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_packbits.py b/numpy/lib/tests/test_packbits.py
index 965cbf67c..fde5c37f2 100644
--- a/numpy/lib/tests/test_packbits.py
+++ b/numpy/lib/tests/test_packbits.py
@@ -1,9 +1,7 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.testing import (
- assert_array_equal, assert_equal, assert_raises, run_module_suite
-)
+from numpy.testing import assert_array_equal, assert_equal, assert_raises
def test_packbits():
@@ -268,7 +266,3 @@ def test_unpackbits_large():
assert_array_equal(np.packbits(np.unpackbits(d, axis=1), axis=1), d)
d = d.T.copy()
assert_array_equal(np.packbits(np.unpackbits(d, axis=0), axis=0), d)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
index 03915cead..7f6fca4a4 100644
--- a/numpy/lib/tests/test_polynomial.py
+++ b/numpy/lib/tests/test_polynomial.py
@@ -1,15 +1,13 @@
-from __future__ import division, absolute_import, print_function
-
'''
>>> p = np.poly1d([1.,2,3])
>>> p
-poly1d([ 1., 2., 3.])
+poly1d([1., 2., 3.])
>>> print(p)
2
1 x + 2 x + 3
>>> q = np.poly1d([3.,2,1])
>>> q
-poly1d([ 3., 2., 1.])
+poly1d([3., 2., 1.])
>>> print(q)
2
3 x + 2 x + 1
@@ -30,23 +28,23 @@ poly1d([ 3., 2., 1.])
86.0
>>> p * q
-poly1d([ 3., 8., 14., 8., 3.])
+poly1d([ 3., 8., 14., 8., 3.])
>>> p / q
-(poly1d([ 0.33333333]), poly1d([ 1.33333333, 2.66666667]))
+(poly1d([0.33333333]), poly1d([1.33333333, 2.66666667]))
>>> p + q
-poly1d([ 4., 4., 4.])
+poly1d([4., 4., 4.])
>>> p - q
poly1d([-2., 0., 2.])
>>> p ** 4
-poly1d([ 1., 8., 36., 104., 214., 312., 324., 216., 81.])
+poly1d([ 1., 8., 36., 104., 214., 312., 324., 216., 81.])
>>> p(q)
-poly1d([ 9., 12., 16., 8., 6.])
+poly1d([ 9., 12., 16., 8., 6.])
>>> q(p)
-poly1d([ 3., 12., 32., 40., 34.])
+poly1d([ 3., 12., 32., 40., 34.])
>>> np.asarray(p)
-array([ 1., 2., 3.])
+array([1., 2., 3.])
>>> len(p)
2
@@ -54,16 +52,16 @@ array([ 1., 2., 3.])
(3.0, 2.0, 1.0, 0)
>>> p.integ()
-poly1d([ 0.33333333, 1. , 3. , 0. ])
+poly1d([0.33333333, 1. , 3. , 0. ])
>>> p.integ(1)
-poly1d([ 0.33333333, 1. , 3. , 0. ])
+poly1d([0.33333333, 1. , 3. , 0. ])
>>> p.integ(5)
-poly1d([ 0.00039683, 0.00277778, 0.025 , 0. , 0. ,
- 0. , 0. , 0. ])
+poly1d([0.00039683, 0.00277778, 0.025 , 0. , 0. ,
+ 0. , 0. , 0. ])
>>> p.deriv()
-poly1d([ 2., 2.])
+poly1d([2., 2.])
>>> p.deriv(2)
-poly1d([ 2.])
+poly1d([2.])
>>> q = np.poly1d([1.,2,3], variable='y')
>>> print(q)
@@ -75,13 +73,15 @@ poly1d([ 2.])
1 lambda + 2 lambda + 3
>>> np.polydiv(np.poly1d([1,0,-1]), np.poly1d([1,1]))
-(poly1d([ 1., -1.]), poly1d([ 0.]))
+(poly1d([ 1., -1.]), poly1d([0.]))
'''
+from __future__ import division, absolute_import, print_function
+
import numpy as np
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_array_equal,
- assert_almost_equal, assert_array_almost_equal, assert_raises, rundocs
+ assert_, assert_equal, assert_array_equal, assert_almost_equal,
+ assert_array_almost_equal, assert_raises, rundocs
)
@@ -243,7 +243,3 @@ class TestDocs(object):
p.coeffs[2] += 10
assert_equal(p.coeffs, [1, 2, 3])
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_recfunctions.py b/numpy/lib/tests/test_recfunctions.py
index bc9f8d7b6..219ae24fa 100644
--- a/numpy/lib/tests/test_recfunctions.py
+++ b/numpy/lib/tests/test_recfunctions.py
@@ -1,12 +1,12 @@
from __future__ import division, absolute_import, print_function
+import pytest
+
import numpy as np
import numpy.ma as ma
from numpy.ma.mrecords import MaskedRecords
from numpy.ma.testutils import assert_equal
-from numpy.testing import (
- run_module_suite, assert_, assert_raises, dec
- )
+from numpy.testing import assert_, assert_raises
from numpy.lib.recfunctions import (
drop_fields, rename_fields, get_fieldstructure, recursive_fill_fields,
find_duplicates, merge_arrays, append_fields, stack_arrays, join_by
@@ -687,7 +687,7 @@ class TestJoinBy(object):
b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])
assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b)
- @dec.knownfailureif(True)
+ @pytest.mark.xfail(reason="See comment at gh-9343")
def test_same_name_different_dtypes_key(self):
a_dtype = np.dtype([('key', 'S5'), ('value', '<f4')])
b_dtype = np.dtype([('key', 'S10'), ('value', '<f4')])
@@ -829,6 +829,3 @@ class TestAppendFieldsObj(object):
control = np.array([(obj, 1.0, 10), (obj, 2.0, 20)],
dtype=[('A', object), ('B', float), ('C', int)])
assert_equal(test, control)
-
-if __name__ == '__main__':
- run_module_suite()
diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py
index d96d3422d..4c46bc46b 100644
--- a/numpy/lib/tests/test_regression.py
+++ b/numpy/lib/tests/test_regression.py
@@ -5,8 +5,8 @@ import sys
import numpy as np
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_array_equal,
- assert_array_almost_equal, assert_raises, _assert_valid_refcount,
+ assert_, assert_equal, assert_array_equal, assert_array_almost_equal,
+ assert_raises, _assert_valid_refcount,
)
from numpy.compat import unicode
@@ -252,7 +252,3 @@ class TestRegression(object):
raise AssertionError()
finally:
out.close()
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py
index d0afeefd9..080fd066d 100644
--- a/numpy/lib/tests/test_shape_base.py
+++ b/numpy/lib/tests/test_shape_base.py
@@ -8,8 +8,7 @@ from numpy.lib.shape_base import (
vsplit, dstack, column_stack, kron, tile, expand_dims,
)
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_array_equal, assert_raises,
- assert_warns
+ assert_, assert_equal, assert_array_equal, assert_raises, assert_warns
)
@@ -569,7 +568,3 @@ class TestMayShareMemory(object):
def compare_results(res, desired):
for i in range(len(desired)):
assert_array_equal(res[i], desired[i])
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py
index 0599324d7..3c2ca8b87 100644
--- a/numpy/lib/tests/test_stride_tricks.py
+++ b/numpy/lib/tests/test_stride_tricks.py
@@ -1,14 +1,13 @@
from __future__ import division, absolute_import, print_function
import numpy as np
-from numpy.core.test_rational import rational
+from numpy.core._rational_tests import rational
from numpy.testing import (
- run_module_suite, assert_equal, assert_array_equal,
- assert_raises, assert_
+ assert_equal, assert_array_equal, assert_raises, assert_
)
from numpy.lib.stride_tricks import (
as_strided, broadcast_arrays, _broadcast_shape, broadcast_to
-)
+ )
def assert_shapes_correct(input_shapes, expected_shape):
# Broadcast a list of arrays with the given input shapes and check the
@@ -432,7 +431,3 @@ def test_reference_types():
actual, _ = broadcast_arrays(input_array, np.ones(3))
assert_array_equal(expected, actual)
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py
index 8183f7ca6..d3a072af3 100644
--- a/numpy/lib/tests/test_twodim_base.py
+++ b/numpy/lib/tests/test_twodim_base.py
@@ -4,14 +4,14 @@
from __future__ import division, absolute_import, print_function
from numpy.testing import (
- run_module_suite, assert_equal, assert_array_equal, assert_array_max_ulp,
+ assert_equal, assert_array_equal, assert_array_max_ulp,
assert_array_almost_equal, assert_raises,
)
from numpy import (
- arange, add, fliplr, flipud, zeros, ones, eye, array, diag,
- histogram2d, tri, mask_indices, triu_indices, triu_indices_from,
- tril_indices, tril_indices_from, vander,
+ arange, add, fliplr, flipud, zeros, ones, eye, array, diag, histogram2d,
+ tri, mask_indices, triu_indices, triu_indices_from, tril_indices,
+ tril_indices_from, vander,
)
import numpy as np
@@ -244,32 +244,32 @@ class TestHistogram2d(object):
def test_binparameter_combination(self):
x = array(
- [0, 0.09207008, 0.64575234, 0.12875982, 0.47390599,
+ [0, 0.09207008, 0.64575234, 0.12875982, 0.47390599,
0.59944483, 1])
y = array(
- [0, 0.14344267, 0.48988575, 0.30558665, 0.44700682,
+ [0, 0.14344267, 0.48988575, 0.30558665, 0.44700682,
0.15886423, 1])
edges = (0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)
H, xe, ye = histogram2d(x, y, (edges, 4))
answer = array(
- [[ 2., 0., 0., 0.],
- [ 0., 1., 0., 0.],
- [ 0., 0., 0., 0.],
- [ 0., 0., 0., 0.],
- [ 0., 1., 0., 0.],
- [ 1., 0., 0., 0.],
- [ 0., 1., 0., 0.],
- [ 0., 0., 0., 0.],
- [ 0., 0., 0., 0.],
- [ 0., 0., 0., 1.]])
+ [[2., 0., 0., 0.],
+ [0., 1., 0., 0.],
+ [0., 0., 0., 0.],
+ [0., 0., 0., 0.],
+ [0., 1., 0., 0.],
+ [1., 0., 0., 0.],
+ [0., 1., 0., 0.],
+ [0., 0., 0., 0.],
+ [0., 0., 0., 0.],
+ [0., 0., 0., 1.]])
assert_array_equal(H, answer)
assert_array_equal(ye, array([0., 0.25, 0.5, 0.75, 1]))
H, xe, ye = histogram2d(x, y, (4, edges))
answer = array(
- [[ 1., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
- [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
- [ 0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
- [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
+ [[1., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
assert_array_equal(H, answer)
assert_array_equal(xe, array([0., 0.25, 0.5, 0.75, 1]))
@@ -288,11 +288,11 @@ def test_tril_triu_ndim2():
a = np.ones((2, 2), dtype=dtype)
b = np.tril(a)
c = np.triu(a)
- yield assert_array_equal, b, [[1, 0], [1, 1]]
- yield assert_array_equal, c, b.T
+ assert_array_equal(b, [[1, 0], [1, 1]])
+ assert_array_equal(c, b.T)
# should return the same dtype as the original array
- yield assert_equal, b.dtype, a.dtype
- yield assert_equal, c.dtype, a.dtype
+ assert_equal(b.dtype, a.dtype)
+ assert_equal(c.dtype, a.dtype)
def test_tril_triu_ndim3():
@@ -314,10 +314,11 @@ def test_tril_triu_ndim3():
], dtype=dtype)
a_triu_observed = np.triu(a)
a_tril_observed = np.tril(a)
- yield assert_array_equal, a_triu_observed, a_triu_desired
- yield assert_array_equal, a_tril_observed, a_tril_desired
- yield assert_equal, a_triu_observed.dtype, a.dtype
- yield assert_equal, a_tril_observed.dtype, a.dtype
+ assert_array_equal(a_triu_observed, a_triu_desired)
+ assert_array_equal(a_tril_observed, a_tril_desired)
+ assert_equal(a_triu_observed.dtype, a.dtype)
+ assert_equal(a_tril_observed.dtype, a.dtype)
+
def test_tril_triu_with_inf():
# Issue 4859
@@ -484,12 +485,12 @@ class TestVander(object):
[16, -8, 4, -2, 1],
[81, 27, 9, 3, 1]])
# Check default value of N:
- yield (assert_array_equal, v, powers[:, 1:])
+ assert_array_equal(v, powers[:, 1:])
# Check a range of N values, including 0 and 5 (greater than default)
m = powers.shape[1]
for n in range(6):
v = vander(c, N=n)
- yield (assert_array_equal, v, powers[:, m-n:m])
+ assert_array_equal(v, powers[:, m-n:m])
def test_dtypes(self):
c = array([11, -12, 13], dtype=np.int8)
@@ -497,7 +498,7 @@ class TestVander(object):
expected = np.array([[121, 11, 1],
[144, -12, 1],
[169, 13, 1]])
- yield (assert_array_equal, v, expected)
+ assert_array_equal(v, expected)
c = array([1.0+1j, 1.0-1j])
v = vander(c, N=3)
@@ -506,8 +507,4 @@ class TestVander(object):
# The data is floating point, but the values are small integers,
# so assert_array_equal *should* be safe here (rather than, say,
# assert_array_almost_equal).
- yield (assert_array_equal, v, expected)
-
-
-if __name__ == "__main__":
- run_module_suite()
+ assert_array_equal(v, expected)
diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py
index ce8ef2f15..2982ca31a 100644
--- a/numpy/lib/tests/test_type_check.py
+++ b/numpy/lib/tests/test_type_check.py
@@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.compat import long
from numpy.testing import (
- assert_, assert_equal, assert_array_equal, run_module_suite, assert_raises
+ assert_, assert_equal, assert_array_equal, assert_raises
)
from numpy.lib.type_check import (
common_type, mintypecode, isreal, iscomplex, isposinf, isneginf,
@@ -440,7 +440,3 @@ class TestArrayConversion(object):
# other numpy function
assert_raises(TypeError,
asfarray, np.array([1, 2, 3]), dtype=np.array(1.0))
-
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py
index 128ce37ab..ad006fe17 100644
--- a/numpy/lib/tests/test_ufunclike.py
+++ b/numpy/lib/tests/test_ufunclike.py
@@ -4,7 +4,7 @@ import numpy as np
import numpy.core as nx
import numpy.lib.ufunclike as ufl
from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_array_equal, assert_warns
+ assert_, assert_equal, assert_array_equal, assert_warns
)
@@ -91,6 +91,3 @@ class TestUfunclike(object):
out = np.array(0.0)
actual = np.fix(x, out=out)
assert_(actual is out)
-
-if __name__ == "__main__":
- run_module_suite()
diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py
index 92bcdc238..c27c3cbf5 100644
--- a/numpy/lib/tests/test_utils.py
+++ b/numpy/lib/tests/test_utils.py
@@ -1,10 +1,10 @@
from __future__ import division, absolute_import, print_function
import sys
+import pytest
+
from numpy.core import arange
-from numpy.testing import (
- run_module_suite, assert_, assert_equal, assert_raises_regex, dec
- )
+from numpy.testing import assert_, assert_equal, assert_raises_regex
from numpy.lib import deprecate
import numpy.lib.utils as utils
@@ -14,7 +14,7 @@ else:
from StringIO import StringIO
-@dec.skipif(sys.flags.optimize == 2)
+@pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
def test_lookfor():
out = StringIO()
utils.lookfor('eigenvalue', module='numpy', output=out,
@@ -65,7 +65,3 @@ def test_byte_bounds():
def test_assert_raises_regex_context_manager():
with assert_raises_regex(ValueError, 'no deprecation warning'):
raise ValueError('no deprecation warning')
-
-
-if __name__ == "__main__":
- run_module_suite()