In [1]:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
In [2]:
def run_simulation(system, update_func):
"""Runs a simulation of the system.
system: System object
update_func: function that updates state
returns: TimeFrame
"""
unpack(system)
frame = TimeFrame(columns=init.index)
frame.row[t0] = init
for t in linrange(t0, t_end):
frame.row[t+1] = update_func(frame.row[t], t, system)
return frame
In [3]:
def update_func(state, t, system):
"""Update the Lotka-Volterra model.
state: State(x, y)
t: time
system: System object
returns: State(x, y)
"""
unpack(system)
x, y = state
dxdt = alpha * x - beta * x * y
dydt = delta * x * y - gamma * y
x += dxdt
y += dydt
return State(x=x, y=y)
In [4]:
init = State(x=1, y=1)
Out[4]:
In [5]:
system = System(alpha=0.05,
beta=0.1,
gamma=0.1,
delta=0.1,
t0=0,
t_end=200)
Out[5]:
In [6]:
update_func(init, 0, system)
Out[6]:
In [7]:
results = run_simulation(system, update_func)
results.head()
Out[7]:
In [8]:
results.plot()
Out[8]:
In [9]:
def slope_func(state, t, system):
"""Compute slopes for the Lotka-Volterra model.
state: State(x, y)
t: time
system: System object
returns: pair of derivatives
"""
unpack(system)
x, y = state
dxdt = alpha * x - beta * x * y
dydt = delta * x * y - gamma * y
return dxdt, dydt
In [10]:
system.set(init=init, t_end=200)
In [11]:
results, details = run_ode_solver(system, slope_func)
details
Out[11]:
In [12]:
results.plot()
Out[12]:
In [13]:
system.set(init=init, t_end=200)
results, details = run_ode_solver(system, slope_func, max_step=2)
details
Out[13]:
In [14]:
results.plot()
Out[14]:
In [15]:
system.set(t_end=2000)
results = run_simulation(system, update_func)
results.head()
Out[15]:
In [16]:
results.plot()
Out[16]:
In [17]:
results, details = run_ode_solver(system, slope_func)
details
Out[17]:
In [18]:
results.plot()
Out[18]:
In [ ]: