Lenia and its expanded universe
Lenia, a continuous automaton whose ring-kernel convolutions grow solitons.
- Class:
LeniaSystem - Import:
from skcomplex.systems.computer_science.automata import LeniaSystem - Field:
computer_science/automata - Topics:
lattice,continuous automaton,convolution,soliton,artificial life,field - References:
- Chan 2019
- Chan 2020
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 LeniaSystem
trajectory = LeniaSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
shape |
(64, 64) |
initial |
None |
R |
13.0 |
T |
10.0 |
mu |
0.15 |
sigma |
0.015 |
beta |
(1.0,) |
channels |
1 |
kernels |
None |
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 | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class LeniaSystem(BaseSystem):
"""Lenia, a continuous automaton whose ring-kernel convolutions grow solitons.
The solitons are gliding and lifelike. The world is a torus of sites with values in `[0, 1]`, and one step of
`1 / T` adds the growth map of the convolution of the world with a ring kernel and clips the result,
`A <- [A + G(K * A) / T]` in `[0, 1]`, with `G(u) = 2 exp(-(u - mu)^2 / (2 sigma^2)) - 1` and the kernel of radius
`R`, whose concentric rings peak at `beta`. The expanded universe of Chan (2020) has several channels and several
kernels `(source, destination, r, h, beta, mu, sigma)`, each of radius `r R` with its own growth map, which reads
its source channel and grows its destination with the weight `h` over the sum of the weights into that destination,
`A_j <- [A_j + sum_k (h_k / h_j) G_k(K_k * A_i) / T]`, on worlds of three or more dimensions. By default the world
holds Orbium unicaudatus, which glides across the torus at a steady speed while its mass stays near 71. Every step
of the system is one update, so a unit of Lenia's time takes `T` steps. The system has the values `world.A`,
`world.B`, and `world.C` of the three channels of the sites, the last two at 0 for a world of one channel. Its
standard observables `mass_A`, `mass_B`, and `mass_C` are the totals of the values of every channel.
Args:
shape:
The number of sites along every axis of the torus, two or more axes.
initial:
The initial values, an array of the shape shared by every channel, or one per channel, or `None` for
Orbium in the middle of a two-dimensional world.
R:
The radius of the kernels in sites.
T:
The number of steps per unit time, the inverse of the increment of the update.
mu:
The centre of the growth map of the single kernel.
sigma:
The width of the growth map of the single kernel.
beta:
The peaks of the concentric rings of the single kernel.
channels:
The number of channels of the world, from one to three.
kernels:
The kernels `(source, destination, r, h, beta, mu, sigma)` of the expanded universe, with the channels as
indices, or `None` for the single kernel of `mu`, `sigma`, and `beta` on the first channel.
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:
ParameterError:
The world has fewer than two axes or not one to three channels, Orbium does not fit a default world, the
initial values do not have the shape, or a kernel names a channel the world does not have.
Examples:
>>> from skcomplex.systems.computer_science.automata import LeniaSystem
>>> LeniaSystem().prepare().system_.elements[0].A.shape
(4096,)
"""
field = 'computer_science/automata'
topics = ('lattice', 'continuous automaton', 'convolution', 'soliton', 'artificial life', 'field')
references = ('Chan 2019', 'Chan 2020')
until = 200
dt = 1
observables = tuple(
Observable(f'mass_{channel}', group='world', variable=channel, reduce=_get_mass) for channel in CHANNELS
)
def __init__(
self,
shape: Sequence[int] = (64, 64),
*,
initial: npt.ArrayLike | None = None,
R: float = 13.0,
T: float = 10.0,
mu: float = 0.15,
sigma: float = 0.015,
beta: Sequence[float] = (1.0,),
channels: int = 1,
kernels: Sequence[Kernel] | None = None,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.shape = shape
self.initial = initial
self.R = R
self.T = T
self.mu = mu
self.sigma = sigma
self.beta = beta
self.channels = channels
self.kernels = kernels
@staticmethod
def _get_initial_values(shape: tuple[int, ...], channels: int, initial: npt.ArrayLike | None) -> AnyArray:
"""Return the initial values of every channel, one array of the shape per channel."""
if initial is None:
if len(shape) != MIN_AXES or min(shape) < ORBIUM.shape[0]:
error_msg = f'Orbium needs a two-dimensional world of at least {ORBIUM.shape[0]} sites a side.'
raise ParameterError(error_msg)
values = np.zeros(shape)
top, left = (shape[0] - ORBIUM.shape[0]) // 2, (shape[1] - ORBIUM.shape[1]) // 2
values[top : top + ORBIUM.shape[0], left : left + ORBIUM.shape[1]] = ORBIUM
else:
values = np.asarray(initial, dtype=float)
if values.shape == shape:
return np.broadcast_to(values, (channels, *shape)).copy()
if values.shape != (channels, *shape):
error_msg = f'The initial values have the shape {values.shape}, but the world has {channels} of {shape}.'
raise ParameterError(error_msg)
return values
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the world and the updates of its channels."""
super()._prepare(context)
shape = tuple(self.shape)
if len(shape) < MIN_AXES or not 1 <= self.channels <= len(CHANNELS):
error_msg = (
f'Lenia needs two or more axes and one to three channels, but got {shape!r} and {self.channels!r}.'
)
raise ParameterError(error_msg)
values = self._get_initial_values(shape, self.channels, self.initial)
rings = (
((0, 0, 1.0, 1.0, tuple(self.beta), self.mu, self.sigma),) if self.kernels is None else tuple(self.kernels)
)
if any(not 0 <= index < self.channels for kernel in rings for index in kernel[:2]):
error_msg = f'Every kernel needs a source and a destination among the {self.channels} channels.'
raise ParameterError(error_msg)
channels = {CHANNELS[index]: values[index].ravel() for index in range(self.channels)}
world = LeniaSiteElement('world', **channels, space=LatticeSpace(shape))
updates = [
LeniaUpdateInteraction(
f'update_{CHANNELS[index]}',
target='world',
channel=CHANNELS[index],
kernels=[
(CHANNELS[source], radius * self.R, weight, tuple(peaks), centre, width)
for source, destination, radius, weight, peaks, centre, width in rings
if destination == index
],
T=self.T,
n_dim=len(shape),
)
for index in range(self.channels)
if any(kernel[1] == index for kernel in rings)
]
self.system_ = System(self.label, elements=[world], interactions=updates)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
LeniaSiteElement, fromElement
Interactions:
LeniaUpdateInteraction, fromInteraction
class LeniaSiteElement(Element):
"""Site of a Lenia world, with a value in `[0, 1]` for each of its channels.
A world has up to three channels. The updates of the world change the channels, and a world of one channel leaves
`B` and `C` at 0. With `space`, the element holds one site on every site of the space.
Args:
label:
The label of the sites.
A:
The initial value of the first channel, or one value per site.
B:
The initial value of the second channel, or one value per site.
C:
The initial value of the third channel, or one value per site.
space:
The space of the world, such as a torus of sites, or `None` for one site.
Examples:
>>> from skcomplex.systems.computer_science.automata import LeniaSiteElement
>>> LeniaSiteElement('site', A=0.5).A
0.5
"""
def __init__(
self,
label: str,
*,
A: Annotated[float | Array, RealSet.closed(0, 1)] = 0.0,
B: Annotated[float | Array, RealSet.closed(0, 1)] = 0.0,
C: Annotated[float | Array, RealSet.closed(0, 1)] = 0.0,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, space=space)
self.A = A
self.B = B
self.C = C
class LeniaUpdateInteraction(Interaction):
"""Update of a channel of a Lenia world by the growth maps of convolutions.
The convolutions are of channels with ring kernels.
Every kernel `(source, radius, h, beta, mu, sigma)` reads the state of its source channel, and its concentric
rings peak at `beta`. At the distance `q` in units of its radius, with `B` rings, it is `beta_i K_C(B q - i)` on
the ring `i = floor(B q)`, with the bump `K_C(x) = exp(4 - 1 / (x (1 - x)))`, normalised to a sum of 1 over the
sites. Its growth map is `G(u) = 2 exp(-(u - mu)^2 / (2 sigma^2)) - 1`, and one step adds the growths weighted by
`h` over the sum of the weights and clips the channel, `A <- [A + sum_k (h_k / h) G_k(K_k * A_k) / T]` in
`[0, 1]`.
Args:
label:
The label of the interaction.
target:
The path of the world.
channel:
The name of the state of the channel that the update changes.
kernels:
The kernels `(source, radius, h, beta, mu, sigma)`, with the name of the state of the source channel and
the radius in sites.
T:
The number of steps per unit time.
n_dim:
The number of dimensions of the world.
Examples:
>>> from skcomplex.systems.computer_science.automata import LeniaUpdateInteraction
>>> LeniaUpdateInteraction('update', target='world').T
10.0
"""
def __init__(
self,
label: str,
*,
target: Role = 'world',
channel: str = 'A',
kernels: Sequence[RingKernel] = (('A', 13.0, 1.0, (1.0,), 0.15, 0.015),),
T: float = 10.0,
n_dim: int = 2,
) -> None:
super().__init__(label)
self.target = target
self.channel = channel
self.kernels = kernels
self.T = T
self.n_dim = n_dim
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the update of the channel by the growths of the kernels as the law.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
distance = sqrt(sum(displacement(axis) ** 2 for axis in range(self.n_dim)))
total = sum(kernel[2] for kernel in self.kernels)
growth: Expression = 0
for source, radius, weight, peaks, mu, sigma in self.kernels:
kernel = self._get_shell(distance / radius, peaks) / self._get_norm(radius, peaks)
potential = convolve(getattr(context.target, source), kernel, math.ceil(radius))
growth += weight / total * (2 * exp(-((potential - mu) ** 2) / (2 * sigma**2)) - 1)
value = getattr(context.target, self.channel)
self.laws_: list[BaseLaw] = [UpdateLaw(value, clip(value + growth / self.T, 0, 1))]
@staticmethod
def _get_shell(q: Expression, peaks: Sequence[float]) -> Expression:
"""Return the rings of a kernel at the distance `q` in units of its radius.
They are zero outside the unit ball.
"""
rings = len(peaks)
shell: Expression = 0
for index, peak in enumerate(peaks):
x = rings * q - index
inside = both(x > 0, x < 1)
shell += where(inside, peak * exp(4 - 1 / where(inside, x * (1 - x), 1)), 0)
return shell
def _get_norm(self, radius: float, peaks: Sequence[float]) -> float:
"""Return the sum of the rings of a kernel over the sites within its radius."""
steps = np.arange(-math.ceil(radius), math.ceil(radius) + 1)
grid = np.meshgrid(*[steps] * self.n_dim, indexing='ij')
q: Array = np.sqrt(sum(axis**2 for axis in grid)) / radius
rings = len(peaks)
values = np.zeros_like(q)
for index, peak in enumerate(peaks):
x = rings * q - index
inside = (x > 0) & (x < 1)
values += np.where(inside, peak * np.exp(4 - 1 / np.where(inside, x * (1 - x), 1)), 0)
return float(values.sum())