Eng*_*ero 7 python lambda function partial-application
我有一个通用函数,它定义了我计划使用的ODE形式scipy.integrate.odeint,例如:
def my_ode(K, tau, y, u):
return K*u/tau - y/tau # dydt
Run Code Online (Sandbox Code Playgroud)
我的代码中有几个对象,它们都具有定义的形式的动态my_ode,但具有唯一的参数K和tau.我希望能够my_ode在我初始化对象时使用已设置的参数传递一个独特的句柄,这样当我更新我的对象时,我所要做的就是soln = odeint(my_ode, t, y, u)模拟时间t.
例如,如果我定义一个类:
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)
Run Code Online (Sandbox Code Playgroud)
当我初始化MyThing基本上分配参数的实例K并tau在初始化时永远不需要再次传递它时,我可以使用Lambdas 吗?我有点卡住了.
看起来我可以在初始化对象时使用 lambda 来生成唯一的函数句柄来完成这项工作。为了与 兼容odeint,我需要定义我的函数,以便前两个参数是时间和初始状态:
def my_ode(t, y, u, K, tau):
return K*u/tau - y/tau # dydt
Run Code Online (Sandbox Code Playgroud)
接下来我可以MyThing使用 lambda 来初始化对象来设置Kandtau为:
thing1 = MyThing(lambda t, y, u: my_ode(t, y, u, 10.0, 0.5), 0.0)
Run Code Online (Sandbox Code Playgroud)
被分配的函数句柄thing1.ode现在是 lambda 返回的函数句柄(这可能不是正确的说法),其值为K和tauset。现在thing1.update,我需要进行一些更改才能使其正常工作odeint:
def update(self, t_step, t_end, u):
t_array = np.arange(self.time, t_end, t_step) # time values at which to evaluate ODE
response = scipy.integrate.odeint(self.ode, self.y, t_array, (u,))
self.y = response[-1] # current state is the last evaluated state
Run Code Online (Sandbox Code Playgroud)
让我有点困惑的一件事是 ODE 的任何额外参数都需要作为元组传递给odeint. 这似乎非常适合我想要的。
还有一种更面向对象的方法scipy.integrate.ode,它允许逐步集成函数,并且非常适合我的模拟目的。为此,我设置了对象的 ODE 并使用以下内容更新它:
class MyThing():
def __init__(self, ode, y0):
self.ode = integrate.ode(ode) # define the ODE
self.ode.set_integrator("dopri5") # choose an integrator
self.ode.set_initial_value(y0)
def update(self, u, t_step):
"""Update the ODE step-wise."""
self.ode.set_f_params(u) # need to pass extra parameters with this method
self.ode.integrate(self.ode.t + t_step) # step-wise update
return self.ode.successful()
def get_output(self):
"""Get output from ODE function."""
return self.ode.y
Run Code Online (Sandbox Code Playgroud)