Skip to content

Szabó cell system

The cells of Szabó et al. (2006) in a periodic box, which move together above a critical density.

  • Name: szabo_cells
  • Field: physics/active_matter
  • Formalism: stochastic differential equations
  • References: Szabó et al. 2006; Vicsek and Zafeiris 2012

Select this system

from skcomplex.systems import create_simulation, create_system, describe

system = create_system('szabo_cells')
entry = describe('szabo_cells')
trajectory = create_simulation('szabo_cells').prepare().run().trajectory_

Factory

@register_system(
    field='physics/active_matter',
    tags=('active matter', 'sde', 'flocking', 'tissue', 'neighbours'),
    references=('Szabó et al. 2006', 'Vicsek and Zafeiris 2012'),
    defaults={'until': 60.0, 'dt': 0.5, 'solver': EulerMaruyamaSolver(dt=0.01), 'backend': NumbaBackend()},
    observables=lambda system: [
        ObservableSpec('mean_heading', _heading, group='cells'),
        ObservableSpec('polarization', _polarization),
    ],
)
def szabo_cells(
    n_cells: int = 200,
    *,
    density: float = 1.0,
    eta: float = 0.6,
    v0: float = 1.0,
    mu: float = 1.0,
    tau: float = 1.0,
    R_eq: float = 5.0 / 6.0,
    R_0: float = 1.0,
    F_rep: float = 30.0,
    F_adh: float = 0.75,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return the cells of Szabó et al. (2006) in a periodic box, which move together above a critical density.

    A cell moves at `x' = v0 n + mu F`, where `F` sums the pair forces of the neighbours within `R_0`, the diameter of a
    cell, and its heading turns towards its velocity, `theta' = arcsin((n x v / |v|) . e_z) / tau + xi`. No cell reads
    the headings of the others, and adhesion alone orders them. With `eta = 0.6` the transition lies at the number
    density `rho_c = 0.18 / R_0^2`.

    Args:
        n_cells:
            The number of cells.

        density:
            The number of cells per unit area.

        eta:
            The strength of the angular noise.

        v0:
            The speed of the motility.

        mu:
            The mobility.

        tau:
            The relaxation time of the heading.

        R_eq:
            The equilibrium distance of a pair.

        R_0:
            The distance beyond which a pair exerts no force.

        F_rep:
            The largest repulsive force.

        F_adh:
            The largest adhesive force.

        random_state:
            The seed or generator of the initial positions and headings.

    Returns:
        system:
            The system, with the positions `cells.x`, the headings `cells.theta`, and the observables `mean_heading` and
            `polarization`.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import szabo_cells
        >>> szabo_cells(16, density=0.5).space.extent
        (5.656854249492381, 5.656854249492381)
    """
    size = math.sqrt(n_cells / density)
    rng = np.random.default_rng(random_state)
    cells = GroupElement(
        'cells',
        element=MotileCellElement,
        size=n_cells,
        values={
            'x': rng.uniform(0.0, size, (n_cells, 2)),
            'theta': rng.uniform(0.0, 2 * math.pi, n_cells),
            'v0': v0,
            'mu': mu,
            'tau': tau,
            'eta': eta,
            'R_eq': R_eq,
            'R_0': R_0,
            'F_rep': F_rep,
            'F_adh': F_adh,
        },
        visual=VisualSpec('points', {'position': 'x', 'radius': R_0 / 2, 'color_by': 'theta'}),
    )
    motion = RateInteraction('motion', target='cells', state='x', rate=functools.partial(_velocity, reach=R_0))
    turning = RateInteraction(
        'turning',
        target='cells',
        state='theta',
        rate=functools.partial(_turning, reach=R_0),
        noise=_angular_noise,
    )
    return System(
        elements=[cells],
        interactions=[motion, turning],
        space=ContinuousSpace(extent=(size, size), boundary='periodic'),
    )

Components

Elements:

  • MotileCellElement, from Element

Interactions:

  • RateInteraction
class MotileCellElement(Element):
    """Motile cell of a tissue, with its position, the heading of its motility, and its force and motility parameters.

    The position follows `x' = v0 n + mu F`, where `n` is the unit vector of the heading and `F` the sum of the pair
    forces. A pair force is `F_rep (d - R_eq) / R_eq` towards the neighbour below the distance `R_eq`, and
    `F_adh (d - R_eq) / (R_0 - R_eq)` towards it up to the distance `R_0`, the cell diameter.

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

        visual:
            How the element is drawn, or `None` for `default_visual_`.

        x:
            The initial position.

        theta:
            The initial heading.

        v0:
            The speed of the motility.

        mu:
            The mobility.

        tau:
            The relaxation time of the heading.

        eta:
            The strength of the angular noise, whose variance per unit time is `eta^2 / 12`.

        R_eq:
            The equilibrium distance of a pair.

        R_0:
            The distance beyond which a pair exerts no force.

        F_rep:
            The largest repulsive force.

        F_adh:
            The largest adhesive force.

    Examples:
        >>> from skcomplex.systems.physics.active_matter import MotileCellElement
        >>> MotileCellElement('cell').F_rep
        30.0
    """

    def __init__(
        self,
        label: str,
        visual: VisualSpec | None = None,
        *,
        x: Annotated[npt.ArrayLike, StateSpec(vector=True, role='position')] = 0.0,
        theta: Annotated[float, StateSpec(period=2 * pi, role='direction')] = 0.0,
        v0: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
        mu: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
        tau: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
        eta: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.6,
        R_eq: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 5.0 / 6.0,
        R_0: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
        F_rep: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 30.0,
        F_adh: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.75,
    ) -> None:
        super().__init__(label, visual=visual)
        self.x = x
        self.theta = theta
        self.v0 = v0
        self.mu = mu
        self.tau = tau
        self.eta = eta
        self.R_eq = R_eq
        self.R_0 = R_0
        self.F_rep = F_rep
        self.F_adh = F_adh

class RateInteraction(Interaction):
    """Rate `rate(ns)` and noise `noise(ns) dW` added to the highest time derivative of a state of a target.

    On a state of order 1 the rate is its first derivative, and on a state of order `k` it adds to the `k`-th
    derivative, so rates on one state superpose. With a divisor `d` the rate and the noise are divided by `d`, the name
    of a state or parameter of the target, such as an inertia, a friction, or a capacitance, which backends can read.

    A rate, a noise, or a divisor function takes the namespace of the interaction, with the namespaces `target` and
    `sources` of the bound elements, the time `t`, and the symbols of the parameters a subclass declares. A number
    stands for a constant, and a number on a vector state applies to every component. The noise is a Wiener process per
    component and member by default, a process of a `WienerProcessSpec` to share or correlate it across states and
    members, or a fractional Brownian motion of a Hurst index.

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

        target:
            The path of the element or group whose state the rate changes.

        state:
            The name of the state of the target that the rate changes.

        rate:
            A function of the namespace that returns the rate, or a number.

        sources:
            The paths of the elements or groups the rate and the noise read but do not change.

        noise:
            A function of the namespace that returns the amplitude of the noise, a number, or `None` for no noise.

        divisor:
            The name of the state or parameter of the target that divides the rate and the noise, a function of the
            namespace of the target that returns the divisor, such as a moment of inertia `m l^2`, or `None`.

        process:
            The Wiener processes that drive the noise, or `None` for one independent process per component and member.

        index:
            The process of `process` that drives the noise, or `None` for every process, one per component of a vector
            state.

        convention:
            The stochastic calculus of the noise, `'ito'`, `'stratonovich'`, or `'anti-ito'`.

        hurst:
            The Hurst index in `(0, 1)` of a fractional Brownian motion that drives the noise, a number or a function
            of the namespace that returns a parameter, or `None` for a Wiener process.

        conserved:
            Whether the noise is the divergence of a random flux on the links of the lattice of a field, so it keeps the
            total of the state.

    Raises:
        ValidationError:
            The state is not a name, a function is neither callable nor a number, the convention is unknown, the Hurst
            index is outside `(0, 1)`, or the noise options cannot combine.

    Examples:
        >>> from skcomplex.core.components.elements import CompartmentElement
        >>> from skcomplex.core.components.interactions import RateInteraction
        >>> from skcomplex.core.components.system import System
        >>> from skcomplex.core.engine.runtime import Simulation
        >>> decay = RateInteraction('decay', target='stock', state='n', rate=lambda s: -0.5 * s.target.n)
        >>> system = System(elements=[CompartmentElement('stock', n=8.0)], interactions=[decay])
        >>> trajectory = Simulation(system, dt=0.01).prepare().run(until=2.0).trajectory_
        >>> round(float(trajectory.values('stock.n')[-1]), 3)
        2.943
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw, NoiseLaw, FractionalNoiseLaw)

    def __init__(
        self,
        label: str,
        *,
        target: Annotated[str, RoleSpec(elements=(ElementKind.ANY,), states=('state', 'divisor'))],
        state: str = 'x',
        rate: Callable[[SimpleNamespace], object] | float = 0.0,
        sources: Annotated[Sequence[str], RoleSpec(variadic=True, elements=(ElementKind.ANY,))] = (),
        noise: Callable[[SimpleNamespace], object] | float | None = None,
        divisor: str | Callable[[SimpleNamespace], object] | None = None,
        process: Annotated[WienerProcessSpec | None, RoleSpec(noise=True)] = None,
        index: int | None = None,
        convention: str = 'ito',
        hurst: Callable[[SimpleNamespace], object] | float | None = None,
        conserved: bool = False,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.rate = rate
        self.sources = sources
        self.noise = noise
        self.divisor = divisor
        self.process = process
        self.index = index
        self.convention = convention
        self.hurst = hurst
        self.conserved = conserved

    def _check_functions(self) -> None:
        """Raise an error for a state that is not a name, or a function that is neither callable nor a number."""
        if not isinstance(self.state, str) or not self.state.isidentifier():
            error_msg = (
                f'{type(self).__name__} {self.label!r} changes the state {self.state!r}, which is not a name of a '
                'state.'
            )
            raise ValidationError(error_msg)
        for name in ('rate', 'noise'):
            value = getattr(self, name)
            if not (value is None or callable(value) or isinstance(value, int | float)):
                error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function of the namespace or a number.'
                raise ValidationError(error_msg)
        if not (
            self.divisor is None
            or callable(self.divisor)
            or (isinstance(self.divisor, str) and self.divisor.isidentifier())
        ):
            error_msg = (
                f'The divisor of {self.label!r} is {self.divisor!r}. Give the name of a state or parameter, or a '
                'function of the namespace of the target.'
            )
            raise ValidationError(error_msg)

    def _check_noise(self) -> None:
        """Raise an error for an unknown convention, a Hurst index outside `(0, 1)`, or noise options that conflict."""
        if self.convention not in CONVENTIONS:
            error_msg = f'Unknown noise convention {self.convention!r}. Use one of {", ".join(CONVENTIONS)}.'
            raise ValidationError(error_msg)
        if not (
            self.hurst is None or callable(self.hurst) or (isinstance(self.hurst, int | float) and 0 < self.hurst < 1)
        ):
            error_msg = f'The Hurst index of {self.label!r} is {self.hurst!r}. Give a number in (0, 1) or a function.'
            raise ValidationError(error_msg)
        if self.index is not None and self.process is None:
            error_msg = f'{self.label!r} picks the process {self.index!r} but binds no processes. Give `process`.'
            raise ValidationError(error_msg)
        options = [
            name
            for name, given in (('hurst', self.hurst), ('process', self.process), ('conserved', self.conserved))
            if given
        ]
        if len(options) > 1:
            error_msg = f'The noise of {self.label!r} takes {" and ".join(options)}. Give at most one of them.'
            raise ValidationError(error_msg)

    def _check(self) -> None:
        """Raise an error for a state, functions, or noise options the interaction cannot take.

        Raises:
            ValidationError:
                The type declares states, the state is not a name, a function is neither callable nor a number, the
                convention is unknown, the Hurst index is outside `(0, 1)`, or the noise options cannot combine.
        """
        super()._check()
        self._check_functions()
        self._check_noise()

    def _evaluate(self, function: Callable[[SimpleNamespace], object] | float, namespace: SimpleNamespace) -> object:
        """Return the value of a function of the namespace, or a number as it is."""
        return function(namespace) if callable(function) else function

    def _broadcast(self, value: object, state: object) -> object:
        """Return a value with one component per component of a vector state, repeating a number."""
        if isinstance(state, FreeModuleElement) and not isinstance(value, FreeModuleElement | list | tuple):
            return vector(SR, [value] * len(state))
        if isinstance(value, list | tuple):
            return vector(SR, value)
        return value

    def _divide(self, value: object, namespace: SimpleNamespace) -> object:
        """Return a value divided by the divisor of the target, or the value without a divisor."""
        if self.divisor is None:
            return value
        divisor = (
            self.divisor(self._get_member(namespace, 'target'))
            if callable(self.divisor)
            else getattr(self._get_member(namespace, 'target'), self.divisor)
        )
        return operator.truediv(value, divisor)

    def _get_rate(self, namespace: SimpleNamespace) -> object:
        """Return the rate before the divisor, the hook a subclass overrides to derive it from its parameters."""
        return self._evaluate(self.rate, namespace)

    def _get_noise(self, namespace: SimpleNamespace) -> object:
        """Return the noise amplitude before the divisor, the hook a subclass overrides, or `None` for no noise."""
        return None if self.noise is None else self._evaluate(self.noise, namespace)

    def _get_noise_law(self, state: object, amplitude: object, namespace: SimpleNamespace) -> BasePart:
        """Return the noise law of an amplitude, by the process, the convention, and the Hurst index."""
        if self.hurst is not None:
            hurst = self._evaluate(self.hurst, namespace)
            return FractionalNoiseLaw(state, amplitude, hurst=hurst, convention=self.convention)
        process = None
        if self.process is not None:
            handle = self._get_member(namespace, 'process').dW
            process = handle if self.index is None else handle[self.index]
        return NoiseLaw(state, amplitude, convention=self.convention, process=process, conserved=self.conserved)

    def _get_laws(self, namespace: SimpleNamespace) -> list[BasePart]:
        """Return the rate law of the state and its noise law, both divided by the divisor.

        Args:
            namespace:
                The namespace of the symbols the laws can use, with the namespaces of the target and the sources.

        Returns:
            laws:
                The rate law, and the noise law when the interaction has noise.
        """
        state = getattr(self._get_member(namespace, 'target'), self.state)
        rate = self._divide(self._broadcast(self._get_rate(namespace), state), namespace)
        laws: list[BasePart] = [RateLaw(state, rate)]
        noise = self._get_noise(namespace)
        if noise is not None:
            laws.append(self._get_noise_law(state, self._divide(noise, namespace), namespace))
        return laws

Equations

cells.x[i, 0]: diff(x_cells_0(t), t) == _neighbours_0*mu_cells + v0_cells*cos(theta_cells(t))
cells.x[i, 1]: diff(x_cells_1(t), t) == _neighbours_1*mu_cells + v0_cells*sin(theta_cells(t))
cells.theta[i]: diff(theta_cells(t), t) == arcsin(where(((_neighbours_1*mu_cells + v0_cells*sin(theta_cells(t)))*cos(theta_cells(t)) - (_neighbours_0*mu_cells + v0_cells*cos(theta_cells(t)))*sin(theta_cells(t)))/sqrt((_neighbours_0*mu_cells + v0_cells*cos(theta_cells(t)))^2 + (_neighbours_1*mu_cells + v0_cells*sin(theta_cells(t)))^2 + 1e-12) < -1, -1, where(((_neighbours_1*mu_cells + v0_cells*sin(theta_cells(t)))*cos(theta_cells(t)) - (_neighbours_0*mu_cells + v0_cells*cos(theta_cells(t)))*sin(theta_cells(t)))/sqrt((_neighbours_0*mu_cells + v0_cells*cos(theta_cells(t)))^2 + (_neighbours_1*mu_cells + v0_cells*sin(theta_cells(t)))^2 + 1e-12) > 1, 1, ((_neighbours_1*mu_cells + v0_cells*sin(theta_cells(t)))*cos(theta_cells(t)) - (_neighbours_0*mu_cells + v0_cells*cos(theta_cells(t)))*sin(theta_cells(t)))/sqrt((_neighbours_0*mu_cells + v0_cells*cos(theta_cells(t)))^2 + (_neighbours_1*mu_cells + v0_cells*sin(theta_cells(t)))^2 + 1e-12))))/tau_cells