当前位置: 首页>>代码示例>>Python>>正文


Python integrate.simps函数代码示例

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


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

示例1: beamfrackernel

def beamfrackernel(kernelx, kernely, length, angle):
    """
    The beam fraction intercepted by a sample, used for calculating footprints.

    Parameters
    ----------
    kernelx: array-like
        x axis for the probability kernel
    kernely: array-like
        probability kernel describing the intensity distribution of the beam
    length: float
        length of the sample
    angle: float
        angle of incidence (degrees)

    Returns
    -------
    fraction: float
        The fraction of the beam intercepted by a sample.
    """
    height_of_sample = length * np.sin(np.radians(angle))
    total = integrate.simps(kernely, kernelx)
    lowlimit = np.where(-height_of_sample / 2. >= kernelx)[0][-1]
    hilimit = np.where(height_of_sample / 2. <= kernelx)[0][0]

    area = integrate.simps(kernely[lowlimit: hilimit + 1],
                           kernelx[lowlimit: hilimit + 1])
    return area / total
开发者ID:tjmurdoch,项目名称:refnx,代码行数:28,代码来源:general.py

示例2: exp

def exp(x,slope,xlo,xhi,efficiency=None,num_int_points=100,subranges=None):

    xnorm = np.linspace(xlo,xhi,num_int_points)
    ynorm = np.exp(-slope*xnorm)

    if efficiency!=None:
        ynorm *= efficiency(xnorm)

    normalization = integrate.simps(ynorm,x=xnorm)

    # Subranges of the normalization.
    if subranges!=None:
        normalization = 0.0
        for sr in subranges:
            xnorm = np.linspace(sr[0],sr[1],num_int_points)
            ynorm = np.exp(-slope*xnorm)

            if efficiency!=None:
                ynorm *= efficiency(xnorm)

            normalization += integrate.simps(ynorm,x=xnorm)

    y = np.exp(-slope*x)/normalization

    #'''
    if efficiency!=None:
        y *= efficiency(x)
    #'''

    return y
开发者ID:mattbellis,项目名称:Siena_College_Ronnie_Rera,代码行数:30,代码来源:pdfs.py

示例3: print_model_results

def print_model_results(model_name, means, sigmas, header=True):

	med_mean = np.median(means)
	n_data = float(np.size(means))
	n_params = likelihood.ndim

	model_grids = model_grids(model_name)
	likelihood = likelihood(means, sigmas, med_mean, *model_grids[0:6])
	posterior, evidence = posterior_evidence(likelihood, *model_grids[6:8])
	AIC, AICc, BIC = info_criteria(likelihood, n_data)

	marg_post = 1.0*posterior
	while marg_post.ndim != 1:
		marg_post = integrate.simps(marg_post)

	cdf = np.zeros_like(marg_post)
	for j in range(1,cdf.size):
		cdf[j] = integrate.simps(p_ld[0:j+1],ld[0:j+1])
	interp_from_cdf = interp1d(cdf,ld)
	cdf_prctls = (int_cdf(0.5), int_cdf(0.84)-int_cdf(0.5), int_cdf(0.5)-int_cdf(0.16))

	if header==True:
		print 'model (M_k) \t N_free \t P(mu0 | D, M_k) \t log evidence \t AIC \t AICc \t BIC'
	print model_name+'\t %1i \t %.2f^{+%.2f}_{-%.2f} \t %.2f \t %.2f \t %.2f \t %.2f' % \
			(n_params, interp_from_cdf(0.5), interp_from_cdf(0.84)-interp_from_cdf(0.5), 
				interp_from_cdf(0.5)-interp_from_cdf(0.16), np.log10(evidence), AIC, AICc, BIC)

	return
开发者ID:tlicquia,项目名称:HBmeta,代码行数:28,代码来源:HBmeta.py

示例4: __init__

    def __init__(self, filepath, maxbins=1000):
        """

        :type filepath: string
        :type maxbins: int
        """
        super(FileFilter, self).__init__()
        self.path = filepath

        data = np.loadtxt(self.path)
        wf = data[:, 0]
        tp = data[:, 1]
        if len(data[:, 0]) < maxbins:  # Re-sample large filters for performance
            wfx = np.linspace(wf[0], wf[-1], maxbins)
            tpx = griddata(wf, tp, wfx)

            wf = wfx
            tp = tpx

        self.wave = wf * u.angstrom
        self.response = tp

        self.freq = (c.c / self.wave).to(u.Hz)

        nmax = np.argmax(self.response)
        halfmax_low = self.wave[:nmax][np.argmin(np.abs(self.response[nmax] - 2 * self.response[:nmax]))]
        halfmax_hi = self.wave[nmax:][np.argmin(np.abs(self.response[nmax] - 2 * self.response[nmax:]))]

        self.fwhm = halfmax_hi - halfmax_low

        self.lambda_c = (simps(self.wave * self.response, self.wave) /
                         simps(self.response, self.wave)) * u.angstrom

        self.nu_c = (simps(self.freq * self.response, self.freq) /
                     simps(self.response, self.freq)) * u.Hz
开发者ID:RossHart,项目名称:smpy,代码行数:35,代码来源:mkCSPs_dev.py

示例5: calculateViolation

def calculateViolation(predictLine, allocateline, startTime ,endTime):
    stepSize = 1
    violateArea = 0
    violateTime = 0
    area_violations = []
    time_violations  = []
    for i in  drange(startTime + stepSize, endTime, stepSize):
        predicted_i0 = getValue(predictLine,i - stepSize)
        predicted_i1 = getValue(predictLine,i)
        ##print("Predicty=  i0 :%s i1:%s" %(predicted_i0,predicted_i1))
        allocated_i0 = getValue(allocateline, i - stepSize)
        allocated_i1 = getValue(allocateline,i)
        area_under_predicted  = simps(y = [predicted_i0, predicted_i1] , dx = stepSize)
        area_under_allocated  = simps(y = [allocated_i0, allocated_i1] , dx = stepSize)
        ##print("Areas : %s, %s"  %(area_under_predicted,area_under_allocated))
        if area_under_allocated < area_under_predicted:
            violateArea += (area_under_predicted -area_under_allocated)
            violateTime += stepSize
        area_violations.append(violateArea)
        time_violations.append(violateTime)

    area = np.array(area_violations)
    time = np.array(time_violations)
    xvalue =  np.arange(startTime+stepSize, endTime, stepSize)
    f , (plt1, plt2) = plt.subplots(1,2, sharex= True)
    plt1.plot(xvalue,area)
    plt2.plot(xvalue,time)
    #plt.show()
    #print("ViolateArea : %s ViolateTime : %s" %(violateArea, violateTime))
    return  violateArea, violateTime
开发者ID:TharinduMunasinge,项目名称:AutoscaleAnalyser,代码行数:30,代码来源:AWS.py

示例6: sfq0

def sfq0(rdfX,rdfY,ndens,Lmax=20.0,qbins=1024,damped=None):
    minq,maxq,dq=0,Lmax,Lmax/qbins
    qs=[i*dq+minq for i in range(qbins)]
    qs[0]=1E-10

    rdfY=np.array(rdfY)
    rdfX=np.array(rdfX)
    dx = rdfX[1]-rdfX[0]

    #Extend the h(r) to get a better estimate near q0
    cr,grExtx,grExty = rdfExtend(rdfX,rdfY,ndens,rmax=50.0,Niter=25,T=1000.0,rm=2.5,eps=-1,damped=0.1)

    sf1=list()
    for i,q in enumerate(qs):
        sf1 += [1 + 4*pi*ndens * integrate.simps((rdfY-1.0)*np.sin(q*rdfX)*rdfX/q ,dx=dx)]

    import pylab as pl
    
    sf2=list()
    for i,q in enumerate(qs):
        sf2 += [1 + 4*pi*ndens * integrate.simps((grExty-1.0)*np.sin(q*grExtx)*grExtx/q ,dx=dx)]
    #        R=1.0/q
    #        alpha = np.array([(1-rij/2.0/R)**2 * (1+rij/4.0/R) if rij<2*R else 0 for rij in rdfX])
    #        sf2 += [1 + 4*pi*ndens * integrate.simps((rdfY-1.0)*np.sin(q*rdfX)*rdfX/q*alpha,dx=dx)]

    f=open("/home/acadien/Dropbox/sfq0.dat","w")
    a=map(lambda x: "%f %f\n"%(x[0],x[1]),zip(qs,sf2))
    f.writelines(a)
#    exit(0)
    pl.plot(qs,sf1)
    pl.plot(qs,sf2)
    pl.show()
    exit(0)
开发者ID:acadien,项目名称:matcalc,代码行数:33,代码来源:sf.py

示例7: fit_single_line

    def fit_single_line(self, x, y, zero_lev, err_continuum, fitting_parameters, bootstrap_iterations = 1000):

        #Simple fit
        if self.fit_dict['MC_iterations'] == 1:
            fit_output = lmfit_minimize(residual_gauss, fitting_parameters, args=(x, y, zero_lev, err_continuum))
            self.fit_dict['area_intg'] = simps(y, x) - simps(zero_lev, x)
            self.fit_dict['area_intg_err'] = 0.0
             
        #Bootstrap
        else:
            mini_posterior  = Minimizer(lnprob_gaussCurve, fitting_parameters, fcn_args = ([x, y, zero_lev, err_continuum]))
            fit_output      = mini_posterior.emcee(steps=200, params = fitting_parameters)
            
            #Bootstrap for the area of the lines
            area_array = empty(bootstrap_iterations) 
            len_x_array = len(x)
            for i in range(bootstrap_iterations):
                y_new =  y + np_normal_dist(0.0, err_continuum, len_x_array)
                area_array[i] = simps(y_new, x) - simps(zero_lev, x)
            self.fit_dict['area_intg'] = mean(area_array)
            self.fit_dict['area_intg_err'] = std(area_array)           
        
        #Store the fitting parameters
        output_params = fit_output.params
        for key in self.fit_dict['parameters_list']:
            self.fit_dict[key + '_norm'] = output_params[key].value
            self.fit_dict[key + '_norm_er'] = output_params[key].stderr
            
        return
开发者ID:Delosari,项目名称:Dazer,代码行数:29,代码来源:FittingTools.py

示例8: __init__

    def __init__(self,filepath,minbins=200):
        self.path = filepath
        
#        try:
        data = numpy.loadtxt(self.path)
        wf = data[:,0]
        tp = data[:,1]
        if len(data[:,0]) < minbins: #Re-sample large filters for performance
            wfx = numpy.linspace(wf[0],wf[-1],minbins)
            tpx = griddata(wf,tp,wfx)

            wf = wfx
            tp = tpx
            
        self.wave = wf * U.angstrom
        self.response = tp
        
        self.freq = (C.c/self.wave).to(U.Hz)
        
        nmax = numpy.argmax(self.response)
        halfmax_low = self.wave[:nmax][numpy.argmin(numpy.abs(self.response[nmax] - 2*self.response[:nmax]))]
        halfmax_hi = self.wave[nmax:][numpy.argmin(numpy.abs(self.response[nmax] - 2*self.response[nmax:]))]
        print self.wave[nmax],halfmax_low, halfmax_hi
        self.fwhm = halfmax_hi-halfmax_low
        
        self.lambda_c = (simps(self.wave*self.response,self.wave) / 
                         simps(self.response,self.wave))

        self.nu_c = (simps(self.freq*self.response,self.freq) / 
                     simps(self.response,self.freq))
开发者ID:RossHart,项目名称:smpy,代码行数:30,代码来源:mkCSPs.py

示例9: SusceptibilityHF

def SusceptibilityHF(U,GF_A,X_A):
	''' susceptibility calculated from the full spectral self-energy derivative '''
	Int1_A = FD_A*sp.imag(GF_A**2*(1.0-U*X_A))
	Int2_A = FD_A*sp.imag(GF_A**2*X_A)
	I1 = simps(Int1_A,En_A)/sp.pi
	I2 = simps(Int2_A,En_A)/sp.pi
	return 2.0*I1/(1.0+U**2*I2)
开发者ID:pokornyv,项目名称:SPEpy,代码行数:7,代码来源:parlib.py

示例10: synthesize_photometric_point

def synthesize_photometric_point(filt, wl, fl):
    import photometry
    '''Takes in a spectrum in [ang], and [erg/(s cm^2 ang)], and then returns Jy'''
    if filt in {"u","g","r","i","z"}:
        wl_key = "lam"
        p_key = "air1.0"
    else:
        wl_key = "WL"
        p_key = "RES"
    p = interp1d(photometry.responses[filt][wl_key],photometry.responses[filt][p_key])
    filt_re = photometry.responses[filt][wl_key]
    p_min = min(filt_re)
    p_max = max(filt_re)
    if p_min < wl[0] or p_max > wl[-1]:
        print("ERROR, spectrum is out of range of filter: %s" % filt)
    def px(x):
        if (x < p_min) or (x > p_max):
            return 0
        else:
            return p(x)
    pxs = map(px, wl)
    f_num = wl * pxs * fl
    f_denom = wl * pxs
    #print f_num, f_denom
    num = simps(f_num, x=wl)
    denom = simps(f_denom, x=wl)
    flux = num/denom
    #This should be in spectral flux [erg/(s cm^2 A)]
    central = denom/simps(pxs, wl)
    #Returned product is in Jy  
    return photometry.Flamb_to_Jy(flux,central)
开发者ID:iancze,项目名称:Pysplotter,代码行数:31,代码来源:spectrum.py

示例11: Compute_Delta

def Compute_Delta(niom, T, mu, Sig):
  # Matsubara Frequencies
  iom = pi*T*(2*arange(niom)+1)
  # Load DOS
  DOSfile = loadtxt('2D_SL_DOS')
  # 1st column as energies
  ommesh = DOSfile[:,0]
  # 2nd column as DOS
  DOS = DOSfile[:,1]
  # Normalize
  DOS = DOS / integrate.simps(DOS, ommesh)
  # Local Green function
  Gloc = zeros(niom, dtype=complex)
  for i in range(niom):
    Re = mu - ommesh - Sig[i].real
    Im = iom[i] - Sig[i].imag
    denom = 1/(Re**2 + Im**2)
    ReInt = DOS*Re*denom
    ImInt = DOS*Im*denom
    Gloc[i] = integrate.simps(ReInt, ommesh) - 1j*integrate.simps(ImInt, ommesh)

  Delta = 1j*iom+mu-Sig-1./Gloc
  with open('Delta.inp', 'w') as f:
    for i in range(niom):
      f.write('%.8f\t%.8f\t%.8f\n'%(iom[i], Delta[i].real, Delta[i].imag))
开发者ID:slek120,项目名称:phys534,代码行数:25,代码来源:dmft.py

示例12: cosine_content

def cosine_content(pca_space, i):
    """Measure the cosine content of the PCA projection.

    The cosine content of pca projections can be used as an indicator if a
    simulation is converged. Values close to 1 are an indicator that the
    simulation isn't converged. For values below 0.7 no statement can be made.
    If you use this function please cite [BerkHess1]_.


    Parameters
    ----------
    pca_space: array, shape (number of frames, number of components)
        The PCA space to be analyzed.
    i: int
        The index of the pca_component projectection to be analyzed.

    Returns
    -------
    A float reflecting the cosine content of the ith projection in the PCA
    space. The output is bounded by 0 and 1, with 1 reflecting an agreement
    with cosine while 0 reflects complete disagreement.

    References
    ----------
    .. [BerkHess1] Berk Hess. Convergence of sampling in protein simulations.
                   Phys. Rev. E 65, 031910 (2002).
    """
    from scipy.integrate import simps
    t = np.arange(len(pca_space))
    T = len(pca_space)
    cos = np.cos(np.pi * t * (i + 1) / T)
    return ((2.0 / T) * (simps(cos*pca_space[:, i])) ** 2 /
            simps(pca_space[:, i] ** 2))
开发者ID:alejob,项目名称:mdanalysis,代码行数:33,代码来源:pca.py

示例13: process_fid

def process_fid(fid, absint=False):
    ft = cut_fft(do_fft(cut_fid(fid)))
    if absint:
        res = integrate.simps(np.abs(ft['fft']), ft.index)
    else:
        res = integrate.simps(np.real(ft['fft']), ft.index)
    return res
开发者ID:serjinio,项目名称:python_tutors,代码行数:7,代码来源:mwdep.py

示例14: test_simpson

def test_simpson():
    ncalls = 10
    func = lambda x: np.sin(x - 0.2414)*x + 2.

    x = np.linspace(0, 10, 250001)
    y = func(x)

    t0 = time.time()
    for i in range(ncalls):
        s1 = simpson(y, dx=x[1]-x[0])
    print("cython (odd): {0} sec for {1} calls".format(time.time() - t0,ncalls))

    t0 = time.time()
    for i in range(ncalls):
        s2 = simps(y, x=x)
    print("python (odd): {0} sec for {1} calls".format(time.time() - t0,ncalls))
    np.testing.assert_allclose(s1, s2)

    # -----------------------------------------------------
    print()
    x = np.linspace(0, 10, 250000)
    y = func(x)
    t0 = time.time()
    for i in range(ncalls):
        s1 = simpson(y, dx=x[1]-x[0])
    print("cython (even): {0} sec for {1} calls".format(time.time() - t0,ncalls))

    t0 = time.time()
    for i in range(ncalls):
        s2 = simps(y, x=x)
    print("python (even): {0} sec for {1} calls".format(time.time() - t0,ncalls))

    np.testing.assert_allclose(s1, s2)
开发者ID:abonaca,项目名称:gary,代码行数:33,代码来源:test_1d.py

示例15: int_func

def int_func( xin, fin=None, simple=None):
    if fin is None :
        f = copy.deepcopy(xin)
        x = numpy.arange(numpy.size(f)).astype(float)
    else:
        f = copy.deepcopy(fin)
        x = copy.deepcopy(xin)
    
    n = numpy.size(f)

    g = numpy.zeros(n)

    if simple is not None :
     # Just use trapezium rule
     
        g[0] = 0.0
        for i in range (1, n) :
            g[i] = g[i-1] + 0.5*(x[i] - x[i-1])*(f[i] + f[i-1])
         
    else:
     
        n2 = numpy.int(old_div(n,2))
     
        g[0] = 0.0
        for i in range (n2, n) :
            g[i] = simps( f[0:i+1], x[0:i+1])


            
        for i in range (1, n2) :
            g[i] = g[n-1] - simps( f[i::], x[i::])
             
    return g
开发者ID:boutproject,项目名称:BOUT-dev,代码行数:33,代码来源:int_func.py


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