在Python中从MATLAB模仿ode45函数

Mig*_*Mag 1 python matlab scipy differential-equations ode45

我想知道如何将MATLAB函数ode45导出到python。根据文档应如下:

 MATLAB:  [t,y]=ode45(@vdp1,[0 20],[2 0]);

 Python:  import numpy as np
          def  vdp1(t,y):
              dydt= np.array([y[1], (1-y[0]**2)*y[1]-y[0]])
              return dydt
          import scipy integrate 
          l=scipy.integrate.ode(vdp1([0,20],[2,0])).set_integrator("dopri5")
Run Code Online (Sandbox Code Playgroud)

结果是完全不同的,Matlab返回的尺寸不同于Python。

小智 5

如@LutzL所述,您可以使用更新的API solve_ivp

results = solve_ivp(obj_func, t_span, y0, t_eval = time_series)
Run Code Online (Sandbox Code Playgroud)

如果t_eval未指定,则每个时间戳不会有一个记录,这主要是我假设的情况。

另一个需要注意的是,对于odeint(通常是其他)积分器,输出数组ndarray的形状为[len(time), len(states)],但是对于solve_ivp,输出的则是list(length of state vector)1维ndarray(长度等于t_eval)。

因此,如果需要相同的订单,则必须将其合并。您可以通过以下方式进行操作:

Y =results
merged = np.hstack([i.reshape(-1,1) for i in Y.y])
Run Code Online (Sandbox Code Playgroud)

首先,您需要调整形状以使其成为[n,1]数组,然后将其水平合并。希望这可以帮助!


小智 4

Integrate.ode的界面不像更简单的方法odeint那样直观,但它不支持选择 ODE 积分器。主要区别在于它ode不会为您运行循环;如果您需要在一堆点上找到解决方案,则必须说明在哪些点上,并一次计算一个点。

import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt

def vdp1(t, y):
    return np.array([y[1], (1 - y[0]**2)*y[1] - y[0]])
t0, t1 = 0, 20                # start and end
t = np.linspace(t0, t1, 100)  # the points of evaluation of solution
y0 = [2, 0]                   # initial value
y = np.zeros((len(t), len(y0)))   # array for solution
y[0, :] = y0
r = integrate.ode(vdp1).set_integrator("dopri5")  # choice of method
r.set_initial_value(y0, t0)   # initial values
for i in range(1, t.size):
   y[i, :] = r.integrate(t[i]) # get one more value, add it to the array
   if not r.successful():
       raise RuntimeError("Could not integrate")
plt.plot(t, y)
plt.show()
Run Code Online (Sandbox Code Playgroud)

解决方案

  • 或者在 [`scipy.integrate.RK45`](https://docs.scipy.org/doc/scipy/reference/ generated/scipy.integrate.RK45.html) 中使用新的 API 和类似 `odeint` 的接口或 [`scipy.integrate.solve_ivp`](https://docs.scipy.org/doc/scipy/reference/ generated/scipy.integrate.solve_ivp.html)。 (3认同)