Skip to content

Iterated function systems by the chaos game

Points that draw the attractor of an iterated function system by the chaos game.

  • Class: ChaosGameSystem
  • Import: from skcomplex.systems.mathematics.fractals import ChaosGameSystem
  • Field: mathematics/fractals
  • Topics: fractal, iterated function system, chaos game, discrete map
  • References:
    • Barnsley 1988
    • Dilão 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 ChaosGameSystem

trajectory = ChaosGameSystem().prepare().simulate()

Parameters

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

Parameter Default
preset 'sierpinski'
maps None
weights None
n_points 20000
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 continuous
Laws update
Randomness stochastic
Domains vector
Structure fixed

Class

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

class ChaosGameSystem(BaseSystem):
    """Points that draw the attractor of an iterated function system by the chaos game.

    At every step each point moves by one of the affine maps of the system, drawn with probabilities proportional to the
    weights. The maps contract, so after a few steps the cloud of points covers the attractor, the unique compact set
    that the union of the maps leaves unchanged. The Sierpiński triangle of three maps of ratio 1/2 has the box-counting
    dimension `log 3 / log 2`, and the Barnsley fern is the attractor of four maps. The system has the positions
    `points.p`.

    Args:
        preset:
            `'sierpinski'` or `'barnsley'`, used when `maps` is `None`.

        maps:
            The coefficients `(a, b, c, d, e, f)` of every map `(x, y) -> (a x + b y + e, c x + d y + f)`, or `None` for
            the preset.

        weights:
            The weight of every map, or `None` for the weights of the preset, or equal weights for given maps.

        n_points:
            The number of points, started uniformly in the unit square.

        random_state:
            The seed or generator of the initial points.

        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 preset is unknown.

    Examples:
        >>> from skcomplex.systems.mathematics.fractals import ChaosGameSystem
        >>> len(ChaosGameSystem('barnsley', n_points=10).prepare().system_.interactions[0].maps)
        4
    """

    field = 'mathematics/fractals'
    topics = ('fractal', 'iterated function system', 'chaos game', 'discrete map')
    references = ('Barnsley 1988', 'Dilão 2023')
    until = 30
    dt = 1

    def __init__(
        self,
        preset: str = 'sierpinski',
        *,
        maps: Sequence[AffineMap] | None = None,
        weights: Sequence[float] | None = None,
        n_points: int = 20000,
        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.preset = preset
        self.maps = maps
        self.weights = weights
        self.n_points = n_points
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the points and the maps that move them.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.

        Raises:
            ValidationError:
                The preset is unknown.
        """
        super()._prepare(context)
        if self.maps is None and self.preset not in PRESETS:
            error_msg = f'Unknown chaos game preset {self.preset!r}. Use one of {", ".join(PRESETS)}, or give the maps.'
            raise ValidationError(error_msg)
        chosen_maps, preset_weights = (
            PRESETS[self.preset] if self.maps is None else (self.maps, (1.0,) * len(self.maps))
        )
        weights = self.weights if self.weights is not None else preset_weights
        starts = np.random.default_rng(self.random_state).random((self.n_points, 2))
        game = RandomAffineMapInteraction(
            'game',
            target='points',
            maps=tuple(map(tuple, chosen_maps)),
            weights=tuple(weights),
        )
        self.system_ = System(
            self.label,
            elements=[ChaosPointElement('points', p=starts, size=self.n_points)],
            interactions=[game],
            space=ContinuousSpace(n_dim=2),
        )

Components

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

Elements:

Interactions:

  • RandomAffineMapInteraction, from Interaction
class ChaosPointElement(Element):
    """Points of the plane, each with its position `p`.

    Args:
        label:
            The label of the points.

        p:
            The initial position, one row per point or shared.

        size:
            The number of points, or `None` for one.

    Examples:
        >>> from skcomplex.systems.mathematics.fractals import ChaosPointElement
        >>> ChaosPointElement('point', p=(0.5, 0.5)).p
        (0.5, 0.5)
    """

    visual = VisualSpec('points', {'position': 'p', 'radius': 0.004, 'states': ()})

    def __init__(self, label: str, *, p: object = (0.0, 0.0), size: int | None = None) -> None:
        super().__init__(label, size=size)
        self.p = p

class RandomAffineMapInteraction(Interaction):
    """Map of a point of the plane by one affine map of an iterated function system.

    The map is drawn anew at every step.

    Map `k` takes `(x, y)` to `(a x + b y + e, c x + d y + f)` for its coefficients `(a, b, c, d, e, f)`, and is drawn
    with a probability proportional to its weight, independently for every member of a bound group.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        target:
            The path of the element or group whose position the map sets.

        state:
            The name of the vector state of the target that holds the position.

        maps:
            The coefficients `(a, b, c, d, e, f)` of every affine map.

        weights:
            The weight of every map.

    Raises:
        ValidationError:
            The number of weights differs from the number of maps, or a map does not have six coefficients.

    Examples:
        >>> from skcomplex.systems.mathematics.fractals import RandomAffineMapInteraction
        >>> game = RandomAffineMapInteraction('game', target='points', maps=[(0.5, 0, 0, 0.5, 0, 0)], weights=[1.0])
        >>> game.maps
        [(0.5, 0, 0, 0.5, 0, 0)]
    """

    law_classes = (UpdateLaw,)
    draws = True

    def __init__(
        self,
        label: str,
        *,
        target: Role = 'points',
        state: str = 'p',
        maps: Sequence[AffineMap] = SIERPINSKI_MAPS,
        weights: Sequence[float] = (1.0, 1.0, 1.0),
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.maps = maps
        self.weights = weights

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The number of weights differs from the number of maps, or a map does not have six coefficients.
        """
        super()._check_arguments()
        if len(self.maps) != len(self.weights) or any(len(item) != AFFINE_COEFFICIENTS for item in self.maps):
            error_msg = (
                f'The random affine map {self.label!r} takes one weight per map and six coefficients per map, but got '
                f'{len(self.maps)} maps and {len(self.weights)} weights.'
            )
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the image of the position by the drawn map as the law.

        The weights must match the maps, and every map must have six coefficients.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        position = getattr(context.target, self.state)
        self.laws_: list[BaseLaw] = [UpdateLaw(position, self._get_image(context))]

    def _get_image(self, namespace: SimpleNamespace) -> FreeModuleElement:
        """Return the image of the position by the map drawn among the maps."""
        chosen = categorical('map', list(self.weights))
        position = getattr(namespace.target, self.state)
        x, y = position[0], position[1]
        images: list[tuple[Expression, Expression]] = [
            (a * x + b * y + e, c * x + d * y + f) for a, b, c, d, e, f in self.maps
        ]
        new_x, new_y = SR(images[-1][0]), SR(images[-1][1])
        for index in range(len(images) - 2, -1, -1):
            new_x = where(chosen == index, images[index][0], new_x)
            new_y = where(chosen == index, images[index][1], new_y)
        return vector(SR, [new_x, new_y])