Bird swarm with pair potentials
A swarm of self-propelled birds held together by a pair potential.
- Class:
BirdSwarmSystem - Import:
from skcomplex.systems.biology.collective_behaviour import BirdSwarmSystem - Field:
biology/collective_behaviour - Topics:
swarms,particles,active matter,self-propulsion - References:
- D'Orsogna et al. 2006
- Gros 2015
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 BirdSwarmSystem
trajectory = BirdSwarmSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_birds |
30 |
alpha |
1.0 |
beta |
0.5 |
C_a |
1.0 |
l_a |
2.0 |
C_r |
2.0 |
l_r |
0.5 |
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 BirdSwarmSystem(BaseSystem):
"""A swarm of self-propelled birds held together by a pair potential.
The potential attracts far and repels near.
Every bird is driven to the speed `sqrt(alpha / beta)` and feels the Morse-type potential of every other bird, so
the swarm stays together and organizes into a flock or a rotating mill. The system has the positions `birds.x` and
the velocities `birds.x'`.
Args:
n_birds:
The number of birds.
alpha:
The propulsion.
beta:
The friction at high speed.
C_a:
The strength of the attraction.
l_a:
The range of the attraction.
C_r:
The strength of the repulsion.
l_r:
The range of the repulsion.
random_state:
The seed or generator of the initial positions and velocities.
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 BirdSwarmSystem
>>> BirdSwarmSystem(5).prepare().system_.elements[0].size
5
"""
field = 'biology/collective_behaviour'
topics = ('swarms', 'particles', 'active matter', 'self-propulsion')
references = ("D'Orsogna et al. 2006", 'Gros 2015')
until = 50.0
dt = 0.5
def __init__(
self,
n_birds: int = 30,
*,
alpha: float = 1.0,
beta: float = 0.5,
C_a: float = 1.0,
l_a: float = 2.0,
C_r: float = 2.0,
l_r: float = 0.5,
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_birds = n_birds
self.alpha = alpha
self.beta = beta
self.C_a = C_a
self.l_a = l_a
self.C_r = C_r
self.l_r = l_r
self.random_state = random_state
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the birds at random places and velocities held together by a pair potential.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
positions, velocities = rng.uniform(-3.0, 3.0, (self.n_birds, 2)), rng.normal(0.0, 1.0, (self.n_birds, 2))
plane = ContinuousSpace(n_dim=2)
birds = PointElement('birds', x=positions, values={"x'": velocities}, size=self.n_birds, space=plane)
potential = MorsePotentialInteraction(
'flocking',
target='birds',
cutoff=10 * self.l_a,
C_a=self.C_a,
l_a=self.l_a,
C_r=self.C_r,
l_r=self.l_r,
)
flight = SelfPropulsionInteraction('flight', target='birds', alpha=self.alpha, beta=self.beta)
self.system_ = System(self.label, elements=[birds], interactions=[potential, flight], space=plane)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
PointElement, fromElement, through the shared recipePointElement
Interactions:
MorsePotentialInteraction, fromInteractionSelfPropulsionInteraction, fromInteraction
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 MorsePotentialInteraction(Interaction):
"""Attraction at long range and repulsion at short range.
The potential is `U(r) = C_r exp(-r / l_r) - C_a exp(-r / l_a)`, and every member feels the force `-U'(r)` along
the line of centres from each member within the cutoff, `x_i'' += sum_j -U'(r_ij) (x_i - x_j) / r_ij`. It holds a
flock of birds, a school of fish, or a swarm of robots together at a spacing.
Args:
label:
The label of the interaction.
target:
The path of the group of members.
cutoff:
The distance beyond which pairs do not interact.
C_a:
The strength of the attraction.
l_a:
The range of the attraction.
C_r:
The strength of the repulsion.
l_r:
The range of the repulsion.
Examples:
>>> from skcomplex.systems.biology.collective_behaviour import MorsePotentialInteraction
>>> MorsePotentialInteraction('flocking', target='birds', cutoff=10.0).l_a
2.0
"""
def __init__(
self,
label: str,
*,
target: Role,
cutoff: Annotated[float, RealSet.open(0, oo)] = 1.0,
C_a: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
l_a: Annotated[float, RealSet.open(0, oo)] = 2.0,
C_r: Annotated[float, RealSet.closed_open(0, oo)] = 2.0,
l_r: Annotated[float, RealSet.open(0, oo)] = 0.5,
) -> None:
super().__init__(label)
self.target = target
self.cutoff = cutoff
self.C_a = C_a
self.l_a = l_a
self.C_r = C_r
self.l_r = l_r
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the force of the members within the cutoff on every member.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
s, x = context, context.target.x
separation = x - s.target.other.x
r = sqrt(separation.dot_product(separation))
distance = SR.var('r', domain='positive')
energy = s.C_r * exp(-distance / s.l_r) - s.C_a * exp(-distance / s.l_a)
slope = energy.diff(distance).subs({distance: r})
force = neighbors(-slope * separation / r, RadiusNeighborhood(self.cutoff))
self.laws_ = [RateLaw(x.diff(s.t, 2), force)]
class SelfPropulsionInteraction(Interaction):
"""Rayleigh self-propulsion, `x'' = (alpha - beta |x'|²) x'`, which drives points to the speed `sqrt(alpha / beta)`.
Args:
label:
The label of the interaction.
target:
The path of the particle or group.
alpha:
The propulsion.
beta:
The friction at high speed.
Examples:
>>> from skcomplex.systems.biology.collective_behaviour import SelfPropulsionInteraction
>>> SelfPropulsionInteraction('flight', target='birds', alpha=1.5).alpha
1.5
"""
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)] = 0.5,
) -> 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 the target.
Args:
context:
The namespace of the target, 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)]