我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.negative()。
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'))
def test_spacing_nextafter(self): """Test np.spacing and np.nextafter""" # All non-negative finite #'s a = np.arange(0x7c00, dtype=uint16) hinf = np.array((np.inf,), dtype=float16) a_f16 = a.view(dtype=float16) assert_equal(np.spacing(a_f16[:-1]), a_f16[1:]-a_f16[:-1]) assert_equal(np.nextafter(a_f16[:-1], hinf), a_f16[1:]) assert_equal(np.nextafter(a_f16[0], -hinf), -a_f16[1]) assert_equal(np.nextafter(a_f16[1:], -hinf), a_f16[:-1]) # switch to negatives a |= 0x8000 assert_equal(np.spacing(a_f16[0]), np.spacing(a_f16[1])) assert_equal(np.spacing(a_f16[1:]), a_f16[:-1]-a_f16[1:]) assert_equal(np.nextafter(a_f16[0], hinf), -a_f16[1]) assert_equal(np.nextafter(a_f16[1:], hinf), a_f16[:-1]) assert_equal(np.nextafter(a_f16[:-1], -hinf), a_f16[1:])
def decimate2(x,dec=2): Nout = int(math.floor(len(x)/dec)) idx = numpy.arange(Nout,dtype=numpy.int)*int(dec) res = x[idx]*0.0 count = numpy.copy(x[idx]) count[:]=1.0 count_vector = numpy.negative(numpy.isnan(x))*1.0 x[numpy.where(numpy.isnan(x))] = 0.0 for i in numpy.arange(dec): res = res + x[idx+i] count += count_vector[idx+i] count[numpy.where(count == 0.0)] = 1.0 return(res/count)
def test_string_parser_variants(self): # Allow space instead of 'T' between date and time assert_equal(np.array(['1980-02-29T01:02:03'], np.dtype('M8[s]')), np.array(['1980-02-29 01:02:03'], np.dtype('M8[s]'))) # Allow negative years assert_equal(np.array(['-1980-02-29T01:02:03'], np.dtype('M8[s]')), np.array(['-1980-02-29 01:02:03'], np.dtype('M8[s]'))) # UTC specifier assert_equal(np.array(['-1980-02-29T01:02:03Z'], np.dtype('M8[s]')), np.array(['-1980-02-29 01:02:03Z'], np.dtype('M8[s]'))) # Time zone offset assert_equal(np.array(['1980-02-29T02:02:03Z'], np.dtype('M8[s]')), np.array(['1980-02-29 00:32:03-0130'], np.dtype('M8[s]'))) assert_equal(np.array(['1980-02-28T22:32:03Z'], np.dtype('M8[s]')), np.array(['1980-02-29 00:02:03+01:30'], np.dtype('M8[s]'))) assert_equal(np.array(['1980-02-29T02:32:03.506Z'], np.dtype('M8[s]')), np.array(['1980-02-29 00:32:03.506-02'], np.dtype('M8[s]'))) assert_equal(np.datetime64('1977-03-02T12:30-0230'), np.datetime64('1977-03-02T15:00Z'))
def rand_sphere_xyz(count=1, hemi=0, seed=None): """ Generates random points on unit sphere. Returns array of random spherical positions, array dimensions is (count, 3), it is count * (x, y, z). @param count: number of returned point, major dimension of returned array @param hemi: if 0 then both hemispheres are filled, if positive then only nothern hemisphere is filled, if negative then only southern hemisphere is filled. """ rs = numpy.random.RandomState(seed=seed) r = rs.normal(size=(count, 3)) r /= numpy.linalg.norm(r, axis=1)[:, numpy.newaxis] if hemi != 0: numpy.absolute(r[:, 2], out=r[:, 2]) if hemi < 0: numpy.negative(r[:, 2], out=r[:, 2]) return r
def df_obs(x, *args): """ Derivative of function which optimises obs. """ sslm, word_counts, totals, mean_deriv_mtx, word, deriv = args sslm.obs[word] = x sslm.mean[word], sslm.fwd_mean[word] = sslm.compute_post_mean(word, sslm.chain_variance) model = "DTM" if model == "DTM": deriv = sslm.compute_obs_deriv(word, word_counts, totals, mean_deriv_mtx, deriv) elif model == "DIM": deriv = sslm.compute_obs_deriv_fixed(p.word, p.word_counts, p.totals, p.sslm, p.mean_deriv_mtx, deriv) return np.negative(deriv)
def update(self): t1,timeTook=time.time(),0 if len(self.ear.data) and not self.btnPause.isChecked(): freqHighCutoff=0 if self.spinLowpass.value()>0: freqHighCutoff=self.spinLowpass.value() data=self.ear.getFiltered(freqHighCutoff) if self.chkInvert.isChecked(): data=np.negative(data) if self.chkAutoscale.isChecked(): self.Yscale=np.max(np.abs(data))*1.1 self.grECG.plotItem.setRange(xRange=[0,self.ear.maxMemorySec], yRange=[-self.Yscale,self.Yscale],padding=0) self.grECG.plot(np.arange(len(data))/float(self.ear.rate),data,clear=True, pen=pyqtgraph.mkPen(color='r'),antialias=True) self.grECG.plotItem.setTitle(self.lineTitle.text(),color=(0,0,0)) self.stamp.setPos(0,-self.Yscale) self.grECG.plotItem.addItem(self.stamp) timeTook=(time.time()-t1)*1000 print("plotting took %.02f ms"%(timeTook)) msTillUpdate=int(self.ear.chunk/self.ear.rate*1000)-timeTook QtCore.QTimer.singleShot(max(0,msTillUpdate), self.update)
def quaternion_conjugate(quaternion): """Return conjugate of quaternion. >>> q0 = random_quaternion() >>> q1 = quaternion_conjugate(q0) >>> q1[0] == q0[0] and all(q1[1:] == -q0[1:]) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) numpy.negative(q[1:], q[1:]) return q
def quaternion_inverse(quaternion): """Return inverse of quaternion. >>> q0 = random_quaternion() >>> q1 = quaternion_inverse(q0) >>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0]) True """ q = numpy.array(quaternion, dtype=numpy.float64, copy=True) numpy.negative(q[1:], q[1:]) return q / numpy.dot(q, q)
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True): """Return spherical linear interpolation between two quaternions. >>> q0 = random_quaternion() >>> q1 = random_quaternion() >>> q = quaternion_slerp(q0, q1, 0) >>> numpy.allclose(q, q0) True >>> q = quaternion_slerp(q0, q1, 1, 1) >>> numpy.allclose(q, q1) True >>> q = quaternion_slerp(q0, q1, 0.5) >>> angle = math.acos(numpy.dot(q0, q)) >>> numpy.allclose(2, math.acos(numpy.dot(q0, q1)) / angle) or \ numpy.allclose(2, math.acos(-numpy.dot(q0, q1)) / angle) True """ q0 = unit_vector(quat0[:4]) q1 = unit_vector(quat1[:4]) if fraction == 0.0: return q0 elif fraction == 1.0: return q1 d = numpy.dot(q0, q1) if abs(abs(d) - 1.0) < _EPS: return q0 if shortestpath and d < 0.0: # invert rotation d = -d numpy.negative(q1, q1) angle = math.acos(d) + spin * math.pi if abs(angle) < _EPS: return q0 isin = 1.0 / math.sin(angle) q0 *= math.sin((1.0 - fraction) * angle) * isin q1 *= math.sin(fraction * angle) * isin q0 += q1 return q0
def arcball_constrain_to_axis(point, axis): """Return sphere point perpendicular to axis.""" v = numpy.array(point, dtype=numpy.float64, copy=True) a = numpy.array(axis, dtype=numpy.float64, copy=True) v -= a * numpy.dot(a, v) # on plane n = vector_norm(v) if n > _EPS: if v[2] < 0.0: numpy.negative(v, v) v /= n return v if a[2] == 1.0: return numpy.array([1.0, 0.0, 0.0]) return unit_vector([-a[1], a[0], 0.0])
def test_power_zero(self): # ticket #1271 zero = np.array([0j]) one = np.array([1+0j]) cnan = np.array([complex(np.nan, np.nan)]) # FIXME cinf not tested. #cinf = np.array([complex(np.inf, 0)]) def assert_complex_equal(x, y): x, y = np.asarray(x), np.asarray(y) assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) # positive powers for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, p), zero) # zero power assert_complex_equal(np.power(zero, 0), one) with np.errstate(invalid="ignore"): assert_complex_equal(np.power(zero, 0+1j), cnan) # negative power for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, -p), cnan) assert_complex_equal(np.power(zero, -1+0.2j), cnan)
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)
def test_lower_align(self): # check data that is not aligned to element size # i.e doubles are aligned to 4 bytes on i386 d = np.zeros(23 * 8, dtype=np.int8)[4:-4].view(np.float64) assert_equal(np.abs(d), d) assert_equal(np.negative(d), -d) np.negative(d, out=d) np.negative(np.ones_like(d), out=d) np.abs(d, out=d) np.abs(np.ones_like(d), out=d)
def test_datetime_unary(self): for tda, tdb, tdzero, tdone, tdmone in \ [ # One-dimensional arrays (np.array([3], dtype='m8[D]'), np.array([-3], dtype='m8[D]'), np.array([0], dtype='m8[D]'), np.array([1], dtype='m8[D]'), np.array([-1], dtype='m8[D]')), # NumPy scalars (np.timedelta64(3, '[D]'), np.timedelta64(-3, '[D]'), np.timedelta64(0, '[D]'), np.timedelta64(1, '[D]'), np.timedelta64(-1, '[D]'))]: # negative ufunc assert_equal(-tdb, tda) assert_equal((-tdb).dtype, tda.dtype) assert_equal(np.negative(tdb), tda) assert_equal(np.negative(tdb).dtype, tda.dtype) # absolute ufunc assert_equal(np.absolute(tdb), tda) assert_equal(np.absolute(tdb).dtype, tda.dtype) # sign ufunc assert_equal(np.sign(tda), tdone) assert_equal(np.sign(tdb), tdmone) assert_equal(np.sign(tdzero), tdzero) assert_equal(np.sign(tda).dtype, tda.dtype) # The ufuncs always produce native-endian results assert_
def test_string_parser_variants(self): # Allow space instead of 'T' between date and time assert_equal(np.array(['1980-02-29T01:02:03'], np.dtype('M8[s]')), np.array(['1980-02-29 01:02:03'], np.dtype('M8[s]'))) # Allow negative years assert_equal(np.array(['-1980-02-29T01:02:03'], np.dtype('M8[s]')), np.array(['-1980-02-29 01:02:03'], np.dtype('M8[s]'))) # UTC specifier with assert_warns(DeprecationWarning): assert_equal( np.array(['-1980-02-29T01:02:03'], np.dtype('M8[s]')), np.array(['-1980-02-29 01:02:03Z'], np.dtype('M8[s]'))) # Time zone offset with assert_warns(DeprecationWarning): assert_equal( np.array(['1980-02-29T02:02:03'], np.dtype('M8[s]')), np.array(['1980-02-29 00:32:03-0130'], np.dtype('M8[s]'))) with assert_warns(DeprecationWarning): assert_equal( np.array(['1980-02-28T22:32:03'], np.dtype('M8[s]')), np.array(['1980-02-29 00:02:03+01:30'], np.dtype('M8[s]'))) with assert_warns(DeprecationWarning): assert_equal( np.array(['1980-02-29T02:32:03.506'], np.dtype('M8[s]')), np.array(['1980-02-29 00:32:03.506-02'], np.dtype('M8[s]'))) with assert_warns(DeprecationWarning): assert_equal(np.datetime64('1977-03-02T12:30-0230'), np.datetime64('1977-03-02T15:00'))
def test_datetime_busday_holidays_count(self): holidays = ['2011-01-01', '2011-10-10', '2011-11-11', '2011-11-24', '2011-12-25', '2011-05-30', '2011-02-21', '2011-01-17', '2011-12-26', '2012-01-02', '2011-02-21', '2011-05-30', '2011-07-01', '2011-07-04', '2011-09-05', '2011-10-10'] bdd = np.busdaycalendar(weekmask='1111100', holidays=holidays) # Validate against busday_offset broadcast against # a range of offsets dates = np.busday_offset('2011-01-01', np.arange(366), roll='forward', busdaycal=bdd) assert_equal(np.busday_count('2011-01-01', dates, busdaycal=bdd), np.arange(366)) # Returns negative value when reversed assert_equal(np.busday_count(dates, '2011-01-01', busdaycal=bdd), -np.arange(366)) dates = np.busday_offset('2011-12-31', -np.arange(366), roll='forward', busdaycal=bdd) assert_equal(np.busday_count(dates, '2011-12-31', busdaycal=bdd), np.arange(366)) # Returns negative value when reversed assert_equal(np.busday_count('2011-12-31', dates, busdaycal=bdd), -np.arange(366)) # Can't supply both a weekmask/holidays and busdaycal assert_raises(ValueError, np.busday_offset, '2012-01-03', '2012-02-03', weekmask='1111100', busdaycal=bdd) assert_raises(ValueError, np.busday_offset, '2012-01-03', '2012-02-03', holidays=holidays, busdaycal=bdd) # Number of Mondays in March 2011 assert_equal(np.busday_count('2011-03', '2011-04', weekmask='Mon'), 4) # Returns negative value when reversed assert_equal(np.busday_count('2011-04', '2011-03', weekmask='Mon'), -4)
def __neg__(self): return negative(self)
def test_neg(input_data): expected_output = np.negative(input_data) node = onnx.helper.make_node('Neg', inputs=['x'], outputs=['y']) ng_results = convert_and_calculate(node, [input_data], [expected_output]) assert np.array_equal(ng_results, [expected_output])
def generate_op(self, op, out, x): self.append("np.negative({}, out={})", x, out)
def testCplxNegGPU(self): shapes = [(5,4,3), (5,4), (5,), (1,)] for sh in shapes: x = ((np.random.randn(*sh) + 1j*np.random.randn(*sh)).astype(np.complex64)) self._compareGpu(x, np.negative, tf.negative)
def testCplxNegGradGPU(self): shapes = [(5,4,3), (5,4), (5,), (1,)] for sh in shapes: x = ((np.random.randn(*sh) + 1j*np.random.randn(*sh)).astype(np.complex64)) self._compareGpuGrad(x, np.negative, tf.negative)