sourcedemos/reaction-diffusion/reaction-diffusion.xtl
1⍝!/usr/bin/env xetal
2⍝# Reaction-diffusion (Gray-Scott): two chemicals U and V on a grid.
3⍝# U is fed in, V eats U to make more V (U + 2V -> 3V), V is removed,
4⍝# and both spread to their neighbors. Every step is a few array
5⍝# expressions over the whole grid: four shifted copies for the
6⍝# spreading, products for the reaction. The patterns (spots, mazes,
7⍝# coral) appear by themselves. Run it with "xetal run
8⍝# demos/reaction-diffusion/reaction-diffusion.xtl"; it prints the
9⍝# seeded grid's shape, a maze drawn with characters, and V's total
10⍝# (grown from the seed's 9.0). The live page runs it frame by frame
11⍝# and lets you click a cell for its neighbors and its update's
12⍝# arithmetic: https://softwarewrighter.github.io/X_eTaL-demos/reaction-diffusion/
13
14⍝## The settings
15
16⍝# n: the grid's side. du, dv: how fast U and V spread. f, k: the feed
17⍝# and kill rates (0.029, 0.057 gives a maze; coral is 0.0545, 0.062,
18⍝# ripples 0.022, 0.051, spots 0.035, 0.065, worms 0.046, 0.063).
19⍝# steps: how many to run.
20n ← 32
21du ← 0.2
22dv ← 0.1
23f ← 0.029
24k ← 0.057
25steps ← 1200
26
27⍝# A matrix as one plane of a rank-3 array (u:p_lane), for stacking
28⍝# U and V with c_at.
29ᵘp̲lane ← { m → (1 c̲at s̲hape m) r̲eshape m }
30
31⍝## The Laplacian: four shifted copies minus four times the center
32
33⍝# u:l_ap x: how much a cell differs from its four neighbors, up down
34⍝# left right (o_-_1, o_-_2), added and the center subtracted four
35⍝# times over (the edges wrap).
36ᵘl̲ap ← { x → ((1 o̲-₁ x) + (-1 o̲-₁ x) + (1 o̲-₂ x) + -1 o̲-₂ x) − 4.0 × x }
37
38⍝## One step for every cell at once
39
40⍝# u:s_tep s: the state s is two planes, U and V. Each spreads by its
41⍝# own rate times its Laplacian; u * v * v is where V meets U and
42⍝# turns U into V (the reaction); U is fed at rate f, V removed at
43⍝# rate f + k.
44ᵘs̲tep ← { s →
45 u ← 1 s̲elect s
46 v ← 2 s̲elect s
47 uvv ← u × v × v
48 (ᵘ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
49}
50⍝ -- end of the core ---------------------------------------------------
51
52⍝# sq, seed, s0: the start, U everywhere, a square of V off the center.
53sq ← ((o̲ffsets n) ≥ 10) ∧ (o̲ffsets n) < 16
54seed ← f̲loat sq '∧ t̲able sq
55s0 ← (ᵘp̲lane 1.0 − 0.5 × seed) c̲at ᵘp̲lane 0.25 × seed
56s̲hape s0
57
58⍝# s, v: the state after all the steps (function power), and V's
59⍝# plane; drawn with a character per cell by how much V it has.
60s ← steps 'ᵘs̲tep p̲ower s0
61v ← 2 s̲elect s
62(1 + f̲loor 4.99 × (v m̲in 0.399) ÷ 0.4) s̲elect " .:o@"
63
64⍝ The total of V, rounded: the pattern has grown from the seed's 9.0.
65(f̲loor 0.5 + 100 × '+ r̲/ r̲avel v) ÷ 100