python - How to add parameter sliders to differential equation plots in python?
问题描述
I'm using Python to plot the system of differential equations
dldt = a*l - b*l*p
dpdt = -c*p + d*l*p
in Jupyter Notebook. How do I add interactive sliders to the plot to allow adjustment of constant parameters in the differential equations?
I've tried adding interactive sliders as per this Jupyter Notebook: https://ipywidgets.readthedocs.io/en/stable/examples/Lorenz%20Differential%20Equations.html, but not being familiar with solving and plotting differential equations in Python, I don't know how to modify it to be able to interact with the parameters a, b, c, and d. The best I could get was a static plot per the code below.
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from IPython.html.widgets import *
import ipywidgets as wg
from IPython.display import display
from numpy import pi
def f(s, t):
a = 1
b = 1
c = 1
d = 0.5
l = s[0]
p = s[1]
dldt = a*l - b*l*p
dpdt = -c*p + d*l*p
return [dldt, dpdt]
t = np.arange(0,10*pi,0.01)
s0=[0.1,5]
s = odeint(f, s0, t)
plt.plot(t,s[:,0],'r-', linewidth=2.0)
plt.plot(t,s[:,1],'b-', linewidth=2.0)
plt.xlabel("day in menstrual cycle")
plt.ylabel("concentration (ng/mL)")
plt.legend(["LH","P"])
plt.show()
What I desire is a graph that starts out like the static graph, but also has sliders for parameters a, b, c, and d that allows you to change the graph as you change their values.
解决方案
You need a function that takes the parameters of the ODE and additional parameters for the plot as named parameters. In the most simple case just a,b,c,d. This function needs to produce a plot.
def plot_solution(a=1.,b=1.,c=1.,d=0.5):
def f(s, t):
l, p = s
dldt = a*l - b*l*p
dpdt = -c*p + d*l*p
return [dldt, dpdt]
t = np.arange(0,10*np.pi,0.01)
s0=[0.1,5]
s = odeint(f, s0, t)
plt.plot(t,s[:,0],'r-', linewidth=2.0)
plt.plot(t,s[:,1],'b-', linewidth=2.0)
plt.xlabel("day in menstrual cycle")
plt.ylabel("concentration (ng/mL)")
plt.legend(["LH","P"])
plt.show()
Then call the interactive widget function as explained in the documentation. Sliders are generated for named parameters that are given pairs of numbers as input.
w = interactive(plot_solution, a=(-2.0,2.0), b=(-2.0,2.0), c=(-2.0,2.0), d=(-2.0,2.0))
display(w)
推荐阅读
- angular - 角度错误无法读取未定义的属性“样式”
- javascript - 使用 Puppeteer 检查网站是否使用 JS 功能
- frida - 如何读取 Frida 中 NativeFunction 返回的 NativeReturnValue?
- azure - Azure Pipeline 部署重置应用配置
- python - 未能获得价格而是我得到“NoneType”对象没有属性“文本”
- java - 我试图理解为什么 notifyAll() 没有在共享锁上醒来
- c# - 动态改变 TargetName DoubleAnimation c# xaml
- node.js - tsconfig 中的路径无法导入类型
- database - MongoDB 聚合具有各个日期范围的子字段
- python - Python:删除标准差小于 25% 的列