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 };
21}
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 };
29}
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;
85}
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 });
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 112
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();
137 ctx.moveTo(x0, floorY - box - 34);
138 ctx.lineTo(x0, floorY);
139 ctx.stroke();
140 ctx.setLineDash([]);
141 ctx.globalAlpha = 1;
142 ctx.fillStyle = fg;
143 ctx.textBaseline = 'bottom';
144 ctx.fillText('q₀', x0, floorY - box - 36);
145 }
147 // q below the floor; F and p above the block
148 const { k, m } = params;
149 const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing;
150 if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below');
151 if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above');
152 if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above');
153 }
155 function setLabels(value) {
156 labels = value;
157 draw();
158 }
160 const loop = createLoop({ button, step, draw, speed });
162 // Back to being held at q0, at rest.
163 function reset() {
164 q = params.q0;
165 p = 0;
166 loop.reset();
167 }
169 return { draw, setLabels, reset, pause: loop.pause };
170}
172// Animation driven by a Start / Stop / Continue button.
173function createLoop({ button, step, draw, speed = 1 }) {
174 let running = false;
175 let lastTime = null;
176 let rafId = null;
178 function frame(t) {
179 if (!running) return;
180 if (lastTime !== null) {
181 const dt = speed * Math.min((t - lastTime) / 1000, 0.05);
182 const n = 4;
183 for (let i = 0; i < n; i++) step(dt / n);
184 }
185 lastTime = t;
186 draw();
187 rafId = requestAnimationFrame(frame);
188 }
190 function setRunning(value) {
191 running = value;
192 cancelAnimationFrame(rafId);
193 if (running) {
194 lastTime = null;
195 rafId = requestAnimationFrame(frame);
196 }
197 if (running || button.textContent !== 'Start') {
198 button.textContent = running ? 'Stop' : 'Continue';
199 }
200 }
202 button.addEventListener('click', () => setRunning(!running));
203 window.addEventListener('resize', draw);
205 return {
206 pause: () => running && setRunning(false),
207 reset: () => {
208 setRunning(false);
209 button.textContent = 'Start';
210 draw();
211 },
212 };
213}
215// Pendulum: a bob of mass m on a massless rod of length L, angle theta from
216// straight down, kept in [-pi, pi].
217// params: { m, L, g, theta0, p0 }, read live so sliders can change them.
218// labels: which of 'm', 'L', 'theta', 'p', 'g' to draw.
219// centered: put the pivot mid-canvas so the bob can go over the top; the rod
220// is then drawn to scale, with L = 1.5 filling the canvas.
221// pScale: length of the p arrow in px per unit momentum; by default the arrow
222// peaks at 70px when let go from theta0 at rest.
223function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) {
224 let theta = params.theta0;
225 let p = params.p0;
227 function step(dt) {
228 // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta)
229 const { m, L, g } = params;
230 p -= 0.5 * dt * m * g * L * Math.sin(theta);
231 theta += dt * p / (m * L * L);
232 p -= 0.5 * dt * m * g * L * Math.sin(theta);
233 if (theta > Math.PI) theta -= 2 * Math.PI;
234 if (theta < -Math.PI) theta += 2 * Math.PI;
235 }
237 function draw() {
238 if (!canvas.clientWidth) return;
239 const { ctx, w, h } = prepare(canvas);
240 const fg = color('--fg');
241 const accent = color('--accent');
242 const { m, L, g } = params;
243 const px = w / 2;
244 const py = centered ? h / 2 : 30;
245 const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4);
246 const rod = centered ? maxRod * L / 1.5 : maxRod;
247 const bx = px + rod * Math.sin(theta);
248 const by = py + rod * Math.cos(theta);
249 const r = 18;
251 // ceiling (only when hanging from the top) and pivot
252 ctx.strokeStyle = fg;
253 ctx.lineWidth = 2;
254 if (!centered) {
255 ctx.beginPath();
256 ctx.moveTo(px - 50, py);
257 ctx.lineTo(px + 50, py);
258 ctx.stroke();
259 }
261 // vertical reference
262 ctx.globalAlpha = 0.3;
263 ctx.setLineDash([4, 4]);
264 ctx.beginPath();
265 ctx.moveTo(px, py);
266 ctx.lineTo(px, py + rod + r + 10);
267 ctx.stroke();
268 ctx.setLineDash([]);
269 ctx.globalAlpha = 1;
271 // rod and bob
272 ctx.lineWidth = 2;
273 ctx.beginPath();
274 ctx.moveTo(px, py);
275 ctx.lineTo(bx, by);
276 ctx.stroke();
277 ctx.fillStyle = fg;
278 ctx.beginPath();
279 ctx.arc(px, py, 4, 0, 2 * Math.PI);
280 ctx.fill();
281 ctx.fillStyle = accent;
282 ctx.beginPath();
283 ctx.arc(bx, by, r, 0, 2 * Math.PI);
284 ctx.fill();
286 onDraw(theta, p);
288 ctx.font = 'italic 18px Georgia, serif';
289 ctx.textAlign = 'center';
290 ctx.textBaseline = 'middle';
292 if (labels.includes('m')) {
293 ctx.fillStyle = color('--bg');
294 ctx.fillText('m', bx, by);
295 }
297 if (labels.includes('L')) {
298 // beside the middle of the rod, on the side away from the vertical
299 const side = theta >= 0 ? 1 : -1;
300 ctx.fillStyle = fg;
301 ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta));
302 }
304 if (labels.includes('theta')) {
305 // arc from the vertical to the rod
306 const arcR = Math.min(44, rod * 0.6);
307 ctx.strokeStyle = fg;
308 ctx.fillStyle = fg;
309 ctx.lineWidth = 1.5;
310 ctx.beginPath();
311 ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0);
312 ctx.stroke();
313 const mid = Math.PI / 2 - theta / 2;
314 ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid));
315 }
317 if (labels.includes('p')) {
318 // along the direction of motion, perpendicular to the rod
319 const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0)));
320 const len = p * (pScale ?? (peak ? 70 / peak : 0));
321 const tx = Math.cos(theta);
322 const ty = -Math.sin(theta);
323 const momentum = color('--momentum');
324 ctx.strokeStyle = momentum;
325 ctx.fillStyle = momentum;
326 ctx.lineWidth = 1.5;
327 ctx.beginPath();
328 ctx.moveTo(bx, by);
329 ctx.lineTo(bx + tx * len, by + ty * len);
330 ctx.stroke();
331 if (Math.abs(len) > 8) {
332 const d = Math.sign(len);
333 const ex = bx + tx * len;
334 const ey = by + ty * len;
335 ctx.beginPath();
336 ctx.moveTo(ex, ey);
337 ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx);
338 ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx);
339 ctx.closePath();
340 ctx.fill();
341 ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty);
342 }
343 }
345 if (labels.includes('g')) {
346 // gravity, pointing down, off to the side
347 const gx = Math.min(px + maxRod + 50, w - 20);
348 ctx.strokeStyle = fg;
349 ctx.fillStyle = fg;
350 ctx.lineWidth = 1.5;
351 ctx.beginPath();
352 ctx.moveTo(gx, py + 40);
353 ctx.lineTo(gx, py + 90);
354 ctx.stroke();
355 ctx.beginPath();
356 ctx.moveTo(gx, py + 90);
357 ctx.lineTo(gx - 4, py + 82);
358 ctx.lineTo(gx + 4, py + 82);
359 ctx.closePath();
360 ctx.fill();
361 ctx.fillText('g', gx + 14, py + 65);
362 }
363 }
365 const loop = createLoop({ button, step, draw });
367 function setLabels(value) {
368 labels = value;
369 draw();
370 }
372 // Back to the initial state, held still.
373 function reset() {
374 theta = params.theta0;
375 p = params.p0;
376 loop.reset();
377 }
379 return { draw, setLabels, reset, pause: loop.pause };
380}
382function arrow(ctx, from, to, y, col, label, side) {
383 const dir = Math.sign(to - from);
384 ctx.strokeStyle = col;
385 ctx.fillStyle = col;
386 ctx.lineWidth = 1.5;
387 ctx.beginPath();
388 ctx.moveTo(from, y);
389 ctx.lineTo(to, y);
390 ctx.stroke();
391 if (Math.abs(to - from) > 8) {
392 ctx.beginPath();
393 ctx.moveTo(to, y);
394 ctx.lineTo(to - dir * 8, y - 4);
395 ctx.lineTo(to - dir * 8, y + 4);
396 ctx.closePath();
397 ctx.fill();
398 }
399 ctx.textBaseline = side === 'above' ? 'bottom' : 'top';
400 ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4);
401}
403// Horizontal bars for kinetic, potential and total energy, scaled to the total.
404function drawEnergyBars(canvas, params, q, p) {
405 if (!canvas.clientWidth) return;
406 const { ctx, w } = prepare(canvas);
407 const { k, m, q0 } = params;
408 const kinetic = (p * p) / (2 * m);
409 const potential = 0.5 * k * q * q;
410 const total = 0.5 * k * q0 * q0;
412 const fg = color('--fg');
413 const kColor = color('--momentum');
414 const pColor = color('--potential');
415 const labelW = 90;
416 const barW = Math.min(w - labelW - 10, 400);
417 const left = Math.max(0, (w - labelW - barW) / 2);
418 const barX = left + labelW;
419 const rowH = 30;
420 const barH = 18;
422 ctx.font = '15px system-ui, sans-serif';
423 ctx.textBaseline = 'middle';
424 ctx.textAlign = 'right';
426 const rows = [
427 ['Kinetic', [[kinetic, kColor]]],
428 ['Potential', [[potential, pColor]]],
429 ['Total', [[kinetic, kColor], [potential, pColor]]],
430 ];
431 rows.forEach(([label, segments], i) => {
432 const y = 10 + i * rowH;
433 ctx.fillStyle = fg;
434 ctx.fillText(label, barX - 12, y + barH / 2);
436 // outline at full scale, then filled segments
437 ctx.strokeStyle = fg;
438 ctx.globalAlpha = 0.25;
439 ctx.lineWidth = 1;
440 ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH);
441 ctx.globalAlpha = 1;
442 let sx = barX;
443 for (const [value, col] of segments) {
444 const sw = Math.min(value / total, 1) * barW;
445 ctx.fillStyle = col;
446 ctx.fillRect(sx, y, sw, barH);
447 sx += sw;
448 }
449 });
450}
452// Phase plot: q horizontal (lined up with the spring diagram), p vertical.
453// The axes are fixed so changing k and m visibly reshapes the orbit.
454const pMax = 3;
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 456// Draw the q and p axes; returns the mapping from (q, p) to canvas coordinates.
457function springAxes(ctx, w, h) {
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 458 const { rest, swing, qToX } = layout(w);
459 const mid = h / 2;
460 const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
461 const fg = color('--fg');
462 ctx.strokeStyle = fg;
463 ctx.fillStyle = fg;
464 ctx.globalAlpha = 0.5;
465 ctx.lineWidth = 1;
466 ctx.beginPath();
467 ctx.moveTo(rest - swing - 20, mid);
468 ctx.lineTo(rest + swing + 20, mid);
469 ctx.moveTo(rest, 8);
470 ctx.lineTo(rest, h - 8);
471 ctx.stroke();
472 ctx.globalAlpha = 1;
473 ctx.font = 'italic 18px Georgia, serif';
474 ctx.textAlign = 'left';
475 ctx.textBaseline = 'middle';
476 ctx.fillText('q', rest + swing + 26, mid);
477 ctx.textBaseline = 'top';
478 ctx.fillText('p', rest + 8, 6);
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 479 return { rest, swing, mid, qToX, pToY };
480}
482function drawPhase(canvas, params, trail, q, p) {
483 if (!canvas.clientWidth) return;
484 const { ctx, w, h } = prepare(canvas);
485 const { rest, swing, mid, qToX, pToY } = springAxes(ctx, w, h);
486 const fg = color('--fg');
487 const accent = color('--accent');
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 488
489 // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m)
490 const { k, m, q0 } = params;
491 const rx = Math.abs(q0) * swing;
492 const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid);
493 ctx.strokeStyle = fg;
494 ctx.globalAlpha = 0.35;
495 ctx.setLineDash([4, 4]);
496 ctx.beginPath();
497 ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI);
498 ctx.stroke();
499 ctx.setLineDash([]);
500 ctx.globalAlpha = 1;
502 // trail, then the current state
503 ctx.strokeStyle = accent;
504 ctx.lineWidth = 2;
505 ctx.beginPath();
506 trail.forEach(([tq, tp], i) => {
507 if (i === 0) ctx.moveTo(qToX(tq), pToY(tp));
508 else ctx.lineTo(qToX(tq), pToY(tp));
509 });
510 ctx.stroke();
511 ctx.fillStyle = accent;
512 ctx.beginPath();
513 ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI);
514 ctx.fill();
515}
517// Page 1: the spring and its equations of motion
518const springParams = { k: 6.25, m: 1, q0: 0.6 };
519const spring = createSpring({
520 canvas: document.getElementById('spring-canvas'),
521 button: document.getElementById('spring-toggle'),
522 params: springParams,
523});
525// Page 2: the same spring, with energy bars. Slower and without the arrows,
526// so the moving bars are the only thing to watch.
527const energyBars = document.getElementById('energy-bars');
528const energy = createSpring({
529 canvas: document.getElementById('energy-canvas'),
530 button: document.getElementById('energy-toggle'),
531 params: springParams,
532 speed: 0.5,
533 onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p),
534});
536// Page 4: phase space, with adjustable q0, k and m
537const phaseParams = { k: 4, m: 1, q0: 0.6 };
538const phaseCanvas = document.getElementById('phase-canvas');
539const phasePlot = document.getElementById('phase-plot');
540const q0Slider = document.getElementById('phase-q0');
541let phaseTrail = [];
542const phase = createSpring({
543 canvas: phaseCanvas,
544 button: document.getElementById('phase-toggle'),
545 params: phaseParams,
546 labels: ['q', 'p', 'k', 'q0'],
547 pScale: 1 / pMax,
548 onDraw: (q, p) => {
549 phaseTrail.push([q, p]);
550 if (phaseTrail.length > 2000) phaseTrail.shift();
551 drawPhase(phasePlot, phaseParams, phaseTrail, q, p);
552 alignSlider();
553 },
554});
556// Stretch the q0 slider so its thumb sits directly under q0 on the diagram.
557function alignSlider() {
558 const { rest, swing } = layout(phaseCanvas.clientWidth);
559 const thumb = 16;
560 q0Slider.style.width = `${2 * swing + thumb}px`;
561 q0Slider.style.marginLeft = `${rest - swing - thumb / 2}px`;
562}
564for (const name of ['q0', 'k', 'm']) {
565 const input = document.getElementById(`phase-${name}`);
566 const output = document.getElementById(`phase-${name}-value`);
567 input.value = phaseParams[name];
568 output.textContent = phaseParams[name];
569 input.addEventListener('input', () => {
570 phaseParams[name] = Number(input.value);
571 output.textContent = input.value;
572 phaseTrail = [];
573 phase.reset();
574 });
575}
577// Page 5: the pendulum
578const pendulum = createPendulum({
579 canvas: document.getElementById('pendulum-canvas'),
580 button: document.getElementById('pendulum-toggle'),
581 params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 },
582});
584// Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at
585// +/- pendulumPMax, which fits the separatrix at the default parameters
586// with room for rotations.
587const pendulumPMax = 12;
588const pendulumDefaults = { m: 1, L: 1, g: 9.8 };
589const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 };
590const pendulumPresets = {
591 small: { theta0: 0.3, p0: 0 },
592 large: { theta0: 2.5, p0: 0 },
593 top: { theta0: 3.1, p0: 0 },
594 rotation: { theta0: 0, p0: 8 },
595 balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds
596 rest: { theta0: 0, p0: 0 },
597};
598const pendulumPlot = document.getElementById('pendulum-plot');
599let pendulumTrail = [];
600const pendulumPhase = createPendulum({
601 canvas: document.getElementById('pendulum-phase-canvas'),
602 button: document.getElementById('pendulum-phase-toggle'),
603 params: pendulumParams,
604 labels: ['theta', 'p'],
605 centered: true,
606 pScale: 60 / pendulumPMax,
607 onDraw: (theta, p) => {
608 pendulumTrail.push([theta, p]);
609 if (pendulumTrail.length > 3000) pendulumTrail.shift();
610 drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p);
611 },
612});
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 614// Draw the pendulum phase portrait (level curves of H) and the theta and p
615// axes; returns the mapping from (theta, p) to canvas coordinates.
616function pendulumAxes(ctx, w, h, params) {
618 const halfW = Math.min(w / 2 - 30, 300);
619 const cx = w / 2;
620 const mid = h / 2;
621 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
622 const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16);
623 const fg = color('--fg');
625 ctx.save();
626 ctx.beginPath();
627 ctx.rect(cx - halfW, 0, 2 * halfW, h);
628 ctx.clip();
629 // background phase portrait: level curves of H, in units of m g L.
630 // Level 1 is the separatrix between swinging and rotating.
631 const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4];
632 const n = 300;
633 for (const c of levels) {
634 ctx.strokeStyle = fg;
635 ctx.globalAlpha = c === 1 ? 0.45 : 0.15;
636 ctx.lineWidth = c === 1 ? 1.5 : 1;
637 for (const sign of [1, -1]) {
638 ctx.beginPath();
639 let drawing = false;
640 for (let i = 0; i <= n; i++) {
641 const t = -Math.PI + (2 * Math.PI * i) / n;
642 // p^2 / (2 m L^2) - m g L cos(t) = c m g L
643 const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t));
644 if (p2 < 0) { drawing = false; continue; }
645 const x = thetaToX(t);
646 const y = pToY(sign * Math.sqrt(p2));
647 if (drawing) ctx.lineTo(x, y);
648 else ctx.moveTo(x, y);
649 drawing = true;
650 }
651 ctx.stroke();
652 }
653 }
654 ctx.globalAlpha = 1;
656 ctx.restore();
658 // axes
659 ctx.strokeStyle = fg;
660 ctx.fillStyle = fg;
661 ctx.globalAlpha = 0.5;
662 ctx.lineWidth = 1;
663 ctx.beginPath();
664 ctx.moveTo(cx - halfW, mid);
665 ctx.lineTo(cx + halfW, mid);
666 ctx.moveTo(cx, 8);
667 ctx.lineTo(cx, h - 8);
668 ctx.stroke();
669 ctx.globalAlpha = 1;
670 ctx.font = 'italic 18px Georgia, serif';
671 ctx.textBaseline = 'middle';
672 ctx.textAlign = 'left';
673 ctx.fillText('θ', cx + halfW + 6, mid);
674 ctx.textBaseline = 'top';
675 ctx.fillText('p', cx + 8, 6);
676 ctx.font = '13px system-ui, sans-serif';
677 ctx.textAlign = 'center';
678 ctx.fillText('−π', cx - halfW, mid + 6);
679 ctx.fillText('π', cx + halfW, mid + 6);
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 680 return { thetaToX, pToY };
681}
683function drawPendulumPhase(canvas, params, trail, theta, p) {
684 if (!canvas.clientWidth) return;
685 const { ctx, w, h } = prepare(canvas);
686 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, params);
687 const accent = color('--accent');
689 // trail, broken where theta wraps around
690 ctx.strokeStyle = accent;
691 ctx.lineWidth = 2;
692 ctx.beginPath();
693 trail.forEach(([tt, tp], i) => {
694 const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI;
695 if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp));
696 else ctx.lineTo(thetaToX(tt), pToY(tp));
697 });
698 ctx.stroke();
699 ctx.fillStyle = accent;
700 ctx.beginPath();
701 ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI);
702 ctx.fill();
705const pendulumPreset = document.getElementById('pendulum-preset');
706const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({
707 name,
708 input: document.getElementById(`pendulum-${name}`),
709 output: document.getElementById(`pendulum-${name}-value`),
710}));
712function syncPendulumInputs() {
713 for (const { name, input, output } of pendulumInputs) {
714 input.value = pendulumParams[name];
715 output.textContent = pendulumParams[name].toFixed(2);
716 }
717}
719function resetPendulumPhase() {
720 pendulumTrail = [];
721 pendulumPhase.reset();
722}
724for (const { name, input, output } of pendulumInputs) {
725 input.addEventListener('input', () => {
726 pendulumParams[name] = Number(input.value);
727 output.textContent = pendulumParams[name].toFixed(2);
728 pendulumPreset.value = 'custom';
729 resetPendulumPhase();
730 });
731}
733// A preset restores the default m, L and g along with its initial state.
734pendulumPreset.addEventListener('change', () => {
735 const preset = pendulumPresets[pendulumPreset.value];
736 if (!preset) return;
737 Object.assign(pendulumParams, pendulumDefaults, preset);
738 syncPendulumInputs();
739 resetPendulumPhase();
740});
741syncPendulumInputs();
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 743// Liouville's theorem: a disk of starting points evolves under the flow, and
744// the area enclosed by its boundary stays constant.
745// force(q) gives dp/dt; m is the mass term in dq/dt = p / m.
746// center and radii set the disk in (q, p); drawDiagram(ctx, w, h, points) and
747// axes(ctx, w, h) draw the physical picture and the phase-plane axes.
748function createLiouville({ id, force, m, center, radii, drawDiagram, axes }) {
749 const canvas = document.getElementById(`${id}-canvas`);
750 const diagram = document.getElementById(`${id}-diagram`);
751 const areaOut = document.getElementById(`${id}-area`);
752 const [rq, rp] = radii;
753 // a fine boundary, so the area stays accurate as the disk stretches
754 const nb = 2000;
755 const boundary = [];
756 for (let i = 0; i < nb; i++) {
757 const a = (2 * Math.PI * i) / nb;
758 boundary.push([center[0] + rq * Math.cos(a), center[1] + rp * Math.sin(a)]);
759 }
760 const interior = [];
761 while (interior.length < 600) {
762 const u = 2 * Math.random() - 1;
763 const v = 2 * Math.random() - 1;
764 if (u * u + v * v <= 1) interior.push([center[0] + rq * u, center[1] + rp * v]);
765 }
766 // each point gets a fixed random offset on the diagram, so they form a cloud
767 const jitter = interior.map(() => Math.random());
769 function step(dt) {
770 // leapfrog on dq/dt = p / m, dp/dt = force(q), for every point
771 for (const pts of [boundary, interior]) {
772 for (const pt of pts) {
773 pt[1] += 0.5 * dt * force(pt[0]);
774 pt[0] += dt * pt[1] / m;
775 pt[1] += 0.5 * dt * force(pt[0]);
776 }
777 }
778 }
780 // shoelace formula on the boundary polygon
781 function area() {
782 let a = 0;
783 for (let i = 0; i < nb; i++) {
784 const [q1, p1] = boundary[i];
785 const [q2, p2] = boundary[(i + 1) % nb];
786 a += q1 * p2 - q2 * p1;
787 }
788 return Math.abs(a) / 2;
789 }
791 function draw() {
792 if (!canvas.clientWidth) return;
793 const d = prepare(diagram);
794 drawDiagram(d.ctx, d.w, d.h, interior, jitter);
796 const { ctx, w, h } = prepare(canvas);
797 const { toX, toY } = axes(ctx, w, h);
798 const accent = color('--accent');
799 ctx.fillStyle = accent;
800 ctx.globalAlpha = 0.15;
801 ctx.beginPath();
802 boundary.forEach(([q, p], i) => (i ? ctx.lineTo(toX(q), toY(p)) : ctx.moveTo(toX(q), toY(p))));
803 ctx.closePath();
804 ctx.fill();
805 ctx.globalAlpha = 1;
806 ctx.strokeStyle = accent;
807 ctx.lineWidth = 1.5;
808 ctx.stroke();
809 for (const [q, p] of interior) ctx.fillRect(toX(q) - 1, toY(p) - 1, 2, 2);
811 areaOut.textContent = area().toFixed(4);
812 }
814 const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 });
815 return { draw, pause: loop.pause };
816}
818// Page 7: the spring, with every block drawn as a point and the spring
819// reaching their mean position. The disk's radii look round at the default scale.
820const liouvilleSpringK = 4;
821const liouville = createLiouville({
822 id: 'liouville',
823 force: (q) => -liouvilleSpringK * q,
824 m: 1,
825 center: [0.5, 0],
826 radii: [0.15, 0.6],
827 drawDiagram: (ctx, w, h, points, jitter) => {
828 const meanQ = points.reduce((sum, pt) => sum + pt[0], 0) / points.length;
829 drawSpringScene(ctx, w, h, meanQ, ({ qToX, floorY, box }) => {
830 ctx.fillStyle = color('--accent');
831 points.forEach(([q], i) => ctx.fillRect(qToX(q) - 1, floorY - 4 - jitter[i] * (box - 8), 2, 2));
832 });
833 },
834 axes: (ctx, w, h) => {
835 const { qToX, pToY } = springAxes(ctx, w, h);
836 return { toX: qToX, toY: pToY };
837 },
838});
840// Page 8: the pendulum, with every bob drawn as a point and the rod pointing
841// at their mean angle. With m = L = 1, p = dtheta/dt.
842const liouvillePendulumParams = { m: 1, L: 1, g: 9.8 };
843const liouvillePendulum = createLiouville({
844 id: 'liouville-pendulum',
845 force: (theta) => -liouvillePendulumParams.g * Math.sin(theta),
846 m: 1,
847 center: [1.2, 0],
848 radii: [0.35, 3.5],
849 drawDiagram: (ctx, w, h, points, jitter) => {
850 const fg = color('--fg');
851 const px = w / 2;
852 const py = 30;
853 const rod = Math.min(h - 80, w * 0.4);
854 const meanTheta = points.reduce((sum, pt) => sum + pt[0], 0) / points.length;
856 ctx.strokeStyle = fg;
857 ctx.lineWidth = 2;
858 ctx.beginPath();
859 ctx.moveTo(px - 50, py);
860 ctx.lineTo(px + 50, py);
861 ctx.stroke();
862 ctx.globalAlpha = 0.3;
863 ctx.setLineDash([4, 4]);
864 ctx.beginPath();
865 ctx.moveTo(px, py);
866 ctx.lineTo(px, py + rod + 28);
867 ctx.stroke();
868 ctx.setLineDash([]);
869 ctx.globalAlpha = 1;
870 ctx.beginPath();
871 ctx.moveTo(px, py);
872 ctx.lineTo(px + (rod - 18) * Math.sin(meanTheta), py + (rod - 18) * Math.cos(meanTheta));
873 ctx.stroke();
875 ctx.fillStyle = color('--accent');
876 points.forEach(([theta], i) => {
877 const r = rod + (jitter[i] - 0.5) * 30;
878 ctx.fillRect(px + r * Math.sin(theta) - 1, py + r * Math.cos(theta) - 1, 2, 2);
879 });
880 },
881 axes: (ctx, w, h) => {
882 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, liouvillePendulumParams);
883 return { toX: thetaToX, toY: pToY };
884 },
885});
887const sims = { spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase, liouville, 'liouville-pendulum': liouvillePendulum };
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 888
889const pageIds = [...document.querySelectorAll('.page')].map((el) => el.id);
890const navPrev = document.getElementById('nav-prev');
891const navNext = document.getElementById('nav-next');
893function show(id) {
894 document.querySelectorAll('.page').forEach((el) => {
895 el.classList.toggle('active', el.id === id);
896 });
897 const i = pageIds.indexOf(id);
898 // label each button with a one-word hint of where it goes
899 const hint = (j) => document.getElementById(pageIds[j])?.dataset.hint ?? '';
900 navPrev.disabled = i === 0;
901 navNext.disabled = i === pageIds.length - 1;
902 navPrev.textContent = `← ${hint(i - 1)}`.trim();
903 navNext.textContent = `${hint(i + 1)} →`.trim();
904 document.getElementById('nav-pos').textContent = `${i + 1} / ${pageIds.length}`;
905 for (const [name, sim] of Object.entries(sims)) {
906 if (name === id) sim.draw();
907 else sim.pause();
908 }
909}
911document.querySelectorAll('[data-tex]').forEach((el) => {
912 katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' });
913});
915document.querySelectorAll('[data-solution]').forEach((toggle) => {
916 toggle.addEventListener('click', () => {
917 const solution = document.getElementById(toggle.dataset.solution);
918 solution.hidden = !solution.hidden;
919 toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution';
920 });
921});
923// Pages that start centered: revealing splits them into text and diagram
924// panels and labels the diagram.
925const revealLabels = {
926 spring: ['m', 'k', 'q', 'F', 'p'],
927 energy: [], // stays unlabeled, so the bars are the only thing moving
928 pendulum: ['m', 'L', 'theta', 'p', 'g'],
929};
931document.querySelectorAll('[data-reveal]').forEach((button) => {
932 button.addEventListener('click', () => {
933 const id = button.dataset.reveal;
934 const section = document.getElementById(id);
935 button.hidden = true;
936 section.classList.add('split');
937 section.querySelector('.text').hidden = false;
938 sims[id].setLabels(revealLabels[id]);
939 });
940});
1aac419Add Liouville pages, crafted-by-human link and CLAUDE.mdJeremy Magland 942// Replay of how recipe.md was written, from app/crafted-link.js (npm run crafted-link).
943if (window.CRAFTED_LINK) {
944 const link = document.getElementById('crafted-link');
945 link.href = window.CRAFTED_LINK;
946 link.hidden = false;
947}
51ce1cdInteractive Hamiltonian systems tutorialJeremy Magland 949// The current page lives in the URL hash, so reloading stays put.
950function showFromHash() {
951 const id = location.hash.slice(1);
952 show(document.getElementById(id)?.classList.contains('page') ? id : 'landing');
953 window.scrollTo(0, 0);
954}
956window.addEventListener('hashchange', showFromHash);
957showFromHash();
959document.querySelectorAll('[data-goto]').forEach((el) => {
960 el.addEventListener('click', () => {
961 location.hash = el.dataset.goto;
962 });
963});
965function goToIndex(i) {
966 location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))];
967}
969function currentIndex() {
970 return pageIds.indexOf(document.querySelector('.page.active').id);
971}
973navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1));
974navNext.addEventListener('click', () => goToIndex(currentIndex() + 1));
976document.addEventListener('keydown', (e) => {
977 if (e.altKey || e.ctrlKey || e.metaKey) return;
978 if (e.target.closest('input, select')) return; // arrow keys belong to the control
979 const target = {
980 ArrowLeft: currentIndex() - 1,
981 ArrowRight: currentIndex() + 1,
982 Home: 0,
983 End: pageIds.length - 1,
984 }[e.key];
985 if (target === undefined) return;
986 e.preventDefault();
987 goToIndex(target);
988});