Skip to content

Ecology

Ecology: population growth, predation, competition, food webs, succession, grazing, and neutral communities.

AbundanceElement(label, visual=None, *, x=0.01, age=0.0, threshold=0.001)

Bases: Element

Species of an ecosystem with its relative abundance and its age, which goes extinct below a threshold.

Parameters:

Name Type Description Default
label str

The label of the species or of the group of species.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
x Annotated[float, StateSpec(domain=closed_open(0, oo))]

The relative abundance.

0.01
age Annotated[float, StateSpec(domain=closed_open(0, oo))]

The number of steps since the species appeared.

0.0
threshold Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The abundance below which the species goes extinct.

0.001

Examples:

>>> from skcomplex.systems.biology.ecology import AbundanceElement
>>> AbundanceElement('species').threshold
0.001
Source code in src/skcomplex/systems/biology/ecology/_sequential.py
53
54
55
56
57
58
59
60
61
62
63
64
65
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    x: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
    age: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    threshold: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.001,
) -> None:
    super().__init__(label, visual=visual)
    self.x = x
    self.age = age
    self.threshold = threshold

CompetitionInteraction(label, *, first, second, r1=1.0, r2=1.0, K1=100.0, K2=100.0, alpha12=0.5, alpha21=0.5)

Bases: Interaction

Lotka-Volterra competition of two species for the same resources.

Each species grows logistically, and the other species fills its carrying capacity in proportion to a competition coefficient, dn1/dt = r1 n1 (1 - (n1 + alpha12 n2) / K1) and dn2/dt = r2 n2 (1 - (n2 + alpha21 n1) / K2).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
first Annotated[str, RoleSpec()]

The path of the first population.

required
second Annotated[str, RoleSpec()]

The path of the second population.

required
r1 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The growth rate of the first population.

1.0
r2 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The growth rate of the second population.

1.0
K1 Annotated[float, ParameterSpec(domain=open(0, oo))]

The carrying capacity of the first population.

100.0
K2 Annotated[float, ParameterSpec(domain=open(0, oo))]

The carrying capacity of the second population.

100.0
alpha12 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The effect of one member of the second population on the first, relative to one of its own.

0.5
alpha21 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The effect of one member of the first population on the second, relative to one of its own.

0.5

Examples:

>>> from skcomplex.systems.biology.ecology import CompetitionInteraction
>>> CompetitionInteraction('competition', first='deer', second='elk', alpha12=0.5).alpha12
0.5
Source code in src/skcomplex/systems/biology/ecology/_communities.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __init__(
    self,
    label: str,
    *,
    first: Annotated[str, RoleSpec()],
    second: Annotated[str, RoleSpec()],
    r1: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    r2: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    K1: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 100.0,
    K2: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 100.0,
    alpha12: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    alpha21: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
) -> None:
    super().__init__(label)
    self.first = first
    self.second = second
    self.r1 = r1
    self.r2 = r2
    self.K1 = K1
    self.K2 = K2
    self.alpha12 = alpha12
    self.alpha21 = alpha21

ConsumerElement(label, visual=None, *, N=0.1, e=1.0, m=1.0)

Bases: Element

Consumer species that grows on the energy it takes from resources and needs a maintenance energy to persist.

Parameters:

Name Type Description Default
label str

The label of the species or of the group of species.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
N Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial population size.

0.1
e Annotated[float, ParameterSpec(domain=open(0, oo))]

The efficiency that converts the energy taken in into growth.

1.0
m Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The maintenance energy, the intake at which the population neither grows nor declines.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import ConsumerElement
>>> ConsumerElement('consumers', m=0.5).m
0.5
Source code in src/skcomplex/systems/biology/ecology/_consumer_resources.py
57
58
59
60
61
62
63
64
65
66
67
68
69
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    N: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    e: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
    m: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
) -> None:
    super().__init__(label, visual=visual)
    self.N = N
    self.e = e
    self.m = m

ConsumerGrowthInteraction(label, *, consumers, resources, c=((1.0,),), kind='substitutable', n=-10.0)

Bases: ConsumptionInteraction

Growth of consumers on the resources they take up, minus their maintenance.

On substitutable resources, dN_i/dt = e_i N_i (sum_b w_b c_ib R_b - m_i). On essential resources, dN_i/dt = N_i (g_i - m_i) with g_i = (sum_b (c_ib R_b)^n)^(1/n).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
consumers Annotated[str, RoleSpec()]

The path of the group of consumers.

required
resources Annotated[str, RoleSpec()]

The path of the group of resources.

required
c Sequence[Sequence[float]]

The uptake rates, one row per consumer and one column per resource.

((1.0,),)
kind str

'substitutable' or 'essential' resources.

'substitutable'
n float

The exponent of the growth on essential resources, below -1.

-10.0

Examples:

>>> from skcomplex.systems.biology.ecology import ConsumerGrowthInteraction
>>> ConsumerGrowthInteraction('growth', consumers='consumers', resources='resources').c
((1.0,),)
Source code in src/skcomplex/systems/biology/ecology/_consumer_resources.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def __init__(
    self,
    label: str,
    *,
    consumers: Annotated[str, RoleSpec()],
    resources: Annotated[str, RoleSpec()],
    c: Sequence[Sequence[float]] = ((1.0,),),
    kind: str = 'substitutable',
    n: float = -10.0,
) -> None:
    super().__init__(label)
    self.consumers = consumers
    self.resources = resources
    self.c = c
    self.kind = kind
    self.n = n

ConsumptionInteraction(label, *, consumers, resources, c=((1.0,),), kind='substitutable', n=-10.0)

Bases: Interaction

Consumption of substitutable or essential resources by consumer species, the only way the consumers interact.

Consumer i takes up resource a at the rate c_ia R_a per individual. Substitutable resources add their energies w_b c_ib R_b, and essential resources all limit the growth, g_i = (sum_b (c_ib R_b)^n)^(1/n) for n < -1, which tends to Liebig's law g_i = min_b c_ib R_b as n goes to minus infinity. Its subclasses give the laws of the consumers and of the resources, which read the other group through reductions.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
consumers Annotated[str, RoleSpec()]

The path of the group of consumers.

required
resources Annotated[str, RoleSpec()]

The path of the group of resources.

required
c Sequence[Sequence[float]]

The uptake rates, one row per consumer and one column per resource.

((1.0,),)
kind str

'substitutable' or 'essential' resources.

'substitutable'
n float

The exponent of the growth on essential resources, below -1.

-10.0

Raises:

Type Description
ValidationError

The kind is unknown, or the exponent of essential resources is not below -1.

Examples:

>>> from skcomplex.systems.biology.ecology import ConsumptionInteraction
>>> uptake = ((0.5, 0.3), (0.4, 0.6))
>>> ConsumptionInteraction('consumption', consumers='consumers', resources='resources', c=uptake).kind
'substitutable'
Source code in src/skcomplex/systems/biology/ecology/_consumer_resources.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def __init__(
    self,
    label: str,
    *,
    consumers: Annotated[str, RoleSpec()],
    resources: Annotated[str, RoleSpec()],
    c: Sequence[Sequence[float]] = ((1.0,),),
    kind: str = 'substitutable',
    n: float = -10.0,
) -> None:
    super().__init__(label)
    self.consumers = consumers
    self.resources = resources
    self.c = c
    self.kind = kind
    self.n = n

CowElement(label, visual=VisualSpec('agents', {'radius': 0.4}), *, bite=0.75)

Bases: Element

Cow of the meadow, which the grazing and herding interactions feed and move every week.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'radius': 0.4})
bite Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The grass a cow eats in a week.

0.75

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import CowElement
>>> GroupElement('cows', element=CowElement, size=10).size
10
Source code in src/skcomplex/systems/biology/ecology/_meadow.py
54
55
56
57
58
59
60
61
62
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'radius': 0.4}),
    *,
    bite: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.75,
) -> None:
    super().__init__(label, visual=visual)
    self.bite = bite

EmotionMarksElement(label, visual=None, *, prey_happiness=0.0, prey_fear=0.0, predator_happiness=0.0, predator_anger=0.0, decay=0.2)

Bases: Element

Marks of one cell, the happiness and fear of prey and the happiness and anger of predators.

Animals with emotions leave their feelings in the cell they stand on, and the marks evaporate at the rate decay, which the system adds as an evaporation of every mark.

Parameters:

Name Type Description Default
label str

The label of the element or the lattice field.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
prey_happiness Annotated[object, StateSpec(domain=closed_open(0, oo))]

The initial happiness left by prey.

0.0
prey_fear Annotated[object, StateSpec(domain=closed_open(0, oo))]

The initial fear left by prey.

0.0
predator_happiness Annotated[object, StateSpec(domain=closed_open(0, oo))]

The initial happiness left by predators.

0.0
predator_anger Annotated[object, StateSpec(domain=closed_open(0, oo))]

The initial anger left by predators.

0.0
decay Annotated[object, ParameterSpec(domain=closed_open(0, oo))]

The rate at which every mark evaporates.

0.2

Examples:

>>> from skcomplex.systems.biology.ecology import EmotionMarksElement
>>> EmotionMarksElement('marks').decay
0.2
Source code in src/skcomplex/systems/biology/ecology/_stigmergy.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    prey_happiness: Annotated[object, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    prey_fear: Annotated[object, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    predator_happiness: Annotated[object, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    predator_anger: Annotated[object, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    decay: Annotated[object, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.2,
) -> None:
    super().__init__(label, visual=visual)
    self.prey_happiness = prey_happiness
    self.prey_fear = prey_fear
    self.predator_happiness = predator_happiness
    self.predator_anger = predator_anger
    self.decay = decay

FisherKPPElement(label, visual=None, *, u=0.0, D=1.0, r=1.0)

Bases: Element

Site of a line whose density u diffuses and grows logistically, du/dt = D laplacian(u) + r u (1 - u).

Parameters:

Name Type Description Default
label str

The label of the site.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
u Annotated[object, StateSpec(domain=closed_open(0, oo))]

The initial density, as a fraction of the carrying capacity.

0.0
D Annotated[object, ParameterSpec(domain=closed_open(0, oo))]

The diffusion coefficient.

1.0
r Annotated[object, ParameterSpec()]

The growth rate.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import FisherKPPElement
>>> FisherKPPElement('site', u=0.5).u
0.5
Source code in src/skcomplex/systems/biology/ecology/_fronts.py
47
48
49
50
51
52
53
54
55
56
57
58
59
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    u: Annotated[object, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    D: Annotated[object, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    r: Annotated[object, ParameterSpec()] = 1.0,
) -> None:
    super().__init__(label, visual=visual)
    self.u = u
    self.D = D
    self.r = r

ForagerElement(label, visual=VisualSpec('agents', {'color_by': 'happiness', 'radius': 0.35}), *, age=0.0, hunger=0.0, happiness=0.0, distress=0.0, experience=0.0, maturity=5.0, reproduction=0.3, starvation=10.0, memory=0.3, communication=0.1, emotions=1.0)

Bases: Element

Animal that hunts its food guided by its emotions and those its kind left on the ground, and breeds.

Every step the animal ages and grows hungry, and starves when its hunger passes starvation. It moves to the neighbouring cell, empty or holding food, of highest preference: 1 for food, plus, with emotions, the happiness marked there minus its own and its own distress minus the distress marked there. It eats food it moves onto. Its emotions follow E' = (1 - memory) (X + communication C) + memory E, with the experience X of the step and the mean emotion C marked around it, and it marks its cell with them. A mature animal breeds into an empty neighbouring cell with a probability that happiness raises and distress lowers, and its offspring shares its hunger, so a lineage starves together when its food is gone. Subclasses name their food and the marks they read, and the system adds the ageing, the hunger, the starvation, the experience of distress, the move, the meal, the emotions, the marks, and the breeding as member interactions.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'color_by': 'happiness', 'radius': 0.35})
age Annotated[float, StateSpec(domain=closed_open(0, oo))]

The steps since the animal last bred.

0.0
hunger Annotated[float, StateSpec(domain=closed_open(0, oo))]

The steps since the animal last ate.

0.0
happiness Annotated[float, StateSpec(domain=closed_open(0, oo))]

The happiness, which eating raises.

0.0
distress Annotated[float, StateSpec(domain=closed_open(0, oo))]

The fear or anger.

0.0
experience Annotated[float, StateSpec(domain=closed_open(0, oo))]

The distress the animal experienced in the step, before it moved.

0.0
maturity Annotated[float, ParameterSpec(domain=open(0, oo))]

The age at which the animal can breed.

5.0
reproduction Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of breeding at maturity without emotions.

0.3
starvation Annotated[float, ParameterSpec(domain=open(0, oo))]

The hunger at which the animal dies.

10.0
memory Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The share of its previous emotion that an animal keeps.

0.3
communication Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The weight of the emotions marked around the animal.

0.1
emotions Annotated[float, ParameterSpec(domain=FiniteEnumeratedSet([0, 1]))]

Whether emotions guide the animal, 1 or 0.

1.0

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import StigmergicPreyElement
>>> GroupElement('prey', element=StigmergicPreyElement, size=10).size
10
Source code in src/skcomplex/systems/biology/ecology/_stigmergy.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'color_by': 'happiness', 'radius': 0.35}),
    *,
    age: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    hunger: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    happiness: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    distress: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    experience: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    maturity: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 5.0,
    reproduction: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.3,
    starvation: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 10.0,
    memory: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.3,
    communication: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    emotions: Annotated[float, ParameterSpec(domain=FiniteEnumeratedSet([0, 1]))] = 1.0,
) -> None:
    super().__init__(label, visual=visual)
    self.age = age
    self.hunger = hunger
    self.happiness = happiness
    self.distress = distress
    self.experience = experience
    self.maturity = maturity
    self.reproduction = reproduction
    self.starvation = starvation
    self.memory = memory
    self.communication = communication
    self.emotions = emotions

GeneralizedLotkaVolterraInteraction(label, *, target, a=-1.0, state='x')

Bases: CouplingInteraction

Interactions of the species of a group, dx_i/dt += x_i sum_j a_ij x_j, through an interaction matrix a.

Every species i couples to every species j of the group, itself included, through the term x_i x_j weighted by the entry a_ij of the interaction matrix, a parameter with one row and one column per species, so a schedule or an experiment changes it. The diagonal entries are the interactions of a species with itself, negative for self-limitation. With the growth b_i x_i as a rate, it gives the generalized Lotka-Volterra equations dx_i/dt = x_i (b_i + sum_j a_ij x_j).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Annotated[str, RoleSpec()]

The path of the group of species.

required
a Annotated[object, ParameterSpec(shape=(target, target))]

The interaction matrix, where a_ij is the effect of species j on the growth of species i, or a number for every entry.

-1.0
state str

The name of the state that holds the abundance of a species.

'x'

Examples:

>>> from skcomplex.systems.biology.ecology import GeneralizedLotkaVolterraInteraction
>>> matrix = ((-1.0, 0.5), (0.5, -1.0))
>>> GeneralizedLotkaVolterraInteraction('glv', target='species', a=matrix).a
((-1.0, 0.5), (0.5, -1.0))
Source code in src/skcomplex/systems/biology/ecology/_microbial_communities.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    label: str,
    *,
    target: Annotated[str, RoleSpec()],
    a: Annotated[object, ParameterSpec(shape=('target', 'target'))] = -1.0,
    state: str = 'x',
) -> None:
    super().__init__(
        label,
        target=target,
        read=state,
        write=state,
        function=self._product,
        mode='group',
        weights='a',
        include_self=True,
    )
    self.a = a
    self.state = state

GrassElement(label, visual=VisualSpec('agents', {'color_by': 'grown', 'color_range': (0.0, 1.0), 'radius': 0.5}), *, grown=1.0, countdown=0.0, regrowth=30.0)

Bases: Element

Grass patch that regrows a fixed number of steps after it is eaten.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'color_by': 'grown', 'color_range': (0.0, 1.0), 'radius': 0.5})
grown Annotated[float, StateSpec(domain=NN)]

Whether the grass is grown, 1 or 0.

1.0
countdown Annotated[float, StateSpec(domain=closed_open(0, oo))]

The steps left until the grass is grown again.

0.0
regrowth Annotated[float, ParameterSpec(domain=open(0, oo))]

The number of steps the grass takes to regrow.

30.0

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import GrassElement
>>> GroupElement('grass', element=GrassElement, size=4, values={'grown': 1.0}).size
4
Source code in src/skcomplex/systems/biology/ecology/_wolf_sheep.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec(
        'agents',
        {'color_by': 'grown', 'color_range': (0.0, 1.0), 'radius': 0.5},
    ),
    *,
    grown: Annotated[float, StateSpec(domain=NN)] = 1.0,
    countdown: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    regrowth: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 30.0,
) -> None:
    super().__init__(label, visual=visual)
    self.grown = grown
    self.countdown = countdown
    self.regrowth = regrowth

regrow(agent, system)

Count down eaten grass and grow it back when the countdown ends.

Parameters:

Name Type Description Default
agent GrassView

The patch.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/biology/ecology/_wolf_sheep.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def regrow(self, agent: GrassView, system: SystemView) -> None:
    """Count down eaten grass and grow it back when the countdown ends.

    Args:
        agent:
            The patch.

        system:
            The system.
    """
    del system
    if agent.grown:
        return
    agent.countdown -= 1
    if agent.countdown <= 0:
        agent.grown = 1.0
        agent.countdown = agent.regrowth

GrazingInteraction(label, *, cows, pasture)

Bases: TransferInteraction

Weekly meal of every cow, which eats its bite of the grass of the patch in its cell.

It is a transfer of the grass of every patch, the bite of the cow in its cell or what grass is left, to the environment.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
cows Annotated[str, RoleSpec()]

The path of the group of cows.

required
pasture Annotated[str, RoleSpec()]

The path of the group of patches.

required

Examples:

>>> from skcomplex.systems.biology.ecology import GrazingInteraction
>>> GrazingInteraction('grazing', cows='cows', pasture='pasture').pasture
'pasture'
Source code in src/skcomplex/systems/biology/ecology/_meadow.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def __init__(
    self,
    label: str,
    *,
    cows: Annotated[str, RoleSpec()],
    pasture: Annotated[str, RoleSpec()],
) -> None:
    super().__init__(
        label,
        source=pasture,
        target=cows,
        state='grass',
        into=Sink(),
        amount=self._get_bite,
        pairing='cell',
        form='agent',
    )
    self.cows = cows
    self.pasture = pasture

HabitatPatchElement(label, visual=VisualSpec('image', {'low': 0.0}), *, n=10.0, alpha=1.0)

Bases: CompartmentElement

Patch of space, a compartment of n organisms that divide and die at the same rate alpha.

The divisions and deaths are jumps of neutral_clustering, so the number of organisms is a symmetric random walk, and an empty patch stays empty without arrivals from its neighbours.

Parameters:

Name Type Description Default
label str

The label of the patch or the lattice of patches.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('image', {'low': 0.0})
n Annotated[float, StateSpec(domain=NN)]

The initial number of organisms.

10.0
alpha Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The rate at which an organism divides, equal to the rate at which it dies.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import HabitatPatchElement
>>> HabitatPatchElement('patch', n=5.0).alpha
1.0
Source code in src/skcomplex/systems/biology/ecology/_clustering.py
49
50
51
52
53
54
55
56
57
58
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('image', {'low': 0.0}),
    *,
    n: Annotated[float, StateSpec(domain=NN)] = 10.0,
    alpha: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
) -> None:
    super().__init__(label, visual=visual, n=n)
    self.alpha = alpha

HerdingInteraction(label, *, cows, pasture, threshold=0.9)

Bases: MovementInteraction

Weekly move of every cow, in random order, to the nearest free patch with enough grass, or death.

It is a movement of the cows whose step leads every cow to the patch nearest to it that no other cow occupies and whose grass reaches threshold, and removes a cow that finds none. Every cow moves every week, the probability of movement fixed to 1 without a parameter.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
cows Annotated[str, RoleSpec()]

The path of the group of cows.

required
pasture Annotated[str, RoleSpec()]

The path of the group of patches.

required
threshold Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The least grass a patch needs for a cow to move there.

0.9

Examples:

>>> from skcomplex.systems.biology.ecology import HerdingInteraction
>>> HerdingInteraction('herding', cows='cows', pasture='pasture').threshold
0.9
Source code in src/skcomplex/systems/biology/ecology/_meadow.py
226
227
228
229
230
231
232
233
234
235
236
237
def __init__(
    self,
    label: str,
    *,
    cows: Annotated[str, RoleSpec()],
    pasture: Annotated[str, RoleSpec()],
    threshold: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.9,
) -> None:
    super().__init__(label, target=cows, step=self._herd)
    self.cows = cows
    self.pasture = pasture
    self.threshold = threshold

HoppingInteraction(label, *, patches, beta=0.5, links=())

Bases: Interaction

Hops of single organisms between neighbouring patches, each organism moving to each neighbour at the rate beta.

The patches are the entries of a variadic role, and every pair (i, j) of links gives a jump that moves one organism from the patch of entry i to the patch of entry j at the rate beta n_i.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
patches Annotated[list[str], RoleSpec(variadic=True)]

The paths of the patches, such as the members patches[i] of a lattice.

required
beta Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The rate at which an organism hops to one neighbouring patch.

0.5
links Sequence[tuple[int, int]]

The ordered pairs of entries of patches between which organisms hop.

()

Examples:

>>> from skcomplex.systems.biology.ecology import HoppingInteraction
>>> HoppingInteraction('hopping', patches=['a', 'b'], links=[(0, 1), (1, 0)]).beta
0.5
Source code in src/skcomplex/systems/biology/ecology/_clustering.py
86
87
88
89
90
91
92
93
94
95
96
97
def __init__(
    self,
    label: str,
    *,
    patches: Annotated[list[str], RoleSpec(variadic=True)],
    beta: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    links: Sequence[tuple[int, int]] = (),
) -> None:
    super().__init__(label)
    self.patches = patches
    self.beta = beta
    self.links = links

LinearGrowthInteraction(label, *, species, influences, rate=0.2)

Bases: Interaction

Linear growth of every species by the abundances of the species that influence it, normalised to one.

Every species grows by rate times the sum of the abundances of the species it reads weighted by the strengths w of the influences, its abundance stays nonnegative, and the abundances are normalised to sum to one.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
species Annotated[str, RoleSpec()]

The path of the group of species on the nodes.

required
influences Annotated[str, RoleSpec()]

The path of the variable group on the edges.

required
rate Annotated[float, ParameterSpec(domain=open(0, oo))]

The growth per step per unit of influence.

0.2

Examples:

>>> from skcomplex.systems.biology.ecology import LinearGrowthInteraction
>>> LinearGrowthInteraction('growth', species='species', influences='influences').rate
0.2
Source code in src/skcomplex/systems/biology/ecology/_sequential.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def __init__(
    self,
    label: str,
    *,
    species: Annotated[str, RoleSpec()],
    influences: Annotated[str, RoleSpec()],
    rate: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.2,
) -> None:
    super().__init__(label)
    self.species = species
    self.influences = influences
    self.rate = rate

MicrobeElement(label, visual=None, *, x=0.1, b=1.0)

Bases: Element

Species of a microbial community, with an abundance and an intrinsic growth rate.

Parameters:

Name Type Description Default
label str

The label of the species or of the group of species.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
x Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial abundance.

0.1
b Annotated[float, ParameterSpec()]

The intrinsic growth rate.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import MicrobeElement
>>> MicrobeElement('species', x=0.1, b=0.8).b
0.8
Source code in src/skcomplex/systems/biology/ecology/_microbial_communities.py
47
48
49
50
51
52
53
54
55
56
57
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    x: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    b: Annotated[float, ParameterSpec()] = 1.0,
) -> None:
    super().__init__(label, visual=visual)
    self.x = x
    self.b = b

MutualismInteraction(label, *, first, second, a=0.1, b=0.1, handling=0.5)

Bases: Interaction

Mutualism with a handling time, where encounters feed both species, a b n1 n2 / (1 + a T n) each.

The benefit to each species saturates with the abundance of its partner, as the handling time T limits how much of the partner's resource it can use. A handling time of 0 gives the unbounded type I mutualism a b n1 n2.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
first Annotated[str, RoleSpec()]

The path of the first population.

required
second Annotated[str, RoleSpec()]

The path of the second population.

required
a Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The effective search rate.

0.1
b Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The rate of encounters.

0.1
handling Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The handling time T of the resource of the partner.

0.5

Examples:

>>> from skcomplex.systems.biology.ecology import MutualismInteraction
>>> MutualismInteraction('pollination', first='orchids', second='bees', handling=0.5).handling
0.5
Source code in src/skcomplex/systems/biology/ecology/_communities.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def __init__(
    self,
    label: str,
    *,
    first: Annotated[str, RoleSpec()],
    second: Annotated[str, RoleSpec()],
    a: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    b: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    handling: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
) -> None:
    super().__init__(label)
    self.first = first
    self.second = second
    self.a = a
    self.b = b
    self.handling = handling

NeutralReplacementInteraction(label, *, target, mutation=0.01)

Bases: EvolutionInteraction

Deaths of random individuals at unit rate, each replaced by the offspring of another, a new species at rate nu.

One unit of time holds N deaths. The offspring belongs to the species of a parent drawn among the individuals, or with the probability mutation to a new species, labelled one above the largest label present. It is the neutral Moran replacement of EvolutionInteraction with mutation to new labels.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Annotated[str, RoleSpec()]

The path of the group of individuals.

required
mutation Annotated[float, ParameterSpec(domain=closed(0, 1))]

The probability nu that an offspring founds a new species.

0.01

Examples:

>>> from skcomplex.systems.biology.ecology import NeutralReplacementInteraction
>>> NeutralReplacementInteraction('replacement', target='community', mutation=0.01).change
'new'
Source code in src/skcomplex/systems/biology/ecology/_speciation.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def __init__(
    self,
    label: str,
    *,
    target: Annotated[str, RoleSpec()],
    mutation: Annotated[float, ParameterSpec(domain=RealSet.closed(0, 1))] = 0.01,
) -> None:
    super().__init__(
        label,
        target=target,
        strategy='species',
        fitness=None,
        selection='proportional',
        replacement='moran',
        mutation=mutation,
        alphabet=None,
        change='new',
    )

NeutralSpeciesElement(label, visual=None, *, n=10.0, b0=1.0, b1=0.9, d0=0.0, d1=1.0)

Bases: CompartmentElement

Species of neutral theory, a compartment of n individuals with birth and death rates shared by every species.

The births of neutral_macroecology occur at the rate b0 + b1 n, with immigration or speciation b0, and its deaths at the rate d0 + d1 n, with emigration or extinction d0 while the species has members.

Parameters:

Name Type Description Default
label str

The label of the species or the group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
n Annotated[float, StateSpec(domain=NN)]

The initial number of individuals.

10.0
b0 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The rate of immigration or speciation.

1.0
b1 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The per capita birth rate.

0.9
d0 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The rate of emigration or extinction.

0.0
d1 Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The per capita death rate.

1.0

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import NeutralSpeciesElement
>>> GroupElement('trees', element=NeutralSpeciesElement, size=50).size
50
Source code in src/skcomplex/systems/biology/ecology/_neutral.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    n: Annotated[float, StateSpec(domain=NN)] = 10.0,
    b0: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    b1: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.9,
    d0: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    d1: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
) -> None:
    super().__init__(label, visual=visual, n=n)
    self.b0 = b0
    self.b1 = b1
    self.d0 = d0
    self.d1 = d1

OrganismElement(label, visual=VisualSpec('agents', {'color_by': 'species'}), *, species=0.0)

Bases: Element

Individual of a neutral community, labelled by its species.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'color_by': 'species'})
species Annotated[float, StateSpec(domain=NN)]

The label of the species.

0.0

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import OrganismElement
>>> GroupElement('community', element=OrganismElement, size=10, values={'species': 0.0}).size
10
Source code in src/skcomplex/systems/biology/ecology/_speciation.py
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'color_by': 'species'}),
    *,
    species: Annotated[float, StateSpec(domain=NN)] = 0.0,
) -> None:
    super().__init__(label, visual=visual)
    self.species = species

ParasitismInteraction(label, *, host, parasitoid, k=2.0, a=0.05, c=1.0)

Bases: Interaction

Nicholson-Bailey parasitism of hosts by parasitoids in discrete generations.

Parasitoids search at random, so a host escapes with probability exp(-a P), giving H' = k H exp(-a P) and P' = c H (1 - exp(-a P)).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
host Annotated[str, RoleSpec()]

The path of the host population H.

required
parasitoid Annotated[str, RoleSpec()]

The path of the parasitoid population P.

required
k Annotated[float, ParameterSpec(domain=open(0, oo))]

The reproductive rate of the hosts.

2.0
a Annotated[float, ParameterSpec(domain=open(0, oo))]

The searching efficiency of the parasitoids.

0.05
c Annotated[float, ParameterSpec(domain=open(0, oo))]

The number of viable eggs a parasitoid lays in a host.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import ParasitismInteraction
>>> ParasitismInteraction('parasitism', host='moths', parasitoid='wasps', k=2.0).k
2.0
Source code in src/skcomplex/systems/biology/ecology/_predation.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(
    self,
    label: str,
    *,
    host: Annotated[str, RoleSpec()],
    parasitoid: Annotated[str, RoleSpec()],
    k: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 2.0,
    a: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.05,
    c: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
) -> None:
    super().__init__(label)
    self.host = host
    self.parasitoid = parasitoid
    self.k = k
    self.a = a
    self.c = c

PastureElement(label, visual=VisualSpec('agents', {'color_by': 'grass', 'color_range': (0.0, 1.0)}), *, grass=1.0, growth=0.2)

Bases: Element

Patch of grass that regrows logistically every week, G' = G + g G (1 - G).

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'color_by': 'grass', 'color_range': (0.0, 1.0)})
grass Annotated[float, StateSpec(domain=closed_open(0, oo))]

The amount of grass, between 0 and 1.

1.0
growth Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The weekly growth rate g of the grass.

0.2

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import PastureElement
>>> GroupElement('pasture', element=PastureElement, size=4, values={'growth': 0.1}).size
4
Source code in src/skcomplex/systems/biology/ecology/_meadow.py
103
104
105
106
107
108
109
110
111
112
113
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'color_by': 'grass', 'color_range': (0.0, 1.0)}),
    *,
    grass: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    growth: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.2,
) -> None:
    super().__init__(label, visual=visual)
    self.grass = grass
    self.growth = growth

regrow(agent, system)

Grow the grass by one week of logistic growth.

Parameters:

Name Type Description Default
agent PastureView

The patch.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/biology/ecology/_meadow.py
133
134
135
136
137
138
139
140
141
142
143
144
def regrow(self, agent: PastureView, system: SystemView) -> None:
    """Grow the grass by one week of logistic growth.

    Args:
        agent:
            The patch.

        system:
            The system.
    """
    del system
    agent.grass += agent.growth * agent.grass * (1 - agent.grass)

PioneerGrowthInteraction(label, *, target, intermediate, climax, half_time=3.65, w_intermediate=0.32, w_climax=0.68)

Bases: RateInteraction

Michaelis-Menten regrowth of pioneer trees, whose input from seeds the other groups suppress.

Alone, the volume follows V(t) = V_mat t / (K_M + t) after a clear cut, which is dV/dt = V (V / V_mat - 2) / K_M + C V_mat / K_M with C = 1. The other groups reduce the factor C = 1 - w_I V_I / V_mat,I - w_C V_C / V_mat,C, with weights normalized to sum to one, and no lower than 0.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Annotated[str, RoleSpec()]

The path of the pioneer stand.

required
intermediate Annotated[str, RoleSpec()]

The path of the intermediate stand.

required
climax Annotated[str, RoleSpec()]

The path of the climax stand.

required
half_time Annotated[float, ParameterSpec(domain=open(0, oo))]

The time K_M the pioneers take to reach half their mature volume.

3.65
w_intermediate Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The weight of the intermediate group in the competition.

0.32
w_climax Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The weight of the climax group in the competition.

0.68

Examples:

>>> from skcomplex.systems.biology.ecology import PioneerGrowthInteraction
>>> PioneerGrowthInteraction('growth', target='keora', intermediate='gewa', climax='sundari').half_time
3.65
Source code in src/skcomplex/systems/biology/ecology/_succession.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def __init__(
    self,
    label: str,
    *,
    target: Annotated[str, RoleSpec()],
    intermediate: Annotated[str, RoleSpec()],
    climax: Annotated[str, RoleSpec()],
    half_time: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 3.65,
    w_intermediate: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.32,
    w_climax: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.68,
) -> None:
    super().__init__(label, target=target, state='volume')
    self.intermediate = intermediate
    self.climax = climax
    self.half_time = half_time
    self.w_intermediate = w_intermediate
    self.w_climax = w_climax

PlantElement(label, visual=VisualSpec('agents', {'radius': 0.25}), *, age=0.0, maturity=4.0)

Bases: Element

Plant that spreads into an empty neighbouring cell whenever it reaches maturity.

The system adds the ageing and the spreading as member interactions, and a plant that spreads starts its age anew.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'radius': 0.25})
age Annotated[float, StateSpec(domain=closed_open(0, oo))]

The steps since the plant last spread.

0.0
maturity Annotated[float, ParameterSpec(domain=open(0, oo))]

The age at which the plant spreads.

4.0

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import PlantElement
>>> GroupElement('plants', element=PlantElement, size=100).size
100
Source code in src/skcomplex/systems/biology/ecology/_stigmergy.py
388
389
390
391
392
393
394
395
396
397
398
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'radius': 0.25}),
    *,
    age: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    maturity: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 4.0,
) -> None:
    super().__init__(label, visual=visual)
    self.age = age
    self.maturity = maturity

PredationInteraction(label, *, predator, prey, a=0.1, b=0.01)

Bases: Interaction

Lotka-Volterra predation, where encounters remove prey and feed predators.

The prey loses a * predator * prey per unit time and the predator gains b * predator * prey.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
predator Annotated[str, RoleSpec()]

The path of the predator population.

required
prey Annotated[str, RoleSpec()]

The path of the prey population.

required
a Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The attack rate.

0.1
b Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The conversion rate of eaten prey into predators.

0.01

Examples:

>>> from skcomplex.systems.biology.ecology import PredationInteraction
>>> PredationInteraction('hunt', predator='foxes', prey='rabbits', a=0.4, b=0.1).prey
'rabbits'
Source code in src/skcomplex/systems/biology/common/populations/_predation.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def __init__(
    self,
    label: str,
    *,
    predator: Annotated[str, RoleSpec()],
    prey: Annotated[str, RoleSpec()],
    a: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    b: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
) -> None:
    super().__init__(label)
    self.predator = predator
    self.prey = prey
    self.a = a
    self.b = b

PredatorElement(label, visual=VisualSpec('agents', {'radius': 0.4}), *, meals=0.0, conversion=0.5, death=0.1)

Bases: Element

Predator that walks at random, eats a prey of its cell, breeds after a meal, and dies.

In its own activation a predator walks to a random neighbouring cell, eats and removes one random prey of the new cell, counted in meals, breeds with the probability conversion after a meal, dies with the probability death, and digests its meals, by member interactions.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'radius': 0.4})
meals Annotated[float, StateSpec(domain=NN)]

The prey the predator ate in the current step.

0.0
conversion Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of breeding after eating a prey.

0.5
death Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of dying at every step.

0.1

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import PredatorElement
>>> GroupElement('foxes', element=PredatorElement, size=50).size
50
Source code in src/skcomplex/systems/biology/ecology/_agent_predation.py
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'radius': 0.4}),
    *,
    meals: Annotated[float, StateSpec(domain=NN)] = 0.0,
    conversion: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    death: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
) -> None:
    super().__init__(label, visual=visual)
    self.meals = meals
    self.conversion = conversion
    self.death = death

PredatorPreyEventsInteraction(label, *, prey, predators, r=1.0, K=200.0, a=0.02, h=0.5, e=0.5, m=0.3, stochastic=True)

Bases: Interaction

Births, crowding, saturating predation, and deaths of prey and predators as events of single individuals.

Prey are born at the rate r x and die of crowding at the rate r x^2 / K. Predators kill prey at the Holling type II rate a x y / (1 + a h x), are born at e times that rate, and die at the rate m y. In deterministic mode the rates drive the populations as differential equations.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
prey Annotated[str, RoleSpec()]

The path of the prey population x.

required
predators Annotated[str, RoleSpec()]

The path of the predator population y.

required
r Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The birth rate of the prey.

1.0
K Annotated[float, ParameterSpec(domain=open(0, oo))]

The carrying capacity of the prey.

200.0
a Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The attack rate.

0.02
h Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The handling time.

0.5
e Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The number of predators born per prey eaten.

0.5
m Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The death rate of the predators.

0.3
stochastic bool

Whether births, deaths, and kills are random events.

True

Examples:

>>> from skcomplex.systems.biology.ecology import PredatorPreyEventsInteraction
>>> PredatorPreyEventsInteraction('events', prey='voles', predators='weasels', K=200.0).K
200.0
Source code in src/skcomplex/systems/biology/ecology/_predation.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def __init__(
    self,
    label: str,
    *,
    prey: Annotated[str, RoleSpec()],
    predators: Annotated[str, RoleSpec()],
    r: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    K: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 200.0,
    a: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.02,
    h: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    e: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    m: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.3,
    stochastic: bool = True,
) -> None:
    super().__init__(label)
    self.prey = prey
    self.predators = predators
    self.r = r
    self.K = K
    self.a = a
    self.h = h
    self.e = e
    self.m = m
    self.stochastic = stochastic

PreyElement(label, visual=VisualSpec('agents', {'radius': 0.3}), *, birth=0.2)

Bases: Element

Prey that walks at random and gives birth in cells it does not share with other prey.

In its own activation a prey walks to a random neighbouring cell and then gives birth with the probability birth when no other prey shares the new cell, by member interactions.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'radius': 0.3})
birth Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of giving birth at every step.

0.2

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import PreyElement
>>> GroupElement('rabbits', element=PreyElement, size=200).size
200
Source code in src/skcomplex/systems/biology/ecology/_agent_predation.py
122
123
124
125
126
127
128
129
130
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'radius': 0.3}),
    *,
    birth: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.2,
) -> None:
    super().__init__(label, visual=visual)
    self.birth = birth

QuotaPhytoplanktonElement(label, visual=None, *, Q=1.5, P=1.0, r_inf=1.0, q=1.0, vmax=2.0, g=1.0, R=1.0, d=0.1)

Bases: Element

Phytoplankton that grows on the nutrient stored in its cells, the Droop cell-quota system.

The quota follows dQ/dt = vmax R / (g + R) - r_inf (1 - q / Q) Q, the Michaelis-Menten uptake from the external nutrient R less the dilution by growth, and the biomass dP/dt = r_inf (1 - q / Q) P - d P.

Parameters:

Name Type Description Default
label str

The label of the population.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
Q Annotated[float, StateSpec(domain=open(0, oo))]

The initial cell quota.

1.5
P Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial biomass.

1.0
r_inf Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The growth rate for an infinite quota.

1.0
q Annotated[float, ParameterSpec(domain=open(0, oo))]

The minimum quota, at which growth stops.

1.0
vmax Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The maximum uptake rate.

2.0
g Annotated[float, ParameterSpec(domain=open(0, oo))]

The external nutrient at which the uptake is half its maximum.

1.0
R Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The external nutrient concentration.

1.0
d Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The death rate.

0.1

Examples:

>>> from skcomplex.systems.biology.ecology import QuotaPhytoplanktonElement
>>> QuotaPhytoplanktonElement('algae', R=2.0).R
2.0
Source code in src/skcomplex/systems/biology/ecology/_cell_quota.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    Q: Annotated[float, StateSpec(domain=RealSet.open(0, oo))] = 1.5,
    P: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    r_inf: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    q: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
    vmax: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 2.0,
    g: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
    R: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    d: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
) -> None:
    super().__init__(label, visual=visual)
    self.Q = Q
    self.P = P
    self.r_inf = r_inf
    self.q = q
    self.vmax = vmax
    self.g = g
    self.R = R
    self.d = d

RabbitsElement(label, visual=None, *, pairs=1.0, pairs_lag1=0.0)

Bases: Element

Pairs of rabbits of this month and of last month, the two age classes of Fibonacci's recurrence.

Parameters:

Name Type Description Default
label str

The label of the element.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
pairs Annotated[object, StateSpec(domain=closed_open(0, oo), lags=1, initial=(0.0,))]

The number of pairs this month, a state that keeps its value one month earlier.

1.0
pairs_lag1 float

The number of pairs last month.

0.0

Examples:

>>> from skcomplex.systems.biology.ecology import RabbitsElement
>>> RabbitsElement('rabbits', pairs=3.0).pairs
3.0
Source code in src/skcomplex/systems/biology/ecology/_factories.py
206
207
208
209
210
211
212
213
214
215
216
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    pairs: Annotated[object, StateSpec(domain=RealSet.closed_open(0, oo), lags=1, initial=(0.0,))] = 1.0,
    pairs_lag1: float = 0.0,
) -> None:
    super().__init__(label, visual=visual)
    self.pairs = pairs
    self.pairs_lag1 = pairs_lag1

ResourceElement(label, visual=None, *, R=1.0, w=1.0, r=1.0, K=1.0, kappa=1.0, omega=1.0)

Bases: Element

Resource that consumers take up, either self-renewing with logistic growth or supplied from outside.

A self-renewing resource grows as r R (K - R) / K, and a supplied one flows in at kappa and is washed out at the rate omega. The interaction that couples the resource to its consumers chooses which supply applies.

Parameters:

Name Type Description Default
label str

The label of the resource or of the group of resources.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
R Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial abundance.

1.0
w Annotated[float, ParameterSpec(domain=open(0, oo))]

The energy a unit of the resource carries.

1.0
r Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The growth rate of a self-renewing resource at low abundance.

1.0
K Annotated[float, ParameterSpec(domain=open(0, oo))]

The carrying capacity of a self-renewing resource.

1.0
kappa Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The inflow of a supplied resource.

1.0
omega Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The dilution rate of a supplied resource.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import ResourceElement
>>> ResourceElement('resources', K=4.8).K
4.8
Source code in src/skcomplex/systems/biology/ecology/_consumer_resources.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    R: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    w: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
    r: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    K: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
    kappa: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    omega: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
) -> None:
    super().__init__(label, visual=visual)
    self.R = R
    self.w = w
    self.r = r
    self.K = K
    self.kappa = kappa
    self.omega = omega

ResourceTurnoverInteraction(label, *, consumers, resources, c=((1.0,),), kind='substitutable', n=-10.0, supply='logistic', v=None)

Bases: ConsumptionInteraction

Supply of resources, by logistic renewal or a chemostat, and their depletion by the consumers.

A 'logistic' supply renews resource a at r_a R_a (K_a - R_a) / K_a, and a 'chemostat' supply at kappa_a - omega_a R_a. Substitutable resources lose sum_j c_ja N_j R_a, and essential resources lose sum_j v_ja N_j g_j by the fixed stoichiometry v of the consumers.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
consumers Annotated[str, RoleSpec()]

The path of the group of consumers.

required
resources Annotated[str, RoleSpec()]

The path of the group of resources.

required
c Sequence[Sequence[float]]

The uptake rates, one row per consumer and one column per resource.

((1.0,),)
kind str

'substitutable' or 'essential' resources.

'substitutable'
n float

The exponent of the growth on essential resources, below -1.

-10.0
supply str

'logistic' for self-renewing resources or 'chemostat' for resources supplied from outside.

'logistic'
v Sequence[Sequence[float]] | None

The stoichiometry of essential resources in the consumers, one row per consumer, or None for c.

None

Raises:

Type Description
ValidationError

The supply or the kind is unknown, or the exponent of essential resources is not below -1.

Examples:

>>> from skcomplex.systems.biology.ecology import ResourceTurnoverInteraction
>>> ResourceTurnoverInteraction('turnover', consumers='consumers', resources='resources').supply
'logistic'
Source code in src/skcomplex/systems/biology/ecology/_consumer_resources.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def __init__(
    self,
    label: str,
    *,
    consumers: Annotated[str, RoleSpec()],
    resources: Annotated[str, RoleSpec()],
    c: Sequence[Sequence[float]] = ((1.0,),),
    kind: str = 'substitutable',
    n: float = -10.0,
    supply: str = 'logistic',
    v: Sequence[Sequence[float]] | None = None,
) -> None:
    super().__init__(label, consumers=consumers, resources=resources, c=c, kind=kind, n=n)
    self.supply = supply
    self.v = v

RickerGrowthInteraction(label, *, target, r=2.0)

Bases: Interaction

Ricker growth of a population in discrete generations, n' = r n exp(-n), overcompensating at high density.

The size n is in units of the density at which the offspring of a generation peak, so a crowded generation leaves fewer offspring than a sparser one.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Annotated[str, RoleSpec()]

The path of the population.

required
r Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The growth factor at low density.

2.0

Examples:

>>> from skcomplex.systems.biology.ecology import RickerGrowthInteraction
>>> RickerGrowthInteraction('growth', target='fish', r=12.0).r
12.0
Source code in src/skcomplex/systems/biology/ecology/_factories.py
241
242
243
244
245
246
247
248
249
250
def __init__(
    self,
    label: str,
    *,
    target: Annotated[str, RoleSpec()],
    r: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 2.0,
) -> None:
    super().__init__(label)
    self.target = target
    self.r = r

RosenzweigMacArthurInteraction(label, *, prey, predators, kappa=0.01, eta=0.8, phi=0.1, phi_end=0.2, rate=0.0)

Bases: Interaction

Rosenzweig-MacArthur predation of fast prey by slow predators, whose prey crowding grows at a constant rate.

In units of the predators' time scale, kappa dx/dt = x (1 - phi x) - x y / (1 + eta x) and dy/dt = x y / (1 + eta x) - y. The crowding phi, the inverse of the prey's carrying capacity, rises at the rate rate from phi to phi_end and stays there.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
prey Annotated[str, RoleSpec()]

The path of the prey population x.

required
predators Annotated[str, RoleSpec()]

The path of the predator population y.

required
kappa Annotated[float, ParameterSpec(domain=open(0, oo))]

The ratio of the time scales of the prey and the predators.

0.01
eta Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The handling time of the predators.

0.8
phi Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The initial crowding of the prey.

0.1
phi_end Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The final crowding of the prey.

0.2
rate Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The rate at which the crowding rises.

0.0

Examples:

>>> from skcomplex.systems.biology.ecology import RosenzweigMacArthurInteraction
>>> RosenzweigMacArthurInteraction('predation', prey='prey', predators='predators', rate=0.01).rate
0.01
Source code in src/skcomplex/systems/biology/ecology/_predation.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def __init__(
    self,
    label: str,
    *,
    prey: Annotated[str, RoleSpec()],
    predators: Annotated[str, RoleSpec()],
    kappa: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.01,
    eta: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.8,
    phi: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    phi_end: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.2,
    rate: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
) -> None:
    super().__init__(label)
    self.prey = prey
    self.predators = predators
    self.kappa = kappa
    self.eta = eta
    self.phi = phi
    self.phi_end = phi_end
    self.rate = rate

SeasonalLogisticGrowthInteraction(label, *, target, r=1.0, K=100.0, amplitude=0.5, period=1.0)

Bases: LogisticGrowthInteraction

Logistic growth under a carrying capacity that varies periodically, K(t) = K (1 + amplitude sin(2 pi t / T)).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Annotated[str, RoleSpec()]

The path of the population.

required
r Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The per capita growth rate at low density.

1.0
K Annotated[float, ParameterSpec(domain=open(0, oo))]

The mean carrying capacity.

100.0
amplitude Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The relative amplitude of the variation of the capacity, below 1.

0.5
period Annotated[float, ParameterSpec(domain=open(0, oo))]

The period T of the variation.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import SeasonalLogisticGrowthInteraction
>>> SeasonalLogisticGrowthInteraction('growth', target='rabbits', period=12.0).period
12.0
Source code in src/skcomplex/systems/biology/ecology/_factories.py
295
296
297
298
299
300
301
302
303
304
305
306
307
def __init__(
    self,
    label: str,
    *,
    target: Annotated[str, RoleSpec()],
    r: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    K: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 100.0,
    amplitude: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    period: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
) -> None:
    super().__init__(label, target=target, r=r, K=K)
    self.amplitude = amplitude
    self.period = period

SheepElement(label, visual=VisualSpec('agents', {'radius': 0.3}), *, energy=8.0, gain=4.0, reproduction=0.04)

Bases: Element

Sheep that wanders, eats grown grass, reproduces, and dies without energy.

In its own activation, a sheep wanders to a neighbouring cell at a cost of one unit of energy, eats the grown grass of its cell, and dies below zero energy or gives birth with probability reproduction, splitting its energy with the lamb, by member interactions.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'radius': 0.3})
energy Annotated[float, StateSpec()]

The initial energy.

8.0
gain Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The energy a sheep gains from grown grass.

4.0
reproduction Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of reproducing at every step.

0.04

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import SheepElement
>>> GroupElement('sheep', element=SheepElement, size=100).size
100
Source code in src/skcomplex/systems/biology/ecology/_wolf_sheep.py
159
160
161
162
163
164
165
166
167
168
169
170
171
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'radius': 0.3}),
    *,
    energy: Annotated[float, StateSpec()] = 8.0,
    gain: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 4.0,
    reproduction: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.04,
) -> None:
    super().__init__(label, visual=visual)
    self.energy = energy
    self.gain = gain
    self.reproduction = reproduction

ShrimpElement(label, visual=None, *, gut=0.5, biomass=1.0, gonads=0.0001, length=0.0, ration=2.5, k=0.12, assimilation=0.8, respiration=0.05, phi=5.0, gsi=0.05, egg_weight=2e-06, L_inf=29.9, K=0.013)

Bases: Element

Penaeid shrimp, an individual whose gut, biomass, gonads, and length grow on food at the water temperature.

The shrimp ingests I = R_max (1 - exp(-k F)) of the food F, with the maximum ration R_max the product of a table of its biomass, a table of the water temperature, and the factor ration. Its gut content G follows dG/dt = I - A_e G, and its total biomass dB/dt = A_e G - M - S, with the respiration M = a exp(0.07 T) (phi B)^0.185 B and the spawning S = 9.3 L^2.8 E_w of eggs of weight E_w. Its gonads grow as dB_g/dt = GSI B, and its carapace length follows von Bertalanffy, dL/dt = K (L_inf - L). The food and the water temperature are the yearly series of the source, interpolated linearly in days.

Parameters:

Name Type Description Default
label str

The label of the shrimp.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
gut Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial gut content, in grams of dry weight.

0.5
biomass Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial total biomass, in grams of dry weight.

1.0
gonads Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial reproductive biomass, in grams of dry weight.

0.0001
length Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial carapace length, in millimetres.

0.0
ration Annotated[float, ParameterSpec(domain=open(0, oo))]

The factor of the maximum ration.

2.5
k Annotated[float, ParameterSpec(domain=open(0, oo))]

The consumption efficiency, per milligram of dry weight per square metre.

0.12
assimilation Annotated[float, ParameterSpec(domain=open(0, oo))]

The assimilation efficiency of the gut content, per day.

0.8
respiration Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The coefficient of the weight-specific respiration, per day.

0.05
phi Annotated[float, ParameterSpec(domain=open(0, oo))]

The conversion factor from dry to fresh weight.

5.0
gsi Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The gonadosomatic index, the growth of the gonads per unit biomass per day.

0.05
egg_weight Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The dry weight of one egg, in grams.

2e-06
L_inf Annotated[float, ParameterSpec(domain=open(0, oo))]

The asymptotic carapace length, in millimetres.

29.9
K Annotated[float, ParameterSpec(domain=open(0, oo))]

The growth coefficient of the length, per day.

0.013

Examples:

>>> from skcomplex.systems.biology.ecology import ShrimpElement
>>> ShrimpElement('shrimp').L_inf
29.9
Source code in src/skcomplex/systems/biology/ecology/_factories.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    gut: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    biomass: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    gonads: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0001,
    length: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    ration: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 2.5,
    k: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.12,
    assimilation: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.8,
    respiration: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.05,
    phi: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 5.0,
    gsi: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.05,
    egg_weight: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 2.0e-6,
    L_inf: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 29.9,
    K: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.013,
) -> None:
    super().__init__(label, visual=visual)
    self.gut = gut
    self.biomass = biomass
    self.gonads = gonads
    self.length = length
    self.ration = ration
    self.k = k
    self.assimilation = assimilation
    self.respiration = respiration
    self.phi = phi
    self.gsi = gsi
    self.egg_weight = egg_weight
    self.L_inf = L_inf
    self.K = K

StandElement(label, visual=None, *, volume=0.0, mature=100.0)

Bases: Element

Stand of trees of one successional group, measured by its stem volume.

Parameters:

Name Type Description Default
label str

The label of the stand.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
volume Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial stem volume.

0.0
mature Annotated[float, ParameterSpec(domain=open(0, oo))]

The stem volume of the group in a mature forest.

100.0

Examples:

>>> from skcomplex.systems.biology.ecology import StandElement
>>> StandElement('keora', mature=196.11).mature
196.11
Source code in src/skcomplex/systems/biology/ecology/_succession.py
43
44
45
46
47
48
49
50
51
52
53
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    volume: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    mature: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 100.0,
) -> None:
    super().__init__(label, visual=visual)
    self.volume = volume
    self.mature = mature

StigmergicPredatorElement(label, visual=VisualSpec('agents', {'color_by': 'distress', 'radius': 0.45}), *, age=0.0, hunger=0.0, happiness=0.0, distress=0.0, experience=0.0, maturity=5.0, reproduction=0.3, starvation=10.0, memory=0.3, communication=0.1, emotions=1.0)

Bases: ForagerElement

Predator that eats prey and grows angry with hunger.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'color_by': 'distress', 'radius': 0.45})
age float

The steps since the animal last bred.

0.0
hunger float

The steps since the animal last ate.

0.0
happiness float

The happiness, which eating raises.

0.0
distress float

The anger, which hunger raises.

0.0
experience float

The distress the animal experienced in the step, before it moved.

0.0
maturity float

The age at which the animal can breed.

5.0
reproduction float

The probability of breeding at maturity without emotions.

0.3
starvation float

The hunger at which the animal dies.

10.0
memory float

The share of its previous emotion that an animal keeps.

0.3
communication float

The weight of the emotions marked around the animal.

0.1
emotions float

Whether emotions guide the animal, 1 or 0.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import StigmergicPredatorElement
>>> StigmergicPredatorElement.food
'prey'
Source code in src/skcomplex/systems/biology/ecology/_stigmergy.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'color_by': 'distress', 'radius': 0.45}),
    *,
    age: float = 0.0,
    hunger: float = 0.0,
    happiness: float = 0.0,
    distress: float = 0.0,
    experience: float = 0.0,
    maturity: float = 5.0,
    reproduction: float = 0.3,
    starvation: float = 10.0,
    memory: float = 0.3,
    communication: float = 0.1,
    emotions: float = 1.0,
) -> None:
    super().__init__(
        label,
        visual=visual,
        age=age,
        hunger=hunger,
        happiness=happiness,
        distress=distress,
        experience=experience,
        maturity=maturity,
        reproduction=reproduction,
        starvation=starvation,
        memory=memory,
        communication=communication,
        emotions=emotions,
    )

StigmergicPreyElement(label, visual=VisualSpec('agents', {'color_by': 'happiness', 'radius': 0.35}), *, age=0.0, hunger=0.0, happiness=0.0, distress=0.0, experience=0.0, maturity=5.0, reproduction=0.3, starvation=10.0, memory=0.3, communication=0.1, emotions=1.0)

Bases: ForagerElement

Prey that eats plants and fears the predators around it.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
age Annotated[float, StateSpec(domain=closed_open(0, oo))]

The steps since the animal last bred.

0.0
hunger Annotated[float, StateSpec(domain=closed_open(0, oo))]

The steps since the animal last ate.

0.0
happiness Annotated[float, StateSpec(domain=closed_open(0, oo))]

The happiness, which eating raises.

0.0
distress Annotated[float, StateSpec(domain=closed_open(0, oo))]

The fear, which predators around it raise.

0.0
experience Annotated[float, StateSpec(domain=closed_open(0, oo))]

The distress the animal experienced in the step, before it moved.

0.0
maturity Annotated[float, ParameterSpec(domain=open(0, oo))]

The age at which the animal can breed.

5.0
reproduction Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of breeding at maturity without emotions.

0.3
starvation Annotated[float, ParameterSpec(domain=open(0, oo))]

The hunger at which the animal dies.

10.0
memory Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The share of its previous emotion that an animal keeps.

0.3
communication Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The weight of the emotions marked around the animal.

0.1
emotions Annotated[float, ParameterSpec(domain=FiniteEnumeratedSet([0, 1]))]

Whether emotions guide the animal, 1 or 0.

1.0

Examples:

>>> from skcomplex.systems.biology.ecology import StigmergicPreyElement
>>> StigmergicPreyElement.food
'plants'
Source code in src/skcomplex/systems/biology/ecology/_stigmergy.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'color_by': 'happiness', 'radius': 0.35}),
    *,
    age: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    hunger: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    happiness: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    distress: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    experience: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    maturity: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 5.0,
    reproduction: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.3,
    starvation: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 10.0,
    memory: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.3,
    communication: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    emotions: Annotated[float, ParameterSpec(domain=FiniteEnumeratedSet([0, 1]))] = 1.0,
) -> None:
    super().__init__(label, visual=visual)
    self.age = age
    self.hunger = hunger
    self.happiness = happiness
    self.distress = distress
    self.experience = experience
    self.maturity = maturity
    self.reproduction = reproduction
    self.starvation = starvation
    self.memory = memory
    self.communication = communication
    self.emotions = emotions

SuccessionalGrowthInteraction(label, *, target, first, second, g=0.05, w_first=0.5, w_second=0.5, seedlings=0.01)

Bases: RateInteraction

Logistic growth of intermediate or climax trees, crowded by their own group and another, with seedling input.

The rate is dV/dt = a + g V (1 - w_1 V_1 / V_mat,1 - w_2 V_2 / V_mat,2), with weights normalized to sum to one. One of the two crowding stands is usually the target itself.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Annotated[str, RoleSpec()]

The path of the growing stand.

required
first Annotated[str, RoleSpec()]

The path of the first crowding stand.

required
second Annotated[str, RoleSpec()]

The path of the second crowding stand.

required
g Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The specific growth rate.

0.05
w_first Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The weight of the first crowding stand.

0.5
w_second Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The weight of the second crowding stand.

0.5
seedlings Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The constant input a of seedlings that averts extinction.

0.01

Examples:

>>> from skcomplex.systems.biology.ecology import SuccessionalGrowthInteraction
>>> SuccessionalGrowthInteraction('growth', target='gewa', first='gewa', second='sundari', g=0.1).g
0.1
Source code in src/skcomplex/systems/biology/ecology/_succession.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def __init__(
    self,
    label: str,
    *,
    target: Annotated[str, RoleSpec()],
    first: Annotated[str, RoleSpec()],
    second: Annotated[str, RoleSpec()],
    g: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.05,
    w_first: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    w_second: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.5,
    seedlings: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
) -> None:
    super().__init__(label, target=target, state='volume')
    self.first = first
    self.second = second
    self.g = g
    self.w_first = w_first
    self.w_second = w_second
    self.seedlings = seedlings

TripletInteraction(label, *, target, a=0.0, state='x')

Bases: RateInteraction

Interactions of every species with the pairs of other species, dx_i/dt += x_i sum_(j<k) a_ijk x_j x_k.

The coefficient a_ijk is the effect of the combination of the species j and k on the growth of the species i (Sidhom and Galla 2024, Eq. 2). The tensor holds it for both orders of the pair, a_ijk = a_ikj, so the sum over the sets j < k is half the contraction of the tensor with the abundances, and it holds 0 where indices coincide.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Annotated[str, RoleSpec()]

The path of the group of species.

required
a Annotated[object, ParameterSpec(shape=(target, target, target))]

The coupling tensor of order 3, with one index per species, or a number for every entry.

0.0
state str

The name of the state that holds the abundance of a species.

'x'

Examples:

>>> from skcomplex.systems.biology.ecology import TripletInteraction
>>> TripletInteraction('triplets', target='species', a=0.0, state='n').state
'n'
Source code in src/skcomplex/systems/biology/ecology/_higher_order.py
50
51
52
53
54
55
56
57
58
59
def __init__(
    self,
    label: str,
    *,
    target: Annotated[str, RoleSpec()],
    a: Annotated[object, ParameterSpec(shape=('target', 'target', 'target'))] = 0.0,
    state: str = 'x',
) -> None:
    super().__init__(label, target=target, state=state, rate=self._triplets)
    self.a = a

UnstablePopulationsElement(label, visual=None, *, x=1.1, y=0.0, eta=0.1, mean=1.0, alpha=0.01, beta=0.01, nu=0.01, p=0.001, sigma=0.01)

Bases: Element

Resident population x and invading population y, after equations (13.3) and (13.4) of Jensen.

The maps of intrinsic_instability step both sizes. At every step x ← [x - eta (x - X)] exp(-alpha y) + √x sigma chi, an Ornstein-Uhlenbeck step damped by the invader. With probability p a mutation from x adds nu x to y, and otherwise y ← y (1 + beta) + √y sigma chi'. The noises chi and chi' are independent standard normal values, scaled by the square root of the population sizes as in birth and death processes, and both sizes are cut at 0.

Parameters:

Name Type Description Default
label str

The label of the populations.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

None
x Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial resident population.

1.1
y Annotated[float, StateSpec(domain=closed_open(0, oo))]

The initial invading population.

0.0
eta Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The restoring rate eta of the resident population.

0.1
mean Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The level X the resident population returns to.

1.0
alpha Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The suppression alpha of the resident population by the invader.

0.01
beta Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The growth rate beta of the invader.

0.01
nu Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The share nu of the resident population that a mutation moves to the invader.

0.01
p Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of a mutation per step.

0.001
sigma Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The amplitude sigma of the noise.

0.01

Examples:

>>> from skcomplex.systems.biology.ecology import UnstablePopulationsElement
>>> UnstablePopulationsElement('populations').p
0.001
Source code in src/skcomplex/systems/biology/ecology/_instability.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = None,
    *,
    x: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 1.1,
    y: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
    eta: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.1,
    mean: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
    alpha: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
    beta: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
    nu: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
    p: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.001,
    sigma: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
) -> None:
    super().__init__(label, visual=visual)
    self.x = x
    self.y = y
    self.eta = eta
    self.mean = mean
    self.alpha = alpha
    self.beta = beta
    self.nu = nu
    self.p = p
    self.sigma = sigma

WolfElement(label, visual=VisualSpec('agents', {'radius': 0.35}), *, energy=20.0, gain=20.0, reproduction=0.05)

Bases: Element

Wolf that wanders, eats a sheep of its cell, reproduces, and dies without energy.

In its own activation, a wolf wanders to a neighbouring cell at a cost of one unit of energy, eats and removes one random sheep of its cell, and dies below zero energy or gives birth with probability reproduction, by member interactions.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
visual VisualSpec | None

How the element is drawn, or None for default_visual_.

VisualSpec('agents', {'radius': 0.35})
energy Annotated[float, StateSpec()]

The initial energy.

20.0
gain Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The energy a wolf gains from a sheep.

20.0
reproduction Annotated[float, ParameterSpec(domain=closed_open(0, oo))]

The probability of reproducing at every step.

0.05

Examples:

>>> from skcomplex.core.components.elements import GroupElement
>>> from skcomplex.systems.biology.ecology import WolfElement
>>> GroupElement('wolves', element=WolfElement, size=25).size
25
Source code in src/skcomplex/systems/biology/ecology/_wolf_sheep.py
220
221
222
223
224
225
226
227
228
229
230
231
232
def __init__(
    self,
    label: str,
    visual: VisualSpec | None = VisualSpec('agents', {'radius': 0.35}),
    *,
    energy: Annotated[float, StateSpec()] = 20.0,
    gain: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 20.0,
    reproduction: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.05,
) -> None:
    super().__init__(label, visual=visual)
    self.energy = energy
    self.gain = gain
    self.reproduction = reproduction

agent_based_lotka_volterra(width=30, height=30, *, prey=300, predators=60, birth=0.2, conversion=0.5, death=0.1, random_state=0)

Return prey and predators that walk on a grid, whose numbers cycle like the Lotka-Volterra equations.

Prey give birth only in cells they do not share with other prey, which limits their density, and predators eat prey they meet and breed after a meal. Demographic noise makes the cycles irregular and can end them by extinction.

Parameters:

Name Type Description Default
width int

The number of columns of the torus.

30
height int

The number of rows of the torus.

30
prey int

The initial number of prey.

300
predators int

The initial number of predators.

60
birth float

The probability that a prey gives birth at every step.

0.2
conversion float

The probability that a predator breeds after eating a prey.

0.5
death float

The probability that a predator dies at every step.

0.1
random_state int | Generator | None

The seed or generator of the initial cells.

0

Returns:

Name Type Description
system System

The system, with the groups prey and predators.

Examples:

>>> from skcomplex.systems.biology.ecology import agent_based_lotka_volterra
>>> [group.size for group in agent_based_lotka_volterra(10, 10, prey=50, predators=5).elements]
[50, 5]
Source code in src/skcomplex/systems/biology/ecology/_agent_predation.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
@register_system(
    field='biology/ecology',
    tags=('predator-prey', 'agents', 'grid', 'oscillation'),
    references=('Argun et al. 2021', 'Lotka 1925', 'Volterra 1926'),
    defaults={'until': 200},
)
def agent_based_lotka_volterra(
    width: int = 30,
    height: int = 30,
    *,
    prey: int = 300,
    predators: int = 60,
    birth: float = 0.2,
    conversion: float = 0.5,
    death: float = 0.1,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return prey and predators that walk on a grid, whose numbers cycle like the Lotka-Volterra equations.

    Prey give birth only in cells they do not share with other prey, which limits their density, and predators eat
    prey they meet and breed after a meal. Demographic noise makes the cycles irregular and can end them by extinction.

    Args:
        width:
            The number of columns of the torus.

        height:
            The number of rows of the torus.

        prey:
            The initial number of prey.

        predators:
            The initial number of predators.

        birth:
            The probability that a prey gives birth at every step.

        conversion:
            The probability that a predator breeds after eating a prey.

        death:
            The probability that a predator dies at every step.

        random_state:
            The seed or generator of the initial cells.

    Returns:
        system:
            The system, with the groups `prey` and `predators`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import agent_based_lotka_volterra
        >>> [group.size for group in agent_based_lotka_volterra(10, 10, prey=50, predators=5).elements]
        [50, 5]
    """
    rng = np.random.default_rng(random_state)
    cells = rng.integers(0, [width, height], size=(prey + predators, 2))
    locations = [tuple(int(item) for item in cell) for cell in cells]
    return System(
        elements=[
            GroupElement(
                'prey',
                element=PreyElement,
                size=prey,
                values={'birth': birth},
                variable=True,
                location=locations[:prey],
            ),
            GroupElement(
                'predators',
                element=PredatorElement,
                size=predators,
                values={'conversion': conversion, 'death': death},
                variable=True,
                location=locations[prey:],
            ),
        ],
        interactions=[*_get_prey('prey'), *_get_predators('predators', 'prey')],
        space=LatticeSpace((width, height), boundary='periodic'),
    )

comets(shape=(50, 50), *, box=0.02, inoculum=3e-07, glucose=5.0, plate_glucose=0.0088, biomass_diffusion=3e-10, glucose_diffusion=5e-06, vmax=10.0, km=0.01, interval=STEP)

Return an expanding colony of the E. coli core system on a lattice, which needs the extra metabolism.

Run with IMEXEulerSolver, every step is a growth step and then a diffusion step, the two steps that COMETS alternates (Raman 2021, Section 11.1.3.4). The growth step solves the program of every site that holds biomass and applies the update rules of Harcombe et al. (2014). The diffusion step solves one implicit Euler system, where Harcombe et al. use an alternating direction implicit scheme. Biomass and glucose both diffuse, as in Harcombe et al., while the short description of Raman names metabolites only.

The states are gDW per L and mM of the medium under a box. A site whose program has no solution has zero fluxes, which happens when its glucose cannot pay for the maintenance flux of the network.

Harcombe et al. in what follows is the main text of Harcombe et al. (2014), and the source of each default is named under its argument. The time step of 0.1 h of the registered run is from its In silico experiments. The length of the registered run keeps it within the budget of the gallery and has no source.

These choices have no source in that text. The periodic edges are those of LatticeSpace, since the text does not state the outer boundary. The volume under a box is the amount of glucose under it over the concentration of the medium, since the text defers the volume to its supplement, which was not read. The molar mass of glucose is 180.16 g/mol.

The network is the E. coli core system, where Harcombe et al. use iJO1366. The death rate of 1% per step, the largest colony height of 200 um, and the oxygen of 0.25 mmol/cm^2 of Harcombe et al. are left out, so the biomass of a box has no upper limit and oxygen is limited only by the network.

Parameters:

Name Type Description Default
shape tuple[int, int]

The number of boxes along each side, by default from Harcombe et al., Colony expansion comparisons.

(50, 50)
box float

The side of a box in cm, by default from Harcombe et al., Colony expansion comparisons.

0.02
inoculum float

The initial biomass of the central box in g, by default from Harcombe et al., Colony expansion comparisons.

3e-07
glucose float

The glucose of the medium in g/L, by default from Harcombe et al., In silico experiments.

5.0
plate_glucose float

The glucose of the medium per area of the plate in mmol/cm^2, by default from Harcombe et al., In silico experiments.

0.0088
biomass_diffusion float

The diffusion coefficient of the biomass in cm^2/s, by default the value for colonies from Harcombe et al., Table 1.

3e-10
glucose_diffusion float

The diffusion coefficient of the glucose in cm^2/s, by default from Harcombe et al., Table 1.

5e-06
vmax float

The largest glucose uptake in mmol/g/h, by default from Harcombe et al., Table 1.

10.0
km float

The half-saturation concentration of glucose in mM, by default from Harcombe et al., Table 1.

0.01
interval float

The time in h over which the glucose of a site must last, by default the time step, the bound of Raman (2021, Section 9.6).

STEP

Returns:

Name Type Description
system System

The system.

Raises:

Type Description
MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.systems.biology.ecology import comets
>>> [element.label for element in comets(shape=(2, 2)).elements]
['cells', 'biomass', 'glucose']
Source code in src/skcomplex/systems/biology/ecology/_comets.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
@register_system(
    field='biology/ecology',
    tags=('COMETS', 'dynamic flux balance', 'lattice', 'diffusion', 'linear program', 'metabolism'),
    references=('Raman 2021', 'Harcombe et al. 2014'),
    defaults={'until': 14.0, 'dt': STEP, 'solver': IMEXEulerSolver(dt=STEP)},
)
def comets(
    shape: tuple[int, int] = (50, 50),
    *,
    box: float = 0.02,
    inoculum: float = 3e-7,
    glucose: float = 5.0,
    plate_glucose: float = 0.0088,
    biomass_diffusion: float = 3e-10,
    glucose_diffusion: float = 5e-6,
    vmax: float = 10.0,
    km: float = 0.01,
    interval: float = STEP,
) -> System:
    """Return an expanding colony of the E. coli core system on a lattice, which needs the extra `metabolism`.

    Run with `IMEXEulerSolver`, every step is a growth step and then a diffusion step, the two steps that COMETS
    alternates (Raman 2021, Section 11.1.3.4). The growth step solves the program of every site that holds biomass and
    applies the update rules of Harcombe et al. (2014). The diffusion step solves one implicit Euler system, where
    Harcombe et al. use an alternating direction implicit scheme. Biomass and glucose both diffuse, as in Harcombe et
    al., while the short description of Raman names metabolites only.

    The states are gDW per L and mM of the medium under a box. A site whose program has no solution has zero fluxes,
    which happens when its glucose cannot pay for the maintenance flux of the network.

    Harcombe et al. in what follows is the main text of Harcombe et al. (2014), and the source of each default is named
    under its argument. The time step of 0.1 h of the registered run is from its In silico experiments. The length of
    the registered run keeps it within the budget of the gallery and has no source.

    These choices have no source in that text. The periodic edges are those of `LatticeSpace`, since the text does not
    state the outer boundary. The volume under a box is the amount of glucose under it over the concentration of the
    medium, since the text defers the volume to its supplement, which was not read. The molar mass of glucose is 180.16
    g/mol.

    The network is the E. coli core system, where Harcombe et al. use iJO1366. The death rate of 1% per step, the
    largest colony height of 200 um, and the oxygen of 0.25 mmol/cm^2 of Harcombe et al. are left out, so the biomass of
    a box has no upper limit and oxygen is limited only by the network.

    Args:
        shape:
            The number of boxes along each side, by default from Harcombe et al., Colony expansion comparisons.

        box:
            The side of a box in cm, by default from Harcombe et al., Colony expansion comparisons.

        inoculum:
            The initial biomass of the central box in g, by default from Harcombe et al., Colony expansion comparisons.

        glucose:
            The glucose of the medium in g/L, by default from Harcombe et al., In silico experiments.

        plate_glucose:
            The glucose of the medium per area of the plate in mmol/cm^2, by default from Harcombe et al., In silico
            experiments.

        biomass_diffusion:
            The diffusion coefficient of the biomass in cm^2/s, by default the value for colonies from Harcombe et al.,
            Table 1.

        glucose_diffusion:
            The diffusion coefficient of the glucose in cm^2/s, by default from Harcombe et al., Table 1.

        vmax:
            The largest glucose uptake in mmol/g/h, by default from Harcombe et al., Table 1.

        km:
            The half-saturation concentration of glucose in mM, by default from Harcombe et al., Table 1.

        interval:
            The time in h over which the glucose of a site must last, by default the time step, the bound of Raman
            (2021, Section 9.6).

    Returns:
        system:
            The system.

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.systems.biology.ecology import comets
        >>> [element.label for element in comets(shape=(2, 2)).elements]
        ['cells', 'biomass', 'glucose']
    """
    source = load_network('textbook', 'cell', needed_by='comets')
    plain = {name: replace(spec, rule='') for name, spec in source.reactions.items()}
    concentration = glucose / GLUCOSE_MOLAR_MASS * MMOL_PER_MOL
    volume = plate_glucose * box**2 / concentration
    initial = np.zeros(shape)
    initial[shape[0] // 2, shape[1] // 2] = inoculum / volume
    space = LatticeSpace(shape, spacing=box)
    images = VisualSpec('image', {'states': [MetabolicNetworkElement.flux_name(GROWTH)]})
    cells = {
        'name': 'ColonyCell',
        'reactions': plain,
        'default_objective': source.default_objective,
        'infeasible': 'zero',
    }
    return System(
        elements=[
            GroupElement(
                'cells',
                element=MetabolicNetworkElement,
                values=cells,
                on='sites',
                space=space,
                visual=images,
            ),
            FieldElement('biomass', element=BiomassElement, space=space, values={'x': initial}),
            FieldElement(
                'glucose',
                element=SubstrateElement,
                space=space,
                values={'c': np.full(shape, concentration)},
            ),
        ],
        interactions=[
            ExchangeInteraction(
                'uptake',
                cell='cells',
                biomass='biomass',
                substrate='glucose',
                reaction=GLUCOSE_EXCHANGE,
                vmax=vmax,
                km=km,
                interval=interval,
                threshold=0.0,
            ),
            GrowthInteraction('growth', cell='cells', biomass='biomass', reaction=GROWTH),
            DiffusionInteraction(
                'biomass_spread',
                target='biomass',
                state='x',
                coefficient=biomass_diffusion * SECONDS_PER_HOUR,
            ),
            DiffusionInteraction(
                'glucose_spread',
                target='glucose',
                state='c',
                coefficient=glucose_diffusion * SECONDS_PER_HOUR,
            ),
        ],
        space=space,
    )

community_fba(knockouts=('ICDHyr', 'NH4t'), *, abundances=(0.5, 0.5), exchanges=None, common_rate=False)

Return two members of the E. coli core system that share a medium, which needs the extra metabolism.

The programs of the members merge through a medium whose law holds the growth weighted by the abundances (Raman 2021, Section 11.1.3). By default one member lacks isocitrate dehydrogenase and takes up 2-oxoglutarate, and the other lacks ammonium transport and takes up glutamate, each from what the other secretes, so neither grows alone, and together both grow. CommunityAnalysis gives SteadyCom and the cooperative trade-off of the same members. The pair is an illustration found on the E. coli core system: the consortium of Raman (Section 11.1.3.6) has four mutants that need amino acids, whose synthesis the core system does not hold.

Parameters:

Name Type Description Default
knockouts Sequence[str]

The reaction to close in each member, or the empty string for none.

('ICDHyr', 'NH4t')
abundances Sequence[float]

The abundance of each member.

(0.5, 0.5)
exchanges Mapping[str, float] | None

The lower bound of the net exchange of the community, by reaction, or None for no net uptake of the cross-fed metabolites.

None
common_rate bool

Whether the members grow at one specific rate, as in community FBA, rather than each at its own, as in joint FBA.

False

Returns:

Name Type Description
system System

The system.

Raises:

Type Description
MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.core.engine.runtime import Simulation
>>> from skcomplex.systems.biology.ecology import community_fba
>>> trajectory = Simulation(community_fba()).prepare().run(0.0).trajectory_
>>> round(float(trajectory.values('medium.objective_0')[0]), 3)
0.862
Source code in src/skcomplex/systems/biology/ecology/_community_fba.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@register_system(
    field='biology/ecology',
    tags=('community flux balance', 'SteadyCom', 'cross-feeding', 'linear program', 'metabolism', 'static'),
    references=('Raman 2021', 'Khandelwal et al. 2013', 'Chan et al. 2017', 'Diener et al. 2020'),
    defaults={'until': 0.0},
)
def community_fba(
    knockouts: Sequence[str] = ('ICDHyr', 'NH4t'),
    *,
    abundances: Sequence[float] = (0.5, 0.5),
    exchanges: Mapping[str, float] | None = None,
    common_rate: bool = False,
) -> System:
    """Return two members of the E. coli core system that share a medium, which needs the extra `metabolism`.

    The programs of the members merge through a medium whose law holds the growth weighted by the abundances (Raman
    2021, Section 11.1.3). By default one member lacks isocitrate dehydrogenase and takes up 2-oxoglutarate, and the
    other lacks ammonium transport and takes up glutamate, each from what the other secretes, so neither grows alone,
    and together both grow. `CommunityAnalysis` gives SteadyCom and the cooperative trade-off of the same members. The
    pair is an illustration found on the E. coli core system: the consortium of Raman (Section 11.1.3.6) has four
    mutants that need amino acids, whose synthesis the core system does not hold.

    Args:
        knockouts:
            The reaction to close in each member, or the empty string for none.

        abundances:
            The abundance of each member.

        exchanges:
            The lower bound of the net exchange of the community, by reaction, or `None` for no net uptake of the
            cross-fed metabolites.

        common_rate:
            Whether the members grow at one specific rate, as in community FBA, rather than each at its own, as in joint
            FBA.

    Returns:
        system:
            The system.

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.core.engine.runtime import Simulation
        >>> from skcomplex.systems.biology.ecology import community_fba
        >>> trajectory = Simulation(community_fba()).prepare().run(0.0).trajectory_
        >>> round(float(trajectory.values('medium.objective_0')[0]), 3)
        0.862
    """
    shared = dict(exchanges) if exchanges is not None else dict.fromkeys(CROSS_FED, 0.0)
    members = []
    for position, knockout in enumerate(knockouts):
        member = load_network('textbook', f'member_{position}', needed_by='community_fba')
        member.objective = {}
        for reaction in shared:
            if shared[reaction] >= 0:
                member.set_params(**{f'lower_{member._identifier(reaction)}': OPEN_UPTAKE})
        if knockout:
            identifier = member._identifier(knockout)
            member.set_params(**{f'lower_{identifier}': 0.0, f'upper_{identifier}': 0.0})
        members.append(member)
    return System(
        elements=[*members, community_medium_type(list(shared))('medium')],
        interactions=[
            CommunityInteraction(
                'joint',
                members=[member.label for member in members],
                medium='medium',
                abundances=tuple(abundances),
                exchanges=shared,
                growth=GROWTH,
                common_rate=common_rate,
            ),
        ],
        time=StaticTime(),
    )

competition(first=10.0, second=10.0, *, r1=1.0, r2=0.8, K1=100.0, K2=80.0, alpha12=0.5, alpha21=0.6)

Return two species that compete for the same resources, which coexist or exclude each other.

The species coexist at n1 = (K1 - alpha12 K2) / (1 - alpha12 alpha21) and n2 = (K2 - alpha21 K1) / (1 - alpha12 alpha21) when both are positive and alpha12 alpha21 < 1. Otherwise one species excludes the other.

Parameters:

Name Type Description Default
first float

The initial size of the first population.

10.0
second float

The initial size of the second population.

10.0
r1 float

The growth rate of the first population.

1.0
r2 float

The growth rate of the second population.

0.8
K1 float

The carrying capacity of the first population.

100.0
K2 float

The carrying capacity of the second population.

80.0
alpha12 float

The effect of one member of the second population on the first, relative to one of its own.

0.5
alpha21 float

The effect of one member of the first population on the second, relative to one of its own.

0.6

Returns:

Name Type Description
system System

The system, with the populations first and second.

Examples:

>>> from skcomplex.systems.biology.ecology import competition
>>> competition(alpha12=0.2).interactions[0].alpha12
0.2
Source code in src/skcomplex/systems/biology/ecology/_communities.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
@register_system(
    field='biology/ecology',
    tags=('competition', 'ode', 'exclusion'),
    references=('Lotka 1925', 'Volterra 1926', 'Argun et al. 2021'),
    defaults={'until': 50.0, 'dt': 0.1},
)
def competition(
    first: float = 10.0,
    second: float = 10.0,
    *,
    r1: float = 1.0,
    r2: float = 0.8,
    K1: float = 100.0,
    K2: float = 80.0,
    alpha12: float = 0.5,
    alpha21: float = 0.6,
) -> System:
    """Return two species that compete for the same resources, which coexist or exclude each other.

    The species coexist at `n1 = (K1 - alpha12 K2) / (1 - alpha12 alpha21)` and
    `n2 = (K2 - alpha21 K1) / (1 - alpha12 alpha21)` when both are positive and `alpha12 alpha21 < 1`. Otherwise one
    species excludes the other.

    Args:
        first:
            The initial size of the first population.

        second:
            The initial size of the second population.

        r1:
            The growth rate of the first population.

        r2:
            The growth rate of the second population.

        K1:
            The carrying capacity of the first population.

        K2:
            The carrying capacity of the second population.

        alpha12:
            The effect of one member of the second population on the first, relative to one of its own.

        alpha21:
            The effect of one member of the first population on the second, relative to one of its own.

    Returns:
        system:
            The system, with the populations `first` and `second`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import competition
        >>> competition(alpha12=0.2).interactions[0].alpha12
        0.2
    """
    return System(
        elements=[PopulationElement('first', n=first), PopulationElement('second', n=second)],
        interactions=[
            CompetitionInteraction(
                'competition',
                first='first',
                second='second',
                r1=r1,
                r2=r2,
                K1=K1,
                K2=K2,
                alpha12=alpha12,
                alpha21=alpha21,
            ),
        ],
    )

consumer_resource(consumers=None, resources=None, *, c=UPTAKE, m=1.0, e=1.0, w=1.0, r=1.0, K=CAPACITIES, kappa=CAPACITIES, omega=1.0, supply='logistic', kind='substitutable', n=-10.0, v=None)

Return consumer species that compete only through the resources they take up, by MacArthur's niche theory.

The 'logistic' supply of substitutable resources is MacArthur's consumer-resource model, dN_i/dt = e_i N_i (sum_b w_b c_ib R_b - m_i) and dR_a/dt = r_a R_a (K_a - R_a) / K_a - sum_j c_ja N_j R_a. The 'chemostat' supply kappa_a - omega_a R_a models nutrients that flow in from outside, and essential resources limit growth jointly through (sum_b (c_ib R_b)^n)^(1/n), consumed by the stoichiometry v. At most as many consumers as resources coexist, at the point where their zero net growth isoclines g_i(R) = m_i cross. With the defaults, the settings of Mehta and Blumenthal (2024, figure 4), both consumers coexist at R = (5/3, 5/9), the point of the region where no consumer can invade that is closest to the supply point K.

The competition for one resource of Gros (2015, exercise 8), dx_i/dt = (f r_i - d) x_i and df/dt = a - f sum_i r_i x_i, is the chemostat with one resource, c = r, m = d, kappa = a, and omega = 0. The total population tends to a / d, the resource to min_i d / r_i, and only the consumer with the largest r_i survives.

Parameters:

Name Type Description Default
consumers Sequence[float] | None

The initial population sizes, or None for 0.1 each.

None
resources Sequence[float] | None

The initial resource abundances, or None for the capacities K or the inflows kappa.

None
c Sequence[Sequence[float]]

The uptake rates, one row per consumer and one column per resource.

UPTAKE
m Sequence[float] | float

The maintenance energies of the consumers.

1.0
e Sequence[float] | float

The efficiencies of the consumers.

1.0
w Sequence[float] | float

The energies of the resources.

1.0
r Sequence[float] | float

The growth rates of self-renewing resources.

1.0
K Sequence[float] | float

The carrying capacities of self-renewing resources.

CAPACITIES
kappa Sequence[float] | float

The inflows of supplied resources.

CAPACITIES
omega Sequence[float] | float

The dilution rates of supplied resources.

1.0
supply str

'logistic' for self-renewing resources or 'chemostat' for supplied ones.

'logistic'
kind str

'substitutable' or 'essential' resources.

'substitutable'
n float

The exponent of the growth on essential resources, below -1.

-10.0
v Sequence[Sequence[float]] | None

The stoichiometry of essential resources, one row per consumer, or None for c.

None

Returns:

Name Type Description
system System

The system, with the populations consumers.N and the resources resources.R.

Raises:

Type Description
ValidationError

The uptake rates are not one row per consumer with one column per resource.

Examples:

>>> from skcomplex.systems.biology.ecology import consumer_resource
>>> [group.prepare().size_ for group in consumer_resource().elements]
[2, 2]
Source code in src/skcomplex/systems/biology/ecology/_consumer_resources.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
@register_system(
    field='biology/ecology',
    tags=('consumer-resource', 'competitive exclusion', 'niche theory', 'ode'),
    references=('MacArthur 1970', 'Tilman 1982', 'Mehta and Blumenthal 2024', 'Gros 2015'),
    defaults={'until': 100.0, 'dt': 0.5},
)
def consumer_resource(
    consumers: Sequence[float] | None = None,
    resources: Sequence[float] | None = None,
    *,
    c: Sequence[Sequence[float]] = UPTAKE,
    m: Sequence[float] | float = 1.0,
    e: Sequence[float] | float = 1.0,
    w: Sequence[float] | float = 1.0,
    r: Sequence[float] | float = 1.0,
    K: Sequence[float] | float = CAPACITIES,
    kappa: Sequence[float] | float = CAPACITIES,
    omega: Sequence[float] | float = 1.0,
    supply: str = 'logistic',
    kind: str = 'substitutable',
    n: float = -10.0,
    v: Sequence[Sequence[float]] | None = None,
) -> System:
    """Return consumer species that compete only through the resources they take up, by MacArthur's niche theory.

    The `'logistic'` supply of substitutable resources is MacArthur's consumer-resource model, `dN_i/dt = e_i N_i
    (sum_b w_b c_ib R_b - m_i)` and `dR_a/dt = r_a R_a (K_a - R_a) / K_a - sum_j c_ja N_j R_a`. The `'chemostat'` supply
    `kappa_a - omega_a R_a` models nutrients that flow in from outside, and essential resources limit growth jointly
    through `(sum_b (c_ib R_b)^n)^(1/n)`, consumed by the stoichiometry `v`. At most as many consumers as resources
    coexist, at the point where their zero net growth isoclines `g_i(R) = m_i` cross. With the defaults, the settings of
    Mehta and Blumenthal (2024, figure 4), both consumers coexist at `R = (5/3, 5/9)`, the point of the region where
    no consumer can invade that is closest to the supply point `K`.

    The competition for one resource of Gros (2015, exercise 8), `dx_i/dt = (f r_i - d) x_i` and `df/dt = a - f sum_i
    r_i x_i`, is the chemostat with one resource, `c = r`, `m = d`, `kappa = a`, and `omega = 0`. The total population
    tends to `a / d`, the resource to `min_i d / r_i`, and only the consumer with the largest `r_i` survives.

    Args:
        consumers:
            The initial population sizes, or `None` for 0.1 each.

        resources:
            The initial resource abundances, or `None` for the capacities `K` or the inflows `kappa`.

        c:
            The uptake rates, one row per consumer and one column per resource.

        m:
            The maintenance energies of the consumers.

        e:
            The efficiencies of the consumers.

        w:
            The energies of the resources.

        r:
            The growth rates of self-renewing resources.

        K:
            The carrying capacities of self-renewing resources.

        kappa:
            The inflows of supplied resources.

        omega:
            The dilution rates of supplied resources.

        supply:
            `'logistic'` for self-renewing resources or `'chemostat'` for supplied ones.

        kind:
            `'substitutable'` or `'essential'` resources.

        n:
            The exponent of the growth on essential resources, below -1.

        v:
            The stoichiometry of essential resources, one row per consumer, or `None` for `c`.

    Returns:
        system:
            The system, with the populations `consumers.N` and the resources `resources.R`.

    Raises:
        ValidationError:
            The uptake rates are not one row per consumer with one column per resource.

    Examples:
        >>> from skcomplex.systems.biology.ecology import consumer_resource
        >>> [group.prepare().size_ for group in consumer_resource().elements]
        [2, 2]
    """
    uptake = np.atleast_2d(np.asarray(c, dtype=float))
    n_consumers, n_resources = uptake.shape
    sizes = np.full(n_consumers, 0.1) if consumers is None else np.asarray(consumers, dtype=float)
    supplied = K if supply == 'logistic' else kappa
    abundances = np.asarray(resources if resources is not None else np.broadcast_to(supplied, n_resources), float)
    if sizes.shape != (n_consumers,) or abundances.shape != (n_resources,):
        error_msg = (
            f'The uptake rates of shape {uptake.shape} need {n_consumers} initial populations and {n_resources} '
            'initial resources.'
        )
        raise ValidationError(error_msg)
    consumer_group = GroupElement(
        'consumers',
        element=ConsumerElement,
        size=n_consumers,
        values={'N': sizes, 'm': m, 'e': e},
    )
    resource_group = GroupElement(
        'resources',
        element=ResourceElement,
        size=n_resources,
        values={'R': np.array(abundances, dtype=float), 'w': w, 'r': r, 'K': K, 'kappa': kappa, 'omega': omega},
    )
    uptake_rates = tuple(map(tuple, uptake.tolist()))
    growth = ConsumerGrowthInteraction(
        'growth',
        consumers='consumers',
        resources='resources',
        c=uptake_rates,
        kind=kind,
        n=n,
    )
    turnover = ResourceTurnoverInteraction(
        'turnover',
        consumers='consumers',
        resources='resources',
        c=uptake_rates,
        kind=kind,
        n=n,
        supply=supply,
        v=v,
    )
    return System(elements=[consumer_group, resource_group], interactions=[growth, turnover])

droop_cell_quota(Q=1.5, P=1.0, *, r_inf=1.0, q=1.0, vmax=2.0, g=1.0, R=1.0, d=0.1)

Return the Droop system, a phytoplankton whose growth rate follows the nutrient stored in its cells.

The growth rate r_inf (1 - q / Q) rises with the quota Q and saturates at r_inf. Under a constant external nutrient the quota settles at Q* = q + v / r_inf, where v = vmax R / (g + R) is the uptake, and the biomass then grows exponentially at r_inf (1 - q / Q*) - d. The book gives no values for this system, so the defaults are in units of the minimum quota, the maximum growth rate, and the half saturation, with time in days.

Parameters:

Name Type Description Default
Q float

The initial cell quota.

1.5
P float

The initial biomass.

1.0
r_inf float

The growth rate for an infinite quota.

1.0
q float

The minimum quota, at which growth stops.

1.0
vmax float

The maximum uptake rate.

2.0
g float

The external nutrient at which the uptake is half its maximum.

1.0
R float

The external nutrient concentration.

1.0
d float

The death rate.

0.1

Returns:

Name Type Description
system System

The system, with the quota algae.Q and the biomass algae.P.

Examples:

>>> from skcomplex.systems.biology.ecology import droop_cell_quota
>>> droop_cell_quota(R=4.0).elements[0].R
4.0
Source code in src/skcomplex/systems/biology/ecology/_cell_quota.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@register_system(
    field='biology/ecology',
    tags=('population growth', 'ode', 'nutrient', 'cell quota', 'phytoplankton'),
    references=('Padmanabhan, Meskin, and Al Moustafa 2021', 'Droop 1973'),
    defaults={'until': 20.0, 'dt': 0.1},
)
def droop_cell_quota(
    Q: float = 1.5,
    P: float = 1.0,
    *,
    r_inf: float = 1.0,
    q: float = 1.0,
    vmax: float = 2.0,
    g: float = 1.0,
    R: float = 1.0,
    d: float = 0.1,
) -> System:
    """Return the Droop system, a phytoplankton whose growth rate follows the nutrient stored in its cells.

    The growth rate `r_inf (1 - q / Q)` rises with the quota `Q` and saturates at `r_inf`. Under a constant external
    nutrient the quota settles at `Q* = q + v / r_inf`, where `v = vmax R / (g + R)` is the uptake, and the biomass
    then grows exponentially at `r_inf (1 - q / Q*) - d`. The book gives no values for this system, so the defaults are
    in units of the minimum quota, the maximum growth rate, and the half saturation, with time in days.

    Args:
        Q:
            The initial cell quota.

        P:
            The initial biomass.

        r_inf:
            The growth rate for an infinite quota.

        q:
            The minimum quota, at which growth stops.

        vmax:
            The maximum uptake rate.

        g:
            The external nutrient at which the uptake is half its maximum.

        R:
            The external nutrient concentration.

        d:
            The death rate.

    Returns:
        system:
            The system, with the quota `algae.Q` and the biomass `algae.P`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import droop_cell_quota
        >>> droop_cell_quota(R=4.0).elements[0].R
        4.0
    """
    algae = QuotaPhytoplanktonElement('algae', Q=Q, P=P, r_inf=r_inf, q=q, vmax=vmax, g=g, R=R, d=d)
    return System(elements=[algae])

dynamic_multispecies_fba(*, fast_vmax=10.0, slow_vmax=8.0, biomass=0.01, glucose=10.0, km=0.015)

Return two E. coli core strains that differ in maximal glucose uptake on one medium, which needs the extra.

Each strain has its own program, uptake kinetics, and biomass, and they read one glucose pool (Raman 2021, Section 11.1.3.4). The strain with the larger uptake grows faster, so its share rises until the glucose runs out. The two strains and their uptakes of 10 and 8 are an illustration of the framework, whose example in the source is the competition between Rhodoferax and Geobacter (Zhuang et al. 2011).

Parameters:

Name Type Description Default
fast_vmax float

The largest glucose uptake of the fast strain, in mmol per gDW per h.

10.0
slow_vmax float

The largest glucose uptake of the slow strain, in mmol per gDW per h.

8.0
biomass float

The initial biomass of each strain in gDW per L.

0.01
glucose float

The initial glucose in mM.

10.0
km float

The half-saturation concentration of glucose in mM.

0.015

Returns:

Name Type Description
system System

The system.

Raises:

Type Description
MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.systems.biology.ecology import dynamic_multispecies_fba
>>> [element.label for element in dynamic_multispecies_fba().systems[1].elements]
['biomass_fast', 'biomass_slow', 'glucose']
Source code in src/skcomplex/systems/biology/ecology/_dynamic_multispecies_fba.py
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@register_system(
    field='biology/ecology',
    tags=('dynamic flux balance', 'competition', 'linear program', 'metabolism', 'co-simulation'),
    references=('Raman 2021', 'Zhuang et al. 2011'),
    defaults={
        'until': 8.0,
        'dt': SYNCHRONISATION,
        'solver': CoSimulationSolver(sync_dt=SYNCHRONISATION, solvers={'culture': RK4Solver(dt=ODE_STEP)}),
    },
)
def dynamic_multispecies_fba(
    *,
    fast_vmax: float = 10.0,
    slow_vmax: float = 8.0,
    biomass: float = 0.01,
    glucose: float = 10.0,
    km: float = 0.015,
) -> System:
    """Return two E. coli core strains that differ in maximal glucose uptake on one medium, which needs the extra.

    Each strain has its own program, uptake kinetics, and biomass, and they read one glucose pool (Raman 2021, Section
    11.1.3.4). The strain with the larger uptake grows faster, so its share rises until the glucose runs out. The two
    strains and their uptakes of 10 and 8 are an illustration of the framework, whose example in the source is the
    competition between Rhodoferax and Geobacter (Zhuang et al. 2011).

    Args:
        fast_vmax:
            The largest glucose uptake of the fast strain, in mmol per gDW per h.

        slow_vmax:
            The largest glucose uptake of the slow strain, in mmol per gDW per h.

        biomass:
            The initial biomass of each strain in gDW per L.

        glucose:
            The initial glucose in mM.

        km:
            The half-saturation concentration of glucose in mM.

    Returns:
        system:
            The system.

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.systems.biology.ecology import dynamic_multispecies_fba
        >>> [element.label for element in dynamic_multispecies_fba().systems[1].elements]
        ['biomass_fast', 'biomass_slow', 'glucose']
    """
    cells = []
    interactions = []
    for name, vmax in (('fast', fast_vmax), ('slow', slow_vmax)):
        cell = load_network('textbook', f'cell_{name}', needed_by='dynamic_multispecies_fba')
        cell.parsimonious, cell.infeasible = True, 'zero'
        cells.append(cell)
        interactions += [
            ExchangeInteraction(
                f'uptake_{name}',
                cell=f'fba/cell_{name}',
                biomass=f'culture/biomass_{name}',
                substrate='culture/glucose',
                reaction=GLUCOSE_EXCHANGE,
                vmax=vmax,
                km=km,
                interval=SYNCHRONISATION,
            ),
            GrowthInteraction(
                f'growth_{name}',
                cell=f'fba/cell_{name}',
                biomass=f'culture/biomass_{name}',
                reaction=GROWTH,
            ),
        ]
    return System(
        systems=[
            System('fba', elements=cells, time=DiscreteTime()),
            System(
                'culture',
                elements=[
                    BiomassElement('biomass_fast', x=biomass),
                    BiomassElement('biomass_slow', x=biomass),
                    SubstrateElement('glucose', c=glucose),
                ],
            ),
        ],
        interactions=interactions,
    )

exponential_growth(n=10.0, r=0.1)

Return a population that grows or declines at a constant per-capita rate.

Parameters:

Name Type Description Default
n float

The initial size.

10.0
r float

The per-capita growth rate.

0.1

Returns:

Name Type Description
system System

The system, with the population population.

Examples:

>>> from skcomplex.systems.biology.ecology import exponential_growth
>>> exponential_growth(r=0.2).interactions[0].r
0.2
Source code in src/skcomplex/systems/biology/ecology/_factories.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
@register_system(
    field='biology/ecology',
    tags=('population', 'ode'),
    references=('Malthus 1798',),
    defaults={'until': 20.0, 'dt': 0.1},
)
def exponential_growth(n: float = 10.0, r: float = 0.1) -> System:
    """Return a population that grows or declines at a constant per-capita rate.

    Args:
        n:
            The initial size.

        r:
            The per-capita growth rate.

    Returns:
        system:
            The system, with the population `population`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import exponential_growth
        >>> exponential_growth(r=0.2).interactions[0].r
        0.2
    """
    return System(
        elements=[PopulationElement('population', n=n)],
        interactions=[ExponentialGrowthInteraction('growth', target='population', r=r)],
    )

fibonacci_rabbits(pairs=1.0, previous=0.0)

Return Fibonacci's rabbits, N_{t+1} = N_t + N_{t-1}, where every pair older than one month breeds a new pair.

The previous population counts the pairs old enough to breed, so the recurrence is an age structure of two classes.

Parameters:

Name Type Description Default
pairs float

The number of pairs this month.

1.0
previous float

The number of pairs last month.

0.0

Returns:

Name Type Description
system System

The system, with the population rabbits.pairs and last month's rabbits.pairs_lag1.

Examples:

>>> from skcomplex.systems.biology.ecology import fibonacci_rabbits
>>> fibonacci_rabbits().elements[0].pairs
1.0
Source code in src/skcomplex/systems/biology/ecology/_factories.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
@register_system(
    field='biology/ecology',
    tags=('population', 'discrete map', 'second order', 'age structure'),
    references=('Fibonacci 1202',),
    defaults={'until': 20, 'dt': 1},
)
def fibonacci_rabbits(pairs: float = 1.0, previous: float = 0.0) -> System:
    """Return Fibonacci's rabbits, `N_{t+1} = N_t + N_{t-1}`, where every pair older than one month breeds a new pair.

    The previous population counts the pairs old enough to breed, so the recurrence is an age structure of two classes.

    Args:
        pairs:
            The number of pairs this month.

        previous:
            The number of pairs last month.

    Returns:
        system:
            The system, with the population `rabbits.pairs` and last month's `rabbits.pairs_lag1`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import fibonacci_rabbits
        >>> fibonacci_rabbits().elements[0].pairs
        1.0
    """
    breeding = MapInteraction(
        'breeding',
        target='rabbits',
        state='pairs',
        function=lambda s: s.target.pairs + lag(s.target.pairs, 1),
    )
    return System(elements=[RabbitsElement('rabbits', pairs=pairs, pairs_lag1=previous)], interactions=[breeding])

fisher_kpp(length=800, *, D=1.0, r=1.0, spacing=0.25, front=0.05)

Return the Fisher-KPP equation, whose step invades the empty line as a front of speed 2 sqrt(r D).

Parameters:

Name Type Description Default
length int

The number of sites of the line.

800
D float

The diffusion coefficient.

1.0
r float

The growth rate.

1.0
spacing float

The distance between sites.

0.25
front float

The fraction of the line that starts occupied, on its left.

0.05

Returns:

Name Type Description
system System

The system, with the density line.u.

Examples:

>>> from skcomplex.systems.biology.ecology import fisher_kpp
>>> int(fisher_kpp(100, front=0.1).elements[0].values['u'].sum())
10
Source code in src/skcomplex/systems/biology/ecology/_fronts.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
@register_system(
    field='biology/ecology',
    tags=('field', 'fronts', 'reaction-diffusion', 'pde'),
    references=('Fisher 1937', 'Kolmogorov, Petrovsky, and Piskunov 1937'),
    defaults={'until': 40.0, 'dt': 1.0},
)
def fisher_kpp(
    length: int = 800,
    *,
    D: float = 1.0,
    r: float = 1.0,
    spacing: float = 0.25,
    front: float = 0.05,
) -> System:
    """Return the Fisher-KPP equation, whose step invades the empty line as a front of speed `2 sqrt(r D)`.

    Args:
        length:
            The number of sites of the line.

        D:
            The diffusion coefficient.

        r:
            The growth rate.

        spacing:
            The distance between sites.

        front:
            The fraction of the line that starts occupied, on its left.

    Returns:
        system:
            The system, with the density `line.u`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import fisher_kpp
        >>> int(fisher_kpp(100, front=0.1).elements[0].values['u'].sum())
        10
    """
    u = (np.arange(length) < front * length).astype(float)
    space = LatticeSpace(length, spacing=spacing)
    return System(
        elements=[
            FieldElement(
                'line',
                element=FisherKPPElement,
                space=space,
                boundary={'u': 'zero-flux'},
                values={'u': u, 'D': D, 'r': r},
            ),
        ],
    )

food_webs(populations=None, *, growth=None, mortality=None, links=None)

Return a food web where basal species grow logistically and consumers live on Lotka-Volterra predation.

The default web has frogs and mice at its base, snakes that eat frogs and mice, and hawks that eat snakes and mice. Its four species coexist at a stable equilibrium.

Parameters:

Name Type Description Default
populations Mapping[str, float] | None

The initial size of every species by name, or None for the default web.

None
growth Mapping[str, tuple[float, float]] | None

The growth rate and the carrying capacity of every basal species, or None for the default web.

None
mortality Mapping[str, float] | None

The death rate of every consumer, or None for the default web.

None
links Sequence[tuple[str, str, float, float]] | None

The links (predator, prey, a, b), with the attack rate a and the conversion rate b, or None for the default web.

None

Returns:

Name Type Description
system System

The system, with one population per species.

Examples:

>>> from skcomplex.systems.biology.ecology import food_webs
>>> [element.label for element in food_webs().elements]
['frogs', 'mice', 'snakes', 'hawks']
Source code in src/skcomplex/systems/biology/ecology/_communities.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
@register_system(
    field='biology/ecology',
    tags=('food web', 'predator-prey', 'ode'),
    references=('Argun et al. 2021', 'Pimm 1982'),
    defaults={'until': 100.0, 'dt': 0.5},
)
def food_webs(
    populations: Mapping[str, float] | None = None,
    *,
    growth: Mapping[str, tuple[float, float]] | None = None,
    mortality: Mapping[str, float] | None = None,
    links: Sequence[tuple[str, str, float, float]] | None = None,
) -> System:
    """Return a food web where basal species grow logistically and consumers live on Lotka-Volterra predation.

    The default web has frogs and mice at its base, snakes that eat frogs and mice, and hawks that eat snakes and
    mice. Its four species coexist at a stable equilibrium.

    Args:
        populations:
            The initial size of every species by name, or `None` for the default web.

        growth:
            The growth rate and the carrying capacity of every basal species, or `None` for the default web.

        mortality:
            The death rate of every consumer, or `None` for the default web.

        links:
            The links `(predator, prey, a, b)`, with the attack rate `a` and the conversion rate `b`, or `None` for the
            default web.

    Returns:
        system:
            The system, with one population per species.

    Examples:
        >>> from skcomplex.systems.biology.ecology import food_webs
        >>> [element.label for element in food_webs().elements]
        ['frogs', 'mice', 'snakes', 'hawks']
    """
    populations = WEB_POPULATIONS if populations is None else populations
    growth = WEB_GROWTH if growth is None else growth
    mortality = WEB_MORTALITY if mortality is None else mortality
    links = WEB_LINKS if links is None else links
    interactions: list[BaseInteraction] = [
        LogisticGrowthInteraction(f'growth_{name}', target=name, r=r, K=K) for name, (r, K) in growth.items()
    ]
    interactions += [MortalityInteraction(f'death_{name}', target=name, d=d) for name, d in mortality.items()]
    interactions += [
        PredationInteraction(f'{predator}_eat_{prey}', predator=predator, prey=prey, a=a, b=b)
        for predator, prey, a, b in links
    ]
    return System(
        elements=[PopulationElement(name, n=n) for name, n in populations.items()],
        interactions=interactions,
    )

forest_size_structure(positions=40, heights=100, *, width=10.0, dispersal=1.0, hurst=1.0, sapling=0.1, top=50.0, shading=1.0, fecundity=0.01, resources=125.0)

Return the McKendrick-von Foerster density of trees over position across a strip and height.

The density f(x, h) of trees of height h at position x across a forest strip grows in height at the rate I (1 - h / top), where the light I = exp(-shading int_h^top f(x, h') h'^(2H) dh') falls through the canopy of taller trees by the Beer-Lambert law. Trees die from competition for canopy space at the rate I h^(2H) f and for resources at the rate I (1 - h / top) a / h, where a = R / resources and R = int h^(1+2H) f dh is the resource consumption of the trees at x. Saplings enter at the height sapling from the seeds int K(x - x') R(x') dx' of the trees around, dispersed by the exponential kernel K of length dispersal and integral fecundity, and no seed comes from beyond the edges of the strip, where the forest was removed. Time and density are rescaled so that the growth rate and the canopy mortality are one (Grilletta et al. 2026, arXiv 2608.11918 Eq. 9, 10, 16, and 25). The kernel is the exponential of Eq. 35 along the axis across the strip, normalized in one dimension.

Parameters:

Name Type Description Default
positions int

The number of positions across the strip.

40
heights int

The number of cells of the height axis.

100
width float

The width L of the strip.

10.0
dispersal float

The dispersal length xi.

1.0
hurst float

The Hurst exponent H of the crown radius, which scales as h^H.

1.0
sapling float

The height h0 at which saplings enter.

0.1
top float

The asymptotic height h_u.

50.0
shading float

The light attenuation gamma.

1.0
fecundity float

The integral kappa of the dispersal kernel.

0.01
resources float

The resource flux R_a.

125.0

Returns:

Name Type Description
system System

The system, with the density forest.f over position and height.

Examples:

>>> from skcomplex.systems.biology.ecology import forest_size_structure
>>> forest_size_structure(8, 12).elements[0].space.prepare().shape_
(8, 12)
Source code in src/skcomplex/systems/biology/ecology/_forest_size_structure.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@register_system(
    field='biology/ecology',
    tags=('field', 'size structure', 'forest', 'integral operator', 'dispersal', 'pde'),
    references=('Grilletta et al. 2026',),
    defaults={'until': 200.0, 'dt': 5.0, 'solver': RK4Solver(dt=0.1)},
)
def forest_size_structure(
    positions: int = 40,
    heights: int = 100,
    *,
    width: float = 10.0,
    dispersal: float = 1.0,
    hurst: float = 1.0,
    sapling: float = 0.1,
    top: float = 50.0,
    shading: float = 1.0,
    fecundity: float = 0.01,
    resources: float = 125.0,
) -> System:
    """Return the McKendrick-von Foerster density of trees over position across a strip and height.

    The density `f(x, h)` of trees of height `h` at position `x` across a forest strip grows in height at the rate
    `I (1 - h / top)`, where the light `I = exp(-shading int_h^top f(x, h') h'^(2H) dh')` falls through the canopy of
    taller trees by the Beer-Lambert law. Trees die from competition for canopy space at the rate `I h^(2H) f` and for
    resources at the rate `I (1 - h / top) a / h`, where `a = R / resources` and `R = int h^(1+2H) f dh` is the
    resource consumption of the trees at `x`. Saplings enter at the height `sapling` from the seeds `int K(x - x') R(x')
    dx'` of the trees around, dispersed by the exponential kernel `K` of length `dispersal` and integral `fecundity`,
    and no seed comes from beyond the edges of the strip, where the forest was removed. Time and density are rescaled
    so that the growth rate and the canopy mortality are one (Grilletta et al. 2026, arXiv 2608.11918 Eq. 9, 10, 16,
    and 25). The kernel is the exponential of Eq. 35 along the axis across the strip, normalized in one dimension.

    Args:
        positions:
            The number of positions across the strip.

        heights:
            The number of cells of the height axis.

        width:
            The width `L` of the strip.

        dispersal:
            The dispersal length `xi`.

        hurst:
            The Hurst exponent `H` of the crown radius, which scales as `h^H`.

        sapling:
            The height `h0` at which saplings enter.

        top:
            The asymptotic height `h_u`.

        shading:
            The light attenuation `gamma`.

        fecundity:
            The integral `kappa` of the dispersal kernel.

        resources:
            The resource flux `R_a`.

    Returns:
        system:
            The system, with the density `forest.f` over position and height.

    Examples:
        >>> from skcomplex.systems.biology.ecology import forest_size_structure
        >>> forest_size_structure(8, 12).elements[0].space.prepare().shape_
        (8, 12)
    """
    step = (top - sapling) / heights
    space = PhaseSpace(
        LatticeSpace((positions,), spacing=width / positions, boundary='fixed'),
        [AxisSpec('h', heights, sapling, top)],
    )
    centres = space.prepare().coordinates_['h']
    start = np.tile(0.1 * (centres / sapling) ** -2.0, (positions, 1))
    forest = FieldElement(
        'forest',
        element=DensityElement,
        space=space,
        values={'f': start},
        discretization='finite-volume',
    )
    h = coordinate('h')
    growth = 1 - h / top
    kernel = fecundity / (2 * dispersal) * exp(-abs(displacement(0)) / dispersal)

    def light(s: SimpleNamespace) -> Expression:
        return exp(-shading * cumulative_integral(s.target.f * h ** (2 * hurst), HEIGHT_AXIS, reverse=True))

    def demography(s: SimpleNamespace) -> Expression:
        consumption = reduce_axes(s.target.f * h ** (1 + 2 * hurst), ('h',))
        recruits = where(h < sapling + step, light(s) * growth * convolve(consumption, kernel) / step, 0)
        mortality = light(s) * (h ** (2 * hurst) * s.target.f + growth * consumption / (resources * h))
        return recruits - mortality * s.target.f

    grow = AdvectionInteraction(
        'growth',
        target='forest',
        state='f',
        drift=lambda s: [0, light(s) * growth],
        limiter=None,
    )
    demographics = RateInteraction('demography', target='forest', state='f', rate=demography)
    return System(elements=[forest], interactions=[grow, demographics])

generalized_lotka_volterra(x=None, *, b=COMMUNITY_GROWTH, a=COMMUNITY_INTERACTIONS)

Return the generalized Lotka-Volterra system of a microbial community, dx_i/dt = x_i (b_i + sum_j a_ij x_j).

Every species grows at its intrinsic rate b_i and its growth changes with the abundance of every species through the pairwise interaction a_ij. A feasible interior fixed point solves b + a x = 0. The book gives no parameter values. The default is a choice, a community of three self-limiting species with weak competition and one weak mutualism, whose fixed point x = -a^-1 b is positive and stable, so the species coexist. Abundances and time are in arbitrary units.

Parameters:

Name Type Description Default
x Sequence[float] | None

The initial abundances, or None for 0.1 each.

None
b Sequence[float]

The intrinsic growth rates.

COMMUNITY_GROWTH
a Sequence[Sequence[float]]

The interaction matrix, one row per species.

COMMUNITY_INTERACTIONS

Returns:

Name Type Description
system System

The system, with the abundances species.x of the members of the group species, the growth growth, and the interactions glv, whose matrix is the parameter glv.a.

Raises:

Type Description
ValidationError

The growth rates, the matrix, and the abundances do not have one entry per species.

Examples:

>>> from skcomplex.systems.biology.ecology import generalized_lotka_volterra
>>> generalized_lotka_volterra().elements[0].prepare().size_
3
Source code in src/skcomplex/systems/biology/ecology/_microbial_communities.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
@register_system(
    field='biology/ecology',
    tags=('microbial community', 'Lotka-Volterra', 'interaction matrix', 'ode'),
    references=('Raman 2021', 'Stein et al. 2013'),
    defaults={'until': 30.0, 'dt': 0.1},
)
def generalized_lotka_volterra(
    x: Sequence[float] | None = None,
    *,
    b: Sequence[float] = COMMUNITY_GROWTH,
    a: Sequence[Sequence[float]] = COMMUNITY_INTERACTIONS,
) -> System:
    """Return the generalized Lotka-Volterra system of a microbial community, `dx_i/dt = x_i (b_i + sum_j a_ij x_j)`.

    Every species grows at its intrinsic rate `b_i` and its growth changes with the abundance of every species through
    the pairwise interaction `a_ij`. A feasible interior fixed point solves `b + a x = 0`. The book gives no parameter
    values. The default is a choice, a community of three self-limiting species with weak competition and one weak
    mutualism, whose fixed point `x = -a^-1 b` is positive and stable, so the species coexist. Abundances and time are
    in arbitrary units.

    Args:
        x:
            The initial abundances, or `None` for 0.1 each.

        b:
            The intrinsic growth rates.

        a:
            The interaction matrix, one row per species.

    Returns:
        system:
            The system, with the abundances `species.x` of the members of the group `species`, the growth `growth`, and
            the interactions `glv`, whose matrix is the parameter `glv.a`.

    Raises:
        ValidationError:
            The growth rates, the matrix, and the abundances do not have one entry per species.

    Examples:
        >>> from skcomplex.systems.biology.ecology import generalized_lotka_volterra
        >>> generalized_lotka_volterra().elements[0].prepare().size_
        3
    """
    size = len(b)
    abundances = [0.1] * size if x is None else [float(value) for value in x]
    if len(abundances) != size or len(a) != size or any(len(row) != size for row in a):
        error_msg = f'The abundances and the interaction matrix must have one entry per species, {size} growth rates.'
        raise ValidationError(error_msg)
    species = GroupElement(
        'species',
        element=MicrobeElement,
        size=size,
        values={'x': abundances, 'b': [float(value) for value in b]},
    )
    matrix = tuple(tuple(float(value) for value in row) for row in a)
    return System(
        elements=[species],
        interactions=[
            RateInteraction('growth', target='species', rate=_growth),
            GeneralizedLotkaVolterraInteraction('glv', target='species', a=matrix),
        ],
    )

higher_order_random_lotka_volterra(size=200, *, mu=-4.0, sigma=1.0, gamma=0.0, k=1.0, random_state=0)

Return a random Lotka-Volterra community with third-order interactions.

The abundances follow dx_i/dt = x_i (k - x_i + sum_(j<k) a_ijk x_j x_k) (Sidhom and Galla 2024, Eq. 2), where the sum runs over the pairs of other species. The coefficients are Gaussian with mean mu / binom(N - 1, 2) and variance 3 sigma^2 / (2 binom(N - 1, 2)), and the three coefficients of a set of three species have the correlation gamma (Eqs. 4 and 5). The defaults are the competitive community of the paper's Fig. 2, 200 species with uncorrelated coefficients at mu = -4 and sigma = 1, in its phase with a unique stable fixed point, where the theory gives a fraction 0.928 of surviving species and a mean abundance 0.392. The paper does not state the distribution of the initial abundances, which are drawn uniformly from the interval from 0 to 1.

Parameters:

Name Type Description Default
size int

The number of species.

200
mu float

The mean of the interactions, negative for competition.

-4.0
sigma float

The heterogeneity of the interactions.

1.0
gamma float

The correlation of the three coefficients of a set of three species, from -1/2 to 1, where 1 gives every species of a set the same coefficient.

0.0
k float

The growth rate at low abundance, which is also the carrying capacity without interactions.

1.0
random_state int | Generator | None

The seed or the generator that draws the tensor and the initial abundances.

0

Returns:

Name Type Description
system System

The system, with the abundances species.n of the members of the group species, the growth growth, and the interactions triplets, whose tensor is the parameter triplets.a.

Examples:

>>> from skcomplex.systems.biology.ecology import higher_order_random_lotka_volterra
>>> higher_order_random_lotka_volterra(5).interactions[1].a.shape
(5, 5, 5)
Source code in src/skcomplex/systems/biology/ecology/_higher_order.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@register_system(
    field='biology/ecology',
    tags=('random community', 'Lotka-Volterra', 'higher-order interactions', 'coupling tensor', 'ode'),
    references=('Sidhom and Galla 2024',),
    defaults={'until': 1000.0, 'dt': 10.0},
)
def higher_order_random_lotka_volterra(
    size: int = 200,
    *,
    mu: float = -4.0,
    sigma: float = 1.0,
    gamma: float = 0.0,
    k: float = 1.0,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return a random Lotka-Volterra community with third-order interactions.

    The abundances follow `dx_i/dt = x_i (k - x_i + sum_(j<k) a_ijk x_j x_k)` (Sidhom and Galla 2024, Eq. 2), where the
    sum runs over the pairs of other species. The coefficients are Gaussian with mean `mu / binom(N - 1, 2)` and
    variance `3 sigma^2 / (2 binom(N - 1, 2))`, and the three coefficients of a set of three species have the
    correlation `gamma` (Eqs. 4 and 5). The defaults are the competitive community of the paper's Fig. 2, 200 species
    with uncorrelated coefficients at `mu = -4` and `sigma = 1`, in its phase with a unique stable fixed point, where
    the theory gives a fraction `0.928` of surviving species and a mean abundance `0.392`. The paper does not state the
    distribution of the initial abundances, which are drawn uniformly from the interval from 0 to 1.

    Args:
        size:
            The number of species.

        mu:
            The mean of the interactions, negative for competition.

        sigma:
            The heterogeneity of the interactions.

        gamma:
            The correlation of the three coefficients of a set of three species, from `-1/2` to 1, where 1 gives every
            species of a set the same coefficient.

        k:
            The growth rate at low abundance, which is also the carrying capacity without interactions.

        random_state:
            The seed or the generator that draws the tensor and the initial abundances.

    Returns:
        system:
            The system, with the abundances `species.n` of the members of the group `species`, the growth `growth`, and
            the interactions `triplets`, whose tensor is the parameter `triplets.a`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import higher_order_random_lotka_volterra
        >>> higher_order_random_lotka_volterra(5).interactions[1].a.shape
        (5, 5, 5)
    """
    rng = np.random.default_rng(random_state)
    tensor = _draw_tensor(size, mu, sigma, gamma, rng)
    species = GroupElement('species', element=PopulationElement, size=size, values={'n': rng.random(size)})
    return System(
        elements=[species],
        interactions=[
            LogisticGrowthInteraction('growth', target='species', r=k, K=k),
            TripletInteraction('triplets', target='species', a=tensor, state='n'),
        ],
    )

hutchinson(n=50.0, *, r=1.0, K=100.0, tau=2.0)

Return Hutchinson's delayed logistic equation, which oscillates around K when r * tau exceeds π/2.

The history before the start is the initial size.

Parameters:

Name Type Description Default
n float

The initial size, also its history.

50.0
r float

The per-capita growth rate at low density.

1.0
K float

The carrying capacity.

100.0
tau float

The delay of the density feedback.

2.0

Returns:

Name Type Description
system System

The system, with the population population.

Examples:

>>> from skcomplex.systems.biology.ecology import hutchinson
>>> hutchinson(tau=1.0).interactions[0].tau
1.0
Source code in src/skcomplex/systems/biology/ecology/_factories.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
@register_system(
    field='biology/ecology',
    tags=('population', 'delay', 'oscillation'),
    references=('Hutchinson 1948', 'Erneux 2009'),
    defaults={'until': 100.0, 'dt': 0.1},
)
def hutchinson(n: float = 50.0, *, r: float = 1.0, K: float = 100.0, tau: float = 2.0) -> System:
    """Return Hutchinson's delayed logistic equation, which oscillates around `K` when `r * tau` exceeds π/2.

    The history before the start is the initial size.

    Args:
        n:
            The initial size, also its history.

        r:
            The per-capita growth rate at low density.

        K:
            The carrying capacity.

        tau:
            The delay of the density feedback.

    Returns:
        system:
            The system, with the population `population`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import hutchinson
        >>> hutchinson(tau=1.0).interactions[0].tau
        1.0
    """
    return System(
        elements=[PopulationElement('population', n=n)],
        interactions=[LogisticGrowthInteraction('growth', target='population', r=r, K=K, tau=tau)],
    )

intrinsic_instability(*, x=1.1, eta=0.1, alpha=0.01, beta=0.01, nu=0.01, p=0.001, sigma=0.01)

Return Jensen's coupled populations, whose steady state becomes unstable without a change of the surroundings.

The resident population fluctuates about its level X = 1 until a rare mutation seeds the invader. The invader then grows by the factor 1 + beta per step and suppresses the resident, so the trajectory leaves the fixed point (X, 0) along its unstable direction, with eigenvalue beta, and the resident declines although no parameter has changed.

Parameters:

Name Type Description Default
x float

The initial resident population.

1.1
eta float

The restoring rate of the resident population.

0.1
alpha float

The suppression of the resident population by the invader.

0.01
beta float

The growth rate of the invader.

0.01
nu float

The share of the resident population that a mutation moves to the invader.

0.01
p float

The probability of a mutation per step.

0.001
sigma float

The amplitude of the noise.

0.01

Returns:

Name Type Description
system System

The system, with the populations populations.x and populations.y.

Examples:

>>> from skcomplex.systems.biology.ecology import intrinsic_instability
>>> intrinsic_instability().elements[0].beta
0.01
Source code in src/skcomplex/systems/biology/ecology/_instability.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
@register_system(
    field='biology/ecology',
    tags=('tipping point', 'stochastic', 'discrete map', 'early warning'),
    references=('Jensen 2023',),
    defaults={'until': 2000, 'dt': 10},
)
def intrinsic_instability(
    *,
    x: float = 1.1,
    eta: float = 0.1,
    alpha: float = 0.01,
    beta: float = 0.01,
    nu: float = 0.01,
    p: float = 0.001,
    sigma: float = 0.01,
) -> System:
    """Return Jensen's coupled populations, whose steady state becomes unstable without a change of the surroundings.

    The resident population fluctuates about its level `X = 1` until a rare mutation seeds the invader. The invader
    then grows by the factor `1 + beta` per step and suppresses the resident, so the trajectory leaves the fixed point
    `(X, 0)` along its unstable direction, with eigenvalue `beta`, and the resident declines although no parameter has
    changed.

    Args:
        x:
            The initial resident population.

        eta:
            The restoring rate of the resident population.

        alpha:
            The suppression of the resident population by the invader.

        beta:
            The growth rate of the invader.

        nu:
            The share of the resident population that a mutation moves to the invader.

        p:
            The probability of a mutation per step.

        sigma:
            The amplitude of the noise.

    Returns:
        system:
            The system, with the populations `populations.x` and `populations.y`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import intrinsic_instability
        >>> intrinsic_instability().elements[0].beta
        0.01
    """
    populations = UnstablePopulationsElement(
        'populations',
        x=x,
        eta=eta,
        alpha=alpha,
        beta=beta,
        nu=nu,
        p=p,
        sigma=sigma,
    )
    return System(
        elements=[populations],
        interactions=[
            MapInteraction('resident', target='populations', state='x', function=_get_resident),
            MapInteraction('invader', target='populations', state='y', function=_get_invader),
        ],
    )

logistic_growth(n=10.0, r=1.0, K=100.0)

Return a population that grows logistically towards its carrying capacity.

Parameters:

Name Type Description Default
n float

The initial size.

10.0
r float

The intrinsic growth rate.

1.0
K float

The carrying capacity.

100.0

Returns:

Name Type Description
system System

The system, with the population population.

Examples:

>>> from skcomplex.systems.biology.ecology import logistic_growth
>>> logistic_growth(K=500.0).interactions[0].K
500.0
Source code in src/skcomplex/systems/biology/ecology/_factories.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
@register_system(
    field='biology/ecology',
    tags=('population', 'ode'),
    references=('Verhulst 1838',),
    defaults={'until': 20.0, 'dt': 0.1},
)
def logistic_growth(n: float = 10.0, r: float = 1.0, K: float = 100.0) -> System:
    """Return a population that grows logistically towards its carrying capacity.

    Args:
        n:
            The initial size.

        r:
            The intrinsic growth rate.

        K:
            The carrying capacity.

    Returns:
        system:
            The system, with the population `population`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import logistic_growth
        >>> logistic_growth(K=500.0).interactions[0].K
        500.0
    """
    return System(
        elements=[PopulationElement('population', n=n)],
        interactions=[LogisticGrowthInteraction('growth', target='population', r=r, K=K)],
    )

lotka_volterra(prey=40.0, predators=9.0, *, r=1.1, a=0.4, b=0.1, d=0.4, K=None)

Return prey and predators whose populations oscillate through predation.

Parameters:

Name Type Description Default
prey float

The initial number of prey.

40.0
predators float

The initial number of predators.

9.0
r float

The growth rate of the prey.

1.1
a float

The rate at which predation removes prey.

0.4
b float

The rate at which predation feeds predators.

0.1
d float

The mortality rate of the predators.

0.4
K float | None

The carrying capacity of the prey, or None for exponential growth of the prey.

None

Returns:

Name Type Description
system System

The system, with the populations prey and predators.

Examples:

>>> from skcomplex.systems.biology.ecology import lotka_volterra
>>> [element.label for element in lotka_volterra().elements]
['prey', 'predators']
Source code in src/skcomplex/systems/biology/ecology/_factories.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
@register_system(
    field='biology/ecology',
    tags=('predator-prey', 'ode', 'oscillation'),
    references=('Lotka 1925', 'Volterra 1926'),
    defaults={'until': 50.0, 'dt': 0.1},
)
def lotka_volterra(
    prey: float = 40.0,
    predators: float = 9.0,
    *,
    r: float = 1.1,
    a: float = 0.4,
    b: float = 0.1,
    d: float = 0.4,
    K: float | None = None,
) -> System:
    """Return prey and predators whose populations oscillate through predation.

    Args:
        prey:
            The initial number of prey.

        predators:
            The initial number of predators.

        r:
            The growth rate of the prey.

        a:
            The rate at which predation removes prey.

        b:
            The rate at which predation feeds predators.

        d:
            The mortality rate of the predators.

        K:
            The carrying capacity of the prey, or `None` for exponential growth of the prey.

    Returns:
        system:
            The system, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import lotka_volterra
        >>> [element.label for element in lotka_volterra().elements]
        ['prey', 'predators']
    """
    growth: BaseInteraction = (
        ExponentialGrowthInteraction('growth', target='prey', r=r)
        if K is None
        else LogisticGrowthInteraction('growth', target='prey', r=r, K=K)
    )
    return System(
        elements=[PopulationElement('prey', n=prey), PopulationElement('predators', n=predators)],
        interactions=[
            growth,
            PredationInteraction('predation', predator='predators', prey='prey', a=a, b=b),
            MortalityInteraction('death', target='predators', d=d),
        ],
    )

lotka_volterra_with_harvesting(prey=16.0, predators=8.0, *, r=1.0, a=0.1, b=0.05, d=0.5, prey_harvest=0.4, predator_harvest=0.4)

Return Lotka-Volterra predation where both species are harvested with a constant effort.

The populations cycle around prey = (d + predator_harvest) / b and predators = (r - prey_harvest) / a, which are also their averages over a cycle. Harvesting raises the average prey and lowers the average predators, and a prey harvest above r drives the predators extinct.

Parameters:

Name Type Description Default
prey float

The initial number of prey.

16.0
predators float

The initial number of predators.

8.0
r float

The growth rate of the prey.

1.0
a float

The rate at which predation removes prey.

0.1
b float

The rate at which predation feeds predators.

0.05
d float

The mortality rate of the predators.

0.5
prey_harvest float

The harvesting effort on the prey.

0.4
predator_harvest float

The harvesting effort on the predators.

0.4

Returns:

Name Type Description
system System

The system, with the populations prey and predators.

Examples:

>>> from skcomplex.systems.biology.ecology import lotka_volterra_with_harvesting
>>> [interaction.label for interaction in lotka_volterra_with_harvesting().interactions][-2:]
['prey_harvest', 'predator_harvest']
Source code in src/skcomplex/systems/biology/ecology/_predation.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
@register_system(
    field='biology/ecology',
    tags=('predator-prey', 'ode', 'harvesting', 'oscillation'),
    references=('Volterra 1926', 'Trzaska 2023'),
    defaults={'until': 50.0, 'dt': 0.1},
)
def lotka_volterra_with_harvesting(
    prey: float = 16.0,
    predators: float = 8.0,
    *,
    r: float = 1.0,
    a: float = 0.1,
    b: float = 0.05,
    d: float = 0.5,
    prey_harvest: float = 0.4,
    predator_harvest: float = 0.4,
) -> System:
    """Return Lotka-Volterra predation where both species are harvested with a constant effort.

    The populations cycle around `prey = (d + predator_harvest) / b` and `predators = (r - prey_harvest) / a`, which are
    also their averages over a cycle. Harvesting raises the average prey and lowers the average predators, and a prey
    harvest above `r` drives the predators extinct.

    Args:
        prey:
            The initial number of prey.

        predators:
            The initial number of predators.

        r:
            The growth rate of the prey.

        a:
            The rate at which predation removes prey.

        b:
            The rate at which predation feeds predators.

        d:
            The mortality rate of the predators.

        prey_harvest:
            The harvesting effort on the prey.

        predator_harvest:
            The harvesting effort on the predators.

    Returns:
        system:
            The system, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import lotka_volterra_with_harvesting
        >>> [interaction.label for interaction in lotka_volterra_with_harvesting().interactions][-2:]
        ['prey_harvest', 'predator_harvest']
    """
    return System(
        elements=[PopulationElement('prey', n=prey), PopulationElement('predators', n=predators)],
        interactions=[
            ExponentialGrowthInteraction('growth', target='prey', r=r),
            PredationInteraction('predation', predator='predators', prey='prey', a=a, b=b),
            MortalityInteraction('death', target='predators', d=d),
            MortalityInteraction('prey_harvest', target='prey', d=prey_harvest),
            MortalityInteraction('predator_harvest', target='predators', d=predator_harvest),
        ],
    )

mangrove_succession(keora=0.0, gewa=0.0, sundari=0.0, *, g_gewa=0.05, g_sundari=0.03, seedlings=0.01)

Return the regrowth of a mangrove forest of the Sundarbans after a clear cut, from pioneers to climax trees.

Keora, the pioneer, regrows fastest, Gewa, the intermediate group, follows, and Sundari, the climax group, grows slowest but comes to dominate the mature forest and suppresses the others. Volumes, mature volumes, and competition weights follow Bala et al. (2017), and the growth rates of Gewa and Sundari are illustrative.

Parameters:

Name Type Description Default
keora float

The initial stem volume of Keora, the pioneer.

0.0
gewa float

The initial stem volume of Gewa, the intermediate group.

0.0
sundari float

The initial stem volume of Sundari, the climax group.

0.0
g_gewa float

The specific growth rate of Gewa.

0.05
g_sundari float

The specific growth rate of Sundari.

0.03
seedlings float

The constant input of Gewa and Sundari seedlings.

0.01

Returns:

Name Type Description
system System

The system, with the stands keora, gewa, and sundari.

Examples:

>>> from skcomplex.systems.biology.ecology import mangrove_succession
>>> [element.mature for element in mangrove_succession().elements]
[196.11, 80.0, 320.0]
Source code in src/skcomplex/systems/biology/ecology/_succession.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
@register_system(
    field='biology/ecology',
    tags=('succession', 'forest', 'ode', 'system dynamics', 'competition'),
    references=('Bala et al. 2017', 'Tietjen and Huth 2006'),
    defaults={'until': 300.0, 'dt': 1.0},
)
def mangrove_succession(
    keora: float = 0.0,
    gewa: float = 0.0,
    sundari: float = 0.0,
    *,
    g_gewa: float = 0.05,
    g_sundari: float = 0.03,
    seedlings: float = 0.01,
) -> System:
    """Return the regrowth of a mangrove forest of the Sundarbans after a clear cut, from pioneers to climax trees.

    Keora, the pioneer, regrows fastest, Gewa, the intermediate group, follows, and Sundari, the climax group, grows
    slowest but comes to dominate the mature forest and suppresses the others. Volumes, mature volumes, and competition
    weights follow Bala et al. (2017), and the growth rates of Gewa and Sundari are illustrative.

    Args:
        keora:
            The initial stem volume of Keora, the pioneer.

        gewa:
            The initial stem volume of Gewa, the intermediate group.

        sundari:
            The initial stem volume of Sundari, the climax group.

        g_gewa:
            The specific growth rate of Gewa.

        g_sundari:
            The specific growth rate of Sundari.

        seedlings:
            The constant input of Gewa and Sundari seedlings.

    Returns:
        system:
            The system, with the stands `keora`, `gewa`, and `sundari`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import mangrove_succession
        >>> [element.mature for element in mangrove_succession().elements]
        [196.11, 80.0, 320.0]
    """
    return System(
        elements=[
            StandElement('keora', volume=keora, mature=196.11),
            StandElement('gewa', volume=gewa, mature=80.0),
            StandElement('sundari', volume=sundari, mature=320.0),
        ],
        interactions=[
            PioneerGrowthInteraction('keora_growth', target='keora', intermediate='gewa', climax='sundari'),
            SuccessionalGrowthInteraction(
                'gewa_growth',
                target='gewa',
                first='gewa',
                second='sundari',
                g=g_gewa,
                w_first=0.32,
                w_second=0.68,
                seedlings=seedlings,
            ),
            SuccessionalGrowthInteraction(
                'sundari_growth',
                target='sundari',
                first='gewa',
                second='sundari',
                g=g_sundari,
                w_first=0.01,
                w_second=0.99,
                seedlings=seedlings,
            ),
        ],
    )

meadow_capacity(width=40, height=40, *, cows=80, growth=0.2, bite=0.75, threshold=0.9, random_state=0)

Return cows that graze a summer of 25 weeks on a meadow, which shows how many cows the meadow can carry.

Every week the grass regrows logistically, each cow eats bite of the grass of its patch, and each cow moves to the nearest patch that no other cow occupies and whose grass reaches threshold. A cow that finds none dies. Without regrowth a cow grazes its first patch and 25 more over the summer, so the meadow feeds about width * height / 26 cows, and regrowth raises its carrying capacity. The cows graze the patches down at the same pace, so a herd above the capacity runs out of grown patches all at once and dies out within a week, instead of shrinking to the capacity.

Parameters:

Name Type Description Default
width int

The number of columns of the meadow.

40
height int

The number of rows of the meadow.

40
cows int

The initial number of cows.

80
growth float

The weekly growth rate of the grass.

0.2
bite float

The grass a cow eats in a week.

0.75
threshold float

The least grass a patch needs for a cow to move there.

0.9
random_state int | Generator | None

The seed or generator of the initial cells of the cows.

0

Returns:

Name Type Description
system System

The system, with the groups pasture and cows.

Examples:

>>> from skcomplex.systems.biology.ecology import meadow_capacity
>>> [group.size for group in meadow_capacity(10, 10, cows=5).elements]
[100, 5]
Source code in src/skcomplex/systems/biology/ecology/_meadow.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
@register_system(
    field='biology/ecology',
    tags=('carrying capacity', 'agents', 'grid', 'grazing', 'commons'),
    references=('Hamill and Gilbert 2016',),
    defaults={'until': 25},
)
def meadow_capacity(
    width: int = 40,
    height: int = 40,
    *,
    cows: int = 80,
    growth: float = 0.2,
    bite: float = 0.75,
    threshold: float = 0.9,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return cows that graze a summer of 25 weeks on a meadow, which shows how many cows the meadow can carry.

    Every week the grass regrows logistically, each cow eats `bite` of the grass of its patch, and each cow moves to the
    nearest patch that no other cow occupies and whose grass reaches `threshold`. A cow that finds none dies. Without
    regrowth a cow grazes its first patch and 25 more over the summer, so the meadow feeds about
    `width * height / 26` cows, and regrowth raises its carrying capacity.
    The cows graze the patches down at the same pace, so a herd above the capacity runs out of grown patches all at
    once and dies out within a week, instead of shrinking to the capacity.

    Args:
        width:
            The number of columns of the meadow.

        height:
            The number of rows of the meadow.

        cows:
            The initial number of cows.

        growth:
            The weekly growth rate of the grass.

        bite:
            The grass a cow eats in a week.

        threshold:
            The least grass a patch needs for a cow to move there.

        random_state:
            The seed or generator of the initial cells of the cows.

    Returns:
        system:
            The system, with the groups `pasture` and `cows`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import meadow_capacity
        >>> [group.size for group in meadow_capacity(10, 10, cows=5).elements]
        [100, 5]
    """
    rng = np.random.default_rng(random_state)
    cells = [(column, row) for column in range(width) for row in range(height)]
    picks = rng.choice(len(cells), size=cows, replace=False)
    return System(
        elements=[
            GroupElement(
                'pasture',
                element=PastureElement,
                size=len(cells),
                values={'growth': growth},
                variable=True,
                location=cells,
            ),
            GroupElement(
                'cows',
                element=CowElement,
                size=cows,
                values={'bite': bite},
                variable=True,
                location=[cells[int(pick)] for pick in picks],
            ),
        ],
        interactions=[
            GrazingInteraction('grazing', cows='cows', pasture='pasture'),
            HerdingInteraction('herding', cows='cows', pasture='pasture', threshold=threshold),
        ],
        space=LatticeSpace((width, height), boundary='fixed'),
    )

mutualism(first=10.0, second=10.0, *, r1=1.0, r2=1.0, K1=50.0, K2=50.0, a=0.1, b=0.5, handling=0.5)

Return two species that grow logistically and feed each other, above their carrying capacities.

With a positive handling time the benefit saturates and the populations settle above their capacities. Without it, strong mutualism grows without bound.

Parameters:

Name Type Description Default
first float

The initial size of the first population.

10.0
second float

The initial size of the second population.

10.0
r1 float

The growth rate of the first population.

1.0
r2 float

The growth rate of the second population.

1.0
K1 float

The carrying capacity of the first population alone.

50.0
K2 float

The carrying capacity of the second population alone.

50.0
a float

The effective search rate.

0.1
b float

The rate of encounters.

0.5
handling float

The handling time of the resource of the partner, 0 for type I mutualism.

0.5

Returns:

Name Type Description
system System

The system, with the populations first and second.

Examples:

>>> from skcomplex.systems.biology.ecology import mutualism
>>> [interaction.label for interaction in mutualism().interactions]
['growth_first', 'growth_second', 'mutualism']
Source code in src/skcomplex/systems/biology/ecology/_communities.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
@register_system(
    field='biology/ecology',
    tags=('mutualism', 'ode', 'handling time'),
    references=('May 1981', 'Wright 1989', 'Argun et al. 2021'),
    defaults={'until': 50.0, 'dt': 0.1},
)
def mutualism(
    first: float = 10.0,
    second: float = 10.0,
    *,
    r1: float = 1.0,
    r2: float = 1.0,
    K1: float = 50.0,
    K2: float = 50.0,
    a: float = 0.1,
    b: float = 0.5,
    handling: float = 0.5,
) -> System:
    """Return two species that grow logistically and feed each other, above their carrying capacities.

    With a positive handling time the benefit saturates and the populations settle above their capacities. Without it,
    strong mutualism grows without bound.

    Args:
        first:
            The initial size of the first population.

        second:
            The initial size of the second population.

        r1:
            The growth rate of the first population.

        r2:
            The growth rate of the second population.

        K1:
            The carrying capacity of the first population alone.

        K2:
            The carrying capacity of the second population alone.

        a:
            The effective search rate.

        b:
            The rate of encounters.

        handling:
            The handling time of the resource of the partner, 0 for type I mutualism.

    Returns:
        system:
            The system, with the populations `first` and `second`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import mutualism
        >>> [interaction.label for interaction in mutualism().interactions]
        ['growth_first', 'growth_second', 'mutualism']
    """
    return System(
        elements=[PopulationElement('first', n=first), PopulationElement('second', n=second)],
        interactions=[
            LogisticGrowthInteraction('growth_first', target='first', r=r1, K=K1),
            LogisticGrowthInteraction('growth_second', target='second', r=r2, K=K2),
            MutualismInteraction('mutualism', first='first', second='second', a=a, b=b, handling=handling),
        ],
    )

neutral_biodiversity(individuals=200, *, nu=0.01, species=1, random_state=0)

Return a neutral community of constant size, where species arise by speciation and vanish by drift.

Every species is transient, yet the number of species settles around S_N = sum_n theta / (theta + n) for n from 0 to N - 1, with theta = (N - 1) nu / (1 - nu), and the mean number of species of k individuals around phi_k = theta / k prod_j (N - j + 1) / (N - j + theta) for j from 1 to k.

Parameters:

Name Type Description Default
individuals int

The number of individuals N.

200
nu float

The probability that an offspring founds a new species.

0.01
species int

The initial number of species, to which the individuals belong at random.

1
random_state int | Generator | None

The seed or generator of the initial species.

0

Returns:

Name Type Description
system System

The system, with the group community and the number richness of species.

Examples:

>>> from skcomplex.systems.biology.ecology import neutral_biodiversity
>>> neutral_biodiversity(20).elements[0].prepare().size_
20
Source code in src/skcomplex/systems/biology/ecology/_speciation.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
@register_system(
    field='biology/ecology',
    tags=('neutral theory', 'biodiversity', 'speciation', 'agents', 'species abundance'),
    references=('Bertin 2021', 'Hubbell 2001', 'Vallade and Houchmandzadeh 2003'),
    defaults={'until': 500},
    observables=lambda system: [
        ObservableSpec('richness', group='community', variable='species', reduce=_richness),
    ],
)
def neutral_biodiversity(
    individuals: int = 200,
    *,
    nu: float = 0.01,
    species: int = 1,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return a neutral community of constant size, where species arise by speciation and vanish by drift.

    Every species is transient, yet the number of species settles around `S_N = sum_n theta / (theta + n)` for `n`
    from 0 to `N - 1`, with `theta = (N - 1) nu / (1 - nu)`, and the mean number of species of `k` individuals around
    `phi_k = theta / k prod_j (N - j + 1) / (N - j + theta)` for `j` from 1 to `k`.

    Args:
        individuals:
            The number of individuals `N`.

        nu:
            The probability that an offspring founds a new species.

        species:
            The initial number of species, to which the individuals belong at random.

        random_state:
            The seed or generator of the initial species.

    Returns:
        system:
            The system, with the group `community` and the number `richness` of species.

    Examples:
        >>> from skcomplex.systems.biology.ecology import neutral_biodiversity
        >>> neutral_biodiversity(20).elements[0].prepare().size_
        20
    """
    labels = np.random.default_rng(random_state).integers(species, size=individuals).astype(float)
    return System(
        elements=[GroupElement('community', element=OrganismElement, size=individuals, values={'species': labels})],
        interactions=[NeutralReplacementInteraction('replacement', target='community', mutation=nu)],
    )

neutral_clustering(shape=64, *, n=10.0, alpha=1.0, beta=0.5)

Return organisms that divide, die, and hop between patches on a periodic lattice, and gather in clusters.

Births balance deaths, so the mean number of organisms per patch stays n while its variance grows. Without hops it grows as 2 alpha n t, so most patches empty while a few fill. Hops at the rate beta slow the growth to t^(1/2) in one dimension and ln t in two, so the clusters persist in low dimension although the mean density obeys a diffusion equation.

Parameters:

Name Type Description Default
shape int | Sequence[int]

The number of patches of a ring, or the shape of a periodic lattice of patches.

64
n float

The initial number of organisms in every patch.

10.0
alpha float

The rate at which an organism divides, equal to the rate at which it dies.

1.0
beta float

The rate at which an organism hops to one neighbouring patch.

0.5

Returns:

Name Type Description
system System

The system, with the numbers patches.n of organisms on the lattice patches, and their mean mean and variance variance over the patches.

Examples:

>>> from skcomplex.systems.biology.ecology import neutral_clustering
>>> neutral_clustering(8).elements[0].prepare().size_
8
Source code in src/skcomplex/systems/biology/ecology/_clustering.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
@register_system(
    field='biology/ecology',
    tags=('neutral theory', 'clustering', 'jump process', 'lattice', 'birth-death', 'diffusion'),
    references=('Bertin 2021', 'Houchmandzadeh 2002', 'Houchmandzadeh 2009'),
    defaults={'until': 50.0, 'dt': 0.5, 'backend': NumbaBackend()},
    observables=lambda system: [
        ObservableSpec('mean', group='patches', variable='n', reduce='mean'),
        ObservableSpec('variance', group='patches', variable='n', reduce='var'),
    ],
)
def neutral_clustering(
    shape: int | Sequence[int] = 64,
    *,
    n: float = 10.0,
    alpha: float = 1.0,
    beta: float = 0.5,
) -> System:
    """Return organisms that divide, die, and hop between patches on a periodic lattice, and gather in clusters.

    Births balance deaths, so the mean number of organisms per patch stays `n` while its variance grows. Without hops it
    grows as `2 alpha n t`, so most patches empty while a few fill. Hops at the rate `beta` slow the growth to
    `t^(1/2)` in one dimension and `ln t` in two, so the clusters persist in low dimension although the mean density
    obeys a diffusion equation.

    Args:
        shape:
            The number of patches of a ring, or the shape of a periodic lattice of patches.

        n:
            The initial number of organisms in every patch.

        alpha:
            The rate at which an organism divides, equal to the rate at which it dies.

        beta:
            The rate at which an organism hops to one neighbouring patch.

    Returns:
        system:
            The system, with the numbers `patches.n` of organisms on the lattice `patches`, and their mean `mean` and
            variance `variance` over the patches.

    Examples:
        >>> from skcomplex.systems.biology.ecology import neutral_clustering
        >>> neutral_clustering(8).elements[0].prepare().size_
        8
    """
    lattice = (shape,) if isinstance(shape, int) else tuple(shape)
    patches = LatticeElement(
        'patches',
        element=HabitatPatchElement,
        space=LatticeSpace(lattice),
        values={'n': np.full(lattice, float(n)), 'alpha': alpha},
    )
    members = [f'patches[{index}]' for index in range(int(np.prod(lattice)))]
    interactions: list[BaseInteraction] = [
        JumpInteraction('division', target='patches', changes={'n': 1}, rate=lambda s: s.target.alpha * s.target.n),
        JumpInteraction('death', target='patches', changes={'n': -1}, rate=lambda s: s.target.alpha * s.target.n),
    ]
    if beta:
        interactions.append(HoppingInteraction('hopping', patches=members, links=_neighbor_pairs(lattice), beta=beta))
    return System(
        elements=[patches],
        interactions=interactions,
    )

neutral_macroecology(species=100, n=10.0, *, b0=1.0, b1=0.9, d0=0.0, d1=1.0)

Return many species under neutral birth, death, and immigration, whose abundances follow a gamma-like law.

Without emigration, d0 = 0, the abundances settle on the negative binomial distribution of mean b0 / (d1 - b1), the discrete form of the gamma distribution that the Fokker-Planck equation of macroecology predicts and that fits the abundances of tropical trees.

Parameters:

Name Type Description Default
species int

The number of species.

100
n float

The initial number of individuals of every species.

10.0
b0 float

The rate of immigration or speciation.

1.0
b1 float

The per capita birth rate.

0.9
d0 float

The rate of emigration or extinction.

0.0
d1 float

The per capita death rate, above b1.

1.0

Returns:

Name Type Description
system System

The system, with the abundances species.n.

Examples:

>>> from skcomplex.systems.biology.ecology import neutral_macroecology
>>> neutral_macroecology(20).elements[0].prepare().size_
20
Source code in src/skcomplex/systems/biology/ecology/_neutral.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
@register_system(
    field='biology/ecology',
    tags=('macroecology', 'neutral theory', 'jump process', 'species abundance'),
    references=('Hubbell 2001', 'Volkov et al. 2003', 'Gros 2015'),
    defaults={'until': 100.0, 'dt': 1.0},
)
def neutral_macroecology(
    species: int = 100,
    n: float = 10.0,
    *,
    b0: float = 1.0,
    b1: float = 0.9,
    d0: float = 0.0,
    d1: float = 1.0,
) -> System:
    """Return many species under neutral birth, death, and immigration, whose abundances follow a gamma-like law.

    Without emigration, `d0 = 0`, the abundances settle on the negative binomial distribution of mean
    `b0 / (d1 - b1)`, the discrete form of the gamma distribution that the Fokker-Planck equation of macroecology
    predicts and that fits the abundances of tropical trees.

    Args:
        species:
            The number of species.

        n:
            The initial number of individuals of every species.

        b0:
            The rate of immigration or speciation.

        b1:
            The per capita birth rate.

        d0:
            The rate of emigration or extinction.

        d1:
            The per capita death rate, above `b1`.

    Returns:
        system:
            The system, with the abundances `species.n`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import neutral_macroecology
        >>> neutral_macroecology(20).elements[0].prepare().size_
        20
    """
    return System(
        elements=[
            GroupElement(
                'species',
                element=NeutralSpeciesElement,
                size=species,
                values={'n': n, 'b0': b0, 'b1': b1, 'd0': d0, 'd1': d1},
            ),
        ],
        interactions=[
            JumpInteraction(
                'birth',
                target='species',
                changes={'n': 1},
                rate=lambda s: s.target.b0 + s.target.b1 * s.target.n,
            ),
            JumpInteraction(
                'death',
                target='species',
                changes={'n': -1},
                rate=lambda s: where(s.target.n > 0, s.target.d0, 0) + s.target.d1 * s.target.n,
            ),
        ],
    )

nicholson_bailey(hosts=25.0, parasitoids=10.0, *, k=2.0, a=0.05, c=1.0)

Return hosts and parasitoids in discrete generations, whose equilibrium is unstable to growing oscillations.

The equilibrium is H = k ln k / ((k - 1) a c) and P = ln k / a.

Parameters:

Name Type Description Default
hosts float

The initial number of hosts.

25.0
parasitoids float

The initial number of parasitoids.

10.0
k float

The reproductive rate of the hosts.

2.0
a float

The searching efficiency of the parasitoids.

0.05
c float

The number of viable eggs a parasitoid lays in a host.

1.0

Returns:

Name Type Description
system System

The system, with the populations hosts and parasitoids.

Examples:

>>> from skcomplex.systems.biology.ecology import nicholson_bailey
>>> nicholson_bailey(k=3.0).interactions[0].k
3.0
Source code in src/skcomplex/systems/biology/ecology/_predation.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
@register_system(
    field='biology/ecology',
    tags=('host-parasitoid', 'discrete map', 'oscillation'),
    references=('Nicholson and Bailey 1935', 'Argun et al. 2021'),
    defaults={'until': 30, 'dt': 1},
)
def nicholson_bailey(
    hosts: float = 25.0,
    parasitoids: float = 10.0,
    *,
    k: float = 2.0,
    a: float = 0.05,
    c: float = 1.0,
) -> System:
    """Return hosts and parasitoids in discrete generations, whose equilibrium is unstable to growing oscillations.

    The equilibrium is `H = k ln k / ((k - 1) a c)` and `P = ln k / a`.

    Args:
        hosts:
            The initial number of hosts.

        parasitoids:
            The initial number of parasitoids.

        k:
            The reproductive rate of the hosts.

        a:
            The searching efficiency of the parasitoids.

        c:
            The number of viable eggs a parasitoid lays in a host.

    Returns:
        system:
            The system, with the populations `hosts` and `parasitoids`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import nicholson_bailey
        >>> nicholson_bailey(k=3.0).interactions[0].k
        3.0
    """
    return System(
        elements=[PopulationElement('hosts', n=hosts), PopulationElement('parasitoids', n=parasitoids)],
        interactions=[ParasitismInteraction('parasitism', host='hosts', parasitoid='parasitoids', k=k, a=a, c=c)],
    )

penaeid_shrimp(gut=0.5, biomass=1.0, *, ration=2.5, respiration=0.05, L_inf=29.9, K=0.013)

Return the growth of one penaeid shrimp from the juvenile stage, forced by the food and the water temperature.

The individual ingests food up to a maximum ration set by its biomass and the water temperature, assimilates its gut content, respires, and spawns, while its gonads grow and its carapace length follows von Bertalanffy's curve L(t) = L_inf (1 - exp(-K t)) from zero, which nears its asymptote after six to eight months. The gut content settles near I / A_e, the ingestion over the assimilation efficiency.

The coefficients are those of the listing of Bala et al. (2017). With them the respiration of a juvenile at 28 C, respiration exp(0.07 T) (phi B)^0.185, is about half its biomass per day, more than its maximum ration, so the total biomass declines slowly while the gonads and the length grow. The weight gain the source describes needs a lower respiration coefficient, such as 0.02.

Parameters:

Name Type Description Default
gut float

The initial gut content, in grams of dry weight.

0.5
biomass float

The initial total biomass, in grams of dry weight.

1.0
ration float

The factor of the maximum ration, lower for males.

2.5
respiration float

The coefficient of the weight-specific respiration, per day.

0.05
L_inf float

The asymptotic carapace length, in millimetres.

29.9
K float

The growth coefficient of the length, per day.

0.013

Returns:

Name Type Description
system System

The system, with the states shrimp.gut, shrimp.biomass, shrimp.gonads, and shrimp.length.

Examples:

>>> from skcomplex.systems.biology.ecology import penaeid_shrimp
>>> penaeid_shrimp().elements[0].K
0.013
Source code in src/skcomplex/systems/biology/ecology/_factories.py
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
@register_system(
    field='biology/ecology',
    tags=('individual growth', 'bioenergetics', 'aquaculture', 'stocks and flows', 'ode'),
    references=('Franco et al. 2006', 'Bala et al. 2017'),
    defaults={'until': 60.0, 'dt': 0.5},
)
def penaeid_shrimp(
    gut: float = 0.5,
    biomass: float = 1.0,
    *,
    ration: float = 2.5,
    respiration: float = 0.05,
    L_inf: float = 29.9,
    K: float = 0.013,
) -> System:
    """Return the growth of one penaeid shrimp from the juvenile stage, forced by the food and the water temperature.

    The individual ingests food up to a maximum ration set by its biomass and the water temperature, assimilates its
    gut content, respires, and spawns, while its gonads grow and its carapace length follows von Bertalanffy's curve
    `L(t) = L_inf (1 - exp(-K t))` from zero, which nears its asymptote after six to eight months. The gut content
    settles near `I / A_e`, the ingestion over the assimilation efficiency.

    The coefficients are those of the listing of Bala et al. (2017). With them the respiration of a juvenile at 28 C,
    `respiration exp(0.07 T) (phi B)^0.185`, is about half its biomass per day, more than its maximum ration, so the
    total biomass declines slowly while the gonads and the length grow. The weight gain the source describes needs a
    lower `respiration` coefficient, such as 0.02.

    Args:
        gut:
            The initial gut content, in grams of dry weight.

        biomass:
            The initial total biomass, in grams of dry weight.

        ration:
            The factor of the maximum ration, lower for males.

        respiration:
            The coefficient of the weight-specific respiration, per day.

        L_inf:
            The asymptotic carapace length, in millimetres.

        K:
            The growth coefficient of the length, per day.

    Returns:
        system:
            The system, with the states `shrimp.gut`, `shrimp.biomass`, `shrimp.gonads`, and `shrimp.length`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import penaeid_shrimp
        >>> penaeid_shrimp().elements[0].K
        0.013
    """
    return System(
        elements=[
            ShrimpElement(
                'shrimp',
                gut=gut,
                biomass=biomass,
                ration=ration,
                respiration=respiration,
                L_inf=L_inf,
                K=K,
            ),
        ],
    )

ricker(n=0.5, *, r=2.0)

Return Ricker's map of a population in discrete generations, n' = r n exp(-n), chaotic for large r.

The positive fixed point n = ln r is stable while 1 < r < e^2. Beyond e^2, about 7.39, it loses stability to a two-cycle, and further period doublings lead to chaos near r = 14.8. The size stays positive for every r.

Parameters:

Name Type Description Default
n float

The initial size, in units of the density at which the offspring peak.

0.5
r float

The growth factor at low density.

2.0

Returns:

Name Type Description
system System

The system, with the population population.n.

Examples:

>>> from skcomplex.systems.biology.ecology import ricker
>>> ricker(r=12.0).interactions[0].r
12.0
Source code in src/skcomplex/systems/biology/ecology/_factories.py
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
@register_system(
    field='biology/ecology',
    tags=('population', 'discrete map', 'period doubling', 'chaos'),
    references=('Ricker 1954', 'Dilão 2023'),
    defaults={'until': 100, 'dt': 1},
)
def ricker(n: float = 0.5, *, r: float = 2.0) -> System:
    """Return Ricker's map of a population in discrete generations, `n' = r n exp(-n)`, chaotic for large `r`.

    The positive fixed point `n = ln r` is stable while `1 < r < e^2`. Beyond `e^2`, about 7.39, it loses stability to
    a two-cycle, and further period doublings lead to chaos near `r = 14.8`. The size stays positive for every `r`.

    Args:
        n:
            The initial size, in units of the density at which the offspring peak.

        r:
            The growth factor at low density.

    Returns:
        system:
            The system, with the population `population.n`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import ricker
        >>> ricker(r=12.0).interactions[0].r
        12.0
    """
    return System(
        elements=[PopulationElement('population', n=n)],
        interactions=[RickerGrowthInteraction('growth', target='population', r=r)],
    )

rosenzweig_macarthur(prey=None, predators=None, *, kappa=0.01, eta=0.8, phi=None, phi_end=None, rate=0.002)

Return fast prey and slow predators whose carrying capacity shrinks at a rate, which tips them when it is fast.

By default the crowding rises from eta (1 - eta) / (1 + eta) to 1 - eta, the range where the coexistence point at x = 1 / (1 - eta) is stable, and the run starts there. A slow rise lets the populations track the point, and a rise faster than about 0.0004 makes the prey collapse for a while before they return.

In a collapse the prey fall to about 1e-30, far below any absolute tolerance, and an error of either sign there decides whether they return or, below zero, run into the pole of the feeding at x = -1 / eta. The registered solver therefore controls the relative error only, with ScipyODESolver(rtol=1e-8, atol=1e-300).

Parameters:

Name Type Description Default
prey float | None

The initial prey x, or None for the coexistence point.

None
predators float | None

The initial predators y, or None for the coexistence point.

None
kappa float

The ratio of the time scales of the prey and the predators.

0.01
eta float

The handling time of the predators.

0.8
phi float | None

The initial crowding, or None for eta (1 - eta) / (1 + eta).

None
phi_end float | None

The final crowding, or None for 1 - eta.

None
rate float

The rate at which the crowding rises.

0.002

Returns:

Name Type Description
system System

The system, with the populations prey and predators.

Examples:

>>> from skcomplex.systems.biology.ecology import rosenzweig_macarthur
>>> round(rosenzweig_macarthur().elements[0].n, 6)
5.0
Source code in src/skcomplex/systems/biology/ecology/_predation.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
@register_system(
    field='biology/ecology',
    tags=('predator-prey', 'ode', 'tipping', 'rate-induced tipping', 'slow-fast'),
    references=('Rosenzweig and MacArthur 1963', 'Datseris and Parlitz 2022'),
    defaults={'until': 150.0, 'dt': 0.5, 'solver': ScipyODESolver(rtol=1e-8, atol=1e-300)},
)
def rosenzweig_macarthur(
    prey: float | None = None,
    predators: float | None = None,
    *,
    kappa: float = 0.01,
    eta: float = 0.8,
    phi: float | None = None,
    phi_end: float | None = None,
    rate: float = 0.002,
) -> System:
    """Return fast prey and slow predators whose carrying capacity shrinks at a rate, which tips them when it is fast.

    By default the crowding rises from `eta (1 - eta) / (1 + eta)` to `1 - eta`, the range where the coexistence point
    at `x = 1 / (1 - eta)` is stable, and the run starts there. A slow rise lets the populations track the point, and a
    rise faster than about 0.0004 makes the prey collapse for a while before they return.

    In a collapse the prey fall to about `1e-30`, far below any absolute tolerance, and an error of either sign there
    decides whether they return or, below zero, run into the pole of the feeding at `x = -1 / eta`. The registered
    solver therefore controls the relative error only, with `ScipyODESolver(rtol=1e-8, atol=1e-300)`.

    Args:
        prey:
            The initial prey `x`, or `None` for the coexistence point.

        predators:
            The initial predators `y`, or `None` for the coexistence point.

        kappa:
            The ratio of the time scales of the prey and the predators.

        eta:
            The handling time of the predators.

        phi:
            The initial crowding, or `None` for `eta (1 - eta) / (1 + eta)`.

        phi_end:
            The final crowding, or `None` for `1 - eta`.

        rate:
            The rate at which the crowding rises.

    Returns:
        system:
            The system, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import rosenzweig_macarthur
        >>> round(rosenzweig_macarthur().elements[0].n, 6)
        5.0
    """
    phi = eta * (1 - eta) / (1 + eta) if phi is None else phi
    phi_end = 1 - eta if phi_end is None else phi_end
    prey = 1 / (1 - eta) if prey is None else prey
    predators = (1 - phi * prey) * (1 + eta * prey) if predators is None else predators
    return System(
        elements=[PopulationElement('prey', n=prey), PopulationElement('predators', n=predators)],
        interactions=[
            RosenzweigMacArthurInteraction(
                'predation',
                prey='prey',
                predators='predators',
                kappa=kappa,
                eta=eta,
                phi=phi,
                phi_end=phi_end,
                rate=rate,
            ),
        ],
    )

sequentially_linear_ecosystem(n=60, k=4, *, rate=0.2, threshold=0.001, seed=1)

Return an ecosystem whose abundances follow linear dynamics between extinctions that rewrite its network.

Every species reads k random species through influences of random sign and strength, and grows linearly with their abundances. Between extinctions the dynamics is linear, so the abundances approach the dominant eigenvector of the current network. A species whose abundance falls below threshold goes extinct with its influences, and a new species with k random influences takes its place, which changes the network and starts a new linear stretch. Extinctions come in bursts separated by quiet periods.

Parameters:

Name Type Description Default
n int

The number of species.

60
k int

The number of species every species reads.

4
rate float

The growth per step per unit of influence.

0.2
threshold float

The abundance below which a species goes extinct.

0.001
seed int | None

The seed of the network and of the initial strengths.

1

Returns:

Name Type Description
system System

The system, with the abundances species.x and ages species.age of the variable group species and the strengths influences.w of the variable group influences on the edges.

Examples:

>>> from skcomplex.systems.biology.ecology import sequentially_linear_ecosystem
>>> [component.label for component in sequentially_linear_ecosystem(n=10).elements]
['species', 'influences']
Source code in src/skcomplex/systems/biology/ecology/_sequential.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
@register_system(
    field='biology/ecology',
    tags=('adaptive network', 'extinction', 'diversity', 'linear dynamics', 'stochastic map'),
    references=('Thurner et al. 2018', 'Thurner, Klimek, and Hanel 2010'),
    defaults={'until': 300, 'dt': 1.0},
)
def sequentially_linear_ecosystem(
    n: int = 60,
    k: int = 4,
    *,
    rate: float = 0.2,
    threshold: float = 1e-3,
    seed: int | None = 1,
) -> System:
    """Return an ecosystem whose abundances follow linear dynamics between extinctions that rewrite its network.

    Every species reads `k` random species through influences of random sign and strength, and grows linearly with
    their abundances. Between extinctions the dynamics is linear, so the abundances approach the dominant eigenvector
    of the current network. A species whose abundance falls below `threshold` goes extinct with its influences, and a
    new species with `k` random influences takes its place, which changes the network and starts a new linear stretch.
    Extinctions come in bursts separated by quiet periods.

    Args:
        n:
            The number of species.

        k:
            The number of species every species reads.

        rate:
            The growth per step per unit of influence.

        threshold:
            The abundance below which a species goes extinct.

        seed:
            The seed of the network and of the initial strengths.

    Returns:
        system:
            The system, with the abundances `species.x` and ages `species.age` of the variable group `species` and the
            strengths `influences.w` of the variable group `influences` on the edges.

    Examples:
        >>> from skcomplex.systems.biology.ecology import sequentially_linear_ecosystem
        >>> [component.label for component in sequentially_linear_ecosystem(n=10).elements]
        ['species', 'influences']
    """
    rng = np.random.default_rng(seed)
    graph = nx.DiGraph()
    graph.add_nodes_from(range(n))
    for node in range(n):
        others = rng.choice(np.delete(np.arange(n), node), size=k, replace=False)
        graph.add_edges_from((node, int(other)) for other in others)
    space = NetworkSpace(graph)
    edges = graph.number_of_edges()
    species = GroupElement(
        'species',
        element=AbundanceElement,
        space=space,
        on='sites',
        variable=True,
        capacity=2 * n,
        values={'x': np.full(n, 1 / n), 'threshold': threshold},
        visual=VisualSpec('sites', {'states': ['x']}),
    )
    influences = GroupElement(
        'influences',
        element=WeightedEdgeElement,
        space=space,
        on='edges',
        variable=True,
        capacity=4 * edges,
        values={'w': rng.uniform(-1, 1, edges), 'fresh': 0.0},
        visual=HIDDEN,
    )
    return System(
        elements=[species, influences],
        interactions=[
            LinearGrowthInteraction('growth', species='species', influences='influences', rate=rate),
            EdgeDrawInteraction('draw', target='species', edges='influences'),
            MapInteraction('ageing', target='species', state='age', function=lambda s: 1, mode='increment'),
            TopologyInteraction(
                'extinction',
                target='species',
                action='replace-node',
                condition=lambda s: s.source.x < s.source.threshold,
                edges=k,
            ),
        ],
        time=DiscreteTime(),
    )

stigmergic_predator_prey(width=30, height=30, *, plants=300, prey=120, predators=20, emotions=True, decay=0.2, random_state=0)

Return plants, prey, and predators on a grid, whose animals share emotions through decaying marks.

Every cell holds at most one organism. Prey eat plants and fear predators, and predators eat prey and grow angry with hunger. Happiness draws animals of the same kind towards the cells where it was marked and distress drives them away, a trail stigmergy of emotions that the cellular automaton of Olsen in Carmichael and Hadžikadić (2019) uses to study cooperation within each species.

Parameters:

Name Type Description Default
width int

The number of columns of the torus.

30
height int

The number of rows of the torus.

30
plants int

The initial number of plants.

300
prey int

The initial number of prey.

120
predators int

The initial number of predators.

20
emotions bool

Whether emotions guide the animals.

True
decay float

The rate at which the marks decay.

0.2
random_state int | Generator | None

The seed or generator of the initial cells.

0

Returns:

Name Type Description
system System

The system, with the groups life/plants, life/prey, and life/predators, and the marks ground/marks.

Examples:

>>> from skcomplex.systems.biology.ecology import stigmergic_predator_prey
>>> [child.label for child in stigmergic_predator_prey(10, 10, plants=20, prey=10, predators=5).systems]
['life', 'ground']
Source code in src/skcomplex/systems/biology/ecology/_stigmergy.py
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
@register_system(
    field='biology/ecology',
    tags=('predator-prey', 'agents', 'stigmergy', 'emotions', 'co-simulation'),
    references=('Carmichael and Hadžikadić 2019', 'Olsen 2019'),
    defaults={'until': 100, 'dt': 1},
)
def stigmergic_predator_prey(
    width: int = 30,
    height: int = 30,
    *,
    plants: int = 300,
    prey: int = 120,
    predators: int = 20,
    emotions: bool = True,
    decay: float = 0.2,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return plants, prey, and predators on a grid, whose animals share emotions through decaying marks.

    Every cell holds at most one organism. Prey eat plants and fear predators, and predators eat prey and grow angry
    with hunger. Happiness draws animals of the same kind towards the cells where it was marked and distress drives
    them away, a trail stigmergy of emotions that the cellular automaton of Olsen in Carmichael and Hadžikadić (2019)
    uses to study cooperation within each species.

    Args:
        width:
            The number of columns of the torus.

        height:
            The number of rows of the torus.

        plants:
            The initial number of plants.

        prey:
            The initial number of prey.

        predators:
            The initial number of predators.

        emotions:
            Whether emotions guide the animals.

        decay:
            The rate at which the marks decay.

        random_state:
            The seed or generator of the initial cells.

    Returns:
        system:
            The system, with the groups `life/plants`, `life/prey`, and `life/predators`, and the marks
            `ground/marks`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import stigmergic_predator_prey
        >>> [child.label for child in stigmergic_predator_prey(10, 10, plants=20, prey=10, predators=5).systems]
        ['life', 'ground']
    """
    rng = np.random.default_rng(random_state)
    plant_cells, prey_cells, predator_cells = _random_cells(rng, width, height, [plants, prey, predators])
    flag = float(emotions)
    life = System(
        'life',
        elements=[
            GroupElement(
                PLANTS,
                element=PlantElement,
                size=plants,
                values={'age': rng.integers(0, 4, plants).astype(float)},
                variable=True,
                location=plant_cells,
            ),
            GroupElement(
                PREY,
                element=StigmergicPreyElement,
                size=prey,
                values={'emotions': flag, **PREY_TRAITS},
                variable=True,
                location=prey_cells,
            ),
            GroupElement(
                PREDATORS,
                element=StigmergicPredatorElement,
                size=predators,
                values={'emotions': flag, **PREDATOR_TRAITS},
                variable=True,
                location=predator_cells,
            ),
        ],
        space=LatticeSpace((width, height), boundary='periodic'),
    )
    marks = FieldElement(
        'marks',
        element=EmotionMarksElement,
        space=LatticeSpace((width, height)),
        values={'decay': decay},
    )
    evaporations = [
        EvaporationInteraction(f'evaporation_{mark}', target='marks', state=mark, evaporation='decay')
        for mark in EMOTIONS
    ]
    return System(
        systems=[life, System('ground', elements=[marks], interactions=evaporations)],
        interactions=[
            *_get_plants('life', PLANTS),
            *_get_animals('life', PREY, StigmergicPreyElement, _get_fear),
            *_get_animals('life', PREDATORS, StigmergicPredatorElement, _get_anger),
        ],
    )

stochastic_predator_prey(prey=200.0, predators=200.0, *, r=1.0, K=600.0, a=0.005, h=0.5, e=0.5, m=0.3, stochastic=True)

Return prey and predators born and killed one at a time, with crowding of the prey and saturating predation.

The deterministic limit has the coexistence point x = m / (a (e - m h)). It is stable while K < 2 x + 1 / (a h), and enriching the prey beyond that turns it into large cycles, which demographic noise drives to extinction.

Parameters:

Name Type Description Default
prey float

The initial number of prey.

200.0
predators float

The initial number of predators.

200.0
r float

The birth rate of the prey.

1.0
K float

The carrying capacity of the prey.

600.0
a float

The attack rate.

0.005
h float

The handling time.

0.5
e float

The number of predators born per prey eaten.

0.5
m float

The death rate of the predators.

0.3
stochastic bool

Whether births, deaths, and kills are random events.

True

Returns:

Name Type Description
system System

The system, with the populations prey and predators.

Examples:

>>> from skcomplex.systems.biology.ecology import stochastic_predator_prey
>>> stochastic_predator_prey(K=1000.0).interactions[0].K
1000.0
Source code in src/skcomplex/systems/biology/ecology/_predation.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
@register_system(
    field='biology/ecology',
    tags=('predator-prey', 'jump process', 'gillespie', 'paradox of enrichment'),
    references=('Carmichael and Hadžikadić 2019', 'Rosenzweig 1971'),
    defaults={'until': 100.0, 'dt': 0.5},
)
def stochastic_predator_prey(
    prey: float = 200.0,
    predators: float = 200.0,
    *,
    r: float = 1.0,
    K: float = 600.0,
    a: float = 0.005,
    h: float = 0.5,
    e: float = 0.5,
    m: float = 0.3,
    stochastic: bool = True,
) -> System:
    """Return prey and predators born and killed one at a time, with crowding of the prey and saturating predation.

    The deterministic limit has the coexistence point `x = m / (a (e - m h))`. It is stable while
    `K < 2 x + 1 / (a h)`, and enriching the prey beyond that turns it into large cycles, which demographic noise drives
    to extinction.

    Args:
        prey:
            The initial number of prey.

        predators:
            The initial number of predators.

        r:
            The birth rate of the prey.

        K:
            The carrying capacity of the prey.

        a:
            The attack rate.

        h:
            The handling time.

        e:
            The number of predators born per prey eaten.

        m:
            The death rate of the predators.

        stochastic:
            Whether births, deaths, and kills are random events.

    Returns:
        system:
            The system, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import stochastic_predator_prey
        >>> stochastic_predator_prey(K=1000.0).interactions[0].K
        1000.0
    """
    return System(
        elements=[PopulationElement('prey', n=prey), PopulationElement('predators', n=predators)],
        interactions=[
            PredatorPreyEventsInteraction(
                'events',
                prey='prey',
                predators='predators',
                r=r,
                K=K,
                a=a,
                h=h,
                e=e,
                m=m,
                stochastic=stochastic,
            ),
        ],
    )

varying_capacity_logistic(n=10.0, *, r=2.0, K=100.0, amplitude=0.5, period=1.0)

Return logistic growth under a seasonal carrying capacity, which settles on a cycle of the season's period.

Whatever its initial size, the population tends to a unique periodic solution, which lags behind the capacity and varies less than it.

Parameters:

Name Type Description Default
n float

The initial size.

10.0
r float

The intrinsic growth rate.

2.0
K float

The mean carrying capacity.

100.0
amplitude float

The relative amplitude of the seasonal variation of the capacity, below 1.

0.5
period float

The period of the seasons.

1.0

Returns:

Name Type Description
system System

The system, with the population population.

Examples:

>>> from skcomplex.systems.biology.ecology import varying_capacity_logistic
>>> varying_capacity_logistic(amplitude=0.2).interactions[0].amplitude
0.2
Source code in src/skcomplex/systems/biology/ecology/_factories.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
@register_system(
    field='biology/ecology',
    tags=('population', 'ode', 'forcing', 'periodic'),
    references=('Coleman 1979', 'Trzaska 2023'),
    defaults={'until': 20.0, 'dt': 0.05},
)
def varying_capacity_logistic(
    n: float = 10.0,
    *,
    r: float = 2.0,
    K: float = 100.0,
    amplitude: float = 0.5,
    period: float = 1.0,
) -> System:
    """Return logistic growth under a seasonal carrying capacity, which settles on a cycle of the season's period.

    Whatever its initial size, the population tends to a unique periodic solution, which lags behind the capacity and
    varies less than it.

    Args:
        n:
            The initial size.

        r:
            The intrinsic growth rate.

        K:
            The mean carrying capacity.

        amplitude:
            The relative amplitude of the seasonal variation of the capacity, below 1.

        period:
            The period of the seasons.

    Returns:
        system:
            The system, with the population `population`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import varying_capacity_logistic
        >>> varying_capacity_logistic(amplitude=0.2).interactions[0].amplitude
        0.2
    """
    return System(
        elements=[PopulationElement('population', n=n)],
        interactions=[
            SeasonalLogisticGrowthInteraction(
                'growth',
                target='population',
                r=r,
                K=K,
                amplitude=amplitude,
                period=period,
            ),
        ],
    )

wolf_sheep(width=20, height=20, *, sheep=100, wolves=25, regrowth=30.0, random_state=0)

Return the wolf and sheep predation system with one grass patch per cell.

Parameters:

Name Type Description Default
width int

The number of columns.

20
height int

The number of rows.

20
sheep int

The initial number of sheep.

100
wolves int

The initial number of wolves.

25
regrowth float

The number of steps grass takes to regrow.

30.0
random_state int | Generator | None

The seed or generator of the initial grass state.

0

Returns:

Name Type Description
system System

The system, with the groups grass, sheep, and wolves.

Examples:

>>> from skcomplex.systems.biology.ecology import wolf_sheep
>>> [group.label for group in wolf_sheep(10, 10).elements]
['grass', 'sheep', 'wolves']
Source code in src/skcomplex/systems/biology/ecology/_wolf_sheep.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
@register_system(
    field='biology/ecology',
    tags=('predator-prey', 'agents', 'grid'),
    references=('Wilensky 1997',),
    defaults={'until': 100},
)
def wolf_sheep(
    width: int = 20,
    height: int = 20,
    *,
    sheep: int = 100,
    wolves: int = 25,
    regrowth: float = 30.0,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return the wolf and sheep predation system with one grass patch per cell.

    Args:
        width:
            The number of columns.

        height:
            The number of rows.

        sheep:
            The initial number of sheep.

        wolves:
            The initial number of wolves.

        regrowth:
            The number of steps grass takes to regrow.

        random_state:
            The seed or generator of the initial grass state.

    Returns:
        system:
            The system, with the groups `grass`, `sheep`, and `wolves`.

    Examples:
        >>> from skcomplex.systems.biology.ecology import wolf_sheep
        >>> [group.label for group in wolf_sheep(10, 10).elements]
        ['grass', 'sheep', 'wolves']
    """
    rng = np.random.default_rng(random_state)
    cells = [(column, row) for column in range(width) for row in range(height)]
    grown = (rng.random(len(cells)) < GROWN_SHARE).astype(float)
    countdown = np.where(grown > 0, regrowth, rng.uniform(0, regrowth, len(cells)))
    grass = GroupElement(
        'grass',
        element=GrassElement,
        size=len(cells),
        values={'grown': grown, 'countdown': countdown, 'regrowth': regrowth},
        variable=True,
        location=cells,
    )
    return System(
        elements=[
            grass,
            GroupElement('sheep', element=SheepElement, size=sheep, variable=True),
            GroupElement('wolves', element=WolfElement, size=wolves, variable=True),
        ],
        interactions=[*_get_animal('sheep', 'grass', removed=False), *_get_animal('wolves', 'sheep', removed=True)],
        space=LatticeSpace((width, height), boundary='periodic'),
    )