/ interactive_tutorials / hamiltonian_systems
Sign in
interactive_tutorials / hamiltonian_systems
hamiltonian_systems / app / main.js
2603 lines · 88.3 KBBlameHistoryRaw
1// Mass on a frictionless spring. Positions are in units of the maximum
2// swing drawn on screen, so q lies in [-1, 1].
4function color(name) {
5 return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
6}
8// Slides are laid out at 1920 x 1080 and the whole deck is scaled to fit the
9// window (see fitDeck below). Diagrams are drawn in units of DRAW_SCALE slide
10// pixels, so their geometry and fonts read well on a full-size slide.
11const DRAW_SCALE = 1.5;
12let deckScale = 1;
14// Size a canvas's backing store to its on-screen pixels (slide size x deck
15// scale x device pixel ratio) and return a context and size in drawing units.
16function prepare(canvas) {
17 const ctx = canvas.getContext('2d');
18 const k = deckScale * (window.devicePixelRatio || 1);
19 const bw = Math.max(1, Math.round(canvas.clientWidth * k));
20 const bh = Math.max(1, Math.round(canvas.clientHeight * k));
21 if (canvas.width !== bw || canvas.height !== bh) {
22 canvas.width = bw;
23 canvas.height = bh;
24 }
25 ctx.setTransform(k * DRAW_SCALE, 0, 0, k * DRAW_SCALE, 0, 0);
26 const w = canvas.clientWidth / DRAW_SCALE;
27 const h = canvas.clientHeight / DRAW_SCALE;
28 ctx.clearRect(0, 0, w, h);
29 return { ctx, w, h };
32// Horizontal layout shared by the spring diagram, the q0 slider and the phase plot,
33// so that a given q sits at the same x on all of them.
34function layout(w) {
35 const rest = w * 0.5;
36 const swing = Math.min(w * 0.3, 200);
37 return { rest, swing, qToX: (q) => rest + q * swing };
40// Wall, floor and a spring reaching a block centered at position q. drawBody
41// draws whatever is attached (it gets the scene geometry), before the
42// rest-position marker goes on top. Returns the geometry for labels.
43function drawSpringScene(ctx, w, h, q, drawBody) {
44 const fg = color('--fg');
45 const { rest, swing, qToX } = layout(w);
46 const wallX = 20;
47 const floorY = h * 0.62;
48 const box = 50;
49 const center = qToX(q);
50 const springY = floorY - box / 2;
52 // wall and floor
53 ctx.strokeStyle = fg;
54 ctx.lineWidth = 2;
55 ctx.beginPath();
56 ctx.moveTo(wallX, floorY - box * 1.6);
57 ctx.lineTo(wallX, floorY);
58 ctx.lineTo(w - 10, floorY);
59 ctx.stroke();
61 // spring (zig-zag)
62 const coils = 12;
63 const amp = 10;
64 const start = wallX;
65 const end = center - box / 2;
66 const lead = 12;
67 ctx.lineWidth = 1.5;
68 ctx.beginPath();
69 ctx.moveTo(start, springY);
70 ctx.lineTo(start + lead, springY);
71 const len = end - start - 2 * lead;
72 for (let i = 0; i < coils; i++) {
73 const sx = start + lead + ((i + 0.5) / coils) * len;
74 ctx.lineTo(sx, springY + (i % 2 ? amp : -amp));
75 }
76 ctx.lineTo(end - lead, springY);
77 ctx.lineTo(end, springY);
78 ctx.stroke();
80 const scene = { rest, swing, qToX, floorY, box, springY, amp, start, end, center };
81 drawBody(scene);
83 // rest position marker
84 ctx.strokeStyle = fg;
85 ctx.globalAlpha = 0.3;
86 ctx.setLineDash([4, 4]);
87 ctx.beginPath();
88 ctx.moveTo(rest, floorY - box * 1.4);
89 ctx.lineTo(rest, floorY + 34);
90 ctx.stroke();
91 ctx.setLineDash([]);
92 ctx.globalAlpha = 1;
93 return scene;
96// params: { k, m, q0, b }, read live so sliders can change them; the damping
97// coefficient b is optional (default 0, no damping).
98// labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw.
99// pScale: length of the p arrow per unit momentum, as a fraction of the swing;
100// by default the arrow peaks at the same length as q.
101function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) {
102 let q = params.q0;
103 let p = 0;
105 function step(dt) {
106 // velocity Verlet on dq/dt = p/m, dp/dt = -k q. Damping, dp/dt = -(b/m) p,
107 // is solved exactly and split around it (Strang splitting), so phase-space
108 // area shrinks at exactly the rate exp(-b t / m).
109 const { k, m, b = 0 } = params;
110 const decay = Math.exp((-0.5 * b * dt) / m);
111 p *= decay;
112 const f = -k * q;
113 q += (p / m) * dt + (0.5 * f / m) * dt * dt;
114 p += 0.5 * (f - k * q) * dt;
115 p *= decay;
116 }
118 function draw() {
119 if (!canvas.clientWidth) return;
120 const { ctx, w, h } = prepare(canvas);
122 const fg = color('--fg');
123 const { rest, swing, qToX, floorY, box, springY, amp, start, end, center } = drawSpringScene(ctx, w, h, q, (sc) => {
124 ctx.fillStyle = color('--accent');
125 ctx.fillRect(sc.center - sc.box / 2, sc.floorY - sc.box, sc.box, sc.box);
126 });
128 onDraw(q, p);
130 if (!labels.length) return;
132 ctx.font = 'italic 18px Georgia, serif';
133 ctx.textAlign = 'center';
135 if (labels.includes('m')) {
136 ctx.fillStyle = color('--bg');
137 ctx.textBaseline = 'middle';
138 ctx.fillText('m', center, floorY - box / 2);
139 }
140 if (labels.includes('k')) {
141 ctx.fillStyle = fg;
142 ctx.textBaseline = 'bottom';
143 ctx.fillText('k', (start + end) / 2, springY - amp - 4);
144 }
145 if (labels.includes('q0')) {
146 // where the block was let go from
147 const x0 = qToX(params.q0);
148 ctx.strokeStyle = fg;
149 ctx.globalAlpha = 0.5;
150 ctx.setLineDash([2, 3]);
151 ctx.beginPath();
152 ctx.moveTo(x0, floorY - box - 48);
153 ctx.lineTo(x0, floorY);
154 ctx.stroke();
155 ctx.setLineDash([]);
156 ctx.globalAlpha = 1;
157 ctx.fillStyle = fg;
158 ctx.textBaseline = 'bottom';
159 // the serif font has no subscript zero, so draw it smaller and lower
160 ctx.fillText('q', x0 - 4, floorY - box - 52);
161 ctx.font = 'italic 12px Georgia, serif';
162 ctx.fillText('0', x0 + 5, floorY - box - 48);
163 ctx.font = 'italic 18px Georgia, serif';
164 }
166 // q below the floor; F and p above the block
167 const { k, m } = params;
168 const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing;
169 if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below');
170 if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above');
171 if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above');
172 }
174 function setLabels(value) {
175 labels = value;
176 draw();
177 }
179 const loop = createLoop({ button, step, draw, speed });
181 // Back to being held at q0, at rest.
182 function reset() {
183 q = params.q0;
184 p = 0;
185 loop.reset();
186 }
188 return { draw, setLabels, reset, pause: loop.pause };
191// Animation driven by a Start / Stop / Continue button. speed is a number, or
192// a function read every frame so it can change while running.
193function createLoop({ button, step, draw, speed = 1 }) {
194 let running = false;
195 let lastTime = null;
196 let rafId = null;
198 function frame(t) {
199 if (!running) return;
200 if (lastTime !== null) {
201 const dt = (typeof speed === 'function' ? speed() : speed) * Math.min((t - lastTime) / 1000, 0.05);
202 const n = 4;
203 for (let i = 0; i < n; i++) step(dt / n);
204 }
205 lastTime = t;
206 draw();
207 rafId = requestAnimationFrame(frame);
208 }
210 function setRunning(value) {
211 running = value;
212 cancelAnimationFrame(rafId);
213 if (running) {
214 lastTime = null;
215 rafId = requestAnimationFrame(frame);
216 }
217 if (running || button.textContent !== 'Start') {
218 button.textContent = running ? 'Stop' : 'Continue';
219 }
220 }
222 button.addEventListener('click', () => setRunning(!running));
224 return {
225 pause: () => running && setRunning(false),
226 reset: () => {
227 setRunning(false);
228 button.textContent = 'Start';
229 draw();
230 },
231 };
234// Pendulum: a bob of mass m on a massless rod of length L, angle theta from
235// straight down, kept in [-pi, pi].
236// params: { m, L, g, theta0, p0 }, read live so sliders can change them.
237// labels: which of 'm', 'L', 'theta', 'p', 'g' to draw.
238// centered: put the pivot mid-canvas so the bob can go over the top; the rod
239// is then drawn to scale, with L = 1.2 (the slider's maximum) filling the canvas.
240// pScale: length of the p arrow in px per unit momentum; by default the arrow
241// peaks at 70px when let go from theta0 at rest.
242function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) {
243 let theta = params.theta0;
244 let p = params.p0;
246 function step(dt) {
247 // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta)
248 const { m, L, g } = params;
249 p -= 0.5 * dt * m * g * L * Math.sin(theta);
250 theta += dt * p / (m * L * L);
251 p -= 0.5 * dt * m * g * L * Math.sin(theta);
252 if (theta > Math.PI) theta -= 2 * Math.PI;
253 if (theta < -Math.PI) theta += 2 * Math.PI;
254 }
256 function draw() {
257 if (!canvas.clientWidth) return;
258 const { ctx, w, h } = prepare(canvas);
259 const fg = color('--fg');
260 const accent = color('--accent');
261 const { m, L, g } = params;
262 const px = w / 2;
263 const py = centered ? h / 2 : 30;
264 const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4);
265 const rod = centered ? maxRod * L / 1.2 : maxRod;
266 const bx = px + rod * Math.sin(theta);
267 const by = py + rod * Math.cos(theta);
268 const r = 18;
270 // ceiling (only when hanging from the top) and pivot
271 ctx.strokeStyle = fg;
272 ctx.lineWidth = 2;
273 if (!centered) {
274 ctx.beginPath();
275 ctx.moveTo(px - 50, py);
276 ctx.lineTo(px + 50, py);
277 ctx.stroke();
278 }
280 // vertical reference
281 ctx.globalAlpha = 0.3;
282 ctx.setLineDash([4, 4]);
283 ctx.beginPath();
284 ctx.moveTo(px, py);
285 ctx.lineTo(px, py + rod + r + 10);
286 ctx.stroke();
287 ctx.setLineDash([]);
288 ctx.globalAlpha = 1;
290 // rod and bob
291 ctx.lineWidth = 2;
292 ctx.beginPath();
293 ctx.moveTo(px, py);
294 ctx.lineTo(bx, by);
295 ctx.stroke();
296 ctx.fillStyle = fg;
297 ctx.beginPath();
298 ctx.arc(px, py, 4, 0, 2 * Math.PI);
299 ctx.fill();
300 ctx.fillStyle = accent;
301 ctx.beginPath();
302 ctx.arc(bx, by, r, 0, 2 * Math.PI);
303 ctx.fill();
305 onDraw(theta, p);
307 ctx.font = 'italic 18px Georgia, serif';
308 ctx.textAlign = 'center';
309 ctx.textBaseline = 'middle';
311 if (labels.includes('m')) {
312 ctx.fillStyle = color('--bg');
313 ctx.fillText('m', bx, by);
314 }
316 if (labels.includes('L')) {
317 // beside the middle of the rod, on the side away from the vertical
318 const side = theta >= 0 ? 1 : -1;
319 ctx.fillStyle = fg;
320 ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta));
321 }
323 if (labels.includes('theta')) {
324 // arc from the vertical to the rod
325 const arcR = Math.min(44, rod * 0.45);
326 ctx.strokeStyle = fg;
327 ctx.fillStyle = fg;
328 ctx.lineWidth = 1.5;
329 ctx.beginPath();
330 ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0);
331 ctx.stroke();
332 const mid = Math.PI / 2 - theta / 2;
333 ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid));
334 }
336 if (labels.includes('p')) {
337 // along the direction of motion, perpendicular to the rod
338 const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0)));
339 const len = p * (pScale ?? (peak ? 70 / peak : 0));
340 const tx = Math.cos(theta);
341 const ty = -Math.sin(theta);
342 const momentum = color('--momentum');
343 ctx.strokeStyle = momentum;
344 ctx.fillStyle = momentum;
345 ctx.lineWidth = 1.5;
346 ctx.beginPath();
347 ctx.moveTo(bx, by);
348 ctx.lineTo(bx + tx * len, by + ty * len);
349 ctx.stroke();
350 if (Math.abs(len) > 8) {
351 const d = Math.sign(len);
352 const ex = bx + tx * len;
353 const ey = by + ty * len;
354 ctx.beginPath();
355 ctx.moveTo(ex, ey);
356 ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx);
357 ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx);
358 ctx.closePath();
359 ctx.fill();
360 ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty);
361 }
362 }
364 if (labels.includes('g')) {
365 // gravity, pointing down, off to the side
366 const gx = Math.min(px + maxRod + 50, w - 20);
367 ctx.strokeStyle = fg;
368 ctx.fillStyle = fg;
369 ctx.lineWidth = 1.5;
370 ctx.beginPath();
371 ctx.moveTo(gx, py + 40);
372 ctx.lineTo(gx, py + 90);
373 ctx.stroke();
374 ctx.beginPath();
375 ctx.moveTo(gx, py + 90);
376 ctx.lineTo(gx - 4, py + 82);
377 ctx.lineTo(gx + 4, py + 82);
378 ctx.closePath();
379 ctx.fill();
380 ctx.fillText('g', gx + 14, py + 65);
381 }
382 }
384 const loop = createLoop({ button, step, draw });
386 function setLabels(value) {
387 labels = value;
388 draw();
389 }
391 // Back to the initial state, held still.
392 function reset() {
393 theta = params.theta0;
394 p = params.p0;
395 loop.reset();
396 }
398 return { draw, setLabels, reset, pause: loop.pause };
401function arrow(ctx, from, to, y, col, label, side) {
402 const dir = Math.sign(to - from);
403 ctx.strokeStyle = col;
404 ctx.fillStyle = col;
405 ctx.lineWidth = 1.5;
406 ctx.beginPath();
407 ctx.moveTo(from, y);
408 ctx.lineTo(to, y);
409 ctx.stroke();
410 if (Math.abs(to - from) > 8) {
411 ctx.beginPath();
412 ctx.moveTo(to, y);
413 ctx.lineTo(to - dir * 8, y - 4);
414 ctx.lineTo(to - dir * 8, y + 4);
415 ctx.closePath();
416 ctx.fill();
417 }
418 ctx.textBaseline = side === 'above' ? 'bottom' : 'top';
419 ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4);
422// Horizontal bars for kinetic, potential and total energy, scaled to the total.
423function drawEnergyBars(canvas, params, q, p) {
424 if (!canvas.clientWidth) return;
425 const { ctx, w } = prepare(canvas);
426 const { k, m, q0 } = params;
427 const kinetic = (p * p) / (2 * m);
428 const potential = 0.5 * k * q * q;
429 const total = 0.5 * k * q0 * q0;
431 const fg = color('--fg');
432 const kColor = color('--momentum');
433 const pColor = color('--potential');
434 const labelW = 90;
435 const barW = Math.min(w - labelW - 10, 400);
436 const left = Math.max(0, (w - labelW - barW) / 2);
437 const barX = left + labelW;
438 const rowH = 30;
439 const barH = 18;
441 ctx.font = `15px ${color('--font-body')}`;
442 ctx.textBaseline = 'middle';
443 ctx.textAlign = 'right';
445 const rows = [
446 ['Kinetic', [[kinetic, kColor]]],
447 ['Potential', [[potential, pColor]]],
448 ['Total', [[kinetic, kColor], [potential, pColor]]],
449 ];
450 rows.forEach(([label, segments], i) => {
451 const y = 10 + i * rowH;
452 ctx.fillStyle = fg;
453 ctx.fillText(label, barX - 12, y + barH / 2);
455 // outline at full scale, then filled segments
456 ctx.strokeStyle = fg;
457 ctx.globalAlpha = 0.25;
458 ctx.lineWidth = 1;
459 ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH);
460 ctx.globalAlpha = 1;
461 let sx = barX;
462 for (const [value, col] of segments) {
463 const sw = Math.min(value / total, 1) * barW;
464 ctx.fillStyle = col;
465 ctx.fillRect(sx, y, sw, barH);
466 sx += sw;
467 }
468 });
471// Phase plot: q horizontal (lined up with the spring diagram), p vertical.
472// The axes are fixed so changing k and m visibly reshapes the orbit.
473const pMax = 3;
475// Draw the q and p axes; returns the mapping from (q, p) to canvas coordinates.
476function springAxes(ctx, w, h) {
477 const { rest, swing, qToX } = layout(w);
478 const mid = h / 2;
479 const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
480 const fg = color('--fg');
481 ctx.strokeStyle = fg;
482 ctx.fillStyle = fg;
483 ctx.globalAlpha = 0.5;
484 ctx.lineWidth = 1;
485 ctx.beginPath();
486 ctx.moveTo(rest - swing - 20, mid);
487 ctx.lineTo(rest + swing + 20, mid);
488 ctx.moveTo(rest, 8);
489 ctx.lineTo(rest, h - 8);
490 ctx.stroke();
491 ctx.globalAlpha = 1;
492 ctx.font = 'italic 18px Georgia, serif';
493 ctx.textAlign = 'left';
494 ctx.textBaseline = 'middle';
495 ctx.fillText('q', rest + swing + 26, mid);
496 ctx.textBaseline = 'top';
497 ctx.fillText('p', rest + 8, 6);
498 return { rest, swing, mid, qToX, pToY };
501function drawPhase(canvas, params, trail, q, p) {
502 if (!canvas.clientWidth) return;
503 const { ctx, w, h } = prepare(canvas);
504 const { rest, swing, mid, qToX, pToY } = springAxes(ctx, w, h);
505 const fg = color('--fg');
506 const accent = color('--accent');
508 // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m)
509 const { k, m, q0 } = params;
510 const rx = Math.abs(q0) * swing;
511 const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid);
512 ctx.strokeStyle = fg;
513 ctx.globalAlpha = 0.35;
514 ctx.setLineDash([4, 4]);
515 ctx.beginPath();
516 ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI);
517 ctx.stroke();
518 ctx.setLineDash([]);
519 ctx.globalAlpha = 1;
521 // trail, then the current state
522 ctx.strokeStyle = accent;
523 ctx.lineWidth = 2;
524 ctx.beginPath();
525 trail.forEach(([tq, tp], i) => {
526 if (i === 0) ctx.moveTo(qToX(tq), pToY(tp));
527 else ctx.lineTo(qToX(tq), pToY(tp));
528 });
529 ctx.stroke();
530 ctx.fillStyle = accent;
531 ctx.beginPath();
532 ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI);
533 ctx.fill();
536// Page 1: the spring and its equations of motion
537const springParams = { k: 6.25, m: 1, q0: 0.6 };
538const spring = createSpring({
539 canvas: document.getElementById('spring-canvas'),
540 button: document.getElementById('spring-toggle'),
541 params: springParams,
542});
544// Page 2: the same spring, with energy bars. Slower and without the arrows,
545// so the moving bars are the only thing to watch.
546const energyBars = document.getElementById('energy-bars');
547const energy = createSpring({
548 canvas: document.getElementById('energy-canvas'),
549 button: document.getElementById('energy-toggle'),
550 params: springParams,
551 speed: 0.5,
552 onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p),
553});
555// The spring in phase space, with a slider for each of the named params.
556// Elements are found by id: `${id}-canvas`, `${id}-plot`, `${id}-${name}`.
557// Reset clears the trail as well.
558function createSpringPhase({ id, params, names }) {
559 const canvas = document.getElementById(`${id}-canvas`);
560 const plot = document.getElementById(`${id}-plot`);
561 const q0Slider = document.getElementById(`${id}-q0`);
562 let trail = [];
563 const sim = createSpring({
564 canvas,
565 button: document.getElementById(`${id}-toggle`),
566 params,
567 labels: ['q', 'p', 'k', 'q0'],
568 pScale: 1 / pMax,
569 onDraw: (q, p) => {
570 trail.push([q, p]);
571 if (trail.length > 2000) trail.shift();
572 drawPhase(plot, params, trail, q, p);
573 alignSlider();
574 },
575 });
577 // Stretch the q0 slider so its thumb sits directly under q0 on the diagram.
578 // The thumb is 30 slide pixels wide (style.css).
579 function alignSlider() {
580 const { rest, swing } = layout(canvas.clientWidth / DRAW_SCALE);
581 const thumb = 30;
582 q0Slider.style.width = `${2 * swing * DRAW_SCALE + thumb}px`;
583 q0Slider.style.marginLeft = `${(rest - swing) * DRAW_SCALE - thumb / 2}px`;
584 }
586 function reset() {
587 trail = [];
588 sim.reset();
589 }
591 for (const name of names) {
592 const input = document.getElementById(`${id}-${name}`);
593 const output = document.getElementById(`${id}-${name}-value`);
594 input.value = params[name];
595 output.textContent = params[name];
596 input.addEventListener('input', () => {
597 params[name] = Number(input.value);
598 output.textContent = input.value;
599 reset();
600 });
601 }
603 return { ...sim, reset };
606// Page 4: phase space, with adjustable q0, k and m
607const phase = createSpringPhase({ id: 'phase', params: { k: 4, m: 1, q0: 0.6 }, names: ['q0', 'k', 'm'] });
609// Page 5: the pendulum
610const pendulum = createPendulum({
611 canvas: document.getElementById('pendulum-canvas'),
612 button: document.getElementById('pendulum-toggle'),
613 params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 },
614});
616// Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at
617// +/- pendulumPMax. The separatrix peaks at p = 2 m L sqrt(g L), and the m, L
618// and g slider ranges keep that under 12 even at their maximums.
619const pendulumPMax = 12;
620const pendulumDefaults = { m: 1, L: 1, g: 9.8 };
621const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 };
622const pendulumPresets = {
623 small: { theta0: 0.3, p0: 0 },
624 large: { theta0: 2.5, p0: 0 },
625 top: { theta0: 3.1, p0: 0 },
626 rotation: { theta0: 0, p0: 8 },
627 balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds
628 rest: { theta0: 0, p0: 0 },
629};
630const pendulumPlot = document.getElementById('pendulum-plot');
631let pendulumTrail = [];
632const pendulumPhase = createPendulum({
633 canvas: document.getElementById('pendulum-phase-canvas'),
634 button: document.getElementById('pendulum-phase-toggle'),
635 params: pendulumParams,
636 labels: ['theta', 'p'],
637 centered: true,
638 pScale: 60 / pendulumPMax,
639 onDraw: (theta, p) => {
640 pendulumTrail.push([theta, p]);
641 if (pendulumTrail.length > 3000) pendulumTrail.shift();
642 drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p);
643 },
644});
646// Draw the pendulum phase portrait (level curves of H) and the theta and p
647// axes; returns the mapping from (theta, p) to canvas coordinates.
648function pendulumAxes(ctx, w, h, params) {
649 const { m, L, g } = params;
650 const halfW = Math.min(w / 2 - 30, 300);
651 const cx = w / 2;
652 const mid = h / 2;
653 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
654 const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16);
655 const fg = color('--fg');
657 ctx.save();
658 ctx.beginPath();
659 ctx.rect(cx - halfW, 0, 2 * halfW, h);
660 ctx.clip();
661 // background phase portrait: level curves of H, in units of m g L.
662 // Level 1 is the separatrix between swinging and rotating.
663 const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4];
664 const n = 300;
665 for (const c of levels) {
666 ctx.strokeStyle = fg;
667 ctx.globalAlpha = c === 1 ? 0.45 : 0.15;
668 ctx.lineWidth = c === 1 ? 1.5 : 1;
669 for (const sign of [1, -1]) {
670 ctx.beginPath();
671 let drawing = false;
672 for (let i = 0; i <= n; i++) {
673 const t = -Math.PI + (2 * Math.PI * i) / n;
674 // p^2 / (2 m L^2) - m g L cos(t) = c m g L
675 const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t));
676 if (p2 < 0) { drawing = false; continue; }
677 const x = thetaToX(t);
678 const y = pToY(sign * Math.sqrt(p2));
679 if (drawing) ctx.lineTo(x, y);
680 else ctx.moveTo(x, y);
681 drawing = true;
682 }
683 ctx.stroke();
684 }
685 }
686 ctx.globalAlpha = 1;
688 ctx.restore();
690 // axes
691 ctx.strokeStyle = fg;
692 ctx.fillStyle = fg;
693 ctx.globalAlpha = 0.5;
694 ctx.lineWidth = 1;
695 ctx.beginPath();
696 ctx.moveTo(cx - halfW, mid);
697 ctx.lineTo(cx + halfW, mid);
698 ctx.moveTo(cx, 8);
699 ctx.lineTo(cx, h - 8);
700 ctx.stroke();
701 ctx.globalAlpha = 1;
702 ctx.font = 'italic 18px Georgia, serif';
703 ctx.textBaseline = 'middle';
704 ctx.textAlign = 'left';
705 ctx.fillText('θ', cx + halfW + 6, mid);
706 ctx.textBaseline = 'top';
707 ctx.fillText('p', cx + 8, 6);
708 ctx.font = `13px ${color('--font-body')}`;
709 ctx.textAlign = 'center';
710 ctx.fillText('−π', cx - halfW, mid + 6);
711 ctx.fillText('π', cx + halfW, mid + 6);
712 return { thetaToX, pToY };
715function drawPendulumPhase(canvas, params, trail, theta, p) {
716 if (!canvas.clientWidth) return;
717 const { ctx, w, h } = prepare(canvas);
718 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, params);
719 const accent = color('--accent');
721 // trail, broken where theta wraps around
722 ctx.strokeStyle = accent;
723 ctx.lineWidth = 2;
724 ctx.beginPath();
725 trail.forEach(([tt, tp], i) => {
726 const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI;
727 if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp));
728 else ctx.lineTo(thetaToX(tt), pToY(tp));
729 });
730 ctx.stroke();
731 ctx.fillStyle = accent;
732 ctx.beginPath();
733 ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI);
734 ctx.fill();
737const pendulumPreset = document.getElementById('pendulum-preset');
738const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({
739 name,
740 input: document.getElementById(`pendulum-${name}`),
741 output: document.getElementById(`pendulum-${name}-value`),
742}));
744function syncPendulumInputs() {
745 for (const { name, input, output } of pendulumInputs) {
746 input.value = pendulumParams[name];
747 output.textContent = pendulumParams[name].toFixed(2);
748 }
751function resetPendulumPhase() {
752 pendulumTrail = [];
753 pendulumPhase.reset();
756for (const { name, input, output } of pendulumInputs) {
757 input.addEventListener('input', () => {
758 pendulumParams[name] = Number(input.value);
759 output.textContent = pendulumParams[name].toFixed(2);
760 pendulumPreset.value = 'custom';
761 resetPendulumPhase();
762 });
765// A preset restores the default m, L and g along with its initial state.
766pendulumPreset.addEventListener('change', () => {
767 const preset = pendulumPresets[pendulumPreset.value];
768 if (!preset) return;
769 Object.assign(pendulumParams, pendulumDefaults, preset);
770 syncPendulumInputs();
771 resetPendulumPhase();
772});
773syncPendulumInputs();
775// Liouville's theorem: a disk of starting points evolves under the flow, and
776// the area enclosed by its boundary stays constant.
777// force(q) gives dp/dt; m is the mass term in dq/dt = p / m.
778// center and radii set the disk in (q, p); the single simulation started from
779// the center is evolved alongside it. drawDiagram(ctx, w, h, points, jitter,
780// central) and axes(ctx, w, h) draw the physical picture and the phase-plane axes.
781function createLiouville({ id, force, m, center, radii, drawDiagram, axes }) {
782 const canvas = document.getElementById(`${id}-canvas`);
783 const diagram = document.getElementById(`${id}-diagram`);
784 const areaOut = document.getElementById(`${id}-area`);
785 const [rq, rp] = radii;
786 // a fine boundary, so the area stays accurate as the disk stretches
787 const nb = 2000;
788 let boundary;
789 let interior;
790 let jitter;
791 let central;
793 function makeDisk() {
794 central = [center[0], center[1]];
795 boundary = [];
796 for (let i = 0; i < nb; i++) {
797 const a = (2 * Math.PI * i) / nb;
798 boundary.push([center[0] + rq * Math.cos(a), center[1] + rp * Math.sin(a)]);
799 }
800 interior = [];
801 while (interior.length < 600) {
802 const u = 2 * Math.random() - 1;
803 const v = 2 * Math.random() - 1;
804 if (u * u + v * v <= 1) interior.push([center[0] + rq * u, center[1] + rp * v]);
805 }
806 // each point gets a fixed random offset on the diagram, so they form a cloud
807 jitter = interior.map(() => Math.random());
808 }
809 makeDisk();
811 function step(dt) {
812 // leapfrog on dq/dt = p / m, dp/dt = force(q), for every point
813 for (const pts of [boundary, interior, [central]]) {
814 for (const pt of pts) {
815 pt[1] += 0.5 * dt * force(pt[0]);
816 pt[0] += dt * pt[1] / m;
817 pt[1] += 0.5 * dt * force(pt[0]);
818 }
819 }
820 }
822 // shoelace formula on the boundary polygon
823 function area() {
824 let a = 0;
825 for (let i = 0; i < nb; i++) {
826 const [q1, p1] = boundary[i];
827 const [q2, p2] = boundary[(i + 1) % nb];
828 a += q1 * p2 - q2 * p1;
829 }
830 return Math.abs(a) / 2;
831 }
833 function draw() {
834 if (!canvas.clientWidth) return;
835 const d = prepare(diagram);
836 drawDiagram(d.ctx, d.w, d.h, interior, jitter, central);
838 const { ctx, w, h } = prepare(canvas);
839 const { toX, toY } = axes(ctx, w, h);
840 const accent = color('--accent');
841 ctx.fillStyle = accent;
842 ctx.globalAlpha = 0.15;
843 ctx.beginPath();
844 boundary.forEach(([q, p], i) => (i ? ctx.lineTo(toX(q), toY(p)) : ctx.moveTo(toX(q), toY(p))));
845 ctx.closePath();
846 ctx.fill();
847 ctx.globalAlpha = 1;
848 ctx.strokeStyle = accent;
849 ctx.lineWidth = 1.5;
850 ctx.stroke();
851 for (const [q, p] of interior) ctx.fillRect(toX(q) - 1, toY(p) - 1, 2, 2);
853 areaOut.textContent = area().toFixed(4);
854 }
856 const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 });
858 function reset() {
859 makeDisk();
860 loop.reset();
861 }
863 return { draw, reset, pause: loop.pause };
866// Page 7: the spring, with every block drawn as a point and the spring
867// reaching the block simulated from the disk's center. The disk's radii look
868// round at the default scale.
869const liouvilleSpringK = 4;
870const liouville = createLiouville({
871 id: 'liouville',
872 force: (q) => -liouvilleSpringK * q,
873 m: 1,
874 center: [0.5, 0],
875 radii: [0.15, 0.6],
876 drawDiagram: (ctx, w, h, points, jitter, [centralQ]) => {
877 drawSpringScene(ctx, w, h, centralQ, ({ qToX, floorY, box }) => {
878 ctx.fillStyle = color('--accent');
879 points.forEach(([q], i) => ctx.fillRect(qToX(q) - 1, floorY - 4 - jitter[i] * (box - 8), 2, 2));
880 });
881 },
882 axes: (ctx, w, h) => {
883 const { qToX, pToY } = springAxes(ctx, w, h);
884 return { toX: qToX, toY: pToY };
885 },
886});
888// Page 8: the pendulum, with every bob drawn as a point and the rod pointing
889// at the bob simulated from the disk's center. With m = L = 1, p = dtheta/dt.
890const liouvillePendulumParams = { m: 1, L: 1, g: 9.8 };
891const liouvillePendulum = createLiouville({
892 id: 'liouville-pendulum',
893 force: (theta) => -liouvillePendulumParams.g * Math.sin(theta),
894 m: 1,
895 center: [1.2, 0],
896 radii: [0.35, 3.5],
897 drawDiagram: (ctx, w, h, points, jitter, [centralTheta]) => {
898 const fg = color('--fg');
899 const px = w / 2;
900 const py = 30;
901 const rod = Math.min(h - 80, w * 0.4);
903 ctx.strokeStyle = fg;
904 ctx.lineWidth = 2;
905 ctx.beginPath();
906 ctx.moveTo(px - 50, py);
907 ctx.lineTo(px + 50, py);
908 ctx.stroke();
909 ctx.globalAlpha = 0.3;
910 ctx.setLineDash([4, 4]);
911 ctx.beginPath();
912 ctx.moveTo(px, py);
913 ctx.lineTo(px, py + rod + 28);
914 ctx.stroke();
915 ctx.setLineDash([]);
916 ctx.globalAlpha = 1;
917 ctx.beginPath();
918 ctx.moveTo(px, py);
919 ctx.lineTo(px + (rod - 18) * Math.sin(centralTheta), py + (rod - 18) * Math.cos(centralTheta));
920 ctx.stroke();
922 ctx.fillStyle = color('--accent');
923 points.forEach(([theta], i) => {
924 const r = rod + (jitter[i] - 0.5) * 30;
925 ctx.fillRect(px + r * Math.sin(theta) - 1, py + r * Math.cos(theta) - 1, 2, 2);
926 });
927 },
928 axes: (ctx, w, h) => {
929 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, liouvillePendulumParams);
930 return { toX: thetaToX, toY: pToY };
931 },
932});
934// Page 9: the spring in phase space again, with damping
935const damped = createSpringPhase({ id: 'damped', params: { k: 4, m: 1, q0: 0.6, b: 0.3 }, names: ['q0', 'k', 'm', 'b'] });
937// Double pendulum: rod angles theta1, theta2 from straight down and their
938// momenta p1, p2, as the state z = [theta1, theta2, p1, p2].
939// params: { m1, m2, L1, L2, g } plus the initial state { theta1, theta2, p1, p2 }.
941function doubleKinetic({ m1, m2, L1, L2 }, delta, p1, p2) {
942 const D = m1 + m2 * Math.sin(delta) ** 2;
943 return (m2 * L2 * L2 * p1 * p1 + (m1 + m2) * L1 * L1 * p2 * p2 - 2 * m2 * L1 * L2 * p1 * p2 * Math.cos(delta))
944 / (2 * m2 * L1 * L1 * L2 * L2 * D);
947function doublePotential({ m1, m2, L1, L2, g }, t1, t2) {
948 return -(m1 + m2) * g * L1 * Math.cos(t1) - m2 * g * L2 * Math.cos(t2);
951function doubleEnergy(params, [t1, t2, p1, p2]) {
952 return doubleKinetic(params, t1 - t2, p1, p2) + doublePotential(params, t1, t2);
955// Hamilton's equations, as written in the recipe: the rates of change of
956// (theta1, theta2, p1, p2), written into out.
957function doubleRates(params, t1, t2, p1, p2, out) {
958 const { m1, m2, L1, L2, g } = params;
959 const delta = t1 - t2;
960 const s = Math.sin(delta);
961 const c = Math.cos(delta);
962 const D = m1 + m2 * s * s;
963 // T as in doubleKinetic, and sin(2 delta) = 2 s c, reusing s and c: this is
964 // the inner loop of every double pendulum simulation
965 const T = (m2 * L2 * L2 * p1 * p1 + (m1 + m2) * L1 * L1 * p2 * p2 - 2 * m2 * L1 * L2 * p1 * p2 * c)
966 / (2 * m2 * L1 * L1 * L2 * L2 * D);
967 const dTdDelta = (p1 * p2 * s / (L1 * L2) - 2 * m2 * T * s * c) / D;
968 out[0] = (L2 * p1 - L1 * p2 * c) / (L1 * L1 * L2 * D);
969 out[1] = ((m1 + m2) * L1 * p2 - m2 * L2 * p1 * c) / (m2 * L1 * L2 * L2 * D);
970 out[2] = -(m1 + m2) * g * L1 * Math.sin(t1) - dTdDelta;
971 out[3] = -m2 * g * L2 * Math.sin(t2) + dTdDelta;
974// One step of the implicit midpoint rule, z' = z + h f((z + z') / 2), solved by
975// fixed-point iteration, updating z in place. It is symplectic, and unlike
976// leapfrog it does not need H to split into a kinetic part in p and a
977// potential part in q (here the kinetic energy depends on the angles too).
978// Allocation-free, since the Liouville slide steps hundreds of these per frame.
979const doubleRate = [0, 0, 0, 0];
980function doubleStep(params, z, h) {
981 const [t1, t2, p1, p2] = z;
982 let a1 = t1;
983 let a2 = t2;
984 let b1 = p1;
985 let b2 = p2;
986 for (let it = 0; it < 20; it++) {
987 doubleRates(params, 0.5 * (t1 + a1), 0.5 * (t2 + a2), 0.5 * (p1 + b1), 0.5 * (p2 + b2), doubleRate);
988 const n1 = t1 + h * doubleRate[0];
989 const n2 = t2 + h * doubleRate[1];
990 const n3 = p1 + h * doubleRate[2];
991 const n4 = p2 + h * doubleRate[3];
992 const change = Math.max(Math.abs(n1 - a1), Math.abs(n2 - a2), Math.abs(n3 - b1), Math.abs(n4 - b2));
993 a1 = n1;
994 a2 = n2;
995 b1 = n3;
996 b2 = n4;
997 if (change < 1e-12) break;
998 }
999 z[0] = wrapAngle(a1);
1000 z[1] = wrapAngle(a2);
1001 z[2] = b1;
1002 z[3] = b2;
1005// One step of the 2-stage Gauss-Legendre method. The implicit midpoint rule
1006// above is the 1-stage member of this family; this one is also symplectic but
1007// of order 4, so for the same accuracy it can take steps several times
1008// longer. Its two stage slopes, k[0..3] and k[4..7], are solved by fixed-point
1009// iteration starting from the previous step's, so each trajectory keeps its
1010// own k (fill it with the rates at the starting state).
1011const GAUSS_A12 = 0.25 - Math.sqrt(3) / 6;
1012const GAUSS_A21 = 0.25 + Math.sqrt(3) / 6;
1013const gaussRate1 = [0, 0, 0, 0];
1014const gaussRate2 = [0, 0, 0, 0];
1015function gaussStep(params, z, h, k) {
1016 for (let it = 0; it < 30; it++) {
1017 doubleRates(params,
1018 z[0] + h * (0.25 * k[0] + GAUSS_A12 * k[4]), z[1] + h * (0.25 * k[1] + GAUSS_A12 * k[5]),
1019 z[2] + h * (0.25 * k[2] + GAUSS_A12 * k[6]), z[3] + h * (0.25 * k[3] + GAUSS_A12 * k[7]), gaussRate1);
1020 doubleRates(params,
1021 z[0] + h * (GAUSS_A21 * k[0] + 0.25 * k[4]), z[1] + h * (GAUSS_A21 * k[1] + 0.25 * k[5]),
1022 z[2] + h * (GAUSS_A21 * k[2] + 0.25 * k[6]), z[3] + h * (GAUSS_A21 * k[3] + 0.25 * k[7]), gaussRate2);
1023 let change = 0;
1024 for (let i = 0; i < 4; i++) {
1025 change = Math.max(change, Math.abs(gaussRate1[i] - k[i]), Math.abs(gaussRate2[i] - k[i + 4]));
1026 k[i] = gaussRate1[i];
1027 k[i + 4] = gaussRate2[i];
1029 if (change * h < 1e-10) break;
1031 for (let i = 0; i < 4; i++) z[i] += 0.5 * h * (k[i] + k[i + 4]);
1032 z[0] = wrapAngle(z[0]);
1033 z[1] = wrapAngle(z[1]);
1036// Where a step of length h from state a to state b crosses theta1 = 0 (theta1
1037// increasing), by cubic Hermite interpolation with the rates at both ends,
1038// which stays accurate for long steps; returns [theta2, p2] there.
1039const hermiteA = [0, 0, 0, 0];
1040const hermiteB = [0, 0, 0, 0];
1041function sectionCrossing(params, a, b, h) {
1042 doubleRates(params, a[0], a[1], a[2], a[3], hermiteA);
1043 doubleRates(params, b[0], b[1], b[2], b[3], hermiteB);
1044 const end = (i) => (i === 1 ? a[1] + wrapAngle(b[1] - a[1]) : b[i]);
1045 const at = (i, s) => {
1046 const s2 = s * s;
1047 const s3 = s2 * s;
1048 return (2 * s3 - 3 * s2 + 1) * a[i] + (s3 - 2 * s2 + s) * h * hermiteA[i]
1049 + (3 * s2 - 2 * s3) * end(i) + (s3 - s2) * h * hermiteB[i];
1050 };
1051 let lo = 0;
1052 let hi = 1;
1053 for (let it = 0; it < 30; it++) {
1054 const m = 0.5 * (lo + hi);
1055 if (at(0, m) < 0) lo = m;
1056 else hi = m;
1058 const s = 0.5 * (lo + hi);
1059 return [wrapAngle(at(1, s)), at(3, s)];
1062function wrapAngle(t) {
1063 return t - 2 * Math.PI * Math.round(t / (2 * Math.PI));
1066function doubleInitial({ theta1, theta2, p1, p2 }) {
1067 return [theta1, theta2, p1, p2];
1070// A label with a subscript, e.g. m with 1, centered at (x, y). The serif font
1071// has no subscript digits, so the digit is drawn smaller and lower.
1072function subText(ctx, base, sub, x, y) {
1073 const font = 'italic 18px Georgia, serif';
1074 const small = 'italic 12px Georgia, serif';
1075 ctx.font = font;
1076 const bw = ctx.measureText(base).width;
1077 ctx.font = small;
1078 const sw = ctx.measureText(sub).width;
1079 const left = x - (bw + sw + 1) / 2;
1080 const align = ctx.textAlign;
1081 ctx.textAlign = 'left';
1082 ctx.font = font;
1083 ctx.fillText(base, left, y);
1084 ctx.font = small;
1085 ctx.fillText(sub, left + bw + 1, y + 5);
1086 ctx.font = font;
1087 ctx.textAlign = align;
1090// L1 + L2 at the slider maximums. The rods are drawn to scale, with a total
1091// length of maxLength reaching from the pivot (mid-canvas) to the edge, so
1092// either bob can go over the top.
1093const DOUBLE_REACH = 2.5;
1095// labels: which of 'm', 'L', 'theta', 'g' to draw.
1096function drawDoublePendulum(ctx, w, h, params, [t1, t2], labels, maxLength = DOUBLE_REACH) {
1097 const fg = color('--fg');
1098 const accent = color('--accent');
1099 const { L1, L2 } = params;
1100 const px = w / 2;
1101 const py = h / 2;
1102 const reach = Math.min(h, w) / 2 - 8;
1103 const r = Math.max(9, Math.min(18, reach * 0.1));
1104 const unit = (reach - r) / maxLength;
1105 const x1 = px + unit * L1 * Math.sin(t1);
1106 const y1 = py + unit * L1 * Math.cos(t1);
1107 const x2 = x1 + unit * L2 * Math.sin(t2);
1108 const y2 = y1 + unit * L2 * Math.cos(t2);
1110 // vertical reference through the pivot
1111 ctx.strokeStyle = fg;
1112 ctx.lineWidth = 1;
1113 ctx.globalAlpha = 0.3;
1114 ctx.setLineDash([4, 4]);
1115 ctx.beginPath();
1116 ctx.moveTo(px, py);
1117 ctx.lineTo(px, py + unit * (L1 + L2) + r);
1118 if (labels.includes('theta')) {
1119 // and through the upper bob, for theta2
1120 ctx.moveTo(x1, y1);
1121 ctx.lineTo(x1, y1 + unit * L2 * 0.7);
1123 ctx.stroke();
1124 ctx.setLineDash([]);
1125 ctx.globalAlpha = 1;
1127 // rods, pivot and bobs
1128 ctx.lineWidth = 2;
1129 ctx.beginPath();
1130 ctx.moveTo(px, py);
1131 ctx.lineTo(x1, y1);
1132 ctx.lineTo(x2, y2);
1133 ctx.stroke();
1134 ctx.fillStyle = fg;
1135 ctx.beginPath();
1136 ctx.arc(px, py, 4, 0, 2 * Math.PI);
1137 ctx.fill();
1138 ctx.fillStyle = accent;
1139 for (const [bx, by] of [[x1, y1], [x2, y2]]) {
1140 ctx.beginPath();
1141 ctx.arc(bx, by, r, 0, 2 * Math.PI);
1142 ctx.fill();
1145 ctx.font = 'italic 18px Georgia, serif';
1146 ctx.textAlign = 'center';
1147 ctx.textBaseline = 'middle';
1149 if (labels.includes('m')) {
1150 ctx.fillStyle = color('--bg');
1151 subText(ctx, 'm', '1', x1, y1);
1152 subText(ctx, 'm', '2', x2, y2);
1155 if (labels.includes('L')) {
1156 // beside the middle of each rod, on the side away from the vertical
1157 ctx.fillStyle = fg;
1158 for (const [sub, ax, ay, bx, by, t] of [['1', px, py, x1, y1, t1], ['2', x1, y1, x2, y2, t2]]) {
1159 const side = t >= 0 ? 1 : -1;
1160 subText(ctx, 'L', sub, (ax + bx) / 2 + side * 16 * Math.cos(t), (ay + by) / 2 - side * 16 * Math.sin(t));
1164 if (labels.includes('theta')) {
1165 // arcs from the vertical to each rod
1166 ctx.strokeStyle = fg;
1167 ctx.fillStyle = fg;
1168 ctx.lineWidth = 1.5;
1169 for (const [sub, cx, cy, t, len] of [['1', px, py, t1, L1], ['2', x1, y1, t2, L2]]) {
1170 const arcR = Math.min(40, unit * len * 0.45);
1171 ctx.beginPath();
1172 ctx.arc(cx, cy, arcR, Math.PI / 2, Math.PI / 2 - t, t > 0);
1173 ctx.stroke();
1174 const mid = Math.PI / 2 - t / 2;
1175 subText(ctx, 'θ', sub, cx + (arcR + 14) * Math.cos(mid), cy + (arcR + 14) * Math.sin(mid));
1179 if (labels.includes('g')) {
1180 // gravity, pointing down, in the bottom-right corner
1181 const gx = w - 24;
1182 const gy = h - 40;
1183 ctx.strokeStyle = fg;
1184 ctx.fillStyle = fg;
1185 ctx.lineWidth = 1.5;
1186 ctx.beginPath();
1187 ctx.moveTo(gx, gy - 25);
1188 ctx.lineTo(gx, gy + 25);
1189 ctx.stroke();
1190 ctx.beginPath();
1191 ctx.moveTo(gx, gy + 25);
1192 ctx.lineTo(gx - 4, gy + 17);
1193 ctx.lineTo(gx + 4, gy + 17);
1194 ctx.closePath();
1195 ctx.fill();
1196 ctx.fillText('g', gx - 14, gy);
1200// onStep(z, h) is called after every integrator step of length h, for
1201// recording trails. speed: see createLoop.
1202// maxLength: see drawDoublePendulum; a number, or a function read at each draw.
1203function createDoublePendulum({ canvas, button, params, labels = [], maxLength, speed = 1, onStep = () => {}, onDraw = () => {} }) {
1204 let state = doubleInitial(params);
1206 function step(dt) {
1207 const n = Math.ceil(dt / 0.0025);
1208 for (let i = 0; i < n; i++) {
1209 doubleStep(params, state, dt / n);
1210 onStep(state, dt / n);
1214 function draw() {
1215 if (!canvas.clientWidth) return;
1216 const { ctx, w, h } = prepare(canvas);
1217 drawDoublePendulum(ctx, w, h, params, state, labels, typeof maxLength === 'function' ? maxLength() : maxLength);
1218 onDraw(state);
1221 const loop = createLoop({ button, step, draw, speed });
1223 function setLabels(value) {
1224 labels = value;
1225 draw();
1228 // Back to the initial state, held still.
1229 function reset() {
1230 state = doubleInitial(params);
1231 loop.reset();
1234 return { draw, setLabels, reset, pause: loop.pause };
1237// Page 10: the double pendulum, let go with both rods horizontal
1238const doubleDefaults = { m1: 1, m2: 1, L1: 1, L2: 1, g: 9.8 };
1239const doublePendulum = createDoublePendulum({
1240 canvas: document.getElementById('double-canvas'),
1241 button: document.getElementById('double-toggle'),
1242 params: { ...doubleDefaults, theta1: Math.PI / 2, theta2: Math.PI / 2, p1: 0, p2: 0 },
1243 maxLength: doubleDefaults.L1 + doubleDefaults.L2, // lengths are fixed here, so fill the canvas
1244});
1246// Pages 11 to 13: double pendulum phase space, projected onto the (theta1, p1)
1247// and (theta2, p2) planes. The p axes cover the momentum sliders' range, which
1248// the high-energy kicks need.
1249const DOUBLE_PMAX = 20;
1251// Draw the theta_k and p_k axes, with p_k running over +/- pMax; returns the
1252// mapping to canvas coordinates.
1253function doubleAxes(ctx, w, h, k, pMax = DOUBLE_PMAX) {
1254 const halfW = w / 2 - 30;
1255 const cx = w / 2;
1256 const mid = h / 2;
1257 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
1258 const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
1259 const fg = color('--fg');
1260 ctx.strokeStyle = fg;
1261 ctx.fillStyle = fg;
1262 ctx.globalAlpha = 0.5;
1263 ctx.lineWidth = 1;
1264 ctx.beginPath();
1265 ctx.moveTo(cx - halfW, mid);
1266 ctx.lineTo(cx + halfW, mid);
1267 ctx.moveTo(cx, 8);
1268 ctx.lineTo(cx, h - 8);
1269 ctx.stroke();
1270 ctx.globalAlpha = 1;
1271 ctx.textAlign = 'center';
1272 ctx.textBaseline = 'middle';
1273 subText(ctx, 'θ', String(k), cx + halfW + 16, mid);
1274 subText(ctx, 'p', String(k), cx + 18, 16);
1275 ctx.font = `13px ${color('--font-body')}`;
1276 ctx.textBaseline = 'top';
1277 ctx.fillText('−π', cx - halfW, mid + 6);
1278 ctx.fillText('π', cx + halfW, mid + 6);
1279 return { thetaToX, pToY };
1282// The trail in the (theta_k, p_k) plane (k = 0 or 1), fading with age and
1283// broken where theta wraps around, then the current state.
1284function drawDoublePlane(canvas, k, trail, state) {
1285 if (!canvas.clientWidth) return;
1286 const { ctx, w, h } = prepare(canvas);
1287 const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1);
1288 const accent = color('--accent');
1289 ctx.save();
1290 ctx.beginPath();
1291 ctx.rect(0, 0, w, h);
1292 ctx.clip();
1293 ctx.strokeStyle = accent;
1294 ctx.lineWidth = 1.5;
1295 const chunks = 6;
1296 for (let c = 0; c < chunks; c++) {
1297 const from = Math.floor((trail.length * c) / chunks);
1298 const to = Math.min(trail.length, Math.floor((trail.length * (c + 1)) / chunks) + 1);
1299 ctx.globalAlpha = 0.15 + (0.75 * (c + 1)) / chunks;
1300 ctx.beginPath();
1301 for (let i = from; i < to; i++) {
1302 const z = trail[i];
1303 const x = thetaToX(z[k]);
1304 const y = pToY(z[k + 2]);
1305 if (i === from || Math.abs(z[k] - trail[i - 1][k]) > Math.PI) ctx.moveTo(x, y);
1306 else ctx.lineTo(x, y);
1308 ctx.stroke();
1310 ctx.restore();
1311 ctx.fillStyle = accent;
1312 ctx.beginPath();
1313 ctx.arc(thetaToX(state[k]), pToY(state[k + 2]), 6, 0, 2 * Math.PI);
1314 ctx.fill();
1317// Presets grouped by energy, all with the default masses, lengths and g.
1318// Within a group every preset has the same energy H, so their Poincare
1319// sections lie on the same energy surface. Above the resting state
1320// (H = -3 m g L) the groups have 0.5, 1.5 and 3 m g L. Finite-time Lyapunov
1321// exponents put almost all motion at the low energy as regular, a mix at the
1322// medium one ("upper rod only" and "lower rod kicked" weakly chaotic, the rest
1323// regular), and all of it at the high one as chaotic.
1324// State: [theta1, theta2, p1, p2]. A kick starts both rods hanging straight
1325// down with the named rod turning and the other not (yet); "both rods kicked"
1326// starts them turning together.
1327const doublePresetGroups = {
1328 low: {
1329 inphase: ['Normal mode, in phase', [0.5081, 0.7186, 0, 0]], // theta2 = sqrt(2) theta1
1330 outphase: ['Normal mode, out of phase', [0.5081, -0.7186, 0, 0]],
1331 upper: ['Upper rod only', [0.7227, 0, 0, 0]],
1332 lower: ['Lower rod only', [0, 1.0472, 0, 0]],
1333 },
1334 medium: {
1335 together: ['Rods together', [Math.PI / 3, Math.PI / 3, 0, 0]],
1336 opposite: ['Rods opposite', [Math.PI / 3, -Math.PI / 3, 0, 0]],
1337 upper: ['Upper rod only', [1.3181, 0, 0, 0]],
1338 lower: ['Lower rod only', [0, 2 * Math.PI / 3, 0, 0]],
1339 kickupper: ['Upper rod kicked', [0, 0, 7.6681, 3.8341]],
1340 kicklower: ['Lower rod kicked', [0, 0, 5.4222, 5.4222]],
1341 },
1342 high: {
1343 together: ['Both rods horizontal', [Math.PI / 2, Math.PI / 2, 0, 0]],
1344 opposite: ['Rods horizontal, opposite', [Math.PI / 2, -Math.PI / 2, 0, 0]],
1345 lowerup: ['Lower rod upright', [Math.PI / 3, Math.PI, 0, 0]],
1346 kickupper: ['Upper rod kicked', [0, 0, 10.8444, 5.4222]],
1347 kicklower: ['Lower rod kicked', [0, 0, 7.6681, 7.6681]],
1348 both: ['Both rods kicked', [0, 0, 10.2879, 6.8586]],
1349 },
1352function doublePreset(level, name) {
1353 const [theta1, theta2, p1, p2] = doublePresetGroups[level][name][1];
1354 return { theta1, theta2, p1, p2 };
1357// The pivot, rods for the central simulation (started from the ball's
1358// center), and every pendulum's two bobs as points.
1359function drawDoubleCloud(ctx, w, h, params, points, [t1, t2]) {
1360 const fg = color('--fg');
1361 const { L1, L2 } = params;
1362 const px = w / 2;
1363 const py = h / 2;
1364 const unit = (Math.min(h, w) / 2 - 8) / (L1 + L2);
1365 const x1 = px + unit * L1 * Math.sin(t1);
1366 const y1 = py + unit * L1 * Math.cos(t1);
1368 ctx.strokeStyle = fg;
1369 ctx.lineWidth = 1;
1370 ctx.globalAlpha = 0.3;
1371 ctx.setLineDash([4, 4]);
1372 ctx.beginPath();
1373 ctx.moveTo(px, py);
1374 ctx.lineTo(px, py + unit * (L1 + L2));
1375 ctx.stroke();
1376 ctx.setLineDash([]);
1377 ctx.globalAlpha = 1;
1378 ctx.lineWidth = 2;
1379 ctx.beginPath();
1380 ctx.moveTo(px, py);
1381 ctx.lineTo(x1, y1);
1382 ctx.lineTo(x1 + unit * L2 * Math.sin(t2), y1 + unit * L2 * Math.cos(t2));
1383 ctx.stroke();
1384 ctx.fillStyle = fg;
1385 ctx.beginPath();
1386 ctx.arc(px, py, 4, 0, 2 * Math.PI);
1387 ctx.fill();
1389 ctx.fillStyle = color('--accent');
1390 for (const [a1, a2] of points) {
1391 const bx = px + unit * L1 * Math.sin(a1);
1392 const by = py + unit * L1 * Math.cos(a1);
1393 ctx.fillRect(bx - 1, by - 1, 2, 2);
1394 ctx.fillRect(bx + unit * L2 * Math.sin(a2) - 1, by + unit * L2 * Math.cos(a2) - 1, 2, 2);
1398// Pages 11 to 13 share a layout: the preset and sliders on the left, and the
1399// pendulum above the (theta1, p1) and (theta2, p2) planes on the right. Each
1400// page has its own state and controls, found by id: `${id}-canvas`,
1401// `${id}-plane1`, `${id}-${name}` and so on. mode chooses what the planes show:
1402// 'trail' (page 11) the trajectory in both planes, fading with age;
1403// 'section' (page 12) the trajectory in the (theta1, p1) plane, and in the
1404// (theta2, p2) plane only a dot each time theta1 passes through
1405// zero (straight down) with p1 > 0, a Poincare section;
1406// 'cloud' (page 13) a small 4D ball of starting points around the initial
1407// state, evolving as on the Liouville slides, with every
1408// pendulum's bobs drawn as points and the rods following the
1409// simulation started from the ball's center.
1410function createDoublePhasePage({ id, mode }) {
1411 const params = { ...doubleDefaults, ...doublePreset('low', 'upper') };
1412 const canvas = document.getElementById(`${id}-canvas`);
1413 const button = document.getElementById(`${id}-toggle`);
1414 const planes = [1, 2].map((k) => document.getElementById(`${id}-plane${k}`));
1415 const energyOut = document.getElementById(`${id}-energy`);
1416 const level = document.getElementById(`${id}-level`);
1417 const preset = document.getElementById(`${id}-preset`);
1418 // the speed-up menu, on the trail and section pages only
1419 const speedSelect = document.getElementById(`${id}-speed`);
1421 function showEnergy(z) {
1422 const e = doubleEnergy(params, z);
1423 energyOut.textContent = (Math.abs(e) < 0.005 ? 0 : e).toFixed(2);
1426 let sim;
1427 let reset;
1429 if (mode === 'cloud') {
1430 // half-widths of the ball in theta1, theta2, p1, p2; roughly round on screen
1431 const radii = [0.2, 0.2, 1.2, 1.2];
1432 let points;
1433 let central;
1435 function makeCloud() {
1436 const center = doubleInitial(params);
1437 central = center.slice();
1438 points = [];
1439 while (points.length < 600) {
1440 const u = [0, 1, 2, 3].map(() => 2 * Math.random() - 1);
1441 if (u.reduce((sum, v) => sum + v * v, 0) > 1) continue;
1442 const z = center.map((c, i) => c + radii[i] * u[i]);
1443 z[0] = wrapAngle(z[0]);
1444 z[1] = wrapAngle(z[1]);
1445 points.push(z);
1448 makeCloud();
1450 function step(dt) {
1451 const n = Math.ceil(dt / 0.0025);
1452 for (const z of [central, ...points]) {
1453 for (let i = 0; i < n; i++) doubleStep(params, z, dt / n);
1457 function draw() {
1458 if (!canvas.clientWidth) return;
1459 const d = prepare(canvas);
1460 drawDoubleCloud(d.ctx, d.w, d.h, params, points, central);
1461 planes.forEach((plane, k) => {
1462 const { ctx, w, h } = prepare(plane);
1463 const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1);
1464 ctx.save();
1465 ctx.beginPath();
1466 ctx.rect(0, 0, w, h);
1467 ctx.clip();
1468 ctx.fillStyle = color('--accent');
1469 for (const z of points) ctx.fillRect(thetaToX(z[k]) - 1, pToY(z[k + 2]) - 1, 2, 2);
1470 ctx.restore();
1471 });
1472 showEnergy(central);
1475 // the same pace as the other Liouville slides
1476 const loop = createLoop({ button, step, draw, speed: 0.5 });
1477 sim = { draw, pause: loop.pause };
1478 reset = () => {
1479 makeCloud();
1480 loop.reset();
1481 };
1482 } else {
1483 // the trail is sampled every TRAIL_DT of simulated time, so it looks the
1484 // same at every speed, and holds up to TRAIL_MAX samples (1000 s)
1485 const TRAIL_DT = 0.01;
1486 const TRAIL_MAX = 100000;
1487 let trail = [];
1488 let sinceSample = 0;
1489 // section mode: (theta2, p2) at each crossing, and the previous state
1490 let dots = [];
1491 let prev = null;
1493 function recordCrossing(z) {
1494 // theta1 passes through zero (straight down) in either direction, and not
1495 // by wrapping around at +/- pi; interpolate linearly to the crossing and
1496 // keep it if p1 is positive there
1497 const crossed = prev && (prev[0] < 0) !== (z[0] < 0) && Math.abs(z[0] - prev[0]) < Math.PI;
1498 const f = crossed ? -prev[0] / (z[0] - prev[0]) : 0;
1499 if (crossed && prev[2] + f * (z[2] - prev[2]) > 0) {
1500 dots.push([wrapAngle(prev[1] + f * wrapAngle(z[1] - prev[1])), prev[3] + f * (z[3] - prev[3])]);
1501 if (dots.length > 50000) dots = dots.slice(-40000);
1503 prev = z.slice();
1506 function drawDots(plane) {
1507 if (!plane.clientWidth) return;
1508 const { ctx, w, h } = prepare(plane);
1509 const { thetaToX, pToY } = doubleAxes(ctx, w, h, 2);
1510 ctx.save();
1511 ctx.beginPath();
1512 ctx.rect(0, 0, w, h);
1513 ctx.clip();
1514 ctx.fillStyle = color('--accent');
1515 ctx.beginPath();
1516 for (const [t2, p2] of dots) {
1517 const x = thetaToX(t2);
1518 const y = pToY(p2);
1519 ctx.moveTo(x + 0.8, y);
1520 ctx.arc(x, y, 0.8, 0, 2 * Math.PI);
1522 ctx.fill();
1523 ctx.restore();
1526 sim = createDoublePendulum({
1527 canvas,
1528 button,
1529 params,
1530 // the canvas is short, so fill it: the rods are drawn to scale relative to
1531 // each other, but not across changes of L1 + L2
1532 maxLength: () => params.L1 + params.L2,
1533 speed: () => Number(speedSelect.value),
1534 onStep: (z, h) => {
1535 sinceSample += h;
1536 if (sinceSample >= TRAIL_DT) {
1537 sinceSample = 0;
1538 trail.push(z.slice());
1539 if (trail.length > TRAIL_MAX) trail = trail.slice(-0.8 * TRAIL_MAX);
1541 if (mode === 'section') recordCrossing(z);
1542 },
1543 onDraw: (z) => {
1544 drawDoublePlane(planes[0], 0, trail, z);
1545 if (mode === 'section') drawDots(planes[1]);
1546 else drawDoublePlane(planes[1], 1, trail, z);
1547 showEnergy(z);
1548 },
1549 });
1550 reset = () => {
1551 trail = [];
1552 sinceSample = 0;
1553 dots = [];
1554 prev = null;
1555 sim.reset();
1556 };
1559 const inputs = ['theta1', 'theta2', 'p1', 'p2', 'm1', 'm2', 'L1', 'L2', 'g'].map((name) => ({
1560 name,
1561 input: document.getElementById(`${id}-${name}`),
1562 output: document.getElementById(`${id}-${name}-value`),
1563 }));
1565 function syncInputs() {
1566 for (const { name, input, output } of inputs) {
1567 input.value = params[name];
1568 output.textContent = params[name].toFixed(2);
1572 for (const { name, input, output } of inputs) {
1573 input.addEventListener('input', () => {
1574 params[name] = Number(input.value);
1575 output.textContent = params[name].toFixed(2);
1576 preset.value = 'custom';
1577 reset();
1578 });
1581 // The preset menu lists the chosen energy's presets, then a Custom entry
1582 // that the sliders select.
1583 function fillPresets() {
1584 preset.replaceChildren();
1585 for (const [value, [label]] of Object.entries(doublePresetGroups[level.value])) {
1586 preset.add(new Option(label, value));
1588 const custom = new Option('Custom', 'custom');
1589 custom.disabled = true;
1590 preset.add(custom);
1593 // A preset restores the default masses, lengths and g along with its initial state.
1594 function applyPreset() {
1595 Object.assign(params, doubleDefaults, doublePreset(level.value, preset.value));
1596 syncInputs();
1597 reset();
1600 level.addEventListener('change', () => {
1601 fillPresets();
1602 applyPreset();
1603 });
1604 preset.addEventListener('change', applyPreset);
1605 fillPresets();
1606 preset.value = 'upper';
1607 syncInputs();
1609 return { draw: sim.draw, pause: sim.pause, reset };
1612const doublePhase = createDoublePhasePage({ id: 'double-phase', mode: 'trail' });
1613const doublePoincare = createDoublePhasePage({ id: 'double-poincare', mode: 'section' });
1614const doubleDispersion = createDoublePhasePage({ id: 'double-dispersion', mode: 'cloud' });
1616// Page 14: Poincare section explorer, with the default masses, lengths and g.
1617// The section is theta1 = 0 with theta1 increasing. Given (theta2, p2) on it
1618// and the energy H, the kinetic energy is quadratic in p1 with two roots, and
1619// the larger one is exactly the one with dtheta1/dt > 0, so each point inside
1620// the allowed region is one state. (With p1 > 0 as the condition instead,
1621// both roots can be positive, and two states would share a point.)
1623// Clicking starts an orbit there, integrated in the background (with
1624// gaussStep, and crossings found by sectionCrossing) until it is complete or
1625// the next click stops it: its dots are binned on a grid of about 5 x 5 slide
1626// pixels, and it stops once EXPLORER_WINDOW dots in a row reach fewer than
1627// EXPLORER_NEW_CELLS new cells (a curve has closed up, or a chaotic region has
1628// mostly filled), or at EXPLORER_MAX_DOTS dots (or 4 simulated seconds per
1629// allowed dot).
1631// Auto starts each new orbit in the middle of the largest gap: the cell
1632// farthest from any dot and from the edge of the allowed region (a chamfer
1633// distance transform on the grid). Each press adds up to AUTO_BATCH orbits,
1634// stopping early when no gap is more than AUTO_MIN_GAP cells from a dot, or
1635// on a click. A press when the gaps are already that small fills smaller ones,
1636// down to 3/4 of the largest gap left (at least one cell); this finds small
1637// islands in a chaotic sea.
1639// Each orbit is colored by an estimate of the dimension of its dots: a regular
1640// orbit lies on a curve (1), a chaotic one fills an area (2). The estimate is
1641// the correlation dimension: the number of pairs of dots closer than r grows
1642// like r^d, so d = log2(C(r) / C(r/2)), with r = 0.03 of the region's half
1643// width (large enough r would see the two sides of a thin loop as an area).
1644// It uses one dot per cell of a grid twice as fine as the one above (the first
1645// to land there), so it measures where the orbit has been rather than how
1646// often: a chaotic orbit that lingers near an island would otherwise look
1647// regular.
1648// Regular orbits all measure about 1, so to tell them apart each orbit has its
1649// own cool color, blended toward red as d goes from 1.25 to 1.85.
1650const EXPLORER_STEP = 0.025;
1651const EXPLORER_GRID = [300, 140];
1652const EXPLORER_FINE_GRID = [600, 280];
1653const EXPLORER_WINDOW = 1000;
1654const EXPLORER_NEW_CELLS = 10;
1655const EXPLORER_MAX_DOTS = 20000;
1656const EXPLORER_MAX_ORBITS = 2000;
1657const AUTO_MIN_GAP = 3;
1658const AUTO_BATCH = 40;
1659// GPU fill: orbits per press, their dot cap, and the crossings each may
1660// report per dispatch
1661const GPU_ORBITS = 256;
1662const GPU_MAX_DOTS = 4000;
1663const GPU_DOTS_PER_DISPATCH = 128;
1664const EXPLORER_COLORS = ['#537eba', '#2e8b57', '#1a9cb0', '#6a4fb3', '#2c5aa0', '#5f9e2f', '#8a5fbf', '#17806d'];
1666// GPU fill: doubleRates, gaussStep and sectionCrossing in WGSL, one orbit per
1667// thread. WebGPU only has 32-bit floats, so this is less precise than the CPU
1668// path (each finished fill logs its largest energy error to the console). Each
1669// dispatch advances every active orbit by P.steps steps and records up to
1670// P.maxDots crossings; the fixed-point iteration stops at a tolerance suited
1671// to 32-bit floats.
1672const EXPLORER_SHADER = `
1673struct Params { m1: f32, m2: f32, L1: f32, L2: f32, g: f32, h: f32, steps: u32, maxDots: u32, n: u32 }
1674@group(0) @binding(0) var<uniform> P: Params;
1675@group(0) @binding(1) var<storage, read_write> state: array<vec4f>;
1676@group(0) @binding(2) var<storage, read_write> slopes: array<vec4f>;
1677@group(0) @binding(3) var<storage, read_write> dots: array<vec2f>;
1678@group(0) @binding(4) var<storage, read_write> counts: array<u32>;
1679@group(0) @binding(5) var<storage, read> running: array<u32>;
1681const PI = 3.141592653589793;
1682const A12 = 0.25 - 0.28867513459481287;
1683const A21 = 0.25 + 0.28867513459481287;
1685fn wrapAngle(t: f32) -> f32 { return t - 2.0 * PI * round(t / (2.0 * PI)); }
1687fn maxAbs(v: vec4f) -> f32 {
1688 let a = abs(v);
1689 return max(max(a.x, a.y), max(a.z, a.w));
1692fn rates(z: vec4f) -> vec4f {
1693 let d = z.x - z.y;
1694 let s = sin(d);
1695 let c = cos(d);
1696 let D = P.m1 + P.m2 * s * s;
1697 let T = (P.m2 * P.L2 * P.L2 * z.z * z.z + (P.m1 + P.m2) * P.L1 * P.L1 * z.w * z.w
1698 - 2.0 * P.m2 * P.L1 * P.L2 * z.z * z.w * c) / (2.0 * P.m2 * P.L1 * P.L1 * P.L2 * P.L2 * D);
1699 let dT = (z.z * z.w * s / (P.L1 * P.L2) - 2.0 * P.m2 * T * s * c) / D;
1700 return vec4f(
1701 (P.L2 * z.z - P.L1 * z.w * c) / (P.L1 * P.L1 * P.L2 * D),
1702 ((P.m1 + P.m2) * P.L1 * z.w - P.m2 * P.L2 * z.z * c) / (P.m2 * P.L1 * P.L2 * P.L2 * D),
1703 -(P.m1 + P.m2) * P.g * P.L1 * sin(z.x) - dT,
1704 -P.m2 * P.g * P.L2 * sin(z.y) + dT);
1707fn hermite(y0: vec4f, f0: vec4f, y1: vec4f, f1: vec4f, h: f32, s: f32) -> vec4f {
1708 let s2 = s * s;
1709 let s3 = s2 * s;
1710 return (2.0 * s3 - 3.0 * s2 + 1.0) * y0 + (s3 - 2.0 * s2 + s) * h * f0
1711 + (3.0 * s2 - 2.0 * s3) * y1 + (s3 - s2) * h * f1;
1714fn crossing(a: vec4f, b: vec4f, h: f32) -> vec2f {
1715 var bu = b;
1716 bu.y = a.y + wrapAngle(b.y - a.y);
1717 let fa = rates(a);
1718 let fb = rates(b);
1719 var lo = 0.0;
1720 var hi = 1.0;
1721 for (var it = 0; it < 24; it++) {
1722 let m = 0.5 * (lo + hi);
1723 if (hermite(a, fa, bu, fb, h, m).x < 0.0) { lo = m; } else { hi = m; }
1725 let y = hermite(a, fa, bu, fb, h, 0.5 * (lo + hi));
1726 return vec2f(wrapAngle(y.y), y.w);
1729@compute @workgroup_size(64)
1730fn main(@builtin(global_invocation_id) id: vec3u) {
1731 let i = id.x;
1732 if (i >= P.n) { return; }
1733 counts[i] = 0u;
1734 if (running[i] == 0u) { return; }
1735 var z = state[i];
1736 var k1 = slopes[2u * i];
1737 var k2 = slopes[2u * i + 1u];
1738 let h = P.h;
1739 var count = 0u;
1740 for (var n = 0u; n < P.steps; n++) {
1741 let a = z;
1742 for (var it = 0; it < 12; it++) {
1743 let n1 = rates(z + h * (0.25 * k1 + A12 * k2));
1744 let n2 = rates(z + h * (A21 * k1 + 0.25 * k2));
1745 let change = max(maxAbs(n1 - k1), maxAbs(n2 - k2));
1746 k1 = n1;
1747 k2 = n2;
1748 if (change * h < 1e-6) { break; }
1750 z += 0.5 * h * (k1 + k2);
1751 z.x = wrapAngle(z.x);
1752 z.y = wrapAngle(z.y);
1753 if (a.x < 0.0 && z.x >= 0.0 && z.x - a.x < PI && count < P.maxDots) {
1754 dots[i * P.maxDots + count] = crossing(a, z, h);
1755 count++;
1758 state[i] = z;
1759 slopes[2u * i] = k1;
1760 slopes[2u * i + 1u] = k2;
1761 counts[i] = count;
1765function createExplorer() {
1766 const id = 'double-explorer';
1767 const canvas = document.getElementById(`${id}-canvas`);
1768 const slider = document.getElementById(`${id}-energy`);
1769 const output = document.getElementById(`${id}-energy-value`);
1770 const autoButton = document.getElementById(`${id}-auto`);
1771 const gpuButton = document.getElementById(`${id}-gpu`);
1772 const params = { ...doubleDefaults };
1773 const [gx, gy] = EXPLORER_GRID;
1774 let H = -14.7;
1775 let orbits = [];
1776 let orbitCount = 0;
1777 let auto = false;
1778 // cells reached by any orbit; the grid spans the allowed region,
1779 // |theta2| <= gridThetaMax and |p2| <= gridPMax
1780 let covered = new Uint8Array(gx * gy);
1781 // the last orbit to reach each cell, for finding the orbit under the mouse
1782 let owner = new Array(gx * gy).fill(null);
1783 let hovered = null;
1784 let gridPMax = 0;
1785 let gridThetaMax = Math.PI;
1786 let inside = new Uint8Array(gx * gy); // cells whose center is in the allowed region
1787 let rafId = null;
1788 let active = false;
1789 let view = null; // the latest mapping, for clicks and the dot layer
1790 // dots are drawn once onto this layer and copied to the canvas each frame;
1791 // it is redrawn in full only when the size changes or orbits are removed
1792 const layer = document.createElement('canvas');
1793 let layerDirty = true;
1795 // the largest |p2| on the section, at theta2 = 0
1796 const sectionPMax = () => Math.sqrt(Math.max(0, 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, 0))));
1798 // the largest |theta2| on the section, where H - V(0, theta2) reaches zero
1799 function sectionThetaMax() {
1800 const { m1, m2, L1, L2, g } = params;
1801 return Math.acos(Math.min(1, Math.max(-1, -(H + (m1 + m2) * g * L1) / (m2 * g * L2))));
1804 function sizeGrid() {
1805 gridPMax = sectionPMax();
1806 gridThetaMax = sectionThetaMax();
1807 inside = new Uint8Array(gx * gy);
1808 for (let j = 0; j < gy; j++) {
1809 const p = cellP(j);
1810 for (let i = 0; i < gx; i++) {
1811 inside[j * gx + i] = p * p <= 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, cellTheta(i))) ? 1 : 0;
1816 // the state on the section at (theta2, p2), or null outside the allowed region
1817 function sectionState(t2, p2) {
1818 const { m1, m2, L1, L2 } = params;
1819 const s = 2 * m2 * L2 * L2 * (H - doublePotential(params, 0, t2)) - p2 * p2;
1820 if (s < 0) return null;
1821 const D = m1 + m2 * Math.sin(t2) ** 2;
1822 return [0, t2, (L1 / L2) * p2 * Math.cos(t2) + Math.sqrt(m2 * L1 * L1 * L2 * L2 * D * s) / (m2 * L2 * L2), p2];
1825 // on at most 4000 of the given dots, evenly spread through the orbit
1826 function correlationDimension(dots) {
1827 const all = dots.length / 2;
1828 const stride = Math.ceil(all / 4000);
1829 const n = Math.floor(all / stride);
1830 const m = Math.min(300, n);
1831 const r2 = 0.03 * 0.03;
1832 let c1 = 0;
1833 let c2 = 0;
1834 for (let k = 0; k < m; k++) {
1835 const i = Math.floor((k * n) / m) * stride;
1836 const ti = dots[2 * i];
1837 const pi = dots[2 * i + 1];
1838 for (let jj = 0; jj < n; jj++) {
1839 const j = jj * stride;
1840 if (j === i) continue;
1841 const dx = wrapAngle(ti - dots[2 * j]) / gridThetaMax;
1842 const dy = (pi - dots[2 * j + 1]) / gridPMax;
1843 const d = dx * dx + dy * dy;
1844 if (d < r2) {
1845 c1++;
1846 if (d < r2 / 4) c2++;
1850 return c2 ? Math.log2(c1 / c2) : 0;
1853 // the orbit's own cool color, blended toward red from d = 1.25 to d = 1.85
1854 function orbitColor(o) {
1855 if (o.d === null) return null;
1856 const t = Math.min(1, Math.max(0, (o.d - 1.25) / 0.6));
1857 const a = o.base;
1858 const b = color('--force');
1859 const mix = (k) => Math.round((1 - t) * parseInt(a.slice(k, k + 2), 16) + t * parseInt(b.slice(k, k + 2), 16));
1860 return `rgb(${mix(1)}, ${mix(3)}, ${mix(5)})`;
1863 function cellOf(t2, p2, [nx, ny] = EXPLORER_GRID) {
1864 const i = Math.min(nx - 1, Math.max(0, Math.floor(((t2 / gridThetaMax + 1) / 2) * nx)));
1865 const j = Math.min(ny - 1, Math.max(0, Math.floor(((p2 / gridPMax + 1) / 2) * ny)));
1866 return j * nx + i;
1869 const cellTheta = (i) => (((i + 0.5) / gx) * 2 - 1) * gridThetaMax;
1870 const cellP = (j) => (((j + 0.5) / gy) * 2 - 1) * gridPMax;
1872 // the empty cell farthest from any dot (any cell set in mask) and from the
1873 // edge of the allowed region, as { i, j, gap } with gap in cells
1874 function largestGap(mask = covered) {
1875 const dist = new Float32Array(gx * gy);
1876 for (let c = 0; c < gx * gy; c++) dist[c] = inside[c] && !mask[c] ? Infinity : 0;
1877 const r2 = Math.SQRT2;
1878 for (let j = 0; j < gy; j++) {
1879 for (let i = 0; i < gx; i++) {
1880 const c = j * gx + i;
1881 let d = dist[c];
1882 if (i > 0) d = Math.min(d, dist[c - 1] + 1);
1883 if (j > 0) {
1884 d = Math.min(d, dist[c - gx] + 1);
1885 if (i > 0) d = Math.min(d, dist[c - gx - 1] + r2);
1886 if (i < gx - 1) d = Math.min(d, dist[c - gx + 1] + r2);
1888 dist[c] = d;
1891 let best = { i: 0, j: 0, gap: 0 };
1892 for (let j = gy - 1; j >= 0; j--) {
1893 for (let i = gx - 1; i >= 0; i--) {
1894 const c = j * gx + i;
1895 let d = dist[c];
1896 if (i < gx - 1) d = Math.min(d, dist[c + 1] + 1);
1897 if (j < gy - 1) {
1898 d = Math.min(d, dist[c + gx] + 1);
1899 if (i < gx - 1) d = Math.min(d, dist[c + gx + 1] + r2);
1900 if (i > 0) d = Math.min(d, dist[c + gx - 1] + r2);
1902 dist[c] = d;
1903 if (d > best.gap && d < Infinity) best = { i, j, gap: d };
1906 return best;
1909 // this press's smallest gap to fill, and how many orbits it may still add
1910 let autoGap = AUTO_MIN_GAP;
1911 let autoLeft = 0;
1913 function setAuto(on) {
1914 auto = on;
1915 autoButton.textContent = on ? 'Stop' : 'Auto';
1916 if (!on) return;
1917 const gap = largestGap().gap;
1918 autoGap = gap >= AUTO_MIN_GAP ? AUTO_MIN_GAP : Math.max(1, 0.75 * gap);
1919 autoLeft = AUTO_BATCH;
1920 if (!orbits.some(unfinishedCpu)) nextAuto();
1923 // up to n starting points spread over the gaps: each goes in the largest gap
1924 // left, then claims a disk of half that gap's radius
1925 function spreadStarts(n) {
1926 const mask = covered.slice();
1927 const starts = [];
1928 while (starts.length < n) {
1929 const { i, j, gap } = largestGap(mask);
1930 if (gap < 1) break;
1931 starts.push([cellTheta(i), cellP(j)]);
1932 const r = Math.max(1, gap / 2);
1933 const m = Math.ceil(r);
1934 for (let dj = -m; dj <= m; dj++) {
1935 for (let di = -m; di <= m; di++) {
1936 const ii = i + di;
1937 const jj = j + dj;
1938 if (di * di + dj * dj <= r * r && ii >= 0 && ii < gx && jj >= 0 && jj < gy) mask[jj * gx + ii] = 1;
1942 return starts;
1945 function nextAuto() {
1946 const { i, j, gap } = largestGap();
1947 if (autoLeft <= 0 || gap < autoGap) {
1948 setAuto(false);
1949 return;
1951 autoLeft--;
1952 addOrbit(cellTheta(i), cellP(j));
1955 // A new orbit at (theta2, p2) on the section, or null outside the allowed
1956 // region. gpu: integrated by the GPU fill rather than on the CPU.
1957 function makeOrbit(t2, p2, { gpu = false, maxDots = EXPLORER_MAX_DOTS } = {}) {
1958 const z = sectionState(t2, p2);
1959 if (!z) return null;
1960 const k = [0, 0, 0, 0, 0, 0, 0, 0];
1961 doubleRates(params, z[0], z[1], z[2], z[3], k);
1962 for (let i = 0; i < 4; i++) k[i + 4] = k[i];
1963 const o = {
1964 z, prev: z.slice(), k, dots: [], firsts: [], d: null, steps: 0, done: false, drawn: 0, gpu, maxDots,
1965 base: EXPLORER_COLORS[orbitCount++ % EXPLORER_COLORS.length],
1966 // cells of the two grids this orbit has reached (dropped when it finishes)
1967 cells: new Set(), fine: new Set(), windowDots: 0, windowNew: 0,
1968 };
1969 addDot(o, t2, p2);
1970 orbits.push(o);
1971 if (orbits.length > EXPLORER_MAX_ORBITS) {
1972 orbits.shift();
1973 layerDirty = true;
1974 covered = new Uint8Array(gx * gy);
1975 owner = new Array(gx * gy).fill(null);
1976 for (const other of orbits) {
1977 for (let i = 0; i < other.dots.length; i += 2) {
1978 const c = cellOf(other.dots[i], other.dots[i + 1]);
1979 covered[c] = 1;
1980 owner[c] = other;
1983 if (!orbits.includes(hovered)) hovered = null;
1985 return o;
1988 // a clicked or Auto orbit; it stops any orbit still being filled in
1989 function addOrbit(t2, p2) {
1990 if (!sectionState(t2, p2)) return;
1991 stopGpu();
1992 for (const prev of orbits) finish(prev);
1993 makeOrbit(t2, p2);
1994 resume();
1997 const unfinishedCpu = (o) => !o.done && !o.gpu;
1999 function addDot(o, t2, p2) {
2000 o.dots.push(t2, p2);
2001 const c = cellOf(t2, p2);
2002 if (!o.cells.has(c)) {
2003 o.cells.add(c);
2004 covered[c] = 1;
2005 owner[c] = o;
2006 o.windowNew++;
2008 const f = cellOf(t2, p2, EXPLORER_FINE_GRID);
2009 if (!o.fine.has(f)) {
2010 o.fine.add(f);
2011 o.firsts.push(t2, p2);
2013 const n = o.dots.length / 2;
2014 // the dimension estimate at 500 dots, then each time the count doubles
2015 if (n === 500 || (n > 1000 && (n & (n - 1)) === 0)) {
2016 o.d = correlationDimension(o.firsts);
2017 o.drawn = 0; // redraw the whole orbit in its new color
2019 if (++o.windowDots === EXPLORER_WINDOW) {
2020 if (o.windowNew < EXPLORER_NEW_CELLS) finish(o);
2021 o.windowDots = 0;
2022 o.windowNew = 0;
2024 if (n >= o.maxDots) finish(o);
2027 // the step cap: 4 simulated seconds per allowed dot
2028 const maxSteps = (o) => (4 / EXPLORER_STEP) * o.maxDots;
2030 function finish(o) {
2031 if (o.done) return;
2032 o.done = true;
2033 o.cells = null; // only needed while dots arrive
2034 o.fine = null;
2035 // too few dots for an estimate (stopped early by a click): it stays gray
2036 if (o.dots.length / 2 < 300) return;
2037 o.d = correlationDimension(o.firsts);
2038 o.drawn = 0;
2041 // integrate orbit o for about ms milliseconds
2042 function advance(o, ms) {
2043 const until = performance.now() + ms;
2044 const { z, prev, k } = o;
2045 const cap = maxSteps(o);
2046 while (!o.done && performance.now() < until) {
2047 for (let i = 0; i < 50 && !o.done; i++) {
2048 prev[0] = z[0];
2049 prev[1] = z[1];
2050 prev[2] = z[2];
2051 prev[3] = z[3];
2052 gaussStep(params, z, EXPLORER_STEP, k);
2053 if (++o.steps > cap) finish(o);
2054 if (prev[0] < 0 && z[0] >= 0 && z[0] - prev[0] < Math.PI) {
2055 const [t2, p2] = sectionCrossing(params, prev, z, EXPLORER_STEP);
2056 addDot(o, t2, p2);
2062 function frame() {
2063 rafId = null;
2064 const busy = orbits.filter(unfinishedCpu);
2065 for (const o of busy) advance(o, 12 / busy.length);
2066 if (auto && !orbits.some(unfinishedCpu)) nextAuto();
2067 draw();
2070 function resume() {
2071 if (active && rafId === null && orbits.some(unfinishedCpu)) rafId = requestAnimationFrame(frame);
2072 if (active && gpuRun && !gpuRun.looping) gpuLoop(gpuRun);
2075 // GPU fill: GPU_ORBITS orbits at once, spread over the gaps, each integrated
2076 // by one thread of EXPLORER_SHADER. Their dots go through addDot like any
2077 // other orbit's, with a cap of GPU_MAX_DOTS. The button only appears if
2078 // WebGPU is available.
2079 let gpu = null; // { device, pipeline } once set up
2080 let gpuRun = null; // the fill in progress
2082 (async () => {
2083 const unavailable = (why) => console.warn(`[explorer] GPU fill unavailable: ${why}`);
2084 try {
2085 if (!window.isSecureContext) return unavailable(`WebGPU needs a secure context (use http://localhost, not ${location.host})`);
2086 if (!navigator.gpu) return unavailable('this browser has no navigator.gpu');
2087 const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
2088 if (!adapter) return unavailable('requestAdapter() found no GPU adapter (see chrome://gpu)');
2089 const device = await adapter.requestDevice();
2090 const module = device.createShaderModule({ code: EXPLORER_SHADER });
2091 const info = await module.getCompilationInfo();
2092 for (const m of info.messages) console[m.type === 'error' ? 'error' : 'warn'](`[explorer] shader ${m.type} at line ${m.lineNum}:${m.linePos}: ${m.message}`);
2093 const pipeline = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main' } });
2094 gpu = { device, pipeline };
2095 gpuButton.hidden = false;
2096 console.info('[explorer] GPU fill ready');
2097 } catch (err) {
2098 unavailable(err);
2100 })();
2102 function startGpu() {
2103 setAuto(false);
2104 for (const o of orbits) finish(o);
2105 const run = { orbits: [], steps: 256, looping: false, started: performance.now() };
2106 for (const [t2, p2] of spreadStarts(GPU_ORBITS)) {
2107 const o = makeOrbit(t2, p2, { gpu: true, maxDots: GPU_MAX_DOTS });
2108 if (o) run.orbits.push(o);
2110 const n = run.orbits.length;
2111 if (!n) return;
2112 const { device, pipeline } = gpu;
2113 const buffer = (size, usage) => device.createBuffer({ size, usage });
2114 const { STORAGE, COPY_SRC, COPY_DST, UNIFORM, MAP_READ } = GPUBufferUsage;
2115 run.params = buffer(48, UNIFORM | COPY_DST);
2116 run.state = buffer(n * 16, STORAGE | COPY_SRC | COPY_DST);
2117 run.slopes = buffer(n * 32, STORAGE | COPY_DST);
2118 run.dots = buffer(n * GPU_DOTS_PER_DISPATCH * 8, STORAGE | COPY_SRC);
2119 run.counts = buffer(n * 4, STORAGE | COPY_SRC);
2120 run.running = buffer(n * 4, STORAGE | COPY_DST);
2121 run.readDots = buffer(n * GPU_DOTS_PER_DISPATCH * 8, MAP_READ | COPY_DST);
2122 run.readCounts = buffer(n * 4, MAP_READ | COPY_DST);
2123 run.readState = buffer(n * 16, MAP_READ | COPY_DST);
2124 device.queue.writeBuffer(run.state, 0, Float32Array.from(run.orbits.flatMap((o) => o.z)));
2125 device.queue.writeBuffer(run.slopes, 0, Float32Array.from(run.orbits.flatMap((o) => o.k)));
2126 run.bindGroup = device.createBindGroup({
2127 layout: pipeline.getBindGroupLayout(0),
2128 entries: [run.params, run.state, run.slopes, run.dots, run.counts, run.running]
2129 .map((b, binding) => ({ binding, resource: { buffer: b } })),
2130 });
2131 gpuRun = run;
2132 gpuButton.textContent = 'Stop';
2133 resume();
2136 function stopGpu() {
2137 const run = gpuRun;
2138 if (!run) return;
2139 gpuRun = null;
2140 gpuButton.textContent = 'GPU fill';
2141 for (const o of run.orbits) finish(o);
2142 if (!run.looping) destroyRun(run);
2145 function destroyRun(run) {
2146 for (const key of ['params', 'state', 'slopes', 'dots', 'counts', 'running', 'readDots', 'readCounts', 'readState']) run[key].destroy();
2149 // dispatch, read back the crossings, repeat; aims for about 30 ms a round
2150 async function gpuLoop(run) {
2151 run.looping = true;
2152 const { device, pipeline } = gpu;
2153 const n = run.orbits.length;
2154 const per = GPU_DOTS_PER_DISPATCH;
2155 try {
2156 while (gpuRun === run && active) {
2157 const t0 = performance.now();
2158 const p = new ArrayBuffer(48);
2159 new Float32Array(p).set([params.m1, params.m2, params.L1, params.L2, params.g, EXPLORER_STEP]);
2160 new Uint32Array(p).set([run.steps, per, n], 6);
2161 device.queue.writeBuffer(run.params, 0, p);
2162 device.queue.writeBuffer(run.running, 0, Uint32Array.from(run.orbits, (o) => (o.done ? 0 : 1)));
2163 const encoder = device.createCommandEncoder();
2164 const pass = encoder.beginComputePass();
2165 pass.setPipeline(pipeline);
2166 pass.setBindGroup(0, run.bindGroup);
2167 pass.dispatchWorkgroups(Math.ceil(n / 64));
2168 pass.end();
2169 encoder.copyBufferToBuffer(run.counts, 0, run.readCounts, 0, n * 4);
2170 encoder.copyBufferToBuffer(run.dots, 0, run.readDots, 0, n * per * 8);
2171 device.queue.submit([encoder.finish()]);
2172 await Promise.all([run.readCounts.mapAsync(GPUMapMode.READ), run.readDots.mapAsync(GPUMapMode.READ)]);
2173 const counts = new Uint32Array(run.readCounts.getMappedRange()).slice();
2174 const dots = new Float32Array(run.readDots.getMappedRange()).slice();
2175 run.readCounts.unmap();
2176 run.readDots.unmap();
2177 if (gpuRun !== run) break;
2178 run.orbits.forEach((o, i) => {
2179 if (o.done) return;
2180 for (let j = 0; j < counts[i] && !o.done; j++) addDot(o, dots[2 * (i * per + j)], dots[2 * (i * per + j) + 1]);
2181 o.steps += run.steps;
2182 if (o.steps > maxSteps(o)) finish(o);
2183 });
2184 draw();
2185 if (run.orbits.every((o) => o.done)) {
2186 await reportGpu(run);
2187 gpuRun = null;
2188 gpuButton.textContent = 'GPU fill';
2189 break;
2191 const ms = performance.now() - t0;
2192 run.steps = Math.max(32, Math.min(4096, Math.round(run.steps * (ms < 20 ? 1.5 : ms > 50 ? 0.7 : 1))));
2194 } catch (err) {
2195 console.error('[explorer] GPU fill failed:', err);
2196 if (gpuRun === run) {
2197 gpuRun = null;
2198 gpuButton.textContent = 'GPU fill';
2199 for (const o of run.orbits) finish(o);
2202 run.looping = false;
2203 if (gpuRun !== run) destroyRun(run);
2206 // log how well the 32-bit integration kept the energy
2207 async function reportGpu(run) {
2208 const { device } = gpu;
2209 const n = run.orbits.length;
2210 const encoder = device.createCommandEncoder();
2211 encoder.copyBufferToBuffer(run.state, 0, run.readState, 0, n * 16);
2212 device.queue.submit([encoder.finish()]);
2213 await run.readState.mapAsync(GPUMapMode.READ);
2214 const z = new Float32Array(run.readState.getMappedRange()).slice();
2215 run.readState.unmap();
2216 let worst = 0;
2217 for (let i = 0; i < n; i++) worst = Math.max(worst, Math.abs(doubleEnergy(params, z.slice(4 * i, 4 * i + 4)) - H));
2218 const dots = run.orbits.reduce((sum, o) => sum + o.dots.length / 2, 0);
2219 const seconds = ((performance.now() - run.started) / 1000).toFixed(1);
2220 console.info(`[explorer] GPU fill: ${n} orbits, ${dots} dots in ${seconds} s; largest energy error ${worst.toExponential(1)} at H = ${H}`);
2223 // draw dots not yet on the layer
2224 function updateLayer(thetaToX, pToY) {
2225 if (layer.width !== canvas.width || layer.height !== canvas.height) {
2226 layer.width = canvas.width;
2227 layer.height = canvas.height;
2228 layerDirty = true;
2230 const lctx = layer.getContext('2d');
2231 lctx.setTransform(canvas.getContext('2d').getTransform());
2232 if (layerDirty) {
2233 lctx.clearRect(0, 0, view.w, view.h);
2234 for (const o of orbits) o.drawn = 0;
2235 layerDirty = false;
2237 const fg = color('--fg');
2238 for (const o of orbits) {
2239 const col = orbitColor(o);
2240 lctx.fillStyle = col ?? fg;
2241 lctx.globalAlpha = col ? 1 : 0.4;
2242 // an orbit with no estimate yet goes underneath, so its gray never
2243 // covers colored dots (a new orbit in a chaotic sea spreads over it);
2244 // once colored it is redrawn on top
2245 lctx.globalCompositeOperation = col ? 'source-over' : 'destination-over';
2246 const { dots } = o;
2247 for (let i = 2 * o.drawn; i < dots.length; i += 2) lctx.fillRect(thetaToX(dots[i]) - 0.7, pToY(dots[i + 1]) - 0.7, 1.4, 1.4);
2248 o.drawn = dots.length / 2;
2250 lctx.globalAlpha = 1;
2251 lctx.globalCompositeOperation = 'source-over';
2254 function draw() {
2255 active = true;
2256 if (!canvas.clientWidth) return;
2257 const { ctx, w, h } = prepare(canvas);
2258 const pMax = Math.max(sectionPMax(), 0.5) * 1.08;
2259 if (!view || view.w !== w || view.h !== h || view.pMax !== pMax) layerDirty = true;
2260 const { thetaToX, pToY } = doubleAxes(ctx, w, h, 2, pMax);
2261 view = { w, h, pMax };
2262 const fg = color('--fg');
2264 // boundary of the allowed region, p2 = +/- sqrt(2 m2 L2^2 (H - V(0, theta2)))
2265 ctx.strokeStyle = fg;
2266 ctx.globalAlpha = 0.4;
2267 ctx.lineWidth = 1;
2268 for (const sign of [1, -1]) {
2269 ctx.beginPath();
2270 let drawing = false;
2271 for (let i = 0; i <= 400; i++) {
2272 const t = -Math.PI + (2 * Math.PI * i) / 400;
2273 const k = 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, t));
2274 if (k < 0) {
2275 drawing = false;
2276 continue;
2278 const x = thetaToX(t);
2279 const y = pToY(sign * Math.sqrt(k));
2280 if (drawing) ctx.lineTo(x, y);
2281 else ctx.moveTo(x, y);
2282 drawing = true;
2284 ctx.stroke();
2286 ctx.globalAlpha = 1;
2288 updateLayer(thetaToX, pToY);
2289 ctx.save();
2290 ctx.setTransform(1, 0, 0, 1, 0, 0);
2291 // the orbit under the mouse lights up: the rest dims, and it is drawn
2292 // on top with larger dots
2293 if (hovered) ctx.globalAlpha = 0.25;
2294 ctx.drawImage(layer, 0, 0);
2295 ctx.restore();
2296 if (hovered) {
2297 ctx.fillStyle = orbitColor(hovered) ?? fg;
2298 const { dots } = hovered;
2299 for (let i = 0; i < dots.length; i += 2) ctx.fillRect(thetaToX(dots[i]) - 1.2, pToY(dots[i + 1]) - 1.2, 2.4, 2.4);
2302 if (!orbits.length) {
2303 ctx.fillStyle = fg;
2304 ctx.globalAlpha = 0.6;
2305 ctx.font = `18px ${color('--font-body')}`;
2306 ctx.textAlign = 'center';
2307 ctx.textBaseline = 'bottom';
2308 ctx.fillText('Click inside the curve to start an orbit, or press Auto', w / 2, h - 12);
2309 ctx.globalAlpha = 1;
2311 resume();
2314 // (theta2, p2) under a mouse event, inverting doubleAxes' mapping
2315 function eventPoint(e) {
2316 const rect = canvas.getBoundingClientRect();
2317 const x = ((e.clientX - rect.left) / rect.width) * view.w;
2318 const y = ((e.clientY - rect.top) / rect.height) * view.h;
2319 return [((x - view.w / 2) / (view.w / 2 - 30)) * Math.PI, ((view.h / 2 - y) / (view.h / 2 - 16)) * view.pMax];
2322 canvas.addEventListener('click', (e) => {
2323 if (!view) return;
2324 const [t2, p2] = eventPoint(e);
2325 if (Math.abs(t2) > Math.PI) return;
2326 setAuto(false);
2327 addOrbit(t2, p2);
2328 });
2330 // the orbit with a dot in the nearest cell within 3 cells of (t2, p2)
2331 function orbitNear(t2, p2) {
2332 if (Math.abs(t2) > gridThetaMax + 0.1 || Math.abs(p2) > gridPMax * 1.05) return null;
2333 const c0 = cellOf(t2, p2);
2334 const i0 = c0 % gx;
2335 const j0 = (c0 - i0) / gx;
2336 let best = null;
2337 let bestD = Infinity;
2338 for (let dj = -3; dj <= 3; dj++) {
2339 for (let di = -3; di <= 3; di++) {
2340 const i = i0 + di;
2341 const j = j0 + dj;
2342 if (i < 0 || i >= gx || j < 0 || j >= gy) continue;
2343 const o = owner[j * gx + i];
2344 const d = di * di + dj * dj;
2345 if (o && d < bestD) {
2346 best = o;
2347 bestD = d;
2351 return best;
2354 let hoverFrame = null;
2355 function setHovered(o) {
2356 if (o === hovered) return;
2357 hovered = o;
2358 if (hoverFrame === null) {
2359 hoverFrame = requestAnimationFrame(() => {
2360 hoverFrame = null;
2361 draw();
2362 });
2366 canvas.addEventListener('mousemove', (e) => {
2367 if (view) setHovered(orbitNear(...eventPoint(e)));
2368 });
2369 canvas.addEventListener('mouseleave', () => setHovered(null));
2371 autoButton.addEventListener('click', () => {
2372 stopGpu();
2373 setAuto(!auto);
2374 });
2376 gpuButton.addEventListener('click', () => {
2377 if (gpuRun) stopGpu();
2378 else if (gpu) startGpu();
2379 });
2381 function reset() {
2382 setAuto(false);
2383 stopGpu();
2384 orbits = [];
2385 orbitCount = 0;
2386 covered = new Uint8Array(gx * gy);
2387 owner = new Array(gx * gy).fill(null);
2388 hovered = null;
2389 sizeGrid();
2390 layerDirty = true;
2391 draw();
2394 slider.value = H;
2395 output.textContent = H.toFixed(1);
2396 sizeGrid();
2397 slider.addEventListener('input', () => {
2398 H = Number(slider.value);
2399 output.textContent = H.toFixed(1);
2400 reset();
2401 });
2403 function pause() {
2404 active = false;
2405 cancelAnimationFrame(rafId);
2406 rafId = null;
2409 return { draw, pause, reset };
2412const doubleExplorer = createExplorer();
2414const sims = {
2415 spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase, liouville, 'liouville-pendulum': liouvillePendulum, damped,
2416 double: doublePendulum, 'double-phase': doublePhase, 'double-poincare': doublePoincare, 'double-dispersion': doubleDispersion,
2417 'double-explorer': doubleExplorer,
2420// Reset buttons next to Start: back to the initial state, with trails cleared.
2421const resets = {
2422 'pendulum-phase': resetPendulumPhase,
2424for (const [name, sim] of Object.entries(sims)) {
2425 document.getElementById(`${name}-reset`).addEventListener('click', resets[name] ?? sim.reset);
2428const pages = [...document.querySelectorAll('.page')];
2429const pageIds = pages.map((p) => p.id);
2430const navPrev = document.getElementById('nav-prev');
2431const navNext = document.getElementById('nav-next');
2432const navPos = document.getElementById('nav-pos');
2434// Flatiron logo on every slide.
2435pages.forEach((p) => {
2436 const img = document.createElement('img');
2437 img.className = 'logo';
2438 img.alt = 'Flatiron Institute';
2439 img.src = 'assets/flatiron-logo.png';
2440 p.appendChild(img);
2441});
2443// Table of contents: the slide counter in the nav bar opens a list of slide
2444// titles; T toggles it and Escape closes it.
2445const toc = document.getElementById('toc');
2446const tocList = document.getElementById('toc-list');
2448pages.forEach((p) => {
2449 const li = document.createElement('li');
2450 const b = document.createElement('button');
2451 b.textContent = p.querySelector('h1, h2').textContent;
2452 b.addEventListener('click', () => {
2453 location.hash = p.id;
2454 setTocOpen(false);
2455 });
2456 li.appendChild(b);
2457 tocList.appendChild(li);
2458});
2460function setTocOpen(open) {
2461 toc.hidden = !open;
2462 navPos.setAttribute('aria-expanded', String(open));
2463 if (open) tocList.querySelector('.current')?.scrollIntoView({ block: 'nearest' });
2466navPos.addEventListener('click', (e) => {
2467 e.stopPropagation();
2468 setTocOpen(toc.hidden);
2469});
2470document.addEventListener('click', (e) => {
2471 if (!toc.hidden && !toc.contains(e.target)) setTocOpen(false);
2472});
2474function show(id) {
2475 pages.forEach((p) => p.classList.toggle('active', p.id === id));
2476 const i = pageIds.indexOf(id);
2477 const prev = pages[i - 1];
2478 const next = pages[i + 1];
2479 // label each button with a one-word hint of where it goes
2480 navPrev.textContent = prev ? `← ${prev.dataset.hint}` : '←';
2481 navNext.textContent = next ? `${next.dataset.hint} →` : '→';
2482 navPrev.disabled = !prev;
2483 navNext.disabled = !next;
2484 navPos.textContent = `${i + 1} / ${pages.length} \u2630`;
2485 tocList.querySelectorAll('button').forEach((b, j) => b.classList.toggle('current', j === i));
2486 for (const [name, sim] of Object.entries(sims)) {
2487 if (name === id) sim.draw();
2488 else sim.pause();
2492// Scale the 1920 x 1080 deck to the largest size that fits, centered, and
2493// redraw the visible diagram at the new resolution.
2494const SLIDE_W = 1920;
2495const SLIDE_H = 1080;
2496const MARGIN = 16;
2497const stage = document.querySelector('main');
2498const deck = document.getElementById('deck');
2500function fitDeck() {
2501 stage.style.bottom = `${document.querySelector('.pager').offsetHeight}px`;
2502 const w = stage.clientWidth;
2503 const h = stage.clientHeight;
2504 deckScale = Math.min((w - 2 * MARGIN) / SLIDE_W, (h - 2 * MARGIN) / SLIDE_H);
2505 deck.style.transform = `scale(${deckScale})`;
2506 deck.style.left = `${(w - SLIDE_W * deckScale) / 2}px`;
2507 deck.style.top = `${(h - SLIDE_H * deckScale) / 2}px`;
2508 const active = document.querySelector('.page.active');
2509 if (active) sims[active.id]?.draw();
2512window.addEventListener('resize', fitDeck);
2513// Canvas text uses the bundled fonts, so redraw once they have loaded.
2514document.fonts?.ready.then(fitDeck);
2516document.querySelectorAll('[data-tex]').forEach((el) => {
2517 katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' });
2518});
2520document.querySelectorAll('[data-solution]').forEach((toggle) => {
2521 toggle.addEventListener('click', () => {
2522 const solution = document.getElementById(toggle.dataset.solution);
2523 solution.hidden = !solution.hidden;
2524 toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution';
2525 });
2526});
2528// Pages that start centered: revealing splits them into text and diagram
2529// panels and labels the diagram.
2530const revealLabels = {
2531 spring: ['m', 'k', 'q', 'F', 'p'],
2532 energy: [], // stays unlabeled, so the bars are the only thing moving
2533 pendulum: ['m', 'L', 'theta', 'p', 'g'],
2534 double: ['m', 'L', 'theta', 'g'],
2537document.querySelectorAll('[data-reveal]').forEach((button) => {
2538 button.addEventListener('click', () => {
2539 const id = button.dataset.reveal;
2540 const section = document.getElementById(id);
2541 button.hidden = true;
2542 section.classList.add('split');
2543 section.querySelector('.text').hidden = false;
2544 sims[id].setLabels(revealLabels[id]);
2545 });
2546});
2548// Replay of how recipe.md was written, from app/crafted-link.js (npm run crafted-link).
2549if (window.CRAFTED_LINK) {
2550 const link = document.getElementById('crafted-link');
2551 link.href = window.CRAFTED_LINK;
2552 link.hidden = false;
2555// The current page lives in the URL hash, so reloading stays put.
2556function showFromHash() {
2557 const id = location.hash.slice(1);
2558 show(document.getElementById(id)?.classList.contains('page') ? id : 'landing');
2559 window.scrollTo(0, 0);
2562window.addEventListener('hashchange', showFromHash);
2563fitDeck();
2564showFromHash();
2566document.querySelectorAll('[data-goto]').forEach((el) => {
2567 el.addEventListener('click', () => {
2568 location.hash = el.dataset.goto;
2569 });
2570});
2572function goToIndex(i) {
2573 location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))];
2576function currentIndex() {
2577 return pageIds.indexOf(document.querySelector('.page.active').id);
2580navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1));
2581navNext.addEventListener('click', () => goToIndex(currentIndex() + 1));
2583document.addEventListener('keydown', (e) => {
2584 if (e.altKey || e.ctrlKey || e.metaKey) return;
2585 if (e.target.closest?.('input, select, textarea')) return; // arrow keys belong to the control
2586 if (e.key === 't' || e.key === 'T') {
2587 setTocOpen(toc.hidden);
2588 return;
2590 if (e.key === 'Escape' && !toc.hidden) {
2591 setTocOpen(false);
2592 return;
2594 const target = {
2595 ArrowLeft: currentIndex() - 1,
2596 ArrowRight: currentIndex() + 1,
2597 Home: 0,
2598 End: pageIds.length - 1,
2599 }[e.key];
2600 if (target === undefined) return;
2601 e.preventDefault();
2602 goToIndex(target);
2603});
↑↓ move↵openescclose