Rewriting
Define the rewriting of words and tilings that several fields share.
A word grows by productions, as an L-system, and a patch of tiles grows by substitutions, as a fractal tiling. The package brings the compiler, the solver, and the drawing of these systems.
AffineSpec(scale=1.0, rotation=0.0, translation=(0.0, 0.0), reflect=False, matrix=None)
dataclass
Bases: BaseSpec
A spec of an affine map of the plane, a linear map followed by a shift.
The map is a reflection across the x axis, a rotation, a scale, and a translation. The scale, the rotation, and the translation can be expressions of the parameters of the element whose laws hold the substitution, which are evaluated at every generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale
|
float | Expression
|
The scale factor. |
1.0
|
rotation
|
float | Expression
|
The rotation in degrees. |
0.0
|
translation
|
Sequence[float | Expression]
|
The translation. |
(0.0, 0.0)
|
reflect
|
bool
|
Whether to reflect across the x axis first. |
False
|
matrix
|
ArrayLike | None
|
A homogeneous 3 by 3 matrix that replaces the other arguments. |
None
|
Examples:
>>> from skcomplex.systems.general.rewriting import AffineSpec
>>> AffineSpec(scale=0.5, translation=(1, 0)).scale
0.5
get_matrix_at(values)
Return the homogeneous matrix of the map at values of its parameters.
The values are those of the parameters its expressions read. The map reflects across the x axis, rotates, scales, and translates, in this order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Mapping[object, float]
|
A mapping from parameter symbol to value. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
matrix |
NDArray[float64]
|
The 3 by 3 matrix. |
Examples:
>>> from skcomplex.systems.general.rewriting import AffineSpec
>>> AffineSpec(scale=0.5, translation=(1, 0)).get_matrix_at({}).tolist()
[[0.5, 0.0, 1.0], [0.0, 0.5, 0.0], [0.0, 0.0, 1.0]]
Source code in src/skcomplex/systems/general/rewriting/_affine_spec.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
GeometrySpec(angle=90.0, step=1.0, contraction=1.0, symbols=None, dimension=2, heading=0.0)
dataclass
Bases: BaseSpec
A spec of how a word is drawn as line segments, as by a turtle.
The segments lie in two or three dimensions. A cursor walks the word: symbols mean draw (forward with a segment),
move (forward without one), left and right (turn by the angle), reverse (turn by 180 degrees), push and
pop (save and restore the position and heading), and in three dimensions pitch_down, pitch_up, roll_left,
and roll_right. This is the turtle interpretation of Prusinkiewicz and Lindenmayer (1990), whose symbols are the
default meanings: F, f, +, -, |, [, ], &, ^, \, and /. A module's first parameter overrides
the step of a move or the angle of a turn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
angle
|
float
|
The turning angle in degrees. |
90.0
|
step
|
float
|
The step at generation 0. |
1.0
|
contraction
|
float
|
The factor the step is multiplied by at every generation. |
1.0
|
symbols
|
Mapping[str, str] | None
|
Meanings of symbols that replace or extend the default ones of |
None
|
dimension
|
int
|
2 or 3. |
2
|
heading
|
float
|
The initial heading in degrees in two dimensions, measured from the x axis. |
0.0
|
Examples:
>>> from skcomplex.systems.general.rewriting import GeometrySpec
>>> GeometrySpec(angle=60.0, contraction=1 / 3).angle
60.0
GeometryVisual(filled=None, resolution=RESOLUTION, *, path=None, recording=None)
Bases: BaseVisual
A visual that logs the structure of a rewritten element at every frame.
The frame of the drawing is fixed across generations. Word segments, segment tiles, and polygon outlines are one
batch of line strips, colored by branch depth or by prototile. A filled patch is an image of its raster instead. The
counts of symbols or prototiles are logged as series under <path>/counts/<state>.
Unlike PointsVisual, which draws members at their positions, it draws a structure that grows outside the state
vector. Choose it when an element is a word or a patch.
It appears in many fields. It draws the plants of botany, the fractal curves and tilings of mathematics, and the sequences of symbolic dynamics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filled
|
bool | None
|
Whether to draw polygons as a filled image, or |
None
|
resolution
|
int
|
The side in pixels of the image of a filled patch. |
RESOLUTION
|
path
|
str | None
|
The entity path of the element or agent group to draw, which also names it in the problem. |
None
|
recording
|
RecordingStream | None
|
The Rerun recording to log to, or |
None
|
Examples:
>>> from skcomplex.systems.general.rewriting import GeometryVisual
>>> GeometryVisual(filled=True)
GeometryVisual(filled=True)
Source code in src/skcomplex/systems/general/rewriting/_geometry_visual.py
59 60 61 62 63 64 65 66 67 68 69 70 | |
ModuleSpec(name, parameters=())
dataclass
Bases: BaseSpec
A spec of a symbol of a word, with numeric or symbolic parameters.
Examples are A(x) or F(1.0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the symbol. |
required |
parameters
|
tuple[float | Expression, ...]
|
The parameters, numbers in a word and symbols or expressions in a production. |
()
|
Examples:
>>> from skcomplex.systems.general.rewriting import ModuleSpec
>>> ModuleSpec('F', (0.5,)).parameters
(0.5,)
parse_word(value, names=())
classmethod
Return the modules of a word.
The word is a string of one-character symbols, a module, or a sequence of both. A string item of a sequence is one symbol when it is a declared name or one character long, and a string of one-character symbols otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Letters
|
The word. |
required |
names
|
Sequence[str]
|
The declared symbol names, which may be longer than one character. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
modules |
list[ModuleSpec]
|
The modules of the word. |
Examples:
>>> from skcomplex.systems.general.rewriting import ModuleSpec
>>> [module.name for module in ModuleSpec.parse_word(['F', ModuleSpec('A', (1.0,)), '+-'])]
['F', 'A', '+', '-']
Source code in src/skcomplex/systems/general/rewriting/_module_spec.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
PatchElement(label, tiles=None, *, prototiles=(), filled=False, max_size=10000000, bounds=None)
Bases: 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The name of the patch, such as |
required |
tiles
|
Sequence[tuple[str, AffineSpec]] | None
|
Each tile at the start, as a pair of a prototile name and its placement, or |
None
|
prototiles
|
Sequence[PrototileSpec]
|
The basic shapes, each a |
()
|
filled
|
bool
|
Whether the drawing fills the polygons as an image instead of drawing their outlines. |
False
|
max_size
|
int
|
The largest number of tiles one step may produce, which guards memory. |
10000000
|
bounds
|
Sequence[float] | None
|
The box |
None
|
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]
Source code in src/skcomplex/systems/general/rewriting/_patch.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
ProductionLaw(predecessor, successor, *, left=None, right=None, condition=None, probability=None, label='')
dataclass
Bases: BaseLaw
A law that rewrites every matching symbol of a word by a successor.
A string rewriting system, or L-system, grows a word by replacing each symbol by a string at every generation. A interaction that binds a word sets its productions, and every generation applies all of them at once. The parameters of the predecessor are symbols bound to the parameters of each matching symbol. The condition, the parameters of the successor, and the probability are expressions of these symbols and of the parameters of the element. A production with a left or a right context matches only where the neighbours spell it, skipping ignored symbols and bracketed branches.
Unlike UpdateLaw, which changes the value of a fixed number of states, it replaces symbols by strings, so the word
grows. Choose it when a structure develops by repeated rewriting.
It appears in many fields. Lindenmayer systems model the branching of plants, rewriting rules build fractal curves, and grammars generate the structure of sentences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predecessor
|
str | ModuleSpec
|
The symbol, or a module whose parameters are symbols. |
required |
successor
|
Letters
|
The word that replaces the predecessor. |
required |
left
|
Letters | None
|
The left context, or |
None
|
right
|
Letters | None
|
The right context, or |
None
|
condition
|
object
|
A symbolic condition of the predecessor's parameters, or |
None
|
probability
|
object
|
The probability of a stochastic production, or |
None
|
label
|
str
|
The name of the law, or the empty string for a law without one. |
''
|
Examples:
>>> from skcomplex.systems.general.rewriting import ProductionLaw
>>> ProductionLaw('F', 'F+F--F+F').successor
'F+F--F+F'
PrototileSpec(name, vertices)
dataclass
Bases: BaseSpec
A spec of a shape of which the tiles of a patch are placed copies.
The shape is a segment or a polygon in its own frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the prototile, which names its count state. |
required |
vertices
|
Sequence[Sequence[float]]
|
The vertices in the plane, two for a segment and at least three for a polygon. |
required |
Examples:
>>> from skcomplex.systems.general.rewriting import PrototileSpec
>>> len(PrototileSpec('interval', [(0, 0), (1, 0)]).vertices)
2
is_segment
property
Whether the prototile is a segment, with two vertices, rather than a polygon.
RewritingInteraction(label, *, target, laws=())
Bases: 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The name of the interaction, such as |
required |
target
|
Role
|
The path of the word or patch it rewrites. |
required |
laws
|
Sequence[ProductionLaw | SubstitutionLaw]
|
The productions of a word or the substitutions of a patch. |
()
|
Raises:
| Type | Description |
|---|---|
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]
Source code in src/skcomplex/systems/general/rewriting/_rewriting_interaction.py
60 61 62 63 | |
RewritingSolver(*, random_state=None, until=math.inf)
Bases: BaseSolver[RewritingProblemSpec]
A solver of rewriting systems, one generation per unit of time.
It rewrites every structure in parallel once per generation. The structures live next to the state vector, whose components are their symbol, prototile, or label counts and sizes. Stochastic productions draw from the simulation's random stream.
Unlike IterationSolver, which applies a map to a state vector of fixed size, it rewrites structures that grow.
Choose it when a system holds words or patches.
It appears in many fields. It grows plants in botany, fractal curves and tilings in mathematics, and the Thue-Morse sequence in computer science.
Examples:
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.general.rewriting import (
... ProductionLaw, RewritingInteraction, RewritingSolver, WordElement
... )
>>> laws = [ProductionLaw('A', 'AB'), ProductionLaw('B', 'A')]
>>> growth = RewritingInteraction('growth', target='algae', laws=laws)
>>> system = System(elements=[WordElement('algae', axiom='A')], interactions=[growth], solver=RewritingSolver())
>>> trajectory = system.prepare().simulate(until=5)
>>> trajectory.get_values('algae.size').tolist()
[1.0, 2.0, 3.0, 5.0, 8.0, 13.0]
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
SubstitutionLaw(prototile, pieces, *, label='')
dataclass
Bases: BaseLaw
A law that replaces every tile of a prototile by smaller placed pieces.
A prototile is a shape of tile. At every generation each tile of that shape is replaced by pieces, placed relative
to the tile. An interaction that binds a patch sets its substitutions, and every generation applies all of them at
once.
Unlike ProductionLaw, which rewrites symbols of a word, it rewrites tiles of the plane. Choose it when a tiling
grows by inflation and subdivision.
It appears in mathematics and materials science. The Penrose tiling grows by substitution, and quasicrystals have the order of such tilings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prototile
|
str
|
The name of the prototile replaced. |
required |
pieces
|
Sequence[tuple[str, AffineSpec]]
|
Pairs of a prototile name and the affine map from the parent tile's frame. |
required |
label
|
str
|
The name of the law, or the empty string for a law without one. |
''
|
Examples:
>>> from skcomplex.systems.general.rewriting import SubstitutionLaw
>>> from skcomplex.systems.general.rewriting import AffineSpec
>>> len(SubstitutionLaw('interval', [('interval', AffineSpec(scale=1 / 3))]).pieces)
1
WordElement(label, axiom='', *, alphabet=None, ignore='', geometry=None, max_size=10000000, bounds=None)
Bases: 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The name of the word, such as |
required |
axiom
|
Letters
|
The word at the start, such as |
''
|
alphabet
|
str | Mapping[str, int] | None
|
The symbols, as a string of one-character symbols or a mapping from each name to its number of parameters,
or |
None
|
ignore
|
str | Sequence[str]
|
The symbols that a production skips when it reads the neighbours of a symbol, such as |
''
|
geometry
|
GeometrySpec | None
|
How the word is drawn as line segments, a |
None
|
max_size
|
int
|
The largest word one step may produce, which guards memory. |
10000000
|
bounds
|
Sequence[float] | None
|
The box |
None
|
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]
Source code in src/skcomplex/systems/general/rewriting/_word.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |