Python numpy.absolute() Examples
The following are 30
code examples of numpy.absolute().
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 also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: test_ufunc.py From recruit with Apache License 2.0 | 6 votes |
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 #2
Source File: reportableqty.py From pyGSTi with Apache License 2.0 | 6 votes |
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 #3
Source File: foa.py From NiaPy with MIT License | 6 votes |
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}
Example #4
Source File: filtering.py From radiometric_normalization with Apache License 2.0 | 6 votes |
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 #5
Source File: _matfuncs_inv_ssq.py From lambda-packs with MIT License | 6 votes |
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 #6
Source File: tracklet_classifier_train.py From TNT with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: lti.py From python-control with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #8
Source File: image_process.py From Advanced_Lane_Lines with MIT License | 6 votes |
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
Example #9
Source File: pi-timolo.py From pi-timolo with MIT License | 6 votes |
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 #10
Source File: BuildAdjacency.py From sparse-subspace-clustering-python with MIT License | 6 votes |
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
Example #11
Source File: intensity_measures.py From gmpe-smtk with GNU Affero General Public License v3.0 | 6 votes |
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 #12
Source File: test_ufunc.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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
Source File: test_old_ma.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_testUfuncRegression(self): f_invalid_ignore = [ 'sqrt', 'arctanh', 'arcsin', 'arccos', 'arccosh', 'arctanh', 'log', 'log10', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod'] for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'absolute', 'fabs', 'negative', 'floor', 'ceil', 'logical_not', 'add', 'subtract', 'multiply', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod', 'hypot', 'arctan2', 'equal', 'not_equal', 'less_equal', 'greater_equal', 'less', 'greater', 'logical_and', 'logical_or', 'logical_xor']: try: uf = getattr(umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(np.ma, f) args = self.d[:uf.nin] with np.errstate(): if f in f_invalid_ignore: np.seterr(invalid='ignore') if f in ['arctanh', 'log', 'log10']: np.seterr(divide='ignore') ur = uf(*args) mr = mf(*args) self.assertTrue(eq(ur.filled(0), mr.filled(0), f)) self.assertTrue(eqmask(ur.mask, mr.mask))
Example #14
Source File: test_old_ma.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_testUfuncs1(self): # Test various functions such as sin, cos. (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d self.assertTrue(eq(np.cos(x), cos(xm))) self.assertTrue(eq(np.cosh(x), cosh(xm))) self.assertTrue(eq(np.sin(x), sin(xm))) self.assertTrue(eq(np.sinh(x), sinh(xm))) self.assertTrue(eq(np.tan(x), tan(xm))) self.assertTrue(eq(np.tanh(x), tanh(xm))) with np.errstate(divide='ignore', invalid='ignore'): self.assertTrue(eq(np.sqrt(abs(x)), sqrt(xm))) self.assertTrue(eq(np.log(abs(x)), log(xm))) self.assertTrue(eq(np.log10(abs(x)), log10(xm))) self.assertTrue(eq(np.exp(x), exp(xm))) self.assertTrue(eq(np.arcsin(z), arcsin(zm))) self.assertTrue(eq(np.arccos(z), arccos(zm))) self.assertTrue(eq(np.arctan(z), arctan(zm))) self.assertTrue(eq(np.arctan2(x, y), arctan2(xm, ym))) self.assertTrue(eq(np.absolute(x), absolute(xm))) self.assertTrue(eq(np.equal(x, y), equal(xm, ym))) self.assertTrue(eq(np.not_equal(x, y), not_equal(xm, ym))) self.assertTrue(eq(np.less(x, y), less(xm, ym))) self.assertTrue(eq(np.greater(x, y), greater(xm, ym))) self.assertTrue(eq(np.less_equal(x, y), less_equal(xm, ym))) self.assertTrue(eq(np.greater_equal(x, y), greater_equal(xm, ym))) self.assertTrue(eq(np.conjugate(x), conjugate(xm))) self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, ym)))) self.assertTrue(eq(np.concatenate((x, y)), concatenate((x, y)))) self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, y)))) self.assertTrue(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
Example #15
Source File: function_base.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def _hist_bin_doane(x): """ Doane's histogram bin estimator. Improved version of Sturges' formula which works better for non-normal data. See http://stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. """ if x.size > 2: sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3))) sigma = np.std(x) if sigma > 0.0: # These three operations add up to # g1 = np.mean(((x - np.mean(x)) / sigma)**3) # but use only one temp array instead of three temp = x - np.mean(x) np.true_divide(temp, sigma, temp) np.power(temp, 3, temp) g1 = np.mean(temp) return x.ptp() / (1.0 + np.log2(x.size) + np.log2(1.0 + np.absolute(g1) / sg1)) return 0.0
Example #16
Source File: reco.py From video-quality with GNU General Public License v2.0 | 5 votes |
def eco(img): l10 = Laguerre_Gauss_Circular_Harmonic_1_0(17, 2) l30 = Laguerre_Gauss_Circular_Harmonic_3_0(17, 2) y10 = scipy.ndimage.filters.convolve(img, numpy.real(l10)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l10)) y30 = scipy.ndimage.filters.convolve(img, numpy.real(l30)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l30)) eco = numpy.sum( - (numpy.absolute(y30) * numpy.absolute(y10)) * numpy.cos( numpy.angle(y30) - 3 * numpy.angle(y10) ) ) return eco
Example #17
Source File: test_core.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_testUfuncRegression(self): # Tests new ufuncs on MaskedArrays. for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'absolute', 'fabs', 'negative', 'floor', 'ceil', 'logical_not', 'add', 'subtract', 'multiply', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod', 'hypot', 'arctan2', 'equal', 'not_equal', 'less_equal', 'greater_equal', 'less', 'greater', 'logical_and', 'logical_or', 'logical_xor', ]: try: uf = getattr(umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(numpy.ma.core, f) args = self.d[:uf.nin] ur = uf(*args) mr = mf(*args) assert_equal(ur.filled(0), mr.filled(0), f) assert_mask_equal(ur.mask, mr.mask, err_msg=f)
Example #18
Source File: test_umath.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_abs_neg_blocked(self): # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1 for dt, sz in [(np.float32, 11), (np.float64, 5)]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', max_size=sz): tgt = [ncu.absolute(i) for i in inp] np.absolute(inp, out=out) assert_equal(out, tgt, err_msg=msg) self.assertTrue((out >= 0).all()) tgt = [-1*(i) for i in inp] np.negative(inp, out=out) assert_equal(out, tgt, err_msg=msg) # will throw invalid flag depending on compiler optimizations with np.errstate(invalid='ignore'): for v in [np.nan, -np.inf, np.inf]: for i in range(inp.size): d = np.arange(inp.size, dtype=dt) inp[:] = -d inp[i] = v d[i] = -v if v == -np.inf else v assert_array_equal(np.abs(inp), d, err_msg=msg) np.abs(inp, out=out) assert_array_equal(out, d, err_msg=msg) assert_array_equal(-inp, -1*inp, err_msg=msg) np.negative(inp, out=out) assert_array_equal(out, -1*inp, err_msg=msg)
Example #19
Source File: MathMisc.py From chainer-compiler with MIT License | 5 votes |
def forward(self, x): y1 = F.absolute(x) return y1
Example #20
Source File: _continuous_distns.py From lambda-packs with MIT License | 5 votes |
def _preprocess(self, x, skew): # The real 'loc' and 'scale' are handled in the calling pdf(...). The # local variables 'loc' and 'scale' within pearson3._pdf are set to # the defaults just to keep them as part of the equations for # documentation. loc = 0.0 scale = 1.0 # If skew is small, return _norm_pdf. The divide between pearson3 # and norm was found by brute force and is approximately a skew of # 0.000016. No one, I hope, would actually use a skew value even # close to this small. norm2pearson_transition = 0.000016 ans, x, skew = np.broadcast_arrays([1.0], x, skew) ans = ans.copy() # mask is True where skew is small enough to use the normal approx. mask = np.absolute(skew) < norm2pearson_transition invmask = ~mask beta = 2.0 / (skew[invmask] * scale) alpha = (scale * beta)**2 zeta = loc - alpha / beta transx = beta * (x[invmask] - zeta) return ans, x, transx, mask, invmask, beta, alpha, zeta
Example #21
Source File: reco.py From video-quality with GNU General Public License v2.0 | 5 votes |
def pec(img): # TODO scale parameter should depend on resolution l10 = Laguerre_Gauss_Circular_Harmonic_1_0(17, 2) l30 = Laguerre_Gauss_Circular_Harmonic_3_0(17, 2) y10 = scipy.ndimage.filters.convolve(img, numpy.real(l10)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l10)) y30 = scipy.ndimage.filters.convolve(img, numpy.real(l30)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l30)) pec_map = - (numpy.absolute(y30) / numpy.absolute(y10)) * numpy.cos( numpy.angle(y30) - 3 * numpy.angle(y10) ) return pec_map
Example #22
Source File: tracklet_classifier_train.py From TNT with GNU General Public License v3.0 | 5 votes |
def estimate_GP(bbox,err_sigma): # h = ax+by+c N_pt = 2*len(bbox) A = np.zeros((N_pt,3)) b = np.zeros((N_pt,1)) w = np.ones(N_pt)/N_pt for n in range(0,len(bbox)): xmin = bbox[n,0] xmax = bbox[n,0]+bbox[n,2] ymax = bbox[n,1]+bbox[n,3] h = bbox[n,3] A[2*n,0] = xmin A[2*n,1] = ymax A[2*n,2] = 1 b[2*n,0] = h A[2*n+1,0] = xmax A[2*n+1,1] = ymax A[2*n+1,2] = 1 b[2*n+1,0] = h iters = 20 for k in range(iters): W = np.diag(w) p = np.matmul(np.linalg.pinv(np.matmul(W,A)),np.matmul(W,b)) err_ratio = np.absolute(np.matmul(A,p)-b)/np.absolute(np.matmul(A,p)) w = np.exp(-np.power(err_ratio[:,0],2)/np.power(err_sigma,2)) ww = (w[::2]+w[1::2])/2 w[::2] = ww w[1::2] = ww w = w/np.sum(w) #import pdb; pdb.set_trace() return p
Example #23
Source File: outlier.py From MegaQC with GNU General Public License v3.0 | 5 votes |
def get_outliers(self, y): return absolute(zscore(y)) > self.threshold
Example #24
Source File: model.py From FreqShow with MIT License | 5 votes |
def get_data(self): """Get spectrogram data from the tuner. Will return width number of values which are the intensities of each frequency bucket (i.e. FFT of radio samples). """ # Get width number of raw samples so the number of frequency bins is # the same as the display width. Add two because there will be mean/DC # values in the results which are ignored. samples = self.sdr.read_samples(freqshow.SDR_SAMPLE_SIZE)[0:self.width+2] # Run an FFT and take the absolute value to get frequency magnitudes. freqs = np.absolute(np.fft.fft(samples)) # Ignore the mean/DC values at the ends. freqs = freqs[1:-1] # Shift FFT result positions to put center frequency in center. freqs = np.fft.fftshift(freqs) # Convert to decibels. freqs = 20.0*np.log10(freqs) # Update model's min and max intensities when auto scaling each value. if self.min_auto_scale: min_intensity = np.min(freqs) self.min_intensity = min_intensity if self.min_intensity is None \ else min(min_intensity, self.min_intensity) if self.max_auto_scale: max_intensity = np.max(freqs) self.max_intensity = max_intensity if self.max_intensity is None \ else max(max_intensity, self.max_intensity) # Update intensity range (length between min and max intensity). self.range = self.max_intensity - self.min_intensity # Return frequency intensities. return freqs
Example #25
Source File: yellowfin_test.py From YellowFin_MXNet with Apache License 2.0 | 5 votes |
def tune_everything(x0squared, C, T, gmin, gmax): # 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 lr_max = (1 + np.sqrt(mu)) ** 2 / max_curv alpha_star = lr_min mustar = mu return alpha_star, mustar
Example #26
Source File: absolute.py From mars with Apache License 2.0 | 5 votes |
def absolute(x, out=None, where=None, **kwargs): r""" Calculate the absolute value element-wise. Parameters ---------- x : array_like Input tensor. out : Tensor, None, or tuple of Tensor and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or `None`, a freshly-allocated tensor is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. where : array_like, optional Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone. **kwargs Returns ------- absolute : Tensor An tensor containing the absolute value of each element in `x`. For complex input, ``a + ib``, the absolute value is :math:`\sqrt{ a^2 + b^2 }`. Examples -------- >>> import mars.tensor as mt >>> x = mt.array([-1.2, 1.2]) >>> mt.absolute(x).execute() array([ 1.2, 1.2]) >>> mt.absolute(1.2 + 1j).execute() 1.5620499351813308 """ op = TensorAbsolute(**kwargs) return op(x, out=out, where=where)
Example #27
Source File: cornernet_saccade.py From CornerNet-Lite-Pytorch with BSD 3-Clause "New" or "Revised" License | 5 votes |
def location_nms(locations, thresh=15): next_locations = [] sorted_inds = np.argsort(locations[:, -1])[::-1] locations = locations[sorted_inds] ys = locations[:, 0] xs = locations[:, 1] scales = locations[:, 2] dist_ys = np.absolute(ys.reshape(-1, 1) - ys.reshape(1, -1)) dist_xs = np.absolute(xs.reshape(-1, 1) - xs.reshape(1, -1)) dists = np.minimum(dist_ys, dist_xs) ratios = scales.reshape(-1, 1) / scales.reshape(1, -1) while dists.shape[0] > 0: next_locations.append(locations[0]) scale = scales[0] dist = dists[0] ratio = ratios[0] keep = (dist > (thresh / scale)) | (ratio > 1.2) | (ratio < 0.8) locations = locations[keep] scales = scales[keep] dists = dists[keep, :] dists = dists[:, keep] ratios = ratios[keep, :] ratios = ratios[:, keep] return np.stack(next_locations) if next_locations else np.zeros((0, 4))
Example #28
Source File: rotation_tools.py From PyMO with MIT License | 5 votes |
def to_euler(self, use_deg=False): eulers = np.zeros((2, 3)) if np.absolute(np.absolute(self.rotmat[2, 0]) - 1) < 1e-12: #GIMBAL LOCK! print('Gimbal') if np.absolute(self.rotmat[2, 0]) - 1 < 1e-12: eulers[:,0] = math.atan2(-self.rotmat[0,1], -self.rotmat[0,2]) eulers[:,1] = -math.pi/2 else: eulers[:,0] = math.atan2(self.rotmat[0,1], -elf.rotmat[0,2]) eulers[:,1] = math.pi/2 return eulers theta = - math.asin(self.rotmat[2,0]) theta2 = math.pi - theta # psi1, psi2 eulers[0,0] = math.atan2(self.rotmat[2,1]/math.cos(theta), self.rotmat[2,2]/math.cos(theta)) eulers[1,0] = math.atan2(self.rotmat[2,1]/math.cos(theta2), self.rotmat[2,2]/math.cos(theta2)) # theta1, theta2 eulers[0,1] = theta eulers[1,1] = theta2 # phi1, phi2 eulers[0,2] = math.atan2(self.rotmat[1,0]/math.cos(theta), self.rotmat[0,0]/math.cos(theta)) eulers[1,2] = math.atan2(self.rotmat[1,0]/math.cos(theta2), self.rotmat[0,0]/math.cos(theta2)) if use_deg: eulers = rad2deg(eulers) return eulers
Example #29
Source File: intensity_measures.py From gmpe-smtk with GNU Affero General Public License v3.0 | 5 votes |
def get_cav(acceleration, time_step, threshold=0.0): """ Returns the cumulative absolute velocity above a given threshold of acceleration """ acceleration = np.fabs(acceleration) idx = np.where(acceleration >= threshold) if len(idx) > 0: return np.trapz(acceleration[idx], dx=time_step) else: return 0.0
Example #30
Source File: test_timedelta64.py From recruit with Apache License 2.0 | 5 votes |
def test_ufunc_coercions(self): # normal ops are also tested in tseries/test_timedeltas.py idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'], freq='2H', name='x') for result in [idx * 2, np.multiply(idx, 2)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['4H', '8H', '12H', '16H', '20H'], freq='4H', name='x') tm.assert_index_equal(result, exp) assert result.freq == '4H' for result in [idx / 2, np.divide(idx, 2)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['1H', '2H', '3H', '4H', '5H'], freq='H', name='x') tm.assert_index_equal(result, exp) assert result.freq == 'H' idx = TimedeltaIndex(['2H', '4H', '6H', '8H', '10H'], freq='2H', name='x') for result in [-idx, np.negative(idx)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['-2H', '-4H', '-6H', '-8H', '-10H'], freq='-2H', name='x') tm.assert_index_equal(result, exp) assert result.freq == '-2H' idx = TimedeltaIndex(['-2H', '-1H', '0H', '1H', '2H'], freq='H', name='x') for result in [abs(idx), np.absolute(idx)]: assert isinstance(result, TimedeltaIndex) exp = TimedeltaIndex(['2H', '1H', '0H', '1H', '2H'], freq=None, name='x') tm.assert_index_equal(result, exp) assert result.freq is None