Skip to content

Swarm with many-body flanking and encirclement alignment

A swarm of self-propelled agents that align through pairs, triples, and quadruples of neighbours.

  • Class: ManyBodyAlignmentSwarmSystem
  • Import: from skcomplex.systems.biology.collective_behaviour import ManyBodyAlignmentSwarmSystem
  • Field: biology/collective_behaviour
  • Topics: swarms, many-body interactions, alignment, self-propulsion
  • References:
    • Gutleb 2026
    • D'Orsogna et al. 2006
    • Cucker and Smale 2007

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 ManyBodyAlignmentSwarmSystem

trajectory = ManyBodyAlignmentSwarmSystem().prepare().simulate()

Parameters

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

Parameter Default
size 40
dimension 2
alpha 20.0
beta 20.0
C_r 2.0
l_r 0.5
C_a 1.0
l_a 2.0
gamma 1.0
l_v 1.0
l_3 1.0
kappa_v 2.0
kappa_4 4.0
R 3.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 continuous
Space continuous
Laws rate
Randomness unknown
Domains vector
Structure fixed

Class

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

class ManyBodyAlignmentSwarmSystem(BaseSystem):
    """A swarm of self-propelled agents that align through pairs, triples, and quadruples of neighbours.

    The acceleration of an agent is the sum of terms of one body order each (Gutleb 2026, Eq. 2): the self-propulsion
    `(alpha - beta |v|^2) v`, a Morse force and Cucker-Smale alignment with every neighbour, a 3-body flanking
    alignment with every pair of neighbours weighted by `kappa_v`, and a 4-body encirclement alignment with every
    triple of neighbours weighted by `kappa_4`. The neighbours are the agents within `R`, found again at every
    evaluation, and the smooth cutoff `(1 - rho^2 / R^2)^2` weighs every neighbour at the distance `rho`. With
    `kappa_v = kappa_4 = 0` the swarm is the classical pairwise collective. The agents move in a periodic box that holds
    about ten neighbours around each. The system has the positions `agents.x` and the velocities `agents.x'`.

    Args:
        size:
            The number of agents.

        dimension:
            The dimension of the space, 2 or 3.

        alpha:
            The propulsion.

        beta:
            The friction at high speed.

        C_r:
            The strength of the repulsion.

        l_r:
            The range of the repulsion.

        C_a:
            The strength of the attraction.

        l_a:
            The range of the attraction.

        gamma:
            The strength of the pairwise alignment.

        l_v:
            The range of the pairwise alignment.

        l_3:
            The range of the weight of a neighbour in the 3-body and 4-body terms.

        kappa_v:
            The strength of the 3-body flanking alignment.

        kappa_4:
            The strength of the 4-body encirclement alignment.

        R:
            The radius of the neighbourhood and of the cutoff.

        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 ManyBodyAlignmentSwarmSystem
        >>> system = ManyBodyAlignmentSwarmSystem(12).prepare().system_
        >>> system.elements[0].size, [component.label for component in system.interactions]
        (12, ['propulsion', 'pairs', 'flanking', 'encirclement'])
    """

    field = 'biology/collective_behaviour'
    topics = ('swarms', 'many-body interactions', 'alignment', 'self-propulsion')
    references = ('Gutleb 2026', "D'Orsogna et al. 2006", 'Cucker and Smale 2007')
    until = 50.0
    dt = 0.5

    def __init__(
        self,
        size: int = 40,
        dimension: int = 2,
        *,
        alpha: float = 20.0,
        beta: float = 20.0,
        C_r: float = 2.0,
        l_r: float = 0.5,
        C_a: float = 1.0,
        l_a: float = 2.0,
        gamma: float = 1.0,
        l_v: float = 1.0,
        l_3: float = 1.0,
        kappa_v: float = 2.0,
        kappa_4: float = 4.0,
        R: float = 3.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.size = size
        self.dimension = dimension
        self.alpha = alpha
        self.beta = beta
        self.C_r = C_r
        self.l_r = l_r
        self.C_a = C_a
        self.l_a = l_a
        self.gamma = gamma
        self.l_v = l_v
        self.l_3 = l_3
        self.kappa_v = kappa_v
        self.kappa_4 = kappa_4
        self.R = R
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the agents and their interactions of every body order.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        spacing = (np.pi * self.R**2 / NEIGHBOURS) ** (1 / self.dimension)
        sides = int(np.ceil(self.size ** (1 / self.dimension)))
        sites = np.stack(np.meshgrid(*[np.arange(sides)] * self.dimension, indexing='ij'), axis=-1)
        sites = sites.reshape(-1, self.dimension)[: self.size]
        positions = spacing * (sites + rng.uniform(-0.25, 0.25, (self.size, self.dimension)))
        headings = rng.normal(size=(self.size, self.dimension))
        speed = np.sqrt(self.alpha / self.beta)
        velocities = speed * headings / np.linalg.norm(headings, axis=1, keepdims=True)
        space = ContinuousSpace(extent=(spacing * sides,) * self.dimension, boundary='periodic')
        agents = PointElement('agents', x=positions, values={"x'": velocities}, size=self.size, space=space)
        propulsion = RayleighPropulsionInteraction('propulsion', target='agents', alpha=self.alpha, beta=self.beta)
        pairs = MorseAlignmentInteraction(
            'pairs',
            target='agents',
            R=self.R,
            C_r=self.C_r,
            l_r=self.l_r,
            C_a=self.C_a,
            l_a=self.l_a,
            gamma=self.gamma,
            l_v=self.l_v,
        )
        flanking = FlankingInteraction('flanking', target='agents', R=self.R, kappa_v=self.kappa_v, l_3=self.l_3)
        encirclement = EncirclementInteraction(
            'encirclement',
            target='agents',
            R=self.R,
            kappa_4=self.kappa_4,
            l_3=self.l_3,
        )
        self.system_ = System(
            self.label,
            elements=[agents],
            interactions=[propulsion, pairs, flanking, encirclement],
            space=space,
        )

Components

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

Elements:

Interactions:

  • RayleighPropulsionInteraction, from Interaction
  • MorseAlignmentInteraction, from Interaction
  • FlankingInteraction, from Interaction
  • EncirclementInteraction, from Interaction
class PointElement(Element):
    """An element of a point at the position `x` that the forces on it move.

    The forces give the acceleration `x''` of the position, and the velocity is the value `x'`, which starts at zero
    unless `values` gives it.

    Unlike `Element`, which takes any values, it names the position `x` and draws it as a point. Choose it when members
    are bodies that move by forces in a continuous space.

    It appears in many fields. Atoms of a gas, stars of a cluster, birds of a flock, and pedestrians of a crowd are
    points that move by the forces on them.

    Args:
        label:
            The label of the point.

        x:
            The initial position. A number applies to every component.

        values:
            Further values by name, such as the starting velocity `"x'"`.

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

        space:
            The space whose sites hold one point each, or `None`.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.elements import PointElement
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> ball = PointElement('ball', x=np.array([1.0, 0.0]), values={"x'": np.array([0.0, 1.0])})
        >>> spring = lambda s: [RateLaw(s.target.x.diff(s.t, 2), -s.target.x)]
        >>> well = Interaction('well', roles={'target': 'ball'}, laws=spring)
        >>> system = System(elements=[ball], interactions=[well]).prepare()
        >>> position = system.simulate(until=np.pi / 2, dt=np.pi / 2).get_values('ball.x')[-1]
        >>> round(float(position[1]), 3)
        1.0
    """

    visual = VisualSpec('points', {'position': 'x'})

    def __init__(
        self,
        label: str,
        x: npt.ArrayLike = 0.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.x = x

class RayleighPropulsionInteraction(Interaction):
    """Rayleigh self-propulsion `x'' = (alpha - beta |x'|^2) x'` of the agents of a swarm.

    It drives every agent to the speed `sqrt(alpha / beta)`.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of agents, whose position is `x`.

        alpha:
            The propulsion.

        beta:
            The friction at high speed.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import RayleighPropulsionInteraction
        >>> RayleighPropulsionInteraction('propulsion', target='agents', alpha=2.0).alpha
        2.0
    """

    law_classes = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        alpha: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        beta: Annotated[float, RealSet.open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.alpha = alpha
        self.beta = beta

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the propulsion of the velocity of every agent.

        Args:
            context:
                The namespace of the agents, the time `t`, and the parameters.
        """
        super()._prepare(context)
        s, t = context, context.t
        x = s.target.x
        velocity = x.diff(t)
        self.laws_ = [RateLaw(x.diff(t, 2), (s.alpha - s.beta * velocity.dot_product(velocity)) * velocity)]

class MorseAlignmentInteraction(Interaction):
    """Morse force and Cucker-Smale alignment between neighbours under a smooth cutoff.

    An agent `i` gains from every neighbour `j` within `R` the acceleration
    `f_c(rho) (U'(rho) r_hat + gamma exp(-rho / l_v) u)`, where `rho` is their distance, `r_hat` the unit vector from
    `i` to `j`, `u` the velocity of `j` relative to `i`, `U(rho) = C_r exp(-rho / l_r) - C_a exp(-rho / l_a)` the Morse
    potential, and `f_c(rho) = (1 - rho^2 / R^2)^2` the smooth cutoff.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of agents, whose position `x` is a state of order 2.

        R:
            The radius of the neighbourhood and of the cutoff.

        C_r:
            The strength of the repulsion.

        l_r:
            The range of the repulsion.

        C_a:
            The strength of the attraction.

        l_a:
            The range of the attraction.

        gamma:
            The strength of the alignment.

        l_v:
            The range of the alignment.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import MorseAlignmentInteraction
        >>> MorseAlignmentInteraction('pairs', target='agents', R=3.0).R
        3.0
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        R: float = 3.0,
        C_r: Annotated[float, RealSet.closed_open(0, oo)] = 2.0,
        l_r: Annotated[float, RealSet.open(0, oo)] = 0.5,
        C_a: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        l_a: Annotated[float, RealSet.open(0, oo)] = 2.0,
        gamma: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        l_v: Annotated[float, RealSet.open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.R = R
        self.C_r = C_r
        self.l_r = l_r
        self.C_a = C_a
        self.l_a = l_a
        self.gamma = gamma
        self.l_v = l_v

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the sum of the Morse forces and the alignments of the neighbours within `R`.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        s, t = context, context.t
        x, other = s.target.x, s.target.other.x
        offset = other - x
        rho = sqrt(offset.dot_product(offset))
        slope = -s.C_r / s.l_r * exp(-rho / s.l_r) + s.C_a / s.l_a * exp(-rho / s.l_a)
        cutoff = (1 - rho**2 / self.R**2) ** 2
        term = cutoff * (slope * offset / rho + s.gamma * exp(-rho / s.l_v) * (other.diff(t) - x.diff(t)))
        self.laws_ = [RateLaw(x.diff(t, 2), neighbors(term, RadiusNeighborhood(self.R)))]

class FlankingInteraction(Interaction):
    """Three-body alignment of an agent with pairs of neighbours that flank it.

    An agent `i` gains from every pair `j < k` of its neighbours within `R` the acceleration
    `kappa_v g_ij g_ik (1 - r_hat_ij . r_hat_ik) / 2 (u_ij + u_ik) / 2`, where `r_hat_ij` is the unit vector from `i`
    to `j`, `u_ij` the velocity of `j` relative to `i`, and `g(rho) = (1 - rho^2 / R^2)^2 exp(-rho / l_3)` the weight of
    a neighbour at the distance `rho`. Two neighbours on opposite sides weigh most, and two on one side not at all.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of agents, whose position `x` is a state of order 2.

        R:
            The radius of the neighbourhood and of the cutoff.

        kappa_v:
            The strength of the flanking alignment.

        l_3:
            The range of the weight of a neighbour.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import FlankingInteraction
        >>> FlankingInteraction('flanking', target='agents').kappa_v
        2.0
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        R: float = 3.0,
        kappa_v: float = 2.0,
        l_3: Annotated[float, RealSet.open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.R = R
        self.kappa_v = kappa_v
        self.l_3 = l_3

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the sum of the flanking alignments over the pairs of neighbours within `R`.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        s, t, member = context, context.t, context.target
        weight, relative = SR(1), vector(SR, [0] * len(member.x))
        directions = []
        for other in member.others[:2]:
            offset = other.x - member.x
            rho = sqrt(offset.dot_product(offset))
            weight *= (1 - rho**2 / self.R**2) ** 2 * exp(-rho / s.l_3)
            directions.append(offset / rho)
            relative += other.x.diff(t) - member.x.diff(t)
        cosine = directions[0].dot_product(directions[1])
        term = s.kappa_v * weight * (1 - cosine) / 2 * relative / 2
        self.laws_ = [RateLaw(member.x.diff(t, 2), hyperedges(term, size=3, over=RadiusNeighborhood(self.R)))]

class EncirclementInteraction(Interaction):
    """Four-body alignment of an agent with triples of neighbours that surround it.

    An agent `i` gains from every triple `j < k < l` of its neighbours within `R` the acceleration
    `kappa_4 g_ij g_ik g_il (1 - |r_hat_ij + r_hat_ik + r_hat_il|^2 / 9) (u_ij + u_ik + u_il) / 3`, where `r_hat_ij`
    is the unit vector from `i` to `j`, `u_ij` the velocity of `j` relative to `i`, and
    `g(rho) = (1 - rho^2 / R^2)^2 exp(-rho / l_3)` the weight of a neighbour at the distance `rho`. Three neighbours
    spread evenly around the agent weigh most.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of agents, whose position `x` is a state of order 2.

        R:
            The radius of the neighbourhood and of the cutoff.

        kappa_4:
            The strength of the encirclement alignment.

        l_3:
            The range of the weight of a neighbour.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import EncirclementInteraction
        >>> EncirclementInteraction('encirclement', target='agents').kappa_4
        4.0
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        R: float = 3.0,
        kappa_4: float = 4.0,
        l_3: Annotated[float, RealSet.open(0, oo)] = 1.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.R = R
        self.kappa_4 = kappa_4
        self.l_3 = l_3

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the sum of the encirclement alignments over the triples of neighbours within `R`.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        s, t, member = context, context.t, context.target
        zero = vector(SR, [0] * len(member.x))
        weight, directions, relative = SR(1), zero, zero
        for other in member.others[:3]:
            offset = other.x - member.x
            rho = sqrt(offset.dot_product(offset))
            weight *= (1 - rho**2 / self.R**2) ** 2 * exp(-rho / s.l_3)
            directions += offset / rho
            relative += other.x.diff(t) - member.x.diff(t)
        term = s.kappa_4 * weight * (1 - directions.dot_product(directions) / 9) * relative / 3
        self.laws_ = [RateLaw(member.x.diff(t, 2), hyperedges(term, size=4, over=RadiusNeighborhood(self.R)))]