python - 使用 SciPy 求解 Lotka-Volterra 模型

标签 python numpy ode differential-equations

我有以下 Lotka-Volterra 模型

dN1/dt = N1(1-N1-0.7N2)

dN2/dt = N2(1-N2-0.3N1)

N 旁边的 1 和 2 是下标。

我想使用 SciPy 解决这个问题并可视化结果。我想在 y 轴上绘制 N2,在 N1 上绘制 N1。如果在第一个方程中将 N1 设置为零,则 N2 = 1/0.7,如果在第二个方程中将 N2 设置为零,则 N1 = 0.3/1。假设两条线相交。我如何在 Python 中执行此操作?

我读了这个tutorial (幻灯片 6 至 16)在线。这是我目前所拥有的。

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

def derivN1(y,t):
    yprime=np.array([1-0.7y[0]])
    return yprime

def derivN2(y,t):
    yprime=np.array([1-0.3y[0]])
    return yprime

start=0
end=1
numsteps=1000
time=np.linspace(start,end,numsteps)
y0=np.array([10])

yN1=integrate.odeint(derivN1,y0,time)
yN2=integrate.odeint(derivN2,y0,time)

plt.plot(time,yN1[:])
plt.plot(time,yN2[:])

但情节不正确。更新:我想我使用了错误的方法。我正在在线阅读另一本 tutorial .我会再解决这个问题。同时,如果有人知道如何解决它,请告诉我。

最佳答案

@WarrenWeckesser 的评论非常好,你应该从这里开始。我只会尝试强调隐式情节和显式情节之间的区别。

首先,设置:

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

time=np.linspace(0,15,5*1024)

def derivN(N, t):
    """Return the derivative of the vector N, which represents
    the tuple (N1, N2). """

    N1, N2  = N
    return np.array([N1*(1 - N1 - .7*N2), N2*(1 - N2 - .3*N1)])

def coupled(time, init, ax):
    """Visualize the system of coupled equations, by passing a timerange and
    initial conditions for the coupled equations.

    The initical condition is the value that (N1, N2) will assume at the first
    timestep. """

    N = integrate.odeint(derivN, init, time)
    ax[0].plot(N[:,0], N[:,1], label='[{:.1f}, {:.1f}]'.format(*init))  # plots N2 vs N1, with time as an implicit parameter
    l1, = ax[1].plot(time, N[:,0], label='[{:.1f}, {:.1f}]'.format(*init))
    ax[1].plot(time, N[:,1], color=l1.get_color())

重要的是要认识到您的方程是耦合的,您应该向 odeint 提供一个返回耦合方程的导数的函数。因为你有 2 个方程,你需要返回一个长度为 2 的数组,每一项代表传入变量的导数(在本例中是数组 N(t) = [N1(t), N2(t)]).

然后您可以完全绘制它,对 N1 和 N2 使用不同的初始条件:

fh, ax = plt.subplots(1,2)
coupled(time, [.3, 1/.7], ax)
coupled(time, [.4, 1/.7], ax)
coupled(time, [1/.7, .3], ax)
coupled(time, [.5, .5], ax)
coupled(time, [.1, .1], ax)
ax[0].legend()
ax[1].legend()
ax[0].set_xlabel('N1')
ax[0].set_ylabel('N2')
ax[1].set_xlabel('time')
ax[1].set_ylabel(r'$N_i$')
ax[0].set_title('implicit')
ax[1].set_title('explicit (i.e. vs independant variable time)')
plt.show()

time evolution of coupled equations

您会注意到 N1N2 都会演变成某个最终值,但这两个值是不同的。对于给定的方程,隐式图中的曲线不相交。

关于python - 使用 SciPy 求解 Lotka-Volterra 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28332217/

相关文章:

python - 在网格中回溯

python - 如何按最大日期时间过滤数据框中的行?

python - 如何将互斥参数作为变量传递

python - Beautiful Soup (bs4) 如何只匹配一个,而且只有一个,css 类

python - Scipy、odeint 以及 odeint 输入函数的输入设置

python - 可以在 numpy 中形成 ndarray 对角线的 View 吗

python - 合并具有不同索引的多个系列,对重复的索引求和

python - Numpy 八倍精度 float 和 128 位整数。为什么以及如何?

python - 多维欧拉法python

python - 实现常微分方程组的循环