summaryrefslogtreecommitdiff
path: root/numpy/ma
diff options
context:
space:
mode:
authorCharles Harris <charlesr.harris@gmail.com>2020-12-13 14:14:49 -0700
committerGitHub <noreply@github.com>2020-12-13 14:14:49 -0700
commit3fe2d9d2627fc0f84aeed293ff8afa7c1f08d899 (patch)
tree2ea27fe06a19c39e8d7a5fe2f87cb7e05363247d /numpy/ma
parent7d7e446fcbeeff70d905bde2eb0264a797488280 (diff)
parenteff302e5e8678fa17fb3d8156d49eb585b0876d9 (diff)
downloadnumpy-3fe2d9d2627fc0f84aeed293ff8afa7c1f08d899.tar.gz
Merge branch 'master' into fix-issue-10244
Diffstat (limited to 'numpy/ma')
-rw-r--r--numpy/ma/__init__.pyi225
-rw-r--r--numpy/ma/bench.py10
-rw-r--r--numpy/ma/core.py56
-rw-r--r--numpy/ma/extras.py10
-rw-r--r--numpy/ma/mrecords.py18
-rw-r--r--numpy/ma/setup.py1
-rw-r--r--numpy/ma/tests/test_core.py34
-rw-r--r--numpy/ma/tests/test_old_ma.py2
-rw-r--r--numpy/ma/tests/test_subclassing.py8
-rw-r--r--numpy/ma/testutils.py10
-rw-r--r--numpy/ma/timer_comparison.py22
11 files changed, 316 insertions, 80 deletions
diff --git a/numpy/ma/__init__.pyi b/numpy/ma/__init__.pyi
new file mode 100644
index 000000000..d1259abcc
--- /dev/null
+++ b/numpy/ma/__init__.pyi
@@ -0,0 +1,225 @@
+from typing import Any
+
+core: Any
+extras: Any
+MAError: Any
+MaskError: Any
+MaskType: Any
+MaskedArray: Any
+abs: Any
+absolute: Any
+add: Any
+all: Any
+allclose: Any
+allequal: Any
+alltrue: Any
+amax: Any
+amin: Any
+angle: Any
+anom: Any
+anomalies: Any
+any: Any
+append: Any
+arange: Any
+arccos: Any
+arccosh: Any
+arcsin: Any
+arcsinh: Any
+arctan: Any
+arctan2: Any
+arctanh: Any
+argmax: Any
+argmin: Any
+argsort: Any
+around: Any
+array: Any
+asanyarray: Any
+asarray: Any
+bitwise_and: Any
+bitwise_or: Any
+bitwise_xor: Any
+bool_: Any
+ceil: Any
+choose: Any
+clip: Any
+common_fill_value: Any
+compress: Any
+compressed: Any
+concatenate: Any
+conjugate: Any
+convolve: Any
+copy: Any
+correlate: Any
+cos: Any
+cosh: Any
+count: Any
+cumprod: Any
+cumsum: Any
+default_fill_value: Any
+diag: Any
+diagonal: Any
+diff: Any
+divide: Any
+empty: Any
+empty_like: Any
+equal: Any
+exp: Any
+expand_dims: Any
+fabs: Any
+filled: Any
+fix_invalid: Any
+flatten_mask: Any
+flatten_structured_array: Any
+floor: Any
+floor_divide: Any
+fmod: Any
+frombuffer: Any
+fromflex: Any
+fromfunction: Any
+getdata: Any
+getmask: Any
+getmaskarray: Any
+greater: Any
+greater_equal: Any
+harden_mask: Any
+hypot: Any
+identity: Any
+ids: Any
+indices: Any
+inner: Any
+innerproduct: Any
+isMA: Any
+isMaskedArray: Any
+is_mask: Any
+is_masked: Any
+isarray: Any
+left_shift: Any
+less: Any
+less_equal: Any
+log: Any
+log10: Any
+log2: Any
+logical_and: Any
+logical_not: Any
+logical_or: Any
+logical_xor: Any
+make_mask: Any
+make_mask_descr: Any
+make_mask_none: Any
+mask_or: Any
+masked: Any
+masked_array: Any
+masked_equal: Any
+masked_greater: Any
+masked_greater_equal: Any
+masked_inside: Any
+masked_invalid: Any
+masked_less: Any
+masked_less_equal: Any
+masked_not_equal: Any
+masked_object: Any
+masked_outside: Any
+masked_print_option: Any
+masked_singleton: Any
+masked_values: Any
+masked_where: Any
+max: Any
+maximum: Any
+maximum_fill_value: Any
+mean: Any
+min: Any
+minimum: Any
+minimum_fill_value: Any
+mod: Any
+multiply: Any
+mvoid: Any
+ndim: Any
+negative: Any
+nomask: Any
+nonzero: Any
+not_equal: Any
+ones: Any
+outer: Any
+outerproduct: Any
+power: Any
+prod: Any
+product: Any
+ptp: Any
+put: Any
+putmask: Any
+ravel: Any
+remainder: Any
+repeat: Any
+reshape: Any
+resize: Any
+right_shift: Any
+round: Any
+round_: Any
+set_fill_value: Any
+shape: Any
+sin: Any
+sinh: Any
+size: Any
+soften_mask: Any
+sometrue: Any
+sort: Any
+sqrt: Any
+squeeze: Any
+std: Any
+subtract: Any
+sum: Any
+swapaxes: Any
+take: Any
+tan: Any
+tanh: Any
+trace: Any
+transpose: Any
+true_divide: Any
+var: Any
+where: Any
+zeros: Any
+apply_along_axis: Any
+apply_over_axes: Any
+atleast_1d: Any
+atleast_2d: Any
+atleast_3d: Any
+average: Any
+clump_masked: Any
+clump_unmasked: Any
+column_stack: Any
+compress_cols: Any
+compress_nd: Any
+compress_rowcols: Any
+compress_rows: Any
+count_masked: Any
+corrcoef: Any
+cov: Any
+diagflat: Any
+dot: Any
+dstack: Any
+ediff1d: Any
+flatnotmasked_contiguous: Any
+flatnotmasked_edges: Any
+hsplit: Any
+hstack: Any
+isin: Any
+in1d: Any
+intersect1d: Any
+mask_cols: Any
+mask_rowcols: Any
+mask_rows: Any
+masked_all: Any
+masked_all_like: Any
+median: Any
+mr_: Any
+notmasked_contiguous: Any
+notmasked_edges: Any
+polyfit: Any
+row_stack: Any
+setdiff1d: Any
+setxor1d: Any
+stack: Any
+unique: Any
+union1d: Any
+vander: Any
+vstack: Any
diff --git a/numpy/ma/bench.py b/numpy/ma/bench.py
index 83cc6aea7..e29d54365 100644
--- a/numpy/ma/bench.py
+++ b/numpy/ma/bench.py
@@ -58,7 +58,7 @@ def compare_functions_1v(func, nloop=500,
xs=xs, nmxs=nmxs, xl=xl, nmxl=nmxl):
funcname = func.__name__
print("-"*50)
- print("%s on small arrays" % funcname)
+ print(f'{funcname} on small arrays')
module, data = "numpy.ma", "nmxs"
timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop)
@@ -70,8 +70,8 @@ def compare_functions_1v(func, nloop=500,
def compare_methods(methodname, args, vars='x', nloop=500, test=True,
xs=xs, nmxs=nmxs, xl=xl, nmxl=nmxl):
print("-"*50)
- print("%s on small arrays" % methodname)
- data, ver = "nm%ss" % vars, 'numpy.ma'
+ print(f'{methodname} on small arrays')
+ data, ver = f'nm{vars}l', 'numpy.ma'
timer("%(data)s.%(methodname)s(%(args)s)" % locals(), v=ver, nloop=nloop)
print("%s on large arrays" % methodname)
@@ -86,11 +86,11 @@ def compare_functions_2v(func, nloop=500, test=True,
yl=yl, nmyl=nmyl):
funcname = func.__name__
print("-"*50)
- print("%s on small arrays" % funcname)
+ print(f'{funcname} on small arrays')
module, data = "numpy.ma", "nmxs,nmys"
timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop)
- print("%s on large arrays" % funcname)
+ print(f'{funcname} on large arrays')
module, data = "numpy.ma", "nmxl,nmyl"
timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop)
return
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index b5371f51a..d6af22337 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -443,9 +443,9 @@ def _check_fill_value(fill_value, ndtype):
if isinstance(fill_value, (ndarray, np.void)):
try:
fill_value = np.array(fill_value, copy=False, dtype=ndtype)
- except ValueError:
+ except ValueError as e:
err_msg = "Unable to transform %s to dtype %s"
- raise ValueError(err_msg % (fill_value, ndtype))
+ raise ValueError(err_msg % (fill_value, ndtype)) from e
else:
fill_value = np.asarray(fill_value, dtype=object)
fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype),
@@ -460,12 +460,12 @@ def _check_fill_value(fill_value, ndtype):
# Also in case of converting string arrays.
try:
fill_value = np.array(fill_value, copy=False, dtype=ndtype)
- except (OverflowError, ValueError):
+ except (OverflowError, ValueError) as e:
# Raise TypeError instead of OverflowError or ValueError.
# OverflowError is seldom used, and the real problem here is
# that the passed fill_value is not compatible with the ndtype.
err_msg = "Cannot convert fill_value %s to dtype %s"
- raise TypeError(err_msg % (fill_value, ndtype))
+ raise TypeError(err_msg % (fill_value, ndtype)) from e
return np.array(fill_value)
@@ -1489,7 +1489,7 @@ def is_mask(m):
See Also
--------
- isMaskedArray : Test whether input is an instance of MaskedArray.
+ ma.isMaskedArray : Test whether input is an instance of MaskedArray.
Examples
--------
@@ -2812,7 +2812,7 @@ class MaskedArray(ndarray):
def __new__(cls, data=None, mask=nomask, dtype=None, copy=False,
subok=True, ndmin=0, fill_value=None, keep_mask=True,
- hard_mask=None, shrink=True, order=None, **options):
+ hard_mask=None, shrink=True, order=None):
"""
Create a new masked array from scratch.
@@ -3538,11 +3538,12 @@ class MaskedArray(ndarray):
Force the mask to hard.
Whether the mask of a masked array is hard or soft is determined by
- its `hardmask` property. `harden_mask` sets `hardmask` to True.
+ its `~ma.MaskedArray.hardmask` property. `harden_mask` sets
+ `~ma.MaskedArray.hardmask` to ``True``.
See Also
--------
- hardmask
+ ma.MaskedArray.hardmask
"""
self._hardmask = True
@@ -3553,11 +3554,12 @@ class MaskedArray(ndarray):
Force the mask to soft.
Whether the mask of a masked array is hard or soft is determined by
- its `hardmask` property. `soften_mask` sets `hardmask` to False.
+ its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
+ `~ma.MaskedArray.hardmask` to ``False``.
See Also
--------
- hardmask
+ ma.MaskedArray.hardmask
"""
self._hardmask = False
@@ -3832,7 +3834,7 @@ class MaskedArray(ndarray):
"""
Return `a` where condition is ``True``.
- If condition is a `MaskedArray`, missing values are considered
+ If condition is a `~ma.MaskedArray`, missing values are considered
as ``False``.
Parameters
@@ -3851,7 +3853,7 @@ class MaskedArray(ndarray):
Returns
-------
result : MaskedArray
- A :class:`MaskedArray` object.
+ A :class:`~ma.MaskedArray` object.
Notes
-----
@@ -4461,7 +4463,7 @@ class MaskedArray(ndarray):
See Also
--------
- count_masked : Count masked elements in array or along a given axis.
+ ma.count_masked : Count masked elements in array or along a given axis.
Examples
--------
@@ -5103,7 +5105,7 @@ class MaskedArray(ndarray):
Notes
-----
- The mask is lost if `out` is not a valid :class:`MaskedArray` !
+ The mask is lost if `out` is not a valid :class:`ma.MaskedArray` !
Arithmetic is modular when using integer types, and no error is
raised on overflow.
@@ -5389,7 +5391,7 @@ class MaskedArray(ndarray):
See Also
--------
- numpy.ndarray.around : corresponding function for ndarrays
+ numpy.ndarray.round : corresponding function for ndarrays
numpy.around : equivalent function
"""
result = self._data.round(decimals=decimals, out=out).view(type(self))
@@ -5437,7 +5439,7 @@ class MaskedArray(ndarray):
When the array contains unmasked values at the same extremes of the
datatype, the ordering of these values and the masked values is
undefined.
- fill_value : {var}, optional
+ fill_value : scalar or None, optional
Value used internally for the masked values.
If ``fill_value`` is not None, it supersedes ``endwith``.
@@ -5449,7 +5451,7 @@ class MaskedArray(ndarray):
See Also
--------
- MaskedArray.sort : Describes sorting algorithms used.
+ ma.MaskedArray.sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
numpy.ndarray.sort : Inplace sort.
@@ -5495,7 +5497,7 @@ class MaskedArray(ndarray):
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
- fill_value : {var}, optional
+ fill_value : scalar or None, optional
Value used to fill in the masked values. If None, the output of
minimum_fill_value(self._data) is used instead.
out : {None, array}, optional
@@ -5541,7 +5543,7 @@ class MaskedArray(ndarray):
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
- fill_value : {var}, optional
+ fill_value : scalar or None, optional
Value used to fill in the masked values. If None, the output of
maximum_fill_value(self._data) is used instead.
out : {None, array}, optional
@@ -5592,7 +5594,7 @@ class MaskedArray(ndarray):
When the array contains unmasked values sorting at the same extremes of the
datatype, the ordering of these values and the masked values is
undefined.
- fill_value : {var}, optional
+ fill_value : scalar or None, optional
Value used internally for the masked values.
If ``fill_value`` is not None, it supersedes ``endwith``.
@@ -5663,7 +5665,7 @@ class MaskedArray(ndarray):
out : array_like, optional
Alternative output array in which to place the result. Must be of
the same shape and buffer length as the expected output.
- fill_value : {var}, optional
+ fill_value : scalar or None, optional
Value used to fill in the masked values.
If None, use the output of `minimum_fill_value`.
keepdims : bool, optional
@@ -5679,7 +5681,7 @@ class MaskedArray(ndarray):
See Also
--------
- minimum_fill_value
+ ma.minimum_fill_value
Returns the minimum filling value for a given datatype.
"""
@@ -5797,7 +5799,7 @@ class MaskedArray(ndarray):
out : array_like, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
- fill_value : {var}, optional
+ fill_value : scalar or None, optional
Value used to fill in the masked values.
If None, use the output of maximum_fill_value().
keepdims : bool, optional
@@ -5813,7 +5815,7 @@ class MaskedArray(ndarray):
See Also
--------
- maximum_fill_value
+ ma.maximum_fill_value
Returns the maximum filling value for a given datatype.
"""
@@ -5874,7 +5876,7 @@ class MaskedArray(ndarray):
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
- fill_value : {var}, optional
+ fill_value : scalar or None, optional
Value used to fill in the masked values.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
@@ -6907,11 +6909,11 @@ def compressed(x):
Return all the non-masked data as a 1-D array.
This function is equivalent to calling the "compressed" method of a
- `MaskedArray`, see `MaskedArray.compressed` for details.
+ `ma.MaskedArray`, see `ma.MaskedArray.compressed` for details.
See Also
--------
- MaskedArray.compressed
+ ma.MaskedArray.compressed
Equivalent method.
"""
diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py
index 8ede29da1..1bf03e966 100644
--- a/numpy/ma/extras.py
+++ b/numpy/ma/extras.py
@@ -901,11 +901,11 @@ def compress_rows(a):
Suppress whole rows of a 2-D array that contain masked values.
This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see
- `extras.compress_rowcols` for details.
+ `compress_rowcols` for details.
See Also
--------
- extras.compress_rowcols
+ compress_rowcols
"""
a = asarray(a)
@@ -918,11 +918,11 @@ def compress_cols(a):
Suppress whole columns of a 2-D array that contain masked values.
This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see
- `extras.compress_rowcols` for details.
+ `compress_rowcols` for details.
See Also
--------
- extras.compress_rowcols
+ compress_rowcols
"""
a = asarray(a)
@@ -1641,7 +1641,7 @@ def flatnotmasked_contiguous(a):
slice_list : list
A sorted sequence of `slice` objects (start index, end index).
- ..versionchanged:: 1.15.0
+ .. versionchanged:: 1.15.0
Now returns an empty list instead of None for a fully masked array
See Also
diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py
index cd93a9a14..70087632e 100644
--- a/numpy/ma/mrecords.py
+++ b/numpy/ma/mrecords.py
@@ -60,7 +60,7 @@ def _checknames(descr, names=None):
elif isinstance(names, str):
new_names = names.split(',')
else:
- raise NameError("illegal input names %s" % repr(names))
+ raise NameError(f'illegal input names {names!r}')
nnames = len(new_names)
if nnames < ndescr:
new_names += default_names[nnames:]
@@ -198,8 +198,8 @@ class MaskedRecords(MaskedArray):
fielddict = ndarray.__getattribute__(self, 'dtype').fields
try:
res = fielddict[attr][:2]
- except (TypeError, KeyError):
- raise AttributeError("record array has no attribute %s" % attr)
+ except (TypeError, KeyError) as e:
+ raise AttributeError(f'record array has no attribute {attr}') from e
# So far, so good
_localdict = ndarray.__getattribute__(self, '__dict__')
_data = ndarray.view(self, _localdict['_baseclass'])
@@ -274,7 +274,7 @@ class MaskedRecords(MaskedArray):
try:
res = fielddict[attr][:2]
except (TypeError, KeyError):
- raise AttributeError("record array has no attribute %s" % attr)
+ raise AttributeError(f'record array has no attribute {attr}')
if val is masked:
_fill_value = _localdict['_fill_value']
@@ -337,13 +337,13 @@ class MaskedRecords(MaskedArray):
"""
if self.size > 1:
- mstr = ["(%s)" % ",".join([str(i) for i in s])
+ mstr = [f"({','.join([str(i) for i in s])})"
for s in zip(*[getattr(self, f) for f in self.dtype.names])]
- return "[%s]" % ", ".join(mstr)
+ return f"[{', '.join(mstr)}]"
else:
- mstr = ["%s" % ",".join([str(i) for i in s])
+ mstr = [f"{','.join([str(i) for i in s])}"
for s in zip([getattr(self, f) for f in self.dtype.names])]
- return "(%s)" % ", ".join(mstr)
+ return f"({', '.join(mstr)})"
def __repr__(self):
"""
@@ -657,7 +657,7 @@ def openfile(fname):
try:
f = open(fname)
except IOError:
- raise IOError("No such file: '%s'" % fname)
+ raise IOError(f"No such file: '{fname}'")
if f.readline()[:2] != "\\x":
f.seek(0, 0)
return f
diff --git a/numpy/ma/setup.py b/numpy/ma/setup.py
index d3f34c874..018d38cdd 100644
--- a/numpy/ma/setup.py
+++ b/numpy/ma/setup.py
@@ -3,6 +3,7 @@ def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('ma', parent_package, top_path)
config.add_subpackage('tests')
+ config.add_data_files('*.pyi')
return config
if __name__ == "__main__":
diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py
index 27f14a5e7..0b2e7303c 100644
--- a/numpy/ma/tests/test_core.py
+++ b/numpy/ma/tests/test_core.py
@@ -244,6 +244,10 @@ class TestMaskedArray:
'offsets':[0,8]})
array(x) # used to fail due to 'V' padding field in x.dtype.descr
+ def test_unknown_keyword_parameter(self):
+ with pytest.raises(TypeError, match="unexpected keyword argument"):
+ MaskedArray([1, 2, 3], maks=[0, 1, 0]) # `mask` is misspelled.
+
def test_asarray(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
xm.fill_value = -9999
@@ -2748,7 +2752,7 @@ class TestMaskedArrayInPlaceArithmetics:
xm += t(1)
assert_equal(xm, y + t(1))
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
def test_inplace_addition_array_type(self):
# Test of inplace additions
@@ -2765,7 +2769,7 @@ class TestMaskedArrayInPlaceArithmetics:
assert_equal(xm, y + a)
assert_equal(xm.mask, mask_or(m, a.mask))
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
def test_inplace_subtraction_scalar_type(self):
# Test of inplace subtractions
@@ -2778,7 +2782,7 @@ class TestMaskedArrayInPlaceArithmetics:
xm -= t(1)
assert_equal(xm, y - t(1))
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
def test_inplace_subtraction_array_type(self):
# Test of inplace subtractions
@@ -2795,7 +2799,7 @@ class TestMaskedArrayInPlaceArithmetics:
assert_equal(xm, y - a)
assert_equal(xm.mask, mask_or(m, a.mask))
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
def test_inplace_multiplication_scalar_type(self):
# Test of inplace multiplication
@@ -2808,7 +2812,7 @@ class TestMaskedArrayInPlaceArithmetics:
xm *= t(2)
assert_equal(xm, y * t(2))
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
def test_inplace_multiplication_array_type(self):
# Test of inplace multiplication
@@ -2825,7 +2829,7 @@ class TestMaskedArrayInPlaceArithmetics:
assert_equal(xm, y * a)
assert_equal(xm.mask, mask_or(m, a.mask))
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
def test_inplace_floor_division_scalar_type(self):
# Test of inplace division
@@ -2861,7 +2865,7 @@ class TestMaskedArrayInPlaceArithmetics:
mask_or(mask_or(m, a.mask), (a == t(0)))
)
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
def test_inplace_division_scalar_type(self):
# Test of inplace division
@@ -2895,9 +2899,9 @@ class TestMaskedArrayInPlaceArithmetics:
warnings.warn(str(e), stacklevel=1)
if issubclass(t, np.integer):
- assert_equal(len(sup.log), 2, "Failed on type=%s." % t)
+ assert_equal(len(sup.log), 2, f'Failed on type={t}.')
else:
- assert_equal(len(sup.log), 0, "Failed on type=%s." % t)
+ assert_equal(len(sup.log), 0, f'Failed on type={t}.')
def test_inplace_division_array_type(self):
# Test of inplace division
@@ -2934,9 +2938,9 @@ class TestMaskedArrayInPlaceArithmetics:
warnings.warn(str(e), stacklevel=1)
if issubclass(t, np.integer):
- assert_equal(len(sup.log), 2, "Failed on type=%s." % t)
+ assert_equal(len(sup.log), 2, f'Failed on type={t}.')
else:
- assert_equal(len(sup.log), 0, "Failed on type=%s." % t)
+ assert_equal(len(sup.log), 0, f'Failed on type={t}.')
def test_inplace_pow_type(self):
# Test keeping data w/ (inplace) power
@@ -2954,7 +2958,7 @@ class TestMaskedArrayInPlaceArithmetics:
assert_equal(x.data, xx_r.data)
assert_equal(x.mask, xx_r.mask)
- assert_equal(len(w), 0, "Failed on type=%s." % t)
+ assert_equal(len(w), 0, f'Failed on type={t}.')
class TestMaskedArrayMethods:
@@ -3858,8 +3862,6 @@ class TestMaskedArrayMathMethods:
assert_almost_equal(np.sqrt(mXvar0[k]),
mX[:, k].compressed().std())
- @pytest.mark.skipif(sys.platform=='win32' and sys.version_info < (3, 6),
- reason='Fails on Python < 3.6 on Windows, gh-9671')
@suppress_copy_mask_on_assignment
def test_varstd_specialcases(self):
# Test a special case for var
@@ -4603,7 +4605,7 @@ class TestMaskedArrayFunctions:
class M(MaskedArray):
pass
- test = np.ma.compressed(M(shape=(0,1,2)))
+ test = np.ma.compressed(M([[[]], [[]]]))
assert_equal(test.ndim, 1)
# with .compressed() overridden
@@ -4611,7 +4613,7 @@ class TestMaskedArrayFunctions:
def compressed(self):
return 42
- test = np.ma.compressed(M(shape=(0,1,2)))
+ test = np.ma.compressed(M([[[]], [[]]]))
assert_equal(test, 42)
def test_convolve(self):
diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py
index 96c7e3609..ab003b94e 100644
--- a/numpy/ma/tests/test_old_ma.py
+++ b/numpy/ma/tests/test_old_ma.py
@@ -27,7 +27,7 @@ pi = np.pi
def eq(v, w, msg=''):
result = allclose(v, w)
if not result:
- print("Not eq:%s\n%s\n----%s" % (msg, str(v), str(w)))
+ print(f'Not eq:{msg}\n{v}\n----{w}')
return result
diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py
index caa746740..f2623406d 100644
--- a/numpy/ma/tests/test_subclassing.py
+++ b/numpy/ma/tests/test_subclassing.py
@@ -109,11 +109,11 @@ class CSAIterator:
class ComplicatedSubArray(SubArray):
def __str__(self):
- return 'myprefix {0} mypostfix'.format(self.view(SubArray))
+ return f'myprefix {self.view(SubArray)} mypostfix'
def __repr__(self):
# Return a repr that does not start with 'name('
- return '<{0} {1}>'.format(self.__class__.__name__, self)
+ return f'<{self.__class__.__name__} {self}>'
def _validate_input(self, value):
if not isinstance(value, ComplicatedSubArray):
@@ -317,8 +317,8 @@ class TestSubclassing:
assert_startswith(repr(mx), 'masked_array')
xsub = SubArray(x)
mxsub = masked_array(xsub, mask=[True, False, True, False, False])
- assert_startswith(repr(mxsub),
- 'masked_{0}(data=[--, 1, --, 3, 4]'.format(SubArray.__name__))
+ assert_startswith(repr(mxsub),
+ f'masked_{SubArray.__name__}(data=[--, 1, --, 3, 4]')
def test_subclass_str(self):
"""test str with subclass that has overridden str, setitem"""
diff --git a/numpy/ma/testutils.py b/numpy/ma/testutils.py
index 51ab03948..8d55e1763 100644
--- a/numpy/ma/testutils.py
+++ b/numpy/ma/testutils.py
@@ -86,7 +86,7 @@ def _assert_equal_on_sequences(actual, desired, err_msg=''):
"""
assert_equal(len(actual), len(desired), err_msg)
for k in range(len(desired)):
- assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg))
+ assert_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
return
@@ -117,8 +117,8 @@ def assert_equal(actual, desired, err_msg=''):
assert_equal(len(actual), len(desired), err_msg)
for k, i in desired.items():
if k not in actual:
- raise AssertionError("%s not in %s" % (k, actual))
- assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg))
+ raise AssertionError(f"{k} not in {actual}")
+ assert_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
return
# Case #2: lists .....
if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
@@ -156,12 +156,12 @@ def fail_if_equal(actual, desired, err_msg='',):
for k, i in desired.items():
if k not in actual:
raise AssertionError(repr(k))
- fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k, err_msg))
+ fail_if_equal(actual[k], desired[k], f'key={k!r}\n{err_msg}')
return
if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):
fail_if_equal(len(actual), len(desired), err_msg)
for k in range(len(desired)):
- fail_if_equal(actual[k], desired[k], 'item=%r\n%s' % (k, err_msg))
+ fail_if_equal(actual[k], desired[k], f'item={k!r}\n{err_msg}')
return
if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
return fail_if_array_equal(actual, desired, err_msg)
diff --git a/numpy/ma/timer_comparison.py b/numpy/ma/timer_comparison.py
index 83bd7852e..9eb1a23cd 100644
--- a/numpy/ma/timer_comparison.py
+++ b/numpy/ma/timer_comparison.py
@@ -7,12 +7,9 @@ import numpy.core.fromnumeric as fromnumeric
from numpy.testing import build_err_msg
-# Fixme: this does not look right.
-np.seterr(all='ignore')
pi = np.pi
-
class ModuleTester:
def __init__(self, module):
self.module = module
@@ -77,8 +74,7 @@ class ModuleTester:
if not cond:
msg = build_err_msg([x, y],
err_msg
- + '\n(shapes %s, %s mismatch)' % (x.shape,
- y.shape),
+ + f'\n(shapes {x.shape}, {y.shape} mismatch)',
header=header,
names=('x', 'y'))
assert cond, msg
@@ -100,9 +96,9 @@ class ModuleTester:
header=header,
names=('x', 'y'))
assert cond, msg
- except ValueError:
+ except ValueError as e:
msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y'))
- raise ValueError(msg)
+ raise ValueError(msg) from e
def assert_array_equal(self, x, y, err_msg=''):
"""
@@ -112,6 +108,7 @@ class ModuleTester:
self.assert_array_compare(self.equal, x, y, err_msg=err_msg,
header='Arrays are not equal')
+ @np.errstate(all='ignore')
def test_0(self):
"""
Tests creation
@@ -122,6 +119,7 @@ class ModuleTester:
xm = self.masked_array(x, mask=m)
xm[0]
+ @np.errstate(all='ignore')
def test_1(self):
"""
Tests creation
@@ -149,6 +147,7 @@ class ModuleTester:
xf.shape = s
assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1))
+ @np.errstate(all='ignore')
def test_2(self):
"""
Tests conversions and indexing.
@@ -191,6 +190,7 @@ class ModuleTester:
m3 = self.make_mask(m, copy=1)
assert(m is not m3)
+ @np.errstate(all='ignore')
def test_3(self):
"""
Tests resize/repeat
@@ -210,6 +210,7 @@ class ModuleTester:
y8 = x4.repeat(2, 0)
assert self.allequal(y5, y8)
+ @np.errstate(all='ignore')
def test_4(self):
"""
Test of take, transpose, inner, outer products.
@@ -233,6 +234,7 @@ class ModuleTester:
assert t[1] == 2
assert t[2] == 3
+ @np.errstate(all='ignore')
def test_5(self):
"""
Tests inplace w/ scalar
@@ -285,6 +287,7 @@ class ModuleTester:
x += 1.
assert self.allequal(x, y + 1.)
+ @np.errstate(all='ignore')
def test_6(self):
"""
Tests inplace w/ array
@@ -336,6 +339,7 @@ class ModuleTester:
x /= a
xm /= a
+ @np.errstate(all='ignore')
def test_7(self):
"Tests ufunc"
d = (self.array([1.0, 0, -1, pi/2]*2, mask=[0, 1]+[0]*6),
@@ -370,6 +374,7 @@ class ModuleTester:
self.assert_array_equal(ur.filled(0), mr.filled(0), f)
self.assert_array_equal(ur._mask, mr._mask)
+ @np.errstate(all='ignore')
def test_99(self):
# test average
ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
@@ -415,6 +420,7 @@ class ModuleTester:
self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0])
self.assert_array_equal(self.average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0])
+ @np.errstate(all='ignore')
def test_A(self):
x = self.arange(24)
x[5:6] = self.masked
@@ -434,4 +440,4 @@ if __name__ == '__main__':
cur = np.sort(cur)
print("#%i" % i + 50*'.')
print(eval("ModuleTester.test_%i.__doc__" % i))
- print("core_current : %.3f - %.3f" % (cur[0], cur[1]))
+ print(f'core_current : {cur[0]:.3f} - {cur[1]:.3f}')