def test_complex128_pass(self):
nulp = 5
x = np.linspace(-20, 20, 50, dtype=np.float64)
x = 10**x
x = np.r_[-x, x]
xi = x + x*1j
eps = np.finfo(x.dtype).eps
y = x + x*eps*nulp/2.
assert_array_almost_equal_nulp(xi, x + y*1j, nulp)
assert_array_almost_equal_nulp(xi, y + x*1j, nulp)
# The test condition needs to be at least a factor of sqrt(2) smaller
# because the real and imaginary parts both change
y = x + x*eps*nulp/4.
assert_array_almost_equal_nulp(xi, y + y*1j, nulp)
epsneg = np.finfo(x.dtype).epsneg
y = x - x*epsneg*nulp/2.
assert_array_almost_equal_nulp(xi, x + y*1j, nulp)
assert_array_almost_equal_nulp(xi, y + x*1j, nulp)
y = x - x*epsneg*nulp/4.
assert_array_almost_equal_nulp(xi, y + y*1j, nulp)
python类finfo()的实例源码
def assert_rel_equal(a1, a2, decimals, err_msg='', verbose=True):
# We have nan checks in here because occasionally we have fields that get
# weighted without non-zero weights. I'm looking at you, particle fields!
if isinstance(a1, np.ndarray):
assert(a1.size == a2.size)
# Mask out NaNs
assert((np.isnan(a1) == np.isnan(a2)).all())
a1[np.isnan(a1)] = 1.0
a2[np.isnan(a2)] = 1.0
# Mask out 0
ind1 = np.array(np.abs(a1) < np.finfo(a1.dtype).eps)
ind2 = np.array(np.abs(a2) < np.finfo(a2.dtype).eps)
assert((ind1 == ind2).all())
a1[ind1] = 1.0
a2[ind2] = 1.0
elif np.any(np.isnan(a1)) and np.any(np.isnan(a2)):
return True
if not isinstance(a1, np.ndarray) and a1 == a2 == 0.0:
# NANS!
a1 = a2 = 1.0
return assert_almost_equal(np.array(a1)/np.array(a2), 1.0, decimals, err_msg=err_msg,
verbose=verbose)
def _initialize_projected_units(self, fields, chunk):
for field in self.data_source._determine_fields(fields):
finfo = self.ds._get_field_info(*field)
if finfo.units is None:
# First time calling a units="auto" field, infer units and cache
# for future field accesses.
finfo.units = str(chunk[field].units)
field_unit = Unit(finfo.units, registry=self.ds.unit_registry)
if self.method == "mip" or self._sum_only:
path_length_unit = Unit(registry=self.ds.unit_registry)
else:
ax_name = self.ds.coordinates.axis_name[self.axis]
path_element_name = ("index", "path_element_%s" % (ax_name))
path_length_unit = self.ds.field_info[path_element_name].units
path_length_unit = Unit(path_length_unit,
registry=self.ds.unit_registry)
# Only convert to appropriate unit system for path
# elements that aren't angles
if not path_length_unit.is_dimensionless:
path_length_unit = path_length_unit.get_base_equivalent(
unit_system=self.ds.unit_system)
if self.weight_field is None:
self._projected_units[field] = field_unit*path_length_unit
else:
self._projected_units[field] = field_unit
def _split_fields(self, fields_to_get):
fill, gen = self.index._split_fields(fields_to_get)
particles = []
alias = {}
for field in gen:
finfo = self.ds._get_field_info(*field)
if finfo._function.__name__ == "_TranslationFunc":
alias[field] = finfo
continue
try:
finfo.check_available(self)
except NeedsOriginalGrid:
fill.append(field)
for field in fill:
finfo = self.ds._get_field_info(*field)
if finfo.particle_type:
particles.append(field)
gen = [f for f in gen if f not in fill and f not in alias]
fill = [f for f in fill if f not in particles]
return fill, gen, particles, alias
def __init__(self, samples, increment):
"""Class constructor.
Args:
samples: Number of samples in the axis.
increment: Increment between samples.
"""
self.samples = int(samples)
self.increment = increment
self.snap_radius = np.finfo(float).eps * 10
def invcheck(x):
eps2 = 2 * np.finfo(np.float).eps
if(x > eps2):
x = 1 / x
else:
x = 0
warnings.warn(
"Ill-conditioning encountered, result accuracy may be poor")
return(x)
def EStep(self):
P = np.zeros((self.M, self.N))
for i in range(0, self.M):
diff = self.X - np.tile(self.TY[i, :], (self.N, 1))
diff = np.multiply(diff, diff)
P[i, :] = P[i, :] + np.sum(diff, axis=1)
c = (2 * np.pi * self.sigma2) ** (self.D / 2)
c = c * self.w / (1 - self.w)
c = c * self.M / self.N
P = np.exp(-P / (2 * self.sigma2))
den = np.sum(P, axis=0)
den = np.tile(den, (self.M, 1))
den[den==0] = np.finfo(float).eps
self.P = np.divide(P, den)
self.Pt1 = np.sum(self.P, axis=0)
self.P1 = np.sum(self.P, axis=1)
self.Np = np.sum(self.P1)
def eStep(self):
P = np.zeros((self.M, self.N))
for i in range(0, self.M):
diff = self.X - np.tile(self.TY[i, :], (self.N, 1))
diff = np.multiply(diff, diff)
P[i, :] = P[i, :] + np.sum(diff, axis=1)
c = (2 * np.pi * self.sigma2) ** (self.D / 2)
c = c * self.w / (1 - self.w)
c = c * self.M / self.N
P = np.exp(-P / (2 * self.sigma2))
den = np.sum(P, axis=0)
den = np.tile(den, (self.M, 1))
den[den==0] = np.finfo(float).eps
self.P = np.divide(P, den)
self.Pt1 = np.sum(self.P, axis=0)
self.P1 = np.sum(self.P, axis=1)
self.Np = np.sum(self.P1)
def null(self):
return self.length() <= 10 * np.finfo(np.float32).eps
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return (2. * intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2*np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2*np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2 * np.finfo('float').eps)
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * (intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + 2*np.finfo('float').eps)
def dice_core(y, y_pred):
y_core = np.zeros(y.shape)
y_core[np.where( (y==1) | (y==3) | (y==4) )[0]] = 1
y_pred_core = np.zeros(y_pred.shape)
y_pred_core[np.where( (y_pred==1) | (y_pred==3) | (y_pred==4) )[0] ] = 1
return (2. * np.sum(y_pred_core*y_core) + np.finfo(float).eps) / (np.sum(y_core) + np.sum(y_pred_core)+ np.finfo(float).eps)
def dice_enhance(y,y_pred):
y_enhance = np.zeros(y.shape)
y_enhance[np.where(y == 4)[0]] = 1
y_pred_enhance = np.zeros(y_pred.shape)
y_pred_enhance[np.where( y_pred == 4)[0]] = 1
return (2. * np.sum(y_pred_enhance * y_enhance) + np.finfo(float).eps ) / (np.sum(y_enhance) + np.sum(y_pred_enhance) + np.finfo(float).eps)
def split_train_val(self, subject_list):
L = len(subject_list)
np.random.seed(42)
np.random.shuffle(subject_list)
L_train = int(np.round(self.train_size * L))
L_val = int(np.round((1 - self.train_size) * L - np.finfo(float).eps))
if L_val == 0:
return subject_list, subject_list
else:
return subject_list[:L_train], subject_list[L_train:L_train + L_val]
def dice(im1, im2):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return (2. * intersection.sum() + np.finfo('float').eps) / (im1.sum() + im2.sum() + np.finfo('float').eps)
def __condjumpprobability(self, expstate, observation):
# Note that scipy.stats.norm.pdf takes the standard deviation (rather
# than variance) as one of its arguments
if self.__params.jumpintensity < np.finfo(float).eps:
return np.zeros(np.shape(expstate))
if self.__oneminusjumpintensity < np.finfo(float).eps:
return np.ones(np.shape(expstate))
numerator = scipy.stats.norm.pdf(observation, 0., np.sqrt(expstate + self.__jumpvar)) * self.__params.jumpintensity
denominator = numerator + scipy.stats.norm.pdf(observation, 0., np.sqrt(expstate)) * self.__oneminusjumpintensity
return numerator / denominator
def add_mip_starts(mip, indices, pool, max_mip_starts=float('inf'), mip_start_effort_level=4):
"""
Parameters
----------
mip - RiskSLIM surrogate MIP
indices - indices of RiskSLIM surrogate MIP
pool - solution pool
max_mip_starts - max number of mip starts to add (optional; default is add all)
mip_start_effort_level - effort that CPLEX will spend trying to fix (optional; default is 4)
Returns
-------
"""
try:
obj_cutoff = mip.parameters.mip.tolerances.uppercutoff.get()
except:
obj_cutoff = np.inf
n_added = 0
for k in range(0, len(pool)):
if n_added < max_mip_starts:
if pool.objvals[0] <= (obj_cutoff + np.finfo('float').eps):
mip_start_name = "mip_start_" + str(n_added)
mip_start_obj, _ = convert_to_risk_slim_cplex_solution(rho=pool.solutions[k, ], indices = indices, objval=pool.objvals[k])
mip.MIP_starts.add(mip_start_obj, mip_start_effort_level, mip_start_name)
n_added += 1
else:
break
return mip
# Data-Related Computation