Skip to content

Koch

The Koch curve as the L-system F → F+F--F+F drawn by a turtle.

  • Class: KochCurveSystem
  • Import: from skcomplex.systems.mathematics.fractals import KochCurveSystem
  • Field: mathematics/fractals
  • Topics: fractal, L-system, rewriting system, turtle
  • References:
    • Prusinkiewicz and Lindenmayer 1990
    • 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 KochCurveSystem

trajectory = KochCurveSystem().prepare().simulate()

Parameters

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

Parameter Default
angle 60.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 none
Laws update
Randomness deterministic
Domains integer
Structure fixed

Class

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

class KochCurveSystem(BaseSystem):
    """The Koch curve as the L-system `F → F+F--F+F` drawn by a turtle.

    Every generation replaces each segment by four segments of a third of its length, with a bump of the turning angle
    in the middle. With the angle of 60 degrees the curve keeps its endpoints at `(0, 0)` and `(1, 0)`, its length is
    `(4/3)^n` at generation `n`, and its similarity dimension is `log 4 / log 3`, about 1.262. The system has the word
    `koch`, its symbol counts `koch.F`, and its size `koch.size`.

    Args:
        angle:
            The turning angle of the turtle in degrees.

        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.

    Examples:
        >>> from skcomplex.systems.mathematics.fractals import KochCurveSystem
        >>> KochCurveSystem().prepare().simulate(until=3).get_values('koch.F').tolist()
        [1.0, 4.0, 16.0, 64.0]
    """

    field = 'mathematics/fractals'
    topics = ('fractal', 'L-system', 'rewriting system', 'turtle')
    references = ('Prusinkiewicz and Lindenmayer 1990', 'Thurner, Hanel, and Klimek 2018', 'Trzaska 2023')
    until = 5
    dt = 1

    def __init__(
        self,
        angle: float = 60.0,
        *,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.angle = angle

    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)
        bend = RewritingInteraction('bend', target='koch', laws=[ProductionLaw('F', 'F+F--F+F')])
        word = WordElement(
            'koch',
            axiom='F',
            alphabet='F+-',
            geometry=GeometrySpec(angle=self.angle, step=1.0, contraction=1 / 3),
            bounds=(-0.03, -0.05, 1.03, 0.35),
        )
        self.system_ = System(self.label, elements=[word], interactions=[bend])

Components

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

Elements:

Interactions:

class WordElement(Element):
    """An element that holds a word of symbols that productions rewrite in parallel.

    A word is a string of modules, symbols that may carry parameters. At each step every symbol is replaced at once by
    the word its `ProductionLaw` gives, as in an L-system, the grammar that Lindenmayer introduced to describe the
    growth of plants. An interaction that binds the word sets these laws, such as a `RewritingInteraction`. The states
    of the word are the count of each symbol whose name is made of letters, digits, and underscores, and the length
    `size` of the word.

    Unlike `PatchElement`, which rewrites shapes, it rewrites a string, which `geometry` can draw as line segments.
    Choose it when a model grows by rewriting symbols, such as a branching plant or a fractal curve.

    It appears in many fields. Lindenmayer modelled the growth of algae with it in biology, the Thue-Morse sequence of
    symbolic dynamics in computer science is a word, and the Koch curve of mathematics is a word drawn as line segments.

    Args:
        label:
            The name of the word, such as `'algae'`.

        axiom:
            The word at the start, such as `'A'`.

        alphabet:
            The symbols, as a string of one-character symbols or a mapping from each name to its number of parameters,
            or `None` to read them from the axiom and the productions.

        ignore:
            The symbols that a production skips when it reads the neighbours of a symbol, such as `'+-'` for turns.

        geometry:
            How the word is drawn as line segments, a `GeometrySpec`, or `None` for no drawing.

        max_size:
            The largest word one step may produce, which guards memory.

        bounds:
            The box `(xmin, ymin, xmax, ymax)` that the drawing shows, or `None` to fit the data.

    Examples:
        In Lindenmayer's algae `A` becomes `AB` and `B` becomes `A`, so the length of the word runs through the
        Fibonacci numbers.

        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.rewriting import ProductionLaw, RewritingInteraction, WordElement
        >>> laws = [ProductionLaw('A', 'AB'), ProductionLaw('B', 'A')]
        >>> growth = RewritingInteraction('growth', target='algae', laws=laws)
        >>> system = System(elements=[WordElement('algae', axiom='A')], interactions=[growth])
        >>> system.prepare().simulate(until=5).get_values('algae.size').tolist()
        [1.0, 2.0, 3.0, 5.0, 8.0, 13.0]
    """

    visual = VisualSpec(GeometryVisual)

    def __init__(
        self,
        label: str,
        axiom: Letters = '',
        *,
        alphabet: str | Mapping[str, int] | None = None,
        ignore: str | Sequence[str] = '',
        geometry: GeometrySpec | None = None,
        max_size: int = 10_000_000,
        bounds: Sequence[float] | None = None,
    ) -> None:
        super().__init__(label)
        self.axiom = axiom
        self.alphabet = alphabet
        self.ignore = ignore
        self.geometry = geometry
        self.max_size = max_size
        self.bounds = bounds

    def _prepare(self, context: BaseSpace | None = None) -> None:
        """Check the geometry and the maximum size of the word.

        It first raises an error for an invalid geometry or a maximum size that is not positive. The maximum size must
        be a positive integer.

        Args:
            context:
                The space the element inherits from its system, which the element does not read.
        """
        super()._prepare(context)
        if self.geometry is not None:
            self.geometry._check()
        if isinstance(self.max_size, bool) or not isinstance(self.max_size, int) or self.max_size < 1:
            error_msg = f'The maximum size of {self.label} must be a positive integer, but it is {self.max_size!r}.'
            raise RewritingError(error_msg)

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

class RewritingInteraction(Interaction):
    """An interaction that rewrites a word or a patch by the rules it is given.

    At every step each symbol of a word is replaced by the successor of its `ProductionLaw`, and each tile of a patch by
    the pieces of its `SubstitutionLaw`, all at once.

    Unlike a subclass of `Interaction` that sets its rules in `_prepare`, it takes fixed rules. Choose it when the rules
    read no parameters of their own, as the algae of Lindenmayer, and write a subclass for rules that do, such as the
    ratio of a Cantor set.

    It appears in many fields. The productions of an L-system grow a plant in biology, a substitution builds a fractal
    in mathematics, and the Thue-Morse word of computer science doubles at every step.

    Args:
        label:
            The name of the interaction, such as `'growth'`.

        target:
            The path of the word or patch it rewrites.

        laws:
            The productions of a word or the substitutions of a patch.

    Raises:
        RewritingError:
            A law is neither a production nor a substitution.

    Examples:
        In Lindenmayer's algae `A` becomes `AB` and `B` becomes `A`, so the length of the word runs through the
        Fibonacci numbers.

        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.rewriting import ProductionLaw, RewritingInteraction, WordElement
        >>> laws = [ProductionLaw('A', 'AB'), ProductionLaw('B', 'A')]
        >>> growth = RewritingInteraction('growth', target='algae', laws=laws)
        >>> system = System(elements=[WordElement('algae', axiom='A')], interactions=[growth])
        >>> system.prepare().simulate(until=5).get_values('algae.size').tolist()
        [1.0, 2.0, 3.0, 5.0, 8.0, 13.0]
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (ProductionLaw, SubstitutionLaw)

    def __init__(self, label: str, *, target: Role, laws: Sequence[ProductionLaw | SubstitutionLaw] = ()) -> None:
        super().__init__(label)
        self.target = target
        self.laws = laws

    def _check_arguments(self) -> None:
        """Raise an error for a law that rewrites nothing.

        Raises:
            RewritingError:
                A law is neither a production nor a substitution.
        """
        super()._check_arguments()
        laws = self.laws if isinstance(self.laws, list | tuple) else []
        wrong = [law for law in laws if not isinstance(law, ProductionLaw | SubstitutionLaw)]
        if wrong:
            error_msg = f'{self.label!r} rewrites by {wrong[0]!r}. Give ProductionLaw or SubstitutionLaw laws.'
            raise RewritingError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of a binding.

        Args:
            context:
                The namespace of the word or patch it binds.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = list(self.laws) if isinstance(self.laws, list | tuple) else []