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.models.biology.ecology import AbundanceElement
>>> AbundanceElement('species').threshold
0.001
Source code in src/skcomplex/models/biology/ecology/_abundance.py
40
41
42
43
44
45
46
47
48
49
50
51
52
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.models.biology.ecology import CompetitionInteraction
>>> CompetitionInteraction('competition', first='deer', second='elk', alpha12=0.5).alpha12
0.5
Source code in src/skcomplex/models/biology/ecology/_competition.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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

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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import CowElement
>>> GroupElement('cows', element=CowElement, size=10).size
10
Source code in src/skcomplex/models/biology/ecology/_cow.py
36
37
38
39
40
41
42
43
44
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 model 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.models.biology.ecology import EmotionMarksElement
>>> EmotionMarksElement('marks').decay
0.2
Source code in src/skcomplex/models/biology/ecology/_emotion_marks.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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.models.biology.ecology import FisherKPPElement
>>> FisherKPPElement('site', u=0.5).u
0.5
Source code in src/skcomplex/models/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 model 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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import StigmergicPreyElement
>>> GroupElement('prey', element=StigmergicPreyElement, size=10).size
10
Source code in src/skcomplex/models/biology/ecology/_forager.py
 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
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.models.biology.ecology import GeneralizedLotkaVolterraInteraction
>>> matrix = ((-1.0, 0.5), (0.5, -1.0))
>>> GeneralizedLotkaVolterraInteraction('glv', target='species', a=matrix).check().a
((-1.0, 0.5), (0.5, -1.0))
Source code in src/skcomplex/models/biology/ecology/_generalized_lotka_volterra.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import GrassElement
>>> GroupElement('grass', element=GrassElement, size=4, values={'grown': 1.0}).size
4
Source code in src/skcomplex/models/biology/ecology/_grass.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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, model)

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

Parameters:

Name Type Description Default
agent GrassView

The patch.

required
model ModelView

The model.

required
Source code in src/skcomplex/models/biology/ecology/_grass.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def regrow(self, agent: GrassView, model: ModelView) -> None:
    """Count down eaten grass and grow it back when the countdown ends.

    Args:
        agent:
            The patch.

        model:
            The model.
    """
    del model
    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.models.biology.ecology import GrazingInteraction
>>> GrazingInteraction('grazing', cows='cows', pasture='pasture').pasture
'pasture'
Source code in src/skcomplex/models/biology/ecology/_grazing.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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.models.biology.ecology import HabitatPatchElement
>>> HabitatPatchElement('patch', n=5.0).alpha
1.0
Source code in src/skcomplex/models/biology/ecology/_habitat_patch.py
40
41
42
43
44
45
46
47
48
49
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.models.biology.ecology import HerdingInteraction
>>> HerdingInteraction('herding', cows='cows', pasture='pasture').threshold
0.9
Source code in src/skcomplex/models/biology/ecology/_herding.py
44
45
46
47
48
49
50
51
52
53
54
55
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.models.biology.ecology import HoppingInteraction
>>> HoppingInteraction('hopping', patches=['a', 'b'], links=[(0, 1), (1, 0)]).beta
0.5
Source code in src/skcomplex/models/biology/ecology/_hopping.py
43
44
45
46
47
48
49
50
51
52
53
54
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.models.biology.ecology import LinearGrowthInteraction
>>> LinearGrowthInteraction('growth', species='species', influences='influences').rate
0.2
Source code in src/skcomplex/models/biology/ecology/_linear_growth.py
43
44
45
46
47
48
49
50
51
52
53
54
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.models.biology.ecology import MicrobeElement
>>> MicrobeElement('species', x=0.1, b=0.8).b
0.8
Source code in src/skcomplex/models/biology/ecology/_microbe.py
37
38
39
40
41
42
43
44
45
46
47
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.models.biology.ecology import MutualismInteraction
>>> MutualismInteraction('pollination', first='orchids', second='bees', handling=0.5).handling
0.5
Source code in src/skcomplex/models/biology/ecology/_mutualism.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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.models.biology.ecology import NeutralReplacementInteraction
>>> NeutralReplacementInteraction('replacement', target='community', mutation=0.01).check().change
'new'
Source code in src/skcomplex/models/biology/ecology/_neutral_replacement.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import NeutralSpeciesElement
>>> GroupElement('trees', element=NeutralSpeciesElement, size=50).size
50
Source code in src/skcomplex/models/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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import OrganismElement
>>> GroupElement('community', element=OrganismElement, size=10, values={'species': 0.0}).size
10
Source code in src/skcomplex/models/biology/ecology/_organism.py
37
38
39
40
41
42
43
44
45
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.models.biology.ecology import ParasitismInteraction
>>> ParasitismInteraction('parasitism', host='moths', parasitoid='wasps', k=2.0).k
2.0
Source code in src/skcomplex/models/biology/ecology/_parasitism.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import PastureElement
>>> GroupElement('pasture', element=PastureElement, size=4, values={'growth': 0.1}).size
4
Source code in src/skcomplex/models/biology/ecology/_pasture.py
42
43
44
45
46
47
48
49
50
51
52
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, model)

Grow the grass by one week of logistic growth.

Parameters:

Name Type Description Default
agent PastureView

The patch.

required
model ModelView

The model.

required
Source code in src/skcomplex/models/biology/ecology/_pasture.py
72
73
74
75
76
77
78
79
80
81
82
83
def regrow(self, agent: PastureView, model: ModelView) -> None:
    """Grow the grass by one week of logistic growth.

    Args:
        agent:
            The patch.

        model:
            The model.
    """
    del model
    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.models.biology.ecology import PioneerGrowthInteraction
>>> PioneerGrowthInteraction('growth', target='keora', intermediate='gewa', climax='sundari').half_time
3.65
Source code in src/skcomplex/models/biology/ecology/_pioneer_growth.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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 model 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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import PlantElement
>>> GroupElement('plants', element=PlantElement, size=100).size
100
Source code in src/skcomplex/models/biology/ecology/_plant.py
41
42
43
44
45
46
47
48
49
50
51
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.models.biology.ecology import PredationInteraction
>>> PredationInteraction('hunt', predator='foxes', prey='rabbits', a=0.4, b=0.1).prey
'rabbits'
Source code in src/skcomplex/models/biology/ecology/_predation_interaction.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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import PredatorElement
>>> GroupElement('foxes', element=PredatorElement, size=50).size
50
Source code in src/skcomplex/models/biology/ecology/_predator.py
46
47
48
49
50
51
52
53
54
55
56
57
58
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.models.biology.ecology import PredatorPreyEventsInteraction
>>> PredatorPreyEventsInteraction('events', prey='voles', predators='weasels', K=200.0).K
200.0
Source code in src/skcomplex/models/biology/ecology/_predator_prey_events.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import PreyElement
>>> GroupElement('rabbits', element=PreyElement, size=200).size
200
Source code in src/skcomplex/models/biology/ecology/_prey.py
39
40
41
42
43
44
45
46
47
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 model.

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.models.biology.ecology import QuotaPhytoplanktonElement
>>> QuotaPhytoplanktonElement('algae', R=2.0).R
2.0
Source code in src/skcomplex/models/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.models.biology.ecology import RabbitsElement
>>> RabbitsElement('rabbits', pairs=3.0).pairs
3.0
Source code in src/skcomplex/models/biology/ecology/_factories.py
276
277
278
279
280
281
282
283
284
285
286
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

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.models.biology.ecology import RosenzweigMacArthurInteraction
>>> RosenzweigMacArthurInteraction('predation', prey='prey', predators='predators', rate=0.01).rate
0.01
Source code in src/skcomplex/models/biology/ecology/_rosenzweig_macarthur.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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.models.biology.ecology import SeasonalLogisticGrowthInteraction
>>> SeasonalLogisticGrowthInteraction('growth', target='rabbits', period=12.0).period
12.0
Source code in src/skcomplex/models/biology/ecology/_seasonal_logistic_growth.py
44
45
46
47
48
49
50
51
52
53
54
55
56
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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import SheepElement
>>> GroupElement('sheep', element=SheepElement, size=100).size
100
Source code in src/skcomplex/models/biology/ecology/_sheep.py
46
47
48
49
50
51
52
53
54
55
56
57
58
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

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.models.biology.ecology import StandElement
>>> StandElement('keora', mature=196.11).mature
196.11
Source code in src/skcomplex/models/biology/ecology/_stand.py
37
38
39
40
41
42
43
44
45
46
47
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.models.biology.ecology import StigmergicPredatorElement
>>> StigmergicPredatorElement.food
'prey'
Source code in src/skcomplex/models/biology/ecology/_stigmergic_predator.py
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
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.models.biology.ecology import StigmergicPreyElement
>>> StigmergicPreyElement.food
'plants'
Source code in src/skcomplex/models/biology/ecology/_forager.py
 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
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.models.biology.ecology import SuccessionalGrowthInteraction
>>> SuccessionalGrowthInteraction('growth', target='gewa', first='gewa', second='sundari', g=0.1).g
0.1
Source code in src/skcomplex/models/biology/ecology/_successional_growth.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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.models.biology.ecology import TripletInteraction
>>> TripletInteraction('triplets', target='species', a=0.0, state='n').check().state
'n'
Source code in src/skcomplex/models/biology/ecology/_triplet.py
41
42
43
44
45
46
47
48
49
50
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.models.biology.ecology import UnstablePopulationsElement
>>> UnstablePopulationsElement('populations').p
0.001
Source code in src/skcomplex/models/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.elements import GroupElement
>>> from skcomplex.models.biology.ecology import WolfElement
>>> GroupElement('wolves', element=WolfElement, size=25).size
25
Source code in src/skcomplex/models/biology/ecology/_wolf.py
46
47
48
49
50
51
52
53
54
55
56
57
58
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 model, with the groups prey and predators.

Examples:

>>> from skcomplex.models.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/models/biology/ecology/_agent_predation.py
 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
@register_model(
    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 model, with the groups `prey` and `predators`.

    Examples:
        >>> from skcomplex.models.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'),
    )

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 model, with the populations first and second.

Examples:

>>> from skcomplex.models.biology.ecology import competition
>>> competition(alpha12=0.2).interactions[0].alpha12
0.2
Source code in src/skcomplex/models/biology/ecology/_communities.py
 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
@register_model(
    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 model, with the populations `first` and `second`.

    Examples:
        >>> from skcomplex.models.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,
            ),
        ],
    )

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 model, 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 model, 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 model, with the quota algae.Q and the biomass algae.P.

Examples:

>>> from skcomplex.models.biology.ecology import droop_cell_quota
>>> droop_cell_quota(R=4.0).elements[0].R
4.0
Source code in src/skcomplex/models/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_model(
    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 model, 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 model, 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 model, with the quota `algae.Q` and the biomass `algae.P`.

    Examples:
        >>> from skcomplex.models.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])

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 model, with the population population.

Examples:

>>> from skcomplex.models.biology.ecology import exponential_growth
>>> exponential_growth(r=0.2).interactions[0].r
0.2
Source code in src/skcomplex/models/biology/ecology/_factories.py
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
@register_model(
    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 model, with the population `population`.

    Examples:
        >>> from skcomplex.models.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 model, with the population rabbits.pairs and last month's rabbits.pairs_lag1.

Examples:

>>> from skcomplex.models.biology.ecology import fibonacci_rabbits
>>> fibonacci_rabbits().elements[0].pairs
1.0
Source code in src/skcomplex/models/biology/ecology/_factories.py
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
@register_model(
    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 model, with the population `rabbits.pairs` and last month's `rabbits.pairs_lag1`.

    Examples:
        >>> from skcomplex.models.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 model, with the density line.u.

Examples:

>>> from skcomplex.models.biology.ecology import fisher_kpp
>>> int(fisher_kpp(100, front=0.1).elements[0].values['u'].sum())
10
Source code in src/skcomplex/models/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_model(
    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 model, with the density `line.u`.

    Examples:
        >>> from skcomplex.models.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 model, with one population per species.

Examples:

>>> from skcomplex.models.biology.ecology import food_webs
>>> [element.label for element in food_webs().elements]
['frogs', 'mice', 'snakes', 'hawks']
Source code in src/skcomplex/models/biology/ecology/_communities.py
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
@register_model(
    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 model, with one population per species.

    Examples:
        >>> from skcomplex.models.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,
    )

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

Return the generalized Lotka-Volterra model 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 model, 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.models.biology.ecology import generalized_lotka_volterra
>>> generalized_lotka_volterra().elements[0].check().prepare().size_
3
Source code in src/skcomplex/models/biology/ecology/_microbial_communities.py
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
@register_model(
    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 model 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 model, 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.models.biology.ecology import generalized_lotka_volterra
        >>> generalized_lotka_volterra().elements[0].check().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 model, 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.models.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/models/biology/ecology/_higher_order.py
 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
@register_model(
    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 model, 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.models.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 model, with the population population.

Examples:

>>> from skcomplex.models.biology.ecology import hutchinson
>>> hutchinson(tau=1.0).interactions[0].tau
1.0
Source code in src/skcomplex/models/biology/ecology/_factories.py
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
@register_model(
    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 model, with the population `population`.

    Examples:
        >>> from skcomplex.models.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 model, with the populations populations.x and populations.y.

Examples:

>>> from skcomplex.models.biology.ecology import intrinsic_instability
>>> intrinsic_instability().elements[0].beta
0.01
Source code in src/skcomplex/models/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_model(
    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 model, with the populations `populations.x` and `populations.y`.

    Examples:
        >>> from skcomplex.models.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 model, with the population population.

Examples:

>>> from skcomplex.models.biology.ecology import logistic_growth
>>> logistic_growth(K=500.0).interactions[0].K
500.0
Source code in src/skcomplex/models/biology/ecology/_factories.py
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
@register_model(
    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 model, with the population `population`.

    Examples:
        >>> from skcomplex.models.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 model, with the populations prey and predators.

Examples:

>>> from skcomplex.models.biology.ecology import lotka_volterra
>>> [element.label for element in lotka_volterra().elements]
['prey', 'predators']
Source code in src/skcomplex/models/biology/ecology/_factories.py
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
@register_model(
    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 model, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.models.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 model, with the populations prey and predators.

Examples:

>>> from skcomplex.models.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/models/biology/ecology/_predation.py
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
@register_model(
    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 model, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.models.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 model, with the stands keora, gewa, and sundari.

Examples:

>>> from skcomplex.models.biology.ecology import mangrove_succession
>>> [element.mature for element in mangrove_succession().elements]
[196.11, 80.0, 320.0]
Source code in src/skcomplex/models/biology/ecology/_succession.py
14
15
16
17
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
@register_model(
    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 model, with the stands `keora`, `gewa`, and `sundari`.

    Examples:
        >>> from skcomplex.models.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 model, with the groups pasture and cows.

Examples:

>>> from skcomplex.models.biology.ecology import meadow_capacity
>>> [group.size for group in meadow_capacity(10, 10, cows=5).elements]
[100, 5]
Source code in src/skcomplex/models/biology/ecology/_meadow.py
 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
 97
 98
 99
100
101
102
@register_model(
    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 model, with the groups `pasture` and `cows`.

    Examples:
        >>> from skcomplex.models.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 model, with the populations first and second.

Examples:

>>> from skcomplex.models.biology.ecology import mutualism
>>> [interaction.label for interaction in mutualism().interactions]
['growth_first', 'growth_second', 'mutualism']
Source code in src/skcomplex/models/biology/ecology/_communities.py
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
@register_model(
    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 model, with the populations `first` and `second`.

    Examples:
        >>> from skcomplex.models.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 model, with the group community and the number richness of species.

Examples:

>>> from skcomplex.models.biology.ecology import neutral_biodiversity
>>> neutral_biodiversity(20).elements[0].check().prepare().size_
20
Source code in src/skcomplex/models/biology/ecology/_speciation.py
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
@register_model(
    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 model, with the group `community` and the number `richness` of species.

    Examples:
        >>> from skcomplex.models.biology.ecology import neutral_biodiversity
        >>> neutral_biodiversity(20).elements[0].check().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 model, with the numbers patches.n of organisms on the lattice patches, and their mean mean and variance variance over the patches.

Examples:

>>> from skcomplex.models.biology.ecology import neutral_clustering
>>> neutral_clustering(8).elements[0].check().prepare().size_
8
Source code in src/skcomplex/models/biology/ecology/_clustering.py
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_model(
    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 model, with the numbers `patches.n` of organisms on the lattice `patches`, and their mean `mean` and
            variance `variance` over the patches.

    Examples:
        >>> from skcomplex.models.biology.ecology import neutral_clustering
        >>> neutral_clustering(8).elements[0].check().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 model, with the abundances species.n.

Examples:

>>> from skcomplex.models.biology.ecology import neutral_macroecology
>>> neutral_macroecology(20).elements[0].check().prepare().size_
20
Source code in src/skcomplex/models/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_model(
    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 model, with the abundances `species.n`.

    Examples:
        >>> from skcomplex.models.biology.ecology import neutral_macroecology
        >>> neutral_macroecology(20).elements[0].check().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 model, with the populations hosts and parasitoids.

Examples:

>>> from skcomplex.models.biology.ecology import nicholson_bailey
>>> nicholson_bailey(k=3.0).interactions[0].k
3.0
Source code in src/skcomplex/models/biology/ecology/_predation.py
 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
@register_model(
    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 model, with the populations `hosts` and `parasitoids`.

    Examples:
        >>> from skcomplex.models.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)],
    )

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 model, with the populations prey and predators.

Examples:

>>> from skcomplex.models.biology.ecology import rosenzweig_macarthur
>>> round(rosenzweig_macarthur().elements[0].n, 6)
5.0
Source code in src/skcomplex/models/biology/ecology/_predation.py
17
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
@register_model(
    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 model, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.models.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 model, 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.models.biology.ecology import sequentially_linear_ecosystem
>>> [component.label for component in sequentially_linear_ecosystem(n=10).elements]
['species', 'influences']
Source code in src/skcomplex/models/biology/ecology/_sequential.py
 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
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@register_model(
    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 model, 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.models.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 model, with the groups life/plants, life/prey, and life/predators, and the marks ground/marks.

Examples:

>>> from skcomplex.models.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/models/biology/ecology/_stigmergy.py
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
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
@register_model(
    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 model, with the groups `life/plants`, `life/prey`, and `life/predators`, and the marks
            `ground/marks`.

    Examples:
        >>> from skcomplex.models.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 model, with the populations prey and predators.

Examples:

>>> from skcomplex.models.biology.ecology import stochastic_predator_prey
>>> stochastic_predator_prey(K=1000.0).interactions[0].K
1000.0
Source code in src/skcomplex/models/biology/ecology/_predation.py
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
287
288
289
290
@register_model(
    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 model, with the populations `prey` and `predators`.

    Examples:
        >>> from skcomplex.models.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 model, with the population population.

Examples:

>>> from skcomplex.models.biology.ecology import varying_capacity_logistic
>>> varying_capacity_logistic(amplitude=0.2).interactions[0].amplitude
0.2
Source code in src/skcomplex/models/biology/ecology/_factories.py
 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
@register_model(
    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 model, with the population `population`.

    Examples:
        >>> from skcomplex.models.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 model 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 model, with the groups grass, sheep, and wolves.

Examples:

>>> from skcomplex.models.biology.ecology import wolf_sheep
>>> [group.label for group in wolf_sheep(10, 10).elements]
['grass', 'sheep', 'wolves']
Source code in src/skcomplex/models/biology/ecology/_wolf_sheep.py
 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
@register_model(
    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 model 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 model, with the groups `grass`, `sheep`, and `wolves`.

    Examples:
        >>> from skcomplex.models.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'),
    )