What: from noise, one sweepOne pass of the for loop: a free period, two frames a third of a period apart, the comparison, the correction of , the average. at a time, until a frame slid by a third of the box matches the frame a third of a period earlier.
Why: that match is the rule the film obeys, so the program stops when the rule holds. Every line below has its own card: tap a line to go to it.
Try it: run the program one line at a time
def find_film(q, T=6.355, tol=1e-10): """Return one frame of the film, its period T, and the number of sweeps it took.""" q = (q + turn(q) + turn(turn(q))) / 3 # costs no time, so impose it once and it stays for sweep in range(1, 400): q = simulate(q, T) # one free period: what decays, decays third = simulate(q, T / 3) two_thirds = simulate(third, T / 3) lag = slide(third) - q # zero on the film if np.sqrt(np.mean(lag * lag)) < tol: return q, T, sweep # T is off by 3 x lag / speed. Move it gently, since at first it's all noise. speed = rate(q) T -= np.clip(3 * np.sum(lag * speed) / np.sum(speed * speed), -0.1, 0.1) # What obeys the rule survives the average; what ticks in unison cancels. q = (q + slide(third) + slide(slide(two_thirds))) / 3 raise RuntimeError('no convergence')
sweep 0 rms(lag) -noise seed 1
q
third
two_thirds
lag, black is zero
speed, black is zero
What one sweep costs, line by line
Almost all of it is simulation. Rate calls are per sweep at (the film's true period) with , seconds per sweep are one NumPy core (find-film-runs.json, block R15).
| Line | rate calls | Seconds |
|---|---|---|
q = simulate(q, T) | 1280 | 0.142 |
third = simulate(q, T / 3) | 428 | 0.047 |
two_thirds = simulate(third, T / 3) | 428 | 0.047 |
speed = rate(q) | 1 | |
lag = ..., the stop test, T -= ..., the average | 0 | each at most |
So a sweep simulates of time. The turn line runs once and costs s.
What a whole run does, over 200 seeds
Seeds 1-200, noise amplitude : the film 200 of 200, in 22 to 29 sweeps, median 26, or 43.3 periods of simulated time. The field's spread settles by sweep 7 (median), settles to within by sweep 7, and rms(lag) then falls faster than it will end up, as quicker modes die: 0.22 to 0.40 a sweep at sweeps 8 to 12 (seeds 1 to 120). From about sweep 15 it holds at 0.4288. That number, and a constant read from the run, set the sweep count (the card on both lines together).
Where the run lands on the loop depends on the seed, and nothing else does: the frame differs, does not (the card on return).
The cost of a run: 55519 rate calls (median), 7.6 s on one NumPy core. Source: find-film-runs.json, block R1: a separate timing from the table above, block R15, so the two need not multiply out.
This is the program itself, not a cartoon
Each button runs the real lines, in the JavaScript port this page already uses (twisted-average.mjs), and To the end takes the same sweeps as twisted_average.py. The listing above is cut from that file when the page is built, so it cannot drift from it.
Seed 1 here is the very draw of python3 twisted_average.py 1, carried as data, since a browser cannot draw NumPy's generator: it lands in 25 sweeps at , as the Python does (find-film-extra-lab.json). A test compares the two sweep by sweep. They part only at round-off, because the two languages add the six neighbours in a different order. New noise draws from a small generator in this page, the same bell curve but not NumPy's draw for that seed.
The colours of q, third and two_thirds stretch to their shared range at each step, stated under the panes: at first the field is nearly flat and on the film's range it would look blank. lag and speed show only, and each has its own scale, also stated.
Mathematica
(* The whole program, one line at a time. Evaluating this runs find_film from noise and records every line; the controls step through that record with the line that ran lit, and show q, third, twoThirds, lag, speed and rms(lag). About 2 s on an M5; New noise about 2 s more. Noise comes from Wolfram's generator, not NumPy's. *)
n = 36; box = 40.; (* a triangular mesh of n x n nodes, in a repeating box of this side *)
a = 1.; b = 2.3; (* the Brusselator's constants; both chemicals diffuse at rate 1 *)
dt = 0.02; (* the longest time step *)
(* How fast the chemicals q = {u, v} are changing: diffusion plus reaction. *)
laplacian[f_] := 2/(3 (box/n)^2) ListCorrelate[{{1, 1, 0}, {1, -6, 1}, {0, 1, 1}}, f, {2, 2}];
rate[{u_, v_}] := {laplacian[u] + a - (b + 1) u + u^2 v, laplacian[v] + b u - u^2 v};
(* Run time forward by t (fourth-order Runge-Kutta). *)
simulate[q0_, t_] := Module[{q = q0, steps = Ceiling[t/dt], h, k1, k2, k3, k4},
h = t/steps;
Do[
k1 = rate[q];
k2 = rate[q + h/2 k1];
k3 = rate[q + h/2 k2];
k4 = rate[q + h k3];
q += h/6 (k1 + 2 k2 + 2 k3 + k4),
{steps}];
q];
(* Slide the picture by a third of the box. On the film this costs T/3 of time. *)
slide[q_] := RotateLeft[q, {0, n/3, 2 n/3}];
(* Turn the picture 120 degrees about the origin. On the film this costs no time. *)
turn[q_] := Table[f[[Mod[x - y, n] + 1, Mod[-y, n] + 1]], {f, q}, {y, 0, n - 1}, {x, 0, n - 1}];
(* Start from the rest state plus white noise, and find the film. *)
rest = {ConstantArray[a, {n, n}], ConstantArray[b/a, {n, n}]};
noise[s_, amp_ : 0.1] := (SeedRandom[s]; rest + RandomVariate[NormalDistribution[0, amp], {2, n, n}]);
(* Four points a mesh step, linear on the mesh's own triangles, as the page paints: a turned field then draws as the turned picture. *)
meshTent = Table[Max[0., 1. - Max[Abs[i], Abs[j], Abs[i - j]]/4.], {j, -3, 3}, {i, -3, 3}];
meshFine[f_] := ListCorrelate[meshTent, KroneckerProduct[f, Normal[SparseArray[{{1, 1} -> 1.}, {4, 4}]]], {4, 4}];
(* A field on the plane, as a picture: the mesh's two axes are 120 degrees apart. Blue is lo, white is hi. *)
picture[u_, {lo_, hi_}, size_ : 240] := Colorize[
Quiet[ (* Wolfram 15's ImageTransformation trips on the notebook's light/dark background, harmlessly *)
ImageTransformation[Image[Rescale[Reverse[meshFine[u]], {lo, hi}]],
{#[[1]] + #[[2]]/Sqrt[3.], 2 #[[2]]/Sqrt[3.]}/box + 0.5/(4 n) &, {size, size},
DataRange -> {{0, 1}, {0, 1}}, PlotRange -> {{-40., 40.}, {-40., 40.}},
Padding -> "Periodic", Resampling -> "Linear"],
RemoveAlphaChannel::imginv],
ColorFunction -> (Blend[{RGBColor[0.118, 0.165, 0.51], RGBColor[0.251, 0.329, 0.808], RGBColor[0.588, 0.667, 0.941], RGBColor[0.961, 0.973, 1.]}, #] &), ColorFunctionScaling -> False];
(* find_film's own lines, with a mark after each: the listing line, what it did, and the field it wrote. *)
stRecord[s_] := Module[{q0 = noise[s], q, T = 6.355, tol = 1*^-10, third, twoThirds, lag, speed, sweepNo = 0, lags = {}, frames = {}, at = <||>, rows = {}, mark},
mark[line_, say_, pane_ : None, f_ : {}] := (
If[pane =!= None, AppendTo[frames, f[[1]]]; at[pane] = Length[frames]];
AppendTo[rows, <|"line" -> line, "say" -> say, "pane" -> pane, "sweep" -> sweepNo, "T" -> T, "lags" -> lags, "at" -> at|>]);
q = q0; mark[1, "The input: q is the rest state plus white noise, T is 6.355.", "q", q];
q = (q0 + turn[q0] + turn[turn[q0]])/3; mark[2, Row[{"Averaged with its two turns: rms(turn[q] - q) is now ", ScientificForm[RootMeanSquare[Flatten[turn[q] - q]], 2], "."}], "q", q];
Do[
sweepNo = sweep; mark[3, Row[{"Sweep ", sweep, " begins."}]];
q = simulate[q, T]; mark[4, Row[{"One free period of ", NumberForm[T, {5, 4}], "."}], "q", q];
third = simulate[q, T/3]; mark[5, "q run on by T/3.", "third", third];
twoThirds = simulate[third, T/3]; mark[6, "Run on by another T/3.", "twoThirds", twoThirds];
lag = slide[third] - q; AppendTo[lags, RootMeanSquare[Flatten[lag]]]; mark[8, "Slide third back by a third of the box and subtract q.", "lag", lag];
If[Last[lags] < tol, mark[9, Row[{"rms(lag) = ", ScientificForm[Last[lags], 2], " is below 1e-10: stop. Returned T = ", NumberForm[T, 11], " after ", sweep, " sweeps."}]]; Return[{frames, rows}, Module]];
mark[9, Row[{"rms(lag) = ", ScientificForm[Last[lags], 2], " is above 1e-10: go on."}]];
speed = rate[q]; mark[12, "speed is the field's rate of change at q.", "speed", speed];
T -= Clip[3 Total[lag speed, 3]/Total[speed speed, 3], {-0.1, 0.1}]; mark[13, Row[{"T moves to ", NumberForm[T, {5, 4}], "."}]];
q = (q + slide[third] + slide[slide[twoThirds]])/3; mark[16, "The three frames, slid back onto q and averaged: this is the next start.", "q", q],
{sweep, 399}];
{frames, rows}];
stRun[s_] := stRun[s] = stRecord[s];
stRun[1];
(* The listing as it runs: the core's findFilm, line for line. *)
stListing = {"findFilm[q0_, T0_ : 6.355, tol_ : 1*^-10] := Module[{q, T = T0, third, twoThirds, lag, speed},",
" q = (q0 + turn[q0] + turn[turn[q0]])/3; (* costs no time, so impose it once and it stays *)", " Do[",
" q = simulate[q, T]; (* one free period: what decays, decays *)", " third = simulate[q, T/3];", " twoThirds = simulate[third, T/3];", "",
" lag = slide[third] - q; (* zero on the film *)", " If[RootMeanSquare[Flatten[lag]] < tol, Return[{q, T, sweep}, Module]];", "",
" (* T is off by 3 x lag / speed. Move it gently, since at first it's all noise. *)", " speed = rate[q];", " T -= Clip[3 Total[lag speed, 3]/Total[speed speed, 3], {-0.1, 0.1}];", "",
" (* What obeys the rule survives the average; what ticks in unison cancels. *)", " q = (q + slide[third] + slide[slide[twoThirds]])/3,", " {sweep, 399}];", " $Failed];"};
(* |u| on the plane, black is zero, white is hi: the geometry of picture. *)
stSize[f_, hi_] := Quiet[ImageTransformation[Image[Clip[Abs[Reverse[meshFine[f]]]/hi, {0, 1}]], {#[[1]] + #[[2]]/Sqrt[3.], 2 #[[2]]/Sqrt[3.]}/box + 0.5/(4 n) &, {300, 300},
DataRange -> {{0, 1}, {0, 1}}, PlotRange -> {{-40., 40.}, {-40., 40.}}, Padding -> "Periodic", Resampling -> "Linear"], RemoveAlphaChannel::imginv];
(* One step of the record: the listing with its line lit, the five fields (orange frame: this line wrote it; grey: not written yet), and rms(lag) so far. *)
stView[s_, k_] := Module[{frames, r, field, lo, hi, pane},
{frames, r} = {stRun[s][[1]], stRun[s][[2, k]]};
field[name_] := If[KeyExistsQ[r["at"], name], frames[[r["at", name]]], None];
{lo, hi} = With[{m = MinMax[DeleteCases[field /@ {"q", "third", "twoThirds"}, None]]}, Mean[m] + {-1, 1} Max[0.02, m[[2]] - m[[1]]]/2];
pane[name_, draw_] := Labeled[Framed[Image[If[field[name] === None, ConstantImage[GrayLevel[0.9], {300, 300}], draw[field[name]]], ImageSize -> 150],
FrameMargins -> 0, FrameStyle -> Directive[Thickness[3], If[r["pane"] === name, Orange, White]]], Style[name, 12, FontFamily -> "Courier"], Top];
Column[{
Column[MapIndexed[Item[Style[If[#1 === "", " ", #1], 11, FontFamily -> "Courier"], Background -> If[First[#2] === r["line"], LightBlue, None]] &, stListing], Spacings -> 0, Alignment -> Left],
Row[{"sweep ", r["sweep"], " T ", NumberForm[r["T"], {5, 4}], " rms(lag) ", If[r["lags"] === {}, "-", ScientificForm[Last[r["lags"]], 2]], " noise seed ", s}],
r["say"],
Grid[{Join[pane[#, picture[#, {lo, hi}, 300] &] & /@ {"q", "third", "twoThirds"}, pane[#, stSize[#, Max[Abs[#]]] &] & /@ {"lag", "speed"}]}, Spacings -> 0.3],
Row[{"Colour: u from ", NumberForm[lo, {4, 3}], " to ", NumberForm[hi, {4, 3}], ". lag and speed show |u|, each on its own scale."}],
ListLogPlot[If[r["lags"] === {}, {{1, 1}}, r["lags"]], Joined -> True, PlotMarkers -> {Automatic, 5}, PlotStyle -> If[r["lags"] === {}, Opacity[0], Automatic],
PlotRange -> {{1, Max[30, Length[r["lags"]]]}, {1*^-11, 1}}, GridLines -> {{Max[1, r["sweep"]]}, None}, AxesLabel -> {"sweep", "rms(lag)"}, ImageSize -> 760, AspectRatio -> 1/5,
Epilog -> {Dashed, Gray, Line[{{1, Log[1*^-10]}, {Max[30, Length[r["lags"]]], Log[1*^-10]}}], Text["tol", {3, Log[1*^-10]}, {0, -1}]}]}, Spacings -> 1]];
Manipulate[
stView[seed, step],
{{seed, 1}, ControlType -> None},
{{step, 1}, ControlType -> None},
Dynamic[Row[{"Step through the run ", Manipulator[Dynamic[step], {1, Length[stRun[seed][[2]]], 1}, ImageSize -> 400], " ", Dynamic[step], " of ", Length[stRun[seed][[2]]]}]],
Row[{
Button["Next line", step = Min[step + 1, Length[stRun[seed][[2]]]]],
Button["Next sweep", step = First[Select[Range[step + 1, Length[stRun[seed][[2]]]], stRun[seed][[2, #, "line"]] === 16 &], Length[stRun[seed][[2]]]]],
Button["To the end", step = Length[stRun[seed][[2]]]],
Button["New noise", stRun[seed + 1]; step = 1; seed = seed + 1, Method -> "Queued"]}, " "],
SaveDefinitions -> True]






















Periodic windmill on 4*2
333, "very long period (~300,000 steps)"
U-gliders on 333
Ginzburg-Landau on 22x
Periodic pattern on 3222
Mazes on 443
Spirals on 543
Ginzburg-Landau on 732
Symmetric chaos on 632
Spinning worms on 333
Evolving maze on 632
Wigglers on 4*2
Spirals on 552
Ginzburg-Landau spirals on 533


















![Noise and its two turned copies with a ring on one bright spot, their average with all three rings, and turn[avg] - avg all black.](assets/mma-ff-turn-avg.webp)













![The change over a time step per unit time beside rate[q] and their difference, on the blue and grey scales, and the film's loop with both as arrows, with sliders for the step and the place on the film.](assets/mma-ff-speed.webp)











