Skip to content

Cyclic cellular automaton

Griffeath's cyclic cellular automaton, whose random levels organize into spiral waves.

  • Name: cyclic_cellular_automaton
  • Field: chemistry/kinetics
  • Formalism: lattice dynamics
  • References: Griffeath 1988; Fisch, Gravner, and Griffeath 1991; Dilão 2023

The cyclic_cellular_automaton example

Example

Factory

@register_model(
    field='chemistry/kinetics',
    tags=('lattice', 'excitable media', 'spirals', 'cellular automaton'),
    references=('Griffeath 1988', 'Fisch, Gravner, and Griffeath 1991', 'Dilão 2023'),
    defaults={'until': 200, 'dt': 1},
)
def cyclic_cellular_automaton(
    shape: Sequence[int] = (64, 64),
    *,
    n: int = 14,
    threshold: int = 1,
    random_state: int | np.random.Generator | None = 0,
) -> System:
    """Return Griffeath's cyclic cellular automaton, whose random levels organize into spiral waves.

    Args:
        shape:
            The number of rows and columns.

        n:
            The number of levels.

        threshold:
            The number of von Neumann neighbours at the following level that advance a cell.

        random_state:
            The seed or generator of the initial levels.

    Returns:
        system:
            The model, with the levels `cells.level`.

    Examples:
        >>> from skcomplex.models.chemistry.kinetics import cyclic_cellular_automaton
        >>> cyclic_cellular_automaton((10, 10), n=8).elements[0].values['n']
        8
    """
    levels = np.random.default_rng(random_state).integers(0, n, size=tuple(shape)).astype(float)
    space = LatticeSpace(tuple(shape))
    return System(
        elements=[
            LatticeElement(
                'cells',
                element=CyclicCellElement,
                space=space,
                values={'level': levels, 'n': n, 'threshold': threshold},
            ),
        ],
        interactions=[
            LocalRuleInteraction(
                'advance',
                target='cells',
                state='level',
                rule=_advance_cyclically,
                neighborhood=VonNeumannNeighborhood(center=True),
            ),
        ],
    )

Components

class CyclicCellElement(Element):
    """Cell of Griffeath's cyclic cellular automaton, with `n` levels that follow each other in a cycle.

    A cell moves from level `k` to level `k + 1` modulo `n` when at least `threshold` of its neighbours hold that
    level, by the local rule of `cyclic_cellular_automaton`, so every level eats its predecessor and random initial
    levels organize into spiral waves.

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

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

        level:
            The initial level, from 0 to `n - 1`.

        n:
            The number of levels.

        threshold:
            The number of neighbours at the following level that advance a cell.

    Examples:
        >>> from skcomplex.models.chemistry.kinetics import CyclicCellElement
        >>> CyclicCellElement('cell').n
        14.0
    """

    def __init__(
        self,
        label: str,
        visual: VisualSpec | None = None,
        *,
        level: Annotated[float, StateSpec(domain=NN)] = 0,
        n: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 14.0,
        threshold: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.0,
    ) -> None:
        super().__init__(label, visual=visual)
        self.level = level
        self.n = n
        self.threshold = threshold

class LocalRuleInteraction(Interaction):
    """Local rule of a cellular automaton, which sets the next value of every cell from its ordered neighbourhood.

    The rule is a table of the next value of every configuration of the neighbourhood, `TableSpec`, a rule of the sum
    of the neighbourhood, `TotalisticSpec`, a rule of the cell and the sum of its neighbours, `OuterTotalisticSpec`, an
    object whose `table()` returns a `TableSpec`, or a function. A function receives one array per neighbour of every
    read state, in neighbourhood order, with one value per cell, the uniform array `random` when the rule is stochastic,
    and the parameters of the bound group it names, and returns the next values of the states, one array per state.

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

        target:
            The path of the group on the cells of a lattice, the nodes of a network, or a Cayley graph.

        state:
            The name of the state the rule sets, or a tuple of the names of the states it sets together.

        rule:
            The table, the totalistic rule, or the function.

        neighborhood:
            The ordered neighbourhood of every cell, such as `VonNeumannNeighborhood(center=True)`.

        reads:
            The names of the states whose neighbourhoods a function reads, or `None` for the states it sets.

        schedule:
            `'synchronous'`, `'random-sequential'`, `'random-site'`, `'checkerboard'`, or `'colored'`.

        stochastic:
            Whether a function receives the uniform random array `random`.

    Raises:
        ValidationError:
            The state or the read states are not names, or the neighbourhood is not a neighbourhood.

    Examples:
        >>> from skcomplex.core.interactions import LocalRuleInteraction
        >>> from skcomplex.core.spaces import VonNeumannNeighborhood
        >>> from skcomplex.specs import TotalisticSpec
        >>> parity = TotalisticSpec({1: 1, 3: 1})
        >>> around = VonNeumannNeighborhood(n_dim=1, center=True)
        >>> rule = LocalRuleInteraction('parity', target='cells', state='cell', rule=parity, neighborhood=around)
        >>> rule.check().schedule
        'synchronous'
    """

    def __init__(
        self,
        label: str,
        *,
        target: Annotated[str, RoleSpec()],
        state: str | tuple[str, ...],
        rule: object,
        neighborhood: BaseNeighborhood,
        reads: Sequence[str] | None = None,
        schedule: str = 'synchronous',
        stochastic: bool = False,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.rule = rule
        self.neighborhood = neighborhood
        self.reads = reads
        self.schedule = schedule
        self.stochastic = stochastic

    def _get_names(self) -> tuple[str, ...]:
        """Return the names of the states the rule sets."""
        return (self.state,) if isinstance(self.state, str) else tuple(self.state)

    def _check(self) -> None:
        """Raise an error for states that are not names, or a neighbourhood that is not one.

        Raises:
            ValidationError:
                The state or the read states are not names, or the neighbourhood is not a neighbourhood.
        """
        super()._check()
        names = [*self._get_names(), *(self.reads or ())]
        if not names or not all(isinstance(name, str) and name.isidentifier() for name in names):
            error_msg = f'The local rule {self.label!r} sets {self.state!r} and reads {self.reads!r}. Give state names.'
            raise ValidationError(error_msg)
        if not isinstance(self.neighborhood, BaseNeighborhood):
            error_msg = f'The neighbourhood of the local rule {self.label!r} is {self.neighborhood!r}. Give one.'
            raise ValidationError(error_msg)

    def _get_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the local rule law of the states of the target.

        Args:
            namespace:
                The namespace of the symbols the laws can use, with `namespace.target`.

        Returns:
            laws:
                The local rule law.
        """
        targets = tuple(getattr(self._get_member(namespace, 'target'), name) for name in self._get_names())
        reads = (
            None
            if self.reads is None
            else tuple(getattr(self._get_member(namespace, 'target'), name) for name in self.reads)
        )
        return [
            LocalRuleLaw(
                targets[0] if isinstance(self.state, str) else targets,
                self.neighborhood,
                self.rule,
                reads=reads,
                schedule=self.schedule,
                stochastic=self.stochastic,
                label=self.label,
            ),
        ]