# HBF Torus Lab: Fusion Observatory

## Graphics, UI/UX and Scientific Development Specification

**Document version:** 1.0 · **Research checked:** 6 September 2026 (UTC)  
**Audience:** frontend developers, 3D artists, numerical-software developers and scientific reviewers.  
**Purpose:** build the selected Fusion Observatory appearance into a usable, reproducible Torus Lab for magnetic-field exploration, equilibrium inspection, particle tracing and explicitly scoped proton–boron calculations.

This is an implementation specification. It does not claim that the current website, a new solver, or the proposed acceptance tests have already been implemented or passed.

**Navigation**

- [Visual design and user journeys](#3-visual-implementation-specification) — Sections 3–4.
- [Scientific inputs, run states and software architecture](#5-scientific-model-and-input-contracts) — Sections 5–9.
- [Physics models, equations and benchmarks](#10-analytic-magnetic-field-and-exact-development-fixture) — Sections 10–16.
- [Data, results, uncertainty and reproduction](#17-import-formats-configuration-schema-and-data-provenance) — Sections 17–20.
- [Reliability, performance, accessibility and hosting](#21-first-load-stability-cancellation-and-recovery) — Sections 21–24.
- [Acceptance tests and development backlog](#25-verification-plan-and-acceptance-tests) — Sections 25–27.
- [Research limits, sources and developer handoff](#28-evidence-reconciliation-and-remaining-limits) — Sections 28–30.

## 1. Development mandate and scope

Build a functioning 3D scientific workspace that closely follows the selected image: midnight-blue surfaces, a restrained left setup panel, a large metallic toroidal assembly, a transparent front inspection sector, cyan plasma visualization and a small camera toolbar. Add scientific depth through expandable setup sections and a results workspace; retain the visual hierarchy of the image.

The deliverable to build is the interactive lab, including its source code, assets, numerical kernels, datasets with provenance, tests, documentation and static hosting output. A background image with overlaid controls does not satisfy this specification. Neither does an animation whose field lines and results are disconnected from its inputs.

### 1.1 Working assumptions

| Item | Assumption and required treatment |
|---|---|
| Selected visual source | The supplied image, `ChatGPT Image Sep 7, 2026, 12_11_33 AM.png`, was directly inspected. It is 1536 × 1024 pixels. |
| Reference identity | SHA-256: `bd2e20a2ca9bf2d745110453b2e92a35dbef7da6d69f00431b4eab1a5f06fdb0`. |
| Existing application | Earlier project context describes static Apache/LiteSpeed hosting. This document uses that as a deployment assumption. No current Torus source archive or live runtime was audited for this document. |
| Application route | `/labs/torus/` is a proposed canonical route. Resolve the real existing route and inbound links before migration. |
| Implementation | Modular JavaScript or TypeScript compiled to browser JavaScript, Three.js for graphics, dedicated workers for numerical work, static assets on the same origin. |
| Scientific scope | Static magnetic fields, field-line topology, prescribed-field particle motion, equilibrium datasets, profile diagnostics and declared fusion/radiation models. |
| Research extensions | Self-consistent time-dependent MHD, turbulence, kinetic transport, RF coupling and complete reactor engineering need dedicated models and their own validation. Define adapters for them; never substitute decorative effects for their outputs. |

**Meaning of scientific readiness:** a user can identify the model, enter dimensional inputs, inspect its assumptions, run a calculation, assess numerical quality, compare results, and reproduce the calculation from an export. A realistic reactor render is a presentation asset, not evidence of a validated reactor.

### 1.2 Required capability groups

| Group | Required capability | Evidence the implementation must provide |
|---|---|---|
| Graphics | Parametric torus, vessel, coil objects, cutaway, camera controls, rendering quality levels | Reference-view captures and tests linking geometry to configuration |
| Setup | Precise numeric inputs, units, presets, validation and model selection | Schema validation and visible input/result consistency |
| Fields | Analytic field, filament-coil field, imported field/equilibrium | Field benchmarks, domain checks and interpolation diagnostics |
| Topology | Field lines, surface seeds, Poincaré sections, winding estimates | Exported line coordinates and convergence evidence |
| Particles | Full-orbit tracing, species, energy, pitch, gyrophase and wall events | Uniform-field, drift, timestep and wall-interception tests |
| Plasma | Density/temperature profiles, pressure, beta and energy inventory where applicable | Dimensional checks and declared profile assumptions |
| H–B calculations | Named cross-section/reactivity evaluations, fusion source and loss ledger | Source provenance, energy-frame and multiplicity tests |
| Interpretation | Numeric tables, plots, probes, warnings, model-domain status | All displayed values traceable to the current run |
| Comparison | Saved runs, parameter sweeps, sensitivity and convergence comparisons | Immutable run snapshots and compatible comparison rules |
| Reproduction | Configuration, numerical results, sources, solver settings and checksums | Export/import round trip and independent reproduction |
| Reliability | Stable first load, cancellation, recovery and non-WebGL operation | Failure-injection and route tests |
| Accessibility | Keyboard/click alternatives, readable controls and equivalent numeric access | Automated checks plus manual task completion |

## 2. Analysis of the selected image

The reference succeeds as a visual direction because the assembly dominates the screen, the controls are grouped coherently, and the dark background makes the vessel and plasma easy to distinguish. The scientific implementation must address the following gaps visible in the concept.

| Image element | Preserve | Development correction |
|---|---|---|
| HBF masthead | Brand position, dark header and restrained typography | Make the lab name and return navigation functional; keep research marketing copy outside the main scientific task. |
| Fusion Observatory title | Placement above the viewport | Use `Fusion Observatory` as the workspace name and `Torus Lab` as the module name. Replace `Visual concept` in the working product with the active model and run status. |
| Field strength slider | Fast adjustment | Add an editable value, unit and definition, such as `Toroidal field at R₀, B₀ [T]`. In coil mode, current is an input and field strength is a computed result. |
| Geometry slider | Simple initial interaction | Replace the ambiguous single control with major radius, plasma minor radius and wall geometry. Put additional shape settings in a disclosure panel. |
| Coils toggle | Visibility control | Rename to `Show coils`. Turning it off hides graphics without changing physical currents. Give current changes separate controls. |
| Plasma toggle | Visual layer control | Rename to `Show plasma volume`. Document whether color represents a selected scalar or an illustrative display material. |
| Field lines toggle | Layer visibility | Display solver-generated trajectories and their seed/termination metadata. Animated dots along a line are playback markers. |
| Transparent front sector | Inspection value and visual identity | Treat it as a viewing cutaway. Hiding a wall sector must not remove that sector from particle collision calculations. |
| Bright inner region | Cyan visual emphasis | Ensure the torus remains a tube around a central opening. Avoid arbitrary luminous chords across the central hole that could be mistaken for confined trajectories. |
| Repeated metallic coil forms | Materials and assembly rhythm | Model conductor centerlines and coil orientation explicitly. Decorative windings cannot establish the magnetic field they produce. |
| Run simulation | Single clear primary action | Add progress, cancellation, completion, failure, stale-input and partial-result behavior. |
| Orbit, reset, export image | Compact camera toolbar | Add keyboard and click alternatives, camera presets, and numerical export separately from image export. |
| Empty lower workspace | Breathing room before a run | Open a results dock after calculation; expose numeric data, diagnostics and comparison without permanently covering the model. |

Toroidal-field magnets, poloidal-field coils and a central solenoid serve different functions; their object names and physical controls must reflect those distinctions. ITER's descriptions support the separation, but do not validate the HBF concept's particular construction. [ITER: magnet systems](https://www.iter.org/machine/magnets).

## 3. Visual implementation specification

### 3.1 Layout dimensions

Measurements below are approximate design targets derived from the image, not recovered source CSS.

| Region | Desktop target | Behavior |
|---|---|---|
| Header | 54–60 CSS px high | Fixed layout height; no late size change when fonts or icons load |
| Setup sidebar | About 312 px at 1536 px width; adjustable 288–340 px | Independent vertical scrolling for advanced setup |
| Viewport | Remaining width and available height | Refit camera when the results dock opens; never stretch the canvas bitmap |
| Workspace title | 32–36 px at the reference width | Smaller than the reactor; use real HTML text |
| Body labels | 14–16 px minimum target | Persistent unit labels and readable help text |
| Main action | Full sidebar width, 48–52 px high | Remains reachable without scrolling through every advanced control |
| Camera toolbar | Approximately 44 px high | Bottom of viewport, clear of the results dock and mobile safe areas |
| Results dock | Initially closed; approximately 280–360 px when opened | Resizable on desktop, full-width panel on smaller screens |

Use a CSS grid with `minmax(0, 1fr)` for the main workspace. Give both scrolling children `min-width: 0` and appropriate `min-height: 0`. The canvas CSS size follows its container; drawing-buffer resolution is controlled separately.

### 3.2 Proposed design tokens

The background samples in the source are near RGB `(13,25,38)` and `(7,21,39)`. These tokens retain that direction while making text and controls measurable.

```css
:root {
  --torus-bg: #071527;
  --torus-panel: #0d1926;
  --torus-surface: #112030;
  --torus-text: #e8f3ff;
  --torus-muted: #a9c1d8;
  --torus-accent: #22d3ee;
  --torus-accent-ink: #061827;
  --torus-focus: #38bdf8;
  --torus-error: #fb7185;
  --torus-divider: #294155;
  --torus-radius: 8px;
  --torus-space: 8px;
}
```

Calculated solid-color contrast ratios are 15.79:1 for primary text on the panel, 9.55:1 for muted text, and 9.95:1 for dark button text on cyan. These calculations do not certify the final interface: inspect actual gradients, disabled states, overlays, focus indicators and antialiasing. Standard normal text needs at least 4.5:1 under WCAG AA; qualifying large text needs 3:1. [W3C: text contrast](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html).

Use a locally hosted, licensed sans-serif family or a system stack. Keep monospaced type for numerical data, not entire labels. Align decimal values in tables; preserve scientific notation and copyable full precision.

### 3.3 Responsive behavior

- **At 1280 px and above:** fixed setup sidebar, large 3D workspace, collapsible results dock.
- **At 900–1279 px:** narrower sidebar; advanced scientific settings open in a dedicated panel rather than a second permanent column.
- **Below 900 px:** full-width viewport with a clearly labelled Setup/Results switch; retain run status and the primary action.
- **At 320 CSS px or 400% zoom:** forms and navigation reflow; the scientific plot may keep its intrinsically two-dimensional area, with an equivalent data table and accessible controls. Do not force the whole page into horizontal scrolling. [W3C: reflow](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html).

Choose breakpoints by task completion and available space, not user-agent detection.

## 4. User journeys and information architecture

### 4.1 First useful run

1. Open Torus Lab. A stable shell appears immediately, with `Loading 3D view` confined to the viewport.
2. Load `Circular field benchmark`, showing its model and dimensional inputs.
3. Edit `B₀ [T]` using either the number field or slider. The two controls stay synchronized.
4. Choose `Field lines` and press `Run simulation`.
5. Show progress and the active run identifier. Allow cancellation.
6. On completion, display the computed geometry, field lines, a compact result summary and a `View results` action.
7. Inspect a probe point, the R–Z section and line winding. Every plot has its underlying table.
8. Save the run, change one input, and compare configurations and outputs.
9. Export a reproduction package and successfully reopen it in a clean session.

### 4.2 Research dataset workflow

1. Import an equilibrium or field dataset locally.
2. Preview detected axes, dimensions, coordinate conventions, units, valid domain and source metadata before accepting it.
3. Resolve missing metadata explicitly. Never silently assume a flux normalization or reverse a sign.
4. Run import diagnostics and show the converted canonical representation.
5. Load compatible profiles and particle initial conditions.
6. Trace fields or particles and examine numerical convergence, domain exits and wall hits.
7. Run a controlled parameter sweep with the source dataset held fixed where appropriate.
8. Export source identifiers, transformations, current configuration, numerical results and the diagnostic report.

### 4.3 Scientific setup organization

Use six collapsible groups: **Model**, **Geometry and coils**, **Fields and seeds**, **Particles**, **Plasma profiles**, and **Numerics**. Show only fields relevant to the selected model/task. Provide a separate **Appearance** disclosure for visibility, glow and rendering quality.

The main progression is **Setup → Run → Interpret → Compare → Export**. The run action stays in the setup area; it does not need a redundant full-page tab. Results, comparison and export are views of a saved or current run.

Avoid blank “advanced” pages, generic dashboards and placeholder controls. If a feature is not implemented, do not present its output as calculated.

## 5. Scientific model and input contracts

### 5.1 Separate the field model from the task

| Field model | Calculation basis | Suitable tasks | Important boundary |
|---|---|---|---|
| `analytic-circular-v1` | Explicit divergence-free field in Section 10 | Field tracing, probes, verification and prescribed-field particles | Generally not a force-balanced equilibrium |
| `filament-coils-v1` | Biot–Savart field from oriented current paths | Coil-field comparison, ripple, field lines and particles | Vacuum/prescribed-current model; no automatic plasma response |
| `equilibrium-import-v1` | Imported poloidal flux and profiles | Equilibrium inspection, topology, profiles and particles | Trust depends on source, conventions and import diagnostics |
| `field-grid-import-v1` | Sampled vector field or compatible potential representation | Probes and tracing within the supplied domain | Interpolation error and divergence must be assessed |
| `gs-solver-v1` | Validated Grad–Shafranov solve | Axisymmetric force-balanced equilibria and parameter studies | Requires boundary and profile specifications; does not solve turbulence |

Tasks are separate identifiers such as `field-map`, `field-lines`, `poincare`, `particle-orbits`, `profile-diagnostics`, `fusion-source` and `parameter-sweep`. An imported equilibrium is not a different particle integrator; both must use the same documented field interface.

### 5.2 Input dictionary

Defaults are development presets, not recommended reactor operating conditions. Values without a default must be supplied by the selected dataset, explicit preset or user.

| Input | Unit / type | Initial preset | Validation and effect |
|---|---|---|---|
| Field model | Enumerated identifier | `analytic-circular-v1` | Determines applicable controls and diagnostics |
| Task | Enumerated identifier | `field-lines` | Determines required inputs and run budget |
| Major radius `R0` | m | 2.0 | Positive; must exceed the outer wall tube radius for the circular template |
| Plasma minor radius `a` | m | 0.5 | Positive and smaller than the wall inner radius |
| Wall inner minor radius | m | 0.65 | Defines particle-interception surface, distinct from plasma boundary |
| Wall thickness | m | 0.05 | Positive for the illustrative assembly; metadata is not a stress calculation |
| Elongation / triangularity | Dimensionless | Circular template: 1 / 0 | Enabled only for geometry templates or models that support the changed shape |
| Reference toroidal field `B0` | T, signed | 2.0 | Nonzero for normalized tracing; sign reverses field direction |
| Axis winding parameter `qAxis` | Dimensionless, signed | 2.0 | Nonzero; actual winding away from axis is calculated |
| Coil current | A, signed | Model-specific | Distinguished from turn count and effective ampere-turns |
| Coil turns | Integer | Model-specific | Positive; multiply current by turns exactly once |
| Coil centerline / cross-section | m | Model-specific | Closed paths, orientation, nondegeneracy and conductor exclusion checks |
| Plasma current | A | Equilibrium-specific | Input to an applicable equilibrium model or an imported result; not inferred from appearance |
| Flux convention | Structured metadata | Explicit internal convention | Includes handedness, sign and total-flux versus flux-per-radian definition |
| Field seed position | m and rad | Valid interior seeds | Must lie in the valid field domain; store exact Cartesian coordinates |
| Seed count | Integer | 24 | Scientific sampling setting; not changed by rendering quality |
| Maximum line length | m | 200 | Stop condition, not physical simulation time |
| Poincaré plane | rad and direction | 0, positive crossing | Event detection must handle angle wrapping |
| Particle species | Identifier plus mass/charge | Proton | Use a versioned constants/species record |
| Particle kinetic energy | eV / keV / MeV | 10 keV | Convert to joules once; select appropriate relativistic treatment |
| Pitch angle | degrees in UI, rad internally | 60° | Relative to local magnetic field, range 0–180° |
| Gyrophase | degrees in UI, rad internally | 0° | Define perpendicular basis; retain random seed if sampled |
| Observation duration | s | 1 µs for a small example | Distinct from animation playback duration |
| Particle timestep | s | Derived from gyrofrequency and requested accuracy | Show derived value and convergence controls |
| Electric field | V/m or named model | Zero | Enable only a defined model; arbitrary time-varying B needs consistent induced E |
| Particle count and weights | Integer and explicit weight | Small deterministic ensemble | Weighted results must retain normalization and sampling method |
| Species densities | m⁻³ | No assumed experimental value | Nonnegative; identify species and ionization states |
| Electron / ion temperature | eV or keV | No assumed experimental value | Meaning is thermal energy `kB T`; model-specific validity limits |
| Profile coordinate | `r`, normalized flux, etc. | Model-specific | Store the exact definition and conversion, not a bare `rho` |
| Cross-section evaluation | Versioned identifier | Explicit user/preset choice | Enforce energy frame, units and documented domain |
| Numerical tolerance | Dimensionless / m | Task-specific | Separate solver tolerance, interpolation error and measurement uncertainty |
| Appearance | Boolean / scalar | Reference-style settings | Must not alter the scientific configuration or result hash |

Parse complete numeric tokens, including scientific notation. Reject trailing text, NaN, infinity and ambiguous decimal separators. Preserve units when the user changes display format. Validate related fields together, such as `a < wallInner < wallOuter < R0` for the circular geometry template. Explain the failed relationship alongside the relevant input.

## 6. Run states and interaction behavior

Use separate state machines for the numerical run and the renderer. A lost graphics context is not a failed numerical result.

| Run state | Visible behavior | Permitted transition |
|---|---|---|
| `empty` | Explain required data or offer a preset | Configure or import |
| `invalid` | Inline errors; primary action explains missing requirements | Correct configuration |
| `ready` | Valid configuration; no current calculation | Run |
| `running` | Frozen run inputs, progress and Cancel | Complete, pause if supported, cancel or fail |
| `paused` | Physical time and step are shown | Resume or cancel; only expose this if checkpointing works |
| `complete` | Current results and available exports | Save, compare or modify setup |
| `stale` | Results remain attached to their previous configuration | Rerun or return to the saved setup |
| `cancelled` | Explain where execution stopped | Restart; export a clearly labelled partial result if retained |
| `error` | Actionable error and preserved configuration | Retry or change the offending input |

Renderer states are `loading`, `ready`, `degraded`, `context-lost` and `unavailable`.

Keep `draftConfiguration` separate from the immutable `runConfiguration`. When a physical input changes during a run, either queue it for the next run or cancel/restart through an explicit action. Never allow an old worker response to overwrite a newer run. A camera orbit or visibility change affects only view state.

Progress should report work completed, such as particles or integration steps. If the total cannot be predicted, show an indeterminate phase label rather than an invented percentage.

## 7. 3D assets and rendering pipeline

### 7.1 Geometry and asset construction

1. Build a canonical parametric geometry description in metres. It owns the plasma surface, wall boundary, coil centerlines and inspection cut.
2. Generate scientific boundary geometry from that description. Create separate display meshes with materials and decorative detail.
3. Author a reusable metallic coil segment and vessel panel in a 3D tool, with correct normals, UVs, pivot points and material assignments. Export glTF/GLB assets.
4. Use procedural placement or bounded shape variants for radius changes. Do not stretch a single baked reactor model arbitrarily and imply that its conductor positions still match the field model.
5. Instance genuinely repeated display parts. Rebuild the scientific coil paths from the same configuration used to place them.
6. Maintain explicit object identifiers for vessel, wall, plasma surface, individual coil groups, field lines, particles, axes and probes.

glTF specifies a right-handed coordinate system, metre-scale linear units and radian angles. Record a deliberate transform between its Y-up presentation coordinates and the physics coordinates. [Khronos: glTF 2.0 specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html). Three.js supports compressed glTF assets and associated texture/mesh decoders through `GLTFLoader`; bundle the matching decoders with the tested application release. [Three.js: GLTFLoader](https://threejs.org/docs/pages/GLTFLoader.html).

### 7.2 Reference appearance

| Layer | Required treatment |
|---|---|
| Vessel | Brushed titanium/steel, moderate roughness, soft highlights and visible panel structure |
| Coil details | Restrained dark cobalt windings and metal clamps; avoid excessive microgeometry at normal viewing distance |
| Plasma volume | Cyan emission constrained to the declared plasma region; display setting separated from physical temperature |
| Inspection sector | Front sector made hidden or selectively translucent; retain a clear edge showing the cut |
| Field lines | Thin solver-derived geometry with depth cues; direction markers and a selectable scientific color mode |
| Grounding | Subtle environment lighting and contact shadow; no starfields, sparks or unexplained energy effects |
| Camera | Three-quarter view from above, looking toward the torus center; fit the entire assembly with padding |

Start camera tuning with a 35–45° perspective field of view and derive camera distance from the bounding box. Fit again after geometry changes or panel resizing. Provide top, side, front and isometric presets with named axes. Clip planes must scale with the object and never cut the vessel unintentionally.

### 7.3 Materials, color and transparency

Use a linear lighting workflow, correct color texture annotations, non-color treatment for normal/roughness textures, and one final output conversion. When using post-processing, put the intended tone/output conversion at the end. Incorrect color-space setup can change the whole scene's brightness; adding more light is not a substitute for correcting it. [Three.js: color management](https://threejs.org/manual/en/color-management.html).

Prefer a geometric cutaway for inspection. Large nested translucent shells are susceptible to ordering artifacts; object sorting does not solve every triangle-order problem. Use limited transparent layers, appropriate depth settings and view-angle tests. Do not prescribe `depthWrite=false` globally. [Three.js: transparency](https://threejs.org/manual/en/transparency.html).

Treat transmission/refraction as an optional higher-quality effect. The default must remain readable when it is disabled. A plasma emissive material is a visual transfer function; if it encodes a scalar, show the scalar name, unit, scale and range. Keep scientific coloring separate from aesthetic glow.

### 7.4 Scientific overlays

Add a scale reference, coordinate axes, selected-probe marker, field-direction key and optional R–Z slice. Enable each deliberately. Use CPU-computed Float64 coordinates for results and down-convert copies for GPU buffers.

Never use a shader's noise, brightness, pulse rate or randomly moving points to calculate density, temperature, field strength, fusion rate or confinement. Rendering quality may reduce visible geometry or sample display density, but it must preserve the full stored numerical result.

## 8. Software architecture and module responsibilities

Use a small HTML/CSS application shell with modular numerical and rendering packages. TypeScript is useful for unit-tagged interfaces and discriminated model types; the deployed output remains static JavaScript. An existing framework can host these modules if its actual source is available, but the physics kernels must not depend on UI components.

| Proposed module / path | Responsibility |
|---|---|
| `src/app/bootstrap.ts` | Load configuration and create shell, worker and renderer in a controlled order |
| `src/app/state.ts` | Draft, run and view state; immutable run identity |
| `src/schema/` | Configuration, import and export schemas plus migrations |
| `src/physics/constants.ts` | Versioned constants and species definitions |
| `src/physics/coordinates.ts` | Coordinate conversion, angle unwrapping and flux conventions |
| `src/physics/fields/` | Analytic, coil, equilibrium and grid field adapters |
| `src/physics/integrators/` | Adaptive line tracer, particle pushers and event location |
| `src/physics/diagnostics/` | Winding, field quality, orbit invariants, pressure and energy inventories |
| `src/physics/fusion/` | Cross-section import, distribution integrals and source/loss accounting |
| `src/workers/` | Run orchestration, cancellation, progress and transferable buffers |
| `src/render/` | Scene objects, camera, materials, overlays and visual quality |
| `src/ui/` | Accessible forms, result tables, plots and comparison views |
| `src/io/` | File parsers, dataset metadata, run packaging and local persistence |
| `assets/` | Versioned GLB/KTX2 assets, fonts, icons and decoder files |
| `datasets/` | Redistributable inputs, provenance, declared domains and hashes |
| `tests/reference/` | Independent reference calculations and numerical fixtures |
| `tests/e2e/` | Scientific journeys, loading, accessibility and deployment tests |
| `dist/` | Deployable static output generated from the source project |

Run numerical work in a dedicated worker so a lengthy calculation does not freeze controls. Transfer copies or ownership of typed-array buffers deliberately; transferred buffers are no longer usable by the sender. [MDN: using Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers).

Start with rendering on the main thread and physics in a worker. Make OffscreenCanvas an optional optimization after measuring the actual bottleneck. Avoid making SharedArrayBuffer or cross-origin isolation a baseline requirement for the existing hosting setup.

The field interface must return a valid value or a structured domain failure:

```ts
type FieldSample = {
  B_T: [number, number, number];
  E_V_per_m?: [number, number, number];
  psi_Wb_per_rad?: number;
  interpolationErrorEstimate?: number;
};

interface StaticFieldModel {
  id: string;
  version: string;
  contains(position_m: [number, number, number]): boolean;
  evaluate(position_m: [number, number, number]): FieldSample;
  metadata(): FieldModelMetadata;
}
```

An omitted diagnostic means unavailable. It must not be coerced into zero.

## 9. Units, coordinates and constants

Use SI units internally: metre, second, tesla, volt per metre, ampere, kilogram, coulomb, joule, pascal and inverse cubic metre. UI conveniences such as keV, MeV, µs and centimetres are explicit conversions.

Pin the constants release. NIST identified the 2022 CODATA adjustment as the current recommended set at the research date; the elementary charge is exactly `1.602176634 × 10⁻¹⁹ C`. Do not label measured masses, vacuum permeability or every other constant as exact. [NIST: fundamental physical constants](https://physics.nist.gov/cuu/Constants/).

### 9.1 Canonical physics coordinates

Use right-handed Cartesian `(x,y,z)` with `z` vertical. Define:

$$
R=\sqrt{x^2+y^2},\qquad \phi=\operatorname{atan2}(y,x),\qquad Z=z.
$$

For a circular torus:

$$
r=\sqrt{(R-R_0)^2+Z^2},\qquad
\theta=\operatorname{atan2}(Z,R-R_0).
$$

Positive toroidal angle is counterclockwise when viewed from `+Z`. Use `atan2`, unwrap angles for winding, and handle the magnetic axis without defining an artificial poloidal angle.

For a Y-up render scene use the proper rotation:

```text
renderX = physicsX
renderY = physicsZ
renderZ = -physicsY
```

Apply it consistently to points, vectors, camera annotations and field directions. Test its inverse and its handedness.

### 9.2 Flux convention

Define internal `psi` as poloidal flux per radian, with:

$$
\mathbf B=\nabla\psi\times\nabla\phi+F\nabla\phi,
\qquad
B_R=-\frac{1}{R}\frac{\partial\psi}{\partial Z},\quad
B_Z=\frac{1}{R}\frac{\partial\psi}{\partial R},\quad
B_\phi=\frac{F}{R}.
$$

The corresponding field is solenoidal for a sufficiently smooth axisymmetric `psi` and `F=F(psi)`. A complete import conversion includes flux normalization, angular orientation, field/current signs and transformed derivatives. A COCOS number in metadata is not evidence that those conversions were implemented. [Sauter and Medvedev: COCOS coordinate conventions](https://www.epfl.ch/research/domains/swiss-plasma-center/wp-content/uploads/2018/10/Sauter_COCOS_Tokamak_Coordinate_Conventions.pdf).

Keep a conversion audit containing the original convention, conversion version, scaling/sign operations and resulting canonical convention. Preserve original input bytes when permitted.

## 10. Analytic magnetic field and exact development fixture

### 10.1 Pure toroidal mode

Implement a pure toroidal field as a separate preset:

$$
\mathbf B=B_0\frac{R_0}{R}\mathbf e_\phi.
$$

This is useful for testing the expected inverse-radius variation and demonstrating the difference between field-line closure and particle motion. The expression is also documented by Simsopt. Use Cartesian components `(-Bphi*y/R, Bphi*x/R, 0)` and exclude `R=0`. [Simsopt: magnetic fields](https://simsopt.readthedocs.io/stable/fields.html).

### 10.2 Circular field fixture

Use this explicitly defined construction for the first verified implementation:

$$
\psi(R,Z)=\frac{B_0}{2q_{\rm axis}}\left[(R-R_0)^2+Z^2\right],
\qquad F=B_0R_0.
$$

It produces:

$$
B_R=-\frac{B_0Z}{q_{\rm axis}R},\qquad
B_Z=\frac{B_0(R-R_0)}{q_{\rm axis}R},\qquad
B_\phi=\frac{B_0R_0}{R}.
$$

This fixture is derived here from the declared flux convention. It is not a published HBF device design. Its divergence vanishes because:

$$
\frac{1}{R}\partial_R(RB_R)+\partial_Z B_Z
=-\frac{1}{R}\partial_R\partial_Z\psi
+\frac{1}{R}\partial_Z\partial_R\psi=0.
$$

For a field line on a circular surface of radius `r`, its signed toroidal winding per poloidal turn is:

$$
\frac{d\phi}{d\theta}
=\frac{q_{\rm axis}R_0}{R_0+r\cos\theta},\qquad
q(r)=\frac{q_{\rm axis}R_0}{\sqrt{R_0^2-r^2}}.
$$

Consequently, `qAxis` is the axis limit; it is not a constant safety factor everywhere. In general geometry, calculate winding using the declared angular convention instead of displaying this circular formula.

### 10.3 Numerical reference values

For `R0=2 m`, `a=0.5 m`, `B0=2 T`, `qAxis=2`:

| Location `(R,Z)` in m | `BR` in T | `Bphi` in T | `BZ` in T | `psi` in Wb/rad |
|---|---:|---:|---:|---:|
| Axis `(2,0)` | 0 | 2 | 0 | 0 |
| Outer midplane `(2.5,0)` | 0 | 1.6 | 0.2 | 0.125 |
| Inner midplane `(1.5,0)` | 0 | 2.666666666666667 | −0.333333333333333 | 0.125 |
| Top `(2,0.5)` | −0.25 | 2 | 0 | 0.125 |

Additional exact-geometry targets, numerically evaluated for this document:

- `q(a) = 2.065591117977289`.
- Circular plasma volume `2π²R0a² = 9.869604401089358 m³`.
- Circular plasma surface area `4π²R0a = 39.47841760435743 m²`.

These are analytic expected values, not measurements or results from a built Torus application. Reuse them as independent tests of that application.

### 10.4 Implementation constraints

- Require nonzero `qAxis`, valid geometry and an evaluation domain excluding `R=0`.
- At the magnetic axis use the component formulas directly. `BR=BZ=0`; the poloidal angle and a numerical winding estimate are undefined there.
- Reversing `B0` reverses both field components while retaining `q`; reversing `qAxis` reverses the poloidal component and signed winding.
- Geometry display changes such as elongation must not silently retain this circular field and claim a self-consistent shaped equilibrium.
- Do not create a general helical field by adding arbitrary trigonometric components. Derive it from a compatible potential or verify its divergence and model assumptions.

This fixture is generally not force-balanced. For it,

$$
\Delta^*\psi=\frac{B_0}{q_{\rm axis}}\left(1+\frac{R_0}{R}\right).
$$

With constant `F`, the pressure derivative required to satisfy the Grad–Shafranov equation would vary around a single circular flux surface. Therefore a pressure setting in this mode is a prescribed diagnostic profile, not a solved equilibrium pressure.

## 11. Coil fields and geometry consistency

Implement the filamentary Biot–Savart law with an explicit current orientation:

$$
\mathbf B(\mathbf x)=\frac{\mu_0}{4\pi}
\sum_k I_k\oint_{C_k}
\frac{d\boldsymbol\ell'\times(\mathbf x-\mathbf x')}
{\lVert\mathbf x-\mathbf x'\rVert^3}.
$$

Simsopt documents coil-based fields and field superposition; use it as one independent comparison implementation. [Simsopt: coil field calculation](https://simsopt.readthedocs.io/stable/fields.html).

### 11.1 Coil data

Each coil record must contain its identifier, centerline geometry, orientation, current in amperes, turn count, conductor/cross-section model, valid sampling distance and optional engineering metadata. Define whether an imported value is conductor current or effective ampere-turns. Never apply the turn count twice.

The display mesh and the field kernel must refer to the same physical coil record. A selected coil highlights its corresponding current path. Provide toggles for displaying toroidal, poloidal and correction groups, but electrical activation must be a separate, unmistakable input.

### 11.2 Numerical strategy

1. Start with direct quadrature on closed centerlines and an independent circular-loop benchmark.
2. Refine the centerline and quadrature until the requested error target is met at representative near and far points.
3. Exclude the mathematical filament singularity. An arbitrary epsilon added to the denominator changes the model and cannot be an undocumented fix.
4. Add a finite conductor cross-section model where internal or near-conductor fields are required.
5. Cache fields using a key containing coil geometry, currents, units, algorithm version and grid definition.
6. If interpolation is introduced, compare off-grid samples against direct evaluation and report its error. Interpolating vector components independently does not automatically preserve zero divergence.

The circular-loop axis oracle is:

$$
B_z(z)=\frac{\mu_0 I a_c^2}{2(a_c^2+z^2)^{3/2}}.
$$

Use the same versioned physical constant but an independently written evaluation of this closed-form expression. Test sign reversal, linear current scaling and field superposition.

### 11.3 Coil-mode results

Provide local field components, magnitude, R–Z or Cartesian slices, selected-region extrema and a clearly defined ripple statistic. For example, if using `(Bmax−Bmin)/(Bmax+Bmin)` along a toroidal sampling curve, name the curve, sample count and statistic. Do not label it a universal machine ripple without specifying those choices.

Coil force, stress, cooling and superconducting margin are separate engineering calculations. If added, they require material data, conductor geometry, thermal assumptions and validated solvers; metallic appearance cannot supply those properties.

## 12. Equilibrium import and Grad–Shafranov development

### 12.1 Import route

Support a documented subset of G-EQDSK and an HBF canonical equilibrium format. G-EQDSK carries the poloidal-flux grid and profiles such as pressure, `F=RBphi` and safety factor, but does not standardize all coil locations and currents. Do not invent the missing coils from the rendered picture. [FreeGS: input and output](https://freegs.readthedocs.io/en/latest/input_and_output.html).

Validate grid shape, axis coordinates, units, finite values, flux boundaries, profiles, interpolation domain, boundary/limiter geometry and coordinate conventions. Parse fixed-width numeric records and Fortran exponents where supported; do not rely on whitespace splitting alone.

An import library's COCOS argument may implement only part of the required conversion. FreeQDSK explicitly documents that its option currently handles the flux `2π` factor rather than every convention. Implement and test the full chosen subset separately. [FreeQDSK: G-EQDSK handling](https://freeqdsk.readthedocs.io/en/stable/geqdsk.html).

### 12.2 Reconstruction and diagnostics

Construct `BR` and `BZ` from derivatives of the same interpolated `psi`. Reconstruct `Bphi` from the compatible `F` profile. Outside the data domain, stop or use an explicitly supplied extension model; never silently clamp to boundary values and continue a scientific orbit.

Calculate normalized flux as:

$$
\psi_N=\frac{\psi-\psi_{\rm axis}}{\psi_{\rm boundary}-\psi_{\rm axis}}.
$$

Require a nonzero denominator and preserve the distinction between normalized poloidal flux and normalized toroidal-flux radius. IMAS records these quantities with explicit coordinates and units; use that vocabulary when designing export adapters. [IMAS: equilibrium data dictionary](https://imas-data-dictionary.readthedocs.io/en/4.1.1/generated/ids/equilibrium.html).

Show the magnetic axis, boundary/LCFS when defined, X-points when supported, contour plots, selected profiles, source time slice and interpolation diagnostics. A limiter contour is a geometry input, not automatically a conducting-wall electromagnetic model.

### 12.3 Local equilibrium solver

For the internal convention, implement:

$$
\Delta^*\psi
=R\frac{\partial}{\partial R}\left(\frac1R\frac{\partial\psi}{\partial R}\right)
+\frac{\partial^2\psi}{\partial Z^2}
=-\mu_0R^2\frac{dp}{d\psi}-F\frac{dF}{d\psi}.
$$

The equation and convention transformations are documented in the COCOS reference. [Sauter and Medvedev: Grad–Shafranov conventions](https://www.epfl.ch/research/domains/swiss-plasma-center/wp-content/uploads/2018/10/Sauter_COCOS_Tokamak_Coordinate_Conventions.pdf).

Build the solver in this order:

1. A fixed-boundary linear or manufactured problem with known solution.
2. A fixed-boundary nonlinear solver with explicit pressure/current profile parameterization.
3. Grid refinement, residual history and comparison against an independent solver.
4. Coil and free-boundary coupling with compatible boundary conditions.
5. Parameter continuation and recoverable nonconvergence behavior.

Use a worker or a separately validated WebAssembly kernel. An offline Python reference can generate benchmarks without adding Python downloads to the browser's critical path. FreeGS is a useful reference for equilibrium inputs, boundary treatment and solving, but its existence does not validate a port. [FreeGS: creating equilibria](https://freegs.readthedocs.io/en/latest/creating_equilibria.html).

Store the residual definition. A useful dimensionless diagnostic divides the maximum absolute equation residual by the sum of representative magnitudes of its terms, with a declared physical scale when all terms approach zero. Also report boundary error and the change on grid refinement. Small residual alone is insufficient if the boundary condition, units or source profiles are wrong.

## 13. Field lines, topology and probes

Field-line geometry solves:

$$
\frac{d\mathbf x}{ds}=\frac{\mathbf B(\mathbf x)}{\lVert\mathbf B(\mathbf x)\rVert}.
$$

Here `s` is arclength. It is not physical time or a particle velocity. Field-line and particle tracing are different calculations, a distinction made explicitly in Simsopt's tracing documentation. [Simsopt: field and particle tracing](https://simsopt.readthedocs.io/stable/tracing.html).

### 13.1 Tracer requirements

- Use an adaptive embedded integrator such as a tested Dormand–Prince 5(4) implementation.
- Work in scaled coordinates or use separate dimensional absolute and relative tolerances. Record both.
- Support tracing along and against the field, deterministic surface seeding and user-specified seed points.
- Stop on wall intersection, field-domain exit, field null, maximum arclength, step budget, cancellation or numerical failure.
- Store a termination reason and final accepted position for every line.
- Refine wall/plane crossings inside an integration step; joining sampled points is not enough for accurate event locations.
- Preserve unsimplified scientific coordinates. Any geometric simplification for display must be bounded and labelled in exports.

### 13.2 Poincaré sections

Use an explicitly selected plane, such as `phi=0 mod 2π`, and crossing direction. Track unwrapped angle and bracket crossings to prevent double-counting near the branch cut. Export `line_id`, crossing index, direction, `R_m`, `Z_m`, arclength and applicable flux values.

Show whether a result came from an axisymmetric field, a discrete coil field or an imported 3D field. Do not generate decorative magnetic islands by distorting a surface; islands must arise from the selected field and be supported by tracing.

### 13.3 Safety factor and probes

For a suitable nested flux surface, estimate signed winding from unwrapped toroidal advance over complete poloidal turns. Compare with the analytic fixture and imported `q` where definitions match. Report undefined or not applicable near the axis, separatrix, open lines or fields without the required surface structure.

A probe must expose position, coordinate system, field vector, field magnitude, model ID, domain status and available interpolation uncertainty. Camera position is not the probe position. Copying a probe returns machine-readable values with units.

## 14. Particle tracing and collision events

### 14.1 Equations and initial conditions

For a nonrelativistic test particle:

$$
\dot{\mathbf x}=\mathbf v,\qquad
m\dot{\mathbf v}=Q_s\left(\mathbf E+\mathbf v\times\mathbf B\right).
$$

Use `Qs` for species charge to avoid confusing it with safety factor `q`. Initial conditions contain position, mass, charge, energy, pitch, gyrophase and optional statistical weight. Construct a robust perpendicular basis even when the field is almost parallel to the nominal basis vector.

Store the distribution and sampling algorithm when generating ensembles. A set of attractive random tracks is not a thermal distribution. Seed reproducibility must include the random-number generator algorithm/version, not only an integer seed.

### 14.2 Nonrelativistic Boris kernel

With positions at integer steps and velocities at half steps:

$$
\begin{aligned}
\mathbf v^- &= \mathbf v^{n-1/2}+\frac{Q_s\Delta t}{2m}\mathbf E^n,\\
\mathbf t &= \frac{Q_s\Delta t}{2m}\mathbf B^n,\qquad
\mathbf s_B=\frac{2\mathbf t}{1+\mathbf t\cdot\mathbf t},\\
\mathbf v' &= \mathbf v^-+\mathbf v^-\times\mathbf t,\\
\mathbf v^+ &= \mathbf v^-+\mathbf v'\times\mathbf s_B,\\
\mathbf v^{n+1/2} &= \mathbf v^++\frac{Q_s\Delta t}{2m}\mathbf E^n,\\
\mathbf x^{n+1} &= \mathbf x^n+\Delta t\,\mathbf v^{n+1/2}.
\end{aligned}
$$

Initialize the half-step velocity consistently with the user's stated initial time. Derive diagnostic velocities at the appropriate time before comparing position/velocity invariants. PlasmaPy provides an inspectable reference implementation and SI interface. [PlasmaPy: particle-integrator implementation](https://docs.plasmapy.org/en/stable/_modules/plasmapy/simulation/particle_integrators.html).

Do not describe Boris as universally symplectic or exactly energy conserving for arbitrary fields. In the zero-electric-field rotation it preserves speed, while trajectory phase can still be wrong. The literature distinguishes its volume-preserving properties from stronger claims. [Ellison, Burby and Qin: analysis of the Boris algorithm](https://arxiv.org/html/1509.02863v1).

### 14.3 Accuracy and model selection

Use local gyrofrequency `Omega=abs(Qs) B/m`, gyroradius `rho=m v_perp/(abs(Qs) B)` and field/geometry scales to choose a timestep. Expose a convergence study rather than a single universal “accuracy” percentage.

For the uniform-field verification case use `Omega*dt <= 0.01`, run 100 gyroperiods, and test energy and phase independently. The Boris rotation per step is `2 atan(Omega*dt/2)`; at the bound above the predicted 100-period phase lag is about 0.00524 rad. A 0.01-rad phase acceptance target is therefore consistent with that fixture.

Relativistic energies require momentum evolution, `v=p/(gamma*m)`, and a separately verified relativistic pusher. Implement automatic applicability checks based on the requested error in the nonrelativistic approximation. Do not allow an unrestricted MeV electron input to run through a nonrelativistic kernel silently. A named full-orbit relativistic task can be added after its independent benchmarks pass.

Guiding-center tracing is an additional model, not a shortcut selected solely because the device is slow. Define its ordering assumptions, field derivatives, magnetic-moment convention and validity diagnostics. Compare against full orbits where the ordering is valid; expose breakdown when gyroradius is not small relative to relevant field/geometry scales.

### 14.4 Boundaries and interpretation

Intersect the physical wall representation, not the visually cutaway mesh. Refine collisions within the step, record hit position, incident energy, time and particle weight, then apply the selected absorbing or explicitly modeled boundary condition.

Distinguish wall loss, plasma-boundary crossing, field-domain exit, timeout and numerical failure. Collisionless survival over one observation interval is an orbit statistic; it is not energy confinement time, MHD stability or a fusion-gain measurement. Purely toroidal fields can have closed field lines while particles drift vertically. [Simsopt: particle drift and tracing models](https://simsopt.readthedocs.io/stable/tracing.html).

## 15. Plasma profiles and dimensional diagnostics

Accept uniform profiles and tabulated profiles with a declared coordinate. For fully specified species and an isotropic thermal model:

$$
p=n_e k_BT_e+\sum_i n_i k_BT_i,\qquad
\beta(\mathbf x)=\frac{2\mu_0p(\mathbf x)}{B(\mathbf x)^2}.
$$

If temperature is entered in eV, use `kB*T = e*T_eV`, not `kB*T_eV`. Enforce or explicitly model charge balance; for a fully ionized proton–boron mixture without other species, `ne=np+5*nB`.

Define every averaged beta: a volume average of local beta is not generally equal to `2*mu0*average(p)/average(B²)`. Label toroidal/poloidal beta separately and identify the denominator. Handle zero fields as undefined for beta, not infinite dashboard values.

Calculate volume integrals using the appropriate Jacobian. In axisymmetry:

$$
\int_V f\,dV=2\pi\int_A f(R,Z)R\,dR\,dZ.
$$

For circular geometry, use the analytic volume as a quadrature test. For shaped boundaries, use the actual accepted domain and demonstrate refinement. A visible surface mesh may be coarsened for graphics while integration uses its own converged representation.

Required outputs are local and integrated pressure, species inventory, applicable thermal-energy inventory, beta with definition, profile coverage and missing-data status. For isotropic nonrelativistic ideal thermal species, the internal-energy density is `3p/2`; use appropriate distribution moments or a relativistic equation of state outside that model.

## 16. Proton–boron source, spectra and energy accounting

### 16.1 Named nuclear data

Offer explicit selectable evaluations rather than one anonymous “accurate fusion formula.”

| Source | Appropriate implementation use | Limits to preserve |
|---|---|---|
| Sikora–Weller, 2016 | Versioned reaction cross-section/reactivity evaluation and reference comparison | Incident proton energy, reaction-channel meaning and alpha-yield normalization must be retained |
| Tentori–Belloni, 2023 | Updated named analytic evaluation and reactivity comparison | Published thermal approximation is defined for 10–500 keV; verify coefficients and boundaries before coding |
| Mazzucconi et al., 2025 | Experimental comparison after numerical data are obtained | Measured proton energies are 0.34–4.73 MeV; the numerical datasets are available on request, not verified here as a public download |
| IAEA EXFOR | Experimental-data discovery and import | Record actual entry/subentry and revision; no particular p–11B entry ID was verified for this specification |

Sikora–Weller distinguishes reaction cross section from measured alpha production and applies the final-state multiplicity correction. [Sikora and Weller, 2016](https://link.springer.com/article/10.1007/s10894-016-0069-y). The 2023 authors' project publication record states the thermal fit domain. [Tentori and Belloni: publication record](https://www.ca-probono.eu/index.php/outcome/peer-reviewed-papers/100-revisiting-p-11b-fusion-cross-section-and-reactivity,-and-their-analytic-approximations). The 2025 paper documents its measurement range and data-access conditions. [Mazzucconi et al., 2025](https://link.springer.com/article/10.1140/epja/s10050-025-01589-3). EXFOR is a compilation of experimental data and descriptions, not automatically a recommended evaluation. [IAEA: EXFOR](https://www.iaea.org/resources/databases/experimental-nuclear-reaction-data).

Dataset disagreement is not automatically an uncertainty confidence interval. Keep experimental errors, evaluation/model differences and numerical integration error as separate quantities.

### 16.2 Energy frame and reactivity

For a projectile proton and stationary boron target in nonrelativistic kinematics:

$$
E_{\rm cm}=\frac{m_B}{m_p+m_B}E_{p,\rm lab}.
$$

Use actual documented masses in the implementation; `11/12` is only a mass-number approximation. A cross-section table must state its frame. Convert its energy axis consistently before integrating; do not convert a table twice.

For a common-temperature Maxwellian pair, with `tau=kB*T` in joules and reduced mass `mu`:

$$
\langle\sigma v\rangle
=\sqrt{\frac{8}{\pi\mu}}\,\tau^{-3/2}
\int_0^\infty \sigma(E)E\exp(-E/\tau)\,dE.
$$

The energy variable is relative center-of-mass energy. Implement adaptive quadrature or a separately validated published fit, with unit tests and a declared integration domain. The source evaluation discusses Maxwellian rates; the browser implementation still requires its own numerical verification. [Sikora and Weller: reaction-rate evaluation](https://link.springer.com/article/10.1007/s10894-016-0069-y).

For isotropic Maxwellians with different species temperatures and no relative drift, use the correctly derived relative thermal scale `tau_rel = mu*(tau_p/mp + tau_B/mB)`. Beam–thermal and arbitrary nonthermal modes require their own normalized relative-velocity distribution; do not reuse a single temperature slider as their definition.

For finite tabulated data, do not silently set unmeasured tails to zero and report a full-domain rate. Report the supported-domain integral and its scope, or use a named documented continuation model with separate sensitivity analysis. Resolve narrow resonances through integration refinement; smooth-looking interpolation is not sufficient.

### 16.3 Rate and multiplicity

For different reactants:

$$
\mathcal R=n_p n_B\langle\sigma v\rangle,
\qquad S_\alpha=3\mathcal R,
\qquad P_{\rm fus}=\int_V\mathcal R Q_{\rm reaction}\,dV.
$$

There is no identical-reactant `1/2` factor for p–11B. Multiply reaction rate by total reaction energy once. Do not multiply nuclear power by three again because three alphas are produced.

The NRL formulary lists the channel as `p + 11B → 3 alpha + 8.7 MeV`, using rounded energy. Use that only as a labelled rounded preset; obtain a sourced mass-based Q if more precision is needed. [NRL Plasma Formulary 2023, fusion section](https://www.nrl.navy.mil/Portals/38/PDF%20Files/NRL_Plasma_Formulary_2023.pdf).

Three equal `Q/3` alpha energies are an illustrative monoenergetic preset. Physical event sampling needs an explicit spectrum/branching model, the incident kinetic energy, a declared frame and momentum/energy conservation. A marginal alpha spectrum alone does not specify the full correlated three-body final state. Provide the simplified preset honestly while developing the physically supported event sampler.

### 16.4 Radiation and power balance

Include a transparent baseline radiation mode and a validated higher-temperature model. The NRL nonrelativistic expression converts to SI as:

$$
p_{\rm Br}=1.69\times10^{-38}
n_e\sqrt{T_{e,\rm eV}}\sum_i Z_i^2 n_i
\quad[\mathrm{W/m^3}],
$$

with densities in `m⁻³`. The original uses `1.69×10⁻³²`, densities in `cm⁻³`, and power per `cm³`; mixing these conventions produces a large error. This baseline is not a complete high-temperature loss model. [NRL Plasma Formulary 2023, radiation section](https://www.nrl.navy.mil/Portals/38/PDF%20Files/NRL_Plasma_Formulary_2023.pdf).

For high-temperature research mode, implement and verify the selected electron–ion/electron–electron and relativistic corrections. Xie's paper supplies relevant fitting approaches; a reported fit error against a theoretical reference is not total experimental uncertainty. Audit redistribution terms before copying associated software. [Xie, 2024: bremsstrahlung fitting](https://arxiv.org/html/2404.11540v2).

Build an explicit energy ledger:

| Quantity | Required definition |
|---|---|
| Nuclear source | Reaction-rate integral times reaction Q |
| Incident kinetic energy | Separate from nuclear Q when event products or beams are modeled |
| Deposited alpha heating | Energy deposited in the plasma, from an explicit deposition model |
| Escaping alpha energy | Energy leaving the plasma, with destination and collection assumptions |
| Radiation | Named models, domain and species/temperature assumptions |
| Transport and particle losses | Separate modeled terms or explicitly unavailable quantities |
| External heating | Power delivered to plasma; distinguish electrical input efficiency |
| Internal species exchange | Equal and opposite terms in species equations; cancels in the total plasma balance |
| Conversion | Separate downstream model, with energy that is actually available to it |
| Stored energy change | Consistent inventory and time interval |

Never count the same alpha energy as both deposited plasma heating and directly exported electricity. Cold electrons cannot be an unexplained control that lowers radiation without accounting for the power needed to maintain the distribution. Liu et al. illustrate how conclusions depend on species exchange, distribution assumptions and recirculating power. [Liu et al., 2025: non-thermonuclear steady-state analysis](https://pubs.aip.org/aip/pop/article-pdf/doi/10.1063/5.0218316/20327489/012101_1_5.0218316.pdf).

Display plasma gain or electrical net power only when its numerator, denominator, energy pathways and missing terms are explicitly defined. Otherwise display the calculated source and loss terms individually. A field/particle visualization alone has no basis for a reactor-gain result.

## 17. Import formats, configuration schema and data provenance

### 17.1 Supported formats

| Format | Initial supported use | Required metadata / checks |
|---|---|---|
| HBF JSON configuration | Exact setup and task reconstruction | Schema version, model version, units and input relationships |
| CSV field samples | Cartesian or cylindrical field points | Column mapping, basis, coordinates, units, grid structure and domain |
| CSV profiles | Density, temperature and other radial profiles | Species, profile coordinate, units, ordering and coverage |
| CSV cross sections | Evaluated or experimental reaction data | Reaction, energy frame, cross-section meaning, units, errors and provenance |
| G-EQDSK | Axisymmetric equilibrium input | Parser subset, complete convention conversion and profile/grid validation |
| HBF run package | Reopen and compare a completed run | Manifest, hashes, configuration, arrays, statuses and source records |
| External solver output | Future adapters or offline conversion | Documented mapping into the canonical schema; preserve source format/version |

HDF5, NetCDF and large external-solver formats need explicit adapters or a supplied offline converter. Do not advertise support because a file extension appears in the picker. A converter must preserve original metadata and report every omitted field.

### 17.2 Example configuration contract

This is a proposed schema example, not a configuration extracted from the current site.

```json
{
  "schemaVersion": "1.0.0",
  "model": {
    "id": "analytic-circular-v1",
    "implementationVersion": "1.0.0",
    "classification": "prescribed-analytic-field"
  },
  "task": "field-lines",
  "coordinates": {
    "cartesian": "right-handed-z-up",
    "toroidalAngle": "atan2(y,x)",
    "poloidalAngle": "atan2(Z,R-R0)",
    "psiDefinition": "poloidal-flux-per-radian",
    "poloidalFieldConvention": "grad-psi-cross-grad-phi"
  },
  "geometry": {
    "majorRadius_m": 2.0,
    "plasmaMinorRadius_m": 0.5,
    "wallInnerMinorRadius_m": 0.65,
    "wallThickness_m": 0.05
  },
  "field": {
    "B0_T": 2.0,
    "qAxis": 2.0
  },
  "seeding": {
    "kind": "explicit-cartesian",
    "points_m": [[2.25, 0.0, 0.0], [2.4, 0.0, 0.0]]
  },
  "numerics": {
    "integrator": "dormand-prince-54",
    "relativeTolerance": 1e-8,
    "absolutePositionTolerance_m": 1e-9,
    "maximumArclength_m": 200.0,
    "maximumAcceptedStepsPerLine": 200000
  },
  "sources": [],
  "view": {
    "cameraPreset": "reference-isometric",
    "showCoils": true,
    "showPlasma": true,
    "showFieldLines": true,
    "cutawayEnabled": true,
    "quality": "balanced"
  }
}
```

Implement a strict schema with model-specific branches. Unknown fields must produce a migration/compatibility response, not silently change behavior. Generate a separate result record; never write solver outputs back into physical input fields.

### 17.3 Dataset record

Every dataset needs:

- Human title, authors/organization, publication or revision date and source URL/DOI.
- Dataset/version identifiers and the exact source-file checksum.
- Reaction/channel or field/profile quantity definitions, axis definitions and units.
- Experimental, evaluated, synthetic or simulation-generated classification.
- Energy frame, flux convention, sign conventions and species where applicable.
- Valid domain, missing-value representation, uncertainties and covariance availability.
- Licence/access conditions and any third-party restrictions.
- Transformations, interpolation choice, conversion-software version and transformed checksum.

Keep original uncertainty columns. If a graph must be digitized because no numeric table is available, label it as digitized, retain digitization uncertainty, document the process and compare against the figure; do not represent it as author-supplied raw data.

### 17.4 Parser and resource integrity

Parse user data locally by default and state that behavior in the import panel. No hidden upload is required for the static lab.

Validate content as well as extensions. Bound row counts, grid dimensions, recursion depth and decompressed size before allocating arrays. Reject non-finite numbers, inconsistent shapes, duplicate axes and out-of-range references. Do not evaluate formulas or executable expressions from imported files.

Preserve correct numerical CSV output while neutralizing untrusted text fields that could be interpreted as spreadsheet formulas. Quote handling alone is not sufficient protection. Keep canonical JSON/raw numeric arrays available so spreadsheet-oriented text sanitization does not corrupt data. [OWASP: CSV injection](https://owasp.org/www-community/attacks/CSV_Injection).

## 18. Results, comparison and research tools

### 18.1 Result surfaces

The results dock opens with the quantities relevant to the completed task, not a wall of unrelated metrics.

| Task | Main view | Numeric export |
|---|---|---|
| Field map | R–Z or selected-plane scalar map and vector probe | Coordinate/basis-aware field table |
| Field lines | 3D trajectories, selected-line details and termination summary | Line coordinates, arclength and events |
| Poincaré | R–Z crossings, seed groups and winding interpretation | Crossing table with direction and index |
| Particle orbits | 3D trajectories plus energy/phase or selected invariant diagnostics | Time, position, velocity/momentum, weight and events |
| Profiles | Density, temperature, pressure and applicable beta | Profiles with original coordinate and converted coordinate |
| Fusion source | Selected evaluation, source profile and domain status | Reactivity, reaction rate, alpha rate and source power |
| Energy ledger | Defined source/loss terms and residual | Term values, units, assumptions and unavailable terms |
| Equilibrium | Flux contours, boundary, axis and residual history | Flux grid, profiles and diagnostic record |

Each view needs a title, quantity, units, scale definition, current run identity, model version and a table toggle. Missing data stays missing. Logarithmic views cannot silently drop zero or negative samples; report how they are treated.

Allow scientific notation, configurable displayed precision and full-precision copying. A rounded label must not replace the underlying value.

### 18.2 Comparisons and parameter sweeps

Save immutable snapshots. The comparison table first shows changed inputs, datasets and solver settings, then compatible output differences. Use synchronized camera views only when scale and orientation match; give the option to link cameras without changing the physics.

For sweeps, specify the varied input, grid/list of values, controlled inputs, seed behavior, computational budget and comparison metric. Show failures as failed sweep points. Never interpolate through failed points and imply a complete curve.

Provide absolute differences and relative differences with an explicit near-zero denominator policy. Avoid percentage changes when the reference is zero or undefined.

Useful research tools include probe sampling, a section-plane editor, seeded surfaces, field-line selection, orbit event filtering, convergence comparison, parameter sensitivity, model/evaluation comparison and a reproducible export. Each tool must have an observable input/output contract.

### 18.3 Integration with the wider HBF labs

Reuse a common data contract where Torus exchanges information with Nuclear Data, FusionSim, AlphaTrack or DirectConvert:

- Nuclear evaluations carry identical dataset IDs, units and versions between modules.
- Particle transfers carry source coordinates, species, energies, weights, frames and observation time.
- Direct conversion receives a defined escaping-particle distribution or an explicit scenario, not the total nuclear source counted a second time.
- Imported results retain the producing module and solver version.

Resolve actual existing routes and contracts during source inspection. These integration points are required development tasks, not claims that current modules already expose these interfaces.

## 19. Numerical quality, uncertainty and interpretation

Display three separate quality dimensions:

1. **Numerical error:** timestep, integration, interpolation, quadrature and mesh error.
2. **Input uncertainty:** experimental errors, uncertain geometry/currents/profiles and covariance.
3. **Model uncertainty:** omitted effects, chosen evaluation and applicability limits.

A low solver residual does not make an uncertain input exact. A difference between two models is not automatically a 95% confidence interval.

Implement convergence studies by varying one numerical resolution at a time while preserving physical inputs. For input propagation, retain parameter distributions and correlations; if independence is assumed, state it. Report sampling error separately and retain the random generator and seed.

For orbit-loss fractions, define the observation duration, weighting and denominator. Show statistical intervals only when their sampling assumptions apply. Do not treat a deterministic set of hand-picked particles as an unbiased population sample.

Use provenance states such as `analytic fixture`, `computed from prescribed field`, `imported equilibrium`, `experimental dataset` and `model-based estimate`. These describe the quantity, not a certification badge. Attach a specific benchmark record before claiming that a particular kernel version passed its tests.

## 20. Export and reproduction package

### 20.1 Required package contents

| File | Required contents |
|---|---|
| `manifest.json` | Schema, application/kernel versions, run ID, input hash, constants release, file inventory and status |
| `configuration.json` | Full immutable scientific setup and separately nested view settings |
| `results.json` | Summaries, definitions, units, status, termination counts and diagnostic references |
| `data/*.csv` | Full-precision numeric tables with an accompanying schema |
| `data/*.bin` when needed | Typed arrays with dtype, byte order, shape and units in metadata |
| `sources.json` | Dataset/evaluation provenance, transformations, licences and hashes |
| `diagnostics.json` | Tolerances, step counts, convergence information and available error estimates |
| `events.csv` | Particle/line event positions, times or arclengths and reasons |
| `view.json` | Camera, visible layers, cut plane, color scale and display sampling |
| `README.md` | Exact reproduction procedure, assumptions and expected numerical comparison |
| `checksums.sha256` | Checksums for package payloads, excluding the checksum file itself |
| `preview.png` | Optional rendered view, labelled with the run and model |

Include source bytes when redistribution is permitted. Otherwise include the resolvable identifiers and precise retrieval requirements. Clearly report that fully offline reproduction requires the missing source file.

The package design applies the FAIR emphasis on metadata, provenance, explicit reuse terms and domain standards. A ZIP alone is not a FAIR certification or a proof of reproducibility. [GO FAIR Foundation: guiding principles](https://www.gofair.foundation/fair-principles).

### 20.2 Identity and deterministic reconstruction

Define a canonical JSON serialization for scientific inputs. Normalize units, object-key order and representations before hashing. The input hash includes model/kernel version, physical setup, solver settings and source checksums; exclude camera, theme and timestamps. Record view state separately.

Avoid checksum recursion: the manifest contains payload hashes but not its own hash; `checksums.sha256` can include the finalized manifest and all other payloads, excluding itself.

Every worker message carries `runId`, `inputHash` and `kernelVersion`. Reject stale responses. Preserve the source result for old runs even if their configuration is no longer editable by the current schema.

For deterministic algorithms, the same seed and inputs should reproduce results within declared numerical tolerances on supported platforms. Do not promise bitwise identity across different engines, GPU implementations or solver versions without testing it. Store the actual environment used.

### 20.3 Image export

Export the render at a user-selected resolution, with optional axes, legend and run annotation. Use a controlled render target or a deliberately timed capture; do not leave expensive preserved drawing buffers enabled for the whole session merely to support screenshots.

An exported scientific image must identify the model, quantity/color scale, relevant units and run. The camera image is separate from the reproduction package and cannot replace numerical data.

## 21. First-load stability, cancellation and recovery

This section specifically prevents the kind of first-visit visual correction or flash previously reported in the project context. The current source was not inspected, so the items below are failure-prevention requirements rather than confirmed diagnoses of the existing site.

### 21.1 Stable startup sequence

1. Deliver critical layout/theme CSS with the HTML. Reserve header, sidebar and viewport space before JavaScript initializes.
2. Establish one authoritative initial configuration. Validate URL, stored and preset inputs using an explicit precedence rule.
3. Show a neutral loading surface or a poster rendered from the actual default 3D scene. Do not flash a different theme, default geometry or arbitrary result values.
4. Create the renderer after the viewport has nonzero dimensions. Set its background and camera before the first frame.
5. Load the initial assets, material textures and environment. Initialize decoder paths and test required capabilities.
6. Precompile the first visible materials once lighting/environment are configured; `compileAsync` can reduce first-use shader stalls. It is not a guarantee that all later materials or GPU uploads are prepared. [Three.js: WebGLRenderer](https://threejs.org/docs/pages/WebGLRenderer.html).
7. Render a complete frame behind the loading surface, then reveal it without changing layout dimensions.
8. Load optional detail and advanced panels afterward. Do not change the scientific preset as those assets arrive.

Do not hide the entire document while waiting for 3D. Navigation, explanatory text and scientific forms should remain useful. Do not use an arbitrary timeout as a substitute for an actual readiness condition.

### 21.2 Common causes and required fixes

| Failure | Required fix |
|---|---|
| Bright/default-theme flash | Apply the chosen theme before first paint; load critical CSS synchronously |
| Torus jumps in size | Initialize and observe the real container size; fit only after geometry bounds are available |
| Incorrect field lines briefly appear | No demo lines in the current-run layer; attach overlays to the matching input hash |
| Old results return after a new run | Validate message run identity and dispose stale resources |
| Exported preset later corrects itself | Resolve stored/query/default configuration once before scientific preview |
| Transparent walls flicker | Limit nested transparent layers; test sorting, depth and cutaway strategy from multiple angles |
| Controls freeze during solve | Worker execution and chunked progress/cancellation checks |
| Worker Cancel never works | Yield between bounded work chunks; a synchronous endless worker loop cannot process cancel messages |
| GPU resources accumulate | Dispose textures, geometries, targets, listeners and worker references on teardown |
| Missing module returns HTML | Correct static-route handling and MIME types; missing assets must remain real errors |

### 21.3 Cancellation and context recovery

Check cancellation between bounded numerical batches. Prefer a clean partial checkpoint where supported; otherwise terminate the worker and record that no complete result was produced. A proposed interaction target is acknowledgement within 250 ms under the agreed workload, measured during testing.

On WebGL context loss, preserve scientific configuration and completed results, display a recovery action and rebuild the scene when the context is restored. Test this using the browser's context-loss mechanism. [MDN: WebGL context loss](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event).

If 3D is unavailable, retain the numerical forms, results tables, two-dimensional sections and export. A graphics limitation must not be presented as a physics failure.

## 22. Performance budgets and quality controls

These are proposed acceptance budgets. Measure them on named devices, browser versions and network profiles; do not present them as observed performance.

The current Three.js `WebGLRenderer` requires WebGL2. Detect that capability before initializing the 3D view, pin the tested Three.js release, and retain the two-dimensional and numerical workflow when WebGL2 is unavailable. [Three.js: WebGLRenderer](https://threejs.org/docs/pages/WebGLRenderer.html).

| Area | Initial target | Measurement |
|---|---|---|
| Application shell | Under 300 KiB compressed for the initial shell, excluding lazy 3D/data payloads | Build artifact inventory and transferred bytes |
| Initial 3D payload | Approximately 5 MiB or less for the default view | Actual compressed transfer and decoder overhead |
| Shell responsiveness | LCP ≤2.5 s, INP ≤200 ms, CLS ≤0.1 as user-experience targets | Field measurements at the 75th percentile where available; lab measurements labelled separately |
| First meaningful 3D frame | Separate custom timing target: ≤5 s under the agreed reference profile | Mark after a complete usable scene, not after an empty canvas |
| Balanced rendering | Aim for 60 fps on the reference desktop and ≥30 fps on the selected lower-tier device | Frame-time distribution during orbit and active calculation |
| Draw calls | Start near or below 120 for the default scene | Renderer instrumentation; justify exceptions |
| Visible triangles | Start around 200k or less in balanced mode | Measured scene inventory, excluding hidden assets |
| Drawing-buffer scale | Adaptive cap around DPR 1–1.5 in balanced mode | Actual framebuffer resolution and frame time |
| Scientific publication rate | Roughly 5–10 UI updates per second during a run | Avoid re-rendering tables for every integration step |
| Resource lifecycle | No persistent growth across repeated open/run/reset/close cycles | Heap/GPU resource trend, not one isolated snapshot |

The Core Web Vitals thresholds are published guidance; the asset sizes, frame rates and 3D timings above are project choices. Canvas readiness needs its own measurement because ordinary page metrics do not establish that the scientific scene is usable. [web.dev: Web Vitals](https://web.dev/articles/vitals).

Use instancing for repeated parts that share geometry and materials. [Three.js: InstancedMesh](https://threejs.org/docs/pages/InstancedMesh.html). Compress suitable textures, detect supported formats before loading KTX2, and ship matching transcoders. [Three.js: KTX2Loader](https://threejs.org/docs/pages/KTX2Loader.html).

Create Low, Balanced and High appearance presets. Change reflections, shadows, line display density, antialiasing, visual geometry detail and framebuffer size. Do not change physical seed count, timestep, grid resolution or solver tolerance through a graphics-quality preset.

Resource limits vary across devices. Bound allocations, handle context loss and avoid unnecessary blocking GPU calls. [MDN: WebGL best practices](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices).

For large imports, estimate memory before allocating: scientific arrays, interpolation caches, worker transfer/copies, result storage and GPU display buffers all count. Offer reduced display detail, chunked import or an offline conversion route while preserving the original scientific dataset. Reject impossible workloads with a concrete explanation rather than crashing the page.

## 23. Accessibility and scientific task equivalence

Target WCAG 2.2 AA for the complete supported workflows. Compliance requires testing the implementation, not adding an accessibility label. [W3C: WCAG 2.2](https://www.w3.org/TR/WCAG22/).

| Interaction | Required alternative and verification |
|---|---|
| Orbit/pan/zoom | Keyboard controls plus clickable directional/zoom controls and named camera presets |
| Slider adjustment | Editable numeric field, step buttons where useful, keyboard range support and persistent unit |
| 3D object selection | Searchable/list-based selection of coils, lines, particles and probes |
| Probe placement | Coordinate entry as an alternative to pointing in 3D |
| Section-plane dragging | Numeric plane position/angle and click-based controls |
| Plot inspection | DOM table with units, selection state and copy/export actions |
| Color coding | Legend and non-color distinction, such as line style or selected-item outline |
| Run status | Text state, progress semantics and restrained live announcements |
| Modal/panel | Predictable focus placement, close control and focus return |
| Motion | Pause playback, reduced-motion behavior and no compulsory auto-orbit |

Keyboard support and a single-pointer alternative to dragging are separate requirements; providing keyboard orbit alone does not resolve every dragging criterion. [W3C: keyboard operation](https://www.w3.org/WAI/WCAG22/Understanding/keyboard.html), [W3C: dragging movements](https://www.w3.org/WAI/WCAG22/Understanding/dragging-movements.html).

Use at least 24 × 24 CSS px targets or meet the criterion's stated exceptions; aim for 44 × 44 px on important touch controls as a product target. [W3C: minimum target size](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html). Meaningful control boundaries and graphical cues need sufficient contrast; a decorative low-contrast divider is not a usable focus indicator. [W3C: non-text contrast](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html).

Announce run start, completion, cancellation and actionable error once. Do not stream every simulation tick into a live region. [W3C: status messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html). Provide pause/stop controls for relevant automatically moving or updating content and respect reduced-motion preferences. [W3C: pause, stop, hide](https://www.w3.org/WAI/WCAG21/Understanding/pause-stop-hide.html).

Test the entire first-run, import, compare and export journeys with keyboard-only input and at least one desktop screen reader. Keep a meaningful DOM summary of the canvas and its selected object. Do not attempt to expose thousands of particles as thousands of focusable elements.

## 24. Static hosting, migration and deployment

### 24.1 Build and hosting contract

Deliver both the editable source project and its built static output. The host serves HTML, CSS, JavaScript modules, workers, GLB, textures, WASM decoders and data files. A Node server or Python interpreter is not required on Apache for the baseline lab.

Pin package versions and the lockfile. Bundle assets and dependencies locally instead of relying on unversioned CDN URLs. Use a build-time public base path and verify every worker/decoder/asset URL under the actual deployed subdirectory.

### 24.2 Route handling

Prefer a real lab directory with its own entry document. Existing files and directories must resolve before any surrounding SPA fallback. Unknown lab assets must return a real 404, not the main site's HTML with status 200.

Merge route rules into the actual server configuration after inspecting it; do not overwrite the entire existing `.htaccess` with a generic example. Apache documents the relevant mapping and rewrite behavior, while host permissions determine which directives are available. [Apache: URL remapping](https://httpd.apache.org/docs/2.4/rewrite/remapping.html), [Apache: configuration in .htaccess](https://httpd.apache.org/docs/current/howto/htaccess.html).

Check JavaScript, WASM, JSON, GLB and texture response content types. Verify worker execution and decoder fetches from the deployed path. Test direct links, trailing slashes, refresh, nested URLs and the parent site's navigation.

### 24.3 Cache and update behavior

Use content-hashed filenames for immutable assets. Keep the HTML entry and release manifest revalidatable. Deploy a complete new asset set before switching its entry document, and preserve the previous release for rollback.

If an existing service worker is present, inspect its cache/version strategy. Do not introduce one merely to hide broken network requests. Test that an old cached entry cannot load a mixture of incompatible kernels and datasets.

### 24.4 Integration sequence

1. Inventory existing Torus routes, scripts, global CSS, datasets and cross-lab contracts.
2. Record current public input/output behavior and saved-state formats.
3. Add the new module in an isolated route or development build with scoped styles and one lifecycle owner.
4. Implement migration of genuinely supported saved configurations; reject incompatible ones clearly.
5. Compare the new view with the selected image and complete the scientific acceptance tests.
6. Package release files, version information, benchmark report and rollback instructions.
7. Test the actual hosting behavior before replacing the public route.

Do not report deployment as complete from a local screenshot or successful ZIP creation alone.

## 25. Verification plan and acceptance tests

All numerical thresholds below are proposed engineering gates for the specified fixtures. They are not universal physics-validity thresholds, experimental uncertainties, or reported test results for the current HBF application.

### 25.1 Scientific verification matrix

| ID | Fixture / operation | Required acceptance evidence |
|---|---|---|
| NUM-01 | Unit conversions | eV/J, keV/eV, barn/m², cm⁻³/m⁻³ and time conversions round-trip within Float64 rounding; imported units never applied twice |
| NUM-02 | Coordinate conversion | Cartesian/cylindrical round trip, all quadrants, angle branch cuts and render transform preserve handedness |
| NUM-03 | Analytic field samples | Section 10 component values agree within `1e-12 T` at the listed non-singular points |
| NUM-04 | Analytic geometry | Circular volume and surface area match the closed-form expressions; mesh/quadrature refinement approaches them |
| NUM-05 | Analytic flux conservation | Along specified off-axis field lines, maximum flux drift normalized to edge flux is below `1e-7` with the accepted solver settings |
| NUM-06 | Winding estimate | At selected off-axis surfaces, relative winding error versus Section 10 is below `1e-4`; axis result is explicitly undefined as a numerical winding |
| NUM-07 | Field null/domain | Zero-field normalization and out-of-domain evaluation return structured stops, never NaN trajectories |
| NUM-08 | Coil field | Circular-loop axis field relative error below `1e-6` after quadrature refinement; correct sign, current scaling and superposition |
| NUM-09 | Coil interpolation | Off-grid comparison against direct evaluation; measured interpolation/divergence quality retained with the cache |
| NUM-10 | G-EQDSK conversion | At least two supported convention fixtures test handedness, flux sign, `2π`, profile derivatives and canonical reconstruction |
| NUM-11 | Manufactured GS problem | Converged solver residual and expected spatial order demonstrated; error falls under grid refinement before roundoff dominates |
| NUM-12 | Cross-code equilibrium | Same boundary/profile problem compared with an independent solver; declared tolerances for flux, axis and selected profile quantities |
| NUM-13 | Poincaré events | Known crossing count, direction and positions; no duplicate crossings at angle wrap or a seed on the plane |
| NUM-14 | Uniform-B orbit | `E=0`, 100 gyroperiods, `Omega*dt<=0.01`: relative kinetic-energy drift below `1e-9` and gyrophase error below `0.01 rad`, with consistent initialization |
| NUM-15 | Charge sign / E×B | Correct gyration direction; gyro-averaged drift approaches `E×B/B²` under timestep refinement in a nonrelativistic uniform-field fixture |
| NUM-16 | Particle convergence | Halving timestep gives approximately fourfold leading trajectory-error reduction for the smooth Boris fixture before other errors dominate |
| NUM-17 | Particle boundary events | Wall-hit time/location converges; physical wall hit, plasma exit and data-domain exit remain distinct |
| NUM-18 | Relativistic / guiding-center modes | Separate applicability checks and independent benchmark evidence before exposing either mode as supported |
| NUM-19 | Reactivity integrator | For a synthetic constant cross section, recover `sigma0*sqrt(8*tau/(pi*mu))`; resolve selected finite-domain and resonance tests |
| NUM-20 | Nuclear data semantics | Lab/CM conversion, channel meaning and alpha-production versus reaction-cross-section cases are tested |
| NUM-21 | Reaction accounting | Zero reactant density gives zero reaction source; alpha rate equals three times reaction rate; total reaction Q is applied once |
| NUM-22 | Radiation units | Original NRL cm-based expression and SI form agree on the same synthetic inputs; eV/keV temperature conversion is explicit |
| NUM-23 | Profile integration | Constant profiles recover analytic volume results; spatially varying profiles show quadrature convergence |
| NUM-24 | Energy inventory | Each transfer has a unique source/destination; species exchange cancels in total balance; deposition and conversion do not double-count energy |
| NUM-25 | Reproduction | Export/import preserves physical inputs, source hashes and numeric results within the declared same-version tolerance |

The constant-cross-section case is a numerical integration test, not a p–11B data model. Use it to isolate kernel errors from nuclear-data uncertainty.

### 25.2 UI, graphics and reliability matrix

| ID | Required scenario | Pass condition |
|---|---|---|
| UX-01 | Reference view at 1536 × 1024 | Header/sidebar proportions, dominant torus, material direction, cutaway and camera toolbar match the selected visual intent |
| UX-02 | Scientific control edit | Numeric field and slider agree; unit/meaning remains visible; run configuration contains the intended value |
| UX-03 | Appearance change | Input hash and numerical outputs do not change |
| UX-04 | Physical edit after a run | Results become stale; no new geometry is combined with old field/particle overlays without an explicit previous-run context |
| UX-05 | Rapid repeated runs | Only the active run can publish into the current results view |
| UX-06 | Cancel / restart | Responsive cancellation, correct final status and no partial result labelled complete |
| UX-07 | Failed import | Actionable field/row error; the previous valid project remains recoverable |
| UX-08 | Fresh slow load | No theme flash, incorrect default values, layout jump or premature trajectory layer |
| UX-09 | Asset/worker/data 404 | Specific recovery message; numerical results are never substituted with demo data |
| UX-10 | Context loss / no WebGL2 | Preserved results; graphics recovery or usable two-dimensional/numeric workflow |
| UX-11 | Keyboard / click-only | Complete first-run, probe, compare and export journeys without dragging |
| UX-12 | Screen reader | Input units, errors, selected object and run status are understandable; no excessive live announcements |
| UX-13 | Mobile / zoom | Reflowing forms, reachable action controls and usable results at target widths/zoom |
| UX-14 | Transparent vessel | No major self-occlusion/sorting artifacts through all camera presets and orbit angles |
| UX-15 | Repeated lifecycle | No duplicate animation loops/listeners or persistent resource growth |
| UX-16 | Image/data export | Correct selected run, labels and file contents; exported image is not confused with a numerical package |
| UX-17 | Hosted route | Direct navigation, refresh, subdirectory assets, workers, decoders and cross-lab links work on the intended host |
| UX-18 | Release update | No mixed kernel/data versions; previous release can be restored |

For the reference comparison, inspect side-by-side captures at the same viewport and camera state. Judge spatial layout, geometry, materials and readability rather than claiming scientific correctness from pixel similarity. A user-facing product release requires both visual and numerical acceptance.

### 25.3 Test evidence format

Each test record needs its ID, application/kernel version, input fixture hash, reference calculation/source, tolerance, measured error, environment, pass/fail and timestamp. Keep numerical oracle code independent from the kernel under test. A test that computes expected values using the same implementation cannot independently verify that implementation.

Run focused checks during development. Broaden testing when a changed shared kernel, parser, renderer or deployment rule creates a concrete regression risk. Resolve failures before marking the associated capability complete.

## 26. Ordered development backlog

The sequence below is dependency-based. The document does not assign unsupported calendar estimates or claim completion of any phase.

| Work item | Owner discipline | Dependencies | Completion condition |
|---|---|---|---|
| DEV-01: existing-source and route inventory | Frontend / deployment | Existing project access | Actual routes, lifecycle, datasets and compatibility needs documented |
| DEV-02: scientific conventions and schemas | Numerical / data | This specification | Units, field convention, schemas and fixture inputs frozen and reviewed |
| DEV-03: reference layout and responsive shell | UI / frontend | DEV-01 | Functional forms and stable layout at reference and narrow widths |
| DEV-04: parametric geometry and asset production | 3D / numerical | DEV-02 | Display assembly and physical boundaries share a documented geometry source |
| DEV-05: renderer, camera and cutaway | 3D / frontend | DEV-03, DEV-04 | Reference-like render with functioning layers, camera presets and disposal |
| DEV-06: worker/state protocol | Frontend / numerical | DEV-02, DEV-03 | Run isolation, progress, cancellation and stale-state behavior tested |
| DEV-07: analytic field and geometry kernels | Numerical | DEV-02 | NUM-01 through NUM-04 pass |
| DEV-08: field-line integrator and probes | Numerical / UI | DEV-06, DEV-07 | NUM-05 through NUM-07 plus numeric probe workflow pass |
| DEV-09: Poincaré and winding diagnostics | Numerical / plots | DEV-08 | NUM-06 and NUM-13 pass with exported crossing data |
| DEV-10: coil editor and direct field kernel | Numerical / 3D | DEV-02, DEV-04, DEV-06 | NUM-08 passes and selected coils map to real current records |
| DEV-11: field caching/interpolation | Numerical | DEV-10 | NUM-09 passes and cache identity/error metadata are retained |
| DEV-12: canonical import parsers | Data / frontend | DEV-02, DEV-06 | Valid/invalid CSV and JSON fixtures pass with local preview |
| DEV-13: equilibrium import and conversion | Numerical / data | DEV-12 | NUM-10 passes, source/convention audit available |
| DEV-14: nonrelativistic particle engine | Numerical | DEV-06, DEV-07 | NUM-14 through NUM-16 pass |
| DEV-15: wall events and ensembles | Numerical / 3D | DEV-04, DEV-14 | NUM-17 and normalization tests pass |
| DEV-16: supported advanced particle models | Numerical | DEV-14, applicable references | NUM-18 passes for each mode exposed |
| DEV-17: pressure/profile diagnostics | Numerical / data | DEV-12, DEV-13 | NUM-23 and dimensional profile tests pass |
| DEV-18: fixed-boundary GS solver | Numerical | DEV-02, DEV-06, DEV-13 | NUM-11 passes on manufactured and analytic problems |
| DEV-19: free-boundary equilibrium coupling | Numerical | DEV-10, DEV-18 | NUM-12 passes for an agreed reference problem |
| DEV-20: nuclear evaluations and reactivity | Nuclear-data / numerical | DEV-02, DEV-12 | NUM-19 through NUM-21 pass; coefficient/domain/source audit complete |
| DEV-21: radiation and energy ledger | Numerical | DEV-17, DEV-20 | NUM-22 and NUM-24 pass with explicit missing-term behavior |
| DEV-22: results and comparison workspace | UI / numerical | Core task outputs | All task-specific views have tables, units, definitions and current-run identity |
| DEV-23: sweeps and uncertainty tools | Numerical / UI | DEV-22 | Controlled inputs, failures, seeds and uncertainty assumptions preserved |
| DEV-24: reproduction and migration | Data / frontend | DEV-12, DEV-22 | NUM-25 passes in a clean session |
| DEV-25: accessible scientific workflows | Accessibility / frontend | DEV-03 onward | UX-11 through UX-13 pass for complete workflows |
| DEV-26: first-load and failure hardening | Frontend / 3D | DEV-05, DEV-06 | UX-08 through UX-10 and UX-15 pass |
| DEV-27: measured performance tuning | 3D / frontend / numerical | Functional baseline | Agreed budgets measured; visual quality reduction leaves scientific output intact |
| DEV-28: cross-lab adapters | Data / frontend | Actual contract inventory, DEV-24 | Matching metadata, units and energy handoffs tested |
| DEV-29: static host release and rollback | Deployment | Relevant acceptance gates | UX-17 and UX-18 pass on the real host |
| DEV-30: scientific release review | Numerical / product | Implemented capability gates | Model cards, benchmark records, sources and limitations match the shipped code |

Release coherent working increments: first the shell and analytic scientific workflow; then coils/imports; then particles and profiles; then validated equilibrium/fusion extensions; finally the complete release package. Do not label the first attractive render as the completed scientific lab.

### 26.1 Required delivery package from the development team

Deliver the editable source, production `dist`, original 3D source or procedural asset recipe, licensed runtime assets, dataset manifests, numerical reference fixtures, test results, import/export schema documentation, model cards, build instructions, hosting instructions and rollback package.

For each model card include the equations, units, valid domain, inputs, outputs, numerical method, conserved quantities/diagnostics, omitted physics, benchmark IDs and source references. Keep the model card accessible from the relevant setup/result view.

## 27. Definition of completion

The requested scientific lab is complete only when the shipped scope meets all of these conditions:

- The selected Fusion Observatory design is implemented as a responsive, interactive 3D scene.
- Numeric controls, sliders, geometry and the active model agree and use explicit units.
- Every visible scientific trajectory or quantity belongs to the selected run and is computed or imported with provenance.
- Field models, equilibrium data and particle models retain their separate assumptions and verification evidence.
- Coils, plasma, field lines and cutaway visibility affect appearance only; physical changes are explicit.
- Results include meaningful tables/plots, diagnostics, definitions, domain status and missing-data handling.
- Nuclear data preserve reaction meaning, multiplicity, energy frame, units and evaluation validity ranges.
- Power accounting does not infer confinement/gain from the animation or count energy twice.
- Complete runs can be saved, compared, exported and reproduced with their sources and solver settings.
- First load, cancellation, invalid import, context loss and missing assets have tested behavior.
- Keyboard, click alternatives, screen-reader access, reduced motion and narrow layouts support the principal tasks.
- The built package works on the actual static host with correct routes, assets and versioning.
- No unimplemented control or unavailable dataset is represented as a functioning scientific capability.

Self-consistent turbulence, RF heating, reactor thermal/mechanical design and complete electrical conversion remain separately specified capabilities until their own implementations and validation are delivered. Their absence must not prevent the supported magnetic-field and particle workflows from being useful and reproducible.

## 28. Evidence reconciliation and remaining limits

### 28.1 Findings that changed the implementation plan

| Issue | Resolution applied in this specification |
|---|---|
| Visually helical field versus physically admissible field | Start from an explicit flux construction and test divergence/winding |
| Ambiguous geometry and field sliders | Replace them with dimensional, model-specific controls |
| Winding parameter versus actual q profile | Derive the circular fixture's q(r); do not display qAxis as uniform q |
| Generic Boris claims | Test energy and phase separately; avoid universal symplecticity/energy claims |
| G-EQDSK convention support | Require complete supported transformations; parser options alone may be partial |
| Alpha yield versus reaction rate | Track reaction cross section and three-alpha multiplicity explicitly |
| Newer p–11B data versus automatic default | Use named evaluations and verified data access; preserve dataset disagreement |
| Simple bremsstrahlung at high temperature | Retain a labelled baseline and add a separately validated higher-temperature model |
| Realistic plasma glow | Keep appearance separate from numerical thermal/radiation quantities |
| Fast visual quality presets | Allow rendering changes without altering scientific resolution |

### 28.2 Research and access limits

The selected image was inspected directly. The current website source, runtime errors and host configuration were not inspected, so route and integration details require the initial development inventory.

The primary numerical tables and fit coefficients must be acquired and checked during implementation. This document does not manufacture missing values. In particular, the 2025 experimental p–11B paper states that its datasets are available on reasonable request. No EXFOR entry ID or private dataset is asserted here.

The 2023 reactivity-domain claim was corroborated through the authors' project publication record; implementation requires checking the full equations and their piecewise details. The AIP HTML article was inaccessible through one route, but its publisher PDF was inspected. The original FAIR article's direct routes were limited; the principles and original-paper attribution were checked through GO FAIR Foundation. No confidential data or inaccessible private research was used.

Searches covered official plasma/field software, original coordinate/numerical papers, nuclear-reaction research and data repositories, official graphics documentation, web standards and hosting documentation. Follow-up concentrated on flux signs, numerical invariants, data multiplicity, temperature domains, access conditions and rendering/worker failure behavior. Research stopped after the material development decisions had primary support or explicit limits; additional broad searching was unlikely to change the build architecture.

## 29. Selected source register

All web sources were checked on 6 September 2026 (UTC). Living documentation can change; pin implementation dependencies and keep the consulted versions with the development record. Sources establish methods and requirements, not validation of future HBF code.

| Source | Publisher / date | Use in this specification |
|---|---|---|
| [Magnet systems](https://www.iter.org/machine/magnets) | ITER Organization; living page | Distinct magnetic-system functions |
| [Magnetic fields](https://simsopt.readthedocs.io/stable/fields.html) | Simsopt authors; living documentation | Toroidal fields, Biot–Savart, field interfaces |
| [Field and particle tracing](https://simsopt.readthedocs.io/stable/tracing.html) | Simsopt authors; living documentation | Tracing models, drift and model distinctions |
| [Tokamak Coordinate Conventions: COCOS](https://www.epfl.ch/research/domains/swiss-plasma-center/wp-content/uploads/2018/10/Sauter_COCOS_Tokamak_Coordinate_Conventions.pdf) | O. Sauter and S. Yu. Medvedev; CPC 184, 293; 2013 | Signs, flux normalization and equilibrium conventions |
| [Particle-integrator implementation](https://docs.plasmapy.org/en/stable/_modules/plasmapy/simulation/particle_integrators.html) | PlasmaPy; documentation inspected as 2026.2.0 | Inspectable Boris update and staggered variables |
| [Proof concerning the Boris algorithm](https://arxiv.org/html/1509.02863v1) | C. L. Ellison, J. W. Burby and H. Qin; 2015 | Limits of variational/symplectic claims |
| [Creating equilibria](https://freegs.readthedocs.io/en/latest/creating_equilibria.html) | FreeGS authors; living documentation | Equilibrium input and solver structure |
| [Equilibrium input and output](https://freegs.readthedocs.io/en/latest/input_and_output.html) | FreeGS authors; living documentation | G-EQDSK content and coil-data limits |
| [G-EQDSK parser documentation](https://freeqdsk.readthedocs.io/en/stable/geqdsk.html) | FreeQDSK; 0.5.2 documentation inspected | Format details and partial COCOS support |
| [Equilibrium data dictionary](https://imas-data-dictionary.readthedocs.io/en/4.1.1/generated/ids/equilibrium.html) | IMAS Data Dictionary; version 4.1.1 | Profile coordinates, quantities and units |
| [A New Evaluation of the 11B(p,α)αα Reaction Rates](https://link.springer.com/article/10.1007/s10894-016-0069-y) | M. H. Sikora and H. R. Weller; Journal of Fusion Energy; 2016 | Alpha multiplicity and reaction-rate evaluation |
| [Revisiting p–11B cross section and reactivity](https://doi.org/10.1088/1741-4326/acda4b) | A. Tentori and F. Belloni; Nuclear Fusion 63, 086001; 2023 | Named modern evaluation; domain corroborated through linked author-project record in Section 16 |
| [Evaluation through a silicon telescope](https://link.springer.com/article/10.1140/epja/s10050-025-01589-3) | D. Mazzucconi et al.; EPJ A 61, 114; 2025 | Experimental comparison and data-access limits |
| [NRL Plasma Formulary](https://www.nrl.navy.mil/Portals/38/PDF%20Files/NRL_Plasma_Formulary_2023.pdf) | A. Beresnyak; U.S. Naval Research Laboratory; 2023 | Rounded reaction energy and radiation unit benchmark |
| [Bremsstrahlung radiation fitting](https://arxiv.org/html/2404.11540v2) | H. Xie; 2024 author manuscript; journal DOI 10.1088/1361-6587/ad877f | Relativistic and electron–electron radiation treatment |
| [Non-thermonuclear steady-state analysis](https://pubs.aip.org/aip/pop/article-pdf/doi/10.1063/5.0218316/20327489/012101_1_5.0218316.pdf) | S. Liu et al.; Physics of Plasmas 32, 012101; 2025 | Species exchange and recirculating-power assumptions |
| [Fundamental constants](https://physics.nist.gov/cuu/Constants/) | NIST/CODATA; 2022 adjustment | Versioned physical constants |
| [Experimental Nuclear Reaction Data](https://www.iaea.org/resources/databases/experimental-nuclear-reaction-data) | IAEA Nuclear Data Section; living database description | EXFOR scope and experimental provenance |
| [FAIR Guiding Principles](https://www.gofair.foundation/fair-principles) | GO FAIR Foundation; reproduces principles of Wilkinson et al., 2016 | Metadata, provenance, reuse terms and original-paper attribution |
| [glTF 2.0 specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) | Khronos Group; version 2.0.1 | Runtime asset format, coordinates and units |
| [Color management](https://threejs.org/manual/en/color-management.html) | Three.js authors; living manual | Linear lighting and output color handling |
| [Transparency](https://threejs.org/manual/en/transparency.html) | Three.js authors; living manual | Transparency ordering limitations |
| [WebGLRenderer](https://threejs.org/docs/pages/WebGLRenderer.html) | Three.js authors; living API documentation | WebGL2, shader preparation and renderer lifecycle |
| [GLTFLoader](https://threejs.org/docs/pages/GLTFLoader.html), [KTX2Loader](https://threejs.org/docs/pages/KTX2Loader.html), [InstancedMesh](https://threejs.org/docs/pages/InstancedMesh.html) | Three.js authors; living API documentation | Asset decoding, compression and repeated geometry |
| [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) | MDN contributors; updated 27 August 2026 | Background execution and buffer ownership |
| [WebGL best practices](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices), [context loss](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/webglcontextlost_event) | MDN contributors; living documentation | Resource limits and graphics recovery |
| [WCAG 2.2](https://www.w3.org/TR/WCAG22/) | W3C; Recommendation updated 12 December 2024 | Accessibility target; criterion-specific guidance linked in Section 23 |
| [Web Vitals](https://web.dev/articles/vitals) | Google web.dev; living guidance | Page experience thresholds and measurement |
| [Apache remapping](https://httpd.apache.org/docs/2.4/rewrite/remapping.html) | Apache Software Foundation; HTTP Server 2.4 documentation | Static route integration |
| [CSV injection](https://owasp.org/www-community/attacks/CSV_Injection) | OWASP Foundation; living guidance | Safe export of untrusted text metadata |

## 30. Developer handoff instruction

Implement the selected Fusion Observatory Torus Lab using this document as the requirement set. Begin by inspecting the actual existing source and routes, then freeze the scientific conventions and configuration schema. Build the responsive reference layout and genuine parameterized 3D assembly. Implement numerical kernels independently of the renderer and connect every scientific visualization to immutable run data. Complete the analytic fixtures before coil/equilibrium and particle extensions. Deliver precise scientific inputs, meaningful results, comparison, provenance and reproducible export. Verify the specified numerical, accessibility, loading and hosting behavior, and include the measured evidence with the source and deployable build. Report remaining capabilities by their actual implementation and test status; do not replace them with simulated success indicators.
