I want to fit a curve to my experimental dataset, and I do not really know how to do it. I have been looking for possibilities, and I came across curve_fit
(and also least_suqares
), which seems to be up for the task, but I am still very much unfamiliar with how it works, as I struggle to get it into my thick head. I started my attempt by defining the initial values:
import numpy as np
import math
from scipy.optimize import curve_fit, least_squares
f_exp = np.array([1, 1.6, 2.7, 4.4, 7.3, 12, 20, 32, 56, 88, 144, 250000])
e_exp = np.array([7.15, 7.30, 7.20, 7.25, 7.26, 7.28, 7.32, 7.25, 7.35, 7.34, 7.37, 13.55])
n_e_exp = len(e_exp)
ezero = 7.15
einf = 13.55
fc = np.arange(1,11000,1000)
alpha = np.arange(0,1.1,0.1)
log_f_mod = np.arange(-3, 6.5, 0.5)
f_mod = 10 ** log_f_mod
n_f_mod = len(f_mod)
n_fc = len(fc)
n_alpha = len(alpha)
x = np.zeros((n_f_mod, n_fc))
for j in range(n_f_mod):
for k in range(n_fc):
x[j,k] = np.log(f_mod[j] / fc[k])
Notice that x
is function of fc
. Now, I define the function I want to run using either curve_fit
, least_squares
, or some other function that is more suitable:
def c_c_eRI(einf, ezero, alpha, x):
eR = einf + 1/2 * (ezero - einf) * (1 - np.sinh((1 - alpha) * x) / (np.cosh((1 - alpha) * x) + np.cos(alpha * math.pi / 2)))
eI = np.abs(1/2 * (ezero - einf) * np.cos(alpha * math.pi / 2) / (np.cosh((1 - alpha) * x) + np.sin(alpha * math.pi / 2)))
eRI = np.sqrt(eR ** 2 + eI ** 2)
return eRI
At this point, I tried to make it work without any luck by:
fit = curve_fit(c_c_eRI, f_exp, e_exp)
- Is there a way to use a function (e.g.
curve_fit
,least_squares
, or some other) to fit the curve to the experimental data and simultaneously provide the value of the independent variables that arealpha
andfc
(whichx
is a function of) that are used to achieve the fit itself?
In other words, the aim is to find the values of alpha
and fc
(which x
is a function of) that provides the best possible fit to f_exp
versus e_exp
in a similar manner as the EXCEL
solver finds the minimum squared residuals by varying alpha
and fc
.
The end goal is to plot f_exp
vs. e_exp
as well as the fitted curve using matplotlib
-- I am also a bit lost on how to do this.
I do apologize for the lack of a more generalized example.