使用滑块更新参数值(python)

2024-05-08 03:39:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个微分方程组。解决方案取决于参数β。我想创建一个滑块,以便可以更改此参数,并在绘图中直接显示解决方案曲线的更改。我想我快拿到了,但我错过了一块

我的代码

N = 1

#Initial conditions
I0 = 0.01
S0= N - I0

#System of diff. equations
def system(x, t, beta, gamma ):
    I, S = x

    dIdt = (beta/gamma*S-1)*I*gamma
    dSdt = -(beta/gamma*S-1)*I*gamma

    return dIdt, dSdt

#Parameters initial value
beta = 0.03
gamma = 0.017

#Initial cond. vector
y0 = I0, S0

#time grid
t = np.linspace(0, 1300, 1300)

# Solution 
sol = odeint(system, y0, t, args=(beta, gamma))


################ Animations part ##################

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

#solution curves for I and S
infected, = plt.plot(t, sol[:,0])
recovered, = plt.plot(t, sol[:,1])

axbeta = plt.axes([0.125, 0.1, 0.5, 0.05])

sliderbeta = Slider(axbeta, 'beta', 0, 1, valinit=beta)

def update_beta(val):
    beta_value = sliderbeta.val
    ??????????????????????????????????????
    fig.canvas.draw_idle()

sliderbeta.on_changed(update_beta)

plt.show()

我不知道如何获取我的初始beta值以及如何用beta\u值替换它。我猜在我的问号处少了一行


Tags: valuedefplt解决方案systeminitialbetagamma
1条回答
网友
1楼 · 发布于 2024-05-08 03:39:48

您可以将任何ODE集成从全局范围中移除,并将其迁移到更新函数中。在Automatically Rescale ylim and xlim in Matplotlib之后,需要添加命令来计算并应用新的限制

# line objects for the solution curves for I and S
infected, = ax.plot([0], [0])
recovered, = ax.plot([0], [0])

def update_beta(beta):
    # if triggered as call-back it passes the current slider value
    # Solution 
    sol = odeint(system, y0, t, args=(beta, gamma))
    # update the data for I and S
    infected.set_data(t, sol[:,0])
    recovered.set_data(t, sol[:,1])
    # recompute the ax.dataLim
    ax.relim()
    # update ax.viewLim using the new dataLim
    ax.autoscale_view()
    fig.canvas.draw_idle()

最后,要在启动时获得初始绘图,请从全局范围调用此更新函数一次

update_beta(beta)

相关问题 更多 >