本文整理汇总了Python中numpy.isfinite方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.isfinite方法的具体用法?Python numpy.isfinite怎么用?Python numpy.isfinite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.isfinite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_load_variable_mask_and_scale
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def test_load_variable_mask_and_scale(load_variable_data_loader):
def convert_all_to_missing_val(ds, **kwargs):
ds['condensation_rain'] = 0. * ds['condensation_rain'] + 1.0e20
ds['condensation_rain'].attrs['_FillValue'] = 1.0e20
return ds
load_variable_data_loader.preprocess_func = convert_all_to_missing_val
data = load_variable_data_loader.load_variable(
condensation_rain, DatetimeNoLeap(5, 1, 1),
DatetimeNoLeap(5, 12, 31),
intvl_in='monthly')
num_non_missing = np.isfinite(data).sum().item()
expected_num_non_missing = 0
assert num_non_missing == expected_num_non_missing
示例2: _convert_observ
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def _convert_observ(self, observ):
"""Convert the observation to 32 bits.
Args:
observ: Numpy observation.
Raises:
ValueError: Observation contains infinite values.
Returns:
Numpy observation with 32-bit data type.
"""
if not np.isfinite(observ).all():
raise ValueError('Infinite observation encountered.')
if observ.dtype == np.float64:
return observ.astype(np.float32)
if observ.dtype == np.int64:
return observ.astype(np.int32)
return observ
示例3: calc_state
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def calc_state(self):
self.theta, theta_dot = self.j1.current_position()
x, vx = self.slider.current_position()
assert( np.isfinite(x) )
if not np.isfinite(x):
print("x is inf")
x = 0
if not np.isfinite(vx):
print("vx is inf")
vx = 0
if not np.isfinite(self.theta):
print("theta is inf")
self.theta = 0
if not np.isfinite(theta_dot):
print("theta_dot is inf")
theta_dot = 0
return np.array([
x, vx,
np.cos(self.theta), np.sin(self.theta), theta_dot
])
示例4: _initialize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def _initialize(self):
super()._initialize()
# Clip initial guess to bounds (SLSQP may fail with bounds-infeasible initial point)
x = asfarray(self.x0.X.flatten())
xl, xu = self.problem.bounds()
have_bound = np.isfinite(xl)
x[have_bound] = np.clip(x[have_bound], xl[have_bound], np.inf)
have_bound = np.isfinite(xu)
x[have_bound] = np.clip(x[have_bound], -np.inf, xu[have_bound])
self.D["X"] = x
self.pop = Population()
self._eval_obj()
self._eval_grad()
self._update()
self._call()
self.major = True
示例5: _check_rep
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def _check_rep(self):
#name
assert isinstance(self._name, str)
assert len(self._name) >= 1
#bounds
assert np.isfinite(self.ub)
assert np.isfinite(self.lb)
assert self.ub >= self.lb
# value
assert self._vtype in self._VALID_TYPES
assert np.isnan(self.c0) or (self.c0 >= 0.0 and np.isfinite(self.c0))
return True
示例6: _check_maxexp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def _check_maxexp(np_type, maxexp):
""" True if fp type `np_type` seems to have `maxexp` maximum exponent
We're testing "maxexp" as returned by numpy. This value is set to one
greater than the maximum power of 2 that `np_type` can represent.
Assumes base 2 representation. Very crude check
Parameters
----------
np_type : numpy type specifier
Any specifier for a numpy dtype
maxexp : int
Maximum exponent to test against
Returns
-------
tf : bool
True if `maxexp` is the correct maximum exponent, False otherwise.
"""
dt = np.dtype(np_type)
np_type = dt.type
two = np_type(2).reshape((1,)) # to avoid upcasting
return (np.isfinite(two ** (maxexp - 1)) and
not np.isfinite(two ** maxexp))
示例7: beta_divergence
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def beta_divergence(x_indices, x_vals, beta, A, B, C):
"""Computes the total beta-divergence between the current model and
a sparse X
"""
rank = len(x_indices[0])
b_vals = np.zeros(x_vals.shape, dtype=np.float32)
parafac_sparse(x_indices, b_vals, A, B, C)
a, b = x_vals, b_vals
idx = np.isfinite(a)
idx &= np.isfinite(b)
idx &= a > 0
idx &= b > 0
a = a[idx]
b = b[idx]
if beta == 0:
return a / b - np.log(a / b) - 1
if beta == 1:
return a * (np.log(a) - np.log(b)) + b - a
return (1. / beta / (beta - 1.) * (a ** beta + (beta - 1.)
* b ** beta - beta * a * b ** (beta - 1)))
示例8: _sanitize_dists
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def _sanitize_dists(self, dists):
"""Replace invalid distances."""
dists = np.copy(dists)
# Note there is an issue in scipy.optimize.linear_sum_assignment where
# it runs forever if an entire row/column is infinite or nan. We therefore
# make a copy of the distance matrix and compute a safe value that indicates
# 'cannot assign'. Also note + 1 is necessary in below inv-dist computation
# to make invdist bigger than max dist in case max dist is zero.
valid_dists = dists[np.isfinite(dists)]
INVDIST = 2 * valid_dists.max() + 1 if valid_dists.shape[0] > 0 else 1.
dists[~np.isfinite(dists)] = INVDIST
return dists, INVDIST
示例9: _reward
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def _reward(self):
reward = self.reward_strategy.get_reward(current_step=self.current_step,
current_price=self._current_price,
observations=self.observations,
account_history=self.account_history,
net_worths=self.net_worths)
reward = float(reward) if np.isfinite(float(reward)) else 0
self.rewards.append(reward)
if self.stationarize_rewards:
rewards = difference(self.rewards, inplace=False)
else:
rewards = self.rewards
if self.normalize_rewards:
mean_normalize(rewards, inplace=True)
rewards = np.array(rewards).flatten()
return float(rewards[-1])
示例10: test_generic
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [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)
示例11: ts
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def ts(self, data, lon_cyclic=True, lon_str=LON_STR, lat_str=LAT_STR,
land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR):
"""Create yearly time-series of region-averaged data.
Parameters
----------
data : xarray.DataArray
The array to create the regional timeseries of
lon_cyclic : { None, True, False }, optional (default True)
Whether or not the longitudes of ``data`` span the whole globe,
meaning that they should be wrapped around as necessary to cover
the Region's full width.
lat_str, lon_str, land_mask_str, sfc_area_str : str, optional
The name of the latitude, longitude, land mask, and surface area
coordinates, respectively, in ``data``. Defaults are the
corresponding values in ``aospy.internal_names``.
Returns
-------
xarray.DataArray
The timeseries of values averaged within the region and within each
year, one value per year.
"""
data_masked = self.mask_var(data, lon_cyclic=lon_cyclic,
lon_str=lon_str, lat_str=lat_str)
sfc_area = data[sfc_area_str]
sfc_area_masked = self.mask_var(sfc_area, lon_cyclic=lon_cyclic,
lon_str=lon_str, lat_str=lat_str)
land_mask = _get_land_mask(data, self.do_land_mask,
land_mask_str=land_mask_str)
weights = sfc_area_masked * land_mask
# Mask weights where data values are initially invalid in addition
# to applying the region mask.
weights = weights.where(np.isfinite(data))
weights_reg_sum = weights.sum(lon_str).sum(lat_str)
data_reg_sum = (data_masked * sfc_area_masked *
land_mask).sum(lat_str).sum(lon_str)
return data_reg_sum / weights_reg_sum
示例12: yearly_average
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def yearly_average(arr, dt):
"""Average a sub-yearly time-series over each year.
Resulting timeseries comprises one value for each year in which the
original array had valid data. Accounts for (i.e. ignores) masked values
in original data when computing the annual averages.
Parameters
----------
arr : xarray.DataArray
The array to be averaged
dt : xarray.DataArray
Array of the duration of each timestep
Returns
-------
xarray.DataArray
Has the same shape and mask as the original ``arr``, except for the
time dimension, which is truncated to one value for each year that
``arr`` spanned
"""
assert_matching_time_coord(arr, dt)
yr_str = TIME_STR + '.year'
# Retain original data's mask.
dt = dt.where(np.isfinite(arr))
return ((arr*dt).groupby(yr_str, restore_coord_dims=True).sum(TIME_STR) /
dt.groupby(yr_str, restore_coord_dims=True).sum(TIME_STR))
示例13: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def __init__(self, map_fname=None):
"""
Args:
map_fname (Optional[:obj:`str`]): Filename at which the map is stored.
Defaults to ``None``, meaning that the default filename is used.
"""
if map_fname is None:
map_fname = os.path.join(data_dir(), 'marshall', 'marshall.h5')
with h5py.File(map_fname, 'r') as f:
self._l = f['l'][:]
self._b = f['b'][:]
self._A = f['A'][:]
self._sigma_A = f['sigma_A'][:]
self._dist = f['dist'][:]
self._sigma_dist = f['sigma_dist'][:]
# self._l.shape = (self._l.size,)
# self._b.shape = (self._b.size,)
# self._A.shape = (self._A.shape[0], self._A.shape[1]*self._A.shape[2])
# Shape of the (l,b)-grid
self._shape = self._l.shape
# Number of distance bins in each sightline
self._n_dists = np.sum(np.isfinite(self._dist), axis=2)
# idx = ~np.isfinite(self._dist)
# if np.any(idx):
# self._dist[idx] = np.inf
self._l_bounds = (-100., 100.) # min,max Galactic longitude, in deg
self._b_bounds = (-10., 10.) # min,max Galactic latitude, in deg
self._inv_pix_scale = 4. # 1 / (pixel scale, in deg)
示例14: segment_intersection_2D
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def segment_intersection_2D(p12arg, p34arg, atol=1e-8):
'''
segment_intersection((a, b), (c, d)) yields the intersection point between the line segments
that pass from point a to point b and from point c to point d. If there is no intersection
point, then (numpy.nan, numpy.nan) is returned.
'''
(p1,p2) = p12arg
(p3,p4) = p34arg
pi = np.asarray(line_intersection_2D(p12arg, p34arg, atol=atol))
p1 = np.asarray(p1)
p2 = np.asarray(p2)
p3 = np.asarray(p3)
p4 = np.asarray(p4)
u12 = p2 - p1
u34 = p4 - p3
cfn = lambda px,iis: (px if iis is None or len(px.shape) == 1 or px.shape[1] == len(iis) else
px[:,iis])
dfn = lambda a,b: a[0]*b[0] + a[1]*b[1]
sfn = lambda a,b: ((a-b) if len(a.shape) == len(b.shape) else
(np.transpose([a])-b) if len(a.shape) < len(b.shape) else
(a - np.transpose([b])))
fn = lambda px,iis: (1 - ((dfn(cfn(u12,iis), sfn( px, cfn(p1,iis))) > 0) *
(dfn(cfn(u34,iis), sfn( px, cfn(p3,iis))) > 0) *
(dfn(cfn(u12,iis), sfn(cfn(p2,iis), px)) > 0) *
(dfn(cfn(u34,iis), sfn(cfn(p4,iis), px)) > 0)))
if len(pi.shape) == 1:
if not np.isfinite(pi[0]): return (np.nan, np.nan)
bad = fn(pi, None)
return (np.nan, np.nan) if bad else pi
else:
nonpar = np.where(np.isfinite(pi[0]))[0]
bad = fn(cfn(pi, nonpar), nonpar)
(xi,yi) = pi
bad = nonpar[np.where(bad)[0]]
xi[bad] = np.nan
yi[bad] = np.nan
return (xi,yi)
示例15: lines_touch_2D
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfinite [as 别名]
def lines_touch_2D(ab, cd, atol=1e-8):
'''
lines_touch_2D((a,b), (c,d)) is equivalent to lines_colinear((a,b), (c,d)) |
numpy.isfinite(line_intersection_2D((a,b), (c,d))[0])
'''
return (lines_colinear(ab, cd, atol=atol) |
np.isfinite(line_intersection_2D(ab, cd, atol=atol)[0]))