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


Python scipy.polyval函数代码示例

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


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

示例1: time_fitting

def time_fitting(x_fit,y_fit):
    """Fit a linear relation to the x_fit and y_fit parameters

    Returns the actual fit and the parameters of the fit,
    """
    import numpy as np
    x_fit = np.array( x_fit )
    y_fit = np.array( y_fit )

    ###First fit iteration and remove outliers
    POLY_FIT_ORDER = 1

    slope,intercept = scipy.polyfit(x_fit,y_fit,POLY_FIT_ORDER)
    fit = scipy.polyval((slope,intercept),x_fit)
    fit_sigma = fit.std()
    include_index = np.where(np.abs(fit-y_fit) < 1.5*fit_sigma)[0]

    if len(include_index) < 4:
        return None,None,False

    ###Final Fit
    x_fit_clipped = x_fit[include_index]
    y_fit_clipped = y_fit[include_index]

    parameters = scipy.polyfit(x_fit_clipped,y_fit_clipped,POLY_FIT_ORDER)
    fit = scipy.polyval(parameters,x_fit)

    return fit,parameters,True
开发者ID:jotaylor,项目名称:cos_monitoring,代码行数:28,代码来源:findbad.py

示例2: x_do_contact

    def x_do_contact(self, args):
        """
        DEBUG COMMAND to be activated in the future
        """
        xext, ysub, contact = self.find_contact_point2(debug=True)

        contact_plot = self.plots[0]
        contact_plot.add_set(xext, ysub)
        contact_plot.add_set([xext[contact]], [self.plots[0].vectors[0][1][contact]])
        # contact_plot.add_set([first_point[0]],[first_point[1]])
        # contact_plot.add_set([last_point[0]],[last_point[1]])
        contact_plot.styles = [None, None, None, "scatter"]
        self._send_plot([contact_plot])
        return

        index, regr, regr_contact = self.find_contact_point2(debug=True)
        print regr
        print regr_contact
        raw_plot = self.current.curve.default_plots()[0]
        xret = raw_plot.vectors[0][0]
        # nc_line=[(item*regr[0])+regr[1] for item in x_nc]
        nc_line = scipy.polyval(regr, xret)
        c_line = scipy.polyval(regr_contact, xret)

        contact_plot = self.current.curve.default_plots()[0]
        contact_plot.add_set(xret, nc_line)
        contact_plot.add_set(xret, c_line)
        contact_plot.styles = [None, None, None, None]
        # contact_plot.styles.append(None)
        contact_plot.destination = 1
        self._send_plot([contact_plot])
开发者ID:Alwnikrotikz,项目名称:hooke,代码行数:31,代码来源:fit.py

示例3: test_scipy

def test_scipy():
    #Sample data creation
    #number of points
    n=50
    t=linspace(-5,5,n)
    #parameters
    a=0.8; b=-4
    x=polyval([a,b],t)
    #add some noise
    xn=x+randn(n)

    #Linear regressison -polyfit - polyfit can be used other orders polys
    (ar,br)=polyfit(t,xn,1)
    xr=polyval([ar,br],t)
    #compute the mean square error
    err=sqrt(sum((xr-xn)**2)/n)

    print('Linear regression using polyfit')
    print('parameters: a=%.2f b=%.2f \nregression: a=%.2f b=%.2f, ms error= %.3f' % (a,b,ar,br,err))

    #matplotlib ploting
    title('Linear Regression Example')
    plot(t,x,'g.--')
    plot(t,xn,'k.')
    plot(t,xr,'r.-')
    legend(['original','plus noise', 'regression'])

    show()

    #Linear regression using stats.linregress
    (a_s,b_s,r,tt,stderr)=stats.linregress(t,xn)
    print('Linear regression using stats.linregress')
    print('parameters: a=%.2f b=%.2f \nregression: a=%.2f b=%.2f, std error= %.3f' % (a,b,a_s,b_s,stderr))
开发者ID:apolitogaga,项目名称:Chess_Stat_ML,代码行数:33,代码来源:get_stats.py

示例4: main

def main(FileName):
    
    for trial in kep.iofiles.passFileToTrialList(FileName):
        tr = kep.pipelinepars.keptrial(trial)
        kw = kep.keplc.kw(**tr.kw)
        X = kep.keplc.keplc(tr.kid)
        X.runPipeline(kw)
        lc = X.lcData.lcData
        Y = kep.qats.qatslc(X.lcFinal,X.KID)
        idx = num.where((X.lcFinal['eMask'] == False))[0]
        Y.padLC(flagids=idx)
        Y.addNoise()
        Y.runQATS(f=0.01)
        
        P,ignored = calcPeriodogram(Y.periods, lc['x'], lc['ydt'], lc['yerr']) ### ADDED ###
                
        coeff = num.polyfit(num.log10(Y.periods),num.log10(Y.snrLC),1)
        outy = scipy.polyval(coeff,num.log10(Y.periods))
        normalizedPower = 10**(outy)
                
        coeff2 = num.polyfit(num.log10(Y.periods),num.log10(Y.snrFLAT),1) ### ADDED ###
        outy2 = scipy.polyval(coeff2,num.log10(Y.periods)) ### ADDED ###
        normalizedPower2 = 10**(outy2) ### ADDED ###
                
        fittedr=Y.snrFLAT/normalizedPower2 ### ADDED ###
        fittedb=Y.snrLC/normalizedPower2 ### ADDED ###
        normalizedPower3 = normalizedPower2/normalizedPower2 ### ADDED ###
                
        plt.subplot(211) ### ADDED ###
        plt.title('unflipped,'+' KID = '+X.KID)
        plt.plot(Y.periods,Y.snrFLAT/normalizedPower,'r-') 
        plt.plot(Y.periods,Y.snrLC/normalizedPower,'b-')
        plt.plot(Y.periods,normalizedPower/normalizedPower,'k-')
                #plt.plot(Y.periods,normalizedPower2, 'k-') ### ADDED ###
        plt.setp(plt.gca().set_xscale('log'))
        plt.ylabel('Signal Power')
        plt.subplot(212)
        plt.plot(Y.periods,P,'g-') ### ADDED ###
        plt.setp(plt.gca().set_xscale('log')) ### ADDED ###
        plt.xlabel('Period (days)') ### MOVED ###
        plt.ylabel('F Transform')
        plt.savefig('sn.SG0XX.unflipped.'+X.KID+'.png') ### MOVED ###
        #coeff = num.polyfit(num.log10(Y.periods),num.log10(Y.snrLC),1)
        #outy = scipy.polyval(coeff,num.log10(Y.periods))
        #normalizedPower = 10**(outy)
        
        #plt.plot(Y.periods,Y.snrFLAT,'r-') 
        #plt.plot(Y.periods,Y.snrLC,'b-')
        #plt.plot(Y.periods,normalizedPower,'k-')
        #plt.setp(plt.gca().set_xscale('log'))
        #plt.savefig('sn.'+X.KID+'.png')
        
        dfile = open('signal.'+X.KID+'.data','w')
        print >> dfile,'#',X.KID,'|', Y.periods[num.argmax(Y.snrLC/normalizedPower)],\
                Y.periods[num.argmax(Y.snrLC)], max(Y.snrLC/normalizedPower), max(Y.snrLC)
        for i in range(len(Y.SignalPower)):
            print >> dfile, Y.periods[i],'|',Y.snrLC[i],'|',\
                            Y.snrFLAT[i],'|',normalizedPower[i]
        dfile.close()
开发者ID:bvegaff,项目名称:uwpyKepler,代码行数:59,代码来源:qatstcase_emask.py

示例5: go

def go(
    mags=(15, 30.1, 0.5), redshifts=(0.01, 12, 0.01), coeff_file="prior_K_zmax7_coeff.dat", outfile="prior_K_extend.dat"
):

    fp = open(coeff_file)
    lines = fp.readlines()
    fp.close()

    mag_list = np.cast[float](lines[0].split()[2:])
    z0 = np.cast[float](lines[1].split()[1:])
    gamma = np.cast[float](lines[2].split()[1:])

    z_grid = np.arange(redshifts[0], redshifts[1], redshifts[2])
    NZ = z_grid.shape[0]

    mag_grid = np.arange(mags[0], mags[1], mags[2])
    NM = mag_grid.shape[0]

    #### Polynomial extrapolation not reliable
    # p_z0 = scipy.polyfit(mag_list, z0, order)
    # z0_grid = np.maximum(scipy.polyval(p_z0, mag_grid), 0.05)
    # p_gamma = scipy.polyfit(mag_list, gamma, order)
    # gamma_grid = np.maximum(scipy.polyval(p_gamma, mag_grid), 0.05)

    #### Interpolations on the defined grid
    z0_grid = np.interp(mag_grid, mag_list, z0)
    gamma_grid = np.interp(mag_grid, mag_list, gamma)

    #### Linear extrapolations of fit coefficients
    p_z0 = scipy.polyfit(mag_list[:3], z0[:3], 1)
    z0_grid[mag_grid < mag_list[0]] = np.maximum(scipy.polyval(p_z0, mag_grid[mag_grid < mag_list[0]]), 0.05)
    p_z0 = scipy.polyfit(mag_list[-3:], z0[-3:], 1)
    z0_grid[mag_grid > mag_list[-1]] = np.maximum(scipy.polyval(p_z0, mag_grid[mag_grid > mag_list[-1]]), 0.05)

    p_gamma = scipy.polyfit(mag_list[:3], gamma[:3], 1)
    gamma_grid[mag_grid < mag_list[0]] = np.maximum(scipy.polyval(p_gamma, mag_grid[mag_grid < mag_list[0]]), 0.05)
    p_gamma = scipy.polyfit(mag_list[-3:], gamma[-3:], 1)
    gamma_grid[mag_grid > mag_list[-1]] = np.maximum(scipy.polyval(p_gamma, mag_grid[mag_grid > mag_list[-1]]), 0.05)

    out_matrix = np.zeros((NZ, NM + 1))
    out_matrix[:, 0] = z_grid

    for i in range(NM):
        pz = z_grid * np.exp(-(z_grid / z0_grid[i]) ** gamma_grid[i])
        pz /= np.trapz(pz, z_grid)
        plt.plot(z_grid, pz, label=mag_grid[i])
        out_matrix[:, i + 1] = pz

    plt.legend(ncol=3, loc="upper right")

    header = "# z "
    for m in mag_grid:
        header += "%6.1f" % (m)

    fp = open(outfile, "w")
    fp.write(header + "\n")
    np.savetxt(fp, out_matrix, fmt="%6.3e")
    fp.close()
开发者ID:BraulioSI,项目名称:eazy-photoz,代码行数:58,代码来源:extend_prior.py

示例6: concat_extrap_ends

def concat_extrap_ends(x, npts, polyorder=1, lowside=True, highside=True):
    i=numpy.arange(npts, dtype='float64')
    if lowside:
        ans=scipy.polyfit(-1*(i+1.), x[:npts], polyorder)
        x=numpy.concatenate([scipy.polyval(list(ans), i[::-1]), x])
    if highside:
        ans=scipy.polyfit(-1*(i[::-1]-1.), x[-1*npts:], polyorder)
        x=numpy.concatenate([x, scipy.polyval(list(ans), i)])
    return x    
开发者ID:johnmgregoire,项目名称:NanoCalorimetry,代码行数:9,代码来源:PnSC_math.py

示例7: mNm_2_raw

	def mNm_2_raw(self,calib,tq):
		#ticks: calibrated sensor value
		#calib: yaml config calibration map
		if self.ctype=='sea_vertx_14bit':
			val=(tq-calib['cb_bias'])/calib['cb_scale']
			val=float(polyval(calib['cb_inv_torque'],val))
			return max(0,min(val,VERTX_14BIT_MAX))
		if self.ctype=='adc_poly':
			val=(tq-calib['cb_bias'])/calib['cb_scale']
			val=float(polyval(calib['cb_inv_torque'],val))
			return max(0,min(val,M3EC_ADC_TICKS_MAX))
开发者ID:CentralLabFacilities,项目名称:m3meka,代码行数:11,代码来源:calibrate_sensors.py

示例8: calculo

    def calculo(self):
        entrada = self.kwargs["entrada"]
        self.rendimientoCalculado = Dimensionless(self.kwargs["rendimiento"])

        if self.kwargs["Pout"]:
            DeltaP = Pressure(self.kwargs["Pout"]-entrada.P)
        elif self.kwargs["deltaP"]:
            DeltaP = Pressure(self.kwargs["deltaP"])
        elif self.kwargs["Carga"]:
            DeltaP = Pressure(self.kwargs["Carga"]*entrada.Liquido.rho*g)
        else:
            DeltaP = Pressure(0)

        if self.kwargs["usarCurva"]:
            b1 = self.kwargs["diametro"] != self.kwargs["curvaCaracteristica"][0]  # noqa
            b2 = self.kwargs["velocidad"] != self.kwargs["curvaCaracteristica"][1]  # noqa
            if b1 or b2:
                self.curvaActual = self.calcularCurvaActual()
            else:
                self.curvaActual = self.kwargs["curvaCaracteristica"]
            self.Ajustar_Curvas_Caracteristicas()

        if not self.kwargs["usarCurva"]:
            head = Length(DeltaP/g/entrada.Liquido.rho)
            power = Power(head*g*entrada.Liquido.rho*entrada.Q /
                          self.rendimientoCalculado)
            P_freno = Power(power*self.rendimientoCalculado)
        elif not self.kwargs["incognita"]:
            head = Length(polyval(self.CurvaHQ, entrada.Q))
            DeltaP = Pressure(head*g*entrada.Liquido.rho)
            power = Power(entrada.Q*DeltaP)
            P_freno = Power(polyval(self.CurvaPotQ, entrada.Q))
            self.rendimientoCalculado = Dimensionless(power/P_freno)
        else:
            head = Length(self.DeltaP/g/entrada.Liquido.rho)
            poli = [self.CurvaHQ[0], self.CurvaHQ[1], self.CurvaHQ[2]-head]
            Q = roots(poli)[0]
            power = Power(Q*self.DeltaP)
            entrada = entrada.clone(split=Q/entrada.Q)
            P_freno = Power(polyval(self.CurvaPotQ, Q))
            self.rendimientoCalculado = Dimensionless(power/P_freno)

        self.deltaP = DeltaP
        self.headCalculada = head
        self.power = power
        self.P_freno = P_freno
        self.salida = [entrada.clone(P=entrada.P+DeltaP)]
        self.Pin = entrada.P
        self.PoutCalculada = self.salida[0].P
        self.volflow = entrada.Q
        self.cp_cv = entrada.Liquido.cp_cv
开发者ID:bkt92,项目名称:pychemqt,代码行数:51,代码来源:pump.py

示例9: estimate_rate_func

def estimate_rate_func(t, T, N, plot_flag=False, method='central diff'):

    t_est_pts = scipy.linspace(t.min(), t.max(), N+2) 
    interp_func = scipy.interpolate.interp1d(t,T,'linear')
    T_est_pts = interp_func(t_est_pts)
 
    if plot_flag == True:
        pylab.figure()
        pylab.subplot(211)
        pylab.plot(t_est_pts, T_est_pts,'or')

    # Estimate slopes
    slope_pts = scipy.zeros((N,)) 
    T_slope_pts = scipy.zeros((N,))  

    if method == 'local fit':
        for i in range(1,(N+1)):
            mask0 = t > 0.5*(t_est_pts[i-1] + t_est_pts[i])
            mask1 = t < 0.5*(t_est_pts[i+1] + t_est_pts[i])
            mask = scipy.logical_and(mask0, mask1)
            t_slope_est = t[mask]
            T_slope_est = T[mask]
            local_fit = scipy.polyfit(t_slope_est,T_slope_est,2)
            dlocal_fit = scipy.polyder(local_fit)
            slope_pts[i-1] = scipy.polyval(dlocal_fit,t_est_pts[i]) 
            T_slope_pts[i-1] = scipy.polyval(local_fit,t_est_pts[i])
            if plot_flag == True:
                t_slope_fit = scipy.linspace(t_slope_est[0], t_slope_est[-1], 100)
                T_slope_fit = scipy.polyval(local_fit,t_slope_fit)
                pylab.plot(t_slope_fit, T_slope_fit,'g')
    elif method == 'central diff':
        dt = t_est_pts[1] - t_est_pts[0]
        slope_pts = (T_est_pts[2:] - T_est_pts[:-2])/(2.0*dt)
        T_slope_pts = T_est_pts[1:-1]
    else:
        raise ValueError, 'unkown method %s'%(method,)
        
    # Fit line to slope estimates
    fit = scipy.polyfit(T_slope_pts, slope_pts,1)

    if plot_flag == True:
        T_slope_fit = scipy.linspace(T_slope_pts.min(), T_slope_pts.max(),100)
        slope_fit = scipy.polyval(fit,T_slope_fit)
        pylab.subplot(212)
        pylab.plot(T_slope_fit, slope_fit,'r')
        pylab.plot(T_slope_pts, slope_pts,'o')
        pylab.show()

    rate_slope = fit[0]
    rate_offset = fit[1]
    return rate_slope, rate_offset 
开发者ID:pfalcon,项目名称:OmniReflow,代码行数:51,代码来源:delay_model.py

示例10: fit_curve

def fit_curve():
	global data, running
	if running == True or len(data[0])==0:
		return
	aa = []
	bb = []
	for k in range(len(data[0])):
		if data[1][k] > 1.0:
			aa.append(data[0][k])
			bb.append(data[1][k])
	x  = array(bb)
	y  = array(aa)
	from scipy import polyfit, polyval
	(ar,br)=polyfit(x,y,1)
	print polyval([ar,br],[0])
开发者ID:raviola,项目名称:expeyes,代码行数:15,代码来源:LED_iv.py

示例11: interpMaskedAreas

def interpMaskedAreas(x, dtfunc):
    idx = num.where(dtfunc == -1)[0]
    # find consecutive points of dtfunc set at -1
    diffs = idx - num.roll(idx, 1)
    setIdx1 = num.where(diffs > 1)[0]
    setIdx2 = num.where(diffs > 1)[0] - 1
    setIdx1 = num.hstack( (num.array([0]), setIdx1) )
    setIdx2 = num.hstack( (setIdx2, num.array([-1])) )
    # each int in setIdx1 is beginning of a set of points
    # each int in setIdx2 is end of a set of points
    for i in range(len(setIdx1)):
        i1 = setIdx1[i]
        i2 = setIdx2[i]
        vals_to_interp = dtfunc[ idx[i1]:idx[i2]+1]
        
        # construct interpolation from points on either side of vals
        # first ydata
        nVals = len(vals_to_interp)
        left = num.array( \
            [ dtfunc[idx[i1]-1-nVals], dtfunc[idx[i1]-1] ])
        right = num.array( \
            [ dtfunc[idx[i2]+1], dtfunc[idx[i2]+1+nVals] ])
        vals_to_construct_interp = num.hstack( (left, right) )
        vtci = vals_to_construct_interp
        
        # now xdata
        leftx = num.array([ x[idx[i1]-1-nVals], x[idx[i1]-1] ])
        rightx = num.array([ x[idx[i2]+1], x[idx[i2]+1+nVals] ])
        x_vtci = num.hstack( (leftx, rightx) )
        # conduct interpolation
        intpCoeffs = scipy.polyfit(x_vtci, vtci, 3)
        dtfunc[ idx[i1]:idx[i2]+1 ] = \
            scipy.polyval(intpCoeffs, x[ idx[i1]:idx[i2]+1 ])
        
    return dtfunc
开发者ID:UWKepler,项目名称:uwpyKepler,代码行数:35,代码来源:func.py

示例12: construct_linear_regression

def construct_linear_regression(x_learn, y_dev_learn, x_test, y_dev_test):

    regression = sp.polyfit(x_learn, y_dev_learn, 1)

    y_exp_learn = sp.polyval(regression, x_learn)
    y_exp_test = sp.polyval(regression, x_test)

    print("For train dataset:\n\ty = a*x + b\n\ta = %f\n\tb = %f" % (regression[0], regression[1]))

    mse_learn = np.sqrt(np.mean((y_exp_learn - y_dev_learn) ** 2))
    mse_test = np.sqrt(np.mean((y_exp_test - y_dev_test) ** 2))
    mse_total = np.sqrt((((mse_learn**2) * learn_set_size)
                         + ((mse_test**2) * (dataset_size - learn_set_size)))
                        / dataset_size)
    print("Train MSE = %f\nTest MSE = %f\nTotal MSE = %f" % (mse_learn, mse_test,mse_total ))
    return regression, mse_learn, mse_test, mse_total, y_exp_learn, y_exp_test
开发者ID:mahajrod,项目名称:bii-14s,代码行数:16,代码来源:regression.py

示例13: calculatePolyfit

def calculatePolyfit(x, y):
    """ Calculate a linear regression using polyfit instead """

    # FIXME(pica) This doesn't work for large ranges (tens of orders of
    # magnitude). No idea why as the fixRange() function above should make
    # all values greater than one. The trouble mainly seems to happen when
    # log10(min(x)) negative.

    # Check the smallest value in x or y isn't below 2x10-7 otherwise
    # we hit numerical instabilities.
    xFactorFix, xFactor = False, 0
    yFactorFix, yFactor = False, 0
    minX = min(x)
    minY = min(y)
    if minX < 2e-7:
        x, xFactor, xFactorFix = fixRange(x)
    if minY < 2e-7:
        y, yFactor, yFactorFix = fixRange(y)

    (ar, br) = polyfit(x, y, 1)
    yf = polyval([ar, br], x)
    xf = x

    if xFactorFix:
        xf = xf / 10**xFactor
    if yFactorFix:
        yf = yf / 10**yFactor

    return xf, yf
开发者ID:zhenkunl,项目名称:PyFVCOM,代码行数:29,代码来源:stats_tools.py

示例14: show_dialog_len

def show_dialog_len():
    import numpy as np
    from scipy import polyfit,polyval
    import matplotlib.pyplot as plt
    import LetsgoCorpus as lc
    import operator

    corpus = lc.Corpus('D:/Data/training',prep=True)
    
    l = [];avg_cs = []
    for dialog in corpus.dialogs():
        if len(dialog.turns) > 40:
            continue
        l.append(len(dialog.turns))
        avg_cs.append(reduce(operator.add,map(lambda x:x['CS'],dialog.turns))/l[-1])
    (ar,br) = polyfit(l,avg_cs,1)
    csr = polyval([ar,br],l)
    plt.plot(l,avg_cs,'g.',alpha=0.75)
    plt.plot(l,csr,'r-',alpha=0.75,linewidth=2)
    plt.axis([0,50,0,1.0])
    plt.xlabel('Dialog length (turn)')
    plt.ylabel('Confidence score')
    plt.title('Dialog length vs. Confidence score')
    plt.grid(True)
    plt.savefig('img/'+'Dialog length vs Confidence score'+'.png')
#    plt.show()
    plt.clf()
开发者ID:junion,项目名称:LGus,代码行数:27,代码来源:LetsgoMain.py

示例15: raw_2_mA

	def raw_2_mA(self,calib,ticks_a,ticks_b):
		#ticks: adc sensor value
		#calib: yaml config calibration map
		if self.ctype=='adc_linear_5V':
			mV_a = 5000.0*(ticks_a-calib['cb_ticks_at_zero_a'])/M3EC_ADC_TICKS_MAX
			mV_b = 5000.0*(ticks_b-calib['cb_ticks_at_zero_b'])/M3EC_ADC_TICKS_MAX
			i_a = 1000.0*mV_a/calib['cb_mV_per_A']
			i_b = 1000.0*mV_b/calib['cb_mV_per_A']
			val=max(abs(i_a), abs(i_b))
			return max(0,val*calib['cb_scale']+calib['cb_bias'])	
		if self.ctype=='adc_poly':
			i_a= float(polyval(calib['cb_current_a'],ticks_a))
			i_b= float(polyval(calib['cb_current_b'],ticks_b))
			val=max(abs(i_a), abs(i_b))
			return val*calib['cb_scale']+calib['cb_bias']
		return 0.0
开发者ID:CentralLabFacilities,项目名称:m3meka,代码行数:16,代码来源:calibrate_sensors.py


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