Skip to content

Active Brownian particles with local alignment

Active Brownian particles in a periodic box whose headings align.

  • Class: AligningActiveBrownianParticlesSystem
  • Import: from skcomplex.systems.physics.active_matter import AligningActiveBrownianParticlesSystem
  • Field: physics/active_matter
  • Topics: active matter, sde, flocking, alignment, pair interaction
  • References:
    • Bertin 2021
    • Peruani, Deutsch, and Bär 2008
    • Chaté 2020

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 AligningActiveBrownianParticlesSystem

trajectory = AligningActiveBrownianParticlesSystem().prepare().simulate()

Parameters

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

Parameter Default
n_particles 200
size 20.0
speed 1.0
gamma 1.0
D_r 0.1
d0 1.0
D_t 0.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 noise, rate
Randomness stochastic
Domains real, vector
Structure fixed

Class

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

class AligningActiveBrownianParticlesSystem(BaseSystem):
    """Active Brownian particles in a periodic box whose headings align.

    A particle aligns with its neighbours within `d0`.

    The heading of particle `i` follows `dtheta_i = gamma sum_{|x_j - x_i| < d0} sin(theta_j - theta_i) dt + sqrt(2 D_r)
    dW`, and the particle swims at the constant `speed` along it. In the mean-field approximation of the Fokker-Planck
    equation, the disordered state is unstable above the density `rho_c = 2 D_r / (gamma pi d0^2)`, so at a fixed
    density `rho` the particles move together when `gamma` exceeds `2 D_r / (pi d0^2 rho)`. The polarization `|<exp(i
    theta)>|` is near 0 in the disordered state and near 1 in the ordered one. The system has the positions
    `swimmers.x`, the headings `swimmers.theta`, and the observables `mean_heading` and `polarization`.

    Args:
        n_particles:
            The number of particles.

        size:
            The side of the periodic box.

        speed:
            The self-propulsion speed.

        gamma:
            The strength of the alignment.

        D_r:
            The rotational diffusion coefficient.

        d0:
            The interaction range.

        D_t:
            The translational diffusion coefficient.

        random_state:
            The seed or generator of the uniform 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.physics.active_matter import AligningActiveBrownianParticlesSystem
        >>> AligningActiveBrownianParticlesSystem(10, gamma=0.5).prepare().system_.interactions[0].gamma
        0.5
    """

    field = 'physics/active_matter'
    topics = ('active matter', 'sde', 'flocking', 'alignment', 'pair interaction')
    references = ('Bertin 2021', 'Peruani, Deutsch, and Bär 2008', 'Chaté 2020')
    until = 100.0
    dt = 1.0
    observables = (
        Observable('mean_heading', _get_heading, group='swimmers'),
        Observable('polarization', _get_polarization),
    )

    def __init__(
        self,
        n_particles: int = 200,
        *,
        size: float = 20.0,
        speed: float = 1.0,
        gamma: float = 1.0,
        D_r: float = 0.1,
        d0: float = 1.0,
        D_t: float = 0.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.n_particles = n_particles
        self.size = size
        self.speed = speed
        self.gamma = gamma
        self.D_r = D_r
        self.d0 = d0
        self.D_t = D_t
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of active Brownian particles in a periodic box whose headings align.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        swimmers = SwimmerElement(
            'swimmers',
            x=rng.uniform(0.0, self.size, (self.n_particles, 2)),
            theta=rng.uniform(0.0, 2 * math.pi, self.n_particles),
            size=self.n_particles,
            space=ContinuousSpace(extent=(self.size, self.size), boundary='periodic'),
        )
        self.system_ = System(
            self.label,
            elements=[swimmers],
            interactions=[
                PolarAlignmentInteraction('align', target='swimmers', gamma=self.gamma, cutoff=self.d0),
                ActiveDiffusionInteraction('diffusion', target='swimmers', D_t=self.D_t, D_r=self.D_r),
                SelfPropulsionInteraction('propulsion', target='swimmers', speed=self.speed),
            ],
            solver=EulerMaruyamaSolver(dt=0.05),
        )

Components

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

Elements:

Interactions:

  • PolarAlignmentInteraction, from Interaction
  • ActiveDiffusionInteraction, from Interaction
  • SelfPropulsionInteraction, from Interaction
class SwimmerElement(ActiveParticleElement):
    """Active particle drawn as a point coloured by its heading."""

    visual = HEADINGS

class PolarAlignmentInteraction(Interaction):
    """Alignment torque `theta_i' += gamma sum_j sin(theta_j - theta_i)` between close particles.

    The sum runs over every neighbour `j` within the interaction range `cutoff`, so the torque turns each particle
    towards the headings of its neighbours. It is a bird turning with its flock, or a bacterium aligning with others
    in a swarm.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the particles, with the positions `x` and the headings `theta`.

        gamma:
            The strength of the alignment.

        cutoff:
            The interaction range.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import PolarAlignmentInteraction
        >>> PolarAlignmentInteraction('align', target='swimmers', gamma=0.5).gamma
        0.5
    """

    law_classes = (RateLaw,)

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

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the torque on the heading of every particle of the target from its neighbours.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        theta = context.target.theta
        torque = neighbors(context.gamma * sin(context.target.other.theta - theta), RadiusNeighborhood(self.cutoff))
        self.laws_ = [RateLaw(theta.diff(context.t), torque)]

class ActiveDiffusionInteraction(Interaction):
    """Diffusion of the position and the orientation of active particles.

    The position follows `dx = sqrt(2 D_t) dW` and the orientation `dtheta = omega dt + sqrt(2 D_r) dW`. With `omega =
    0` it is an active Brownian particle, and otherwise a chiral one. It is a bacterium, a Janus colloid, or a robot
    that loses its heading.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the particles, whose position is `x` and orientation `theta`.

        D_t:
            The translational diffusion coefficient.

        D_r:
            The rotational diffusion coefficient.

        omega:
            The angular velocity of a chiral particle.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components.spaces import ContinuousSpace
        >>> from skcomplex.core.engine.solvers import EulerMaruyamaSolver
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.particles import ActiveDiffusionInteraction, ActiveParticleElement
        >>> plane = ContinuousSpace(n_dim=2)
        >>> swimmers = ActiveParticleElement('swimmers', x=np.zeros((4000, 2)), size=4000, space=plane)
        >>> diffusion = ActiveDiffusionInteraction('diffusion', target='swimmers', D_r=0.5)
        >>> system = System(elements=[swimmers], interactions=[diffusion], solver=EulerMaruyamaSolver(dt=0.1))
        >>> angles = system.prepare().simulate(until=2.0, dt=2.0, random_state=0).get_values('swimmers.theta')[-1]
        >>> round(float((angles**2).mean()), 1)
        2.0
    """

    law_classes = (NoiseLaw, RateLaw)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        D_t: Annotated[float, RealSet.closed_open(0, oo)] = 0.1,
        D_r: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        omega: float = 0.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.D_t = D_t
        self.D_r = D_r
        self.omega = omega

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the noise of the position, and the turning and the noise of the orientation of the target.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        s = context
        theta = s.target.theta
        self.laws_ = [
            NoiseLaw(s.target.x, sqrt(2 * s.D_t)),
            RateLaw(theta.diff(s.t), s.omega),
            NoiseLaw(theta, sqrt(2 * s.D_r)),
        ]

class SelfPropulsionInteraction(Interaction):
    """Self-propulsion `x' += speed (cos theta, sin theta)` of a position in the plane.

    The position drifts along a heading `theta`, which other laws turn and diffuse. It is a swimming bacterium, a
    Janus colloid, or a walking robot.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the particle or the group whose positions move.

        speed:
            The self-propulsion speed.

        state:
            The name of the vector value that holds the position.

        heading:
            The name of the value that holds the heading.

    Examples:
        >>> import math
        >>> from skcomplex.core.components.spaces import ContinuousSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.particles import ActiveParticleElement, SelfPropulsionInteraction
        >>> swimmer = ActiveParticleElement('swimmer', theta=math.pi / 2)
        >>> propulsion = SelfPropulsionInteraction('propulsion', target='swimmer', speed=2.0)
        >>> system = System(elements=[swimmer], interactions=[propulsion], space=ContinuousSpace(n_dim=2))
        >>> trajectory = system.prepare().simulate(until=1.0, dt=1.0)
        >>> trajectory.get_values('swimmer.x')[-1].round(6).tolist()
        [0.0, 2.0]
    """

    law_classes = (RateLaw,)

    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 drift of the position of the target along its heading.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        heading = getattr(context.target, self.heading)
        velocity = context.speed * vector(SR, [cos(heading), sin(heading)])
        self.laws_ = [RateLaw(getattr(context.target, self.state), velocity)]