General realizations
skcomplex.systems.general holds the recipes that systems of several fields share, such as a nonnegative amount, a
reaction, an agent that moves, or a market that matches buyers with sellers. A recipe is a component written with the
public components of the core alone, so each one is also an example of how to build a component of your own. The core
never imports these recipes, and every field imports them freely. How the components fit shows the
components of the core that the recipes are written with, and the section Where a component
goes at the end of this page gives the rule that decides whether a new component is a recipe.
The package has one subpackage per concept, and every recipe is imported from its subpackage.
| Subpackage | Concept | Recipes |
|---|---|---|
elements |
amounts and bodies | NonnegativeElement, PointElement |
reactions |
reactions at a product propensity | ReactionInteraction, ReactionNetworkSystem |
kinetics |
encounters of distributions | EncounterInteraction |
dynamics |
systems given as equations | EquationInteraction, FlowInteraction, AnnotatedElement, DynamicalSystem, NetworkDynamicalSystem, ReactionDiffusionSystem, StockFlowSystem |
agents |
agent rules | MovementInteraction, ChoiceInteraction, ImitationInteraction, EvolutionInteraction, BirthDeathInteraction |
matching |
markets that pair two groups | MatchingInteraction, its rule specs, and MatchSpec |
rewriting |
words and tilings that grow by rules | WordElement, PatchElement, RewritingInteraction, ProductionLaw, SubstitutionLaw, their specs, GeometryVisual, and RewritingSolver |
NonnegativeElement
A NonnegativeElement holds one number x that stays at zero or above, such as a count of people or the moles of a
chemical species. It is an Element whose value x carries the allowed values [0, +oo), and
it takes size for many members and space for one member per site. Here 100 infected people recover at a rate of
0.1 a day through a ReactionInteraction with no products.
from skcomplex.core.systems import System
from skcomplex.systems.general.elements import NonnegativeElement
from skcomplex.systems.general.reactions import ReactionInteraction
recovery = ReactionInteraction('recovery', reactants={('infected', 'x'): 1}, k=0.1)
epidemic = System(elements=[NonnegativeElement('infected', x=100.0)], interactions=[recovery]).prepare()
epidemic.simulate(until=10, dt=5.0).get_values('infected.x').round(1).tolist()
[100.0, 60.7, 36.8]
The infected fall from 100 to 60.7 after five days and to 36.8 after ten.
The same element holds the moles of a chemical species in a reactor. A species that decays at the rate 0.5 loses about two thirds of its amount in two seconds.
decay = ReactionInteraction('decay', reactants={('A', 'x'): 1}, k=0.5)
reactor = System(elements=[NonnegativeElement('A', x=2.0)], interactions=[decay]).prepare()
reactor.simulate(until=2, dt=1.0).get_values('A.x').round(3).tolist()
[2.0, 1.213, 0.736]
The amount falls from 2.0 to 1.213 and then to 0.736, which is 2 exp(-1).
How the engine runs it. The element adds no laws. A law of an interaction that changes x makes it a state, and
without one x is a parameter.
How it combines. It is the species of ReactionInteraction and
ReactionNetworkSystem, and on a lattice of classes, with space=, it is the distribution
that EncounterInteraction reads.
Limits and errors. It holds one number per member. A system that tracks several numbers per member uses its own
Element. The allowed values are checked when the system is prepared, so a negative initial value raises a
ValidationError from prepare.
from skcomplex.core.errors import ValidationError
try:
System(elements=[NonnegativeElement('A', x=-1.0)]).prepare()
except ValidationError as error:
message = str(error)
message
The system is not valid, with 1 error(s):
- A: A.x = -1.0 is not in its domain [0, +oo). Correct the component as the message describes. [value]
The message names the value A.x and the allowed values [0, +oo) that do not hold -1.0. The fix is an initial
value of zero or above.
A field realization. Biology names it a compartment of an epidemic, so the docstring of the subclass can say that
x counts people.
from typing import Annotated
from sage.all__sagemath_symbolics import oo
from sage.sets.real_set import RealSet
class CompartmentElement(NonnegativeElement):
def __init__(self, label, *, x: Annotated[float, RealSet.closed_open(0, oo)] = 0.0, size=None, space=None):
super().__init__(label, x=x, size=size, space=space)
CompartmentElement('susceptible', x=990.0).get_params()
{'label': 'susceptible', 'size': None, 'space': None, 'x': 990.0}
See its API entry.
PointElement
A PointElement is a body at the position x that the forces on it move. The forces give the acceleration x'', and
the velocity is the value x', which starts at zero unless values gives it. Here a ball leaves the origin at the
velocity (1, 2) and falls under a gravity of 1, the gradient of the potential y.
import numpy as np
from skcomplex.core.components.spaces import ContinuousSpace
from skcomplex.core.systems import System
from skcomplex.systems.general.elements import PointElement
from sage.all__sagemath_symbolics import vector
from skcomplex.core.components.interactions import Interaction
from skcomplex.core.components.laws import RateLaw
ball = PointElement('ball', x=np.array([0.0, 0.0]), values={"x'": np.array([1.0, 2.0])})
fall = lambda s: [RateLaw(s.target.x.diff(s.t, 2), vector([0, -1]))]
gravity = Interaction('gravity', roles={'target': 'ball'}, laws=fall)
flight = System(elements=[ball], interactions=[gravity], space=ContinuousSpace(n_dim=2)).prepare()
flight.simulate(until=2.0, dt=1.0).get_values('ball.x').round(3).tolist()
[[0.0, 0.0], [1.0, 1.5], [2.0, 2.0]]
The ball reaches (1, 1.5) after one second and (2, 2) after two, the parabola (t, 2t - t^2 / 2).
How the engine runs it. The laws on x'' give the order of the position, and the compiler adds the first-order
equations of the pair x and x'. A backend for molecular dynamics, such as LAMMPS, reads the velocity of a point
from x', and the boundary of the space acts on x.
How it combines. It lives in a ContinuousSpace. An
Interaction with within=RadiusNeighborhood(r) adds forces between points, such as
those of a gas or of a flock.
A field realization. Physics names the point with a mass a MassPointElement, whose forces divide by m.
See its API entry.
ReactionInteraction
A ReactionInteraction moves units from its reactants to its products, at a propensity that is the rate constant k
times the product of the reactant amounts, each raised to its coefficient. It is an
Interaction whose laws move the units of the stoichiometric vector, the number of units
each reaction takes from or gives to every species. A species is a pair of the path of an element and a state name. Here
an epidemic runs as two reactions, infection S + I -> 2 I and recovery I -> R.
from skcomplex.core.components.interactions import Interaction
from skcomplex.core.systems import System
from skcomplex.systems.general.elements import NonnegativeElement
from skcomplex.systems.general.reactions import ReactionInteraction
infection = ReactionInteraction('infection', reactants={('S', 'x'): 1, ('I', 'x'): 1}, products={('I', 'x'): 2}, k=5e-4)
recovery = ReactionInteraction('recovery', reactants={('I', 'x'): 1}, products={('R', 'x'): 1}, k=0.1)
people = [NonnegativeElement('S', x=990), NonnegativeElement('I', x=10), NonnegativeElement('R')]
sir = System(elements=people, interactions=[infection, recovery]).prepare()
trajectory = sir.simulate(until=50, dt=10.0)
infected = trajectory.get_values('I.x').round(1).tolist()
infected, float(trajectory.states[-1].sum()), issubclass(ReactionInteraction, Interaction)
([10.0, 294.4, 400.3, 175.0, 68.6, 26.4], 1000.0000000000003, True)
The infected rise from 10 to 400.3 at day 20 and fall to 26.4 at day 50, while the population stays at 1000. The last
value confirms that the class is an Interaction.
In chemistry the same class is the law of mass action. Two species bind into a complex, A + B -> C.
binding = ReactionInteraction('binding', reactants={('A', 'x'): 1, ('B', 'x'): 1}, products={('C', 'x'): 1}, k=0.01)
species = [NonnegativeElement('A', x=100.0), NonnegativeElement('B', x=50.0), NonnegativeElement('C')]
reactor = System(elements=species, interactions=[binding]).prepare()
reactor.simulate(until=10, dt=5.0).get_values('C.x').round(2).tolist()
[0.0, 47.86, 49.83]
The complex reaches 47.86 after five seconds and 49.83 after ten, close to the 50 units of B, the reactant that
runs out.
How the engine runs it. The argument mode chooses the laws. With 'rate' the reaction is a
RateLaw per species, the rate equation. With 'jump' it is a JumpLaw that
fires at the propensity and moves the units of the coefficients, which the algorithm of Gillespie runs. With
'langevin' it adds to the rate a NoiseLaw whose amplitude is the square root of the
propensity. The tags follow the mode.
jumps = binding.set_params(mode='jump')
sorted(jumps.get_tags().laws), jumps.get_tags().randomness
(['jump'], 'stochastic')
The laws are ['jump'] and the randomness is 'stochastic'.
How it combines. Its species are usually NonnegativeElement components. With target, a species may be the name
of a state of the target alone, and a target that is a group or a field reacts in every member. modifiers enter the
propensity without changing, as a catalyst does, and propensity replaces the product form, such as a saturating rate
of enzyme kinetics.
Limits and errors. The propensity is a product of amounts unless propensity says otherwise, and a reaction needs
at least one reactant or product. prepare raises a ValidationError for an empty reaction.
from skcomplex.core.errors import ValidationError
try:
ReactionInteraction('nothing', k=1.0).prepare()
except ValidationError as error:
message = str(error)
message
Reaction 'nothing' has neither reactants nor products. Give at least one of them.
The message reads "Reaction 'nothing' has neither reactants nor products. Give at least one of them." The fix is a
reactant, such as reactants={('A', 'x'): 1} for a decay.
A field realization. Epidemiology binds the species under roles of its own names. The subclass types the roles
with Role and returns the stoichiometry from the hooks _get_reactants and _get_products.
from skcomplex.core.types import Role
class InfectionInteraction(ReactionInteraction):
def __init__(self, label, *, susceptible: Role, infected: Role, k=5e-4):
super().__init__(label, k=k)
self.susceptible = susceptible
self.infected = infected
def _get_reactants(self):
return {(self.susceptible, 'x'): 1, (self.infected, 'x'): 1}
def _get_products(self):
return {(self.infected, 'x'): 2}
spread = InfectionInteraction('infection', susceptible='S', infected='I')
compartments = [NonnegativeElement('S', x=990), NonnegativeElement('I', x=10)]
outbreak = System(elements=compartments, interactions=[spread]).prepare()
outbreak.simulate(until=10, dt=10.0).get_values('I.x').round(1).tolist()
[10.0, 599.9]
Without recovery the infected reach 599.9 after ten days.
See its API entry.
ReactionNetworkSystem
A ReactionNetworkSystem writes a whole network of reactions as a table, with no element or interaction to write. It
takes the initial amount of every species and maps the label of every reaction to its reactants, its products, and its
rate constant. Here A and B convert into each other.
from skcomplex.systems.general.reactions import ReactionNetworkSystem
isomerization = ReactionNetworkSystem(
species={'A': 10.0, 'B': 0.0},
reactions={'forth': ({'A': 1}, {'B': 1}, 0.3), 'back': ({'B': 1}, {'A': 1}, 0.1)},
)
round(float(isomerization.prepare().simulate(until=50.0, dt=1.0).get_values('A.x')[-1]), 3)
2.5
The amount of A relaxes to 2.5, which is 0.1 / (0.3 + 0.1) of the total.
An epidemic of susceptible, infected, and recovered people is the same table with other names.
from skcomplex.systems.general.reactions import ReactionNetworkSystem
sir = ReactionNetworkSystem(
species={'S': 990.0, 'I': 10.0, 'R': 0.0},
reactions={'infection': ({'S': 1, 'I': 1}, {'I': 2}, 5e-4), 'recovery': ({'I': 1}, {'R': 1}, 0.1)},
)
sir.prepare().simulate(until=50, dt=10.0).get_values('I.x').round(1).tolist()
[10.0, 294.4, 400.3, 175.0, 68.6, 26.4]
The infected follow the curve of the epidemic of the previous section, 10, 294.4, 400.3, 175.0, 68.6, and 26.4 every ten days.
How the engine runs it. prepare builds a System with one
NonnegativeElement per species, named after it with its amount in x, and one ReactionInteraction per reaction.
The mode writes the reactions as rate equations, 'rate', as random events of single units, 'jump', or as
chemical Langevin equations, 'langevin'.
sir.set_params(mode='jump').get_tags().randomness
stochastic
The jump mode makes the system 'stochastic'.
How it combines. It is a BaseSystem, so simulate, calibrate, and the analyses take
it as they take any system. A field system subclasses it and gives its components through hooks:
_get_speciesreturns the initial amount of every species by name._get_reactionsreturns the reaction table._get_modereturns the mode._get_interactionsreturns the reactions as interactions, for a realization whose reactions bind roles of their own names, such as thesusceptibleandinfectedroles of an infection.
Limits and errors. Every propensity is a product of amounts. A reaction with another propensity goes through
_get_interactions. An unknown mode raises a ValidationError from prepare.
from skcomplex.core.errors import ValidationError
try:
sir.set_params(mode='fast').prepare()
except ValidationError as error:
message = str(error)
message
The system is not valid, with 2 error(s):
- infection: Reaction 'infection' has the mode 'fast'. Use one of rate, jump, langevin. Correct the component as the message describes. [value]
- recovery: Reaction 'recovery' has the mode 'fast'. Use one of rate, jump, langevin. Correct the component as the message describes. [value]
The message reads "Reaction 'infection' has the mode 'fast'. Use one of rate, jump, langevin."
A field realization. A field system takes the parameters of its model under its own names. SIRSystem of
biology takes beta and gamma this way. Epidemics and enzyme kinetics are both reaction networks with a product
propensity, which epidemiology calls homogeneous mixing and chemistry the law of mass action, so they share the
general system and differ in their realizations.
class OutbreakSystem(ReactionNetworkSystem):
def __init__(self, *, beta=5e-4, gamma=0.1, label='system'):
super().__init__(label=label)
self.beta = beta
self.gamma = gamma
def _get_species(self):
return {'S': 990.0, 'I': 10.0, 'R': 0.0}
def _get_reactions(self):
return {'infection': ({'S': 1, 'I': 1}, {'I': 2}, self.beta), 'recovery': ({'I': 1}, {'R': 1}, self.gamma)}
OutbreakSystem(gamma=0.2).prepare().simulate(until=50, dt=25.0).get_values('I.x').round(1).tolist()
[10.0, 132.1, 4.1]
With a faster recovery of 0.2 a day the infected number 132.1 at day 25 and 4.1 at day 50, so the outbreak stays smaller.
See its API entry.
EncounterInteraction
An EncounterInteraction models the meetings of members of two distributions in a kinetic system. A distribution is
a NonnegativeElement on a lattice with one value per class of a trait, such as the levels of an opinion. A
candidate at class h meets the field at class k at the rate rate[h, k], and a conservative encounter moves it to
class i with the probability kernel[h, k, i]. Here candidates at three opinion levels meet a field that pulls every
one of them to the first level.
import numpy as np
from skcomplex.core.components.spaces import LatticeSpace
from skcomplex.core.systems import System
from skcomplex.systems.general.elements import NonnegativeElement
from skcomplex.systems.general.kinetics import EncounterInteraction
kernel = np.zeros((3, 1, 3))
kernel[:, :, 0] = 1.0
gather = EncounterInteraction(
'gather', candidate='candidates', field='field', rate=lambda s: 1.0, kernel=lambda s: kernel
)
levels = LatticeSpace(3, boundary='fixed')
system = System(
elements=[
NonnegativeElement('candidates', x=[0.2, 0.3, 0.5], space=levels),
NonnegativeElement('field', x=[1.0], size=1),
],
interactions=[gather],
).prepare()
np.round(system.simulate(until=4.0, dt=0.5).get_values('candidates.x')[-1], 2).tolist()
[0.99, 0.01, 0.01]
After four units of time 0.99 of the candidates hold the first level.
In immunology a destructive encounter removes the tumour cells that immune cells meet. A tumour density of 1 meets an immune density of 0.4 at the rate 0.5, so it decays at the rate 0.2.
killing = EncounterInteraction('killing', candidate='tumour', field='immune', rate=lambda s: 0.5, outcome='destructive')
cells = System(
elements=[
NonnegativeElement('tumour', x=[1.0], space=LatticeSpace(1, boundary='fixed')),
NonnegativeElement('immune', x=[0.4], size=1),
],
interactions=[killing],
).prepare()
cells.simulate(until=10.0, dt=5.0).get_values('tumour.x').round(3).tolist()
[[1.0], [0.368], [0.135]]
The tumour falls to 0.368 at time 5 and to 0.135 at time 10, which is exp(-2).
How the engine runs it. The interaction returns a RateLaw whose rate is the
bilinear form of the core, a sum
of products of the two densities, which the compiler evaluates as arrays over the classes. A proliferative outcome adds
a candidate at class i, and with a cross_section the rate is the collision integral of kinetic theory, evaluated
by a fast spectral method.
How it combines. The candidates sit on the sites of a LatticeSpace of classes, or on a
PhaseSpace, where encounters pair classes at the same position. A density the encounter
reads is a state also when no law changes it, as the field of the tumour above. Without a field the encounter is a
linear redistribution between classes.
Limits and errors. The bilinear form needs a lattice of classes. A conservative encounter moves candidates by a
kernel, so prepare raises a ValidationError without one.
from skcomplex.core.errors import ValidationError
try:
EncounterInteraction('exchange', candidate='candidates', rate=lambda s: 1.0).prepare()
except ValidationError as error:
message = str(error)
message
The conservative encounter 'exchange' moves candidates by a kernel. Give `kernel`.
The message reads "The conservative encounter 'exchange' moves candidates by a kernel. Give kernel."
See its API entry.
GradientInteraction
A GradientInteraction takes a potential, one scalar function of the states, and moves every state down its
gradient. Here a particle in the double well U = (x^2 - 1)^2 / 4 slides from 0.5 to the bottom of the well at 1.
from skcomplex.core.components.elements import Element
from skcomplex.core.systems import System
from skcomplex.systems.general.gradients import GradientInteraction
well = GradientInteraction('well', target='particle', potential=lambda s: (s.target.x**2 - 1) ** 2 / 4)
landscape = System(elements=[Element('particle', values={'x': 0.5})], interactions=[well]).prepare()
landscape.simulate(until=10, dt=5.0).get_values('particle.x').round(3).tolist()
[0.5, 1.0, 1.0]
The particle reaches 1.0 by the fifth unit of time and stays there.
The same class fits the two weights of a model by descending its loss, the squared distance to the values 1 and -2.
loss = lambda s: (s.target.a - 1) ** 2 + (s.target.b + 2) ** 2
descent = GradientInteraction('descent', target='model', states=('a', 'b'), potential=loss)
model = Element('model', values={'a': 0.0, 'b': 0.0})
trajectory = System(elements=[model], interactions=[descent]).prepare().simulate(until=5, dt=5.0)
round(float(trajectory.get_values('model.a')[-1]), 3), round(float(trajectory.get_values('model.b')[-1]), 3)
(1.0, -2.0)
The weights reach 1.0 and -2.0, the minimum of the loss.
How the engine runs it. The interaction differentiates the potential symbolically and returns one rate law per
moving state, the gradient flow x' = -dU/dx. With inertia=True the force -dU/dx moves the second derivative
instead, divided by the mass m of an element that has one, for Newton's law. ScipyODESolver integrates the rates.
[law.__name__ for law in descent.law_classes]
['RateLaw']
The interaction emits rate laws.
How it combines. The role target binds an element or a group, and sources names the elements the potential
reads without moving them, such as the position of a fixed charge. Several gradient interactions on one state add
their forces. On an element with one member per site of a lattice, with variational=True, the potential is the density of a functional and the field
follows the Allen-Cahn equation, and conserved=True gives the Cahn-Hilliard equation.
Limits and errors. One potential gives every rate, so a force that is not the gradient of a potential, such as
friction, needs an interaction that sets its own rate law. The potential must be a function, and prepare raises a ValidationError
otherwise.
from skcomplex.core.errors import ValidationError
try:
GradientInteraction('well', target='particle', potential=1.0).prepare()
except ValidationError as error:
message = str(error)
message
The potential of 'well' is 1.0. Give a function of the namespace.
The message reads "The potential of 'well' is 1.0. Give a function of the namespace." The fix is a function, such as
lambda s: s.target.x**2 / 2.
A field realization. A field fixes the potential and names its parameters, such as a spring of stiffness k.
class SpringInteraction(GradientInteraction):
def __init__(self, label, *, target, k=1.0):
super().__init__(label, target=target, potential=lambda s: s.k * s.target.x**2 / 2)
self.k = k
spring = SpringInteraction('spring', target='particle', k=2.0)
relaxation = System(elements=[Element('particle', values={'x': 1.0})], interactions=[spring]).prepare()
round(float(relaxation.simulate(until=1, dt=1.0).get_values('particle.x')[-1]), 3)
0.135
The particle relaxes from 1 to 0.135 in one unit of time, which is exp(-2).
See its API entry.
EulerLagrangeInteraction
An EulerLagrangeInteraction takes a Lagrangian, the kinetic minus the potential energy, and moves the coordinates by
its equations of motion. Here a pendulum swings from an angle of 0.1 radians, with the Lagrangian
q'^2 / 2 + cos q in units where gravity and the length are 1.
from sage.all__sagemath_symbolics import cos
from skcomplex.core.components.elements import Element
from skcomplex.core.systems import System
from skcomplex.systems.general.mechanics import EulerLagrangeInteraction
lagrangian = lambda s: s.target.q.diff(s.t) ** 2 / 2 + cos(s.target.q)
swing = EulerLagrangeInteraction('swing', target='bob', states='q', lagrangian=lagrangian)
pendulum = System(elements=[Element('bob', values={'q': 0.1})], interactions=[swing]).prepare()
pendulum.simulate(until=3.2, dt=1.6).get_values('bob.q').round(3).tolist()
[0.1, -0.003, -0.1]
The angle passes through -0.003 at 1.6 seconds and reaches -0.1 at 3.2, half of the period 2 pi of small swings.
q.diff(t) is the velocity of the coordinate, and the trajectory reports it as "bob.q'".
The same class gives an electric circuit of a coil and a capacitor, written by its energy. The charge q is the
coordinate, the coil of inductance 2 stores L q'^2 / 2, and the capacitor of capacitance 0.5 stores q^2 / (2 C).
energy = lambda s: 2.0 * s.target.q.diff(s.t) ** 2 / 2 - s.target.q**2 / (2 * 0.5)
oscillation = EulerLagrangeInteraction('oscillation', target='circuit', states='q', lagrangian=energy)
circuit = System(elements=[Element('circuit', values={'q': 1.0})], interactions=[oscillation]).prepare()
circuit.simulate(until=3.14159, dt=3.14159 / 2).get_values('circuit.q').round(3).tolist()
[1.0, 0.0, -1.0]
The charge goes from 1 to 0 and to -1 in half a period, since the frequency 1 / sqrt(L C) is 1.
How the engine runs it. The interaction differentiates the Lagrangian and returns one equation per coordinate,
d/dt dL/dq' - dL/dq = Q - dR/dq', with the generalized forces Q and the dissipation R. The compiler solves the
equations together for the accelerations, so a Lagrangian with a mass matrix, such as that of a double pendulum,
needs no inversion by hand.
[law.__name__ for law in swing.law_classes]
['ConstraintLaw']
The interaction emits equation laws, which hold at every time.
How it combines. The role target binds an element or a group, and every role that binds one element adds its
coordinates. Equations of one coordinate from several interactions add, so a spring between two pendulums is an
interaction of its own whose Lagrangian holds only the coupling energy. dissipation and forcing add friction and
external forces.
Limits and errors. The Lagrangian must be a function, and the coordinates take the order 2 its equations
give them. prepare raises
a ValidationError for a Lagrangian that is not one.
from skcomplex.core.errors import ValidationError
try:
EulerLagrangeInteraction('swing', target='bob', states='q', lagrangian=0.5).prepare()
except ValidationError as error:
message = str(error)
message
The lagrangian of 'swing' is 0.5. Give a function of the namespace.
The message reads "The lagrangian of 'swing' is 0.5. Give a function of the namespace." The fix is a function of the namespace, as above.
A field realization. A field fixes the Lagrangian and names its parameters, such as a pendulum of length l under
gravity g.
class PendulumInteraction(EulerLagrangeInteraction):
def __init__(self, label, *, target, g=9.81, l=1.0):
lagrangian = lambda s: s.l**2 * s.target.q.diff(s.t) ** 2 / 2 + s.g * s.l * cos(s.target.q)
super().__init__(label, target=target, states='q', lagrangian=lagrangian)
self.g = g
self.l = l
PendulumInteraction('swing', target='bob', l=2.0).get_params()
{'g': 9.81, 'l': 2.0, 'label': 'swing', 'target': 'bob'}
Its parameters are the label, the target, g, and l.
See its API entry.
EquationInteraction
An EquationInteraction gives one state of an element its equation, written as a function. In continuous time the
equation is the rate of the state, and in discrete time it is the next value. A state named with a prime takes the
rate of its derivative, so "x''" gives an acceleration. The function reads the values of the element from s.target
and the time from s.t. Here a tank drains at half its level.
from skcomplex.core.components.elements import Element
from skcomplex.core.systems import System
from skcomplex.systems.general.dynamics import EquationInteraction
tank = Element('tank', values={'x': 1.0, 'k': 0.5})
decay = EquationInteraction('decay', target='tank', state='x', equation=lambda s: -s.target.k * s.target.x)
system = System(elements=[tank], interactions=[decay]).prepare()
system.simulate(until=2.0, dt=1.0).get_values('tank.x').round(3).tolist()
[1.0, 0.607, 0.368]
The level falls from 1.0 to 0.607 and 0.368, the curve exp(-t / 2). The same interaction with time='discrete' is
the logistic map of a population, whose next value reads the value at the start of the step.
population = Element('population', values={'n': 0.2, 'r': 3.2})
growth = EquationInteraction(
'growth',
target='population',
state='n',
equation=lambda s: s.target.r * s.target.n * (1 - s.target.n),
time='discrete',
)
logistic = System(elements=[population], interactions=[growth]).prepare()
logistic.simulate(until=3).get_values('population.n').round(3).tolist()
[0.2, 0.512, 0.8, 0.513]
The population runs through 0.2, 0.512, 0.8, and 0.513, on its way to a cycle of two values. A noise amplitude, such
as noise=0.1, adds a noise in the Itô convention, or in the Stratonovich one with convention='stratonovich'.
DynamicalSystem writes one such interaction for every state.
See its API entry.
FlowInteraction
A FlowInteraction moves an amount per unit of time from one stock of an element to another. It sets one rate law
whose target maps the stock it leaves to -1 and the stock it enters to +1, RateLaw({leaves: -1, enters: +1}, f,
label=label), so what leaves one stock enters the other and the trajectory records the flow f under its label. The amount reads the values of the
element from s.target and the time from s.t. Here people die at a rate of 0.05 and are counted among the dead.
from skcomplex.core.components.elements import Element
from skcomplex.core.systems import System
from skcomplex.systems.general.dynamics import FlowInteraction
population = Element('population', values={'alive': 100.0, 'dead': 0.0, 'd': 0.05})
deaths = FlowInteraction(
'deaths',
target='population',
leaves='alive',
enters='dead',
amount=lambda s: s.target.d * s.target.alive,
)
trajectory = System(elements=[population], interactions=[deaths]).prepare().simulate(until=10.0, dt=10.0)
trajectory.get_values('population.alive').round(2).tolist(), trajectory.get_values('population.deaths').round(
2
).tolist()
([100.0, 60.65], [5.0, 3.03])
The living fall from 100 to 60.65, the curve 100 exp(-t / 20), the dead hold the other 39.35, and the flow
population.deaths falls from 5.0 to 3.03 with them. A flow from outside the system gives only enters, such as
births, and a flow out of it only leaves. The loops analysis reads the flow as
a node between its stocks.
See its API entry.
AnnotatedElement
An AnnotatedElement holds values by name, as Element(label, values=...) does, with the allowed values and the
quantity of some of them. It reads them as a class would read Annotated on its arguments, so a value outside its
allowed values is rejected and the conservation monitor follows a quantity. DynamicalSystem and StockFlowSystem
build it from their allowed= and quantities=. Here a herd that cannot have a negative size is given one.
from sage.all__sagemath_symbolics import oo
from sage.sets.real_set import RealSet
from skcomplex.core.errors import ValidationError
from skcomplex.core.systems import System
from skcomplex.systems.general.dynamics import AnnotatedElement
herd = AnnotatedElement('herd', values={'n': -5.0}, allowed={'n': RealSet.closed_open(0, oo)})
try:
System(elements=[herd]).prepare()
except ValidationError as error:
message = str(error)
message
The system is not valid, with 1 error(s):
- herd: herd.n = -5.0 is not in its domain [0, +oo). Correct the component as the message describes. [value]
The message reads "herd.n = -5.0 is not in its domain [0, +oo)." A set of categories, such as
allowed={'status': {'S', 'I', 'R'}}, allows only those.
See its API entry.
DynamicalSystem
A DynamicalSystem is a set of states and the equations that evolve them, rates in continuous time or next values in
discrete time. It takes its data by name and writes one AnnotatedElement with one
EquationInteraction per state. The populations of Wilson and Cowan
in neuroscience are rates.
from sage.all__sagemath_symbolics import exp
from skcomplex.systems.general.dynamics import DynamicalSystem
populations = DynamicalSystem(
states={'e': 0.1, 'i': 0.05},
equations={
'e': lambda s: -s.target.e + 1 / (1 + exp(-(2 * s.target.e - 3 * s.target.i))),
'i': lambda s: -s.target.i + 1 / (1 + exp(-(2 * s.target.e - s.target.i))),
},
element='populations',
)
round(float(populations.prepare().simulate(until=20.0, dt=1.0).get_values('populations.e')[-1]), 3)
0.272
The excitatory activity e is 0.272 at time 20.
The multiplier and accelerator model of economics is a map. In discrete time every equation reads the states at the
start of the step, so previous takes the income of the last year.
economy = DynamicalSystem(
states={'y': 1.0, 'previous': 1.0},
equations={
'y': lambda s: (
s.target.g + s.target.c * (1 + s.target.v) * s.target.y - s.target.c * s.target.v * s.target.previous
),
'previous': lambda s: s.target.y,
},
parameters={'g': 1.0, 'c': 0.5, 'v': 0.5},
time='discrete',
element='economy',
)
economy.prepare().simulate(until=3).get_values('economy.y').round(3).tolist()
[1.0, 1.5, 1.875, 2.031]
The income runs through 1.0, 1.5, 1.875, and 2.031, a damped oscillation around the level g / (1 - c), which is 2.
How the engine runs it. In continuous time the rates form an ordinary differential equation, or a stochastic one
with noises, whose amplitudes are read in the Itô or Stratonovich convention. In discrete time the maps set the
next values once per step. An equation is a function of a namespace whose target holds the states and parameters
and whose t holds the time.
How it combines. It is a BaseSystem, so every workflow takes it. A subclass takes the parameters of its model
under its own names and returns its data from the hooks _get_states, _get_equations, _get_parameters,
_get_noises, _get_time, and _get_element_label. The arguments allowed and quantities, or the hooks
_get_allowed and _get_quantities, give the allowed values and the quantity of a state, such as
allowed={'n': RealSet.closed_open(0, oo)} for a population that cannot be negative.
Limits and errors. All states live in one element, so a model with many members uses
NetworkDynamicalSystem or ReactionDiffusionSystem. A noise
needs continuous time, and prepare raises a ValidationError otherwise.
from skcomplex.core.errors import ValidationError
noisy = DynamicalSystem(
states={'y': 1.0}, equations={'y': lambda s: s.target.y}, noises={'y': lambda s: 0.1}, time='discrete'
)
try:
noisy.prepare()
except ValidationError as error:
message = str(error)
message
DynamicalSystem has noise amplitudes in discrete time. Noise amplitudes need continuous time.
The message reads "DynamicalSystem has noise amplitudes in discrete time. Noise amplitudes need continuous time." The
fix is time='continuous', or no noise.
A field realization. Ecology writes the logistic growth of a population with its own parameters.
class LogisticSystem(DynamicalSystem):
def __init__(self, *, r=1.0, K=100.0, label='system'):
super().__init__(label=label)
self.r = r
self.K = K
def _get_states(self):
return {'n': 10.0}
def _get_equations(self):
return {'n': lambda s: s.target.r * s.target.n * (1 - s.target.n / s.target.K)}
def _get_parameters(self):
return {'r': self.r, 'K': self.K}
round(float(LogisticSystem().prepare().simulate(until=10.0, dt=10.0).get_values('state.n')[-1]), 2)
99.96
The population approaches its capacity of 100 and reaches 99.96 at time 10.
See its API entry.
NetworkDynamicalSystem
A NetworkDynamicalSystem puts the states on every node of a graph and adds to the rate of every coupled state the
sum over the neighbours sum_j A_ij g(x_i, x_j). Cells of a tissue exchange ions through gap junctions this way.
import networkx as nx
from skcomplex.systems.general.dynamics import NetworkDynamicalSystem
cells = NetworkDynamicalSystem(
nx.cycle_graph(4),
states={'v': [1.0, 0.0, 0.0, 0.0]},
equations={'v': lambda s: -s.target.v / s.target.tau},
coupling={'v': lambda s: s.member.g * (s.other.v - s.member.v)},
parameters={'tau': 10.0, 'g': 0.5},
element='cells',
)
cells.prepare().simulate(until=5.0, dt=1.0).get_values('cells.v')[-1].round(3).tolist()
[0.154, 0.152, 0.15, 0.152]
After five units of time the voltages are 0.154, 0.152, 0.15, and 0.152. The charge of the first cell has spread over the ring and decays.
Heat that flows between three rooms in a row is diffusion on a path graph, with no local equation.
rooms = NetworkDynamicalSystem(
nx.path_graph(3),
states={'u': [3.0, 0.0, 0.0]},
equations={'u': lambda s: 0 * s.target.u},
coupling={'u': lambda s: s.other.u - s.member.u},
element='rooms',
)
rooms.prepare().simulate(until=10.0, dt=10.0).get_values('rooms.u')[-1].round(3).tolist()
[1.0, 1.0, 1.0]
The rooms reach the same temperature, 1.0 each, and the total stays 3.
How the engine runs it. The states are the values of an Element with one member on
every node of the NetworkSpace of the graph. The equations are
EquationInteraction components, and every coupling is one more whose rate is the reduction
neighbors of its term, which reads node i as s.member and its neighbour as s.other. The rate laws make the
time continuous.
How it combines. A subclass returns the graph from _get_graph and the couplings from _get_coupling, besides
the hooks of DynamicalSystem. A local equation may also read the graph Laplacian, as network diffusion does.
Limits and errors. Every node holds the same states. A system without a graph raises a ValidationError from
prepare.
from skcomplex.core.errors import ValidationError
try:
NetworkDynamicalSystem(states={'v': 1.0}, equations={'v': lambda s: -s.target.v}).prepare()
except ValidationError as error:
message = str(error)
message
NetworkDynamicalSystem has no graph. Give a NetworkX graph whose nodes hold the states.
The message reads "NetworkDynamicalSystem has no graph. Give a NetworkX graph whose nodes hold the states."
See its API entry.
ReactionDiffusionSystem
A ReactionDiffusionSystem puts the states as fields on the sites of a lattice, with local kinetics and the diffusion
D laplacian(u) of every field that has a diffusivity D. The front of Fisher and Kolmogorov in ecology invades an
empty line.
import numpy as np
from skcomplex.systems.general.dynamics import ReactionDiffusionSystem
initial = np.zeros(50)
initial[:5] = 1.0
front = ReactionDiffusionSystem(
states={'u': initial},
equations={'u': lambda s: s.target.r * s.target.u * (1 - s.target.u)},
diffusivities={'u': 1.0},
shape=50,
boundary='reflecting',
parameters={'r': 1.0},
)
density = front.prepare().simulate(until=10.0, dt=5.0).get_values('medium.u')[-1]
int((density > 0.5).sum())
20
After ten units of time 20 sites hold more than half the capacity.
A pollutant that spreads along a channel and decays at the rate 0.1 is the same system with linear kinetics.
spill = np.zeros(20)
spill[10] = 1.0
channel = ReactionDiffusionSystem(
states={'u': spill},
equations={'u': lambda s: -s.target.k * s.target.u},
diffusivities={'u': 0.5},
shape=20,
boundary='reflecting',
parameters={'k': 0.1},
)
round(float(channel.prepare().simulate(until=5.0, dt=5.0).get_values('medium.u')[-1].sum()), 3)
0.607
The total falls to 0.607, which is exp(-0.5), since diffusion keeps the total and only the decay removes it.
How the engine runs it. The states are the values of an Element with one member on every site of a
LatticeSpace. The diffusion of every field is a separate EquationInteraction, so a split solver can treat it apart
from the kinetics, and the compiler turns the Laplacian into a stencil of the lattice.
How it combines. A subclass returns the diffusivities from _get_diffusivities, the lattice from _get_space, and
the boundary of every field from _get_boundaries, besides the hooks of DynamicalSystem. A chemistry system whose
kinetics are reactions returns them from _get_equation_interactions, as the Gray-Scott system of pattern formation
does.
Limits and errors. Every diffusivity must name a declared state, and prepare raises a ValidationError
otherwise.
from skcomplex.core.errors import ValidationError
broken = ReactionDiffusionSystem(
states={'u': 0.0}, equations={'u': lambda s: 0 * s.target.u}, diffusivities={'w': 1.0}, shape=5
)
try:
broken.prepare()
except ValidationError as error:
message = str(error)
message
ReactionDiffusionSystem has a diffusivity for the state 'w', which it does not declare. The declared states are ['u'].
The message says that the system has a diffusivity for the state 'w', which it does not declare, and lists the
declared states ['u'].
See its API entry.
StockFlowSystem
A StockFlowSystem is a set of stocks that change only through named flows, each from a stock, or from outside the
system, to a stock, or out of the system. The trajectory reports every flow. The arms race of Richardson is two stocks of arms that grow with the arms
of the other nation.
from skcomplex.systems.general.dynamics import StockFlowSystem
race = StockFlowSystem(
stocks={'a': 1.0, 'b': 1.0},
flows={
'arming_a': (None, 'a', lambda s: s.target.k * s.target.b),
'arming_b': (None, 'b', lambda s: s.target.k * s.target.a),
},
parameters={'k': 0.1},
element='nations',
)
trajectory = race.prepare().simulate(until=10.0, dt=5.0)
trajectory.get_values('nations.a').round(3).tolist(), trajectory.get_values('nations.arming_a').round(3).tolist()
([1.0, 1.649, 2.718], [0.1, 0.165, 0.272])
The arms of each nation grow as exp(0.1 t), to 2.718 at time 10, and the flow arming_a grows with them.
The bathtub of engineering fills from a tap at a rate of 1 and drains at half its content.
from skcomplex.systems.general.dynamics import StockFlowSystem
tub = StockFlowSystem(
stocks={'water': 0.0},
flows={'tap': (None, 'water', 1.0), 'drain': ('water', None, lambda s: 0.5 * s.target.water)},
element='tub',
)
tub.prepare().simulate(until=10.0, dt=5.0).get_values('tub.water').round(3).tolist()
[0.0, 1.836, 1.987]
The water rises to 1.836 at time 5 and to 1.987 at time 10, towards the level 2 where the drain matches the tap.
How the engine runs it. The stocks and parameters are the values of one AnnotatedElement,
which holds the allowed values and quantities given by allowed= and quantities=. Every flow is a
FlowInteraction, the rate terms -f on the stock it leaves and f on the stock it enters, so a
flow between two stocks keeps their total, and the trajectory reports it as <element>.<flow>. None stands for the
outside of the system, which the flow matrix of the loops analysis books as
'environment'. The amounts read the stocks and parameters from s.target and the time from s.t.
How it combines. A subclass returns its data from the hooks _get_stocks, _get_flows, _get_parameters,
_get_allowed, _get_quantities, and _get_element_label. The translator of system dynamics files reads models into this system.
Limits and errors. Every flow must leave or enter a declared stock, and prepare raises a ValidationError
otherwise.
from skcomplex.core.errors import ValidationError
try:
StockFlowSystem(stocks={'water': 0.0}, flows={'tap': (None, 'bath', 1.0)}).prepare()
except ValidationError as error:
message = str(error)
message
The flow 'tap' of StockFlowSystem names the stock 'bath', which it does not declare. The declared stocks are ['water'].
The message says that the flow 'tap' names the stock 'bath', which the system does not declare, and lists the
declared stocks ['water']. A stock allowed only values of zero or more rejects a negative start.
from sage.all__sagemath_symbolics import oo
from sage.sets.real_set import RealSet
drained = StockFlowSystem(
stocks={'water': -1.0},
flows={'drain': ('water', None, lambda s: 0.5 * s.target.water)},
allowed={'water': RealSet.closed_open(0, oo)},
element='tub',
)
try:
drained.prepare()
except ValidationError as error:
message = str(error)
message
The system is not valid, with 1 error(s):
- tub: tub.water = -1.0 is not in its domain [0, +oo). Correct the component as the message describes. [value]
The message reads "tub.water = -1.0 is not in its domain [0, +oo)."
See its API entry.
MovementInteraction
A MovementInteraction moves the agents of a group by steps at every step of discrete time. It returns an
UpdateLaw whose value is an agent rule, which the agent solver runs on every agent. Here two
sheep start in the middle of a pasture of 5 by 5 cells, at the cell their values x and y give, and each takes one
step to a neighbouring cell.
from skcomplex.core.components.elements import Element
from skcomplex.core.components.spaces import LatticeSpace
from skcomplex.core.systems import System
from skcomplex.systems.general.agents import MovementInteraction
pasture = LatticeSpace((5, 5), metric='manhattan')
sheep = Element('sheep', values={'x': [2, 2], 'y': [2, 2]}, size=2, space=pasture)
walk = MovementInteraction('walk', target='sheep', step='neighbor')
trajectory = System(elements=[sheep], interactions=[walk], space=pasture).prepare().simulate(until=1, random_state=0)
[int(abs(cell - 2).sum()) for cell in trajectory.get_agents('sheep', 1).locations]
[1, 1]
Each sheep stands one cell away from the middle.
Divers swim in a box of three dimensions by Gaussian steps, the random walk of physics.
from skcomplex.core.components.elements import Element
from skcomplex.core.components.spaces import ContinuousSpace
from skcomplex.core.systems import System
from skcomplex.systems.general.agents import MovementInteraction
divers = Element('divers', values={}, size=4)
swim = MovementInteraction('swim', target='divers', step='gaussian', scale=0.1)
space = ContinuousSpace(extent=(10.0, 5.0, 2.0), boundary='periodic')
trajectory = System(elements=[divers], interactions=[swim], space=space).prepare().simulate(until=5, random_state=0)
trajectory.get_agents('divers', 5).locations.shape
(4, 3)
The trajectory holds one location of three coordinates for each of the four divers.
How the engine runs it. MesaSolver runs the rule once per step for every agent for which condition holds, in
the order of schedule. The step chooses where an agent goes:
'neighbor': a random cell or node next to its own, on a lattice or a network.'gaussian': its position plus a normal vector of deviationscale, in a continuous space.'levy': a random direction and a Pareto length, in a continuous space.'best': the next cell with the highestscore(agent, cell, system).- a function
step(agent, system)that returns the destination, orNoneto stay.
An agent takes a step with the probability probability and then with the probability accept(agent, destination,
system). An exclusive movement never enters a cell held by another agent, and every step charges its cost.
How it combines. It moves the members of a group on a LatticeSpace, a NetworkSpace, or a
ContinuousSpace of two or three sides, and it changes where agents stand, while an UpdateLaw of a
TopologyRequestSpec changes the space itself. In three dimensions, placement,
steps, radius queries, the minimum image of a periodic box, and the locations of a trajectory use every side, and
system.dimensions returns every side. The solver rejects a continuous space with any other number of sides, or
without an extent, before the first frame, and the compile report holds the issue location-dimension for an initial
location whose length differs from the dimension of its space. AgentsVisual draws agents in three dimensions as
Points3D.
Limits and errors. It runs in discrete time with the agent solver. The step 'best' maximizes a score, so
prepare raises a ValidationError without one.
from skcomplex.core.errors import ValidationError
try:
MovementInteraction('forage', target='divers', step='best').prepare()
except ValidationError as error:
message = str(error)
message
The step `best` of 'forage' maximizes a score. Pass `score(agent, cell, system)`.
The message reads "The step best of 'forage' maximizes a score. Pass score(agent, cell, system)." The fix is a
score, such as the food in a cell.
A field realization. ZoneCouplingInteraction of biology and the boids of Boids3dSystem move agents by forces
of their own. A short realization fixes the step of a foraging animal.
class LevyForagingInteraction(MovementInteraction):
def __init__(self, label, *, target, exponent=1.5):
super().__init__(label, target=target, step='levy', exponent=exponent)
LevyForagingInteraction('forage', target='divers').step
levy
See its API entry.
Agents on region layers
Agents can move between named regions, such as census tracts. A space of two sides takes named polygons and layers
of polygons. An agent whose value region names a polygon starts inside it, and a step that returns the polygon of a
region moves an agent into it.
from shapely import Point, box
from skcomplex.core.components.elements import Element
from skcomplex.core.components.spaces import ContinuousSpace
from skcomplex.core.systems import System
from skcomplex.systems.general.agents import MovementInteraction
homes = {'home_0': box(0.0, 0.0, 4.0, 4.0), 'home_1': box(5.0, 0.0, 9.0, 4.0)}
places = [box(1.0, 6.0, 3.0, 8.0)]
people = Element('people', values={'region': ['home_0', 'home_0', 'home_1']}, size=3)
outing = MovementInteraction('outing', target='people', step=lambda agent, system: system.get_region('places', 0))
space = ContinuousSpace(extent=(10.0, 10.0), regions={**homes, 'places': places})
trajectory = System(elements=[people], interactions=[outing], space=space).prepare().simulate(until=1, random_state=0)
all(places[0].contains(Point(point)) for point in trajectory.get_agents('people', 1).locations)
True
Every person stands inside the place after one step.
ContinuousSpace(regions=...) maps the name of a region to a Shapely polygon, or the name of a layer to a sequence of
polygons, in the coordinates of the space. prepare keeps one STRtree per layer in regions_, and it raises
SpaceError, naming the layer and the region, for a region that is not a valid polygon.
- A polygon is a location in the value
regionof an element,SystemView.create, andAgentView.move_to. The solver draws a uniform point inside it from the generator of the run. It chooses a triangle of the constrained Delaunay triangulation of the polygon with a probability proportional to its area. AgentView.get_regions_here(layer)returns the indices of the regions of a layer that contain the agent.SystemView.get_region(layer, index)returns the polygon of a region, andSystemView.get_regions(layer)the number of regions of a layer.AgentsVisualdraws every layer once as staticLineStrips2Dunder the agents.
Real maps. The polygons of a space are in the coordinates of the space, and the library reads no coordinate
reference system. Census shapefiles usually come in longitude and latitude, where every distance, such as a radius, is
in degrees. Reproject them to a metric system first. With GeoPandas,
geopandas.read_file(path).to_crs(epsg=32604).geometry gives the polygons of a shapefile in metres for a Hawaiian
island. Then shift them so that no coordinate is negative, since a box runs from 0 to its sides. The next example does
the same with a plain local projection of one census polygon.
import math
import numpy as np
import shapely
from shapely import Polygon
from shapely.affinity import translate
EARTH_RADIUS = 6371000.0
tract = Polygon([(-159.6, 21.9), (-159.4, 21.9), (-159.4, 22.1), (-159.6, 22.1)])
def project(points):
scale = math.cos(math.radians(22.0))
return EARTH_RADIUS * np.radians(points) * np.array([scale, 1.0])
projected = shapely.transform(tract, project)
low_x, low_y, _, _ = projected.bounds
tract_in_metres = translate(projected, -low_x, -low_y)
[round(value, -3) for value in tract_in_metres.bounds]
[0.0, 0.0, 21000.0, 22000.0]
The tract spans about 21000 metres from west to east and 22000 metres from south to north.
KauaiPopulationSystem of skcomplex.systems.social.organizations places one agent per resident of the census
regions of the synthetic island of its package, and Boids3dSystem of skcomplex.systems.biology.collective_behaviour
flies in a periodic cube.
from skcomplex.systems.biology.collective_behaviour import Boids3dSystem
from skcomplex.systems.social.organizations import KauaiPopulationSystem
system = KauaiPopulationSystem(populations=(10, 5, 0)).prepare().system_
system.elements[0].size, list(system.space.regions), Boids3dSystem(n_boids=10).prepare().system_.space.extent
(15, ['boundary', 'places', 'facilities', 'census_0', 'census_1', 'census_2'], (20.0, 20.0, 20.0))
The island holds 15 agents, its space has the layers boundary, places, and facilities and one region per census
tract, census_0 to census_2, and the boids fly in a cube of side 20.
ChoiceInteraction
A ChoiceInteraction lets every member of a group pick an option by its utility. By the logit rule of discrete
choice, option k has the probability exp(beta u_k) / sum_j exp(beta u_j), where beta is the intensity of
choice. Here 500 members prefer to agree with the mean of the group, and a small majority for the option 1 grows into
a consensus.
import numpy as np
from skcomplex.core.components.elements import Element
from skcomplex.core.components.laws.utils import mean
from skcomplex.core.systems import System
from skcomplex.systems.general.agents import ChoiceInteraction
utility = lambda s, option: 2.0 * option * mean(s.target.option)
choice = ChoiceInteraction('choice', target='members', state='option', options=(-1, 1), utility=utility)
initial = np.where(np.random.default_rng(0).random(500) < 0.6, 1.0, -1.0)
members = Element('members', values={'option': initial}, size=500)
system = System(elements=[members], interactions=[choice]).prepare()
values = system.simulate(until=10, random_state=0).get_values('members.option')
round(float(initial.mean()), 2), round(float(values[-1].mean()), 2)
(0.13, 0.96)
The mean option rises from 0.13 to 0.96 in ten steps, close to the root of m = tanh(2 m), the consensus that the
mean field predicts.
In transport economics commuters choose between the bus, option 0, and the car, option 1, whose utility is one unit
higher. The logit rule gives the car the share e / (1 + e), about 0.73.
modes = (0, 1)
commute = ChoiceInteraction('commute', target='commuters', state='mode', options=modes, utility=lambda s, k: k)
commuters = Element('commuters', values={'mode': 0.0}, size=1000)
city = System(elements=[commuters], interactions=[commute]).prepare()
float(city.simulate(until=1, random_state=0).get_values('commuters.mode')[-1].mean())
0.75
In one draw 0.75 of the commuters take the car, close to the share of the logit rule.
How the engine runs it. Without a schedule, utility(namespace, option) returns an expression, and the
interaction returns an UpdateLaw that draws a new option for every member at once. With a
schedule, such as 'synchronous' or 'random-sequential', utility(agent, system, option) returns a number, and one
rule of the whole system walks the agents in that order with its own draws.
The rule 'metropolis' or 'fermi' accepts a proposed option, and the rule 'best' takes an option of largest
utility.
How it combines. It writes a discrete state of the members of a group, in discrete time since its laws are
updates, and the utility may read any state of the group, such as its mean, or of
neighbours. Each member revises with the probability activity.
Limits and errors. A choice needs at least two options, and prepare raises a ValidationError otherwise.
from skcomplex.core.errors import ValidationError
try:
single = ChoiceInteraction('commute', target='commuters', state='mode', options=(1,), utility=lambda s, k: k)
single.prepare()
except ValidationError as error:
message = str(error)
message
'commute' chooses among [1]. Give at least 2 options.
The message reads "'commute' chooses among [1]. Give at least 2 options."
A field realization. Social science names the choice above conformity. The catalog writes the standardization of
a technology the same way, as StandardizationInteraction of skcomplex.systems.social.opinion_dynamics.
class ConformityInteraction(ChoiceInteraction):
def __init__(self, label, *, target, strength=2.0):
super().__init__(
label,
target=target,
state='option',
options=(-1, 1),
utility=lambda s, option: strength * option * mean(s.target.option),
)
self.strength = strength
ConformityInteraction('conformity', target='members').options
(-1, 1)
See its API entry.
ImitationInteraction
An ImitationInteraction lets members copy a discrete state from their neighbours. It is a
interaction on the neighbours of a lattice or a network whose rule says whom a member copies: a random
neighbour, the local majority, the neighbour with the best payoff, or a neighbour chosen by the Fermi rule. Here
voters on a ring of twelve follow the majority of their two neighbours.
import numpy as np
from skcomplex.core.components.elements import Element
from skcomplex.core.components.spaces import LatticeSpace
from skcomplex.core.systems import System
from skcomplex.systems.general.agents import ImitationInteraction
initial = np.array([1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0], dtype=float)
majority = ImitationInteraction('majority', target='voters', rule='majority', probability=1.0)
voters = Element('voters', values={'state': initial}, space=LatticeSpace(12))
system = System(elements=[voters], interactions=[majority]).prepare()
system.simulate(until=1, random_state=0).get_values('voters.state')[-1].tolist()
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
After one step the lone 0 at the fourth site has joined its neighbours, and the votes read
[1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0].
Farmers adopt the crops of their neighbours on a network. On a star, the hub grows a new crop and four farms around it
do not. With the rule 'random' every farm copies a random neighbour at once.
import networkx as nx
from skcomplex.core.components.spaces import NetworkSpace
farms = Element('farms', values={'state': [1, 0, 0, 0, 0]}, space=NetworkSpace(nx.star_graph(4)))
adoption = ImitationInteraction('adoption', target='farms', rule='random', probability=1.0)
village = System(elements=[farms], interactions=[adoption]).prepare()
village.simulate(until=1, random_state=0).get_values('farms.state')[-1].tolist()
[0.0, 1.0, 1.0, 1.0, 1.0]
The four farms take the crop of the hub, and the hub takes the old crop of a farm, so the states read
[0, 1, 1, 1, 1].
How the engine runs it. Without a schedule imitation is a JumpLaw at the rate rate in
continuous time, or, when probability is given, an UpdateLaw that every member applies with that probability per
step, all at once. With a schedule it is one rule of the whole system that walks the agents in that order with its
own draws.
How it combines. Its neighbours come from the space of the group, a LatticeSpace or a NetworkSpace, or from
the layer of a network with several layers. The rules 'best' and 'fermi' read the payoff state, which another
interaction, such as a game, writes.
Limits and errors. It copies one discrete value, while a rate law along the edges, such as
RateLaw(s.target.x.diff(s.t), s.source.x - s.target.x), averages numeric states. The rule 'better' runs with a
schedule only, and prepare raises a ValidationError without one.
from skcomplex.core.errors import ValidationError
try:
ImitationInteraction('adoption', target='farms', rule='better').prepare()
except ValidationError as error:
message = str(error)
message
The rule of imitation 'better' runs with a schedule only, such as `"synchronous"`.
The message reads "The rule of imitation 'better' runs with a schedule only, such as "synchronous"."
A field realization. The voter model of social science is an imitation of a random neighbour at rate 1.
class VoterModelInteraction(ImitationInteraction):
def __init__(self, label, *, target):
super().__init__(label, target=target, rule='random')
VoterModelInteraction('voting', target='voters').rule
random
See its API entry.
EvolutionInteraction
An EvolutionInteraction breeds the strategies of a group by selection, crossover, and mutation, as a genetic
algorithm does. Every period steps it selects parents by their fitness and replaces strategies by offspring. Here the
fitness of a bit string is its number of ones, which an agent rule writes in a phase before the breeding.
import numpy as np
from skcomplex.core.components.elements import Element
from skcomplex.core.components.interactions import Interaction
from skcomplex.core.components.laws import UpdateLaw
from skcomplex.core.engine.compile import PhaseSpec
from skcomplex.core.engine.solvers import MesaSolver
from skcomplex.core.systems import System
from skcomplex.systems.general.agents import EvolutionInteraction
def score(agent, system):
agent.fitness = float(np.sum(agent.strategy))
initial = np.random.default_rng(0).integers(0, 2, size=(40, 20)).astype(float)
agents = Element('agents', values={'strategy': initial, 'fitness': 0.0}, size=40)
scoring = Interaction(
'scoring', roles={'target': 'agents'}, laws=lambda s: [UpdateLaw(s.target, score, phase='scoring')]
)
evolution = EvolutionInteraction('evolution', target='agents', phase='evolution')
solver = MesaSolver(phases=[PhaseSpec('scoring'), PhaseSpec('evolution')])
system = System(elements=[agents], interactions=[scoring, evolution], solver=solver).prepare()
trajectory = system.simulate(until=30, random_state=0)
final = np.array(trajectory.get_agents('agents', 30).values['strategy'].tolist())
float(initial.sum(axis=1).mean()), float(final.sum(axis=1).mean())
(10.675, 19.675)
The mean number of ones rises from 10.675 to 19.675 of 20 in thirty generations.
In economics firms learn a price by imitation of the profitable ones and by small trials. A real strategy, with
alphabet=None, mutates by a normal step of deviation scale, and the function evaluate gives the profit of every
price, highest at 3.
prices = np.random.default_rng(0).uniform(0, 6, size=(30, 1))
firms = Element('firms', values={'strategy': prices}, size=30)
learning = EvolutionInteraction(
'learning',
target='firms',
fitness=None,
alphabet=None,
scale=0.2,
mutation=0.5,
evaluate=lambda strategies, system: -((strategies[:, 0] - 3.0) ** 2),
)
market = System(elements=[firms], interactions=[learning]).prepare()
learned = np.array(market.simulate(until=20, random_state=0).get_agents('firms', 20).values['strategy'].tolist())
round(float(prices.std()), 2), round(float(learned.mean()), 2), round(float(learned.std()), 2)
(1.9, 3.01, 0.14)
The prices start spread with a deviation of 1.9 and gather near 3.01 with a deviation of 0.14 after twenty steps.
How the engine runs it. It returns one UpdateLaw whose value is a rule of the system, which the agent solver
runs once per period. The selection
picks parents by tournament, roulette, proportion, or rank. The replacement replaces the whole generation, or one
member at a time by the process of Moran, or by death and birth, truncation, or the best mutant.
How it combines. The strategies and the fitness are values of the members of a group. An agent rule, a game, or
the function evaluate writes the fitness, and the phases of
MesaSolver order the scoring before the
breeding.
Limits and errors. It replaces strategies across the whole group, while ImitationInteraction copies neighbours.
The counts must be valid, and prepare raises a ValidationError for a negative elite.
from skcomplex.core.errors import ValidationError
try:
EvolutionInteraction('learning', target='firms', elite=-1).prepare()
except ValidationError as error:
message = str(error)
message
'learning' has elite -1 and tournament 2. Give an elite of at least 0 and a tournament of at least 1.
The message reads "'learning' has elite -1 and tournament 2. Give an elite of at least 0 and a tournament of at least 1."
A field realization. Biology writes the process of Moran, one birth and one death at a time.
class MoranInteraction(EvolutionInteraction):
def __init__(self, label, *, target, mutation=0.01):
super().__init__(label, target=target, replacement='moran', mutation=mutation)
MoranInteraction('moran', target='agents').replacement
moran
See its API entry.
BirthDeathInteraction
A BirthDeathInteraction creates and removes the agents of a group. At every step an agent dies with the probability
death, and an agent that survives gives birth with the probability birth or at a Poisson rate. Here a cell of
mass 8 divides twice, and each division splits the mass between the parent and its offspring.
from skcomplex.core.components.elements import Element
from skcomplex.core.components.spaces import LatticeSpace
from skcomplex.core.systems import System
from skcomplex.systems.general.agents import BirthDeathInteraction
cells = Element('cells', values={'mass': 8.0}, size=1)
division = BirthDeathInteraction('division', target='cells', birth=1.0, split=('mass',))
system = System(elements=[cells], interactions=[division], space=LatticeSpace((3, 3))).prepare()
system.simulate(until=2, random_state=0).get_agents('cells', 2).values['mass'].tolist()
[2.0, 2.0, 2.0, 2.0]
After two steps four cells of mass 2.0 share the mass 8 of the first.
Rabbits in a warren breed with the probability 0.3 and die with the probability 0.1 each step. The interaction reports the births and deaths of every step.
rabbits = Element('rabbits', values={'mass': 0.0}, size=10)
breeding = BirthDeathInteraction('breeding', target='rabbits', birth=0.3, death=0.1)
field = System(elements=[rabbits], interactions=[breeding], space=LatticeSpace((10, 10))).prepare()
warren = field.simulate(until=5, random_state=0)
warren.get_values('breeding.births')[1:].tolist(), warren.get_values('breeding.deaths')[1:].tolist()
([2.0, 2.0, 2.0, 4.0, 5.0], [1.0, 2.0, 1.0, 1.0, 1.0])
Over five steps 15 rabbits are born and 6 die.
How the engine runs it. It returns one UpdateLaw whose value is a rule, and the agent solver runs it for every
agent in the order of schedule. Offspring stand where placement says, copy the states of inherit, take the values
of values, share the states of split with the parent, and may then mutate.
How it combines. Its group grows and shrinks as members come and go, with no setting. Further options reset or
replace the parent, renew a dying agent in place, cull a member of a kin group, and add arrivals without a parent. A
JumpLaw changes numeric states of a fixed set of members, while this interaction adds and removes
the members themselves.
Limits and errors. Births come by a probability or by a rate, not both, and prepare raises a
ValidationError when both are given.
from skcomplex.core.errors import ValidationError
try:
BirthDeathInteraction('breeding', target='rabbits', birth=0.3, rate=1.0).prepare()
except ValidationError as error:
message = str(error)
message
'breeding' gives births by a probability and by a rate. Give one of them.
The message reads "'breeding' gives births by a probability and by a rate. Give one of them."
A field realization. Biology writes cell division as a birth that halves the mass.
class DivisionInteraction(BirthDeathInteraction):
def __init__(self, label, *, target, probability=1.0):
super().__init__(label, target=target, birth=probability, split=('mass',))
DivisionInteraction('division', target='cells').split
('mass',)
See its API entry.
MatchingInteraction
A MatchingInteraction pairs requesters with providers by a rule and settles every match. Requesters state the
highest value they accept in their reserve state and the quantity they want in quantity, and providers the lowest
value they accept and the quantity they offer. Every match lowers the quantities of both sides and moves the states of
transfers. Here four buyers meet four sellers in a market for one good, and the function trade runs one round
under a given rule.
from skcomplex.core.components.elements import Element
from skcomplex.core.systems import System
from skcomplex.systems.general.matching import BatchMatchingSpec, MatchingInteraction
def trade(rule, on_match=None):
bids = {'reserve': [10.0, 8.0, 6.0, 4.0], 'quantity': 1.0, 'money': 20.0, 'goods': 0.0, 'partner': -1.0}
asks = {'reserve': [3.0, 5.0, 7.0, 9.0], 'quantity': 1.0, 'money': 0.0, 'goods': 1.0, 'partner': -1.0}
buyers = Element('buyers', values=bids, size=4)
sellers = Element('sellers', values=asks, size=4)
transfers = (('money', -1), ('goods', 1))
market = MatchingInteraction(
'market', requesters='buyers', providers='sellers', rule=rule, transfers=transfers, on_match=on_match
)
trajectory = System(elements=[buyers, sellers], interactions=[market]).prepare().simulate(until=1, random_state=0)
value, volume = trajectory.get_values('market.value')[-1], trajectory.get_values('market.volume')[-1]
return round(float(value), 2), float(volume)
trade(BatchMatchingSpec())
(6.5, 2.0)
A batch auction pairs the buyer at 10 with the seller at 3 and the buyer at 8 with the seller at 5, and both units clear at 6.5, the midpoint of the last paired limits.
In a labour market the requesters are firms that offer a wage up to their reserve, and the providers are workers who
accept a wage above theirs. The same interaction with transfers=(('money', -1),) moves the wage from the firm to the
worker for every match, and the section A market in two phases below runs a market over
several rounds.
How the engine runs it. It returns an UpdateLaw whose value is a rule of the system, which
pairs the two groups with pairs, the primitive of the core that pairs agents, and settles the matches. The matching
runs once per round of its phase, runs the algorithm of its rule on the offers, and reports <label>.value, the
clearing value weighted by quantity, <label>.volume, and <label>.unmatched. With ('money', -1) the value times the
quantity moves from the requester to the provider, and with ('goods', 1) the quantity moves back, so the totals stay
the same. on_match(match, system) adds any other effect.
How it combines. The rule is one of the specs below, or a function rule(requesters, providers, rng, capacity)
that returns pairs, which match at the midpoint of both limits. A name given as a pair, such as
reserve=('bid', 'ask'), names the state of the requesters and of the providers. A labelled
RateLaw flow map moves amounts between given stocks, while this interaction forms the pairs
first.
Limits and errors. A transfer moves value with the sign -1 or quantity with the sign 1, and prepare raises a
ValidationError for another sign.
from skcomplex.core.errors import ValidationError
try:
MatchingInteraction('market', requesters='buyers', providers='sellers', transfers=(('money', 2),)).prepare()
except ValidationError as error:
message = str(error)
message
The transfer of 'money' has the sign 2. Use one of (-1, 1).
The message reads "The transfer of 'money' has the sign 2. Use one of (-1, 1)."
See its API entry.
RandomSearchSpec
A RandomSearchSpec is the default rule of a matching, the decentralised exchange of Hamill and Gilbert (2016,
chapter 5). Every requester, in random order, meets up to tries providers that still offer something and matches
when the limits cross, at the midpoint of the two limits or at the limit of one side. Job seekers who meet a few firms
and buyers in a bazaar search this way. It continues the market of MatchingInteraction.
from skcomplex.systems.general.matching import RandomSearchSpec
trade(RandomSearchSpec()), trade(RandomSearchSpec(tries=4))
((8.0, 2.0), (6.83, 3.0))
With one meeting per buyer two units trade at a mean value of 8.0. With four meetings three units trade at 6.83, since
more buyers find a seller whose limit they accept. The value rule is 'midpoint', 'requester', or 'provider', and
the matching raises a ValidationError for any other when it checks its rule. See its
API entry.
PartnerMatchingSpec
A PartnerMatchingSpec lets requesters pick partners among candidates and then trade at a value. It is a
PartnerSpec of the core with the value of a pair, which only a matching reads. Its settings candidates, choice,
fallback, capacity, and score are those of PartnerSpec, such as the nearest shops of a buyer or the firms
within reach of a worker.
from skcomplex.systems.general.matching import PartnerMatchingSpec
trade(PartnerMatchingSpec())
(6.5, 4.0)
Each buyer picks a seller whose limit it accepts, and four units trade at a mean value of 6.5. See its API entry.
PartnerSwitchSpec
A PartnerSwitchSpec keeps a partner across steps and switches with friction, as in Caiani et al. (2016, chapter 2).
Every requester samples sample providers, and when the lowest limit among them is below that of its partner it
switches with the probability 1 - exp(intensity (p_new - p_old) / p_new). Households that keep their shops and firms
that keep their banks follow this rule. The state partner holds the id of the partner, which is why the traders
above declare it.
from skcomplex.systems.general.matching import PartnerSwitchSpec
trade(PartnerSwitchSpec())
(5.0, 3.0)
Three units trade at a mean value of 5.0, the limits of the chosen sellers. See its API entry.
QueueSpec
A QueueSpec serves requesters one by one, first come first served. Requesters queue in random order, by decreasing
reserve, or in order of creation, and each matches at the reserve of the cheapest provider whose reserve it accepts.
Customers at a shop and households waiting for housing queue this way.
from skcomplex.systems.general.matching import QueueSpec
trade(QueueSpec(order='reserve'))
(4.0, 2.0)
The buyers at 10 and 8 buy from the sellers at 3 and 5, so two units trade at a mean value of 4.0, and the buyers at
6 and 4 get nothing. An unknown order raises a ValidationError when the matching checks its rule.
from skcomplex.core.errors import ValidationError
try:
trade(QueueSpec(order='alphabetical'))
except ValidationError as error:
message = str(error)
message
The system is not valid, with 1 error(s):
- market: Unknown order 'alphabetical'. Use one of ('random', 'reserve', 'sequential'). Correct the component as the message describes. [value]
The message reads "Unknown order 'alphabetical'. Use one of ('random', 'reserve', 'sequential')." See its API entry.
IterativeMatchingSpec
An IterativeMatchingSpec moves a value until supply meets demand, the tâtonnement of Walras, as in Hamill and
Gilbert (2016, chapter 5). From the last clearing value, or the median of the limits, the value moves by
p <- p (1 + adjustment (D - S) / (D + S)) until the relative excess of requests falls below tolerance. The members
then match at that value, and the long side is rationed in random order. Prices in general equilibrium and wages in a
labour market adjust this way.
from skcomplex.systems.general.matching import IterativeMatchingSpec
trade(IterativeMatchingSpec())
(6.5, 2.0)
The value settles where two units are requested and offered, and both trade at 6.5. See its API entry.
ContinuousMatchingSpec
A ContinuousMatchingSpec matches offers as they arrive, as a limit order book does, following Caiani et al. (2016,
chapter 3). An arriving offer matches the best resting offers of the other side at their limits as long as the limits
cross, and its remainder rests until the end of the matching.
from skcomplex.systems.general.matching import ContinuousMatchingSpec
trade(ContinuousMatchingSpec())
(7.0, 3.0)
Three units trade at a mean value of 7.0, each at the limit of the offer that was resting. The order of arrival is
'random' or 'sequential'. See its API entry.
StableMatchingSpec
A StableMatchingSpec pairs by mutual preferences, the stable matching of Gale and Shapley that matches medical
residents with hospitals and students with schools. Requesters rank providers by requester_preference, by default
the lower reserve, and providers rank requesters by provider_preference, by default the higher reserve. The solver
of the matching library pairs every requester with at most one provider, so no requester and provider prefer each
other to their partners.
from skcomplex.systems.general.matching import StableMatchingSpec
trade(StableMatchingSpec())
(4.0, 2.0)
Two units trade at a mean value of 4.0, the limits of the providers, since value='provider' is the default. See its
API entry.
MatchSpec
A MatchSpec records one match that a rule made: the requester, the provider, the quantity, and the value per unit.
The function on_match of a MatchingInteraction receives one for every match, such as the loan a borrower takes at a
rate.
matches = []
trade(BatchMatchingSpec(), on_match=lambda match, system: matches.append((match.quantity, match.value)))
matches
(6.5, 2.0)
[(1.0, 6.5), (1.0, 6.5)]
The batch auction makes two matches of one unit, each at 6.5. See its API entry.
BatchMatchingSpec
A BatchMatchingSpec collects every offer and clears them at one value, as the call auction that opens a stock
exchange does. Requesters are sorted by decreasing and providers by increasing limit, and they pair while the limit of
the requester covers that of the provider. The value is the midpoint of the last paired limits.
MatchingInteraction runs it above, where two units clear at 6.5, and the
market in two phases below runs it over several rounds. It takes no settings.
BatchMatchingSpec()
BatchMatchingSpec()
See its API entry.
A market in two phases
Traders quote prices in one phase and trade in a batch auction in the next, while a clerk sets a fee from the volume
traded. The quotes are agent rules, the clerk is a rule of the whole system, UpdateLaw(s, rule), and the phases are
a setting of MesaSolver, which the section
Activation and phases
explains.
import numpy as np
from skcomplex.core.components.elements import Element
from skcomplex.core.components.interactions import Interaction
from skcomplex.core.components.laws import UpdateLaw
from skcomplex.core.engine.compile import PhaseSpec
from skcomplex.core.engine.solvers import MesaSolver
from skcomplex.core.systems import System
from skcomplex.core.types import Role
from skcomplex.systems.general.matching import BatchMatchingSpec, MatchingInteraction
class QuoteInteraction(Interaction):
def __init__(self, label, *, target: Role):
super().__init__(label)
self.target = target
def _prepare(self, s):
super()._prepare(s)
self.laws_ = [UpdateLaw(s.target, self.quote, phase='quote')]
def quote(self, agent, system):
agent.bid = system.rng.uniform(0, agent.value) if agent.demand else 0.0
agent.ask = system.rng.uniform(agent.value, 2.0) if agent.supply else 2.0
class ClerkInteraction(Interaction):
reports = ('traded',)
def __init__(self, label, *, buyers: Role = 'buyers', fee=0.0):
super().__init__(label)
self.buyers = buyers
self.fee = fee
def _prepare(self, s):
super()._prepare(s)
self.laws_ = [UpdateLaw(s, self.act, phase='trade')]
def act(self, system):
traded = sum(agent.goods for agent in system.get_agents('buyers'))
system.report('traded', traded)
system.set_parameter('fee', 0.01 * traded)
rng = np.random.default_rng(0)
quotes = {'bid': 0.0, 'ask': 0.0, 'demand': 0.0, 'supply': 0.0, 'money': 0.0, 'goods': 0.0}
buyers = {**quotes, 'value': rng.uniform(0.5, 2, 20), 'demand': 1.0, 'money': 2.0}
sellers = {**quotes, 'value': rng.uniform(0, 1.5, 20), 'supply': 1.0}
auction = System(
elements=[Element('buyers', values=buyers, size=20), Element('sellers', values=sellers, size=20)],
interactions=[
QuoteInteraction('buyer_quotes', target='buyers'),
QuoteInteraction('seller_quotes', target='sellers'),
MatchingInteraction(
'auction',
requesters='buyers',
providers='sellers',
rule=BatchMatchingSpec(),
reserve=('bid', 'ask'),
quantity=('demand', 'supply'),
cap='money',
transfers=(('money', -1), ('goods', 1)),
phase='trade',
),
ClerkInteraction('clerk'),
],
solver=MesaSolver(phases=[PhaseSpec('quote'), PhaseSpec('trade')]),
).prepare()
trajectory = auction.simulate(until=5, random_state=0)
prices = [round(float(price), 3) for price in trajectory.get_values('auction.value')[1:]]
prices, trajectory.get_values('auction.volume')[1:].tolist(), round(float(trajectory.get_values('clerk.fee')[-1]), 3)
([1.018, 1.231, 1.074, nan, 1.155], [4.0, 4.0, 1.0, 0.0, 2.0], 0.11)
The clearing prices of the rounds are 1.018, 1.231, 1.074, none in the fourth round, and 1.155, with the volumes 4,
4, 1, 0, and 2. No bid of the fourth round covers an ask, so nothing trades. The clerk counts 11 goods bought and
ends with a fee of 0.11. The state cap names the money of a buyer, the most value it can give.
The package rewriting brings numerics of its own: a compiler, a solver that rewrites one generation per step,
and a visual that draws words and tiles. The computer science of shift spaces and the fractals of mathematics both
use it.
WordElement
A WordElement holds a word of symbols, and the productions of an interaction that binds it rewrite it at every
generation. In the algae of Lindenmayer A becomes AB and B becomes A, so the length of the word runs through
the Fibonacci numbers.
from skcomplex.core.systems import System
from skcomplex.systems.general.rewriting import ProductionLaw, RewritingInteraction, WordElement
growth = RewritingInteraction('growth', target='algae', laws=[ProductionLaw('A', 'AB'), ProductionLaw('B', 'A')])
algae = System(elements=[WordElement('algae', axiom='A')], interactions=[growth]).prepare()
algae.simulate(until=5).get_values('algae.size').tolist()
[1.0, 2.0, 3.0, 5.0, 8.0, 13.0]
The Thue and Morse sequence of symbolic dynamics comes from the same classes, with 0 becoming 01 and 1
becoming 10.
doubling = RewritingInteraction('doubling', target='morse', laws=[ProductionLaw('0', '01'), ProductionLaw('1', '10')])
morse = System(elements=[WordElement('morse', axiom='0')], interactions=[doubling]).prepare()
morse.simulate(until=3).get_values('morse.size').tolist()
[1.0, 2.0, 4.0, 8.0]
How the engine runs it. Each generation applies every production to every matching symbol at once. The
rewriting solver advances one generation per unit of time and records the size of the word as the state size.
How it combines. The interactions that bind it set its productions, and a system of words holds only words,
patches, and these interactions. A geometry draws the word as line segments, as a turtle does, for plants and fractal
curves.
Limits and errors. The word grows at every generation, so max_size bounds it. A symbol outside alphabet, or a
word that would grow past max_size, raises a RewritingError during the run.
from skcomplex.core.errors import RewritingError
try:
System(elements=[WordElement('algae', axiom='A', max_size=4)], interactions=[growth]).prepare().simulate(until=5)
except RewritingError as error:
message = str(error)
message
Word 'algae' would reach 5 symbols at generation 3, above its maximum size 4. Raise max_size or run fewer generations.
The message says that the word would reach 5 symbols at generation 3, above its maximum size 4. The fix is a larger
max_size or fewer generations.
A field realization. The MorseSubshiftSystem of computer science rewrites a Thue-Morse word, and the
KochCurveSystem of mathematics a Koch curve, both with a RewritingInteraction.
See its API entry.
RewritingInteraction
A RewritingInteraction rewrites the word or the patch it binds by the productions or substitutions it is given. Here
it doubles every symbol of a word.
from skcomplex.core.systems import System
from skcomplex.systems.general.rewriting import ProductionLaw, RewritingInteraction, WordElement
doubling = RewritingInteraction('doubling', target='word', laws=[ProductionLaw('A', 'AA')])
word = System(elements=[WordElement('word', axiom='A')], interactions=[doubling]).prepare()
word.simulate(until=3).get_values('word.size').tolist()
[1.0, 2.0, 4.0, 8.0]
The word holds 1, 2, 4, and 8 symbols.
How the engine runs it. The interaction sets its laws in laws_ when it is prepared on the namespace of its word,
and the rewriting compiler, which the word names, compiles them into one kernel per word or patch.
How it combines. Rules that read parameters of their own, such as the ratio of a Cantor set, are written as a
subclass of Interaction whose _prepare sets them, and its numeric arguments are parameters of the system that a
schedule may change between generations.
Limits and errors. It takes only productions and substitutions, and prepare raises a RewritingError for any
other law.
See its API entry.
ProductionLaw
A ProductionLaw rewrites every matching symbol of a word by a string at every generation, as an L-system does. The
Koch curve replaces each segment F by F+F--F+F, where + and - turn the drawing pen.
from skcomplex.core.systems import System
from skcomplex.systems.general.rewriting import ProductionLaw, RewritingInteraction, WordElement
bend = RewritingInteraction('bend', target='koch', laws=[ProductionLaw('F', 'F+F--F+F')])
koch = System(elements=[WordElement('koch', axiom='F')], interactions=[bend]).prepare()
koch.simulate(until=3).get_values('koch.size').tolist()
[1.0, 8.0, 36.0, 148.0]
The word holds 1, 8, 36, and 148 symbols, since every segment becomes four segments and four turns.
The same law runs a grammar of linguistics. A sentence S becomes a noun phrase N and a verb phrase V, a noun
phrase becomes a determiner D and a word W, and a verb phrase takes a noun phrase as its object.
grammar = [ProductionLaw('S', 'NV'), ProductionLaw('N', 'DW'), ProductionLaw('V', 'VN')]
parsing = RewritingInteraction('grammar', target='sentence', laws=grammar)
sentence = System(elements=[WordElement('sentence', axiom='S')], interactions=[parsing]).prepare()
sentence.simulate(until=3).get_values('sentence.size').tolist()
[1.0, 2.0, 4.0, 6.0]
The structure holds 1, 2, 4, and 6 symbols.
How the engine runs it. The rewriting solver applies every production to every matching symbol at once, one
generation per unit of time, and records the length of the word as the state size.
How it combines. An interaction that binds a WordElement sets its productions, which act on its word. A production may read a left or
a right context, a condition on the parameters of a module, or a probability, so stochastic and parametric L-systems
use the same law.
Limits and errors. A word grows at every generation, so the element bounds it with max_size. The probability of a
stochastic production lies in [0, 1], and preparing a system with it raises a RewritingError otherwise.
from skcomplex.core.errors import RewritingError
weeds = RewritingInteraction('weeds', target='weed', laws=[ProductionLaw('F', 'FF', probability=1.5)])
try:
System(elements=[WordElement('weed', axiom='F')], interactions=[weeds]).prepare()
except RewritingError as error:
message = str(error)
message
The probability of a production is in [0, 1], not 1.5.
The message reads "The probability of a production is in [0, 1], not 1.5."
A field realization. The WordElement section holds the algae of Lindenmayer, a realization of botany.
See its API entry.
PatchElement
A PatchElement holds tiles, placed copies of basic shapes, and the substitutions of an interaction that binds it
replace them by smaller pieces at every generation. Keeping the outer thirds of every interval builds the Cantor set.
from skcomplex.core.systems import System
from skcomplex.systems.general.rewriting import (
AffineSpec,
PatchElement,
PrototileSpec,
RewritingInteraction,
SubstitutionLaw,
)
thirds = [AffineSpec(scale=1 / 3), AffineSpec(scale=1 / 3, translation=(2 / 3, 0))]
removal = RewritingInteraction(
'removal', target='cantor', laws=[SubstitutionLaw('interval', [('interval', third) for third in thirds])]
)
cantor = PatchElement('cantor', prototiles=[PrototileSpec('interval', [(0, 0), (1, 0)])])
System(elements=[cantor], interactions=[removal]).prepare().simulate(until=3).get_values('cantor.size').tolist()
[1.0, 2.0, 4.0, 8.0]
Replacing every triangle by its three corner triangles builds the Sierpinski triangle of geometry.
corners = [(0, 0), (1 / 2, 0), (1 / 4, 1 / 2)]
pieces = [('triangle', AffineSpec(scale=1 / 2, translation=corner)) for corner in corners]
copies = RewritingInteraction('copies', target='sierpinski', laws=[SubstitutionLaw('triangle', pieces)])
triangle = PatchElement('sierpinski', prototiles=[PrototileSpec('triangle', [(0, 0), (1, 0), (1 / 2, 1)])])
System(elements=[triangle], interactions=[copies]).prepare().simulate(until=3).get_values('sierpinski.size').tolist()
[1.0, 3.0, 9.0, 27.0]
How the engine runs it. Each generation applies every substitution to every tile of its prototile at once, and
the rewriting solver records the number of tiles as the state size.
How it combines. The interactions that bind it set its substitutions, and its tiles are drawn as polygons.
Limits and errors. Every tile must name a prototile of the patch, and prepare raises a RewritingError
otherwise.
from skcomplex.core.errors import RewritingError
try:
interval = PrototileSpec('interval', [(0, 0), (1, 0)])
PatchElement('patch', tiles=[('square', None)], prototiles=[interval]).prepare()
except RewritingError as error:
message = str(error)
message
The patch patch has a tile of the unknown prototile 'square'.
The message names the unknown prototile square. The fix is a tile of the prototile interval.
A field realization. The CantorInteraction and SierpinskiInteraction of
skcomplex.systems.mathematics.fractals are realizations of mathematics, and a tiling of physics, such as the Penrose
tiling of a quasicrystal, is written the same way.
See its API entry.
SubstitutionLaw
A SubstitutionLaw replaces every tile of a prototile, a shape of tile, by smaller placed pieces at every generation.
The Sierpinski carpet keeps eight of the nine thirds of every square.
from skcomplex.core.systems import System
from skcomplex.systems.general.rewriting import (
AffineSpec,
PatchElement,
PrototileSpec,
RewritingInteraction,
SubstitutionLaw,
)
corners = [(i / 3, j / 3) for i in range(3) for j in range(3) if (i, j) != (1, 1)]
pieces = [('square', AffineSpec(scale=1 / 3, translation=corner)) for corner in corners]
square = PrototileSpec('square', [(0, 0), (1, 0), (1, 1), (0, 1)])
holes = RewritingInteraction('holes', target='carpet', laws=[SubstitutionLaw('square', pieces)])
carpet = System(elements=[PatchElement('carpet', prototiles=[square])], interactions=[holes]).prepare()
carpet.simulate(until=3).get_values('carpet.size').tolist()
[1.0, 8.0, 64.0, 512.0]
The carpet holds 1, 8, 64, and 512 squares.
The same law subdivides the square tiling of the plane, which is its own substitution tiling. Every square becomes four squares of half the size.
corners = [(0, 0), (1 / 2, 0), (0, 1 / 2), (1 / 2, 1 / 2)]
pieces = [('square', AffineSpec(scale=1 / 2, translation=corner)) for corner in corners]
refinement = RewritingInteraction('refinement', target='grid', laws=[SubstitutionLaw('square', pieces)])
grid = System(elements=[PatchElement('grid', prototiles=[square])], interactions=[refinement]).prepare()
grid.simulate(until=3).get_values('grid.size').tolist()
[1.0, 4.0, 16.0, 64.0]
The tiling holds 1, 4, 16, and 64 squares.
How the engine runs it. The rewriting solver applies every substitution to every tile of its prototile at once,
one generation per unit of time, and records the number of tiles as the state size.
How it combines. An interaction that binds a PatchElement sets its substitutions, and several prototiles with one law each build a
tiling of several shapes, as the Penrose tiling does.
Limits and errors. Each piece pairs a prototile name with an AffineSpec, the map from the frame of the parent
tile, and preparing a system with it raises a RewritingError for any other piece.
from skcomplex.core.errors import RewritingError
thirds = RewritingInteraction('thirds', target='tiles', laws=[SubstitutionLaw('square', [('square', 1 / 3)])])
try:
System(elements=[PatchElement('tiles', prototiles=[square])], interactions=[thirds]).prepare()
except RewritingError as error:
message = str(error)
message
A piece of a substitution is a prototile name and an `AffineSpec`, not ('square', 0.3333333333333333).
The message says that a piece is a prototile name and an AffineSpec, not ('square', 0.3333333333333333). The fix
is ('square', AffineSpec(scale=1 / 3)).
A field realization. The PatchElement section holds the Cantor set and the Sierpinski triangle, realizations of mathematics.
See its API entry.
ModuleSpec
A ModuleSpec is a symbol of a word with parameters, such as a segment F(0.5) of length 0.5 or an apex A(x) whose
parameter a production reads. A word mixes plain symbols and modules, and parse_word reads it into modules.
from skcomplex.systems.general.rewriting import ModuleSpec
[module.name for module in ModuleSpec.parse_word(['F', ModuleSpec('A', (1.0,)), '+-'])]
['F', 'A', '+', '-']
The word reads as the modules F, A, +, and -. The parametric plant of Rewriting
systems shrinks its apex with them. See its
API entry.
AffineSpec
An AffineSpec places a piece of a substitution in the frame of its parent tile, by a scale, a rotation, a
translation, and an optional reflection. The right third of an interval is the interval scaled by a half and shifted
by one.
from skcomplex.systems.general.rewriting import AffineSpec
AffineSpec(scale=0.5, translation=(1, 0)).get_matrix_at({}).tolist()
[[0.5, 0.0, 1.0], [0.0, 0.5, 0.0], [0.0, 0.0, 1.0]]
The homogeneous matrix is [[0.5, 0, 1], [0, 0.5, 0], [0, 0, 1]]. Its entries can be expressions of the parameters
of the patch, which every generation evaluates. See its API entry.
PrototileSpec
A PrototileSpec is a shape of which the tiles of a patch are placed copies, a segment of two vertices or a polygon
of at least three. Its name names the count state of its tiles.
from skcomplex.systems.general.rewriting import PrototileSpec
interval = PrototileSpec('interval', [(0, 0), (1, 0)])
square = PrototileSpec('square', [(0, 0), (1, 0), (1, 1), (0, 1)])
interval.is_segment, square.is_segment
(True, False)
The interval is a segment and the square a polygon. See its API entry.
GeometrySpec
A GeometrySpec draws a word as line segments, as a turtle walks it: F draws a step, + and - turn by the angle,
and [ and ] save and restore the position for branches. The step shrinks by contraction at every generation, so
the Koch curve keeps its size.
from skcomplex.systems.general.rewriting import GeometrySpec
GeometrySpec(angle=60.0, contraction=1 / 3).dimension
2
The drawing is in two dimensions unless dimension=3. See its API entry.
GeometryVisual
A GeometryVisual logs the word or the patch of an element to the Rerun viewer, as line strips, or as an image for a
filled patch, with the counts of its symbols or tiles as time series. Words and patches name it as their visual, so a
RerunObserver draws them with it.
from skcomplex.systems.general.rewriting import GeometryVisual, WordElement
WordElement.visual.kind is GeometryVisual, GeometryVisual(filled=True)
(True, GeometryVisual(filled=True))
See its API entry.
RewritingSolver
A RewritingSolver rewrites every word and patch of a system once per unit of time, applying all productions at once.
The compiler of the rewriting package names it, so a run of words or patches uses it without a solver.
from skcomplex.systems.general.rewriting import RewritingSolver
RewritingSolver()
See its API entry.
Where a component goes
One ordered test, the placement rule of the package layout, decides where any new component goes. The source tests check it mechanically. It reads, word for word:
Every new component SHALL be placed by one ordered test. A structural base SHALL go to the core. A law kind, an operator generated from one function, or numerics the engine handles by type SHALL go to the core under a mathematical name, and the engine SHALL key only on the seven law kinds. Any other component is a recipe of core components, placed by its users:
skcomplex.systems.general.<concept>for several fields,systems/<field>/common/<family>for one field, its system's module for one system. Numerics that serve one field alone SHALL come as a solver or a compiler built on the public engine bases, in the package of that field. Every analysis SHALL be placed by its users too: an analysis that measures what systems of several fields share SHALL go toskcomplex.core.analysis, and an analysis of one field SHALL go tosystems/<field>/common/<family>. The core SHALL never importskcomplex.systems.
A field with its own term names its recipe, and general uses neutral names. One example for each step follows.
A structural base. A way for laws to run once per triangle of a cell complex goes to the core, as
Interaction with along='hyperedges' runs its laws once per hyperedge, and System
holds the components of a system. Components of every field build on them.
A component the engine handles by type. A law that a kernel lowers goes to the core under a mathematical name. The
binding along=RandomPartition(k) of Interaction stays in the core, since a compile
pass lowers it to kernels over random groups, and economics and social science both form groups. The operator bilinear
is in the core because the compiler lowers it, while EncounterInteraction, which only builds rate laws of bilinear
forms, is a recipe.
A recipe of several fields. An agent rule that economics and social science both use goes to a concept subpackage
of skcomplex.systems.general. ChoiceInteraction returns only laws the core already runs, and the oligopoly markets
of economics and the standardization of social science use it, so it lives in skcomplex.systems.general.agents.
A recipe of one field. The toppling of a sandpile serves several systems of physics only, so it lives in the
family avalanches of the physics common package, under the physics name TopplingInteraction.
A recipe of one system. The satisfiability of logical constraints serves one system, so
SatisfiabilityInteraction lives in the module of PerceptronSatisfiabilitySystem.
from skcomplex.core.components.interactions import Interaction, RandomPartition
from skcomplex.core.components.laws.utils import bilinear
from skcomplex.systems.general.agents import ChoiceInteraction
components = [Interaction, RandomPartition, bilinear, ChoiceInteraction]
[component.__module__.rsplit('.', 1)[0] for component in components]
['skcomplex.core.components.interactions', 'skcomplex.core.components.interactions',
'skcomplex.core.components.laws.utils', 'skcomplex.systems.general.agents']
The first three components live in skcomplex.core.components and the choice in skcomplex.systems.general.agents. The
toppling lives in the physics common package and the satisfiability in the module of its system, so the guide names
them without importing them, since only system classes are imported from a field.
A recipe that reveals a missing primitive. A recipe that needs an operation the engine cannot lower reveals a
missing primitive, which enters the core by the second step, and the recipe keeps no engine code. The satisfiability
once had a check of its own in the compiler, engine support inside a recipe. The check that a role accepts only Boolean
states became a primitive of the core, a word after the role in Annotated, such as Annotated[Role, 'boolean'], so
the recipe types its role with it and the compiler keeps no code for the class. Any interaction declares such a role the
same way. Here a rule on bits accepts only Boolean states, and a group of real states fails the check of the role before
any run.
from typing import Annotated
from skcomplex.core.components.elements import Element
from skcomplex.core.components.interactions import Interaction
from skcomplex.core.components.laws import UpdateLaw
from skcomplex.core.errors import RoleElementError
from skcomplex.core.systems import System
from skcomplex.core.types import Role
class BitRuleInteraction(Interaction):
def __init__(self, label, *, target: Annotated[Role, 'boolean']):
super().__init__(label)
self.target = target
def _prepare(self, s):
super()._prepare(s)
self.laws_ = [UpdateLaw(s.target.bit, 1 - s.target.bit)]
rule = BitRuleInteraction('sat', target='bits')
try:
System(elements=[Element('bits', values={'bit': 0.0}, size=2)], interactions=[rule]).prepare()
except RoleElementError as error:
message = str(error)
message
The system is not valid, with 1 error(s):
- system: The role 'target' of 'sat' accepts the domains boolean, but the element 'bits' bound to it has the state 'bit' of the domain 'real'. Bind the role to an element that has the value, give the element the value, such as `Element('ball', values={'x': 0.0})`, or read another value. `get_requirements()` of an interaction shows the values its roles read. [role-element]
The message says that the role target of sat accepts the domain boolean, but the element bits has the state
bit of the domain real. The fix is a Boolean value, such as values={'bit': False}.
Finally, sparse_identification of the core returns a System of core components, never a class of
skcomplex.systems, so the core runs without the catalog.
Recipes of one field
A recipe that only one field uses lives in that field, under the name the field gives it. Its system classes are the examples to read, and the gallery example of each system runs it.
TopplingInteractiondrives the members of a lattice and relaxes every member at or above a threshold, as inSandpileSystemofskcomplex.systems.physics.criticality. The section Cascades writes a cascade with the core operatorrelax.SimplexSpaceholds a density over the frequencies of several types, which sum to at most one, as inTrimorphicMultilevelSelectionSystemofskcomplex.systems.social.cooperation. The section Simplex domains runs it.PolicyRuleInteractionsets parameters once per round of its phase from what happened in the round, as inBrockHommesSystemofskcomplex.systems.economics.markets. A plainInteractionthat setsUpdateLaw(s, self.act, phase=...)does the same, as the clerk of the market above shows.SpacetimeSpaceandGeodesicInteractionmove a particle along the geodesics of a metric, as inSchwarzschildPrecessionSystemofskcomplex.systems.physics.celestial_mechanics. They need the extrarelativity, which installs EinsteinPy.ZoneCouplingInteractioncouples agents by zones of repulsion, alignment, and attraction, as inBoidsSystemofskcomplex.systems.biology.collective_behaviour.CellAdhesionInteractionsamples the regions of a cellular Potts model, as inCellularPottsSystemofskcomplex.systems.biology.physiology.SequenceSamplingInteractionsamples the rows of sequences, as inRNANeutralNetworksSystemofskcomplex.systems.biology.evolution.WilsonSamplingInteractionsamples the matrix links of a lattice gauge field, as inLatticeYangMillsSystemofskcomplex.systems.physics.waves.OptimizationInteractionmoves a population of candidates through pymoo, as inEvolutionaryOptimisersSystemofskcomplex.systems.computer_science.evolutionary_computation.SatisfiabilityInteractionreveals logical constraints step by step to a PySAT solver, as inPerceptronSatisfiabilitySystemofskcomplex.systems.computer_science.neural_networks.