Interactive Hamiltonian systems tutorial
Slide-style web app built from recipe.md: mass on a spring, energy
conservation, Hamilton's equations, phase space, the pendulum and its
phase portrait. Includes the arewehuman keystroke recording for the
recipe.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 changed files+7969−0
.arewehuman/config.jsonadded+5−0View file
@@ -0,0 +1,5 @@
1+{
2+ "autoRecord": [
3+ "*.md"
4+ ]
5+}
.arewehuman/recipe.md/jeremy-magland-f74a.awh.jsonladded+6518−0View file
This diff is 6,523 lines long and is not shown.
.gitignoreadded+11−0View file
@@ -0,0 +1,11 @@
1+# macOS
2+.DS_Store
3+
4+# Editors
5+.vscode/
6+.idea/
7+*.swp
8+
9+# Logs and temp files
10+*.log
11+*.tmp
app/index.htmladded+252−0View file
@@ -0,0 +1,252 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>Hamiltonian Systems</title>
7+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css">
8+ <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.js"></script>
9+ <link rel="stylesheet" href="style.css">
10+</head>
11+<body>
12+ <nav class="pager">
13+ <button id="nav-prev" aria-label="Previous page"></button>
14+ <span id="nav-pos"></span>
15+ <button id="nav-next" aria-label="Next page"></button>
16+ </nav>
17+ <main>
18+ <section id="landing" data-hint="Title" class="page active">
19+ <h1>Introduction to Hamiltonian Systems</h1>
20+ <button data-goto="spring">Click to get started</button>
21+ </section>
22+
23+ <section id="spring" data-hint="Spring" class="page">
24+ <h2>Example 1: Mass on a spring with no friction</h2>
25+
26+ <div class="demo">
27+ <canvas id="spring-canvas"></canvas>
28+ <button id="spring-toggle">Start</button>
29+ <p><button id="spring-reveal" class="next ready" data-reveal="spring">Show details</button></p>
30+ </div>
31+
32+ <div class="text" hidden>
33+ <div class="equations">
34+ <div>
35+ <ul class="defs">
36+ <li><span data-tex="q"></span> — position of the block, measured from rest</li>
37+ <li><span data-tex="m"></span> — mass of the block</li>
38+ <li><span data-tex="k"></span> — stiffness of the spring</li>
39+ <li><span data-tex="p = m\,\dfrac{dq}{dt}"></span> — momentum</li>
40+ </ul>
41+
42+ <h3>Hooke's law</h3>
43+ <p>The force from the spring:</p>
44+ <div data-tex="F = -k\,q"></div>
45+ </div>
46+
47+ <div>
48+ <h3>Newton's second law</h3>
49+ <div data-tex="\frac{dp}{dt} = F = -k\,q"></div>
50+ <p>The rate of change of momentum is proportional to the position, in the opposite direction.</p>
51+
52+ <p>So we have a system relating position and momentum:</p>
53+ <div data-tex="\begin{aligned} \frac{dq}{dt} &= \frac{p}{m} \\[4pt] \frac{dp}{dt} &= -k\,q \end{aligned}"></div>
54+ </div>
55+ </div>
56+
57+ </div>
58+ </section>
59+
60+ <section id="energy" data-hint="Energy" class="page">
61+ <h2>Total energy is conserved</h2>
62+
63+ <div class="demo">
64+ <canvas id="energy-canvas"></canvas>
65+ <canvas id="energy-bars" class="bars"></canvas>
66+ <button id="energy-toggle">Start</button>
67+ <p><button id="energy-reveal" class="next ready" data-reveal="energy">Show details</button></p>
68+ </div>
69+
70+ <div class="text" hidden>
71+ <div class="equations">
72+ <div>
73+ <h3>Kinetic energy</h3>
74+ <div data-tex="\frac{p^2}{2m}"></div>
75+
76+ <h3>Potential energy</h3>
77+ <p>Stored in the stretched or compressed spring:</p>
78+ <div data-tex="\tfrac{1}{2}\,k\,q^2"></div>
79+ </div>
80+
81+ <div>
82+ <h3>Total energy</h3>
83+ <p>As the block moves, energy shifts between kinetic and potential, but the sum stays constant.</p>
84+ <p>The <strong>Hamiltonian</strong> is the total energy:</p>
85+ <div data-tex="H = \frac{p^2}{2m} + \tfrac{1}{2}\,k\,q^2"></div>
86+ </div>
87+ </div>
88+
89+ <div class="exercise">
90+ <h3>Exercise</h3>
91+ <p>Prove that <span data-tex="H"></span> is constant by differentiating with respect to <span data-tex="t"></span>.</p>
92+ <p><button class="link" data-solution="energy-solution">Show solution</button></p>
93+ <div id="energy-solution" hidden>
94+ <p>Use the chain rule, then the equations of motion from the previous page:</p>
95+ <div data-tex="\begin{aligned} \frac{dH}{dt} &= \frac{p}{m}\,\frac{dp}{dt} + k\,q\,\frac{dq}{dt} \\[4pt] &= \frac{p}{m}\,(-k\,q) + k\,q\,\frac{p}{m} \\[4pt] &= 0 \end{aligned}"></div>
96+ </div>
97+ </div>
98+
99+ </div>
100+ </section>
101+
102+ <section id="hamilton" data-hint="Hamilton" class="page text-only">
103+ <h2>Hamilton's equations</h2>
104+
105+ <div class="equations">
106+ <div>
107+ <h3>The Hamiltonian</h3>
108+ <div data-tex="H(q, p) = \frac{p^2}{2m} + \tfrac{1}{2}\,k\,q^2"></div>
109+
110+ <h3>Hamilton's equations</h3>
111+ <p>In general:</p>
112+ <div data-tex="\begin{aligned} \frac{dq}{dt} &= \frac{\partial H}{\partial p} \\[4pt] \frac{dp}{dt} &= -\frac{\partial H}{\partial q} \end{aligned}"></div>
113+ </div>
114+
115+ <div>
116+ <h3>For the spring</h3>
117+ <p>Taking the partial derivatives of <span data-tex="H"></span> gives back our equations of motion:</p>
118+ <div data-tex="\begin{aligned} \frac{dq}{dt} &= \frac{\partial H}{\partial p} = \frac{p}{m} \\[4pt] \frac{dp}{dt} &= -\frac{\partial H}{\partial q} = -k\,q \end{aligned}"></div>
119+ </div>
120+ </div>
121+
122+ </section>
123+
124+ <section id="phase" data-hint="Phase" class="page split">
125+ <h2>Phase space trajectories</h2>
126+
127+ <div class="text">
128+ </div>
129+
130+ <div class="demo">
131+ <canvas id="phase-canvas"></canvas>
132+ <div class="q0-row">
133+ <input id="phase-q0" type="range" min="-1" max="1" step="0.01" aria-label="Initial position q0">
134+ </div>
135+ <p class="slider-caption">Initial position <span data-tex="q_0"></span> = <span id="phase-q0-value"></span></p>
136+
137+ <canvas id="phase-plot" class="phase"></canvas>
138+
139+ <div class="controls">
140+ <label><span data-tex="k"></span>
141+ <input id="phase-k" type="range" min="0.5" max="8" step="0.1">
142+ <output id="phase-k-value"></output>
143+ </label>
144+ <label><span data-tex="m"></span>
145+ <input id="phase-m" type="range" min="0.25" max="4" step="0.05">
146+ <output id="phase-m-value"></output>
147+ </label>
148+ </div>
149+
150+ <button id="phase-toggle">Start</button>
151+ </div>
152+ </section>
153+
154+ <section id="pendulum" data-hint="Pendulum" class="page">
155+ <h2>Example 2: Pendulum with no friction</h2>
156+
157+ <div class="demo">
158+ <canvas id="pendulum-canvas" class="pendulum"></canvas>
159+ <button id="pendulum-toggle">Start</button>
160+ <p><button id="pendulum-reveal" class="next ready" data-reveal="pendulum">Show details</button></p>
161+ </div>
162+
163+ <div class="text" hidden>
164+ <div class="equations">
165+ <div>
166+ <ul class="defs">
167+ <li><span data-tex="L"></span> — length of the rod</li>
168+ <li><span data-tex="m"></span> — mass of the bob</li>
169+ <li><span data-tex="g"></span> — gravitational acceleration</li>
170+ <li><span data-tex="q = \theta"></span> — angular position</li>
171+ <li><span data-tex="p = m L^2 \dfrac{d\theta}{dt}"></span> — angular momentum</li>
172+ </ul>
173+
174+ <h3>The Hamiltonian</h3>
175+ <p>Kinetic plus gravitational potential energy:</p>
176+ <div data-tex="H = \frac{p^2}{2 m L^2} - m g L \cos\theta"></div>
177+ </div>
178+
179+ <div>
180+ <h3>Hamilton's equations</h3>
181+ <p>The system is then:</p>
182+ <div data-tex="\begin{aligned} \frac{d\theta}{dt} &= \frac{p}{m L^2} \\[4pt] \frac{dp}{dt} &= -m g L \sin\theta \end{aligned}"></div>
183+ </div>
184+ </div>
185+
186+ <div class="exercise">
187+ <h3>Exercise</h3>
188+ <p>Apply Hamilton's equations to <span data-tex="H"></span> to derive this system.</p>
189+ <p><button class="link" data-solution="pendulum-solution">Show solution</button></p>
190+ <div id="pendulum-solution" hidden>
191+ <div data-tex="\begin{aligned} \frac{d\theta}{dt} &= \frac{\partial H}{\partial p} = \frac{p}{m L^2} \\[4pt] \frac{dp}{dt} &= -\frac{\partial H}{\partial \theta} = -m g L \sin\theta \end{aligned}"></div>
192+ </div>
193+ </div>
194+
195+ </div>
196+ </section>
197+
198+ <section id="pendulum-phase" data-hint="Phase" class="page split">
199+ <h2>Pendulum phase space</h2>
200+
201+ <div class="text"></div>
202+
203+ <div class="demo">
204+ <p>
205+ <label class="preset">Preset
206+ <select id="pendulum-preset">
207+ <option value="small" selected>Small swings</option>
208+ <option value="large">Large swings</option>
209+ <option value="top">Almost to the top</option>
210+ <option value="rotation">Rotation</option>
211+ <option value="balanced">Balanced at the top</option>
212+ <option value="rest">At rest</option>
213+ <option value="custom" disabled>Custom</option>
214+ </select>
215+ </label>
216+ </p>
217+
218+ <canvas id="pendulum-phase-canvas" class="pendulum-centered"></canvas>
219+ <canvas id="pendulum-plot" class="phase"></canvas>
220+
221+ <div class="controls">
222+ <label><span data-tex="\theta_0"></span>
223+ <input id="pendulum-theta0" type="range" min="-3.1416" max="3.1416" step="any">
224+ <output id="pendulum-theta0-value"></output>
225+ </label>
226+ <label><span data-tex="p_0"></span>
227+ <input id="pendulum-p0" type="range" min="-12" max="12" step="0.1">
228+ <output id="pendulum-p0-value"></output>
229+ </label>
230+ </div>
231+ <div class="controls">
232+ <label><span data-tex="m"></span>
233+ <input id="pendulum-m" type="range" min="0.5" max="2" step="0.05">
234+ <output id="pendulum-m-value"></output>
235+ </label>
236+ <label><span data-tex="L"></span>
237+ <input id="pendulum-L" type="range" min="0.5" max="1.5" step="0.05">
238+ <output id="pendulum-L-value"></output>
239+ </label>
240+ <label><span data-tex="g"></span>
241+ <input id="pendulum-g" type="range" min="2" max="20" step="0.1">
242+ <output id="pendulum-g-value"></output>
243+ </label>
244+ </div>
245+
246+ <button id="pendulum-phase-toggle">Start</button>
247+ </div>
248+ </section>
249+ </main>
250+ <script src="main.js"></script>
251+</body>
252+</html>
app/main.jsadded+816−0View file
@@ -0,0 +1,816 @@
1+// Mass on a frictionless spring. Positions are in units of the maximum
2+// swing drawn on screen, so q lies in [-1, 1].
3+
4+function color(name) {
5+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
6+}
7+
8+// Size a canvas for the device pixel ratio and return its context and CSS size.
9+function 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+}
22+
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.
25+function 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+}
30+
31+// params: { k, m, q0 }, read live so sliders can change them.
32+// labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw.
33+// pScale: length of the p arrow per unit momentum, as a fraction of the swing;
34+// by default the arrow peaks at the same length as q.
35+function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) {
36+ let q = params.q0;
37+ let p = 0;
38+
39+ function step(dt) {
40+ // velocity Verlet on dq/dt = p/m, dp/dt = -k q
41+ const { k, m } = params;
42+ const f = -k * q;
43+ q += (p / m) * dt + (0.5 * f / m) * dt * dt;
44+ p += 0.5 * (f - k * q) * dt;
45+ }
46+
47+ function draw() {
48+ if (!canvas.clientWidth) return;
49+ const { ctx, w, h } = prepare(canvas);
50+
51+ const fg = color('--fg');
52+ const accent = color('--accent');
53+ const { rest, swing, qToX } = layout(w);
54+ const wallX = 20;
55+ const floorY = h * 0.62;
56+ const box = 50;
57+ const center = qToX(q);
58+ const boxX = center - box / 2;
59+ const springY = floorY - box / 2;
60+
61+ // wall and floor
62+ ctx.strokeStyle = fg;
63+ ctx.lineWidth = 2;
64+ ctx.beginPath();
65+ ctx.moveTo(wallX, floorY - box * 1.6);
66+ ctx.lineTo(wallX, floorY);
67+ ctx.lineTo(w - 10, floorY);
68+ ctx.stroke();
69+
70+ // spring (zig-zag)
71+ const coils = 12;
72+ const amp = 10;
73+ const start = wallX;
74+ const end = boxX;
75+ const lead = 12;
76+ ctx.lineWidth = 1.5;
77+ ctx.beginPath();
78+ ctx.moveTo(start, springY);
79+ ctx.lineTo(start + lead, springY);
80+ const len = end - start - 2 * lead;
81+ for (let i = 0; i < coils; i++) {
82+ const sx = start + lead + ((i + 0.5) / coils) * len;
83+ ctx.lineTo(sx, springY + (i % 2 ? amp : -amp));
84+ }
85+ ctx.lineTo(end - lead, springY);
86+ ctx.lineTo(end, springY);
87+ ctx.stroke();
88+
89+ // mass
90+ ctx.fillStyle = accent;
91+ ctx.fillRect(boxX, floorY - box, box, box);
92+
93+ // rest position marker
94+ ctx.strokeStyle = fg;
95+ ctx.globalAlpha = 0.3;
96+ ctx.setLineDash([4, 4]);
97+ ctx.beginPath();
98+ ctx.moveTo(rest, floorY - box * 1.4);
99+ ctx.lineTo(rest, floorY + 34);
100+ ctx.stroke();
101+ ctx.setLineDash([]);
102+ ctx.globalAlpha = 1;
103+
104+ onDraw(q, p);
105+
106+ if (!labels.length) return;
107+
108+ ctx.font = 'italic 18px Georgia, serif';
109+ ctx.textAlign = 'center';
110+
111+ if (labels.includes('m')) {
112+ ctx.fillStyle = color('--bg');
113+ ctx.textBaseline = 'middle';
114+ ctx.fillText('m', center, floorY - box / 2);
115+ }
116+ if (labels.includes('k')) {
117+ ctx.fillStyle = fg;
118+ ctx.textBaseline = 'bottom';
119+ ctx.fillText('k', (start + end) / 2, springY - amp - 4);
120+ }
121+ if (labels.includes('q0')) {
122+ // where the block was let go from
123+ const x0 = qToX(params.q0);
124+ ctx.strokeStyle = fg;
125+ ctx.globalAlpha = 0.5;
126+ ctx.setLineDash([2, 3]);
127+ ctx.beginPath();
128+ ctx.moveTo(x0, floorY - box - 34);
129+ ctx.lineTo(x0, floorY);
130+ ctx.stroke();
131+ ctx.setLineDash([]);
132+ ctx.globalAlpha = 1;
133+ ctx.fillStyle = fg;
134+ ctx.textBaseline = 'bottom';
135+ ctx.fillText('q₀', x0, floorY - box - 36);
136+ }
137+
138+ // q below the floor; F and p above the block
139+ const { k, m } = params;
140+ const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing;
141+ if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below');
142+ if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above');
143+ if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above');
144+ }
145+
146+ function setLabels(value) {
147+ labels = value;
148+ draw();
149+ }
150+
151+ const loop = createLoop({ button, step, draw, speed });
152+
153+ // Back to being held at q0, at rest.
154+ function reset() {
155+ q = params.q0;
156+ p = 0;
157+ loop.reset();
158+ }
159+
160+ return { draw, setLabels, reset, pause: loop.pause };
161+}
162+
163+// Animation driven by a Start / Stop / Continue button.
164+function createLoop({ button, step, draw, speed = 1 }) {
165+ let running = false;
166+ let lastTime = null;
167+ let rafId = null;
168+
169+ function frame(t) {
170+ if (!running) return;
171+ if (lastTime !== null) {
172+ const dt = speed * Math.min((t - lastTime) / 1000, 0.05);
173+ const n = 4;
174+ for (let i = 0; i < n; i++) step(dt / n);
175+ }
176+ lastTime = t;
177+ draw();
178+ rafId = requestAnimationFrame(frame);
179+ }
180+
181+ function setRunning(value) {
182+ running = value;
183+ cancelAnimationFrame(rafId);
184+ if (running) {
185+ lastTime = null;
186+ rafId = requestAnimationFrame(frame);
187+ }
188+ if (running || button.textContent !== 'Start') {
189+ button.textContent = running ? 'Stop' : 'Continue';
190+ }
191+ }
192+
193+ button.addEventListener('click', () => setRunning(!running));
194+ window.addEventListener('resize', draw);
195+
196+ return {
197+ pause: () => running && setRunning(false),
198+ reset: () => {
199+ setRunning(false);
200+ button.textContent = 'Start';
201+ draw();
202+ },
203+ };
204+}
205+
206+// Pendulum: a bob of mass m on a massless rod of length L, angle theta from
207+// straight down, kept in [-pi, pi].
208+// params: { m, L, g, theta0, p0 }, read live so sliders can change them.
209+// labels: which of 'm', 'L', 'theta', 'p', 'g' to draw.
210+// centered: put the pivot mid-canvas so the bob can go over the top; the rod
211+// is then drawn to scale, with L = 1.5 filling the canvas.
212+// pScale: length of the p arrow in px per unit momentum; by default the arrow
213+// peaks at 70px when let go from theta0 at rest.
214+function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) {
215+ let theta = params.theta0;
216+ let p = params.p0;
217+
218+ function step(dt) {
219+ // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta)
220+ const { m, L, g } = params;
221+ p -= 0.5 * dt * m * g * L * Math.sin(theta);
222+ theta += dt * p / (m * L * L);
223+ p -= 0.5 * dt * m * g * L * Math.sin(theta);
224+ if (theta > Math.PI) theta -= 2 * Math.PI;
225+ if (theta < -Math.PI) theta += 2 * Math.PI;
226+ }
227+
228+ function draw() {
229+ if (!canvas.clientWidth) return;
230+ const { ctx, w, h } = prepare(canvas);
231+ const fg = color('--fg');
232+ const accent = color('--accent');
233+ const { m, L, g } = params;
234+ const px = w / 2;
235+ const py = centered ? h / 2 : 30;
236+ const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4);
237+ const rod = centered ? maxRod * L / 1.5 : maxRod;
238+ const bx = px + rod * Math.sin(theta);
239+ const by = py + rod * Math.cos(theta);
240+ const r = 18;
241+
242+ // ceiling (only when hanging from the top) and pivot
243+ ctx.strokeStyle = fg;
244+ ctx.lineWidth = 2;
245+ if (!centered) {
246+ ctx.beginPath();
247+ ctx.moveTo(px - 50, py);
248+ ctx.lineTo(px + 50, py);
249+ ctx.stroke();
250+ }
251+
252+ // vertical reference
253+ ctx.globalAlpha = 0.3;
254+ ctx.setLineDash([4, 4]);
255+ ctx.beginPath();
256+ ctx.moveTo(px, py);
257+ ctx.lineTo(px, py + rod + r + 10);
258+ ctx.stroke();
259+ ctx.setLineDash([]);
260+ ctx.globalAlpha = 1;
261+
262+ // rod and bob
263+ ctx.lineWidth = 2;
264+ ctx.beginPath();
265+ ctx.moveTo(px, py);
266+ ctx.lineTo(bx, by);
267+ ctx.stroke();
268+ ctx.fillStyle = fg;
269+ ctx.beginPath();
270+ ctx.arc(px, py, 4, 0, 2 * Math.PI);
271+ ctx.fill();
272+ ctx.fillStyle = accent;
273+ ctx.beginPath();
274+ ctx.arc(bx, by, r, 0, 2 * Math.PI);
275+ ctx.fill();
276+
277+ onDraw(theta, p);
278+
279+ ctx.font = 'italic 18px Georgia, serif';
280+ ctx.textAlign = 'center';
281+ ctx.textBaseline = 'middle';
282+
283+ if (labels.includes('m')) {
284+ ctx.fillStyle = color('--bg');
285+ ctx.fillText('m', bx, by);
286+ }
287+
288+ if (labels.includes('L')) {
289+ // beside the middle of the rod, on the side away from the vertical
290+ const side = theta >= 0 ? 1 : -1;
291+ ctx.fillStyle = fg;
292+ ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta));
293+ }
294+
295+ if (labels.includes('theta')) {
296+ // arc from the vertical to the rod
297+ const arcR = Math.min(44, rod * 0.6);
298+ ctx.strokeStyle = fg;
299+ ctx.fillStyle = fg;
300+ ctx.lineWidth = 1.5;
301+ ctx.beginPath();
302+ ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0);
303+ ctx.stroke();
304+ const mid = Math.PI / 2 - theta / 2;
305+ ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid));
306+ }
307+
308+ if (labels.includes('p')) {
309+ // along the direction of motion, perpendicular to the rod
310+ const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0)));
311+ const len = p * (pScale ?? (peak ? 70 / peak : 0));
312+ const tx = Math.cos(theta);
313+ const ty = -Math.sin(theta);
314+ const momentum = color('--momentum');
315+ ctx.strokeStyle = momentum;
316+ ctx.fillStyle = momentum;
317+ ctx.lineWidth = 1.5;
318+ ctx.beginPath();
319+ ctx.moveTo(bx, by);
320+ ctx.lineTo(bx + tx * len, by + ty * len);
321+ ctx.stroke();
322+ if (Math.abs(len) > 8) {
323+ const d = Math.sign(len);
324+ const ex = bx + tx * len;
325+ const ey = by + ty * len;
326+ ctx.beginPath();
327+ ctx.moveTo(ex, ey);
328+ ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx);
329+ ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx);
330+ ctx.closePath();
331+ ctx.fill();
332+ ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty);
333+ }
334+ }
335+
336+ if (labels.includes('g')) {
337+ // gravity, pointing down, off to the side
338+ const gx = Math.min(px + maxRod + 50, w - 20);
339+ ctx.strokeStyle = fg;
340+ ctx.fillStyle = fg;
341+ ctx.lineWidth = 1.5;
342+ ctx.beginPath();
343+ ctx.moveTo(gx, py + 40);
344+ ctx.lineTo(gx, py + 90);
345+ ctx.stroke();
346+ ctx.beginPath();
347+ ctx.moveTo(gx, py + 90);
348+ ctx.lineTo(gx - 4, py + 82);
349+ ctx.lineTo(gx + 4, py + 82);
350+ ctx.closePath();
351+ ctx.fill();
352+ ctx.fillText('g', gx + 14, py + 65);
353+ }
354+ }
355+
356+ const loop = createLoop({ button, step, draw });
357+
358+ function setLabels(value) {
359+ labels = value;
360+ draw();
361+ }
362+
363+ // Back to the initial state, held still.
364+ function reset() {
365+ theta = params.theta0;
366+ p = params.p0;
367+ loop.reset();
368+ }
369+
370+ return { draw, setLabels, reset, pause: loop.pause };
371+}
372+
373+function arrow(ctx, from, to, y, col, label, side) {
374+ const dir = Math.sign(to - from);
375+ ctx.strokeStyle = col;
376+ ctx.fillStyle = col;
377+ ctx.lineWidth = 1.5;
378+ ctx.beginPath();
379+ ctx.moveTo(from, y);
380+ ctx.lineTo(to, y);
381+ ctx.stroke();
382+ if (Math.abs(to - from) > 8) {
383+ ctx.beginPath();
384+ ctx.moveTo(to, y);
385+ ctx.lineTo(to - dir * 8, y - 4);
386+ ctx.lineTo(to - dir * 8, y + 4);
387+ ctx.closePath();
388+ ctx.fill();
389+ }
390+ ctx.textBaseline = side === 'above' ? 'bottom' : 'top';
391+ ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4);
392+}
393+
394+// Horizontal bars for kinetic, potential and total energy, scaled to the total.
395+function drawEnergyBars(canvas, params, q, p) {
396+ if (!canvas.clientWidth) return;
397+ const { ctx, w } = prepare(canvas);
398+ const { k, m, q0 } = params;
399+ const kinetic = (p * p) / (2 * m);
400+ const potential = 0.5 * k * q * q;
401+ const total = 0.5 * k * q0 * q0;
402+
403+ const fg = color('--fg');
404+ const kColor = color('--momentum');
405+ const pColor = color('--potential');
406+ const labelW = 90;
407+ const barW = Math.min(w - labelW - 10, 400);
408+ const left = Math.max(0, (w - labelW - barW) / 2);
409+ const barX = left + labelW;
410+ const rowH = 30;
411+ const barH = 18;
412+
413+ ctx.font = '15px system-ui, sans-serif';
414+ ctx.textBaseline = 'middle';
415+ ctx.textAlign = 'right';
416+
417+ const rows = [
418+ ['Kinetic', [[kinetic, kColor]]],
419+ ['Potential', [[potential, pColor]]],
420+ ['Total', [[kinetic, kColor], [potential, pColor]]],
421+ ];
422+ rows.forEach(([label, segments], i) => {
423+ const y = 10 + i * rowH;
424+ ctx.fillStyle = fg;
425+ ctx.fillText(label, barX - 12, y + barH / 2);
426+
427+ // outline at full scale, then filled segments
428+ ctx.strokeStyle = fg;
429+ ctx.globalAlpha = 0.25;
430+ ctx.lineWidth = 1;
431+ ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH);
432+ ctx.globalAlpha = 1;
433+ let sx = barX;
434+ for (const [value, col] of segments) {
435+ const sw = Math.min(value / total, 1) * barW;
436+ ctx.fillStyle = col;
437+ ctx.fillRect(sx, y, sw, barH);
438+ sx += sw;
439+ }
440+ });
441+}
442+
443+// Phase plot: q horizontal (lined up with the spring diagram), p vertical.
444+// The axes are fixed so changing k and m visibly reshapes the orbit.
445+const pMax = 3;
446+
447+function drawPhase(canvas, params, trail, q, p) {
448+ if (!canvas.clientWidth) return;
449+ const { ctx, w, h } = prepare(canvas);
450+ const { rest, swing, qToX } = layout(w);
451+ const mid = h / 2;
452+ const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
453+ const fg = color('--fg');
454+ const accent = color('--accent');
455+
456+ // axes
457+ ctx.strokeStyle = fg;
458+ ctx.fillStyle = fg;
459+ ctx.globalAlpha = 0.5;
460+ ctx.lineWidth = 1;
461+ ctx.beginPath();
462+ ctx.moveTo(rest - swing - 20, mid);
463+ ctx.lineTo(rest + swing + 20, mid);
464+ ctx.moveTo(rest, 8);
465+ ctx.lineTo(rest, h - 8);
466+ ctx.stroke();
467+ ctx.globalAlpha = 1;
468+ ctx.font = 'italic 18px Georgia, serif';
469+ ctx.textAlign = 'left';
470+ ctx.textBaseline = 'middle';
471+ ctx.fillText('q', rest + swing + 26, mid);
472+ ctx.textBaseline = 'top';
473+ ctx.fillText('p', rest + 8, 6);
474+
475+ // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m)
476+ const { k, m, q0 } = params;
477+ const rx = Math.abs(q0) * swing;
478+ const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid);
479+ ctx.strokeStyle = fg;
480+ ctx.globalAlpha = 0.35;
481+ ctx.setLineDash([4, 4]);
482+ ctx.beginPath();
483+ ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI);
484+ ctx.stroke();
485+ ctx.setLineDash([]);
486+ ctx.globalAlpha = 1;
487+
488+ // trail, then the current state
489+ ctx.strokeStyle = accent;
490+ ctx.lineWidth = 2;
491+ ctx.beginPath();
492+ trail.forEach(([tq, tp], i) => {
493+ if (i === 0) ctx.moveTo(qToX(tq), pToY(tp));
494+ else ctx.lineTo(qToX(tq), pToY(tp));
495+ });
496+ ctx.stroke();
497+ ctx.fillStyle = accent;
498+ ctx.beginPath();
499+ ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI);
500+ ctx.fill();
501+}
502+
503+// Page 1: the spring and its equations of motion
504+const springParams = { k: 6.25, m: 1, q0: 0.6 };
505+const spring = createSpring({
506+ canvas: document.getElementById('spring-canvas'),
507+ button: document.getElementById('spring-toggle'),
508+ params: springParams,
509+});
510+
511+// Page 2: the same spring, with energy bars. Slower and without the arrows,
512+// so the moving bars are the only thing to watch.
513+const energyBars = document.getElementById('energy-bars');
514+const energy = createSpring({
515+ canvas: document.getElementById('energy-canvas'),
516+ button: document.getElementById('energy-toggle'),
517+ params: springParams,
518+ speed: 0.5,
519+ onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p),
520+});
521+
522+// Page 4: phase space, with adjustable q0, k and m
523+const phaseParams = { k: 4, m: 1, q0: 0.6 };
524+const phaseCanvas = document.getElementById('phase-canvas');
525+const phasePlot = document.getElementById('phase-plot');
526+const q0Slider = document.getElementById('phase-q0');
527+let phaseTrail = [];
528+const phase = createSpring({
529+ canvas: phaseCanvas,
530+ button: document.getElementById('phase-toggle'),
531+ params: phaseParams,
532+ labels: ['q', 'p', 'k', 'q0'],
533+ pScale: 1 / pMax,
534+ onDraw: (q, p) => {
535+ phaseTrail.push([q, p]);
536+ if (phaseTrail.length > 2000) phaseTrail.shift();
537+ drawPhase(phasePlot, phaseParams, phaseTrail, q, p);
538+ alignSlider();
539+ },
540+});
541+
542+// Stretch the q0 slider so its thumb sits directly under q0 on the diagram.
543+function alignSlider() {
544+ const { rest, swing } = layout(phaseCanvas.clientWidth);
545+ const thumb = 16;
546+ q0Slider.style.width = `${2 * swing + thumb}px`;
547+ q0Slider.style.marginLeft = `${rest - swing - thumb / 2}px`;
548+}
549+
550+for (const name of ['q0', 'k', 'm']) {
551+ const input = document.getElementById(`phase-${name}`);
552+ const output = document.getElementById(`phase-${name}-value`);
553+ input.value = phaseParams[name];
554+ output.textContent = phaseParams[name];
555+ input.addEventListener('input', () => {
556+ phaseParams[name] = Number(input.value);
557+ output.textContent = input.value;
558+ phaseTrail = [];
559+ phase.reset();
560+ });
561+}
562+
563+// Page 5: the pendulum
564+const pendulum = createPendulum({
565+ canvas: document.getElementById('pendulum-canvas'),
566+ button: document.getElementById('pendulum-toggle'),
567+ params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 },
568+});
569+
570+// Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at
571+// +/- pendulumPMax, which fits the separatrix at the default parameters
572+// with room for rotations.
573+const pendulumPMax = 12;
574+const pendulumDefaults = { m: 1, L: 1, g: 9.8 };
575+const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 };
576+const pendulumPresets = {
577+ small: { theta0: 0.3, p0: 0 },
578+ large: { theta0: 2.5, p0: 0 },
579+ top: { theta0: 3.1, p0: 0 },
580+ rotation: { theta0: 0, p0: 8 },
581+ balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds
582+ rest: { theta0: 0, p0: 0 },
583+};
584+const pendulumPlot = document.getElementById('pendulum-plot');
585+let pendulumTrail = [];
586+const pendulumPhase = createPendulum({
587+ canvas: document.getElementById('pendulum-phase-canvas'),
588+ button: document.getElementById('pendulum-phase-toggle'),
589+ params: pendulumParams,
590+ labels: ['theta', 'p'],
591+ centered: true,
592+ pScale: 60 / pendulumPMax,
593+ onDraw: (theta, p) => {
594+ pendulumTrail.push([theta, p]);
595+ if (pendulumTrail.length > 3000) pendulumTrail.shift();
596+ drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p);
597+ },
598+});
599+
600+function drawPendulumPhase(canvas, params, trail, theta, p) {
601+ if (!canvas.clientWidth) return;
602+ const { ctx, w, h } = prepare(canvas);
603+ const { m, L, g } = params;
604+ const halfW = Math.min(w / 2 - 30, 300);
605+ const cx = w / 2;
606+ const mid = h / 2;
607+ const thetaToX = (t) => cx + (t / Math.PI) * halfW;
608+ const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16);
609+ const fg = color('--fg');
610+ const accent = color('--accent');
611+
612+ ctx.save();
613+ ctx.beginPath();
614+ ctx.rect(cx - halfW, 0, 2 * halfW, h);
615+ ctx.clip();
616+
617+ // background phase portrait: level curves of H, in units of m g L.
618+ // Level 1 is the separatrix between swinging and rotating.
619+ const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4];
620+ const n = 300;
621+ for (const c of levels) {
622+ ctx.strokeStyle = fg;
623+ ctx.globalAlpha = c === 1 ? 0.45 : 0.15;
624+ ctx.lineWidth = c === 1 ? 1.5 : 1;
625+ for (const sign of [1, -1]) {
626+ ctx.beginPath();
627+ let drawing = false;
628+ for (let i = 0; i <= n; i++) {
629+ const t = -Math.PI + (2 * Math.PI * i) / n;
630+ // p^2 / (2 m L^2) - m g L cos(t) = c m g L
631+ const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t));
632+ if (p2 < 0) { drawing = false; continue; }
633+ const x = thetaToX(t);
634+ const y = pToY(sign * Math.sqrt(p2));
635+ if (drawing) ctx.lineTo(x, y);
636+ else ctx.moveTo(x, y);
637+ drawing = true;
638+ }
639+ ctx.stroke();
640+ }
641+ }
642+ ctx.globalAlpha = 1;
643+
644+ // trail, broken where theta wraps around
645+ ctx.strokeStyle = accent;
646+ ctx.lineWidth = 2;
647+ ctx.beginPath();
648+ trail.forEach(([tt, tp], i) => {
649+ const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI;
650+ if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp));
651+ else ctx.lineTo(thetaToX(tt), pToY(tp));
652+ });
653+ ctx.stroke();
654+ ctx.fillStyle = accent;
655+ ctx.beginPath();
656+ ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI);
657+ ctx.fill();
658+ ctx.restore();
659+
660+ // axes
661+ ctx.strokeStyle = fg;
662+ ctx.fillStyle = fg;
663+ ctx.globalAlpha = 0.5;
664+ ctx.lineWidth = 1;
665+ ctx.beginPath();
666+ ctx.moveTo(cx - halfW, mid);
667+ ctx.lineTo(cx + halfW, mid);
668+ ctx.moveTo(cx, 8);
669+ ctx.lineTo(cx, h - 8);
670+ ctx.stroke();
671+ ctx.globalAlpha = 1;
672+ ctx.font = 'italic 18px Georgia, serif';
673+ ctx.textBaseline = 'middle';
674+ ctx.textAlign = 'left';
675+ ctx.fillText('θ', cx + halfW + 6, mid);
676+ ctx.textBaseline = 'top';
677+ ctx.fillText('p', cx + 8, 6);
678+ ctx.font = '13px system-ui, sans-serif';
679+ ctx.textAlign = 'center';
680+ ctx.fillText('−π', cx - halfW, mid + 6);
681+ ctx.fillText('π', cx + halfW, mid + 6);
682+}
683+
684+const pendulumPreset = document.getElementById('pendulum-preset');
685+const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({
686+ name,
687+ input: document.getElementById(`pendulum-${name}`),
688+ output: document.getElementById(`pendulum-${name}-value`),
689+}));
690+
691+function syncPendulumInputs() {
692+ for (const { name, input, output } of pendulumInputs) {
693+ input.value = pendulumParams[name];
694+ output.textContent = pendulumParams[name].toFixed(2);
695+ }
696+}
697+
698+function resetPendulumPhase() {
699+ pendulumTrail = [];
700+ pendulumPhase.reset();
701+}
702+
703+for (const { name, input, output } of pendulumInputs) {
704+ input.addEventListener('input', () => {
705+ pendulumParams[name] = Number(input.value);
706+ output.textContent = pendulumParams[name].toFixed(2);
707+ pendulumPreset.value = 'custom';
708+ resetPendulumPhase();
709+ });
710+}
711+
712+// A preset restores the default m, L and g along with its initial state.
713+pendulumPreset.addEventListener('change', () => {
714+ const preset = pendulumPresets[pendulumPreset.value];
715+ if (!preset) return;
716+ Object.assign(pendulumParams, pendulumDefaults, preset);
717+ syncPendulumInputs();
718+ resetPendulumPhase();
719+});
720+syncPendulumInputs();
721+
722+const sims = { spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase };
723+
724+const pageIds = [...document.querySelectorAll('.page')].map((el) => el.id);
725+const navPrev = document.getElementById('nav-prev');
726+const navNext = document.getElementById('nav-next');
727+
728+function show(id) {
729+ document.querySelectorAll('.page').forEach((el) => {
730+ el.classList.toggle('active', el.id === id);
731+ });
732+ const i = pageIds.indexOf(id);
733+ // label each button with a one-word hint of where it goes
734+ const hint = (j) => document.getElementById(pageIds[j])?.dataset.hint ?? '';
735+ navPrev.disabled = i === 0;
736+ navNext.disabled = i === pageIds.length - 1;
737+ navPrev.textContent = `← ${hint(i - 1)}`.trim();
738+ navNext.textContent = `${hint(i + 1)} →`.trim();
739+ document.getElementById('nav-pos').textContent = `${i + 1} / ${pageIds.length}`;
740+ for (const [name, sim] of Object.entries(sims)) {
741+ if (name === id) sim.draw();
742+ else sim.pause();
743+ }
744+}
745+
746+document.querySelectorAll('[data-tex]').forEach((el) => {
747+ katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' });
748+});
749+
750+document.querySelectorAll('[data-solution]').forEach((toggle) => {
751+ toggle.addEventListener('click', () => {
752+ const solution = document.getElementById(toggle.dataset.solution);
753+ solution.hidden = !solution.hidden;
754+ toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution';
755+ });
756+});
757+
758+// Pages that start centered: revealing splits them into text and diagram
759+// panels and labels the diagram.
760+const revealLabels = {
761+ spring: ['m', 'k', 'q', 'F', 'p'],
762+ energy: [], // stays unlabeled, so the bars are the only thing moving
763+ pendulum: ['m', 'L', 'theta', 'p', 'g'],
764+};
765+
766+document.querySelectorAll('[data-reveal]').forEach((button) => {
767+ button.addEventListener('click', () => {
768+ const id = button.dataset.reveal;
769+ const section = document.getElementById(id);
770+ button.hidden = true;
771+ section.classList.add('split');
772+ section.querySelector('.text').hidden = false;
773+ sims[id].setLabels(revealLabels[id]);
774+ });
775+});
776+
777+// The current page lives in the URL hash, so reloading stays put.
778+function showFromHash() {
779+ const id = location.hash.slice(1);
780+ show(document.getElementById(id)?.classList.contains('page') ? id : 'landing');
781+ window.scrollTo(0, 0);
782+}
783+
784+window.addEventListener('hashchange', showFromHash);
785+showFromHash();
786+
787+document.querySelectorAll('[data-goto]').forEach((el) => {
788+ el.addEventListener('click', () => {
789+ location.hash = el.dataset.goto;
790+ });
791+});
792+
793+function goToIndex(i) {
794+ location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))];
795+}
796+
797+function currentIndex() {
798+ return pageIds.indexOf(document.querySelector('.page.active').id);
799+}
800+
801+navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1));
802+navNext.addEventListener('click', () => goToIndex(currentIndex() + 1));
803+
804+document.addEventListener('keydown', (e) => {
805+ if (e.altKey || e.ctrlKey || e.metaKey) return;
806+ if (e.target.closest('input, select')) return; // arrow keys belong to the control
807+ const target = {
808+ ArrowLeft: currentIndex() - 1,
809+ ArrowRight: currentIndex() + 1,
810+ Home: 0,
811+ End: pageIds.length - 1,
812+ }[e.key];
813+ if (target === undefined) return;
814+ e.preventDefault();
815+ goToIndex(target);
816+});
app/style.cssadded+242−0View file
@@ -0,0 +1,242 @@
1+:root {
2+ --bg: #fafaf7;
3+ --fg: #1d1d1f;
4+ --accent: #2f5d8a;
5+ --force: #c0392b;
6+ --momentum: #2e8b57;
7+ --potential: #c98a1b;
8+}
9+
10+@media (prefers-color-scheme: dark) {
11+ :root {
12+ --bg: #141416;
13+ --fg: #e8e8ea;
14+ --accent: #7fb0e0;
15+ --force: #ec7063;
16+ --momentum: #58d68d;
17+ --potential: #f0b450;
18+ }
19+}
20+
21+* { box-sizing: border-box; }
22+
23+body {
24+ margin: 0;
25+ background: var(--bg);
26+ color: var(--fg);
27+ font-family: system-ui, -apple-system, sans-serif;
28+}
29+
30+main {
31+ min-height: 100vh;
32+ display: flex;
33+ align-items: flex-start;
34+ justify-content: center;
35+ padding: 64px 16px 16px;
36+}
37+
38+/* Slide titles sit at the top; only the title slide is centered vertically. */
39+#landing { align-self: center; }
40+
41+.page { display: none; text-align: center; width: 100%; max-width: 720px; }
42+.page.active { display: block; }
43+
44+/* Slides: text and equations on the left, interactive content on the right.
45+ On narrow screens they stack, with the interactive part first. */
46+.page.split, .page.text-only { max-width: 1200px; }
47+
48+.page.split.active {
49+ display: grid;
50+ grid-template-columns: 1fr 1fr;
51+ grid-template-areas: "title title" "text demo";
52+ gap: 0 3rem;
53+ align-items: start;
54+}
55+
56+.page.split > h2 { grid-area: title; }
57+.page.split > .text { grid-area: text; text-align: left; }
58+.page.split > .demo { grid-area: demo; min-width: 0; }
59+
60+/* On desktop the slide fills the window below the nav bar, and the two
61+ panels scroll independently. */
62+@media (min-width: 861px) {
63+ .page.split.active {
64+ height: calc(100vh - 64px - 16px);
65+ grid-template-rows: auto minmax(0, 1fr);
66+ }
67+ .page.split > .text,
68+ .page.split > .demo {
69+ height: 100%;
70+ overflow-y: auto;
71+ padding: 0 8px 16px;
72+ }
73+}
74+
75+@media (max-width: 860px) {
76+ .page.split.active {
77+ grid-template-columns: 1fr;
78+ grid-template-areas: "title" "demo" "text";
79+ }
80+ .page.split > .text { margin-top: 1.5rem; }
81+}
82+
83+.pager {
84+ position: fixed;
85+ top: 0;
86+ left: 0;
87+ right: 0;
88+ z-index: 1;
89+ display: flex;
90+ align-items: center;
91+ justify-content: space-between;
92+ padding: 10px 16px;
93+ background: var(--bg);
94+ border-bottom: 1px solid color-mix(in srgb, var(--fg) 12%, transparent);
95+}
96+
97+.pager button { padding: 0.35rem 0.8rem; font-size: 0.9rem; }
98+.pager button:disabled { opacity: 0.3; cursor: default; background: none; color: var(--accent); }
99+#nav-pos { font-size: 0.85rem; opacity: 0.6; }
100+
101+h2 {
102+ font-weight: 500;
103+ font-size: clamp(1.2rem, 4vw, 1.6rem);
104+ margin: 0 0 1.5rem;
105+}
106+
107+canvas {
108+ display: block;
109+ width: 100%;
110+ height: 200px;
111+ margin: 0 0 1.5rem;
112+}
113+
114+canvas.bars { height: 100px; margin-top: -0.5rem; }
115+canvas.phase { height: 260px; }
116+canvas.pendulum { height: 260px; }
117+canvas.pendulum-centered { height: 240px; }
118+
119+.preset { display: inline-flex; align-items: center; gap: 0.5rem; }
120+
121+select {
122+ font: inherit;
123+ color: var(--fg);
124+ background: var(--bg);
125+ border: 1px solid var(--accent);
126+ border-radius: 6px;
127+ padding: 0.35rem 0.5rem;
128+}
129+
130+.q0-row { text-align: left; margin-top: -1.25rem; }
131+.q0-row input { display: block; margin: 0; }
132+.slider-caption { margin: 0.25rem 0 1rem; font-size: 0.9rem; opacity: 0.8; }
133+
134+.controls {
135+ display: flex;
136+ justify-content: center;
137+ flex-wrap: wrap;
138+ gap: 0.5rem 2rem;
139+ margin: 0 0 1.25rem;
140+}
141+
142+.controls label { display: flex; align-items: center; gap: 0.5rem; }
143+.controls output { min-width: 2.5em; text-align: left; font-variant-numeric: tabular-nums; }
144+
145+input[type="range"] { accent-color: var(--accent); }
146+
147+h1 {
148+ font-weight: 500;
149+ font-size: clamp(1.6rem, 5vw, 2.6rem);
150+ margin: 0 0 1.5rem;
151+}
152+
153+button {
154+ font: inherit;
155+ color: var(--accent);
156+ background: none;
157+ border: 1px solid var(--accent);
158+ border-radius: 6px;
159+ padding: 0.6rem 1.2rem;
160+ cursor: pointer;
161+}
162+
163+button:hover { background: var(--accent); color: var(--bg); }
164+
165+/* The suggested next step: hidden until the user has tried the demo, then filled and pulsing gently. */
166+button.next {
167+ margin-top: 1.5rem;
168+ background: var(--accent);
169+ color: var(--bg);
170+ visibility: hidden;
171+ opacity: 0;
172+ transition: opacity 0.6s;
173+}
174+
175+button.next.ready {
176+ visibility: visible;
177+ opacity: 1;
178+ animation: pulse 2s ease-in-out 0.6s 3;
179+}
180+
181+button.next:hover { opacity: 0.85; }
182+
183+@keyframes pulse {
184+ 0%, 100% { box-shadow: 0 0 0 0 var(--accent); }
185+ 50% { box-shadow: 0 0 0 6px transparent; }
186+}
187+
188+.equations {
189+ text-align: left;
190+ margin: 0;
191+ line-height: 1.6;
192+ display: grid;
193+ grid-template-columns: 1fr 1fr;
194+ gap: 0 2.5rem;
195+}
196+
197+.equations[hidden] { display: none; }
198+
199+.equations > div > :first-child { margin-top: 0; }
200+
201+/* Two columns of equations only when the text panel is wide enough. */
202+@media (max-width: 1100px) and (min-width: 861px), (max-width: 600px) {
203+ .equations { grid-template-columns: 1fr; }
204+ .equations > div + div { margin-top: 1.5rem; }
205+}
206+
207+.equations h3 {
208+ font-weight: 500;
209+ font-size: 1.05rem;
210+ margin: 1.5rem 0 0.25rem;
211+}
212+
213+button.link {
214+ border: none;
215+ padding: 0.3rem 0;
216+ text-decoration: underline;
217+ text-underline-offset: 3px;
218+}
219+
220+button.link:hover { background: none; color: var(--accent); opacity: 0.8; }
221+
222+.exercise {
223+ text-align: left;
224+ margin: 2rem 0 0;
225+ padding: 1rem 1.25rem;
226+ border-left: 3px solid var(--accent);
227+ line-height: 1.6;
228+}
229+
230+.exercise h3 {
231+ font-weight: 500;
232+ font-size: 1.05rem;
233+ margin: 0 0 0.25rem;
234+}
235+
236+.defs {
237+ list-style: none;
238+ padding: 0;
239+ margin: 0;
240+}
241+
242+.defs li { margin: 0.35rem 0; }
package.jsonadded+7−0View file
@@ -0,0 +1,7 @@
1+{
2+ "name": "hamiltonian-systems-tutorial",
3+ "private": true,
4+ "scripts": {
5+ "dev": "python3 -m http.server 8000 --directory app"
6+ }
7+}
recipe.mdadded+118−0View file
@@ -0,0 +1,118 @@
1+# Hamiltonian Systems Interactive Tutorial
2+
3+The landing page simply says "Introduction to Hamiltonian Systems" with an invitation to click to get started.
4+
5+Notes:
6+- The url contains the current page, so reloading the page doesn't bring us back to the beginning
7+- Have navigation buttons (next/prev) always at the top of each page, and let the arrow keys (left/right) nad home/end also control this. This is an interactive slide presentation.
8+- The app is meant to be viewed on a desktop but should also be compatible with mobile devices. On desktop there should be two panels. On the left is the text, equations, etc. On the right is the interactive content, diagrams and controls. But some pages start with centered content, and only expand to two panels when the user clicks something.
9+- The title of each slide should be at the top and the panels should be independently scrollable.
10+- The next and prev buttons should have a single word hint of the content.
11+
12+## Page 1: Mass on a spring with no friction
13+
14+When user clicks, we go to the first (non title page). It shows a mass on a spring with no friction with the text Example 1: Mass on a spring with no friction. We see a representation of a mass on a spring held at a particular position. The user clicks to "start" and we see the motion start. The user can click to stop it as well.
15+
16+This is centered at first with no labels and no equations. Users click a button "show details" reveal the two panels with the equations on left and the labeled diagram on the right.
17+
18+q - the position of the block measured from rest
19+m - the mass of the block
20+k - the stiffness of the spring
21+p = m * dq/dt - the momentum
22+
23+Hooke's law:
24+F = -k * q - the force imparted by the spring
25+
26+Newton's second law:
27+dp/dt = F = -k * q
28+
29+The rate of change in momentum is proportional to the position (opposite direction).
30+
31+So we have the system relating position and momentum:
32+
33+dq/dt = p/m
34+dp/dt = -k q
35+
36+And the various quantities should appear on the diagram.
37+
38+Use two columns for the equations section so that it can fit better, stacking to one on a narrower screen.
39+
40+## Page 2: Conserved Energy
41+
42+Title: Total energy is conserved
43+
44+In this page, we show the same spring diagram with a start/stop button, and we depict the kinetic/potential/total energy with bars. But we don't want people to feel dizzy. Again, we just show the unlabeled diagram at the center with the kinetic/potential/total bars with a start/stop button and a details button.
45+
46+The details are.
47+
48+kinetic: p^2/2m and
49+potential: 1/2 k * q^2
50+
51+They sum up to a constant, the total energy.
52+
53+Depict that in the diagram and show the equations below.
54+
55+The Hamiltonian is the total energy
56+H = p^2/2m + 1/2 k q^2
57+
58+Exercise: Prove H is constant by differentiating with respect to it. The user clicks to reveal the solution.
59+
60+
61+## Page 3: Hamilton's Equations
62+
63+We write
64+
65+H = p^2/2m + 1/2 k q^2
66+
67+And in general, Hamilton's equations are:
68+
69+dq/dt = \partial H/\partial p
70+dp/dt = -partial H/\partial q
71+
72+which in this case yields our equations of motion
73+
74+dq/dt = \partial H/\partial p = p/m
75+dp/dt = -\partial H/\partial q = -kq
76+
77+## Page 4: Phase space trajectories
78+
79+On this page, we will show the trajectory through phase space. We will ahve the diagram again at the top, but this time with only p and q and k labeled, together with initial position q_0. Then below that we will have an axes with q horizontal and p vertical and the q should line up.
80+
81+Then user can adjust the initial position, k, and m.
82+
83+Keep the axes fixed. Leave a trail and draw the level curve. The starting position should be a slider that lines up with the q.
84+
85+## Page 5: Pendulum with no friction
86+
87+Similarly, we will have a diagram at the top with a swinging pendulum. The bob will be on a massless rod at an initial position and again a "Let Go" button. And then a button to reveal the equations of motion and labels on the diagram.
88+
89+In this case
90+
91+L - rod length
92+m - mass of bob
93+g - gravitational acceleration
94+
95+q = \theta - angular position
96+p = m L^2 d\theta/dt - angular momentum
97+
98+The Hamiltonian in this case is
99+
100+H = p^2/(2 m L^2) - m g L cos \theta (kinetic plus gravitational potential)
101+
102+The Hamiltonian system is then:
103+
104+d\theta/dt = p/(mL^2)
105+dp/dt = -m g L sin \theta
106+
107+Exercise: Apply Hamilton's equations to H to derive this system
108+
109+## Page 6: Pendulum phase space
110+
111+Again, the pendulum diagram is at the top. Below that we have an axes for q and p. And the user can control the parameters in the same way. But we should also have an initial momentum. And there should be a dropdown that has presets to show the different types of phenomena.
112+
113+- small swings
114+- large swings
115+- almost to the top
116+- rotation
117+- balanced at the top
118+- at rest