本文整理汇总了Python中numpy.geterr函数的典型用法代码示例。如果您正苦于以下问题:Python geterr函数的具体用法?Python geterr怎么用?Python geterr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了geterr函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:GavinHuttley,项目名称:pycogent,代码行数:33,代码来源:test_array.py
示例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)
开发者ID:Keita1,项目名称:obspy,代码行数:25,代码来源:test_ppsd.py
示例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)
开发者ID:krischer,项目名称:obspy,代码行数:32,代码来源:test_konnoohmachi.py
示例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')
开发者ID:AntonyButcher,项目名称:obspy,代码行数:7,代码来源:test_response.py
示例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)
开发者ID:euripedesrocha,项目名称:pyFDA,代码行数:60,代码来源:pyfda_lib.py
示例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)
开发者ID:GavinHuttley,项目名称:pycogent,代码行数:29,代码来源:test_array.py
示例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
开发者ID:brockho,项目名称:numbbo,代码行数:7,代码来源:toolsdivers.py
示例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
开发者ID:forking-repos,项目名称:pandas,代码行数:7,代码来源:test_util.py
示例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)
开发者ID:krischer,项目名称:obspy,代码行数:33,代码来源:test_konnoohmachi.py
示例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)
开发者ID:mikegwyn17,项目名称:ANN,代码行数:26,代码来源:NeuralNet.py
示例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)
开发者ID:mugiro,项目名称:elm-python,代码行数:26,代码来源:test_tree.py
示例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
开发者ID:Leguark,项目名称:pynoddy,代码行数:33,代码来源:sampling.py
示例13: __enter__
def __enter__(self):
try:
import numpy
except ImportError:
return None
self.errstate = numpy.geterr()
numpy.seterr(invalid="ignore")
return numpy
开发者ID:histogrammar,项目名称:histogrammar-python,代码行数:8,代码来源:testnumpy.py
示例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
开发者ID:ankostis,项目名称:pandas,代码行数:8,代码来源:test_util.py
示例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)
开发者ID:jjmantilla,项目名称:FilesM,代码行数:8,代码来源:Segmentation.py
示例16: 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.
tm.assert_equal(np.geterr(), expected)
开发者ID:parthea,项目名称:pandas,代码行数:8,代码来源:test_util.py
示例17: summarize
def summarize(self, interval, bins=None, method='summarize',
function='mean'):
# We may be dividing by zero in some cases, which raises a warning in
# NumPy based on the IEEE 754 standard (see
# http://docs.scipy.org/doc/numpy/reference/generated/
# numpy.seterr.html)
#
# That's OK -- we're expecting that to happen sometimes. So temporarily
# disable this error reporting for the duration of this method.
orig = np.geterr()['invalid']
np.seterr(invalid='ignore')
if (bins is None) or (method == 'get_as_array'):
bw = BigWigFile(open(self.fn))
s = bw.get_as_array(
interval.chrom,
interval.start,
interval.stop,)
if s is None:
s = np.zeros((interval.stop - interval.start,))
else:
s[np.isnan(s)] = 0
elif method == 'ucsc_summarize':
if function in ['mean', 'min', 'max', 'std', 'coverage']:
return self.ucsc_summarize(interval, bins, function=function)
else:
raise ValueError('function "%s" not supported by UCSC\'s'
'bigWigSummary')
else:
bw = BigWigFile(open(self.fn))
s = bw.summarize(
interval.chrom,
interval.start,
interval.stop, bins)
if s is None:
s = np.zeros((bins,))
else:
if function == 'sum':
s = s.sum_data
if function == 'mean':
s = s.sum_data / s.valid_count
s[np.isnan(s)] = 0
if function == 'min':
s = s.min_val
s[np.isinf(s)] = 0
if function == 'max':
s = s.max_val
s[np.isinf(s)] = 0
if function == 'std':
s = (s.sum_squares / s.valid_count)
s[np.isnan(s)] = 0
# Reset NumPy error reporting
np.seterr(divide=orig)
return s
开发者ID:bakerwm,项目名称:metaseq,代码行数:58,代码来源:filetype_adapters.py
示例18: _prepare_amr_slice
def _prepare_amr_slice(self, selection):
""" return list of patches that contain selection """
# FIXME: it's not good to reach in to src_field[0]'s private methods
# like this, but it's also not good to implement these things twice
# print("??", len(self.patches))
if len(self.patches) == 0:
raise ValueError("AMR field must contain patches to be slicable")
selection, _ = self.patches[0]._prepare_slice(selection)
extent = self.patches[0]._src_crds.get_slice_extent(selection)
inds = []
maybe = [] # these are patches that look like they contain selection
# but might not due to finite precision errors when
# calculating xh
for i, fld in enumerate(self.patches):
# - if xl - atol > the extent of the slice in any direction, then
# there's no overlap
# - if xh <= the lower corner of the slice in any direction, then
# there's no overlap
# the atol and equals are done to match cases where extent overlaps
# the lower corner, but not the upper corner
# logic goes this way cause extent has NaNs in
# dimensions that aren't specified in selection... super-kludge
# also, temporarily disable warnings on NaNs in numpy
invalid_err_level = np.geterr()['invalid']
np.seterr(invalid='ignore')
atol = 100 * np.finfo(fld.crds.xl_nc.dtype).eps
if (not np.any(np.logical_or(fld.crds.xl_nc - atol > extent[1],
fld.crds.xh_nc <= extent[0]))):
if np.any(np.isclose(fld.crds.xh_nc, extent[0], atol=atol)):
maybe.append(i)
else:
inds.append(i)
np.seterr(invalid=invalid_err_level)
# if we found some maybes, but no real hits, then use the maybes
if maybe and not inds:
inds = maybe
if len(inds) == 0:
viscid.logger.error("selection {0} not in any patch @ time {1}"
"".format(selection, self.patches[0].time))
if self.skeleton:
s = (" skeleton: xl= {0} xh = {1}"
"".format(self.skeleton.global_xl,
self.skeleton.global_xh))
viscid.logger.error(s)
inds = None
flds = None
elif len(inds) == 1:
inds = inds[0]
flds = self.patches[inds]
else:
flds = [self.patches[i] for i in inds]
return flds, inds
开发者ID:jobejen,项目名称:Viscid,代码行数:57,代码来源:amr_field.py
示例19: check_typecast
def check_typecast(self, val, dtype):
operators = [operator.add, operator.sub, operator.mul, operator.div]
for op in operators:
err = numpy.geterr()
numpy.seterr(divide='ignore', invalid='ignore')
a = op(val, (testing.shaped_arange((5,), numpy, dtype) - 2))
numpy.seterr(**err)
b = op(val, (testing.shaped_arange((5,), cupy, dtype) - 2))
self.assertEqual(a.dtype, b.dtype)
开发者ID:assyu1103,项目名称:chainer,代码行数:9,代码来源:test_ndarray_elementwise_op.py
示例20: setUp
def setUp(self):
# directory where the test files are located
self.path = PATH
self.path_images = os.path.join(PATH, os.pardir, "images")
# some pre-computed ppsd used for plotting tests:
# (ppsd._psd_periods was downcast to np.float16 to save space)
self.example_ppsd_npz = os.path.join(PATH, "ppsd_kw1_ehz.npz")
# ignore some "RuntimeWarning: underflow encountered in multiply"
self.nperr = np.geterr()
np.seterr(all='ignore')
开发者ID:petrrr,项目名称:obspy,代码行数:10,代码来源:test_spectral_estimation.py
注:本文中的numpy.geterr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论