/ interactive_tutorials / hamiltonian_systems
Sign in
interactive_tutorials / hamiltonian_systems
hamiltonian_systems / app / main.js
1017 lines · 31.5 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}
8// Size a canvas for the device pixel ratio and return its context and CSS size.
9function prepare(canvas) {
10 const ctx = canvas.getContext('2d');
11 const dpr = window.devicePixelRatio || 1;
12 const w = canvas.clientWidth;
13 const h = canvas.clientHeight;
14 if (canvas.width !== w * dpr || canvas.height !== h * dpr) {
15 canvas.width = w * dpr;
16 canvas.height = h * dpr;
17 }
18 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
19 ctx.clearRect(0, 0, w, h);
20 return { ctx, w, h };
23// Horizontal layout shared by the spring diagram, the q0 slider and the phase plot,
24// so that a given q sits at the same x on all of them.
25function layout(w) {
26 const rest = w * 0.5;
27 const swing = Math.min(w * 0.3, 200);
28 return { rest, swing, qToX: (q) => rest + q * swing };
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 31// Wall, floor and a spring reaching a block centered at position q. drawBody
32// draws whatever is attached (it gets the scene geometry), before the
33// rest-position marker goes on top. Returns the geometry for labels.
34function drawSpringScene(ctx, w, h, q, drawBody) {
35 const fg = color('--fg');
36 const { rest, swing, qToX } = layout(w);
37 const wallX = 20;
38 const floorY = h * 0.62;
39 const box = 50;
40 const center = qToX(q);
41 const springY = floorY - box / 2;
43 // wall and floor
44 ctx.strokeStyle = fg;
45 ctx.lineWidth = 2;
46 ctx.beginPath();
47 ctx.moveTo(wallX, floorY - box * 1.6);
48 ctx.lineTo(wallX, floorY);
49 ctx.lineTo(w - 10, floorY);
50 ctx.stroke();
52 // spring (zig-zag)
53 const coils = 12;
54 const amp = 10;
55 const start = wallX;
56 const end = center - box / 2;
57 const lead = 12;
58 ctx.lineWidth = 1.5;
59 ctx.beginPath();
60 ctx.moveTo(start, springY);
61 ctx.lineTo(start + lead, springY);
62 const len = end - start - 2 * lead;
63 for (let i = 0; i < coils; i++) {
64 const sx = start + lead + ((i + 0.5) / coils) * len;
65 ctx.lineTo(sx, springY + (i % 2 ? amp : -amp));
66 }
67 ctx.lineTo(end - lead, springY);
68 ctx.lineTo(end, springY);
69 ctx.stroke();
71 const scene = { rest, swing, qToX, floorY, box, springY, amp, start, end, center };
72 drawBody(scene);
74 // rest position marker
75 ctx.strokeStyle = fg;
76 ctx.globalAlpha = 0.3;
77 ctx.setLineDash([4, 4]);
78 ctx.beginPath();
79 ctx.moveTo(rest, floorY - box * 1.4);
80 ctx.lineTo(rest, floorY + 34);
81 ctx.stroke();
82 ctx.setLineDash([]);
83 ctx.globalAlpha = 1;
84 return scene;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 87// params: { k, m, q0 }, read live so sliders can change them.
88// labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw.
89// pScale: length of the p arrow per unit momentum, as a fraction of the swing;
90// by default the arrow peaks at the same length as q.
91function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) {
92 let q = params.q0;
93 let p = 0;
95 function step(dt) {
96 // velocity Verlet on dq/dt = p/m, dp/dt = -k q
97 const { k, m } = params;
98 const f = -k * q;
99 q += (p / m) * dt + (0.5 * f / m) * dt * dt;
100 p += 0.5 * (f - k * q) * dt;
101 }
103 function draw() {
104 if (!canvas.clientWidth) return;
105 const { ctx, w, h } = prepare(canvas);
107 const fg = color('--fg');
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 108 const { rest, swing, qToX, floorY, box, springY, amp, start, end, center } = drawSpringScene(ctx, w, h, q, (sc) => {
109 ctx.fillStyle = color('--accent');
110 ctx.fillRect(sc.center - sc.box / 2, sc.floorY - sc.box, sc.box, sc.box);
111 });
113 onDraw(q, p);
115 if (!labels.length) return;
117 ctx.font = 'italic 18px Georgia, serif';
118 ctx.textAlign = 'center';
120 if (labels.includes('m')) {
121 ctx.fillStyle = color('--bg');
122 ctx.textBaseline = 'middle';
123 ctx.fillText('m', center, floorY - box / 2);
124 }
125 if (labels.includes('k')) {
126 ctx.fillStyle = fg;
127 ctx.textBaseline = 'bottom';
128 ctx.fillText('k', (start + end) / 2, springY - amp - 4);
129 }
130 if (labels.includes('q0')) {
131 // where the block was let go from
132 const x0 = qToX(params.q0);
133 ctx.strokeStyle = fg;
134 ctx.globalAlpha = 0.5;
135 ctx.setLineDash([2, 3]);
136 ctx.beginPath();
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 137 ctx.moveTo(x0, floorY - box - 48);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 138 ctx.lineTo(x0, floorY);
139 ctx.stroke();
140 ctx.setLineDash([]);
141 ctx.globalAlpha = 1;
142 ctx.fillStyle = fg;
143 ctx.textBaseline = 'bottom';
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 144 // the serif font has no subscript zero, so draw it smaller and lower
145 ctx.fillText('q', x0 - 4, floorY - box - 52);
146 ctx.font = 'italic 12px Georgia, serif';
147 ctx.fillText('0', x0 + 5, floorY - box - 48);
148 ctx.font = 'italic 18px Georgia, serif';
151 // q below the floor; F and p above the block
152 const { k, m } = params;
153 const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing;
154 if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below');
155 if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above');
156 if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above');
157 }
159 function setLabels(value) {
160 labels = value;
161 draw();
162 }
164 const loop = createLoop({ button, step, draw, speed });
166 // Back to being held at q0, at rest.
167 function reset() {
168 q = params.q0;
169 p = 0;
170 loop.reset();
171 }
173 return { draw, setLabels, reset, pause: loop.pause };
176// Animation driven by a Start / Stop / Continue button.
177function createLoop({ button, step, draw, speed = 1 }) {
178 let running = false;
179 let lastTime = null;
180 let rafId = null;
182 function frame(t) {
183 if (!running) return;
184 if (lastTime !== null) {
185 const dt = speed * Math.min((t - lastTime) / 1000, 0.05);
186 const n = 4;
187 for (let i = 0; i < n; i++) step(dt / n);
188 }
189 lastTime = t;
190 draw();
191 rafId = requestAnimationFrame(frame);
192 }
194 function setRunning(value) {
195 running = value;
196 cancelAnimationFrame(rafId);
197 if (running) {
198 lastTime = null;
199 rafId = requestAnimationFrame(frame);
200 }
201 if (running || button.textContent !== 'Start') {
202 button.textContent = running ? 'Stop' : 'Continue';
203 }
204 }
206 button.addEventListener('click', () => setRunning(!running));
207 window.addEventListener('resize', draw);
209 return {
210 pause: () => running && setRunning(false),
211 reset: () => {
212 setRunning(false);
213 button.textContent = 'Start';
214 draw();
215 },
216 };
219// Pendulum: a bob of mass m on a massless rod of length L, angle theta from
220// straight down, kept in [-pi, pi].
221// params: { m, L, g, theta0, p0 }, read live so sliders can change them.
222// labels: which of 'm', 'L', 'theta', 'p', 'g' to draw.
223// centered: put the pivot mid-canvas so the bob can go over the top; the rod
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 224// is then drawn to scale, with L = 1.2 (the slider's maximum) filling the canvas.
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 225// pScale: length of the p arrow in px per unit momentum; by default the arrow
226// peaks at 70px when let go from theta0 at rest.
227function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) {
228 let theta = params.theta0;
229 let p = params.p0;
231 function step(dt) {
232 // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta)
233 const { m, L, g } = params;
234 p -= 0.5 * dt * m * g * L * Math.sin(theta);
235 theta += dt * p / (m * L * L);
236 p -= 0.5 * dt * m * g * L * Math.sin(theta);
237 if (theta > Math.PI) theta -= 2 * Math.PI;
238 if (theta < -Math.PI) theta += 2 * Math.PI;
239 }
241 function draw() {
242 if (!canvas.clientWidth) return;
243 const { ctx, w, h } = prepare(canvas);
244 const fg = color('--fg');
245 const accent = color('--accent');
246 const { m, L, g } = params;
247 const px = w / 2;
248 const py = centered ? h / 2 : 30;
249 const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4);
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 250 const rod = centered ? maxRod * L / 1.2 : maxRod;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 251 const bx = px + rod * Math.sin(theta);
252 const by = py + rod * Math.cos(theta);
253 const r = 18;
255 // ceiling (only when hanging from the top) and pivot
256 ctx.strokeStyle = fg;
257 ctx.lineWidth = 2;
258 if (!centered) {
259 ctx.beginPath();
260 ctx.moveTo(px - 50, py);
261 ctx.lineTo(px + 50, py);
262 ctx.stroke();
263 }
265 // vertical reference
266 ctx.globalAlpha = 0.3;
267 ctx.setLineDash([4, 4]);
268 ctx.beginPath();
269 ctx.moveTo(px, py);
270 ctx.lineTo(px, py + rod + r + 10);
271 ctx.stroke();
272 ctx.setLineDash([]);
273 ctx.globalAlpha = 1;
275 // rod and bob
276 ctx.lineWidth = 2;
277 ctx.beginPath();
278 ctx.moveTo(px, py);
279 ctx.lineTo(bx, by);
280 ctx.stroke();
281 ctx.fillStyle = fg;
282 ctx.beginPath();
283 ctx.arc(px, py, 4, 0, 2 * Math.PI);
284 ctx.fill();
285 ctx.fillStyle = accent;
286 ctx.beginPath();
287 ctx.arc(bx, by, r, 0, 2 * Math.PI);
288 ctx.fill();
290 onDraw(theta, p);
292 ctx.font = 'italic 18px Georgia, serif';
293 ctx.textAlign = 'center';
294 ctx.textBaseline = 'middle';
296 if (labels.includes('m')) {
297 ctx.fillStyle = color('--bg');
298 ctx.fillText('m', bx, by);
299 }
301 if (labels.includes('L')) {
302 // beside the middle of the rod, on the side away from the vertical
303 const side = theta >= 0 ? 1 : -1;
304 ctx.fillStyle = fg;
305 ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta));
306 }
308 if (labels.includes('theta')) {
309 // arc from the vertical to the rod
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 310 const arcR = Math.min(44, rod * 0.45);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 311 ctx.strokeStyle = fg;
312 ctx.fillStyle = fg;
313 ctx.lineWidth = 1.5;
314 ctx.beginPath();
315 ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0);
316 ctx.stroke();
317 const mid = Math.PI / 2 - theta / 2;
318 ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid));
319 }
321 if (labels.includes('p')) {
322 // along the direction of motion, perpendicular to the rod
323 const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0)));
324 const len = p * (pScale ?? (peak ? 70 / peak : 0));
325 const tx = Math.cos(theta);
326 const ty = -Math.sin(theta);
327 const momentum = color('--momentum');
328 ctx.strokeStyle = momentum;
329 ctx.fillStyle = momentum;
330 ctx.lineWidth = 1.5;
331 ctx.beginPath();
332 ctx.moveTo(bx, by);
333 ctx.lineTo(bx + tx * len, by + ty * len);
334 ctx.stroke();
335 if (Math.abs(len) > 8) {
336 const d = Math.sign(len);
337 const ex = bx + tx * len;
338 const ey = by + ty * len;
339 ctx.beginPath();
340 ctx.moveTo(ex, ey);
341 ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx);
342 ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx);
343 ctx.closePath();
344 ctx.fill();
345 ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty);
346 }
347 }
349 if (labels.includes('g')) {
350 // gravity, pointing down, off to the side
351 const gx = Math.min(px + maxRod + 50, w - 20);
352 ctx.strokeStyle = fg;
353 ctx.fillStyle = fg;
354 ctx.lineWidth = 1.5;
355 ctx.beginPath();
356 ctx.moveTo(gx, py + 40);
357 ctx.lineTo(gx, py + 90);
358 ctx.stroke();
359 ctx.beginPath();
360 ctx.moveTo(gx, py + 90);
361 ctx.lineTo(gx - 4, py + 82);
362 ctx.lineTo(gx + 4, py + 82);
363 ctx.closePath();
364 ctx.fill();
365 ctx.fillText('g', gx + 14, py + 65);
366 }
367 }
369 const loop = createLoop({ button, step, draw });
371 function setLabels(value) {
372 labels = value;
373 draw();
374 }
376 // Back to the initial state, held still.
377 function reset() {
378 theta = params.theta0;
379 p = params.p0;
380 loop.reset();
381 }
383 return { draw, setLabels, reset, pause: loop.pause };
386function arrow(ctx, from, to, y, col, label, side) {
387 const dir = Math.sign(to - from);
388 ctx.strokeStyle = col;
389 ctx.fillStyle = col;
390 ctx.lineWidth = 1.5;
391 ctx.beginPath();
392 ctx.moveTo(from, y);
393 ctx.lineTo(to, y);
394 ctx.stroke();
395 if (Math.abs(to - from) > 8) {
396 ctx.beginPath();
397 ctx.moveTo(to, y);
398 ctx.lineTo(to - dir * 8, y - 4);
399 ctx.lineTo(to - dir * 8, y + 4);
400 ctx.closePath();
401 ctx.fill();
402 }
403 ctx.textBaseline = side === 'above' ? 'bottom' : 'top';
404 ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4);
407// Horizontal bars for kinetic, potential and total energy, scaled to the total.
408function drawEnergyBars(canvas, params, q, p) {
409 if (!canvas.clientWidth) return;
410 const { ctx, w } = prepare(canvas);
411 const { k, m, q0 } = params;
412 const kinetic = (p * p) / (2 * m);
413 const potential = 0.5 * k * q * q;
414 const total = 0.5 * k * q0 * q0;
416 const fg = color('--fg');
417 const kColor = color('--momentum');
418 const pColor = color('--potential');
419 const labelW = 90;
420 const barW = Math.min(w - labelW - 10, 400);
421 const left = Math.max(0, (w - labelW - barW) / 2);
422 const barX = left + labelW;
423 const rowH = 30;
424 const barH = 18;
426 ctx.font = '15px system-ui, sans-serif';
427 ctx.textBaseline = 'middle';
428 ctx.textAlign = 'right';
430 const rows = [
431 ['Kinetic', [[kinetic, kColor]]],
432 ['Potential', [[potential, pColor]]],
433 ['Total', [[kinetic, kColor], [potential, pColor]]],
434 ];
435 rows.forEach(([label, segments], i) => {
436 const y = 10 + i * rowH;
437 ctx.fillStyle = fg;
438 ctx.fillText(label, barX - 12, y + barH / 2);
440 // outline at full scale, then filled segments
441 ctx.strokeStyle = fg;
442 ctx.globalAlpha = 0.25;
443 ctx.lineWidth = 1;
444 ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH);
445 ctx.globalAlpha = 1;
446 let sx = barX;
447 for (const [value, col] of segments) {
448 const sw = Math.min(value / total, 1) * barW;
449 ctx.fillStyle = col;
450 ctx.fillRect(sx, y, sw, barH);
451 sx += sw;
452 }
453 });
456// Phase plot: q horizontal (lined up with the spring diagram), p vertical.
457// The axes are fixed so changing k and m visibly reshapes the orbit.
458const pMax = 3;
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 460// Draw the q and p axes; returns the mapping from (q, p) to canvas coordinates.
461function springAxes(ctx, w, h) {
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 462 const { rest, swing, qToX } = layout(w);
463 const mid = h / 2;
464 const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
465 const fg = color('--fg');
466 ctx.strokeStyle = fg;
467 ctx.fillStyle = fg;
468 ctx.globalAlpha = 0.5;
469 ctx.lineWidth = 1;
470 ctx.beginPath();
471 ctx.moveTo(rest - swing - 20, mid);
472 ctx.lineTo(rest + swing + 20, mid);
473 ctx.moveTo(rest, 8);
474 ctx.lineTo(rest, h - 8);
475 ctx.stroke();
476 ctx.globalAlpha = 1;
477 ctx.font = 'italic 18px Georgia, serif';
478 ctx.textAlign = 'left';
479 ctx.textBaseline = 'middle';
480 ctx.fillText('q', rest + swing + 26, mid);
481 ctx.textBaseline = 'top';
482 ctx.fillText('p', rest + 8, 6);
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 483 return { rest, swing, mid, qToX, pToY };
486function drawPhase(canvas, params, trail, q, p) {
487 if (!canvas.clientWidth) return;
488 const { ctx, w, h } = prepare(canvas);
489 const { rest, swing, mid, qToX, pToY } = springAxes(ctx, w, h);
490 const fg = color('--fg');
491 const accent = color('--accent');
493 // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m)
494 const { k, m, q0 } = params;
495 const rx = Math.abs(q0) * swing;
496 const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid);
497 ctx.strokeStyle = fg;
498 ctx.globalAlpha = 0.35;
499 ctx.setLineDash([4, 4]);
500 ctx.beginPath();
501 ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI);
502 ctx.stroke();
503 ctx.setLineDash([]);
504 ctx.globalAlpha = 1;
506 // trail, then the current state
507 ctx.strokeStyle = accent;
508 ctx.lineWidth = 2;
509 ctx.beginPath();
510 trail.forEach(([tq, tp], i) => {
511 if (i === 0) ctx.moveTo(qToX(tq), pToY(tp));
512 else ctx.lineTo(qToX(tq), pToY(tp));
513 });
514 ctx.stroke();
515 ctx.fillStyle = accent;
516 ctx.beginPath();
517 ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI);
518 ctx.fill();
521// Page 1: the spring and its equations of motion
522const springParams = { k: 6.25, m: 1, q0: 0.6 };
523const spring = createSpring({
524 canvas: document.getElementById('spring-canvas'),
525 button: document.getElementById('spring-toggle'),
526 params: springParams,
527});
529// Page 2: the same spring, with energy bars. Slower and without the arrows,
530// so the moving bars are the only thing to watch.
531const energyBars = document.getElementById('energy-bars');
532const energy = createSpring({
533 canvas: document.getElementById('energy-canvas'),
534 button: document.getElementById('energy-toggle'),
535 params: springParams,
536 speed: 0.5,
537 onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p),
538});
540// Page 4: phase space, with adjustable q0, k and m
541const phaseParams = { k: 4, m: 1, q0: 0.6 };
542const phaseCanvas = document.getElementById('phase-canvas');
543const phasePlot = document.getElementById('phase-plot');
544const q0Slider = document.getElementById('phase-q0');
545let phaseTrail = [];
546const phase = createSpring({
547 canvas: phaseCanvas,
548 button: document.getElementById('phase-toggle'),
549 params: phaseParams,
550 labels: ['q', 'p', 'k', 'q0'],
551 pScale: 1 / pMax,
552 onDraw: (q, p) => {
553 phaseTrail.push([q, p]);
554 if (phaseTrail.length > 2000) phaseTrail.shift();
555 drawPhase(phasePlot, phaseParams, phaseTrail, q, p);
556 alignSlider();
557 },
558});
560// Stretch the q0 slider so its thumb sits directly under q0 on the diagram.
561function alignSlider() {
562 const { rest, swing } = layout(phaseCanvas.clientWidth);
563 const thumb = 16;
564 q0Slider.style.width = `${2 * swing + thumb}px`;
565 q0Slider.style.marginLeft = `${rest - swing - thumb / 2}px`;
568for (const name of ['q0', 'k', 'm']) {
569 const input = document.getElementById(`phase-${name}`);
570 const output = document.getElementById(`phase-${name}-value`);
571 input.value = phaseParams[name];
572 output.textContent = phaseParams[name];
573 input.addEventListener('input', () => {
574 phaseParams[name] = Number(input.value);
575 output.textContent = input.value;
576 phaseTrail = [];
577 phase.reset();
578 });
581// Page 5: the pendulum
582const pendulum = createPendulum({
583 canvas: document.getElementById('pendulum-canvas'),
584 button: document.getElementById('pendulum-toggle'),
585 params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 },
586});
588// Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 589// +/- pendulumPMax. The separatrix peaks at p = 2 m L sqrt(g L), and the m, L
590// and g slider ranges keep that under 12 even at their maximums.
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 591const pendulumPMax = 12;
592const pendulumDefaults = { m: 1, L: 1, g: 9.8 };
593const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 };
594const pendulumPresets = {
595 small: { theta0: 0.3, p0: 0 },
596 large: { theta0: 2.5, p0: 0 },
597 top: { theta0: 3.1, p0: 0 },
598 rotation: { theta0: 0, p0: 8 },
599 balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds
600 rest: { theta0: 0, p0: 0 },
601};
602const pendulumPlot = document.getElementById('pendulum-plot');
603let pendulumTrail = [];
604const pendulumPhase = createPendulum({
605 canvas: document.getElementById('pendulum-phase-canvas'),
606 button: document.getElementById('pendulum-phase-toggle'),
607 params: pendulumParams,
608 labels: ['theta', 'p'],
609 centered: true,
610 pScale: 60 / pendulumPMax,
611 onDraw: (theta, p) => {
612 pendulumTrail.push([theta, p]);
613 if (pendulumTrail.length > 3000) pendulumTrail.shift();
614 drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p);
615 },
616});
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 618// Draw the pendulum phase portrait (level curves of H) and the theta and p
619// axes; returns the mapping from (theta, p) to canvas coordinates.
620function pendulumAxes(ctx, w, h, params) {
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 621 const { m, L, g } = params;
622 const halfW = Math.min(w / 2 - 30, 300);
623 const cx = w / 2;
624 const mid = h / 2;
625 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
626 const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16);
627 const fg = color('--fg');
629 ctx.save();
630 ctx.beginPath();
631 ctx.rect(cx - halfW, 0, 2 * halfW, h);
632 ctx.clip();
633 // background phase portrait: level curves of H, in units of m g L.
634 // Level 1 is the separatrix between swinging and rotating.
635 const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4];
636 const n = 300;
637 for (const c of levels) {
638 ctx.strokeStyle = fg;
639 ctx.globalAlpha = c === 1 ? 0.45 : 0.15;
640 ctx.lineWidth = c === 1 ? 1.5 : 1;
641 for (const sign of [1, -1]) {
642 ctx.beginPath();
643 let drawing = false;
644 for (let i = 0; i <= n; i++) {
645 const t = -Math.PI + (2 * Math.PI * i) / n;
646 // p^2 / (2 m L^2) - m g L cos(t) = c m g L
647 const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t));
648 if (p2 < 0) { drawing = false; continue; }
649 const x = thetaToX(t);
650 const y = pToY(sign * Math.sqrt(p2));
651 if (drawing) ctx.lineTo(x, y);
652 else ctx.moveTo(x, y);
653 drawing = true;
654 }
655 ctx.stroke();
656 }
657 }
658 ctx.globalAlpha = 1;
660 ctx.restore();
662 // axes
663 ctx.strokeStyle = fg;
664 ctx.fillStyle = fg;
665 ctx.globalAlpha = 0.5;
666 ctx.lineWidth = 1;
667 ctx.beginPath();
668 ctx.moveTo(cx - halfW, mid);
669 ctx.lineTo(cx + halfW, mid);
670 ctx.moveTo(cx, 8);
671 ctx.lineTo(cx, h - 8);
672 ctx.stroke();
673 ctx.globalAlpha = 1;
674 ctx.font = 'italic 18px Georgia, serif';
675 ctx.textBaseline = 'middle';
676 ctx.textAlign = 'left';
677 ctx.fillText('θ', cx + halfW + 6, mid);
678 ctx.textBaseline = 'top';
679 ctx.fillText('p', cx + 8, 6);
680 ctx.font = '13px system-ui, sans-serif';
681 ctx.textAlign = 'center';
682 ctx.fillText('−π', cx - halfW, mid + 6);
683 ctx.fillText('π', cx + halfW, mid + 6);
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 684 return { thetaToX, pToY };
687function drawPendulumPhase(canvas, params, trail, theta, p) {
688 if (!canvas.clientWidth) return;
689 const { ctx, w, h } = prepare(canvas);
690 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, params);
691 const accent = color('--accent');
693 // trail, broken where theta wraps around
694 ctx.strokeStyle = accent;
695 ctx.lineWidth = 2;
696 ctx.beginPath();
697 trail.forEach(([tt, tp], i) => {
698 const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI;
699 if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp));
700 else ctx.lineTo(thetaToX(tt), pToY(tp));
701 });
702 ctx.stroke();
703 ctx.fillStyle = accent;
704 ctx.beginPath();
705 ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI);
706 ctx.fill();
709const pendulumPreset = document.getElementById('pendulum-preset');
710const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({
711 name,
712 input: document.getElementById(`pendulum-${name}`),
713 output: document.getElementById(`pendulum-${name}-value`),
714}));
716function syncPendulumInputs() {
717 for (const { name, input, output } of pendulumInputs) {
718 input.value = pendulumParams[name];
719 output.textContent = pendulumParams[name].toFixed(2);
720 }
723function resetPendulumPhase() {
724 pendulumTrail = [];
725 pendulumPhase.reset();
728for (const { name, input, output } of pendulumInputs) {
729 input.addEventListener('input', () => {
730 pendulumParams[name] = Number(input.value);
731 output.textContent = pendulumParams[name].toFixed(2);
732 pendulumPreset.value = 'custom';
733 resetPendulumPhase();
734 });
737// A preset restores the default m, L and g along with its initial state.
738pendulumPreset.addEventListener('change', () => {
739 const preset = pendulumPresets[pendulumPreset.value];
740 if (!preset) return;
741 Object.assign(pendulumParams, pendulumDefaults, preset);
742 syncPendulumInputs();
743 resetPendulumPhase();
744});
745syncPendulumInputs();
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 747// Liouville's theorem: a disk of starting points evolves under the flow, and
748// the area enclosed by its boundary stays constant.
749// force(q) gives dp/dt; m is the mass term in dq/dt = p / m.
750// center and radii set the disk in (q, p); drawDiagram(ctx, w, h, points) and
751// axes(ctx, w, h) draw the physical picture and the phase-plane axes.
752function createLiouville({ id, force, m, center, radii, drawDiagram, axes }) {
753 const canvas = document.getElementById(`${id}-canvas`);
754 const diagram = document.getElementById(`${id}-diagram`);
755 const areaOut = document.getElementById(`${id}-area`);
756 const [rq, rp] = radii;
757 // a fine boundary, so the area stays accurate as the disk stretches
758 const nb = 2000;
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 759 let boundary;
760 let interior;
761 let jitter;
763 function makeDisk() {
764 boundary = [];
765 for (let i = 0; i < nb; i++) {
766 const a = (2 * Math.PI * i) / nb;
767 boundary.push([center[0] + rq * Math.cos(a), center[1] + rp * Math.sin(a)]);
768 }
769 interior = [];
770 while (interior.length < 600) {
771 const u = 2 * Math.random() - 1;
772 const v = 2 * Math.random() - 1;
773 if (u * u + v * v <= 1) interior.push([center[0] + rq * u, center[1] + rp * v]);
774 }
775 // each point gets a fixed random offset on the diagram, so they form a cloud
776 jitter = interior.map(() => Math.random());
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 778 makeDisk();
780 function step(dt) {
781 // leapfrog on dq/dt = p / m, dp/dt = force(q), for every point
782 for (const pts of [boundary, interior]) {
783 for (const pt of pts) {
784 pt[1] += 0.5 * dt * force(pt[0]);
785 pt[0] += dt * pt[1] / m;
786 pt[1] += 0.5 * dt * force(pt[0]);
787 }
788 }
789 }
791 // shoelace formula on the boundary polygon
792 function area() {
793 let a = 0;
794 for (let i = 0; i < nb; i++) {
795 const [q1, p1] = boundary[i];
796 const [q2, p2] = boundary[(i + 1) % nb];
797 a += q1 * p2 - q2 * p1;
798 }
799 return Math.abs(a) / 2;
800 }
802 function draw() {
803 if (!canvas.clientWidth) return;
804 const d = prepare(diagram);
805 drawDiagram(d.ctx, d.w, d.h, interior, jitter);
807 const { ctx, w, h } = prepare(canvas);
808 const { toX, toY } = axes(ctx, w, h);
809 const accent = color('--accent');
810 ctx.fillStyle = accent;
811 ctx.globalAlpha = 0.15;
812 ctx.beginPath();
813 boundary.forEach(([q, p], i) => (i ? ctx.lineTo(toX(q), toY(p)) : ctx.moveTo(toX(q), toY(p))));
814 ctx.closePath();
815 ctx.fill();
816 ctx.globalAlpha = 1;
817 ctx.strokeStyle = accent;
818 ctx.lineWidth = 1.5;
819 ctx.stroke();
820 for (const [q, p] of interior) ctx.fillRect(toX(q) - 1, toY(p) - 1, 2, 2);
822 areaOut.textContent = area().toFixed(4);
823 }
825 const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 });
827 function reset() {
828 makeDisk();
829 loop.reset();
830 }
832 return { draw, reset, pause: loop.pause };
835// Page 7: the spring, with every block drawn as a point and the spring
836// reaching their mean position. The disk's radii look round at the default scale.
837const liouvilleSpringK = 4;
838const liouville = createLiouville({
839 id: 'liouville',
840 force: (q) => -liouvilleSpringK * q,
841 m: 1,
842 center: [0.5, 0],
843 radii: [0.15, 0.6],
844 drawDiagram: (ctx, w, h, points, jitter) => {
845 const meanQ = points.reduce((sum, pt) => sum + pt[0], 0) / points.length;
846 drawSpringScene(ctx, w, h, meanQ, ({ qToX, floorY, box }) => {
847 ctx.fillStyle = color('--accent');
848 points.forEach(([q], i) => ctx.fillRect(qToX(q) - 1, floorY - 4 - jitter[i] * (box - 8), 2, 2));
849 });
850 },
851 axes: (ctx, w, h) => {
852 const { qToX, pToY } = springAxes(ctx, w, h);
853 return { toX: qToX, toY: pToY };
854 },
855});
857// Page 8: the pendulum, with every bob drawn as a point and the rod pointing
858// at their mean angle. With m = L = 1, p = dtheta/dt.
859const liouvillePendulumParams = { m: 1, L: 1, g: 9.8 };
860const liouvillePendulum = createLiouville({
861 id: 'liouville-pendulum',
862 force: (theta) => -liouvillePendulumParams.g * Math.sin(theta),
863 m: 1,
864 center: [1.2, 0],
865 radii: [0.35, 3.5],
866 drawDiagram: (ctx, w, h, points, jitter) => {
867 const fg = color('--fg');
868 const px = w / 2;
869 const py = 30;
870 const rod = Math.min(h - 80, w * 0.4);
871 const meanTheta = points.reduce((sum, pt) => sum + pt[0], 0) / points.length;
873 ctx.strokeStyle = fg;
874 ctx.lineWidth = 2;
875 ctx.beginPath();
876 ctx.moveTo(px - 50, py);
877 ctx.lineTo(px + 50, py);
878 ctx.stroke();
879 ctx.globalAlpha = 0.3;
880 ctx.setLineDash([4, 4]);
881 ctx.beginPath();
882 ctx.moveTo(px, py);
883 ctx.lineTo(px, py + rod + 28);
884 ctx.stroke();
885 ctx.setLineDash([]);
886 ctx.globalAlpha = 1;
887 ctx.beginPath();
888 ctx.moveTo(px, py);
889 ctx.lineTo(px + (rod - 18) * Math.sin(meanTheta), py + (rod - 18) * Math.cos(meanTheta));
890 ctx.stroke();
892 ctx.fillStyle = color('--accent');
893 points.forEach(([theta], i) => {
894 const r = rod + (jitter[i] - 0.5) * 30;
895 ctx.fillRect(px + r * Math.sin(theta) - 1, py + r * Math.cos(theta) - 1, 2, 2);
896 });
897 },
898 axes: (ctx, w, h) => {
899 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, liouvillePendulumParams);
900 return { toX: thetaToX, toY: pToY };
901 },
902});
904const sims = { spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase, liouville, 'liouville-pendulum': liouvillePendulum };
443a2ccBundle KaTeX locally and add reset buttonsJeremy Magland 906// Reset buttons next to Start: back to the initial state, with trails cleared.
907const resets = {
908 phase: () => {
909 phaseTrail = [];
910 phase.reset();
911 },
912 'pendulum-phase': resetPendulumPhase,
913};
914for (const [name, sim] of Object.entries(sims)) {
915 document.getElementById(`${name}-reset`).addEventListener('click', resets[name] ?? sim.reset);
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 918const pageIds = [...document.querySelectorAll('.page')].map((el) => el.id);
919const navPrev = document.getElementById('nav-prev');
920const navNext = document.getElementById('nav-next');
922function show(id) {
923 document.querySelectorAll('.page').forEach((el) => {
924 el.classList.toggle('active', el.id === id);
925 });
926 const i = pageIds.indexOf(id);
927 // label each button with a one-word hint of where it goes
928 const hint = (j) => document.getElementById(pageIds[j])?.dataset.hint ?? '';
929 navPrev.disabled = i === 0;
930 navNext.disabled = i === pageIds.length - 1;
931 navPrev.textContent = `← ${hint(i - 1)}`.trim();
932 navNext.textContent = `${hint(i + 1)} →`.trim();
933 document.getElementById('nav-pos').textContent = `${i + 1} / ${pageIds.length}`;
934 for (const [name, sim] of Object.entries(sims)) {
935 if (name === id) sim.draw();
936 else sim.pause();
937 }
940document.querySelectorAll('[data-tex]').forEach((el) => {
941 katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' });
942});
944document.querySelectorAll('[data-solution]').forEach((toggle) => {
945 toggle.addEventListener('click', () => {
946 const solution = document.getElementById(toggle.dataset.solution);
947 solution.hidden = !solution.hidden;
948 toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution';
949 });
950});
952// Pages that start centered: revealing splits them into text and diagram
953// panels and labels the diagram.
954const revealLabels = {
955 spring: ['m', 'k', 'q', 'F', 'p'],
956 energy: [], // stays unlabeled, so the bars are the only thing moving
957 pendulum: ['m', 'L', 'theta', 'p', 'g'],
958};
960document.querySelectorAll('[data-reveal]').forEach((button) => {
961 button.addEventListener('click', () => {
962 const id = button.dataset.reveal;
963 const section = document.getElementById(id);
964 button.hidden = true;
965 section.classList.add('split');
966 section.querySelector('.text').hidden = false;
967 sims[id].setLabels(revealLabels[id]);
968 });
969});
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 971// Replay of how recipe.md was written, from app/crafted-link.js (npm run crafted-link).
972if (window.CRAFTED_LINK) {
973 const link = document.getElementById('crafted-link');
974 link.href = window.CRAFTED_LINK;
975 link.hidden = false;
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 978// The current page lives in the URL hash, so reloading stays put.
979function showFromHash() {
980 const id = location.hash.slice(1);
981 show(document.getElementById(id)?.classList.contains('page') ? id : 'landing');
982 window.scrollTo(0, 0);
985window.addEventListener('hashchange', showFromHash);
986showFromHash();
988document.querySelectorAll('[data-goto]').forEach((el) => {
989 el.addEventListener('click', () => {
990 location.hash = el.dataset.goto;
991 });
992});
994function goToIndex(i) {
995 location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))];
998function currentIndex() {
999 return pageIds.indexOf(document.querySelector('.page.active').id);
1002navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1));
1003navNext.addEventListener('click', () => goToIndex(currentIndex() + 1));
1005document.addEventListener('keydown', (e) => {
1006 if (e.altKey || e.ctrlKey || e.metaKey) return;
1007 if (e.target.closest('input, select')) return; // arrow keys belong to the control
1008 const target = {
1009 ArrowLeft: currentIndex() - 1,
1010 ArrowRight: currentIndex() + 1,
1011 Home: 0,
1012 End: pageIds.length - 1,
1013 }[e.key];
1014 if (target === undefined) return;
1015 e.preventDefault();
1016 goToIndex(target);
1017});
↑↓ move↵openescclose