我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用numpy.modf()。
def jd2dt(jd): """Convert julian date to datetime """ n = int(round(float(jd))) a = n + 32044 b = (4*a + 3)//146097 c = a - (146097*b)//4 d = (4*c + 3)//1461 e = c - (1461*d)//4 m = (5*e + 2)//153 day = e + 1 - (153*m + 2)//5 month = m + 3 - 12*(m//10) year = 100*b + d - 4800 + m/10 tfrac = 0.5 + float(jd) - n tfrac_s = 86400.0 * tfrac minfrac, hours = np.modf(tfrac_s / 3600.) secfrac, minutes = np.modf(minfrac * 60.) microsec, seconds = np.modf(secfrac * 60.) return datetime(year, month, day, int(hours), int(minutes), int(seconds), int(microsec*1E6)) #This has not been tested
def test_ufunc_override_out(self): # 2016-01-29: NUMPY_UFUNC_DISABLED return class A(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return kwargs class B(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return kwargs a = A() b = B() res0 = np.multiply(a, b, 'out_arg') res1 = np.multiply(a, b, out='out_arg') res2 = np.multiply(2, b, 'out_arg') res3 = np.multiply(3, b, out='out_arg') res4 = np.multiply(a, 4, 'out_arg') res5 = np.multiply(a, 5, out='out_arg') assert_equal(res0['out'], 'out_arg') assert_equal(res1['out'], 'out_arg') assert_equal(res2['out'], 'out_arg') assert_equal(res3['out'], 'out_arg') assert_equal(res4['out'], 'out_arg') assert_equal(res5['out'], 'out_arg') # ufuncs with multiple output modf and frexp. res6 = np.modf(a, 'out0', 'out1') res7 = np.frexp(a, 'out0', 'out1') assert_equal(res6['out'][0], 'out0') assert_equal(res6['out'][1], 'out1') assert_equal(res7['out'][0], 'out0') assert_equal(res7['out'][1], 'out1')
def test_numpy_ufunc_index(self): # 2016-01-29: NUMPY_UFUNC_DISABLED return # Check that index is set appropriately, also if only an output # is passed on (latter is another regression tests for github bug 4753) class CheckIndex(object): def __numpy_ufunc__(self, ufunc, method, i, inputs, **kw): return i a = CheckIndex() dummy = np.arange(2.) # 1 input, 1 output assert_equal(np.sin(a), 0) assert_equal(np.sin(dummy, a), 1) assert_equal(np.sin(dummy, out=a), 1) assert_equal(np.sin(dummy, out=(a,)), 1) assert_equal(np.sin(a, a), 0) assert_equal(np.sin(a, out=a), 0) assert_equal(np.sin(a, out=(a,)), 0) # 1 input, 2 outputs assert_equal(np.modf(dummy, a), 1) assert_equal(np.modf(dummy, None, a), 2) assert_equal(np.modf(dummy, dummy, a), 2) assert_equal(np.modf(dummy, out=a), 1) assert_equal(np.modf(dummy, out=(a,)), 1) assert_equal(np.modf(dummy, out=(a, None)), 1) assert_equal(np.modf(dummy, out=(a, dummy)), 1) assert_equal(np.modf(dummy, out=(None, a)), 2) assert_equal(np.modf(dummy, out=(dummy, a)), 2) assert_equal(np.modf(a, out=(dummy, a)), 0) # 2 inputs, 1 output assert_equal(np.add(a, dummy), 0) assert_equal(np.add(dummy, a), 1) assert_equal(np.add(dummy, dummy, a), 2) assert_equal(np.add(dummy, a, a), 1) assert_equal(np.add(dummy, dummy, out=a), 2) assert_equal(np.add(dummy, dummy, out=(a,)), 2) assert_equal(np.add(a, dummy, out=a), 0)
def main(self, input_rings, output_rings): """Generate a histogram from the input ring data @param[in] input_rings List with first ring containing data of interest. Must terminate before histogram is generated. @param[out] output_rings First ring in this list will contain the output histogram""" histogram = np.reshape( np.zeros(self.bins).astype(np.float32), (1, self.bins)) tstart = None for span in self.iterate_ring_read(input_rings[0]): nchans = self.data_settings['frame_shape'][0] if tstart is None: tstart = self.data_settings['tstart'] frequency = self.data_settings['fch1'] for chan in range(nchans): modified_tstart = tstart - self.calculate_delay( frequency, self.data_settings['fch1']) frequency -= self.data_settings['foff'] sort_indices = np.argsort( self.calculate_bin_indices( modified_tstart, self.data_settings['tsamp'], span.data.shape[1] / nchans)) sorted_data = span.data[0][chan::nchans][sort_indices] extra_elements = np.round(self.bins * (1 - np.modf( float(span.data.shape[1] / nchans) / self.bins)[0])).astype(int) sorted_data = insert_zeros_evenly(sorted_data, extra_elements) histogram += np.sum( sorted_data.reshape(self.bins, -1), 1).astype(np.float32) tstart += (self.data_settings['tsamp'] * self.gulp_size * 8 / self.data_settings['nbit'] / nchans) self.out_gulp_size = self.bins * 4 out_span_generator = self.iterate_ring_write(output_rings[0]) out_span = out_span_generator.next() bifrost.memory.memcpy( out_span.data_view(dtype=np.float32), histogram)
def o2dt(o): """Convert Python ordinal to datetime """ #omod = np.modf(o) #return datetime.fromordinal(int(omod[1])) + timedelta(days=omod[0]) #Note: num2date returns dt or list of dt #This funciton should always return a list #return np.array(matplotlib.dates.num2date(o)) return matplotlib.dates.num2date(o) #Return integer DOY (julian)
def doy2dt(yr, j): """Convert year + integer DOY (Julian) to datetime """ return o2dt(dt2o(datetime(int(yr), 1, 1))+j-1) #The solution below can't deal with jd>365 #jmod = np.modf(j) #return datetime.strptime(str(yr)+str(int(jmod[1])), '%Y%j') + timedelta(days=jmod[0])
def _format_label(x, precision=3): fmt_str = '%%.%dg' % precision if np.isinf(x): return str(x) elif com.is_float(x): frac, whole = np.modf(x) sgn = '-' if x < 0 else '' whole = abs(whole) if frac != 0.0: val = fmt_str % frac # rounded up or down if '.' not in val: if x < 0: return '%d' % (-whole - 1) else: return '%d' % (whole + 1) if 'e' in val: return _trim_zeros(fmt_str % x) else: val = _trim_zeros(val) if '.' in val: return sgn + '.'.join(('%d' % whole, val.split('.')[1])) else: # pragma: no cover return sgn + '.'.join(('%d' % whole, val)) else: return sgn + '%0.f' % whole else: return str(x)
def test_ufunc_override_out(self): # Temporarily disable __numpy_ufunc__ for 1.10; see gh-5844 return class A(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return kwargs class B(object): def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs): return kwargs a = A() b = B() res0 = np.multiply(a, b, 'out_arg') res1 = np.multiply(a, b, out='out_arg') res2 = np.multiply(2, b, 'out_arg') res3 = np.multiply(3, b, out='out_arg') res4 = np.multiply(a, 4, 'out_arg') res5 = np.multiply(a, 5, out='out_arg') assert_equal(res0['out'], 'out_arg') assert_equal(res1['out'], 'out_arg') assert_equal(res2['out'], 'out_arg') assert_equal(res3['out'], 'out_arg') assert_equal(res4['out'], 'out_arg') assert_equal(res5['out'], 'out_arg') # ufuncs with multiple output modf and frexp. res6 = np.modf(a, 'out0', 'out1') res7 = np.frexp(a, 'out0', 'out1') assert_equal(res6['out'][0], 'out0') assert_equal(res6['out'][1], 'out1') assert_equal(res7['out'][0], 'out0') assert_equal(res7['out'][1], 'out1')
def turning_points(mu, vv, Gv, Bv, dv=0.1): DD = np.sqrt(const.h/(8*mu*const.m_u*const.c*100))*1.0e10/np.pi # Gv spline gsp = splrep(vv, Gv, s=0) # Bv spline bsp = splrep(vv, Bv, s=0) # vibrational QN at which to evaluate turning points V = np.arange(dv-1/2, vv[-1], dv) # add a point close to v=-0.5, the bottom of the well V = np.append([-1/2+0.0001], V) Rmin = []; Rmax = []; E = [] # compute turning points using RKR method print(u"RKR: v Rmin(A) Rmax(A) E(cm-1)") for vib in V: E.append(G(vib, gsp)) # energy of vibrational level ff = fg_integral(vib, gsp, bsp, lambda x, y: 1) gg = fg_integral(vib, gsp, bsp, B) fg = np.sqrt(ff/gg + ff**2) Rmin.append((fg - ff)*DD) # turning points Rmax.append((fg + ff)*DD) frac, integ = np.modf(vib) if frac > 0 and frac < dv: print(u" {:d} {:6.4f} {:6.4f} {:6.2f}". format(int(vib), Rmin[-1], Rmax[-1], np.float(E[-1]))) return Rmin, Rmax, E
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ cycles = self.freq * ts + self.offset / PI2 frac, _ = numpy.modf(cycles) ys = self.amp * numpy.sign(unbias(frac)) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ cycles = self.freq * ts + self.offset / PI2 frac, _ = numpy.modf(cycles) ys = frac ys = normalize(unbias(ys), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ cycles = self.freq * ts + self.offset / PI2 frac, _ = numpy.modf(cycles) ys = frac**2 ys = normalize(unbias(ys), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ cycles = self.freq * ts + self.offset / PI2 frac, _ = numpy.modf(cycles) ys = frac**4 * (1-frac) ys = normalize(unbias(ys), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ cycles = self.freq * ts frac, _ = numpy.modf(cycles) ys = numpy.abs(frac - 0.5) ys = normalize(unbias(ys), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ ts = np.asarray(ts) cycles = self.freq * ts + self.offset / PI2 frac, _ = np.modf(cycles) ys = self.amp * np.sign(unbias(frac)) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ ts = np.asarray(ts) cycles = self.freq * ts + self.offset / PI2 frac, _ = np.modf(cycles) ys = normalize(unbias(frac), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ ts = np.asarray(ts) cycles = self.freq * ts + self.offset / PI2 frac, _ = np.modf(cycles) ys = (frac - 0.5)**2 ys = normalize(unbias(ys), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ ts = np.asarray(ts) cycles = self.freq * ts + self.offset / PI2 frac, _ = np.modf(cycles) ys = frac**4 * (1-frac) ys = normalize(unbias(ys), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ ts = np.asarray(ts) cycles = self.freq * ts + self.offset / PI2 frac, _ = np.modf(cycles) ys = np.abs(frac - 0.5) ys = normalize(unbias(ys), self.amp) return ys
def evaluate(self, ts): """Evaluates the signal at the given times. ts: float array of times returns: float wave array """ ts = np.asarray(ts) cycles = self.freq * ts + self.offset / PI2 frac, _ = np.modf(cycles) ys = frac**2 * (1-frac) ys = normalize(unbias(ys), self.amp) return ys
def ipart(x): """Return integer part of given number.""" return np.modf(x)[1]
def next_batch(self, batch_size = 50) : start = self._index_in_epoch if ( self._epochs_completed == 0 ) and ( start == 0 ) : self.batch_size = batch_size while np.modf(float(self._ndata)/self.batch_size)[0] > 0.0 : print 'Warning! Number of data/ batch size must be an integer.' print 'number of data: %d' % self._ndata print 'batch size: %d' % self.batch_size self.batch_size = int(input('Input new batch size: ')) print 'batch size : %d' % self.batch_size print 'number of data: %d' % self._ndata self._index_in_epoch += self.batch_size if self._index_in_epoch > self._ndata : # Number of training epochs completed self._epochs_completed += 1 # Shuffle data random.shuffle(self.shuffle_index) self._images = self._images[self.shuffle_index] self._labels = self._labels[self.shuffle_index] # Reinitialize conunter start = 0 self._index_in_epoch = self.batch_size assert self.batch_size <= self._ndata end = self._index_in_epoch return self._images[start:end], self._labels[start:end]
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 interp( self, nH, T ): nH = np.array( nH ) T = np.array( T ) if nH.size != T.size: raise ValueError(' owls_ion_tables: array size mismatch !!! ') # field discovery will have nH.size == 1 and T.size == 1 # in that case we simply return 1.0 if nH.size == 1 and T.size == 1: ionfrac = 1.0 return ionfrac # find inH and fnH #----------------------------------------------------- x_nH = ( nH - self.nH[0] ) / self.DELTA_nH x_nH_clip = np.clip( x_nH, 0.0, self.nH.size-1.001 ) fnH,inH = np.modf( x_nH_clip ) inH = inH.astype( np.int32 ) # find iT and fT #----------------------------------------------------- x_T = ( T - self.T[0] ) / self.DELTA_T x_T_clip = np.clip( x_T, 0.0, self.T.size-1.001 ) fT,iT = np.modf( x_T_clip ) iT = iT.astype( np.int32 ) # short names for previously calculated iz and fz #----------------------------------------------------- iz = self.iz fz = self.fz # calculate interpolated value # use tri-linear interpolation on the log values #----------------------------------------------------- ionfrac = self.ionbal[inH, iT, iz ] * (1-fnH) * (1-fT) * (1-fz) + \ self.ionbal[inH+1, iT, iz ] * (fnH) * (1-fT) * (1-fz) + \ self.ionbal[inH, iT+1, iz ] * (1-fnH) * (fT) * (1-fz) + \ self.ionbal[inH, iT, iz+1] * (1-fnH) * (1-fT) * (fz) + \ self.ionbal[inH+1, iT, iz+1] * (fnH) * (1-fT) * (fz) + \ self.ionbal[inH, iT+1, iz+1] * (1-fnH) * (fT) * (fz) + \ self.ionbal[inH+1, iT+1, iz] * (fnH) * (fT) * (1-fz) + \ self.ionbal[inH+1, iT+1, iz+1] * (fnH) * (fT) * (fz) return 10**ionfrac
def next_dose(self, batch_size = 50) : def convert_to_one_hot( label ) : label_one_hot = np.zeros((len(label),2)) for i in range(len(label)) : label_one_hot[i,label[i]] = 1 return label_one_hot start = self._index_in_datafile if ( self._file_index == self.start_file_index ) and ( start == 0 ) : self.batch_size = batch_size while np.modf(float(self.nrows)/self.batch_size)[0] > 0.0 : print 'Warning! Number of data per file/ dose size must be an integer.' print 'number of data per file: %d' % self.nrows print 'dose size: %d' % self.batch_size self.batch_size = int(input('Input new dose size: ')) print 'dose size : %d' % self.batch_size print 'number of data: %d' % self._ndata # Read in one file at a time data = np.genfromtxt(self.full_file_path%(self._file_index) ,dtype=int, skip_header=0, skip_footer=0) self._images = data[:,:-1].astype('int') labels = data[:,-1:].astype('int') if self.convert_to_one_hot : self._labels = convert_to_one_hot(labels) self._index_in_datafile += self.batch_size if self._index_in_datafile > self.nrows : self._file_index += 1 start = 0 self._index_in_datafile = self.batch_size assert self.batch_size <= self.nrows # Read in one file at a time data = np.genfromtxt(self.full_file_path%(self._file_index) ,dtype=int, skip_header=0, skip_footer=0) self._images = data[:,:-1].astype('int') labels = data[:,-1:].astype('int') if self.convert_to_one_hot : self._labels = convert_to_one_hot(labels) # Shufle data random.shuffle(self.shuffle_index_dose) self._images = self._images[self.shuffle_index_dose] self._labels = self._labels[self.shuffle_index_dose] if self._file_index > self.end_file_index : # Number of training epochs completed self._epochs_completed += 1 self._file_index = self.start_file_index # Reinitialize conunter start = 0 self._index_in_datafile = self.batch_size end = self._index_in_datafile return self._images[start:end], self._labels[start:end]
def next_dose_old(self, batch_size = 50) : def convert_to_one_hot( label ) : label_one_hot = np.zeros((len(label),2)) for i in range(len(label)) : label_one_hot[i,label[i]] = 1 return label_one_hot start = self._index_in_datafile if ( self._file_index == self.start_file_index ) and ( start == 0 ) : self.batch_size = batch_size while np.modf(float(self.nrows)/self.batch_size)[0] > 0.0 : print 'Warning! Number of data per file/ dose size must be an integer.' print 'number of data per file: %d' % self.nrows print 'dose size: %d' % self.batch_size self.batch_size = int(input('Input new dose size: ')) print 'dose size : %d' % self.batch_size print 'number of data: %d' % self._ndata self.shuffle_index_dose_old = np.arange(0,self.batch_size,1) self._index_in_datafile += self.batch_size if self._index_in_datafile > self.nrows : self._file_index += 1 start = 0 self._index_in_datafile = self.batch_size assert self.batch_size <= self.nrows if self._file_index > self.end_file_index : # Number of training epochs completed self._epochs_completed += 1 self._file_index = self.start_file_index # Reinitialize conunter start = 0 self._index_in_datafile = self.batch_size end = self._index_in_datafile # Read in small dosage of data data = np.genfromtxt(self.full_file_path%(self._file_index) ,dtype=int, skip_header=start, skip_footer=self.nrows-end) self._images = data[:,:-1].astype('int') labels = data[:,-1:].astype('int') if self.convert_to_one_hot : self._labels = convert_to_one_hot(labels) # Shufle data random.shuffle(self.shuffle_index_dose_old) self._images = self._images[self.shuffle_index_dose_old] self._labels = self._labels[self.shuffle_index_dose_old] return self._images, self._labels