Skip to content

Evolution

Evolution systems.

They cover evolutionary games, quasispecies, hypercycles, finite populations, landscapes, and coevolution.

AdaptiveClimbingInteraction(label, *, target, mutation=0.1, length=20, seed=0)

Bases: EvolutionInteraction

One generation of a population that climbs a random fitness landscape.

The population climbs as a whole, under strong selection.

All individuals share one genome. Each mutates one random locus with probability u, to a genome of random fitness in [0, 1], with probability mutation. If a mutant is fitter, the whole population takes the fittest mutant. If every individual mutated to a less fit genome, the population escapes to the fittest of them. Otherwise it stays. It is the best-mutant replacement of EvolutionInteraction on genomes stored as the integers their bits spell.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of individuals.

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

The probability that an individual mutates in a generation.

0.1
length int

The number of loci of a genome.

20
seed int

The seed of the fitness landscape.

0

Examples:

>>> from skcomplex.systems.biology.evolution import AdaptiveClimbingInteraction
>>> AdaptiveClimbingInteraction('climbing', target='population', mutation=0.1).replacement
'best-mutant'
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
292
293
294
295
296
297
298
299
300
301
302
303
def __init__(
    self,
    label: str,
    *,
    target: Role,
    mutation: Annotated[float, RealSet.closed(0, 1)] = 0.1,
    length: int = 20,
    seed: int = 0,
) -> None:
    super().__init__(label, target=target, strategy='trait', replacement='best-mutant', mutation=mutation)
    self.length = length
    self.seed = seed

AdaptiveClimbingSystem(size=10, *, u=0.1, length=20, seed=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A finite population that climbs a random fitness landscape.

It climbs by mutation and strong selection.

The population climbs to a local optimum in an adaptive walk, ever slower near the top. When every individual mutates in the same generation, which is likely only in small populations with a large u, it escapes to a lower genome and starts a new walk, the wandering regime. The system has the group population.

Parameters:

Name Type Description Default
size int

The number of individuals.

10
u float

The probability that an individual mutates in a generation.

0.1
length int

The number of loci of a genome.

20
seed int

The seed of the fitness landscape.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import AdaptiveClimbingSystem
>>> AdaptiveClimbingSystem(5).prepare().system_.elements[0].size
5
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
def __init__(
    self,
    size: int = 10,
    *,
    u: float = 0.1,
    length: int = 20,
    seed: int = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.size = size
    self.u = u
    self.length = length
    self.seed = seed

AlleleFrequencyElement(label, *, x=0.5, Ns=0.0, size=None)

Bases: Element

Frequency x of an allele in a population, with the scaled selection Ns of the allele.

Parameters:

Name Type Description Default
label str

The label of the allele or of the group of replicate populations.

required
x Annotated[float, closed(0, 1)]

The initial frequency.

0.5
Ns float

The scaled selection, the population size times the excess fitness.

0.0
size int | None

The number of replicate populations, or None for one.

None

Examples:

>>> from skcomplex.systems.biology.evolution import AlleleFrequencyElement
>>> AlleleFrequencyElement('allele', Ns=2.0).Ns
2.0
Source code in src/skcomplex/systems/biology/evolution/_drift.py
49
50
51
52
53
54
55
56
57
58
59
def __init__(
    self,
    label: str,
    *,
    x: Annotated[float, RealSet.closed(0, 1)] = 0.5,
    Ns: float = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.x = x
    self.Ns = Ns

AssemblyDiscoveryInteraction(label, *, target, N0=1.0)

Bases: Interaction

Discovery of the objects of every assembly level from the level below, dN_{a+1}/dt = k (N_a)^alpha.

The rate k and the selectivity alpha are values of the levels, an AssemblyLevelElement, and the first level is discovered from the pool of building blocks N0.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of levels, ordered by assembly index.

required
N0 float

The number of building blocks below the first level.

1.0

Examples:

>>> from skcomplex.systems.biology.evolution import AssemblyDiscoveryInteraction
>>> AssemblyDiscoveryInteraction('discovery', target='levels').N0
1.0
Source code in src/skcomplex/systems/biology/evolution/_assembly.py
102
103
104
105
def __init__(self, label: str, *, target: Role, N0: float = 1.0) -> None:
    super().__init__(label)
    self.target = target
    self.N0 = N0

AssemblyGrowthSystem(levels=10, *, k=1.0, alpha=1.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The numbers of objects at successive assembly indices.

Each level is discovered from the level below.

The objects of assembly index a + 1 grow as dN_{a+1}/dt = k (N_a)^alpha from a constant pool of building blocks. Without selection, alpha = 1, every object built before is reused and N_a(t) = (k t)^a / a!, the exponential expansion of the assembly possible. Selection, alpha < 1, reuses only a subset, so the discovery of new objects slows down and the deeper levels fill far later. The system has the numbers levels.N of the group levels, ordered by assembly index from 1.

Parameters:

Name Type Description Default
levels int

The number of assembly indices above the building blocks.

10
k float

The rate of discovery.

1.0
alpha float

The selectivity of reuse, 1 for no selection.

1.0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import AssemblyGrowthSystem
>>> AssemblyGrowthSystem(5).prepare().system_.elements[0].size
5
Source code in src/skcomplex/systems/biology/evolution/_assembly.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def __init__(
    self,
    levels: int = 10,
    *,
    k: float = 1.0,
    alpha: float = 1.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.levels = levels
    self.k = k
    self.alpha = alpha

AssemblyLevelElement(label, *, N=0.0, k=1.0, alpha=1.0, size=None)

Bases: Element

Objects of one assembly index.

They are discovered from the objects one assembly step below them.

In a group ordered by assembly index, an AssemblyDiscoveryInteraction grows the objects of index a + 1 as dN_{a+1}/dt = k (N_a)^alpha, Eq. (3) of Sharma et al. (2022), where the first member reads the constant pool N_0 of building blocks. The selectivity alpha = 1 reuses every object built before, and alpha < 1 only a subset, the signature of selection.

Parameters:

Name Type Description Default
label str

The label of the level or of the group of levels.

required
N Annotated[float | Array, closed_open(0, oo)]

The initial number of objects.

0.0
k Annotated[float | Array, closed_open(0, oo)]

The rate of discovery.

1.0
alpha Annotated[float | Array, closed(0, 1)]

The selectivity of reuse.

1.0
size int | None

The number of levels, or None for one.

None

Examples:

>>> from skcomplex.systems.biology.evolution import AssemblyLevelElement
>>> AssemblyLevelElement('levels', alpha=0.5).alpha
0.5
Source code in src/skcomplex/systems/biology/evolution/_assembly.py
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(
    self,
    label: str,
    *,
    N: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.0,
    k: Annotated[float | Array, RealSet.closed_open(0, oo)] = 1.0,
    alpha: Annotated[float | Array, RealSet.closed(0, 1)] = 1.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.N = N
    self.k = k
    self.alpha = alpha

AutocatalyticGrowthInteraction(label, *, target, k=1)

Bases: Interaction

Catalytic growth of the species of a pool and the replacement of the least populated one.

The populations follow the catalytic network: every species gains h times the populations of the species that catalyse it, and the populations are normalised, so they approach the Perron eigenvector of the network. Every period steps the least populated species, with ties broken at random, is replaced by a new species with k random catalysts, and every species catalyses the new one with probability p. The growth h, the probability p, and the period are values of the species, a ChemicalElement.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of species on the nodes.

required
k int

The number of catalysts of a new species.

1

Examples:

>>> from skcomplex.systems.biology.evolution import AutocatalyticGrowthInteraction
>>> AutocatalyticGrowthInteraction('growth', target='species', k=2).k
2
Source code in src/skcomplex/systems/biology/evolution/_networks.py
122
123
124
125
def __init__(self, label: str, *, target: Role, k: int = 1) -> None:
    super().__init__(label)
    self.target = target
    self.k = k

BakSneppenSystem(size=200, *, graph=None, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Bak-Sneppen system of punctuated equilibrium.

Its fitnesses self-organise above a critical value in avalanches of extinction.

On a ring the fitnesses gather above the critical value 0.667, and the minimum fitness rises towards it through avalanches of every size. Every step is one extinction, so time counts the extinctions. The system has the fitnesses species.fitness.

Parameters:

Name Type Description Default
size int

The number of species on the ring, unused on a graph.

200
graph Graph | None

The graph whose nodes are the species, or None for a ring.

None
random_state int | Generator | None

The seed or generator of the initial fitnesses.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import BakSneppenSystem
>>> BakSneppenSystem(50).prepare().system_.interactions[0].neighbors
'ring'
Source code in src/skcomplex/systems/biology/evolution/_coevolution.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def __init__(
    self,
    size: int = 200,
    *,
    graph: nx.Graph | None = None,
    random_state: int | np.random.Generator | None = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.size = size
    self.graph = graph
    self.random_state = random_state

CatalysisInteraction(label, *, target, omega=1.0, topology=((0.0, 1.0), (1.0, 0.0)))

Bases: ReplicatorInteraction

Catalysed replication of the molecules of a group.

A common outflow keeps the total at 1.

Molecule i replicates at the rate f_i = lambda_i + omega sum_j T_ij x_j, with its own growth lambda_i and the 0 or 1 topology T of the catalytic links read as the weights of a total over the molecules. The outflow is the total replication, so the concentrations follow the replicator equation dx_i/dt = x_i (f_i - sum_j x_j f_j).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of molecules.

required
omega Annotated[float, closed_open(0, oo)]

The catalytic rate of a link.

1.0
topology Sequence[Sequence[float]]

The catalytic links, 1 where molecule j catalyses molecule i.

((0.0, 1.0), (1.0, 0.0))

Examples:

>>> from skcomplex.systems.biology.evolution import CatalysisInteraction
>>> CatalysisInteraction('catalysis', target='soup', topology=((0, 1), (1, 0))).topology
((0, 1), (1, 0))
Source code in src/skcomplex/systems/biology/evolution/_prebiotic.py
164
165
166
167
168
169
170
171
172
173
174
def __init__(
    self,
    label: str,
    *,
    target: Role,
    omega: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
    topology: Sequence[Sequence[float]] = ((0.0, 1.0), (1.0, 0.0)),
) -> None:
    super().__init__(label, target=target)
    self.omega = omega
    self.topology = topology

ChemicalElement(label, *, x=0.0, tie=0.5, fresh=1.0, h=0.5, p=0.02, period=10.0, space=None)

Bases: Element

Molecular species of a pool whose population grows with its catalysts.

The relative population grows with the populations of its catalysts under an AutocatalyticGrowthInteraction.

Parameters:

Name Type Description Default
label str

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

required
x Annotated[float | Array, closed_open(0, oo)]

The relative population.

0.0
tie Annotated[float | Array, closed_open(0, oo)]

The random key that breaks ties between the least populated species.

0.5
fresh Annotated[float | Array, FiniteEnumeratedSet([0, 1])]

Whether the species appeared at the previous graph update.

1.0
h Annotated[float | Array, open(0, oo)]

The growth of a step from the catalysts.

0.5
p Annotated[float | Array, closed_open(0, oo)]

The probability of every catalytic link of a new species.

0.02
period Annotated[float | Array, open(0, oo)]

The number of steps between two graph updates.

10.0
space BaseSpace | None

The network whose nodes hold one species each, or None for one species.

None

Examples:

>>> from skcomplex.systems.biology.evolution import ChemicalElement
>>> ChemicalElement('species').period
10.0
Source code in src/skcomplex/systems/biology/evolution/_networks.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def __init__(
    self,
    label: str,
    *,
    x: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.0,
    tie: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.5,
    fresh: Annotated[float | Array, FiniteEnumeratedSet([0, 1])] = 1.0,
    h: Annotated[float | Array, RealSet.open(0, oo)] = 0.5,
    p: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.02,
    period: Annotated[float | Array, RealSet.open(0, oo)] = 10.0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.x = x
    self.tie = tie
    self.fresh = fresh
    self.h = h
    self.p = p
    self.period = period

ClimberElement(label, *, genome=0.0, fitness=0.0, n=10.0, k=2.0, seed=0.0, values=None, size=None, space=None)

Bases: Element

Agent that walks an NK fitness landscape.

It flips one random bit of its genome when that raises its fitness, by ClimbingInteraction.

The fitness of a genome of n bits is the mean of the contributions of its bits, each a random function of the bit and the next k bits, fixed by seed.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
genome Annotated[float | ArrayLike, NN]

The bits of the genome.

0.0
fitness Annotated[float | ArrayLike, closed_open(0, oo)]

The fitness of the genome.

0.0
n Annotated[float, open(0, oo)]

The number of bits.

10.0
k Annotated[float, NN]

The number of other bits each bit interacts with.

2.0
seed Annotated[float, NN]

The seed of the landscape.

0.0
values Mapping[str, object] | None

Further values by name, or None for none.

None
size int | None

The number of climbers, or None for one.

None
space BaseSpace | None

The space of the climbers, or None for none.

None

Examples:

>>> from skcomplex.systems.biology.evolution import ClimberElement
>>> ClimberElement('climbers', size=10).size
10
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(
    self,
    label: str,
    *,
    genome: Annotated[float | npt.ArrayLike, NN] = 0.0,
    fitness: Annotated[float | npt.ArrayLike, RealSet.closed_open(0, oo)] = 0.0,
    n: Annotated[float, RealSet.open(0, oo)] = 10.0,
    k: Annotated[float, NN] = 2.0,
    seed: Annotated[float, NN] = 0.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.genome = genome
    self.fitness = fitness
    self.n = n
    self.k = k
    self.seed = seed

ClimbingInteraction(label, *, target)

Bases: Interaction

Hill climbing of agents on an NK fitness landscape.

At every step each climber flips one random bit of its genome and keeps the flip when it raises its fitness.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of climbers.

required

Examples:

>>> from skcomplex.systems.biology.evolution import ClimbingInteraction
>>> ClimbingInteraction('climbing', target='climbers').target
'climbers'
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
227
228
229
def __init__(self, label: str, *, target: Role) -> None:
    super().__init__(label)
    self.target = target

climb(agent, system)

Flip a random bit, and keep the flip when it raises the fitness.

Parameters:

Name Type Description Default
agent ClimberView

The climber.

required
system SystemView

The system.

required
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def climb(self, agent: ClimberView, system: SystemView) -> None:
    """Flip a random bit, and keep the flip when it raises the fitness.

    Args:
        agent:
            The climber.

        system:
            The system.
    """
    n, k, seed = int(agent.n), int(agent.k), int(agent.seed)
    mutant = int(agent.genome) ^ (1 << int(system.rng.integers(n)))
    fitness = ClimberElement._get_nk_fitness(mutant, n, k, seed)
    if fitness > agent.fitness:
        agent.genome = float(mutant)
        agent.fitness = fitness

CoevolutionaryClimbingInteraction(label, *, species, n=12, k=2, c=1, s=2, seed=0)

Bases: Interaction

Hill climbing of species on coupled NK landscapes, the NKCS model.

Each species takes one point mutation per step.

Every gene of a species contributes to its fitness through a random table of its own state, the states of the next k genes of the species, and the states of c random genes in each of s other species. The fitness of a species is the mean contribution of its n genes. At every step the species are picked in turn, and each flips one random bit and keeps the flip when it raises its fitness against the current genomes of the others. The tables, the partner species, and the coupled genes are fixed by seed.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
species Role

The path of the group of species.

required
n int

The number of genes of every species.

12
k int

The number of genes of its own species each gene depends on.

2
c int

The number of genes of every partner species each gene depends on.

1
s int

The number of partner species of every species.

2
seed int

The seed of the landscapes and the couplings.

0

Examples:

>>> from skcomplex.systems.biology.evolution import CoevolutionaryClimbingInteraction
>>> CoevolutionaryClimbingInteraction('climbing', species='species', k=4).k
4
Source code in src/skcomplex/systems/biology/evolution/_nkcs.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def __init__(
    self,
    label: str,
    *,
    species: Role,
    n: int = 12,
    k: int = 2,
    c: int = 1,
    s: int = 2,
    seed: int = 0,
) -> None:
    super().__init__(label)
    self.species = species
    self.n = n
    self.k = k
    self.c = c
    self.s = s
    self.seed = seed

climb(system)

Let every species in turn try one point mutation, and update the fitness of all.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/biology/evolution/_nkcs.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def climb(self, system: SystemView) -> None:
    """Let every species in turn try one point mutation, and update the fitness of all.

    Args:
        system:
            The system.
    """
    species = cast(list[CoevolvingSpeciesView], system.get_agents(self.species))
    genomes = [int(item.genome) for item in species]
    for index, item in enumerate(species):
        mutant = genomes[index] ^ (1 << int(system.rng.integers(self.n)))
        trial = [*genomes[:index], mutant, *genomes[index + 1 :]]
        accepted = self._get_fitness(index, trial) > self._get_fitness(index, genomes)
        if accepted:
            genomes[index] = mutant
        item.moves = float(accepted)
    for index, item in enumerate(species):
        item.genome = float(genomes[index])
        item.fitness = self._get_fitness(index, genomes)

CoevolvingSpeciesElement(label, *, genome=0.0, fitness=0.0, moves=0.0, size=None)

Bases: Element

Species of an NKCS ecosystem, a genome with a fitness.

The fitness depends on its own genes and on genes of other species.

A CoevolutionaryClimbingInteraction mutates the genome and sets the fitness and the number of accepted moves of the last step.

Parameters:

Name Type Description Default
label str

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

required
genome Annotated[float | Array, NN]

The bits of the genome, as an integer.

0.0
fitness Annotated[float | Array, closed_open(0, oo)]

The fitness of the genome against the current genomes of the other species.

0.0
moves Annotated[float | Array, NN]

Whether the species accepted a mutation in the last step.

0.0
size int | None

The number of members, or None for one.

None

Examples:

>>> from skcomplex.systems.biology.evolution import CoevolvingSpeciesElement
>>> CoevolvingSpeciesElement('species', genome=5.0).genome
5.0
Source code in src/skcomplex/systems/biology/evolution/_nkcs.py
67
68
69
70
71
72
73
74
75
76
77
78
79
def __init__(
    self,
    label: str,
    *,
    genome: Annotated[float | Array, NN] = 0.0,
    fitness: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.0,
    moves: Annotated[float | Array, NN] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.genome = genome
    self.fitness = fitness
    self.moves = moves

CompetingSpeciesElement(label, *, x=0.0, links=0.0, size=None)

Bases: Element

Species of the competitive Jain-Krishna model.

It holds a relative population and the signed effects of all species on it.

The links are the row of the interaction matrix of the species, M_ij for every species j, between -1 and 1, with the degradation M_ii between -1 and 0 on the diagonal.

Parameters:

Name Type Description Default
label str

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

required
x Annotated[float | Array, closed_open(0, oo)]

The relative population.

0.0
links float | Array

The effects of every species on this one, one row of the interaction matrix per member.

0.0
size int | None

The number of species, or None for one.

None

Examples:

>>> from skcomplex.systems.biology.evolution import CompetingSpeciesElement
>>> CompetingSpeciesElement('species', x=0.1).x
0.1
Source code in src/skcomplex/systems/biology/evolution/_networks.py
246
247
248
249
250
251
252
253
254
255
256
def __init__(
    self,
    label: str,
    *,
    x: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.0,
    links: float | Array = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.x = x
    self.links = links

CompetitiveJainKrishnaSystem(n=50, *, p=0.05, duration=20.0, seed=1, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Jain-Krishna model with signed interactions.

Its surviving species come to cooperate.

Every link of the interaction matrix is present with the probability p and drawn from [-1, 1], and every species degrades at a rate drawn from [-1, 0]. The populations follow the linear catalytic dynamics with a floor at zero, and at every step the least populated species is replaced by a new random one. Selection keeps the species that catalyse each other, so once an autocatalytic set forms the links among the surviving species turn mostly positive, the emergence of cooperation, and diversity grows until a keystone species is lost. The system has the populations x and the rows links of the interaction matrix of the group species.

Parameters:

Name Type Description Default
n int

The number of species.

50
p float

The probability of every link.

0.05
duration float

The time of the population dynamics between replacements.

20.0
seed int | None

The seed of the initial matrix.

1
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import CompetitiveJainKrishnaSystem
>>> CompetitiveJainKrishnaSystem(10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/biology/evolution/_networks.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def __init__(
    self,
    n: int = 50,
    *,
    p: float = 0.05,
    duration: float = 20.0,
    seed: int | None = 1,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n = n
    self.p = p
    self.duration = duration
    self.seed = seed

CompetitiveSelectionInteraction(label, *, species, p=0.05, duration=20.0, step=0.05)

Bases: Interaction

Population dynamics of signed catalytic interactions.

The least populated species is replaced at every step.

Between replacements the relative populations follow Eq. (5.37) of Thurner et al. (2018), dx_i/dt = f_i with f_i = sum_j M_ij x_j - x_i phi, where phi = sum_jk M_jk x_k keeps the total at one, except that a species at zero stays there while f_i < 0. The rule integrates them for the time duration by Euler steps of step, then replaces the least populated species, ties broken at random, by a new one whose links to and from every other species are drawn from [-1, 1] with the probability p, whose degradation is drawn from [-1, 0], and whose population starts at 1 / N.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
species Role

The path of the group of species.

required
p float

The probability of every link of a new species.

0.05
duration float

The time of the population dynamics between replacements.

20.0
step float

The Euler step of the population dynamics.

0.05

Examples:

>>> from skcomplex.systems.biology.evolution import CompetitiveSelectionInteraction
>>> CompetitiveSelectionInteraction('selection', species='species', p=0.1).p
0.1
Source code in src/skcomplex/systems/biology/evolution/_networks.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def __init__(
    self,
    label: str,
    *,
    species: Role,
    p: float = 0.05,
    duration: float = 20.0,
    step: float = 0.05,
) -> None:
    super().__init__(label)
    self.species = species
    self.p = p
    self.duration = duration
    self.step = step

select(system)

Run the population dynamics, then replace the least populated species.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/biology/evolution/_networks.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def select(self, system: SystemView) -> None:
    """Run the population dynamics, then replace the least populated species.

    Args:
        system:
            The system.
    """
    species = cast(list[CompetingSpeciesView], system.get_agents(self.species))
    matrix = np.array([np.asarray(item.links, dtype=float) for item in species])
    populations = self._relax(matrix, np.array([item.x for item in species]))
    size = len(species)
    weakest = np.flatnonzero(populations <= populations.min() + 1e-12)
    k = int(system.rng.choice(weakest))
    drawn = system.rng.uniform(-1, 1, (2, size)) * (system.rng.random((2, size)) < self.p)
    matrix[k, :], matrix[:, k] = drawn[0], drawn[1]
    matrix[k, k] = -system.rng.random()
    populations[k] = 1 / size
    populations /= populations.sum()
    for index, item in enumerate(species):
        item.x = float(populations[index])
        item.links = matrix[index]

CyclicInvasionInteraction(label, *, target='lattice')

Bases: Interaction

Invasion of the sites of rock, paper, and scissors by a random neighbour that beats them.

The sites update one at a time in a random order, and each adopts the strategy of a random von Neumann neighbour when that strategy beats its own, rock 0 beaten by paper 1, paper by scissors 2, and scissors by rock.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The sites whose state strategy the rule updates.

'lattice'

Examples:

>>> from skcomplex.systems.biology.evolution import CyclicInvasionInteraction
>>> CyclicInvasionInteraction('invasion', target='lattice').target
'lattice'
Source code in src/skcomplex/systems/biology/evolution/_games.py
207
208
209
def __init__(self, label: str, *, target: Role = 'lattice') -> None:
    super().__init__(label)
    self.target = target

CyclicSpeciesElement(label, *, strategy=0, space=None)

Bases: Element

Site of a lattice of rock, paper, and scissors, 0, 1, and 2.

Each strategy beats the one before it.

The sites update one at a time in random order by a CyclicInvasionInteraction, and a site adopts the strategy of a random neighbour that beats it.

Parameters:

Name Type Description Default
label str

The label of the site or the lattice group.

required
strategy Annotated[float | Array, NN]

The initial strategy, 0, 1, or 2, one per site or shared.

0
space BaseSpace | None

The lattice whose sites hold one strategy each, or None for one site.

None

Examples:

>>> from skcomplex.systems.biology.evolution import CyclicSpeciesElement
>>> CyclicSpeciesElement('site', strategy=2).strategy
2
Source code in src/skcomplex/systems/biology/evolution/_games.py
57
58
59
60
61
62
63
64
65
def __init__(
    self,
    label: str,
    *,
    strategy: Annotated[float | Array, NN] = 0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.strategy = strategy

DependencyFieldInteraction(label, *, species, couplings)

Bases: Interaction

Field of every species.

The field is the sum of the couplings w of its edges to the species it depends on.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
species Role

The path of the group of species on the nodes.

required
couplings Role

The path of the variable group on the edges.

required

Examples:

>>> from skcomplex.systems.biology.evolution import DependencyFieldInteraction
>>> DependencyFieldInteraction('field', species='species', couplings='couplings').couplings
'couplings'
Source code in src/skcomplex/systems/biology/evolution/_networks.py
383
384
385
386
387
388
389
390
391
392
def __init__(
    self,
    label: str,
    *,
    species: Role,
    couplings: Role,
) -> None:
    super().__init__(label)
    self.species = species
    self.couplings = couplings

EigenQuasispeciesSystem(classes=12, *, u=0.3, sigma=0.5, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The linear chain system of a population around a master sequence.

It holds the shares of a population at every number of mutations from the master sequence.

Below the error threshold, u < sigma, a quasispecies forms around the master sequence, whose share settles at x0 = 1 - u / sigma. Above it the master sequence is lost, the error catastrophe. Back mutations and multiple mutations are neglected, so the chain holds only forward mutations, and the last class collects the far mutants. The system has the shares master.x and k1.x to k<classes>.x.

Parameters:

Name Type Description Default
classes int

The number of classes of mutants after the master sequence.

12
u float

The mutation rate per genome and generation.

0.3
sigma float

The selective disadvantage of the mutants.

0.5
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import EigenQuasispeciesSystem
>>> [element.label for element in EigenQuasispeciesSystem(2).prepare().system_.elements]
['master', 'k1', 'k2']
Source code in src/skcomplex/systems/biology/evolution/_prebiotic.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def __init__(
    self,
    classes: int = 12,
    *,
    u: float = 0.3,
    sigma: float = 0.5,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.classes = classes
    self.u = u
    self.sigma = sigma

ExtinctionInteraction(label, *, target, neighbors='ring')

Bases: Interaction

Extinctions of the Bak-Sneppen system, which renew the least fit species and its neighbours.

Every step is one extinction. The least fit species of the group and its neighbours take new fitnesses, drawn uniformly from the unit interval, and every other species keeps its fitness. A species renews when the smallest fitness of the group lies in its neighbourhood or is its own, so the update needs no index of the least fit species. Ties of the smallest fitness, which uniform draws make vanishingly rare, renew every tied species with its neighbours.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the species, whose value is fitness.

required
neighbors str

'ring' for the two neighbours on a ring or 'graph' for the neighbours of a node.

'ring'

Examples:

>>> from skcomplex.systems.biology.evolution import ExtinctionInteraction
>>> ExtinctionInteraction('extinction', target='species').neighbors
'ring'
Source code in src/skcomplex/systems/biology/evolution/_coevolution.py
101
102
103
104
def __init__(self, label: str, *, target: Role, neighbors: str = 'ring') -> None:
    super().__init__(label)
    self.target = target
    self.neighbors = neighbors

GenotypeClassElement(label, *, x=0.0)

Bases: Element

Share of a population some number of point mutations from the master sequence.

Parameters:

Name Type Description Default
label str

The label of the class.

required
x Annotated[float, closed_open(0, oo)]

The initial share.

0.0

Examples:

>>> from skcomplex.systems.biology.evolution import GenotypeClassElement
>>> GenotypeClassElement('k1', x=0.1).x
0.1
Source code in src/skcomplex/systems/biology/evolution/_prebiotic.py
48
49
50
51
52
53
54
55
def __init__(
    self,
    label: str,
    *,
    x: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
) -> None:
    super().__init__(label)
    self.x = x

HypercyclesSystem(molecules=4, *, alpha=0.1, omega=1.0, topology='cycle', label='system', solver='auto', backend='auto')

Bases: BaseSystem

A hypercycle of self-replicating molecules.

The catalysis of the network keeps a set of them alive.

The growth rates rise as lambda_i = alpha i. In a 'cycle', every molecule catalyses the next one. Up to four molecules the hypercycle keeps all of them at a fixed point, and from five some members die out and the others settle at a fixed point. In a 'complete' network every molecule catalyses every other, and about sqrt(2 omega / alpha) of the fastest replicators survive while the others die out. The system has the concentrations soup.x of the molecules, members of the group soup.

Parameters:

Name Type Description Default
molecules int

The number of molecules.

4
alpha float

The step of the autocatalytic growth rates.

0.1
omega float

The catalytic rate of a link.

1.0
topology str

'cycle' or 'complete'.

'cycle'
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Raises:

Type Description
ValidationError

The topology is unknown.

Examples:

>>> from skcomplex.systems.biology.evolution import HypercyclesSystem
>>> HypercyclesSystem(3).prepare().system_.interactions[0].topology
((0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))
Source code in src/skcomplex/systems/biology/evolution/_prebiotic.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def __init__(
    self,
    molecules: int = 4,
    *,
    alpha: float = 0.1,
    omega: float = 1.0,
    topology: str = 'cycle',
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.molecules = molecules
    self.alpha = alpha
    self.omega = omega
    self.topology = topology

IndividualElement(label, *, trait=0.0, fitness=1.0, values=None, size=None, space=None)

Bases: Element

Individual of a finite population, with an integer trait or genome.

Parameters:

Name Type Description Default
label str

The label of the agent or group.

required
trait Annotated[float | ArrayLike, ZZ]

The trait, a type index or the bits of a genome.

0.0
fitness Annotated[float | ArrayLike, closed_open(0, oo)]

The fitness of the trait.

1.0
values Mapping[str, object] | None

Further values by name, or None for none.

None
size int | None

The number of individuals, or None for one.

None
space BaseSpace | None

The space of the individuals, or None for none.

None

Examples:

>>> from skcomplex.systems.biology.evolution import IndividualElement
>>> IndividualElement('population', trait=0.0, size=10).size
10
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
178
179
180
181
182
183
184
185
186
187
188
189
190
def __init__(
    self,
    label: str,
    *,
    trait: Annotated[float | npt.ArrayLike, ZZ] = 0.0,
    fitness: Annotated[float | npt.ArrayLike, RealSet.closed_open(0, oo)] = 1.0,
    values: Mapping[str, object] | None = None,
    size: int | None = None,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, values=values, size=size, space=space)
    self.trait = trait
    self.fitness = fitness

JainKrishnaSystem(n=40, *, p=0.02, h=0.5, period=10, seed=1, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The system of Jain and Krishna.

Selection of the fittest builds autocatalytic sets of molecules.

The populations of n molecular species approach the Perron eigenvector of their catalytic network between graph updates, every period steps. At every graph update the least populated species is replaced by a new one, linked to the others with probability p. Once a cycle of catalysts forms by chance, the species it supports win, and the autocatalytic set grows until it spans the network, so the number of links and the populated species jump. The system has the populations species.x of the variable group species on the nodes and the variable group links on the edges, where an edge from i to j means that j catalyses i.

Parameters:

Name Type Description Default
n int

The number of species.

40
p float

The probability of every catalytic link.

0.02
h float

The growth of a step from the catalysts.

0.5
period int

The number of steps between two graph updates.

10
seed int | None

The seed of the initial network.

1
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import JainKrishnaSystem
>>> round(float(JainKrishnaSystem(n=10).prepare().system_.elements[0].x.sum()), 6)
1.0
Source code in src/skcomplex/systems/biology/evolution/_networks.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def __init__(
    self,
    n: int = 40,
    *,
    p: float = 0.02,
    h: float = 0.5,
    period: int = 10,
    seed: int | None = 1,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n = n
    self.p = p
    self.h = h
    self.period = period
    self.seed = seed

KimuraDiffusionSystem(x=0.1, *, Ns=2.0, replicates=500, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Replicate populations whose allele frequencies diffuse by drift.

The frequencies diffuse until the allele is lost or fixed.

Each replicate follows dx = N s x (1 - x) dt + sqrt(2 x (1 - x)) dW, whose density obeys Kimura's diffusion equation dp/dt = -N s d/dx [x (1 - x) p] + d^2/dx^2 [x (1 - x) p]. Every replicate ends at loss or fixation, and an allele that starts at the frequency x fixes with the probability (1 - exp(-N s x)) / (1 - exp(-N s)), or x for a neutral allele. The system has the frequencies alleles.x of the replicates.

Parameters:

Name Type Description Default
x float

The initial frequency of the allele.

0.1
Ns float

The scaled selection, the population size times the excess fitness.

2.0
replicates int

The number of independent replicate populations.

500
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import KimuraDiffusionSystem
>>> KimuraDiffusionSystem(replicates=10).prepare().system_.elements[0].size
10
Source code in src/skcomplex/systems/biology/evolution/_drift.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def __init__(
    self,
    x: float = 0.1,
    *,
    Ns: float = 2.0,
    replicates: int = 500,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.x = x
    self.Ns = Ns
    self.replicates = replicates

KimuraDriftInteraction(label, *, target)

Bases: Interaction

Selection and genetic drift of an allele frequency, Kimura's diffusion.

The population is large. The frequency follows the Itô equation dx = N s x (1 - x) dt + sqrt(2 x (1 - x)) dW, the continuum limit of the Moran process with the scaled selection N s of the target, in units of N generations. The frequencies 0 and 1, loss and fixation, are absorbing, and a boundary keeps the frequency between them.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the alleles, whose values are x and Ns.

required

Examples:

>>> from skcomplex.systems.biology.evolution import KimuraDriftInteraction
>>> KimuraDriftInteraction('drift', target='alleles').target
'alleles'
Source code in src/skcomplex/systems/biology/evolution/_drift.py
89
90
91
def __init__(self, label: str, *, target: Role) -> None:
    super().__init__(label)
    self.target = target

LocusElement(label, *, s=-1.0, h=0.0, space=None)

Bases: Element

Locus of the genome of a monomorphic population, with an allele of -1 or 1.

Parameters:

Name Type Description Default
label str

The label of the locus or the group of loci.

required
s Annotated[float | Array, ZZ]

The allele, -1 or 1.

-1.0
h float | Array

The random field of the locus, the fitness gained by the allele 1 over the allele -1, halved.

0.0
space BaseSpace | None

The lattice whose sites hold one locus each, or None for one locus.

None

Examples:

>>> from skcomplex.core.components.spaces import LatticeSpace
>>> from skcomplex.systems.biology.evolution import LocusElement
>>> LocusElement('genome', h=0.05, space=LatticeSpace(10)).h
0.05
Source code in src/skcomplex/systems/biology/evolution/_substitutions.py
56
57
58
59
60
61
62
63
64
65
66
def __init__(
    self,
    label: str,
    *,
    s: Annotated[float | Array, ZZ] = -1.0,
    h: float | Array = 0.0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.s = s
    self.h = h

MasterSequenceElement(label, *, x=0.0, u=0.3, sigma=0.5)

Bases: GenotypeClassElement

Share of the population with the fittest genome, in a sharp-peak landscape.

In the landscape every other genome is less fit.

The master sequence has fitness 1 and every other genome 1 - sigma. A genome mutates at one locus with probability u per generation. The master sequence holds the parameters of the landscape that the maps of every class read.

Parameters:

Name Type Description Default
label str

The label of the class.

required
x float

The initial share.

0.0
u Annotated[float, closed_open(0, oo)]

The mutation rate per genome and generation.

0.3
sigma Annotated[float, closed_open(0, oo)]

The selective disadvantage of the other genomes.

0.5

Examples:

>>> from skcomplex.systems.biology.evolution import MasterSequenceElement
>>> MasterSequenceElement('master', u=0.2).u
0.2
Source code in src/skcomplex/systems/biology/evolution/_prebiotic.py
86
87
88
89
90
91
92
93
94
95
96
def __init__(
    self,
    label: str,
    *,
    x: float = 0.0,
    u: Annotated[float, RealSet.closed_open(0, oo)] = 0.3,
    sigma: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
) -> None:
    super().__init__(label, x=x)
    self.u = u
    self.sigma = sigma

MoleculeElement(label, *, x=0.5, growth=0.0, size=None)

Bases: Element

Self-replicating molecule of a prebiotic soup.

It has its concentration x and its own growth rate.

Parameters:

Name Type Description Default
label str

The label of the molecule or of the group of molecules.

required
x Annotated[object, closed_open(0, oo)]

The initial concentration.

0.5
growth object

The rate of replication without catalysis.

0.0
size int | None

The number of molecules, or None for one.

None

Examples:

>>> from skcomplex.systems.biology.evolution import MoleculeElement
>>> MoleculeElement('molecule', growth=0.1).growth
0.1
Source code in src/skcomplex/systems/biology/evolution/_prebiotic.py
123
124
125
126
127
128
129
130
131
132
133
def __init__(
    self,
    label: str,
    *,
    x: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    growth: object = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.x = x
    self.growth = growth

MoranProcessSystem(size=50, *, mutants=1, selection=0.0, mutation=0.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Moran process, a population of constant size.

Fitter traits fix by selection and drift.

The population starts with mutants individuals of trait 1 among individuals of trait 0. Without mutation one trait eventually fixes, the mutant with probability (1 - 1 / r^m) / (1 - 1 / r^N) for the relative fitness r = 1 + selection. With mutation the traits diffuse along the trait axis, in clusters rather than as a spreading Gaussian, which distinguishes evolutionary diffusion from a random walk. The system has the group population.

Parameters:

Name Type Description Default
size int

The number of individuals.

50
mutants int

The initial number of individuals of trait 1.

1
selection float

The selective advantage of one unit of the trait.

0.0
mutation float

The probability that an offspring's trait mutates by one unit.

0.0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import MoranProcessSystem
>>> float(MoranProcessSystem(10, mutants=3).prepare().system_.elements[0].trait.sum())
3.0
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def __init__(
    self,
    size: int = 50,
    *,
    mutants: int = 1,
    selection: float = 0.0,
    mutation: float = 0.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.size = size
    self.mutants = mutants
    self.selection = selection
    self.mutation = mutation

MoranStepInteraction(label, *, target, advantage=0.0, mutation=0.0, phase=None)

Bases: EvolutionInteraction

One generation of the Moran process.

A generation is as many birth and death events as there are individuals.

At every event an individual reproduces with probability proportional to its fitness (1 + advantage)^trait, its offspring mutates to the trait one above or one below with probability mutation / 2 each, and it replaces an individual chosen uniformly at random, so the size of the population stays constant. It is the Moran replacement of EvolutionInteraction with proportional selection and steps of the trait.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of individuals.

required
advantage float

The selective advantage of one unit of the trait.

0.0
mutation Annotated[float, closed(0, 1)]

The probability that an offspring mutates.

0.0
phase str | None

The phase of the step the generation runs in, or None for the default phase.

None

Examples:

>>> from skcomplex.systems.biology.evolution import MoranStepInteraction
>>> MoranStepInteraction('moran', target='population', advantage=0.1).replacement
'moran'
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def __init__(
    self,
    label: str,
    *,
    target: Role,
    advantage: float = 0.0,
    mutation: Annotated[float, RealSet.closed(0, 1)] = 0.0,
    phase: str | None = None,
) -> None:
    super().__init__(
        label,
        target=target,
        strategy='trait',
        selection='proportional',
        replacement='moran',
        mutation=mutation,
        alphabet=None,
        change='step',
        phase=phase,
    )
    self.advantage = advantage

NKCSSystem(n_species=10, *, n=12, k=2, c=1, s=2, seed=0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The NKCS model of Kauffman and Johnsen.

Species climb NK landscapes coupled to each other's genes.

Every gene of a species depends on k genes of its own species and on c genes in each of s partner species. A species keeps a point mutation when it raises its fitness, which changes the landscapes of the species that depend on it, so adaptations trigger coevolutionary avalanches. Rugged landscapes, k above about c s, freeze the ecosystem once every species sits on a peak, and smoother ones keep it in a chaotic regime of endless adaptation. The system has the genomes species.genome, fitnesses species.fitness, and accepted mutations species.moves of the group species.

Parameters:

Name Type Description Default
n_species int

The number of species.

10
n int

The number of genes of every species.

12
k int

The number of genes of its own species each gene depends on.

2
c int

The number of genes of every partner species each gene depends on.

1
s int

The number of partner species of every species.

2
seed int

The seed of the landscapes and the couplings.

0
random_state int | Generator | None

The seed or generator of the initial genomes.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import NKCSSystem
>>> NKCSSystem(5).prepare().system_.elements[0].size
5
Source code in src/skcomplex/systems/biology/evolution/_nkcs.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def __init__(
    self,
    n_species: int = 10,
    *,
    n: int = 12,
    k: int = 2,
    c: int = 1,
    s: int = 2,
    seed: int = 0,
    random_state: int | np.random.Generator | None = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n_species = n_species
    self.n = n
    self.k = k
    self.c = c
    self.s = s
    self.seed = seed
    self.random_state = random_state

NKLandscapeSystem(climbers=50, *, n=10, k=2, seed=0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Agents that climb Kauffman's NK fitness landscape until they reach local peaks.

The agents start from random genomes.

The landscape grows more rugged with k, from a single peak at k = 0 to a random landscape at k = n - 1, so the climbers end on more peaks of lower fitness. The system has the group climbers.

Parameters:

Name Type Description Default
climbers int

The number of agents.

50
n int

The number of bits of a genome.

10
k int

The number of other bits each bit interacts with.

2
seed int

The seed of the landscape.

0
random_state int | Generator | None

The seed or generator of the initial genomes.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import NKLandscapeSystem
>>> NKLandscapeSystem(5).prepare().system_.elements[0].size
5
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def __init__(
    self,
    climbers: int = 50,
    *,
    n: int = 10,
    k: int = 2,
    seed: int = 0,
    random_state: int | np.random.Generator | None = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.climbers = climbers
    self.n = n
    self.k = k
    self.seed = seed
    self.random_state = random_state

NeutralNetworkResult(genotypes, values=None, networks=None) dataclass

Neutral networks, robustness, or evolvability of the sequences of a source.

Parameters:

Name Type Description Default
genotypes ndarray

The sequences of the source, in an array of their shape without the letters.

required
values ndarray | dict[Hashable, float] | None

For a genotype kind, one value per sequence of the source. For a phenotype kind, the value of every phenotype of the source, by key. None for 'network'.

None
networks dict[Hashable, Graph] | None

For the kind 'network', the graph per phenotype of the sequences of the source that one point mutation joins, or None for the other kinds.

None

NucleotideElement(label, base='A', space=None)

Bases: Element

Site of an RNA sequence that holds one base.

Parameters:

Name Type Description Default
label str

The label of the element.

required
base Annotated[str | IntArray, FiniteEnumeratedSet(list(BASES))]

The base of the site.

'A'
space BaseSpace | None

The lattice whose sites hold one base each, or None for one site.

None

Examples:

>>> from skcomplex.systems.biology.evolution import NucleotideElement
>>> NucleotideElement('site').base
'A'
Source code in src/skcomplex/systems/biology/evolution/_rna_walks.py
59
60
61
62
63
64
65
66
def __init__(
    self,
    label: str,
    base: Annotated[str | IntArray, FiniteEnumeratedSet(list(BASES))] = 'A',
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.base = base

OriginFixationWalkSystem(loci=96, *, N=100.0, mu=0.01, field_scale=0.01, coupling=0.0, F0=1.0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

A monomorphic population that climbs a fitness landscape.

Mutants arise and fix one at a time.

Under strong selection and weak mutation the population carries one genome of loci alleles -1 or 1, and every substitution of a mutant moves it to a neighbouring genome. The walk climbs the landscape and settles on the stationary distribution Q ~ f^(N - 1), a Boltzmann distribution of the energy -ln f at the temperature 1 / (N - 1). Random fields alone, coupling = 0, give a landscape with one peak. Couplings J_ij of variance coupling^2 / loci give the rugged landscape of a spin glass, where a small population escapes local peaks. The system has the alleles genome.s on a one-dimensional lattice of loci, starting from the genome of all -1, and the fitness fitness of the genome.

Parameters:

Name Type Description Default
loci int

The number of loci of the genome.

96
N float

The size of the population.

100.0
mu float

The rate at which one locus of an individual mutates.

0.01
field_scale float

The standard deviation of the random fields h_i.

0.01
coupling float

The scale of the random couplings J_ij, or 0 for none.

0.0
F0 float

The fitness of a genome without fields and couplings, above the sum of the |h_i| and |J_ij| so that every fitness is positive.

1.0
random_state int | Generator | None

The seed or generator of the fields and couplings.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import OriginFixationWalkSystem
>>> OriginFixationWalkSystem(8).prepare().system_.elements[0].h.shape
(8,)
Source code in src/skcomplex/systems/biology/evolution/_substitutions.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def __init__(
    self,
    loci: int = 96,
    *,
    N: float = 100.0,
    mu: float = 0.01,
    field_scale: float = 0.01,
    coupling: float = 0.0,
    F0: float = 1.0,
    random_state: int | np.random.Generator | None = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.loci = loci
    self.N = N
    self.mu = mu
    self.field_scale = field_scale
    self.coupling = coupling
    self.F0 = F0
    self.random_state = random_state

PolymerAssemblyPoolSystem(mode='undirected', *, label='system', solver='auto', backend='auto')

Bases: BaseSystem

An assembly pool of linear polymers grown from one monomer.

The pool grows by joining pairs of its polymers.

Undirected exploration joins two random polymers of the pool, and directed exploration, a model of selection, joins the newest polymer with a random one. Undirected joining fills the pool with many short polymers, while directed joining builds ever longer chains, of a higher assembly index, about the base 2 logarithm of the length. The system has the lengths pool.length of the variable group pool.

Parameters:

Name Type Description Default
mode str

'undirected' or 'directed'.

'undirected'
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import PolymerAssemblyPoolSystem
>>> PolymerAssemblyPoolSystem('directed').prepare().system_.interactions[0].mode
'directed'
Source code in src/skcomplex/systems/biology/evolution/_assembly.py
346
347
348
349
350
351
352
353
354
355
def __init__(
    self,
    mode: str = 'undirected',
    *,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.mode = mode

PolymerElement(label, *, length=1.0, born=0.0, size=None)

Bases: Element

Linear polymer of an assembly pool, with its length and the step it was made.

Parameters:

Name Type Description Default
label str

The label of the polymer or of the group of polymers.

required
length Annotated[float | Array, NN]

The number of monomers.

1.0
born Annotated[float | Array, NN]

The step at which the polymer was made.

0.0
size int | None

The number of polymers, or None for one.

None

Examples:

>>> from skcomplex.systems.biology.evolution import PolymerElement
>>> PolymerElement('polymer', length=3.0).length
3.0
Source code in src/skcomplex/systems/biology/evolution/_assembly.py
152
153
154
155
156
157
158
159
160
161
162
def __init__(
    self,
    label: str,
    *,
    length: Annotated[float | Array, NN] = 1.0,
    born: Annotated[float | Array, NN] = 0.0,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.length = length
    self.born = born

PolymerJoiningInteraction(label, *, polymers, mode='undirected')

Bases: Interaction

Joining of two polymers of an assembly pool into a new one.

The polymers are joined at random or by reuse of the newest polymer.

At every step, undirected exploration joins two polymers drawn at random from the pool, and directed exploration joins the polymer made most recently with one drawn at random. The joined polymer, of the summed length, is added to the pool, and the two polymers it joins stay in it.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
polymers Role

The path of the variable group of polymers.

required
mode str

'undirected' or 'directed'.

'undirected'

Raises:

Type Description
ValidationError

The mode is unknown.

Examples:

>>> from skcomplex.systems.biology.evolution import PolymerJoiningInteraction
>>> PolymerJoiningInteraction('joining', polymers='pool', mode='directed').mode
'directed'
Source code in src/skcomplex/systems/biology/evolution/_assembly.py
198
199
200
201
def __init__(self, label: str, *, polymers: Role, mode: str = 'undirected') -> None:
    super().__init__(label)
    self.polymers = polymers
    self.mode = mode

join(system)

Join two polymers and add the product to the pool.

Parameters:

Name Type Description Default
system SystemView

The system.

required
Source code in src/skcomplex/systems/biology/evolution/_assembly.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def join(self, system: SystemView) -> None:
    """Join two polymers and add the product to the pool.

    Args:
        system:
            The system.
    """
    pool = cast(list[PolymerView], system.get_agents(self.polymers))
    partner = pool[int(system.rng.integers(len(pool)))]
    if self.mode == 'directed':
        first = max(pool, key=lambda polymer: polymer.born)
    else:
        first = pool[int(system.rng.integers(len(pool)))]
    born = max(polymer.born for polymer in pool) + 1
    system.create(self.polymers, length=first.length + partner.length, born=born)

RNANeutralNetworksSystem(walkers=8, length=30, *, start=START, target=TARGET, regime='neutral', seed=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Walkers of RNA sequences at temperature zero.

They take one proposed point mutation per unit of time.

In the 'neutral' regime a mutation is accepted when the minimum free energy fold of the sequence stays on the target. In the 'adaptive' regime a mutation is accepted when the base-pair distance between the fold and the target does not grow. The neighbours of the visited sequences give the robustness and evolvability of Raman (2021 §13.3) through neutral_network. The folds come from ViennaRNA at 37 °C with its default energy parameters. Every walker records its score as walk.score. The system has the lattice walkers of the state base.

Parameters:

Name Type Description Default
walkers int

The number of walkers, the rows of the lattice.

8
length int

The length of the sequences, the columns of the lattice.

30
start str | None

The sequence every walker starts on, or None for random sequences.

START
target str

The target structure in dot-bracket notation, of the length of the sequences.

TARGET
regime str

'neutral' or 'adaptive'.

'neutral'
seed int

The seed of the random starting sequences.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Raises:

Type Description
MissingExtraError

The extra rna is not installed.

ValidationError

The regime is unknown, or the start or the target does not have the length of the sequences.

Examples:

>>> from skcomplex.systems.biology.evolution import RNANeutralNetworksSystem
>>> RNANeutralNetworksSystem(walkers=2).prepare().system_.elements[0].space.shape
(2, 30)
Source code in src/skcomplex/systems/biology/evolution/_rna_walks.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def __init__(
    self,
    walkers: int = 8,
    length: int = 30,
    *,
    start: str | None = START,
    target: str = TARGET,
    regime: str = 'neutral',
    seed: int = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.walkers = walkers
    self.length = length
    self.start = start
    self.target = target
    self.regime = regime
    self.seed = seed

ReplicatorDynamicsSystem(x=None, *, payoff=None, V=2.0, C=3.0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The replicator dynamics of a game, by default hawks and doves.

Hawks and doves settle at a share V / C of hawks.

Every strategy is a member of the group population, and it grows with its payoff above the mean payoff. The hawks and doves game has the payoff matrix ((V - C) / 2, V), (0, V / 2) with hawks first. When the cost of a fight C exceeds the value V, hawks and doves coexist with V / C hawks, and otherwise hawks take over. A payoff matrix gives any other game, such as the prisoner's dilemma or rock, paper, scissors. The system has the shares population.x of the strategies, hawks first.

Parameters:

Name Type Description Default
x Sequence[float] | None

The initial shares of the strategies, or None for equal shares.

None
payoff Sequence[Sequence[float]] | None

The payoff matrix of another game, one row per strategy, or None for hawks and doves.

None
V float

The value of the resource contested by hawks and doves.

2.0
C float

The cost of a fight between hawks.

3.0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import ReplicatorDynamicsSystem
>>> system = ReplicatorDynamicsSystem(payoff=((0, -1, 1), (1, 0, -1), (-1, 1, 0))).prepare().system_
>>> system.elements[0].size
3
Source code in src/skcomplex/systems/biology/evolution/_games.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def __init__(
    self,
    x: Sequence[float] | None = None,
    *,
    payoff: Sequence[Sequence[float]] | None = None,
    V: float = 2.0,
    C: float = 3.0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.x = x
    self.payoff = payoff
    self.V = V
    self.C = C

ReplicatorInteraction(label, *, target, fitness=None, state='x')

Bases: Interaction

Replicator equation of the shares of a group, with a fitness f.

The shares follow dx_i/dt = x_i (f_i - sum_j x_j f_j).

Every member of the group holds the share of a type, such as a strategy or a molecule. Its share grows with its fitness above the mean fitness of the group, so the total of the shares stays constant.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of types.

required
fitness Callable[[SimpleNamespace], object] | None

The function of the namespace that returns the fitness of a member, such as lambda s: total(s.target.x, weights=payoff) for the payoff of a strategy against the others.

None
state str

The name of the state of the members that holds the share.

'x'

Raises:

Type Description
ValidationError

The fitness is not callable, raised by prepare.

Examples:

>>> from skcomplex.core.components.laws.utils import total
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.evolution import ReplicatorInteraction, StrategyElement
>>> population = StrategyElement('population', x=[0.5, 0.5], size=2)
>>> payoff = ((1.0, 1.0), (0.0, 0.0))
>>> replication = ReplicatorInteraction(
...     'replication', target='population', fitness=lambda s: total(s.target.x, weights=payoff)
... )
>>> system = System(elements=[population], interactions=[replication])
>>> trajectory = system.prepare().simulate(until=20.0, dt=0.1)
>>> [round(float(share), 3) for share in trajectory.get_values('population.x')[-1]]
[1.0, 0.0]
Source code in src/skcomplex/systems/biology/common/populations/_replicator.py
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(
    self,
    label: str,
    *,
    target: Role,
    fitness: Callable[[SimpleNamespace], object] | None = None,
    state: str = 'x',
) -> None:
    super().__init__(label)
    self.target = target
    self.state = state
    self.fitness = fitness

RockPaperScissorsSystem(shape=(60, 60), *, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

Rock, paper, and scissors on a lattice.

Cyclic invasions keep the three strategies coexisting.

Starting from random strategies, the strategies chase each other in domains and fronts, and each keeps about a third of the lattice. The system has the strategies lattice.strategy.

Parameters:

Name Type Description Default
shape Sequence[int]

The number of rows and columns of the periodic lattice.

(60, 60)
random_state int | Generator | None

The seed or generator of the initial strategies.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import RockPaperScissorsSystem
>>> RockPaperScissorsSystem((10, 10)).prepare().system_.elements[0].strategy.shape
(10, 10)
Source code in src/skcomplex/systems/biology/evolution/_games.py
279
280
281
282
283
284
285
286
287
288
289
290
def __init__(
    self,
    shape: Sequence[int] = (60, 60),
    *,
    random_state: int | np.random.Generator | None = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.shape = shape
    self.random_state = random_state

SoleManrubiaSystem(n=100, k=5, *, noise=0.05, seed=1, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The ecosystem of Solé and Manrubia.

Its species go extinct when their dependencies turn against them.

Every species depends on k species through couplings drawn from [-1, 1], and its field is the sum of these couplings. The couplings drift at random. A species whose field turns negative goes extinct, the species that depend on it lose a coupling, and their fields may turn negative in turn, so extinctions come in avalanches with a broad distribution of sizes. A new species with k random dependencies replaces every extinct one. The system has the fields species.h and ages species.age of the variable group species and the couplings couplings.w of the variable group couplings on the edges.

Parameters:

Name Type Description Default
n int

The number of species.

100
k int

The number of dependencies of every species.

5
noise float

The standard deviation of the drift of every coupling at a step.

0.05
seed int | None

The seed of the network and of the initial couplings.

1
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import SoleManrubiaSystem
>>> [component.label for component in SoleManrubiaSystem(n=20).prepare().system_.elements]
['species', 'couplings']
Source code in src/skcomplex/systems/biology/evolution/_networks.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
def __init__(
    self,
    n: int = 100,
    k: int = 5,
    *,
    noise: float = 0.05,
    seed: int | None = 1,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.n = n
    self.k = k
    self.noise = noise
    self.seed = seed

SpeciesElement(label, *, fitness=0.5, space=None)

Bases: Element

Species with a fitness in the unit interval, one per site of a space.

Parameters:

Name Type Description Default
label str

The label of the species.

required
fitness Annotated[float | Array, closed_open(0, oo)]

The initial fitness, one per species or shared.

0.5
space BaseSpace | None

The ring or the graph whose sites hold one species each, or None for one species.

None

Examples:

>>> from skcomplex.systems.biology.evolution import SpeciesElement
>>> SpeciesElement('species', fitness=0.2).fitness
0.2
Source code in src/skcomplex/systems/biology/evolution/_coevolution.py
62
63
64
65
66
67
68
69
70
def __init__(
    self,
    label: str,
    *,
    fitness: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.5,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.fitness = fitness

StrategyElement(label, *, x=0.5, size=None)

Bases: Element

Strategy of an evolutionary game, with the share x of players.

The share is the one of the population that plays the strategy.

Parameters:

Name Type Description Default
label str

The label of the strategy or of the group of strategies.

required
x Annotated[object, closed_open(0, oo)]

The initial share, one per strategy or shared.

0.5
size int | None

The number of strategies, or None for one.

None

Examples:

>>> from skcomplex.systems.biology.evolution import StrategyElement
>>> StrategyElement('hawks', x=0.4).x
0.4
Source code in src/skcomplex/systems/biology/evolution/_games.py
89
90
91
92
93
94
95
96
97
def __init__(
    self,
    label: str,
    *,
    x: Annotated[object, RealSet.closed_open(0, oo)] = 0.5,
    size: int | None = None,
) -> None:
    super().__init__(label, size=size)
    self.x = x

SubstitutionInteraction(label, *, target, N=100.0, mu=0.01, F0=1.0, couplings=None, state='s')

Bases: Interaction

Origin and fixation of mutants that flip one locus of a genome.

The genome is the one of a monomorphic population.

Every locus of each of the N individuals mutates at the rate mu, so mutants of a given locus arise at the rate N mu. A mutant from the fitness f to f' fixes with the Moran probability (1 - f / f') / (1 - (f / f')^N), so the allele s of the locus moves between -1 and 1 by transitions at the product of the two. The fitness is F0 + sum_i h_i s_i + sum_ij J_ij s_i s_j / 2, and a flip of locus i changes it by -2 s_i (h_i + sum_j J_ij s_j).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
target Role

The path of the group of loci.

required
N Annotated[float, open(0, oo)]

The size of the population.

100.0
mu Annotated[float, closed_open(0, oo)]

The rate at which one locus of an individual mutates.

0.01
F0 Annotated[float, open(0, oo)]

The fitness of a genome without fields and couplings, above the sum of the |h_i| and |J_ij| so that every fitness is positive.

1.0
couplings ArrayLike | None

The symmetric matrix J of couplings between loci, with a zero diagonal, or None for no couplings.

None
state str

The name of the state of the loci that holds the allele.

's'

Examples:

>>> from skcomplex.systems.biology.evolution import SubstitutionInteraction
>>> SubstitutionInteraction('substitution', target='genome', N=50.0).N
50.0
Source code in src/skcomplex/systems/biology/evolution/_substitutions.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def __init__(
    self,
    label: str,
    *,
    target: Role,
    N: Annotated[float, RealSet.open(0, oo)] = 100.0,
    mu: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
    F0: Annotated[float, RealSet.open(0, oo)] = 1.0,
    couplings: npt.ArrayLike | None = None,
    state: str = 's',
) -> None:
    super().__init__(label)
    self.target = target
    self.N = N
    self.mu = mu
    self.F0 = F0
    self.couplings = couplings
    self.state = state

TangledNatureLifeCycleInteraction(label, *, target, k=5.0, mu=0.01, p_mut=0.01, p_kill=0.2, length=8, seed=0, phase='generation')

Bases: BirthDeathInteraction

Life cycle of the organisms of the Tangled Nature system.

The cycle is run by the visits of a phase drawn with replacement.

A visited organism of type S reproduces with probability 1 / (1 + exp(-H(S))), where H(S) = k / N sum_S' J(S, S') n(S') - mu N reads the composition n of the population of N organisms, and is replaced by two offspring, whose genome bits flip with probability p_mut each. Then a random organism dies with probability p_kill. The couplings J are uniform in [-1, 1] between different types, 0 within a type, and fixed by seed.

Parameters:

Name Type Description Default
label str

The label of the life cycle.

required
target Role

The path of the variable group of organisms.

required
k Annotated[float, closed_open(0, oo)]

The strength of the couplings.

5.0
mu Annotated[float, closed_open(0, oo)]

The limit of resources, which lowers reproduction in large populations.

0.01
p_mut Annotated[float, closed_open(0, oo)]

The probability that a bit of an offspring's genome flips.

0.01
p_kill Annotated[float, closed_open(0, oo)]

The probability that a visit kills a random organism.

0.2
length int

The number of bits of a genome.

8
seed int

The seed of the couplings.

0
phase str | None

The phase whose visits run the life cycle.

'generation'

Examples:

>>> from skcomplex.systems.biology.evolution import TangledNatureLifeCycleInteraction
>>> TangledNatureLifeCycleInteraction('evolution', target='organisms').offspring
2
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def __init__(
    self,
    label: str,
    *,
    target: Role,
    k: Annotated[float, RealSet.closed_open(0, oo)] = 5.0,
    mu: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
    p_mut: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
    p_kill: Annotated[float, RealSet.closed_open(0, oo)] = 0.2,
    length: int = 8,
    seed: int = 0,
    phase: str | None = 'generation',
) -> None:
    super().__init__(
        label,
        target=target,
        birth=self.compute_birth,
        offspring=2,
        inherit=('trait',),
        mutate=self.mutate_genome,
        schedule='member',
        phase=phase,
        replace=True,
        cull=self.compute_kill,
        pick='random',
    )
    self.k = k
    self.mu = mu
    self.p_mut = p_mut
    self.p_kill = p_kill
    self.length = length
    self.seed = seed

compute_birth(agent, system)

Return the probability that an organism of type S reproduces.

The probability is 1 / (1 + exp(-H(S))).

Parameters:

Name Type Description Default
agent IndividualView

The organism.

required
system SystemView

The system view of the life cycle.

required

Returns:

Name Type Description
probability float

The probability of reproduction.

Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def compute_birth(self, agent: IndividualView, system: SystemView) -> float:
    """Return the probability that an organism of type `S` reproduces.

    The probability is `1 / (1 + exp(-H(S)))`.

    Args:
        agent:
            The organism.

        system:
            The system view of the life cycle.

    Returns:
        probability:
            The probability of reproduction.
    """
    composition = system.get_composition('target', 'trait')
    size = sum(composition.values())
    row = self._get_couplings(self.seed, self.length)[int(agent.trait)]
    coupling = sum(row[int(np.asarray(genome))] * count for genome, count in composition.items())
    return float(expit(system.get_parameter('k') / size * coupling - system.get_parameter('mu') * size))

compute_kill(agent, system)

Return the probability p_kill that a visit kills a random organism.

Parameters:

Name Type Description Default
agent IndividualView

The visited organism.

required
system SystemView

The system view of the life cycle.

required

Returns:

Name Type Description
probability float

The probability of a death.

Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
def compute_kill(self, agent: IndividualView, system: SystemView) -> float:
    """Return the probability `p_kill` that a visit kills a random organism.

    Args:
        agent:
            The visited organism.

        system:
            The system view of the life cycle.

    Returns:
        probability:
            The probability of a death.
    """
    return system.get_parameter('p_kill')

mutate_genome(values, system)

Return the values of an offspring with mutated genome bits.

Every genome bit flips with probability p_mut.

Parameters:

Name Type Description Default
values dict[str, object]

The values of the offspring, with the genome of its parent as trait.

required
system SystemViewProtocol

The system view of the life cycle.

required

Returns:

Name Type Description
values dict[str, object]

The values with the mutated genome.

Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def mutate_genome(self, values: dict[str, object], system: SystemViewProtocol) -> dict[str, object]:
    """Return the values of an offspring with mutated genome bits.

    Every genome bit flips with probability `p_mut`.

    Args:
        values:
            The values of the offspring, with the genome of its parent as `trait`.

        system:
            The system view of the life cycle.

    Returns:
        values:
            The values with the mutated genome.
    """
    genome = int(np.asarray(values['trait'], dtype=float))
    flips = np.flatnonzero(system.rng.random(self.length) < system.get_parameter('p_mut'))
    return {**values, 'trait': float(genome ^ sum(1 << int(locus) for locus in flips))}

TangledNatureSystem(organisms=100, *, k=5.0, mu=0.01, p_mut=0.01, p_kill=0.2, length=8, seed=0, random_state=0, label='system', solver='auto', backend='auto')

Bases: BaseSystem

The Tangled Nature system of coevolving organisms.

The types of the organisms interact through random couplings.

Organisms of one random type start the run. Mutants spread through the space of genomes, and the population settles into quasi-stable configurations of a few dominant types, the q-ESS, that end in abrupt transitions, a punctuated equilibrium. The trait of an organism holds the bits of its genome. A generation is N / p_kill visits to organisms drawn with replacement, where N is the population at its start. The system has the group organisms.

Parameters:

Name Type Description Default
organisms int

The initial number of organisms.

100
k float

The strength of the couplings.

5.0
mu float

The limit of resources, which lowers reproduction in large populations.

0.01
p_mut float

The probability that a bit of an offspring's genome flips.

0.01
p_kill float

The probability that a chosen organism dies.

0.2
length int

The number of bits of a genome.

8
seed int

The seed of the couplings.

0
random_state int | Generator | None

The seed or generator of the initial type.

0
label str

The label of the system, which names it when it is nested in another one.

'system'
solver BaseSolver | str

The solver of the problem, or 'auto' for the one the system chooses.

'auto'
backend BaseBackend | str

The backend that evaluates the compiled functions, or 'auto' for the one the system chooses.

'auto'

Examples:

>>> from skcomplex.systems.biology.evolution import TangledNatureSystem
>>> TangledNatureSystem(20).prepare().system_.elements[0].size
20
Source code in src/skcomplex/systems/biology/evolution/_finite_populations.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def __init__(
    self,
    organisms: int = 100,
    *,
    k: float = 5.0,
    mu: float = 0.01,
    p_mut: float = 0.01,
    p_kill: float = 0.2,
    length: int = 8,
    seed: int = 0,
    random_state: int | np.random.Generator | None = 0,
    label: str = 'system',
    solver: BaseSolver | str = 'auto',
    backend: BaseBackend | str = 'auto',
) -> None:
    super().__init__(label, solver=solver, backend=backend)
    self.organisms = organisms
    self.k = k
    self.mu = mu
    self.p_mut = p_mut
    self.p_kill = p_kill
    self.length = length
    self.seed = seed
    self.random_state = random_state

TaxonElement(label, *, h=1.0, age=0.0, space=None)

Bases: Element

Species of an ecosystem with its field and its age.

The field is the sum of the couplings of the species it depends on.

A species whose field is negative goes extinct, and a new species takes its niche.

Parameters:

Name Type Description Default
label str

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

required
h float | Array

The field, the sum of the couplings of its dependencies.

1.0
age Annotated[float | Array, closed_open(0, oo)]

The number of steps since the species appeared.

0.0
space BaseSpace | None

The network whose nodes hold one species each, or None for one species.

None

Examples:

>>> from skcomplex.systems.biology.evolution import TaxonElement
>>> TaxonElement('species').h
1.0
Source code in src/skcomplex/systems/biology/evolution/_networks.py
184
185
186
187
188
189
190
191
192
193
194
def __init__(
    self,
    label: str,
    *,
    h: float | Array = 1.0,
    age: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.0,
    space: BaseSpace | None = None,
) -> None:
    super().__init__(label, space=space)
    self.h = h
    self.age = age

fold_sequence(sequence) cached

Return the minimum free energy secondary structure of an RNA sequence.

It also returns its energy, at 37 °C, memoised.

Parameters:

Name Type Description Default
sequence str

The sequence over the letters ACGU.

required

Returns:

Name Type Description
fold tuple[str, float]

The structure in dot-bracket notation and its free energy in kcal/mol.

Raises:

Type Description
MissingExtraError

The extra rna is not installed.

Examples:

>>> from skcomplex.systems.biology.evolution import fold_sequence
>>> structure, energy = fold_sequence('GGGGAAACCCC')
>>> structure, energy < 0
('((((...))))', True)
Source code in src/skcomplex/systems/biology/evolution/_rna_walks.py
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
@lru_cache(maxsize=FOLD_CACHE)
def fold_sequence(sequence: str) -> tuple[str, float]:
    """Return the minimum free energy secondary structure of an RNA sequence.

    It also returns its energy, at 37 °C, memoised.

    Args:
        sequence:
            The sequence over the letters `ACGU`.

    Returns:
        fold:
            The structure in dot-bracket notation and its free energy in kcal/mol.

    Raises:
        MissingExtraError:
            The extra `rna` is not installed.

    Examples:
        >>> from skcomplex.systems.biology.evolution import fold_sequence
        >>> structure, energy = fold_sequence('GGGGAAACCCC')
        >>> structure, energy < 0
        ('((((...))))', True)
    """
    structure, energy = import_extra('RNA', SYSTEM, EXTRA).fold_compound(sequence).mfe()
    return str(structure), float(energy)

mutate_point(row, random)

Return a row of indices of bases with one random site mutated.

The base at the site is replaced by one of the other three.

Parameters:

Name Type Description Default
row ndarray

The indices of the bases, which the function changes.

required
random Generator

The random generator.

required

Returns:

Name Type Description
row ndarray

The row after the mutation.

Examples:

>>> import numpy as np
>>> from skcomplex.systems.biology.evolution import mutate_point
>>> row = mutate_point(np.zeros(4), np.random.default_rng(0))
>>> int((row != 0).sum())
1
Source code in src/skcomplex/systems/biology/evolution/_rna_walks.py
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
def mutate_point(row: np.ndarray, random: np.random.Generator) -> np.ndarray:
    """Return a row of indices of bases with one random site mutated.

    The base at the site is replaced by one of the other three.

    Args:
        row:
            The indices of the bases, which the function changes.

        random:
            The random generator.

    Returns:
        row:
            The row after the mutation.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.systems.biology.evolution import mutate_point
        >>> row = mutate_point(np.zeros(4), np.random.default_rng(0))
        >>> int((row != 0).sum())
        1
    """
    site = random.integers(row.size)
    row[site] = (row[site] + random.integers(1, len(BASES))) % len(BASES)
    return row

neutral_network(source, *, phenotype_of, kind='network', alphabet='ACGU', state=None)

Return the neutral networks of a map from sequences to phenotypes.

It returns their robustness and evolvability instead on request.

The neighbours of a genotype are the sequences one point mutation away. Its robustness is the number of its neighbours of the same phenotype, and its evolvability the number of different phenotypes among its neighbours. The robustness of a phenotype is the mean robustness of its genotypes, and its evolvability the number of different phenotypes among the neighbours of all its genotypes. The definitions follow Wagner (2008), as Raman (2021, §13.3) states them, so the phenotype of a genotype itself counts when a neighbour has it.

Parameters:

Name Type Description Default
source object

A trajectory whose lattice state holds one sequence per row, an array of strings, or an array of letters on its last axis.

required
phenotype_of Callable[[str], Hashable]

The function from a sequence to a phenotype key.

required
kind str

'network', 'genotype-robustness', 'genotype-evolvability', 'phenotype-robustness', or 'phenotype-evolvability'.

'network'
alphabet Sequence[str]

The letters of the sequences.

'ACGU'
state str | None

The dotted name of the lattice state of a trajectory that holds one sequence per row, or None for the first state.

None

Returns:

Name Type Description
result NeutralNetworkResult

The sequences, and the networks or the values of the kind.

Raises:

Type Description
AnalysisError

The kind is unknown, the mapping is not callable, or a sequence holds a letter outside the alphabet.

Examples:

>>> import itertools
>>> from skcomplex.systems.biology.evolution import neutral_network
>>> genotypes = [''.join(letters) for letters in itertools.product('01', repeat=4)]
>>> result = neutral_network(
...     genotypes, phenotype_of=lambda sequence: sequence[0], kind='genotype-robustness', alphabet='01'
... )
>>> set(result.values.tolist())
{3.0}
Source code in src/skcomplex/systems/biology/evolution/_neutral_network_analysis.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def neutral_network(
    source: object,
    *,
    phenotype_of: Callable[[str], Hashable],
    kind: str = 'network',
    alphabet: Sequence[str] = 'ACGU',
    state: str | None = None,
) -> NeutralNetworkResult:
    """Return the neutral networks of a map from sequences to phenotypes.

    It returns their robustness and evolvability instead on request.

    The neighbours of a genotype are the sequences one point mutation away. Its robustness is the number of its
    neighbours of the same phenotype, and its evolvability the number of different phenotypes among its neighbours. The
    robustness of a phenotype is the mean robustness of its genotypes, and its evolvability the number of different
    phenotypes among the neighbours of all its genotypes. The definitions follow Wagner (2008), as Raman (2021, §13.3)
    states them, so the phenotype of a genotype itself counts when a neighbour has it.

    Args:
        source:
            A trajectory whose lattice state holds one sequence per row, an array of strings, or an array of letters
            on its last axis.

        phenotype_of:
            The function from a sequence to a phenotype key.

        kind:
            `'network'`, `'genotype-robustness'`, `'genotype-evolvability'`, `'phenotype-robustness'`, or
            `'phenotype-evolvability'`.

        alphabet:
            The letters of the sequences.

        state:
            The dotted name of the lattice state of a trajectory that holds one sequence per row, or `None` for the
            first state.

    Returns:
        result:
            The sequences, and the networks or the values of the kind.

    Raises:
        AnalysisError:
            The kind is unknown, the mapping is not callable, or a sequence holds a letter outside the alphabet.

    Examples:
        >>> import itertools
        >>> from skcomplex.systems.biology.evolution import neutral_network
        >>> genotypes = [''.join(letters) for letters in itertools.product('01', repeat=4)]
        >>> result = neutral_network(
        ...     genotypes, phenotype_of=lambda sequence: sequence[0], kind='genotype-robustness', alphabet='01'
        ... )
        >>> set(result.values.tolist())
        {3.0}
    """
    if kind not in KINDS:
        error_msg = f'neutral_network has kind={kind!r}. Use one of {", ".join(KINDS)}.'
        raise AnalysisError(error_msg)
    if not callable(phenotype_of):
        error_msg = f'neutral_network reads a function from sequences, not {phenotype_of!r}.'
        raise AnalysisError(error_msg)
    genotypes = _read_sequences(source, state)
    foreign = {letter for sequence in genotypes.flat for letter in sequence} - set(alphabet)
    if foreign:
        error_msg = f'The sequences hold the letters {sorted(foreign)}, which the alphabet {alphabet} lacks.'
        raise AnalysisError(error_msg)
    if kind == 'network':
        networks = {key: _network(items, alphabet) for key, items in _by_phenotype(genotypes, phenotype_of).items()}
        return NeutralNetworkResult(genotypes, networks=networks)
    values: np.ndarray | dict[Hashable, float]
    if kind == 'genotype-robustness':
        values = np.vectorize(lambda item: _robustness(item, phenotype_of, alphabet), otypes=[float])(genotypes)
    elif kind == 'genotype-evolvability':
        values = np.vectorize(
            lambda item: float(len(_neighbouring_phenotypes(item, phenotype_of, alphabet))),
            otypes=[float],
        )(genotypes)
    elif kind == 'phenotype-robustness':
        values = {
            key: float(np.mean([_robustness(item, phenotype_of, alphabet) for item in items]))
            for key, items in _by_phenotype(genotypes, phenotype_of).items()
        }
    else:
        values = {
            key: float(
                len(set().union(*(_neighbouring_phenotypes(item, phenotype_of, alphabet) for item in items))),
            )
            for key, items in _by_phenotype(genotypes, phenotype_of).items()
        }
    return NeutralNetworkResult(genotypes, values=values)

read_base_pair_distance(first, second)

Return the number of base pairs that only one of two secondary structures holds.

The structures have one length.

Parameters:

Name Type Description Default
first str

The first structure in dot-bracket notation.

required
second str

The second structure in dot-bracket notation.

required

Returns:

Name Type Description
distance int

The base-pair distance.

Raises:

Type Description
MissingExtraError

The extra rna is not installed.

Examples:

>>> from skcomplex.systems.biology.evolution import read_base_pair_distance
>>> read_base_pair_distance('((((...))))', '.(((...))).')
1
Source code in src/skcomplex/systems/biology/evolution/_rna_walks.py
 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
def read_base_pair_distance(first: str, second: str) -> int:
    """Return the number of base pairs that only one of two secondary structures holds.

    The structures have one length.

    Args:
        first:
            The first structure in dot-bracket notation.

        second:
            The second structure in dot-bracket notation.

    Returns:
        distance:
            The base-pair distance.

    Raises:
        MissingExtraError:
            The extra `rna` is not installed.

    Examples:
        >>> from skcomplex.systems.biology.evolution import read_base_pair_distance
        >>> read_base_pair_distance('((((...))))', '.(((...))).')
        1
    """
    return int(import_extra('RNA', SYSTEM, EXTRA).bp_distance(first, second))

read_plane_layout(structure)

Return the positions in a plane of the bases of a secondary structure.

The positions follow the simple layout of ViennaRNA.

Parameters:

Name Type Description Default
structure str

The structure in dot-bracket notation.

required

Returns:

Name Type Description
positions NDArray[float64]

One row of two coordinates per base.

Raises:

Type Description
MissingExtraError

The extra rna is not installed.

Examples:

>>> from skcomplex.systems.biology.evolution import read_plane_layout
>>> read_plane_layout('((((...))))').shape
(11, 2)
Source code in src/skcomplex/systems/biology/evolution/_rna_walks.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def read_plane_layout(structure: str) -> npt.NDArray[np.float64]:
    """Return the positions in a plane of the bases of a secondary structure.

    The positions follow the simple layout of ViennaRNA.

    Args:
        structure:
            The structure in dot-bracket notation.

    Returns:
        positions:
            One row of two coordinates per base.

    Raises:
        MissingExtraError:
            The extra `rna` is not installed.

    Examples:
        >>> from skcomplex.systems.biology.evolution import read_plane_layout
        >>> read_plane_layout('((((...))))').shape
        (11, 2)
    """
    layout = import_extra('RNA', SYSTEM, EXTRA).simple_xy_coordinates(structure)
    return np.array([[point.X, point.Y] for point in layout[: len(structure)]], dtype=float)

read_sequence(row)

Return the sequence of a row of indices of bases.

Parameters:

Name Type Description Default
row ndarray

The indices of the bases.

required

Returns:

Name Type Description
sequence str

The sequence over the letters ACGU.

Examples:

>>> import numpy as np
>>> from skcomplex.systems.biology.evolution import read_sequence
>>> read_sequence(np.array([0.0, 3.0, 2.0]))
'AUG'
Source code in src/skcomplex/systems/biology/evolution/_rna_walks.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def read_sequence(row: np.ndarray) -> str:
    """Return the sequence of a row of indices of bases.

    Args:
        row:
            The indices of the bases.

    Returns:
        sequence:
            The sequence over the letters `ACGU`.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.systems.biology.evolution import read_sequence
        >>> read_sequence(np.array([0.0, 3.0, 2.0]))
        'AUG'
    """
    return ''.join(BASES[int(value)] for value in row)