programdemos/nbody/nbody.xtl
N-body gravity with no loops. Every pair of bodies at once: the displacements of all pairs form a cube (2 x N x N, built by broadcasting with t_able), the cube gives every pair's softened inverse-square pull, and one reduce over the second body sums the pulls into each body's acceleration. A kick-drift-kick (leapfrog) step moves them all. Run it with "xetal run demos/nbody/nbody.xtl"; it prints the cube's shape, its x plane, the starting accelerations, the state after 50 steps, and the total momentum (which stays 0). The live page has four presets (the figure-eight, a binary star, a collapsing cluster, a Kepler ellipse) and lets you click a body for its row of the cube: https://softwarewrighter.github.io/X_eTaL-demos/nbody/
g : Float
g, eps2, dt, m, steps: G = 1, the softening (keeps close passes finite), the time step, the masses, and how many steps to run. The figure-eight starting masses: three equal, chasing each other round one curve (Chenciner and Montgomery's orbit).
g ← 1.0
n : Int
-- the bodies' masses, spread over every pair. n, mj: mj is N x N, row i column j holds m_j, the mass pulling on body i.
n ← t̲ally m
ᵘp̲lane : a -> a
u:p_lane a: a matrix as one plane of a rank-3 array, to stack planes.
ᵘp̲lane ← { a → (1 c̲at s̲hape a) r̲eshape a }
The cube: every pair's displacement, by broadcasting
ᵘc̲ube : Num a => a -> a
u:c_ube p: p is 2 x N, the x row and the y row. A table of differences gives x_i - x_j for every pair, N x N; the tables for x and y stack into a 2 x N x N cube.
ᵘc̲ube ← { p → x ← 1 s̲elect p y ← 2 s̲elect p (ᵘp̲lane x '− t̲able x) c̲at ᵘp̲lane y '− t̲able y }
The pull: softened inverse-square
ᵘp̲ull : Float -> Float
u:p_ull d: g m_j / (r^2 + eps2)^(3/2) for every pair: the inverse square, and one more 1 / r because the displacement in the cube has length r.
ᵘp̲ull ← { d → g × mj ÷ (('+ r̲/ d × d) + eps2) ^ 1.5 }
The reduction: sum over the second body
ᵘa̲cc : Float -> Float
u:a_cc p: each plane of the cube times the pull, summed along j (axis 3): the 2 x N accelerations. The diagonal, a body and itself, is 0 times its pull.
ᵘa̲cc ← { p → d ← ᵘc̲ube p w ← ᵘp̲ull d n̲eg '+ r̲/₃ d × (2 c̲at s̲hape w) r̲eshape w }
One step: kick, drift, kick
ᵘs̲tep : Float -> Float
u:s_tep s: the state s is 4 x N, the x and y rows, then the velocities' x and y rows.
ᵘs̲tep ← { s → p ← 2 t̲ake s h ← (2 d̲rop s) + (dt ÷ 2.0) × ᵘa̲cc p p1 ← p + dt × h p1 c̲at h + (dt ÷ 2.0) × ᵘa̲cc p1 }