Python numpy.errstate() Examples
The following are 30
code examples of numpy.errstate().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: grid.py From python-control with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __call__(self, transform_xy, x1, y1, x2, y2): x_, y_ = np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny) x, y = np.meshgrid(x_, y_) lon, lat = transform_xy(np.ravel(x), np.ravel(y)) with np.errstate(invalid='ignore'): if self.lon_cycle is not None: lon0 = np.nanmin(lon) # Changed from 180 to 360 to be able to span only # 90-270 (left hand side) lon -= 360. * ((lon - lon0) > 360.) if self.lat_cycle is not None: lat0 = np.nanmin(lat) # Changed from 180 to 360 to be able to span only # 90-270 (left hand side) lat -= 360. * ((lat - lat0) > 360.) lon_min, lon_max = np.nanmin(lon), np.nanmax(lon) lat_min, lat_max = np.nanmin(lat), np.nanmax(lat) lon_min, lon_max, lat_min, lat_max = \ self._adjust_extremes(lon_min, lon_max, lat_min, lat_max) return lon_min, lon_max, lat_min, lat_max
Example #2
Source File: test_getlimits.py From recruit with Apache License 2.0 | 6 votes |
def test_known_types(): # Test we are correctly compiling parameters for known types for ftype, ma_like in ((np.float16, _float_ma[16]), (np.float32, _float_ma[32]), (np.float64, _float_ma[64])): assert_ma_equal(_discovered_machar(ftype), ma_like) # Suppress warning for broken discovery of double double on PPC with np.errstate(all='ignore'): ld_ma = _discovered_machar(np.longdouble) bytes = np.dtype(np.longdouble).itemsize if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16): # 80-bit extended precision assert_ma_equal(ld_ma, _float_ma[80]) elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16: # IEE 754 128-bit assert_ma_equal(ld_ma, _float_ma[128])
Example #3
Source File: test_numeric.py From recruit with Apache License 2.0 | 6 votes |
def test_warnings(self): # test warning code path with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") with np.errstate(all="warn"): np.divide(1, 0.) assert_equal(len(w), 1) assert_("divide by zero" in str(w[0].message)) np.array(1e300) * np.array(1e300) assert_equal(len(w), 2) assert_("overflow" in str(w[-1].message)) np.array(np.inf) - np.array(np.inf) assert_equal(len(w), 3) assert_("invalid value" in str(w[-1].message)) np.array(1e-300) * np.array(1e-300) assert_equal(len(w), 4) assert_("underflow" in str(w[-1].message))
Example #4
Source File: test_umath.py From recruit with Apache License 2.0 | 6 votes |
def test_complex_nan_comparisons(): nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)] fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1), complex(1, 1), complex(-1, -1), complex(0, 0)] with np.errstate(invalid='ignore'): for x in nans + fins: x = np.array([x]) for y in nans + fins: y = np.array([y]) if np.isfinite(x) and np.isfinite(y): continue 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)) assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y)) assert_equal(x == y, False, err_msg="%r == %r" % (x, y))
Example #5
Source File: helpers.py From quail with MIT License | 6 votes |
def z2r(z): """ Function that calculates the inverse Fisher z-transformation Parameters ---------- z : int or ndarray Fishers z transformed correlation value Returns ---------- result : int or ndarray Correlation value """ with np.errstate(invalid='ignore', divide='ignore'): return (np.exp(2 * z) - 1) / (np.exp(2 * z) + 1)
Example #6
Source File: helpers.py From quail with MIT License | 6 votes |
def r2z(r): """ Function that calculates the Fisher z-transformation Parameters ---------- r : int or ndarray Correlation value Returns ---------- result : int or ndarray Fishers z transformed correlation value """ with np.errstate(invalid='ignore', divide='ignore'): return 0.5 * (np.log(1 + r) - np.log(1 - r))
Example #7
Source File: test_type_check.py From recruit with Apache License 2.0 | 6 votes |
def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): vals = nan_to_num(np.array((-1., 0, 1))/0.) assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0])) assert_(vals[1] == 0) assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2])) assert_equal(type(vals), np.ndarray) # perform the same test but in-place with np.errstate(divide='ignore', invalid='ignore'): vals = np.array((-1., 0, 1))/0. result = nan_to_num(vals, copy=False) assert_(result is vals) assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0])) assert_(vals[1] == 0) assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2])) assert_equal(type(vals), np.ndarray)
Example #8
Source File: test_scalarmath.py From recruit with Apache License 2.0 | 6 votes |
def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b/a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a))
Example #9
Source File: thermo.py From pyscf with Apache License 2.0 | 6 votes |
def rotation_const(mass, atom_coords, unit='GHz'): '''Rotational constants to characterize rotational spectra Kwargs: unit (string) : One of GHz, wavenumber ''' mass_center = numpy.einsum('z,zr->r', mass, atom_coords) / mass.sum() r = atom_coords - mass_center im = numpy.einsum('z,zr,zs->rs', mass, r, r) im = numpy.eye(3) * im.trace() - im e = numpy.sort(numpy.linalg.eigvalsh(im)) unit_im = nist.ATOMIC_MASS * (nist.BOHR_SI)**2 unit_hz = nist.HBAR / (4 * numpy.pi * unit_im) with numpy.errstate(divide='ignore'): if unit.lower() == 'ghz': e = unit_hz / e * 1e-9 elif unit.lower() == 'wavenumber': e = unit_hz / e / nist.LIGHT_SPEED_SI * 1e-2 else: raise RuntimeError('Unsupported unit ' + unit) return e
Example #10
Source File: test_scalarmath.py From recruit with Apache License 2.0 | 6 votes |
def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = ( (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)), (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)), (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)), (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)), ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0)) ) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1])
Example #11
Source File: methods.py From recruit with Apache License 2.0 | 6 votes |
def test_combine_add(self, data_repeated): # GH 20825 orig_data1, orig_data2 = data_repeated(2) s1 = pd.Series(orig_data1) s2 = pd.Series(orig_data2) result = s1.combine(s2, lambda x1, x2: x1 + x2) with np.errstate(over='ignore'): expected = pd.Series( orig_data1._from_sequence([a + b for (a, b) in zip(list(orig_data1), list(orig_data2))])) self.assert_series_equal(result, expected) val = s1.iloc[0] result = s1.combine(val, lambda x1, x2: x1 + x2) expected = pd.Series( orig_data1._from_sequence([a + val for a in list(orig_data1)])) self.assert_series_equal(result, expected)
Example #12
Source File: utils.py From recruit with Apache License 2.0 | 6 votes |
def gisinf(x): """like isinf, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- isinf and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception is always raised. This should be removed once this problem is solved at the Ufunc level.""" 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") return st
Example #13
Source File: test_nanops.py From recruit with Apache License 2.0 | 5 votes |
def test_nansem(self, ddof): from scipy.stats import sem with np.errstate(invalid='ignore'): self.check_funs(nanops.nansem, sem, allow_complex=False, allow_str=False, allow_date=False, allow_tdelta=False, allow_obj='convert', ddof=ddof)
Example #14
Source File: test_regression.py From recruit with Apache License 2.0 | 5 votes |
def test_signed_integer_division_overflow(self): # Ticket #1317. def test_type(t): min = np.array([np.iinfo(t).min]) min //= -1 with np.errstate(divide="ignore"): for t in (np.int8, np.int16, np.int32, np.int64, int, np.long): test_type(t)
Example #15
Source File: test_merge.py From recruit with Apache License 2.0 | 5 votes |
def test_merge_two_empty_df_no_division_error(self): # GH17776, PR #17846 a = pd.DataFrame({'a': [], 'b': [], 'c': []}) with np.errstate(divide='raise'): merge(a, a, on=('a', 'b'))
Example #16
Source File: test_scalarmath.py From recruit with Apache License 2.0 | 5 votes |
def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = list() # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append((( 1.0, 2.0), ( 1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1])
Example #17
Source File: test_panel.py From recruit with Apache License 2.0 | 5 votes |
def test_comparisons(self): p1 = tm.makePanel() p2 = tm.makePanel() tp = p1.reindex(items=p1.items + ['foo']) df = p1[p1.items[0]] def test_comp(func): # versus same index result = func(p1, p2) tm.assert_numpy_array_equal(result.values, func(p1.values, p2.values)) # versus non-indexed same objs pytest.raises(Exception, func, p1, tp) # versus different objs pytest.raises(Exception, func, p1, df) # versus scalar result3 = func(self.panel, 0) tm.assert_numpy_array_equal(result3.values, func(self.panel.values, 0)) with np.errstate(invalid='ignore'): test_comp(operator.eq) test_comp(operator.ne) test_comp(operator.lt) test_comp(operator.gt) test_comp(operator.ge) test_comp(operator.le)
Example #18
Source File: test_eval.py From recruit with Apache License 2.0 | 5 votes |
def test_binary_functions(self): df = DataFrame({'a': np.random.randn(10), 'b': np.random.randn(10)}) a = df.a b = df.b for fn in self.binary_fns: expr = "{0}(a, b)".format(fn) got = self.eval(expr) with np.errstate(all='ignore'): expect = getattr(np, fn)(a, b) tm.assert_almost_equal(got, expect, check_names=False)
Example #19
Source File: test_umath.py From recruit with Apache License 2.0 | 5 votes |
def test_inf(self): 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] with np.errstate(invalid='raise'): 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)
Example #20
Source File: test_umath.py From recruit with Apache License 2.0 | 5 votes |
def test_power_complex(self): x = np.array([1+2j, 2+3j, 3+4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j]) assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3]) assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4]) assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)]) assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2]) assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197, (-117-44j)/15625]) assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j), ncu.sqrt(3+4j)]) norm = 1./((x**14)[0]) assert_almost_equal(x**14 * norm, [i * norm for i in [-76443+16124j, 23161315+58317492j, 5583548873 + 2465133864j]]) # Ticket #836 def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: z = np.array([z], dtype=np.complex_) 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)
Example #21
Source File: test_umath.py From recruit with Apache License 2.0 | 5 votes |
def test_sign(self): a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) out = np.zeros(a.shape) tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0]) 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)
Example #22
Source File: test_umath.py From recruit with Apache License 2.0 | 5 votes |
def test_zero_division_complex(self): with np.errstate(invalid="ignore", divide="ignore"): x = np.array([0.0], dtype=np.complex128) y = 1.0/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.nan)/x assert_(np.isinf(y)[0]) y = complex(np.nan, np.inf)/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.inf)/x assert_(np.isinf(y)[0]) y = 0.0/x assert_(np.isnan(y)[0])
Example #23
Source File: test_numeric.py From recruit with Apache License 2.0 | 5 votes |
def test_divide_err(self): with np.errstate(divide='raise'): with assert_raises(FloatingPointError): np.array([1.]) / np.array([0.]) np.seterr(divide='ignore') np.array([1.]) / np.array([0.])
Example #24
Source File: test_numeric.py From recruit with Apache License 2.0 | 5 votes |
def test_set(self): with np.errstate(): err = np.seterr() old = np.seterr(divide='print') assert_(err == old) new = np.seterr() assert_(new['divide'] == 'print') np.seterr(over='raise') assert_(np.geterr()['over'] == 'raise') assert_(new['divide'] == 'print') np.seterr(**old) assert_(np.geterr() == old)
Example #25
Source File: test_umath_complex.py From recruit with Apache License 2.0 | 5 votes |
def check_complex_value(f, x1, y1, x2, y2, exact=True): z1 = np.array([complex(x1, y1)]) z2 = complex(x2, y2) with np.errstate(invalid='ignore'): if exact: assert_equal(f(z1), z2) else: assert_almost_equal(f(z1), z2)
Example #26
Source File: test_errstate.py From recruit with Apache License 2.0 | 5 votes |
def test_errcall(self): def foo(*args): print(args) olderrcall = np.geterrcall() with np.errstate(call=foo): assert_(np.geterrcall() is foo, 'call is not foo') with np.errstate(call=None): assert_(np.geterrcall() is None, 'call is not None') assert_(np.geterrcall() is olderrcall, 'call is not olderrcall')
Example #27
Source File: test_errstate.py From recruit with Apache License 2.0 | 5 votes |
def test_invalid(self): with np.errstate(all='raise', under='ignore'): a = -np.arange(3) # This should work with np.errstate(invalid='ignore'): np.sqrt(a) # While this should fail! with assert_raises(FloatingPointError): np.sqrt(a)
Example #28
Source File: test_half.py From recruit with Apache License 2.0 | 5 votes |
def test_nans_infs(self): 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)) assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32)) assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32)) assert_equal(np.spacing(float16(65504)), np.inf) # Check comparisons of all values with NaN nan = float16(np.nan) assert_(not (self.all_f16 == nan).any()) assert_(not (nan == self.all_f16).any()) assert_((self.all_f16 != nan).all()) assert_((nan != self.all_f16).all()) assert_(not (self.all_f16 < nan).any()) assert_(not (nan < self.all_f16).any()) assert_(not (self.all_f16 <= nan).any()) assert_(not (nan <= self.all_f16).any()) assert_(not (self.all_f16 > nan).any()) assert_(not (nan > self.all_f16).any()) assert_(not (self.all_f16 >= nan).any()) assert_(not (nan >= self.all_f16).any())
Example #29
Source File: test_machar.py From recruit with Apache License 2.0 | 5 votes |
def test_underlow(self): # Regression test for #759: # instantiating MachAr for dtype = np.float96 raises spurious warning. with errstate(all='raise'): try: self._run_machar_highprec() except FloatingPointError as e: msg = "Caught %s exception, should not have been raised." % e raise AssertionError(msg)
Example #30
Source File: test_subclassing.py From recruit with Apache License 2.0 | 5 votes |
def test_masked_unary_operations(self): # Tests masked_unary_operation (x, mx) = self.data with np.errstate(divide='ignore'): assert_(isinstance(log(mx), msubarray)) assert_equal(log(x), np.log(x))