Skip to content

Adaptive SIS with rewiring

The SIS epidemic where susceptible nodes cut their edges to infected neighbours.

  • Class: AdaptiveSISSystem
  • Import: from skcomplex.systems.biology.epidemiology import AdaptiveSISSystem
  • Field: biology/epidemiology
  • Topics: network, adaptive network, rewiring, jumps, epidemic threshold
  • References:
    • Gross, Dommar D'Lima, and Blasius 2006
    • Thurner et al. 2018
    • Pastor-Satorras et al. 2015

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.epidemiology import AdaptiveSISSystem

trajectory = AdaptiveSISSystem().prepare().simulate()

Parameters

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

Parameter Default
n 200
k 6.0
beta 0.4
gamma 1.0
w 1.0
infected 0.2
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 continuous
Space network
Laws jump
Randomness stochastic
Domains real
Structure variable membership

Class

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

class AdaptiveSISSystem(BaseSystem):
    """The SIS epidemic where susceptible nodes cut their edges to infected neighbours.

    Every edge between a susceptible and an infected node is rewired at rate `w`: the susceptible end keeps it and joins
    it to another susceptible node. Rewiring isolates the infected nodes and raises the epidemic threshold above its
    value on the fixed network, while the susceptible nodes cluster. The system has the states `hosts.i` of the variable
    group `hosts` on the nodes and the variable group `contacts` on the edges.

    Args:
        n:
            The number of nodes.

        k:
            The mean degree of the initial Erdős-Rényi network.

        beta:
            The infection rate per edge to an infected neighbour.

        gamma:
            The recovery rate.

        w:
            The rewiring rate of an edge between a susceptible and an infected node.

        infected:
            The initial share of infected nodes.

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

        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.epidemiology import AdaptiveSISSystem
        >>> [component.label for component in AdaptiveSISSystem(n=20).prepare().system_.elements]
        ['hosts', 'contacts']
    """

    field = 'biology/epidemiology'
    topics = ('network', 'adaptive network', 'rewiring', 'jumps', 'epidemic threshold')
    references = ("Gross, Dommar D'Lima, and Blasius 2006", 'Thurner et al. 2018', 'Pastor-Satorras et al. 2015')
    until = 30.0
    dt = 0.25

    def __init__(
        self,
        n: int = 200,
        k: float = 6.0,
        *,
        beta: float = 0.4,
        gamma: float = 1.0,
        w: float = 1.0,
        infected: float = 0.2,
        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.beta = beta
        self.gamma = gamma
        self.w = w
        self.infected = infected
        self.seed = seed

    @staticmethod
    def _get_susceptible(node: SimpleNamespace) -> object:
        """Return the weight of a candidate new end of an edge.

        The weight is 1 for a susceptible node and 0 otherwise.
        """
        return 1 - node.i

    def _get_rewiring(self, keep: str) -> Interaction:
        """Return the rewiring of edges from a susceptible end `keep` to an infected end."""
        other = 'target' if keep == 'source' else 'source'

        def rewire(edge: SimpleNamespace) -> list[BaseLaw]:
            """Return the rewiring of the edge at the rate of its susceptible end.

            The susceptible end rewires the edge away from the infected end.
            """
            kept, left = getattr(edge, keep), getattr(edge, other)
            request = TopologyRequestSpec('rewire', toward=self._get_susceptible, keep=keep)
            return [JumpLaw(kept.w * (1 - kept.i) * left.i, {request: 1})]

        return Interaction(f'rewiring_{keep}', roles={'nodes': 'hosts'}, laws=rewire, along=True)

    @staticmethod
    def _get_random_network(n: int, k: float, seed: int | None) -> NetworkSpace:
        """Return an Erdős-Rényi network of `n` nodes with mean degree `k`."""
        return NetworkSpace(nx.gnp_random_graph(n, k / (n - 1), seed=seed))

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the SIS epidemic on a network.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        space = self._get_random_network(self.n, self.k, self.seed)
        initial = (np.random.default_rng(self.seed).random(self.n) < self.infected).astype(float)
        hosts = AdaptiveHostElement('hosts', i=initial, w=self.w, space=space)
        contacts = ContactEdgeElement('contacts', space=space, on='edges')
        spreading = SpreadingInteraction('spreading', target='hosts', state='i', beta=self.beta, gamma=self.gamma)
        self.system_ = System(
            self.label,
            elements=[hosts, contacts],
            interactions=[spreading, self._get_rewiring('source'), self._get_rewiring('target')],
        )

Components

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

Elements:

Interactions:

  • SpreadingInteraction, from Interaction
  • Interaction
class AdaptiveHostElement(HostElement):
    """Host of an adaptive network, drawn by whether it is infected."""

    visual = VisualSpec('sites', {'states': ['i'], 'low': 0, 'high': 1})

class ContactEdgeElement(Element):
    """Contact between two hosts, hidden from the drawing."""

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

class SpreadingInteraction(Interaction):
    """Spreading of the active value of a discrete state to neighbours.

    The neighbours are along the edges of a network or the bonds of a lattice.

    An inactive member becomes active at the rate `beta` times the number of its active neighbours, or times their
    fraction of its neighbours. An active member recovers at the rate `gamma`, to the inactive value, or to the removed
    value when there is one, and a removed member returns to the inactive value at the rate `omega`. Every move is a
    jump at a rate, so the state changes by random events in continuous time.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        target:
            The path of the group on the nodes or sites.

        state:
            The name of the discrete state of the members.

        beta:
            The rate of spreading from one active neighbour, or from all neighbours when they are all active.

        gamma:
            The rate of recovery of an active member.

        omega:
            The rate at which a removed member returns to the inactive value.

        inactive:
            The value of the state of an inactive member.

        active:
            The value of the state of an active member.

        removed:
            The value of the state of a recovered member, or `None` for members that recover to the inactive value.

        form:
            `'number'` for a rate proportional to the number of active neighbours, or `'fraction'` for one
            proportional to their fraction of the neighbours.

        layer:
            The layer of the network whose edges the spreading runs on, or `None` for the graph of the network or the
            neighbourhood of the lattice.

    Raises:
        ValidationError:
            The form is unknown, or the values of the state are not distinct.

    Examples:
        >>> from skcomplex.systems.biology.epidemiology import SpreadingInteraction
        >>> spreading = SpreadingInteraction('spreading', target='sites', beta=2.0, gamma=1.0, form='fraction')
        >>> spreading.form
        'fraction'
    """

    law_classes = (JumpLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'state',
        beta: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        gamma: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        omega: Annotated[float, RealSet.closed_open(0, oo)] = 0.0,
        inactive: float = 0.0,
        active: float = 1.0,
        removed: float | None = None,
        form: str = 'number',
        layer: str | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.beta = beta
        self.gamma = gamma
        self.omega = omega
        self.inactive = inactive
        self.active = active
        self.removed = removed
        self.form = form
        self.layer = layer

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The form is unknown, or the values of the state are not distinct.
        """
        super()._check_arguments()
        if self.form not in FORMS:
            error_msg = f'The form of spreading is {self.form!r}. Use one of {", ".join(FORMS)}.'
            raise ValidationError(error_msg)
        values = [self.inactive, self.active, *([] if self.removed is None else [self.removed])]
        if len(set(values)) < len(values):
            error_msg = (
                f'The inactive, active, and removed values of spreading are {values}. Give each a distinct value.'
            )
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the spreading, the recovery, and the return of every member.

        The spreading comes from the active neighbours.

        Args:
            context:
                The namespace of the group, with `context.target`.
        """
        super()._prepare(context)
        member = context.target
        value = getattr(member, self.state)
        over = None if self.layer is None else AdjacencyNeighborhood(layer=self.layer)
        reduce = 'mean' if self.form == 'fraction' else 'sum'
        held = neighbors(where(getattr(member.other, self.state) == self.active, 1, 0), over=over, reduce=reduce)
        recovered = self.inactive if self.removed is None else self.removed
        laws: list[BaseLaw] = [
            self._get_jump(value, self.inactive, self.active, context.beta * held),
            self._get_jump(value, self.active, recovered, context.gamma),
        ]
        if self.removed is not None:
            laws.append(self._get_jump(value, self.removed, self.inactive, context.omega))
        self.laws_ = laws

    @staticmethod
    def _get_jump(value: Expression, source: float, destination: float, rate: Expression) -> JumpLaw:
        """Return the jump of the state from a source value to the destination at a rate."""
        return JumpLaw(rate * where(value == source, 1, 0), {value: destination - source})

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