Skip to content

Solé-Manrubia extinctions

The ecosystem of Solé and Manrubia.

  • Class: SoleManrubiaSystem
  • Import: from skcomplex.systems.biology.evolution import SoleManrubiaSystem
  • Field: biology/evolution
  • Topics: adaptive network, extinction, avalanches, coevolution, stochastic map
  • References:
    • Solé and Manrubia 1996
    • Thurner et al. 2018

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 SoleManrubiaSystem

trajectory = SoleManrubiaSystem().prepare().simulate()

Parameters

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

Parameter Default
n 100
k 5
noise 0.05
seed 1
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 network
Laws update
Randomness unknown
Domains boolean, real
Structure variable membership

Class

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

class SoleManrubiaSystem(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.

    Args:
        n:
            The number of species.

        k:
            The number of dependencies of every species.

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

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

        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 SoleManrubiaSystem
        >>> [component.label for component in SoleManrubiaSystem(n=20).prepare().system_.elements]
        ['species', 'couplings']
    """

    field = 'biology/evolution'
    topics = ('adaptive network', 'extinction', 'avalanches', 'coevolution', 'stochastic map')
    references = ('Solé and Manrubia 1996', 'Thurner et al. 2018')
    until = 300
    dt = 1.0

    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

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the ecosystem of Solé and Manrubia.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        rng = np.random.default_rng(self.seed)
        graph = nx.DiGraph()
        graph.add_nodes_from(range(self.n))
        for node in range(self.n):
            others = rng.choice(np.delete(np.arange(self.n), node), size=self.k, replace=False)
            graph.add_edges_from((node, int(other)) for other in others)
        space = NetworkSpace(graph).prepare()
        edges = graph.number_of_edges()
        couplings = rng.uniform(-1, 1, edges)
        sources, _ = space.edges_[None]
        fields = np.bincount(sources, weights=couplings, minlength=self.n)
        species = TaxonElement('species', h=fields, space=space)
        edge_group = CouplingEdgeElement('couplings', w=couplings, fresh=np.zeros(edges), space=space, on='edges')
        self.system_ = System(
            self.label,
            elements=[species, edge_group],
            interactions=[
                DependencyFieldInteraction('field', species='species', couplings='couplings'),
                EdgeDrawInteraction('drift', among='species', noise=self.noise),
                Interaction(
                    'ageing',
                    roles={'target': 'species'},
                    laws=lambda s: [UpdateLaw(s.target.age, s.target.age + 1, increment=True)],
                ),
                Interaction('extinction', roles={'nodes': 'species'}, laws=self._get_extinction, along=True),
            ],
        )

    def _get_extinction(self, s: SimpleNamespace) -> list[BaseLaw]:
        """Return the replacement of a species whose field turns negative by a new species."""
        return [UpdateLaw(TopologyRequestSpec('replace-node', self.k), where(s.source.h < 0, 1, 0))]

Components

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

Elements:

Interactions:

  • DependencyFieldInteraction, from Interaction
  • EdgeDrawInteraction, from Interaction
  • Interaction
class TaxonElement(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.

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

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

        age:
            The number of steps since the species appeared.

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

    Examples:
        >>> from skcomplex.systems.biology.evolution import TaxonElement
        >>> TaxonElement('species').h
        1.0
    """

    visual = VisualSpec('sites', {'states': ['age']})

    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

class CouplingEdgeElement(WeightedEdgeElement):
    """Coupling of one species to another, hidden from the drawing."""

    visual = VisualSpec('sites', {'states': []})

class DependencyFieldInteraction(Interaction):
    """Field of every species.

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

    Args:
        label:
            The label of the interaction.

        species:
            The path of the group of species on the nodes.

        couplings:
            The path of the variable group on the edges.

    Examples:
        >>> from skcomplex.systems.biology.evolution import DependencyFieldInteraction
        >>> DependencyFieldInteraction('field', species='species', couplings='couplings').couplings
        'couplings'
    """

    law_classes = (UpdateLaw,)

    def __init__(
        self,
        label: str,
        *,
        species: Role,
        couplings: Role,
    ) -> None:
        super().__init__(label)
        self.species = species
        self.couplings = couplings

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the field of every species.

        Args:
            context:
                The namespace with `context.species` and `context.couplings`.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [UpdateLaw(context.species.h, neighbors(1, weight=context.couplings.w))]

class EdgeDrawInteraction(Interaction):
    """First draw of the weight of every new edge of a network.

    The weights of the other edges drift at random.

    Every step of discrete time an edge marked `fresh` draws its weight uniformly from `[low, high]` and loses its mark,
    and every other edge adds `noise` times a standard normal draw to its weight, or keeps it without noise.

    Args:
        label:
            The label of the interaction.

        among:
            The path of the group on the nodes of the network. The weight and the mark are values of the group on its
            edges.

        noise:
            The standard deviation of the drift of a weight in a step, 0 for none.

        low:
            The least weight of a new edge.

        high:
            The largest weight of a new edge.

        state:
            The name of the state of the edges that holds the weight.

        along:
            The edges the laws run on, `True` for the edges of the network the group lives on, or the name of a layer.

    Examples:
        >>> from skcomplex.systems.biology.common.networks import EdgeDrawInteraction
        >>> EdgeDrawInteraction('draw', among='species', noise=0.1).noise
        0.1
    """

    law_classes = (UpdateLaw,)

    def __init__(
        self,
        label: str,
        *,
        among: Role,
        noise: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        low: float = -1.0,
        high: float = 1.0,
        state: str = 'w',
        along: bool | str = True,
    ) -> None:
        super().__init__(label, among=among, along=along)
        self.noise = noise
        self.low = low
        self.high = high
        self.state = state

    def _get_name(self, draw: str) -> str:
        """Return the name of a random draw of the interaction."""
        return re.sub(r'\W', '_', f'{draw}_{self.label}')

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the draw or the drift of the weight of an edge, and the removal of the mark of the edge.

        Args:
            context:
                The namespace of an edge, with the member `context.edge` of the group on the edges.
        """
        super()._prepare(context)
        edge = context.edge
        weight = getattr(edge, self.state)
        drawn = uniform(self._get_name('draw'), self.low, self.high)
        kept = weight + context.noise * normal(self._get_name('drift')) if self.noise else weight
        self.laws_: list[BaseLaw] = [
            UpdateLaw(weight, where(edge.fresh > 1 / 2, drawn, kept)),
            UpdateLaw(edge.fresh, 0),
        ]

class Interaction(BaseInteraction):
    """An interaction whose laws run once for the elements its roles bind.

    It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
    `Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
    role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
    edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
    random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
    members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
    parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
    populations, a reaction between two chemicals, and an infection along the contacts of a network.

    Read more in the user guide, under Interactions.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'predation'`.

        roles:
            The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
            without a class, or `None`.

        laws:
            The function of the namespace that returns the laws of a rule written without a class, such as
            `lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
            `None`.

        among:
            The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
            their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

        along:
            `True` for the edges of the network the group lives on, the name of a layer of a network with several, such
            as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
            `RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
            member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
            element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.

        within:
            A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
            closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
            walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
            give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
            force `-dV/dx` on its position `x`.

    See Also:
        BaseInteraction: The base of every interaction.
        RandomPartition: Groups the members of a group at random at every step.
        TrainingInteraction: Trains the parameters of a nested system.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
        >>> birth.roles
        {'target': 'fish'}
    """

    def __init__(
        self,
        label: str,
        *,
        roles: Mapping[str, object] | None = None,
        laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
        among: str | None = None,
        along: bool | str | tuple[str, int] | RandomPartition | None = None,
        within: RadiusNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.roles = roles
        self.laws = laws
        self.among = among
        self.along = along
        self.within = within

    def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
        """Return the numeric arguments as parameters, and `roles` and `among` as roles.

        With `within`, `among` binds both members of a pair, `first` and `second`.
        """
        declared = dict(super()._get_declared())
        for name, binding in (self.roles or {}).items():
            declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
        if self.among is not None and self.within is not None:
            for name in PAIR_ROLES:
                declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
        elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
            declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
        return declared

    @classmethod
    def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
        """Return the arguments that name the states a role reads.

        The mapping `roles` of bindings names none.
        """
        return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')

    def _get_binding(self, role: str) -> object:
        """Return what a role binds, from `roles` or from the argument of its name.

        Args:
            role:
                The name of the role.

        Returns:
            binding:
                The label, labels, or entries the role binds, or `None` when it binds nothing.
        """
        if self.roles is not None and role in self.roles:
            return self.roles[role]
        if self.among is not None and self.within is not None and role in PAIR_ROLES:
            return self.among
        return super()._get_binding(role)

    def _check_arguments(self) -> None:
        """Raise an error for roles, laws, or groups the interaction cannot take.

        Raises:
            ValidationError:
                A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
                `along` names hyperedges of fewer than two members.
        """
        clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
        if clashes:
            error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
            raise ValidationError(error_msg)
        if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
            error_msg = (
                f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
                '`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, tuple) and not self._is_sized(self.along):
            error_msg = (
                f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
                "more, such as `along=('hyperedges', 3)`."
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, RandomPartition):
            self.along._check()
        grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
        if grouped and self.among is None:
            error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
            raise ValidationError(error_msg)
        super()._check_arguments()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of `laws` for a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        if self.laws is not None:
            self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)

    @staticmethod
    def _is_sized(along: tuple[object, ...]) -> bool:
        """Return whether `along` names hyperedges of a whole size of at least two."""
        if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
            return False
        size = along[1]
        return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE

    def _get_draws(self) -> bool:
        """Return whether the interaction draws, as it does along random groups."""
        return super()._get_draws() or isinstance(self.along, RandomPartition)

    def _runs_on_edges(self) -> bool:
        """Return whether the interaction runs along edges."""
        grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
        return self.along is not None and self.along is not False and not grouped

    def _runs_on_hyperedges(self) -> bool:
        """Return whether the interaction runs along the hyperedges of a network."""
        return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)

    def _get_hyperedge_size(self) -> int | None:
        """Return the size `along` gives the hyperedges, or `None` for every size."""
        return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None

    def _get_within(self) -> RadiusNeighborhood | None:
        """Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
        return self.within

    def _get_layer(self) -> str | None:
        """Return the layer `along` names, or `None` for no layer."""
        if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
            return None
        return self.along

    def _get_grouping(self) -> tuple[str, int, str] | None:
        """Return the kind, size, and reduction of the groups `along` names, or `None`."""
        if isinstance(self.along, RandomPartition):
            return ('partition', self.along.size, 'sum')
        if self.along == NEIGHBORHOODS:
            return ('neighborhood', 0, 'sum')
        return None