本文整理汇总了Python中numpy.absolute方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.absolute方法的具体用法?Python numpy.absolute怎么用?Python numpy.absolute使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.absolute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BuildAdjacency
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def BuildAdjacency(CMat, K):
CMat = CMat.astype(float)
CKSym = None
N, _ = CMat.shape
CAbs = np.absolute(CMat).astype(float)
for i in range(0, N):
c = CAbs[:, i]
PInd = np.flip(np.argsort(c), 0)
CAbs[:, i] = CAbs[:, i] / float(np.absolute(c[PInd[0]]))
CSym = np.add(CAbs, CAbs.T).astype(float)
if K != 0:
Ind = np.flip(np.argsort(CSym, axis=0), 0)
CK = np.zeros([N, N]).astype(float)
for i in range(0, N):
for j in range(0, K):
CK[Ind[j, i], i] = CSym[Ind[j, i], i] / float(np.absolute(CSym[Ind[0, i], i]))
CKSym = np.add(CK, CK.T)
else:
CKSym = CSym
return CKSym
示例2: filter_by_residuals_from_line_pixel_list
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def filter_by_residuals_from_line_pixel_list(candidate_data, reference_data,
threshold=1000, line_gain=1.0,
line_offset=0.0):
''' Calculates the residuals from a line and filters by residuals.
:param list candidate_band: A list of valid candidate data
:param list reference_band: A list of coincident valid reference data
:param float line_gain: The gradient of the line
:param float line_offset: The intercept of the line
:returns: A list of booleans the same length as candidate representing if
the data point is still active after filtering or not
'''
logging.info('Filtering: Filtering from line: y = '
'{} * x + {} @ {}'.format(line_gain, line_offset, threshold))
def _get_residual(data_1, data_2):
return numpy.absolute(line_gain * data_1 - data_2 + line_offset) / \
numpy.sqrt(1 + line_gain * line_gain)
residuals = _get_residual(candidate_data, reference_data)
return residuals < threshold
示例3: damp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def damp(self):
'''Natural frequency, damping ratio of system poles
Returns
-------
wn : array
Natural frequencies for each system pole
zeta : array
Damping ratio for each system pole
poles : array
Array of system poles
'''
poles = self.pole()
if isdtime(self, strict=True):
splane_poles = np.log(poles)/self.dt
else:
splane_poles = poles
wn = absolute(splane_poles)
Z = -real(splane_poles)/wn
return wn, Z, poles
示例4: absdiff
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [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)
示例5: color_grid_thresh
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def color_grid_thresh(img, s_thresh=(170,255), sx_thresh=(20, 100)):
img = np.copy(img)
# Convert to HLS color space and separate the V channel
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
l_channel = hls[:,:,1]
s_channel = hls[:,:,2]
# Sobel x
sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivateive in x
abs_sobelx = np.absolute(sobelx) # Absolute x derivateive to accentuate lines
scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))
# Threshold x gradient
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1
# Threshold color channel
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1
# combine the two binary
binary = sxbinary | s_binary
# Stack each channel (for visual check the pixal sourse)
# color_binary = np.dstack((np.zeros_like(sxbinary), sxbinary,s_binary)) * 255
return binary
示例6: test_endian
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def test_endian(self):
msg = "big endian"
a = np.arange(6, dtype='>i4').reshape((2, 3))
assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1),
err_msg=msg)
msg = "little endian"
a = np.arange(6, dtype='<i4').reshape((2, 3))
assert_array_equal(umt.inner1d(a, a), np.sum(a*a, axis=-1),
err_msg=msg)
# Output should always be native-endian
Ba = np.arange(1, dtype='>f8')
La = np.arange(1, dtype='<f8')
assert_equal((Ba+Ba).dtype, np.dtype('f8'))
assert_equal((Ba+La).dtype, np.dtype('f8'))
assert_equal((La+Ba).dtype, np.dtype('f8'))
assert_equal((La+La).dtype, np.dtype('f8'))
assert_equal(np.absolute(La).dtype, np.dtype('f8'))
assert_equal(np.absolute(Ba).dtype, np.dtype('f8'))
assert_equal(np.negative(La).dtype, np.dtype('f8'))
assert_equal(np.negative(Ba).dtype, np.dtype('f8'))
示例7: get_fourier_spectrum
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def get_fourier_spectrum(time_series, time_step):
"""
Returns the Fourier spectrum of the time series
:param numpy.ndarray time_series:
Array of values representing the time series
:param float time_step:
Time step of the time series
:returns:
Frequency (as numpy array)
Fourier Amplitude (as numpy array)
"""
n_val = nextpow2(len(time_series))
# numpy.fft.fft will zero-pad records whose length is less than the
# specified nval
# Get Fourier spectrum
fspec = np.fft.fft(time_series, n_val)
# Get frequency axes
d_f = 1. / (n_val * time_step)
freq = d_f * np.arange(0., (n_val / 2.0), 1.0)
return freq, time_step * np.absolute(fspec[:int(n_val / 2.0)])
示例8: checkForMotion
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def checkForMotion(image1, image2):
# Find motion between two data streams based on sensitivity and threshold
motionDetected = False
pixColor = 3 # red=0 green=1 blue=2 all=3 default=1
if pixColor == 3:
pixChanges = (np.absolute(image1-image2)>motionThreshold).sum()/3
else:
pixChanges = (np.absolute(image1[...,pixColor]-image2[...,pixColor])>motionThreshold).sum()
if pixChanges > motionSensitivity:
motionDetected = True
if motionDetected:
if motionDotsOn:
dotCount = showDots(motionDotsMax + 2) # New Line
else:
print("")
logging.info("Found Motion: Threshold=%s Sensitivity=%s changes=%s",
motionThreshold, motionSensitivity, pixChanges)
return motionDetected
#-----------------------------------------------------------------------------------------------
示例9: h_err_pred
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def h_err_pred(p,bbox,err_sigma):
x_center = (bbox[:,0]+bbox[:,2])/2
ymax = bbox[:,1]+bbox[:,3]
h = bbox[:,3]
A = np.ones((len(bbox),3))
A[:,0] = x_center
A[:,1] = ymax
h_pred = np.matmul(A,p)
#import pdb; pdb.set_trace()
err_ratio = np.absolute(h_pred[:,0]-h)/np.absolute(h_pred[:,0])
err_ratio[h_pred[:,0]==0] = 0
import pdb; pdb.set_trace()
'''
for n in range(len(h_pred)):
if h_pred[n,0]==0:
import pdb; pdb.set_trace()
'''
return err_ratio
示例10: initPopulation
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def initPopulation(self, task):
r"""Initialize the starting population.
Args:
task (Task): Optimization task
Returns:
Tuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]:
1. New population.
2. New population fitness/function values.
3. Additional arguments:
* age (numpy.ndarray[int32]): Age of trees.
See Also:
* :func:`NiaPy.algorithms.Algorithm.initPopulation`
"""
Trees, Evaluations, _ = Algorithm.initPopulation(self, task)
age = zeros(self.NP, dtype=int32)
self.dx = absolute(task.benchmark.Upper) / 5
return Trees, Evaluations, {'age': age}
示例11: _logm_force_nonsingular_triangular_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def _logm_force_nonsingular_triangular_matrix(T, inplace=False):
# The input matrix should be upper triangular.
# The eps is ad hoc and is not meant to be machine precision.
tri_eps = 1e-20
abs_diag = np.absolute(np.diag(T))
if np.any(abs_diag == 0):
exact_singularity_msg = 'The logm input matrix is exactly singular.'
warnings.warn(exact_singularity_msg, LogmExactlySingularWarning)
if not inplace:
T = T.copy()
n = T.shape[0]
for i in range(n):
if not T[i, i]:
T[i, i] = tri_eps
elif np.any(abs_diag < tri_eps):
near_singularity_msg = 'The logm input matrix may be nearly singular.'
warnings.warn(near_singularity_msg, LogmNearlySingularWarning)
return T
示例12: _convert_to_torque_from_pwm
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def _convert_to_torque_from_pwm(self, pwm, true_motor_velocity):
"""Convert the pwm signal to torque.
Args:
pwm: The pulse width modulation.
true_motor_velocity: The true motor velocity at the current moment. It is
used to compute the back EMF voltage and the viscous damping.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor.
"""
observed_torque = np.clip(
self._torque_constant *
(np.asarray(pwm) * self._voltage / self._resistance),
-OBSERVED_TORQUE_LIMIT, OBSERVED_TORQUE_LIMIT)
# Net voltage is clipped at 50V by diodes on the motor controller.
voltage_net = np.clip(
np.asarray(pwm) * self._voltage -
(self._torque_constant + self._viscous_damping) *
np.asarray(true_motor_velocity), -VOLTAGE_CLIPPING, VOLTAGE_CLIPPING)
current = voltage_net / self._resistance
current_sign = np.sign(current)
current_magnitude = np.absolute(current)
# Saturate torque based on empirical current relation.
actual_torque = np.interp(current_magnitude, self._current_table,
self._torque_table)
actual_torque = np.multiply(current_sign, actual_torque)
actual_torque = np.multiply(self._strength_ratios, actual_torque)
return actual_torque, observed_torque
示例13: _convert_to_torque_from_pwm
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def _convert_to_torque_from_pwm(self, pwm, current_motor_velocity):
"""Convert the pwm signal to torque.
Args:
pwm: The pulse width modulation.
current_motor_velocity: The motor velocity at the current time step.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor.
"""
observed_torque = np.clip(
self._torque_constant * (pwm * self._voltage / self._resistance),
-OBSERVED_TORQUE_LIMIT, OBSERVED_TORQUE_LIMIT)
# Net voltage is clipped at 50V by diodes on the motor controller.
voltage_net = np.clip(pwm * self._voltage -
(self._torque_constant + self._viscous_damping)
* current_motor_velocity,
-VOLTAGE_CLIPPING, VOLTAGE_CLIPPING)
current = voltage_net / self._resistance
current_sign = np.sign(current)
current_magnitude = np.absolute(current)
# Saturate torque based on empirical current relation.
actual_torque = np.interp(current_magnitude, self._current_table,
self._torque_table)
actual_torque = np.multiply(current_sign, actual_torque)
return actual_torque, observed_torque
示例14: tune_everything
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def tune_everything(self, x0squared, c, t, gmin, gmax):
del t
# First tune based on dynamic range
if c == 0:
dr = gmax / gmin
mustar = ((np.sqrt(dr) - 1) / (np.sqrt(dr) + 1))**2
alpha_star = (1 + np.sqrt(mustar))**2/gmax
return alpha_star, mustar
dist_to_opt = x0squared
grad_var = c
max_curv = gmax
min_curv = gmin
const_fact = dist_to_opt * min_curv**2 / 2 / grad_var
coef = [-1, 3, -(3 + const_fact), 1]
roots = np.roots(coef)
roots = roots[np.real(roots) > 0]
roots = roots[np.real(roots) < 1]
root = roots[np.argmin(np.imag(roots))]
assert root > 0 and root < 1 and np.absolute(root.imag) < 1e-6
dr = max_curv / min_curv
assert max_curv >= min_curv
mu = max(((np.sqrt(dr) - 1) / (np.sqrt(dr) + 1))**2, root**2)
lr_min = (1 - np.sqrt(mu))**2 / min_curv
alpha_star = lr_min
mustar = mu
return alpha_star, mustar
示例15: worldToVoxelCoord
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import absolute [as 别名]
def worldToVoxelCoord(worldCoord, origin, spacing):
stretchedVoxelCoord = np.absolute(worldCoord - origin)
voxelCoord = stretchedVoxelCoord / spacing
return voxelCoord
# read map file