我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用numpy.copysign()。
def dec2dms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. if isinstance(dec,basestring): dec = float(dec) sign = numpy.copysign(1.0,dec) fdeg = np.abs(dec) deg = int(fdeg) fminute = (fdeg - deg)*MINUTE minute = int(fminute) second = (fminute - minute)*MINUTE deg = int(deg * sign) return (deg, minute, second)
def dms2dec(dms): """ Convert latitude from degrees,minutes,seconds in string or 3-array format to decimal degrees. """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. # Be careful here, degree needs to be a float so that negative zero # can have its signbit set: # http://docs.scipy.org/doc/numpy-1.7.0/reference/c-api.coremath.html#NPY_NZERO if isinstance(dms,basestring): degree,minute,second = numpy.array(re.split('[dms]',hms))[:3].astype(float) else: degree,minute,second = dms.T sign = numpy.copysign(1.0,degree) decimal = numpy.abs(degree) + minute * 1./MINUTE + second * 1./SECOND decimal *= sign return decimal
def test_copysign(): assert_(np.copysign(1, -1) == -1) with np.errstate(divide="ignore"): assert_(1 / np.copysign(0, -1) < 0) assert_(1 / np.copysign(0, 1) > 0) assert_(np.signbit(np.copysign(np.nan, -1))) assert_(not np.signbit(np.copysign(np.nan, 1)))
def copy_sign(x: Number = 1.0, y: Number = -1.0) -> Number: return np.copysign(x, y)
def range_(start: Float = 0.0, stop: Float = 1.0, step: Float = 0.1, ) -> [Float]: if stop < start: step = np.copysign(step, -1) return np.arange(start, stop, step)
def sample_at_prob(self, prob, mean, var, rstate=None): """ """ shape = mean.shape[0] # Get a sample from a distribution N(0,I) scale = spstat.norm.ppf(prob, loc=0, scale=1) v = spstat.multivariate_normal.rvs( mean=None, cov=1, size=shape, random_state=rstate) v *= np.fabs(scale) / np.sqrt((v**2).sum()) # Spectral decomposition of target dist covariance eigs, vects = np.linalg.eigh(var) assert eigs.shape[0] == shape, 'Too few eigenvalues' assert np.all(eigs >= 0.0), 'Negative eigenvalues' assert np.all(np.isreal(eigs)), 'Imaginary eigenvalues' assert np.all(np.fabs( np.dot(vects.T, vects) - np.eye(shape)) < 1E-14),\ 'Eigenvectors are not orthogonal' # Calculate map from N(0,I) to N(0,E) a_mat = np.dot(vects.T, np.dot(np.diag(np.sqrt(eigs)), vects)) # Add the mean to get N(u,E) #return mean + np.copysign(np.dot(a_mat, v), scale) return mean + scale * np.diag(np.sqrt(var))
def compute_edge_types(machina, edge_index): """Classify the internal edges by type, and find the singular graph. The edge type is determined by concatenating the matchings around the edges one-ring.""" # For each internal edge of the tetrahedral mesh. for ei in edge_index: try: one_ring = machina.one_rings[ei] except KeyError: continue # Not an internal edge. # Concatenate the matchings around the edge to find its type. edge_type = np.identity(3) for fi in one_ring['faces']: matching = [] # Recall that in the one-ring, if 'fi' is negative, it is # a 't-s' pair, as opposed to a 's-t' pair. # If pair order is reversed, invert/transpose rotation matrix. # Use copysign to distinguish +0 from -0. if np.copysign(1, fi) > 0: matching = chiral_symmetries[machina.matchings[fi]] else: matching = chiral_symmetries[machina.matchings[-fi]].T # Concatenate transforms edge_type = np.dot(edge_type, matching) # Locate singular (not identity) and improper (not restricted) edges. is_singular, is_improper = True, True for si, restricted_type in enumerate(chiral_symmetries[0:9]): if np.allclose(edge_type, restricted_type): if si == 0 : is_singular = False is_improper = False break # Classify as proper(0), singular(1), improper (2) if is_singular: machina.edge_types[ei] = 1 if is_improper: machina.edge_types[ei] = 2
def _fWeightsInv(self, pop): return 4*np.copysign(np.power(np.abs(pop), 1/5), pop)
def __init__(self, file, isomer, *args): # Frequencies in waveunmbers self.frequency_wn = [] # Extract the Force constants from a g09 logfile and generate the # mass-weighted Hessian matrix in Hartree/(amu Bohr^2) mw_hessmat = read_hess(file, isomer) # Convert from atomic units - a bit ugly unit_conversion = ENERGY_AU / (BOHR_RADIUS**2 * ATOMIC_MASS_UNIT) / ((SPEED_OF_LIGHT * 2 * np.pi)**2) eigs = np.linalg.eigvalsh(mw_hessmat * unit_conversion) freqs = [ np.copysign(np.sqrt(np.abs(freq)),freq) for freq in eigs ] # 5 or 6 small normal modes will be removed (depending on whether the molecule is linear or non-linear) if is_linear(file) == 'linear': trans_rot_modes = 5 else: trans_rot_modes = 6 # Keep a single imaginary frequency. It should be larger than the predefined cut-off if np.abs(freqs[0]) > freq_cutoff: self.im_frequency_wn = -1.0 * freqs[0] trans_rot_modes = trans_rot_modes + 1 for freq in freqs[trans_rot_modes:]: self.frequency_wn.append(freq) # Calculate the excitation factor (EXC), the ZPE (ZPE) and Teller-Redlich product factor (PF) # returns a 1D-array of all terms self.PF = calc_product_factor(self.frequency_wn, freq_scale_factor) self.ZPE = calc_zpe_factor(self.frequency_wn, temperature, freq_scale_factor) self.EXC = calc_excitation_factor(self.frequency_wn, temperature, freq_scale_factor)
def initialize(self): (cube_result, cube_hit_t_min, cube_hit_t_max) = self.grid.aabb.intersects(self.ray) if cube_result: cube_hit_point = self.ray.origin + (cube_hit_t_min) * self.ray.direction self.t_min = cube_hit_t_min self.cube_hit_t_min = cube_hit_t_min # print "DDA: Cube Hit Point:", cube_hit_point self.step_x = np.copysign(1., self.ray.direction[0]) self.step_y = np.copysign(1., self.ray.direction[1]) self.t_delta_x = (self.step_x / self.ray.direction[0]) self.t_delta_y = (self.step_y / self.ray.direction[1]) self.t_max_x = diff_distance(cube_hit_point[0], self.ray.direction[0]) self.t_max_y = diff_distance(cube_hit_point[1], self.ray.direction[1]) if cube_hit_point[0] < 0: cube_hit_point[0] -= 1 if cube_hit_point[1] < 0: cube_hit_point[1] -= 1 self.voxel = np.array(cube_hit_point, dtype=int) # print("DDA: Initial Voxel:" , self.voxel) ''' this conditional solves the problem where the "cube_hit_point" is just outside the grid because of floating point imprecision. ''' while self.voxel[0] < self.grid.aabb.low[0] or self.voxel[1] < self.grid.aabb.low[1]\ or self.voxel[0] >= self.grid.aabb.high[0] or self.voxel[1] >= self.grid.aabb.high[1]: print("DDA: Skyping:", self.voxel) if not self.step(): return False return True else: return False
def _copysign(x1, x2): """Slow replacement for np.copysign, which was introduced in numpy 1.4""" return np.abs(x1) * np.sign(x2)
def differential_func(cls, x): return np.copysign(np.ones(x.shape), x)
def test_half_ufuncs(self): """Test the various ufuncs""" a = np.array([0, 1, 2, 4, 2], dtype=float16) b = np.array([-2, 5, 1, 4, 3], dtype=float16) c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16) assert_equal(np.add(a, b), [-2, 6, 3, 8, 5]) assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1]) assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6]) assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625]) assert_equal(np.equal(a, b), [False, False, False, True, False]) assert_equal(np.not_equal(a, b), [True, True, True, False, True]) assert_equal(np.less(a, b), [False, True, False, False, True]) assert_equal(np.less_equal(a, b), [False, True, False, True, True]) assert_equal(np.greater(a, b), [True, False, True, False, False]) assert_equal(np.greater_equal(a, b), [True, False, True, True, False]) assert_equal(np.logical_and(a, b), [False, True, True, True, True]) assert_equal(np.logical_or(a, b), [True, True, True, True, True]) assert_equal(np.logical_xor(a, b), [True, False, False, False, False]) assert_equal(np.logical_not(a), [True, False, False, False, False]) assert_equal(np.isnan(c), [False, False, False, True, False]) assert_equal(np.isinf(c), [False, False, True, False, False]) assert_equal(np.isfinite(c), [True, True, False, False, True]) assert_equal(np.signbit(b), [True, False, False, False, False]) assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3]) assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3]) x = np.maximum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [0, 5, 1, 0, 6]) assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2]) x = np.minimum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [-2, -1, -np.inf, 0, 3]) assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3]) assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6]) assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2]) assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3]) assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0]) assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2]) assert_equal(np.square(b), [4, 25, 1, 16, 9]) assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125]) assert_equal(np.ones_like(b), [1, 1, 1, 1, 1]) assert_equal(np.conjugate(b), b) assert_equal(np.absolute(b), [2, 5, 1, 4, 3]) assert_equal(np.negative(b), [2, -5, -1, -4, -3]) assert_equal(np.sign(b), [-1, 1, 1, 1, 1]) assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b)) assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2])) assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
def test_eod_order_cancel_minute(self, direction, minute_emission): """ Test that EOD order cancel works in minute mode for both shorts and longs, and both daily emission and minute emission """ # order 1000 shares of asset1. the volume is only 1 share per bar, # so the order should be cancelled at the end of the day. algo = self.prep_algo( "set_cancel_policy(cancel_policy.EODCancel())", amount=np.copysign(1000, direction), minute_emission=minute_emission ) log_catcher = TestHandler() with log_catcher: results = algo.run(self.data_portal) for daily_positions in results.positions: self.assertEqual(1, len(daily_positions)) self.assertEqual( np.copysign(389, direction), daily_positions[0]["amount"], ) self.assertEqual(1, results.positions[0][0]["sid"]) # should be an order on day1, but no more orders afterwards np.testing.assert_array_equal([1, 0, 0], list(map(len, results.orders))) # should be 389 txns on day 1, but no more afterwards np.testing.assert_array_equal([389, 0, 0], list(map(len, results.transactions))) the_order = results.orders[0][0] self.assertEqual(ORDER_STATUS.CANCELLED, the_order["status"]) self.assertEqual(np.copysign(389, direction), the_order["filled"]) warnings = [record for record in log_catcher.records if record.level == WARNING] self.assertEqual(1, len(warnings)) if direction == 1: self.assertEqual( "Your order for 1000 shares of ASSET1 has been partially " "filled. 389 shares were successfully purchased. " "611 shares were not filled by the end of day and " "were canceled.", str(warnings[0].message) ) elif direction == -1: self.assertEqual( "Your order for -1000 shares of ASSET1 has been partially " "filled. 389 shares were successfully sold. " "611 shares were not filled by the end of day and " "were canceled.", str(warnings[0].message) )
def _load(self,filename): kwargs = dict(delimiter=[1,1,4,15,3,3,8,3,3,7],usecols=[1,2]+range(4,10),dtype=['S1']+[int]+6*[float]) if filename is None: raw = [] for basename in ['VII_239A/ngcpos.dat','VII_239A/icpos.dat']: filename = os.path.join(self.DATADIR,basename) raw.append(np.genfromtxt(filename,**kwargs)) raw = numpy.concatenate(raw) else: raw = numpy.genfromtxt(filename,**kwargs) self.filename = filename # Some entries are missing... raw['f4'] = numpy.where(numpy.isnan(raw['f4']),0,raw['f4']) raw['f7'] = numpy.where(numpy.isnan(raw['f7']),0,raw['f7']) self.data.resize(len(raw)) names = numpy.where(raw['f0'] == 'N', 'NGC %04i', 'IC %04i') self.data['name'] = numpy.char.mod(names,raw['f1']) ra = raw[['f2','f3','f4']].view(float).reshape(len(raw),-1) dec = raw[['f5','f6','f7']].view(float).reshape(len(raw),-1) self.data['ra'] = ugali.utils.projector.hms2dec(ra) self.data['dec'] = ugali.utils.projector.dms2dec(dec) glon,glat = cel2gal(self.data['ra'],self.data['dec']) self.data['glon'],self.data['glat'] = glon,glat #class Steinicke10(SourceCatalog): # """ # Another modern compilation of the New General Catalogue # (people still don't agree on the composition of NGC...) # """ # def _load(self,filename): # if filename is None: # filename = os.path.join(self.DATADIR,"NI2013.csv") # # raw = numpy.genfromtxt(filename,delimiter=',',usecols=[5,6]+range(13,20),dtype=['S1',int]+3*[float]+['S1']+3*[float]) # # self.data.resize(len(raw)) # names = numpy.where(raw['f0'] == 'N', 'NGC %04i', 'IC %04i') # self.data['name'] = numpy.char.mod(names,raw['f1']) # # sign = numpy.where(raw['f5'] == '-',-1,1) # ra = raw[['f2','f3','f4']].view(float).reshape(len(raw),-1) # dec = raw[['f6','f7','f8']].view(float).reshape(len(raw),-1) # dec[:,0] = numpy.copysign(dec[:,0], sign) # # self.data['ra'] = ugali.utils.projector.hms2dec(ra) # self.data['dec'] = ugali.utils.projector.dms2dec(dec) # # glon,glat = ugali.utils.projector.celToGal(self.data['ra'],self.data['dec']) # self.data['glon'],self.data['glat'] = glon,glat