/ interactive_tutorials / hamiltonian_systems
Sign in
interactive_tutorials / hamiltonian_systems
hamiltonian_systems / app / main.js
3016 lines · 102.4 KBCodeBlameHistory
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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}
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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.
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 16function prepare(canvas) {
17 const ctx = canvas.getContext('2d');
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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 };
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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;
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 96// params: { k, m, q0, b }, read live so sliders can change them; the damping
97// coefficient b is optional (default 0, no damping).
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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) {
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 112 const f = -k * q;
113 q += (p / m) * dt + (0.5 * f / m) * dt * dt;
114 p += 0.5 * (f - k * q) * dt;
118 function draw() {
119 if (!canvas.clientWidth) return;
120 const { ctx, w, h } = prepare(canvas);
122 const fg = color('--fg');
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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();
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 152 ctx.moveTo(x0, floorY - box - 48);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 153 ctx.lineTo(x0, floorY);
154 ctx.stroke();
155 ctx.setLineDash([]);
156 ctx.globalAlpha = 1;
157 ctx.fillStyle = fg;
158 ctx.textBaseline = 'bottom';
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 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';
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 };
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 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.
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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) {
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 201 const dt = (typeof speed === 'function' ? speed() : speed) * Math.min((t - lastTime) / 1000, 0.05);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 239// is then drawn to scale, with L = 1.2 (the slider's maximum) filling the canvas.
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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);
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 265 const rod = centered ? maxRod * L / 1.2 : maxRod;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 325 const arcR = Math.min(44, rod * 0.45);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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;
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 441 ctx.font = `15px ${color('--font-body')}`;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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;
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 475// Draw the q and p axes; returns the mapping from (q, p) to canvas coordinates.
476function springAxes(ctx, w, h) {
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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);
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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});
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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 });
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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 }
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 };
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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'] });
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 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.
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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});
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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) {
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 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);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 708 ctx.font = `13px ${color('--font-body')}`;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 709 ctx.textAlign = 'center';
710 ctx.fillText('−π', cx - halfW, mid + 6);
711 ctx.fillText('π', cx + halfW, mid + 6);
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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();
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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.
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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.
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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;
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 788 let boundary;
789 let interior;
790 let jitter;
793 function makeDisk() {
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 794 central = [center[0], center[1]];
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 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());
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 809 makeDisk();
811 function step(dt) {
812 // leapfrog on dq/dt = p / m, dp/dt = force(q), for every point
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 813 for (const pts of [boundary, interior, [central]]) {
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 867// reaching the block simulated from the disk's center. The disk's radii look
868// round at the default scale.
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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],
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 876 drawDiagram: (ctx, w, h, points, jitter, [centralQ]) => {
877 drawSpringScene(ctx, w, h, centralQ, ({ qToX, floorY, box }) => {
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 889// at the bob simulated from the disk's center. With m = L = 1, p = dtheta/dt.
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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],
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 897 drawDiagram: (ctx, w, h, points, jitter, [centralTheta]) => {
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 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);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 919 ctx.lineTo(px + (rod - 18) * Math.sin(centralTheta), py + (rod - 18) * Math.cos(centralTheta));
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});
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 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
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 956// (theta1, theta2, p1, p2), written into out. With params.b (page 16) there
957// is also friction, a force -b dtheta_k/dt on each angle, as on the damped
958// spring page; the system is then no longer Hamiltonian.
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 959function doubleRates(params, t1, t2, p1, p2, out) {
960 const { m1, m2, L1, L2, g } = params;
961 const delta = t1 - t2;
962 const s = Math.sin(delta);
963 const c = Math.cos(delta);
964 const D = m1 + m2 * s * s;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 965 // T as in doubleKinetic, and sin(2 delta) = 2 s c, reusing s and c: this is
966 // the inner loop of every double pendulum simulation
967 const T = (m2 * L2 * L2 * p1 * p1 + (m1 + m2) * L1 * L1 * p2 * p2 - 2 * m2 * L1 * L2 * p1 * p2 * c)
968 / (2 * m2 * L1 * L1 * L2 * L2 * D);
969 const dTdDelta = (p1 * p2 * s / (L1 * L2) - 2 * m2 * T * s * c) / D;
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 970 out[0] = (L2 * p1 - L1 * p2 * c) / (L1 * L1 * L2 * D);
971 out[1] = ((m1 + m2) * L1 * p2 - m2 * L2 * p1 * c) / (m2 * L1 * L2 * L2 * D);
972 out[2] = -(m1 + m2) * g * L1 * Math.sin(t1) - dTdDelta;
973 out[3] = -m2 * g * L2 * Math.sin(t2) + dTdDelta;
975 out[2] -= params.b * out[0];
976 out[3] -= params.b * out[1];
977 }
980// One step of the implicit midpoint rule, z' = z + h f((z + z') / 2), solved by
981// fixed-point iteration, updating z in place. It is symplectic, and unlike
982// leapfrog it does not need H to split into a kinetic part in p and a
983// potential part in q (here the kinetic energy depends on the angles too).
984// Allocation-free, since the Liouville slide steps hundreds of these per frame.
985const doubleRate = [0, 0, 0, 0];
986function doubleStep(params, z, h) {
987 const [t1, t2, p1, p2] = z;
988 let a1 = t1;
989 let a2 = t2;
990 let b1 = p1;
991 let b2 = p2;
992 for (let it = 0; it < 20; it++) {
993 doubleRates(params, 0.5 * (t1 + a1), 0.5 * (t2 + a2), 0.5 * (p1 + b1), 0.5 * (p2 + b2), doubleRate);
994 const n1 = t1 + h * doubleRate[0];
995 const n2 = t2 + h * doubleRate[1];
996 const n3 = p1 + h * doubleRate[2];
997 const n4 = p2 + h * doubleRate[3];
998 const change = Math.max(Math.abs(n1 - a1), Math.abs(n2 - a2), Math.abs(n3 - b1), Math.abs(n4 - b2));
999 a1 = n1;
1000 a2 = n2;
1001 b1 = n3;
1002 b2 = n4;
1003 if (change < 1e-12) break;
1005 z[0] = wrapAngle(a1);
1006 z[1] = wrapAngle(a2);
1007 z[2] = b1;
1008 z[3] = b2;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1011// One step of the 2-stage Gauss-Legendre method. The implicit midpoint rule
1012// above is the 1-stage member of this family; this one is also symplectic but
1013// of order 4, so for the same accuracy it can take steps several times
1014// longer. Its two stage slopes, k[0..3] and k[4..7], are solved by fixed-point
1015// iteration starting from the previous step's, so each trajectory keeps its
1016// own k (fill it with the rates at the starting state).
1017const GAUSS_A12 = 0.25 - Math.sqrt(3) / 6;
1018const GAUSS_A21 = 0.25 + Math.sqrt(3) / 6;
1019const gaussRate1 = [0, 0, 0, 0];
1020const gaussRate2 = [0, 0, 0, 0];
1021function gaussStep(params, z, h, k) {
1022 for (let it = 0; it < 30; it++) {
1023 doubleRates(params,
1024 z[0] + h * (0.25 * k[0] + GAUSS_A12 * k[4]), z[1] + h * (0.25 * k[1] + GAUSS_A12 * k[5]),
1025 z[2] + h * (0.25 * k[2] + GAUSS_A12 * k[6]), z[3] + h * (0.25 * k[3] + GAUSS_A12 * k[7]), gaussRate1);
1026 doubleRates(params,
1027 z[0] + h * (GAUSS_A21 * k[0] + 0.25 * k[4]), z[1] + h * (GAUSS_A21 * k[1] + 0.25 * k[5]),
1028 z[2] + h * (GAUSS_A21 * k[2] + 0.25 * k[6]), z[3] + h * (GAUSS_A21 * k[3] + 0.25 * k[7]), gaussRate2);
1029 let change = 0;
1030 for (let i = 0; i < 4; i++) {
1031 change = Math.max(change, Math.abs(gaussRate1[i] - k[i]), Math.abs(gaussRate2[i] - k[i + 4]));
1032 k[i] = gaussRate1[i];
1033 k[i + 4] = gaussRate2[i];
1035 if (change * h < 1e-10) break;
1037 for (let i = 0; i < 4; i++) z[i] += 0.5 * h * (k[i] + k[i + 4]);
1038 z[0] = wrapAngle(z[0]);
1039 z[1] = wrapAngle(z[1]);
1042// Where a step of length h from state a to state b crosses theta1 = 0 (theta1
1043// increasing), by cubic Hermite interpolation with the rates at both ends,
1044// which stays accurate for long steps; returns [theta2, p2] there.
1045const hermiteA = [0, 0, 0, 0];
1046const hermiteB = [0, 0, 0, 0];
1047function sectionCrossing(params, a, b, h) {
1048 doubleRates(params, a[0], a[1], a[2], a[3], hermiteA);
1049 doubleRates(params, b[0], b[1], b[2], b[3], hermiteB);
1050 const end = (i) => (i === 1 ? a[1] + wrapAngle(b[1] - a[1]) : b[i]);
1051 const at = (i, s) => {
1052 const s2 = s * s;
1053 const s3 = s2 * s;
1054 return (2 * s3 - 3 * s2 + 1) * a[i] + (s3 - 2 * s2 + s) * h * hermiteA[i]
1055 + (3 * s2 - 2 * s3) * end(i) + (s3 - s2) * h * hermiteB[i];
1056 };
1057 let lo = 0;
1058 let hi = 1;
1059 for (let it = 0; it < 30; it++) {
1060 const m = 0.5 * (lo + hi);
1061 if (at(0, m) < 0) lo = m;
1062 else hi = m;
1064 const s = 0.5 * (lo + hi);
1065 return [wrapAngle(at(1, s)), at(3, s)];
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1068function wrapAngle(t) {
1069 return t - 2 * Math.PI * Math.round(t / (2 * Math.PI));
1072function doubleInitial({ theta1, theta2, p1, p2 }) {
1073 return [theta1, theta2, p1, p2];
1076// A label with a subscript, e.g. m with 1, centered at (x, y). The serif font
1077// has no subscript digits, so the digit is drawn smaller and lower.
1078function subText(ctx, base, sub, x, y) {
1079 const font = 'italic 18px Georgia, serif';
1080 const small = 'italic 12px Georgia, serif';
1081 ctx.font = font;
1082 const bw = ctx.measureText(base).width;
1083 ctx.font = small;
1084 const sw = ctx.measureText(sub).width;
1085 const left = x - (bw + sw + 1) / 2;
1086 const align = ctx.textAlign;
1087 ctx.textAlign = 'left';
1088 ctx.font = font;
1089 ctx.fillText(base, left, y);
1090 ctx.font = small;
1091 ctx.fillText(sub, left + bw + 1, y + 5);
1092 ctx.font = font;
1093 ctx.textAlign = align;
1096// L1 + L2 at the slider maximums. The rods are drawn to scale, with a total
1097// length of maxLength reaching from the pivot (mid-canvas) to the edge, so
1098// either bob can go over the top.
1099const DOUBLE_REACH = 2.5;
1101// labels: which of 'm', 'L', 'theta', 'g' to draw.
1102function drawDoublePendulum(ctx, w, h, params, [t1, t2], labels, maxLength = DOUBLE_REACH) {
1103 const fg = color('--fg');
1104 const accent = color('--accent');
1105 const { L1, L2 } = params;
1106 const px = w / 2;
1107 const py = h / 2;
1108 const reach = Math.min(h, w) / 2 - 8;
1109 const r = Math.max(9, Math.min(18, reach * 0.1));
1110 const unit = (reach - r) / maxLength;
1111 const x1 = px + unit * L1 * Math.sin(t1);
1112 const y1 = py + unit * L1 * Math.cos(t1);
1113 const x2 = x1 + unit * L2 * Math.sin(t2);
1114 const y2 = y1 + unit * L2 * Math.cos(t2);
1116 // vertical reference through the pivot
1117 ctx.strokeStyle = fg;
1118 ctx.lineWidth = 1;
1119 ctx.globalAlpha = 0.3;
1120 ctx.setLineDash([4, 4]);
1121 ctx.beginPath();
1122 ctx.moveTo(px, py);
1123 ctx.lineTo(px, py + unit * (L1 + L2) + r);
1124 if (labels.includes('theta')) {
1125 // and through the upper bob, for theta2
1126 ctx.moveTo(x1, y1);
1127 ctx.lineTo(x1, y1 + unit * L2 * 0.7);
1129 ctx.stroke();
1130 ctx.setLineDash([]);
1131 ctx.globalAlpha = 1;
1133 // rods, pivot and bobs
1134 ctx.lineWidth = 2;
1135 ctx.beginPath();
1136 ctx.moveTo(px, py);
1137 ctx.lineTo(x1, y1);
1138 ctx.lineTo(x2, y2);
1139 ctx.stroke();
1140 ctx.fillStyle = fg;
1141 ctx.beginPath();
1142 ctx.arc(px, py, 4, 0, 2 * Math.PI);
1143 ctx.fill();
1144 ctx.fillStyle = accent;
1145 for (const [bx, by] of [[x1, y1], [x2, y2]]) {
1146 ctx.beginPath();
1147 ctx.arc(bx, by, r, 0, 2 * Math.PI);
1148 ctx.fill();
1151 ctx.font = 'italic 18px Georgia, serif';
1152 ctx.textAlign = 'center';
1153 ctx.textBaseline = 'middle';
1155 if (labels.includes('m')) {
1156 ctx.fillStyle = color('--bg');
1157 subText(ctx, 'm', '1', x1, y1);
1158 subText(ctx, 'm', '2', x2, y2);
1161 if (labels.includes('L')) {
1162 // beside the middle of each rod, on the side away from the vertical
1163 ctx.fillStyle = fg;
1164 for (const [sub, ax, ay, bx, by, t] of [['1', px, py, x1, y1, t1], ['2', x1, y1, x2, y2, t2]]) {
1165 const side = t >= 0 ? 1 : -1;
1166 subText(ctx, 'L', sub, (ax + bx) / 2 + side * 16 * Math.cos(t), (ay + by) / 2 - side * 16 * Math.sin(t));
1170 if (labels.includes('theta')) {
1171 // arcs from the vertical to each rod
1172 ctx.strokeStyle = fg;
1173 ctx.fillStyle = fg;
1174 ctx.lineWidth = 1.5;
1175 for (const [sub, cx, cy, t, len] of [['1', px, py, t1, L1], ['2', x1, y1, t2, L2]]) {
1176 const arcR = Math.min(40, unit * len * 0.45);
1177 ctx.beginPath();
1178 ctx.arc(cx, cy, arcR, Math.PI / 2, Math.PI / 2 - t, t > 0);
1179 ctx.stroke();
1180 const mid = Math.PI / 2 - t / 2;
1181 subText(ctx, 'θ', sub, cx + (arcR + 14) * Math.cos(mid), cy + (arcR + 14) * Math.sin(mid));
1185 if (labels.includes('g')) {
1186 // gravity, pointing down, in the bottom-right corner
1187 const gx = w - 24;
1188 const gy = h - 40;
1189 ctx.strokeStyle = fg;
1190 ctx.fillStyle = fg;
1191 ctx.lineWidth = 1.5;
1192 ctx.beginPath();
1193 ctx.moveTo(gx, gy - 25);
1194 ctx.lineTo(gx, gy + 25);
1195 ctx.stroke();
1196 ctx.beginPath();
1197 ctx.moveTo(gx, gy + 25);
1198 ctx.lineTo(gx - 4, gy + 17);
1199 ctx.lineTo(gx + 4, gy + 17);
1200 ctx.closePath();
1201 ctx.fill();
1202 ctx.fillText('g', gx - 14, gy);
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1206// onStep(z, h) is called after every integrator step of length h, for
1207// recording trails. speed: see createLoop.
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1208// maxLength: see drawDoublePendulum; a number, or a function read at each draw.
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1209function createDoublePendulum({ canvas, button, params, labels = [], maxLength, speed = 1, onStep = () => {}, onDraw = () => {} }) {
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1210 let state = doubleInitial(params);
1212 function step(dt) {
1213 const n = Math.ceil(dt / 0.0025);
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1214 for (let i = 0; i < n; i++) {
1215 doubleStep(params, state, dt / n);
1216 onStep(state, dt / n);
1220 function draw() {
1221 if (!canvas.clientWidth) return;
1222 const { ctx, w, h } = prepare(canvas);
1223 drawDoublePendulum(ctx, w, h, params, state, labels, typeof maxLength === 'function' ? maxLength() : maxLength);
1224 onDraw(state);
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1227 const loop = createLoop({ button, step, draw, speed });
1229 function setLabels(value) {
1230 labels = value;
1231 draw();
1234 // Back to the initial state, held still.
1235 function reset() {
1236 state = doubleInitial(params);
1237 loop.reset();
1240 return { draw, setLabels, reset, pause: loop.pause };
1243// Page 10: the double pendulum, let go with both rods horizontal
1244const doubleDefaults = { m1: 1, m2: 1, L1: 1, L2: 1, g: 9.8 };
1245const doublePendulum = createDoublePendulum({
1246 canvas: document.getElementById('double-canvas'),
1247 button: document.getElementById('double-toggle'),
1248 params: { ...doubleDefaults, theta1: Math.PI / 2, theta2: Math.PI / 2, p1: 0, p2: 0 },
1249 maxLength: doubleDefaults.L1 + doubleDefaults.L2, // lengths are fixed here, so fill the canvas
1250});
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1252// Pages 11 to 13: double pendulum phase space, projected onto the (theta1, p1)
1253// and (theta2, p2) planes. The p axes cover the momentum sliders' range, which
1254// the high-energy kicks need.
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1255const DOUBLE_PMAX = 20;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1257// Draw the theta_k and p_k axes, with p_k running over +/- pMax; returns the
1258// mapping to canvas coordinates.
1259function doubleAxes(ctx, w, h, k, pMax = DOUBLE_PMAX) {
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1260 const halfW = w / 2 - 30;
1261 const cx = w / 2;
1262 const mid = h / 2;
1263 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1264 const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1265 const fg = color('--fg');
1266 ctx.strokeStyle = fg;
1267 ctx.fillStyle = fg;
1268 ctx.globalAlpha = 0.5;
1269 ctx.lineWidth = 1;
1270 ctx.beginPath();
1271 ctx.moveTo(cx - halfW, mid);
1272 ctx.lineTo(cx + halfW, mid);
1273 ctx.moveTo(cx, 8);
1274 ctx.lineTo(cx, h - 8);
1275 ctx.stroke();
1276 ctx.globalAlpha = 1;
1277 ctx.textAlign = 'center';
1278 ctx.textBaseline = 'middle';
1279 subText(ctx, 'θ', String(k), cx + halfW + 16, mid);
1280 subText(ctx, 'p', String(k), cx + 18, 16);
1281 ctx.font = `13px ${color('--font-body')}`;
1282 ctx.textBaseline = 'top';
1283 ctx.fillText('−π', cx - halfW, mid + 6);
1284 ctx.fillText('π', cx + halfW, mid + 6);
1285 return { thetaToX, pToY };
1288// The trail in the (theta_k, p_k) plane (k = 0 or 1), fading with age and
1289// broken where theta wraps around, then the current state.
1290function drawDoublePlane(canvas, k, trail, state) {
1291 if (!canvas.clientWidth) return;
1292 const { ctx, w, h } = prepare(canvas);
1293 const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1);
1294 const accent = color('--accent');
1295 ctx.save();
1296 ctx.beginPath();
1297 ctx.rect(0, 0, w, h);
1298 ctx.clip();
1299 ctx.strokeStyle = accent;
1300 ctx.lineWidth = 1.5;
1301 const chunks = 6;
1302 for (let c = 0; c < chunks; c++) {
1303 const from = Math.floor((trail.length * c) / chunks);
1304 const to = Math.min(trail.length, Math.floor((trail.length * (c + 1)) / chunks) + 1);
1305 ctx.globalAlpha = 0.15 + (0.75 * (c + 1)) / chunks;
1306 ctx.beginPath();
1307 for (let i = from; i < to; i++) {
1308 const z = trail[i];
1309 const x = thetaToX(z[k]);
1310 const y = pToY(z[k + 2]);
1311 if (i === from || Math.abs(z[k] - trail[i - 1][k]) > Math.PI) ctx.moveTo(x, y);
1312 else ctx.lineTo(x, y);
1314 ctx.stroke();
1316 ctx.restore();
1317 ctx.fillStyle = accent;
1318 ctx.beginPath();
1319 ctx.arc(thetaToX(state[k]), pToY(state[k + 2]), 6, 0, 2 * Math.PI);
1320 ctx.fill();
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1323// Presets grouped by energy, all with the default masses, lengths and g.
1324// Within a group every preset has the same energy H, so their Poincare
1325// sections lie on the same energy surface. Above the resting state
1326// (H = -3 m g L) the groups have 0.5, 1.5 and 3 m g L. Finite-time Lyapunov
1327// exponents put almost all motion at the low energy as regular, a mix at the
1328// medium one ("upper rod only" and "lower rod kicked" weakly chaotic, the rest
1329// regular), and all of it at the high one as chaotic.
1330// State: [theta1, theta2, p1, p2]. A kick starts both rods hanging straight
1331// down with the named rod turning and the other not (yet); "both rods kicked"
1332// starts them turning together.
1333const doublePresetGroups = {
1334 low: {
1335 inphase: ['Normal mode, in phase', [0.5081, 0.7186, 0, 0]], // theta2 = sqrt(2) theta1
1336 outphase: ['Normal mode, out of phase', [0.5081, -0.7186, 0, 0]],
1337 upper: ['Upper rod only', [0.7227, 0, 0, 0]],
1338 lower: ['Lower rod only', [0, 1.0472, 0, 0]],
1341 together: ['Rods together', [Math.PI / 3, Math.PI / 3, 0, 0]],
1342 opposite: ['Rods opposite', [Math.PI / 3, -Math.PI / 3, 0, 0]],
1343 upper: ['Upper rod only', [1.3181, 0, 0, 0]],
1344 lower: ['Lower rod only', [0, 2 * Math.PI / 3, 0, 0]],
1345 kickupper: ['Upper rod kicked', [0, 0, 7.6681, 3.8341]],
1346 kicklower: ['Lower rod kicked', [0, 0, 5.4222, 5.4222]],
1349 together: ['Both rods horizontal', [Math.PI / 2, Math.PI / 2, 0, 0]],
1350 opposite: ['Rods horizontal, opposite', [Math.PI / 2, -Math.PI / 2, 0, 0]],
1351 lowerup: ['Lower rod upright', [Math.PI / 3, Math.PI, 0, 0]],
1352 kickupper: ['Upper rod kicked', [0, 0, 10.8444, 5.4222]],
1353 kicklower: ['Lower rod kicked', [0, 0, 7.6681, 7.6681]],
1354 both: ['Both rods kicked', [0, 0, 10.2879, 6.8586]],
1355 },
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1358function doublePreset(level, name) {
1359 const [theta1, theta2, p1, p2] = doublePresetGroups[level][name][1];
1360 return { theta1, theta2, p1, p2 };
1363// The pivot, rods for the central simulation (started from the ball's
1364// center), and every pendulum's two bobs as points.
1365function drawDoubleCloud(ctx, w, h, params, points, [t1, t2]) {
1366 const fg = color('--fg');
1367 const { L1, L2 } = params;
1368 const px = w / 2;
1369 const py = h / 2;
1370 const unit = (Math.min(h, w) / 2 - 8) / (L1 + L2);
1371 const x1 = px + unit * L1 * Math.sin(t1);
1372 const y1 = py + unit * L1 * Math.cos(t1);
1374 ctx.strokeStyle = fg;
1375 ctx.lineWidth = 1;
1376 ctx.globalAlpha = 0.3;
1377 ctx.setLineDash([4, 4]);
1378 ctx.beginPath();
1379 ctx.moveTo(px, py);
1380 ctx.lineTo(px, py + unit * (L1 + L2));
1381 ctx.stroke();
1382 ctx.setLineDash([]);
1383 ctx.globalAlpha = 1;
1384 ctx.lineWidth = 2;
1385 ctx.beginPath();
1386 ctx.moveTo(px, py);
1387 ctx.lineTo(x1, y1);
1388 ctx.lineTo(x1 + unit * L2 * Math.sin(t2), y1 + unit * L2 * Math.cos(t2));
1389 ctx.stroke();
1390 ctx.fillStyle = fg;
1391 ctx.beginPath();
1392 ctx.arc(px, py, 4, 0, 2 * Math.PI);
1393 ctx.fill();
1395 ctx.fillStyle = color('--accent');
1396 for (const [a1, a2] of points) {
1397 const bx = px + unit * L1 * Math.sin(a1);
1398 const by = py + unit * L1 * Math.cos(a1);
1399 ctx.fillRect(bx - 1, by - 1, 2, 2);
1400 ctx.fillRect(bx + unit * L2 * Math.sin(a2) - 1, by + unit * L2 * Math.cos(a2) - 1, 2, 2);
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1404// Pages 11 to 13 share a layout: the preset and sliders on the left, and the
1405// pendulum above the (theta1, p1) and (theta2, p2) planes on the right. Each
1406// page has its own state and controls, found by id: `${id}-canvas`,
1407// `${id}-plane1`, `${id}-${name}` and so on. mode chooses what the planes show:
1408// 'trail' (page 11) the trajectory in both planes, fading with age;
1409// 'section' (page 12) the trajectory in the (theta1, p1) plane, and in the
1410// (theta2, p2) plane only a dot each time theta1 passes through
1411// zero (straight down) with p1 > 0, a Poincare section;
1412// 'cloud' (page 13) a small 4D ball of starting points around the initial
1413// state, evolving as on the Liouville slides, with every
1414// pendulum's bobs drawn as points and the rods following the
1415// simulation started from the ball's center.
1416function createDoublePhasePage({ id, mode }) {
1417 const params = { ...doubleDefaults, ...doublePreset('low', 'upper') };
1418 const canvas = document.getElementById(`${id}-canvas`);
1419 const button = document.getElementById(`${id}-toggle`);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1420 const planes = [1, 2].map((k) => document.getElementById(`${id}-plane${k}`));
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1421 const energyOut = document.getElementById(`${id}-energy`);
1422 const level = document.getElementById(`${id}-level`);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 1423 const preset = document.getElementById(`${id}-preset`);
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1424 // the speed-up menu, on the trail and section pages only
1425 const speedSelect = document.getElementById(`${id}-speed`);
1428 const e = doubleEnergy(params, z);
1429 energyOut.textContent = (Math.abs(e) < 0.005 ? 0 : e).toFixed(2);
1433 let reset;
1435 if (mode === 'cloud') {
1436 // half-widths of the ball in theta1, theta2, p1, p2; roughly round on screen
1437 const radii = [0.2, 0.2, 1.2, 1.2];
1438 let points;
1439 let central;
1441 function makeCloud() {
1442 const center = doubleInitial(params);
1443 central = center.slice();
1444 points = [];
1445 while (points.length < 600) {
1446 const u = [0, 1, 2, 3].map(() => 2 * Math.random() - 1);
1447 if (u.reduce((sum, v) => sum + v * v, 0) > 1) continue;
1448 const z = center.map((c, i) => c + radii[i] * u[i]);
1449 z[0] = wrapAngle(z[0]);
1450 z[1] = wrapAngle(z[1]);
1451 points.push(z);
1457 const n = Math.ceil(dt / 0.0025);
1458 for (const z of [central, ...points]) {
1459 for (let i = 0; i < n; i++) doubleStep(params, z, dt / n);
1463 function draw() {
1464 if (!canvas.clientWidth) return;
1465 const d = prepare(canvas);
1466 drawDoubleCloud(d.ctx, d.w, d.h, params, points, central);
1467 planes.forEach((plane, k) => {
1468 const { ctx, w, h } = prepare(plane);
1469 const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1);
1470 ctx.save();
1471 ctx.beginPath();
1472 ctx.rect(0, 0, w, h);
1473 ctx.clip();
1474 ctx.fillStyle = color('--accent');
1475 for (const z of points) ctx.fillRect(thetaToX(z[k]) - 1, pToY(z[k + 2]) - 1, 2, 2);
1476 ctx.restore();
1477 });
1478 showEnergy(central);
1481 // the same pace as the other Liouville slides
1482 const loop = createLoop({ button, step, draw, speed: 0.5 });
1483 sim = { draw, pause: loop.pause };
1484 reset = () => {
1485 makeCloud();
1486 loop.reset();
1487 };
1488 } else {
1489 // the trail is sampled every TRAIL_DT of simulated time, so it looks the
1490 // same at every speed, and holds up to TRAIL_MAX samples (1000 s)
1491 const TRAIL_DT = 0.01;
1492 const TRAIL_MAX = 100000;
1493 let trail = [];
1494 let sinceSample = 0;
1495 // section mode: (theta2, p2) at each crossing, and the previous state
1496 let dots = [];
1497 let prev = null;
1499 function recordCrossing(z) {
1500 // theta1 passes through zero (straight down) in either direction, and not
1501 // by wrapping around at +/- pi; interpolate linearly to the crossing and
1502 // keep it if p1 is positive there
1503 const crossed = prev && (prev[0] < 0) !== (z[0] < 0) && Math.abs(z[0] - prev[0]) < Math.PI;
1504 const f = crossed ? -prev[0] / (z[0] - prev[0]) : 0;
1505 if (crossed && prev[2] + f * (z[2] - prev[2]) > 0) {
1506 dots.push([wrapAngle(prev[1] + f * wrapAngle(z[1] - prev[1])), prev[3] + f * (z[3] - prev[3])]);
1507 if (dots.length > 50000) dots = dots.slice(-40000);
1509 prev = z.slice();
1512 function drawDots(plane) {
1513 if (!plane.clientWidth) return;
1514 const { ctx, w, h } = prepare(plane);
1515 const { thetaToX, pToY } = doubleAxes(ctx, w, h, 2);
1517 ctx.beginPath();
1518 ctx.rect(0, 0, w, h);
1519 ctx.clip();
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1520 ctx.fillStyle = color('--accent');
1521 ctx.beginPath();
1522 for (const [t2, p2] of dots) {
1523 const x = thetaToX(t2);
1524 const y = pToY(p2);
1525 ctx.moveTo(x + 0.8, y);
1526 ctx.arc(x, y, 0.8, 0, 2 * Math.PI);
1528 ctx.fill();
1532 sim = createDoublePendulum({
1533 canvas,
1534 button,
1535 params,
1536 // the canvas is short, so fill it: the rods are drawn to scale relative to
1537 // each other, but not across changes of L1 + L2
1538 maxLength: () => params.L1 + params.L2,
1539 speed: () => Number(speedSelect.value),
1540 onStep: (z, h) => {
1541 sinceSample += h;
1542 if (sinceSample >= TRAIL_DT) {
1543 sinceSample = 0;
1544 trail.push(z.slice());
1545 if (trail.length > TRAIL_MAX) trail = trail.slice(-0.8 * TRAIL_MAX);
1547 if (mode === 'section') recordCrossing(z);
1548 },
1549 onDraw: (z) => {
1550 drawDoublePlane(planes[0], 0, trail, z);
1551 if (mode === 'section') drawDots(planes[1]);
1552 else drawDoublePlane(planes[1], 1, trail, z);
1553 showEnergy(z);
1554 },
1557 trail = [];
1558 sinceSample = 0;
1559 dots = [];
1560 prev = null;
1561 sim.reset();
1562 };
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1565 const inputs = ['theta1', 'theta2', 'p1', 'p2', 'm1', 'm2', 'L1', 'L2', 'g'].map((name) => ({
1566 name,
1567 input: document.getElementById(`${id}-${name}`),
1568 output: document.getElementById(`${id}-${name}-value`),
1569 }));
1571 function syncInputs() {
1572 for (const { name, input, output } of inputs) {
1573 input.value = params[name];
1574 output.textContent = params[name].toFixed(2);
1578 for (const { name, input, output } of inputs) {
1579 input.addEventListener('input', () => {
1580 params[name] = Number(input.value);
1581 output.textContent = params[name].toFixed(2);
1582 preset.value = 'custom';
1583 reset();
1584 });
1587 // The preset menu lists the chosen energy's presets, then a Custom entry
1588 // that the sliders select.
1589 function fillPresets() {
1590 preset.replaceChildren();
1591 for (const [value, [label]] of Object.entries(doublePresetGroups[level.value])) {
1592 preset.add(new Option(label, value));
1594 const custom = new Option('Custom', 'custom');
1595 custom.disabled = true;
1596 preset.add(custom);
1599 // A preset restores the default masses, lengths and g along with its initial state.
1600 function applyPreset() {
1601 Object.assign(params, doubleDefaults, doublePreset(level.value, preset.value));
1602 syncInputs();
1603 reset();
1606 level.addEventListener('change', () => {
1607 fillPresets();
1608 applyPreset();
1609 });
1610 preset.addEventListener('change', applyPreset);
1611 fillPresets();
1612 preset.value = 'upper';
1613 syncInputs();
1615 return { draw: sim.draw, pause: sim.pause, reset };
1618const doublePhase = createDoublePhasePage({ id: 'double-phase', mode: 'trail' });
1619const doublePoincare = createDoublePhasePage({ id: 'double-poincare', mode: 'section' });
1620const doubleDispersion = createDoublePhasePage({ id: 'double-dispersion', mode: 'cloud' });
1622// Page 14: Poincare section explorer, with the default masses, lengths and g.
1623// The section is theta1 = 0 with theta1 increasing. Given (theta2, p2) on it
1624// and the energy H, the kinetic energy is quadratic in p1 with two roots, and
1625// the larger one is exactly the one with dtheta1/dt > 0, so each point inside
1626// the allowed region is one state. (With p1 > 0 as the condition instead,
1627// both roots can be positive, and two states would share a point.)
1629// Clicking starts an orbit there, integrated in the background (with
1630// gaussStep, and crossings found by sectionCrossing) until it is complete or
1631// the next click stops it: its dots are binned on a grid of about 5 x 5 slide
1632// pixels, and it stops once EXPLORER_WINDOW dots in a row reach fewer than
1633// EXPLORER_NEW_CELLS new cells (a curve has closed up, or a chaotic region has
1634// mostly filled), or at EXPLORER_MAX_DOTS dots (or 4 simulated seconds per
1635// allowed dot).
1637// Auto starts each new orbit in the middle of the largest gap: the cell
1638// farthest from any dot and from the edge of the allowed region (a chamfer
1639// distance transform on the grid). Each press adds up to AUTO_BATCH orbits,
1640// stopping early when no gap is more than AUTO_MIN_GAP cells from a dot, or
1641// on a click. A press when the gaps are already that small fills smaller ones,
1642// down to 3/4 of the largest gap left (at least one cell); this finds small
1643// islands in a chaotic sea.
1645// Each orbit is colored by an estimate of the dimension of its dots: a regular
1646// orbit lies on a curve (1), a chaotic one fills an area (2). The estimate is
1647// the correlation dimension: the number of pairs of dots closer than r grows
1648// like r^d, so d = log2(C(r) / C(r/2)), with r = 0.03 of the region's half
1649// width (large enough r would see the two sides of a thin loop as an area).
1650// It uses one dot per cell of a grid twice as fine as the one above (the first
1651// to land there), so it measures where the orbit has been rather than how
1652// often: a chaotic orbit that lingers near an island would otherwise look
1653// regular.
1654// Regular orbits all measure about 1, so to tell them apart each orbit has its
1655// own cool color, blended toward red as d goes from 1.25 to 1.85.
1656const EXPLORER_STEP = 0.025;
1657const EXPLORER_GRID = [300, 140];
1658const EXPLORER_FINE_GRID = [600, 280];
1659const EXPLORER_WINDOW = 1000;
1660const EXPLORER_NEW_CELLS = 10;
1661const EXPLORER_MAX_DOTS = 20000;
1662const EXPLORER_MAX_ORBITS = 2000;
1663const AUTO_MIN_GAP = 3;
1664const AUTO_BATCH = 40;
1665// GPU fill: orbits per press, their dot cap, and the crossings each may
1666// report per dispatch
1667const GPU_ORBITS = 256;
1668const GPU_MAX_DOTS = 4000;
1669const GPU_DOTS_PER_DISPATCH = 128;
1670const EXPLORER_COLORS = ['#537eba', '#2e8b57', '#1a9cb0', '#6a4fb3', '#2c5aa0', '#5f9e2f', '#8a5fbf', '#17806d'];
1672// GPU fill: doubleRates, gaussStep and sectionCrossing in WGSL, one orbit per
1673// thread. WebGPU only has 32-bit floats, so this is less precise than the CPU
1674// path (each finished fill logs its largest energy error to the console). Each
1675// dispatch advances every active orbit by P.steps steps and records up to
1676// P.maxDots crossings; the fixed-point iteration stops at a tolerance suited
1677// to 32-bit floats.
1678const EXPLORER_SHADER = `
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 1679struct Params { m1: f32, m2: f32, L1: f32, L2: f32, g: f32, h: f32, steps: u32, maxDots: u32, n: u32, b: f32 }
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1680@group(0) @binding(0) var<uniform> P: Params;
1681@group(0) @binding(1) var<storage, read_write> state: array<vec4f>;
1682@group(0) @binding(2) var<storage, read_write> slopes: array<vec4f>;
1683@group(0) @binding(3) var<storage, read_write> dots: array<vec2f>;
1684@group(0) @binding(4) var<storage, read_write> counts: array<u32>;
1685@group(0) @binding(5) var<storage, read> running: array<u32>;
1687const PI = 3.141592653589793;
1688const A12 = 0.25 - 0.28867513459481287;
1689const A21 = 0.25 + 0.28867513459481287;
1691fn wrapAngle(t: f32) -> f32 { return t - 2.0 * PI * round(t / (2.0 * PI)); }
1693fn maxAbs(v: vec4f) -> f32 {
1694 let a = abs(v);
1695 return max(max(a.x, a.y), max(a.z, a.w));
1698fn rates(z: vec4f) -> vec4f {
1699 let d = z.x - z.y;
1700 let s = sin(d);
1701 let c = cos(d);
1702 let D = P.m1 + P.m2 * s * s;
1703 let T = (P.m2 * P.L2 * P.L2 * z.z * z.z + (P.m1 + P.m2) * P.L1 * P.L1 * z.w * z.w
1704 - 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);
1705 let dT = (z.z * z.w * s / (P.L1 * P.L2) - 2.0 * P.m2 * T * s * c) / D;
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 1706 let w1 = (P.L2 * z.z - P.L1 * z.w * c) / (P.L1 * P.L1 * P.L2 * D);
1707 let w2 = ((P.m1 + P.m2) * P.L1 * z.w - P.m2 * P.L2 * z.z * c) / (P.m2 * P.L1 * P.L2 * P.L2 * D);
1708 return vec4f(w1, w2,
1709 -(P.m1 + P.m2) * P.g * P.L1 * sin(z.x) - dT - P.b * w1,
1710 -P.m2 * P.g * P.L2 * sin(z.y) + dT - P.b * w2);
1713fn hermite(y0: vec4f, f0: vec4f, y1: vec4f, f1: vec4f, h: f32, s: f32) -> vec4f {
1714 let s2 = s * s;
1715 let s3 = s2 * s;
1716 return (2.0 * s3 - 3.0 * s2 + 1.0) * y0 + (s3 - 2.0 * s2 + s) * h * f0
1717 + (3.0 * s2 - 2.0 * s3) * y1 + (s3 - s2) * h * f1;
1720fn crossing(a: vec4f, b: vec4f, h: f32) -> vec2f {
1721 var bu = b;
1722 bu.y = a.y + wrapAngle(b.y - a.y);
1723 let fa = rates(a);
1724 let fb = rates(b);
1725 var lo = 0.0;
1726 var hi = 1.0;
1727 for (var it = 0; it < 24; it++) {
1728 let m = 0.5 * (lo + hi);
1729 if (hermite(a, fa, bu, fb, h, m).x < 0.0) { lo = m; } else { hi = m; }
1731 let y = hermite(a, fa, bu, fb, h, 0.5 * (lo + hi));
1732 return vec2f(wrapAngle(y.y), y.w);
1735@compute @workgroup_size(64)
1736fn main(@builtin(global_invocation_id) id: vec3u) {
1737 let i = id.x;
1738 if (i >= P.n) { return; }
1739 counts[i] = 0u;
1740 if (running[i] == 0u) { return; }
1741 var z = state[i];
1742 var k1 = slopes[2u * i];
1743 var k2 = slopes[2u * i + 1u];
1744 let h = P.h;
1745 var count = 0u;
1746 for (var n = 0u; n < P.steps; n++) {
1747 let a = z;
1748 for (var it = 0; it < 12; it++) {
1749 let n1 = rates(z + h * (0.25 * k1 + A12 * k2));
1750 let n2 = rates(z + h * (A21 * k1 + 0.25 * k2));
1751 let change = max(maxAbs(n1 - k1), maxAbs(n2 - k2));
1752 k1 = n1;
1753 k2 = n2;
1754 if (change * h < 1e-6) { break; }
1756 z += 0.5 * h * (k1 + k2);
1757 z.x = wrapAngle(z.x);
1758 z.y = wrapAngle(z.y);
1759 if (a.x < 0.0 && z.x >= 0.0 && z.x - a.x < PI && count < P.maxDots) {
1760 dots[i * P.maxDots + count] = crossing(a, z, h);
1761 count++;
1764 state[i] = z;
1765 slopes[2u * i] = k1;
1766 slopes[2u * i + 1u] = k2;
1767 counts[i] = count;
9740780Double pendulum listening to orbits slideJeremy Magland 1771// WebGPU device and pipeline for the GPU fill, set up once and shared by the
1772// explorer pages: a promise of { device, pipeline }, or of null without WebGPU.
1773let explorerGpu = null;
1774function explorerGpuSetup() {
1775 explorerGpu ??= (async () => {
1776 const unavailable = (why) => {
1777 console.warn(`[explorer] GPU fill unavailable: ${why}`);
1778 return null;
1779 };
1780 try {
1781 if (!window.isSecureContext) return unavailable(`WebGPU needs a secure context (use http://localhost, not ${location.host})`);
1782 if (!navigator.gpu) return unavailable('this browser has no navigator.gpu');
1783 const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
1784 if (!adapter) return unavailable('requestAdapter() found no GPU adapter (see chrome://gpu)');
1785 const device = await adapter.requestDevice();
1786 const module = device.createShaderModule({ code: EXPLORER_SHADER });
1787 const info = await module.getCompilationInfo();
1788 for (const m of info.messages) console[m.type === 'error' ? 'error' : 'warn'](`[explorer] shader ${m.type} at line ${m.lineNum}:${m.linePos}: ${m.message}`);
1789 const pipeline = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main' } });
1790 console.info('[explorer] GPU fill ready');
1791 return { device, pipeline };
1792 } catch (err) {
1793 return unavailable(err);
1795 })();
1796 return explorerGpu;
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 1799// listen: also play orbits as sound, with createListener (page 15).
1800// damping: with a damping slider (page 16); orbits then spiral inward, so
1801// they are not colored by dimension, and H is the energy they start with.
1802function createExplorer({ id, listen = false, damping = false }) {
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1803 const canvas = document.getElementById(`${id}-canvas`);
1804 const slider = document.getElementById(`${id}-energy`);
1805 const output = document.getElementById(`${id}-energy-value`);
1806 const autoButton = document.getElementById(`${id}-auto`);
1807 const gpuButton = document.getElementById(`${id}-gpu`);
1808 const params = { ...doubleDefaults };
1809 const [gx, gy] = EXPLORER_GRID;
1810 let H = -14.7;
1811 let orbits = [];
1812 let orbitCount = 0;
1813 let auto = false;
9740780Double pendulum listening to orbits slideJeremy Magland 1814 // the orbit being listened to, lit up like a hovered one while it plays
1815 let selected = null;
1816 const listener = listen ? createListener({ id, params, onChange: () => active && draw() }) : null;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1817 // cells reached by any orbit; the grid spans the allowed region,
1818 // |theta2| <= gridThetaMax and |p2| <= gridPMax
1819 let covered = new Uint8Array(gx * gy);
1820 // the last orbit to reach each cell, for finding the orbit under the mouse
1821 let owner = new Array(gx * gy).fill(null);
1822 let hovered = null;
1823 let gridPMax = 0;
1824 let gridThetaMax = Math.PI;
1825 let inside = new Uint8Array(gx * gy); // cells whose center is in the allowed region
1826 let rafId = null;
1827 let active = false;
1828 let view = null; // the latest mapping, for clicks and the dot layer
1829 // dots are drawn once onto this layer and copied to the canvas each frame;
1830 // it is redrawn in full only when the size changes or orbits are removed
1831 const layer = document.createElement('canvas');
1832 let layerDirty = true;
1834 // the largest |p2| on the section, at theta2 = 0
1835 const sectionPMax = () => Math.sqrt(Math.max(0, 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, 0))));
1837 // the largest |theta2| on the section, where H - V(0, theta2) reaches zero
1838 function sectionThetaMax() {
1839 const { m1, m2, L1, L2, g } = params;
1840 return Math.acos(Math.min(1, Math.max(-1, -(H + (m1 + m2) * g * L1) / (m2 * g * L2))));
1843 function sizeGrid() {
1844 gridPMax = sectionPMax();
1845 gridThetaMax = sectionThetaMax();
1846 inside = new Uint8Array(gx * gy);
1847 for (let j = 0; j < gy; j++) {
1848 const p = cellP(j);
1849 for (let i = 0; i < gx; i++) {
1850 inside[j * gx + i] = p * p <= 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, cellTheta(i))) ? 1 : 0;
1855 // the state on the section at (theta2, p2), or null outside the allowed region
1856 function sectionState(t2, p2) {
1857 const { m1, m2, L1, L2 } = params;
1858 const s = 2 * m2 * L2 * L2 * (H - doublePotential(params, 0, t2)) - p2 * p2;
1859 if (s < 0) return null;
1860 const D = m1 + m2 * Math.sin(t2) ** 2;
1861 return [0, t2, (L1 / L2) * p2 * Math.cos(t2) + Math.sqrt(m2 * L1 * L1 * L2 * L2 * D * s) / (m2 * L2 * L2), p2];
1864 // on at most 4000 of the given dots, evenly spread through the orbit
1865 function correlationDimension(dots) {
1866 const all = dots.length / 2;
1867 const stride = Math.ceil(all / 4000);
1868 const n = Math.floor(all / stride);
1869 const m = Math.min(300, n);
1870 const r2 = 0.03 * 0.03;
1871 let c1 = 0;
1872 let c2 = 0;
1873 for (let k = 0; k < m; k++) {
1874 const i = Math.floor((k * n) / m) * stride;
1875 const ti = dots[2 * i];
1876 const pi = dots[2 * i + 1];
1877 for (let jj = 0; jj < n; jj++) {
1878 const j = jj * stride;
1879 if (j === i) continue;
1880 const dx = wrapAngle(ti - dots[2 * j]) / gridThetaMax;
1881 const dy = (pi - dots[2 * j + 1]) / gridPMax;
1882 const d = dx * dx + dy * dy;
1883 if (d < r2) {
1884 c1++;
1885 if (d < r2 / 4) c2++;
1889 return c2 ? Math.log2(c1 / c2) : 0;
1892 // the orbit's own cool color, blended toward red from d = 1.25 to d = 1.85
1893 function orbitColor(o) {
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 1894 if (damping) return o.base;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 1895 if (o.d === null) return null;
1896 const t = Math.min(1, Math.max(0, (o.d - 1.25) / 0.6));
1897 const a = o.base;
1898 const b = color('--force');
1899 const mix = (k) => Math.round((1 - t) * parseInt(a.slice(k, k + 2), 16) + t * parseInt(b.slice(k, k + 2), 16));
1900 return `rgb(${mix(1)}, ${mix(3)}, ${mix(5)})`;
1903 function cellOf(t2, p2, [nx, ny] = EXPLORER_GRID) {
1904 const i = Math.min(nx - 1, Math.max(0, Math.floor(((t2 / gridThetaMax + 1) / 2) * nx)));
1905 const j = Math.min(ny - 1, Math.max(0, Math.floor(((p2 / gridPMax + 1) / 2) * ny)));
1906 return j * nx + i;
1909 const cellTheta = (i) => (((i + 0.5) / gx) * 2 - 1) * gridThetaMax;
1910 const cellP = (j) => (((j + 0.5) / gy) * 2 - 1) * gridPMax;
1912 // the empty cell farthest from any dot (any cell set in mask) and from the
1913 // edge of the allowed region, as { i, j, gap } with gap in cells
1914 function largestGap(mask = covered) {
1915 const dist = new Float32Array(gx * gy);
1916 for (let c = 0; c < gx * gy; c++) dist[c] = inside[c] && !mask[c] ? Infinity : 0;
1917 const r2 = Math.SQRT2;
1918 for (let j = 0; j < gy; j++) {
1919 for (let i = 0; i < gx; i++) {
1920 const c = j * gx + i;
1921 let d = dist[c];
1922 if (i > 0) d = Math.min(d, dist[c - 1] + 1);
1923 if (j > 0) {
1924 d = Math.min(d, dist[c - gx] + 1);
1925 if (i > 0) d = Math.min(d, dist[c - gx - 1] + r2);
1926 if (i < gx - 1) d = Math.min(d, dist[c - gx + 1] + r2);
1928 dist[c] = d;
1931 let best = { i: 0, j: 0, gap: 0 };
1932 for (let j = gy - 1; j >= 0; j--) {
1933 for (let i = gx - 1; i >= 0; i--) {
1934 const c = j * gx + i;
1935 let d = dist[c];
1936 if (i < gx - 1) d = Math.min(d, dist[c + 1] + 1);
1937 if (j < gy - 1) {
1938 d = Math.min(d, dist[c + gx] + 1);
1939 if (i < gx - 1) d = Math.min(d, dist[c + gx + 1] + r2);
1940 if (i > 0) d = Math.min(d, dist[c + gx - 1] + r2);
1942 dist[c] = d;
1943 if (d > best.gap && d < Infinity) best = { i, j, gap: d };
1946 return best;
1949 // this press's smallest gap to fill, and how many orbits it may still add
1950 let autoGap = AUTO_MIN_GAP;
1951 let autoLeft = 0;
1953 function setAuto(on) {
1954 auto = on;
1955 autoButton.textContent = on ? 'Stop' : 'Auto';
1956 if (!on) return;
1957 const gap = largestGap().gap;
1958 autoGap = gap >= AUTO_MIN_GAP ? AUTO_MIN_GAP : Math.max(1, 0.75 * gap);
1959 autoLeft = AUTO_BATCH;
1960 if (!orbits.some(unfinishedCpu)) nextAuto();
1963 // up to n starting points spread over the gaps: each goes in the largest gap
1964 // left, then claims a disk of half that gap's radius
1965 function spreadStarts(n) {
1966 const mask = covered.slice();
1967 const starts = [];
1968 while (starts.length < n) {
1969 const { i, j, gap } = largestGap(mask);
1970 if (gap < 1) break;
1971 starts.push([cellTheta(i), cellP(j)]);
1972 const r = Math.max(1, gap / 2);
1973 const m = Math.ceil(r);
1974 for (let dj = -m; dj <= m; dj++) {
1975 for (let di = -m; di <= m; di++) {
1976 const ii = i + di;
1977 const jj = j + dj;
1978 if (di * di + dj * dj <= r * r && ii >= 0 && ii < gx && jj >= 0 && jj < gy) mask[jj * gx + ii] = 1;
1982 return starts;
1985 function nextAuto() {
1986 const { i, j, gap } = largestGap();
1987 if (autoLeft <= 0 || gap < autoGap) {
1988 setAuto(false);
1989 return;
1991 autoLeft--;
1992 addOrbit(cellTheta(i), cellP(j));
1995 // A new orbit at (theta2, p2) on the section, or null outside the allowed
1996 // region. gpu: integrated by the GPU fill rather than on the CPU.
1997 function makeOrbit(t2, p2, { gpu = false, maxDots = EXPLORER_MAX_DOTS } = {}) {
1998 const z = sectionState(t2, p2);
1999 if (!z) return null;
2000 const k = [0, 0, 0, 0, 0, 0, 0, 0];
2001 doubleRates(params, z[0], z[1], z[2], z[3], k);
2002 for (let i = 0; i < 4; i++) k[i + 4] = k[i];
2003 const o = {
9740780Double pendulum listening to orbits slideJeremy Magland 2004 z, start: z.slice(), prev: z.slice(), k, dots: [], firsts: [], d: null, steps: 0, done: false, drawn: 0, gpu, maxDots,
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2005 base: EXPLORER_COLORS[orbitCount++ % EXPLORER_COLORS.length],
2006 // cells of the two grids this orbit has reached (dropped when it finishes)
2007 cells: new Set(), fine: new Set(), windowDots: 0, windowNew: 0,
2008 };
2009 addDot(o, t2, p2);
2010 orbits.push(o);
2011 if (orbits.length > EXPLORER_MAX_ORBITS) {
2012 orbits.shift();
2013 layerDirty = true;
2014 covered = new Uint8Array(gx * gy);
2015 owner = new Array(gx * gy).fill(null);
2016 for (const other of orbits) {
2017 for (let i = 0; i < other.dots.length; i += 2) {
2018 const c = cellOf(other.dots[i], other.dots[i + 1]);
2019 covered[c] = 1;
2020 owner[c] = other;
2023 if (!orbits.includes(hovered)) hovered = null;
9740780Double pendulum listening to orbits slideJeremy Magland 2024 if (!orbits.includes(selected)) selected = null;
2026 return o;
2029 // a clicked or Auto orbit; it stops any orbit still being filled in
2030 function addOrbit(t2, p2) {
9740780Double pendulum listening to orbits slideJeremy Magland 2031 if (!sectionState(t2, p2)) return null;
2033 for (const prev of orbits) finish(prev);
9740780Double pendulum listening to orbits slideJeremy Magland 2034 const o = makeOrbit(t2, p2);
9740780Double pendulum listening to orbits slideJeremy Magland 2036 return o;
2039 const unfinishedCpu = (o) => !o.done && !o.gpu;
2041 function addDot(o, t2, p2) {
2042 o.dots.push(t2, p2);
2043 const c = cellOf(t2, p2);
2044 if (!o.cells.has(c)) {
2045 o.cells.add(c);
2046 covered[c] = 1;
2047 owner[c] = o;
2048 o.windowNew++;
2050 const f = cellOf(t2, p2, EXPLORER_FINE_GRID);
2051 if (!o.fine.has(f)) {
2052 o.fine.add(f);
2053 o.firsts.push(t2, p2);
2055 const n = o.dots.length / 2;
2056 // the dimension estimate at 500 dots, then each time the count doubles
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 2057 if (!damping && (n === 500 || (n > 1000 && (n & (n - 1)) === 0))) {
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2058 o.d = correlationDimension(o.firsts);
2059 o.drawn = 0; // redraw the whole orbit in its new color
2061 if (++o.windowDots === EXPLORER_WINDOW) {
2062 if (o.windowNew < EXPLORER_NEW_CELLS) finish(o);
2063 o.windowDots = 0;
2064 o.windowNew = 0;
2066 if (n >= o.maxDots) finish(o);
2069 // the step cap: 4 simulated seconds per allowed dot
2070 const maxSteps = (o) => (4 / EXPLORER_STEP) * o.maxDots;
2072 function finish(o) {
2073 if (o.done) return;
2074 o.done = true;
2075 o.cells = null; // only needed while dots arrive
2076 o.fine = null;
2077 // too few dots for an estimate (stopped early by a click): it stays gray
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 2078 if (damping || o.dots.length / 2 < 300) return;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2079 o.d = correlationDimension(o.firsts);
2080 o.drawn = 0;
2083 // integrate orbit o for about ms milliseconds
2084 function advance(o, ms) {
2085 const until = performance.now() + ms;
2086 const { z, prev, k } = o;
2087 const cap = maxSteps(o);
2088 while (!o.done && performance.now() < until) {
2089 for (let i = 0; i < 50 && !o.done; i++) {
2090 prev[0] = z[0];
2091 prev[1] = z[1];
2092 prev[2] = z[2];
2093 prev[3] = z[3];
2094 gaussStep(params, z, EXPLORER_STEP, k);
2095 if (++o.steps > cap) finish(o);
2096 if (prev[0] < 0 && z[0] >= 0 && z[0] - prev[0] < Math.PI) {
2097 const [t2, p2] = sectionCrossing(params, prev, z, EXPLORER_STEP);
2098 addDot(o, t2, p2);
2104 function frame() {
2105 rafId = null;
2106 const busy = orbits.filter(unfinishedCpu);
2107 for (const o of busy) advance(o, 12 / busy.length);
2108 if (auto && !orbits.some(unfinishedCpu)) nextAuto();
2109 draw();
2112 function resume() {
2113 if (active && rafId === null && orbits.some(unfinishedCpu)) rafId = requestAnimationFrame(frame);
2114 if (active && gpuRun && !gpuRun.looping) gpuLoop(gpuRun);
2117 // GPU fill: GPU_ORBITS orbits at once, spread over the gaps, each integrated
2118 // by one thread of EXPLORER_SHADER. Their dots go through addDot like any
2119 // other orbit's, with a cap of GPU_MAX_DOTS. The button only appears if
2120 // WebGPU is available.
2121 let gpu = null; // { device, pipeline } once set up
2122 let gpuRun = null; // the fill in progress
9740780Double pendulum listening to orbits slideJeremy Magland 2124 explorerGpuSetup().then((g) => {
2125 if (!g) return;
2126 gpu = g;
2127 gpuButton.hidden = false;
2128 });
2130 function startGpu() {
2131 setAuto(false);
2132 for (const o of orbits) finish(o);
2133 const run = { orbits: [], steps: 256, looping: false, started: performance.now() };
2134 for (const [t2, p2] of spreadStarts(GPU_ORBITS)) {
2135 const o = makeOrbit(t2, p2, { gpu: true, maxDots: GPU_MAX_DOTS });
2136 if (o) run.orbits.push(o);
2138 const n = run.orbits.length;
2139 if (!n) return;
2140 const { device, pipeline } = gpu;
2141 const buffer = (size, usage) => device.createBuffer({ size, usage });
2142 const { STORAGE, COPY_SRC, COPY_DST, UNIFORM, MAP_READ } = GPUBufferUsage;
2143 run.params = buffer(48, UNIFORM | COPY_DST);
2144 run.state = buffer(n * 16, STORAGE | COPY_SRC | COPY_DST);
2145 run.slopes = buffer(n * 32, STORAGE | COPY_DST);
2146 run.dots = buffer(n * GPU_DOTS_PER_DISPATCH * 8, STORAGE | COPY_SRC);
2147 run.counts = buffer(n * 4, STORAGE | COPY_SRC);
2148 run.running = buffer(n * 4, STORAGE | COPY_DST);
2149 run.readDots = buffer(n * GPU_DOTS_PER_DISPATCH * 8, MAP_READ | COPY_DST);
2150 run.readCounts = buffer(n * 4, MAP_READ | COPY_DST);
2151 run.readState = buffer(n * 16, MAP_READ | COPY_DST);
2152 device.queue.writeBuffer(run.state, 0, Float32Array.from(run.orbits.flatMap((o) => o.z)));
2153 device.queue.writeBuffer(run.slopes, 0, Float32Array.from(run.orbits.flatMap((o) => o.k)));
2154 run.bindGroup = device.createBindGroup({
2155 layout: pipeline.getBindGroupLayout(0),
2156 entries: [run.params, run.state, run.slopes, run.dots, run.counts, run.running]
2157 .map((b, binding) => ({ binding, resource: { buffer: b } })),
2158 });
2159 gpuRun = run;
2160 gpuButton.textContent = 'Stop';
2161 resume();
2164 function stopGpu() {
2165 const run = gpuRun;
2166 if (!run) return;
2167 gpuRun = null;
2168 gpuButton.textContent = 'GPU fill';
2169 for (const o of run.orbits) finish(o);
2170 if (!run.looping) destroyRun(run);
2173 function destroyRun(run) {
2174 for (const key of ['params', 'state', 'slopes', 'dots', 'counts', 'running', 'readDots', 'readCounts', 'readState']) run[key].destroy();
2177 // dispatch, read back the crossings, repeat; aims for about 30 ms a round
2178 async function gpuLoop(run) {
2179 run.looping = true;
2180 const { device, pipeline } = gpu;
2181 const n = run.orbits.length;
2182 const per = GPU_DOTS_PER_DISPATCH;
2183 try {
2184 while (gpuRun === run && active) {
2185 const t0 = performance.now();
2186 const p = new ArrayBuffer(48);
2187 new Float32Array(p).set([params.m1, params.m2, params.L1, params.L2, params.g, EXPLORER_STEP]);
2188 new Uint32Array(p).set([run.steps, per, n], 6);
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 2189 new Float32Array(p)[9] = params.b ?? 0;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2190 device.queue.writeBuffer(run.params, 0, p);
2191 device.queue.writeBuffer(run.running, 0, Uint32Array.from(run.orbits, (o) => (o.done ? 0 : 1)));
2192 const encoder = device.createCommandEncoder();
2193 const pass = encoder.beginComputePass();
2194 pass.setPipeline(pipeline);
2195 pass.setBindGroup(0, run.bindGroup);
2196 pass.dispatchWorkgroups(Math.ceil(n / 64));
2197 pass.end();
2198 encoder.copyBufferToBuffer(run.counts, 0, run.readCounts, 0, n * 4);
2199 encoder.copyBufferToBuffer(run.dots, 0, run.readDots, 0, n * per * 8);
2200 device.queue.submit([encoder.finish()]);
2201 await Promise.all([run.readCounts.mapAsync(GPUMapMode.READ), run.readDots.mapAsync(GPUMapMode.READ)]);
2202 const counts = new Uint32Array(run.readCounts.getMappedRange()).slice();
2203 const dots = new Float32Array(run.readDots.getMappedRange()).slice();
2204 run.readCounts.unmap();
2205 run.readDots.unmap();
2206 if (gpuRun !== run) break;
2207 run.orbits.forEach((o, i) => {
2208 if (o.done) return;
2209 for (let j = 0; j < counts[i] && !o.done; j++) addDot(o, dots[2 * (i * per + j)], dots[2 * (i * per + j) + 1]);
2210 o.steps += run.steps;
2211 if (o.steps > maxSteps(o)) finish(o);
2212 });
2213 draw();
2214 if (run.orbits.every((o) => o.done)) {
2215 await reportGpu(run);
2216 gpuRun = null;
2217 gpuButton.textContent = 'GPU fill';
2218 break;
2220 const ms = performance.now() - t0;
2221 run.steps = Math.max(32, Math.min(4096, Math.round(run.steps * (ms < 20 ? 1.5 : ms > 50 ? 0.7 : 1))));
2223 } catch (err) {
2224 console.error('[explorer] GPU fill failed:', err);
2225 if (gpuRun === run) {
2226 gpuRun = null;
2227 gpuButton.textContent = 'GPU fill';
2228 for (const o of run.orbits) finish(o);
2231 run.looping = false;
2232 if (gpuRun !== run) destroyRun(run);
2235 // log how well the 32-bit integration kept the energy
2236 async function reportGpu(run) {
2237 const { device } = gpu;
2238 const n = run.orbits.length;
2239 const encoder = device.createCommandEncoder();
2240 encoder.copyBufferToBuffer(run.state, 0, run.readState, 0, n * 16);
2241 device.queue.submit([encoder.finish()]);
2242 await run.readState.mapAsync(GPUMapMode.READ);
2243 const z = new Float32Array(run.readState.getMappedRange()).slice();
2244 run.readState.unmap();
2245 let worst = 0;
2246 for (let i = 0; i < n; i++) worst = Math.max(worst, Math.abs(doubleEnergy(params, z.slice(4 * i, 4 * i + 4)) - H));
2247 const dots = run.orbits.reduce((sum, o) => sum + o.dots.length / 2, 0);
2248 const seconds = ((performance.now() - run.started) / 1000).toFixed(1);
2249 console.info(`[explorer] GPU fill: ${n} orbits, ${dots} dots in ${seconds} s; largest energy error ${worst.toExponential(1)} at H = ${H}`);
2252 // draw dots not yet on the layer
2253 function updateLayer(thetaToX, pToY) {
2254 if (layer.width !== canvas.width || layer.height !== canvas.height) {
2255 layer.width = canvas.width;
2256 layer.height = canvas.height;
2257 layerDirty = true;
2259 const lctx = layer.getContext('2d');
2260 lctx.setTransform(canvas.getContext('2d').getTransform());
2261 if (layerDirty) {
2262 lctx.clearRect(0, 0, view.w, view.h);
2263 for (const o of orbits) o.drawn = 0;
2264 layerDirty = false;
2266 const fg = color('--fg');
2267 for (const o of orbits) {
2268 const col = orbitColor(o);
2269 lctx.fillStyle = col ?? fg;
2270 lctx.globalAlpha = col ? 1 : 0.4;
2271 // an orbit with no estimate yet goes underneath, so its gray never
2272 // covers colored dots (a new orbit in a chaotic sea spreads over it);
2273 // once colored it is redrawn on top
2274 lctx.globalCompositeOperation = col ? 'source-over' : 'destination-over';
2275 const { dots } = o;
2276 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);
2277 o.drawn = dots.length / 2;
2279 lctx.globalAlpha = 1;
2280 lctx.globalCompositeOperation = 'source-over';
2283 function draw() {
2284 active = true;
2285 if (!canvas.clientWidth) return;
2286 const { ctx, w, h } = prepare(canvas);
2287 const pMax = Math.max(sectionPMax(), 0.5) * 1.08;
2288 if (!view || view.w !== w || view.h !== h || view.pMax !== pMax) layerDirty = true;
2289 const { thetaToX, pToY } = doubleAxes(ctx, w, h, 2, pMax);
2290 view = { w, h, pMax };
2291 const fg = color('--fg');
2293 // boundary of the allowed region, p2 = +/- sqrt(2 m2 L2^2 (H - V(0, theta2)))
2294 ctx.strokeStyle = fg;
2295 ctx.globalAlpha = 0.4;
2296 ctx.lineWidth = 1;
2297 for (const sign of [1, -1]) {
2298 ctx.beginPath();
2299 let drawing = false;
2300 for (let i = 0; i <= 400; i++) {
2301 const t = -Math.PI + (2 * Math.PI * i) / 400;
2302 const k = 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, t));
2303 if (k < 0) {
2304 drawing = false;
2305 continue;
2307 const x = thetaToX(t);
2308 const y = pToY(sign * Math.sqrt(k));
2309 if (drawing) ctx.lineTo(x, y);
2310 else ctx.moveTo(x, y);
2311 drawing = true;
2313 ctx.stroke();
2315 ctx.globalAlpha = 1;
2317 updateLayer(thetaToX, pToY);
2318 ctx.save();
2319 ctx.setTransform(1, 0, 0, 1, 0, 0);
2320 // the orbit under the mouse lights up: the rest dims, and it is drawn
2321 // on top with larger dots
9740780Double pendulum listening to orbits slideJeremy Magland 2322 // (or, with no hover, the one playing)
2323 const lit = hovered ?? (listener?.playing ? selected : null);
2324 if (lit) ctx.globalAlpha = 0.25;
2326 ctx.restore();
9740780Double pendulum listening to orbits slideJeremy Magland 2327 if (lit) {
2328 ctx.fillStyle = orbitColor(lit) ?? fg;
2329 const { dots } = lit;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2330 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);
2333 if (!orbits.length) {
2334 ctx.fillStyle = fg;
2335 ctx.globalAlpha = 0.6;
2336 ctx.font = `18px ${color('--font-body')}`;
2337 ctx.textAlign = 'center';
2338 ctx.textBaseline = 'bottom';
9740780Double pendulum listening to orbits slideJeremy Magland 2339 const hint = listener ? 'Click inside the curve to start an orbit and listen to it, or press Auto' : 'Click inside the curve to start an orbit, or press Auto';
2340 ctx.fillText(hint, w / 2, h - 12);
2343 resume();
2346 // (theta2, p2) under a mouse event, inverting doubleAxes' mapping
2347 function eventPoint(e) {
2348 const rect = canvas.getBoundingClientRect();
2349 const x = ((e.clientX - rect.left) / rect.width) * view.w;
2350 const y = ((e.clientY - rect.top) / rect.height) * view.h;
2351 return [((x - view.w / 2) / (view.w / 2 - 30)) * Math.PI, ((view.h / 2 - y) / (view.h / 2 - 16)) * view.pMax];
2354 canvas.addEventListener('click', (e) => {
2355 if (!view) return;
2356 const [t2, p2] = eventPoint(e);
2357 if (Math.abs(t2) > Math.PI) return;
abcc9b6Light up a clicked orbit so it is not dimmed by the previous hoverJeremy Magland 2358 // the clicked orbit lights up, and stays lit until the mouse moves away
2359 // (otherwise the orbit that was under the mouse stays lit, and dims the
2360 // new one to almost nothing)
2361 clickAt = [e.clientX, e.clientY];
2362 // listening: a click on an orbit's dots plays it, and a click elsewhere
2363 // starts a new orbit and plays that
2364 const near = listener && orbitNear(t2, p2, 1);
9740780Double pendulum listening to orbits slideJeremy Magland 2365 if (near) {
2366 selected = near;
9740780Double pendulum listening to orbits slideJeremy Magland 2368 listener.play(near.start);
2369 return;
9740780Double pendulum listening to orbits slideJeremy Magland 2372 const o = addOrbit(t2, p2);
2374 setHovered(o);
2375 if (listener) {
9740780Double pendulum listening to orbits slideJeremy Magland 2376 selected = o;
2377 listener.play(o.start);
abcc9b6Light up a clicked orbit so it is not dimmed by the previous hoverJeremy Magland 2381 // the orbit with a dot in the nearest cell within r cells of (t2, p2)
2382 function orbitNear(t2, p2, r = 3) {
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2383 if (Math.abs(t2) > gridThetaMax + 0.1 || Math.abs(p2) > gridPMax * 1.05) return null;
2384 const c0 = cellOf(t2, p2);
2385 const i0 = c0 % gx;
2386 const j0 = (c0 - i0) / gx;
2387 let best = null;
2388 let bestD = Infinity;
abcc9b6Light up a clicked orbit so it is not dimmed by the previous hoverJeremy Magland 2389 for (let dj = -r; dj <= r; dj++) {
2390 for (let di = -r; di <= r; di++) {
2392 const j = j0 + dj;
2393 if (i < 0 || i >= gx || j < 0 || j >= gy) continue;
2394 const o = owner[j * gx + i];
2395 const d = di * di + dj * dj;
2396 if (o && d < bestD) {
2397 best = o;
2398 bestD = d;
2402 return best;
2405 let hoverFrame = null;
2406 function setHovered(o) {
2407 if (o === hovered) return;
2408 hovered = o;
2409 if (hoverFrame === null) {
2410 hoverFrame = requestAnimationFrame(() => {
2411 hoverFrame = null;
2412 draw();
2413 });
abcc9b6Light up a clicked orbit so it is not dimmed by the previous hoverJeremy Magland 2417 // where the last click was, in client pixels, until the mouse leaves it
2418 let clickAt = null;
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2419 canvas.addEventListener('mousemove', (e) => {
2421 if (clickAt && Math.hypot(e.clientX - clickAt[0], e.clientY - clickAt[1]) < 12) return;
2422 clickAt = null;
2423 setHovered(orbitNear(...eventPoint(e)));
2424 });
2425 canvas.addEventListener('mouseleave', () => {
2426 clickAt = null;
2427 setHovered(null);
2430 autoButton.addEventListener('click', () => {
2431 stopGpu();
2432 setAuto(!auto);
2433 });
2435 gpuButton.addEventListener('click', () => {
2436 if (gpuRun) stopGpu();
2437 else if (gpu) startGpu();
2438 });
2440 function reset() {
2442 stopGpu();
2443 orbits = [];
2444 orbitCount = 0;
2445 covered = new Uint8Array(gx * gy);
2446 owner = new Array(gx * gy).fill(null);
2447 hovered = null;
9740780Double pendulum listening to orbits slideJeremy Magland 2448 selected = null;
2449 listener?.clear();
2451 layerDirty = true;
2452 draw();
2456 output.textContent = H.toFixed(1);
2457 sizeGrid();
2458 slider.addEventListener('input', () => {
2459 H = Number(slider.value);
2460 output.textContent = H.toFixed(1);
2461 reset();
2462 });
2465 const bSlider = document.getElementById(`${id}-damping`);
2466 const bOutput = document.getElementById(`${id}-damping-value`);
2467 params.b = DAMPED_B;
2468 bSlider.value = params.b;
2469 bOutput.textContent = params.b.toFixed(4);
2470 bSlider.addEventListener('input', () => {
2471 params.b = Number(bSlider.value);
2472 bOutput.textContent = params.b.toFixed(4);
2473 reset();
2474 });
2478 active = false;
2479 cancelAnimationFrame(rafId);
2480 rafId = null;
9740780Double pendulum listening to orbits slideJeremy Magland 2481 listener?.stop();
9740780Double pendulum listening to orbits slideJeremy Magland 2484 const drawAll = () => {
2485 draw();
2486 listener?.draw();
2487 };
2489 return { draw: drawAll, pause, reset };
2492// Page 15: listening to orbits. The explorer of page 14, plus sound: a click
2493// on an orbit plays it, and a click on an empty spot starts a new orbit there
2494// and plays that. The sound is one coordinate of the orbit (or the lower bob's
2495// horizontal position) as a waveform, with the motion sped up by the
2496// Frequency slider's factor so that it is audible. For scale: with the
2497// default masses and lengths the two small-swing normal modes have
2498// omega^2 = (g / L)(2 -/+ sqrt 2), or 0.38 and 0.92 Hz, so x400 puts them at
2499// 150 and 370 Hz.
2501// For the sound the orbit is integrated on its own, from its first point on
2502// the section, with gaussStep at EXPLORER_STEP; samples between steps come
2503// from cubic Hermite interpolation with the rates at both ends (as in
2504// sectionCrossing). The waveform is centered and scaled by the range it
2505// covers over a warm-up of LISTEN_WARMUP steps, and the scale shrinks if it
2506// later goes further. It is made in chunks of LISTEN_CHUNK samples, scheduled
2507// up to LISTEN_AHEAD seconds ahead of playback, so the slider and the signal
2508// menu take effect within that time.
2510// The spectrogram is the AnalyserNode's spectrum of what is playing (before
2511// the volume), a column every 1/60 s, linear in frequency up to LISTEN_FMAX.
2512const LISTEN_WARMUP = 4000;
2513const LISTEN_CHUNK = 2048;
2514const LISTEN_AHEAD = 0.25;
2515const LISTEN_VOLUME = 0.3;
2516const LISTEN_FFT = 8192;
2517const LISTEN_FMAX = 2000;
2518const LISTEN_COLUMNS = 480;
2519const LISTEN_COLUMN_MS = 1000 / 60;
2521// the menu's signals, from the state (theta1, theta2, p1, p2)
2522const listenSignals = {
2523 theta1: (params, z) => wrapAngle(z[0]),
2524 theta2: (params, z) => wrapAngle(z[1]),
2525 p1: (params, z) => z[2],
2526 p2: (params, z) => z[3],
2527 x: ({ L1, L2 }, z) => L1 * Math.sin(z[0]) + L2 * Math.sin(z[1]),
2530// The orbit from state start as a waveform: next(out, speed) fills out with
2531// the following samples, at speed simulated seconds per second of sound.
2532function orbitWaveform(params, start, signalName, sampleRate) {
2533 const h = EXPLORER_STEP;
2534 const z = start.slice();
2535 const k = [0, 0, 0, 0, 0, 0, 0, 0];
2536 const a = [0, 0, 0, 0]; // the state at the last step, and its rates
2537 const fa = [0, 0, 0, 0];
2538 const fb = [0, 0, 0, 0]; // the rates at z
2539 const y = [0, 0, 0, 0];
2540 doubleRates(params, z[0], z[1], z[2], z[3], fb);
2541 for (let i = 0; i < 4; i++) k[i] = k[i + 4] = fb[i];
2542 let tau = 0; // simulated time since the last step
2543 let signal = null;
2544 let mid = 0;
2545 let dev = 1;
2547 function step() {
2548 for (let i = 0; i < 4; i++) {
2549 a[i] = z[i];
2550 fa[i] = fb[i];
2552 gaussStep(params, z, h, k);
2553 doubleRates(params, z[0], z[1], z[2], z[3], fb);
2556 // the state at fraction s of the last step, into y
2557 function interpolate(s) {
2558 const s2 = s * s;
2559 const s3 = s2 * s;
2560 for (let i = 0; i < 4; i++) {
2561 const b = i < 2 ? a[i] + wrapAngle(z[i] - a[i]) : z[i];
2562 y[i] = (2 * s3 - 3 * s2 + 1) * a[i] + (s3 - 2 * s2 + s) * h * fa[i]
2563 + (3 * s2 - 2 * s3) * b + (s3 - s2) * h * fb[i];
2567 // the signal's range over the warm-up, on a copy of the current state
2568 function setSignal(name) {
2569 signal = listenSignals[name];
2570 const zc = z.slice();
2571 const kc = k.slice();
2572 let lo = Infinity;
2573 let hi = -Infinity;
2574 for (let n = 0; n < LISTEN_WARMUP; n++) {
2575 gaussStep(params, zc, h, kc);
2576 const v = signal(params, zc);
2577 lo = Math.min(lo, v);
2578 hi = Math.max(hi, v);
2580 mid = 0.5 * (lo + hi);
2581 dev = Math.max(1e-6, 0.5 * (hi - lo));
2584 function next(out, speed) {
2585 const dt = speed / sampleRate;
2586 for (let n = 0; n < out.length; n++) {
2587 tau += dt;
2588 while (tau >= h) {
2589 step();
2590 tau -= h;
2592 interpolate(tau / h);
2593 const v = signal(params, y) - mid;
2594 dev = Math.max(dev, Math.abs(v));
2595 out[n] = (0.9 * v) / dev;
2599 step();
2600 setSignal(signalName);
2601 return { next, setSignal };
2604// Sound and spectrogram for the listening page; play(start) plays the orbit
2605// from state start, and onChange is called when playback starts or stops.
2606function createListener({ id, params, onChange }) {
2607 const canvas = document.getElementById(`${id}-spectrogram`);
2608 const button = document.getElementById(`${id}-play`);
2609 const signalMenu = document.getElementById(`${id}-signal`);
2610 const speedSlider = document.getElementById(`${id}-speed`);
2611 const speedOutput = document.getElementById(`${id}-speed-value`);
2612 let audio = null; // set up on the first play, which comes from a click
2613 let start = null;
2614 let wave = null;
2615 let playing = false;
2616 let timer = null;
2617 let nextTime = 0;
2618 let sources = [];
2619 let rafId = null;
2620 let lastColumn = 0;
2622 // the slider runs over x100 to x2000, evenly in log
2623 const speed = () => 100 * 20 ** Number(speedSlider.value);
2624 speedSlider.value = Math.log(4) / Math.log(20);
2625 function showSpeed() {
2626 const s = speed();
2627 speedOutput.textContent = `×${s < 1000 ? Math.round(s / 10) * 10 : Math.round(s / 100) * 100}`;
2629 showSpeed();
2630 speedSlider.addEventListener('input', showSpeed);
2631 signalMenu.addEventListener('change', () => wave?.setSignal(signalMenu.value));
2633 function setupAudio() {
2634 const ctx = new AudioContext();
2635 const analyser = ctx.createAnalyser();
2636 analyser.fftSize = LISTEN_FFT;
2637 analyser.smoothingTimeConstant = 0;
2638 analyser.minDecibels = -100;
2639 analyser.maxDecibels = -20;
2640 const gain = ctx.createGain();
2641 gain.gain.value = 0;
2642 analyser.connect(gain);
2643 gain.connect(ctx.destination);
2644 const rows = Math.round(LISTEN_FMAX / (ctx.sampleRate / LISTEN_FFT));
2645 const spec = document.createElement('canvas');
2646 spec.width = LISTEN_COLUMNS;
2647 spec.height = rows;
2648 const sctx = spec.getContext('2d');
2649 // colors from the background through the accent to the text color
2650 const hex = (name) => [1, 3, 5].map((i) => parseInt(color(name).slice(i, i + 2), 16));
2651 const stops = [hex('--bg'), hex('--accent'), hex('--fg')];
2652 const lut = new Uint8Array(256 * 3);
2653 for (let v = 0; v < 256; v++) {
2654 const t = (2 * v) / 255;
2655 const [c0, c1] = t < 1 ? [stops[0], stops[1]] : [stops[1], stops[2]];
2656 const f = t < 1 ? t : t - 1;
2657 for (let c = 0; c < 3; c++) lut[3 * v + c] = Math.round((1 - f) * c0[c] + f * c1[c]);
2659 audio = { ctx, analyser, gain, rows, spec, sctx, lut, bytes: new Uint8Array(analyser.frequencyBinCount), column: sctx.createImageData(1, rows) };
2660 clearSpectrogram();
2663 function clearSpectrogram() {
2664 if (!audio) return;
2665 audio.sctx.fillStyle = color('--bg');
2666 audio.sctx.fillRect(0, 0, LISTEN_COLUMNS, audio.rows);
2669 // make and queue chunks up to LISTEN_AHEAD seconds ahead
2670 function schedule() {
2671 const { ctx, analyser } = audio;
2672 if (nextTime < ctx.currentTime + 0.01) nextTime = ctx.currentTime + 0.05; // fell behind
2673 while (nextTime < ctx.currentTime + LISTEN_AHEAD) {
2674 const buffer = ctx.createBuffer(1, LISTEN_CHUNK, ctx.sampleRate);
2675 wave.next(buffer.getChannelData(0), speed());
2676 const src = ctx.createBufferSource();
2677 src.buffer = buffer;
2678 src.connect(analyser);
2679 src.start(nextTime);
2680 src.onended = () => {
2681 sources = sources.filter((s) => s !== src);
2682 };
2683 sources.push(src);
2684 nextTime += LISTEN_CHUNK / ctx.sampleRate;
2688 // fade out what is queued over 30 ms
2689 function silence() {
2690 const { ctx, gain } = audio;
2691 const now = ctx.currentTime;
2692 gain.gain.cancelScheduledValues(now);
2693 gain.gain.setValueAtTime(gain.gain.value, now);
2694 gain.gain.linearRampToValueAtTime(0, now + 0.03);
2695 for (const src of sources) src.stop(now + 0.035);
2696 sources = [];
2699 function play(s) {
2700 if (s) start = s;
2701 if (!start) return;
2702 if (!audio) setupAudio();
2703 const { ctx, gain } = audio;
2704 ctx.resume();
2705 clearInterval(timer);
2706 silence();
2707 wave = orbitWaveform(params, start, signalMenu.value, ctx.sampleRate);
2708 nextTime = ctx.currentTime + 0.05;
2709 gain.gain.setValueAtTime(0, nextTime);
2710 gain.gain.linearRampToValueAtTime(LISTEN_VOLUME, nextTime + 0.03);
2711 schedule();
2712 timer = setInterval(schedule, 40);
2713 playing = true;
2714 button.disabled = false;
2715 button.textContent = 'Stop';
2716 lastColumn = performance.now();
2717 if (rafId === null) rafId = requestAnimationFrame(loop);
2718 onChange();
2721 function stop() {
2722 if (!playing) return;
2723 playing = false;
2724 clearInterval(timer);
2725 silence();
2726 button.textContent = 'Play';
2727 onChange();
2730 // stop, and forget the orbit (its energy level is gone)
2731 function clear() {
2732 stop();
2733 start = null;
2734 wave = null;
2735 button.disabled = true;
2736 clearSpectrogram();
2737 draw();
2740 // shift the spectrogram left and add the current spectrum on the right
2741 function addColumn() {
2742 const { analyser, rows, spec, sctx, lut, bytes, column } = audio;
2743 analyser.getByteFrequencyData(bytes);
2744 sctx.drawImage(spec, -1, 0);
2745 for (let r = 0; r < rows; r++) {
2746 const v = bytes[rows - 1 - r];
2747 column.data[4 * r] = lut[3 * v];
2748 column.data[4 * r + 1] = lut[3 * v + 1];
2749 column.data[4 * r + 2] = lut[3 * v + 2];
2750 column.data[4 * r + 3] = 255;
2752 sctx.putImageData(column, LISTEN_COLUMNS - 1, 0);
2755 function loop() {
2756 rafId = null;
2757 if (!playing) return;
2758 const now = performance.now();
2759 if (now - lastColumn > 200) lastColumn = now - LISTEN_COLUMN_MS; // after a stall
2760 while (now - lastColumn >= LISTEN_COLUMN_MS) {
2761 addColumn();
2762 lastColumn += LISTEN_COLUMN_MS;
2764 draw();
2765 rafId = requestAnimationFrame(loop);
2768 function draw() {
2769 if (!canvas.clientWidth) return;
2770 const { ctx, w, h } = prepare(canvas);
2771 // room on top for the Play button, and on the left for the axis
2772 const x0 = 46;
2773 const y0 = 40;
2774 const x1 = w - 4;
2775 const y1 = h - 24;
2776 const fg = color('--fg');
2777 if (audio) {
2778 ctx.imageSmoothingEnabled = true;
2779 ctx.drawImage(audio.spec, x0, y0, x1 - x0, y1 - y0);
2781 ctx.strokeStyle = fg;
2782 ctx.fillStyle = fg;
2783 ctx.globalAlpha = 0.5;
2784 ctx.lineWidth = 1;
2785 ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
2786 ctx.globalAlpha = 1;
2787 ctx.font = `13px ${color('--font-body')}`;
2788 ctx.textAlign = 'right';
2789 ctx.textBaseline = 'middle';
2790 for (let f = 0; f <= LISTEN_FMAX; f += 500) ctx.fillText(String(f), x0 - 6, y1 - (f / LISTEN_FMAX) * (y1 - y0));
2791 ctx.textAlign = 'left';
2792 ctx.textBaseline = 'bottom';
2793 ctx.fillText('Hz', 4, y0 - 12);
2794 ctx.textAlign = 'right';
2795 ctx.textBaseline = 'top';
2796 ctx.fillText('time →', x1, y1 + 6);
2797 if (!start) {
2798 ctx.globalAlpha = 0.6;
2799 ctx.font = `16px ${color('--font-body')}`;
2800 ctx.textAlign = 'center';
2801 ctx.textBaseline = 'middle';
2802 ctx.fillText('Click an orbit to listen to it', (x0 + x1) / 2, (y0 + y1) / 2);
2803 ctx.globalAlpha = 1;
2807 button.addEventListener('click', () => {
2808 if (playing) stop();
2809 else play();
2810 });
2812 return {
2813 play, stop, clear, draw,
2814 get playing() { return playing; },
2815 };
9740780Double pendulum listening to orbits slideJeremy Magland 2818const doubleExplorer = createExplorer({ id: 'double-explorer' });
2819const doubleListen = createExplorer({ id: 'double-listen', listen: true });
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 2821// Page 16: listening to orbits with damping. The default b gives a decay time
2822// of very roughly 1000 simulated seconds, a few seconds of sound at x400.
2823const DAMPED_B = 0.002;
2824const doubleDamped = createExplorer({ id: 'double-damped', listen: true, damping: true });
2827 spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase, liouville, 'liouville-pendulum': liouvillePendulum, damped,
4bc2ee1Double pendulum Poincare section, dispersion and section explorer slidesJeremy Magland 2828 double: doublePendulum, 'double-phase': doublePhase, 'double-poincare': doublePoincare, 'double-dispersion': doubleDispersion,
9740780Double pendulum listening to orbits slideJeremy Magland 2829 'double-explorer': doubleExplorer, 'double-listen': doubleListen,
01a2ed1Double pendulum listening to orbits with damping slideJeremy Magland 2830 'double-damped': doubleDamped,
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 2833// Reset buttons next to Start: back to the initial state, with trails cleared.
2834const resets = {
2835 'pendulum-phase': resetPendulumPhase,
2837for (const [name, sim] of Object.entries(sims)) {
2838 document.getElementById(`${name}-reset`).addEventListener('click', resets[name] ?? sim.reset);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2841const pages = [...document.querySelectorAll('.page')];
2842const pageIds = pages.map((p) => p.id);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 2843const navPrev = document.getElementById('nav-prev');
2844const navNext = document.getElementById('nav-next');
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2845const navPos = document.getElementById('nav-pos');
2847// Flatiron logo on every slide.
2848pages.forEach((p) => {
2849 const img = document.createElement('img');
2850 img.className = 'logo';
2851 img.alt = 'Flatiron Institute';
2852 img.src = 'assets/flatiron-logo.png';
2853 p.appendChild(img);
2854});
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2856// Table of contents: the slide counter in the nav bar opens a list of slide
2857// titles; T toggles it and Escape closes it.
2858const toc = document.getElementById('toc');
2859const tocList = document.getElementById('toc-list');
2861pages.forEach((p) => {
2862 const li = document.createElement('li');
2863 const b = document.createElement('button');
2864 b.textContent = p.querySelector('h1, h2').textContent;
2865 b.addEventListener('click', () => {
2866 location.hash = p.id;
2867 setTocOpen(false);
2870 tocList.appendChild(li);
2871});
2873function setTocOpen(open) {
2874 toc.hidden = !open;
2875 navPos.setAttribute('aria-expanded', String(open));
2876 if (open) tocList.querySelector('.current')?.scrollIntoView({ block: 'nearest' });
2879navPos.addEventListener('click', (e) => {
2880 e.stopPropagation();
2881 setTocOpen(toc.hidden);
2882});
2883document.addEventListener('click', (e) => {
2884 if (!toc.hidden && !toc.contains(e.target)) setTocOpen(false);
2885});
2887function show(id) {
2888 pages.forEach((p) => p.classList.toggle('active', p.id === id));
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 2889 const i = pageIds.indexOf(id);
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2890 const prev = pages[i - 1];
2891 const next = pages[i + 1];
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 2892 // label each button with a one-word hint of where it goes
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2893 navPrev.textContent = prev ? `← ${prev.dataset.hint}` : '←';
2894 navNext.textContent = next ? `${next.dataset.hint} →` : '→';
2895 navPrev.disabled = !prev;
2896 navNext.disabled = !next;
2897 navPos.textContent = `${i + 1} / ${pages.length} \u2630`;
2898 tocList.querySelectorAll('button').forEach((b, j) => b.classList.toggle('current', j === i));
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 2899 for (const [name, sim] of Object.entries(sims)) {
2900 if (name === id) sim.draw();
2901 else sim.pause();
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2905// Scale the 1920 x 1080 deck to the largest size that fits, centered, and
2906// redraw the visible diagram at the new resolution.
2907const SLIDE_W = 1920;
2908const SLIDE_H = 1080;
2909const MARGIN = 16;
2910const stage = document.querySelector('main');
2911const deck = document.getElementById('deck');
2913function fitDeck() {
2914 stage.style.bottom = `${document.querySelector('.pager').offsetHeight}px`;
2915 const w = stage.clientWidth;
2916 const h = stage.clientHeight;
2917 deckScale = Math.min((w - 2 * MARGIN) / SLIDE_W, (h - 2 * MARGIN) / SLIDE_H);
2918 deck.style.transform = `scale(${deckScale})`;
2919 deck.style.left = `${(w - SLIDE_W * deckScale) / 2}px`;
2920 deck.style.top = `${(h - SLIDE_H * deckScale) / 2}px`;
2921 const active = document.querySelector('.page.active');
2922 if (active) sims[active.id]?.draw();
2925window.addEventListener('resize', fitDeck);
2926// Canvas text uses the bundled fonts, so redraw once they have loaded.
2927document.fonts?.ready.then(fitDeck);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 2929document.querySelectorAll('[data-tex]').forEach((el) => {
2930 katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' });
2931});
2933document.querySelectorAll('[data-solution]').forEach((toggle) => {
2934 toggle.addEventListener('click', () => {
2935 const solution = document.getElementById(toggle.dataset.solution);
2936 solution.hidden = !solution.hidden;
2937 toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution';
2938 });
2939});
2941// Pages that start centered: revealing splits them into text and diagram
2942// panels and labels the diagram.
2943const revealLabels = {
2944 spring: ['m', 'k', 'q', 'F', 'p'],
2945 energy: [], // stays unlabeled, so the bars are the only thing moving
2946 pendulum: ['m', 'L', 'theta', 'p', 'g'],
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2947 double: ['m', 'L', 'theta', 'g'],
2950document.querySelectorAll('[data-reveal]').forEach((button) => {
2951 button.addEventListener('click', () => {
2952 const id = button.dataset.reveal;
2953 const section = document.getElementById(id);
2954 button.hidden = true;
2955 section.classList.add('split');
2956 section.querySelector('.text').hidden = false;
2957 sims[id].setLabels(revealLabels[id]);
2958 });
2959});
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 2961// Replay of how recipe.md was written, from app/crafted-link.js (npm run crafted-link).
2962if (window.CRAFTED_LINK) {
2963 const link = document.getElementById('crafted-link');
2964 link.href = window.CRAFTED_LINK;
2965 link.hidden = false;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 2968// The current page lives in the URL hash, so reloading stays put.
2969function showFromHash() {
2970 const id = location.hash.slice(1);
2971 show(document.getElementById(id)?.classList.contains('page') ? id : 'landing');
2972 window.scrollTo(0, 0);
2975window.addEventListener('hashchange', showFromHash);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 2977showFromHash();
2979document.querySelectorAll('[data-goto]').forEach((el) => {
2980 el.addEventListener('click', () => {
2981 location.hash = el.dataset.goto;
2982 });
2983});
2985function goToIndex(i) {
2986 location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))];
2989function currentIndex() {
2990 return pageIds.indexOf(document.querySelector('.page.active').id);
2993navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1));
2994navNext.addEventListener('click', () => goToIndex(currentIndex() + 1));
2996document.addEventListener('keydown', (e) => {
2997 if (e.altKey || e.ctrlKey || e.metaKey) return;
d6afb6aTemplate styling, double pendulum pages and Liouville updatesJeremy Magland 2998 if (e.target.closest?.('input, select, textarea')) return; // arrow keys belong to the control
2999 if (e.key === 't' || e.key === 'T') {
3000 setTocOpen(toc.hidden);
3001 return;
3003 if (e.key === 'Escape' && !toc.hidden) {
3004 setTocOpen(false);
3005 return;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 3007 const target = {
3008 ArrowLeft: currentIndex() - 1,
3009 ArrowRight: currentIndex() + 1,
3010 Home: 0,
3011 End: pageIds.length - 1,
3012 }[e.key];
3013 if (target === undefined) return;
3014 e.preventDefault();
3015 goToIndex(target);
3016});
↑↓ move↵openescclose