programdemos/reaction-diffusion/reaction-diffusion.xtl

Reaction-diffusion (Gray-Scott): two chemicals U and V on a grid. U is fed in, V eats U to make more V (U + 2V -> 3V), V is removed, and both spread to their neighbors. Every step is a few array expressions over the whole grid: four shifted copies for the spreading, products for the reaction. The patterns (spots, mazes, coral) appear by themselves. Run it with "xetal run demos/reaction-diffusion/reaction-diffusion.xtl"; it prints the seeded grid's shape, a maze drawn with characters, and V's total (grown from the seed's 9.0). The live page runs it frame by frame and lets you click a cell for its neighbors and its update's arithmetic: https://softwarewrighter.github.io/X_eTaL-demos/reaction-diffusion/

source

The settings

n : Int

value · line 20

n: the grid's side. du, dv: how fast U and V spread. f, k: the feed and kill rates (0.029, 0.057 gives a maze; coral is 0.0545, 0.062, ripples 0.022, 0.051, spots 0.035, 0.065, worms 0.046, 0.063). steps: how many to run.

n ← 32
Used in: sq

du : Float

value · line 21
du ← 0.2
Used in: ᵘs̲tep

dv : Float

value · line 22
dv ← 0.1
Used in: ᵘs̲tep

f : Float

value · line 23
f ← 0.029
Used in: ᵘs̲tep

k : Float

value · line 24
k ← 0.057
Used in: ᵘs̲tep

steps : Int

value · line 25
steps ← 1200
Used in: s

ᵘp̲lane : a -> a

function · line 29

A matrix as one plane of a rank-3 array (u:p_lane), for stacking U and V with c_at.

ᵘp̲lane ← { m → (1 c̲at s̲hape m) r̲eshape m }
Used in: ᵘs̲tep, s0

The Laplacian: four shifted copies minus four times the center

ᵘl̲ap : Float -> Float

function · line 36

u:l_ap x: how much a cell differs from its four neighbors, up down left right (o_-_1, o_-_2), added and the center subtracted four times over (the edges wrap).

ᵘl̲ap ← { x → ((1 o̲-₁ x) + (-1 o̲-₁ x) + (1 o̲-₂ x) + -1 o̲-₂ x) − 4.0 × x }
Used in: ᵘs̲tep

One step for every cell at once

ᵘs̲tep : Float -> Float

function · line 44

u:s_tep s: the state s is two planes, U and V. Each spreads by its own rate times its Laplacian; u * v * v is where V meets U and turns U into V (the reaction); U is fed at rate f, V removed at rate f + k.

ᵘs̲tep ← { s →
  u ← 1 s̲elect s
  v ← 2 s̲elect s
  uvv ← u × v × v
  (ᵘp̲lane u + ((du × ᵘl̲ap u) − uvv) + f × 1.0 − u) c̲at ᵘp̲lane v + ((dv × ᵘl̲ap v) + uvv) − (f + k) × v
}
Used in: s

sq : Bool

value · line 53

sq, seed, s0: the start, U everywhere, a square of V off the center.

sq ← ((o̲ffsets n) ≥ 10) ∧ (o̲ffsets n) < 16
Used in: seed

seed : Float

value · line 54
seed ← f̲loat sq '∧ t̲able sq
Used in: s0

s0 : Float

value · line 55
s0 ← (ᵘp̲lane 1.0 − 0.5 × seed) c̲at ᵘp̲lane 0.25 × seed

s : Float

value · line 60

s, v: the state after all the steps (function power), and V's plane; drawn with a character per cell by how much V it has.

s ← steps 'ᵘs̲tep p̲ower s0
Used in: v

v : Float

value · line 61
v ← 2 s̲elect s