Vicsek system with metric, topological, vision-cone, and delayed alignment
The Vicsek system.
- Class:
VicsekSystem - Import:
from skcomplex.systems.physics.active_matter import VicsekSystem - Field:
physics/active_matter - Topics:
active matter,flocking,alignment,discrete time,neighborhood - References:
- Vicsek et al. 1995
- Argun et al. 2021
- Jensen 2023
- Vicsek and Zafeiris 2012
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.physics.active_matter import VicsekSystem
trajectory = VicsekSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_particles |
400 |
size |
10.0 |
v0 |
0.5 |
eta |
0.1 |
seed |
0 |
neighbors |
None |
vision |
None |
delay |
0 |
memory |
5 |
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, vector |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class VicsekSystem(BaseSystem):
"""The Vicsek system.
Particles move at a constant speed along the mean heading of their neighbours.
At every step particle `i` takes the direction of the sum of the headings of the particles within the unit
distance, itself included, plus a uniform angle in `[-eta pi, eta pi]`, and moves `v0` along it in a periodic box.
At low noise and high density the particles align into a flock, and the polar order parameter
`|<exp(i theta)>|` grows from about `1 / sqrt(N)` to near 1. Raising the noise or lowering the density destroys
the order.
Two variants of Argun et al. (2021, Section 8.3) make the interaction non-metric or non-reciprocal. With
`neighbors`, a particle aligns with its `neighbors` nearest particles and itself at any distance, a topological
interaction that need not be reciprocal, and the clusters grow with `neighbors`. With `vision`, a particle sees only
the particles within the unit distance whose direction from it makes an angle of at most `vision` with its heading,
a vision cone that breaks reciprocity. The two variants do not combine, since the nearest neighbourhood of the core
has no cone.
With a positive `delay` `h`, the sensory delay of Section 8.2, a particle aligns with the headings its neighbours
had `h` steps ago, `theta_j(n + 1) = <theta_k(n - h)> + noise`. Argun et al. report that a short delay stabilizes
the clusters, and a long delay hinders them. A negative delay is a prediction: the headings of the neighbours `|h|`
steps ahead are extrapolated by a least-squares line through their last `memory` headings, and it hinders
clustering. The delay lies in `[-25, 25]`, and before the start the past headings equal the initial heading. The
system has the positions `flock.x`, the headings `flock.theta`, and the observables `polarization` and
`nematic_order`.
Args:
n_particles:
The number of particles.
size:
The side of the periodic box, in units of the interaction radius.
v0:
The distance a particle moves in one step.
eta:
The amplitude of the noise, as a fraction of `pi`.
seed:
The seed of the uniform initial positions and headings.
neighbors:
The number of nearest particles a particle aligns with, or `None` for the particles within the unit
distance.
vision:
The half-angle of the vision cone in `(0, pi]`, or `None` for the whole disk.
delay:
The delay of the alignment in steps, negative for a prediction.
memory:
The number of past headings a prediction fits, from 2 to 26.
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.
Raises:
ParameterError:
Both `neighbors` and `vision` are given, or the delay or the memory exceeds the 25 kept headings.
Examples:
>>> from skcomplex.systems.physics.active_matter import VicsekSystem
>>> VicsekSystem(10).prepare().system_.elements[0].size
10
>>> type(VicsekSystem(10, neighbors=4).prepare().system_.interactions[1].neighborhood).__name__
'NearestNeighborhood'
"""
field = 'physics/active_matter'
topics = ('active matter', 'flocking', 'alignment', 'discrete time', 'neighborhood')
references = ('Vicsek et al. 1995', 'Argun et al. 2021', 'Jensen 2023', 'Vicsek and Zafeiris 2012')
until = 200.0
dt = 1.0
observables = tuple(_get_orders('flock'))
@staticmethod
def _get_modulus(name: str, s: SimpleNamespace) -> Expression:
"""Return the modulus of an observable of a system."""
return abs(getattr(s, name))
def __init__(
self,
n_particles: int = 400,
*,
size: float = 10.0,
v0: float = 0.5,
eta: float = 0.1,
seed: int = 0,
neighbors: int | None = None,
vision: float | None = None,
delay: int = 0,
memory: int = 5,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n_particles = n_particles
self.size = size
self.v0 = v0
self.eta = eta
self.seed = seed
self.neighbors = neighbors
self.vision = vision
self.delay = delay
self.memory = memory
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of Vicsek particles in a periodic box.
Args:
context:
The observables to compile with the problem, or `None` for none.
Raises:
ParameterError:
Both `neighbors` and `vision` are given, or the delay or the memory exceeds 25 past headings.
"""
super()._prepare(context)
if self.neighbors is not None and self.vision is not None:
error_msg = 'A Vicsek flock aligns with its nearest neighbours or within a vision cone, not both.'
raise ParameterError(error_msg)
if abs(self.delay) > MEMORY or not FIT_POINTS <= self.memory <= MEMORY + 1:
error_msg = (
f'The delay {self.delay!r} and the memory {self.memory!r} need |delay| <= {MEMORY} and 2 <= memory <= '
f'{MEMORY + 1}.'
)
raise ParameterError(error_msg)
neighborhood: BaseNeighborhood | None = None
if self.neighbors is not None:
neighborhood = NearestNeighborhood(self.neighbors, center=True)
if self.vision is not None:
neighborhood = RadiusNeighborhood(1.0, angle=self.vision, direction='theta', center=True)
rng = np.random.default_rng(self.seed)
flock = VicsekParticleElement(
'flock',
x=rng.uniform(0.0, self.size, (self.n_particles, 2)),
theta=rng.uniform(-math.pi, math.pi, self.n_particles),
eta=self.eta,
size=self.n_particles,
space=ContinuousSpace(extent=(self.size, self.size), boundary='periodic'),
)
alignment = HeadingAlignmentInteraction(
'alignment',
target='flock',
neighborhood=neighborhood,
latency=self.delay,
memory=self.memory,
)
self.system_ = System(
self.label,
elements=[flock],
interactions=[PropulsionStepInteraction('propulsion', target='flock', speed=self.v0), alignment],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
VicsekParticleElement, fromElement
Interactions:
PropulsionStepInteraction, fromInteractionHeadingAlignmentInteraction, fromInteraction
class VicsekParticleElement(Element):
"""Particles of a Vicsek flock with the positions `x`, the headings `theta`, and the noise amplitudes `eta`.
`HeadingAlignmentInteraction` sets the new heading to the circular mean of the headings within the unit distance,
itself included, plus a uniform angle in `[-eta pi, eta pi]`. A propulsion step moves the particle along its
heading, which wraps around the circle. A delayed alignment reads past headings, which hold the initial heading
before the start.
Args:
label:
The label of the particles.
x:
The initial positions, one row per particle or shared.
theta:
The initial headings, one per particle or shared.
eta:
The amplitude of the noise, as a fraction of `pi`.
size:
The number of particles, or `None` for one.
space:
The continuous space of the particles, or `None` for none.
Examples:
>>> from skcomplex.systems.physics.active_matter import VicsekParticleElement
>>> VicsekParticleElement('bird').eta
0.1
"""
visual = HEADINGS
def __init__(
self,
label: str,
*,
x: object = (0.0, 0.0),
theta: Annotated[object, Period(2 * math.pi)] = 0.0,
eta: Annotated[object, RealSet.closed_open(0, oo)] = 0.1,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, size=size, space=space)
self.x = x
self.theta = theta
self.eta = eta
class PropulsionStepInteraction(Interaction):
"""Step `x(t + 1) = x + speed (cos theta, sin theta)` of a position in the plane.
The step is along a heading, in discrete time.
The step reads the heading at the start of the step, as every map of the step does.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the particle or the group whose positions move.
speed:
The distance moved in one step.
state:
The name of the vector state that holds the position.
heading:
The name of the state that holds the heading.
Examples:
>>> from types import SimpleNamespace
>>> from sage.all__sagemath_symbolics import var, vector
>>> from skcomplex.systems.physics.common.particles import PropulsionStepInteraction
>>> target = SimpleNamespace(x=vector([var('x1'), var('x2')]), theta=var('theta'))
>>> step = PropulsionStepInteraction('propulsion', target='flock')
>>> [law.value for law in step.prepare(SimpleNamespace(target=target, speed=var('v'), t=var('t'))).laws_]
[(v*cos(theta) + x1, v*sin(theta) + x2)]
"""
def __init__(
self,
label: str,
*,
target: Role,
speed: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
state: str = 'x',
heading: str = 'theta',
) -> None:
super().__init__(label)
self.target = target
self.speed = speed
self.state = state
self.heading = heading
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the step of the position along the heading.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
position = getattr(context.target, self.state)
self.laws_ = [UpdateLaw(position, position + self._step(context), increment=True)]
def _step(self, namespace: SimpleNamespace) -> FreeModuleElement:
"""Return the step `speed (cos theta, sin theta)`."""
heading = getattr(namespace.target, self.heading)
return namespace.speed * vector(SR, [cos(heading), sin(heading)])
class HeadingAlignmentInteraction(Interaction):
"""Vicsek alignment.
Every particle turns to the circular mean heading of its neighbours plus noise.
Every step the heading `theta` of every particle becomes the circular mean of the headings within the unit
distance, itself included, plus a uniform angle in `[-eta pi, eta pi]` with the parameter `eta` of the particle.
With `nematic`, every heading is flipped to the side nearer the particle's own heading first, as for particles
with an axis rather than a direction. Another neighbourhood, such as the `k` nearest particles or a vision cone,
replaces the unit disk.
With a positive `latency` `h`, every particle reads the headings of its neighbours `h` steps ago. With a negative
latency it reads their headings predicted `|h|` steps ahead, by a least-squares line through their last `memory`
headings, unwrapped by taking every change between two steps as the smallest angle.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the group of particles.
nematic:
Whether every heading is flipped to the side nearer the particle's own heading.
neighborhood:
The neighbourhood of every particle, itself included, or `None` for the unit disk.
latency:
The number of steps by which the headings of the neighbours are read late, or predicted ahead when
negative.
memory:
The number of past headings a prediction fits, at least 2.
Examples:
>>> from skcomplex.systems.physics.active_matter import HeadingAlignmentInteraction
>>> HeadingAlignmentInteraction('alignment', target='flock', nematic=True).nematic
True
"""
law_classes = (UpdateLaw,)
draws = True
def __init__(
self,
label: str,
*,
target: Role,
nematic: bool = False,
neighborhood: BaseNeighborhood | None = None,
latency: int = 0,
memory: int = 5,
) -> None:
super().__init__(label)
self.target = target
self.nematic = nematic
self.neighborhood = neighborhood
self.latency = latency
self.memory = memory
def _get_heading(self, heading: Expression, t: Expression) -> Expression:
"""Return the heading of a neighbour, delayed or predicted."""
if self.latency >= 0:
return heading if self.latency == 0 else heading(t=t - self.latency)
past = [heading if step == 0 else heading(t=t - step) for step in range(self.memory)]
unwrapped = [past[0]]
for step in range(1, self.memory):
change = past[step - 1] - past[step]
unwrapped.append(unwrapped[-1] - atan2(sin(change), cos(change)))
times = [-step for step in range(self.memory)]
mean_time = sum(times) / self.memory
mean_heading = sum(unwrapped) / self.memory
spread = sum((time - mean_time) ** 2 for time in times)
slope = sum((time - mean_time) * (value - mean_heading) for time, value in zip(times, unwrapped, strict=True))
return mean_heading + slope / spread * (-self.latency - mean_time)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the heading of every particle to the mean heading of its neighbours plus noise.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
member, other = context.target, context.target.other
over = RadiusNeighborhood(1.0, center=True) if self.neighborhood is None else self.neighborhood
side = where(cos(other.theta - member.theta) >= 0, 1, -1) if self.nematic else None
heading = self._get_heading(other.theta, context.t)
mean = neighbors(heading, over=over, reduce='circular-mean', weight=side)
noise = uniform('noise', -member.eta * math.pi, member.eta * math.pi)
self.laws_ = [UpdateLaw(member.theta, mean + noise)]