使用滑块更新参数值(python) [英] Updating parameter value with slider (python)

查看:72
本文介绍了使用滑块更新参数值(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个微分方程组.解决方案取决于参数beta.我想创建一个滑块,以便我可以更改此参数并直接在我的绘图中显示解曲线的变化.我想差不多了,但是我错过了一件.

I have a system of differential equations. The solutions depend on a parameter beta. I want to create a slider so I can change this parameter and display the changes of the solution curves directly in my plot. I almost got it I think, but I miss one piece.

我的代码

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_value.我猜我在问号的位置缺少一行.

I don't know how to acces my initial beta value and how to replace it by beta_value. I guess there is some line missing where I put the question marks.

推荐答案

您可以将任何 ODE 集成移出全局范围并将其迁移到更新函数.遵循 在 Matplotlib 中自动重新缩放 ylim 和 xlim,需要添加命令来计算新限制并应用它们.

You take any ODE integration out of the global scope and migrate it to the update function. Following Automatically Rescale ylim and xlim in Matplotlib, one needs to add commands to compute the new limits and apply them.

# 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()

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

And finally, to get an initial plot on startup, call this update function from the global scope once

update_beta(beta)

这篇关于使用滑块更新参数值(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆