Skip to main content
 首页 » 编程设计

python之如何强制 scipy 使用 Adams 进行集成

2025年04月02日9duanxz

我正在使用 scipy.integrate.odeint,当它切换到 bdf 方法时遇到了麻烦(因为系统显得僵硬)。不幸的是,bdf 需要计算 Jacobian。我的系统有数十万个方程,所以这会杀死 Python(段错误!!)

我有充分的理由相信亚当斯在这个系统上会做得很好。所以我想强制 scipy 使用它。我认为使用 odeint 是不可能的,所以我正在尝试使用 ode。我已经编写了自己的函数,它应该采用与 odeint 相同的输入。看起来我的代码有问题:

def my_odeint(dfunc, V0, times, args=()): 
    r = integrate.ode(dfunc) 
    r.set_integrator('vode', method='adams') 
    r.set_initial_value(V0,times[0]).set_f_params(*args) 
    V=[V0] 
    for time in times[1:]: 
        V.append(r.integrate(time)) 
    V = scipy.array(V) 
    return V 

当我测试它时出现错误:

def dx(X, t): 
    x=X[0] 
    y=X[1] 
    return (-x, x+y) 
X0 = [1,1] 
times = scipy.linspace(0,2,10) 
my_odeint(dx, X0, times) 
> capi_return is NULL 
> Call-back cb_f_in_dvode__user__routines failed. 

然后

TypeError                                 Traceback (most recent call last) 
<ipython-input-6-cc286a9956a2> in <module>() 
----> 1 my_odeint(dx, X0, times) 
 
in my_odeint(dfunc, V0, times, args) 
   1352     V=[V0] 
   1353     for time in times[1:]: 
-> 1354         V.append(r.integrate(time)) 
 
in integrate(self, t, step, relax) 
    406             self._y, self.t = mth(self.f, self.jac or (lambda: None), 
    407                                 self._y, self.t, t, 
--> 408                                 self.f_params, self.jac_params) 
 
 in run(self, f, jac, y0, t0, t1, f_params, jac_params) 
    863         args = ((f, jac, y0, t0, t1) + tuple(self.call_args) + 
    864                 (f_params, jac_params)) 
--> 865         y1, t, istate = self.runner(*args) 
 
<ipython-input-4-1770d3974ec9> in dx(X, t) 
      1 def dx(X, t): 
----> 2     x=X[0] 
      3     y=X[1] 
 
> TypeError: 'float' object has no attribute '__getitem__' 

所以我的问题是 - 我如何修复我的代码,以便我有一个函数,它接受与 odeint 相同的输入但使用 adams 并且永远不会切换到 bdf?

请您参考如下方法:

scipy.ode需要 f(t, y, *f_args) 形式的右侧,和 odeint要求它的形式为 f(y, t, *f_args)。

所以这会起作用:

def my_odeint(dfunc, V0, times, args=()): 
    r = integrate.ode(lambda t, X: scipy.array(dfunc(X, t, *args))) 
    r.set_integrator('vode', method='adams') 
    r.set_initial_value(V0,times[0]) 
    V=[V0] 
    for time in times[1:]: 
        V.append(r.integrate(time)) 
    V = scipy.array(V) 
    return V 

请注意,根据文档,vode 实现了 Adams-Moulton,而不是 Adams-Bashforth。也就是说,您仍然有一个隐式方法。如果集成继续失败,请尝试在 integrate.ode 中实现的 Dormand/Prince 方法。