vizmatic 0.3.2 → 0.5.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 (150) hide show
  1. package/PROMPT.md +75 -525
  2. package/README.md +87 -578
  3. package/ROADMAP.md +49 -67
  4. package/SCIENCE.md +250 -0
  5. package/assets/THIRD_PARTY_LICENSES.md +40 -1
  6. package/assets/fonts/InstrumentSerif-Italic.ttf +0 -0
  7. package/assets/fonts/InstrumentSerif-Regular.ttf +0 -0
  8. package/assets/licenses/raster-codecs-MIT.txt +74 -0
  9. package/dist/chunk-3F2VQ7NW.js +1 -0
  10. package/dist/chunk-4XE64I2U.js +755 -0
  11. package/dist/chunk-JHHPLALU.js +79 -0
  12. package/dist/chunk-LTX44BAE.js +112 -0
  13. package/dist/chunk-MLKGABMK.js +9 -0
  14. package/dist/chunk-PSBF4TEK.js +1 -0
  15. package/dist/chunk-RPAHMKAR.js +605 -0
  16. package/dist/chunk-RWF4VBUL.js +3617 -0
  17. package/dist/chunk-WHT6HRMX.js +4201 -0
  18. package/dist/cli.js +371 -10
  19. package/dist/index.cjs +11129 -2922
  20. package/dist/index.d.cts +1225 -369
  21. package/dist/index.d.ts +1225 -369
  22. package/dist/index.js +6220 -3015
  23. package/dist/math-LXB4FH4E.js +7 -0
  24. package/dist/math-QVCETQDQ.js +1 -0
  25. package/dist/scene-browser-assets.d.ts +38 -0
  26. package/dist/scene-browser-assets.js +53 -0
  27. package/dist/scene-browser-chunks/chunk-5MVLYGXM.js +70 -0
  28. package/dist/scene-browser-chunks/chunk-ASXKN3NU.js +1 -0
  29. package/dist/scene-browser-chunks/chunk-CM5Y5LZP.js +1 -0
  30. package/dist/scene-browser-chunks/chunk-DP7NB4EW.js +6 -0
  31. package/dist/scene-browser-chunks/emscripten-module.browser-M5AEKJGE.js +1 -0
  32. package/dist/scene-browser-chunks/ffi-FL6ORJU3.js +1 -0
  33. package/dist/scene-browser-chunks/module-ES6BEMUI-JD5S5VKR.js +1 -0
  34. package/dist/scene-browser-chunks/module-asyncify-2EFITU5U-HWPFJFJC.js +1 -0
  35. package/dist/scene-browser-chunks/scene-browser-layout-M3XSXMV4.js +27 -0
  36. package/dist/scene-browser.d.ts +117 -0
  37. package/dist/scene-browser.js +220 -0
  38. package/dist/scene-cli.d.ts +1 -0
  39. package/dist/scene-cli.js +4 -0
  40. package/dist/scene-runtime.cjs +995 -0
  41. package/dist/scene-runtime.d.cts +81 -0
  42. package/dist/scene-runtime.d.ts +81 -0
  43. package/dist/scene-runtime.js +22 -0
  44. package/dist/server-2FYHZ4UO.js +331 -0
  45. package/dist/stage-browser/browser.d.ts +2482 -0
  46. package/dist/stage-browser/chunk-SQE76S5B.js +1 -0
  47. package/dist/stage-browser/chunk-VZNL6JY2.js +59 -0
  48. package/dist/stage-browser/dagre.esm-N2NIVIAZ.js +6 -0
  49. package/dist/stage-browser/math-4WFNHVV2.js +18 -0
  50. package/dist/stage-browser/stage.js +19 -0
  51. package/dist/stage-export.cjs +4950 -0
  52. package/dist/stage-export.d.cts +112 -0
  53. package/dist/stage-export.d.ts +112 -0
  54. package/dist/stage-export.js +544 -0
  55. package/dist/stage.cjs +9745 -0
  56. package/dist/stage.d.cts +1678 -0
  57. package/dist/stage.d.ts +1678 -0
  58. package/dist/stage.js +5404 -0
  59. package/dist/svg-import-Djj2q7Pc.d.cts +742 -0
  60. package/dist/svg-import-Djj2q7Pc.d.ts +742 -0
  61. package/dist/video-CcHW1qhV.d.cts +532 -0
  62. package/dist/video-CcHW1qhV.d.ts +532 -0
  63. package/examples/README.md +18 -0
  64. package/examples/agent-pipeline.tsx +4 -4
  65. package/examples/animated-pipeline.tsx +1 -5
  66. package/examples/attention-head.tsx +12 -12
  67. package/examples/aurora-incident.tsx +4 -3
  68. package/examples/building-blocks.tsx +8 -9
  69. package/examples/catalog-charts.tsx +4 -4
  70. package/examples/catalog-content.tsx +7 -9
  71. package/examples/catalog-convolution-kernel.tsx +116 -0
  72. package/examples/catalog-data.tsx +2 -8
  73. package/examples/catalog-dataflow.tsx +5 -9
  74. package/examples/catalog-dense.tsx +80 -0
  75. package/examples/catalog-deployment.tsx +5 -11
  76. package/examples/catalog-diagrams.tsx +13 -16
  77. package/examples/catalog-drawing.tsx +7 -7
  78. package/examples/catalog-flows.tsx +4 -4
  79. package/examples/catalog-foundations.tsx +11 -11
  80. package/examples/catalog-gaussian-blur.tsx +146 -0
  81. package/examples/catalog-image-tensors.tsx +115 -0
  82. package/examples/catalog-ml.tsx +36 -31
  83. package/examples/catalog-numeric-matrices.tsx +93 -0
  84. package/examples/catalog-photo-blur.tsx +209 -0
  85. package/examples/catalog-science-ai.tsx +130 -0
  86. package/examples/catalog-science-chemistry.tsx +103 -0
  87. package/examples/catalog-science-math.tsx +93 -0
  88. package/examples/catalog-science-physics.tsx +84 -0
  89. package/examples/catalog-sequence.tsx +59 -38
  90. package/examples/data-pipeline-lineage-presentation.tsx +5 -0
  91. package/examples/data-pipeline-lineage.tsx +85 -0
  92. package/examples/daybreak-launch.tsx +1 -0
  93. package/examples/desired-quadrant.tsx +7 -8
  94. package/examples/engineering-dashboard-presentation.tsx +13 -0
  95. package/examples/engineering-dashboard.tsx +160 -0
  96. package/examples/engineering-flow.tsx +2 -4
  97. package/examples/eval-dashboard.tsx +6 -6
  98. package/examples/films/attention.ts +278 -0
  99. package/examples/films/cache-miss.ts +431 -0
  100. package/examples/films/catalog.json +132 -0
  101. package/examples/films/central-limit.ts +269 -0
  102. package/examples/films/complex-maps.ts +273 -0
  103. package/examples/films/deck-example.ts +224 -0
  104. package/examples/films/euler-circle.ts +179 -0
  105. package/examples/films/fourier-epicycles.ts +265 -0
  106. package/examples/films/gradient-descent.ts +345 -0
  107. package/examples/films/linear-maps.ts +175 -0
  108. package/examples/films/lorenz.ts +207 -0
  109. package/examples/films/pythagoras.ts +185 -0
  110. package/examples/films/taylor-series.ts +159 -0
  111. package/examples/films/vizmatic-title.ts +117 -0
  112. package/examples/llm-serving-stack-presentation.tsx +5 -0
  113. package/examples/llm-serving-stack.tsx +94 -0
  114. package/examples/model-garden.tsx +1 -0
  115. package/examples/model-router.tsx +6 -6
  116. package/examples/nccl-all-gather.tsx +3 -3
  117. package/examples/nccl-all-reduce.tsx +3 -3
  118. package/examples/nccl-all-to-all.tsx +1 -1
  119. package/examples/nccl-broadcast.tsx +1 -1
  120. package/examples/nccl-reduce-scatter.tsx +5 -5
  121. package/examples/orthogonal-routing.tsx +4 -4
  122. package/examples/pareto-frontier.tsx +9 -10
  123. package/examples/presentation-frame.tsx +6 -6
  124. package/examples/pressure-mechanism.scene.json +14 -0
  125. package/examples/production-system-map-presentation.tsx +5 -0
  126. package/examples/production-system-map.tsx +130 -0
  127. package/examples/rag-graph.tsx +7 -7
  128. package/examples/release-card.tsx +5 -5
  129. package/examples/spec-anatomy.tsx +5 -5
  130. package/examples/system-architecture.tsx +19 -32
  131. package/examples/theme-system.tsx +1 -1
  132. package/examples/token-matrix.tsx +4 -2
  133. package/examples/transparent-badge.tsx +1 -2
  134. package/examples/videos/README.md +62 -0
  135. package/examples/videos/calculus-tangent.tsx +101 -0
  136. package/examples/videos/catalyst-pathway.tsx +56 -0
  137. package/examples/videos/causal-attention.tsx +91 -0
  138. package/examples/videos/convolution-kernel.tsx +34 -0
  139. package/examples/videos/gaussian-blur.tsx +32 -0
  140. package/examples/videos/image-to-matrix.tsx +22 -0
  141. package/examples/videos/matrix-multiplication.tsx +128 -0
  142. package/examples/videos/photo-gaussian-blur.tsx +39 -0
  143. package/examples/videos/request-lifecycle.tsx +99 -0
  144. package/examples/videos/signal-to-story.tsx +126 -0
  145. package/examples/videos/wave-interference.tsx +80 -0
  146. package/examples/vizmatic-bare.d.ts +1 -0
  147. package/examples/vizmatic-hero.tsx +9 -18
  148. package/examples/website-workflow.tsx +7 -7
  149. package/examples/weekend-field-notes.tsx +3 -2
  150. package/package.json +77 -12
package/ROADMAP.md CHANGED
@@ -1,76 +1,58 @@
1
- # Technical diagram roadmap
1
+ # Roadmap
2
2
 
3
- Vizmatic aims to make polished technical diagrams easy from TSX while keeping rendering deterministic, offline-capable, theme-aware, and composable with charts or presentation frames.
4
-
5
- Benchmarks: [Diagrams](https://diagrams.mingrammer.com/), [D2](https://d2lang.com/), [Structurizr](https://docs.structurizr.com/), [Mermaid](https://mermaid.js.org/), and [PlantUML](https://plantuml.com/).
3
+ This page states what Vizmatic can do now and what comes next. Vizmatic aims to make technical ideas easy to explain from code: motion that teaches, and figures that hold real information. Rendering stays deterministic, offline, and theme-aware.
6
4
 
7
5
  ## Available now
8
6
 
9
- - Deterministic Dagre layout in four directions.
10
- - Nested system boundaries through `GraphDiagram.groups`.
11
- - Built-in generic icons for users, clients, services, infrastructure, data, networks, and operations.
12
- - Reusable custom icon definitions and typed icon registries.
13
- - Labeled synchronous, asynchronous, event, data, dependency, and association relationships.
14
- - Solid, dashed, and dotted connectors with forward, backward, bidirectional, or no arrows.
15
- - Named ports and endpoint sides, with straight or obstacle-aware orthogonal routing and separated parallel connectors.
16
- - Manual positioning for ungrouped editorial diagrams.
17
- - Connector diagnostics for crossings, label collisions, crowded endpoints, and parallel routes.
18
- - Typed in-process visual checks with stable diagnostic codes, element locations where available, and configurable failure policy.
19
- - Dark, light, and Engineering visual presets with PNG, SVG, and GIF output.
20
- - Accessible SVG titles, descriptions, stable element IDs, and optional links for graph diagrams and their typed graph views.
21
- - Conservative Mermaid flowchart and D2 text import with explicit diagnostics for unsupported or lossy syntax.
22
- - Typed state timelines with holds, eased tweens, keyframes, parallel tracks, deterministic sampling, and streamed GIF encoding.
23
- - Sequence diagrams with participants, lifelines, activations, sync/async/return messages, notes, and `alt`, `loop`, or `parallel` fragments.
24
- - Typed batch/stream dataflow and lineage views with schema metadata.
25
- - Deployment and network views with nested boundaries, ports, protocols, and trust direction.
26
- - Transformer topology views with tensor shapes, repeated blocks, residual/cache/expert routes, and collectives.
27
- - Cadence-boundary animation sampling, per-frame overflow detection, and opaque delta-frame GIF encoding.
28
- - Compressed offline Twemoji bundle instead of thousands of package entries.
29
- - Positioned browser builder with editable text and chart data, drag/resize, undo/redo, local drafts, and portable project files.
30
- - Pie, donut, bar, line, scatter, classic Pareto bar, Pareto frontier, quadrant, and interval charts.
31
-
32
- ## Next capability batches
33
-
34
- Specialized APIs remain declarative and reusable. Examples contain complete scenario code, while scenario-specific NCCL or model helpers stay outside core presets.
35
-
36
- ### Architecture model and views
37
-
38
- - C4 person, software system, container, component, and deployment semantics.
39
- - One reusable model with context, container, component, deployment, and dynamic views.
40
- - Named views, filtered views, legends, tags, and technology metadata.
41
- - Drill-down links and stable element identifiers in SVG output.
42
-
43
- ### Technical icon packs
44
-
45
- - Build-time generated GCP and Kubernetes packs from pinned Apache-2.0 Iconify data.
46
- - Optional provider modules so unused icons do not increase core bundle size.
47
- - Asset metadata with source, version, license, and trademark notice.
48
- - User-supplied AWS and Azure adapters until redistribution terms support bundled packs.
49
- - No default runtime icon API or network dependency.
50
-
51
- ### Interaction and software design
52
-
53
- - UML class and component diagrams with compartments, inheritance, aggregation, composition, multiplicity, and stereotypes.
54
- - State machines with nested states, guards, entry/exit actions, and parallel regions.
55
- - ER diagrams with tables, fields, keys, data types, and cardinality-aware relationships.
56
-
57
- ### Infrastructure and data systems
58
-
59
- - Swimlanes and activity diagrams for ownership, handoffs, conditions, and parallel work.
60
-
61
- ### Layout and rendering
62
-
63
- - Curved and user-routed connectors with editable waypoints.
64
- - Layout adapter interface with Dagre as default and ELK as optional backend.
65
- - Per-boundary direction, collapsed groups, named scenarios, and reusable animation compositions.
66
- - Extend structured SVG accessibility beyond graph diagrams to charts and other visual primitives.
67
- - Expand Mermaid and D2 interoperability, and add Structurizr, Kubernetes, and Terraform adapters where semantics map safely.
7
+ ### Films
8
+
9
+ - A vector animation engine in `vizmatic/stage`. Every object is Bezier geometry, so any shape can trace itself, morph, or bend through a function.
10
+ - A timeline that is a pure function of time. Any frame can be sampled in any order, so scrubbing is instant and output is reproducible.
11
+ - TeX glyphs for equations, with `morphMatching` to carry shared terms between lines.
12
+ - Objects for math, charts, computer science, and systems, plus 3D scenes with surfaces, curves, and an orbiting camera.
13
+ - Five looks, gradient strokes, glow, and bloom.
14
+ - `<vz-film>`, a live, seekable player for any page, with chapters and a stepped presentation mode.
15
+ - `fromSvg` and `fromComponent`, which turn any SVG or TSX figure into shapes that films can animate.
16
+ - Export to MP4 and WebM with BT.709 color, GIF with a shared palette, PNG, and SVG. Frames rasterize on worker threads with a memory limit, with optional motion blur.
17
+ - `vizmatic new`, `preview`, `check`, `film`, `looks`, and `objects`. Preview reloads on save and keeps the playhead.
18
+ - `vizmatic check` for films: off-canvas marks, overlapping text, and strokes through text, with times and bounding boxes as JSON.
19
+ - The Studio, which builds and exports a film in the browser.
20
+
21
+ ### Figures
22
+
23
+ - Typed primitives for system, sequence, dataflow, deployment, and transformer diagrams, with charts, tables, and scientific components.
24
+ - A density system: `dense` by default, with `compact`, `comfortable`, `presentation`, or a numeric scale from one source.
25
+ - Deterministic Dagre layout with nested boundaries, named ports, and obstacle-aware orthogonal routing.
26
+ - Dark, light, and Engineering presets with PNG, SVG, and GIF output.
27
+ - Accessible SVG titles, descriptions, stable element IDs, and links for graph diagrams.
28
+ - Typed checks with stable diagnostic codes for overflow, contrast, small text, overlaps, and connector congestion.
29
+ - Conservative Mermaid and D2 text import with explicit diagnostics for lossy syntax.
30
+ - A positioned browser builder with editable text and data, undo and redo, and portable project files.
31
+ - An isolated runtime for editable scenes from users or agents, with resource limits, in Node and in browsers.
32
+
33
+ ## Next
34
+
35
+ ### Films
36
+
37
+ - Burned-in captions and audio-synchronized timing from a narration script. Today captions export as a VTT sidecar.
38
+ - ProRes and 4:4:4 masters for video editors. MP4 and WebM use 4:2:0 today for browser compatibility.
39
+ - Frame caching for faster incremental renders.
40
+ - Parity tests between the canvas and SVG backends, which today share one display list but use separate painters.
41
+
42
+ ### Figures
43
+
44
+ - C4 semantics: one reusable model with context, container, component, deployment, and dynamic views.
45
+ - UML class and component diagrams, state machines with nested states, and ER diagrams with keys and cardinality.
46
+ - Swimlanes and activity diagrams.
47
+ - A layout adapter interface with Dagre as the default and ELK as an option. Per-boundary direction and collapsed groups.
48
+ - Build-time icon packs for GCP and Kubernetes from pinned Apache-2.0 data, as optional modules. User-supplied AWS and Azure adapters until redistribution terms support bundled packs.
49
+ - Structured accessibility for charts and other primitives, as graph diagrams have today.
50
+ - Wider Mermaid and D2 import, and Structurizr, Kubernetes, and Terraform adapters where semantics map safely.
68
51
 
69
52
  ## Design constraints
70
53
 
71
- - Keep current `GraphDiagram` input backward compatible.
72
- - Compile specialized diagram APIs into shared typed models instead of separate rendering stacks.
54
+ - Keep public APIs backward compatible, or document the break in the release notes.
73
55
  - Keep default rendering deterministic and offline.
74
56
  - Treat provider licensing and trademarks as product requirements.
75
- - Add tests for behavior contracts and regressions, not source-text presence.
76
- - Ship each capability with dark/light reference renders, docs, and diagnostics.
57
+ - Add tests for behavior contracts and regressions, not for source-text presence.
58
+ - Ship each capability with dark and light reference renders, docs, and diagnostics.
package/SCIENCE.md ADDED
@@ -0,0 +1,250 @@
1
+ # Scientific videos and diagrams
2
+
3
+ Vizmatic combines mathematical typesetting, coordinate plots, diagrams, and
4
+ deterministic animation. Scientific components use the same public API and scene
5
+ registry in native rendering and the in-browser editor. They require no network
6
+ requests or scientific drawing service.
7
+
8
+ ## Choose a foundation
9
+
10
+ | Subject | Components and helpers | Worked examples |
11
+ |---|---|---|
12
+ | Mathematics | `NumberLine`, `GeometryDiagram`, `AxisPlot`, `MathText`, `EquationCard`, matrices, function sampling | [Intervals and geometry](examples/catalog-science-math.tsx), [secant to tangent](examples/videos/calculus-tangent.tsx) |
13
+ | Physics | `FreeBodyDiagram`, `WaveDiagram`, vectors, coordinate paths, `sumForces`, `waveValue`, `sampleWave` | [Forces and interference](examples/catalog-science-physics.tsx), [wave superposition](examples/videos/wave-interference.tsx) |
14
+ | Chemistry | `MoleculeDiagram`, `ReactionEquation`, `ReactionEnergyDiagram`, `reactionBalance` | [Structures, conservation, and energy](examples/catalog-science-chemistry.tsx), [catalyst pathways](examples/videos/catalyst-pathway.tsx) |
15
+ | Artificial intelligence | `AttentionMatrix`, `scaledDotProductAttention`, `TransformerTopology`, `LayeredNetwork`, convolution kernels, `Heatmap`, `Matrix`, tensor shapes and collectives | [Causal probabilities](examples/catalog-science-ai.tsx), [convolution filter](examples/catalog-convolution-kernel.tsx), [computed attention](examples/videos/causal-attention.tsx) |
16
+
17
+ The component explorer includes runnable snippets and typed props for every
18
+ component. The four subject examples render in dark and light themes. Video
19
+ sources export a static `create(theme)` and a deterministic
20
+ `createAnimation(theme)` timeline, so the same numerical state can drive an
21
+ equation, diagram, and explanation.
22
+
23
+ ## Make the mechanism visible
24
+
25
+ For numerical linear algebra, start with
26
+ [numeric matrices](examples/catalog-numeric-matrices.tsx) and the
27
+ [animated dot product](examples/videos/matrix-multiplication.tsx). `Matrix` and
28
+ `Heatmap` support readable `fontSize`, row/column/cell highlights, and an explicit
29
+ `colorDomain` that changes the color scale without changing the displayed
30
+ numbers. `multiplyMatrices` computes the result; `transposeMatrix` exchanges
31
+ rows and columns without mutating the input.
32
+
33
+ For computer vision, use [the actual CIFAR-10 sample](examples/catalog-image-tensors.tsx)
34
+ and its [image-to-matrix animation](examples/videos/image-to-matrix.tsx).
35
+ `PixelGrid` displays row-major RGB byte tuples as square pixels. `rgbChannel`
36
+ extracts one 0–255 matrix, `cropRgbImage` copies a rectangular region, and
37
+ `flattenRgbImage(pixels, 'CHW')` reproduces channel-first storage. Use `'HWC'`
38
+ for interleaved storage and the third argument `true` to divide by 255.
39
+ The helpers reject invalid bytes and support up to 1,024 pixels. A 32×32 color
40
+ image contains three 32×32 matrices, or 3,072 values; a single scalar matrix
41
+ does not preserve its RGB colors.
42
+
43
+ For deep-learning filters, see the [single-channel kernel example](examples/catalog-convolution-kernel.tsx)
44
+ and its [animated lesson](examples/videos/convolution-kernel.tsx). It uses a
45
+ synthetic image and one hand-set edge filter to show each multiply and sum,
46
+ then applies ReLU. The weights are illustrative, not learned. `crossCorrelate2d`
47
+ implements the unflipped cross-correlation convention used by deep-learning
48
+ `Conv2d` layers; it handles one 2D input and one 2D kernel, with no channel
49
+ stacking, bias, or learned parameters. The default stride is 1 and
50
+ `padding: 'valid'` emits only fully covered windows. `padding: 'same'` uses
51
+ SAME_UPPER zero padding, returns `ceil(input / stride)` output dimensions, and
52
+ places any odd extra padding at the bottom or right. Padding a blur with zeros
53
+ can dim the image edges; a constant image stays constant only where the full
54
+ kernel fits. This helper supports strides greater than 1 with `same`; PyTorch
55
+ `Conv2d` currently limits `padding='same'` to stride 1.
56
+
57
+ For smoothing, the [Gaussian blur example](examples/catalog-gaussian-blur.tsx)
58
+ and [animation](examples/videos/gaussian-blur.tsx) follow a normalized kernel
59
+ through a bright point and its neighbors. `gaussianKernel(size, sigma)` samples
60
+ and normalizes a finite, odd-sized 2D Gaussian kernel. The displayed 3×3
61
+ `[[1,2,1],[2,4,2],[1,2,1]] / 16` kernel is a separable binomial approximation
62
+ to a Gaussian, not the exact sampled kernel. `crossCorrelate2d` preserves
63
+ floating-point results.
64
+
65
+ For an actual photo, the [photo blur example](examples/catalog-photo-blur.tsx)
66
+ and [animation](examples/videos/photo-gaussian-blur.tsx) use a sharp 384 × 256
67
+ CC0 coffee photograph. They compute nine outputs at σ = 0, 0.5, …, 4 using a
68
+ 25 × 25 Gaussian footprint; σ = 0 is the unchanged identity crop. The source
69
+ crop and each valid-convolution output share a 360 × 232 field of view. Each
70
+ animation stage displays its computed result. The numerical matrix shows the
71
+ center 5 × 5 weights, rounded to six decimals, with the center coefficient
72
+ highlighted. The sum readout covers all 625 weights, including the 600 omitted
73
+ from the excerpt. The separable implementation
74
+ returns floating-point RGB values; the lesson rounds them only for the byte
75
+ readout and PNG encoding. Blur uses stored, gamma-encoded channel values and
76
+ does not linearize RGB before filtering.
77
+
78
+ The full SDK exposes `RgbRaster`, `decodeRgbPng`, `encodeRgbPng`,
79
+ `cropRgbRaster`, and `gaussianBlurRgb` to imported scene modules and the full
80
+ browser Playground. A raster is a flat, row-major RGB buffer. PNG decoding
81
+ accepts opaque, noninterlaced 8-bit images up to 2 MiB and 1,048,576 pixels; it
82
+ rejects embedded ICC profiles. Raster operations also cap dimensions at
83
+ 1,048,576 pixels. Gaussian blur uses valid convolution, returns a `Float64Array`,
84
+ accepts σ ≥ 0 and integer radius 0–64, and defaults the radius to `ceil(3σ)`.
85
+ An explicit radius at σ = 0 keeps the matching valid crop while leaving its
86
+ pixels unchanged. These helpers are not part of the bare QuickJS author-code
87
+ environment. The helpers are in this source checkout; consumers need a
88
+ Vizmatic release that includes them.
89
+
90
+ See [PyTorch Conv2d](https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv2d.html)
91
+ for learned spatial filters and [OpenCV image filtering](https://docs.opencv.org/4.x/d4/d86/group__imgproc__filter.html)
92
+ for Gaussian blur and border handling.
93
+
94
+ The CIFAR image-to-matrix example embeds training batch 1, record 0 (frog), so
95
+ preview and rendering need no runtime downloads. It shows the full image and
96
+ three full channel planes, then enlarges the same 4×4 crop into numerical
97
+ matrices. Moving values land in the corresponding row and column. Regenerate
98
+ the pinned record in `examples/catalog-image-tensors.tsx` with
99
+ `node scripts/extract-cifar-sample.mjs`; the photo lesson has its own prepared
100
+ sample from `node scripts/prepare-photo-sample.mjs`. Provenance and third-party
101
+ notices are in `assets/THIRD_PARTY_LICENSES.md`.
102
+
103
+ Start with the objects the lesson explains. Keep the coordinate system and color
104
+ meaning stable while the relevant quantity changes. A force diagram keeps one
105
+ scale for every vector; an interference diagram adds signed displacements; an
106
+ attention diagram displays the probabilities that actually produce its output.
107
+
108
+ Sample frames from explicit time or timeline state. Avoid accumulated updates
109
+ such as `position += velocity`, which make seeking depend on previously rendered
110
+ frames. Label units and numerical examples. Keep generated or illustrative data
111
+ distinct from measurements.
112
+
113
+ The worked lessons use these contracts:
114
+
115
+ - **Derivative:** for `f(x) = x²` at `x = 1`, the secant slope is `2 + h`,
116
+ approaching the tangent slope `2` as a nonzero `h` shrinks.
117
+ - **Interference:** two equal sinusoidal waves add to amplitude `2A` in phase
118
+ and cancel at a relative phase of `π`. The displayed domain stays fixed.
119
+ - **Catalysis:** both pathways share reactant and product energy levels. The
120
+ numerical energy profile is illustrative; a catalyst provides a different
121
+ activation barrier without changing the energy difference between endpoints.
122
+ - **Attention:** the example computes `softmax(QKᵀ / √dₖ)V` from explicit small
123
+ tensors. Causal masking removes future keys, each visible row sums to one,
124
+ and the weighted output uses that same row.
125
+
126
+ ## Chemistry data contracts
127
+
128
+ `MoleculeDiagram` renders supplied 2D atom positions and bond orders. It checks
129
+ elements, identifiers, endpoints, and finite geometry. Supply the molecular
130
+ structure deliberately: the renderer does not infer bonds, valence, a 3D
131
+ conformation, stereochemistry, or chemical validity from a formula.
132
+
133
+ `ReactionEquation` displays supplied formulas, coefficients, and phase labels.
134
+ For conservation checks, supply an explicit `composition` map and optional
135
+ integer `charge` for each term. `reactionBalance` compares coefficient-weighted
136
+ element counts and charge. Missing composition means balance is unavailable;
137
+ the rendered formula is not parsed or automatically balanced.
138
+
139
+ `ReactionEnergyDiagram` accepts absolute energy levels in one explicitly named
140
+ unit. The barrier is the peak energy, not activation energy itself. Activation
141
+ energy is `barrier - reactants`; the endpoint change is `products - reactants`.
142
+ Its horizontal axis is reaction coordinate, not elapsed time. It does not
143
+ estimate a reaction rate or convert units.
144
+
145
+ ## Attention data contracts
146
+
147
+ `scaledDotProductAttention(queries, keys, values, options)` computes one head
148
+ without dropout or learned projections. `mask[i][j] = true` permits a query/key
149
+ pair. With `causal: true`, key index `j` must also satisfy `j <= i`, using
150
+ top-left alignment for rectangular matrices. Fully masked rows are rejected;
151
+ their softmax is undefined by this API. Masked scores are returned as `null`,
152
+ weights as zero, and outputs as finite numbers.
153
+
154
+ `AttentionMatrix` accepts normalized probabilities, explicit query/key labels,
155
+ and the same optional mask. Its shared color scale is zero to one. Attention
156
+ weights are a computation view, not an explanation of a model's reasoning.
157
+
158
+ ## Render and reuse
159
+
160
+ Run from a checkout containing the scientific components:
161
+
162
+ ```sh
163
+ pnpm build
164
+ pnpm exec tsx scripts/render-examples.ts --only=catalog-science-math,catalog-science-physics,catalog-science-chemistry,catalog-science-ai
165
+ node dist/cli.js render examples/catalog-science-chemistry.tsx --theme dark,light --out /tmp/science
166
+ node dist/cli.js gif examples/videos/wave-interference.tsx --theme dark,light --fps 20 --out /tmp/science
167
+ node dist/cli.js video examples/videos/causal-attention.tsx --theme dark --fps 30 --out /tmp/science
168
+ ```
169
+
170
+ The scoped gallery command retains existing assets and refreshes all source
171
+ metadata. It requires the other examples to have been rendered already. The
172
+ default `pnpm render:examples` still rebuilds the complete gallery.
173
+
174
+ MP4 output requires FFmpeg with `libx264`. Captions and narration can be added
175
+ through the existing video APIs. The examples are visual lesson segments, not
176
+ narrated or publication-approved full videos.
177
+
178
+ Bare scenes in the editor use the same component names without imports:
179
+
180
+ ```tsx
181
+ <WaveDiagram
182
+ waves={[
183
+ { amplitude: 1, wavelength: 4, phase: 0 },
184
+ { amplitude: 1, wavelength: 4, phase: progress * Math.PI },
185
+ ]}
186
+ time={time}
187
+ xMin={-4} xMax={4} yMin={-2.5} yMax={2.5}
188
+ width={760} height={420}
189
+ showComponents showSum
190
+ />
191
+ ```
192
+
193
+ The editor validates bounded collection sizes before rendering. Scientific
194
+ components also reject invalid dimensions, nonfinite values, missing endpoints,
195
+ and data that would silently distort their stated numerical contract.
196
+
197
+ ## Scientific references
198
+
199
+ - [OpenStax Calculus Volume 1: Defining the Derivative](https://openstax.org/books/calculus-volume-1/pages/3-1-defining-the-derivative)
200
+ - [OpenStax University Physics Volume 1: Interference of Waves](https://openstax.org/books/university-physics-volume-1/pages/16-5-interference-of-waves)
201
+ - [OpenStax Chemistry 2e: Catalysis](https://openstax.org/books/chemistry-2e/pages/12-7-catalysis)
202
+ - [Vaswani et al.: Attention Is All You Need](https://arxiv.org/abs/1706.03762)
203
+
204
+ ## Lesson sources
205
+
206
+ Use this guide for mathematical plots and geometry,
207
+ force and wave diagrams, molecular structures, reaction equations and energy
208
+ profiles, and computed attention. Eight subject components complement the
209
+ existing equations, matrices, graphs, and transformer tools. Each is available
210
+ in the component explorer and the isolated browser scene renderer.
211
+
212
+ The [animated lesson sources](examples/videos/README.md) demonstrate a
213
+ secant approaching a tangent, signed wave superposition, catalyst pathways,
214
+ and causal attention with a computed weighted output. Render the checked-out
215
+ sources to GIF or MP4; examples use explicit numerical state and both themes.
216
+
217
+ For numbers and computer vision, try the [numeric matrix example](examples/catalog-numeric-matrices.tsx)
218
+ or the [actual CIFAR-10 image split into RGB matrices](examples/catalog-image-tensors.tsx).
219
+ The latter reconstructs one original 32×32 frog image from byte data and follows
220
+ the same selected pixel into three numerical channel crops. `PixelGrid`, channel
221
+ and tensor helpers, and matrix focus controls are reusable in browser previews
222
+ and native video renders.
223
+
224
+ For deep learning and image smoothing, try the [convolution filter](examples/catalog-convolution-kernel.tsx)
225
+ and [Gaussian blur](examples/catalog-gaussian-blur.tsx) examples. They show an
226
+ unflipped, single-channel filter calculation and a normalized blur kernel; the
227
+ weights are illustrative. The [mechanism section](#make-the-mechanism-visible)
228
+ covers stride, padding, Gaussian sampling, and border behavior.
229
+
230
+ The [photo blur lesson](examples/catalog-photo-blur.tsx) uses a sharp CC0 coffee
231
+ photo. Its [animation](examples/videos/photo-gaussian-blur.tsx) computes and
232
+ shows actual 25 × 25 Gaussian results from σ = 0 to 4, with σ = 0 as the
233
+ unchanged identity crop. A numerical matrix shows the center 5 × 5 weights
234
+ rounded to six decimals; the sum covers the full 25 × 25 filter. The sharp
235
+ source and filtered image use the same size and crop. The embedded 384 × 256
236
+ sample is prepared by
237
+ [`scripts/prepare-photo-sample.mjs`](scripts/prepare-photo-sample.mjs), which
238
+ requires Node.js and FFmpeg. The photo and codec notices are in
239
+ [`assets/THIRD_PARTY_LICENSES.md`](assets/THIRD_PARTY_LICENSES.md).
240
+
241
+ The raster helpers `decodeRgbPng`, `encodeRgbPng`, `cropRgbRaster`, and
242
+ `gaussianBlurRgb` operate on flat row-major RGB data. Decoding accepts opaque,
243
+ noninterlaced 8-bit PNG data URIs up to 2 MiB and 1,048,576 pixels and rejects
244
+ embedded ICC profiles. Raster operations use the same 1,048,576-pixel limit.
245
+ Blur uses the stored, gamma-encoded channel values without linearizing them and
246
+ returns floating-point RGB with valid convolution and an integer radius from 0
247
+ to 64, defaulting to `ceil(3σ)`. PNG encoding rounds values when writing the
248
+ output image. These helpers are available from full Vizmatic SDK modules and
249
+ the full Playground, not from the isolated QuickJS author-code environment
250
+ described above.
@@ -3,6 +3,42 @@
3
3
  Vizmatic vendors these assets so the CLI and renderer can run without public
4
4
  runtime fetches.
5
5
 
6
+ ## CIFAR-10 image-to-matrix example
7
+
8
+ `examples/catalog-image-tensors.tsx` contains 3,072 RGB bytes from training
9
+ batch 1, record 0 (frog), plus numerical channel views. Source:
10
+ https://www.cs.toronto.edu/~kriz/cifar.html. Cite Alex Krizhevsky,
11
+ *Learning Multiple Layers of Features from Tiny Images* (2009).
12
+
13
+ The dataset page does not specify a dataset license. The sample bytes and their
14
+ rendered visualization are third-party material, not part of Vizmatic's MIT
15
+ code license. `node scripts/extract-cifar-sample.mjs` reproduces the exact
16
+ sample in `examples/catalog-image-tensors.tsx` from the official binary archive
17
+ without loading pickle or downloading the full dataset. The reviewed record
18
+ SHA-256 is
19
+ `945dc5584f8efcf7dc58367c3b072c0a23dacc05ae824d7c77a33874a8ec83c7`.
20
+
21
+ ## Coffee photo blur example
22
+
23
+ `examples/catalog-photo-blur.tsx` uses a sharp, prepared 384 × 256 palette PNG
24
+ derived from scikit-image's `coffee.png`. The source image is pinned at
25
+ [scikit-image commit `e8a42ba85aaf5fd9322ef9ca51bc21063b22fcae`](https://github.com/scikit-image/scikit-image/blob/e8a42ba85aaf5fd9322ef9ca51bc21063b22fcae/skimage/data/coffee.png)
26
+ and has SHA-256
27
+ `cc02f8ca188b167c775a7101b5d767d1e71792cf762c33d6fa15a4599b5a8de7`. The
28
+ scikit-image [sample-data documentation](https://scikit-image.org/docs/stable/api/skimage.data.html#skimage.data.coffee)
29
+ identifies the photograph as CC0 by photographer Rachel Michetti. The prepared
30
+ palette PNG has SHA-256
31
+ `7ce98fef02b2bb5d6a073502c70e7ca5203187a4133973f8729e2d2be3ff7ba4`; it has
32
+ not been blurred. Recreate and re-embed the sample with
33
+ `node scripts/prepare-photo-sample.mjs` (requires FFmpeg); the script verifies
34
+ both pinned hashes before updating the photo block.
35
+
36
+ ## RGB PNG codec dependencies
37
+
38
+ The raster helpers use `fast-png` 8.0.0, `iobuffer` 6.0.1, and `fflate` 0.7.5,
39
+ each under the MIT License. Their full notices are in
40
+ [`licenses/raster-codecs-MIT.txt`](licenses/raster-codecs-MIT.txt).
41
+
6
42
  ## Fonts
7
43
 
8
44
  - Inter: SIL Open Font License 1.1.
@@ -11,6 +47,9 @@ runtime fetches.
11
47
  - JetBrains Mono: SIL Open Font License 1.1.
12
48
  Copyright 2020 The JetBrains Mono Project Authors.
13
49
  Source: https://github.com/JetBrains/JetBrainsMono
50
+ - Instrument Serif: SIL Open Font License 1.1.
51
+ Copyright 2022 The Instrument Serif Project Authors.
52
+ Source: https://github.com/Instrument/instrument-serif
14
53
  - Noto Sans: SIL Open Font License 1.1.
15
54
  Copyright Google Inc.
16
55
  Source: https://github.com/notofonts/noto-fonts
@@ -20,7 +59,7 @@ runtime fetches.
20
59
 
21
60
  Full license: [`licenses/OFL-1.1.txt`](licenses/OFL-1.1.txt).
22
61
 
23
- The website uses WOFF2 copies of the same Inter and JetBrains Mono font files.
62
+ The website uses WOFF2 copies of the same Inter, JetBrains Mono, and Instrument Serif font files.
24
63
  Regenerate them with `pnpm site:fonts`; the original font licenses apply.
25
64
 
26
65
  ## Emoji
@@ -0,0 +1,74 @@
1
+ fast-png
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2015 Michaël Zasso
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+
26
+ iobuffer
27
+
28
+ The MIT License (MIT)
29
+
30
+ Copyright (c) 2015 Michaël Zasso
31
+
32
+ Permission is hereby granted, free of charge, to any person obtaining a copy
33
+ of this software and associated documentation files (the "Software"), to deal
34
+ in the Software without restriction, including without limitation the rights
35
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36
+ copies of the Software, and to permit persons to whom the Software is
37
+ furnished to do so, subject to the following conditions:
38
+
39
+ The above copyright notice and this permission notice shall be included in all
40
+ copies or substantial portions of the Software.
41
+
42
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
48
+ SOFTWARE.
49
+
50
+
51
+
52
+ fflate
53
+
54
+ MIT License
55
+
56
+ Copyright (c) 2020 Arjun Barrett
57
+
58
+ Permission is hereby granted, free of charge, to any person obtaining a copy
59
+ of this software and associated documentation files (the "Software"), to deal
60
+ in the Software without restriction, including without limitation the rights
61
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
62
+ copies of the Software, and to permit persons to whom the Software is
63
+ furnished to do so, subject to the following conditions:
64
+
65
+ The above copyright notice and this permission notice shall be included in all
66
+ copies or substantial portions of the Software.
67
+
68
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
69
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
70
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
71
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
72
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
73
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
74
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ import parseCssColor from"parse-css-color";import{liteAdaptor}from"mathjax-full/js/adaptors/liteAdaptor.js";import{RegisterHTMLHandler}from"mathjax-full/js/handlers/html.js";import{TeX}from"mathjax-full/js/input/tex.js";import"mathjax-full/js/input/tex/ams/AmsConfiguration.js";import"mathjax-full/js/input/tex/newcommand/NewcommandConfiguration.js";import{mathjax}from"mathjax-full/js/mathjax.js";import{SVG}from"mathjax-full/js/output/svg.js";var DEFAULT_FONT_SIZE=16;var EX_FACTOR=.5;var adaptor=liteAdaptor({fontSize:DEFAULT_FONT_SIZE});RegisterHTMLHandler(adaptor);var outputJax=new SVG({fontCache:"none",exFactor:EX_FACTOR});var renderCache=new Map;var RENDER_CACHE_LIMIT=128;function createDocument(){const inputJax=new TeX({packages:["base","ams","newcommand"],formatError(_jax,error){throw new Error(`Invalid TeX: ${error.message}`,{cause:error})}});return mathjax.document("",{InputJax:inputJax,OutputJax:outputJax})}function parseEx(value,name){if(typeof value!=="string"||!value.endsWith("ex")){throw new Error(`MathJax returned an unsupported ${name} dimension`)}const amount=Number(value.slice(0,-2));if(!Number.isFinite(amount)||amount<=0){throw new Error(`MathJax returned an invalid ${name} dimension`)}return amount}function parseViewBox(value){if(typeof value!=="string")throw new Error("MathJax returned an SVG without a viewBox");const values=value.trim().split(/[ ,]+/).map(Number);if(values.length!==4||values.some(part=>!Number.isFinite(part))||values[2]<=0||values[3]<=0){throw new Error("MathJax returned an invalid SVG viewBox")}return[values[0],values[1],values[2],values[3]]}function renderMathSvg(tex,options={}){if(typeof tex!=="string"||tex.trim().length===0){throw new Error("TeX input must be a non-empty string")}const fontSize=options.fontSize??DEFAULT_FONT_SIZE;if(!Number.isFinite(fontSize)||fontSize<=0){throw new Error("Math SVG fontSize must be a positive finite number")}const color=options.color??"#000000";if(typeof color!=="string"||!parseCssColor(color.trim())){throw new Error("Math SVG color must be a valid CSS color")}const normalizedColor=color.trim();const display=options.display??false;const key=JSON.stringify([tex,fontSize,normalizedColor,display]);const cached=renderCache.get(key);if(cached){renderCache.delete(key);renderCache.set(key,cached);return{...cached}}let container;try{container=createDocument().convert(tex,{display,em:fontSize,ex:fontSize*EX_FACTOR,containerWidth:fontSize*80})}catch(cause){if(cause instanceof Error&&cause.message.startsWith("Invalid TeX:"))throw cause;const detail=cause instanceof Error?cause.message:String(cause);throw new Error(`Unable to render TeX: ${detail}`,{cause})}const svgElement=adaptor.tags(container,"svg")[0];if(!svgElement)throw new Error("MathJax did not produce an SVG image");const width=parseEx(adaptor.getAttribute(svgElement,"width"),"width")*fontSize*EX_FACTOR;const height=parseEx(adaptor.getAttribute(svgElement,"height"),"height")*fontSize*EX_FACTOR;if(!Number.isFinite(width)||!Number.isFinite(height)){throw new Error("MathJax returned non-finite SVG dimensions")}const[,viewBoxY,,viewBoxHeight]=parseViewBox(adaptor.getAttribute(svgElement,"viewBox"));const baseline=-viewBoxY*height/viewBoxHeight;if(!Number.isFinite(baseline)){throw new Error("MathJax returned an invalid SVG baseline")}const drawing=adaptor.tags(svgElement,"g")[0];if(!drawing)throw new Error("MathJax returned an SVG without a drawing group");adaptor.removeAttribute(svgElement,"style");adaptor.setAttribute(svgElement,"width",`${width}px`);adaptor.setAttribute(svgElement,"height",`${height}px`);adaptor.setAttribute(drawing,"fill",normalizedColor);adaptor.setAttribute(drawing,"stroke",normalizedColor);const result={svg:adaptor.serializeXML(svgElement),width,height,baseline};renderCache.set(key,result);if(renderCache.size>RENDER_CACHE_LIMIT){renderCache.delete(renderCache.keys().next().value)}return{...result}}export{renderMathSvg};