python - 我正在尝试通过绘制捕食者与猎物的图表来可视化我的 Predator-Prey 模型的解决方案(使用 Runge-kutta 3)。但它不会情节
问题描述
我试图通过在 python 中绘制捕食者与猎物数量的图表来可视化我的代码的解决方案,并使用黑色圆圈标记当前状态。我的代码运行正常,除了我无法让图表的绘图部分打印图表上的图表。
这是我当前的python代码:
import matplotlib.pyplot as plt
import numpy as np
from trajectoryplotsupport import *
def ExactTrajectory(dt, ntimesteps):
tt = np.linspace(0, dt*ntimesteps, ntimesteps+1)
x = np.cos(2*np.pi*tt)
y = np.sin(2*np.pi*tt)
return x,y
def GetVelocity(pos, tn):
u =-2.0*np.pi * pos[1]
v = 2.0*np.pi * pos[0]
vel = np.array([u,v])
return vel
def RK3(p, t):
vel = GetVelocity(p, t) # stage 1 velocity
pt = p + 0.5*dt*vel # stage 1 provisional position
vel = GetVelocity(pt, t+dt) # stage 2 velocity
pt = 0.25 * p + 0.75*( pt + dt*vel ) # stage 2 provisional position
vel = GetVelocity(pt, t+0.5*dt) # stage 3 velocity
p = ( p + 2.0*(pt + dt*vel) )/3.0 # stage 3 provisional position
return p
def PreyPred(p, t):
b = 0.5 # prey birth rate
m = 0.2 # predator mortality
a = 0.04 # effect of predator abundance on prey
r = 0.01 # effect of prey abundance on predator
h, w = p[0], p[1] # initial densities of prey and predator are h(0) = 4.0 and w(0) = 8.0
dht = h*(b - a*w)
dwt = w*(-m + r*h)
return np.array([dht, dwt])
#################MAIN CODE#############
p = np.array([4.0, 8.0]) # initial position
ntimesteps = 120 # number of time steps
finalTime = 480 # final time
dt = 1 # time step
xe,ye = ExactTrajectory(dt, ntimesteps) # call exact trajectory
# Check on computations. Create 2 array to track the positions and initialize
pos = np.zeros(2) # create current position array
pos[0] = xe[0]; pos[1]=ye[0] # initialize current position
fig, lastPosition = InitialPlot(p, xe,ye)
for it in range(finalTime): # time loop
t = it*dt # set current time
p = RK3(p, t)
print(t, p)
UpdatePlot(fig,lastPosition,p,t) # update the plot
ttpoints = np.arange(0, 480, dt) #edited
hpoints, wpoints = [], []
p = np.array([0, 0], float)
for tt in ttpoints:
hpoints.append(p[0])
wpoints.append(p[1])
p += RK3(p, tt)
plt.plot(ttpoints, hpoints)
plt.plot(ttpoints, wpoints)
plt.xlabel("Prey")
plt.ylabel("Predator")
plt.plot(hpoints, wpoints)
plt.show()
解决方案
推荐阅读
- node.js - Angular/NodeJS Getstream.io 构建关注/取消关注按钮
- go - 延长长度,保持价值
- javascript - 如何在 Duktape 中创建 C++ 对象
- android - Cordova 使用相同的 LAN/wifi 从 android 访问共享的 pc 文件
- c++ - 为什么 'enable_if' 不能用于在此处禁用此声明
- mysql - 如何在 MySQL 中编写用户定义的函数,以便当我从一个表中删除一行时,另一个表中的特定行也会被删除?
- python-3.x - 当驱动程序失去焦点时,Actionchains 无法正常工作
- objective-c - GMSMapView 在 Swift 中绘制自定义折线
- ruby-on-rails-5 - 多个请求在同一时间实例,rails 无法处理数组列类型的更新
- php - Laravel 全局查询范围的 withoutGlobalScope() 没有返回所需的记录