Langton's ant
Langton's ant, which builds a periodic highway after a chaotic transient.
- Class:
LangtonsAntSystem - Import:
from skcomplex.systems.computer_science.automata import LangtonsAntSystem - Field:
computer_science/automata - Topics:
lattice,ant,emergence - References:
- Langton 1986
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.computer_science.automata import LangtonsAntSystem
trajectory = LangtonsAntSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
shape |
(80, 80) |
heading |
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 | lattice |
| Laws | update |
| Randomness | unknown |
| Domains | boolean, integer |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class LangtonsAntSystem(BaseSystem):
"""Langton's ant, which builds a periodic highway after a chaotic transient.
It wanders chaotically for about 10,000 steps before it builds the highway. The system has the colors `cells.color`
and the ant `cells.ant`.
Args:
shape:
The number of rows and columns of the torus.
heading:
The initial heading of the ant, 0 to 3 for north, east, south, and west.
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.computer_science.automata import LangtonsAntSystem
>>> int((LangtonsAntSystem((9, 9)).prepare().system_.elements[0].ant >= 0).sum())
1
"""
field = 'computer_science/automata'
topics = ('lattice', 'ant', 'emergence')
references = ('Langton 1986',)
until = 11000
dt = 100
def __init__(
self,
shape: Sequence[int] = (80, 80),
*,
heading: int = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.shape = shape
self.heading = heading
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the colored cells and the ant on them."""
super()._prepare(context)
ant = np.full(tuple(self.shape), -1.0)
ant[self.shape[0] // 2, self.shape[1] // 2] = self.heading
cells = AntCellElement(
'cells',
color=np.zeros(ant.size),
ant=ant.ravel(),
space=LatticeSpace(tuple(self.shape)),
)
self.system_ = System(
self.label,
elements=[cells],
interactions=[LangtonsAntInteraction('ant', target='cells')],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
AntCellElement, fromElement
Interactions:
LangtonsAntInteraction, fromInteraction
class AntCellElement(Element):
"""Cell of Langton's ant: a color, and the heading of the ant on it or -1.
A `LangtonsAntInteraction` turns the ant right on a white cell and left on a black one, flips the cell's color, and
moves the ant one cell forward. With `space`, the element holds one cell on every site.
Args:
label:
The label of the cells.
color:
The initial color, 0 for white and 1 for black, or one color per cell.
ant:
The initial heading of an ant on the cell, 0 to 3 for north, east, south, and west, or -1 for none, or one
heading per cell.
space:
The space with one cell on every site, such as a lattice, or `None` for one cell.
Examples:
>>> from skcomplex.systems.computer_science.automata import AntCellElement
>>> AntCellElement('cell').ant
-1
"""
def __init__(
self,
label: str,
*,
color: Annotated[float | Array, {0, 1}] = 0,
ant: Annotated[float | Array, ZZ] = -1,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, space=space)
self.color = color
self.ant = ant
class LangtonsAntInteraction(Interaction):
"""Move of Langton's ant over the colored cells.
The ant turns right on a white cell and left on a black one, flips the color of the cell it leaves, and moves one
cell forward. Every cell holds its color and the heading of an ant on it, or -1 for none.
Args:
label:
The label of the interaction.
target:
The cells whose states `color` and `ant` the ant changes.
Examples:
>>> from skcomplex.systems.computer_science.automata import LangtonsAntInteraction
>>> LangtonsAntInteraction('ant', target='cells').target
'cells'
"""
def __init__(self, label: str, *, target: Role = 'cells') -> None:
super().__init__(label)
self.target = target
@staticmethod
def _get_next(*values: Array, **kwargs: object) -> tuple[Array, Array]:
"""Return the next colors and ants from the von Neumann neighbourhoods of both states."""
colors, ants = values[:5], values[5:]
color = np.where(ants[0] >= 0, 1 - colors[0], colors[0])
ant = np.full(color.shape, -1.0)
arrivals = {1: 2, 2: 1, 3: 3, 4: 0}
for column, heading in arrivals.items():
turned = np.where(colors[column] == 0, (ants[column] + 1) % 4, (ants[column] + 3) % 4)
ant = np.where((ants[column] >= 0) & (turned == heading), turned, ant)
return color, ant
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the move of the ant as the law.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
states = (context.target.color, context.target.ant)
self.laws_: list[BaseLaw] = [
UpdateLaw(states, self._get_next, neighborhood=VON_NEUMANN, label=self.label),
]