Skip to content

Flocking with active and passive agents

The active and passive agents of Charbonneau (2017) in a periodic box.

  • Class: ActivePassiveFlockingSystem
  • Import: from skcomplex.systems.physics.active_matter import ActivePassiveFlockingSystem
  • Field: physics/active_matter
  • Topics: active matter, sde, flocking, phase separation, pair interaction
  • References:
    • Charbonneau 2017
    • Silverberg et al. 2013

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 ActivePassiveFlockingSystem

trajectory = ActivePassiveFlockingSystem().prepare().simulate()

Parameters

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

Parameter Default
n_agents 342
n_active 45
size 1.0
radius 0.025
epsilon 25.0
exponent 1.5
flocking_radius 0.1
alpha 1.0
v0 0.02
mu 10.0
eta 0.1
time_step 0.01
initial_speed 1.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 vector
Structure fixed

Class

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

class ActivePassiveFlockingSystem(BaseSystem):
    """The active and passive agents of Charbonneau (2017) in a periodic box.

    The system is that of section 10.4.

    All agents repel each other within `2 r_0` with the force `epsilon (1 - r / (2 r_0))^exponent`, and all feel the
    force `mu (v_t - |v|) v / |v|`, with the target speed `v_t = v0` for an active agent and 0 for a passive one. An
    active agent also feels the flocking force `alpha V / |V|`, with `V` the sum of the velocities of the agents of both
    kinds within the flocking radius, itself excluded, and a random force. Agents start at uniform random positions with
    velocity components uniform up to `initial_speed`. The defaults are those of figure 10.7 at the compactness `C = pi
    N r_0^2 / size^2 = 0.672`. The values `exponent=2.5`, `epsilon=100`, `mu=0.05`, `radius=1`, `flocking_radius=4`, and
    `v0=1` are those of Silverberg et al. (2013). The system has the group `agents` that holds the active agents first,
    the positions `agents.x`, the velocities `agents.x'`, the marks `agents.active`, and the observables
    `polarization`, `active_distance`, and `passive_distance`.

    Args:
        n_agents:
            The number of agents.

        n_active:
            The number of active agents.

        size:
            The side of the periodic box.

        radius:
            The radius `r_0` of an agent, so agents overlap below the distance `2 r_0`.

        epsilon:
            The strength of the repulsion.

        exponent:
            The exponent of the repulsion.

        flocking_radius:
            The radius within which an active agent reads the velocities of the others.

        alpha:
            The size of the flocking force on an active agent, 0 for no flocking.

        v0:
            The target speed of the active agents.

        mu:
            The strength of the propulsion.

        eta:
            The half-width of the uniform random force per step of the book. The noise is a Wiener process with the
            same variance per step, of amplitude `eta sqrt(time_step / 3)`.

        time_step:
            The step of the solver that `eta` refers to.

        initial_speed:
            The largest size of a component of an initial velocity.

        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 Euler-Maruyama with the step `time_step`.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for Numba.

    Raises:
        ValidationError:
            The number of active agents is not between 1 and `n_agents`.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import ActivePassiveFlockingSystem
        >>> [element.label for element in ActivePassiveFlockingSystem(114).prepare().system_.elements]
        ['agents']
    """

    field = 'physics/active_matter'
    topics = ('active matter', 'sde', 'flocking', 'phase separation', 'pair interaction')
    references = ('Charbonneau 2017', 'Silverberg et al. 2013')
    until = 50.0
    dt = 0.5

    @staticmethod
    def _get_velocity_x(member: SimpleNamespace) -> Expression:
        """Return the first velocity component of a member when active, and 0 otherwise."""
        return member.active * member.x.diff(member.t)[0]

    @staticmethod
    def _get_velocity_y(member: SimpleNamespace) -> Expression:
        """Return the second velocity component of a member when active, and 0 otherwise."""
        return member.active * member.x.diff(member.t)[1]

    @staticmethod
    def _get_speed(member: SimpleNamespace) -> Expression:
        """Return the speed of a member when active, and 0 otherwise."""
        velocity = member.x.diff(member.t)
        return member.active * sqrt(velocity.dot_product(velocity))

    @staticmethod
    def _get_polarization(s: SimpleNamespace) -> Expression:
        """Return the modulus of the mean active velocity over the mean active speed."""
        return sqrt(s.velocity_x**2 + s.velocity_y**2) / s.mean_speed

    @staticmethod
    def _get_mean_distance(t: float, values: Mapping[str, object], *, mark: float, size: float) -> float:
        """Return the mean distance between the agents of a mark in a periodic box.

        The distance is 0 for fewer than two agents.
        """
        del t
        positions = np.asarray(values['agents.x'], dtype=float)[np.asarray(values['agents.active']) == mark]
        count = len(positions)
        if count < SMALLEST_GROUP:
            return 0.0
        separations = positions[:, None, :] - positions[None, :, :]
        separations -= size * np.round(separations / size)
        distances: Array = np.sqrt((separations**2).sum(axis=-1))
        return float(distances.sum() / (count * (count - 1)))

    def __init__(
        self,
        n_agents: int = 342,
        *,
        n_active: int = 45,
        size: float = 1.0,
        radius: float = 0.025,
        epsilon: float = 25.0,
        exponent: float = 1.5,
        flocking_radius: float = 0.1,
        alpha: float = 1.0,
        v0: float = 0.02,
        mu: float = 10.0,
        eta: float = 0.1,
        time_step: float = TIME_STEP,
        initial_speed: float = 1.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_agents = n_agents
        self.n_active = n_active
        self.size = size
        self.radius = radius
        self.epsilon = epsilon
        self.exponent = exponent
        self.flocking_radius = flocking_radius
        self.alpha = alpha
        self.v0 = v0
        self.mu = mu
        self.eta = eta
        self.time_step = time_step
        self.initial_speed = initial_speed
        self.random_state = random_state

    @staticmethod
    def _get_repulsion_energy(
        s: SimpleNamespace,
        r: Expression,
        *,
        epsilon: float,
        radius: float,
        exponent: float,
    ) -> Expression:
        """Return the energy of the soft repulsion between agents.

        Its force at the distance `r` is the repulsion `epsilon (1 - r / (2 r_0))^exponent`.
        """
        del s
        overlap = 1 - r / (2 * radius)
        return epsilon * 2 * radius * overlap ** (exponent + 1) / (exponent + 1)

    def _get_repulsion_laws(self, s: SimpleNamespace) -> list[BaseLaw]:
        """Return the push of every agent by the agents that overlap it.

        The push of one agent is minus the slope of the repulsion energy along the line of centres, summed over the
        agents within two radii.
        """
        x = s.target.x
        separation = x - s.target.other.x
        r = sqrt(separation.dot_product(separation))
        distance = SR.var('r', domain='positive')
        energy = self._get_repulsion_energy(
            s,
            distance,
            epsilon=self.epsilon,
            radius=self.radius,
            exponent=self.exponent,
        )
        slope = SR(energy).diff(distance).subs({distance: r})
        push = neighbors(-slope * separation / r, RadiusNeighborhood(2 * self.radius))
        return [RateLaw(x.diff(s.t, 2), push)]

    @staticmethod
    def _get_observables(system: System) -> list[Observable]:
        """Return the observables of the agents.

        They are the velocity of the active agents, their polarization, and the mean distance within each kind.
        """
        if not isinstance(system.space, ContinuousSpace):
            error_msg = (
                'The observables of `ActivePassiveFlockingSystem` read the periodic box of its continuous space.'
            )
            raise ValidationError(error_msg)
        size = float(system.space.extent[0])
        return [
            Observable('velocity_x', ActivePassiveFlockingSystem._get_velocity_x, group='agents'),
            Observable('velocity_y', ActivePassiveFlockingSystem._get_velocity_y, group='agents'),
            Observable('mean_speed', ActivePassiveFlockingSystem._get_speed, group='agents'),
            Observable('polarization', ActivePassiveFlockingSystem._get_polarization),
            Observable(
                'active_distance',
                function=functools.partial(
                    ActivePassiveFlockingSystem._get_mean_distance,
                    mark=ACTIVE_AGENT,
                    size=size,
                ),
            ),
            Observable(
                'passive_distance',
                function=functools.partial(
                    ActivePassiveFlockingSystem._get_mean_distance,
                    mark=PASSIVE_AGENT,
                    size=size,
                ),
            ),
        ]

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to the active and passive agents at random places and velocities in a periodic box.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.

        Raises:
            ValidationError:
                The number of active agents is not between 1 and `n_agents`.
        """
        super()._prepare(context)
        if not 1 <= self.n_active <= self.n_agents:
            error_msg = (
                f'The system has {self.n_active} active agents among {self.n_agents}. Give at least one, and at most '
                'all.'
            )
            raise ValidationError(error_msg)
        rng = np.random.default_rng(self.random_state)
        box = ContinuousSpace(extent=(self.size, self.size), boundary='periodic')
        agents = FlockingAgentElement(
            'agents',
            x=rng.uniform(0.0, self.size, (self.n_agents, 2)),
            active=np.where(np.arange(self.n_agents) < self.n_active, ACTIVE_AGENT, PASSIVE_AGENT),
            radius=self.radius,
            values={"x'": rng.uniform(-self.initial_speed, self.initial_speed, (self.n_agents, 2))},
            size=self.n_agents,
            space=box,
        )
        interactions = [
            Interaction('repulsion', roles={'target': 'agents'}, laws=self._get_repulsion_laws),
            TargetSpeedInteraction(
                'propulsion',
                target='agents',
                mu=self.mu,
                v0=self.v0,
                eta=self.eta * math.sqrt(self.time_step / 3),
            ),
            VelocityFlockingInteraction('flocking', target='agents', alpha=self.alpha, reach=self.flocking_radius),
        ]
        self.system_ = System(
            self.label,
            elements=[agents],
            interactions=interactions,
            space=box,
            solver=EulerMaruyamaSolver(dt=self.time_step),
            backend=NumbaBackend(),
        )
        self.observables_ = tuple(self._get_observables(self.system_))

Components

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

Elements:

Interactions:

  • Interaction
  • TargetSpeedInteraction, from Interaction
  • VelocityFlockingInteraction, from Interaction
class FlockingAgentElement(PointElement):
    """Agent of a crowd, a point with a mark that says whether it is active or passive.

    Args:
        label:
            The label of the agent or the group.

        x:
            The initial position.

        active:
            The mark, 1 for an active agent or 0 for a passive one.

        radius:
            The radius `r_0` of the agent, which it is drawn with.

        values:
            Further values by name, such as the starting velocity `"x'"`.

        size:
            The number of agents, or `None` for one.

        space:
            The continuous space of the agents, or `None` for none.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import FlockingAgentElement
        >>> FlockingAgentElement('agent', active=0.0).active
        0.0
    """

    visual = VisualSpec(
        'points',
        {'position': 'x', 'radius': 'radius', 'color_by': 'active', 'color_range': (0.0, 1.0)},
    )

    def __init__(
        self,
        label: str,
        x: npt.ArrayLike = 0.0,
        *,
        active: Annotated[object, FiniteEnumeratedSet([PASSIVE_AGENT, ACTIVE_AGENT])] = ACTIVE_AGENT,
        radius: Annotated[float, RealSet.open(0, oo)] = 1.0,
        values: Mapping[str, object] | None = None,
        size: int | None = None,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, x=x, values=values, size=size, space=space)
        self.active = active
        self.radius = radius

class Interaction(BaseInteraction):
    """An interaction whose laws run once for the elements its roles bind.

    It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
    `Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
    role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
    edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
    random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
    members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
    parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
    populations, a reaction between two chemicals, and an infection along the contacts of a network.

    Read more in the user guide, under Interactions.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'predation'`.

        roles:
            The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
            without a class, or `None`.

        laws:
            The function of the namespace that returns the laws of a rule written without a class, such as
            `lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
            `None`.

        among:
            The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
            their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

        along:
            `True` for the edges of the network the group lives on, the name of a layer of a network with several, such
            as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
            `RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
            member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
            element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.

        within:
            A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
            closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
            walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
            give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
            force `-dV/dx` on its position `x`.

    See Also:
        BaseInteraction: The base of every interaction.
        RandomPartition: Groups the members of a group at random at every step.
        TrainingInteraction: Trains the parameters of a nested system.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
        >>> birth.roles
        {'target': 'fish'}
    """

    def __init__(
        self,
        label: str,
        *,
        roles: Mapping[str, object] | None = None,
        laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
        among: str | None = None,
        along: bool | str | tuple[str, int] | RandomPartition | None = None,
        within: RadiusNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.roles = roles
        self.laws = laws
        self.among = among
        self.along = along
        self.within = within

    def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
        """Return the numeric arguments as parameters, and `roles` and `among` as roles.

        With `within`, `among` binds both members of a pair, `first` and `second`.
        """
        declared = dict(super()._get_declared())
        for name, binding in (self.roles or {}).items():
            declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
        if self.among is not None and self.within is not None:
            for name in PAIR_ROLES:
                declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
        elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
            declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
        return declared

    @classmethod
    def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
        """Return the arguments that name the states a role reads.

        The mapping `roles` of bindings names none.
        """
        return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')

    def _get_binding(self, role: str) -> object:
        """Return what a role binds, from `roles` or from the argument of its name.

        Args:
            role:
                The name of the role.

        Returns:
            binding:
                The label, labels, or entries the role binds, or `None` when it binds nothing.
        """
        if self.roles is not None and role in self.roles:
            return self.roles[role]
        if self.among is not None and self.within is not None and role in PAIR_ROLES:
            return self.among
        return super()._get_binding(role)

    def _check_arguments(self) -> None:
        """Raise an error for roles, laws, or groups the interaction cannot take.

        Raises:
            ValidationError:
                A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
                `along` names hyperedges of fewer than two members.
        """
        clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
        if clashes:
            error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
            raise ValidationError(error_msg)
        if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
            error_msg = (
                f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
                '`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, tuple) and not self._is_sized(self.along):
            error_msg = (
                f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
                "more, such as `along=('hyperedges', 3)`."
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, RandomPartition):
            self.along._check()
        grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
        if grouped and self.among is None:
            error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
            raise ValidationError(error_msg)
        super()._check_arguments()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of `laws` for a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        if self.laws is not None:
            self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)

    @staticmethod
    def _is_sized(along: tuple[object, ...]) -> bool:
        """Return whether `along` names hyperedges of a whole size of at least two."""
        if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
            return False
        size = along[1]
        return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE

    def _get_draws(self) -> bool:
        """Return whether the interaction draws, as it does along random groups."""
        return super()._get_draws() or isinstance(self.along, RandomPartition)

    def _runs_on_edges(self) -> bool:
        """Return whether the interaction runs along edges."""
        grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
        return self.along is not None and self.along is not False and not grouped

    def _runs_on_hyperedges(self) -> bool:
        """Return whether the interaction runs along the hyperedges of a network."""
        return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)

    def _get_hyperedge_size(self) -> int | None:
        """Return the size `along` gives the hyperedges, or `None` for every size."""
        return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None

    def _get_within(self) -> RadiusNeighborhood | None:
        """Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
        return self.within

    def _get_layer(self) -> str | None:
        """Return the layer `along` names, or `None` for no layer."""
        if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
            return None
        return self.along

    def _get_grouping(self) -> tuple[str, int, str] | None:
        """Return the kind, size, and reduction of the groups `along` names, or `None`."""
        if isinstance(self.along, RandomPartition):
            return ('partition', self.along.size, 'sum')
        if self.along == NEIGHBORHOODS:
            return ('neighborhood', 0, 'sum')
        return None

class TargetSpeedInteraction(Interaction):
    """Propulsion towards a target speed with a random force, which only active agents feel at full strength.

    Every agent feels `mu (active v0 - |v|) v / |v|` on its velocity `v = x'`, so active agents speed up to `v0` and
    passive ones slow to rest, and a random force of amplitude `active eta`. It is a self-propelled bacterium among
    dead ones, a walking pedestrian among standing ones, or a running fan in a crowd.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the agents, whose values are `x` and `active`.

        mu:
            The strength of the propulsion.

        v0:
            The target speed of the active agents.

        eta:
            The amplitude of the random force on an active agent.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import TargetSpeedInteraction
        >>> TargetSpeedInteraction('propulsion', target='agents', v0=0.5).v0
        0.5
    """

    law_classes = (RateLaw, NoiseLaw)

    def __init__(self, label: str, *, target: Role, mu: float = 10.0, v0: float = 0.02, eta: float = 0.0) -> None:
        super().__init__(label)
        self.target = target
        self.mu = mu
        self.v0 = v0
        self.eta = eta

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the propulsion and the random force on the velocity of the agents.

        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)
        speed = sqrt(velocity.dot_product(velocity) + SOFTENING)
        self.laws_ = [
            RateLaw(x.diff(t, 2), velocity * (s.mu * (s.target.active * s.v0 - speed) / speed)),
            NoiseLaw(x.diff(t, 2), s.target.active * s.eta),
        ]

class VelocityFlockingInteraction(Interaction):
    """Flocking force of size `alpha` along the summed velocities of the neighbours, felt by active agents.

    The force is `active alpha V / |V|`, with `V` the sum of the velocities `x'` of the other agents within `reach`. It
    is the alignment of birds in a flock, of fish in a school, or of marching locusts.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the agents, whose values are `x` and `active`.

        alpha:
            The size of the flocking force.

        reach:
            The radius within which an agent reads the velocities of the others.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import VelocityFlockingInteraction
        >>> VelocityFlockingInteraction('flocking', target='agents', reach=0.2).reach
        0.2
    """

    law_classes = (RateLaw,)

    def __init__(self, label: str, *, target: Role, alpha: float = 1.0, reach: float = 0.1) -> None:
        super().__init__(label)
        self.target = target
        self.alpha = alpha
        self.reach = reach

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the flocking force on the velocity of the agents.

        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
        summed = neighbors(s.target.other.x.diff(t), over=RadiusNeighborhood(self.reach))
        force = summed * (s.target.active * s.alpha / sqrt(summed.dot_product(summed) + SOFTENING))
        self.laws_ = [RateLaw(x.diff(t, 2), force)]