vizmatic 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/PROMPT.md +42 -9
  2. package/README.md +172 -61
  3. package/ROADMAP.md +9 -6
  4. package/SCIENCE.md +70 -5
  5. package/assets/THIRD_PARTY_LICENSES.md +3 -3
  6. package/assets/fonts/SourceSerif4-24pt-SemiBold.ttf +0 -0
  7. package/assets/licenses/raster-codecs-MIT.txt +2 -2
  8. package/dist/chunk-6JI55YX4.js +604 -0
  9. package/dist/{chunk-LTX44BAE.js → chunk-BYKXNUX7.js} +25 -4
  10. package/dist/{chunk-ZB3HK7RM.js → chunk-EPZLNABN.js} +345 -25
  11. package/dist/chunk-EWCO6ZT6.js +696 -0
  12. package/dist/{chunk-DZHX76RS.js → chunk-G7HRSKHV.js} +33 -4
  13. package/dist/{chunk-RPAHMKAR.js → chunk-JTWC2OPN.js} +7 -5
  14. package/dist/chunk-LJZO36IR.js +124 -0
  15. package/dist/chunk-REL2BZ2B.js +88 -0
  16. package/dist/chunk-RLPEOWST.js +1 -0
  17. package/dist/chunk-VMHOWCDL.js +296 -0
  18. package/dist/chunk-YDD63HHD.js +1 -0
  19. package/dist/chunk-YNGDEARY.js +7230 -0
  20. package/dist/cli.js +124 -270
  21. package/dist/gpu-selection-CDWCZH27.js +1 -0
  22. package/dist/gpu-selection-MX6NHMNA.js +635 -0
  23. package/dist/index.cjs +1492 -217
  24. package/dist/index.d.cts +233 -230
  25. package/dist/index.d.ts +233 -230
  26. package/dist/index.js +1103 -479
  27. package/dist/math-E7W5LFWO.js +1 -0
  28. package/dist/{math-LXB4FH4E.js → math-NEFQUPRV.js} +3 -1
  29. package/dist/scene-browser-chunks/chunk-RQNLYYJN.js +70 -0
  30. package/dist/scene-browser-chunks/{scene-browser-layout-M3XSXMV4.js → scene-browser-layout-RC3ECYRK.js} +1 -1
  31. package/dist/scene-browser.js +18 -18
  32. package/dist/scene-cli.js +1 -1
  33. package/dist/scene-runtime.cjs +28 -5
  34. package/dist/scene-runtime.js +2 -2
  35. package/dist/{server-2FYHZ4UO.js → server-Q4COUZHV.js} +3 -3
  36. package/dist/stage-browser/browser.d.ts +8962 -685
  37. package/dist/stage-browser/gpu-renderer.js +138 -0
  38. package/dist/stage-browser/{math-4WFNHVV2.js → math-KYHUOK7A.js} +46 -10
  39. package/dist/stage-browser/stage.js +110 -5
  40. package/dist/stage-export.cjs +8616 -3888
  41. package/dist/stage-export.d.cts +65 -4
  42. package/dist/stage-export.d.ts +65 -4
  43. package/dist/stage-export.js +314 -325
  44. package/dist/stage.cjs +36997 -8756
  45. package/dist/stage.d.cts +8456 -634
  46. package/dist/stage.d.ts +8456 -634
  47. package/dist/stage.js +28135 -3502
  48. package/dist/{svg-import-C-RG1t7s.d.cts → svg-import-CSCFWYaB.d.cts} +473 -62
  49. package/dist/{svg-import-C-RG1t7s.d.ts → svg-import-CSCFWYaB.d.ts} +473 -62
  50. package/dist/teaching-math-DTKc0XsB.d.cts +243 -0
  51. package/dist/teaching-math-ydDBhJ2M.d.ts +243 -0
  52. package/dist/{video-BSwNJZkn.d.cts → theme-DhVdDQKO.d.cts} +4 -212
  53. package/dist/{video-BSwNJZkn.d.ts → theme-DhVdDQKO.d.ts} +4 -212
  54. package/dist/video-BYCeOz8F.d.ts +259 -0
  55. package/dist/video-CGLxJXqu.d.cts +259 -0
  56. package/examples/README.md +1 -1
  57. package/examples/_teaching/layer-stack-connector.ts +36 -0
  58. package/examples/_teaching/layer-stack-recurrence.ts +29 -0
  59. package/examples/_teaching/layer-stack-tiny-gpt.ts +37 -0
  60. package/examples/_teaching/layer-stack-transformer.ts +44 -0
  61. package/examples/catalog-convolution-kernel.tsx +6 -7
  62. package/examples/catalog-science-physics.tsx +6 -6
  63. package/examples/{aurora-incident.tsx → checkout-incident.tsx} +1 -1
  64. package/examples/films/_boltzmann-entropy/model.ts +63 -0
  65. package/examples/films/_catalysis/model.ts +49 -0
  66. package/examples/films/_gravitational-waves/model.ts +32 -0
  67. package/examples/films/_heat-equation/model.ts +54 -0
  68. package/examples/films/_hydrogen-orbitals/model.ts +31 -0
  69. package/examples/films/_maxwell/model.ts +84 -0
  70. package/examples/films/_planetary-orbits/appearance.ts +71 -0
  71. package/examples/films/_planetary-orbits/model.ts +152 -0
  72. package/examples/films/_planetary-orbits/saturn.ts +142 -0
  73. package/examples/films/_quantum-tunneling/model.ts +58 -0
  74. package/examples/films/_reaction-diffusion/model.ts +61 -0
  75. package/examples/films/_stationary-action/model.ts +38 -0
  76. package/examples/films/attention.ts +309 -253
  77. package/examples/films/beam-search.ts +324 -0
  78. package/examples/films/boltzmann-entropy.ts +104 -0
  79. package/examples/films/cache-miss.ts +387 -393
  80. package/examples/films/catalog.json +251 -60
  81. package/examples/films/catalysis.ts +128 -0
  82. package/examples/films/central-limit.ts +27 -22
  83. package/examples/films/complex-maps.ts +70 -56
  84. package/examples/films/deck-example.ts +261 -200
  85. package/examples/films/euler-circle.ts +72 -28
  86. package/examples/films/flash-attention.ts +549 -0
  87. package/examples/films/forecast.ts +354 -0
  88. package/examples/films/fourier-epicycles.ts +21 -20
  89. package/examples/films/gradient-descent.ts +23 -49
  90. package/examples/films/gravitational-waves.ts +179 -0
  91. package/examples/films/heat-equation.ts +124 -0
  92. package/examples/films/hydrogen-orbitals.ts +135 -0
  93. package/examples/films/io-uring.ts +635 -0
  94. package/examples/films/linear-maps.ts +42 -31
  95. package/examples/films/lorenz.ts +42 -79
  96. package/examples/films/maxwell.ts +197 -0
  97. package/examples/films/passage/chunking.ts +40 -0
  98. package/examples/films/passage/evidence.ts +44 -0
  99. package/examples/films/passage/prompt.ts +34 -0
  100. package/examples/films/pathlines.ts +85 -0
  101. package/examples/films/paxos.ts +596 -0
  102. package/examples/films/planetary-orbits.ts +146 -0
  103. package/examples/films/pythagoras.ts +18 -10
  104. package/examples/films/quantum-tunneling.ts +116 -0
  105. package/examples/films/rag-citations.ts +423 -0
  106. package/examples/films/reaction-diffusion.ts +70 -0
  107. package/examples/films/ring-allreduce.ts +531 -0
  108. package/examples/films/stationary-action.ts +170 -0
  109. package/examples/films/svd-3d.ts +605 -0
  110. package/examples/films/taylor-series.ts +10 -10
  111. package/examples/films/vizmatic-title.ts +1 -0
  112. package/examples/narrated-cues/README.md +32 -0
  113. package/examples/narrated-cues/data/numbers.json +1 -0
  114. package/examples/narrated-cues/film.json +9 -0
  115. package/examples/narrated-cues/film.ts +78 -0
  116. package/examples/narrated-cues/package.json +1 -0
  117. package/examples/narrated-cues/script.json +57 -0
  118. package/examples/narrated-cues/timing.json +1 -0
  119. package/examples/narrated-cues/tsconfig.json +1 -0
  120. package/examples/proofs/decoding-bars.ts +67 -0
  121. package/examples/proofs/pipeline.ts +27 -0
  122. package/examples/proofs/table/evaluation.ts +41 -0
  123. package/examples/proofs/table/ledger.ts +47 -0
  124. package/examples/proofs/table/routing.ts +46 -0
  125. package/examples/vizmatic-hero.tsx +102 -32
  126. package/package.json +11 -4
  127. package/templates/narrated/README.md +61 -0
  128. package/templates/narrated/data/numbers.json +5 -0
  129. package/templates/narrated/film.json +12 -0
  130. package/templates/narrated/film.ts +14 -0
  131. package/templates/narrated/gitignore +8 -0
  132. package/templates/narrated/package.json +1 -0
  133. package/templates/narrated/scenes/answer.ts +25 -0
  134. package/templates/narrated/scenes/kit.ts +39 -0
  135. package/templates/narrated/scenes/question.ts +31 -0
  136. package/templates/narrated/script.json +26 -0
  137. package/templates/narrated/sources.md +22 -0
  138. package/templates/narrated/timing.json +1 -0
  139. package/templates/narrated/tsconfig.json +1 -0
  140. package/tools/narration/README.md +123 -0
  141. package/tools/narration/beats.py +43 -0
  142. package/tools/narration/checks.py +587 -0
  143. package/tools/narration/draft.py +73 -0
  144. package/tools/narration/film.py +341 -0
  145. package/tools/narration/lag.py +58 -0
  146. package/tools/narration/mix.py +265 -0
  147. package/tools/narration/probe.py +99 -0
  148. package/tools/narration/record.py +33 -0
  149. package/tools/narration/resound.py +170 -0
  150. package/tools/narration/soundbed.py +404 -0
  151. package/tools/narration/sync.py +93 -0
  152. package/tools/narration/transcribe.py +84 -0
  153. package/tools/narration/verify.py +59 -0
  154. package/tools/narration/voice.py +113 -0
  155. package/dist/chunk-3F2VQ7NW.js +0 -1
  156. package/dist/chunk-6H2KTNJ7.js +0 -4774
  157. package/dist/chunk-6N6P2GJG.js +0 -88
  158. package/dist/math-QVCETQDQ.js +0 -1
  159. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +0 -70
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Normalized toy model: P(the,a,some) = (0.5,0.4,0.1).
3
+ * P(best,old | the) = (0.6,0.4); P(clear,rough | a) = (0.9,0.1).
4
+ * P(guess | the best) = 0.6; P(proof | a clear) = 0.9.
5
+ * Each final expansion has one omitted alternative with the remaining mass.
6
+ * At a fixed three-token horizon, greedy scores log(0.18) and beam scores log(0.324).
7
+ * This example does not claim beam search is globally optimal in general.
8
+ */
9
+ import {
10
+ Node, assertEqual, barChart, column, fadeIn, fadeOut, film, indicate, place,
11
+ sceneKit, seq, spotlight, tagTrack, tokens, tree, type TreeSpec,
12
+ } from 'vizmatic/stage'
13
+
14
+ // ── Search tree specification & cumulative log-prob invariants ──────────────
15
+
16
+ const SEARCH_TREE: TreeSpec = {
17
+ id: 'root',
18
+ label: 'Give',
19
+ children: [
20
+ {
21
+ id: 'the',
22
+ label: 'the',
23
+ weight: Math.log(0.5),
24
+ children: [
25
+ {
26
+ id: 'best',
27
+ label: 'best',
28
+ weight: Math.log(0.6),
29
+ children: [
30
+ { id: 'guess', label: 'guess', weight: Math.log(0.6) },
31
+ ],
32
+ },
33
+ { id: 'old', label: 'old', weight: Math.log(0.4) },
34
+ ],
35
+ },
36
+ {
37
+ id: 'a',
38
+ label: 'a',
39
+ weight: Math.log(0.4),
40
+ children: [
41
+ {
42
+ id: 'clear',
43
+ label: 'clear',
44
+ weight: Math.log(0.9),
45
+ children: [
46
+ { id: 'proof', label: 'proof', weight: Math.log(0.9) },
47
+ ],
48
+ },
49
+ { id: 'rough', label: 'rough', weight: Math.log(0.1) },
50
+ ],
51
+ },
52
+ { id: 'some', label: 'some', weight: Math.log(0.1) },
53
+ ],
54
+ }
55
+
56
+ const fmtLogProb = (v: number): string => (Object.is(v, -0) || Math.abs(v) < 1e-9 ? '0.0' : v.toFixed(1))
57
+
58
+ function collectScores(node: TreeSpec, acc = 0, map = new Map<string, number>()): Map<string, number> {
59
+ const next = acc + (node.weight ?? 0)
60
+ if (node.id) map.set(node.id, next)
61
+ for (const child of node.children ?? []) collectScores(child, next, map)
62
+ return map
63
+ }
64
+
65
+ const SCORES = collectScores(SEARCH_TREE)
66
+ // The two leaf expansions omit one lower-probability alternative each.
67
+ const omittedMass: Record<string, number> = { best: 0.4, clear: 0.1 }
68
+ function checkDistribution(node: TreeSpec): void {
69
+ if (!node.children?.length) return
70
+ const mass = node.children.reduce((sum, child) => sum + Math.exp(child.weight!), 0) + (omittedMass[node.id!] ?? 0)
71
+ assertEqual(Math.abs(mass - 1) < 1e-12, true, 'conditional probabilities sum to one')
72
+ for (const child of node.children) checkDistribution(child)
73
+ }
74
+ checkDistribution(SEARCH_TREE)
75
+ assertEqual(['the', 'a', 'some'].sort((a, b) => SCORES.get(b)! - SCORES.get(a)!).slice(0, 2), ['the', 'a'], 'first beam frontier')
76
+ assertEqual(['best', 'old', 'clear', 'rough'].sort((a, b) => SCORES.get(b)! - SCORES.get(a)!).slice(0, 2), ['clear', 'best'], 'second beam frontier')
77
+ assertEqual(Math.abs(Math.exp(SCORES.get('guess')!) - 0.18) < 1e-12, true, 'greedy sequence probability')
78
+ assertEqual(Math.abs(Math.exp(SCORES.get('proof')!) - 0.324) < 1e-12, true, 'beam sequence probability')
79
+ assertEqual(SCORES.get('proof')! > SCORES.get('guess')!, true, 'beam wins this fixed-length example')
80
+
81
+ // ── Film ────────────────────────────────────────────────────────────────────
82
+
83
+ export default film({
84
+ title: 'A beam keeps more than one path',
85
+ description: 'A normalized toy model: greedy ends at log(0.18), while beam search (k = 2) finds log(0.324).',
86
+ fps: 60,
87
+ look: 'midnight',
88
+ font: 'text-serif',
89
+ }, (s) => {
90
+ const { area, heading, source, label } = sceneKit({
91
+ size: 38,
92
+ source: { size: 28 },
93
+ chip: { size: 28, font: 'mono' },
94
+ })
95
+
96
+ const title = heading('A beam keeps more than one path')
97
+ const foot = source('Toy model · 3-token horizon · lower-ranked leaf alternatives omitted · natural log scores')
98
+ const modeTagHolder = new Node()
99
+
100
+ const [prefixBand, mainBand, captionBand] = area.rows([1.15, 6.0, 0.85], 'tight')
101
+ const [treeCol, chartCol] = mainBand.columns([1.95, 1.0], 'normal')
102
+
103
+ // ── Top prefix strips: Greedy (k = 1) vs Beam (k = 2) ───────────────────
104
+
105
+ const prefixStates = {
106
+ kept: {},
107
+ trapped: { color: 'orange', fill: 0.28, mark: 'cross' as const },
108
+ winner: { color: 'teal', fill: 0.30, mark: 'check' as const },
109
+ }
110
+
111
+ const [greedySlot, beamSlot] = prefixBand.columns([1, 1], 'normal')
112
+ const greedyStrip = tokens(['Give'], {
113
+ width: 780,
114
+ size: 29,
115
+ rowSize: 27,
116
+ gap: 10,
117
+ label: 'k=1',
118
+ states: prefixStates,
119
+ })
120
+ const beamStrip = tokens(['Give'], {
121
+ width: 780,
122
+ size: 29,
123
+ rowSize: 27,
124
+ gap: 10,
125
+ label: 'k=2',
126
+ states: prefixStates,
127
+ })
128
+ place(greedyStrip, greedySlot, 'center')
129
+ place(beamStrip, beamSlot, 'center')
130
+
131
+ // ── Unified multi-step search tree ──────────────────────────────────────
132
+
133
+ const searchTree = tree(SEARCH_TREE, {
134
+ direction: 'right',
135
+ score: 'sum',
136
+ shown: 0,
137
+ width: 1030,
138
+ siblingGap: 102,
139
+ labelSize: 28,
140
+ valueSize: 27,
141
+ edgeLabelSize: 27,
142
+ format: fmtLogProb,
143
+ })
144
+ assertEqual(Math.round(searchTree.score('guess') * 10) / 10, -1.7, 'tree score at greedy leaf guess')
145
+ assertEqual(Math.round(searchTree.score('proof') * 10) / 10, -1.1, 'tree score at beam leaf proof')
146
+ place(searchTree, treeCol, 'center')
147
+
148
+ // ── Side BarCharts: step-1 token log-probs & final sequence comparison ──
149
+
150
+ const step1Title = label('Step-1 token log-prob', { size: 29, color: 'dim' })
151
+ const step1Bars = barChart(
152
+ [
153
+ { label: 'the', value: Math.exp(SCORES.get('the')!), color: 'orange' },
154
+ { label: 'a', value: Math.exp(SCORES.get('a')!), color: 'teal' },
155
+ { label: 'some', value: Math.exp(SCORES.get('some')!), color: 'blue' },
156
+ ],
157
+ {
158
+ width: 490,
159
+ height: 290,
160
+ max: 0.85,
161
+ labelSize: 28,
162
+ showValues: true,
163
+ states: true,
164
+ format: (p) => Math.log(Math.max(p, 1e-6)).toFixed(1),
165
+ },
166
+ )
167
+ place(column([step1Title, step1Bars], { gap: 28, align: 'center' }), chartCol, 'center')
168
+
169
+ const finalTitle = label('Completed sequence log-prob', { size: 29, color: 'dim' })
170
+ const finalBars = barChart(
171
+ [
172
+ { label: 'a..proof', value: Math.exp(SCORES.get('proof')!), color: 'teal' },
173
+ { label: 'the..guess', value: Math.exp(SCORES.get('guess')!), color: 'orange' },
174
+ ],
175
+ {
176
+ width: 500,
177
+ height: 290,
178
+ max: 0.4,
179
+ labelSize: 28,
180
+ showValues: true,
181
+ states: true,
182
+ format: (p) => Math.log(Math.max(p, 1e-6)).toFixed(1),
183
+ },
184
+ )
185
+ place(column([finalTitle, finalBars], { gap: 28, align: 'center' }), chartCol, 'center')
186
+
187
+ // ── Stage subtitle helper ───────────────────────────────────────────────
188
+
189
+ let activeNote: Node | null = null
190
+ const setStageNote = (words: string) => {
191
+ const next = place(label(words, { size: 32 }), captionBand, 'left')
192
+ if (!activeNote) {
193
+ activeNote = next
194
+ s.add(next)
195
+ return
196
+ }
197
+ const prev = activeNote
198
+ activeNote = next
199
+ s.play(seq(fadeOut(prev, { duration: 0.2 }), fadeIn(next, { duration: 0.3 })))
200
+ }
201
+
202
+ // ── Chapter 1: Greedy decoding (k = 1) gets trapped at -1.7 ─────────────
203
+
204
+ s.add(title, foot, modeTagHolder)
205
+ const ch1At = 0.2
206
+ setStageNote(`Greedy search (k = 1) picks locally highest "the" (${fmtLogProb(SCORES.get('the')!)}) and ignores runner-up "a" (${fmtLogProb(SCORES.get('a')!)}).`)
207
+ s.chapter('Greedy trap (k = 1)')
208
+ s.caption(`Greedy keeps one token: "the", with log-probability ${fmtLogProb(SCORES.get('the')!)}.`, 5.4)
209
+
210
+ s.play(
211
+ greedyStrip.enter({ duration: 0.9 }),
212
+ searchTree.enter({ duration: 0.9 }),
213
+ fadeIn(step1Title, { duration: 0.8 }),
214
+ step1Bars.enter({ duration: 1.0 }),
215
+ )
216
+
217
+ s.play(searchTree.grow(['the', 'a', 'some'], { duration: 1.3 }))
218
+ s.play(
219
+ searchTree.path('the', { color: 'orange', duration: 1.0 }),
220
+ step1Bars.mark('the', 'chosen', { duration: 0.65 }),
221
+ step1Bars.mark(['a', 'some'], 'masked', { duration: 0.65 }),
222
+ greedyStrip.append('the', { from: step1Bars.bar(0), duration: 0.85 }),
223
+ )
224
+ s.wait(1.6)
225
+
226
+ s.caption(`Greedy follows "the" and finishes with log-probability ${fmtLogProb(SCORES.get('guess')!)}.`, 7.0)
227
+ setStageNote(`Locked into "the", every continuation drops sharply: "Give the best guess" ends at ${fmtLogProb(SCORES.get('guess')!)}.`)
228
+
229
+ s.play(searchTree.grow(['best', 'old'], { duration: 1.1 }))
230
+ s.play(
231
+ searchTree.path('best', { color: 'orange', duration: 1.0 }),
232
+ greedyStrip.append('best', { duration: 0.75 }),
233
+ )
234
+ s.wait(1.0)
235
+ s.play(searchTree.grow(['guess'], { duration: 1.0 }))
236
+ s.play(
237
+ searchTree.path('guess', { color: 'orange', duration: 1.0 }),
238
+ greedyStrip.append('guess', { duration: 0.75 }),
239
+ )
240
+ s.play(greedyStrip.mark([1, 2, 3], 'trapped', { duration: 0.7 }))
241
+ s.wait(2.6)
242
+
243
+ // ── Chapter 2: Beam search (k = 2) keeps "the" and "a", discovers -1.1 ──
244
+
245
+ const ch2At = s.time
246
+ s.chapter('Beam width k = 2')
247
+ setStageNote(`Beam search (k = 2) keeps both "the" (${fmtLogProb(SCORES.get('the')!)}) and "a" (${fmtLogProb(SCORES.get('a')!)}), pruning only "some" (${fmtLogProb(SCORES.get('some')!)}).`)
248
+ s.caption('Beam search with k equals two keeps both the and the runner-up token a, pruning only some.', 5.6)
249
+
250
+ s.play(
251
+ beamStrip.enter({ duration: 0.85 }),
252
+ step1Bars.clearStates({ duration: 0.5 }),
253
+ )
254
+ s.play(
255
+ searchTree.prune('some', { duration: 0.8 }),
256
+ step1Bars.mark(['the', 'a'], 'chosen', { duration: 0.65 }),
257
+ step1Bars.mark('some', 'masked', { duration: 0.65 }),
258
+ )
259
+ s.play(searchTree.path(['the', 'a'], { color: 'teal', duration: 1.0 }))
260
+ s.wait(1.6)
261
+
262
+ s.caption(`Expanding "a" reveals "clear" at ${fmtLogProb(SCORES.get('clear')!)}, ahead of "the best" at ${fmtLogProb(SCORES.get('best')!)}.`, 6.4)
263
+ setStageNote(`Step 2: expanding "a" uncovers "a -> clear" (${fmtLogProb(SCORES.get('clear')!)}), overtaking "the -> best" (${fmtLogProb(SCORES.get('best')!)}).`)
264
+
265
+ s.play(searchTree.grow(['clear', 'rough'], { duration: 1.2 }))
266
+ s.play(
267
+ searchTree.prune('old', { duration: 0.75 }),
268
+ searchTree.prune('rough', { duration: 0.75 }),
269
+ )
270
+ s.play(searchTree.path(['clear', 'best'], { color: 'teal', duration: 1.0 }))
271
+ s.wait(1.6)
272
+
273
+ // Swap right chart to completed path scores as step 3 expands "clear" -> "proof" (-1.1).
274
+ s.play(fadeOut([step1Title, step1Bars], { duration: 0.55 }))
275
+ s.play(
276
+ fadeIn(finalTitle, { duration: 0.65 }),
277
+ finalBars.enter({ duration: 0.95 }),
278
+ searchTree.grow(['proof'], { duration: 1.1 }),
279
+ )
280
+
281
+ const ch3At = s.time
282
+ s.chapter(`Winning path (${fmtLogProb(SCORES.get('proof')!)})`)
283
+ setStageNote(`Winner: "Give a clear proof" reaches ${fmtLogProb(SCORES.get('proof')!)} total log-prob, beating greedy (${fmtLogProb(SCORES.get('guess')!)}) by +${fmtLogProb(SCORES.get('proof')! - SCORES.get('guess')!)}.`)
284
+ s.caption(`Beam selects "Give a clear proof" at ${fmtLogProb(SCORES.get('proof')!)}, ahead of greedy at ${fmtLogProb(SCORES.get('guess')!)}.`, 7.2)
285
+
286
+ // Frontier is now ['guess', 'proof']: keep('proof') prunes the entire 'the -> best -> guess' trap!
287
+ s.play(
288
+ searchTree.keep('proof', { color: 'yellow', duration: 1.1 }),
289
+ finalBars.mark('a..proof', 'chosen', { duration: 0.65 }),
290
+ finalBars.mark('the..guess', 'masked', { duration: 0.65 }),
291
+ beamStrip.append(['a', 'clear', 'proof'], { duration: 1.3, lag: 0.4 }),
292
+ )
293
+ s.play(
294
+ searchTree.setState('proof', 'done', { duration: 0.7 }),
295
+ beamStrip.mark([1, 2, 3], 'winner', { duration: 0.7 }),
296
+ indicate(finalBars.bar(0), { color: 'yellow', scale: 1.06, duration: 1.0 }),
297
+ )
298
+
299
+ s.play(
300
+ spotlight([searchTree, beamStrip, finalBars], {
301
+ keep: [title, foot, modeTagHolder, greedyStrip, finalTitle, activeNote!],
302
+ duration: 0.8,
303
+ }),
304
+ )
305
+ s.wait(2.8)
306
+ s.play(spotlight(null, { duration: 0.6 }))
307
+ s.wait(2.6)
308
+
309
+ const endAt = s.time
310
+ s.at(0, () => {
311
+ modeTagHolder.add(
312
+ tagTrack([
313
+ { at: ch1At, word: 'GREEDY k = 1', note: `trapped at ${fmtLogProb(SCORES.get('guess')!)}` },
314
+ { at: ch2At, word: 'BEAM k = 2', note: 'keep top 2' },
315
+ { at: ch3At, word: 'WINNER', note: `proof = ${fmtLogProb(SCORES.get('proof')!)}` },
316
+ ], {
317
+ until: endAt + 1,
318
+ size: 28,
319
+ anchor: 'right',
320
+ noteFont: 'text-serif',
321
+ }).at(area.right, title.get('y')),
322
+ )
323
+ })
324
+ })
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Exact two-compartment multiplicity for 20 labeled particles.
3
+ * Primary teaching sources:
4
+ * David Tong, Statistical Physics, sections 1.2.1 and 1.2.3:
5
+ * https://www.damtp.cam.ac.uk/user/tong/statphys/statmechhtml/S1.html
6
+ * Feynman Lectures I.6, binomial probabilities:
7
+ * https://www.feynmanlectures.caltech.edu/I_06.html
8
+ *
9
+ * Ω counts only labeled left/right assignments, with equal weights. This is a
10
+ * finite coarse-grained state count, not the full phase-space entropy of a gas.
11
+ * Seeded urn flips and interpolated motion illustrate a realization, not a
12
+ * microscopic trajectory, H-theorem, or monotonically increasing entropy.
13
+ */
14
+ import {
15
+ assertEqual, axes, Box, delay, dot, dynamic, fadeIn, fadeOut,
16
+ film, line, linear, place, rect, sceneKit, tex, text,
17
+ } from 'vizmatic/stage'
18
+ import { LOG_MULTIPLICITIES, MULTIPLICITIES, PARTICLES, STEPS, stateAt } from './_boltzmann-entropy/model'
19
+
20
+ assertEqual(MULTIPLICITIES.reduce((a, b) => a + b), 2 ** PARTICLES, 'every binary assignment counted once')
21
+ assertEqual(MULTIPLICITIES[10], 184756, 'exact balanced multiplicity')
22
+ assertEqual(MULTIPLICITIES[20], 1, 'one all-left assignment')
23
+
24
+ export default film({
25
+ title: 'Entropy counts hidden arrangements',
26
+ description: 'Twenty labeled particles change compartments. Exact binomial counts drive a logarithmic entropy plot, including finite fluctuations. A coarse-grained urn model, with deterministic illustrative motion.',
27
+ look: 'midnight', font: 'text-serif', fps: 60, poster: 18.5, bloom: 0.1,
28
+ }, (s) => {
29
+ const kit = sceneKit({ size: 38, area: { left: -850, right: 850, top: -250, bottom: 320 }, heading: { size: 66, y: -466 }, source: { size: 26, y: -401 } })
30
+ const title = kit.heading('Entropy counts hidden arrangements')
31
+ const source = kit.source('Tong, Statistical Physics §1.2 · Feynman Lectures I.6 · exact two-compartment model')
32
+ const [words, main, metrics] = kit.area.rows([1, 7, 2], 34)
33
+ const [tankArea, plotArea] = main.columns([1.3, 1], 95)
34
+ const [tankHead, tankBody, tankFoot] = tankArea.rows([1.3, 7.4, 1.3], 18)
35
+ const [plotHead, plotBody, plotFoot] = plotArea.rows([1.3, 7.4, 1.3], 18)
36
+ const caption = (content: string) => place(kit.label(content), words, 'left')
37
+ const first = caption('Record only which half each labeled particle occupies.')
38
+ const many = caption('The left count hides many different assignments.')
39
+ const balanced = caption('Ten on each side: 184,756 left/right assignments.')
40
+ const fluctuations = caption('Small systems fluctuate. This entropy can decrease.')
41
+ const conclusion = caption('Balanced counts collect far more assignments than all left.')
42
+ const progress = s.value(0), distributionVisible = s.value(0)
43
+ const tankTitle = place(text('20 labeled particles · illustrative urn motion', { size: 28, color: 'dim' }), tankHead, 'left')
44
+ const tank = place(rect(tankBody.width - 8, tankBody.height - 8, { stroke: 'dim', width: 2, radius: 14 }), tankBody)
45
+ const halfWidth = (tankBody.width - 8) / 2, halfHeight = (tankBody.height - 8) / 2
46
+ const divider = line([tankBody.cx, tankBody.cy - halfHeight], [tankBody.cx, tankBody.cy + halfHeight], { stroke: 'dim', width: 2, dash: [7, 10] }).opacity(0.5)
47
+ const particles = dynamic(() => stateAt(progress.value).particles.map((p) =>
48
+ dot(p.moving ? 13 : 10, p.left ? 'blue' : 'teal')
49
+ .at(tankBody.cx + p.x * halfWidth, tankBody.cy + p.y * halfHeight)
50
+ .glow(p.moving ? 18 : 2),
51
+ ))
52
+ const [leftFoot, rightFoot] = tankFoot.columns(2)
53
+ const leftName = place(text('LEFT', { size: 26, color: 'blue', font: 'mono' }), leftFoot)
54
+ const rightName = place(text('RIGHT', { size: 26, color: 'teal', font: 'mono' }), rightFoot)
55
+ const axisName = place(tex('S_{\\rm coarse}/k_B = \\ln\\Omega', { size: 32 }), plotHead, 'left')
56
+ const plot = place(axes({ x: [-0.8, 20.8], y: [-0.7, 14], width: plotBody.width - 40, height: plotBody.height - 40, xTicks: [0, 5, 10, 15, 20], yTicks: [0, 4, 8, 12], labelSize: 26, tips: false, color: 'dim' }), plotBody)
57
+ plot.add(dynamic(() => distributionVisible.value < 0.01 ? [] : LOG_MULTIPLICITIES.map((logOmega, left) =>
58
+ dot(5, 'dim').opacity(distributionVisible.value * 0.65).at(plot.p(left, logOmega)),
59
+ )))
60
+ plot.add(dynamic(() => {
61
+ const state = stateAt(progress.value)
62
+ return [line(plot.p(state.left, 0), plot.p(state.left, state.logOmega), { stroke: 'teal', width: 2, dash: [5, 7] }).opacity(0.6), dot(9, 'teal').glow(12).at(plot.p(state.left, state.logOmega))]
63
+ }))
64
+ const xName = place(text('Particles in the left half', { size: 28, color: 'dim' }), plotFoot)
65
+
66
+ const [countsRoom, omegaRoom, logRoom] = metrics.columns([1, 1, 1], 48)
67
+ const countLabel = place(text('LEFT : RIGHT', { size: 26, font: 'mono', color: 'dim' }), countsRoom, 'top')
68
+ const omegaLabel = place(text('Ω: assignments', { size: 28, color: 'dim' }), omegaRoom, 'top')
69
+ const logLabel = place(tex('S_{\\rm coarse}/k_B = \\ln\\Omega', { size: 32 }), logRoom, 'top')
70
+ const countValue = dynamic(() => {
71
+ const st = stateAt(progress.value)
72
+ return place(text(`${String(st.left).padStart(2, ' ')} : ${String(st.right).padStart(2, ' ')}`, { size: 52, font: 'mono', color: 'blue' }), countsRoom, 'bottom')
73
+ })
74
+ const omegaValue = dynamic(() => place(text(stateAt(progress.value).omega.toLocaleString('en-US'), { size: 52, font: 'mono', color: 'teal' }), omegaRoom, 'bottom'))
75
+ const logValue = dynamic(() => place(text(stateAt(progress.value).logOmega.toFixed(3), { size: 52, font: 'mono' }), logRoom, 'bottom'))
76
+ const assumptions = place(text('Equal-weight side assignments only; positions within halves and momenta omitted.', { size: 26, color: 'dim' }), new Box(-850, -377, 850, -337))
77
+ const equation = place(tex('\\Omega(n_L) = \\tbinom{20}{n_L},\\qquad S_{\\rm coarse} = k_B \\ln\\Omega', { size: 32 }), new Box(-850, -326, 850, -270), 'right')
78
+
79
+ s.chapter('One left/right assignment')
80
+ s.add(title, source, first, tankTitle, tank, divider, particles, leftName, rightName, axisName, plot, xName, countLabel, omegaLabel, logLabel, countValue, omegaValue, logValue, assumptions, equation)
81
+ s.caption('Twenty labeled particles start on the left. Only their left/right assignments are counted.', 5)
82
+ s.wait(4)
83
+
84
+ s.chapter('Count the hidden assignments')
85
+ s.play(fadeOut(first, { duration: 0.2 }), delay(fadeIn(many, { duration: 0.4 }), 0.2))
86
+ s.play(distributionVisible.to(1), { duration: 0.9 })
87
+ s.wait(1)
88
+ s.caption('The multiplicity is twenty choose the number on the left. Its natural logarithm gives the entropy of this coarse description in units of Boltzmann’s constant.', 12)
89
+ s.play(progress.to(18, { ease: linear }), { duration: 9 })
90
+ s.wait(1.5)
91
+
92
+ s.chapter('Many ways to balance')
93
+ s.play(fadeOut(many, { duration: 0.2 }), delay(fadeIn(balanced, { duration: 0.4 }), 0.2))
94
+ s.caption('Ten per side: 184,756 assignments, each with equal weight.', 6)
95
+ s.wait(3.5)
96
+
97
+ s.chapter('Finite fluctuations')
98
+ s.play(fadeOut(balanced, { duration: 0.2 }), delay(fadeIn(fluctuations, { duration: 0.4 }), 0.2))
99
+ s.caption('This finite urn realization fluctuates. Its coarse-grained entropy can decrease. The illustrated motion is not a microscopic gas trajectory.', 13)
100
+ s.play(progress.to(STEPS, { ease: linear }), { duration: 12 })
101
+ s.play(fadeOut(fluctuations, { duration: 0.2 }), delay(fadeIn(conclusion, { duration: 0.4 }), 0.2))
102
+ s.caption('This model counts left/right assignments only, not the full phase space of a gas.', 40 - s.time)
103
+ s.wait(Math.max(0, 40 - s.time))
104
+ })