本文整理汇总了Python中numpy.geterr函数的典型用法代码示例。如果您正苦于以下问题:Python geterr函数的具体用法?Python geterr怎么用?Python geterr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了geterr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_log2
def test_log2(self):
"""log2: should work fine on positive/negative numbers and zero"""
self.assertEqual(log2(1),0)
self.assertEqual(log2(2),1)
self.assertEqual(log2(4),2)
self.assertEqual(log2(8),3)
#SUPPORT2425
#with numpy_err(divide='ignore'):
ori_err = numpy.geterr()
numpy.seterr(divide='ignore')
try:
try:
self.assertEqual(log2(0),float('-inf'))
except (ValueError, OverflowError): #platform-dependent
pass
finally:
numpy.seterr(**ori_err)
#SUPPORT2425
ori_err = numpy.geterr()
numpy.seterr(divide='raise')
try:
#with numpy_err(divide='raise'):
self.assertRaises(FloatingPointError, log2, 0)
finally:
numpy.seterr(**ori_err)
#nan is the only thing that's not equal to itself
try:
self.assertNotEqual(log2(-1),log2(-1)) #now nan
except ValueError:
pass
示例2: test_ppsd_plot_cumulative
def test_ppsd_plot_cumulative(self):
"""
Test plot of ppsd example data, cumulative style.
"""
# Catch underflow warnings due to plotting on log-scale.
_t = np.geterr()
np.seterr(all="ignore")
try:
with ImageComparison(self.path, 'ppsd_cumulative.png',
reltol=1.5) as ic:
self.ppsd.plot(
show=False, show_coverage=True, show_histogram=True,
show_noise_models=True, grid=True, period_lim=(0.02, 100),
cumulative=True,
# This does not do anything but silences a warning that
# the `cumulative` and `max_percentage` arguments cannot
# be used at the same time.
max_percentage=None)
fig = plt.gcf()
ax = fig.axes[0]
ax.set_ylim(-160, -130)
plt.draw()
fig.savefig(ic.name)
finally:
np.seterr(**_t)
示例3: test_smoothingMatrix
def test_smoothingMatrix(self):
"""
Tests some aspects of the matrix.
"""
# Disable div by zero errors.
temp = np.geterr()
np.seterr(all="ignore")
frequencies = np.array([0.0, 1.0, 2.0, 10.0, 25.0, 50.0, 100.0], dtype=np.float32)
matrix = calculateSmoothingMatrix(frequencies, 20.0)
self.assertEqual(matrix.dtype, np.float32)
for _i, freq in enumerate(frequencies):
np.testing.assert_array_equal(matrix[_i], konnoOhmachiSmoothingWindow(frequencies, freq, 20.0))
# Should not be normalized. Test only for larger frequencies
# because smaller ones have a smaller window.
if freq >= 10.0:
self.assertTrue(matrix[_i].sum() > 1.0)
# Input should be output dtype.
frequencies = np.array([0.0, 1.0, 2.0, 10.0, 25.0, 50.0, 100.0], dtype=np.float64)
matrix = calculateSmoothingMatrix(frequencies, 20.0)
self.assertEqual(matrix.dtype, np.float64)
# Check normalization.
frequencies = np.array([0.0, 1.0, 2.0, 10.0, 25.0, 50.0, 100.0], dtype=np.float32)
matrix = calculateSmoothingMatrix(frequencies, 20.0, normalize=True)
self.assertEqual(matrix.dtype, np.float32)
for _i, freq in enumerate(frequencies):
np.testing.assert_array_equal(
matrix[_i], konnoOhmachiSmoothingWindow(frequencies, freq, 20.0, normalize=True)
)
# Should not be normalized. Test only for larger frequencies
# because smaller ones have a smaller window.
self.assertAlmostEqual(matrix[_i].sum(), 1.0, 5)
np.seterr(**temp)
示例4: setUp
def setUp(self):
# Most generic way to get the actual data directory.
self.data_dir = os.path.join(os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe()))), "data")
self.image_dir = os.path.join(os.path.dirname(__file__), 'images')
self.nperr = np.geterr()
np.seterr(all='ignore')
示例5: H_mag
def H_mag(num, den, z, H_max, H_min = None, log = False, div_by_0 = 'ignore'):
"""
Calculate `|H(z)|` at the complex frequency(ies) `z` (scalar or
array-like). The function `H(z)` is given in polynomial form with numerator and
denominator. When log = True, `20 log_10 (|H(z)|)` is returned.
The result is clipped at H_min, H_max; clipping can be disabled by passing
None as the argument.
Parameters
----------
num : float or array-like
The numerator polynome of H(z).
den : float or array-like
The denominator polynome of H(z).
z : float or array-like
The complex frequency(ies) where `H(z)` is to be evaluated
H_max : float
The maximum value to which the result is clipped
H_min : float, optional
The minimum value to which the result is clipped (default: 0)
log : boolean, optional
When true, return 20 * log10 (|H(z)|). The clipping limits have to
be given as dB in this case.
div_by_0 : string, optional
What to do when division by zero occurs during calculation (default:
'ignore'). As the denomintor of H(z) becomes 0 at each pole, warnings
are suppressed by default. This parameter is passed to numpy.seterr(),
hence other valid options are 'warn', 'raise' and 'print'.
Returns
-------
H_mag : float or ndarray
The magnitude |`H(z)`| for each value of `z`.
"""
try: len(num)
except TypeError:
num_val = abs(num) # numerator is a scalar
else:
num_val = abs(np.polyval(num, z)) # evaluate numerator at z
try: len(den)
except TypeError:
den_val = abs(den) # denominator is a scalar
else:
den_val = abs(np.polyval(den, z)) # evaluate denominator at z
olderr = np.geterr() # store current floating point error behaviour
# turn off divide by zero warnings, just return 'inf':
np.seterr(divide = 'ignore')
if log:
H_val = 20 * np.log10(num_val / den_val)
else:
H_val = num_val / den_val
np.seterr(**olderr) # restore previous floating point error behaviour
# clip result to H_min / H_max
return np.clip(H_val, H_min, H_max)
示例6: test_scale_trace
def test_scale_trace(self):
"""scale_trace should scale trace to correct values"""
#should scale to -1 by default
#WARNING: won't work with integer matrices
m = array([[-2., 0],[0,-2]])
scale_trace(m)
self.assertFloatEqual(m, [[-0.5, 0],[0,-0.5]])
#should work even with zero rows
m = array([
[1.0,2,3,4],
[2,4,4,0],
[1,1,0,1],
[0,0,0,0]
])
m_orig = m.copy()
scale_trace(m)
self.assertFloatEqual(m, m_orig / -5)
#but should fail if trace is zero
m = array([[0,1,1],[1,0,1],[1,1,0]])
#SUPPORT2425
ori_err = numpy.geterr()
numpy.seterr(divide='raise')
try:
#with numpy_err(divide='raise'):
self.assertRaises((ZeroDivisionError, FloatingPointError), \
scale_trace, m)
finally:
numpy.seterr(**ori_err)
示例7: less
def less(a, b):
"""return a < b, while comparing nan results in False without warning"""
current_err_setting = np.geterr()
np.seterr(invalid='ignore')
res = a < b
np.seterr(**current_err_setting)
return res
示例8: test_numpy_err_state_is_default
def test_numpy_err_state_is_default():
expected = {"over": "warn", "divide": "warn",
"invalid": "warn", "under": "ignore"}
import numpy as np
# The error state should be unchanged after that import.
assert np.geterr() == expected
示例9: test_smoothingWindow
def test_smoothingWindow(self):
"""
Tests the creation of the smoothing window.
"""
# Disable div by zero errors.
temp = np.geterr()
np.seterr(all="ignore")
# Frequency of zero results in a delta peak at zero (there usually
# should be just one zero in the frequency array.
window = konnoOhmachiSmoothingWindow(np.array([0, 1, 0, 3], dtype=np.float32), 0)
np.testing.assert_array_equal(window, np.array([1, 0, 1, 0], dtype=np.float32))
# Wrong dtypes raises.
self.assertRaises(ValueError, konnoOhmachiSmoothingWindow, np.arange(10, dtype=np.int32), 10)
# If frequency=center frequency, log results in infinity. Limit of
# whole formulae is 1.
window = konnoOhmachiSmoothingWindow(np.array([5.0, 1.0, 5.0, 2.0], dtype=np.float32), 5)
np.testing.assert_array_equal(window[[0, 2]], np.array([1.0, 1.0], dtype=np.float32))
# Output dtype should be the dtype of frequencies.
self.assertEqual(konnoOhmachiSmoothingWindow(np.array([1, 6, 12], dtype=np.float32), 5).dtype, np.float32)
self.assertEqual(konnoOhmachiSmoothingWindow(np.array([1, 6, 12], dtype=np.float64), 5).dtype, np.float64)
# Check if normalizing works.
window = konnoOhmachiSmoothingWindow(self.frequencies, 20)
self.assertTrue(window.sum() > 1.0)
window = konnoOhmachiSmoothingWindow(self.frequencies, 20, normalize=True)
self.assertAlmostEqual(window.sum(), 1.0, 5)
# Just one more to test if there are no invalid values and the range if
# ok.
window = konnoOhmachiSmoothingWindow(self.frequencies, 20)
self.assertEqual(np.any(np.isnan(window)), False)
self.assertEqual(np.any(np.isinf(window)), False)
self.assertTrue(np.all(window <= 1.0))
self.assertTrue(np.all(window >= 0.0))
np.seterr(**temp)
示例10: __init__
def __init__(self, hidden_layers=[32]):
restore_these_settings = np.geterr()
temp_settings = restore_these_settings.copy()
temp_settings["over"] = "ignore"
temp_settings["under"] = "ignore"
np.seterr(**temp_settings)
np.seterr(**restore_these_settings)
self.input_nodes = 65 # number of input nodes + 1 for the bias
self.hidden_layers = hidden_layers # list containing the number of hidden nodes and number of nodes per layer
self.output_nodes = 10 # number of output nodes
self.alpha = 1.0 # scalar used when back propagating the errors
# initialize the weights which are is a list of nxm 2d arrays where each weight corresponds to a layer
self.weights = [
np.random.random_sample((self.input_nodes, self.hidden_layers[0])) * .09 + .01
]
for i in range(len(hidden_layers) - 1):
self.weights.append(
np.random.random_sample((self.hidden_layers[i], self.hidden_layers[i + 1])) * .09 + .01)
self.weights.append(
np.random.random_sample((self.hidden_layers[-1], self.output_nodes)) * .09 + .01)
示例11: test_numerical_stability
def test_numerical_stability():
"""Check numerical stability."""
old_settings = np.geterr()
np.seterr(all="raise")
X = np.array(
[
[152.08097839, 140.40744019, 129.75102234, 159.90493774],
[142.50700378, 135.81935120, 117.82884979, 162.75781250],
[127.28772736, 140.40744019, 129.75102234, 159.90493774],
[132.37025452, 143.71923828, 138.35694885, 157.84558105],
[103.10237122, 143.71928406, 138.35696411, 157.84559631],
[127.71276855, 143.71923828, 138.35694885, 157.84558105],
[120.91514587, 140.40744019, 129.75102234, 159.90493774],
]
)
y = np.array([1.0, 0.70209277, 0.53896582, 0.0, 0.90914464, 0.48026916, 0.49622521])
dt = tree.DecisionTreeRegressor()
dt.fit(X, y)
dt.fit(X, -y)
dt.fit(-X, y)
dt.fit(-X, -y)
np.seterr(**old_settings)
示例12: VMLookupTable
def VMLookupTable():
try: # try loading ordered dict
from collections import OrderedDict
except ImportError: # not installed, try on pythonpath
try:
from OrderedDict import OrderedDict
except ImportError:
"PyNoddy requires OrderedDict to run. Please download it and make it available on the pythonpath."
kappa_lookup = OrderedDict()
#disable numpy warnings
err = np.geterr()
np.seterr(all='ignore')
# build lookup table
for k in range(1000, 100, -20):
ci = sc.stats.vonmises.interval(0.95, k)
kappa_lookup[ci[1]] = k
for k in range(100, 10, -1):
ci = sc.stats.vonmises.interval(0.95, k)
kappa_lookup[ci[1]] = k
for k in np.arange(10, 0, -0.1):
ci = sc.stats.vonmises.interval(0.95, k)
kappa_lookup[ci[1]] = k
#re-enable numpy warnings
np.seterr(**err)
# return lookup table
return kappa_lookup
示例13: __enter__
def __enter__(self):
try:
import numpy
except ImportError:
return None
self.errstate = numpy.geterr()
numpy.seterr(invalid="ignore")
return numpy
示例14: test_numpy_errstate_is_default
def test_numpy_errstate_is_default():
# The defaults since numpy 1.6.0
expected = {'over': 'warn', 'divide': 'warn', 'invalid': 'warn',
'under': 'ignore'}
import numpy as np
from pandas.compat import numpy # noqa
# The errstate should be unchanged after that import.
assert np.geterr() == expected
示例15: wrapped
def wrapped(e):
old_settings = np.geterr()
np.seterr(invalid="raise")
try:
return func(e)
except exception:
warnings.warn(msg + " " + e.fname, exc.EmptyStep)
np.seterr(**old_settings)