Skip to content

Ginelli nematic particles

Polar particles with nematic alignment.

  • Class: GinelliNematicsSystem
  • Import: from skcomplex.systems.physics.active_matter import GinelliNematicsSystem
  • Field: physics/active_matter
  • Topics: active matter, flocking, nematic, discrete time, neighborhood
  • References:
    • Ginelli et al. 2010
    • 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 GinelliNematicsSystem

trajectory = GinelliNematicsSystem().prepare().simulate()

Parameters

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

Parameter Default
n_particles 400
size 10.0
v0 0.3
eta 0.08
seed 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, vector
Structure fixed

Class

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

class GinelliNematicsSystem(BaseSystem):
    """Polar particles with nematic alignment.

    The particles order along a common axis but move both ways along it.

    At every step particle `i` takes the direction of `sum_j sign(cos(theta_j - theta_i)) exp(i theta_j)` over the
    particles within the unit distance, itself included, so it aligns with the axis of every neighbour on the side
    nearer its own heading, plus a uniform angle in `[-eta pi, eta pi]`, and moves `v0` along it. At low noise the
    particles share an axis, with as many moving one way as the other: the nematic order parameter `|<exp(2 i theta)>|`
    grows towards 1 while the polar order parameter stays small. 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.

        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 GinelliNematicsSystem
        >>> GinelliNematicsSystem(10).prepare().system_.elements[0].eta
        0.08
    """

    field = 'physics/active_matter'
    topics = ('active matter', 'flocking', 'nematic', 'discrete time', 'neighborhood')
    references = ('Ginelli et al. 2010', 'Chaté 2020')
    until = 300.0
    dt = 1.0
    observables = tuple(_get_orders('flock'))

    def __init__(
        self,
        n_particles: int = 400,
        *,
        size: float = 10.0,
        v0: float = 0.3,
        eta: float = 0.08,
        seed: int = 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.v0 = v0
        self.eta = eta
        self.seed = seed

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of polar particles with nematic alignment.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        x, theta = GregoireChateSystem._get_flockers(self.n_particles, self.size, self.seed)
        flock = NematicParticleElement(
            'flock',
            x=x,
            theta=theta,
            eta=self.eta,
            size=self.n_particles,
            space=ContinuousSpace(extent=(self.size, self.size), boundary='periodic'),
        )
        self.system_ = System(
            self.label,
            elements=[flock],
            interactions=[
                PropulsionStepInteraction('propulsion', target='flock', speed=self.v0),
                HeadingAlignmentInteraction('alignment', target='flock', nematic=True),
            ],
        )

Components

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

Elements:

  • NematicParticleElement, from Element

Interactions:

  • PropulsionStepInteraction, from Interaction
  • HeadingAlignmentInteraction, from Interaction
class NematicParticleElement(Element):
    """Polar particles with the positions `x`, the headings `theta`, and the noise amplitudes `eta`.

    `HeadingAlignmentInteraction` with `nematic=True` sets the new heading to the circular mean of the headings within
    the unit distance, itself included, each flipped to the side nearer the particle's own heading, plus a uniform
    angle in `[-eta pi, eta pi]`. A propulsion step moves the particle along its heading.

    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 NematicParticleElement
        >>> NematicParticleElement('rod', eta=0.2).eta
        0.2
    """

    visual = HEADINGS

    def __init__(
        self,
        label: str,
        *,
        x: object = (0.0, 0.0),
        theta: Annotated[object, Period(2 * math.pi)] = 0.0,
        eta: object = 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)]