本文整理汇总了Python中scipy.optimize.curve_fit方法的典型用法代码示例。如果您正苦于以下问题:Python optimize.curve_fit方法的具体用法?Python optimize.curve_fit怎么用?Python optimize.curve_fit使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.optimize
的用法示例。
在下文中一共展示了optimize.curve_fit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_dirichlet
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
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 = popt
return fit_offset
return _interpolator
示例2: find_ab_params
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def find_ab_params(spread, min_dist):
"""Fit a, b params for the differentiable curve used in lower
dimensional fuzzy simplicial complex construction. We want the
smooth curve (from a pre-defined family with simple gradient) that
best matches an offset exponential decay.
"""
def curve(x, a, b):
return 1.0 / (1.0 + a * x ** (2 * b))
xv = np.linspace(0, spread * 3, 300)
yv = np.zeros(xv.shape)
yv[xv < min_dist] = 1.0
yv[xv >= min_dist] = np.exp(-(xv[xv >= min_dist] - min_dist) / spread)
params, covar = curve_fit(curve, xv, yv)
return params[0], params[1]
示例3: get_at_timestamps
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def get_at_timestamps(sentence):
# audio_stamps = np.arange(sentence.shape[1]) * 30
audio_stamps = []
audio_len, char_len = sentence.shape
x = np.arange(audio_len)
for step in range(char_len):
slice = sentence[:, step]
try:
mean = np.argmax(slice)
# sigma = np.std(slice)
sigma = 0.5
p0 = [1, mean, sigma]
popt, pcov = curve_fit(gaussian, x, slice, p0=p0, maxfev=200000)
x2 = np.linspace(0, audio_len, audio_len * 10)
new_curve = gaussian(x2, *popt)
argmax_id = np.argmax(new_curve)
except:
argmax_id = np.argmax(slice) * 10
audio_stamps.append(argmax_id / 10)
audio_stamps = np.array(audio_stamps) * 30
return audio_stamps
示例4: fit_gaussian
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def fit_gaussian(x):
"""
Fit a Gaussian function to x and return its parameters
Parameters
----------
x : 1D np.array
1D profile of your data
Returns
-------
out : tuple of float
(a, mu, sigma, c)
"""
p, q = curve_fit(gaussian, list(range(x.size)), x, p0=guss_gaussian(x))
return p
示例5: curvefit
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def curvefit(self,correlation,time, begin,end):
#Fit the exponential functions to the correlation function to estimate the ion pair lifetime
funlist = [self.exponential1,self.exponential2,self.exponential3,self.exponential4,self.exponential5]
IPL = []
r2 = []
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for fun in funlist:
popt, pcov = curve_fit(fun, time[begin:end], correlation[begin:end],maxfev=100000000)
fit = []
for i in time:
fit.append(fun(i,*popt))
yave = np.average(correlation[begin:end])
SStot = 0
SSres = 0
for l in range(begin,end):
SStot += (correlation[l]-yave)**2
SSres += (correlation[l]-fit[l])**2
r2.append(1-SSres/SStot)
IPL.append(0)
for i in range(0,int(len(popt)/2)):
IPL[-1] += popt[i]*popt[i+int(len(popt)/2)]
return (IPL,r2)
示例6: fit
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def fit(t_data, y_data):
""" Fit a complex exponential to y_data
:param t_data: array of values for t-axis (x-axis)
:param y_data: array of values for y-axis. of the same shape as t-data
:returns: fitted parameters: (exp_coef, cos_coef)
:rtype: tuple
"""
# very fast way to check for nan
if not np.isnan(np.sum(y_data)):
# p_0 = estimate_params(t_data, y_data)
p_0 = None
opt_params = curve_fit(curve_fn, t_data, y_data, p0=p_0, maxfev=1000)[0]
return opt_params
else:
return 1E3, 0
示例7: optimize_bowers_trace
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def optimize_bowers_trace(depth_tr, vel_tr, obp_tr, hydro_tr,
depth_upper, depth_lower):
es_data = np.array(obp_tr) - np.array(hydro_tr)
depth = np.array(depth_tr)
mask = depth < depth_lower
mask *= depth > depth_upper
vel_interval = np.array(vel_tr)[mask]
es_interval = es_data[mask]
vel_to_fit = pick_sparse(vel_interval, 3)
es_to_fit = pick_sparse(es_interval, 3)
popt, _ = curve_fit(virgin_curve, es_to_fit, vel_to_fit)
a, b = popt
return a, b
示例8: optimize_nct_trace
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def optimize_nct_trace(depth, vel, fit_start, fit_stop, pick=True):
mask = depth > fit_start
mask *= depth < fit_stop
mask *= np.isfinite(vel)
depth_interval = np.array(depth)[mask]
vel_interval = np.array(vel)[mask]
if pick is True:
depth_to_fit = pick_sparse(depth_interval, 3)
vel_to_fit = pick_sparse(vel_interval, 3)
else:
depth_to_fit = depth_interval
vel_to_fit = vel_interval
dt = vel_to_fit**(-1)
log_dt = np.log(dt)
popt, _ = curve_fit(normal_dt, depth_to_fit, log_dt)
a, b = popt
return a, b
示例9: get_fitting_parameters
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def get_fitting_parameters(self):
if self._fit_params is None:
if self.guess_pos is None or self.guess_height is None:
fit_params, fit_covariances = curve_fit(self._function,
self.test_frequencies_range,
self.power_spectrum)
else:
fit_params, fit_covariances = curve_fit(self._function,
self.test_frequencies_range,
self.power_spectrum,
p0=[self.guess_pos, 0.1, self.guess_height, 0.0])
self._fit_covariances = fit_covariances
self._fit_params = fit_params
return self._fit_params, self._fit_covariances
示例10: leastsq_curve_fit
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def leastsq_curve_fit(x, y, f, p0):
"""
Args:
x (1d array): domain values for fitting
y (1d array): range values
f (function): function that maps x to y; must have x as first param
p0 (tuple): default parameter values for function f
returns:
popt (tuple): best fit parameters for function f
"""
try:
popt, pcov = optimize.curve_fit(f, x, y, p0)
return popt
except RuntimeError as e:
return None
示例11: _estimate_hack_coeff
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def _estimate_hack_coeff(A, L):
"""Estimate Hack parameters.
Given A and L, estimate C and h Where
L = C * A**h
Examples
--------
>>> import numpy as np
>>> np.random.seed(42)
>>> from landlab.components.hack_calculator.hack_calculator import (
... _estimate_hack_coeff, _hacks_law)
>>> C = 0.5
>>> h = 0.75
>>> A = np.arange(1, 1000)
>>> L = _hacks_law(A, C, h) + np.random.randn(A.size)
>>> C_hat, h_hat = _estimate_hack_coeff(A, L)
>>> np.round(C_hat, decimals=3)
0.497
>>> np.round(h_hat, decimals=3)
0.751
"""
popt, pcov = curve_fit(_hacks_law, A, L, (0.5, 0.7))
return popt
示例12: _components
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def _components(self, magnitude, time, error, lscargle_kwds):
time = time - np.min(time)
A, PH = [], []
for i in range(3):
frequency, power = lscargle(
time=time, magnitude=magnitude, error=error, **lscargle_kwds
)
fmax = np.argmax(power)
fundamental_Freq = frequency[fmax]
Atemp, PHtemp = [], []
omagnitude = magnitude
for j in range(4):
function_to_fit = self._yfunc_maker((j + 1) * fundamental_Freq)
popt0, popt1, popt2 = curve_fit(
function_to_fit, time, omagnitude
)[0][:3]
Atemp.append(np.sqrt(popt0 ** 2 + popt1 ** 2))
PHtemp.append(np.arctan(popt1 / popt0))
model = self._model(
time, popt0, popt1, popt2, (j + 1) * fundamental_Freq
)
magnitude = np.array(magnitude) - model
A.append(Atemp)
PH.append(PHtemp)
PH = np.asarray(PH)
scaledPH = PH - PH[:, 0].reshape((len(PH), 1))
return A, scaledPH
示例13: _components
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def _components(self, magnitude, time, ofac):
time = time - np.min(time)
A, PH = [], []
for i in range(3):
wk1, wk2, nout, jmax, prob = lomb.fasper(
time, magnitude, ofac, 100.)
fundamental_Freq = wk1[jmax]
Atemp, PHtemp = [], []
omagnitude = magnitude
for j in range(4):
function_to_fit = self._yfunc_maker((j + 1) * fundamental_Freq)
popt0, popt1, popt2 = curve_fit(
function_to_fit, time, omagnitude)[0][:3]
Atemp.append(np.sqrt(popt0 ** 2 + popt1 ** 2))
PHtemp.append(np.arctan(popt1 / popt0))
model = self._model(
time, popt0, popt1, popt2,
(j+1) * fundamental_Freq)
magnitude = np.array(magnitude) - model
A.append(Atemp)
PH.append(PHtemp)
PH = np.asarray(PH)
scaledPH = PH - PH[:, 0].reshape((len(PH), 1))
return A, scaledPH
示例14: fit_plot_central_charge
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def fit_plot_central_charge(s_list, xi_list, filename):
"""Plot routine in order to determine the cental charge."""
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def fitFunc(Xi, c, a):
return (c / 6) * np.log(Xi) + a
Xi = np.array(xi_list)
S = np.array(s_list)
LXi = np.log(Xi) # Logarithm of the correlation length xi
fitParams, fitCovariances = curve_fit(fitFunc, Xi, S)
# Plot fitting parameter and covariances
print('c =', fitParams[0], 'a =', fitParams[1])
print('Covariance Matrix', fitCovariances)
# plot the data as blue circles
plt.errorbar(LXi,
S,
fmt='o',
c='blue',
ms=5.5,
markerfacecolor='white',
markeredgecolor='blue',
markeredgewidth=1.4)
# plot the fitted line
plt.plot(LXi,
fitFunc(Xi, fitParams[0], fitParams[1]),
linewidth=1.5,
c='black',
label='fit c={c:.2f}'.format(c=fitParams[0]))
plt.xlabel(r'$\log{\,}\xi_{\chi}$', fontsize=16)
plt.ylabel(r'$S$', fontsize=16)
plt.legend(loc='lower right', borderaxespad=0., fancybox=True, shadow=True, fontsize=16)
plt.savefig(filename)
示例15: apply
# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import curve_fit [as 别名]
def apply(self, p_array, dz):
_logger.debug(" BeamAnalysis applied, dz =" + str(dz))
def test_func(x, a, phi, delta, g):
return a * np.sin(2 * np.pi / self.lambda_mod * x + phi) + delta + g * x
bunch_c = np.mean(p_array.tau())
slice_min = bunch_c - self.lambda_mod * self.nlambdas
slice_max = bunch_c + self.lambda_mod * self.nlambdas
indx = np.where(np.logical_and(np.greater_equal(p_array.tau(), slice_min),
np.less(p_array.tau(), slice_max)))[0]
p = p_array.p()[indx]
tau = p_array.tau()[indx]
sigma_x, sigma_y = np.std(p_array.x()[indx]), np.std(p_array.y()[indx])
# sigma_px, sigma_py = np.std(p_array.px()[indx]), np.std(p_array.py()[indx])
params, params_covariance = optimize.curve_fit(test_func, tau, p, p0=[0.001, 0, 0, 0])
b = slice_bunching(tau, charge=np.sum(p_array.q_array[indx]), lambda_mod=self.lambda_mod,
smooth_sigma=self.lambda_mod / 5)
self.p.append(params[0])
self.phi.append(params[1])
self.s.append(np.copy(p_array.s))
self.energy.append(np.copy(p_array.E))
self.bunching.append(b)
self.sigma_x.append(sigma_x)
self.sigma_y.append(sigma_y)
# print("center = ", (slice_max + slice_min)/2.)
# self.sigma_px.append(sigma_px)
# self.sigma_py.append(sigma_py)