odeint:数学建模的可变时间步长

odeint: Variable timestep for mathematical modelling

我以 Sci Py 僵尸代码为例。

ODEint 的问题是我整合了很长时间(在本例中是从 0 到 500,但对于其他项目长达数千年)并且它一次性完成了这个整合。我想实现一个长输出时间尺度,但一个小积分时间尺度,并将生成的样本数更改为 1,但不断更新时间尺度,以便我可以在每个循环中将一个新点写入一个文件。也就是说,我不希望它一次从 0 集成到 500,而是在不断变化的时间尺度上循环。可以实现吗?

# zombie apocalypse modeling
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
plt.ion()
plt.rcParams['figure.figsize'] = 10, 8

P = 0      # birth rate
d = 0.0001  # natural death percent (per day)
B = 0.0095  # transmission percent  (per day)
G = 0.0001  # resurect percent (per day)
A = 0.0001  # destroy percent  (per day)

# solve the system dy/dt = f(y, t)
def f(y, t):
     Si = y[0]
     Zi = y[1]
     Ri = y[2]
     # the model equations (see Munz et al. 2009)
     f0 = P - B*Si*Zi - d*Si
     f1 = B*Si*Zi + G*Ri - A*Si*Zi
     f2 = d*Si + A*Si*Zi - G*Ri
     return [f0, f1, f2]

# initial conditions
S0 = 500.              # initial population
Z0 = 0                 # initial zombie population
R0 = 0                 # initial death population
y0 = [S0, Z0, R0]     # initial condition vector
t  = np.linspace(0, 50, 1000)         # time grid

# solve the DEs
soln = odeint(f, y0, t)
S = soln[:, 0]
Z = soln[:, 1]
R = soln[:, 2]

为什么不这样做呢?

for k in range(50):
    t = np.linspace(k, k+1, 20)
    sol = odeint(f, y0, t)
    y0 = sol[-1] #initial value for next segment
    S,Z,R = sol.T
    # output to file, other post-processing