Fitting data to system of ODEs - type error using lambda function with Scipy/Numpy/Python
-
18-06-2021 - |
Question
I am getting the following error when running my code:
Typeerror: lambda() takes exactly 4 arguments (3 given)
Here is my code - my error is coming from the last line of code (I think) where I am trying to implement Scipy's optimization algorithm fmin
from pylab import *
import pylab as pl
from numpy import *
from scipy.optimize import fmin
from scipy import integrate
import numpy as np
def ode(s,t,k1,k2):
A = s[0]
B = s[1]
C = s[2]
dA = -k1*A
dB = k1*A-k2*B
dC = k2*B
ds = [dA,dB,dC]
return ds
def myllsq(teta,s0,t,s):
y_obs = s
k1 = teta[0]
k2 = teta[1]
s = integrate.odeint(ode,s0,t,args=(k1,k2))
y_cal = s[:,1]
lsq = sum(y_obs-y_cal)**2
return lsq
e = lambda teta,s0,t,s: myllsq(teta,s0,t,s)
if __name__ == '__main__':
n = 10
tmin = 0.0
tmax = 9
k1 = 0.3
k2 = 0.2
s0 = [1,0,0]
t = linspace(tmin,tmax,n)
s = [0.000,0.416,0.489,0.595,0.506,0.493,0.458,0.394,0.335,0.309]
teta = [k1,k2]
print e(teta,s0,t,s)
fmin(e,teta,args=(t,s),maxiter=10000,maxfun=10000)
Solution
I think it should be something like:
fmin(e,teta,args=(s0,t,s),maxiter=10000,maxfun=10000)
instead of:
fmin(e,teta,args=(t,s),maxiter=10000,maxfun=10000)
You're not passing the s0
list to your function.
As a side note, there's no real need for lambda
here. You could just pass myllsq
directly -- e
is just a less efficient version of myllsq
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow