本文整理汇总了Python中numpy.fabs方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.fabs方法的具体用法?Python numpy.fabs怎么用?Python numpy.fabs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.fabs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: absdiff
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def absdiff(self, constant_value, separate_re_im=False):
"""
Returns a ReportableQty that is the (element-wise in the vector case)
difference between `constant_value` and this one given by:
`abs(self - constant_value)`.
"""
if separate_re_im:
re_v = _np.fabs(_np.real(self.value) - _np.real(constant_value))
im_v = _np.fabs(_np.imag(self.value) - _np.imag(constant_value))
if self.has_eb():
return (ReportableQty(re_v, _np.fabs(_np.real(self.errbar)), self.nonMarkovianEBs),
ReportableQty(im_v, _np.fabs(_np.imag(self.errbar)), self.nonMarkovianEBs))
else:
return ReportableQty(re_v), ReportableQty(im_v)
else:
v = _np.absolute(self.value - constant_value)
if self.has_eb():
return ReportableQty(v, _np.absolute(self.errbar), self.nonMarkovianEBs)
else:
return ReportableQty(v)
示例2: test_irreg_hf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def test_irreg_hf(self):
idx = date_range('2012-6-22 21:59:51', freq='S', periods=100)
df = DataFrame(np.random.randn(len(idx), 2), idx)
irreg = df.iloc[[0, 1, 3, 4]]
_, ax = self.plt.subplots()
irreg.plot(ax=ax)
diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
sec = 1. / 24 / 60 / 60
assert (np.fabs(diffs[1:] - [sec, sec * 2, sec]) < 1e-8).all()
_, ax = self.plt.subplots()
df2 = df.copy()
df2.index = df.index.astype(object)
df2.plot(ax=ax)
diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
assert (np.fabs(diffs[1:] - sec) < 1e-8).all()
示例3: rotipp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def rotipp(acceleration_x, time_step_x, acceleration_y, time_step_y, periods,
percentile, damping=0.05, units="cm/s/s", method="Nigam-Jennings"):
"""
Returns the rotationally independent spectrum RotIpp as defined by
Boore (2010)
"""
if np.fabs(time_step_x - time_step_y) > 1E-10:
raise ValueError("Record pair must have the same time-step!")
acceleration_x, acceleration_y = equalise_series(acceleration_x,
acceleration_y)
target, rota, rotv, rotd, angles = rotdpp(acceleration_x, time_step_x,
acceleration_y, time_step_y,
periods, percentile, damping,
units, method)
locn, penalty = _get_gmrotd_penalty(
np.hstack([target["PGA"],target["Pseudo-Acceleration"]]),
rota)
target_theta = np.radians(angles[locn])
arotpp = acceleration_x * np.cos(target_theta) +\
acceleration_y * np.sin(target_theta)
spec = get_response_spectrum(arotpp, time_step_x, periods, damping, units,
method)[0]
spec["GMRot{:2.0f}".format(percentile)] = target
return spec
示例4: nextPos
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def nextPos(self, x, x_b, r1, r2, r3, r4, task):
r"""Move individual to new position in search space.
Args:
x (numpy.ndarray): Individual represented with components.
x_b (nmppy.ndarray): Best individual represented with components.
r1 (float): Number dependent on algorithm iteration/generations.
r2 (float): Random number in range of 0 and 2 * PI.
r3 (float): Random number in range [Rmin, Rmax].
r4 (float): Random number in range [0, 1].
task (Task): Optimization task.
Returns:
numpy.ndarray: New individual that is moved based on individual ``x``.
"""
return task.repair(x + r1 * (sin(r2) if r4 < 0.5 else cos(r2)) * fabs(r3 * x_b - x), self.Rand)
示例5: rho
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def rho(self, z):
r"""
The robust criterion function for Huber's t.
Parameters
----------
z : array-like
1d array
Returns
-------
rho : array
rho(z) = .5*z**2 for \|z\| <= t
rho(z) = \|z\|*t - .5*t**2 for \|z\| > t
"""
z = np.asarray(z)
test = self._subset(z)
return (test * 0.5 * z**2 +
(1 - test) * (np.fabs(z) * self.t - 0.5 * self.t**2))
示例6: weights
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def weights(self, z):
"""
Huber's t weighting function for the IRLS algorithm
The psi function scaled by z
Parameters
----------
z : array-like
1d array
Returns
-------
weights : array
weights(z) = 1 for \|z\| <= t
weights(z) = t/\|z\| for \|z\| > t
"""
z = np.asarray(z)
test = self._subset(z)
absz = np.fabs(z)
absz[test] = 1.0
return test + (1 - test) * self.t / absz
示例7: psi
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def psi(self, z):
"""
The psi function for Ramsay's Ea estimator
The analytic derivative of rho
Parameters
----------
z : array-like
1d array
Returns
-------
psi : array
psi(z) = z*exp(-a*\|z\|)
"""
z = np.asarray(z)
return z * np.exp(-self.a * np.fabs(z))
示例8: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def __call__(self, df_resid, nobs, resid):
h = (df_resid)/nobs*(self.d**2 + (1-self.d**2)*\
Gaussian.cdf(self.d)-.5 - self.d/(np.sqrt(2*np.pi))*\
np.exp(-.5*self.d**2))
s = mad(resid)
subset = lambda x: np.less(np.fabs(resid/x),self.d)
chi = lambda s: subset(s)*(resid/s)**2/2+(1-subset(s))*(self.d**2/2)
scalehist = [np.inf,s]
niter = 1
while (np.abs(scalehist[niter-1] - scalehist[niter])>self.tol \
and niter < self.maxiter):
nscale = np.sqrt(1/(nobs*h)*np.sum(chi(scalehist[-1]))*\
scalehist[-1]**2)
scalehist.append(nscale)
niter += 1
#if niter == self.maxiter:
# raise ValueError("Huber's scale failed to converge")
return scalehist[-1]
示例9: cont
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def cont(self, ML=False, rtol=1.0e-05, params_rtol=1e-5, params_atol=1e-4):
'''convergence check for iterative estimation
'''
self.dev, old = self.deviance(ML=ML), self.dev
#self.history.append(np.hstack((self.dev, self.a)))
self.history['llf'].append(self.dev)
self.history['params'].append(self.a.copy())
self.history['D'].append(self.D.copy())
if np.fabs((self.dev - old) / self.dev) < rtol: #why is there times `*`?
#print np.fabs((self.dev - old)), self.dev, old
self.termination = 'llf'
return False
#break if parameters converged
#TODO: check termination conditions, OR or AND
if np.all(np.abs(self.a - self._a_old) < (params_rtol * self.a + params_atol)):
self.termination = 'params'
return False
self._a_old = self.a.copy()
return True
示例10: _wrap_results
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def _wrap_results(result, dtype):
""" wrap our results if needed """
if is_datetime64_dtype(dtype):
if not isinstance(result, np.ndarray):
result = tslib.Timestamp(result)
else:
result = result.view(dtype)
elif is_timedelta64_dtype(dtype):
if not isinstance(result, np.ndarray):
# raise if we have a timedelta64[ns] which is too large
if np.fabs(result) > _int64_max:
raise ValueError("overflow in timedelta operation")
result = tslib.Timedelta(result, unit='ns')
else:
result = result.astype('i8').view(dtype)
return result
示例11: lidar_to_img
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def lidar_to_img(points, img_size):
# pdb.set_trace()
lidar_data = np.array(points[:, :2])
lidar_data *= 9.9999
lidar_data -= (0.5 * img_size, 0.5 * img_size)
lidar_data = np.fabs(lidar_data)
lidar_data = lidar_data.astype(np.int32)
lidar_data = np.reshape(lidar_data, (-1, 2))
lidar_img = np.zeros((img_size, img_size))
lidar_img[tuple(lidar_data.T)] = 255
return torch.tensor(lidar_img).cuda()
# def lidar_to_img(points, img_size):
# # pdb.set_trace()
# lidar_data = points[:, :2]
# lidar_data *= 9.9999
# lidar_data -= torch.tensor((0.5 * img_size, 0.5 * img_size)).cuda()
# lidar_data = torch.abs(lidar_data)
# lidar_data = torch.floor(lidar_data).long()
# lidar_data = lidar_data.view(-1, 2)
# lidar_img = torch.zeros((img_size, img_size)).cuda()
# lidar_img[lidar_data.permute(1,0)] = 255
# return lidar_img
示例12: lidar_to_heightmap
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def lidar_to_heightmap(points, img_size):
# pdb.set_trace()
lidar_data = np.array(points[:, :2])
height_data = np.array(points[:,2])
height_data *= 255/2
height_data[height_data < 0] = 0
height_data[height_data > 255] = 255
height_data = np.fabs(height_data)
height_data = height_data.astype(np.int32)
lidar_data *= 9.9999
lidar_data -= (0.5 * img_size, 0.5 * img_size)
lidar_data = np.fabs(lidar_data)
lidar_data = lidar_data.astype(np.int32)
lidar_data = np.reshape(lidar_data, (-1, 2))
lidar_img = np.zeros((img_size, img_size))
lidar_img[tuple(lidar_data.T)] = height_data # TODO: sort the point wrt height first lex sort
return lidar_img
示例13: _max_error
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def _max_error(arrays1, arrays2):
"""Computes maximum elementwise gap between two lists of ndarrays.
Computes the maximum elementwise gap between two lists with the same length,
of arrays with the same shape.
Args:
arrays1: a lists of np.ndarrays.
arrays2: a lists of np.ndarrays of the same shape as arrays1.
Returns:
The maximum elementwise absolute difference between the two lists of arrays.
"""
error = 0
for array1, array2 in zip(arrays1, arrays2):
if array1.size or array2.size: # Handle zero size ndarrays correctly
error = np.maximum(error, np.fabs(array1 - array2).max())
return error
示例14: test_irreg_hf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def test_irreg_hf(self):
import matplotlib.pyplot as plt
fig = plt.gcf()
plt.clf()
fig.add_subplot(111)
idx = date_range('2012-6-22 21:59:51', freq='S', periods=100)
df = DataFrame(np.random.randn(len(idx), 2), idx)
irreg = df.ix[[0, 1, 3, 4]]
ax = irreg.plot()
diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
sec = 1. / 24 / 60 / 60
self.assert_((np.fabs(diffs[1:] - [sec, sec * 2, sec]) < 1e-8).all())
plt.clf()
fig.add_subplot(111)
df2 = df.copy()
df2.index = df.index.asobject
ax = df2.plot()
diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
self.assert_((np.fabs(diffs[1:] - sec) < 1e-8).all())
示例15: find_right_intersect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fabs [as 别名]
def find_right_intersect(vec, target_val, start_index=0):
nearest_index = start_index
next_index = start_index
size = len(vec) - 1
if next_index == size:
return size
next_val = vec[next_index]
best_distance = np.abs(next_val - target_val)
while (next_index < size):
next_index += 1
next_val = vec[next_index]
dist = np.fabs(next_val - target_val) # pylint: disable=assignment-from-no-return
if dist < best_distance:
best_distance = dist
nearest_index = next_index
if next_index == size or next_val < target_val:
break
return nearest_index