programdemos/fourier-epicycles/fourier-epicycles.xtl
Fourier epicycles: any closed curve is a sum of circles turning at whole-number speeds. Its points z = x + i y go through a discrete Fourier transform, written as two matrix products with the cosines and sines of one outer product of angles; each frequency is a circle, and the circles, strongest first, chained end to end, trace the curve. A running sum along the chain gives, at once, the curve rebuilt from the first 1, 2, 3, ... circles. Run it with "xetal run demos/fourier-epicycles/fourier-epicycles.xtl"; it prints the strength of each frequency, the four strongest speeds, and the mean error rebuilt from 1, 2, 4, 8 and all 16 circles. The live page lets you pick or draw a curve and slides how many circles trace it: https://softwarewrighter.github.io/X_eTaL-demos/fourier-epicycles/
x : Float
x, y: the curve, a square of side 2, 16 points round its edge.
x ← 1.0 1.0 1.0 1.0 1.0 0.5 0.0 -0.5 -1.0 -1.0 -1.0 -1.0 -1.0 -0.5 0.0 0.5
y : Float
y ← -1.0 -0.5 0.0 0.5 1.0 1.0 1.0 1.0 1.0 0.5 0.0 -0.5 -1.0 -1.0 -1.0 -1.0
n : Int
-- the angles: one outer product. n: how many points. k: 0 .. n - 1. A, C, S: row k, column j of A is 2 pi k j / n, the angle of frequency k at sample j; C and S its cosine and sine.
n ← t̲ally x
The transform: two matrix products
re : Float
re, im, amp: Z_k = (1 / n) sum over j of z_j e^(-i A[k;j]), as real and imaginary parts: the cosines and sines times x and y (two matrix products, i_nner), then each frequency's strength.
re ← ((C '+ '× i̲nner x) + S '+ '× i̲nner y) ÷ f̲loat n
f : Float
f: each circle's speed: k, or k - n past the middle (turning the other way), so the circles stay small.
f ← k − f̲loat n × 1 × k ≥ f̲loat n d̲iv 2
The circles, strongest first
T : Float
T, zr, zi, vx, vy: circle c at time j (row j, column c): its vector Z e^(i f t_j), turned by its own speed and time.
T ← (2.0 × (p̲i @) ÷ f̲loat n) × k '× t̲able order s̲elect f
The chain: a running sum along the circles
cx : Float
cx, cy: column c is where the first c circles end at each time, so column c is the curve rebuilt from the c strongest circles.
cx ← '+ s̲\₂ vx
The error of each reconstruction
dx : Float
dx, dy, err: the mean distance from the curve, for 1, 2, ... n circles.
dx ← cx − x 'l̲eft t̲able k