2016-04-21 112 views
0

我想創建一個集成了模型的腳本,以便我可以更改其中一個參數並查看系統對此更改的響應。如果,例如,我有一個的Lotka-Volterra模型(從這個example截取):Python中的ODE模型的交互式多點繪圖

import numpy as np 
from scipy import integrate 
a = 1. 
b = 0.1 
c = 1.5 
d = 0.75 

def dX_dt(X, t=0): 
    """ Return the growth rate of fox and rabbit populations. """ 
    return array([ a*X[0] - b*X[0]*X[1] , 
        -c*X[1] + d*b*X[0]*X[1] ]) 

t = np.linspace(0, 15, 1000)    # time 
X0 = np.array([10, 5]) # initials conditions: 10 rabbits and 5 foxes 

X, infodict = integrate.odeint(dX_dt, X0, t, full_output=True) 

我想創建參數ac的滑塊,如在slider_demo of matplotlib,或任何其他工具。情節應該顯示總是橫跨[t_current - delta_t ,t_current]的某個時間窗口。因此,通過更改參數的滑塊,我將能夠不斷探索參數空間。

任何想法如何做到這一點?

回答

2

您已完成所有工作,基本上只是更改小部件example中的更新方法,以使用基於滑塊的新值重新計算dX_dt的積分,然後使用此值設置y線值。該代碼將如下所示:

import numpy as np 
from scipy import integrate 
import matplotlib.pyplot as plt 
from matplotlib.widgets import Slider, Button, RadioButtons 

b = 0.1 
d = 0.75 
a=1 
c=1.5 
def dX_dt(X, t=0, a=1, c=1.5): 
    """ Return the growth rate of fox and rabbit populations. """ 
    return np.array([ a*X[0] - b*X[0]*X[1] , 
        -c*X[1] + d*b*X[0]*X[1] ]) 


t = np.linspace(0, 15, 1000)    # time 
X0 = np.array([10, 5])   # initials conditions: 10 rabbits and 5 foxes 

fig, ax = plt.subplots() 
plt.subplots_adjust(left=0.25, bottom=0.25) 

l1, l2 = plt.plot(t, integrate.odeint(dX_dt, X0, t, (a, c))) 

axcolor = 'black' 
ax_a = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) 
ax_c = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) 

sa = Slider(ax_a, 'a', 0.1, 10.0, valinit=1) 
sc = Slider(ax_c, 'c', 0.1, 10.0, valinit=1.5) 


def update(val): 
    a = sa.val 
    c = sc.val 
    x = integrate.odeint(dX_dt, X0, t, (a, c)) 
    l1.set_ydata(x[:,0]) 
    l2.set_ydata(x[:,1]) 
    fig.canvas.draw_idle() 

sa.on_changed(update) 
sc.on_changed(update) 

plt.show()