Skip to content

Boids in two dimensions

Reynolds' boids in two dimensions.

  • Class: BoidsSystem
  • Import: from skcomplex.systems.biology.collective_behaviour import BoidsSystem
  • Field: biology/collective_behaviour
  • Topics: agents, flocking, self-organization, continuous space
  • References:
    • Reynolds 1987
    • Downey 2018

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.biology.collective_behaviour import BoidsSystem

trajectory = BoidsSystem().prepare().simulate()

Parameters

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

Parameter Default
n_boids 40
size 30.0
radius 5.0
cohesion 0.01
separation 0.1
alignment 0.1
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 BoidsSystem(BaseSystem):
    """Reynolds' boids in two dimensions.

    They are birds that flock by local rules without a leader.

    The boids start at random positions with random headings on a torus. Alignment makes neighbours fly in the same
    direction and cohesion pulls them together, so the flock becomes polarized while separation keeps the birds apart.
    The system has the group `flock` and the velocities `"x'"` and `"y'"` of its boids.

    Args:
        n_boids:
            The number of boids.

        size:
            The side of the square torus.

        radius:
            The distance within which a boid sees others.

        cohesion:
            The weight of cohesion.

        separation:
            The weight of separation.

        alignment:
            The weight of alignment.

        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 BoidsSystem
        >>> BoidsSystem(10).prepare().system_.elements[0].size
        10
    """

    field = 'biology/collective_behaviour'
    topics = ('agents', 'flocking', 'self-organization', 'continuous space')
    references = ('Reynolds 1987', 'Downey 2018')
    until = 100
    dt = 1

    def __init__(
        self,
        n_boids: int = 40,
        *,
        size: float = 30.0,
        radius: float = 5.0,
        cohesion: float = 0.01,
        separation: float = 0.1,
        alignment: float = 0.1,
        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_boids = n_boids
        self.size = size
        self.radius = radius
        self.cohesion = cohesion
        self.separation = separation
        self.alignment = alignment
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of Reynolds' boids in two dimensions.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        headings = rng.uniform(0.0, 2 * math.pi, self.n_boids)
        positions = rng.uniform(0.0, self.size, (self.n_boids, 2))
        space = ContinuousSpace(extent=(self.size, self.size), boundary='periodic')
        flock = BoidElement(
            'flock',
            x=positions[:, 0],
            y=positions[:, 1],
            radius=self.radius,
            cohesion=self.cohesion,
            separation=self.separation,
            alignment=self.alignment,
            width=self.size,
            height=self.size,
            values={"x'": np.cos(headings), "y'": np.sin(headings)},
            size=self.n_boids,
            space=space,
        )
        interactions = [FlockingInteraction('flocking', target='flock'), FlightInteraction('flight', target='flock')]
        self.system_ = System(
            self.label,
            elements=[flock],
            interactions=interactions,
            space=space,
        )

Components

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

Elements:

Interactions:

  • FlockingInteraction, from Interaction
  • FlightInteraction, from Interaction, through the shared recipe MovementInteraction
class BoidElement(Element):
    """Boid of Reynolds, a bird that steers by three rules.

    The rules steer it toward, away from, and along its neighbours.

    Every step a boid sees the boids within `radius`. `FlockingInteraction` steers it by cohesion toward their center,
    by separation away from those closer than `separation_radius`, and by alignment toward their mean velocity, with
    its speed between `min_speed` and `max_speed`, and `FlightInteraction` moves it on a torus of side `width` by
    `height`. Its position is `x` and `y`, and its velocity `"x'"` and `"y'"`, which its rules read and change as
    `agent.get_value("x'")` and `agent.set_value("x'", value)`.

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

        x:
            The initial horizontal position.

        y:
            The initial vertical position.

        radius:
            The distance within which a boid sees others.

        separation_radius:
            The distance within which a boid avoids others.

        cohesion:
            The weight of cohesion.

        separation:
            The weight of separation.

        alignment:
            The weight of alignment.

        min_speed:
            The smallest speed.

        max_speed:
            The largest speed.

        width:
            The width of the torus.

        height:
            The height of the torus.

        values:
            Further values by name, such as the velocity `{"x'": 1.0, "y'": 0.0}`.

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

        space:
            The space of the boids, or `None` for none.

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

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

    def __init__(
        self,
        label: str,
        *,
        x: float | Array = 0.0,
        y: float | Array = 0.0,
        radius: Annotated[float, RealSet.open(0, oo)] = 5.0,
        separation_radius: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        cohesion: Annotated[float, RealSet.closed_open(0, oo)] = 0.01,
        separation: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        alignment: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        min_speed: Annotated[float, RealSet.closed_open(0, oo)] = 0.5,
        max_speed: Annotated[float, RealSet.open(0, oo)] = 1.0,
        width: Annotated[float, RealSet.open(0, oo)] = 30.0,
        height: Annotated[float, RealSet.open(0, oo)] = 30.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
        self.y = y
        self.radius = radius
        self.separation_radius = separation_radius
        self.cohesion = cohesion
        self.separation = separation
        self.alignment = alignment
        self.min_speed = min_speed
        self.max_speed = max_speed
        self.width = width
        self.height = height

class FlockingInteraction(ZoneCouplingInteraction):
    """Reynolds' steering of every boid by the boids it sees, with a bounded speed.

    It steers a boid toward, away from, and along those boids.

    The velocity of a boid gains the mean offset to the boids within `radius` weighted by `cohesion`, loses the summed
    offset to the boids within `separation_radius` weighted by `separation`, and gains the mean difference of their
    velocities from its own weighted by `alignment`. Its speed is then clipped between `min_speed` and `max_speed`.
    Offsets are the shortest ones on the torus of side `width` by `height`. It is the agent form of coupling over two
    radii of one priority, with a clamp of the norm.

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

        target:
            The path of the group of boids.

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

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import FlockingInteraction
        >>> [spec.reduce for spec in FlockingInteraction('flocking', target='flock').radii]
        ['mean', 'sum', 'mean']
    """

    def __init__(self, label: str, *, target: Role, phase: str | None = None) -> None:
        super().__init__(
            label,
            target=target,
            write=("x'", "y'"),
            radii=(
                RadiusSpec('radius', self._get_cohesion, reduce='mean'),
                RadiusSpec('separation_radius', self._get_separation),
                RadiusSpec('radius', self._get_alignment, reduce='mean'),
            ),
            clamp=ClampSpec(min_norm='min_speed', max_norm='max_speed'),
            phase=phase,
        )

    @staticmethod
    def _get_offset(agent: BoidView, other: BoidView) -> Array:
        """Return the shortest offset from a boid to another on the torus."""
        size = np.array([agent.width, agent.height])
        offset = np.asarray(other.location, dtype=float) - np.asarray(agent.location, dtype=float)
        return (offset + size / 2) % size - size / 2

    def _get_cohesion(self, agent: BoidView, other: BoidView, system: SystemView) -> Array:
        """Return the pull of a boid toward another."""
        return agent.cohesion * self._get_offset(agent, other)

    def _get_separation(self, agent: BoidView, other: BoidView, system: SystemView) -> Array:
        """Return the push of a boid away from a close one."""
        return -agent.separation * self._get_offset(agent, other)

    @staticmethod
    def _get_alignment(agent: BoidView, other: BoidView, system: SystemView) -> Array:
        """Return the turn of a boid toward the velocity of another."""
        return agent.alignment * (FlightInteraction._get_velocity(other) - FlightInteraction._get_velocity(agent))

class FlightInteraction(MovementInteraction):
    """Flight of every boid by its velocity `("x'", "y'")` in one step.

    The boids fly on the torus of side `width` by `height`.

    Every boid moves in its own activation, after the rules and member interactions listed before it.

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

        target:
            The path of the group of boids.

        probability:
            The probability that a boid moves in a step.

    Examples:
        >>> from skcomplex.systems.biology.collective_behaviour import FlightInteraction
        >>> FlightInteraction('flight', target='flock').schedule
        'member'
    """

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

    @staticmethod
    def _get_velocity(boid: AgentViewProtocol) -> Array:
        """Return the velocity of a boid as a vector."""
        return np.array([boid.get_value("x'"), boid.get_value("y'")], dtype=float)

    @staticmethod
    def _fly(agent: AgentViewProtocol, system: SystemViewProtocol) -> tuple[float, ...]:
        """Return the position of a boid after one step along its velocity."""
        boid = cast(BoidView, agent)
        position = np.asarray(boid.location, dtype=float) + FlightInteraction._get_velocity(boid)
        return tuple(float(item) for item in np.mod(position, np.array([boid.width, boid.height])))