Skip to content

Bertin-Droz-Grégoire kinetic flocking

The kinetic theory of flocking.

  • Class: BertinDrozGregoireSystem
  • Import: from skcomplex.systems.physics.active_matter import BertinDrozGregoireSystem
  • Field: physics/active_matter
  • Topics: field, kinetic, phase space, flocking, pde
  • References:
    • Bertin, Droz, and Grégoire 2006
    • Bertin, Droz, and Grégoire 2009

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 BertinDrozGregoireSystem

trajectory = BertinDrozGregoireSystem().prepare().simulate()

Parameters

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

Parameter Default
positions 4
angles 16
density 1.0
speed 1.0
interaction_range 0.5
tumbling 1.0
noise 0.5
perturbation 0.01
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 phase space
Laws rate
Randomness unknown
Domains real
Structure fixed

Class

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

class BertinDrozGregoireSystem(BaseSystem):
    """The kinetic theory of flocking.

    Its polar order grows above a transition density.

    Particles stream along their orientation, tumble at a rate by a wrapped normal noise, and align in binary collisions
    at their mean angle with the same noise. A homogeneous disordered state is unstable above the density `pi tumbling
    (1 - exp(-noise^2 / 2)) / (8 interaction_range speed (exp(-noise^2 / 2) - 2 / 3))`. The system has the density
    `flock.x`.

    Args:
        positions:
            The number of positions along each of the two periodic position axes of unit spacing.

        angles:
            The number of cells of the orientation axis.

        density:
            The density of the homogeneous state.

        speed:
            The speed of the particles.

        interaction_range:
            The interaction range.

        tumbling:
            The rate of the tumbling events.

        noise:
            The standard deviation of the noise of tumbling and alignment.

        perturbation:
            The relative amplitude of the initial polar perturbation.

        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 Runge-Kutta steps of 0.05.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import BertinDrozGregoireSystem
        >>> BertinDrozGregoireSystem(2, 8).prepare().system_.elements[0].space.prepare().size_
        32
    """

    field = 'physics/active_matter'
    topics = ('field', 'kinetic', 'phase space', 'flocking', 'pde')
    references = ('Bertin, Droz, and Grégoire 2006', 'Bertin, Droz, and Grégoire 2009')
    until = 0.5
    dt = 0.1

    def __init__(
        self,
        positions: int = 4,
        angles: int = 16,
        *,
        density: float = 1.0,
        speed: float = 1.0,
        interaction_range: float = 0.5,
        tumbling: float = 1.0,
        noise: float = 0.5,
        perturbation: float = 0.01,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.positions = positions
        self.angles = angles
        self.density = density
        self.speed = speed
        self.interaction_range = interaction_range
        self.tumbling = tumbling
        self.noise = noise
        self.perturbation = perturbation

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a homogeneous flock with a small polar perturbation.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        axis = AxisSpec('theta', self.angles, 0.0, 2 * math.pi, periodic=True)
        position = LatticeSpace((self.positions, self.positions), discretization='finite-volume')
        space = PhaseSpace(position, [axis]).prepare()
        theta = space.coordinates_['theta']
        profile = self.density * (1.0 + self.perturbation * np.cos(theta)) / (2 * math.pi)
        flock = PhaseSpaceDensityElement('flock', x=np.broadcast_to(profile, space.shape_).ravel(), space=space)

        def drift(_: SimpleNamespace) -> list[Expression]:
            return [self.speed * cos(coordinate('theta')), self.speed * sin(coordinate('theta')), 0]

        self.system_ = System(
            self.label,
            elements=[flock],
            interactions=[
                AdvectionInteraction('stream', target='flock', state='x', drift=drift),
                AngularDiffusionInteraction(
                    'tumble',
                    candidate='flock',
                    angles=self.angles,
                    tumbling=self.tumbling,
                    noise=self.noise,
                ),
                AngularAlignmentInteraction(
                    'align',
                    candidate='flock',
                    field='flock',
                    angles=self.angles,
                    frequency=self.interaction_range * self.speed,
                    noise=self.noise,
                ),
            ],
            solver=RK4Solver(dt=0.05),
        )

Components

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

Elements:

  • PhaseSpaceDensityElement, from Element

Interactions:

  • AdvectionInteraction, from Interaction
  • AngularDiffusionInteraction, from Interaction, through the shared recipe EncounterInteraction
  • AngularAlignmentInteraction, from Interaction, through the shared recipe EncounterInteraction
class PhaseSpaceDensityElement(Element):
    """Value `x` of the one-particle density of kinetic theory at every point of a phase space.

    A gas is one member per position and velocity of a `PhaseSpace`, and streaming, collisions, and relaxation change
    it. The density is nonnegative.

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

        x:
            The initial density, one nonnegative value per point or one for all.

        space:
            The phase space of the points, or `None` for one point.

    Examples:
        >>> from skcomplex.core.components.spaces import AxisSpec, LatticeSpace, PhaseSpace
        >>> from skcomplex.systems.physics.common.fields import PhaseSpaceDensityElement
        >>> space = PhaseSpace(LatticeSpace(4), [AxisSpec('v', 8, -3.0, 3.0)])
        >>> PhaseSpaceDensityElement('gas', x=0.2, space=space).space.prepare().size_
        32
    """

    def __init__(
        self,
        label: str,
        *,
        x: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.x = x

class AdvectionInteraction(Interaction):
    """Advection `du/dt + divergence(a u) = source(ns)` of a state `u` of a field by a drift.

    Physics names it advection, the transport of a state by a flow or by the streaming of a phase-space density.
    The drift field is `a(ns)`. The flux of the conservation law is the drift times the state, written in conservative
    form, so the total of the state on a periodic field stays constant and, on a spectral field, the dealiasing of
    products applies to it. The drift is one expression for a field of one dimension, or one per dimension, of the
    states and parameters of the field, and may read other states than the one it carries, such as the flow of a fluid
    derived from a streamfunction, or the drift of a probability density in a Fokker-Planck equation.

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

        target:
            The path of the field whose state is carried.

        state:
            The name of the carried state of the field.

        drift:
            A function of the namespace that returns the drift, or one drift per dimension.

        source:
            A function of the namespace that returns the source, or `None` for none.

    Raises:
        ValidationError:
            The state is not a name, or a function is not callable.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.fields import AdvectionInteraction
        >>> space = LatticeSpace((50,), spacing=0.1, boundary='periodic', discretization='finite-volume')
        >>> values = {'u': np.exp(-((np.arange(50) - 25) / 5.0) ** 2)}
        >>> tracer = Element('tracer', values=values, space=space)
        >>> drift = AdvectionInteraction('drift', target='tracer', state='u', drift=lambda s: 1.0)
        >>> trajectory = System(elements=[tracer], interactions=[drift]).prepare().simulate(until=1.0, dt=0.01)
        >>> total = trajectory.get_values('tracer.u')[-1].sum()
        >>> round(float(total), 6) == round(float(values['u'].sum()), 6)
        True
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'u',
        drift: Callable[[SimpleNamespace], object] | None = None,
        source: Callable[[SimpleNamespace], object] | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.drift = drift
        self.source = source

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The state is not a name, the drift is not callable, or the source is neither callable nor `None`.
        """
        super()._check_arguments()
        if not isinstance(self.state, str) or not self.state.isidentifier():
            error_msg = f'{type(self).__name__} {self.label!r} carries the state {self.state!r}, which is no name.'
            raise ValidationError(error_msg)
        if not callable(self.drift):
            error_msg = f'The drift of {self.label!r} is {self.drift!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)
        if self.source is not None and not callable(self.source):
            error_msg = f'The source of {self.label!r} is {self.source!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate of the divergence of the flux `a u` and the rate of the source.

        Args:
            context:
                The namespace of the field, the time `t`, and the parameters.
        """
        super()._prepare(context)
        u = getattr(context.target, self.state)
        drift = cast('Callable[[SimpleNamespace], object]', self.drift)(context)
        components = drift if isinstance(drift, FreeModuleElement | list | tuple) else [drift]
        self.laws_ = [RateLaw(u, -divergence([SR(component) * u for component in components]))]
        if self.source is not None:
            self.laws_.append(RateLaw(u, self.source(context)))

class AngularDiffusionInteraction(EncounterInteraction):
    """Self-diffusion of self-propelled particles, a linear redistribution.

    The particles change their angle at a rate by a wrapped normal noise.

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

        candidate:
            The path of the field on a phase space with a periodic orientation axis.

        angles:
            The number of cells of the orientation axis on `[0, 2 pi)`.

        tumbling:
            The rate of the events.

        noise:
            The standard deviation of the noise of an event.

        state:
            The name of the state of the density.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import AngularDiffusionInteraction
        >>> AngularDiffusionInteraction('tumble', candidate='flock', angles=8, tumbling=1.0, noise=0.5).field
    """

    def __init__(
        self,
        label: str,
        *,
        candidate: Role,
        angles: int = 32,
        tumbling: float = 1.0,
        noise: float = 0.5,
        state: str = 'x',
    ) -> None:
        super().__init__(label, candidate=candidate, rate=self._get_rate, kernel=self._get_kernel, state=state)
        self.angles = angles
        self.tumbling = tumbling
        self.noise = noise

    def _get_rate(self, _: SimpleNamespace) -> float:
        """Return the rate of the events."""
        return self.tumbling

    def _get_kernel(self, _: SimpleNamespace) -> npt.NDArray[np.float64]:
        """Return the probability of every angle after an event at every angle."""
        centres = 2 * np.pi * (np.arange(self.angles) + 0.5) / self.angles
        gaps = np.angle(np.exp(1j * np.subtract.outer(centres, centres)))
        weights = np.exp(-(gaps**2) / (2 * self.noise**2))
        return weights / weights.sum(axis=1, keepdims=True)

class AngularAlignmentInteraction(EncounterInteraction):
    """Binary collisions of self-propelled particles.

    Pairs of particles leave a collision at their mean angle plus a wrapped normal noise.

    A pair of angles meets at the rate `4 d0 v0 |sin((a - b) / 2)|`, the frequency of Bertin, Droz, and Grégoire, with
    `d0` the interaction range and `v0` the speed. A pair of opposite angles leaves at either of its two mean angles
    with equal probability.

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

        candidate:
            The path of the field on a phase space with a periodic orientation axis.

        field:
            The path of the field the candidate meets, usually the candidate itself.

        angles:
            The number of cells of the orientation axis on `[0, 2 pi)`.

        frequency:
            The product `d0 v0` of the interaction range and the speed.

        noise:
            The standard deviation of the noise of the outcome.

        state:
            The name of the state of the density.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import AngularAlignmentInteraction
        >>> align = AngularAlignmentInteraction('align', candidate='flock', field='flock', frequency=0.5, noise=0.5)
        >>> align.outcome
        'conservative'
    """

    def __init__(
        self,
        label: str,
        *,
        candidate: Role,
        field: Role,
        angles: int = 32,
        frequency: float = 1.0,
        noise: float = 0.5,
        state: str = 'x',
    ) -> None:
        super().__init__(
            label,
            candidate=candidate,
            field=field,
            rate=self._get_rate,
            kernel=self._get_kernel,
            state=state,
        )
        self.angles = angles
        self.frequency = frequency
        self.noise = noise

    def _get_centres(self) -> npt.NDArray[np.float64]:
        """Return the angle of every cell."""
        return 2 * np.pi * (np.arange(self.angles) + 0.5) / self.angles

    def _get_rate(self, _: SimpleNamespace) -> npt.NDArray[np.float64]:
        """Return the rate of every pair of angles times the cell width of the partner."""
        centres = self._get_centres()
        return 8 * np.pi / self.angles * self.frequency * np.abs(np.sin(np.subtract.outer(centres, centres) / 2))

    def _get_noise_weights(
        self,
        centres: npt.NDArray[np.float64],
        means: npt.NDArray[np.float64],
    ) -> npt.NDArray[np.float64]:
        """Return the wrapped normal weight of every angle around each pair's mean angle."""
        gaps = np.angle(np.exp(1j * (centres[None, None, :] - means[:, :, None])))
        return np.exp(-(gaps**2) / (2 * self.noise**2))

    def _get_kernel(self, _: SimpleNamespace) -> npt.NDArray[np.float64]:
        """Return the probability of every outcome angle of every pair of angles.

        The outcome angles spread around the mean angle of the pair.
        """
        centres = self._get_centres()
        cosines, sines = np.cos(centres), np.sin(centres)
        along, across = np.add.outer(cosines, cosines), np.add.outer(sines, sines)
        means = np.arctan2(across, along)
        opposite = np.hypot(along, across) < ANTIPODAL
        means = np.where(opposite, centres[:, None] + np.pi / 2, means)
        weights = self._get_noise_weights(centres, means)
        weights = np.where(
            opposite[:, :, None],
            (weights + self._get_noise_weights(centres, means + np.pi)) / 2,
            weights,
        )
        return weights / weights.sum(axis=2, keepdims=True)