Python scipy.optimize 模块,curve_fit() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用scipy.optimize.curve_fit()

项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码

def fit_rabi(xdata, ydata):"""Analyze Rabi amplitude data to find pi-pulse amplitude and phase offset.Arguments:xdata: ndarray of calibration amplitudes. length should be even.ydata: measurement amplitudesReturns:pi_amp: Fitted amplitude of pi pulsedoffset: Fitted mixer offsetfit_pts: Fitted points."""#seed Rabi frequency from largest FFT componentN = len(ydata)yfft = fft(ydata)f_max_ind = np.argmax(np.abs(yfft[1:N//2]))f_0 = 0.5 * max([1, f_max_ind]) / xdata[-1]amp_0 = 0.5*(ydata.max() - ydata.min())offset_0 = np.mean(ydata)phase_0 = 0if ydata[N//2 - 1] > offset_0:amp_0 = -amp_0popt, _ = curve_fit(rabi_model, xdata, ydata, [offset_0, amp_0, f_0, phase_0])f_rabi = np.abs(popt[2])pi_amp = 0.5/f_rabioffset = popt[3]return pi_amp, offset, popt

项目:pyqha    作者:mauropalumbo75    | 项目源码 | 文件源码

def fit_Murn(V,E,guess=[0.0,0.0,900/RY_KBAR,1.15],lm_pars={}):"""This is the function for fitting with the Murnaghan EOS as a function of volume only.The input variable *V* is an 1D array of volumes, *E* are the corresponding energies (or other analogous quantity to be fitted with the Murnaghan EOS.*a*Note: volumes must be in a.u.^3 and energies in Rydberg."""# reasonable initial guesses for EOS parametersif guess[0]==0.0:guess[0] = E[len(E) / 2]if guess[1]==0.0:guess[1] = V[len(V) / 2]a, pcov = curve_fit(E_MurnV, V, E, p0=guess, **lm_pars)chi = 0for i in range(0,len(V)):chi += (E[i]-E_Murn(V[i],a))**2return a, pcov, chi

项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码

def fit_photon_number(xdata, ydata, params):''' Fit number of measurement photons before a Ramsey. See McClure et al., Phys. Rev. App. 2016input params:1 - cavity decay rate kappa (MHz)2 - detuning Delta (MHz)3 - dispersive shift 2Chi (MHz)4 - Ramsey decay time T2* (us)5 - exp(-t_meas/T1) (us), only if starting from |1> (to include relaxation during the 1st msm't)6 - initial qubit state (0/1)'''params = [2*np.pi*p for p in params[:3]] + params[3:] # convert to angular frequenciesdef model_0(t, pa, pb):return (-np.imag(np.exp(-(1/params[3]+params[1]*1j)*t + (pa-pb*params[2]*(1-np.exp(-((params[0] + params[2]*1j)*t)))/(params[0]+params[2]*1j))*1j)))def model(t, pa, pb):return  params[4]*model_0(t, pa, pb) + (1-params[4])*model_0(t, pa+np.pi, pb) if params[5] == 1  else model_0(t, pa, pb)popt, pcov = curve_fit(model, xdata, ydata, p0 = [0, 1])perr = np.sqrt(np.diag(pcov))finer_delays = np.linspace(np.min(xdata), np.max(xdata), 4*len(xdata))fit_curve = model(finer_delays, *popt)return popt[1], perr[1], (finer_delays, fit_curve)

项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码

def find_null_offset(xpts, powers, default=0.0):"""Finds the offset corresponding to the minimum power using a fit to the measured data"""def model(x, a, b, c):return a*(x - b)**2 + cpowers = np.power(10, powers/10.)min_idx = np.argmin(powers)try:fit = curve_fit(model, xpts, powers, p0=[1, xpts[min_idx], powers[min_idx]])except RuntimeError:logger.warning("Mixer null offset fit failed.")return default, np.zeros(len(powers))best_offset = np.real(fit[0][1])best_offset = np.minimum(best_offset, xpts[-1])best_offset = np.maximum(best_offset, xpts[0])xpts_fine = np.linspace(xpts[0],xpts[-1],101)fit_pts = np.array([np.real(model(x, *fit[0])) for x in xpts_fine])if min(fit_pts)<0: fit_pts-=min(fit_pts)-1e-10 #prevent log of a negative numberreturn best_offset, xpts_fine, 10*np.log10(fit_pts)

项目:dataArtist    作者:radjkarl    | 项目源码 | 文件源码

def activate(self):if self.pMethod.value() == 'Poisson':v = self.pPlot.value()index = Noneif v != 'All':# index here if specific plot chosenindex = self.pPlot.opts['limits'].index(v) - 1plots = self.display.widget.getData(index)for plot in plots:# fit with curve_fitx, y = plot.x, plot.yif not self.guess:self.guess = _Poisson.initGuess(x, y)parameters, cov_matrix = curve_fit(_Poisson.function, x, y, self.guess)# plot poisson-deviation with fitted parameterx_vals = self._getXVals()y_vals = _Poisson.function(x_vals, *parameters)self.display.addLayer(data=(x_vals, y_vals),filename='X - Poission fitted')

项目:Thrifty    作者:swkrueger    | 项目源码 | 文件源码

def make_dirichlet(block_len, carrier_len, width=6):def _fit_model(xdata, amplitude, time_offset):xdata = np.array(xdata, dtype=np.float64)dirichlet = _dirichlet_kernel(xdata-time_offset,block_len,carrier_len)return amplitude * np.abs(dirichlet)def _interpolator(fft_mag, peak):xdata = np.array(np.arange(-(width//2), width//2+1))ydata = fft_mag[peak + xdata]initial_guess = (fft_mag[peak], 0)popt, _ = curve_fit(_fit_model, xdata, ydata, p0=initial_guess)_, fit_offset = poptreturn fit_offsetreturn _interpolator

项目:GPfates    作者:Teichlab    | 项目源码 | 文件源码

def identify_bifurcation_point(omgp, n_splits=30):''' Linear breakpoint model to infer drastic likelihood decrease'''mix_m = OMGP(omgp.X, omgp.Y, K=omgp.K, kernels=omgp.kern)mix_m.variance = omgp.variancephi = omgp.philog_liks = []t_splits = np.linspace(mix_m.X.min(), mix_m.X.max(), n_splits)for t_s in tqdm(t_splits):mask = mix_m.X > t_sphi_mix = np.ones_like(phi) * 0.5phi_mix[mask[:, 0]] = phi[mask[:, 0]]mix_m.phi = phi_mixlog_liks.append(mix_m.log_likelihood())x = t_splitsy = np.array(log_liks)p, e = optimize.curve_fit(breakpoint_linear, x, y)return p[0]

项目:social-media-pulse    作者:jrmontag    | 项目源码 | 文件源码

def optimize(self):"""Applies the chosen optimization technique to the model's evaluate method and the appropriate data structures.  """ # use helper method to possibly narrow data by user-entered window x, y = self.data.get_data_to_fit()# optimize based on model-specific evaluate() optimal_params, covar = sp_optimize.curve_fit( self.model.evaluate,x, y, self.model.parameters )# store the final fit parameters and covariance in the model object for JIT calculationsself.model.parameters = optimal_paramsself.model.covariance = covarreturn optimal_params, covar

项目:pynephoscope    作者:neXyon    | 项目源码 | 文件源码

def findStar(self, x, y):x = int(x)y = int(y)roi_size = Configuration.gaussian_roi_sizeroi = self.image[y - roi_size:y + roi_size + 1, x - roi_size:x + roi_size + 1]X, Y = np.meshgrid(range(x - roi_size, x + roi_size + 1), range(y - roi_size, y + roi_size + 1))p0 = (1, x, y, 1, 0, 1)try:popt, _ = optimize.curve_fit(self.gaussBivarFit, (X, Y), roi.ravel(), p0=p0, maxfev=10000)except Exception as e:return 0, (0, 0), np.matrix([[0, 0], [0, 0]]), roiA, x0, y0, v1, v2, v3 = poptcov = np.matrix([[v1, v2 / 2], [v2 / 2, v3]]).Imu = (x0, y0)return A, mu, cov, roi

项目:qmflows-namd    作者:SCM-NV    | 项目源码 | 文件源码

def dephasing(f):"""Computes the dephasing time of a given function using optical responseformalisms:S. Mukamel, Principles of Nonlinear Optical Spectroscopy, 1995About the implementation we use the 2nd order cumulant expansion.See also eq. (2) in : Kilina et al. Phys. Rev. Lett., 110, 180404, (2013)To calculate the dephasing time tau we fit the dephasing function to agaussian of the type : exp(-0.5 * (-x / tau) ** 2)"""ts = np.arange(f.shape[0])cumu_ii = np.stack(np.sum(f[0:i]) for i in range(ts.size)) / hbarcumu_i = np.stack(np.sum(cumu_ii[0:i]) for i in range(ts.size)) / hbardeph = np.exp(-cumu_i)np.seterr(over='ignore')popt = curve_fit(gauss_function, ts, deph)[0]xs = np.exp(-0.5 * (-ts / popt[0]) ** 2)deph = np.column_stack((deph, xs))rate = popt[0]return deph, rate

项目:WXMLTilingsHOWTO    作者:maxieds    | 项目源码 | 文件源码

def fit_SaddleConnGoldenL_pdf(hist_data, xdata, ydata, hrange): [sl, su] = hrange[fl, fu] = [2.3528, 8.1976]b = (fu - fl) / (su - sl)c = fu - b * su#if len(xdata) > 2 * MAX_FIT_POINTS: # trim to the middle 9000 x values#     idxl, idxu = len(xdata) / 2 - MAX_FIT_POINTS/4, len(xdata) / 2 + MAX_FIT_POINTS/4#     endu = len(xdata) - MAX_FIT_POINTS / 4 - 1#     xdata = list(xdata)[idxl:idxu+1] + list(xdata)[0:MAX_FIT_POINTS/4+1] + list(xdata)[endu:]#     ydata = list(ydata)[idxl:idxu+1] + list(ydata)[0:MAX_FIT_POINTS/4+1] + list(ydata)[endu:]### it appears that scipy has a bug, let's do an adjustment to make it go away:if len(ydata) - len(xdata) == 1:ydata = ydata[:-1]##fit_func_v1 = lambda x, a, b, c, d: a * sc_fitfunc(b*x+c) + dfit_func = lambda x, a, d: fit_func_v1(x, a, b, c, d)p, pcov = curve_fit(fit_func, xdata, ydata)#, bounds = ([0,0], [10,10]))print p, pcovreturn lambda x: fit_func(x, p[0], p[1]), (1 - c) / b, [p[0], b, c, p[1]]##

项目:BigDataML    作者:azheng333    | 项目源码 | 文件源码

def fun():T = [1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968]S = [29.72, 30.61, 31.51, 32.13, 32.34, 32.85, 33.56, 34.20, 34.83]xdata = np.array(T)ydata = np.log(np.array(S))def func(x, a, b):return a + b * x# ??????????????popt, pcov = curve_fit(func, xdata, ydata)plt.figure()plt.plot(xdata, ydata, 'ko', label="Original Noised Data")plt.plot(xdata, func(xdata, *popt), 'r', label="Fitted Curve")plt.show()plt.savefig('test.png')

项目:Optics    作者:danustc    | 项目源码 | 文件源码

def psf_zplane(stack, dz, w0, de = 1):'''determine the position of the real focal plane.Don't mistake with psf_slice!'''nz, ny, nx = stack.shapecy, cx = np.unravel_index(np.argmax(gf(stack,2)), (nz,ny,nx))[1:]zrange = (nz-1)*dz*0.5zz = np.linspace(-zrange, zrange, nz)center_z = stack[:,cy-de:cy+de+1,cx-de:cx+de+1]im_z = center_z.mean(axis=2).mean(axis=1)b = np.mean((im_z[0],im_z[-1]))a = im_z.max() - bp0 = (a,0,w0,b)popt = optimize.curve_fit(gaussian, zz, im_z, p0)[0]z_offset = popt[1] # The original version is wrongreturn z_offset, zz

项目:Optics    作者:danustc    | 项目源码 | 文件源码

def psf_zplane(stack, dz, w0, de = 1):'''determine the position of the real focal plane.Don't mistake with psf_slice!'''nz, ny, nx = stack.shapecy, cx = np.unravel_index(np.argmax(gf(stack,2)), (nz,ny,nx))[1:]zrange = (nz-1)*dz*0.5zz = np.linspace(-zrange, zrange, nz)center_z = stack[:,cy-de:cy+de+1,cx-de:cx+de+1]im_z = center_z.mean(axis=2).mean(axis=1)b = np.mean((im_z[0],im_z[-1]))a = im_z.max() - bp0 = (a,0,w0,b)popt = optimize.curve_fit(gaussian, zz, im_z, p0)[0]z_offset = popt[1] # The original version is wrongreturn z_offset, zz

项目:Ship    作者:jarlekramer    | 项目源码 | 文件源码

def __init__(self, A, h, alpha, CL, CD, x0=0.95):rho = 1025super().__init__(A, h, alpha, CL, CD, rho)self.x0 = x0# Create force functions based on input datafitParams, fitCovariances = curve_fit(liftFunc, self.alpha, self.CL)self.CL_a1 = fitParams[0]fitParams, fitCovariances = curve_fit(dragFunc, self.alpha, self.CD)self.CD_a0 = fitParams[0]self.CD_a2 = fitParams[1]# Max and min alphaself.alpha_min = 0self.alpha_max = 30*np.pi/180

项目:Ship    作者:jarlekramer    | 项目源码 | 文件源码

def __init__(self, A, h, alpha, CL, CD, x0=0.95):rho = 1025self.removeBaseDrag = Truesuper().__init__(A, h, alpha, CL, CD, rho)self.x0 = x0# Create force functions based on input datafitParams, fitCovariances = curve_fit(liftFunc, self.alpha, self.CL)self.CL_a1 = fitParams[0]fitParams, fitCovariances = curve_fit(dragFunc, self.alpha, self.CD)self.CD_a0 = fitParams[0]self.CD_a2 = fitParams[1]# Max and min alphaself.alpha_min = 0self.alpha_max = 40*np.pi/180self.alpha_max = 30*np.pi/180

项目:Ship    作者:jarlekramer    | 项目源码 | 文件源码

def setDriftData(self, alpha, CL, CDi, CM):self.alpha = alphaself.CL    = CLself.CDi   = CDiself.CM    = CM# Calculate coefficients for liftfitParams, fitCovariances = curve_fit(liftFunc, self.alpha, self.CL)self.CL_a1 = fitParams[0]self.CL_a2 = fitParams[1]# Calculate coefficients for induced dragfitParams, fitCovariances = curve_fit(inducedDragFunc, self.alpha, self.CDi)self.CDi_a2 = fitParams[0]# Spline interpolation for momentself.CMspl = interpolate.splrep(self.alpha, self.CM, s=1e-9)

项目:WellApplication    作者:inkenbrandt    | 项目源码 | 文件源码

def ratingCurve(discharge, stage):"""Computes rating curve based on discharge measurements coupled with stagereadings.discharge = array of measured discharges;stage = array of corresponding stage readings;Returns coefficients a, b for the rating curve in the form y = a * x**bhttps://github.com/hydrogeog/hydro/blob/master/hydro/core.py"""from scipy.optimize import curve_fitexp_curve = lambda x, a, b: (a * x ** b)popt, pcov = curve_fit(exp_curve, stage, discharge)a = 0.0b = 0.0for i, j in zip(discharge, stage):a += (i - exp_curve(j, popt[0], popt[1]))**2b += (i - np.mean(discharge))**2r_squ = 1 - a / breturn popt, r_squ

项目:WellApplication    作者:inkenbrandt    | 项目源码 | 文件源码

def ratingCurve(discharge, stage):"""Computes rating curve based on discharge measurements coupled with stagereadings.discharge = array of measured discharges;stage = array of corresponding stage readings;Returns coefficients a, b for the rating curve in the form y = a * x**b"""from scipy.optimize import curve_fitpopt, pcov = curve_fit(exp_curve, stage, discharge)def r_squ():a = 0.0b = 0.0for i, j in zip(discharge, stage):a += (i - exp_curve(j, popt[0], popt[1]))**2b += (i - np.mean(discharge))**2return 1 - a / breturn popt, r_squ()

项目:dragonboard_testbench    作者:cta-observatory    | 项目源码 | 文件源码

def fit(df, cell, plot=False):big_time = df.delta_t.quantile(0.75)p0 = [1.3,-0.38,df.adc_counts[df.delta_t >= big_time].mean(),]try:(a, b, c), cov = curve_fit(f,df['delta_t'],df['adc_counts'],p0=p0,)except RuntimeError:logging.error('Could not fit cell {}'.format(cell))return np.full(4, np.nan)ndf = len(df.index) - 3residuals = df['adc_counts'] - f(df['delta_t'], a, b, c)chisquare = np.sum(residuals**2) / ndfreturn a, b, c, chisquare

项目:ProtScan    作者:gianlucacorrado    | 项目源码 | 文件源码

def fit_optimal(blocks, keys):"""Fit the cumulative distribution, by optimization."""values = list()for k in keys:values.extend([max_val for (_, _, max_val) in blocks[k]])hist, bin_edges = np.histogram(values, bins=100, normed=True)bin_centers = np.array([(bin_edges[i - 1] + bin_edges[i]) / 2for i in range(1, len(bin_edges))])cumulative = np.cumsum(hist) / np.sum(hist)popt, _ = optimize.curve_fit(func, bin_centers, cumulative)return popt

项目:atoolbox    作者:liweitianux    | 项目源码 | 文件源码

def fit_model(func, xdata, ydata, yerrdata, p0):"""Fit the provided data with the beta model.Arguments:p0: initial values for the parameters of beta modelReturn:(popt, infodict)popt: optimal values for the parametersinfodict:* fvec: the function evaluated at the output parameters* dof: degree of freedom* chisq: chi-squared* perr: one standard deviation errors on the parameters"""popt, pcov = curve_fit(func, xdata, ydata, p0=p0, sigma=yerrdata)# the function evaluated at the output parametersfvec = lambda x: func(x, *popt)# degree of freedomdof = len(xdata) - len(popt) - 1# chi squaredchisq = np.sum(((ydata - fvec(xdata)) / yerrdata) ** 2)# one standard deviation errors on the parametersperr = np.sqrt(np.diag(pcov))infodict = {'fvec': fvec,'dof': dof,'chisq': chisq,'perr': perr}return (popt, infodict)

项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码

def fit_drag(data, DRAG_vec, pulse_vec):"""Fit calibration curves vs DRAG parameter, for variable number of pulses"""num_DRAG = len(DRAG_vec)num_seqs = len(pulse_vec)xopt_vec = np.zeros(num_seqs)perr_vec = np.zeros(num_seqs)popt_mat = np.zeros((4, num_seqs))data = data.reshape(len(data)//num_DRAG, num_DRAG)#first fit sine to lowest n, for the full rangedata_n = data[1, :]T0 = 2*(DRAG_vec[np.argmax(data_n)] - DRAG_vec[np.argmin(data_n)]) #rough estimate of periodp0 = [0, 1, T0, 0]popt, pcov = curve_fit(sinf, DRAG_vec, data_n, p0 = p0)perr_vec[0] = np.sqrt(np.diag(pcov))[0]x_fine = np.linspace(min(DRAG_vec), max(DRAG_vec), 1001)xopt_vec[0] = x_fine[np.argmin(sinf(x_fine, *popt))]popt_mat[:,0] = poptfor ct in range(1, len(pulse_vec)):#quadratic fit for subsequent steps, narrower rangedata_n = data[ct, :]p0 = [1, xopt_vec[ct-1], 0]#recenter for next fitclosest_ind =np.argmin(abs(DRAG_vec - xopt_vec[ct-1]))fit_range = int(np.round(0.5*num_DRAG*pulse_vec[0]/pulse_vec[ct]))curr_DRAG_vec = DRAG_vec[max(0, closest_ind - fit_range) : min(num_DRAG-1, closest_ind + fit_range)]reduced_data_n = data_n[max(0, closest_ind - fit_range) : min(num_DRAG-1, closest_ind + fit_range)]#quadratic fitpopt, pcov = curve_fit(quadf, curr_DRAG_vec, reduced_data_n, p0 = p0)perr_vec[ct] = np.sqrt(np.diag(pcov))[0]x_fine = np.linspace(min(curr_DRAG_vec), max(curr_DRAG_vec), 1001)xopt_vec[ct] = x_fine[np.argmin(quadf(x_fine, *popt))] #why not x0?popt_mat[:3,ct] = poptreturn xopt_vec, perr_vec, popt_mat

项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码

def fit_quad(xdata, ydata):popt, pcov = curve_fit(quadf, xdata, ydata, p0 = [1, min(ydata), 0])perr = np.sqrt(np.diag(pcov))return popt, perr

项目:modesolverpy    作者:jtambasco    | 项目源码 | 文件源码

def fit_gaussian(x, y, z_2d, save_fits=False):z = z_2dmax_idx = np.unravel_index(z.argmax(), z.shape)max_row = max_idx[0] - 1max_col = max_idx[1] - 1z_max_row = z[max_row, :]z_max_col = z[:, max_col]A = z[max_row, max_col]p_guess_x = (A, x[max_col], 0.1*(x[-1] - x[0]))p_guess_y = (A, y[max_row], 0.1*(y[-1] - y[0]))coeffs_x, var_matrix_x = sciopt.curve_fit(gaussian, x, z_max_row, p_guess_x)coeffs_y, var_matrix_y = sciopt.curve_fit(gaussian, y, z_max_col, p_guess_y)c_x = (x[-1]-x[0])*(max_col+1)/x.size + x[0]c_y = (y[-1]-y[0])*(y.size-(max_row+1))/y.size + y[0]centre = (c_x, c_y)sigma = np.array([coeffs_x[2], coeffs_y[2]])fwhm = 2.355 * sigmasigma_2 = 1.699 * fwhmif save_fits:with open('x_fit.dat', 'w') as fs:for c in np.c_[x, z_max_row, gaussian(x, *coeffs_x)]:s = ','.join([str(v) for v in c])fs.write(s+'\n')with open('y_fit.dat', 'w') as fs:for c in np.c_[y, z_max_col, gaussian(y, *coeffs_y)]:s = ','.join([str(v) for v in c])fs.write(s+'\n')return A, centre, sigma_2

项目:pystudio    作者:satorchi    | 项目源码 | 文件源码

def fit_Pbath(T_pts, P_pts):'''find best fit to the P_bath function'''# make sure T_pts and P_pts are 1d arraysnpts=len(T_pts)T=np.array(T_pts).reshape(npts)P=np.array(P_pts).reshape(npts)try:ret=curve_fit(P_bath_function,T,P)except:print('insufficient data for TES %i' % TES)ret=Nonereturn ret

项目:accpy    作者:kramerfelix    | 项目源码 | 文件源码

def myfit(x, y, betagamma, qL, orientation, T, yerr=None, krange=[]):if len(krange) != 0:# trim to given rangebooleanrange = [(x >= krange[0]) & (x <= krange[1])]x = x[booleanrange]y = y[booleanrange]if yerr is None:popt, pcov = curve_fit(fun, x, y, sigma=None)else:if len(krange) != 0:yerr = yerr[booleanrange]popt, pcov = curve_fit(fun, x, y, sigma=yerr, absolute_sigma=True)x = linspace(x[0], x[-1], 1e3)fit = fun(x, *popt)perr = sqrt(diag(pcov))A = array([popt[0], perr[0]])/qL**2B = array([popt[1], perr[1]])/qL*orientationC = array([popt[2], perr[2]])eps, bet, alp, gam = twissfromparabola(A, B, C, T)epsn = betagamma*eps*1e6eps *= 1e9string = (r'$\beta=%.2f \pm %.2f$''\n'r'$\alpha=%.2f \pm %.2f$''\n'r'$\gamma=%.2f \pm %.2f$''\n'r'$\epsilon=(%.2f \pm %.2f)\pi\, nm\, rad$''\n'r'$\epsilon^*=(%.2f \pm %.2f)\pi\, \mu m\, rad$'% (bet[0], bet[1], alp[0], alp[1], gam[0], gam[1],eps[0], eps[1], epsn[0], epsn[1]))return x, fit, string

项目:accpy    作者:kramerfelix    | 项目源码 | 文件源码

def dofit(xdata, ydata, betagamma, T, dE, D, QL, orientation, yerr=None,krange=[]):# make sure that k is positive k = abs(g)/Brho_0xdata = abs(xdata)if len(krange) != 0:# trim to given rangexdata = xdata[krange]ydata = ydata[krange]yerr = yerr[krange]if yerr is None:popt, pcov = curve_fit(fun, xdata, ydata, sigma=None)else:popt, pcov = curve_fit(fun, xdata, ydata, sigma=yerr, absolute_sigma=True)fit = fun(xdata, *popt)perr = np.sqrt(np.diag(pcov))A = np.array([popt[0], perr[0]])B = np.array([popt[1], perr[1]])C = np.array([popt[2], perr[2]])eps, bet, alp, gam = twissfromparabola(A, B, C, T, dE, D, QL, orientation)epsn = betagamma*eps*1e6eps *= 1e9A *= 1e9B *= 1e9C *= 1e9string = (r'$function:\;y=ax^2+bx+c$''\n'r'$a=(%.2f \pm %.2f)\cdot10^{-9}$''\n'r'$b=(%.2f \pm %.2f)\cdot10^{-9}$''\n'r'$c=(%.2f \pm %.2f)\cdot10^{-9}$''\n'r'$\beta=%.2f \pm %.2f$''\n'r'$\alpha=%.2f \pm %.2f$''\n'r'$\gamma=%.2f \pm %.2f$''\n'r'$\epsilon=(%.2f \pm %.2f)\pi\, nm\, rad$''\n'r'$\epsilon^*=(%.2f \pm %.2f)\pi\, \mu m\, rad$'% (A[0], A[1], B[0], B[1], C[0], C[1],bet[0], bet[1], alp[0], alp[1], gam[0], gam[1],eps[0], eps[1], epsn[0], epsn[1]))return string, fit, xdata

项目:accpy    作者:kramerfelix    | 项目源码 | 文件源码

def parabolafit(xdata, ydata, init, sigma):popt, pcov = curve_fit(fun, xdata, ydata, p0=init, sigma=sigma)perr = np.sqrt(np.diag(pcov))x = np.linspace(min(xdata), max(xdata), 1e3)fit = fun(x, *popt)A = np.array([popt[0], perr[0]])B = np.array([popt[1], perr[1]])C = np.array([popt[2], perr[2]])return x, fit, A, B, C

项目:georges    作者:chernals    | 项目源码 | 文件源码

def bpm_fit(a, p):if a is None:return Nonex = a['channel']['data'][p][:, 1]y = a['channel']['data'][p][:, 2]ar = np.trapz(y / np.sum(y) * len(y), x)mean = np.mean(x * y / np.sum(y) * len(y))rms = np.std(x * y / np.sum(y) * len(y))popt, pcov = curve_fit(gaussian, x, y, p0=[ar, mean, rms])return [popt, np.sqrt(pcov.diagonal())]

项目:georges    作者:chernals    | 项目源码 | 文件源码

def variquad_fit(x, y):popt, pcov = curve_fit(quadratic, x, y, p0=[0, 0, 1])return [popt, np.sqrt(pcov.diagonal())]

项目:nmmn    作者:rsnemmen    | 项目源码 | 文件源码

def _peakdetect_parabole_fitter(raw_peaks, x_axis, y_axis, points):"""Performs the actual parabole fitting for the peakdetect_parabole function.keyword arguments:raw_peaks -- A list of either the maximium or the minimum peaks, as givenby the peakdetect_zero_crossing function, with index used as x-axisx_axis -- A numpy list of all the x valuesy_axis -- A numpy list of all the y valuespoints -- How many points around the peak should be used during curvefitting, must be odd.return -- A list giving all the peaks and the fitted waveform, format:[[x, y, [fitted_x, fitted_y]]]"""func = lambda x, k, tau, m: k * ((x - tau) ** 2) + mfitted_peaks = []for peak in raw_peaks:index = peak[0]x_data = x_axis[index - points // 2: index + points // 2 + 1]y_data = y_axis[index - points // 2: index + points // 2 + 1]# get a first approximation of tau (peak position in time)tau = x_axis[index]# get a first approximation of peak amplitudem = peak[1]# build list of approximations# k = -m as first approximation?p0 = (-m, tau, m)popt, pcov = curve_fit(func, x_data, y_data, p0)# retrieve tau and m i.e x and y value of peakx, y = popt[1:3]# create a high resolution data set for the fitted waveformx2 = np.linspace(x_data[0], x_data[-1], points * 10)y2 = func(x2, *popt)fitted_peaks.append([x, y, [x2, y2]])return fitted_peaks

项目:frc_rekt    作者:jaustinpage    | 项目源码 | 文件源码

def _fit_func_factory(a=None, b=None, c=None, d=None, e=None):# Specific with correctionif a and b and c and d and e:def func(x):"""Specific Function."""return a * ((b * (x + c))**d) + e# Specific without correctionelif a and b and c and d:def func(x):"""Specific Function."""return a * ((b * (x + c))**d)# Generic, which we have scipy.optimize.curve_fit run on# scipy.optimize.curve_fit will then give us a, b, c, d,# however, scipy.optimize has touble with e. We correct e "by hand"# at the end.else:def func(x, a, b, c, d):"""Unparameterized Function."""return a * ((b * (x + c))**d)return func

项目:frc_rekt    作者:jaustinpage    | 项目源码 | 文件源码

def _generate_func_fit(func_factory, x, y):popt, pcov = optimize.curve_fit(func_factory(), x, y)logging.debug(popt)logging.debug(pcov)# Static shift to have the end condition be niceunshifted_func = func_factory(*popt)end_diff = y.iloc[-1] - unshifted_func(x.iloc[-1])logging.debug("end diff: %s", end_diff)popt_shifted = np.append(popt, end_diff)return func_factory(*popt_shifted)

项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码

def fit(self, lambdav, fluxv, sigmav):if np.all(np.asarray(fluxv)>0):popt, pcov = curve_fit(self._bound_greybody, lambdav, fluxv, p0=(17,1e7), sigma=sigmav,absolute_sigma=False, maxfev=5000)return poptelse:return (0,0)# ----------------------------------------------------------------------

项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码

def fit(self, lambdav, fluxv, sigmav):if np.all(np.asarray(fluxv)>0):popt, pcov = curve_fit(self._bound_greybody, lambdav, fluxv, p0=(17,1e7), sigma=sigmav,absolute_sigma=False, maxfev=5000)return poptelse:return (0,0)# ----------------------------------------------------------------------

项目:Orbit-Fitting    作者:jacob-i-skinner    | 项目源码 | 文件源码

def initialGuessNoE(lower, upper, JDp, RVp):'''Make a guess of the values of the elements, assuming it is circular.Parameters----------lower : list(ndim)Lower bounds of the orbital elements.upper : list(ndim)Upper bounds of the orbital elements.JDp : listTimes of observation of the primary component.RVp : listRadial velocities of the primary component.Returns-------(K, T, P, y) : listOutput from curve_fit.'''from scipy.optimize import curve_fit# This is a simple harmonic function.def alteredNoERV(x, K, T, P, y):return K*cos((2*pi/P)*(x-T))+yreturn curve_fit(alteredNoERV, JDp, np.asarray(RVp), bounds=(lower, upper))[0]

项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码

def scaleSignal(img, fitParams=None,backgroundToZero=False, reference=None):'''scale the image between...backgroundToZero=True -> 0 (average background) and 1 (maximum signal)backgroundToZero=False -> signal+-3stdreference -> reference image -- scale image to fit this onereturns:scaled image'''img = imread(img)if reference is not None:#         def fn(ii, m,n):#             return ii*m+n#         curve_fit(fn, img[::10,::10], ref[::10,::10])low, high = signalRange(img, fitParams)low2, high2 = signalRange(reference)img = np.asfarray(img)ampl = (high2 - low2) / (high - low)img -= lowimg *= amplimg += low2return imgelse:offs, div = scaleParams(img, fitParams, backgroundToZero)img = np.asfarray(img) - offsimg /= divprint('offset: %s, divident: %s' % (offs, div))return img

项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码

def scaleParamsFromReference(img, reference):# saving startup time:from scipy.optimize import curve_fitdef ff(arr):arr = imread(arr, 'gray')if arr.size > 300000:arr = arr[::10, ::10]m = np.nanmean(arr)s = np.nanstd(arr)r = m - 3 * s, m + 3 * sb = (r[1] - r[0]) / 5return arr, r, bimg, imgr, imgb = ff(img)reference, refr, refb = ff(reference)nbins = np.clip(15, max(imgb, refb), 50)refh = np.histogram(reference, bins=nbins, range=refr)[0].astype(np.float32)imgh = np.histogram(img, bins=nbins, range=imgr)[0].astype(np.float32)import pylab as pltplt.figure(1)plt.plot(refh)plt.figure(2)plt.plot(imgh)plt.show()def fn(x, offs, div):return (x - offs) / divparams, fitCovariances = curve_fit(fn, refh, imgh, p0=(0, 1))perr = np.sqrt(np.diag(fitCovariances))print('error scaling to reference image: %s' % perr[0])# if perr[0] < 0.1:return params[0], params[1]

项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码

def _fit(x, y):popt, _ = curve_fit(function, x, y, check_finite=False)return popt

项目:CElegansBehaviour    作者:ChristophKirst    | 项目源码 | 文件源码

def g(x,a,b):return a * np.exp(b * ()popt, pcov = opt.curve_fit(f, xdata, w, p0 = (0.1, 10));plt.figure(1); plt.clf();
plt.plot(xdata, w)
plt.plot(xdata, f(xdata, *popt), 'r')
plt.title(str(popt))

项目:Wind-Turbine-Design    作者:doublerob7    | 项目源码 | 文件源码

def sigmoid(x, x0, k):import numpy as npimport pylabfrom scipy.optimize import curve_fity = 1 / (1 + np.exp(-k*(x-x0)))return y

项目:scrap    作者:BruceJohnJennerLawso    | 项目源码 | 文件源码

def __init__(self, data, mleValue, fitParameters=True, a=None, b=None):super(uniformModel, self).__init__(data)self.MLE = mleValueif(None in [a,b]):fitParameters = Trueif(fitParameters):self.b = max(self.getDataSet())self.a = min(self.getDataSet())def uniDist(x, a, b):return scipy.where((a<=x) & (x<=b), 1.0/float(b-a), 0.0)try:self.n, self.bins, patches = plt.hist(self.getDataSet(), self.getDatasetSize()/10, normed=1, facecolor='blue', alpha = 0.55)popt,pcov = curve_fit(uniDist,self.bins[:-1], self.n, p0=[self.a, self.b])##plt.plot(bins[:-1], gaus(bins[:-1],*popt),'c-',label="Gaussian Curve with params\na=%f\nx0=%f\nsigma=%f" % (popt[0], popt[1], popt[2]), alpha=0.5)print "Fitted uniform distribution pdf curve to data with params a %f, b %f" % (popt[0], popt[1])self.a = popt[0]self.b = popt[1]##self.sigma = popt[2]self.fitted = Trueexcept RuntimeError:print "Unable to fit data to uniform distribution pdf curve"raiseexcept Warning:raise RuntimeErrorelse:self.a = aself.b = b

项目:scrap    作者:BruceJohnJennerLawso    | 项目源码 | 文件源码

def __init__(self, data, mleValue, fitParameters=True, mean=None, sigma=None):super(normalModel, self).__init__(data)self.MLE = mleValueif(None in [mean, sigma]):fitParameters=Trueif(fitParameters):mean = Mean(self.getDataSet())      sigma = standardDeviation(self.getDataSet())try:def normDist(x, x0, sigma):output = 1.0/sqrt(2*np.pi*(sigma**2))output *= exp(-0.5*((x - x0)/sigma)**2)return outputself.n, self.bins, patches = plt.hist(self.getDataSet(), self.getDatasetSize()/10, normed=1, facecolor='blue', alpha = 0.55)popt,pcov = curve_fit(normDist,self.bins[:-1], self.n, p0=[mean, sigma])##plt.plot(bins[:-1], gaus(bins[:-1],*popt),'c-',label="Gaussian Curve with params\na=%f\nx0=%f\nsigma=%f" % (popt[0], popt[1], popt[2]), alpha=0.5)print "Fitted gaussian curve to data with params x0 %f, sigma %f" % (popt[0], popt[1])self.x0 = popt[0]self.sigma = popt[1]self.fitted = Trueexcept RuntimeError:print "Unable to fit data to normal curve, runtime error"raiseexcept Warning:raise RuntimeErrorelse:self.x0 = meanself.sigma = sigma

项目:scrap    作者:BruceJohnJennerLawso    | 项目源码 | 文件源码

def __init__(self, data, mleValue, fitParameters=True, mean=None):super(exponentialModel, self).__init__(data)self.MLE = mleValueif(None in [mean]):fitParameters = Trueif(fitParameters):mean = Mean(self.getDataSet())      try:def expDist(x, x0):return (exp(-(x/x0))/x0)self.n, self.bins, patches = plt.hist(self.getDataSet(), self.getDatasetSize()/10, normed=1, facecolor='blue', alpha = 0.55)popt,pcov = curve_fit(expDist,self.bins[:-1], self.n, p0=[mean])##plt.plot(bins[:-1], gaus(bins[:-1],*popt),'c-',label="Gaussian Curve with params\na=%f\nx0=%f\nsigma=%f" % (popt[0], popt[1], popt[2]), alpha=0.5)print "Fitted gaussian curve to data with params x0 %f" % (popt[0])self.x0 = popt[0]##self.sigma = popt[2]self.fitted = Trueexcept RuntimeError:print "Unable to fit data to exponential curve"raiseexcept Warning:raise RuntimeErrorelse:self.x0 = mean

项目:PyCS    作者:COSMOGRAIL    | 项目源码 | 文件源码

def calcslope(self, fmin=1./1000.0, fmax=1./2.0):"""Measures the slope of the PS, between fmin and fmax.All info about this slope is sored into the dictionnary self.slope.Should this depend on self.flux ?? No, only the constructor depends on this !This is just fitting the powerspectrum as given by the constructor."""if fmin == None:fmin = self.f[1]if fmax == None:fmax = self.f[-1]reg = np.logical_and(self.f <= fmax, self.f >= fmin)fitx = np.log10(self.f[reg]).flatten()fity = np.log10(self.p[reg]).flatten()if not np.all(np.isfinite(fity)):print "Skipping calcsclope for flat function !"returnself.slope = {}def func(x, m, h):return m*x + hpopt = spopt.curve_fit(func, fitx, fity, p0=[0.0, 0.0])[0]sepfit = func(fitx, popt[0], popt[1]) # we evaluate the linear fit.self.slope["slope"] = popt[0]self.slope["f"] = 10.0**fitxself.slope["p"] = 10.0**sepfitself.slope["fmin"] = fminself.slope["fmax"] = fmax

项目:upho    作者:yuzie007    | 项目源码 | 文件源码

def _create_initial_peak_position(self, frequencies, sf, prec=1e-12):position = frequencies[np.argmax(sf)]# "curve_fit" does not work well for extremely small initial guess.# To avoid this problem, "position" is rounded.# See also "http://stackoverflow.com/questions/15624070"if abs(position) < prec:position = 0.0return position

项目:pyrl    作者:frsong    | 项目源码 | 文件源码

def fit_psychometric(xdata, ydata, func=None, p0=None):"""Fit a psychometric function."""if func is None:func = 'cdf_gaussian'if p0 is None:if func == 'cdf_gaussian':p0 = [np.mean(xdata), np.std(xdata)]elif func == 'cdf_gaussian_with_guessing':p0 = [np.mean(xdata), np.std(xdata), 0.1]else:raise ValueError("[ pycog.fittools.fit_psychometric ] Need initial guess p0.")if isinstance(func, str):func = fit_functions[func]popt_list, pcov_list = curve_fit(func, xdata, ydata, p0=p0)# Return parameters with namesargs = inspect.getargspec(func).argspopt = OrderedDict()for name, value in zip(args[1:], popt_list):popt[name] = valuereturn popt, func

项目:Dart_EnvGIS    作者:geojames    | 项目源码 | 文件源码

def expfit(x, p1, p2):return p1 * np.exp(p2*x)# popt, pcov = curve_fit(func, xdata, ydata)
#   popt = optimized parameters matrix (in the order they ar in your func)
#   pcov = covariance stats
#   p0 = (p1,p2,...) - initial guesses at the coeff, optional

项目:OilLibrary    作者:NOAA-ORR-ERD    | 项目源码 | 文件源码

def normalized_cut_values(self, N=10):f_res, f_asph, _estimated = self.inert_fractions()cuts = list(self.culled_cuts())if len(cuts) == 0:if self.record.api is not None:oil_api = self.record.apielse:oil_rho = self.density_at_temp(288.15)oil_api = est.api_from_density(oil_rho)BP_i = est.cut_temps_from_api(oil_api)fevap_i = np.cumsum(est.fmasses_flat_dist(f_res, f_asph))else:BP_i, fevap_i = zip(*[(c.vapor_temp_k, c.fraction) for c in cuts])popt, _pcov = curve_fit(_linear_curve, BP_i, fevap_i)f_cutoff = _linear_curve(732.0, *popt)  # center of asymptote (< 739)popt = popt.tolist() + [f_cutoff]fevap_i = np.linspace(0.0, 1.0 - f_res - f_asph, (N * 2) + 1)[1:]T_i = _inverse_linear_curve(fevap_i, *popt)fevap_i = fevap_i.reshape(-1, 2)[:, 1]T_i = T_i.reshape(-1, 2)[:, 0]above_zero = T_i > 0.0T_i = T_i[above_zero]fevap_i = fevap_i[above_zero]return T_i, fevap_i

python scipy拟合曲线optimize.curve_fit 50例相关推荐

  1. python scipy optimize_scipy.optimize.fminbound:设置参数的界限

    我正在尝试使用的fminbound函数优化函数scipy.optimize公司模块.我想设置参数边界以使答案在物理上合理(例如,&gt:0).在import scipy.optimize as ...

  2. python 曲线拟合(numpy.polyfit、scipy.optimize.curve_fit)

    小白的学习笔记,欢迎各位大神批评指正. python 曲线拟合 (一次二次比较简单,直接使用numpy中的函数即可,来自 <https://blog.csdn.net/yefengzhichen ...

  3. 50例源码Python scipy.stats.norm 模块,pdf()

    Python scipy.stats.norm 模块,pdf() 实例源码 转:http://codingdict.com/sources/py/scipy.stats.norm/13753.html ...

  4. python中curve fit_scipy.optimize.curve_fit函数用法解析

    在日常数据分析中,免不了要用到数据曲线拟合,而optimize.curve_fit()函数正好满足你的需求 scipy.optimize.curve_fit(f,xdata,ydata,p0=None ...

  5. python scipy.optimize.minimize多变量多参数优化

    python scipy.optimize.minimize多变量多参数优化 x是一维变量,无超参数 x是二维变量,无超参数,带bounds x是二维变量,有一个超参数,带bounds x是二维变量, ...

  6. scipy.optimize.curve_fit函数用法解析

    scipy.optimize.curve_fit函数用法解析 转:https://zhuanlan.zhihu.com/p/144353126 optimize.curve_fit()函数,用于日常数 ...

  7. 使用python scipy.optimize linprog和lingo线性规划求解最大值,最小值(运筹学学习笔记)

    1. 线性模型 2. 使用python scipy.optimize linprog求解模型最优解: 在这里我们用到scipy中的linprog进行求解,linprog的用法见https://docs ...

  8. python 使用scipy中的curve_fit拟合自定义曲线

    Scipy是一个用于数学.科学.工程领域的常用软件包,可以处理插值.积分.优化.图像处理.常微分方程数值解的求解.信号处理等问题.它用于有效计算Numpy矩阵,使Numpy和Scipy协同工作,高效解 ...

  9. scipy中的scipy.optimize.curve_fit

    scipy中的scipy.optimize.curve_fit 这里写目录标题 scipy中的scipy.optimize.curve_fit 参数 Return scipy.optimize.``c ...

  10. Python Scipy 科学计算库

    Python机器学习及分析工具:Scipy篇 原文:https://www.jianshu.com/p/6c742912047f   Scipy是一个用于数学.科学.工程领域的常用软件包,可以处理插值 ...

最新文章

  1. 安卓系统底层C语言算法之测试参数是几个long型的算法
  2. 图解10大机器学习算法
  3. java 静态变量的使用_java的static静态变量是不是不安全的?应该如何正确的使用他呢...
  4. 进展-Silverlight5、 windows phone 7、pc 三栖引擎,2D核心已完成
  5. 沙扬娜拉一首——赠日本女郎(徐志摩)
  6. Windows Server 2012远程默认端口3389的修改
  7. html文本框后面紧挨着按钮,Word题目与答案
  8. 在Java中用正则表达式判断一个字符串是否是数字的方法
  9. 百家号视频怎么消重批量处理去重消重去水印去logo软件视频MD5修改工具(短视频去重) 自媒体如何解...
  10. 浏览器中实现深度学习?有人分析了7个基于JS语言的DL框架
  11. python如何下载安装glfw_Python之OpenGL笔记(1):窗口工具包GLFW的安装
  12. 解析pubmed文献数据库的xml文章结构
  13. JAVA 时间和日期的API
  14. linux tty pty 的使用
  15. 增值税发票二维码解析
  16. 关于用Java程序实现8421码权限管理 -第三部分
  17. 使用IMS实现LTE的语音通话(VoLTE)
  18. 为什么JavaScript中的this如此强大?
  19. Matplotlib绘制雷达图
  20. Windows和Ubuntu双系统完全独立(双硬盘)的安装方法

热门文章

  1. 删除Linux Terminal中的历史记录
  2. 快递单号快速查询,自动识别快递公司
  3. Math常用的数学运算(包括取整、取绝对值、保留几位小数等)
  4. python解压文件并检查_python脚本简单实现对压缩文件是否加密的检测
  5. 性能优化-service进程防杀
  6. jsp主机与asp主机的区别和支持分析
  7. Linux查看公网IP和私网(内网)IP的方法
  8. 彩扩机项目--NPN和PNP三极管作为开关管的区别
  9. 电子取证技术--概述
  10. 2020年如何利用外链提升网站排名和权重?