Build a custom system
This tutorial builds one model three ways: from the components of the core, as a subclass of a shared recipe, and as a system class with model parameters. The model is the predator and prey cycle of the snowshoe hare and the Canada lynx, and every later tutorial of the guide starts from it.
The data
The Hudson's Bay Company bought the pelts of hares and lynx from trappers for two centuries, and the counts rise and
fall in cycles of about ten years. Hewitt (1921, The Conservation of the Wild Life of Canada) analysed these records.
The counts below are the pelts of 1900 to 1920, in thousands, as distributed with the case study of Carpenter (2018,
Predator-Prey Population Dynamics: the Lotka-Volterra model in Stan) in the file
knitr/lotka-volterra/hudson-bay-lynx-hare.csv of the Stan example models. That file cites the lecture notes of
Howard (2009) at Texas A&M University, which trace the numbers through the notes of Mahaffy (Math 636,
San Diego State University) to Purves, Sadava, Orians, and Heller, Life: The Science of Biology.
import numpy as np
years = np.arange(1900, 1921)
hares = np.array(
[30.0, 47.2, 70.2, 77.4, 36.3, 20.6, 18.1, 21.4, 22.0, 25.4, 27.1]
+ [40.3, 57.0, 76.6, 52.3, 19.5, 11.2, 7.6, 14.6, 16.2, 24.7]
)
lynx = np.array(
[4.0, 6.1, 9.8, 35.2, 59.4, 41.7, 19.0, 13.0, 8.3, 9.1, 7.4]
+ [8.0, 12.3, 19.5, 45.7, 51.1, 29.7, 15.8, 9.7, 10.1, 8.6]
)
int(years[hares.argmax()]), int(years[lynx.argmax()])
(1903, 1904)
The hares peak in 1903 and the lynx a year later, in 1904. The predators follow their prey.
The model
Lotka and Volterra wrote the cycle as two equations. Hares H are born at the rate alpha H and are hunted at the
rate beta H L. Lynx L gain at the rate delta H L from the hares they eat and die at the rate gamma L:
dH/dt = alpha H - beta H L
dL/dt = delta H L - gamma L
Carpenter estimated alpha = 0.55, beta = 0.028, gamma = 0.80, and delta = 0.024 per year, the means of the
posterior of a Bayesian fit. The sections below use these rates and start from the records of 1900, 30.0 thousand
hares and 4.0 thousand lynx.
From the components of the core
Each population is an Element with one value x, such as Element('hares', values={'x': 30.0}). Each term of the
equations is a one-off Interaction whose roles name the elements it reads and changes, and whose laws give the
rate of change as a function of the namespace s. A value that a law changes is a state, so x is a state of both
populations. How the components fit explains each component in turn.
from skcomplex.core.components.elements import Element
from skcomplex.core.components.interactions import Interaction
from skcomplex.core.components.laws import RateLaw
from skcomplex.core.systems import System
def hunt(s):
return [RateLaw(s.prey.x, -0.028 * s.prey.x * s.predator.x)]
def feed(s):
return [RateLaw(s.predator.x, 0.024 * s.prey.x * s.predator.x)]
hare_population = Element('hares', values={'x': 30.0})
lynx_population = Element('lynx', values={'x': 4.0})
births = Interaction('births', roles={'target': 'hares'}, laws=lambda s: [RateLaw(s.target.x, 0.55 * s.target.x)])
hunting = Interaction('hunting', roles={'prey': 'hares', 'predator': 'lynx'}, laws=hunt)
feeding = Interaction('feeding', roles={'prey': 'hares', 'predator': 'lynx'}, laws=feed)
deaths = Interaction('deaths', roles={'target': 'lynx'}, laws=lambda s: [RateLaw(s.target.x, -0.80 * s.target.x)])
pelts = System(elements=[hare_population, lynx_population], interactions=[births, hunting, feeding, deaths])
trajectory = pelts.prepare().simulate(until=20, dt=1.0)
trajectory.get_values('hares.x').round(1)[:6].tolist()
[30.0, 46.4, 68.5, 81.2, 48.8, 18.6]
The simulated hares rise from 30.0 to 81.2 thousand in 1903, the year of the highest count of pelts, and fall to 18.6 thousand in 1905. The root mean square difference to the records, 7.8 thousand pelts, measures the fit.
fit = np.sqrt(np.mean((trajectory.get_values('hares.x') - hares) ** 2))
round(float(fit), 1)
7.8
As a subclass of a shared recipe
The model is a set of reactions between two species. ReactionNetworkSystem of skcomplex.systems.general.reactions
builds one element per species and one reaction per row of a table, with a propensity of mass action, the rate
constant times the product of the reactant amounts. A subclass takes the parameters of the model under its own names
and returns the species and the reactions. Each row holds the reactants, the products, and the rate constant.
from skcomplex.systems.general.reactions import ReactionNetworkSystem
class HareLynxSystem(ReactionNetworkSystem):
until = 20.0
dt = 1.0
def __init__(
self, hares=30.0, lynx=4.0, *, alpha=0.55, beta=0.028, gamma=0.80, delta=0.024, mode='rate', label='system'
):
super().__init__(mode=mode, label=label)
self.hares = hares
self.lynx = lynx
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.delta = delta
def _get_species(self):
return {'hares': self.hares, 'lynx': self.lynx}
def _get_reactions(self):
return {
'births': ({'hares': 1}, {'hares': 2}, self.alpha),
'hunting': ({'hares': 1, 'lynx': 1}, {'lynx': 1}, self.beta),
'feeding': ({'hares': 1, 'lynx': 1}, {'hares': 1, 'lynx': 2}, self.delta),
'deaths': ({'lynx': 1}, {}, self.gamma),
}
HareLynxSystem().prepare().simulate().get_values('hares.x').round(1)[:6].tolist()
[30.0, 46.4, 68.5, 81.2, 48.8, 18.6]
The values match the system above. The class variables until and dt are tuned run settings, which simulate
reads when a call leaves them out. The recipe also runs the same reactions as random events, which suits a
small population.
jumps = HareLynxSystem(hares=30, lynx=4, mode='jump')
sorted(jumps.get_tags().laws), jumps.get_tags().randomness
(['jump'], 'stochastic')
As a system class with model parameters
A BaseSystem subclass builds its components in _prepare from its model parameters and keeps them as system_, so
set_params, clone, and the experiments of the library change them by name.
from skcomplex.core.systems import BaseSystem
class PeltSystem(BaseSystem):
until = 20.0
dt = 1.0
def __init__(self, hares=30.0, lynx=4.0, *, alpha=0.55, beta=0.028, gamma=0.80, delta=0.024, label='system'):
super().__init__(label)
self.hares = hares
self.lynx = lynx
self.alpha = alpha
self.beta = beta
self.gamma = gamma
self.delta = delta
def _prepare(self, context=None):
super()._prepare(context)
alpha, beta, gamma, delta = self.alpha, self.beta, self.gamma, self.delta
def predation(s):
contacts = s.prey.x * s.predator.x
return [RateLaw(s.prey.x, -beta * contacts), RateLaw(s.predator.x, delta * contacts)]
interactions = [
Interaction('births', roles={'target': 'hares'}, laws=lambda s: [RateLaw(s.target.x, alpha * s.target.x)]),
Interaction('predation', roles={'prey': 'hares', 'predator': 'lynx'}, laws=predation),
Interaction('deaths', roles={'target': 'lynx'}, laws=lambda s: [RateLaw(s.target.x, -gamma * s.target.x)]),
]
elements = [Element('hares', values={'x': self.hares}), Element('lynx', values={'x': self.lynx})]
self.system_ = System(self.label, elements=elements, interactions=interactions)
system = PeltSystem()
system.prepare().simulate().get_values('lynx.x').round(1)[:6].tolist()
[4.0, 4.4, 7.9, 22.5, 52.3, 49.5]
A faster birth rate of the hares raises their highest count over the twenty years from 81.2 to 85.8 thousand.
faster = system.set_params(alpha=0.65).prepare().simulate().get_values('hares.x')
round(float(faster.max()), 1)
85.8
The catalog class
LotkaVolterraSystem of skcomplex.systems.biology.ecology is the same model, ready made, with the rates r, a,
b, and d. The later tutorials start from it in one line.
from skcomplex.systems.biology.ecology import LotkaVolterraSystem
catalog = LotkaVolterraSystem(prey=30.0, predators=4.0, r=0.55, a=0.028, b=0.024, d=0.80)
catalog.prepare().simulate(until=20, dt=1.0).get_values('prey.x').round(1)[:6].tolist()
[30.0, 46.4, 68.5, 81.2, 48.8, 18.6]
Recipes by kind of system
The pages below build other kinds of system from the same components.
- Defining elements
- Kinds of dynamics
- General interactions
- Delays, events, drivers, and noise
- Stochastic maps
- Anomalous processes
- Geometry of chains
- Groups of many elements
- Lattice systems
- Networks
- Fields
- Phase-space fields
- Kinetic systems of active particles
- Agent-based systems
- Cell complexes and link fields
- Rewriting systems
- Quantum systems
- Stocks and flows
- Linear programs
- Static systems
- Constraints and search
- Control
- Learning by gradient steps