Skip to content

Couzin shoal with repulsion, alignment, and informed leaders

The Couzin shoal, in which a small informed minority leads a group.

  • Class: CouzinLeadershipSystem
  • Import: from skcomplex.systems.biology.collective_behaviour import CouzinLeadershipSystem
  • Field: biology/collective_behaviour
  • Topics: agents, schooling, leadership, collective decision, continuous space
  • References:
    • Couzin et al. 2005
    • Mihailović et al. 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.collective_behaviour import CouzinLeadershipSystem

trajectory = CouzinLeadershipSystem().prepare().simulate()

Parameters

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

Parameter Default
n_fish 50
informed 0.1
omega 0.5
preferred 0.0
side 100.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 continuous
Laws update
Randomness stochastic
Domains real
Structure variable membership

Class

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

class CouzinLeadershipSystem(BaseSystem):
    """The Couzin shoal, in which a small informed minority leads a group.

    The group does not know who is informed.

    The fish start in a disk of radius 5 at the center of a torus with random headings, and a fraction `informed` of
    them prefers the direction at the angle `preferred` with the weight `omega`. Repulsion, attraction, and alignment
    keep the shoal together, and the informed fish pull its mean heading toward their direction. The accuracy, the
    closeness of the group's heading to the preferred direction, grows with the size of the minority, and a minority of
    about 10% already steers a group of 50. The system has the group `shoal`, the unit headings `vx` and `vy` of its
    fish, and the weight `omega` of each, positive for the informed ones.

    Args:
        n_fish:
            The number of fish.

        informed:
            The fraction of informed fish.

        omega:
            The weight of the preferred direction of the informed fish.

        preferred:
            The angle of the preferred direction.

        side:
            The side of the square torus.

        random_state:
            The seed or generator of the initial positions and headings.

        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 CouzinLeadershipSystem
        >>> int((CouzinLeadershipSystem(20, informed=0.2).prepare().system_.elements[0].omega > 0).sum())
        4
    """

    field = 'biology/collective_behaviour'
    topics = ('agents', 'schooling', 'leadership', 'collective decision', 'continuous space')
    references = ('Couzin et al. 2005', 'Mihailović et al. 2023')
    until = 300
    dt = 1

    def __init__(
        self,
        n_fish: int = 50,
        *,
        informed: float = 0.1,
        omega: float = 0.5,
        preferred: float = 0.0,
        side: float = 100.0,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.n_fish = n_fish
        self.informed = informed
        self.omega = omega
        self.preferred = preferred
        self.side = side
        self.random_state = random_state

    @staticmethod
    def _draw_deviation(agent: ShoalMemberView, system: SystemView) -> float:
        """Return a Gaussian angular noise of the turn of a fish.

        The noise has the standard deviation `noise`.
        """
        return float(system.rng.normal(0.0, agent.noise))

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

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        radius = 5.0 * np.sqrt(rng.uniform(0.0, 1.0, self.n_fish))
        place = rng.uniform(0.0, 2 * math.pi, self.n_fish)
        headings = rng.uniform(0.0, 2 * math.pi, self.n_fish)
        weights = np.zeros(self.n_fish)
        weights[: round(self.informed * self.n_fish)] = self.omega
        locations = self.side / 2 + np.column_stack([radius * np.cos(place), radius * np.sin(place)])
        shoal = ShoalMemberElement(
            'shoal',
            vx=np.cos(headings),
            vy=np.sin(headings),
            omega=weights,
            preferred=self.preferred,
            side=self.side,
            values={'x': locations[:, 0], 'y': locations[:, 1]},
            size=self.n_fish,
            space=ContinuousSpace(extent=(self.side, self.side), boundary='periodic'),
        )
        self.system_ = System(
            self.label,
            elements=[shoal],
            interactions=[
                SchoolingInteraction('schooling', target='shoal', phase='turn'),
                Interaction(
                    'deviation',
                    roles={'target': 'shoal'},
                    laws=lambda s: [
                        UpdateLaw(
                            s.target,
                            lambda agent, system: setattr(
                                agent,
                                'deviation',
                                float(self._draw_deviation(agent, system)),
                            ),
                            phase='turn',
                        ),
                    ],
                ),
                SwimmingInteraction('swimming', target='shoal', phase='swim'),
            ],
            solver=MesaSolver(phases=[PhaseSpec('turn', activation='simultaneous'), PhaseSpec('swim')]),
        )

Components

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

Elements:

Interactions:

  • SchoolingInteraction, from Interaction
  • Interaction
  • SwimmingInteraction, from Interaction, through the shared recipe MovementInteraction
class ShoalMemberElement(Element):
    """Fish of a Couzin shoal that avoids close neighbours and follows farther ones.

    It may know a preferred direction.

    Every step `SchoolingInteraction` turns a fish toward its desired direction by at most `max_turn`. When neighbours
    lie within the zone of repulsion `alpha`, it points away from them. Otherwise it points toward the neighbours
    within the zone of interaction `rho` and along their headings and its own. An informed fish adds its preferred
    direction with the weight `omega`, while a naive fish has `omega = 0`. It then draws a Gaussian angular noise
    `deviation` of standard deviation `noise`, and `SwimmingInteraction` turns it by the noise and moves it at the
    speed `speed`.

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

        vx:
            The horizontal component of the unit heading.

        vy:
            The vertical component of the unit heading.

        omega:
            The weight of the preferred direction, 0 for a naive fish.

        deviation:
            The angular noise of the last turn.

        preferred:
            The angle of the preferred direction of the informed fish.

        alpha:
            The radius of the zone of repulsion.

        rho:
            The radius of the zone of interaction.

        speed:
            The distance a fish swims per step.

        max_turn:
            The largest turning angle per step.

        noise:
            The standard deviation of the angular noise.

        side:
            The side of the square torus.

        values:
            Further values by name, such as the coordinates `x` and `y` of the fish on the torus.

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

        space:
            The torus the fish swim on, whose axes `x` and `y` place them, or `None`.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import ShoalMemberElement
        >>> ShoalMemberElement('shoal', values={'x': 5.0, 'y': 5.0}, size=10).size
        10
    """

    visual = VisualSpec('agents', {'color_by': 'omega'})

    def __init__(
        self,
        label: str,
        *,
        vx: object = 1.0,
        vy: object = 0.0,
        omega: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        deviation: object = 0.0,
        preferred: float = 0.0,
        alpha: Annotated[float, RealSet.open(0, oo)] = 1.0,
        rho: Annotated[float, RealSet.open(0, oo)] = 6.0,
        speed: Annotated[object, RealSet.open(0, oo)] = 0.3,
        max_turn: Annotated[float, RealSet.open(0, oo)] = 0.4,
        noise: Annotated[float, RealSet.closed_open(0, oo)] = 0.05,
        side: Annotated[float, RealSet.open(0, oo)] = 100.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.vx = vx
        self.vy = vy
        self.omega = omega
        self.deviation = deviation
        self.preferred = preferred
        self.alpha = alpha
        self.rho = rho
        self.speed = speed
        self.max_turn = max_turn
        self.noise = noise
        self.side = side

class SchoolingInteraction(ZoneCouplingInteraction):
    """Couzin's turn of every fish toward a desired direction, by at most `max_turn`.

    Zones around the fish set the desired direction.

    When neighbours lie within the zone of repulsion `alpha`, the desired direction points away from them, and
    repulsion overrides the other zones. Otherwise it points toward the neighbours within the zone of interaction `rho`
    and along their headings and the fish's own, and an informed fish adds its preferred direction with the weight
    `omega`. A fish with no neighbour keeps its heading. Offsets are the shortest ones on the torus of side `side`. It
    is the agent form of coupling over two radii of different priorities, with a clamp of the turn.

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

        target:
            The path of the group of fish.

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

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import SchoolingInteraction
        >>> [spec.priority for spec in SchoolingInteraction('schooling', target='shoal').radii]
        [1, 0, 0]
    """

    def __init__(self, label: str, *, target: Role, phase: str | None = None) -> None:
        super().__init__(
            label,
            target=target,
            write=('vx', 'vy'),
            combine=self._get_desired,
            radii=(
                RadiusSpec('alpha', self._get_repulsion, priority=1),
                RadiusSpec('rho', self._get_attraction),
                RadiusSpec('rho', self._get_alignment),
            ),
            clamp=ClampSpec(max_angle='max_turn'),
            phase=phase,
        )

    @staticmethod
    def _get_unit(vector: Array) -> Array:
        """Return a vector scaled to unit length, or the vector itself when it is zero."""
        norm = float(np.hypot(*vector))
        return vector / norm if norm > 0 else vector

    def _get_direction(self, agent: ShoalMemberView, other: ShoalMemberView) -> Array:
        """Return the unit direction from a fish to another.

        It lies along the shortest offset on the torus.
        """
        side = agent.side
        offset = np.asarray(other.location, dtype=float) - np.asarray(agent.location, dtype=float)
        return self._get_unit((offset + side / 2) % side - side / 2)

    def _get_repulsion(self, agent: ShoalMemberView, other: ShoalMemberView, system: SystemView) -> Array:
        """Return the direction away from a close neighbour."""
        return -self._get_direction(agent, other)

    def _get_attraction(self, agent: ShoalMemberView, other: ShoalMemberView, system: SystemView) -> Array:
        """Return the direction toward a neighbour."""
        return self._get_direction(agent, other)

    @staticmethod
    def _get_alignment(agent: ShoalMemberView, other: ShoalMemberView, system: SystemView) -> Array:
        """Return the heading of a neighbour."""
        return np.array([other.vx, other.vy])

    def _get_desired(
        self,
        agent: AgentViewProtocol,
        system: SystemViewProtocol,
        reduction: Array | None,
        priority: int | None,
    ) -> Array:
        """Return the desired direction of a fish.

        It comes from repulsion, or from attraction, alignment, and the preferred direction.
        """
        fish = cast(ShoalMemberView, agent)
        heading = np.array([fish.vx, fish.vy])
        if reduction is None:
            return heading
        if priority == 1:
            desired = self._get_unit(reduction)
        else:
            goal = np.array([math.cos(fish.preferred), math.sin(fish.preferred)])
            desired = self._get_unit(self._get_unit(heading + reduction) + fish.omega * goal)
        return desired if float(np.hypot(*desired)) > 0 else heading

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 SwimmingInteraction(MovementInteraction):
    """Swim of every fish by `speed` along its heading.

    The heading is turned first by its angular noise `deviation`.

    The heading `(vx, vy)` stays a unit vector, and the fish moves on the torus of side `side`.

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

        target:
            The path of the group of fish.

        probability:
            The probability that a fish swims in a step.

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

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import SwimmingInteraction
        >>> SwimmingInteraction('swimming', target='shoal', phase='swim').phase
        'swim'
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        probability: Annotated[float, RealSet.closed(0, 1)] = 1.0,
        phase: str | None = None,
    ) -> None:
        super().__init__(
            label,
            target=target,
            step=self._swim,
            probability=probability,
            schedule='member',
            phase=phase,
        )

    @staticmethod
    def _swim(agent: AgentViewProtocol, system: SystemViewProtocol) -> tuple[float, ...]:
        """Turn the heading of a fish by its angular noise and return its new position.

        The position is the one after one swim.
        """
        fish = cast(ShoalMemberView, agent)
        angle = math.atan2(fish.vy, fish.vx) + fish.deviation
        fish.vx, fish.vy = math.cos(angle), math.sin(angle)
        position = np.asarray(fish.location, dtype=float) + fish.speed * np.array([fish.vx, fish.vy])
        return tuple(float(item) for item in np.mod(position, fish.side))