本文整理汇总了Python中numpy.errstate方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.errstate方法的具体用法?Python numpy.errstate怎么用?Python numpy.errstate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.errstate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rotation_const
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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
示例2: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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
示例3: r2z
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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))
示例4: z2r
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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)
示例5: test_generic
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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)
示例6: gisinf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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
示例7: test_warnings
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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))
示例8: test_known_types
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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])
示例9: test_complex_nan_comparisons
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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))
示例10: test_zero_division
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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))
示例11: test_signed_zeros
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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])
示例12: test_combine_add
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
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)
示例13: test1
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
def test1(self):
r"""Testing some limiting cases."""
p = np.array([0.0,1.0,1.0,1.0,1.0])
Rp = np.array([1.0,0.0,1.0,1.0,1.0]) * u.kilometer
d = np.array([1.0,1.0,0.0,1.0,np.inf]) * u.kilometer
Phi = np.array([1.0,1.0,1.0,0.0,1.0])
# suppress division-by-zero warnings
with np.errstate(divide='ignore'):
result = deltaMag(p, Rp, d, Phi)
expected = np.array([np.inf, np.inf, -np.inf, np.inf, np.inf])
np.testing.assert_allclose(expected, result, rtol=1e-1, atol=0)
示例14: _incremental_mean_and_var
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
def _incremental_mean_and_var(X, epsilon, bounds, last_mean, last_variance, last_sample_count):
# Initialising new accountant, as budget is tracked in main class. Subject to review in line with GH issue #21
temp_acc = BudgetAccountant()
# old = stats until now
# new = the current increment
# updated = the aggregated stats
last_sum = last_mean * last_sample_count
new_mean = nanmean(X, epsilon=epsilon, axis=0, bounds=bounds, accountant=temp_acc)
new_sample_count = np.sum(~np.isnan(X), axis=0)
new_sum = new_mean * new_sample_count
updated_sample_count = last_sample_count + new_sample_count
updated_mean = (last_sum + new_sum) / updated_sample_count
if last_variance is None:
updated_variance = None
else:
new_unnormalized_variance = nanvar(X, epsilon=epsilon, axis=0, bounds=bounds,
accountant=temp_acc) * new_sample_count
last_unnormalized_variance = last_variance * last_sample_count
with np.errstate(divide='ignore', invalid='ignore'):
last_over_new_count = last_sample_count / new_sample_count
updated_unnormalized_variance = (
last_unnormalized_variance + new_unnormalized_variance +
last_over_new_count / updated_sample_count *
(last_sum / last_over_new_count - new_sum) ** 2)
zeros = last_sample_count == 0
updated_unnormalized_variance[zeros] = new_unnormalized_variance[zeros]
updated_variance = updated_unnormalized_variance / updated_sample_count
return updated_mean, updated_variance, updated_sample_count
# noinspection PyPep8Naming,PyAttributeOutsideInit
示例15: _evaluate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import errstate [as 别名]
def _evaluate(self, X, out, *args, **kwargs):
g = self.g1(X)
f0 = g * X[:, 0]
f1 = g * np.sqrt(1.0 - np.power(f0 / g, 2.0))
with np.errstate(divide='ignore'):
atan = np.arctan(f1 / f0)
g0 = f0 ** 2 + f1 ** 2 - np.power(1.7 - self.LA2(0.2, 2.0, 1.0, 1.0, atan), 2.0)
t = 0.5 * np.pi - 2 * np.abs(atan - 0.25 * np.pi)
g1 = np.power(1 + self.LA2(0.5, 6.0, 3.0, 1.0, t), 2.0) - f0 ** 2 - f1 ** 2
g2 = np.power(1 - self.LA2(0.45, 6.0, 3.0, 1.0, t), 2.0) - f0 ** 2 - f1 ** 2
out["F"] = np.column_stack([f0, f1])
out["G"] = np.column_stack([g0, g1, g2])