我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用numpy.remainder()。
def createRFmask(self): center_row = int(self.newSimulation.Params['N']/2.0) center_col = int(self.newSimulation.Params['N']/2.0) for cell in np.arange(self.newSimulation.Params['N']*self.newSimulation.Params['N']): row = int(cell/self.newSimulation.Params['N']) col = np.remainder(cell,self.newSimulation.Params['N']) if(row >= center_row - self.mask_side and row<= center_row + self.mask_side and col >= center_col - self.mask_side and col<= center_col + self.mask_side): self.RF_mask.append([row,col]) # print ("self.RF_mask = ",self.RF_mask) # Create input stimulus and simulate photoreceptors' response
def test_remainder_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): if sg1 == -1 and dt1 in np.typecodes['UnsignedInteger']: continue if sg2 == -1 and dt2 in np.typecodes['UnsignedInteger']: continue fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1) b = np.array(sg2*19, dtype=dt2) div = np.floor_divide(a, b) rem = np.remainder(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg)
def test_float_remainder_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for dt in np.typecodes['Float']: msg = 'dtype: %s' % (dt,) fa = a.astype(dt) fb = b.astype(dt) div = np.floor_divide(fa, fb) rem = np.remainder(fa, fb) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg)
def test_float_remainder_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1) b = np.array(sg2*6e-8, dtype=dt2) div = np.floor_divide(a, b) rem = np.remainder(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg)
def one_melody_matrix(track_id): tchr, chroma, t, melody = aligned_pitch_features(track_id) melody = np.round(melody) pitched = melody > 0 pitchclass = np.remainder(melody - 69, 12) framerate = 1.0/(t[1]-t[0]) nmel = len(melody) vals = np.ones(nmel)[pitched] vals *= 1.0 / framerate rows = np.arange(nmel)[pitched] cols = pitchclass[pitched] melmat = csr_matrix((vals, (rows, cols)), shape=(nmel, 12)) return t, melmat.todense()
def frame_to_state_mapping(shift_file, lab_file, fs, states_per_phone=5): #Read files: v_shift = lu.read_binfile(shift_file, dim=1) v_pm = la.shift_to_pm(v_shift) m_state_times = np.loadtxt(lab_file, usecols=(0,1)) # to miliseconds: v_pm_ms = 1000 * v_pm / fs m_state_times_ms = m_state_times / 10000.0 # Compare: nfrms = len(v_pm_ms) v_st = np.zeros(nfrms) - 1 # init for f in xrange(nfrms): vb_greater = (v_pm_ms[f] >= m_state_times_ms[:,0]) # * (v_pm_ms[f] < m_state_times_ms[:,1]) state_nx = np.where(vb_greater)[0][-1] v_st[f] = np.remainder(state_nx, states_per_phone) return v_st #==============================================================================
def test_float_remainder_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = np.remainder(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = np.remainder(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with warnings.catch_warnings(): warnings.simplefilter('always') warnings.simplefilter('ignore', RuntimeWarning) for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = np.remainder(fone, fzer) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) # MSVC 2008 returns NaN here, so disable the check. #rem = np.remainder(fone, finf) #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem)) rem = np.remainder(fone, fnan) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) rem = np.remainder(finf, fone) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
def __mod__(self, other): return remainder(self, other)
def __imod__(self, other): return remainder(self, other, self)
def __rmod__(self, other): return remainder(other, self)
def gridF(fs, csf): """ Concatenates PSF kernels to one 2d image, potentially useful for plotting. -------------------------------------------------------------------------- Usage: Call: gridF(fs, csf) Input: fs PSF kernels, i.e. 3d array with kernels indexed by 0th index csf size of kernels in x and y direction Output: 2d image with PSF kernels arranged according to csf -------------------------------------------------------------------------- Copyright (C) 2011 Michael Hirsch """ f = np.ones((fs.shape[1]*csf[0],fs.shape[2]*csf[1])) for i in range(np.prod(csf)): k = i/csf[1] l = np.remainder(i,csf[1]) f[k * fs.shape[1]:(k+1)*fs.shape[1], l * fs.shape[2]:(l+1)*fs.shape[2]] = fs[i,:,:] return f
def modTwo(C): """Q & D way to Mod 2 all results""" D = C.copy() D.fill(2) return np.remainder(C,D)
def gravityeffect(h0,s0,p0,tl,amp,phases): """ purpose: To compute the gravity effect due to each tidal component. """ dtor = np.pi/180 R90 = np.pi/2 R360 = np.pi*2 p0 = np.remainder(p0,R360) h0 = np.remainder(h0,R360) s0 = np.remainder(s0,R360) tl = np.remainder(tl,R360) arg=np.zeros(11) # argument component arg[0] = 2*tl - 2*s0 # M2 arg[1] = 2*tl - 2*h0 # S2 arg[2] = tl - R90 # K1 arg[3] = tl - 2*s0 + R90 # O1 arg[4] = 2*tl - 3*s0 + p0 # N2 arg[5] = tl - 2*h0 + R90 # P1 arg[6] = 2*tl # K2 arg[7] = tl - 3*s0 + p0 +R90 # Q1 arg[8] = 2*s0 # Mf arg[9] = s0 - p0 # Mm arg[10] = 2*h0 # Ssa totaleffect=np.sum([amp[i]*np.cos(arg[i] - phases[i]*dtor) for i in range(len(arg))]) return totaleffect
def keepParticlesInCell(positions): for p in range(config.nParticles): positions[p,:] = np.remainder(positions[p,:], config.lCalc); # Calculate the forces. Jitted to make is super fast # Code has been based on: http://combichem.blogspot.nl/2013/04/fun-with-numba-numpy-and-f2py.html
def lanczosIndexedShift( params ): """ lanczosIndexedShift( params ) params = (index, imageStack, translations, kernelShape=3, lobes=None) imageStack = input 3D numpy array translations = [y,x] shift, recommened not to exceed 1.0, should be float Random values of kernelShape and lobes gives poor performance. Generally the lobes has to increase with the kernelShape or you'll get a lowpass filter. Generally lobes = (kernelShape+1)/2 kernelShape=3 and lobes=2 is a lanczos2 kernel, it has almost no-lowpass character kernelShape=5 and lobes=3 is a lanczos3 kernel, it's the typical choice Anything with lobes=1 is a low-pass filter, but next to no ringing artifacts If you cheat and pass in rounded shifts only the roll will be performed, so this can be used to accelerate roll as well in a parallel environment. """ if len( params ) == 3: [index, imageStack, translations] = params kernelShape = 3 lobes = None elif len( params ) == 4: [index, imageStack, translations, kernelShape] = params lobes = None elif len( params ) == 5: [index, imageStack, translations, kernelShape, lobes] = params integer_trans = np.round( translations[index,:] ).astype('int') # Integer shift imageStack[index,:,:] = np.roll( np.roll( imageStack[index,:,:], integer_trans[0], axis=0 ), integer_trans[1], axis=1 ) # Subpixel shift remain_trans = np.remainder( translations[index,:], 1) if not (np.isclose( remain_trans[0], 0.0) and np.isclose( remain_trans[1], 0.0) ): kernel = lanczosSubPixKernel( remain_trans, kernelShape=kernelShape, lobes=lobes ) # RAM: I tried to use the out= keyword but it's perhaps not thread-safe. imageStack[index,:,:] = scipy.ndimage.convolve( imageStack[index,:,:], kernel, mode='reflect' )
def test_float_remainder_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = np.remainder(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = np.remainder(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = np.remainder(fone, fzer) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) # MSVC 2008 returns NaN here, so disable the check. #rem = np.remainder(fone, finf) #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem)) rem = np.remainder(fone, fnan) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) rem = np.remainder(finf, fone) assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
def frame_to_state_mapping2(shift_file, state_lab_file, fs, states_per_phone=5, b_refine=True): #Read files: v_shift = lu.read_binfile(shift_file, dim=1) v_pm = la.shift_to_pm(v_shift) m_state_times = np.loadtxt(state_lab_file, usecols=(0,1)) # to miliseconds: v_pm_ms = 1000 * v_pm / fs m_state_times_ms = m_state_times / 10000.0 # Compare: nfrms = len(v_pm_ms) v_st = np.zeros(nfrms) - 1 # init for f in xrange(nfrms): vb_greater = (v_pm_ms[f] >= m_state_times_ms[:,0]) # * (v_pm_ms[f] < m_state_times_ms[:,1]) state_nx = np.where(vb_greater)[0][-1] v_st[f] = np.remainder(state_nx, states_per_phone) # Refining: if b_refine: state_len_ms = m_state_times_ms[state_nx,1] - m_state_times_ms[state_nx,0] fine_pos = ( v_pm_ms[f] - m_state_times_ms[state_nx,0] ) / state_len_ms v_st[f] += fine_pos # Protection against wrong ended label files: np.clip(v_st, 0, states_per_phone, out=v_st) return v_st #==============================================================================
def mand2pixmap(self,width:int,height:int, mand, maxiter:int, pixmap, progress, e): pen=[] pen.append(qRgb(0,0,0)) maxcol=len(colormap) for i in range(maxcol): (r,g,b)=colormap[(i+self.coffset)%maxcol] pen.append(qRgb(r,g,b)) z = np.full((width, height),maxcol, dtype=int) mand2 = np.remainder(mand, z) mand2[mand==0]=-1 mand2 = np.add(mand2, np.ones((width, height), int)) st=100/height im=QImage(height, width, QImage.Format_RGB888) for j in range(0,height-1,5): for i in range(width): im.setPixel(height-j-1,width-i-1,pen[mand2[i,j]]) im.setPixel(height-j-2,width-i-1,pen[mand2[i,j+1]]) im.setPixel(height-j-3,width-i-1,pen[mand2[i,j+2]]) im.setPixel(height-j-4,width-i-1,pen[mand2[i,j+3]]) im.setPixel(height-j-5,width-i-1,pen[mand2[i,j+4]]) progress.setValue(st*j) e.processEvents() p = QPainter() p.begin(pixmap) p.drawImage(QPoint(0,0),im) self.bild.update()
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 ang2pix_ring_single(nside, theta, phi): """Calculate the pixel indexes in RING ordering scheme for one single pair of angular coordinate on the sphere. Parameters ---------- theta : float The polar angle (i.e., latitude), ? ? [0, ?]. (unit: rad) phi : float The azimuthal angle (i.e., longitude), ? ? [0, 2?). (unit: rad) Returns ------- ipix : int The index of the pixel corresponding to the input coordinate. NOTE ---- * Only support the *RING* ordering scheme * This is the JIT-optimized version that partially replaces the ``healpy.ang2pix`` References ---------- - HEALPix software: ``src/C/subs/chealpix.c``: ``ang2pix_ring_z_phi()`` http://healpix.sourceforge.net/ """ z = np.cos(theta) # colatitude za = np.absolute(z) tt = (2.0 / np.pi) * np.remainder(phi, 2*np.pi) # range: [0, 4) if za <= 2.0/3.0: # Equatorial region temp1 = nside * (tt + 0.5) temp2 = nside * z * 0.75 jp = int(temp1 - temp2) # Index of ascending edge line jm = int(temp1 + temp2) # Index of descending edge line # Ring number counted from z=2/3 iring = nside + 1 + jp - jm # range: [1, 2n+1] kshift = 1 - (iring & 1) # kshift=1 if ir even, 0 otherwise ip = int((jp + jm - nside + kshift + 1) / 2) ip = np.remainder(ip, 4*nside) ipix = nside * (nside-1) * 2 + (iring-1) * 4 * nside + ip else: # North & South polar caps tp = tt - int(tt) tmp = nside * np.sqrt(3 * (1-za)) jp = int(tp * tmp) jm = int((1.0-tp) * tmp) # Ring number counted from the closest pole iring = jp + jm + 1 ip = int(tt * iring) ip = np.remainder(ip, 4*iring) # if z > 0: ipix = 2 * iring * (iring-1) + ip else: ipix = 12 * nside * nside - 2 * iring * (iring+1) + ip # return ipix
def compute(self, X=[]): if len(X)==0: X=self.data else: pass originalLength=X.shape[0] originalWidth=self.weightsOpenCL.shape[0] if not self.openCL.active: raise Exception('openCL not active') #=================================================================== # networks=self.weights.wHL.shape[0] # phiOL=np.empty((X.shape[0], networks)) # for i0 in range(networks): # aHL=X.dot(self.weights.wHL[i0,:,:])+np.tile(self.weights.bHL[i0,],(X.shape[0],1)) # phiHL=self._activate(aHL,0) # aOL=phiHL.dot(self.weights.wOL[:,i0])+self.weights.bOL[i0,] # phiOL[:,i0]=self._activate(aOL,1) #=================================================================== else: remData=np.remainder(X.shape[0],self.openCL.workGroup[0]) if remData != 0: X=np.vstack((X, np.zeros((self.openCL.workGroup[0]-remData, X.shape[1])))) else: remData=self.openCL.workGroup[0] remNetwork=np.remainder(self.weightsOpenCL.shape[0],self.openCL.workGroup[1]) if remNetwork != 0: weights=np.vstack((self.weightsOpenCL, np.zeros((self.openCL.workGroup[1]-remNetwork, self.weightsOpenCL.shape[1])))) else: weights=self.weightsOpenCL remNetwork=self.openCL.workGroup[1] XOpenCL=X.reshape(-1, order = 'C').astype(np.float32) weightsOpenCL=weights.reshape(-1, order = 'C').astype(np.float32) mf = cl.mem_flags inputs=np.int32(X.shape[1]) nodes=np.int32(self.nodes) dataSize=np.int32(X.shape[0]) weightSize=np.int32(self.weightsOpenCL.shape[1]) dataBuffer = cl.Buffer(self.openCL.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=XOpenCL) weightsBuffer = cl.Buffer(self.openCL.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=weightsOpenCL) outBuffer = cl.Buffer(self.openCL.ctx, mf.WRITE_ONLY, int(XOpenCL.nbytes/inputs*weights.shape[0])) kernel=self.openCL.prg.ann globalSize=(int(X.shape[0]), int(weights.shape[0])) localSize=(int(self.openCL.workGroup[0]), int(self.openCL.workGroup[1])) kernel(self.openCL.queue, globalSize, localSize, inputs, nodes, dataSize, weightSize, dataBuffer, outBuffer, weightsBuffer, cl.LocalMemory(self.weightsOpenCL[0,].nbytes*localSize[1])) phiOL = np.empty((np.prod(globalSize),)).astype(np.float32) cl.enqueue_copy(self.openCL.queue, phiOL, outBuffer) phiOL=np.reshape(phiOL, globalSize, order='F')[:originalLength,:originalWidth] if self.lowerThreshold!=-999: phiOL[phiOL<self.lowerThreshold] = self.lowerThreshold return phiOL
def pbc_wrap_coords(coords_frac, copy=True, mask=[True]*3, xyz_axis=-1): """Apply periodic boundary conditions to array of fractional coords. Wrap atoms with fractional coords > 1 or < 0 into the cell. Parameters ---------- coords_frac : array 2d or 3d fractional coords, if 3d then one axis is assumed to be a time axis and the array is a MD trajectory or such copy : bool Copy coords_frac before applying pbc. mask : sequence of bools, len = 3 for x,y,z Apply pbc only x, y or z. E.g. [True, True, False] would not wrap the z coordinate. xyz_axis : the axis of `coords_frac` where the indices 0,1,2 pull out the x,y,z coords. For a usual 2d array of coords with shape (natoms,3), xyz_axis=1 (= last axis = -1). For a 3d array (natoms, nstep, 3), xyz_axis=2 (also -1). Returns ------- coords_frac : array_like(coords_frac) Array with all values in [0,1] except for those where ``mask[i]=False``. Notes ----- About the copy arg: If ``copy=False``, then this is an in-place operation and the array in the global scope is modified! In fact, then these do the same:: >>> a = pbc_wrap_coords(a, copy=False) >>> pbc_wrap_coords(a, copy=False) """ assert coords_frac.shape[xyz_axis] == 3, "dim of xyz_axis of `coords_frac` must be == 3" ndim = coords_frac.ndim assert ndim in [2,3], "coords_frac must be 2d or 3d array" tmp = coords_frac.copy() if copy else coords_frac for i in range(3): if mask[i]: sl = [slice(None)]*ndim sl[xyz_axis] = i tmp[sl] = np.remainder(tmp[sl], 1.0) return tmp