Skip to content

Boids in three dimensions

Boids in three dimensions, birds that flock by local rules in a periodic cube.

  • Class: Boids3dSystem
  • Import: from skcomplex.systems.biology.collective_behaviour import Boids3dSystem
  • Field: biology/collective_behaviour
  • Topics: agents, flocking, self-organization, continuous space, three dimensions
  • 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 Boids3dSystem

trajectory = Boids3dSystem().prepare().simulate()

Parameters

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

Parameter Default
n_boids 50
size 20.0
radius 6.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 Boids3dSystem(BaseSystem):
    """Boids in three dimensions, birds that flock by local rules in a periodic cube.

    The boids start at random positions with random headings. Every step a boid steers by the boids within `radius` and
    then flies along its velocity, so with alignment alone the flock turns to one heading and keeps its spread in depth.
    The system has the group `flock` and the velocities `"x'"`, `"y'"`, and `"z'"` of its boids.

    Args:
        n_boids:
            The number of boids.

        size:
            The side of the periodic cube.

        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 Boids3dSystem
        >>> Boids3dSystem(10).prepare().system_.space.extent
        (20.0, 20.0, 20.0)
    """

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

    def __init__(
        self,
        n_boids: int = 50,
        *,
        size: float = 20.0,
        radius: float = 6.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 Boids in three 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.normal(size=(self.n_boids, 3))
        velocities = headings / np.linalg.norm(headings, axis=1, keepdims=True)
        positions = rng.uniform(0.0, self.size, (self.n_boids, 3))
        space = ContinuousSpace(extent=(self.size, self.size, self.size), boundary='periodic')
        flock = SpatialBoidElement(
            'flock',
            x=positions[:, 0],
            y=positions[:, 1],
            z=positions[:, 2],
            radius=self.radius,
            cohesion=self.cohesion,
            separation=self.separation,
            alignment=self.alignment,
            values={"x'": velocities[:, 0], "y'": velocities[:, 1], "z'": velocities[:, 2]},
            size=self.n_boids,
            space=space,
        )
        interactions = [
            HeadingInteraction('heading', target='flock'),
            SpatialFlightInteraction('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:

  • HeadingInteraction, from Interaction
  • SpatialFlightInteraction, from Interaction, through the shared recipe MovementInteraction
class SpatialBoidElement(Element):
    """Boid in three dimensions, a bird that steers by the boids it sees.

    It steers by the velocity and the position of those boids.

    Every step `HeadingInteraction` steers a boid by cohesion, separation, and alignment with the boids within `radius`,
    with its speed between `min_speed` and `max_speed`, and `SpatialFlightInteraction` moves it along its velocity. Its
    position is `x`, `y`, and `z`, and its velocity `"x'"`, `"y'"`, and `"z'"`, 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 position along the first axis.

        y:
            The initial position along the second axis.

        z:
            The initial position along the third axis.

        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.

        values:
            Further values by name, such as the velocity `{"x'": 1.0, "y'": 0.0, "z'": 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 SpatialBoidElement
        >>> SpatialBoidElement('flock', size=10).size
        10
    """

    visual = VisualSpec('agents')

    def __init__(
        self,
        label: str,
        *,
        x: float | Array = 0.0,
        y: float | Array = 0.0,
        z: 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,
        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.z = z
        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

class HeadingInteraction(Interaction):
    """Steering of the velocity of every boid by cohesion, separation, and alignment.

    The speed stays bounded.

    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 of the space. Every boid steers in its own activation.

    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 HeadingInteraction
        >>> HeadingInteraction('heading', target='flock').target
        'flock'
    """

    law_classes = (UpdateLaw,)

    def __init__(self, label: str, *, target: Role, phase: str | None = None) -> None:
        super().__init__(label)
        self.target = target
        self.phase = phase

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the steering rule of every boid.

        Args:
            context:
                The namespace of the boids.
        """
        super()._prepare(context)
        self.laws_ = [UpdateLaw(context.target, self.steer, phase=self.phase)]

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

    @staticmethod
    def _get_steering(boid: SpatialBoidView, others: list[SpatialBoidView]) -> Array:
        """Return the change of the velocity of a boid from the boids it sees."""
        offsets = np.array([boid.get_displacement_to(other) for other in others])
        velocities = np.array([HeadingInteraction._get_velocity(other) for other in others])
        close = np.linalg.norm(offsets, axis=1) < boid.separation_radius
        return (
            boid.cohesion * offsets.mean(axis=0)
            - boid.separation * offsets[close].sum(axis=0)
            + boid.alignment * (velocities.mean(axis=0) - HeadingInteraction._get_velocity(boid))
        )

    def steer(self, agent: SpatialBoidView, system: SystemView) -> None:
        """Steer a boid by the boids it sees, with its speed clipped.

        Args:
            agent:
                The boid.

            system:
                The system.
        """
        del system
        if not agent.alive:
            return
        others = [cast(SpatialBoidView, other) for other in agent.get_neighbors(agent.radius)]
        velocity = self._get_velocity(agent)
        if others:
            velocity = velocity + self._get_steering(agent, others)
        speed = float(np.linalg.norm(velocity))
        velocity = velocity * np.clip(speed, agent.min_speed, agent.max_speed) / speed if speed else velocity
        for name, item in zip(("x'", "y'", "z'"), velocity, strict=True):
            agent.set_value(name, float(item))

class SpatialFlightInteraction(MovementInteraction):
    """Flight of every boid by its velocity in one step.

    The boundary of its space acts on the new position.

    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 SpatialFlightInteraction
        >>> SpatialFlightInteraction('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 _fly(agent: AgentViewProtocol, system: SystemViewProtocol) -> Array:
        """Return the position of a boid after one step along its velocity."""
        boid = cast(SpatialBoidView, agent)
        return np.asarray(boid.location, dtype=float) + HeadingInteraction._get_velocity(boid)