• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python scipy.arange函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中scipy.arange函数的典型用法代码示例。如果您正苦于以下问题:Python arange函数的具体用法?Python arange怎么用?Python arange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了arange函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: range_query_geno_local

 def range_query_geno_local(self, idx_start=None, idx_end=None, chrom=None,pos_start=None, pos_end=None,windowsize=0):
     """
     return an index for a range query on the genotypes
     """
     if idx_start==None and idx_end==None and pos_start==None and pos_end==None and chrom==None:
         return  sp.arange(0,self.num_snps)
     elif idx_start is not None or idx_end is not None:
         if idx_start is None:
             idx_start = 0
         if idx_end is None:
             idx_end = self.num_snps
         res =  sp.arange(idx_start,idx_end)
         return res
     elif chrom is not None:
         res = self.geno_pos["chrom"]==chrom
     elif pos_start is not None or pos_end is not None:
         if pos_start is not None and pos_end is not None:
             assert pos_start[0] == pos_end[0], "chromosomes have to match"
         
         if pos_start is None:
             idx_larger =  sp.ones(self.num_snps,dtype=bool)
         else:
             idx_larger = (self.geno_pos["pos"]>=(pos_start[1]-windowsize)) & (self.geno_pos["chrom"]==pos_start[0])
         if pos_end is None:
             idx_smaller =  sp.ones(self.num_snps,dtype=bool)
         else:
             idx_smaller = (self.geno_pos["pos"]<=(pos_end[1]+windowsize)) & (self.geno_pos["chrom"]==pos_end[0])
         res = idx_smaller & idx_larger
     else:
         raise Exception("This should not be triggered")#res =  sp.ones(self.geno_pos.shape,dtype=bool)
     return  sp.where(res)[0]
开发者ID:MMesbahU,项目名称:limix,代码行数:31,代码来源:data.py


示例2: audio_cb

    def audio_cb(self, data):
        rospy.loginfo("Callback received!")
        print "<Previous y_data len: " + str(len(self.y_data))
        self.y_data.extend(data.data)
        #self.y_data = data.data
        print ">After y_data len: " + str(len(self.y_data))
        
        print "--------------"
        print "len of y_data: " + str(len(self.y_data))
        excess_of_data = None
        if len(self.y_data) > self.MAX_DATA:
            print "excess of data: " + str(len(self.y_data) - self.MAX_DATA)
            excess_of_data = len(self.y_data) - self.MAX_DATA
#             self.x_data = arange(self.x_data[excess_of_data], (len(self.x_data) - 1) * 0.01, 0.01).tolist()
            self.y_data = self.y_data[excess_of_data:]
            
        print "<Previous x_data len: " + str(len(self.x_data))
        if excess_of_data:
            new_times = arange(self.x_data[-1], len(self.y_data) * 0.01 + self.x_data[-1], 0.01).tolist()
            print "Initial time: " + str(self.x_data[-1])
            self.x_data = new_times[:len(self.y_data)]
            print "Final time: "+ str(self.x_data[-1])
            
        else: # if we are just adding data to the array
            new_times = arange(self.x_data[-1], len(data.data) * 0.01 + self.x_data[-1], 0.01).tolist()
            self.x_data.extend(new_times[:len(self.y_data)])
        print ">After x_data len: " + str(len(self.x_data))
        
        if len(self.x_data) != len(self.y_data):
            rospy.logerr("Error, not same size")
            exit(0)
开发者ID:awesomebytes,项目名称:nao_audio_to_audio_common,代码行数:31,代码来源:plot_stream.py


示例3: test_covariate_shift

    def test_covariate_shift(self):
        n_sample = 100
        # Biased training
        var_bias = .5**2
        mean_bias = .7
        x_train = SP.random.randn(n_sample)*SP.sqrt(var_bias) + mean_bias
        y_train = self.complete_sample(x_train)

        # Unbiased test set
        var = .3**2
        mean = 0

        x_test = SP.random.randn(n_sample)*SP.sqrt(var) + mean
        x_complete = SP.hstack((x_train, x_test))

        kernel = utils.getQuadraticKernel(x_complete, d=1) +\
            10 * SP.dot(x_complete.reshape(-1, 1), x_complete.reshape(1, -1))
        kernel = utils.scale_K(kernel)
        kernel_train = kernel[SP.ix_(SP.arange(x_train.size),
                                     SP.arange(x_train.size))]
        kernel_test = kernel[SP.ix_(SP.arange(x_train.size, x_complete.size),
                             SP.arange(x_train.size))]

        mf = MF(n_estimators=100, kernel=kernel_train, min_depth=0,
                subsampling=False)
        mf.fit(x_train.reshape(-1, 1), y_train.reshape(-1, 1))
        response_gp = mf.predict(x_test.reshape(-1, 1), kernel_test, depth=0)
        self.assertTrue(((response_gp - self.polynom(x_test))**2).sum() < 2.4)
开发者ID:PMBio,项目名称:limix,代码行数:28,代码来源:test_lmm_forest.py


示例4: save_plotSpectrum

def save_plotSpectrum(y,Fs,image_name):
    """
    Plots a Single-Sided Amplitude Spectrum of y(t)
    """
    fig = Figure(linewidth=0.0)
    fig.set_size_inches(fig_width,fig_length, forward=True)
    Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace)
    n = len(y) # length of the signal

    _subplot = fig.add_subplot(2,1,1)        
    print "Fi"
    _subplot.plot(arange(0,n),y)
    xlabel('Time')
    ylabel('Amplitude')
    _subploti_2=fig.add_subplot(2,1,2)
    k = arange(n)
    T = n/Fs
    frq = k/T # two sides frequency range
    frq = frq[range(n/2)] # one side frequency range

    Y = fft(y)/n # fft computing and normalization
    Y = Y[range(n/2)]

    _subplot_2.plot(frq,abs(Y),'r') # plotting the spectrum
    xlabel('Freq (Hz)')
    ylabel('|Y(freq)|')
    print "here"
    canvas = FigureCanvasAgg(fig)
    if '.eps' in outfile_name:
        canvas.print_eps(outfile_name, dpi = 110)
    if '.png' in outfile_name:
        canvas.print_figure(outfile_name, dpi = 110)
开发者ID:FomkaV,项目名称:wifi-arsenal,代码行数:32,代码来源:non_wifi_interference_analysis.py


示例5: test_rigged_pointing

 def test_rigged_pointing(self) :
     Data = self.blocks[0]
     Data.calc_freq()
     map = self.map
     # Set all data = (f + cal_ind)*time_ind
     Data.data[:,:,:,:] = (sp.arange(-4.5, 5)
                           [:,sp.newaxis,sp.newaxis,sp.newaxis]
                           *(Data.freq/100e6))
     Data.data[...] -= sp.mean(Data.data, 0)
     Data.data[...] += (sp.arange(6,8).reshape((1,1,2,1)) * (Data.freq/100e6) 
                        * sp.arange(-4.5, 5).reshape((10, 1, 1, 1)))
     map[:,:,:] = 0.0
     # Set 10 pixels to match data (except for cal_ind part).
     map[:, range(10), range(10)] = (sp.arange(-4.5, 5)[None,:]
                                     * map.get_axis('freq')[:,None]/100e6)
     # We should be completely insensitive to the map mean.  Th following
     # should have no effect.
     map[...] += 0.352*map.get_axis('freq')[:, None, None]/800.0e7
     # Rig the pointing to point to those 10 pixels.
     def rigged_pointing() :
         Data.ra = map.get_axis('ra')[range(10)]
         Data.dec = map.get_axis('dec')[range(10)]
     Data.calc_pointing = rigged_pointing
     smd.sub_map(Data, map)
     # Now data should be just f*time_ind*(cal_ind+6), within 2.0 MHz/2.
     Data.data /= sp.arange(-4.5, 5)[:,sp.newaxis,sp.newaxis,sp.newaxis]
     Data.data /= Data.freq/100e6
     # Relative tol of 1/700, is the frequency bin width.
     self.assertTrue(sp.allclose(Data.data[:,:,0,:], 6.0, rtol=1.0/700))
     self.assertTrue(sp.allclose(Data.data[:,:,1,:], 7.0, rtol=1.0/700))
开发者ID:OMGitsHongyu,项目名称:analysis_IM,代码行数:30,代码来源:test_subtract_map_data.py


示例6: setUp

 def setUp(self):
     # Make a positive definite noise matrix, clean map, and dirty_map.
     self.nra = 10
     self.ndec = 5
     self.nf = 20
     self.shape = (self.nf, self.nra, self.ndec)
     self.size = self.nra * self.ndec * self.nf
     # Clean map.
     clean_map = sp.empty(self.shape, dtype=float)
     clean_map = al.make_vect(clean_map, axis_names=('freq', 'ra', 'dec'))
     clean_map[...] = sp.sin(sp.arange(self.nf))[:,None,None]
     clean_map *= sp.cos(sp.arange(self.nra))[:,None]
     clean_map *= sp.cos(sp.arange(self.ndec))
     # Noise inverse matrix.
     noise_inv = sp.empty(self.shape * 2, dtype=float)
     noise_inv = al.make_mat(noise_inv, axis_names=('freq', 'ra', 'dec')*2,
                             row_axes=(0, 1, 2), col_axes=(3, 4, 5))
     rand_mat = rand.randn(*((self.size,) * 2))
     information_factor = 1.e6  # K**-2
     rand_mat = sp.dot(rand_mat, rand_mat.transpose()) * information_factor
     noise_inv.flat[...] = rand_mat.flat
     # Dirty map.
     dirty_map = al.partial_dot(noise_inv, clean_map)
     # Store in self.
     self.clean_map = clean_map
     self.noise_inv = noise_inv
     self.dirty_map = dirty_map
开发者ID:OMGitsHongyu,项目名称:analysis_IM,代码行数:27,代码来源:test_clean_map.py


示例7: waveGen

def waveGen():
	n = 4096			# samples
	freq0 = 0 	# Hz
	samp_rate = 64	# Hz
	levels = 8

	start_freq = 1	# Hz
	end_freq = 2	# Hz
	if (start_freq != end_freq):
		freq0 = arange(start_freq, end_freq, (end_freq - start_freq) / (n * 1.0))
	else:
		freq0 = start_freq


	factor0 = samp_rate / freq0
	time = arange(n)/float(samp_rate)
	wave0 = sin(2 * pi * freq0 * time)

	# errors = [random() - 0.5 for _ in range(n)]
	# wave0 += errors

	sampleList = list()
	for t in arange(len(time)):
		sample = [time[t], wave0[t]]
		sampleList.append(sample)

	return sampleList
开发者ID:chris-smith,项目名称:ShakingTable,代码行数:27,代码来源:test_local_new.py


示例8: numProj

	def numProj(self, ang=5, sym='d7', with_mirror=False):
		csym = abs(float(sym[1:]))
		ang = abs(float(ang))
		if ang == 0.0:
			return 0
		angrad = ang*math.pi/180.0
		maxalt = math.pi/2.0 + angrad/1.99
		maxaz = 2.0*math.pi/csym
		if sym[0].lower() == 'd':
			maxaz /= 2.0
		numproj = 0
		for alt in arange(0.0, maxalt, angrad):
			if alt < 1.0e-6:
				### only one for top projection
				numproj+=1
				continue
			### calculate number of steps
			numsteps = math.floor(360.0/(ang*1.1547));
			numsteps = math.floor(numsteps * math.sin(alt) + 0.5)
			if numsteps < 1.0e-3:
				### only valid for c1, d1, c2 and d2
				numsteps = 1.0
			numsteps = csym * math.floor(numsteps/csym + 0.5) + 1.0e-6
			### calculate azimuthal step size
			azstep = 2.0*math.pi/numsteps
			if (maxaz/azstep) < 2.8:
				### if less than 2.8 steps, use 2 steps
				azstep = maxaz/2.1
			for az in arange(0.0, maxaz-azstep/4.0, azstep):
				if not with_mirror and az > math.pi-1.0e-3 and abs(alt-math.pi/2.0) < 1.0e-3:
					### ignore half of the equator
					continue
				numproj+=1

		return numproj
开发者ID:leschzinerlab,项目名称:myami-3.2-freeHand,代码行数:35,代码来源:createSyntheticDataset.py


示例9: gqr

def gqr(A):
	"""Finds the QR decomposition of A using Givens rotations.
	input: 	A, mxn array with m>=n
	output: Q, orthogonal mxm array
	        R, upper triangular mxn array
	        s.t QR = A
	"""
	def rotate(i,k,B):
	# create the Givens rotation matrix G to zero out the i,k entry of B
		c,s,r = solve(B[k,k],B[i,k])
		r = sp.sqrt(B[k,k]**2 + B[i,k]**2)
		c = B[k,k]/r
		s = -B[i,k]/r
		G = sp.eye(m)
		G[i,i] = c
		G[k,k] = c
		G[k,i] = -s
		G[i,k] = s
		return G
	
	B = A.copy()	
	m,n = B.shape
	G = sp.eye(m)
	#cycle through each nonzero subdiagonal element of B, and rotate it to zero
	for k in sp.arange(n-1):
		for i in sp.arange(k+1,m):
			if B[i,k] is not 0:
				H = rotate(i,k,B)
				B = sp.dot(H,B)
				G = sp.dot(H,G)
	return G.T, B
开发者ID:KathleenF,项目名称:numerical_computing,代码行数:31,代码来源:ct.py


示例10: triples2mat

def triples2mat(triples,shape="csr"):
    n = len(triples)
    data = arange(n)
    ij = arange(2*n).reshape(2,n)
    for k,item in enumerate(triples):
        ij[0][k],ij[1][k],data[k] = item
    return scipy.sparse.coo_matrix((data, ij)).asformat(shape)
开发者ID:cvdlab,项目名称:lar-cc,代码行数:7,代码来源:larcc.py


示例11: getData

def getData(shot, tags=False,
            probesort=True, internal=True, external=False):
    if tags == False:
        print 'tags must be specified in getMDSplus.getData(tags="typetagshere")'
        return False
    if type(tags)==str:
        tags = [tags]
    data = {}
    data["Shot"] = shot
    data["Tags"] = tags
    if "RespModes" in tags  or "AppModes"in tags:
        data["gamma"] = getGamma(shot)
    if "RespModes" in tags:
        data["RespModes"] = getRespModes(shot)
        data["Mtime"] = sp.arange(0, max(data["RespModes"].shape)/512, 1/512)
    if "AppModes" in tags:
        data["AppModes"] = getRespModes(shot)
        data["Mtime"] = sp.arange(0, max(data["AppModes"].shape)/512, 1/512)
    if "Bfield" in tags:
        data["Bfield"] = getBfield(shot)
    if "Bfield" in tags or "Appfield" in tags or "RespField" in tags:
        data["Serials"] = getSerials(shot)
        data["Position"] = getPosition(shot)
        # a time field is created so that resampling can be kept track of within the dictionary
        data["Btime"] = sp.arange(0, max(data["Bfield"].shape)/512, 1/512)
        if probesort == True:
            probeSort(shot, data, internal=internal, external=external)
    if "RawData" in tags:
        data["RawData"] = getRawData(shot)
    return data
开发者ID:muyu0117,项目名称:svd,代码行数:30,代码来源:getMDSplus.py


示例12: eig

def eig(A, normal = False, iter = 100):
	'''Finds eigenvalues of an nxn array A. If A is normal, QRalg.eig 
	may also return eigenvectors.
	
	Parameters
	----------
	A :  nxn array
	     May be real or complex
	normal : bool, optional
		     Set to True if A is normal and you want to calculate
		     the eigenvectors.
	iter : positive integer, optional
			
	Returns
	-------
	v : 1xn array of eigenvectors, may be real or complex
	Q : (only returned if normal = True) 
		nxn array whose columns are eigenvectors, s.t. A*Q = Q*diag(v)
		real if A is real, complex if A is complex
	
	For more on the QR algorithm, see Eigenvalue Solvers lab.
	'''
	def getSchurEig(A):
		#Find the eigenvalues of a Schur form matrix. These are the 
		#elements on the main diagonal, except where there's a 2x2 
		#block on the main diagonal. Then we have to find the 
		#eigenvalues of that block.
		D = sp.diag(A).astype(complex)
		#Find all the 2x2 blocks:
		LD = sp.diag(A,-1)
		index = sp.nonzero(abs(LD)>.01)[0] #is this a good tolerance?
		#Find the eigenvalues of those blocks:
		a = 1
		b = -D[index]-D[index+1]
		c = D[index]*D[index+1] - A[index,index+1]*LD[index]
		discr = sp.sqrt(b**2-4*a*c)
		#Fill in vector D with those eigenvalues
		D[index] = (-b + discr)/(2*a)
		D[index+1] = (-b - discr)/(2*a)
		return D

	n,n = A.shape
	I = sp.eye(n)
	A,Q = hessenberg(A,True)
	if normal == False:
		for i in sp.arange(iter):
			s = A[n-1,n-1].copy()
			Qi,R = la.qr(A-s*I)
			A = sp.dot(R,Qi) + s*I
		v = getSchurEig(A)
		return v
	
	elif normal == True:
		for i in sp.arange(iter):
			s = A[n-1,n-1].copy()
			Qi,R = la.qr(A-s*I)
			A = sp.dot(R,Qi) + s*I
			Q = sp.dot(Q,Qi)
		v = sp.diag(A)
		return v,Q
开发者ID:davidreber,项目名称:Labs,代码行数:60,代码来源:solutions.py


示例13: getGenoID

    def getGenoID(self,i0=None,i1=None,pos0=None,pos1=None,chrom=None,pos_cum0=None,pos_cum1=None):
        """get genotype IDs. 
        Optionally the indices for loading subgroups the genotype IDs for all people
        can be given in one out of three ways: 
        - 0-based indexing (i0-i1)
        - position (pos0-pos1 on chrom)
        - cumulative position (pos_cum0-pos_cum1)
        If all these are None (default), then all genotypes are returned

        Args:
            i0:         genotype index based selection (start index)
            i1:         genotype index based selection (stop index)
            pos0:       position based selection (start position)
            pos1:       position based selection (stop position)
            chrom:      position based selection (chromosome)
            pos_cum0:   cumulative position based selection (start position)
            pos_cum1:   cumulative position based selection (stop position)
           
        Returns:
            ID:         scipy.array of genotype IDs (e.g. rs IDs)
        """
        #position based matching?
        if (i0 is None) and (i1 is None) and ((pos0 is not None) & (pos1 is not None) & (chrom is not None)) or ((pos_cum0 is not None) & (pos_cum1 is not None)):
            i0,i1=self.getGenoIndex(pos0=pos0,pos1=pos1,chrom=chrom,pos_cum0=pos_cum0,pos_cum1=pose_cum1)
        if "genotype_id" in list(self.geno.keys()):
            if (i0 is not None) & (i1 is not None):
                return self.geno["genotype_id"][i0:i1]
            else:
                return self.geno["genotype_id"][i0:i1]
        else:
            if (i0 is not None) & (i1 is not None):
                return SP.arange(i0,i0)
            else:
                return SP.arange(self.genoM.shape[1])
        pass
开发者ID:PMBio,项目名称:limix,代码行数:35,代码来源:data_deprecated.py


示例14: PlotLc

def PlotLc(id=None, dir=None, quarter=None, tset=None):
    if id != None:
        tset, status = GetLc(id=id, dir=dir, tr_out=True)
        if tset is None:
            return
    elif tset == None:
        print "no tset"
        return
    if quarter != None:
        tset.tables[1] = tset.tables[1].where(tset.tables[1].Q == quarter)
        if len(tset.tables[1].TIME) == 0:
            print "No data for Q%d" % quarter
            return
    time = tset.tables[1].TIME
    phase, inTr = TransitPhase(tset)
    col = ["r", "g", "b", "y", "c", "m", "grey"]
    npl, nobs = inTr.shape
    pylab.figure(1)
    pylab.clf()
    pylab.plot(time, tset.tables[1].PDCSAP_FLUX, "k-")
    for ipl in scipy.arange(npl):
        list = inTr[ipl, :].astype(bool)
        pylab.plot(time[list], tset.tables[1].PDCSAP_FLUX[list], ".", c=col[ipl])
    l = scipy.isfinite(time)
    pylab.xlim(time[l].min(), time[l].max())
    ttl = "KIC %d, P=" % (tset.tables[0].KID[0])
    for i in scipy.arange(npl):
        ttl = "%s%.5f " % (ttl, tset.tables[0].Period[i])
    if quarter != None:
        ttl += "Q%d" % quarter
    pylab.title(ttl)

    return
开发者ID:RuthAngus,项目名称:K-ACF,代码行数:33,代码来源:KOI_tools_b12.py


示例15: estimateBeta

def estimateBeta(X,Y,K,C=None,addBiasTerm=False,numintervals0=100,ldeltamin0=-5.0,ldeltamax0=5.0):
    """ compute all pvalues
    If numintervalsAlt==0 use EMMA-X trick (keep delta fixed over alternative models)
    """
    n,s=X.shape;
    n_pheno=Y.shape[1];
    S,U=LA.eigh(K);
    UY=SP.dot(U.T,Y);
    UX=SP.dot(U.T,X);
    if (C==None):
        Ucovariate=SP.dot(U.T,SP.ones([n,1]));
    else:
        if (addBiasTerm):
            C_=SP.concatenate((C,SP.ones([n,1])),axis=1)
            Ucovariate=SP.dot(U.T,C_);
        else:
            Ucovariate=SP.dot(U.T,C);
    n_covar=Ucovariate.shape[1];
    beta = SP.empty((n_pheno,s,n_covar+1));
    LL=SP.ones((n_pheno,s))*(-SP.inf);
    ldelta=SP.empty((n_pheno,s));
    sigg2=SP.empty((n_pheno,s));
    pval=SP.ones((n_pheno,s))*(-SP.inf);
    for phen in SP.arange(n_pheno):
        UY_=UY[:,phen];
        ldelta[phen]=optdelta(UY_,Ucovariate,S,ldeltanull=None,numintervals=numintervals0,ldeltamin=ldeltamin0,ldeltamax=ldeltamax0);
        for snp in SP.arange(s):
            UX_=SP.hstack((UX[:,snp:snp+1],Ucovariate));
            nLL_, beta_, sigg2_=nLLeval(ldelta[phen,snp],UY_,UX_,S,MLparams=True);
            beta[phen,snp,:]=beta_;
            sigg2[phen,snp]=sigg2_;
            LL[phen,snp]=-nLL_;
    return beta, ldelta
开发者ID:PMBio,项目名称:limix,代码行数:33,代码来源:lmm_fast.py


示例16: _update_indicator

	def _update_indicator(self,K,L):
		""" update the indicator """
		_update = {'term': self.n_terms*SP.ones((K,L)).T.ravel(),
					'row': SP.kron(SP.arange(K)[:,SP.newaxis],SP.ones((1,L))).T.ravel(),
					'col': SP.kron(SP.ones((K,1)),SP.arange(L)[SP.newaxis,:]).T.ravel()} 
		for key in _update.keys():
			self.indicator[key] = SP.concatenate([self.indicator[key],_update[key]])
开发者ID:PMBio,项目名称:mtSet,代码行数:7,代码来源:mean.py


示例17: fit_gaussian_state

def fit_gaussian_state(Q, P, W):
    q = Q[0,:]
    p = P[:,0]
    m, n = W.shape
    idx_to_q = interp1d(scipy.arange(n), q)
    idx_to_p = interp1d(scipy.arange(m), p)
    i_mean = find_mean(W)
    try:
        q0, p0 = idx_to_q(i_mean[0]), idx_to_p(i_mean[1])
        s0 = 1./(W.max()*sqrt(2.*pi))
        theta0 = 0.
        def twoD_Gaussian(qp, a, b, c):
            q, p = qp
            det = a*c-b**2
            if det<0:
                raise RuntimeError
            normalization = sqrt(det)/(2.*pi)
            g = normalization*exp( -1./2.* (a*((q-q0)**2) + 2*b*(q-q0)*(p-p0) + c*((p-p0)**2)))
            return g.ravel()
        initial_guess = convert_params(s0, s0, theta0)
        (a, b, c), pcov = curve_fit(twoD_Gaussian, (Q, P), W.ravel(), p0=initial_guess)
        cov = scipy.array([[c, -b], [-b, a]])/(a*c-b**2)
        dq = cov[0,0]
        cqp = cov[0,1]
        dp = cov[1,1]
    except:
        q0 = scipy.nan
        p0 = scipy.nan
        dq = scipy.nan
        cqp = scipy.nan
        dp = scipy.nan
    return scipy.array([q0, p0, dq, cqp, dp])
开发者ID:martina88esposito,项目名称:tomohowk,代码行数:32,代码来源:fit_gaussians.py


示例18: plotSpectrum

def plotSpectrum(y,Fs):
    """
    Plots a Single-Sided Amplitude Spectrum of y(t)
    :param y: the signal
    :param Fs: the sampling frequency
    """
    n = len(y) # length of the signal
    k = arange(n)
    T = n/Fs 
    frq = k/T # Two sides frequency range
    frq = np.squeeze(frq)

    frq = frq[range(int(n/2))] # One side frequency range

    Y = fft(y)/n # FFT computing and normalization
    Y = Y[range(int(n/2))]
    # Plot the signal in wall-clock time
    subplot(2,1,1)
    Ts = 1.0/Fs; # sampling interval
    t = arange(0, 1.0*len(y)/Fs, Ts)
    plot(t, y)
    xlabel('Time')
    ylabel('Amplitude')
    # Plot the spectrum 
    subplot(2,1,2)
    plot( frq, np.log(abs(Y)),'r') # Plotting the spectrum
    xlabel('Freq (Hz)')
    ylabel('log|Y(freq)|')
    show()      
开发者ID:ankush-me,项目名称:cdt_courses,代码行数:29,代码来源:lab_session_1.py


示例19: Evolve_DE

 def Evolve_DE(self):
  for i in scipy.arange(self.npop1):
   # para cada individuo da populacao 
   # gera trial vector usado para perturbar individuo atual (indice i)
   # a partir de 3 individuos escolhidos aleatoriamente na populacao e
   # cujos indices sejam distintos e diferentes de i
   invalido = True
   while invalido:
    j = random_integers(0,self.npop1-1,3)
    invalido = (i in j)
    invalido = invalido or (j[0] == j[1]) 
    invalido = invalido or (j[1] == j[2]) 
    invalido = invalido or (j[2] == j[0])    
   # trial vector a partir da mutacao de um alvo 
   u = self.pop1[j[0]] + self.beta*(self.pop1[j[1]] - self.pop1[j[2]]) 
   # gera por crossover solucao candidata
   c = self.pop1[i].copy()  
   # seleciona indices para crossover
   # garantindo que ocorra crossover em
   # pelo menos uma vez                 
   j = random_integers(0,self.pop1.shape[1]-1)
   for k in scipy.arange(self.pop1.shape[1]):
    if (scipy.rand() < self.pr) or (k == j):
     c[k] = u[k]  
   ans,c = self.resolve_desafio(c)
   c_fit = self.avalia_aptidao1(ans)    
   # leva para proxima geracao quem tiver melhor fitness
   if (c_fit > self.fit1[i]):
    self.pop1[i] = c
    self.fit1[i] = c_fit
    self.ans1[i] = ans
开发者ID:mmssouza,项目名称:idsc,代码行数:31,代码来源:optimize.py


示例20: plotmap

    def plotmap(self,fig,ax):
        """ This function will plot the map of Alaska. The data will be plotted
            over it and will use the basemap class to position everything.
            Input
                fig - The figure handle for the plots.
                ax - The axes handle that the map will be plotted over.
            Output
                m - This is the handle for the basemap object.
        """
        latlim2 = self.params['latbounds']
        lonlim2 = self.params['lonbounds']
        m = Basemap(projection='merc',lon_0=sp.mean(lonlim2),lat_0=sp.mean(latlim2),\
        lat_ts=sp.mean(latlim2),llcrnrlat=latlim2[0],urcrnrlat=latlim2[1],\
        llcrnrlon=lonlim2[0],urcrnrlon=lonlim2[1],\
        rsphere=6371200.,resolution='i',ax=ax)
        # draw coastlines, state and country boundaries, edge of map.
        #m.drawcoastlines()
    #    m.drawstates()
    #    m.drawcountries()
        m.readshapefile('st99_d00','states',drawbounds=True)

        merstep = sp.round_((lonlim2[1]-lonlim2[0])/5.)
        parstep = sp.round_((latlim2[1]-latlim2[0])/5.)
        meridians=sp.arange(lonlim2[0],lonlim2[1],merstep)
        parallels = sp.arange(latlim2[0],latlim2[1],parstep)
        m.drawparallels(parallels,labels=[1,0,0,0],fontsize=10)
        m.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10)
        plt.hold(True)
        return m
开发者ID:jswoboda,项目名称:MahaliPlotting,代码行数:29,代码来源:PlottingClass.py



注:本文中的scipy.arange函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python scipy.arccos函数代码示例发布时间:2022-05-27
下一篇:
Python scipy.append函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap