Share a system
This tutorial turns the hare and lynx model into a system class of the catalog, checks it the way the tests of the catalog do, and writes its inventory entry and its gallery example. It ends with the steps of a contribution to the repository. The page Extend the library explains where a new component goes, and this page follows its placement rule.
The system class
A system of the catalog is a subclass of BaseSystem whose name ends
in System. It takes its model parameters as arguments, stores each under its own name, and builds its components in
_prepare, which sets system_, the System of its components. Four class
variables describe it:
fieldis the field path, a field and a subfield of the catalog, such as'biology/ecology'.topicsare the words thatall_systemsfilters by, such as'predator-prey'.referencesare the works the model comes from, each an author and a year.untilanddtare the tuned run settings, whichsimulatereads when a call leaves them out.
The tutorial Build a custom system wrote the model as PeltSystem from core
components. The class below builds it from the same core components. A class of the catalog would build it from the
components that the systems of ecology share in skcomplex.systems.biology.common, a population element and the
growth, predation, and mortality interactions, so that one model has one implementation. Its defaults are the rates
of Carpenter (2018) and the pelt records of 1900, and its docstring follows the style of the catalog: a summary, a
paragraph on what the model shows, the arguments, and an example.
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 BaseSystem, System
class HareLynxSystem(BaseSystem):
"""Snowshoe hares and Canada lynx whose populations cycle through predation.
The defaults are the posterior means that Carpenter (2018) fitted to the pelt records of the Hudson's Bay Company,
and the initial populations are the records of 1900, in thousands of pelts. The system has the populations `hares`
and `lynx`.
Args:
hares:
The initial number of hares, in thousands, such as `30.0`.
lynx:
The initial number of lynx, in thousands, such as `4.0`.
alpha:
The birth rate of the hares, per year.
beta:
The rate at which the lynx remove hares, per thousand lynx and year.
gamma:
The death rate of the lynx, per year.
delta:
The rate at which eating hares feeds the lynx, per thousand hares and year.
label:
The label of the system, which names it when it is nested in another one.
Examples:
>>> HareLynxSystem().prepare().system_.elements[0].label
'hares'
"""
field = 'biology/ecology'
topics = ('predator-prey', 'ode', 'oscillation', 'data')
references = ('Hewitt 1921', 'Carpenter 2018')
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)]
elements = [Element('hares', values={'x': self.hares}), Element('lynx', values={'x': self.lynx})]
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)]),
]
self.system_ = System(self.label, elements=elements, interactions=interactions)
HareLynxSystem().get_params()
{'alpha': 0.55, 'beta': 0.028, 'delta': 0.024, 'gamma': 0.8, 'hares': 30.0, 'label': 'system', 'lynx': 4.0}
get_params returns the initial populations, the four rates, and the label by name, as for any estimator of
scikit-learn, so set_params, clone, and the experiments of the library change them. The constructor only stores its arguments, which is what makes this
work.
Checking the class
The catalog tests run every system class through one generic check. It builds the class with its default parameters,
simulates it for ten frames while a RerunObserver saves the run, and
requires a frame logged for every simulated frame. Then it clones the system and compiles the copy. The block below
runs the same check on the new class, saving to a temporary file so that no viewer opens.
import tempfile
from pathlib import Path
from sklearn.base import clone
from skcomplex.core.engine.viz import RerunObserver
system = HareLynxSystem().prepare()
observer = RerunObserver('hare_lynx', save_path=Path(tempfile.mkdtemp()) / 'run.rrd')
trajectory = system.simulate(until=10 * system.dt, observers=[observer], random_state=0)
copy = clone(system)
hares = trajectory.get_values('hares.x').round(1)[:4].tolist()
observer.logged_frames_ == len(trajectory.times), copy is not system, hares
(True, True, [30.0, 46.4, 68.5, 81.2])
The observer logged all eleven frames, the clone is a new object, and the hares rise from 30.0 to 81.2 thousand in
1903, as in the build tutorial. The tuned dt of one year set the length of the run.
A class of the catalog must also run like the same components put together by hand, and it must say what it is, such as
the kind of problem it is. The block below compares the states of a run with those of LotkaVolterraSystem, which holds
the same model with the rates r, a, b, and d, and reads the form of the prepared system.
import numpy as np
from skcomplex.systems.biology.ecology import LotkaVolterraSystem
reference = LotkaVolterraSystem(prey=30.0, predators=4.0, r=0.55, a=0.028, b=0.024, d=0.80)
difference = system.simulate(until=20).states - reference.prepare().simulate(until=20, dt=1.0).states
bool(np.abs(difference).max() < 1e-9), system.form_
(True, 'ordinary differential equations')
The states of the two systems agree to within rounding error, below 1e-9 thousand animals, so the new class adds the data and the names, not a new model. The form says that the system is an ordinary differential equation. A class of the catalog also says what it is through its capability tags, which its catalog test and the inventory read from the class rather than repeating them.
A class is listed by all_systems when its module lives in the package skcomplex.systems and its body sets field.
The listing reads the sources without importing them, so field, topics, and references must be literal values.
A class defined anywhere else, such as on this page, stays out of the listing.
from skcomplex.systems import all_systems
listed = [name for name, _ in all_systems(field='biology/ecology')]
'LotkaVolterraSystem' in listed, 'HareLynxSystem' in listed
(True, False)
LotkaVolterraSystem is listed and HareLynxSystem is not. The listing raises a RegistryError for a class of the
package whose name lacks the suffix System or whose field is computed at run time.
The files of a contribution
A new system adds a module, an export, an inventory entry, and a gallery example. The catalog already holds this model
as LotkaVolterraSystem, so the files below show the steps rather than a contribution the catalog needs. A real one
adds a system the catalog lacks.
src/skcomplex/systems/biology/ecology/
_pelts.py the class HareLynxSystem
__init__.py imports HareLynxSystem and lists it in __all__
tests/systems/biology/ecology/
test_pelts.py the tests of the class, mirroring the source
docs/overview/inventory.toml the entry hare_lynx under [biology.ecology]
docs/examples/biology/ecology/
plot_hare_lynx.py the gallery example
The module holds one system with the components only it uses. A component that several systems of ecology share goes to
skcomplex.systems.biology.common, and a component that several fields share goes to skcomplex.systems.general, as
the placement rule of Extend the library says.
The inventory entry
The inventory docs/overview/inventory.toml lists every system surveyed from the reference books and articles, with
its status. The name of an entry is the class name without System in snake case, so HareLynxSystem is hare_lynx.
The entry sits in the table of its field path, and the check of the inventory, which the documentation build runs,
compares it with the class.
[biology.ecology]
hare_lynx = { title = "Hare and lynx pelts", sources = ["Hewitt 1921", "Carpenter 2018"], primitives = ["rates", "interactions"], system = { components = ["element"], bindings = ["members"] }, priority = "example", status = "implemented" }
The fields of the entry are these:
titlenames the system in the gallery.sourcesare keys of the tablesourceswith a section, arXiv identifiers, or citations of an author and a year.primitivesare the capabilities of the core the system exercises, from the tableprimitives.systemmaps the system to the vocabulary: its components, here single elements, and its bindings, here roles bound to elements.priorityis'core'when the system exercises a set of primitives that no earlier entry exercises, and'example'otherwise. The rates and interactions of this model repeat those oflotka_volterra.statusis'implemented'once the class exists, or'pending <change>'while an OpenSpec change builds it.
An implemented entry does not write its time, space, laws, or domains, since the check reads them from get_tags() of
the class, as the block above did.
The gallery example
Every system of the catalog has one example in the gallery, a script under
docs/examples/<field>/<subfield>/plot_<name>.py. After the inventory entry exists, the command
PYTHONPATH=docs python -m gallery_tools scaffold writes a scaffold for every system without an example. The finished
script sets SYSTEM to the gallery name, runs the system with a RerunObserver and a blueprint, and draws one figure
of an analysis whose result the caption predicts.
"""
# Hare and lynx pelts
The hares and the lynx of the Hudson's Bay Company records cycle out of phase, and every peak of the hares is followed
by a peak of the lynx a year later.
"""
# %%
# The system starts from the records of 1900 and runs for twenty years with the rates of Carpenter (2018).
import matplotlib.pyplot as plt
from skcomplex.core.engine.viz import RerunObserver
from skcomplex.systems.biology.ecology import HareLynxSystem
SYSTEM = 'hare_lynx'
observer = RerunObserver(SYSTEM, save_path=f'{SYSTEM}.rrd', blueprint='default')
trajectory = HareLynxSystem().prepare().simulate(observers=[observer])
# %%
# The phase plane
# ---------------
# The run is one closed cycle around the equilibrium (gamma / delta, alpha / beta).
fig, axes = plt.subplots()
axes.plot(trajectory.get_values('hares.x'), trajectory.get_values('lynx.x'))
axes.set(xlabel='hares (thousands)', ylabel='lynx (thousands)', title='The phase plane')
plt.show()
The docstring gives the title and a caption of the behaviour the thumbnail must show. The command
PYTHONPATH=docs python -m gallery_tools run hare_lynx runs the example and captures its screenshot, which a reviewer
compares with the caption.
Contributing
A contribution goes to the repository as a pull request. The contributing guide
lists the tasks that format the code, run the checks and the tests, and build the documentation, with the convention of
commit messages and the guidelines of pull requests. Before the pull request, run the tests of the catalog,
pytest tests/systems/test_catalog.py, which apply the checks of this page to the new class, and build the
documentation, which runs the check of the inventory and the gallery example.