Numerical details and validation¶
FACS separates equilibrium interpolation, angular integration, frequency sampling, and root refinement. Each contributes a different error. A small boundary residual checks the integrated matrix's boundary condition at a candidate frequency. It alone does not prove an exact root, establish multiplicity, or show convergence of the equilibrium or angular integrator.
This page describes the native and WebAssembly solvers. See WebGPU for its precision, scan, and fallback limits.
Grids and defaults¶
| Setting | Native CLI value | Control |
|---|---|---|
| Equilibrium radial grid | 256 resolved surfaces | constants::RADIAL_SAMPLE_POINTS in constants.h. |
| Equilibrium poloidal grid | 256 shifted Boozer nodes per period | constants::POLOIDAL_SAMPLE_POINTS in constants.h. |
| Angular integration | 8192 steps per period | constants::POLOIDAL_INTEGRATION_STEPS in constants.h. |
| libmeq flux, profile, and Boozer interpolation order | Quintic | ORDER=5 in MagneticEquilibrium.h. |
| FACS coefficient and sampled-profile interpolation order | Cubic | constants::EQUILIBRIUM_INTERPOLATION_ORDER in constants.h. |
| Adaptive coupled frequency scan | Default; 129 seed nodes and a 1025-sample uniform fallback | --omega-samples 0. |
| Uniform coupled frequency scan | Optional; includes zero and the cap | --omega-samples N, integer at least 2. |
| Radial cutoff | \(\psi/\psi_{\rm wall}<0.8\) by default | --psi-max, or --rho-max for toroidal-flux radius. |
| Continuum radial sampling | Adaptive in safety factor | --radial-resolution selects a prescribed grid. |
| Ratio of specific heats | \(\Gamma=5/3\) | --adiabatic-index, finite and positive. |
| Coupled frequency range | User-supplied positive cap | --omega-max; continuum zones do not apply. |
The integration step is \(h=2\pi/8192\). With --omega-samples 1025,
the uniform spacing is \(\Delta\Omega=\Omega_{\max}/1024\).
On a surface, the corresponding local spacing is \(\lvert q\rvert\Delta\Omega\).
--rho-max sets \(\rho_t=\sqrt{\psi_t/\psi_{t,\rm wall}}\) in \((0,1]\).
The solver bisects the equilibrium's radius function to find the poloidal
cutoff, including its near-axis extension. It keeps the inward bound when
floating-point rounding prevents an exact match. Radial grid construction
then uses that cutoff with the usual sampling rule.
The adaptive sampler stops boundary subdivision at
\(\Delta\omega=\omega_{\max}/512\) and uses a stable-trace interpolation
indicator of \(2\times10^{-4}\omega_{\max}\). The indicator can request finer
spacing. Boundary variation uses a roundoff floor of
\(128\epsilon\max(1,|F_l|,|F_m|,|F_r|)\) for \(F=Q(2),Q(-2),D\).
The scan budget is 4097 evaluations per surface. If another sample would
exceed it, the CLI sampler returns 1025 uniform samples and reports the
fallback; those earlier evaluations still count as work. Library callers
can set these values through
AdaptiveCoupledOptions.
Midpoint and quarter probes can still miss features below the seed scale.
Compare uniform runs with increasing positive --omega-samples counts to
check density convergence. The interpolation indicator estimates error; it
does not guarantee a bound for every root.
The C++ solver defaults and numerical controls live in
constants.h, in the constants namespace. Rebuild
after changing them. Template constructors accept other angular step counts for
library use and convergence tests. A denser coupled scan changes the
frequency mesh without changing either equilibrium or angular resolution.
Equilibrium derivatives¶
The real FFT stores harmonics from DC through Nyquist. FACS differentiates over a \(2\pi\) period and applies the filter
Thus derivative order \(k\) multiplies each Fourier coefficient by \((im)^kW_m\). The high harmonics have a soft tail, rather than a hard cutoff at 10. The implementation includes \(1/N\) because neither FFT direction normalizes its output. For a first derivative, DC and the real Nyquist term vanish. The second derivative retains the Nyquist contribution with its filter weight.
The radial coefficient uses the filtered second derivative of \(g=\lvert\nabla\psi\rvert\), divided by the sampled \(g\). Coupling uses the filtered first derivative of \(B\). Differentiation, filtering, and subsequent interpolation alter the coefficient problem before integration begins. Refining \(N_\theta\) alone cannot remove these errors.
The axis model fits the flux Hessian from a local quartic polynomial on up to \(7\times7\) input nodes. Its accuracy depends on the raw flux grid and the supplied axis position. It retains ellipse tilt and uses the same angular filter for the limiting radial term. Strong elongation can therefore leave a fixed difference from the unfiltered analytic \(-G''/G\), even when the angular grid is refined.
Angular fields interpolate in \(\sqrt\psi\) before the axis extension matches their values and radial slopes. Interpolation in \(\psi\) gives a biased first radial derivative for the leading \(\sqrt\psi\) term. The equilibrium regression checks the circular solution both below and between resolved surfaces, tilted elliptical axis limits, field reversal, the join, and raw-flux-grid refinement.
Pointwise Verlet bound¶
For a constant positive eigenvalue \(\kappa^2\) of \(K\), the Verlet step has an oscillatory solution when \(h\kappa<2\). The coupled cache checks this restriction at every angular node and at the frequency cap.
For \(K=\begin{pmatrix}a&b\\b&d\end{pmatrix}\), its largest eigenvalue is
with zero correction when the denominator is zero. The code evaluates this
correction through scaled ratios to avoid cancellation or overflow. It adds
a conservative allowance of 8*epsilon times the absolute diagonal and
correction, plus an underflow allowance when needed, and requires
For cached coefficients, \(a_A,a_S\geq0\) and \(w\geq0\). The largest eigenvalue increases with \(w\): a sign change of one field makes the off-diagonal magnitude \(w|c|\), and the maximizing Rayleigh vector can have nonnegative components. Checking the cap therefore covers lower frequencies on the same coefficient grid.
Falling pressure increases acoustic inertia and can violate the bound. FACS
then rejects the cap and asks for a smaller --omega-max. The check controls
the local oscillatory step restriction. It does not prove the global
Floquet spectrum stable, certify scan completeness, or bound frequency
error. Angular gaps can be part of the physical coefficient problem.
Scalar tolerances¶
The scalar path uses the full exponent and an adaptive frequency mesh. The values below apply to local frequency \(w\), with machine epsilon \(\epsilon\) for the selected scalar type.
| Check | Value |
|---|---|
| Open stable-band scan phase error | 1e-2 in the CLI; the library function defaults to 1e-3. |
| Other scan phase error | 1e-3. |
| Phase span that forces subdivision | 0.25. |
| Stable-probe thinning phase error | 5e-4, together with a 1e-3 relative inverse-frequency check. |
| Gap transition resolution | 1e-6. |
| Half-integer target snap | Doubled phase distance below 1e-6: \(\lvert2(\nu_{\rm target}-\nu_{\rm half})\rvert<10^{-6}\). |
| Initial-phase acceptance | 1e-6 through constants::ZERO_TOLERANCE in the CLI. |
| Ordinary root bracket width | \(32\epsilon\max(1,\lvert w\rvert)+10^{-5}\lvert w\rvert\). |
| Ordinary root phase residual | \(\max(10^{-8},32\epsilon\max(1,\nu_{\rm target}))\). |
| Accumulation-root bracket width | Minimum of 1e-6 and the ordinary root width. |
| Maximum refinement iterations | 96. |
Ordinary roots must pass both bracket and stable phase checks. A gap edge has a flat half-integer real phase, so its sign-selected boundary uses a frequency bracket check instead. The scalar Floquet export keeps the coarser adaptive curve; interpolation of that export has scan accuracy, rather than the directly refined mode accuracy.
Coupled tolerances and boundary checks¶
At nonzero distance from an edge, direct refinement uses
It compares shifted reciprocal traces to the target offset. Target-hit
acceptance includes relative trace roundoff and variation across nearby
frequencies. Complete pivoting measures the complex boundary matrix
\(M-e^{2\pi i nq}I\). Its nullity threshold combines 4096*epsilon with
matrix variation across the frequency uncertainty. Final nonedge candidate
groups use a window of \(64r_w\) and the detected reciprocal branches.
Exact periodic and antiperiodic roots use a separate uncertainty scale,
For double precision and \(|w|\leq1\), this is about \(1.42\times10^{-14}\). Signed crossings refine further, down to adjacent representable frequencies; the uncertainty scale controls sampled hits, turns, and bracket grouping.
| Exact-edge check | Implementation value |
|---|---|
| Chart shifts \(t\) | \(0,1,-1,1/2,-1/2,2,-2,4,-4\), for root solving and coloring. |
| Denominator pivot floor | \(32\epsilon\lVert D_t\rVert_\infty\). |
| Denominator condition estimate | \(\operatorname{cond}_\infty(D_t)\sqrt\epsilon<1\). |
| Sampled denominator variation | \(\lVert D_{t,\rm mid}^{-1}\rVert_\infty\max\lVert D_t-D_{t,\rm mid}\rVert_\infty<1/2\). |
| Symmetric eigensystem | At most 64 Jacobi rotations; off-diagonal stopping scale 2*epsilon times the diagonal scale. |
| Boundary-vector residual | See the equation below. |
| Independent-vector test | Squared norm after two orthogonalization passes exceeds 4096*epsilon. |
| CSSC zero-energy threshold | 1e-14 after division by the squared state norm at θ=0 (local) or its full-period mean (averaged). |
For both period measures, stable propagation requires \(\big||\lambda|-1\big|\leq64\epsilon\). FACS rescales the eigenvector so its largest component has magnitude 1, then checks \(\|\Phi(2\pi)v-\lambda v\|_\infty\leq64\sqrt\epsilon\). The original matrix integration accumulates quadratic forms for signed channel currents and the full state norm. It aligns a copy of the momenta with the field samples before applying trapezoidal weights. Neither form uses the Falessi kernel. Their contraction with the eigenvector gives the period integrals without another integration.
Stable modes can cancel large fundamental solutions, so FACS checks the contraction before using it. Let \(G\) be the accumulated full-state Gram matrix and \(c\) the normalized initial vector. The indicators
bound products before cancellation in both accumulation and contraction.
FACS multiplies them by \(64(N_\theta+1)\epsilon\) to estimate roundoff.
The current error also includes \(8\epsilon\) times the same diagonal sum
with \(|\operatorname{Im}(c_a^*c_b)|\) replaced by
\(|\operatorname{Re}(c_a)\operatorname{Im}(c_b)|+
|\operatorname{Im}(c_a)\operatorname{Re}(c_b)|\). This covers cancellation
while forming the eigenvector cross terms after a common phase rotation.
FACS requires a positive resolved norm, an unambiguous 1e-14 zero-energy decision,
and a fraction error estimate at most \(\sqrt\epsilon\). Weighted amplitude
forms use their own Gram diagonals. These are conservative conditioning
indicators, not forward-error bounds for arbitrary unstable equations.
If a form is absent or fails these checks, the shared Verlet integrator
advances the selected complex vectors directly, checks finite components,
and applies the same quadrature and closure tests. This avoids reconstructing
a bounded mode from large fundamental columns. Roundoff can still excite
an unstable companion; failed closure leaves both measures as nan.
Energy uses signed sums before taking absolute values. Valid nonunit modes
keep energy fraction 0.5 and an unresolved amplitude fraction.
The squared-Jacobian kernel is sampled once on the coefficient grid and
normalized by a common maximum before quadrature. Both endpoints keep half
weight. Geometry samples must be finite and positive; the kernel must cover
all nodes, contain finite nonnegative weights, and have at least one positive
weight. The axis uses the finite normalized flux-gradient shape.
Equilibrium setup builds its log-gradient interpolant for all runs; the
Falessi flag controls the per-surface kernel sampling and amplitude sums.
The recovered boundary vector has unit Euclidean norm. It must satisfy
The sampled denominator bound guides chart selection; it is not a proof that no pole exists between samples. The solver rechecks variation and eigenvector matching during refinement, splits failed intervals, and checks the original boundary equation before accepting a mode. It averages the small skew part of the computed symmetric chart, so this original-matrix check matters.
Both coupled CLI modes use these exact-edge checks. A nearby phase, including the tested \(10^{-8}\) offsets, remains in the ordinary trace solver.
Error and completeness¶
Four refinements answer different questions:
- Increase the equilibrium grid or change derivative treatment to assess errors in geometry, profiles, and coefficients.
- Increase \(N_\theta\) to assess the integrated monodromy matrix.
- Compare uniform scans with increasing positive
--omega-samplescounts to expose more frequency brackets and turns. - Enable
--refine-coupled-rootsto reduce ordinary interpolation error.
The full coupled root solver still starts from a finite scan. A narrow feature with no detected bracket or visible turn can remain unresolved. Equal total root counts alone do not establish correct multiplicity; compare ordered frequencies, resolved close pairs, independent vectors, and their convergence.
For a constant uncoupled coefficient \(K_j=a_jw^2\) with \(a_j>0\), let the target full phase be \(\nu_* = |nq-m|\). The exact frequency is \(w_*=\nu_*/\sqrt{a_j}\). The constant-grid Verlet frequency is
This relation assumes the resolved phase range \(0\leq h\nu_*<\pi\). Outside that range, sampling aliases the full phase. Within it, the analytic discrete dispersion relation separates root-finder error from angular integration error. Smooth coefficients normally give second-order Verlet convergence, so halving \(h\) reduces the leading error by four. Near a zero eigenvalue, compare squared frequency as well as frequency.
Portable regression tests¶
Build and run the committed tests from the repository root:
git submodule update --init --recursive
cmake -S . -B build/debug -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON
cmake --build build/debug -j
ctest --test-dir build/debug --output-on-failure
| CTest | Coverage |
|---|---|
| fft | Transform reconstruction, real spectra, Nyquist terms, and angular derivatives. |
| numerics | Scalar integration, Floquet curves, gap edges, and direct mode refinement. |
| coupled | Symplectic matrices, reciprocal spectra, cache validation, character, and coupled roots. |
| effective_energy | Signed averages with changing channel signs, analytic variable polarization, second-order convergence, scale and origin invariance, zero energy, and scan/root output. |
| falessi | Analytic fractions, explicit-η RK4 comparison, second-order convergence, kernel scaling and origin invariance, boundary vectors, and an unstable companion. |
| coupled_scan | Adaptive boundary sampling, cap and zero endpoints, interpolation convergence, aliasing, uniform fallback, and exact matrix reuse. |
| floquet_analysis | Analytic traces and invariants, complex reciprocal traces, complete exponent pairs, and full-precision exports. |
| solver | Library calls without a frontend, serial/parallel results, preview ownership, ordered exports, callback failures, and Falessi opt-in. |
| stability | Seven Broucke regions, scalar bands, degenerate boundaries, large trace ratios, and nonuniform frequency bins. Runs when Node.js is available. |
| equilibrium | Normalization, derivative fields, Miller axis limits, tilted geometry, join continuity, and radial and raw-flux-grid convergence. |
| parallel | Ordered concurrent results, shared weighted sections, work stealing, bounded profile estimates, and progress timing. |
The coupled tests include periodic and antiperiodic pairs separated by
3e-11 within an ordinary coarse scan cell; boundary kernels of dimensions
one, two, and four; coincident crossings in opposite directions; an opposite
unit multiplier at the same frequency; avoided crossings with several
positive gap widths; quadratic tangencies and two roots beneath one visible
turn; exact scan nodes and caps; acoustic zero modes; and nearby nonzero phases.
They exercise the selective and fully refined APIs with analytic inputs.
Debug builds enable AddressSanitizer when the compiler supports it. The regression inputs are constructed by the tests, so they do not depend on local equilibrium files or saved outputs.
Independent spectral check¶
A Fourier quadratic eigenproblem provides a separate check of the Floquet frequencies. Express the coefficients in global \(\Omega\) units as \((a_0,q^2a_A,q^2a_S,|q|c)\). Let \(\bar\nu=nq-\operatorname{round}(nq)\) and expand the fields in \(e^{i(m+\bar\nu)\theta}\) for \(|m|\leq M\). Write the Fourier multiplication matrices as \(R,A,S,C\), and let \(D=\operatorname{diag}((m+\bar\nu)^2)\). The discretized equations are
One linearization is
Select finite real nonnegative frequencies within the requested range and check the polynomial residual. Set reality and residual tolerances from precision and matrix scale. Check zero-frequency kernels separately; linearization can repeat a zero eigenvalue without adding an independent boundary vector.
Increase the harmonic cutoff \(M\) and the coefficient sampling resolution until the retained frequencies converge. Matching the same coefficient problem separates angular integration and root-finder errors from errors in equilibrium construction. This check is an independent validation method; it is not part of the production CLI.
Convergence procedure¶
Hold the equilibrium coefficients and boundary target fixed when checking angular integration. Compute roots at \(N_\theta\), \(2N_\theta\), and \(4N_\theta\). Match their frequencies while preserving multiplicity and verify that close pairs remain resolved. For a smooth, resolved mode with leading error proportional to \(h^2\),
Once this asymptotic regime is established, Richardson extrapolation gives
Near zero, inspect \(\Omega^2\) as well. Taking a square root can amplify a small eigenvalue error and change the apparent convergence rate in \(\Omega\). For repeated roots, compare the boundary kernel dimensions and residuals as well as frequencies. Frequency ranks alone do not continue a physical eigenvector branch.
Check frequency-scan convergence separately by increasing a positive
--omega-samples count while leaving coefficients and \(N_\theta\) fixed. Stable
root counts, persistent close pairs, and converged refined frequencies give
stronger evidence than root counts alone. They still do not prove that a
finite scan has detected every narrow feature.
To assess the equilibrium model, increase its radial and poloidal grids and examine changes in the coefficient functions before repeating the spectral solve. Axis extensions and derivative filtering require their own checks; refining the integrator does not remove their effects.
Computational cost¶
For fixed-size fundamental matrices, one matrix integration costs \(O(N_\theta)\). A coupled surface with \(N_{\rm scan}\) scan cache misses, \(N_{\rm root}\) additional root cache misses, \(N_{\rm color}\) coloring cache misses, and \(N_{\rm norm}\) period-quadrature passes performs
integrations. Scan work includes adaptive probes discarded on fallback, so it can exceed the stored scan point count \(N_\Omega\). Root and coloring counts sum over requested toroidal modes. The scan and matrix cache are shared across these modes. Coefficient caching removes repeated equilibrium interpolation from these integrations. Full refinement usually increases \(N_{\rm root}\), while a denser scan increases \(N_{\rm scan}\) and can reduce later cache misses. Exact unit targets also require chart selection, eigensystem matching, and vector validation. Frequency-rank grouping connects the sorted roots in linear time, without matrix integrations. It retains an active segment ID per rank and retires IDs when ranks disappear. The CLI reports this time separately from surface integration time. Enabling either period measure adds a fixed number of products and sums at each node of matrices requested for scan diagnostics or root colors. Each matrix stores a fixed number of form coefficients shared by its copies; each selected vector then needs only a fixed-size contraction. Local energy alone needs neither forms nor vector propagation. Frequency-only root probes and scans without diagnostic output skip collection.
The \(N_{\rm norm}\) passes now cover only direct fallback: a selected vector has no saved forms, or the contraction fails its conditioning checks. Both scan branches and period measures share a fallback pass where possible. Falessi adds geometry sampling and weighted amplitude forms. Accumulation appears in the corresponding matrix integration time; contractions and fallback passes appear in coloring time. Matrix-cache counters report the first three terms separately.
Baseline x86-64 ELF builds with GCC or Clang select an AVX kernel at runtime when the CPU supports it. It integrates the four fundamental solutions in parallel, preserving the double kernel's operation order and endpoint half-kicks without fused multiply-adds. Other CPUs, WebAssembly, and builds with global AVX flags use the generic implementation. This changes neither adaptive sampling decisions nor the number of integrations.
Memory per active coupled surface scales with \(N_\theta\) for cached coefficients, \(N_\Omega\) for the scan grid, and the total number of distinct scan, root, and coloring frequencies for cached matrices. Rank grouping stores one segment ID per active rank. Collected continuum output grows with the number of surfaces and modes. Radial surfaces run concurrently with one coefficient and matrix cache per active surface. Eight angular profile probes per surface estimate phase span for initial section weights; this adds no matrix integrations. These weights and the resulting time estimate do not bound work near gaps or control numerical accuracy.
The browser also retains each surface's frequency scan in packed arrays for radial diagnostics. Each sample uses 120 bytes for global frequency, two Broucke coefficients, four real/imaginary exponent entries, four reciprocal-trace entries, and two values for each Alfvénicity definition. This storage grows with the sum of scan sizes across surfaces; uniform and scalar scans need not fit the adaptive 4097-sample budget. The browser copies each completed scan before releasing its worker-owned buffer and clears the arrays on a new or failed run. Selecting a surface reads these arrays and performs no matrix integrations.
Measure wall time and the separate equilibrium, cache, scan, root, rank grouping, coloring, and output stages. Record the matrix evaluation counts alongside elapsed time. For a timing comparison, hold the input, radial surfaces, angular grid, frequency range, requested modes, compiler settings, and thread count fixed. Repeat runs under similar system load; one measurement does not establish a speedup.