本文整理汇总了Python中numpy.isposinf函数的典型用法代码示例。如果您正苦于以下问题:Python isposinf函数的具体用法?Python isposinf怎么用?Python isposinf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isposinf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: assert_almost_equal_inf
def assert_almost_equal_inf(x, y, decimal=6, msg=None):
x = np.atleast_1d(x)
y = np.atleast_1d(y)
assert_equal(np.isposinf(x), np.isposinf(y))
assert_equal(np.isneginf(x), np.isneginf(y))
assert_equal(np.isnan(x), np.isnan(y))
assert_almost_equal(x[np.isfinite(x)], y[np.isfinite(y)])
示例2: test_init_owa_inf
def test_init_owa_inf(self):
r"""Test of initialization and __init__ -- OWA.
Method: An affordance to allow you to set OWA = +Infinity from a JSON
specs-file is offered by OpticalSystem: if OWA is supplied as 0, it is
set to +Infinity. We instantiate OpticalSystem objects and verify that
this is done.
"""
for specs in [specs_default, specs_simple, specs_multi]:
# the input dict is modified in-place -- so copy it
our_specs = deepcopy(specs)
our_specs['OWA'] = 0
for syst in our_specs['starlightSuppressionSystems']:
syst['OWA'] = 0
optsys = self.fixture(**deepcopy(our_specs))
self.assertTrue(np.isposinf(optsys.OWA.value))
for syst in optsys.starlightSuppressionSystems:
self.assertTrue(np.isposinf(syst['OWA'].value))
# repeat, but allow the special value to propagate up
for specs in [specs_default, specs_simple, specs_multi]:
# the input dict is modified in-place -- so copy it
our_specs = deepcopy(specs)
for syst in our_specs['starlightSuppressionSystems']:
syst['OWA'] = 0
optsys = self.fixture(**deepcopy(our_specs))
self.assertTrue(np.isposinf(optsys.OWA.value))
示例3: non_matches
def non_matches(arr, val):
'''
Given a ndarray and an arbitrary
value, including np.nan, np.inf, etc.,
return an ndarray that contains
only elements that are *not* equal
to val.
:param arr: n-dimensional numpy array
:type arr: numpy.ndarray
:param val: value, including special values numpy.nan, numpy.inf, numpy.neginf, etc.
:type val: ANY.
'''
# Special value?
if np.isfinite(val):
# No, just normal value:
return arr[arr != val]
# Is special value, such as numpy.nan.
# Create ndarray with True/False entries
# that reflect which entries are not equal
# to val:
elif np.isnan(val):
cond = np.logical_not(np.isnan(arr))
elif np.isinf(val):
cond = np.logical_not(np.isinf(arr))
elif np.isneginf(val):
cond = np.logical_not(np.isneginf(arr))
elif np.isposinf(val):
cond = np.logical_not(np.isposinf(arr))
# Use the True/False ndarray as a mask
# over arr:
return arr[cond]
示例4: __add__
def __add__(self, other):
assert isinstance(other, ShapeFunction), "Can only add other shape function"
assert self.name == other.name, "Cannot add shapes of different features"
new_splits = self.splits.copy()
new_vals = self.values.copy()
for split, val in zip(other.splits, other.values):
idx = np.searchsorted(new_splits, split, side='right')
new_val = val
if split in new_splits:
idx_2 = np.argwhere(new_splits == split)
new_vals[idx_2] = new_vals[idx_2] + new_val
elif idx == len(new_splits) and (~np.isposinf(split)):
new_splits = np.append(new_splits, split)
new_vals = np.append(new_vals, new_val)
elif np.isposinf(split):
new_vals[-1] = new_vals[-1] + new_val
else:
new_splits = np.insert(new_splits, idx, split)
new_vals = np.insert(new_vals, idx, new_val)
return ShapeFunction(new_splits, new_vals, self.name)
示例5: imagesDiffer
def imagesDiffer(imageArr1, imageArr2, skipMaskArr=None, rtol=1.0e-05, atol=1e-08):
"""Compare the pixels of two image arrays; return True if close, False otherwise
Inputs:
- image1: first image to compare
- image2: second image to compare
- skipMaskArr: pixels to ignore; nonzero values are skipped
- rtol: relative tolerance (see below)
- atol: absolute tolerance (see below)
rtol and atol are positive, typically very small numbers.
The relative difference (rtol * abs(b)) and the absolute difference "atol" are added together
to compare against the absolute difference between "a" and "b".
Return a string describing the error if the images differ significantly, an empty string otherwise
"""
retStrs = []
if skipMaskArr != None:
maskedArr1 = numpy.ma.array(imageArr1, copy=False, mask = skipMaskArr)
maskedArr2 = numpy.ma.array(imageArr2, copy=False, mask = skipMaskArr)
filledArr1 = maskedArr1.filled(0.0)
filledArr2 = maskedArr2.filled(0.0)
else:
filledArr1 = imageArr1
filledArr2 = imageArr2
nan1 = numpy.isnan(filledArr1)
nan2 = numpy.isnan(filledArr2)
if numpy.any(nan1 != nan2):
retStrs.append("NaNs differ")
posinf1 = numpy.isposinf(filledArr1)
posinf2 = numpy.isposinf(filledArr2)
if numpy.any(posinf1 != posinf2):
retStrs.append("+infs differ")
neginf1 = numpy.isneginf(filledArr1)
neginf2 = numpy.isneginf(filledArr2)
if numpy.any(neginf1 != neginf2):
retStrs.append("-infs differ")
# compare values that should be comparable (are neither infinite, nan nor masked)
valSkipMaskArr = nan1 | nan2 | posinf1 | posinf2 | neginf1 | neginf2
if skipMaskArr != None:
valSkipMaskArr |= skipMaskArr
valMaskedArr1 = numpy.ma.array(imageArr1, copy=False, mask = valSkipMaskArr)
valMaskedArr2 = numpy.ma.array(imageArr2, copy=False, mask = valSkipMaskArr)
valFilledArr1 = valMaskedArr1.filled(0.0)
valFilledArr2 = valMaskedArr2.filled(0.0)
if not numpy.allclose(valFilledArr1, valFilledArr2, rtol=rtol, atol=atol):
errArr = numpy.abs(valFilledArr1 - valFilledArr2)
maxErr = errArr.max()
maxPosInd = numpy.where(errArr==maxErr)
maxPosTuple = (maxPosInd[1][0], maxPosInd[0][0])
errStr = "maxDiff=%s at position %s; value=%s vs. %s" % \
(maxErr, maxPosTuple, valFilledArr1[maxPosInd][0], valFilledArr2[maxPosInd][0])
retStrs.insert(0, errStr)
return "; ".join(retStrs)
示例6: _generate_colorbar_ticks_label
def _generate_colorbar_ticks_label(
data_transform=False, colorbarlabel=None, trans_base_list=None, forcelabel=None, plotlev=None, plotlab=None
):
"""
Return (colorbar_ticks,colorbar_labels)
"""
# data_transform==True and levels!=None
if data_transform == True:
if colorbarlabel != None:
colorbarlabel = pb.iteflat(colorbarlabel)
transformed_colorbarlabel_ticks, x, y, trans_base_list = mathex.plot_array_transg(
colorbarlabel, trans_base_list, copy=True
)
# Note if/else blocks are organized in 1st tire by check if the two
# ends are -inf/inf and 2nd tire by check if colorbarlabel is None
if np.isneginf(plotlab[0]) and np.isposinf(plotlab[-1]):
if colorbarlabel != None:
ftuple = (transformed_colorbarlabel_ticks, colorbarlabel)
else:
ftuple = (plotlev, plotlab[1:-1])
elif np.isneginf(plotlab[0]) or np.isposinf(plotlab[-1]):
raise ValueError("It's strange to set only side as infitive")
else:
if colorbarlabel != None:
ftuple = (transformed_colorbarlabel_ticks, colorbarlabel)
else:
ftuple = (plotlev, plotlab)
# data_transform==False
else:
if np.isneginf(plotlab[0]) and np.isposinf(plotlab[-1]):
# if colorbarlabel is forced, then ticks and ticklabels will be forced.
if colorbarlabel != None:
ftuple = (colorbarlabel, colorbarlabel)
# This by default will be done, it's maintained here only for clarity.
else:
ftuple = (plotlab[1:-1], plotlab[1:-1])
elif np.isneginf(plotlab[0]) or np.isposinf(plotlab[-1]):
raise ValueError("It's strange to set only side as infitive")
else:
if colorbarlabel != None:
ftuple = (colorbarlabel, colorbarlabel)
else:
ftuple = (plotlab, plotlab)
ftuple = list(ftuple)
if forcelabel != None:
if len(forcelabel) != len(ftuple[1]):
raise ValueError(
"""the length of the forcelabel and the
length of labeled ticks is not equal!"""
)
else:
ftuple[1] = forcelabel
return ftuple
示例7: _transform_data
def _transform_data(pdata, levels, data_transform):
"""
Return [pdata,plotlev,plotlab,extend,trans_base_list];
if data_transform == False, trans_base_list = None.
Notes:
------
pdata: data used for contourf plotting.
plotlev: the levels used in contourf plotting.
extend: the value for parameter extand in contourf.
trans_base_list: cf. mathex.plot_array_transg
"""
if levels == None:
ftuple = (pdata, None, None, "neither")
if data_transform == True:
raise Warning("Strange levels is None but data_transform is True")
else:
if data_transform == True:
# make the data transform before plotting.
pdata_trans, plotlev, plotlab, trans_base_list = mathex.plot_array_transg(pdata, levels, copy=True)
if np.isneginf(plotlab[0]) and np.isposinf(plotlab[-1]):
ftuple = (pdata_trans, plotlev[1:-1], plotlab, "both")
elif np.isneginf(plotlab[0]) or np.isposinf(plotlab[-1]):
raise ValueError(
"""only one extreme set as infinitive, please
set both as infinitive if arrow colorbar is wanted."""
)
else:
ftuple = (pdata_trans, plotlev, plotlab, "neither")
# data_transform==False
else:
plotlev = pb.iteflat(levels)
plotlab = pb.iteflat(levels)
if np.isneginf(plotlab[0]) and np.isposinf(plotlab[-1]):
# here the levels would be like [np.NINF,1,2,3,np.PINF]
# in following contourf, all values <1 and all values>3 will be
# automatically plotted in the color of two arrows.
# easy to see in this example:
# a=np.tile(np.arange(10),10).reshape(10,10);
# fig,ax=g.Create_1Axes();
# cs=ax.contourf(a,levels=np.arange(2,7),extend='both');
# plt.colorbar(cs)
ftuple = (pdata, plotlev[1:-1], plotlab, "both")
elif np.isneginf(plotlab[0]) or np.isposinf(plotlab[-1]):
raise ValueError(
"""only one extreme set as infinitive, please
set both as infinitive if arrow colorbar is wanted."""
)
else:
ftuple = (pdata, plotlev, plotlab, "neither")
datalist = list(ftuple)
if data_transform == True:
datalist.append(trans_base_list)
else:
datalist.append(None)
return datalist
示例8: _diagnose
def _diagnose(self):
# Update log.
self.logger.debug("diagnose: data: shape: " + str(self.data.shape))
self.logger.debug("diagnose: data: dtype: " + str(self.data.dtype))
self.logger.debug("diagnose: data: size: %.2fMB", self.data.nbytes * 9.53674e-7)
self.logger.debug("diagnose: data: nans: " + str(np.sum(np.isnan(self.data))))
self.logger.debug("diagnose: data: -inf: " + str(np.sum(np.isneginf(self.data))))
self.logger.debug("diagnose: data: +inf: " + str(np.sum(np.isposinf(self.data))))
self.logger.debug("diagnose: data: positives: " + str(np.sum(self.data > 0)))
self.logger.debug("diagnose: data: negatives: " + str(np.sum(self.data < 0)))
self.logger.debug("diagnose: data: mean: " + str(np.mean(self.data)))
self.logger.debug("diagnose: data: min: " + str(np.min(self.data)))
self.logger.debug("diagnose: data: max: " + str(np.max(self.data)))
self.logger.debug("diagnose: data_white: shape: " + str(self.data_white.shape))
self.logger.debug("diagnose: data_white: dtype: " + str(self.data_white.dtype))
self.logger.debug("diagnose: data_white: size: %.2fMB", self.data_white.nbytes * 9.53674e-7)
self.logger.debug("diagnose: data_white: nans: " + str(np.sum(np.isnan(self.data_white))))
self.logger.debug("diagnose: data_white: -inf: " + str(np.sum(np.isneginf(self.data_white))))
self.logger.debug("diagnose: data_white: +inf: " + str(np.sum(np.isposinf(self.data_white))))
self.logger.debug("diagnose: data_white: positives: " + str(np.sum(self.data_white > 0)))
self.logger.debug("diagnose: data_white: negatives: " + str(np.sum(self.data_white < 0)))
self.logger.debug("diagnose: data_white: mean: " + str(np.mean(self.data_white)))
self.logger.debug("diagnose: data_white: min: " + str(np.min(self.data_white)))
self.logger.debug("diagnose: data_white: max: " + str(np.max(self.data_white)))
self.logger.debug("diagnose: data_dark: shape: " + str(self.data_dark.shape))
self.logger.debug("diagnose: data_dark: dtype: " + str(self.data_dark.dtype))
self.logger.debug("diagnose: data_dark: size: %.2fMB", self.data_dark.nbytes * 9.53674e-7)
self.logger.debug("diagnose: data_dark: nans: " + str(np.sum(np.isnan(self.data_dark))))
self.logger.debug("diagnose: data_dark: -inf: " + str(np.sum(np.isneginf(self.data_dark))))
self.logger.debug("diagnose: data_dark: +inf: " + str(np.sum(np.isposinf(self.data_dark))))
self.logger.debug("diagnose: data_dark: positives: " + str(np.sum(self.data_dark > 0)))
self.logger.debug("diagnose: data_dark: negatives: " + str(np.sum(self.data_dark < 0)))
self.logger.debug("diagnose: data_dark: mean: " + str(np.mean(self.data_dark)))
self.logger.debug("diagnose: data_dark: min: " + str(np.min(self.data_dark)))
self.logger.debug("diagnose: data_dark: max: " + str(np.max(self.data_dark)))
self.logger.debug("diagnose: theta: shape: " + str(self.theta.shape))
self.logger.debug("diagnose: theta: dtype: " + str(self.theta.dtype))
self.logger.debug("diagnose: theta: size: %.2fMB", self.theta.nbytes * 9.53674e-7)
self.logger.debug("diagnose: theta: nans: " + str(np.sum(np.isnan(self.theta))))
self.logger.debug("diagnose: theta: -inf: " + str(np.sum(np.isneginf(self.theta))))
self.logger.debug("diagnose: theta: +inf: " + str(np.sum(np.isposinf(self.theta))))
self.logger.debug("diagnose: theta: positives: " + str(np.sum(self.theta > 0)))
self.logger.debug("diagnose: theta: negatives: " + str(np.sum(self.theta < 0)))
self.logger.debug("diagnose: theta: mean: " + str(np.mean(self.theta)))
self.logger.debug("diagnose: theta: min: " + str(np.min(self.theta)))
self.logger.debug("diagnose: theta: max: " + str(np.max(self.theta)))
self.logger.info("diagnose [ok]")
示例9: test_neginf
def test_neginf(self):
arr =np.empty(100)
arr[:] = -np.inf
for np_func, acml_func in self.vector_funcs:
np_out = np_func(arr)
acml_out = acml_func(arr)
equal_nan = np.isnan(np_out) == np.isnan(acml_out)
equal_posinf = np.isposinf(np_out) == np.isposinf(acml_out)
equal_neginf = np.isneginf(np_out) == np.isneginf(acml_out)
self.assertTrue( np.alltrue(equal_nan), msg="NaN-test failed for %s" % acml_func)
self.assertTrue( np.alltrue(equal_posinf), msg="posinf-test failed for %s" % acml_func)
self.assertTrue( np.alltrue(equal_neginf), msg="neginf-test failed for %s" % acml_func)
示例10: set_logp_to_neg_inf
def set_logp_to_neg_inf(X, logp, bounds):
"""Set `logp` to negative infinity when `X` is outside the allowed bounds.
# Arguments
X: tensorflow.Tensor
The variable to apply the bounds to
logp: tensorflow.Tensor
The log probability corrosponding to `X`
bounds: list of `Region` objects
The regions corrosponding to allowed regions of `X`
# Returns
logp: tensorflow.Tensor
The newly bounded log probability
"""
conditions = []
for l, u in bounds:
lower_is_neg_inf = not isinstance(l, tf.Tensor) and np.isneginf(l)
upper_is_pos_inf = not isinstance(u, tf.Tensor) and np.isposinf(u)
if not lower_is_neg_inf and upper_is_pos_inf:
conditions.append(tf.greater(X, l))
elif lower_is_neg_inf and not upper_is_pos_inf:
conditions.append(tf.less(X, u))
elif not (lower_is_neg_inf or upper_is_pos_inf):
conditions.append(tf.logical_and(tf.greater(X, l), tf.less(X, u)))
if len(conditions) > 0:
is_inside_bounds = conditions[0]
for condition in conditions[1:]:
is_inside_bounds = tf.logical_or(is_inside_bounds, condition)
logp = tf.select(is_inside_bounds, logp, tf.fill(tf.shape(X), config.dtype(-np.inf)))
return logp
示例11: traverse_data
def traverse_data(obj, is_numpy=is_numpy, use_numpy=True):
""" Recursively traverse an object until a flat list is found.
If NumPy is available, the flat list is converted to a numpy array
and passed to transform_array() to handle ``nan``, ``inf``, and
``-inf``.
Otherwise, iterate through all items, converting non-JSON items
Args:
obj (list) : a list of values or lists
is_numpy (bool, optional): Whether NumPy is availanble
(default: True if NumPy is importable)
use_numpy (bool, optional) toggle NumPy as a dependency for testing
This argument is only useful for testing (default: True)
"""
is_numpy = is_numpy and use_numpy
if is_numpy and all(isinstance(el, np.ndarray) for el in obj):
return [transform_array(el) for el in obj]
obj_copy = []
for item in obj:
if isinstance(item, (list, tuple)):
obj_copy.append(traverse_data(item))
elif isinstance(item, float):
if np.isnan(item):
item = 'NaN'
elif np.isposinf(item):
item = 'Infinity'
elif np.isneginf(item):
item = '-Infinity'
obj_copy.append(item)
else:
obj_copy.append(item)
return obj_copy
示例12: check_kurt_expect
def check_kurt_expect(distfn, arg, m, v, k, msg):
if np.isfinite(k):
m4e = distfn.expect(lambda x: np.power(x-m, 4), arg)
npt.assert_allclose(m4e, (k + 3.) * np.power(v, 2), atol=1e-5, rtol=1e-5,
err_msg=msg + ' - kurtosis')
elif not np.isposinf(k):
npt.assert_(np.isnan(k))
示例13: merciless_print
def merciless_print(i, node, fn):
"""Debugging theano. Prints inputs and outputs at every point.
In case NaN, Inf or -Inf is detected, fires up the pdb debugger."""
print ''
print '-------------------------------------------------------'
print 'Node %s' % str(i)
theano.printing.debugprint(node)
print 'Inputs : %s' % [input for input in fn.inputs]
print 'Outputs: %s' % [output for output in fn.outputs]
print 'Node:'
for output in fn.outputs:
try:
if numpy.isnan(output[0]).any():
print '*** NaN detected ***'
theano.printing.debugprint(node)
print 'Inputs : %s' % [input[0] for input in fn.inputs]
print 'Outputs: %s' % [output[0] for output in fn.outputs]
pdb.set_trace()
raise ValueError('Found NaN in computation!')
if numpy.isposinf(output[0]).any() or numpy.isneginf(output[0]).any():
print '*** Inf detected ***'
theano.printing.debugprint(node)
print 'Inputs : %s' % [input[0] for input in fn.inputs]
print 'Outputs: %s' % [output[0] for output in fn.outputs]
pdb.set_trace()
raise ValueError('Found Inf in computation!')
except TypeError:
logging.debug('Couldn\'t check node for NaN/Inf: {0}'.format(node))
示例14: encode_fill_value
def encode_fill_value(v, dtype):
# early out
if v is None:
return v
if dtype.kind == 'f':
if np.isnan(v):
return 'NaN'
elif np.isposinf(v):
return 'Infinity'
elif np.isneginf(v):
return '-Infinity'
else:
return float(v)
elif dtype.kind in 'ui':
return int(v)
elif dtype.kind == 'b':
return bool(v)
elif dtype.kind in 'SV':
v = base64.standard_b64encode(v)
if not PY2: # pragma: py2 no cover
v = str(v, 'ascii')
return v
elif dtype.kind == 'U':
return v
elif dtype.kind in 'mM':
return int(v.view('u8'))
else:
return v
示例15: _update_parameters
def _update_parameters(self):
"""
Update parameters of the acquisition required to evaluate the function. In particular:
* Sample representer points repr_points
* Compute their log values repr_points_log
* Compute belief locations logP
"""
self.repr_points, self.repr_points_log = self.sampler.get_samples(self.num_repr_points, self.proposal_function, self.burn_in_steps)
if np.any(np.isnan(self.repr_points_log)) or np.any(np.isposinf(self.repr_points_log)):
raise RuntimeError("Sampler generated representer points with invalid log values: {}".format(self.repr_points_log))
# Removing representer points that have 0 probability of being the minimum (corresponding to log probability being minus infinity)
idx_to_remove = np.where(np.isneginf(self.repr_points_log))[0]
if len(idx_to_remove) > 0:
idx = list(set(range(self.num_repr_points)) - set(idx_to_remove))
self.repr_points = self.repr_points[idx, :]
self.repr_points_log = self.repr_points_log[idx]
# We predict with the noise as we need to make sure that var is indeed positive definite.
mu, _ = self.model.predict(self.repr_points)
# we need a vector
mu = np.ndarray.flatten(mu)
var = self.model.predict_covariance(self.repr_points)
self.logP, self.dlogPdMu, self.dlogPdSigma, self.dlogPdMudMu = epmgp.joint_min(mu, var, with_derivatives=True)
# add a second dimension to the array
self.logP = np.reshape(self.logP, (self.logP.shape[0], 1))