sourcedemos/sandpile/sandpile.xtl
1⍝!/usr/bin/env xetal
2⍝# The abelian sandpile: drop grains on a grid; a cell with 4 or more
3⍝# grains topples, giving one to each of its four neighbors, and
4⍝# grains that fall off the edge are lost. Repeat until every cell
5⍝# has fewer than 4. The order of the topples does not matter (that
6⍝# is what abelian means), so every cell topples at once, as often as
7⍝# it can: one array expression a round. The stable pile is a
8⍝# fractal. Run it with "xetal run demos/sandpile/sandpile.xtl"; it
9⍝# prints whether the pile is stable, the grains left, the total
10⍝# topples, and the pile drawn with characters. The live page runs it
11⍝# round by round, colored by grains, and lets you drop more:
12⍝# https://softwarewrighter.github.io/X_eTaL-demos/sandpile/
13
14⍝# side, grains, rounds: the grid's side (the outer ring is the edge,
15⍝# where grains fall off), grains dropped at the center, rounds to run.
16side ← 21
17grains ← 300
18rounds ← 150
19
20⍝# -- the edge: a ring of cells that loses what it gets. row, col:
21⍝# each cell's position, by broadcasting. edge, inside: each cell's
22⍝# distance to the border, and whether it is inside (the ring has 0).
23row ← (o̲ffsets side) 'l̲eft t̲able o̲ffsets side
24col ← (o̲ffsets side) 'r̲ight t̲able o̲ffsets side
25edge ← row m̲in col m̲in ((side − 1) − row) m̲in (side − 1) − col
26inside ← 1 × edge > 0
27
28⍝## One round: every cell topples as often as it can
29
30⍝# u:t_opple h: q is how many times each cell topples: its grains over
31⍝# 4. It keeps h - 4 q and gets q from each of its four neighbors
32⍝# (four rotations, g); the edge is outside, so its grains fall off.
33ᵘt̲opple ← { h →
34 q ← h d̲iv 4
35 g ← (1 o̲-₁ q) + (-1 o̲-₁ q) + (1 o̲-₂ q) + -1 o̲-₂ q
36 inside × (h − 4 × q) + g
37}
38⍝# u:s_table h: whether no cell has 4 or more.
39ᵘs̲table ← { h → 1 × 4 > 'm̲ax r̲/₁₂ h }
40
41⍝## A round that also counts the topples
42
43⍝# u:p_lane m: a matrix as one plane of a rank-3 array, for stacking
44⍝# with c_at.
45⍝# u:s_tep s: the state s is two planes, the grains and how many times
46⍝# each cell has toppled so far (the avalanche's shape).
47ᵘp̲lane ← { m → (1 c̲at s̲hape m) r̲eshape m }
48ᵘs̲tep ← { s →
49 h ← 1 s̲elect s
50 (ᵘp̲lane ᵘt̲opple h) c̲at ᵘp̲lane (2 s̲elect s) + h d̲iv 4
51}
52⍝ -- end of the core -------------------------------------
53
54mid ← side d̲iv 2
55h0 ← grains × 1 × ((o̲ffsets side) 'l̲eft t̲able o̲ffsets side) = mid
56h0 ← h0 × 1 × ((o̲ffsets side) 'r̲ight t̲able o̲ffsets side) = mid
57s ← rounds 'ᵘs̲tep p̲ower (ᵘp̲lane h0) c̲at ᵘp̲lane 0 × h0
58h ← 1 s̲elect s
59⍝ Stable after the rounds (1), the grains left on the grid, and the
60⍝ topples there were.
61(ᵘs̲table h) c̲at ('+ r̲/₁₂ h) c̲at '+ r̲/₁₂ 2 s̲elect s
62⍝ The pile: blank for 0 grains, then . : # for 1, 2, 3.
63(1 + h) s̲elect " .:#"