Cantor
The Cantor set as the substitution of every interval by its two outer parts.
- Class:
CantorSetSystem - Import:
from skcomplex.systems.mathematics.fractals import CantorSetSystem - Field:
mathematics/fractals - Topics:
fractal,substitution,rewriting system - References:
- Cantor 1883
- 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 CantorSetSystem
trajectory = CantorSetSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
ratio |
0.3333333333333333 |
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 CantorSetSystem(BaseSystem):
"""The Cantor set as the substitution of every interval by its two outer parts.
Every generation keeps the first and the last part of each interval, each `ratio` of its length, and removes the
middle. With the ratio of one third, generation `n` has `2^n` intervals of total length `(2/3)^n`, and the limit set
has the similarity dimension `log 2 / log 3`, about 0.631. The system has the patch `cantor` and its number of
intervals `cantor.size`.
Args:
ratio:
The length of each kept part relative to its interval, below one half.
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 ratio is not between 0 and 1/2.
Examples:
>>> from skcomplex.systems.mathematics.fractals import CantorSetSystem
>>> CantorSetSystem().prepare().simulate(until=3).get_values('cantor.size').tolist()
[1.0, 2.0, 4.0, 8.0]
"""
field = 'mathematics/fractals'
topics = ('fractal', 'substitution', 'rewriting system')
references = ('Cantor 1883', 'Thurner, Hanel, and Klimek 2018', 'Trzaska 2023')
until = 8
dt = 1
def __init__(
self,
ratio: float = 1 / 3,
*,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.ratio = ratio
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components of the system built from its model parameters.
Args:
context:
The observables to compile with the problem, or `None` for none.
Raises:
ValidationError:
The ratio is not between 0 and 1/2.
"""
super()._prepare(context)
if not 0 < self.ratio < LARGEST_RATIO:
error_msg = f'ratio = {self.ratio!r} must lie between 0 and 1/2.'
raise ValidationError(error_msg)
interval = PrototileSpec('interval', [(0.0, 0.0), (1.0, 0.0)])
cantor = PatchElement('cantor', prototiles=[interval], bounds=(-0.03, -0.1, 1.03, 0.1))
removal = CantorInteraction('removal', target='cantor', ratio=self.ratio)
self.system_ = System(self.label, elements=[cantor], interactions=[removal])
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
PatchElement, fromElement, through the shared recipePatchElement
Interactions:
CantorInteraction, fromInteraction
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 CantorInteraction(Interaction):
"""Removal of the middle of every interval of a patch.
Each interval is replaced by its first and its last part of the length `ratio`.
Args:
label:
The label of the interaction.
target:
The path of the patch of intervals.
ratio:
The length of each kept part relative to its interval.
Examples:
>>> from skcomplex.systems.mathematics.fractals import CantorInteraction
>>> CantorInteraction('removal', target='cantor', ratio=0.25).ratio
0.25
"""
law_classes = (SubstitutionLaw,)
def __init__(
self,
label: str,
*,
target: Role,
ratio: Annotated[float, RealSet.open(0, oo)] = 1 / 3,
) -> None:
super().__init__(label)
self.target = target
self.ratio = ratio
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the substitution of every interval by its two outer parts.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
pieces = [
('interval', AffineSpec(scale=context.ratio)),
('interval', AffineSpec(scale=context.ratio, translation=(1 - context.ratio, 0))),
]
self.laws_: list[BaseLaw] = [SubstitutionLaw('interval', pieces)]