Skip to content

Pheromone foraging

Ants that find food and lay a pheromone trail home, which other ants follow.

  • Class: PheromoneForagingSystem
  • Import: from skcomplex.systems.biology.collective_behaviour import PheromoneForagingSystem
  • Field: biology/collective_behaviour
  • Topics: field, agents, stigmergy, co-simulation
  • References:
    • Argun et al. 2021
    • Carmichael and Hadžikadić 2019

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.collective_behaviour import PheromoneForagingSystem

trajectory = PheromoneForagingSystem().prepare().simulate()

Parameters

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

Parameter Default
width 40
height 20
n_ants 40
D 0.05
evaporation 0.05
attraction 5.0
solver 'auto'
backend 'auto'

Tags

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

Tag Values
Time continuous, discrete
Space lattice
Laws rate, update
Randomness stochastic
Domains boolean, integer, real
Structure variable membership

Class

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

class PheromoneForagingSystem(BaseSystem):
    """Ants that find food and lay a pheromone trail home, which other ants follow.

    It is stigmergy.

    The ants live on a grid and the pheromone on a lattice of the same shape, as two partitions of a co-simulation that
    exchange the field and the deposits at every step. The nest is near the left edge and the food near the right. The
    system has the ants `colony/ants` and the pheromone `ground/pheromone.level`.

    Args:
        width:
            The number of columns.

        height:
            The number of rows.

        n_ants:
            The number of ants, which start at the nest.

        D:
            The diffusion of the pheromone.

        evaporation:
            The evaporation rate of the pheromone.

        attraction:
            How strongly pheromone draws searching ants.

        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.collective_behaviour import PheromoneForagingSystem
        >>> [child.label for child in PheromoneForagingSystem().prepare().system_.systems]
        ['colony', 'ground']
    """

    field = 'biology/collective_behaviour'
    topics = ('field', 'agents', 'stigmergy', 'co-simulation')
    references = ('Argun et al. 2021', 'Carmichael and Hadžikadić 2019')
    until = 600
    dt = 1

    def __init__(
        self,
        width: int = 40,
        height: int = 20,
        *,
        n_ants: int = 40,
        D: float = 0.05,
        evaporation: float = 0.05,
        attraction: float = 5.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.width = width
        self.height = height
        self.n_ants = n_ants
        self.D = D
        self.evaporation = evaporation
        self.attraction = attraction

    @staticmethod
    def _get_diffusion(namespace: SimpleNamespace) -> Expression:
        """Return the diffusion coefficient `D` of the pheromone."""
        coefficient: Expression = namespace.target.D
        return coefficient

    @staticmethod
    def _get_nest(ant: AntView) -> tuple[int, int]:
        """Return the cell of the nest of an ant."""
        return round(ant.nest_x), round(ant.nest_y)

    def _is_homing(self, ant: AgentViewProtocol, system: SystemViewProtocol) -> bool:
        """Return whether an ant carries food away from the nest.

        Such an ant walks home.
        """
        del system
        return isinstance(ant, AntView) and bool(ant.carrying) and ant.location != self._get_nest(ant)

    @staticmethod
    def _searches(ant: AgentViewProtocol, system: SystemViewProtocol) -> bool:
        """Return whether an ant without food stands farther than `food_radius` from the food.

        Such an ant searches.
        """
        del system
        if not isinstance(ant, AntView) or ant.carrying:
            return False
        x, y = cast('tuple[int, int]', ant.location)
        return bool(np.hypot(x - ant.food_x, y - ant.food_y) > ant.food_radius)

    def _get_home_step(self, ant: AgentViewProtocol, system: SystemViewProtocol) -> object:
        """Return the cell one step straight toward the nest."""
        del system
        if not isinstance(ant, AntView):
            return None
        x, y = cast('tuple[int, int]', ant.location)
        nest = self._get_nest(ant)
        return x + int(np.sign(nest[0] - x)), y + int(np.sign(nest[1] - y))

    def _get_search_step(self, ant: AgentViewProtocol, system: SystemViewProtocol) -> object:
        """Return a neighbouring cell drawn with a weight growing with its pheromone.

        The weight also grows with the distance of the cell from the nest.
        """
        if not isinstance(ant, AntView):
            return None
        x, y = cast('tuple[int, int]', ant.location)
        nest = self._get_nest(ant)
        cells = cast('list[tuple[int, int]]', list(ant.get_neighbor_cells()))
        distance = np.hypot(x - nest[0], y - nest[1])
        weights = np.asarray(
            [
                (1.0 + ant.attraction * system.get_field(PHEROMONE, cell))
                * np.exp(ant.outward * (np.hypot(cell[0] - nest[0], cell[1] - nest[1]) - distance))
                for cell in cells
            ],
        )
        return cells[int(system.rng.choice(len(cells), p=weights / weights.sum()))]

    @staticmethod
    def _carries(ant: AgentViewProtocol, cell: object, system: SystemViewProtocol) -> bool:
        """Return whether an ant carries food and walked home in its activation.

        Such an ant marks its cell with pheromone.
        """
        del cell, system
        return isinstance(ant, AntView) and bool(ant.carrying) and not ant.arrived

    @staticmethod
    def _get_deposit(ant: AgentViewProtocol, cell: object, system: SystemViewProtocol) -> float:
        """Return the pheromone `deposit` an ant leaves on its cell."""
        del cell, system
        return float(ant.deposit) if isinstance(ant, AntView) else 0.0

    def _mark(self, ant: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Leave the pheromone of an ant that carries food on the ground of its cell."""
        cell = ant.location_key
        if not ant.alive or not self._carries(ant, cell, system):
            return
        system.deposit('pheromone.level', cell, self._get_deposit(ant, cell, system))

    @staticmethod
    def _get_carrying(ant: AgentViewProtocol, system: SystemViewProtocol) -> float:
        """Return whether an ant carries food next.

        The step after arriving, it takes food or drops it at the nest.
        """
        if not isinstance(ant, AntView):
            return 0.0
        return float(not ant.carrying) if ant.arrived else float(ant.carrying)

    def _get_arrived(self, ant: AgentViewProtocol, system: SystemViewProtocol) -> float:
        """Return whether an ant arrived at the end of its turn.

        It arrived when it stands at the nest with food, or near the food without it.
        """
        if not isinstance(ant, AntView):
            return 0.0
        return float(not self._is_homing(ant, system) and not self._searches(ant, system))

    def _carry(self, ant: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Let an ant take food at the food source or drop it at the nest, the step after it arrived."""
        if isinstance(ant, AntView):
            ant.carrying = self._get_carrying(ant, system)

    def _arrive(self, ant: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Mark whether an ant arrived at the end of its turn, at the nest with food or near the food without it."""
        if isinstance(ant, AntView):
            ant.arrived = self._get_arrived(ant, system)

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of ants that find food and lay a pheromone trail home.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        nest, food = (5, self.height // 2), (self.width - 6, self.height // 2)
        grid = LatticeSpace((self.width, self.height), boundary='fixed')
        ants = AntElement(
            'ants',
            nest_x=float(nest[0]),
            nest_y=float(nest[1]),
            food_x=float(food[0]),
            food_y=float(food[1]),
            attraction=self.attraction,
            values={'x': np.full(self.n_ants, nest[0]), 'y': np.full(self.n_ants, nest[1])},
            size=self.n_ants,
            space=grid,
        )
        pheromone = PheromoneElement(
            'pheromone',
            D=self.D,
            evaporation=self.evaporation,
            space=LatticeSpace((self.width, self.height), boundary={'level': 'zero-flux'}),
        )
        self.system_ = System(
            self.label,
            systems=[
                System('colony', elements=[ants], space=grid),
                System(
                    'ground',
                    elements=[pheromone],
                    interactions=[
                        Interaction(
                            'diffusion',
                            roles={'target': 'pheromone'},
                            laws=lambda s: [
                                RateLaw(s.target.level, self._get_diffusion(s) * laplacian(s.target.level)),
                            ],
                        ),
                        EvaporationInteraction('evaporation', target='pheromone', state='level'),
                    ],
                ),
            ],
            interactions=[
                MovementInteraction(
                    'homing',
                    target='colony/ants',
                    step=self._get_home_step,
                    condition=self._is_homing,
                    schedule='member',
                ),
                Interaction(
                    'marking',
                    roles={'target': 'colony/ants', 'pheromone': 'ground/pheromone'},
                    laws=lambda s: [UpdateLaw(s.target, self._mark)],
                ),
                MovementInteraction(
                    'search',
                    target='colony/ants',
                    step=self._get_search_step,
                    condition=self._searches,
                    schedule='member',
                ),
                Interaction(
                    'carrying',
                    roles={'target': 'colony/ants'},
                    laws=lambda s: [UpdateLaw(s.target, self._carry)],
                ),
                Interaction(
                    'arrival',
                    roles={'target': 'colony/ants'},
                    laws=lambda s: [UpdateLaw(s.target, self._arrive)],
                ),
            ],
        )

Components

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

Elements:

Interactions:

  • MovementInteraction, from Interaction, through the shared recipe MovementInteraction
  • Interaction
  • EvaporationInteraction, from Interaction
class MovementInteraction(Interaction):
    """An interaction that moves the agents of a group by steps at every discrete step.

    The `step` says where an agent goes:

    - `'neighbor'`: a random cell or node next to its own, on a lattice or a network.
    - `'gaussian'`: its position plus a normal vector of deviation `scale`, in a continuous space.
    - `'levy'`: a random direction and a Pareto length of least value `scale` and tail `exponent`, in a continuous
      space.
    - `'best'`: the next cell with the highest `score(agent, cell, system)`, or with a `vision` the best cell along each
      direction up to that many cells, with ties broken by `ties`.
    - A function `step(agent, system)` that returns the destination, or `None` to stay.

    An agent for which `condition` holds attempts one step, or a Poisson number of mean `rate`, takes it with the
    probability `probability`, and then with the probability `accept(agent, destination, system)`. An exclusive movement
    never enters a cell held by another agent of the group. The agents move one after another by `schedule`, and every
    step charges its `cost`.

    Unlike an `UpdateLaw` on the edges of a network, which changes the space, it changes where agents stand in it.
    Choose it when agents walk, forage, or relocate.

    It appears in many fields. Sheep wander a pasture, foragers follow Lévy flights, ants climb a pheromone gradient,
    and residents move house in the segregation model of Schelling.

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

        target:
            The path of the group whose agents move.

        step:
            The kind of step, `'neighbor'`, `'gaussian'`, `'levy'`, or `'best'`, or a function of the agent and the
            system view that returns the destination.

        probability:
            The probability that an agent takes an attempted step.

        rate:
            The mean number of attempted steps of an agent in one unit of time, or `None` for one attempt every step.

        condition:
            A function of the agent and the system view that returns whether the agent moves, or `None` for every agent.

        accept:
            A function of the agent, its destination, and the system view that returns the probability of taking the
            step, or `None` to take every step.

        exclusive:
            Whether an agent moves only to cells or nodes no other agent of the group holds.

        score:
            The function of the agent, a neighbouring cell, and the system view that the step `'best'` maximizes.

        scale:
            The standard deviation of every component of a Gaussian step, or the least length of a Lévy step.

        exponent:
            The tail exponent of the length of a Lévy step.

        cost:
            A function of the agent and the system view run for every step taken, such as one that takes the energy a
            step costs from the agent, `def pay(agent, system): agent.energy -= 1.0`, or `None`.

        vision:
            The number of cells the step `'best'` looks along every direction of a lattice, a number or a function of
            the agent and the system view, or `None` for the cells next to the agent.

        schedule:
            The order of the agents, `'sequential'`, `'random-sequential'`, or `'member'`.

        phase:
            The phase of the step the movement runs in, or `None` for the default phase.

        ties:
            The cell the step `'best'` takes among cells of equal highest score, `'random'`, `'first'`, or `'nearest'`,
            or `None` for `'random'` without a vision and `'nearest'` with one.

    Raises:
        ValidationError:
            The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable, or
            the step `'best'` has no score, raised by `prepare`.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.agents import MovementInteraction
        >>> space = LatticeSpace((5, 5), metric='manhattan')
        >>> walkers = Element('walkers', values={'x': [2, 2], 'y': [2, 2]}, size=2, space=space)
        >>> walk = MovementInteraction('walk', target='walkers', step='neighbor')
        >>> trajectory = System(elements=[walkers], interactions=[walk]).prepare().simulate(until=1, random_state=0)
        >>> [bool(abs(cell - 2).sum() == 1) for cell in trajectory.get_agents('walkers', 1).locations]
        [True, True]
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)

    def _get_draws(self) -> bool:
        """Return whether the movement draws.

        It draws by its order, a random step, a probability or rate, or random ties.
        """
        ties = self.ties or ('random' if self.vision is None else 'nearest')
        drawn = self.step in ('neighbor', 'gaussian', 'levy') or (self.step == 'best' and ties == 'random')
        return (
            super()._get_draws() or drawn or self.probability != 1 or self.rate is not None or self.accept is not None
        )

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        step: Step = 'neighbor',
        probability: Annotated[float, RealSet.closed(0, 1)] = 1.0,
        rate: float | None = None,
        condition: Callable[[AgentViewProtocol, SystemViewProtocol], bool] | None = None,
        accept: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
        exclusive: bool = False,
        score: Callable[[AgentViewProtocol, object, SystemViewProtocol], float] | None = None,
        scale: Annotated[float, RealSet.open(0, oo)] = 1.0,
        exponent: Annotated[float, RealSet.open(0, oo)] = 1.5,
        cost: Cost | None = None,
        vision: Vision | None = None,
        schedule: str = 'random-sequential',
        phase: str | None = None,
        ties: str | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.step = step
        self.probability = probability
        self.rate = rate
        self.condition = condition
        self.accept = accept
        self.exclusive = exclusive
        self.score = score
        self.scale = scale
        self.exponent = exponent
        self.cost = cost
        self.vision = vision
        self.schedule = schedule
        self.phase = phase
        self.ties = ties

    def _check_functions(self) -> None:
        """Raise an error for a condition, acceptance, score, or cost that is not callable."""
        for name in ('condition', 'accept', 'score', 'cost'):
            value = getattr(self, name)
            if value is not None and not callable(value):
                error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function, or None.'
                raise ValidationError(error_msg)

    def _check_space(self, space: BaseSpace | None) -> None:
        """Raise an error for a step to a neighbouring cell or node in a continuous space."""
        if isinstance(self.step, str) and self.step in GRID_STEPS:
            self._check_grid('step', self.step, space, "step='gaussian' or step='levy', or a step function")

    def _check_arguments(self) -> None:
        """Raise an error for an unknown step, a rate not positive, or a bad function.

        Raises:
            ValidationError:
                The step, the schedule, or the ties are unknown, the rate is not positive, a function is not callable,
                or the step `'best'` has no score.
        """
        super()._check_arguments()
        self._check_variant('step', self.step, STEPS, functions=True)
        if self.rate is not None and (isinstance(self.rate, bool) or not self.rate > 0):
            error_msg = f'The rate of {self.label!r} is {self.rate!r}. Give a positive number, or None.'
            raise ValidationError(error_msg)
        if self.schedule not in SCHEDULES:
            error_msg = f'Unknown schedule {self.schedule!r} of {self.label!r}. Use one of {", ".join(SCHEDULES)}.'
            raise ValidationError(error_msg)
        if self.ties is not None:
            self._check_variant('ties', self.ties, TIES)
        if self.vision is not None and not callable(self.vision) and not isinstance(self.vision, int | float):
            error_msg = f'The vision of {self.label!r} is {self.vision!r}. Give a number, a function, or None.'
            raise ValidationError(error_msg)
        if self.step == 'best' and self.score is None:
            error_msg = f'The step `best` of {self.label!r} maximizes a score. Pass `score(agent, cell, system)`.'
            raise ValidationError(error_msg)
        self._check_functions()

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

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = self._get_movement_laws(context)

    def _count_attempts(self, system: SystemViewProtocol) -> int:
        """Return the number of steps an agent attempts in one step of time."""
        return 1 if self.rate is None else int(system.rng.poisson(self.rate))

    def _get_cells(self, agent: AgentViewProtocol, occupied: set[object]) -> list[object]:
        """Return the cells or nodes around an agent that it may move to."""
        cells = agent.get_neighbor_cells()
        if not self.exclusive:
            return cells
        return [cell for cell in cells if cell not in occupied]

    def _get_best(
        self,
        agent: AgentViewProtocol,
        cells: list[object],
        system: SystemViewProtocol,
        distances: list[int] | None = None,
    ) -> object:
        """Return the cell of the highest score, chosen among ties by the tie rule."""
        if self.score is None or not cells:
            return None
        scores = [self.score(agent, cell, system) for cell in cells]
        ties = self.ties or ('random' if distances is None else 'nearest')
        if ties != 'nearest':
            return cells[self._pick_best(scores, ties, system)]
        values = np.asarray(scores, dtype=float)
        best = np.flatnonzero(values == values.max())
        near = np.asarray([1 if distances is None else distances[int(index)] for index in best])
        return cells[int(best[near == near.min()][0])]

    @staticmethod
    def _shift(here: tuple[int, ...], cell: tuple[int, ...], system: SystemViewProtocol) -> tuple[int, ...]:
        """Return the unit step from a cell to a neighbouring cell.

        The step goes across the wrapped edge of a torus.
        """
        shift = [b - a for a, b in zip(here, cell, strict=True)]
        if system.torus:
            sizes = [int(item) for item in system.dimensions or ()]
            shift = [d - round(d / n) * n for d, n in zip(shift, sizes, strict=True)]
        return tuple(shift)

    def _get_sight(
        self,
        agent: AgentViewProtocol,
        occupied: set[object],
        system: SystemViewProtocol,
    ) -> tuple[list[object], list[int]]:
        """Return the cells in sight of an agent along every direction of a lattice.

        Its own cell comes first, with the distances.
        """
        vision = self.vision(agent, system) if callable(self.vision) else self.vision
        reach = int(vision or 0)
        here = tuple(int(item) for item in np.atleast_1d(np.asarray(agent.location_key)))
        sizes = [int(item) for item in system.dimensions or ()]
        cells: list[object] = [agent.location_key]
        distances = [0]
        shifts = [
            self._shift(here, tuple(int(item) for item in np.atleast_1d(np.asarray(neighbor))), system)
            for neighbor in agent.get_neighbor_cells()
        ]
        for shift in sorted(shifts, key=lambda step: tuple((item == 0, -item) for item in step)):
            for distance in range(1, reach + 1):
                point = [a + distance * d for a, d in zip(here, shift, strict=True)]
                if system.torus:
                    point = [item % size for item, size in zip(point, sizes, strict=True)]
                elif any(not 0 <= item < size for item, size in zip(point, sizes, strict=True)):
                    break
                cell = tuple(point)
                if not self.exclusive or cell not in occupied:
                    cells.append(cell)
                    distances.append(distance)
        return cells, distances

    def _get_destination(self, agent: AgentViewProtocol, system: SystemViewProtocol, occupied: set[object]) -> object:
        """Return the location a step of an agent leads to, or `None` to stay."""
        rng = system.rng
        if callable(self.step):
            return self.step(agent, system)
        if self.step == 'best' and self.vision is not None:
            cells, distances = self._get_sight(agent, occupied, system)
            return self._get_best(agent, cells, system, distances)
        if self.step in ('neighbor', 'best'):
            cells = self._get_cells(agent, occupied)
            if self.step == 'best':
                return self._get_best(agent, cells, system)
            return cells[int(rng.integers(len(cells)))] if cells else None
        position = np.asarray(agent.location, dtype=float)
        if self.step == 'gaussian':
            return position + rng.normal(0.0, self._get_parameter_value('scale', system), position.shape)
        direction = rng.normal(size=position.shape)
        length = self._get_parameter_value('scale', system) * (
            1.0 + rng.pareto(self._get_parameter_value('exponent', system))
        )
        return position + length * direction / np.linalg.norm(direction)

    def _charge(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Charge the cost of one step taken to an agent."""
        if self.cost is not None:
            self.cost(agent, system)

    def _take(self, agent: AgentViewProtocol, destination: object, occupied: set[object]) -> bool:
        """Move an agent to a destination unless an exclusive movement finds it held.

        It returns whether it moved.
        """
        if not self.exclusive:
            agent.move_to(destination)
            return True
        if destination == agent.location_key:
            return True
        if destination in occupied:
            return False
        occupied.discard(agent.location_key)
        agent.move_to(destination)
        occupied.add(agent.location_key)
        return True

    def _move(
        self,
        agent: AgentViewProtocol,
        system: SystemViewProtocol,
        probability: float,
        occupied: set[object],
    ) -> None:
        """Take the attempted steps of one agent.

        Each step has its probability and acceptance, and every step is charged.
        """
        for _ in range(self._count_attempts(system)):
            if probability < 1.0 and system.rng.random() >= probability:
                continue
            destination = self._get_destination(agent, system, occupied)
            if destination is None:
                continue
            if self.accept is not None and system.rng.random() >= self.accept(agent, destination, system):
                continue
            if self._take(agent, destination, occupied):
                self._charge(agent, system)

    def _move_member(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> None:
        """Move one agent whose condition holds, in its own activation."""
        if agent.alive and (self.condition is None or self.condition(agent, system)):
            occupied = (
                {other.location_key for other in system.get_agents(self._get_role('target'))}
                if self.exclusive
                else set()
            )
            self._move(agent, system, self._get_parameter_value('probability', system), occupied)

    def _move_all(self, system: SystemViewProtocol) -> None:
        """Move every agent of the group whose condition holds.

        They move in their order or in random order.
        """
        agents = system.get_agents(self._get_role('target'))
        occupied = {agent.location_key for agent in agents} if self.exclusive else set()
        probability = self._get_parameter_value('probability', system)
        order = system.rng.permutation(len(agents)) if self.schedule == 'random-sequential' else range(len(agents))
        for index in order:
            agent = agents[int(index)]
            if agent.alive and (self.condition is None or self.condition(agent, system)):
                self._move(agent, system, probability, occupied)

    def _get_movement_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the rule of the movement.

        Args:
            namespace:
                The namespace of the symbols the laws can use.

        Returns:
            laws:
                The rule that moves the agents every step.
        """
        if self.schedule == 'member':
            return [UpdateLaw(self._get_member(namespace, 'target'), self._move_member, phase=self.phase)]
        return [UpdateLaw(namespace, self._move_all, phase=self.phase)]

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

class AntElement(Element):
    """Ant that searches for food guided by pheromone and carries food home.

    It marks the way home with pheromone.

    A searching ant moves to a neighbouring cell with a probability that grows with its pheromone and, by `outward`,
    with its distance from the nest, as a scent of the nest would, and picks up food within a radius of the food. A
    carrying ant walks straight home, deposits pheromone on every cell it enters, and drops the food at the nest. The
    system adds the walk home, the deposit, the search, the pick-up and drop, and the arrival as member interactions,
    and an ant picks up or drops food the step after it arrives.

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

        carrying:
            Whether the ant carries food.

        arrived:
            Whether the ant stood at the nest with food, or near the food without it, at the end of the previous step.

        nest_x:
            The column of the nest.

        nest_y:
            The row of the nest.

        food_x:
            The column of the food.

        food_y:
            The row of the food.

        food_radius:
            The distance from the food within which ants pick it up.

        attraction:
            How strongly pheromone draws searching ants.

        outward:
            How strongly searching ants move away from the nest.

        deposit:
            The pheromone an ant deposits per step home.

        values:
            Further values by name, such as the cells `x` and `y` of the ants, or `None`.

        size:
            The number of ants, or `None` for one.

        space:
            The grid the ants walk on, whose axes `x` and `y` place them, or `None`.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import AntElement
        >>> AntElement('ants', size=5).size
        5
    """

    visual = VisualSpec('agents', {'color_by': 'carrying', 'color_range': (0.0, 1.0)})

    def __init__(
        self,
        label: str,
        *,
        carrying: Annotated[float, FiniteEnumeratedSet([0, 1])] = 0.0,
        arrived: Annotated[float, FiniteEnumeratedSet([0, 1])] = 0.0,
        nest_x: float = 5.0,
        nest_y: float = 10.0,
        food_x: float = 34.0,
        food_y: float = 10.0,
        food_radius: Annotated[float, RealSet.closed_open(0, oo)] = 3.0,
        attraction: Annotated[float, RealSet.closed_open(0, oo)] = 5.0,
        outward: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
        deposit: Annotated[float, 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.carrying = carrying
        self.arrived = arrived
        self.nest_x = nest_x
        self.nest_y = nest_y
        self.food_x = food_x
        self.food_y = food_y
        self.food_radius = food_radius
        self.attraction = attraction
        self.outward = outward
        self.deposit = deposit

class PheromoneElement(Element):
    """Pheromone of one cell of the ground.

    It is a level that diffuses to the neighbouring cells and evaporates.

    The element holds the level and its parameters. The system adds the diffusion `D laplacian(level)` and the
    evaporation `-evaporation level` as interactions.

    Args:
        label:
            The label of the element or the lattice field.

        level:
            The initial level of pheromone.

        D:
            The diffusion coefficient of the pheromone.

        evaporation:
            The rate at which the pheromone evaporates.

        space:
            The lattice whose cells hold the pheromone, or `None` for one cell.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import PheromoneElement
        >>> PheromoneElement('pheromone').evaporation
        0.05
    """

    def __init__(
        self,
        label: str,
        *,
        level: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        D: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
        evaporation: Annotated[object, RealSet.closed_open(0, oo)] = 0.05,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.level = level
        self.D = D
        self.evaporation = evaporation

class EvaporationInteraction(Interaction):
    """Evaporation of a mark, `dm/dt = -e m`.

    The rate `e` is a parameter of the element that holds the mark.

    Animals leave marks such as pheromone or emotional traces in the cells of a field, and every mark evaporates at
    the rate its cell holds, so the rate can vary from cell to cell.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the element or field that holds the mark.

        state:
            The name of the state of the target that holds the mark.

        evaporation:
            The name of the parameter of the target that holds the rate of evaporation.

    Raises:
        ValidationError:
            The state or the name of the rate of evaporation is not a name.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.stigmergy import EvaporationInteraction
        >>> evaporation = EvaporationInteraction('evaporation', target='scent', state='level', evaporation='e')
        >>> system = System(elements=[Element('scent', values={'level': 8.0, 'e': 0.5})], interactions=[evaporation])
        >>> trajectory = system.prepare().simulate(until=2.0, dt=0.01)
        >>> round(float(trajectory.get_values('scent.level')[-1]), 3)
        2.943
    """

    law_classes = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'level',
        evaporation: str = 'evaporation',
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.evaporation = evaporation

    def _check_arguments(self) -> None:
        """Raise an error for a name of the rate of evaporation that is no parameter.

        Raises:
            ValidationError:
                The state or the name of the rate of evaporation is not a name.
        """
        super()._check_arguments()
        if not isinstance(self.evaporation, str) or not self.evaporation.isidentifier():
            error_msg = f'The evaporation of {self.label!r} is {self.evaporation!r}. Name a parameter of the target.'
            raise ValidationError(error_msg)

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

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = [RateLaw(getattr(context.target, self.state), self._get_rate(context))]

    def _get_rate(self, namespace: SimpleNamespace) -> Expression:
        """Return the loss `-e m` of the mark.

        Args:
            namespace:
                The namespace of the symbols the rate can use, with the namespace of the target.

        Returns:
            rate:
                The rate of the mark.
        """
        loss: Expression = -getattr(namespace.target, self.evaporation) * getattr(namespace.target, self.state)
        return loss