Skip to content

Context-free subshift

A Markov chain on the context-free subshift.

  • Class: ContextFreeSubshiftSystem
  • Import: from skcomplex.systems.computer_science.automata import ContextFreeSubshiftSystem
  • Field: computer_science/automata
  • Topics: subshift, context-free, Monte Carlo, not sofic
  • References:
    • Ceccherini-Silberstein and Coornaert 2023

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.computer_science.automata import ContextFreeSubshiftSystem

trajectory = ContextFreeSubshiftSystem().prepare().simulate()

Parameters

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

Parameter Default
size 60
initial None
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 discrete
Space lattice
Laws update
Randomness unknown
Domains integer
Structure fixed

Class

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

class ContextFreeSubshiftSystem(BaseSystem):
    """A Markov chain on the context-free subshift.

    The subshift holds the ternary rings where every block `0 1^h 2^k 0` has `h = k`.

    The subshift is not sofic, since a finite graph cannot match the counts of ones and twos (Ceccherini-Silberstein and
    Coornaert 2023, Exercise 6.80). Every step proposes to change every cell of the ring, in a random order, to one of
    the two other symbols, and rejects the changes that would leave the subshift, so the chain samples its admissible
    rings uniformly. It starts from blocks `0 1^h 2^h`, with `h` drawn from a geometric law. The system has the symbols
    `cells.symbol`.

    Args:
        size:
            The number of cells of the ring.

        initial:
            The initial symbols, an admissible ring, or `None` for random balanced blocks.

        random_state:
            The seed or generator of the initial blocks.

        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.

    Raises:
        ParameterError:
            The initial ring is not admissible.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import ContextFreeSubshiftSystem
        >>> ContextFreeSubshiftSystem(12).prepare().system_.elements[0].symbol.tolist()
        [0.0, 1.0, 1.0, 2.0, 2.0, 0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0]
    """

    field = 'computer_science/automata'
    topics = ('subshift', 'context-free', 'Monte Carlo', 'not sofic')
    references = ('Ceccherini-Silberstein and Coornaert 2023',)
    until = 50
    dt = 1

    def __init__(
        self,
        size: int = 60,
        *,
        initial: npt.ArrayLike | None = None,
        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.size = size
        self.initial = initial
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a ring of balanced blocks and its random moves."""
        super()._prepare(context)
        if self.initial is None:
            generator = np.random.default_rng(self.random_state)
            blocks: list[float] = []
            while len(blocks) < self.size:
                height = int(generator.geometric(BALANCED_BLOCK))
                blocks += [0.0] + [1.0] * height + [2.0] * height
            symbols = np.zeros(self.size)
            cut = max(index for index in range(self.size + 1) if index == len(blocks) or blocks[index] == 0)
            symbols[:cut] = blocks[:cut]
        else:
            symbols = np.asarray(self.initial, dtype=float)
        if not ContextFreeMoveInteraction._is_context_free(symbols):
            error_msg = f'The initial ring {symbols.tolist()} holds a block 0 1^h 2^k 0 with h != k.'
            raise ParameterError(error_msg)
        self.system_ = System(
            self.label,
            elements=[TernaryCellElement('cells', symbol=symbols, space=LatticeSpace(self.size))],
            interactions=[ContextFreeMoveInteraction('moves', target='cells', size=self.size)],
        )

Components

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

Elements:

Interactions:

  • ContextFreeMoveInteraction, from Interaction
class TernaryCellElement(Element):
    """Cell of a subshift over the alphabet `{0, 1, 2}`.

    An example is the context-free subshift. With `space`, the element holds one cell on every site.

    Args:
        label:
            The label of the cells.

        symbol:
            The initial symbol, 0, 1, or 2, or one symbol per cell.

        space:
            The space with one cell on every site, such as a lattice, or `None` for one cell.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import TernaryCellElement
        >>> TernaryCellElement('cell', symbol=2).symbol
        2
    """

    def __init__(
        self,
        label: str,
        *,
        symbol: Annotated[float | Array, {0, 1, 2}] = 0,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.symbol = symbol

class ContextFreeMoveInteraction(Interaction):
    """Random moves of a ring of symbols that stay in the context-free subshift.

    Every step proposes to change every cell, in a random order, to one of the two other symbols, and rejects the
    changes that would leave a block `0 1^h 2^k 0` with `h != k`. The moves sample the admissible rings uniformly.

    Args:
        label:
            The label of the interaction.

        target:
            The cells of the ring, whose state `symbol` the moves change.

        size:
            The number of cells of the ring.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import ContextFreeMoveInteraction
        >>> ContextFreeMoveInteraction('moves', target='cells', size=12).size
        12
    """

    def __init__(self, label: str, *, target: Role = 'cells', size: int = 60) -> None:
        super().__init__(label)
        self.target = target
        self.size = size

    @staticmethod
    def _is_balanced(word: Array) -> bool:
        """Return whether a word over `{1, 2}` between two zeros is no block `1^h 2^k` with `h != k`."""
        if np.any(np.diff(word) < 0):
            return True
        ones = int(np.sum(word == 1))
        return ones == word.size - ones

    @staticmethod
    def _is_context_free(ring: Array) -> bool:
        """Return whether a ring of symbols holds no block `0 1^h 2^k 0` with `h != k` between consecutive zeros."""
        zeros = np.flatnonzero(ring == 0)
        if zeros.size == 0:
            return True
        rolled = np.roll(ring, -int(zeros[0]))
        bounds = [*(zeros - zeros[0]).tolist(), ring.size]
        return all(
            ContextFreeMoveInteraction._is_balanced(rolled[start + 1 : end])
            for start, end in itertools.pairwise(bounds)
        )

    @staticmethod
    def _get_move(*values: Array, random: Array, **kwargs: object) -> Array:
        """Return the cell changed to another random symbol, unless the ring would leave the subshift."""
        window = np.stack(values)
        size = (window.shape[0] + 1) // 2
        center = window[size - 1]
        proposals = (center + 1 + np.floor(2 * random)) % SYMBOLS
        following = center.copy()
        for row in range(window.shape[1]):
            ring = window[size - 1 :, row].copy()
            ring[0] = proposals[row]
            if ContextFreeMoveInteraction._is_context_free(ring):
                following[row] = proposals[row]
        return following

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the moves, which read every cell of the ring from both sides, as the law.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        ring = LatticeNeighborhood(tuple((offset,) for offset in range(1 - self.size, self.size)))
        symbol = context.target.symbol
        self.laws_: list[BaseLaw] = [
            UpdateLaw(
                symbol,
                self._get_move,
                neighborhood=ring,
                schedule='random-sequential',
                label=self.label,
                stochastic=True,
            ),
        ]