Skip to content

Tangled Nature

The Tangled Nature system of coevolving organisms.

  • Class: TangledNatureSystem
  • Import: from skcomplex.systems.biology.evolution import TangledNatureSystem
  • Field: biology/evolution
  • Topics: coevolution, agents, punctuated equilibrium, ecosystems
  • References:
    • Christensen et al. 2002
    • Jensen 2023

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.biology.evolution import TangledNatureSystem

trajectory = TangledNatureSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
organisms 100
k 5.0
mu 0.01
p_mut 0.01
p_kill 0.2
length 8
seed 0
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space none
Laws update
Randomness stochastic
Domains integer, real
Structure variable membership

Class

The source of the class shows how it builds its components from its model parameters.

class TangledNatureSystem(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`.

    Args:
        organisms:
            The initial number of organisms.

        k:
            The strength of the couplings.

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

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

        p_kill:
            The probability that a chosen organism dies.

        length:
            The number of bits of a genome.

        seed:
            The seed of the couplings.

        random_state:
            The seed or generator of the initial type.

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

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

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

    Examples:
        >>> from skcomplex.systems.biology.evolution import TangledNatureSystem
        >>> TangledNatureSystem(20).prepare().system_.elements[0].size
        20
    """

    field = 'biology/evolution'
    topics = ('coevolution', 'agents', 'punctuated equilibrium', 'ecosystems')
    references = ('Christensen et al. 2002', 'Jensen 2023')
    until = 50

    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

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the Tangled Nature system.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        genome = float(np.random.default_rng(self.random_state).integers(2**self.length))
        life_cycle = TangledNatureLifeCycleInteraction(
            'evolution',
            target=ORGANISMS,
            k=self.k,
            mu=self.mu,
            p_mut=self.p_mut,
            p_kill=self.p_kill,
            length=self.length,
            seed=self.seed,
        )
        self.system_ = System(
            self.label,
            elements=[TangledOrganismElement(ORGANISMS, trait=genome, size=self.organisms)],
            interactions=[life_cycle],
            solver=MesaSolver(phases=[PhaseSpec('generation', activation='visits', visits=1 / self.p_kill)]),
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

  • TangledOrganismElement, from Element

Interactions:

class TangledOrganismElement(IndividualElement):
    """Organism of the Tangled Nature system, drawn by its distinct genomes."""

    visual = VisualSpec('histograms', {'color_by': 'trait', 'shown': ('distinct',)})

class TangledNatureLifeCycleInteraction(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`.

    Args:
        label:
            The label of the life cycle.

        target:
            The path of the variable group of organisms.

        k:
            The strength of the couplings.

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

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

        p_kill:
            The probability that a visit kills a random organism.

        length:
            The number of bits of a genome.

        seed:
            The seed of the couplings.

        phase:
            The phase whose visits run the life cycle.

    Examples:
        >>> from skcomplex.systems.biology.evolution import TangledNatureLifeCycleInteraction
        >>> TangledNatureLifeCycleInteraction('evolution', target='organisms').offspring
        2
    """

    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

    @staticmethod
    @lru_cache(maxsize=16)
    def _get_couplings(seed: int, length: int) -> Array:
        """Return the random couplings `J(S, S')`, uniform in [-1, 1] and 0 within a type."""
        size = 2**length
        couplings = np.random.default_rng(seed).uniform(-1.0, 1.0, size=(size, size))
        np.fill_diagonal(couplings, 0.0)
        return couplings

    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))

    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')

    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))}

Equations

The equations are those that symbolic returns for the system with its default parameters.