Skip to content

Sierpiński substitutions

The Sierpiński triangle or carpet.

  • Class: SierpinskiSubstitutionSystem
  • Import: from skcomplex.systems.mathematics.fractals import SierpinskiSubstitutionSystem
  • Field: mathematics/fractals
  • Topics: fractal, substitution, rewriting system
  • References:
    • Sierpiński 1915
    • Sierpiński 1916
    • Thurner, Hanel, and Klimek 2018
    • Trzaska 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.mathematics.fractals import SierpinskiSubstitutionSystem

trajectory = SierpinskiSubstitutionSystem().prepare().simulate()

Parameters

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

Parameter Default
shape 'triangle'
filled True
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 none
Laws update
Randomness deterministic
Domains boolean, integer, real
Structure fixed

Class

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

class SierpinskiSubstitutionSystem(BaseSystem):
    """The Sierpiński triangle or carpet.

    The shape is the substitution of a polygon by scaled copies of itself.

    The triangle is replaced by its three corner copies of half its side, so generation `n` has `3^n` triangles of
    total area `(3/4)^n` times the first, and the gasket has the similarity dimension `log 3 / log 2`, about 1.585. The
    square is replaced by the eight copies of a third of its side around its middle, so generation `n` has `8^n`
    squares of area `(8/9)^n`, and the carpet has the dimension `log 8 / log 3`, about 1.893. The system has the patch
    `sierpinski` and its number of polygons `sierpinski.size`.

    Args:
        shape:
            `'triangle'` or `'carpet'`.

        filled:
            Whether the geometry visual draws the polygons as a filled image instead of outlines.

        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:
        ValidationError:
            The shape is unknown.

    Examples:
        >>> from skcomplex.systems.mathematics.fractals import SierpinskiSubstitutionSystem
        >>> SierpinskiSubstitutionSystem().prepare().simulate(until=2).get_values('sierpinski.size').tolist()
        [1.0, 3.0, 9.0]
    """

    field = 'mathematics/fractals'
    topics = ('fractal', 'substitution', 'rewriting system')
    references = ('Sierpiński 1915', 'Sierpiński 1916', 'Thurner, Hanel, and Klimek 2018', 'Trzaska 2023')
    until = 6
    dt = 1

    def __init__(
        self,
        shape: str = 'triangle',
        *,
        filled: bool = True,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.shape = shape
        self.filled = filled

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to the components of the system built from its model parameters."""
        super()._prepare(context)
        prototile, _ = SierpinskiInteraction._get_sierpinski_tiles(self.shape)
        sierpinski = PatchElement('sierpinski', prototiles=[prototile], filled=self.filled)
        copies = SierpinskiInteraction('copies', target='sierpinski', shape=self.shape)
        self.system_ = System(self.label, elements=[sierpinski], interactions=[copies])

Components

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

Elements:

Interactions:

  • SierpinskiInteraction, from Interaction
class PatchElement(Element):
    """An element that holds tiles that substitutions replace in parallel.

    A tile is a copy of a prototile, a basic shape, under an affine placement, a map that scales, rotates, and moves it.
    At each step every tile is replaced at once by the tiles that its `SubstitutionLaw` gives. An interaction that binds
    the patch sets these laws, such as a `RewritingInteraction`. The states of the patch are the count of each
    prototile and the number `size` of tiles.

    Unlike `WordElement`, which rewrites a string of symbols, it rewrites shapes in the plane. Choose it when a model
    grows a geometric pattern by substitution, such as a fractal or a tiling that never repeats.

    It appears in mathematics and physics. The Cantor set and the Sierpinski triangle are built by substitution, and
    Penrose tilings, which never repeat, model the atomic order of quasicrystals.

    Args:
        label:
            The name of the patch, such as `'cantor'`.

        tiles:
            Each tile at the start, as a pair of a prototile name and its placement, or `None` for the first prototile
            in place.

        prototiles:
            The basic shapes, each a `PrototileSpec` with a name and the corners of its polygon, such as
            `PrototileSpec('interval', [(0, 0), (1, 0)])`.

        filled:
            Whether the drawing fills the polygons as an image instead of drawing their outlines.

        max_size:
            The largest number of tiles one step may produce, which guards memory.

        bounds:
            The box `(xmin, ymin, xmax, ymax)` that the drawing shows, or `None` for the box of the initial tiles.

    Examples:
        Each step keeps the outer thirds of every interval, which builds the Cantor set.

        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.rewriting import (
        ...     AffineSpec, PatchElement, PrototileSpec, RewritingInteraction, SubstitutionLaw
        ... )
        >>> thirds = [AffineSpec(scale=1 / 3), AffineSpec(scale=1 / 3, translation=(2 / 3, 0))]
        >>> substitution = SubstitutionLaw('interval', [('interval', third) for third in thirds])
        >>> cantor = PatchElement('cantor', prototiles=[PrototileSpec('interval', [(0, 0), (1, 0)])])
        >>> removal = RewritingInteraction('removal', target='cantor', laws=[substitution])
        >>> trajectory = System(elements=[cantor], interactions=[removal]).prepare().simulate(until=3)
        >>> trajectory.get_values('cantor.size').tolist()
        [1.0, 2.0, 4.0, 8.0]
    """

    visual = VisualSpec(GeometryVisual)

    def __init__(
        self,
        label: str,
        tiles: Sequence[tuple[str, AffineSpec]] | None = None,
        *,
        prototiles: Sequence[PrototileSpec] = (),
        filled: bool = False,
        max_size: int = 10_000_000,
        bounds: Sequence[float] | None = None,
    ) -> None:
        super().__init__(label)
        self.tiles = tiles
        self.prototiles = prototiles
        self.filled = filled
        self.max_size = max_size
        self.bounds = bounds

    def _prepare(self, context: BaseSpace | None = None) -> None:
        """Check the prototiles of the patch.

        It first raises an error for no prototiles, an invalid prototile, or an unknown one. An unknown prototile is one
        a tile names.

        Args:
            context:
                The space the element inherits from its system, which the element does not read.
        """
        super()._prepare(context)
        if not self.prototiles:
            error_msg = f'The patch {self.label} needs at least one prototile.'
            raise RewritingError(error_msg)
        names = {prototile.name for prototile in self.prototiles}
        for name, placement in self.tiles or ():
            if name not in names:
                error_msg = f'The patch {self.label} has a tile of the unknown prototile {name!r}.'
                raise RewritingError(error_msg)
            placement._check()

    def _get_compiler(self) -> BaseCompiler:
        """Return the rewriting compiler, which compiles words and patches."""
        return _rewriting_compiler.RewritingCompiler()

class SierpinskiInteraction(Interaction):
    """Replacement of every triangle or square of a patch by the scaled copies of the Sierpiński triangle or carpet.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the patch.

        shape:
            `'triangle'` or `'carpet'`.

    Raises:
        ValidationError:
            The shape is unknown.

    Examples:
        >>> from skcomplex.systems.mathematics.fractals import SierpinskiInteraction
        >>> SierpinskiInteraction('copies', target='sierpinski', shape='carpet').shape
        'carpet'
    """

    law_classes = (SubstitutionLaw,)

    def __init__(self, label: str, *, target: Role, shape: str = 'triangle') -> None:
        super().__init__(label)
        self.target = target
        self.shape = shape

    def _check_arguments(self) -> None:
        """Raise an error for an unknown shape.

        Raises:
            ValidationError:
                The shape is unknown.
        """
        super()._check_arguments()
        self._get_sierpinski_tiles(self.shape)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the substitution of every polygon by its scaled copies.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        prototile, pieces = self._get_sierpinski_tiles(self.shape)
        self.laws_: list[BaseLaw] = [SubstitutionLaw(prototile.name, pieces)]

    @staticmethod
    def _get_sierpinski_tiles(shape: str) -> tuple[PrototileSpec, list[tuple[str, AffineSpec]]]:
        """Return the prototile of a Sierpiński shape and its scaled replacing copies."""
        if shape == 'triangle':
            height = np.sqrt(3) / 2
            corners = [(0.0, 0.0), (0.5, 0.0), (0.25, height / 2)]
            pieces = [('triangle', AffineSpec(scale=0.5, translation=corner)) for corner in corners]
            return PrototileSpec('triangle', [(0.0, 0.0), (1.0, 0.0), (0.5, height)]), pieces
        if shape == 'carpet':
            cells = [(column, row) for row in range(3) for column in range(3) if (column, row) != (1, 1)]
            pieces = [('square', AffineSpec(scale=1 / 3, translation=(column / 3, row / 3))) for column, row in cells]
            return PrototileSpec('square', [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]), pieces
        error_msg = f'Unknown shape {shape!r}. Use one of {", ".join(SHAPES)}.'
        raise ValidationError(error_msg)