summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--numpy/core/arrayprint.py12
-rw-r--r--numpy/core/machar.py7
-rw-r--r--numpy/core/numeric.py11
-rw-r--r--numpy/core/tests/test_half.py11
-rw-r--r--numpy/core/tests/test_machar.py7
-rw-r--r--numpy/core/tests/test_numeric.py16
-rw-r--r--numpy/core/tests/test_regression.py20
-rw-r--r--numpy/core/tests/test_scalarmath.py5
-rw-r--r--numpy/core/tests/test_umath.py83
-rw-r--r--numpy/core/tests/test_umath_complex.py68
-rw-r--r--numpy/lib/financial.py5
-rw-r--r--numpy/lib/tests/test_function_base.py5
-rw-r--r--numpy/lib/tests/test_type_check.py99
-rw-r--r--numpy/linalg/linalg.py11
-rw-r--r--numpy/ma/core.py26
-rw-r--r--numpy/ma/tests/test_core.py5
-rw-r--r--numpy/ma/tests/test_old_ma.py186
-rw-r--r--numpy/ma/tests/test_subclassing.py5
-rw-r--r--numpy/ma/timer_comparison.py1
-rw-r--r--numpy/testing/utils.py20
20 files changed, 194 insertions, 409 deletions
diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py
index a0f2cfa63..ad6a5d074 100644
--- a/numpy/core/arrayprint.py
+++ b/numpy/core/arrayprint.py
@@ -546,8 +546,8 @@ class FloatFormat(object):
def fillFormat(self, data):
from . import numeric as _nc
- errstate = _nc.seterr(all='ignore')
- try:
+
+ with _nc.errstate(all='ignore'):
special = isnan(data) | isinf(data)
valid = not_equal(data, 0) & ~special
non_zero = absolute(data.compress(valid))
@@ -562,8 +562,6 @@ class FloatFormat(object):
if not self.suppress_small and (min_val < 0.0001
or max_val/min_val > 1000.):
self.exp_format = True
- finally:
- _nc.seterr(**errstate)
if self.exp_format:
self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100
@@ -599,8 +597,8 @@ class FloatFormat(object):
def __call__(self, x, strip_zeros=True):
from . import numeric as _nc
- err = _nc.seterr(invalid='ignore')
- try:
+
+ with _nc.errstate(invalid='ignore'):
if isnan(x):
if self.sign:
return self.special_fmt % ('+' + _nan_str,)
@@ -614,8 +612,6 @@ class FloatFormat(object):
return self.special_fmt % (_inf_str,)
else:
return self.special_fmt % ('-' + _inf_str,)
- finally:
- _nc.seterr(**err)
s = self.format % x
if self.large_exponent:
diff --git a/numpy/core/machar.py b/numpy/core/machar.py
index 85eb6b625..9eb4430a6 100644
--- a/numpy/core/machar.py
+++ b/numpy/core/machar.py
@@ -10,7 +10,7 @@ from __future__ import division, absolute_import, print_function
__all__ = ['MachAr']
from numpy.core.fromnumeric import any
-from numpy.core.numeric import seterr
+from numpy.core.numeric import errstate
# Need to speed this up...especially for longfloat
@@ -107,11 +107,8 @@ class MachAr(object):
"""
# We ignore all errors here because we are purposely triggering
# underflow to detect the properties of the runninng arch.
- saverrstate = seterr(under='ignore')
- try:
+ with errstate(under='ignore'):
self._do_init(float_conv, int_conv, float_to_float, float_to_str, title)
- finally:
- seterr(**saverrstate)
def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title):
max_iterN = 10000
diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py
index 13ee89744..9ae1af654 100644
--- a/numpy/core/numeric.py
+++ b/numpy/core/numeric.py
@@ -2125,8 +2125,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8):
y = y[~xinf]
# ignore invalid fpe's
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
+ with errstate(invalid='ignore'):
r = all(less_equal(abs(x-y), atol + rtol * abs(y)))
return r
@@ -2191,11 +2190,8 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
array([True, True])
"""
def within_tol(x, y, atol, rtol):
- err = seterr(invalid='ignore')
- try:
+ with errstate(invalid='ignore'):
result = less_equal(abs(x-y), atol + rtol * abs(y))
- finally:
- seterr(**err)
if isscalar(a) and isscalar(b):
result = bool(result)
return result
@@ -2705,15 +2701,18 @@ class errstate(object):
def __init__(self, **kwargs):
self.call = kwargs.pop('call',_Unspecified)
self.kwargs = kwargs
+
def __enter__(self):
self.oldstate = seterr(**self.kwargs)
if self.call is not _Unspecified:
self.oldcall = seterrcall(self.call)
+
def __exit__(self, *exc_info):
seterr(**self.oldstate)
if self.call is not _Unspecified:
seterrcall(self.oldcall)
+
def _setdef():
defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT2, None]
umath.seterrobj(defval)
diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py
index 223a6f551..e5f2eaf9b 100644
--- a/numpy/core/tests/test_half.py
+++ b/numpy/core/tests/test_half.py
@@ -71,8 +71,7 @@ class TestHalf(TestCase):
assert_equal(i_int,j)
def test_nans_infs(self):
- oldsettings = np.seterr(all='ignore')
- try:
+ with np.errstate(all='ignore'):
# Check some of the ufuncs
assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
@@ -100,9 +99,6 @@ class TestHalf(TestCase):
assert_(not (self.all_f16 >= nan).any())
assert_(not (nan >= self.all_f16).any())
- finally:
- np.seterr(**oldsettings)
-
def test_half_values(self):
"""Confirms a small number of known half values"""
@@ -363,8 +359,7 @@ class TestHalf(TestCase):
@dec.skipif(platform.machine() == "armv5tel", "See gh-413.")
def test_half_fpe(self):
- oldsettings = np.seterr(all='raise')
- try:
+ with np.errstate(all='raise'):
sx16 = np.array((1e-4,),dtype=float16)
bx16 = np.array((1e4,),dtype=float16)
sy16 = float16(1e-4)
@@ -426,8 +421,6 @@ class TestHalf(TestCase):
float16(-2**-14)/float16(2**10)
float16(2**-14+2**-23)/float16(2)
float16(-2**-14-2**-23)/float16(2)
- finally:
- np.seterr(**oldsettings)
def test_half_array_interface(self):
"""Test that half is compatible with __array_interface__"""
diff --git a/numpy/core/tests/test_machar.py b/numpy/core/tests/test_machar.py
index 120d51339..8d858c28b 100644
--- a/numpy/core/tests/test_machar.py
+++ b/numpy/core/tests/test_machar.py
@@ -4,7 +4,7 @@ from numpy.testing import *
from numpy.core.machar import MachAr
import numpy.core.numerictypes as ntypes
-from numpy import seterr, array
+from numpy import errstate, array
class TestMachAr(TestCase):
def _run_machar_highprec(self):
@@ -19,14 +19,11 @@ class TestMachAr(TestCase):
def test_underlow(self):
"""Regression testing for #759: instanciating MachAr for dtype =
np.float96 raises spurious warning."""
- serrstate = seterr(all='raise')
- try:
+ with errstate(all='raise'):
try:
self._run_machar_highprec()
except FloatingPointError as e:
self.fail("Caught %s exception, should not have been raised." % e)
- finally:
- seterr(**serrstate)
if __name__ == "__main__":
diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py
index 751722ffb..1be0f4105 100644
--- a/numpy/core/tests/test_numeric.py
+++ b/numpy/core/tests/test_numeric.py
@@ -351,8 +351,8 @@ class TestSeterr(TestCase):
))
def test_set(self):
- err = seterr()
- try:
+ with np.errstate():
+ err = seterr()
old = seterr(divide='print')
self.assertTrue(err == old)
new = seterr()
@@ -362,13 +362,10 @@ class TestSeterr(TestCase):
self.assertTrue(new['divide'] == 'print')
seterr(**old)
self.assertTrue(geterr() == old)
- finally:
- seterr(**err)
@dec.skipif(platform.machine() == "armv5tel", "See gh-413.")
def test_divide_err(self):
- err = seterr(divide='raise')
- try:
+ with errstate(divide='raise'):
try:
array([1.]) / array([0.])
except FloatingPointError:
@@ -377,8 +374,6 @@ class TestSeterr(TestCase):
self.fail()
seterr(divide='ignore')
array([1.]) / array([0.])
- finally:
- seterr(**err)
class TestFloatExceptions(TestCase):
@@ -407,8 +402,7 @@ class TestFloatExceptions(TestCase):
@dec.knownfailureif(True, "See ticket 1755")
def test_floating_exceptions(self):
# Test basic arithmetic function errors
- oldsettings = np.seterr(all='raise')
- try:
+ with np.errstate(all='raise'):
# Test for all real and complex float types
for typecode in np.typecodes['AllFloat']:
ftype = np.obj2sctype(typecode)
@@ -459,8 +453,6 @@ class TestFloatExceptions(TestCase):
lambda a,b:a+b, ftype(np.inf), ftype(-np.inf))
self.assert_raises_fpe(invalid,
lambda a,b:a*b, ftype(0), ftype(np.inf))
- finally:
- np.seterr(**oldsettings)
class TestTypes(TestCase):
def check_promotion_cases(self, promote_func):
diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py
index 6dfee51d8..492b08cb9 100644
--- a/numpy/core/tests/test_regression.py
+++ b/numpy/core/tests/test_regression.py
@@ -655,11 +655,8 @@ class TestRegression(TestCase):
def test_array_str_64bit(self, level=rlevel):
"""Ticket #501"""
s = np.array([1, np.nan],dtype=np.float64)
- errstate = np.seterr(all='raise')
- try:
+ with np.errstate(all='raise'):
sstr = np.array_str(s)
- finally:
- np.seterr(**errstate)
def test_frompyfunc_endian(self, level=rlevel):
"""Ticket #503"""
@@ -1120,14 +1117,11 @@ class TestRegression(TestCase):
def test_sign_for_complex_nan(self, level=rlevel):
"""Ticket 794."""
- olderr = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan])
have = np.sign(C)
want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan])
assert_equal(have, want)
- finally:
- np.seterr(**olderr)
def test_for_equal_names(self, level=rlevel):
"""Ticket #674"""
@@ -1169,8 +1163,7 @@ class TestRegression(TestCase):
def test_errobj_reference_leak(self, level=rlevel):
"""Ticket #955"""
- old_err = np.seterr(all="ignore")
- try:
+ with np.errstate(all="ignore"):
z = int(0)
p = np.int32(-1)
@@ -1180,8 +1173,6 @@ class TestRegression(TestCase):
gc.collect()
n_after = len(gc.get_objects())
assert_(n_before >= n_after, (n_before, n_after))
- finally:
- np.seterr(**old_err)
def test_void_scalar_with_titles(self, level=rlevel):
"""No ticket"""
@@ -1415,12 +1406,9 @@ class TestRegression(TestCase):
min = np.array([np.iinfo(t).min])
min //= -1
- old_err = np.seterr(divide="ignore")
- try:
+ with np.errstate(divide="ignore"):
for t in (np.int8, np.int16, np.int32, np.int64, np.int, np.long):
test_type(t)
- finally:
- np.seterr(**old_err)
def test_buffer_hashlib(self):
try:
diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py
index 952a89999..3e1aaef3b 100644
--- a/numpy/core/tests/test_scalarmath.py
+++ b/numpy/core/tests/test_scalarmath.py
@@ -110,8 +110,7 @@ class TestPower(TestCase):
class TestComplexDivision(TestCase):
def test_zero_division(self):
- err = np.seterr(all="ignore")
- try:
+ with np.errstate(all="ignore"):
for t in [np.complex64, np.complex128]:
a = t(0.0)
b = t(1.0)
@@ -126,8 +125,6 @@ class TestComplexDivision(TestCase):
assert_(np.isnan(b/a))
b = t(0.)
assert_(np.isnan(b/a))
- finally:
- np.seterr(**err)
class TestConversion(TestCase):
diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py
index c58a0d3f5..c2304a748 100644
--- a/numpy/core/tests/test_umath.py
+++ b/numpy/core/tests/test_umath.py
@@ -60,8 +60,7 @@ class TestDivision(TestCase):
assert_almost_equal(y/x, [1, 1], err_msg=msg)
def test_zero_division_complex(self):
- err = np.seterr(invalid="ignore", divide="ignore")
- try:
+ with np.errstate(invalid="ignore", divide="ignore"):
x = np.array([0.0], dtype=np.complex128)
y = 1.0/x
assert_(np.isinf(y)[0])
@@ -73,8 +72,6 @@ class TestDivision(TestCase):
assert_(np.isinf(y)[0])
y = 0.0/x
assert_(np.isnan(y)[0])
- finally:
- np.seterr(**err)
def test_floor_division_complex(self):
# check that implementation is correct
@@ -140,14 +137,11 @@ class TestPower(TestCase):
assert_array_equal(x.imag, y.imag)
for z in [complex(0, np.inf), complex(1, np.inf)]:
- err = np.seterr(invalid="ignore")
z = np.array([z], dtype=np.complex_)
- try:
+ with np.errstate(invalid="ignore"):
assert_complex_equal(z**1, z)
assert_complex_equal(z**2, z*z)
assert_complex_equal(z**3, z*z*z)
- finally:
- np.seterr(**err)
def test_power_zero(self):
# ticket #1271
@@ -221,19 +215,16 @@ class TestLogAddExp2(_FilterInvalids):
assert_almost_equal(np.logaddexp2(logxf, logyf), logzf)
def test_inf(self) :
- err = np.seterr(invalid='ignore')
inf = np.inf
x = [inf, -inf, inf, -inf, inf, 1, -inf, 1]
y = [inf, inf, -inf, -inf, 1, inf, 1, -inf]
z = [inf, inf, inf, -inf, inf, inf, 1, 1]
- try:
+ with np.errstate(invalid='ignore'):
for dt in ['f','d','g'] :
logxf = np.array(x, dtype=dt)
logyf = np.array(y, dtype=dt)
logzf = np.array(z, dtype=dt)
assert_equal(np.logaddexp2(logxf, logyf), logzf)
- finally:
- np.seterr(**err)
def test_nan(self):
assert_(np.isnan(np.logaddexp2(np.nan, np.inf)))
@@ -287,19 +278,16 @@ class TestLogAddExp(_FilterInvalids):
assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
def test_inf(self) :
- err = np.seterr(invalid='ignore')
inf = np.inf
x = [inf, -inf, inf, -inf, inf, 1, -inf, 1]
y = [inf, inf, -inf, -inf, 1, inf, 1, -inf]
z = [inf, inf, inf, -inf, inf, inf, 1, 1]
- try:
+ with np.errstate(invalid='ignore'):
for dt in ['f','d','g'] :
logxf = np.array(x, dtype=dt)
logyf = np.array(y, dtype=dt)
logzf = np.array(z, dtype=dt)
assert_equal(np.logaddexp(logxf, logyf), logzf)
- finally:
- np.seterr(**err)
def test_nan(self):
assert_(np.isnan(np.logaddexp(np.nan, np.inf)))
@@ -328,19 +316,15 @@ class TestHypot(TestCase, object):
def assert_hypot_isnan(x, y):
- err = np.seterr(invalid='ignore')
- try:
- assert_(np.isnan(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y)))
- finally:
- np.seterr(**err)
+ with np.errstate(invalid='ignore'):
+ assert_(np.isnan(ncu.hypot(x, y)),
+ "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y)))
def assert_hypot_isinf(x, y):
- err = np.seterr(invalid='ignore')
- try:
- assert_(np.isinf(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y)))
- finally:
- np.seterr(**err)
+ with np.errstate(invalid='ignore'):
+ assert_(np.isinf(ncu.hypot(x, y)),
+ "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y)))
class TestHypotSpecialValues(TestCase):
@@ -465,14 +449,11 @@ class TestLdexp(TestCase):
def test_ldexp_overflow(self):
# silence warning emitted on overflow
- err = np.seterr(over="ignore")
- try:
+ with np.errstate(over="ignore"):
imax = np.iinfo(np.dtype('l')).max
imin = np.iinfo(np.dtype('l')).min
assert_equal(ncu.ldexp(2., imax), np.inf)
assert_equal(ncu.ldexp(2., imin), 0)
- finally:
- np.seterr(**err)
class TestMaximum(_FilterInvalids):
@@ -676,15 +657,12 @@ class TestSign(TestCase):
out = np.zeros(a.shape)
tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0])
- olderr = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
res = ncu.sign(a)
assert_equal(res, tgt)
res = ncu.sign(a, out)
assert_equal(res, tgt)
assert_equal(out, tgt)
- finally:
- np.seterr(**olderr)
class TestMinMax(TestCase):
@@ -719,19 +697,17 @@ class TestAbsolute(TestCase):
assert_equal(out, tgt, err_msg=msg)
self.assertTrue((out >= 0).all())
- prev = np.geterr()
# will throw invalid flag depending on compiler optimizations
- np.seterr(invalid='ignore')
- for v in [np.nan, -np.inf, np.inf]:
- for i in range(inp.size):
- d = np.arange(inp.size, dtype=dt)
- inp[:] = -d
- inp[i] = v
- d[i] = -v if v == -np.inf else v
- assert_array_equal(np.abs(inp), d, err_msg=msg)
- np.abs(inp, out=out)
- assert_array_equal(out, d, err_msg=msg)
- np.seterr(invalid=prev['invalid'])
+ with np.errstate(invalid='ignore'):
+ for v in [np.nan, -np.inf, np.inf]:
+ for i in range(inp.size):
+ d = np.arange(inp.size, dtype=dt)
+ inp[:] = -d
+ inp[i] = v
+ d[i] = -v if v == -np.inf else v
+ assert_array_equal(np.abs(inp), d, err_msg=msg)
+ np.abs(inp, out=out)
+ assert_array_equal(out, d, err_msg=msg)
class TestSpecialMethods(TestCase):
@@ -1164,12 +1140,9 @@ def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False,
def test_copysign():
assert_(np.copysign(1, -1) == -1)
- old_err = np.seterr(divide="ignore")
- try:
+ with np.errstate(divide="ignore"):
assert_(1 / np.copysign(0, -1) < 0)
assert_(1 / np.copysign(0, 1) > 0)
- finally:
- np.seterr(**old_err)
assert_(np.signbit(np.copysign(np.nan, -1)))
assert_(not np.signbit(np.copysign(np.nan, 1)))
@@ -1196,19 +1169,16 @@ def test_nextafterl():
return _test_nextafter(np.longdouble)
def _test_spacing(t):
- err = np.seterr(invalid='ignore')
one = t(1)
eps = np.finfo(t).eps
nan = t(np.nan)
inf = t(np.inf)
- try:
+ with np.errstate(invalid='ignore'):
assert_(np.spacing(one) == eps)
assert_(np.isnan(np.spacing(nan)))
assert_(np.isnan(np.spacing(inf)))
assert_(np.isnan(np.spacing(-inf)))
assert_(np.spacing(t(1e30)) != 0)
- finally:
- np.seterr(**err)
def test_spacing():
return _test_spacing(np.float64)
@@ -1299,8 +1269,7 @@ def test_complex_nan_comparisons():
fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1),
complex(1, 1), complex(-1, -1), complex(0, 0)]
- olderr = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
for x in nans + fins:
x = np.array([x])
for y in nans + fins:
@@ -1314,8 +1283,6 @@ def test_complex_nan_comparisons():
assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y))
assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y))
assert_equal(x == y, False, err_msg="%r == %r" % (x, y))
- finally:
- np.seterr(**olderr)
if __name__ == "__main__":
diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py
index f9681ff07..ebf805c6d 100644
--- a/numpy/core/tests/test_umath_complex.py
+++ b/numpy/core/tests/test_umath_complex.py
@@ -14,12 +14,9 @@ import numpy as np
# At least on Windows the results of many complex functions are not conforming
# to the C99 standard. See ticket 1574.
# Ditto for Solaris (ticket 1642) and OS X on PowerPC.
-olderr = np.seterr(all='ignore')
-try:
+with np.errstate(all='ignore'):
functions_seem_flaky = ((np.exp(complex(np.inf, 0)).imag != 0)
or (np.log(complex(np.NZERO, 0)).imag != np.pi))
-finally:
- np.seterr(**olderr)
# TODO: replace with a check on whether platform-provided C99 funcs are used
skip_complex_tests = (not sys.platform.startswith('linux') or functions_seem_flaky)
@@ -78,52 +75,40 @@ class TestCexp(object):
# cexp(-inf + inf i) is +-0 +- 0i (signs unspecified)
def _check_ninf_inf(dummy):
msgform = "cexp(-inf, inf) is (%f, %f), expected (+-0, +-0)"
- err = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
z = f(np.array(np.complex(-np.inf, np.inf)))
if z.real != 0 or z.imag != 0:
raise AssertionError(msgform %(z.real, z.imag))
- finally:
- np.seterr(**err)
yield _check_ninf_inf, None
# cexp(inf + inf i) is +-inf + NaNi and raised invalid FPU ex.
def _check_inf_inf(dummy):
msgform = "cexp(inf, inf) is (%f, %f), expected (+-inf, nan)"
- err = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
z = f(np.array(np.complex(np.inf, np.inf)))
if not np.isinf(z.real) or not np.isnan(z.imag):
raise AssertionError(msgform % (z.real, z.imag))
- finally:
- np.seterr(**err)
yield _check_inf_inf, None
# cexp(-inf + nan i) is +-0 +- 0i
def _check_ninf_nan(dummy):
msgform = "cexp(-inf, nan) is (%f, %f), expected (+-0, +-0)"
- err = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
z = f(np.array(np.complex(-np.inf, np.nan)))
if z.real != 0 or z.imag != 0:
raise AssertionError(msgform % (z.real, z.imag))
- finally:
- np.seterr(**err)
yield _check_ninf_nan, None
# cexp(inf + nan i) is +-inf + nan
def _check_inf_nan(dummy):
msgform = "cexp(-inf, nan) is (%f, %f), expected (+-inf, nan)"
- err = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
z = f(np.array(np.complex(np.inf, np.nan)))
if not np.isinf(z.real) or not np.isnan(z.imag):
raise AssertionError(msgform % (z.real, z.imag))
- finally:
- np.seterr(**err)
yield _check_inf_nan, None
@@ -164,30 +149,24 @@ class TestClog(TestCase):
# clog(-0 + i0) returns -inf + i pi and raises the 'divide-by-zero'
# floating-point exception.
- err = np.seterr(divide='raise')
- try:
+ with np.errstate(divide='raise'):
x = np.array([np.NZERO], dtype=np.complex)
y = np.complex(-np.inf, np.pi)
self.assertRaises(FloatingPointError, np.log, x)
- np.seterr(divide='ignore')
+ with np.errstate(divide='ignore'):
assert_almost_equal(np.log(x), y)
- finally:
- np.seterr(**err)
xl.append(x)
yl.append(y)
# clog(+0 + i0) returns -inf + i0 and raises the 'divide-by-zero'
# floating-point exception.
- err = np.seterr(divide='raise')
- try:
+ with np.errstate(divide='raise'):
x = np.array([0], dtype=np.complex)
y = np.complex(-np.inf, 0)
self.assertRaises(FloatingPointError, np.log, x)
- np.seterr(divide='ignore')
+ with np.errstate(divide='ignore'):
assert_almost_equal(np.log(x), y)
- finally:
- np.seterr(**err)
xl.append(x)
yl.append(y)
@@ -206,27 +185,21 @@ class TestClog(TestCase):
# clog(x + iNaN) returns NaN + iNaN and optionally raises the
# 'invalid' floating- point exception, for finite x.
- err = np.seterr(invalid='raise')
- try:
+ with np.errstate(invalid='raise'):
x = np.array([complex(1., np.nan)], dtype=np.complex)
y = np.complex(np.nan, np.nan)
#self.assertRaises(FloatingPointError, np.log, x)
- np.seterr(invalid='ignore')
+ with np.errstate(invalid='ignore'):
assert_almost_equal(np.log(x), y)
- finally:
- np.seterr(**err)
xl.append(x)
yl.append(y)
- err = np.seterr(invalid='raise')
- try:
+ with np.errstate(invalid='raise'):
x = np.array([np.inf + 1j * np.nan], dtype=np.complex)
#self.assertRaises(FloatingPointError, np.log, x)
- np.seterr(invalid='ignore')
+ with np.errstate(invalid='ignore'):
assert_almost_equal(np.log(x), y)
- finally:
- np.seterr(**err)
xl.append(x)
yl.append(y)
@@ -296,12 +269,9 @@ class TestClog(TestCase):
# clog(conj(z)) = conj(clog(z)).
xa = np.array(xl, dtype=np.complex)
ya = np.array(yl, dtype=np.complex)
- err = np.seterr(divide='ignore')
- try:
+ with np.errstate(divide='ignore'):
for i in range(len(xa)):
assert_almost_equal(np.log(np.conj(xa[i])), np.conj(np.log(xa[i])))
- finally:
- np.seterr(**err)
class TestCsqrt(object):
@@ -362,12 +332,9 @@ class TestCsqrt(object):
msgform = "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)"
z = np.sqrt(np.array(np.complex(-np.inf, np.nan)))
#Fixme: ugly workaround for isinf bug.
- err = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
if not (np.isnan(z.real) and np.isinf(z.imag)):
raise AssertionError(msgform % (z.real, z.imag))
- finally:
- np.seterr(**err)
yield _check_ninf_nan, None
@@ -558,16 +525,13 @@ def check_real_value(f, x1, y1, x, exact=True):
assert_almost_equal(f(z1), x)
def check_complex_value(f, x1, y1, x2, y2, exact=True):
- err = np.seterr(invalid='ignore')
z1 = np.array([complex(x1, y1)])
z2 = np.complex(x2, y2)
- try:
+ with np.errstate(invalid='ignore'):
if exact:
assert_equal(f(z1), z2)
else:
assert_almost_equal(f(z1), z2)
- finally:
- np.seterr(**err)
if __name__ == "__main__":
run_module_suite()
diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py
index 0be12f2c7..8cac117c9 100644
--- a/numpy/lib/financial.py
+++ b/numpy/lib/financial.py
@@ -266,14 +266,11 @@ def nper(rate, pmt, pv, fv=0, when='end'):
(rate, pmt, pv, fv, when) = map(np.asarray, [rate, pmt, pv, fv, when])
use_zero_rate = False
- old_err = np.seterr(divide="raise")
- try:
+ with np.errstate(divide="raise"):
try:
z = pmt*(1.0+rate*when)/rate
except FloatingPointError:
use_zero_rate = True
- finally:
- np.seterr(**old_err)
if use_zero_rate:
return (-fv + pv) / (pmt + 0.0)
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 45e248913..a23e406e3 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -1062,8 +1062,7 @@ class TestHistogramdd(TestCase):
def test_inf_edges(self):
"""Test using +/-inf bin edges works. See #1788."""
- olderr = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
x = np.arange(6).reshape(3, 2)
expected = np.array([[1, 0], [0, 1], [0, 1]])
h, e = np.histogramdd(x, bins=[3, [-np.inf, 2, 10]])
@@ -1072,8 +1071,6 @@ class TestHistogramdd(TestCase):
assert_allclose(h, expected)
h, e = np.histogramdd(x, bins=[3, [-np.inf, 3, np.inf]])
assert_allclose(h, expected)
- finally:
- np.seterr(**olderr)
class TestUnique(TestCase):
diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py
index 25e697924..8b01a974a 100644
--- a/numpy/lib/tests/test_type_check.py
+++ b/numpy/lib/tests/test_type_check.py
@@ -1,9 +1,11 @@
from __future__ import division, absolute_import, print_function
-from numpy.testing import *
from numpy.lib import *
from numpy.core import *
+from numpy.random import rand
from numpy.compat import asbytes, long
+from numpy.testing import (
+ TestCase, assert_, assert_equal, assert_array_equal, run_module_suite)
try:
import ctypes
@@ -163,25 +165,16 @@ class TestIsnan(TestCase):
assert_all(alltrue(res,axis=0))
def test_posinf(self):
- olderr = seterr(divide='ignore')
- try:
+ with errstate(divide='ignore'):
assert_all(isnan(array((1.,))/0.) == 0)
- finally:
- seterr(**olderr)
def test_neginf(self):
- olderr = seterr(divide='ignore')
- try:
+ with errstate(divide='ignore'):
assert_all(isnan(array((-1.,))/0.) == 0)
- finally:
- seterr(**olderr)
def test_ind(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isnan(array((0.,))/0.) == 1)
- finally:
- seterr(**olderr)
#def test_qnan(self): log(-1) return pi*j now
# assert_all(isnan(log(-1.)) == 1)
@@ -193,11 +186,8 @@ class TestIsnan(TestCase):
assert_all(isnan(1+1j) == 0)
def test_complex1(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isnan(array(0+0j)/0.) == 1)
- finally:
- seterr(**olderr)
class TestIsfinite(TestCase):
@@ -208,25 +198,16 @@ class TestIsfinite(TestCase):
assert_all(alltrue(res,axis=0))
def test_posinf(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isfinite(array((1.,))/0.) == 0)
- finally:
- seterr(**olderr)
def test_neginf(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isfinite(array((-1.,))/0.) == 0)
- finally:
- seterr(**olderr)
def test_ind(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isfinite(array((0.,))/0.) == 0)
- finally:
- seterr(**olderr)
#def test_qnan(self):
# assert_all(isfinite(log(-1.)) == 0)
@@ -238,11 +219,8 @@ class TestIsfinite(TestCase):
assert_all(isfinite(1+1j) == 1)
def test_complex1(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isfinite(array(1+1j)/0.) == 0)
- finally:
- seterr(**olderr)
class TestIsinf(TestCase):
@@ -253,39 +231,24 @@ class TestIsinf(TestCase):
assert_all(alltrue(res,axis=0))
def test_posinf(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isinf(array((1.,))/0.) == 1)
- finally:
- seterr(**olderr)
def test_posinf_scalar(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isinf(array(1.,)/0.) == 1)
- finally:
- seterr(**olderr)
def test_neginf(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isinf(array((-1.,))/0.) == 1)
- finally:
- seterr(**olderr)
def test_neginf_scalar(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isinf(array(-1.)/0.) == 1)
- finally:
- seterr(**olderr)
def test_ind(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
assert_all(isinf(array((0.,))/0.) == 0)
- finally:
- seterr(**olderr)
#def test_qnan(self):
# assert_all(isinf(log(-1.)) == 0)
@@ -295,23 +258,18 @@ class TestIsinf(TestCase):
class TestIsposinf(TestCase):
def test_generic(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
vals = isposinf(array((-1.,0,1))/0.)
- finally:
- seterr(**olderr)
assert_(vals[0] == 0)
assert_(vals[1] == 0)
assert_(vals[2] == 1)
class TestIsneginf(TestCase):
+
def test_generic(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
vals = isneginf(array((-1.,0,1))/0.)
- finally:
- seterr(**olderr)
assert_(vals[0] == 1)
assert_(vals[1] == 0)
assert_(vals[2] == 0)
@@ -320,11 +278,8 @@ class TestIsneginf(TestCase):
class TestNanToNum(TestCase):
def test_generic(self):
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
vals = nan_to_num(array((-1.,0,1))/0.)
- finally:
- seterr(**olderr)
assert_all(vals[0] < -1e10) and assert_all(isfinite(vals[0]))
assert_(vals[1] == 0)
assert_all(vals[2] > 1e10) and assert_all(isfinite(vals[2]))
@@ -338,23 +293,17 @@ class TestNanToNum(TestCase):
assert_all(vals == 1+1j)
def test_complex_bad(self):
- v = 1+1j
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
+ v = 1 + 1j
v += array(0+1.j)/0.
- finally:
- seterr(**olderr)
vals = nan_to_num(v)
# !! This is actually (unexpectedly) zero
assert_all(isfinite(vals))
def test_complex_bad2(self):
- v = 1+1j
- olderr = seterr(divide='ignore', invalid='ignore')
- try:
+ with errstate(divide='ignore', invalid='ignore'):
+ v = 1 + 1j
v += array(-1+1.j)/0.
- finally:
- seterr(**olderr)
vals = nan_to_num(v)
assert_all(isfinite(vals))
#assert_all(vals.imag > 1e10) and assert_all(isfinite(vals))
diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py
index 279ce21f9..4c4e51748 100644
--- a/numpy/linalg/linalg.py
+++ b/numpy/linalg/linalg.py
@@ -18,11 +18,12 @@ __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
import warnings
-from numpy.core import array, asarray, zeros, empty, transpose, \
- intc, single, double, csingle, cdouble, inexact, complexfloating, \
- newaxis, ravel, all, Inf, dot, add, multiply, sqrt, maximum, \
- fastCopyAndTranspose, sum, isfinite, size, finfo, errstate, \
- geterrobj, longdouble, rollaxis, amin, amax
+from numpy.core import (
+ array, asarray, zeros, empty, transpose, intc, single, double, csingle,
+ cdouble, inexact, complexfloating, newaxis, ravel, all, Inf, dot, add,
+ multiply, sqrt, maximum, fastCopyAndTranspose, sum, isfinite, size,
+ finfo, errstate, geterrobj, longdouble, rollaxis, amin, amax
+ )
from numpy.lib import triu, asfarray
from numpy.linalg import lapack_lite, _umath_linalg
from numpy.matrixlib.defmatrix import matrix_power
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index b2e6ad91b..ccf62bdcf 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -838,13 +838,9 @@ class _MaskedUnaryOperation:
d = getdata(a)
# Case 1.1. : Domained function
if self.domain is not None:
- # Save the error status
- err_status_ini = np.geterr()
- try:
+ with np.errstate():
np.seterr(divide='ignore', invalid='ignore')
result = self.f(d, *args, **kwargs)
- finally:
- np.seterr(**err_status_ini)
# Make a mask
m = ~umath.isfinite(result)
m |= self.domain(d)
@@ -931,12 +927,9 @@ class _MaskedBinaryOperation:
else:
m = umath.logical_or(ma, mb)
# Get the result
- err_status_ini = np.geterr()
- try:
+ with np.errstate():
np.seterr(divide='ignore', invalid='ignore')
result = self.f(da, db, *args, **kwargs)
- finally:
- np.seterr(**err_status_ini)
# Case 1. : scalar
if not result.ndim:
if m:
@@ -1069,12 +1062,9 @@ class _DomainedBinaryOperation:
(da, db) = (getdata(a, subok=False), getdata(b, subok=False))
(ma, mb) = (getmask(a), getmask(b))
# Get the result
- err_status_ini = np.geterr()
- try:
+ with np.errstate():
np.seterr(divide='ignore', invalid='ignore')
result = self.f(da, db, *args, **kwargs)
- finally:
- np.seterr(**err_status_ini)
# Get the mask as a combination of ma, mb and invalid
m = ~umath.isfinite(result)
m |= ma
@@ -3815,12 +3805,9 @@ class MaskedArray(ndarray):
"Raise self to the power other, in place."
other_data = getdata(other)
other_mask = getmask(other)
- err_status = np.geterr()
- try:
+ with np.errstate():
np.seterr(divide='ignore', invalid='ignore')
ndarray.__ipow__(self._data, np.where(self._mask, 1, other_data))
- finally:
- np.seterr(**err_status)
invalid = np.logical_not(np.isfinite(self._data))
if invalid.any():
if self._mask is not nomask:
@@ -6083,12 +6070,9 @@ def power(a, b, third=None):
else:
basetype = MaskedArray
# Get the result and view it as a (subclass of) MaskedArray
- err_status = np.geterr()
- try:
+ with np.errstate():
np.seterr(divide='ignore', invalid='ignore')
result = np.where(m, fa, umath.power(fa, fb)).view(basetype)
- finally:
- np.seterr(**err_status)
result._update_from(a)
# Find where we're in trouble w/ NaNs and Infs
invalid = np.logical_not(np.isfinite(result.view(ndarray)))
diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py
index a32f6a76b..32aee119a 100644
--- a/numpy/ma/tests/test_core.py
+++ b/numpy/ma/tests/test_core.py
@@ -196,15 +196,12 @@ class TestMaskedArray(TestCase):
def test_fix_invalid(self):
"Checks fix_invalid."
- err_status_ini = np.geterr()
- try:
+ with np.errstate():
np.seterr(invalid='ignore')
data = masked_array([np.nan, 0., 1.], mask=[0, 0, 1])
data_fixed = fix_invalid(data)
assert_equal(data_fixed._data, [data.fill_value, 0., 1.])
assert_equal(data_fixed._mask, [1., 0., 1.])
- finally:
- np.seterr(**err_status_ini)
def test_maskedelement(self):
"Test of masked element"
diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py
index baa6f69a1..50247df37 100644
--- a/numpy/ma/tests/test_old_ma.py
+++ b/numpy/ma/tests/test_old_ma.py
@@ -3,14 +3,14 @@ from __future__ import division, absolute_import, print_function
import sys
from functools import reduce
-import numpy
+import numpy as np
from numpy.ma import *
from numpy.core.numerictypes import float32
from numpy.ma.core import umath
from numpy.testing import *
-pi = numpy.pi
+pi = np.pi
def eq(v, w, msg=''):
result = allclose(v, w)
if not result:
@@ -22,16 +22,16 @@ def eq(v, w, msg=''):
class TestMa(TestCase):
def setUp (self):
- x = numpy.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.])
- y = numpy.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
+ x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.])
+ y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
a10 = 10.
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0 , 0, 1]
xm = array(x, mask=m1)
ym = array(y, mask=m2)
- z = numpy.array([-.5, 0., .5, .8])
+ z = np.array([-.5, 0., .5, .8])
zm = array(z, mask=[0, 1, 0, 0])
- xf = numpy.where(m1, 1e+20, x)
+ xf = np.where(m1, 1e+20, x)
s = x.shape
xm.set_fill_value(1e+20)
self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf, s)
@@ -89,19 +89,13 @@ class TestMa(TestCase):
self.assertTrue(eq(x + y, xm + ym))
self.assertTrue(eq(x - y, xm - ym))
self.assertTrue(eq(x * y, xm * ym))
- olderr = numpy.seterr(divide='ignore', invalid='ignore')
- try:
+ with np.errstate(divide='ignore', invalid='ignore'):
self.assertTrue(eq(x / y, xm / ym))
- finally:
- numpy.seterr(**olderr)
self.assertTrue(eq(a10 + y, a10 + ym))
self.assertTrue(eq(a10 - y, a10 - ym))
self.assertTrue(eq(a10 * y, a10 * ym))
- olderr = numpy.seterr(divide='ignore', invalid='ignore')
- try:
+ with np.errstate(divide='ignore', invalid='ignore'):
self.assertTrue(eq(a10 / y, a10 / ym))
- finally:
- numpy.seterr(**olderr)
self.assertTrue(eq(x + a10, xm + a10))
self.assertTrue(eq(x - a10, xm - a10))
self.assertTrue(eq(x * a10, xm * a10))
@@ -109,18 +103,15 @@ class TestMa(TestCase):
self.assertTrue(eq(x ** 2, xm ** 2))
self.assertTrue(eq(abs(x) ** 2.5, abs(xm) ** 2.5))
self.assertTrue(eq(x ** y, xm ** ym))
- self.assertTrue(eq(numpy.add(x, y), add(xm, ym)))
- self.assertTrue(eq(numpy.subtract(x, y), subtract(xm, ym)))
- self.assertTrue(eq(numpy.multiply(x, y), multiply(xm, ym)))
- olderr = numpy.seterr(divide='ignore', invalid='ignore')
- try:
- self.assertTrue(eq(numpy.divide(x, y), divide(xm, ym)))
- finally:
- numpy.seterr(**olderr)
+ self.assertTrue(eq(np.add(x, y), add(xm, ym)))
+ self.assertTrue(eq(np.subtract(x, y), subtract(xm, ym)))
+ self.assertTrue(eq(np.multiply(x, y), multiply(xm, ym)))
+ with np.errstate(divide='ignore', invalid='ignore'):
+ self.assertTrue(eq(np.divide(x, y), divide(xm, ym)))
def test_testMixedArithmetic(self):
- na = numpy.array([1])
+ na = np.array([1])
ma = array([1])
self.assertTrue(isinstance(na + ma, MaskedArray))
self.assertTrue(isinstance(ma + na, MaskedArray))
@@ -128,51 +119,48 @@ class TestMa(TestCase):
def test_testUfuncs1 (self):
"Test various functions such as sin, cos."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
- self.assertTrue (eq(numpy.cos(x), cos(xm)))
- self.assertTrue (eq(numpy.cosh(x), cosh(xm)))
- self.assertTrue (eq(numpy.sin(x), sin(xm)))
- self.assertTrue (eq(numpy.sinh(x), sinh(xm)))
- self.assertTrue (eq(numpy.tan(x), tan(xm)))
- self.assertTrue (eq(numpy.tanh(x), tanh(xm)))
- olderr = numpy.seterr(divide='ignore', invalid='ignore')
- try:
- self.assertTrue (eq(numpy.sqrt(abs(x)), sqrt(xm)))
- self.assertTrue (eq(numpy.log(abs(x)), log(xm)))
- self.assertTrue (eq(numpy.log10(abs(x)), log10(xm)))
- finally:
- numpy.seterr(**olderr)
- self.assertTrue (eq(numpy.exp(x), exp(xm)))
- self.assertTrue (eq(numpy.arcsin(z), arcsin(zm)))
- self.assertTrue (eq(numpy.arccos(z), arccos(zm)))
- self.assertTrue (eq(numpy.arctan(z), arctan(zm)))
- self.assertTrue (eq(numpy.arctan2(x, y), arctan2(xm, ym)))
- self.assertTrue (eq(numpy.absolute(x), absolute(xm)))
- self.assertTrue (eq(numpy.equal(x, y), equal(xm, ym)))
- self.assertTrue (eq(numpy.not_equal(x, y), not_equal(xm, ym)))
- self.assertTrue (eq(numpy.less(x, y), less(xm, ym)))
- self.assertTrue (eq(numpy.greater(x, y), greater(xm, ym)))
- self.assertTrue (eq(numpy.less_equal(x, y), less_equal(xm, ym)))
- self.assertTrue (eq(numpy.greater_equal(x, y), greater_equal(xm, ym)))
- self.assertTrue (eq(numpy.conjugate(x), conjugate(xm)))
- self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, ym))))
- self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((x, y))))
- self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, y))))
- self.assertTrue (eq(numpy.concatenate((x, y, x)), concatenate((x, ym, x))))
+ self.assertTrue (eq(np.cos(x), cos(xm)))
+ self.assertTrue (eq(np.cosh(x), cosh(xm)))
+ self.assertTrue (eq(np.sin(x), sin(xm)))
+ self.assertTrue (eq(np.sinh(x), sinh(xm)))
+ self.assertTrue (eq(np.tan(x), tan(xm)))
+ self.assertTrue (eq(np.tanh(x), tanh(xm)))
+ with np.errstate(divide='ignore', invalid='ignore'):
+ self.assertTrue (eq(np.sqrt(abs(x)), sqrt(xm)))
+ self.assertTrue (eq(np.log(abs(x)), log(xm)))
+ self.assertTrue (eq(np.log10(abs(x)), log10(xm)))
+ self.assertTrue (eq(np.exp(x), exp(xm)))
+ self.assertTrue (eq(np.arcsin(z), arcsin(zm)))
+ self.assertTrue (eq(np.arccos(z), arccos(zm)))
+ self.assertTrue (eq(np.arctan(z), arctan(zm)))
+ self.assertTrue (eq(np.arctan2(x, y), arctan2(xm, ym)))
+ self.assertTrue (eq(np.absolute(x), absolute(xm)))
+ self.assertTrue (eq(np.equal(x, y), equal(xm, ym)))
+ self.assertTrue (eq(np.not_equal(x, y), not_equal(xm, ym)))
+ self.assertTrue (eq(np.less(x, y), less(xm, ym)))
+ self.assertTrue (eq(np.greater(x, y), greater(xm, ym)))
+ self.assertTrue (eq(np.less_equal(x, y), less_equal(xm, ym)))
+ self.assertTrue (eq(np.greater_equal(x, y), greater_equal(xm, ym)))
+ self.assertTrue (eq(np.conjugate(x), conjugate(xm)))
+ self.assertTrue (eq(np.concatenate((x, y)), concatenate((xm, ym))))
+ self.assertTrue (eq(np.concatenate((x, y)), concatenate((x, y))))
+ self.assertTrue (eq(np.concatenate((x, y)), concatenate((xm, y))))
+ self.assertTrue (eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
def test_xtestCount (self):
"Test count"
ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
if sys.version_info[0] >= 3:
- self.assertTrue(isinstance(count(ott), numpy.integer))
+ self.assertTrue(isinstance(count(ott), np.integer))
else:
self.assertTrue(isinstance(count(ott), int))
self.assertEqual(3, count(ott))
self.assertEqual(1, count(1))
self.assertTrue (eq(0, array(1, mask=[1])))
ott = ott.reshape((2, 2))
- assert_(isinstance(count(ott, 0), numpy.ndarray))
+ assert_(isinstance(count(ott, 0), np.ndarray))
if sys.version_info[0] >= 3:
- assert_(isinstance(count(ott), numpy.integer))
+ assert_(isinstance(count(ott), np.integer))
else:
assert_(isinstance(count(ott), int))
self.assertTrue (eq(3, count(ott)))
@@ -182,7 +170,7 @@ class TestMa(TestCase):
def test_testMinMax (self):
"Test minimum and maximum."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
- xr = numpy.ravel(x) #max doesn't work if shaped
+ xr = np.ravel(x) #max doesn't work if shaped
xmr = ravel(xm)
#true because of careful selection of data
@@ -194,34 +182,34 @@ class TestMa(TestCase):
def test_testAddSumProd (self):
"Test add, sum, product."
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
- self.assertTrue (eq(numpy.add.reduce(x), add.reduce(x)))
- self.assertTrue (eq(numpy.add.accumulate(x), add.accumulate(x)))
+ self.assertTrue (eq(np.add.reduce(x), add.reduce(x)))
+ self.assertTrue (eq(np.add.accumulate(x), add.accumulate(x)))
self.assertTrue (eq(4, sum(array(4), axis=0)))
self.assertTrue (eq(4, sum(array(4), axis=0)))
- self.assertTrue (eq(numpy.sum(x, axis=0), sum(x, axis=0)))
- self.assertTrue (eq(numpy.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
- self.assertTrue (eq(numpy.sum(x, 0), sum(x, 0)))
- self.assertTrue (eq(numpy.product(x, axis=0), product(x, axis=0)))
- self.assertTrue (eq(numpy.product(x, 0), product(x, 0)))
- self.assertTrue (eq(numpy.product(filled(xm, 1), axis=0),
+ self.assertTrue (eq(np.sum(x, axis=0), sum(x, axis=0)))
+ self.assertTrue (eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
+ self.assertTrue (eq(np.sum(x, 0), sum(x, 0)))
+ self.assertTrue (eq(np.product(x, axis=0), product(x, axis=0)))
+ self.assertTrue (eq(np.product(x, 0), product(x, 0)))
+ self.assertTrue (eq(np.product(filled(xm, 1), axis=0),
product(xm, axis=0)))
if len(s) > 1:
- self.assertTrue (eq(numpy.concatenate((x, y), 1),
+ self.assertTrue (eq(np.concatenate((x, y), 1),
concatenate((xm, ym), 1)))
- self.assertTrue (eq(numpy.add.reduce(x, 1), add.reduce(x, 1)))
- self.assertTrue (eq(numpy.sum(x, 1), sum(x, 1)))
- self.assertTrue (eq(numpy.product(x, 1), product(x, 1)))
+ self.assertTrue (eq(np.add.reduce(x, 1), add.reduce(x, 1)))
+ self.assertTrue (eq(np.sum(x, 1), sum(x, 1)))
+ self.assertTrue (eq(np.product(x, 1), product(x, 1)))
def test_testCI(self):
"Test of conversions and indexing"
- x1 = numpy.array([1, 2, 4, 3])
+ x1 = np.array([1, 2, 4, 3])
x2 = array(x1, mask=[1, 0, 0, 0])
x3 = array(x1, mask=[0, 1, 0, 1])
x4 = array(x1)
# test conversion to strings
junk, garbage = str(x2), repr(x2)
- assert_(eq(numpy.sort(x1), sort(x2, fill_value=0)))
+ assert_(eq(np.sort(x1), sort(x2, fill_value=0)))
# tests of indexing
assert_(type(x2[1]) is type(x1[1]))
assert_(x1[1] == x2[1])
@@ -248,13 +236,13 @@ class TestMa(TestCase):
x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
assert_(allequal(x4, array([1, 2, 3, 4])))
- x1 = numpy.arange(5) * 1.0
+ x1 = np.arange(5) * 1.0
x2 = masked_values(x1, 3.0)
assert_(eq(x1, x2))
assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
assert_(eq(3.0, x2.fill_value))
x1 = array([1, 'hello', 2, 3], object)
- x2 = numpy.array([1, 'hello', 2, 3], object)
+ x2 = np.array([1, 'hello', 2, 3], object)
s1 = x1[1]
s2 = x2[1]
self.assertEqual(type(s2), str)
@@ -271,7 +259,7 @@ class TestMa(TestCase):
m3 = make_mask(m, copy=1)
self.assertTrue(m is not m3)
- x1 = numpy.arange(5)
+ x1 = np.arange(5)
y1 = array(x1, mask=m)
self.assertTrue(y1._data is not x1)
self.assertTrue(allequal(x1, y1._data))
@@ -324,7 +312,7 @@ class TestMa(TestCase):
def test_testMaPut(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
- i = numpy.nonzero(m)[0]
+ i = np.nonzero(m)[0]
put(ym, i, zm)
assert_(all(take(ym, i, axis=0) == zm))
@@ -439,15 +427,15 @@ class TestMa(TestCase):
def test_testTakeTransposeInnerOuter(self):
"Test of take, transpose, inner, outer products"
x = arange(24)
- y = numpy.arange(24)
+ y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
- assert_(eq(numpy.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))
- assert_(eq(numpy.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))
- assert_(eq(numpy.inner(filled(x, 0), filled(y, 0)),
+ assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1))))
+ assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1)))
+ assert_(eq(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y)))
- assert_(eq(numpy.outer(filled(x, 0), filled(y, 0)),
+ assert_(eq(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y)))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
@@ -557,8 +545,8 @@ class TestMa(TestCase):
self.assertTrue(allclose(average(x, axis=0, weights=w1), 2.5))
y = array([arange(6), 2.0 * arange(6)])
self.assertTrue(allclose(average(y, None),
- numpy.add.reduce(numpy.arange(6)) * 3. / 12.))
- self.assertTrue(allclose(average(y, axis=0), numpy.arange(6) * 3. / 2.))
+ np.add.reduce(np.arange(6)) * 3. / 12.))
+ self.assertTrue(allclose(average(y, axis=0), np.arange(6) * 3. / 2.))
self.assertTrue(allclose(average(y, axis=1),
[average(x, axis=0), average(x, axis=0) * 2.0]))
self.assertTrue(allclose(average(y, None, weights=w2), 20. / 6.))
@@ -617,12 +605,9 @@ class TestMa(TestCase):
def test_testScalarArithmetic(self):
xm = array(0, mask=1)
#TODO FIXME: Find out what the following raises a warning in r8247
- err_status = numpy.geterr()
- try:
- numpy.seterr(divide='ignore')
+ with np.errstate():
+ np.seterr(divide='ignore')
self.assertTrue((1 / array(0)).mask)
- finally:
- numpy.seterr(**err_status)
self.assertTrue((1 + xm).mask)
self.assertTrue((-xm).mask)
self.assertTrue((-xm).mask)
@@ -656,7 +641,7 @@ class TestMa(TestCase):
self.assertEqual(a.ndim, 1)
def test_testAPI(self):
- self.assertFalse([m for m in dir(numpy.ndarray)
+ self.assertFalse([m for m in dir(np.ndarray)
if m not in dir(MaskedArray) and not m.startswith('_')])
def test_testSingleElementSubscript(self):
@@ -699,18 +684,15 @@ class TestUfuncs(TestCase):
uf = getattr(umath, f)
except AttributeError:
uf = getattr(fromnumeric, f)
- mf = getattr(numpy.ma, f)
+ mf = getattr(np.ma, f)
args = self.d[:uf.nin]
- olderr = numpy.geterr()
- try:
+ with np.errstate():
if f in f_invalid_ignore:
- numpy.seterr(invalid='ignore')
+ np.seterr(invalid='ignore')
if f in ['arctanh', 'log', 'log10']:
- numpy.seterr(divide='ignore')
+ np.seterr(divide='ignore')
ur = uf(*args)
mr = mf(*args)
- finally:
- numpy.seterr(**olderr)
self.assertTrue(eq(ur.filled(0), mr.filled(0), f))
self.assertTrue(eqmask(ur.mask, mr.mask))
@@ -740,7 +722,7 @@ class TestUfuncs(TestCase):
class TestArrayMethods(TestCase):
def setUp(self):
- x = numpy.array([ 8.375, 7.545, 8.828, 8.5 , 1.757, 5.928,
+ x = np.array([ 8.375, 7.545, 8.828, 8.5 , 1.757, 5.928,
8.43 , 7.78 , 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
6.04 , 9.63 , 7.712, 3.382, 4.489, 6.479,
@@ -749,7 +731,7 @@ class TestArrayMethods(TestCase):
X = x.reshape(6, 6)
XX = x.reshape(3, 2, 2, 3)
- m = numpy.array([0, 1, 0, 1, 0, 0,
+ m = np.array([0, 1, 0, 1, 0, 0,
1, 0, 1, 1, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, 1, 1, 1,
@@ -759,7 +741,7 @@ class TestArrayMethods(TestCase):
mX = array(data=X, mask=m.reshape(X.shape))
mXX = array(data=XX, mask=m.reshape(XX.shape))
- m2 = numpy.array([1, 1, 0, 1, 0, 0,
+ m2 = np.array([1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 0, 1,
0, 0, 1, 1, 0, 1,
0, 0, 0, 1, 1, 1,
@@ -789,8 +771,8 @@ class TestArrayMethods(TestCase):
(x, X, XX, m, mx, mX, mXX,) = self.d
(n, m) = X.shape
self.assertEqual(mx.ptp(), mx.compressed().ptp())
- rows = numpy.zeros(n, numpy.float_)
- cols = numpy.zeros(m, numpy.float_)
+ rows = np.zeros(n, np.float_)
+ cols = np.zeros(m, np.float_)
for k in range(m):
cols[k] = mX[:, k].compressed().ptp()
for k in range(n):
@@ -830,7 +812,7 @@ class TestArrayMethods(TestCase):
for k in range(6):
self.assertTrue(eq(mXvar1[k], mX[k].compressed().var()))
self.assertTrue(eq(mXvar0[k], mX[:, k].compressed().var()))
- self.assertTrue(eq(numpy.sqrt(mXvar0[k]),
+ self.assertTrue(eq(np.sqrt(mXvar0[k]),
mX[:, k].compressed().std()))
@@ -856,7 +838,7 @@ def eqmask(m1, m2):
#""" % (n, t*1000.0, t1/t, t2/t)
#def testta(n, f):
-# x=numpy.arange(n) + 1.0
+# x=np.arange(n) + 1.0
# tn0 = time.time()
# z = f(x)
# return time.time() - tn0
diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py
index 54b202684..7014246d4 100644
--- a/numpy/ma/tests/test_subclassing.py
+++ b/numpy/ma/tests/test_subclassing.py
@@ -96,12 +96,9 @@ class TestSubclassing(TestCase):
def test_masked_unary_operations(self):
"Tests masked_unary_operation"
(x, mx) = self.data
- olderr = np.seterr(divide='ignore')
- try:
+ with np.errstate(divide='ignore'):
self.assertTrue(isinstance(log(mx), mmatrix))
assert_equal(log(x), np.log(x))
- finally:
- np.seterr(**olderr)
def test_masked_binary_operations(self):
"Tests masked_binary_operation"
diff --git a/numpy/ma/timer_comparison.py b/numpy/ma/timer_comparison.py
index 6345f9ca3..350412b85 100644
--- a/numpy/ma/timer_comparison.py
+++ b/numpy/ma/timer_comparison.py
@@ -9,6 +9,7 @@ import np.core.fromnumeric as fromnumeric
from np.testing.utils import build_err_msg
+# Fixme: this does not look right.
np.seterr(all='ignore')
pi = np.pi
diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py
index f58997d58..ca564721a 100644
--- a/numpy/testing/utils.py
+++ b/numpy/testing/utils.py
@@ -71,14 +71,11 @@ def gisfinite(x):
exception is always raised.
This should be removed once this problem is solved at the Ufunc level."""
- from numpy.core import isfinite, seterr
- err = seterr(invalid='ignore')
- try:
+ from numpy.core import isfinite, errstate
+ with errstate(invalid='ignore'):
st = isfinite(x)
if isinstance(st, type(NotImplemented)):
raise TypeError("isfinite not supported for this type")
- finally:
- seterr(**err)
return st
def gisinf(x):
@@ -92,14 +89,11 @@ def gisinf(x):
exception is always raised.
This should be removed once this problem is solved at the Ufunc level."""
- from numpy.core import isinf, seterr
- err = seterr(invalid='ignore')
- try:
+ from numpy.core import isinf, errstate
+ with errstate(invalid='ignore'):
st = isinf(x)
if isinstance(st, type(NotImplemented)):
raise TypeError("isinf not supported for this type")
- finally:
- seterr(**err)
return st
def rand(*args):
@@ -539,13 +533,9 @@ def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
return
# Normalized the numbers to be in range (-10.0,10.0)
# scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))))
- err = np.seterr(invalid='ignore')
- try:
+ with np.errstate(invalid='ignore'):
scale = 0.5*(np.abs(desired) + np.abs(actual))
scale = np.power(10,np.floor(np.log10(scale)))
- finally:
- np.seterr(**err)
-
try:
sc_desired = desired/scale
except ZeroDivisionError: