# Python numpy.absolute() Examples

The following are 30 code examples for showing how to use numpy.absolute(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module , or try the search function .

Example 1
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]]))
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]))
else:
CKSym = CSym
return CKSym 
Example 2
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 
Example 3
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 
Example 4
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) 
Example 5
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))

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 
Example 6
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')) 
Example 7
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)]) 
Example 8
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

#----------------------------------------------------------------------------------------------- 
Example 9
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 
Example 10
def initPopulation(self, task):
r"""Initialize the starting population.

Args:

Returns:
Tuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]:
1. New population.
2. New population fitness/function values.
* age (numpy.ndarray[int32]): Age of trees.

* :func:NiaPy.algorithms.Algorithm.initPopulation
"""
Trees, Evaluations, _ = Algorithm.initPopulation(self, task)
age = zeros(self.NP, dtype=int32)
return Trees, Evaluations, {'age': age} 
Example 11
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 
Example 12
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')) 
Example 13
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 
Example 14
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 
Example 15
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
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 
Example 16
def worldToVoxelCoord(worldCoord, origin, spacing):
stretchedVoxelCoord = np.absolute(worldCoord - origin)
voxelCoord = stretchedVoxelCoord / spacing
return voxelCoord
# read map file 
Example 17
def worldToVoxelCoord(worldCoord, origin, spacing):
stretchedVoxelCoord = np.absolute(worldCoord - origin)
voxelCoord = stretchedVoxelCoord / spacing
return voxelCoord
# read map file 
Example 18
def worldToVoxelCoord(worldCoord, origin, spacing):
stretchedVoxelCoord = np.absolute(worldCoord - origin)
voxelCoord = stretchedVoxelCoord / spacing
return voxelCoord
# read map file 
Example 19
def worldToVoxelCoord(worldCoord, origin, spacing):
stretchedVoxelCoord = np.absolute(worldCoord - origin)
voxelCoord = stretchedVoxelCoord / spacing
return voxelCoord
# read groundtruth from original data space
# remove data of 0 value 
Example 20
def worldToVoxelCoord(worldCoord, origin, spacing):

stretchedVoxelCoord = np.absolute(worldCoord - origin)
voxelCoord = stretchedVoxelCoord / spacing
return voxelCoord 
Example 21
def g_r(grids_coor, site, l, mr, r, zona, x_axis = [1,0,0], z_axis = [0,0,1], unit = 'B'):
r'''
Evaluate the projection function g(r) or \Theta_{l,m_r}(\theta,\phi) on a grid
ref: Chapter 3, wannier90 User Guide
Attributes:
grids_coor : a grids for the cell of interest
site       : absolute coordinate (in Borh/Angstrom) of the g(r) in the cell
l, mr      : l and mr value in the Table 3.1 and 3.2 of the ref
Return:
theta_lmr  : an array (ngrid, value) of g(r)

'''

unit_conv = 1
if unit == 'A': unit_conv = param.BOHR

r_vec = (grids_coor - site)
r_vec = np.einsum('iv,uv ->iu', r_vec, transform(x_axis, z_axis))
r_norm = np.linalg.norm(r_vec,axis=1)
if (r_norm < 1e-8).any() == True:
r_vec = (grids_coor - site - 1e-5)
r_vec = np.einsum('iv,uv ->iu', r_vec, transform(x_axis, z_axis))
r_norm = np.linalg.norm(r_vec,axis=1)
cost = r_vec[:,2]/r_norm

phi = np.empty_like(r_norm)
for point in range(phi.shape[0]):
if r_vec[point,0] > 1e-8:
phi[point] = np.arctan(r_vec[point,1]/r_vec[point,0])
elif r_vec[point,0] < -1e-8:
phi[point] = np.arctan(r_vec[point,1]/r_vec[point,0]) + np.pi
else:
phi[point] = np.sign(r_vec[point,1]) * 0.5 * np.pi

return theta_lmr(l, mr, cost, phi) * R_r(r_norm * unit_conv, r = r, zona = zona) 
Example 22
def get_wannier(self, supercell = [1,1,1], grid = [50,50,50]):
'''
Evaluate the MLWF using a periodic grid
'''

grids_coor, weights = periodic_grid(self.cell, grid, supercell = [1,1,1], order = 'C')
kpts = self.cell.get_abs_kpts(self.kpt_latt_loc)

u_mo  = []
for k_id in range(self.num_kpts_loc):
mo_included = self.mo_coeff_kpts[k_id][:,self.band_included_list]
mo_in_window = self.lwindow[k_id]
C_opt = mo_included[:,mo_in_window].dot(self.U_matrix_opt[k_id].T)
C_tildle = C_opt.dot(self.U_matrix[k_id].T)
kpt = kpts[k_id]
ao = numint.eval_ao(self.cell, grids_coor, kpt = kpt)
u_ao = np.einsum('x,xi->xi', np.exp(-1j*np.dot(grids_coor, kpt)), ao, optimize = True)
u_mo.append(np.einsum('xi,in->xn', u_ao, C_tildle, optimize = True))

u_mo = np.asarray(u_mo)
WF0 = libwannier90.get_WF0s(self.kpt_latt_loc.shape[0],self.kpt_latt_loc, supercell, grid, u_mo)
# Fix the global phase following the pw2wannier90 procedure
max_index = (WF0*WF0.conj()).real.argmax(axis=0)
norm_wfs = np.diag(WF0[max_index,:])
norm_wfs = norm_wfs/np.absolute(norm_wfs)
WF0 = WF0/norm_wfs/self.num_kpts_loc

# Check the 'reality' following the pw2wannier90 procedure
for WF_id in range(self.num_wann_loc):
ratio_max = np.abs(WF0[np.abs(WF0[:,WF_id].real) >= 0.01,WF_id].imag/WF0[np.abs(WF0[:,WF_id].real) >= 0.01,WF_id].real).max(axis=0)
print('The maximum imag/real for wannier function ', WF_id,' : ', ratio_max)

return WF0 
Example 23
def int_abs(arr):
""" Absolute values of array taking care of max negative int values

Parameters
----------
arr : array-like

Returns
-------
abs_arr : array
array the same shape as arr in which all negative numbers have been
changed to positive numbers with the magnitude.

Examples
--------
This kind of thing is confusing in base numpy:

>>> import numpy as np
>>> np.abs(np.int8(-128))
-128

int_abs fixes that:

>>> int_abs(np.int8(-128))
128
>>> int_abs(np.array([-128, 127], dtype=np.int8))
array([128, 127], dtype=uint8)
>>> int_abs(np.array([-128, 127], dtype=np.float32))
array([ 128.,  127.], dtype=float32)
"""
arr = np.array(arr, copy=False)
dt = arr.dtype
if dt.kind == 'u':
return arr
if dt.kind != 'i':
return np.absolute(arr)
out = arr.astype(np.dtype(dt.str.replace('i', 'u')))
return np.choose(arr < 0, (arr, arr * -1), out=out) 
Example 24
def __init__(self):
self.calculate = lambda dataset, cluster: numpy.absolute(dataset - cluster) 
Example 25
def allChange(threshold):
"""Generates a stopping condition that stops if all cluster changes are less than a threshold.

:type threshold: number
:param threshold: maximum change allowed for all clusters
:rtype: callable that takes iterationNumber, corrections, values, datasetSize as arguments
:return: stopping condition function
"""
return lambda iterationNumber, corrections, values, datasetSize: not all((numpy.absolute(x) < threshold).all() for x in corrections if x is not None) 
Example 26
def halfChange(threshold):
"""Generates a stopping condition that stops if half of the cluster changes are less than a threshold.

:type threshold: number
:param threshold: maximum change allowed for half of the clusters
:rtype: callable that takes iterationNumber, corrections, values, datasetSize as arguments
:return: stopping condition function
"""
return lambda iterationNumber, corrections, values, datasetSize: numpy.sum([(numpy.absolute(x) < threshold).all() for x in corrections if x is not None], dtype=numpy.dtype(float)) / numpy.sum([x is not None for x in corrections], dtype=numpy.dtype(float)) < 0.5 
Example 27
def _get_array_index(self, value, array):
'''Calculate the exact index position within latitude array'''
# Find the spacing
dp = np.absolute(array[1] - array[0])
# Calculate the relative position
pos = np.absolute(value - array[0]) / dp
return pos

####################
# DEM file methods #
#################### 
Example 28
def scat_coeff(D, lam, m):
"""
Scattering coefficient of a spherical particle. Unitless.

Doviak and Zrnic (1993), Eqn 3.14b or Battan (1973), Eqn 6.5

Parameters
----------
D : float or array
Particle diameter [m]
lam : float
m : float
Complex refractive index [unitless]

Notes
-----
An example from Battan (1973) is for water at 0C m=7.14-2.89j for a
wavelength of 3.21 cm and for ice m=1.78-0.0024j for
wavelength range from 1-10 cm.
See Battan (1973) Ch.4 , Tables 4.1 and 4.2 for values from
Gunn and East (1954).
Also see Doviak and Zrnic (1993), Fig. 3.3 caption.
"""

Km = (m**2 - 1) / (m**2 + 2)
Qs = (2 * np.pi**5 * np.asarray(D)**6 / (3 * lam**4) * (np.absolute(Km))**2)
return Qs 
Example 29
def test_discrete_bode(self):
# Create a simple discrete time system and check the calculation
sys = TransferFunction([1], [1, 0.5], 1)
omega = [1, 2, 3]
mag_out, phase_out, omega_out = bode(sys, omega)
H_z = list(map(lambda w: 1./(np.exp(1.j * w) + 0.5), omega))
np.testing.assert_array_almost_equal(omega, omega_out)
np.testing.assert_array_almost_equal(mag_out, np.absolute(H_z))
np.testing.assert_array_almost_equal(phase_out, np.angle(H_z)) 
Example 30
def apply_one(self, data, meta=None):
# Take the upper right triangle of a matrix