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)