Skip to content

Even and S-gap subshifts

The shift on the S-gap subshift.

  • Class: GapSubshiftSystem
  • Import: from skcomplex.systems.computer_science.automata import GapSubshiftSystem
  • Field: computer_science/automata
  • Topics: subshift, S-gap, even shift, renewal, 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 GapSubshiftSystem

trajectory = GapSubshiftSystem().prepare().simulate()

Parameters

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

Parameter Default
size 120
gaps 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 boolean
Structure fixed

Class

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

class GapSubshiftSystem(BaseSystem):
    """The shift on the S-gap subshift.

    The S-gap subshift holds the binary sequences whose runs of zeros between ones lie in `S`.

    With `S` the even numbers it is the even subshift, strictly sofic and not of finite type (Ceccherini-Silberstein and
    Coornaert 2023, Exercises 1.85 and 1.92). The cells are a window of a configuration drawn from the measure of
    maximal entropy, whose gaps are independent with the probability `λ^-(h + 1)` of the gap `h`, where `λ` solves
    `sum_(h in S) λ^-(h + 1) = 1` and `log λ` is the entropy. Every step shifts the window one cell to the left, and the
    cell entering on the right is a one with the probability that the gap since the last one ends there. A gap longer
    than the window counts as the window. Gaps are taken below ten times the size. The system has the cells
    `cells.alive`.

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

        gaps:
            The allowed numbers of zeros between consecutive ones, the set `S`, or `None` for the even numbers.

        random_state:
            The seed or generator of the initial window.

        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:
            No allowed gap lies below ten times the size.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import GapSubshiftSystem
        >>> cells = GapSubshiftSystem(40).prepare().system_.elements[0].alive
        >>> runs = [len(run) for run in ''.join(str(int(cell)) for cell in cells).strip('0').split('1') if run]
        >>> all(run % 2 == 0 for run in runs)
        True
    """

    field = 'computer_science/automata'
    topics = ('subshift', 'S-gap', 'even shift', 'renewal', 'sofic')
    references = ('Ceccherini-Silberstein and Coornaert 2023',)
    until = 100
    dt = 1
    observables = (Observable('density', group='cells', variable='alive'),)

    def __init__(
        self,
        size: int = 120,
        *,
        gaps: Sequence[int] | 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.gaps = gaps
        self.random_state = random_state

    @staticmethod
    def _get_gap_lengths(size: int, gaps: Sequence[int] | None) -> npt.NDArray[np.bool_]:
        """Return whether every gap length below the cap is allowed.

        By default the even lengths are allowed.
        """
        lengths = np.arange(GAP_CAP * size)
        if gaps is None:
            return lengths % 2 == 0
        allowed = np.zeros(lengths.size, dtype=bool)
        chosen = np.asarray([gap for gap in gaps if 0 <= gap < lengths.size], dtype=np.intp)
        allowed[chosen] = True
        if not allowed.any():
            error_msg = f'The S-gap subshift needs at least one allowed gap below {lengths.size}, but got {gaps!r}.'
            raise ParameterError(error_msg)
        return allowed

    @staticmethod
    def _get_gap_law(allowed: npt.NDArray[np.bool_]) -> tuple[float, Array, Array]:
        """Return the growth and the gap law of the maximal entropy measure.

        The law is given by the growth `λ`, the gap probabilities `λ^-(h + 1)`, and the hazards.
        """
        lengths = np.flatnonzero(allowed)

        def excess(growth: float) -> float:
            return float(np.sum(growth ** -(lengths + 1.0))) - 1.0

        growth = 1.0 if excess(1.0) <= 0 else float(scipy.optimize.brentq(excess, 1.0, 2.0))
        probabilities = np.where(allowed, growth ** -(np.arange(allowed.size) + 1.0), 0.0)
        probabilities /= probabilities.sum()
        survival = probabilities[::-1].cumsum()[::-1]
        hazards = np.divide(probabilities, survival, out=np.ones_like(probabilities), where=survival > 0)
        return growth, probabilities, hazards

    @staticmethod
    def _get_renewal_cells(size: int, probabilities: Array, random_state: int | np.random.Generator | None) -> Array:
        """Return a window of a configuration whose gaps between ones are independent.

        The gaps are drawn independently, after a burn-in.
        """
        generator = np.random.default_rng(random_state)
        cells: list[float] = []
        while len(cells) < BURN_IN * size:
            cells += [1.0] + [0.0] * int(generator.choice(probabilities.size, p=probabilities))
        return np.asarray(cells[-size:])

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a window drawn from the maximal entropy measure and its shift."""
        super()._prepare(context)
        _, probabilities, hazards = self._get_gap_law(self._get_gap_lengths(self.size, self.gaps))
        cells = self._get_renewal_cells(self.size, probabilities, self.random_state)
        space = LatticeSpace(self.size, boundary='fixed', fill=OUTSIDE)
        shift = GapShiftInteraction('shift', target='cells', hazards=tuple(hazards.tolist()), size=self.size)
        self.system_ = System(
            self.label,
            elements=[BinaryCellElement('cells', alive=cells, space=space)],
            interactions=[shift],
        )

Components

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

Elements:

Interactions:

  • GapShiftInteraction, from Interaction
class BinaryCellElement(Element):
    """Cell of an automaton whose value `alive` is 0 or 1.

    The local rule of an interaction changes the value. With `space`, the element holds one cell on every site.

    Args:
        label:
            The label of the cells.

        alive:
            The initial value, 0 or 1, or one value 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 BinaryCellElement
        >>> BinaryCellElement('cell', alive=1).alive
        1
    """

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

class GapShiftInteraction(Interaction):
    """Shift of a window of a binary configuration whose gaps between ones are independent.

    Every step moves the window one cell to the left. The cell entering on the right is a one with the hazard of the
    gap since the last one, the probability that a gap of that length ends there.

    Args:
        label:
            The label of the interaction.

        target:
            The cells of the window, whose state `alive` the shift moves.

        hazards:
            The probability that a gap ends at every length, from 0.

        size:
            The number of cells of the window.

    Examples:
        >>> from skcomplex.systems.computer_science.automata import GapShiftInteraction
        >>> GapShiftInteraction('shift', target='cells', hazards=(0.5, 1.0), size=10).size
        10
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role = 'cells',
        hazards: Sequence[float] = (1.0,),
        size: int = 120,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.hazards = hazards
        self.size = size

    def _get_function(self) -> Callable[..., Array]:
        """Return the shift that reads the cell to the right, or draws a new cell at the right end."""
        hazards = np.asarray(self.hazards, dtype=float)

        def shift(*values: Array, random: Array, **kwargs: object) -> Array:
            window = np.stack(values)
            right, inside = window[-1], window[1:-1]
            ones = inside[::-1] == 1
            gap = np.where(ones.any(axis=0), ones.argmax(axis=0), inside.shape[0])
            drawn = (random < hazards[np.minimum(gap, hazards.size - 1)]).astype(float)
            return np.where(right == OUTSIDE, drawn, right)

        return shift

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the shift, which reads the whole window and the cell to the right, as the law.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        window = LatticeNeighborhood(tuple((offset,) for offset in range(1 - self.size, 2)))
        alive = context.target.alive
        self.laws_: list[BaseLaw] = [
            UpdateLaw(alive, self._get_function(), neighborhood=window, label=self.label, stochastic=True),
        ]