vizmatic 0.8.3 → 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 (99) hide show
  1. package/PROMPT.md +32 -0
  2. package/README.md +8 -3
  3. package/ROADMAP.md +4 -2
  4. package/SCIENCE.md +69 -3
  5. package/dist/chunk-6JI55YX4.js +604 -0
  6. package/dist/{chunk-LTX44BAE.js → chunk-BYKXNUX7.js} +25 -4
  7. package/dist/{chunk-4MXGLMBG.js → chunk-EPZLNABN.js} +107 -37
  8. package/dist/chunk-EWCO6ZT6.js +696 -0
  9. package/dist/{chunk-JZPMGVBP.js → chunk-G7HRSKHV.js} +1 -1
  10. package/dist/{chunk-RPAHMKAR.js → chunk-JTWC2OPN.js} +7 -5
  11. package/dist/chunk-LJZO36IR.js +124 -0
  12. package/dist/chunk-REL2BZ2B.js +88 -0
  13. package/dist/chunk-RLPEOWST.js +1 -0
  14. package/dist/chunk-VMHOWCDL.js +296 -0
  15. package/dist/chunk-YDD63HHD.js +1 -0
  16. package/dist/{chunk-I745F4QK.js → chunk-YNGDEARY.js} +1134 -643
  17. package/dist/cli.js +80 -543
  18. package/dist/gpu-selection-CDWCZH27.js +1 -0
  19. package/dist/gpu-selection-MX6NHMNA.js +635 -0
  20. package/dist/index.cjs +473 -155
  21. package/dist/index.d.cts +30 -239
  22. package/dist/index.d.ts +30 -239
  23. package/dist/index.js +410 -457
  24. package/dist/math-E7W5LFWO.js +1 -0
  25. package/dist/{math-LXB4FH4E.js → math-NEFQUPRV.js} +3 -1
  26. package/dist/scene-browser.js +17 -17
  27. package/dist/scene-cli.js +1 -1
  28. package/dist/scene-runtime.cjs +4 -2
  29. package/dist/scene-runtime.js +2 -2
  30. package/dist/stage-browser/browser.d.ts +1206 -854
  31. package/dist/stage-browser/gpu-renderer.js +138 -0
  32. package/dist/stage-browser/{math-4WFNHVV2.js → math-KYHUOK7A.js} +46 -10
  33. package/dist/stage-browser/stage.js +107 -19
  34. package/dist/stage-export.cjs +8221 -6784
  35. package/dist/stage-export.d.cts +13 -5
  36. package/dist/stage-export.d.ts +13 -5
  37. package/dist/stage-export.js +111 -601
  38. package/dist/stage.cjs +6243 -3474
  39. package/dist/stage.d.cts +1064 -765
  40. package/dist/stage.d.ts +1064 -765
  41. package/dist/stage.js +3571 -2405
  42. package/dist/{svg-import-B5BGbC1t.d.cts → svg-import-CSCFWYaB.d.cts} +21 -12
  43. package/dist/{svg-import-B5BGbC1t.d.ts → svg-import-CSCFWYaB.d.ts} +21 -12
  44. package/dist/teaching-math-DTKc0XsB.d.cts +243 -0
  45. package/dist/teaching-math-ydDBhJ2M.d.ts +243 -0
  46. package/dist/{video-CiN1MDCS.d.cts → theme-DhVdDQKO.d.cts} +4 -237
  47. package/dist/{video-CiN1MDCS.d.ts → theme-DhVdDQKO.d.ts} +4 -237
  48. package/dist/video-BYCeOz8F.d.ts +259 -0
  49. package/dist/video-CGLxJXqu.d.cts +259 -0
  50. package/examples/catalog-science-physics.tsx +6 -6
  51. package/examples/films/_boltzmann-entropy/model.ts +63 -0
  52. package/examples/films/_catalysis/model.ts +49 -0
  53. package/examples/films/_gravitational-waves/model.ts +32 -0
  54. package/examples/films/_heat-equation/model.ts +54 -0
  55. package/examples/films/_hydrogen-orbitals/model.ts +31 -0
  56. package/examples/films/_maxwell/model.ts +84 -0
  57. package/examples/films/_planetary-orbits/appearance.ts +71 -0
  58. package/examples/films/_planetary-orbits/model.ts +152 -0
  59. package/examples/films/_planetary-orbits/saturn.ts +142 -0
  60. package/examples/films/_quantum-tunneling/model.ts +58 -0
  61. package/examples/films/_reaction-diffusion/model.ts +61 -0
  62. package/examples/films/_stationary-action/model.ts +38 -0
  63. package/examples/films/attention.ts +309 -253
  64. package/examples/films/beam-search.ts +321 -49
  65. package/examples/films/boltzmann-entropy.ts +104 -0
  66. package/examples/films/cache-miss.ts +387 -394
  67. package/examples/films/catalog.json +238 -77
  68. package/examples/films/catalysis.ts +128 -0
  69. package/examples/films/central-limit.ts +27 -22
  70. package/examples/films/complex-maps.ts +70 -56
  71. package/examples/films/deck-example.ts +261 -200
  72. package/examples/films/euler-circle.ts +72 -28
  73. package/examples/films/flash-attention.ts +549 -0
  74. package/examples/films/forecast.ts +2 -2
  75. package/examples/films/fourier-epicycles.ts +21 -20
  76. package/examples/films/gradient-descent.ts +23 -49
  77. package/examples/films/gravitational-waves.ts +179 -0
  78. package/examples/films/heat-equation.ts +124 -0
  79. package/examples/films/hydrogen-orbitals.ts +135 -0
  80. package/examples/films/io-uring.ts +635 -0
  81. package/examples/films/linear-maps.ts +42 -31
  82. package/examples/films/lorenz.ts +42 -79
  83. package/examples/films/maxwell.ts +197 -0
  84. package/examples/films/pathlines.ts +85 -0
  85. package/examples/films/planetary-orbits.ts +146 -0
  86. package/examples/films/pythagoras.ts +18 -10
  87. package/examples/films/quantum-tunneling.ts +116 -0
  88. package/examples/films/rag-citations.ts +423 -0
  89. package/examples/films/reaction-diffusion.ts +70 -0
  90. package/examples/films/ring-allreduce.ts +531 -0
  91. package/examples/films/stationary-action.ts +170 -0
  92. package/examples/films/svd-3d.ts +605 -0
  93. package/examples/films/taylor-series.ts +9 -9
  94. package/examples/films/vizmatic-title.ts +1 -0
  95. package/examples/vizmatic-hero.tsx +102 -32
  96. package/package.json +3 -1
  97. package/dist/chunk-3F2VQ7NW.js +0 -1
  98. package/dist/chunk-GGFDBJ25.js +0 -88
  99. package/dist/math-QVCETQDQ.js +0 -1
@@ -0,0 +1,259 @@
1
+ import React, { ReactNode } from 'react';
2
+ import { b as ThemeMode } from './theme-DhVdDQKO.cjs';
3
+
4
+ /**
5
+ * Vizmatic — Brand
6
+ *
7
+ * Adds a small theme-aware watermark to rendered artifacts.
8
+ */
9
+
10
+ type WatermarkPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
11
+ interface WatermarkImageOptions {
12
+ src: string;
13
+ width?: number;
14
+ height?: number;
15
+ alt?: string;
16
+ }
17
+ interface WatermarkOptions {
18
+ text?: string | false;
19
+ image?: string | WatermarkImageOptions;
20
+ icon?: ReactNode | string | false;
21
+ element?: ReactNode;
22
+ position?: WatermarkPosition;
23
+ opacity?: number;
24
+ color?: string;
25
+ }
26
+ interface WatermarkElementProps extends WatermarkOptions {
27
+ children?: ReactNode;
28
+ }
29
+ type WatermarkInput = boolean | string | WatermarkOptions | React.ReactElement<WatermarkElementProps>;
30
+ declare function normalizeWatermark(watermark: WatermarkInput | undefined): WatermarkOptions | undefined;
31
+ declare function Watermark(_props: WatermarkElementProps): null;
32
+ /**
33
+ * Wrap an illustration element with a watermark overlay.
34
+ */
35
+ declare function wrapWithWatermark(element: React.ReactNode, width: number, height: number, theme?: 'dark' | 'light', watermark?: WatermarkInput): React.ReactElement;
36
+ declare function wrapWithBrand(element: React.ReactNode, width: number, height: number, theme?: 'dark' | 'light', label?: string): React.ReactElement;
37
+
38
+ type RenderBackground = 'transparent' | 'theme' | (string & {});
39
+
40
+ type AnimationEasingName = 'linear' | 'ease-in' | 'ease-out' | 'ease-in-out';
41
+ type AnimationEasing = AnimationEasingName | ((progress: number) => number);
42
+ type AnimationInterpolator<T> = {
43
+ bivarianceHack(from: T, to: T, progress: number): T;
44
+ }['bivarianceHack'];
45
+ interface AnimationHoldStep {
46
+ type: 'hold';
47
+ duration: number;
48
+ label?: string;
49
+ }
50
+ interface AnimationKeyframeStep<T> {
51
+ type: 'keyframe';
52
+ value: T;
53
+ label?: string;
54
+ }
55
+ interface AnimationTweenStep<T> {
56
+ type: 'tween';
57
+ to: T;
58
+ duration: number;
59
+ easing?: AnimationEasing;
60
+ interpolate?: AnimationInterpolator<T>;
61
+ label?: string;
62
+ }
63
+ type AnimationPropertyStep<T> = AnimationHoldStep | AnimationKeyframeStep<T> | AnimationTweenStep<T>;
64
+ type AnimationParallelTracks<S extends object> = {
65
+ [K in keyof S]?: readonly AnimationPropertyStep<S[K]>[];
66
+ };
67
+ interface AnimationParallelStep<S extends object> {
68
+ type: 'parallel';
69
+ tracks: AnimationParallelTracks<S>;
70
+ label?: string;
71
+ }
72
+ type AnimationTimelineStep<S extends object> = AnimationHoldStep | AnimationKeyframeStep<Partial<S>> | AnimationTweenStep<Partial<S>> | AnimationParallelStep<S>;
73
+ interface AnimationFrameContext {
74
+ index: number;
75
+ count: number;
76
+ time: number;
77
+ duration: number;
78
+ delay: number;
79
+ progress: number;
80
+ step: number;
81
+ stepProgress: number;
82
+ label?: string;
83
+ fps: number;
84
+ }
85
+ interface AnimationDefinition<S extends object> {
86
+ initial: S;
87
+ timeline: readonly AnimationTimelineStep<S>[];
88
+ render: (state: Readonly<S>, frame: Readonly<AnimationFrameContext>) => ReactNode;
89
+ fps?: number;
90
+ }
91
+ interface DefinedAnimation<S extends object> extends AnimationDefinition<S> {
92
+ readonly kind: 'vizmatic.animation';
93
+ readonly duration: number;
94
+ readonly fps: number;
95
+ }
96
+ interface SampleAnimationOptions {
97
+ fps?: number;
98
+ }
99
+ interface SampledAnimationFrame<S extends object> {
100
+ state: Readonly<S>;
101
+ frame: Readonly<AnimationFrameContext>;
102
+ }
103
+ interface AnimationCadenceAnalysis {
104
+ fps: number;
105
+ duration: number;
106
+ frameCount: number;
107
+ encodedDuration: number;
108
+ targetInterval: number;
109
+ minDelay: number;
110
+ maxDelay: number;
111
+ }
112
+ declare function hold(duration: number, label?: string): AnimationHoldStep;
113
+ declare function keyframe<T>(value: T, label?: string): AnimationKeyframeStep<T>;
114
+ declare function tween<T>(to: T, options: Omit<AnimationTweenStep<T>, 'type' | 'to'>): AnimationTweenStep<T>;
115
+ declare function parallel<S extends object>(tracks: AnimationParallelTracks<S>, label?: string): AnimationParallelStep<S>;
116
+ declare function defineAnimation<S extends object>(definition: AnimationDefinition<S>): DefinedAnimation<S>;
117
+ declare function sampleAnimation<S extends object>(animation: DefinedAnimation<S>, time: number): Readonly<S>;
118
+ /** Samples an exact timestamp with caller-provided frame timing, without GIF cadence rounding. */
119
+ declare function sampleAnimationFrame<S extends object>(animation: DefinedAnimation<S>, requestedTime: number, timing: Pick<AnimationFrameContext, 'index' | 'count' | 'delay' | 'fps'>): SampledAnimationFrame<S>;
120
+ declare function analyzeAnimationCadence<S extends object>(animation: DefinedAnimation<S>, options?: SampleAnimationOptions): AnimationCadenceAnalysis;
121
+ declare function sampleAnimationFrames<S extends object>(animation: DefinedAnimation<S>, options?: SampleAnimationOptions): readonly SampledAnimationFrame<S>[];
122
+
123
+ interface VideoFrameInfo {
124
+ /** Zero-based frame index. The final frame is always before the video endpoint. */
125
+ index: number;
126
+ count: number;
127
+ /** Frame presentation time in milliseconds. */
128
+ time: number;
129
+ /** Duration rounded to the nearest whole frame, in milliseconds. */
130
+ duration: number;
131
+ /** Fraction of the video represented by this frame, from 0 to 1. */
132
+ progress: number;
133
+ fps: number;
134
+ }
135
+ type VideoCodec = 'h264' | 'vp9';
136
+ type H264Encoder = 'libx264' | 'videotoolbox' | 'nvenc';
137
+ type H264EncoderRequest = H264Encoder | 'auto';
138
+ interface RgbaVideoOptions {
139
+ width: number;
140
+ height: number;
141
+ /** Requested duration before rounding to a whole number of frames. */
142
+ duration: number;
143
+ outputPath: string;
144
+ /** After drawing, return true only if the RGBA bytes equal the preceding frame.
145
+ * Return 'compare' to check consecutive RGBA snapshots byte for byte.
146
+ * Sends timestamped RGBA packets and expands holds after color conversion. */
147
+ frameIsRepeat?: (frame: VideoFrameInfo) => boolean | 'compare';
148
+ fps?: number;
149
+ audioPath?: string;
150
+ /** Seconds to skip in the audio file, for a render that starts partway through a timeline. */
151
+ audioOffset?: number;
152
+ ffmpegPath?: string;
153
+ /** H.264 writes MP4. VP9 writes WebM. */
154
+ codec?: VideoCodec;
155
+ /**
156
+ * The default is libx264. Auto probes local hardware for standard-quality output, except in CI.
157
+ * Auto preserves custom CRF, x264 parameters and tuning by selecting software.
158
+ * NVENC uses NVIDIA's dedicated video encoder; RGBA drawing and color conversion are unchanged.
159
+ */
160
+ h264Encoder?: H264EncoderRequest;
161
+ /** Fail before painting if an explicit encoder cannot encode these settings. Auto permits software. */
162
+ requireH264Encoder?: boolean;
163
+ /**
164
+ * x264 speed preset, default fast. NVENC maps ultrafast/superfast/veryfast/faster/fast/medium
165
+ * to p1/p2/p3/p4/p5/p6, and slow/slower/veryslow/placebo to p7, with high-quality tuning.
166
+ * These preserve the speed/quality preference, not identical compression or image quality.
167
+ */
168
+ preset?: string;
169
+ /** x264 tuning, such as "animation" or "grain". NVENC falls back to software to preserve it. */
170
+ tune?: string;
171
+ /**
172
+ * More settings for the H.264 encoder, as x264 writes them: `name=value` pairs with a colon between them,
173
+ * such as "aq-strength=1.0:trellis=0". They come after the preset and the tune, so they replace a value of those.
174
+ */
175
+ x264Params?: string;
176
+ /**
177
+ * Default 18 for H.264, 30 for VP9. Explicit NVENC maps 1..51 to VBR CQ of the same number,
178
+ * without a bitrate cap. CQ and CRF are not equivalent quality scales. CRF 0 keeps software
179
+ * lossless encoding, since NVENC CQ 0 means automatic quality, not lossless.
180
+ */
181
+ crf?: number;
182
+ threads?: number;
183
+ /** Title in the file's metadata. MP4 only. */
184
+ title?: string;
185
+ /** Chapter markers, in seconds from the start of the video. MP4 only. Players show them on the timeline. */
186
+ chapters?: readonly {
187
+ title: string;
188
+ time: number;
189
+ }[];
190
+ /** A caption track that the viewer can switch on, in seconds from the start of the video. MP4 only. */
191
+ captions?: readonly {
192
+ t0: number;
193
+ t1: number;
194
+ text: string;
195
+ }[];
196
+ signal?: AbortSignal;
197
+ onProgress?: (frame: VideoFrameInfo) => void | Promise<void>;
198
+ }
199
+ /** FFmpeg metadata with a title and chapters. Each chapter ends where the next one starts. */
200
+ declare function chapterMetadata(title: string | undefined, chapters: readonly {
201
+ title: string;
202
+ time: number;
203
+ }[], duration: number): string;
204
+ /** Captions as SubRip text, clipped to the video. */
205
+ declare function captionsToSrt(captions: readonly {
206
+ t0: number;
207
+ t1: number;
208
+ text: string;
209
+ }[], duration: number): string;
210
+ interface RgbaVideoOutput {
211
+ width: number;
212
+ height: number;
213
+ frameCount: number;
214
+ duration: number;
215
+ fps: number;
216
+ bytes: number;
217
+ outputPath: string;
218
+ audioIncluded: boolean;
219
+ /** Full RGBA packets written when frameIsRepeat is supplied. */
220
+ rgbaPackets?: number;
221
+ /** The encoder that produced the H.264 stream. Absent for other codecs. */
222
+ h264Encoder?: H264Encoder;
223
+ }
224
+ interface AnimationVideoOptions extends Omit<RgbaVideoOptions, 'duration'> {
225
+ /** Physical output pixels per logical scene pixel. Defaults to 1. Scaled dimensions must be even integers. */
226
+ scale?: number;
227
+ theme?: ThemeMode;
228
+ /** MP4 has no alpha channel. Defaults to the opaque theme background. */
229
+ background?: RenderBackground;
230
+ watermark?: WatermarkInput;
231
+ brand?: boolean | string;
232
+ }
233
+ type RgbaVideoFrameRenderer = (frame: VideoFrameInfo) => Uint8Array | Promise<Uint8Array>;
234
+ /** Lazily yields every frame timestamp; it never emits a duplicate endpoint frame. */
235
+ declare function videoFrameSchedule(duration: number, fps?: number): Generator<VideoFrameInfo>;
236
+ /** Streams a typed TSX animation to H.264 MP4 with BT.709 color at exact video frame times (30 fps by default). */
237
+ declare function renderAnimationVideo<S extends object>(animation: DefinedAnimation<S>, options: AnimationVideoOptions): Promise<RgbaVideoOutput>;
238
+ type H264Format = {
239
+ width: number;
240
+ height: number;
241
+ fps: number;
242
+ };
243
+ type H264SelectionOptions = Pick<RgbaVideoOptions, 'preset' | 'crf' | 'tune' | 'x264Params' | 'signal' | 'requireH264Encoder'>;
244
+ /**
245
+ * Resolve to an actual encoder after encoding one frame with the output format and settings.
246
+ * Auto prefers VideoToolbox on macOS and NVENC elsewhere, with a software fallback. Any nonempty
247
+ * CI or GITHUB_ACTIONS environment variable disables automatic hardware selection. Explicit requests
248
+ * still probe in CI. Custom x264 tuning/parameters and nondefault CRF keep auto on software.
249
+ */
250
+ declare function resolveH264Encoder(requested?: H264EncoderRequest, ffmpegPath?: string, format?: H264Format, options?: H264SelectionOptions): Promise<H264Encoder>;
251
+ /**
252
+ * Encodes caller-rendered RGBA frames as H.264 MP4 or VP9 WebM, tagged BT.709.
253
+ * Frames are requested and written one at a time, so the caller controls
254
+ * rendering and memory use.
255
+ */
256
+ declare function renderRgbaVideo(renderFrame: RgbaVideoFrameRenderer, options: RgbaVideoOptions): Promise<RgbaVideoOutput>;
257
+
258
+ export { chapterMetadata as B, defineAnimation as C, hold as E, keyframe as F, normalizeWatermark as G, parallel as I, renderAnimationVideo as J, renderRgbaVideo as K, resolveH264Encoder as L, sampleAnimation as M, sampleAnimationFrame as N, sampleAnimationFrames as O, tween as P, videoFrameSchedule as Q, wrapWithBrand as T, wrapWithWatermark as U, Watermark as t, analyzeAnimationCadence as y, captionsToSrt as z };
259
+ export type { AnimationCadenceAnalysis as A, DefinedAnimation as D, H264Encoder as H, RenderBackground as R, SampleAnimationOptions as S, VideoCodec as V, WatermarkInput as W, AnimationDefinition as a, AnimationEasing as b, AnimationEasingName as c, AnimationFrameContext as d, AnimationHoldStep as e, AnimationInterpolator as f, AnimationKeyframeStep as g, AnimationParallelStep as h, AnimationParallelTracks as i, AnimationPropertyStep as j, AnimationTimelineStep as k, AnimationTweenStep as l, AnimationVideoOptions as m, H264EncoderRequest as n, RgbaVideoFrameRenderer as o, RgbaVideoOptions as p, RgbaVideoOutput as q, SampledAnimationFrame as r, VideoFrameInfo as s, WatermarkElementProps as u, WatermarkImageOptions as v, WatermarkOptions as w, WatermarkPosition as x };
@@ -52,19 +52,19 @@ export function create(theme: ThemeMode = 'dark') {
52
52
 
53
53
  <Panel
54
54
  c={c}
55
- title="In-phase wave superposition"
56
- subtitle="Two equal waves add point by point to a wave with twice the amplitude."
55
+ title="Phase-shifted wave superposition"
56
+ subtitle="Two coherent waves with Δφ = 1.2 rad add point by point into a shifted resultant."
57
57
  width={608}
58
58
  align="center"
59
- footer="Illustrative sinusoidal waves · A = 1 m each · λ = 4 m"
59
+ footer="Illustrative sinusoidal waves · A = 1 m each · λ = 4 m · Δφ = 1.2 rad"
60
60
  >
61
61
  <WaveDiagram
62
62
  c={c}
63
63
  width={600}
64
64
  height={360}
65
65
  waves={[
66
- { amplitude: 1, wavelength: 4, phase: 0, color: c.info, label: 'wave 1 · A' },
67
- { amplitude: 1, wavelength: 4, phase: 0, color: c.primary, label: 'wave 2 · A' },
66
+ { amplitude: 1, wavelength: 4, phase: 0, color: c.info, label: 'wave 1 · φ = 0' },
67
+ { amplitude: 1, wavelength: 4, phase: 1.2, color: c.primary, label: 'wave 2 · φ = 1.2' },
68
68
  ]}
69
69
  time={0}
70
70
  xMin={-4}
@@ -74,7 +74,7 @@ export function create(theme: ThemeMode = 'dark') {
74
74
  showComponents
75
75
  showSum
76
76
  />
77
- <TextLabel c={c} text="At matching crests and troughs, the displacement adds to ±2A." fontSize={12} color={c.textSecondary} />
77
+ <TextLabel c={c} text="At each position x, the combined wave sums the two individual displacements." fontSize={12} color={c.textSecondary} />
78
78
  </Panel>
79
79
  </Row>
80
80
  </Scene>
@@ -0,0 +1,63 @@
1
+ /** A finite two-compartment urn model, not molecular dynamics. A microstate in
2
+ * this coarse description is one left/right bit for each of 20 labeled particles.
3
+ * Coordinates within a half and momenta are deliberately not counted.
4
+ */
5
+ export const PARTICLES = 20
6
+ export const STEPS = 42
7
+
8
+ export function multiplicity(left: number): number {
9
+ if (!Number.isInteger(left) || left < 0 || left > PARTICLES) throw new RangeError('left count must be an integer from 0 to 20')
10
+ let result = 1
11
+ for (let k = 1; k <= Math.min(left, PARTICLES - left); k++) result = result * (PARTICLES - k + 1) / k
12
+ return Math.round(result)
13
+ }
14
+
15
+ export const MULTIPLICITIES = Array.from({ length: PARTICLES + 1 }, (_, n) => multiplicity(n))
16
+ export const LOG_MULTIPLICITIES = MULTIPLICITIES.map(Math.log)
17
+
18
+ // One seeded Ehrenfest-style urn realization. Each event flips one selected
19
+ // particle's side. Animation interpolates the relocation; it is not a gas trajectory.
20
+ let seed = 0x5eeda11
21
+ export const FLIPS: readonly number[] = Array.from({ length: STEPS }, () => {
22
+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0
23
+ return Math.floor(seed / 2 ** 32 * PARTICLES)
24
+ })
25
+ const assignments: readonly (readonly boolean[])[] = (() => {
26
+ const states = [Array<boolean>(PARTICLES).fill(true)]
27
+ for (const id of FLIPS) {
28
+ const next = [...states[states.length - 1]]
29
+ next[id] = !next[id]
30
+ states.push(next)
31
+ }
32
+ return states
33
+ })()
34
+
35
+ export interface ParticleState { id: number; x: number; y: number; left: boolean; moving: boolean }
36
+ export interface EntropyState {
37
+ particles: ParticleState[]
38
+ left: number
39
+ right: number
40
+ omega: number
41
+ logOmega: number
42
+ }
43
+
44
+ /** Pure state at a fractional urn step. Counts come from the displayed side,
45
+ * including the crossing frame, so every dot agrees with the numeric readout.
46
+ */
47
+ export function stateAt(step: number): EntropyState {
48
+ if (!Number.isFinite(step)) throw new TypeError('urn step must be finite')
49
+ const progress = Math.max(0, Math.min(STEPS, step)), index = Math.floor(progress)
50
+ const fraction = progress - index
51
+ const eased = (1 - Math.cos(Math.PI * fraction)) / 2
52
+ const particles = assignments[index].map((left, id) => {
53
+ const moving = index < STEPS && FLIPS[index] === id
54
+ // Each particle has a stable lane; all coordinates remain in [-1, 1].
55
+ const reach = 0.2 + (id % 4) * 0.2
56
+ const initialX = left ? -reach : reach
57
+ const x = moving ? initialX * (1 - 2 * eased) : initialX
58
+ const y = -0.76 + Math.floor(id / 4) * 0.38 + 0.035 * Math.sin(progress * 1.7 + id * 2.1)
59
+ return { id, x, y, left: x < 0, moving }
60
+ })
61
+ const left = particles.filter((particle) => particle.left).length
62
+ return { particles, left, right: PARTICLES - left, omega: MULTIPLICITIES[left], logOmega: LOG_MULTIPLICITIES[left] }
63
+ }
@@ -0,0 +1,49 @@
1
+ import type { Molecule3DData } from 'vizmatic/stage'
2
+
3
+ // Schematic Gibbs-energy profiles in arbitrary units. These are author-chosen
4
+ // teaching curves, not measured barriers or a computed hydrogenation pathway.
5
+ export const direct = [[0, 0], [0.45, 85], [1, -25]] as const
6
+ export const catalyzed = [[0, 0], [0.26, 37], [0.5, -5], [0.73, 28], [1, -25]] as const
7
+
8
+ export function energy(knots: readonly (readonly [number, number])[], x: number): number {
9
+ const i = Math.max(0, Math.min(knots.length - 2, knots.findIndex(([at]) => at >= x) - 1))
10
+ const [a, ya] = knots[i], [b, yb] = knots[i + 1]
11
+ const t = Math.max(0, Math.min(1, (x - a) / (b - a)))
12
+ return ya + (yb - ya) * (1 - Math.cos(Math.PI * t)) / 2
13
+ }
14
+
15
+ // Author-supplied diagram coordinates. The nickel patch is a visual symbol for
16
+ // a catalyst surface, not a crystallographic facet. No force field is applied.
17
+ const nickel: Molecule3DData['atoms'] = [-1.8, -0.6, 0.6, 1.8].map((x, i) => ({ id: `ni${i}`, element: 'Ni', position: [x, 0, -1.6] }))
18
+ const attached: Molecule3DData['bonds'] = [
19
+ { from: 'c1', to: 'h1', order: 1 }, { from: 'c1', to: 'h2', order: 1 },
20
+ { from: 'c2', to: 'h3', order: 1 }, { from: 'c2', to: 'h4', order: 1 },
21
+ ]
22
+ export const reactants: Molecule3DData = {
23
+ atoms: [
24
+ { id: 'c1', element: 'C', position: [-0.7, 0, 0.5] },
25
+ { id: 'c2', element: 'C', position: [0.7, 0, 0.5] },
26
+ { id: 'h1', element: 'H', position: [-1.3, 0, 1.45] },
27
+ { id: 'h2', element: 'H', position: [-1.3, 0, -0.45] },
28
+ { id: 'h3', element: 'H', position: [1.3, 0, 1.45] },
29
+ { id: 'h4', element: 'H', position: [1.3, 0, -0.45] },
30
+ { id: 'h5', element: 'H', position: [-0.5, 0, 2.9] },
31
+ { id: 'h6', element: 'H', position: [0.5, 0, 2.9] },
32
+ ...nickel,
33
+ ],
34
+ bonds: [...attached, { from: 'c1', to: 'c2', order: 2 }, { from: 'h5', to: 'h6', order: 1 }],
35
+ }
36
+ export const products: Molecule3DData = {
37
+ atoms: [
38
+ { id: 'c1', element: 'C', position: [-0.77, 0, 0.5] },
39
+ { id: 'c2', element: 'C', position: [0.77, 0, 0.5] },
40
+ { id: 'h1', element: 'H', position: [-1.13, 0.94, 0.5] },
41
+ { id: 'h2', element: 'H', position: [-1.13, -0.47, -0.31] },
42
+ { id: 'h3', element: 'H', position: [1.13, 0.47, 1.31] },
43
+ { id: 'h4', element: 'H', position: [1.13, 0.47, -0.31] },
44
+ { id: 'h5', element: 'H', position: [-1.13, -0.47, 1.31] },
45
+ { id: 'h6', element: 'H', position: [1.13, -0.94, 0.5] },
46
+ ...nickel,
47
+ ],
48
+ bonds: [...attached, { from: 'c1', to: 'c2', order: 1 }, { from: 'c1', to: 'h5', order: 1 }, { from: 'c2', to: 'h6', order: 1 }],
49
+ }
@@ -0,0 +1,32 @@
1
+ // Linearized TT metric and local separation response, to FIRST ORDER in h:
2
+ // https://www.damtp.cam.ac.uk/user/tong/gr/grhtml/S5.html#S5.SS2
3
+ // Eqs. 5.235-5.238. Physical strain is small; only its drawn displacement is
4
+ // magnified. The display map is not an exact finite-strain spacetime metric.
5
+ export const strainAmplitude = 1e-3
6
+ export const displayGain = 600
7
+ export const wavelength = 4
8
+ export const speed = 1
9
+ export const period = wavelength / speed
10
+ export type Polarization = 'plus' | 'cross' | 'circular'
11
+
12
+ export function strain(z: number, time: number, polarization: Polarization): { plus: number; cross: number } {
13
+ const phase = 2 * Math.PI * (z - speed * time) / wavelength
14
+ return {
15
+ plus: polarization === 'cross' ? 0 : strainAmplitude * Math.cos(phase),
16
+ cross: polarization === 'plus' ? 0 : strainAmplitude * (polarization === 'cross' ? Math.cos(phase) : Math.sin(phase)),
17
+ }
18
+ }
19
+
20
+ export function ttMatrix(plus: number, cross: number): number[][] {
21
+ return [[plus, cross, 0], [cross, -plus, 0], [0, 0, 0]]
22
+ }
23
+
24
+ export function separation(x: number, y: number, plus: number, cross: number, gain = 1): [number, number] {
25
+ return [x + gain * (plus * x + cross * y) / 2,
26
+ y + gain * (cross * x - plus * y) / 2]
27
+ }
28
+
29
+ export function ringPoint(angle: number, z: number, time: number, polarization: Polarization, gain = displayGain): [number, number, number] {
30
+ const { plus, cross } = strain(z, time, polarization)
31
+ return [...separation(Math.cos(angle), Math.sin(angle), plus, cross, gain), z]
32
+ }
@@ -0,0 +1,54 @@
1
+ import { assertEqual } from 'vizmatic/stage'
2
+
3
+ // MIT 18.03, Poonen, §29: https://math.mit.edu/~poonen/03/notes.pdf
4
+ // Dimensionless u_tau = u_xx on [0, pi], with both ends held at zero.
5
+ // The finite sum is an exact solution for this chosen smooth initial profile.
6
+ export const MODES = [{ n: 1, a: 0.5 }, { n: 3, a: 0.3 }, { n: 5, a: 0.2 }] as const
7
+ export const remaining = (n: number, tau: number): number => Math.exp(-n * n * tau)
8
+ export const temperature = (x: number, tau: number): number =>
9
+ MODES.reduce((sum, { n, a }) => sum + a * remaining(n, tau) * Math.sin(n * x), 0)
10
+
11
+ export function modelTime(seconds: number): number {
12
+ if (seconds <= 8) return 0
13
+ if (seconds <= 20) return (seconds - 8) * 0.01
14
+ if (seconds <= 30) return 0.12 + (seconds - 20) * 0.048
15
+ return 0.6 + Math.min(10, seconds - 30) * 0.18
16
+ }
17
+
18
+ export function verifyHeatSolution(): void {
19
+ const near = (a: number, b: number, why: string, tolerance = 1e-9) =>
20
+ assertEqual(Math.abs(a - b) < tolerance, true, why)
21
+ const h = 1e-4
22
+ let previousMass = Infinity, previousNorm = Infinity
23
+ for (const tau of [0, 0.02, 0.06, 0.12, 0.6, 1, 2.4, 20]) {
24
+ near(temperature(0, tau), 0, 'Left endpoint stays at zero')
25
+ near(temperature(Math.PI, tau), 0, 'Right endpoint stays at zero')
26
+ for (let i = 1; i < 100; i++) {
27
+ const x = i * Math.PI / 100
28
+ const u = temperature(x, tau)
29
+ assertEqual(u >= -1e-12 && u <= 1, true, 'Temperature stays inside the fixed color domain')
30
+ const dt = (temperature(x, tau + h) - temperature(x, tau - h)) / (2 * h)
31
+ const dxx = (temperature(x + h, tau) - 2 * u + temperature(x - h, tau)) / (h * h)
32
+ near(dt, dxx, 'The displayed analytic profile obeys u_tau = u_xx', 1e-5)
33
+ if (tau === 0) {
34
+ // Positive initial profile: sin(x) [3.2(sin²x - 13/16)² + 23/80].
35
+ near(u, Math.sin(x) * (3.2 * (Math.sin(x) ** 2 - 13 / 16) ** 2 + 23 / 80), 'Chosen initial profile is nonnegative')
36
+ }
37
+ }
38
+ const mass = MODES.reduce((sum, { n, a }) => sum + 2 * a * remaining(n, tau) / n, 0)
39
+ const norm = Math.PI / 2 * MODES.reduce((sum, { n, a }) => sum + (a * remaining(n, tau)) ** 2, 0)
40
+ assertEqual(mass < previousMass, true, 'Heat leaves through the fixed-temperature ends')
41
+ assertEqual(norm < previousNorm, true, 'Squared L2 norm decreases')
42
+ previousMass = mass
43
+ previousNorm = norm
44
+ for (const { n } of MODES) {
45
+ near(Math.log(remaining(n, tau + 0.01) / remaining(n, tau)) / 0.01, -n * n, 'Log-amplitude decay rate is exactly -n²')
46
+ }
47
+ }
48
+ near(modelTime(8), 0, 'Initial profile is held for the first chapter')
49
+ near(modelTime(20), 0.12, 'First time segment reaches tau = 0.12')
50
+ near(modelTime(30), 0.6, 'Second time segment reaches tau = 0.6')
51
+ near(modelTime(40), 2.4, 'Final displayed model time is 2.4')
52
+ assertEqual(temperature(Math.PI / 3, 0.12) > temperature(Math.PI / 3, 0), true, 'The linked cool probe initially warms')
53
+ assertEqual(Math.abs(temperature(Math.PI / 3, 20)) < 1e-8, true, 'The solution approaches zero')
54
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Normalized real spatial eigenfunctions for nonrelativistic hydrogen, with
3
+ * a fixed proton, Z = 1 and coordinates in Bohr radii a0. Returned amplitudes
4
+ * have units a0^(-3/2), and their squares have units a0^(-3).
5
+ *
6
+ * UCSB PHYSCS36, Hydrogen Atom Wavefunctions (1s and 2pz):
7
+ * https://web.ece.ucsb.edu/~ilan/Classes/PHYSCS36_S2008/Hydrogen_Wavefunctions.htm
8
+ * Rosenthal, University of Delaware CHEM651, normalized real d orbitals:
9
+ * https://www1.udel.edu/chem/rosenthal/CHEM651/Fall%202012/Lectures/Lecture%201%20-%20Structure%20of%20the%20Atom_Slides.pdf
10
+ * The real x2-y2 orbital is the normalized sum of m = +2 and m = -2.
11
+ * Global time phase is omitted; stationary-state density does not change.
12
+ */
13
+ export const psi1s = (x: number, y: number, z: number): number => Math.exp(-Math.hypot(x, y, z)) / Math.sqrt(Math.PI)
14
+ export const psi2pz = (x: number, y: number, z: number): number => z * Math.exp(-Math.hypot(x, y, z) / 2) / (4 * Math.sqrt(2 * Math.PI))
15
+ export const psi3dx2y2 = (x: number, y: number, z: number): number => (x * x - y * y) * Math.exp(-Math.hypot(x, y, z) / 3) / (81 * Math.sqrt(2 * Math.PI))
16
+
17
+ export const orbitals = [
18
+ { id: '1s', psi: psi1s, n: 1, l: 0, extent: 3, unit: 150, peak: psi1s(0, 0, 0) ** 2, slice: 'xz', formula: '\\psi_{1s}=\\frac{e^{-r}}{\\sqrt{\\pi}}', nodes: 'No nodal plane' },
19
+ { id: '2pz', psi: psi2pz, n: 2, l: 1, extent: 9, unit: 28, peak: psi2pz(0, 0, 2) ** 2, slice: 'xz', formula: '\\psi_{2p_z}=\\frac{z e^{-r/2}}{4\\sqrt{2\\pi}}', nodes: 'One nodal plane: z = 0' },
20
+ { id: '3dx2-y2', psi: psi3dx2y2, n: 3, l: 2, extent: 22, unit: 14, peak: psi3dx2y2(6, 0, 0) ** 2, slice: 'xy', formula: '\\psi_{3d_{x^2-y^2}}=\\frac{(x^2-y^2)e^{-r/3}}{81\\sqrt{2\\pi}}', nodes: 'Two nodal planes: x = ±y' },
21
+ ] as const
22
+
23
+ /** Model coordinates of the moving section; this moves the view, not the state. */
24
+ export function sliceOffset(time: number, start: number, extent: number): number {
25
+ const phase = Math.max(0, Math.min(1, (time - start - 2) / 8))
26
+ return phase === 0 || phase === 1 ? 0 : extent * 0.35 * Math.sin(2 * Math.PI * phase)
27
+ }
28
+
29
+ export function density(orbital: typeof orbitals[number], x: number, y: number, z: number): number {
30
+ return orbital.psi(x, y, z) ** 2
31
+ }
@@ -0,0 +1,84 @@
1
+ import { assertEqual, type Vec3 } from 'vizmatic/stage'
2
+
3
+ // Tong, Electrodynamics, §§4.3.1–4.3.2 and 4.4:
4
+ // https://www.damtp.cam.ac.uk/user/tong/em/em3.pdf
5
+ // E is in units of E0, cB in the same units, and distance/time units give c = 1.
6
+ export const C = 1
7
+ export const K = 2 * Math.PI / 5
8
+ export const OMEGA = C * K
9
+ export const PERIOD = 2 * Math.PI / OMEGA
10
+
11
+ export function cross(a: Vec3, b: Vec3): Vec3 {
12
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
13
+ }
14
+
15
+ export function wave(x: number, t: number, ratio: number): { e: Vec3; cb: Vec3 } {
16
+ const phase = K * x - OMEGA * t
17
+ const e: Vec3 = [0, ratio * Math.sin(phase), Math.cos(phase)]
18
+ return { e, cb: cross([1, 0, 0], e) }
19
+ }
20
+
21
+ // Each shot is a distinct monochromatic solution, not a time-varying medium.
22
+ export function polarizationAt(time: number): number {
23
+ return time < 16 ? 0 : time < 25 ? 0.5 : 1
24
+ }
25
+
26
+ export function verifyPlaneWaves(): void {
27
+ const near = (a: number, b: number, why: string, tolerance = 1e-9) =>
28
+ assertEqual(Math.abs(a - b) < tolerance, true, why)
29
+ const h = 1e-4
30
+ const derivative = (a: Vec3, b: Vec3): Vec3 => [
31
+ (a[0] - b[0]) / (2 * h), (a[1] - b[1]) / (2 * h), (a[2] - b[2]) / (2 * h),
32
+ ]
33
+ const curlAlongX = (d: Vec3): Vec3 => [0, -d[2], d[1]]
34
+
35
+ near(OMEGA, C * K, 'Vacuum dispersion: omega = ck')
36
+ for (const ratio of [0, 0.5, 1]) {
37
+ let meanFlux = 0
38
+ for (let i = 0; i < 64; i++) {
39
+ const t = i * PERIOD / 64
40
+ const x = 0.37
41
+ const { e, cb } = wave(x, t, ratio)
42
+ const flow = cross(e, cb)
43
+ const e2 = e.reduce((sum, v) => sum + v * v, 0)
44
+ near(e[0], 0, 'E is transverse and divergence-free')
45
+ near(cb[0], 0, 'B is transverse and divergence-free')
46
+ near(e.reduce((sum, v, j) => sum + v * cb[j], 0), 0, 'E and B are orthogonal')
47
+ near(Math.hypot(...e), Math.hypot(...cb), '|E| = |cB|')
48
+ near(flow[0], e2, 'E cross cB = |E| squared along +x')
49
+ near(flow[1], 0, 'No transverse energy flow along y')
50
+ near(flow[2], 0, 'No transverse energy flow along z')
51
+ assertEqual(flow[0] >= 0, true, 'Energy never flows backward')
52
+ const shifted = wave(x + C * 0.23, t + 0.23, ratio)
53
+ for (let j = 0; j < 3; j++) {
54
+ near(shifted.e[j], e[j], 'E travels at +c')
55
+ near(shifted.cb[j], cb[j], 'cB travels at the same +c')
56
+ }
57
+
58
+ // Independent centered differences check both curl equations, including signs.
59
+ const xp = wave(x + h, t, ratio), xm = wave(x - h, t, ratio)
60
+ const tp = wave(x, t + h, ratio), tm = wave(x, t - h, ratio)
61
+ const curlE = curlAlongX(derivative(xp.e, xm.e))
62
+ const curlB = curlAlongX(derivative(xp.cb, xm.cb))
63
+ const dtE = derivative(tp.e, tm.e), dtB = derivative(tp.cb, tm.cb)
64
+ for (let j = 0; j < 3; j++) {
65
+ near(curlE[j], -dtB[j], 'Faraday: curl E = -dt B, c = 1', 1e-8)
66
+ near(curlB[j], dtE[j], 'Ampere-Maxwell: curl B = dt E, c = 1', 1e-8)
67
+ }
68
+ if (ratio === 0) near(e[1], 0, 'Linear polarization stays on one axis')
69
+ else near(e[1] ** 2 / ratio ** 2 + e[2] ** 2, 1, 'Observer tip lies on the displayed ellipse')
70
+ if (ratio === 1) near(e2, 1, 'Circular polarization has constant magnitude and flux')
71
+ meanFlux += flow[0] / 64
72
+ }
73
+ near(meanFlux, (1 + ratio ** 2) / 2, 'Cycle-average flux follows the squared component amplitudes')
74
+ const zeroPhaseTime = 0
75
+ const now = wave(0, zeroPhaseTime, ratio)
76
+ const quarter = wave(0, zeroPhaseTime + PERIOD / 4, ratio)
77
+ near(now.e[2], 1, 'Observer starts at +z when phase is zero')
78
+ near(quarter.e[1], -ratio, 'Quarter-cycle later, the tip rotates toward -y')
79
+ near(quarter.e[2], 0, 'Components are in quadrature')
80
+ }
81
+ near(polarizationAt(15.99), 0, 'Linear chapter uses the linear solution')
82
+ near(polarizationAt(16), 0.5, 'Elliptical chapter uses the 2:1 solution')
83
+ near(polarizationAt(25), 1, 'Circular chapter uses equal amplitudes')
84
+ }