I am trying to fit three time-evolution curves with two rate constants, k1 and k2. The system of equations I am trying to solve is:
A_t = A_0 * exp(-k1*t)
B_t = [A_0 * k1/(k2-k1)]* exp(-k1*t) - [A_0*(k1/(k2-k1)-B_0] * exp(-k2*t)
C_t = [A_0 * -k2/(k2-k1) ]* exp(-k1*t) + [A_0*(k1/(k2-k1)-B_0] * exp(-k2*t) + A_0 + B_0
where I want fit the best values of k1
and k2
to my data values of A,B and C, where A_t
etc is the current population of A at time t
, A_0=0.4
and B_0=0.6
.
To solve this I am using the scipy.optimize.curve_fit function where I set up the equations as matrices u
and w
. In the following, I have manually entered the A_0=0.4
and B_0=0.6
into the function (which relates to part 2 of my question at the bottom):
def func(t,k1,k2):
u = np.array([[0.4,0,0],
[0.4*k1/(k2-k1),-0.4*(k1/(k2-k1))+0.6,0],
[0.4*(-k2/(k2-k1)),0.4*k1/(k2-k1)-0.6,1]])
w = np.array([np.exp(-t*k1),
np.exp(-t*k2),
np.ones_like(t)])
return np.dot(u,w).flatten()
To solve for some test
data, I create a test set where I set k1=0.03
and k2=0.003
:
t=np.arange(1000)*0.5
test=func(t,0.03,0.004).reshape((3,1000))
test+=np.random.normal(size=test.shape)*0.01
which produces the following plot:
When I then try to fit values of k1
and k2
, I get the following error:
popt,popc=optimize.curve_fit(func,t,test.flatten(),method='lm')
/usr/local/lib/python3.6/site-packages/ipykernel_launcher.py:4: RuntimeWarning: divide by zero encountered in double_scalars after removing the cwd from sys.path. /usr/local/lib/python3.6/site-packages/ipykernel_launcher.py:5: RuntimeWarning: divide by zero encountered in double_scalars """ /usr/local/lib/python3.6/site-packages/scipy/optimize/minpack.py:785: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning)
I understand that there is a divide by zero error somewhere here, but I am not sure where it is or how to solve it. So, my questions are:
- How to solve for this error in the curve_fit function?
- Is there a way to pass
A_0
andB_0
into optimize.curve_fit, rather than manually entering the concentrations as I have done above? My understanding is that only the independent variablet
and the unknownsk1
andk2
can be passed to the function?
Thank you for any help that can be provided