Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/notebooks/chap18.ipynb
Views: 531
Modeling and Simulation in Python
Chapter 18
Copyright 2017 Allen Downey
Code from the previous chapter
Read the data.
Interpolate the insulin data.
The glucose minimal model
I'll cheat by starting with parameters that fit the data roughly; then we'll see how to improve them.
Here's a version of make_system
that takes the parameters and data:
And here's the update function.
Before running the simulation, it is always a good idea to test the update function using the initial conditions. In this case we can veryify that the results are at least qualitatively correct.
Now run_simulation
is pretty much the same as it always is.
And here's how we run it.
The results are in a TimeFrame
object with one column per state variable.
The following plot shows the results of the simulation along with the actual glucose data.
Numerical solution
Now let's solve the differential equation numerically using run_ode_solver
, which is an implementation of Ralston's method.
Instead of an update function, we provide a slope function that evaluates the right-hand side of the differential equations.
We don't have to do the update part; the solver does it for us.
We can test the slope function with the initial conditions.
Here's how we run the ODE solver.
details
is a ModSimSeries
object with information about how the solver worked.
results
is a TimeFrame
with one row for each time step and one column for each state variable:
Plotting the results from run_simulation
and run_ode_solver
, we can see that they are not very different.
The differences in G
are less than 2%.
Exercises
Exercise: Our solution to the differential equations is only approximate because we used a finite step size, dt=2
minutes.
If we make the step size smaller, we expect the solution to be more accurate. Run the simulation with dt=1
and compare the results. What is the largest relative error between the two solutions?
Under the hood
Here's the source code for run_ode_solver
if you'd like to know how it works.
Notice that run_ode_solver
is another name for run_ralston
, which implements Ralston's method.
Related reading: You might be interested in this article about people making a DIY artificial pancreas.