"""Microstructures generated by cellular automata and reaction-diffusion.
Each realization is a :class:`~morphogen.models.lattice_field.LatticeField` on a
lattice of cells of edge ``cell_size`` covering the domain:
* periodic domains use periodic lattices (the realization tiles space);
* non-periodic domains are windows of an automaton running on a larger periodic
lattice, enlarged by the distance information travels in the run (the light cone:
neighbourhood radius times the number of steps, at most 32 cells): the windows are
then unbiased, without boundary effects.
``dimension: 2`` runs planar automata (one cell through the thickness of the domain).
Other ``lattice`` values than ``square`` run the automata (and reaction-diffusion, with
the finite-volume Laplacian of the tiling) on the cells of a tiling
(:mod:`morphogen.automata.tilings`: triangles, hexagons, Penrose and Ammann-Beenker
tiles, prisms, the Voronoi cells of the BCC and FCC lattices, golden rhombohedra) and
give a :class:`~morphogen.models.tiling_field.TilingField`, rasterized cell by cell; the
non-periodic windows are then cut from a larger periodic tiling (a larger quasi-periodic
patch, with free boundaries) in the same way. Quasi-periodic tilings fill periodic
domains through their periodic approximants (``approximant``: an order), the same tiles
in a rectangle or a cube of which the box holds a whole number.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import ClassVar
import numpy as np
from morphogen._utils import check_fraction, check_positive
from morphogen.automata.engine import UPDATES, CellularAutomaton, random_state
from morphogen.automata.lattice import NEIGHBOURHOODS
from morphogen.automata.reaction import (
GRAY_SCOTT_PRESETS,
gray_scott,
gray_scott_tiling,
stable_substeps,
)
from morphogen.automata.rules import ActivatorInhibitorRule, make_rule
from morphogen.automata.tilings import LATTICES, PLANAR, QUASIPERIODIC, REACH, make_tiling
from morphogen.domain import Domain
from morphogen.models.base import Model, param, register
from morphogen.models.lattice_field import LatticeField, lattice_shape
from morphogen.models.tiling_field import TilingField, default_grid
from morphogen.seeding import SeedLike, make_rng
#: Largest margin (in cells) added around non-periodic windows.
MAX_MARGIN = 32
_LATTICE_DOC = (
"Cells: square (cubes in 3D), triangular, hexagonal, penrose or ammann_beenker "
"(quasi-periodic: non-periodic domains, or periodic ones with an approximant), "
"stacked as prisms in 3D; bcc, fcc or "
"icosahedral (3D: truncated octahedra, rhombic dodecahedra, golden rhombohedra, the "
"last quasi-periodic). Cells of area cell_size^2 or volume cell_size^3 (on average "
"for quasi-periodic tilings)"
)
_APPROXIMANT_DOC = (
"Order (1, 2, ...) of the periodic approximant of a quasi-periodic lattice (penrose, "
"ammann_beenker, icosahedral) for periodic domains: the same tiles, periodic in a "
"rectangle or a cube that the box holds a whole number of times (fitted to it; "
"morphogen.automata.tilings.approximant_period). Non-periodic domains: windows of it"
)
def _recorder(steps: int, frames: int, crop, pick=None):
"""Frames (window sections of the states) at about ``frames`` evenly spaced steps,
and the callback that records them (None without frames)."""
record: list[np.ndarray] = []
if frames <= 0:
return record, None
every = max(1, round(steps / frames))
def callback(k, *state):
if k % every == 0 or k == steps:
current = pick(*state) if pick is not None else state[0]
record.append(np.array(current[crop]))
return record, callback
@dataclass(frozen=True)
class _LatticeModel(Model):
"""Common parameters of the models generated cell by cell."""
phases: ClassVar[dict[int, str]] = {0: "phase 0", 1: "phase 1"}
cell_size: float = param(
1.0,
doc="Edge of the cells of the lattice (other lattices than square: the edge of the "
"square or cube of the same area or volume)",
unit="length",
)
dimension: int = param(
3, doc="3, or 2 for planar structures (one cell through the thickness)", kind="int"
)
smoothing: float = param(
0.0,
doc="Gaussian smoothing (in cells) of the interface for other resolutions and "
"conforming meshes (0: trilinear interpolation of the cells)",
unit="cells",
)
def _validate_lattice(self) -> None:
check_positive(self.cell_size, "cell_size")
if self.dimension not in (2, 3):
raise ValueError("dimension: 2 or 3")
check_positive(self.smoothing, "smoothing", allow_zero=True)
def evolution(self, domain: Domain, seed: SeedLike = None, frames: int = 20):
"""States of the lattice of the domain along the formation of the realization of
``generate(domain, seed)`` (about ``frames`` of them, the realization last)."""
rng, _ = make_rng(seed)
return self._simulate(domain, rng, max(1, int(frames)))[-1]
def _validate_tiling(self) -> None:
if self.lattice not in LATTICES:
raise ValueError(f"lattice: one of {LATTICES}")
if self.lattice not in PLANAR and self.dimension != 3:
raise ValueError(f"lattice {self.lattice}: three-dimensional (dimension: 3)")
if self.lattice != "square" and self.smoothing > 0:
raise ValueError(
"smoothing: square lattices only (tilings are rasterized cell by cell)"
)
if self.approximant is not None:
if self.lattice not in QUASIPERIODIC:
raise ValueError(
f"approximant: quasi-periodic lattices only ({', '.join(QUASIPERIODIC)})"
)
if self.approximant < 1:
raise ValueError("approximant: an order of at least 1")
def _tiling(self, domain: Domain, reach_cells: float, rng):
"""Tiling of the simulation and the indices of its cells meeting the domain (None:
all): the periodic tiling of a periodic domain (the approximant of a quasi-periodic
one), otherwise a tiling of the domain enlarged by the light cone (periodic, or a
free patch for quasi-periodic tilings without approximant)."""
h, dims = self.cell_size, self.dimension
approximant = self.approximant
if domain.periodic:
tiling = make_tiling(
self.lattice, domain.lengths, h, dims=dims, periodic=True, origin=domain.lower,
rng=rng, approximant=approximant,
) # fmt: skip
return tiling, None
margin = min(MAX_MARGIN, math.ceil(reach_cells)) * h
pad = np.array([margin, margin, margin if dims == 3 else 0.0])
tiling = make_tiling(
self.lattice,
domain.lengths + 2 * pad,
h,
dims=dims,
periodic=self.lattice not in QUASIPERIODIC or approximant is not None,
origin=domain.lower - pad,
rng=rng,
approximant=approximant,
)
r = tiling.circumradius
lo, hi = domain.lower - r, domain.upper + r
inside = np.all((tiling.centres >= lo) & (tiling.centres <= hi), axis=1)
return tiling, np.flatnonzero(inside)
def _frames_of(self, domain: Domain, tiling, frames: int):
"""Image of the cells of the window (default grid of the realizations), indexing
the states of the frames, or None without frames."""
return tiling.cell_index(default_grid(domain, tiling)) if frames > 0 else None
def _window(self, domain: Domain, reach_cells: float):
"""Lattice of the domain, simulation lattice and the slices of the window."""
shape = lattice_shape(domain, self.cell_size, self.dimension)
if domain.periodic:
return shape, shape, (slice(None),) * 3
margin = int(min(MAX_MARGIN, math.ceil(reach_cells)))
sim = tuple(
n + 2 * margin if (a < 2 or self.dimension == 3) else n for a, n in enumerate(shape)
)
crop = tuple(
slice(margin, margin + n) if (a < 2 or self.dimension == 3) else slice(None)
for a, n in enumerate(shape)
)
return shape, sim, crop
[docs]
@register
@dataclass(frozen=True)
class CellularAutomatonModel(_LatticeModel):
"""Two-phase structure grown by a cellular automaton from random noise."""
name = "cellular_automaton"
rule: str = param(
"anneal",
doc="majority, anneal (twisted majority: bicontinuous coarsening), conserved "
"(majority at constant volume fraction), clouds, life, or B<counts>/S<counts>",
kind="str",
)
steps: int = param(30, doc="Number of updates", kind="int")
neighbourhood: str = param("moore", doc="von_neumann, moore, edges or euclidean", kind="str")
radius: float = param(1.0, doc="Radius of the neighbourhood, in cells")
initial_fraction: float = param(
0.5, doc="Probability of phase 1 in the initial noise", kind="fraction"
)
volume_fraction: float | None = param(
None, doc="Volume fraction kept by the 'conserved' rule", kind="fraction"
)
update: str = param("synchronous", doc="synchronous, asynchronous or sequential", kind="str")
async_fraction: float = param(
0.5,
doc="Probability that a cell is updated at each asynchronous step",
kind="fraction",
)
lattice: str = param(
"square",
doc=_LATTICE_DOC,
kind="str",
)
approximant: int | None = param(None, doc=_APPROXIMANT_DOC, kind="int")
def _validate(self) -> None:
self._validate_lattice()
self._validate_tiling()
conserved = str(self.rule).strip().lower() == "conserved"
if conserved and self.volume_fraction is None:
raise ValueError("the 'conserved' rule needs 'volume_fraction'")
if not conserved and self.volume_fraction is not None:
raise ValueError(
"volume_fraction is kept only by the 'conserved' rule; other rules start "
"from 'initial_fraction'"
)
make_rule(self.rule, fraction=self.volume_fraction) # raises on bad rules
if self.neighbourhood not in NEIGHBOURHOODS:
raise ValueError(f"neighbourhood: one of {NEIGHBOURHOODS}")
if not self.radius >= 1:
raise ValueError("radius: at least 1 cell")
if self.steps < 0:
raise ValueError("steps: must be non-negative")
if self.update not in UPDATES:
raise ValueError(f"update: one of {UPDATES}")
check_fraction(self.initial_fraction, "initial_fraction")
if self.volume_fraction is not None:
check_fraction(self.volume_fraction, "volume_fraction")
@property
def conserved(self) -> bool:
return self.volume_fraction is not None
[docs]
def automaton(self, periodic: bool = True, tiling=None) -> CellularAutomaton:
return CellularAutomaton(
self.rule,
neighbourhood=self.neighbourhood,
radius=self.radius,
dims=self.dimension,
periodic=periodic,
fraction=self.volume_fraction,
tiling=tiling,
)
def _simulate_tiling(self, domain: Domain, rng, frames: int = 0):
reach = self.radius * self.steps
if self.neighbourhood != "euclidean":
reach *= REACH[self.lattice]
tiling, cells = self._tiling(domain, reach, rng)
p0 = self.volume_fraction if self.conserved else self.initial_fraction
state = random_state((tiling.n_cells,), p0, rng, exact=self.conserved)
crop = self._frames_of(domain, tiling, frames)
record, callback = _recorder(self.steps, frames, crop)
if callback is not None:
callback(0, state)
evo = self.automaton(tiling=tiling).run(
state,
self.steps,
rng,
update=self.update,
async_fraction=self.async_fraction,
callback=callback,
)
if callback is not None and not np.array_equal(record[-1], evo.state[crop]):
record.append(evo.state[crop].copy())
return evo, (tiling, cells), record
def _simulate(self, domain: Domain, rng, frames: int = 0):
if self.lattice != "square":
return self._simulate_tiling(domain, rng, frames)
_, sim, crop = self._window(domain, self.radius * self.steps)
p0 = self.volume_fraction if self.conserved else self.initial_fraction
state = random_state(sim, p0, rng, exact=self.conserved)
record, callback = _recorder(self.steps, frames, crop)
if callback is not None:
callback(0, state)
evo = self.automaton().run(
state,
self.steps,
rng,
update=self.update,
async_fraction=self.async_fraction,
callback=callback,
)
if callback is not None and not np.array_equal(record[-1], evo.state[crop]):
record.append(evo.state[crop].copy()) # stopped early: stable state
return evo, crop, record
[docs]
def generate(self, domain: Domain, seed: SeedLike = None) -> LatticeField:
rng, seed_info = make_rng(seed)
evo, crop, _ = self._simulate(domain, rng)
attributes = {"steps": evo.steps, "history": evo.history}
if self.lattice != "square":
tiling, cells = crop
phases = evo.state if cells is None else evo.state[cells]
return TilingField(
domain, tiling, phases, cells=cells, model=self, seed=seed_info,
attributes=attributes,
) # fmt: skip
return LatticeField(
domain,
evo.state[crop],
smoothing=self.smoothing,
model=self,
seed=seed_info,
attributes=attributes,
)
[docs]
def theory(self, domain: Domain | None = None) -> dict[str, float]:
return {"volume_fraction": self.volume_fraction} if self.conserved else {}
[docs]
@register
@dataclass(frozen=True)
class ActivatorInhibitorModel(_LatticeModel):
"""Turing patterns of Young's (1984) activator-inhibitor cellular automaton.
Spots, stripes or labyrinths with a wavelength set by the inhibition radius.
"""
name = "activator_inhibitor"
activation_radius: float = param(
2.0, doc="Radius of the activating neighbourhood", unit="length"
)
inhibition_radius: float = param(5.0, doc="Outer radius of the inhibiting shell", unit="length")
inhibition_weight: float | None = param(
None,
doc="Weight of the inhibiting cells (default: balanced, a uniform state scores 0)",
)
volume_fraction: float | None = param(
None,
doc="Keep this fraction of active cells (the highest scores); otherwise the sign "
"of the score decides",
kind="fraction",
)
initial_fraction: float = param(
0.5, doc="Probability of phase 1 in the initial noise", kind="fraction"
)
steps: int = param(15, doc="Number of updates", kind="int")
lattice: str = param(
"square",
doc=_LATTICE_DOC,
kind="str",
)
approximant: int | None = param(None, doc=_APPROXIMANT_DOC, kind="int")
def _validate(self) -> None:
self._validate_lattice()
self._validate_tiling()
r1 = check_positive(self.activation_radius, "activation_radius")
r2 = check_positive(self.inhibition_radius, "inhibition_radius")
if r1 < self.cell_size:
raise ValueError("activation_radius: at least one cell")
if r2 <= r1:
raise ValueError("inhibition_radius must exceed activation_radius")
if self.inhibition_weight is not None:
check_positive(self.inhibition_weight, "inhibition_weight")
if self.volume_fraction is not None:
check_fraction(self.volume_fraction, "volume_fraction")
check_fraction(self.initial_fraction, "initial_fraction")
if self.steps < 0:
raise ValueError("steps: must be non-negative")
def _simulate(self, domain: Domain, rng, frames: int = 0):
r1 = self.activation_radius / self.cell_size
r2 = self.inhibition_radius / self.cell_size
rule = ActivatorInhibitorRule(
r1, r2, self.inhibition_weight, self.volume_fraction, dims=self.dimension
)
if self.lattice != "square":
tiling, cells = self._tiling(domain, r2 * self.steps, rng)
p0 = self.volume_fraction if self.volume_fraction is not None else self.initial_fraction
state = random_state((tiling.n_cells,), p0, rng, exact=self.volume_fraction is not None)
crop = self._frames_of(domain, tiling, frames)
record, callback = _recorder(self.steps, frames, crop)
if callback is not None:
callback(0, state)
ca = CellularAutomaton(rule, tiling=tiling)
evo = ca.run(state, self.steps, rng, callback=callback)
if callback is not None and not np.array_equal(record[-1], evo.state[crop]):
record.append(evo.state[crop].copy())
return evo, (tiling, cells, ca.lattice), rule, record
_, sim, crop = self._window(domain, r2 * self.steps)
p0 = self.volume_fraction if self.volume_fraction is not None else self.initial_fraction
state = random_state(sim, p0, rng, exact=self.volume_fraction is not None)
record, callback = _recorder(self.steps, frames, crop)
if callback is not None:
callback(0, state)
ca = CellularAutomaton(rule, dims=self.dimension, periodic=True)
evo = ca.run(state, self.steps, rng, callback=callback)
if callback is not None and not np.array_equal(record[-1], evo.state[crop]):
record.append(evo.state[crop].copy())
return evo, crop, rule, record
[docs]
def generate(self, domain: Domain, seed: SeedLike = None) -> LatticeField:
rng, seed_info = make_rng(seed)
evo, crop, rule, _ = self._simulate(domain, rng)
if self.lattice != "square":
tiling, cells, context = crop
weight = np.mean(rule.tiling_kernels(context)[2])
return TilingField(
domain,
tiling,
evo.state if cells is None else evo.state[cells],
cells=cells,
model=self,
seed=seed_info,
attributes={
"steps": evo.steps,
"inhibition_weight": float(weight),
"history": evo.history,
},
)
return LatticeField(
domain,
evo.state[crop],
smoothing=self.smoothing,
model=self,
seed=seed_info,
attributes={
"steps": evo.steps,
"inhibition_weight": rule.weight,
"history": evo.history,
},
)
[docs]
def theory(self, domain: Domain | None = None) -> dict[str, float]:
if self.volume_fraction is None:
return {}
return {"volume_fraction": self.volume_fraction}
#: Initial conditions drawn (from the same random stream) before giving up on a pattern.
MAX_ATTEMPTS = 5
[docs]
@register
@dataclass(frozen=True)
class ReactionDiffusionModel(_LatticeModel):
"""Turing patterns of the Gray-Scott reaction-diffusion system.
Spots, worms, labyrinths or holes, thresholded on the activator concentration.
With the default diffusion coefficients, the patterns have a period of about 12
cells: ``cell_size`` sets their scale. Lattices narrower than about two periods
(24 cells) may not sustain them; the activator then dies out and new initial
conditions are drawn (up to 5 times). Other lattices than ``square`` run the
system on the cells of a tiling with its finite-volume Laplacian (a
:class:`~morphogen.models.tiling_field.TilingField`).
"""
name = "reaction_diffusion"
pattern: str | None = param(
"labyrinth",
doc="Preset of feed and kill rates: spots, worms, labyrinth or holes "
"(ignored when feed and kill are given)",
kind="str",
)
feed: float | None = param(None, doc="Feed rate F (with kill: overrides the preset)")
kill: float | None = param(None, doc="Kill rate k (with feed: overrides the preset)")
diffusion_u: float = param(0.16, doc="Diffusion coefficient of u, in cells^2 per step")
diffusion_v: float = param(0.08, doc="Diffusion coefficient of v, in cells^2 per step")
steps: int = param(4000, doc="Number of explicit time steps", kind="int")
volume_fraction: float | None = param(
None,
doc="Fraction of phase 1 (the cells of highest activator concentration); "
"otherwise phase 1 is v > threshold",
kind="fraction",
)
threshold: float = param(0.2, doc="Activator level of phase 1 without volume_fraction")
seed_fraction: float = param(
0.1, doc="Fraction of the cells in the initial activator blobs", kind="fraction"
)
lattice: str = param("square", doc=_LATTICE_DOC, kind="str")
approximant: int | None = param(None, doc=_APPROXIMANT_DOC, kind="int")
def _validate(self) -> None:
self._validate_lattice()
self._validate_tiling()
if (self.feed is None) != (self.kill is None):
raise ValueError("give both 'feed' and 'kill', or a 'pattern' preset")
if self.feed is None and self.pattern not in GRAY_SCOTT_PRESETS:
raise ValueError(f"pattern: one of {list(GRAY_SCOTT_PRESETS)}")
if self.feed is not None:
check_positive(self.feed, "feed")
check_positive(self.kill, "kill")
limit = 1.0 / (2 * self.dimension)
for name in ("diffusion_u", "diffusion_v"):
d = check_positive(getattr(self, name), name)
if d > limit:
raise ValueError(f"{name}: at most {limit:g} for a stable explicit scheme")
if self.steps < 1:
raise ValueError("steps: at least 1")
if self.volume_fraction is not None:
check_fraction(self.volume_fraction, "volume_fraction")
check_fraction(self.seed_fraction, "seed_fraction")
[docs]
def rates(self) -> tuple[float, float]:
if self.feed is not None:
return float(self.feed), float(self.kill)
return GRAY_SCOTT_PRESETS[self.pattern]
def _simulate(self, domain: Domain, rng, frames: int = 0):
feed, kill = self.rates()
# the pattern has a finite correlation length: a margin of 16 cells is enough
if self.lattice != "square":
tiling, cells = self._tiling(domain, 16, rng)
crop = self._frames_of(domain, tiling, frames)
else:
_, sim, crop = self._window(domain, 16)
attempts = 0
while True:
attempts += 1
record, callback = _recorder(self.steps, frames, crop, pick=lambda u, v: v)
options = {
"feed": feed,
"kill": kill,
"du": self.diffusion_u,
"dv": self.diffusion_v,
"steps": self.steps,
"seed_fraction": self.seed_fraction,
"callback": callback,
}
if self.lattice != "square":
_, v = gray_scott_tiling(tiling, rng, **options)
else:
_, v = gray_scott(sim, rng, periodic=True, **options)
if v.max() > 1e-3:
break
if attempts == MAX_ATTEMPTS:
raise ValueError(
f"reaction_diffusion: the activator died out {MAX_ATTEMPTS} times (F = "
f"{feed:g}, k = {kill:g}); use a lattice of at least 24 cells across "
"(smaller cell_size), or feed and kill rates that form patterns"
)
if self.lattice != "square":
crop = (tiling, cells)
return v, crop, feed, kill, attempts, record
[docs]
def generate(self, domain: Domain, seed: SeedLike = None) -> LatticeField:
rng, seed_info = make_rng(seed)
v, crop, feed, kill, attempts, _ = self._simulate(domain, rng)
attributes = {"steps": self.steps, "feed": feed, "kill": kill, "attempts": attempts}
if self.lattice != "square":
tiling, cells = crop
kept = slice(None) if cells is None else cells
v, volumes = v[kept], tiling.volumes[kept]
if self.volume_fraction is not None: # the cells of highest v, by volume
order = np.argsort(-v, kind="stable")
filled = np.cumsum(volumes[order]) / volumes.sum()
k = min(len(v) - 1, int(np.searchsorted(filled, self.volume_fraction)))
threshold = float(v[order[k]])
else:
threshold = float(self.threshold)
attributes["threshold"] = threshold
attributes["substeps"] = stable_substeps(tiling, self.diffusion_u, self.diffusion_v)
return TilingField(
domain, tiling, (v > threshold).astype(np.uint8), cells=cells, model=self,
seed=seed_info, attributes=attributes,
) # fmt: skip
v = v[crop].astype(np.float32) # the stored field: phases are thresholded on it
if self.volume_fraction is not None:
threshold = float(np.quantile(v, 1.0 - self.volume_fraction))
else:
threshold = float(self.threshold)
phases = (v > threshold).astype(np.uint8)
return LatticeField(
domain,
phases,
field=v,
threshold=threshold,
smoothing=self.smoothing,
model=self,
seed=seed_info,
attributes=attributes,
)