I have a general function that defines a form of an ODE that I plan to integrate using scipy.integrate.odeint
, for example:
def my_ode(K, tau, y, u):
return K*u/tau - y/tau # dydt
I have several objects in my code that all have dynamics of the form defined in my_ode
, but with unique parameters K
and tau
. I would love to be able to just pass a unique handle to my_ode
with those parameters already set when I initialize my objects, so that when I update my objects, all I have to do is something like soln = odeint(my_ode, t, y, u)
for some simulation time t
.
For example, if I define a class:
class MyThing:
def __init__(self, ode, y0):
# I would rather not maintain K and tau in the objects, I just want the ODE with unique parameters here.
self.ode = ode
self.y = y0
self.time = 0.0
def update(self, t, u):
# I want this to look something like:
self.y = scipy.integrate.odeint(self.ode, t, self.y, u)
Can I do something with Lambdas when I initialize instances of MyThing
to basically assign parameters K
and tau
at initialization and never need to pass them again? I am a bit stuck.
If you have:
def my_ode(K, tau, y, u):
return K*u/tau - y/tau
you could define something like:
def make_ode_helper(k, tau):
return lambda (y, u): my_ode(K, tau, y, u)
and should be able to initialize MyThing with:
mt = new MyThing(make_ode_helper(k, tau), y0)
then you could call this helper with only y and u parameters:
someresult = ode_helper(y, u)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With