Continuum algorithms

The native and WebAssembly solvers use the same equilibrium and Floquet code. Equilibrium construction sets the periodic coefficients. The scalar and coupled paths share the integrator, then use different frequency scans and root finders. The WebGPU backend uses separate approximate scans and root searches.

flowchart TD G[GEQDSK equilibrium] --> E[Flux contours and Boozer fields] E --> C[Coefficient cache on each sampled surface] C --> S{Continuum type} S -->|Alfvénic| A[Adaptive full-exponent scan] S -->|Coupled| F[Monodromy frequency scan] A --> R[Refine sign-selected scalar modes] F --> P{Exact unit multiplier target} P -->|Yes| B[Signed boundary charts] P -->|No| T[Trace interpolation and direct crossing checks] B --> V[Validate boundary vectors and multiplicity] T --> O V --> O[Join equal frequency ranks across radius] R --> U[Export continuum zones]

Equilibrium construction

NumericEquilibrium uses libmeq to read the g-file and form fields on flux contours. A quintic B-spline represents \(\psi(R,Z)\). The interpolated flux at the magnetic axis sets the shift. The outer contour flux is clipped if boundary samples have smaller flux than the stated LCFS. Profile interpolation still uses the stated g-file LCFS flux range.

libmeq constructs the Boozer angle from an integral along each contour so that \(JB^2\) is constant on a surface. It samples fields at shifted nodes \(\theta_j=(j+1/2)2\pi/N_{\rm eq}\), then appends the first value at the periodic endpoint. FACS builds cubic interpolants in \(\sqrt\psi\) and angle for \(J\), \(B\), the radial term, and coupling. The square-root coordinate represents their leading radial variation near the axis. Safety factor and pressure use one-dimensional cubic interpolants in flux.

Angular derivatives use the real FFT in util.h. For derivative order \(k\), the mathematical multiplier is \((im)^k\). The transform pair is unnormalized, so the implementation also applies \(1/N_{\rm eq}\). It preserves the shifted grid origin. The first derivative sets DC and the real Nyquist component to zero; the second derivative retains the Nyquist term. Both derivatives use the soft harmonic filter described in Numerical details.

The code first computes \(g''/g\) and the formed ratio \(2JFB'/(\lvert q\rvert Bg)\) at resolved surfaces, then interpolates them. Forming these coefficients before treating the axis avoids an indeterminate ratio of two vanishing fields.

Below the first resolved surface, FACS uses the regular elliptical axis limit of Miller geometry. MillerAxis fits a quartic polynomial to the nearest \(7\times7\) input flux nodes, or all available nodes on a smaller grid. The fit uses scaled coordinates and Householder QR. Constant, linear, cubic, and quartic terms keep flux offsets and higher-order shaping from biasing the quadratic term. The fit keeps the g-file axis position fixed.

In normalized coordinates \(x=((R-R_0)/R_0,(Z-Z_0)/R_0)\), the quadratic flux is \(\psi=\tfrac12x^THx\), with \(H=\left(\begin{smallmatrix}a&b\\b&c\end{smallmatrix}\right)\) and \(D=ac-b^2>0\). The mixed term retains ellipse tilt. Nonfinite samples or a Hessian that is not positive definite cause an error.

Define \(u=(\cos\theta,\sin\theta)\) and

\[ A=\begin{pmatrix}1/\sqrt a&-b/\sqrt{aD}\\0&\sqrt{a/D}\end{pmatrix}, \qquad X=(Au)_R,\qquad G=|HAu|. \]

Then \(x=\sqrt{2\psi}\,Au\) places \(\theta=0\) on the outboard horizontal ray, matching libmeq's Boozer origin in the axis limit. The normalized limits are

\[ J_0=\frac{\operatorname{sign}(F_{\rm physical,0})}{\sqrt D},\qquad a_{0,0}=-\frac{G''}{G},\qquad a_{A,0}=\left(\frac{J_0}{q_0}\right)^2,\qquad c_0=-\frac{2J_0X'}{|q_0|G}. \]

The radial term uses the same filtered Fourier derivative as resolved surfaces. The supplied \(q_0\) remains independent of the fitted curvature; \(J_0/q_0\) need not be one when those inputs disagree. Coupling uses its formed limit, avoiding division of two vanishing fields.

Let \(s=\sqrt{\psi/\psi_{\min}}\). The extensions are:

Quantity Axis treatment
Radial term \(a_0\) Quadratic in \(s\), matching its fitted axis limit and the first resolved value and slope.
Alfvénic inertia \(a_A\) Square of a cubic extension of \(J/q\), matching both endpoint values and slopes.
Safety factor and pressure Linear in flux between the stored axis and first resolved values.
Magnetic field Cubic in \(s\), matching both endpoint values and slopes.
\(B'\) Filtered Fourier derivative of the magnetic-field polynomial; zero at the axis.
Formed coupling \(c\) Quadratic in \(s\), matching its fitted axis limit and the first resolved value and slope.

The known axis slopes are \(B_s(0)=-\sqrt{2\psi_{\min}}X\) and \((J/q)_s(0)=2(J_0/q_0)\sqrt{2\psi_{\min}}X\). The radial and coupling slopes at the axis follow from their endpoint constraints. This is a local axis expansion; finite-radius shaping comes from the numerical coefficients.

The axis extension is part of the equilibrium model. Increasing the angular integration resolution does not improve that model by itself.

Toroidal flux uses a trapezoid from the axis to the first resolved surface, then coarse quadrature of the cubic \(q(\psi)\) interpolant on later intervals. Below the first surface, the code extends \(\psi_t\) linearly in \(\psi\), so \(\rho_t\) scales as \(\sqrt\psi\) there. This approximates the integral in Theory near the extrapolated axis.

Construction uses polynomial spline evaluation when the estimated work reaches 12 evaluations per active cell. Smaller workloads keep control-point evaluation. This policy applies to the quintic flux, current-profile, and angle-map splines; the GPU sampler exports the final fields’ cubic cell coefficients. See the construction measurements.

Radial sampling

The equilibrium grid and the continuum surface grid serve different purposes. The equilibrium uses fixed grids; the continuum chooses a set of surfaces on which to solve the local spectra.

By default, make_radial_grid finds monotone portions of \(q\) and chooses the next surface to change \(q\) by about

\[ \Delta q=\frac{1}{15n_{\max}}. \]

It caps the flux step at 1% of the scanned flux interval to retain points near safety-factor extrema. The loop starts at the axis and samples fluxes strictly below \(\psi_{\rm cut}={\tt psi\_ratio}\,\psi_{\rm wall}\).

--radial-resolution selects the prescribed sequence \(\psi_i=(i/N_r)^2\psi_{\rm cut}\). This changes continuum sampling, not the equilibrium interpolation grid. The current loop also repeats its initial axis evaluation in this prescribed-grid mode.

Coefficient cache and integration

On each surface, cache the frequency-independent coefficients at \(N_\theta+1\) nodes, including both ends of \([0,2\pi]\). The scalar cache stores \((a_0,a_A)\); the coupled cache stores \((a_0,a_A,a_S,c)\). A matrix evaluation combines them with the local frequency without calling the equilibrium interpolants again.

Let \(F\) and \(P\) contain the position and momentum rows of the fundamental matrix, and let \(h=2\pi/N_\theta\). One Verlet step is

\[ P_{i+1/2}=P_i-\frac h2K_iF_i, \qquad F_{i+1}=F_i+hP_{i+1/2}, \qquad P_{i+1}=P_{i+1/2}-\frac h2K_{i+1}F_{i+1}. \]

Every column advances independently. Adjacent half-kicks combine into one full kick at interior nodes. The scalar observer counts signs after each drift, when positions are at the new node. For symmetric \(K_i\), each kick and drift is symplectic in exact arithmetic. This gives a second-order approximation to the monodromy matrix. See the Störmer–Verlet discussion by Hairer, Lubich, and Wanner for the method's geometric properties.

The integration stages use ode::PartitionedIntegrator from the utils ODE header, copied into ode.h. The native AVX path uses the same drift-kick stages and endpoint half-kicks.

The coupled cache validates finite coefficients, nonnegative inertia terms, and the pointwise Verlet bound at its frequency cap. Later evaluations need only check the requested frequency against that certified range. A matrix constructed directly from an arbitrary coefficient span checks each node.

Scalar scan and root refinement

FloquetMatrix combines the monodromy trace with the zero count of the solution \(s(0)=0\), \(s'(0)=1\) to retain the full real Floquet exponent. It reconstructs the index independently at each trial frequency. Exact-zero samples do not create extra sign changes. The trace sign fixes the half-integer index within a gap, where a Dirichlet eigenvalue can change the zero count. See the Sturm and interlacing derivation for the branch formulas, boundary conditions, and angular-resolution limits.

sample_floquet_exponents grows the frequency range in local intervals of width 0.5. It caches each evaluation by frequency. Endpoint phases select the tolerance for an interval. Midpoint and quarter-point probes detect curvature and changes between stable bands and gaps. Small stable phase spans can be accepted without new interior probes. The returned curve thins stable probes that meet its phase and inverse-curve tolerances, while retaining gap probes and edge brackets.

For each requested \(n\), floquet_modes enumerates the allowed integer \(m\) and solves \(\nu(w)=\lvert nq-m\rvert\). Targets below the initial exponent are omitted. A continuum-zone cap limits the full exponent; a frequency cap limits the scanned range.

Ordinary stable roots use a safeguarded Illinois secant iteration, with periodic bisection. Acceptance requires both a narrow frequency bracket and a small phase residual. Half-integer accumulation targets instead refine the gap boundary selected by the sign of \(nq-m\). If a cap has an ambiguous half-integer phase, a small probe beyond the cap can classify the boundary; it does not extend the exported frequency range.

Coupled scan and spectral reduction

sample_coupled_floquet_matrices evaluates exactly \(N_\Omega\) equally spaced local frequencies from zero to \(\lvert q\rvert\Omega_{\max}\). The surface's scanned matrices are shared by all requested \(n\). The scan and Floquet export retain this fixed count even when root refinement adds evaluations. Select this scan with --omega-samples N, where \(N\geq2\).

With --omega-samples 0 (the CLI default), sample_adaptive_coupled_floquet_matrices starts from \(\max(2,\lfloor(N_\Omega-1)/8\rfloor+1)\) seed nodes and checks each interval's midpoint. The CLI uses the internal \(N_\Omega=1025\), giving 129 seed nodes. It follows the three spectral boundaries

\[ Q(2)=B+2-2A=0,\qquad Q(-2)=B+2+2A=0,\qquad D=A^2-4(B-2)=0. \]

For \(F\in\{Q(2),Q(-2),D\}\), it subdivides an interval with an observed sign change or with

\[ \min(|F_l|,|F_m|,|F_r|) \leq\max(|F_m-F_l|,|F_r-F_m|). \]

Variation must exceed a local roundoff floor for the proximity test. An observed sign change still triggers subdivision. A persistent \(D=0\) does not force refinement. When all indicators appear flat, quarter probes check for features hidden from the endpoints and midpoint. Boundary subdivision stops at \(\omega_{\max}/512\).

For each monotone real trace inside \([-2,2]\), a separate indicator estimates inverse-interpolation error:

\[ e_\omega=(\omega_r-\omega_l) \frac{|\mu_m-(\mu_l+\mu_r)/2|}{|\mu_r-\mu_l|}. \]

The sampler refines when \(e_\omega>2\times10^{-4}\omega_{\max}\), including below the boundary spacing. It skips roundoff-flat traces. This indicator does not bound every root error or prove finite-grid completeness.

Successful adaptive scans retain every evaluated probe. If another sample would exceed 4097 scan evaluations, the sampler returns its uniform fallback grid (1025 points for the CLI) and reports a fallback. Its work count includes earlier adaptive probes. The root checks below apply to both sampling modes.

CoupledMatrixCache borrows the surface's coefficient cache and stores each matrix by its exact frequency. Scanning, root checks, and coloring share it across all requested \(n\). Distinct nearby frequencies retain separate entries. The cache is discarded after the surface, and reported integration counts include only cache misses.

CoupledFloquetMatrix stores its spectral invariants after integration. The reciprocal polynomial is shifted by \(2s\), with \(s\) chosen from the sign of the matrix trace. For \(x_j=\mu_j-2s\),

\[ x_1+x_2=\operatorname{tr}(M-sI),\qquad x_1x_2=\det(M-sI). \]

The code evaluates the discriminant from blocks of \(M+M^{-1}\) to reduce subtraction of large characteristic terms. It uses the Cayley invariants near a common unit edge when their denominator is regular. Roundoff bounds include the measured symplectic defect. A discriminant within that bound is set to zero, preventing numerical noise from turning equal stable pairs into a complex quartet.

The quadratic solution chooses the root with larger magnitude first and obtains its partner from the product. Each reciprocal multiplier pair is then recovered analytically; its smaller multiplier is the reciprocal of the larger one. Folded exponents use inverse-sine expressions built from the shifted traces, preserving small phases before adding an edge constant.

Coupled roots at nonzero edge distance

Let \(\phi=\lvert\operatorname{remainder}(nq,1)\rvert\). Select the nearest unit edge and write the target without subtracting two close cosine values:

\[ s=\begin{cases}1,&\phi\leq1/4,\\-1,&\phi>1/4,\end{cases} \qquad \delta=\begin{cases}\phi,&s=1,\\1/2-\phi,&s=-1,\end{cases} \]
\[ \mu_{\rm target}=2s+\Delta,\qquad \Delta=-4s\sin^2(\pi\delta). \]

FACS evaluates \((\mu_j-2s)-\Delta\), which retains the distance of a tiny nonzero target phase from the unit edge.

The default three-argument coupled_floquet_frequencies first interpolates ordinary crossings on the stored grid. It then opens windows around gap edges, changes between real pairs and complex quartets, trace exchanges, and visible turns near the target. It merges overlapping windows and replaces their interpolated results with direct refinement.

--refine-coupled-roots calls refine_coupled_floquet_frequencies over the entire grid. That path probes sampled discriminant valleys, resolves real/complex transition intervals, bisects trace crossings, and locates visible extrema. A final boundary-residual check uses the complex matrix \(M-e^{2\pi i nq}I\) to accept modes and retain repeated detections. Its multiplicity is limited by the independent reciprocal branches detected at a nonreal target.

The two-argument coupled_floquet_frequencies(grid,nq) uses stored data only. It does not perform direct crossing checks. The CLI uses the three-argument overload or the fully refined solver.

Exact unit multiplier roots

When \(\phi=0\) or \(\phi=1/2\) exactly, both CLI modes call coupled_detail::edge_frequencies. No phase tolerance snaps nearby nonzero targets into this path.

For each interval, the solver evaluates a midpoint and tries a finite set of symmetric boundary charts \(H_t=(M-sI)D_t^{-1}\). It requires regular denominators at the endpoints and midpoint, limits their sampled variation, and selects the chart with the best worst condition estimate. If no chart passes, it splits the interval. The chart stays fixed during refinement.

Eigenvalues sorted by magnitude or sign can exchange order at a coincidence. The solver instead matches consecutive eigensystems by the permutation that maximizes the sum of squared eigenvector overlaps. All 24 permutations of the four vectors are small enough to check directly. During bisection it rechecks endpoint matching. A failed match or denominator check discards that interval's provisional candidates, splits the interval, and restarts. This also handles an avoided crossing whose rotating vectors could otherwise create a false sign bracket.

Each signed crossing is bisected until its endpoints are adjacent representable frequencies. The accepted endpoint has the smaller absolute signed residual among endpoints with valid original boundary vectors. Failure to validate a bracket raises an error rather than silently dropping the crossing.

Visible signed turns need a separate check. The solver locates their signed extremum in a fixed chart. If the extremum crosses zero, it searches both flanks, retaining two roots hidden within one scan cell. If it only touches zero, local variation and the original boundary-vector residual determine acceptance. Original scan triples also expose turns close to cell boundaries.

Sampled hits require a signed residual consistent with frequency uncertainty, as well as a valid boundary vector. The vector check alone would accept many tiny positive frequencies near the quadratic acoustic zero mode.

Candidates retain their final frequency brackets and recovered vectors. Only overlapping uncertainty brackets form a group. Two passes of Gram–Schmidt retain independent kernel directions, so repeated detections from adjacent intervals do not inflate multiplicity. Distinct close roots keep separate frequencies when their brackets are resolved.

Character and output

--floquet-output writes an acoustic-branch flag, then one row per radius. Each row starts with its entry count and toroidal-flux radius. Scalar entries contain frequency, matrix trace, and both exponents. Coupled entries contain frequency, \(A\), \(B\), both reciprocal traces, all four exponents, and local energy, Falessi amplitude, and averaged energy Alfvénicities for the two representative pairs. Complex values occupy real and imaginary fields; exponents use reciprocal-pair order. The output guide defines the complete text format.

Radial continuum lines

continuum_lines.h connects coupled roots on consecutive calculation surfaces. Solver assigns IDs in radial order, with an independent tracker for each toroidal mode number. Worker completion order does not affect the result. Each worker can publish its points and diagnostics at once; the browser receives a small ordered update with their final line IDs.

The frequency solver already sorts each toroidal mode's roots in ascending Ω. The line builder connects rank zero to rank zero on the next surface, rank one to rank one, and so on. At a crossing this keeps frequency order; it can exchange polarization. No Alfvénicity definition enters the assignment. Equal-frequency roots retain separate ordinal positions.

ContinuumLines stores an active ID per rank. A smaller root count retires the missing tail; a larger count creates new IDs for the new tail. An empty surface retires all IDs. Returning ranks never reuse retired IDs, so a saved line cannot bridge a missing surface. Every ID identifies a contiguous rank segment, not necessarily the rank itself. Duplicate radii retain distinct calculation indices without any special numerical matching.

The work is linear in the root count and adds no ODE integrations. Output records line_method="frequency_rank". Worker completion order, the order of requested toroidal modes, and the optional Falessi calculation do not affect grouping. Both plotting tools use the saved segments; binary surface indices also guard against connections across missing surfaces. Scalar zones without saved indices remain scatter points.

The browser cycles its palette by rank separately for each n. Its earlier colors also followed rank, though their palette index accumulated across mode groups. Equal colors alone are not a group key: the four-color palette repeats, while connections use the full rank and toroidal mode number.

The standalone coupled_bands.h helper still supports continuation of reciprocal pairs and stable arcs in frequency. The solver does not call it to construct radial curves.

After the frequency solve, the CLI requests a matrix per returned mode for Alfvénicity, constructing that matrix only on a cache miss. At ordinary targets it selects the reciprocal pair closest to \(e^{2\pi i nq}\) and recovers an eigenvector with complete pivoting. At exact unit roots it uses validated real boundary vectors. Repeated frequencies request distinct vectors where available.

Local effective energy uses CSSC's signed channel energies at θ=0 and is the default. It needs only the selected vector. The solver skips integral accumulation and further propagation unless either period measure is requested.

With --period-averaged-alfvenicity, the third definition averages each signed channel energy over the period before taking the absolute ratio. During the original fundamental-matrix integration, a node observer corrects a copy of the half-step momenta by \(-\Delta\theta K(\theta)f/2\). It accumulates six antisymmetric coefficients per channel and ten symmetric norm coefficients:

\[ C_{i,ab}=\sum_k w_k (\Phi_{i,a}\Phi_{i+2,b}-\Phi_{i+2,a}\Phi_{i,b}),\quad a<b, \qquad G=\sum_k w_k\Phi^T\Phi. \]

Here \(i=0,1\) labels the channels, and trapezoidal weights \(w_k\) equal one except at the two half-weight endpoints. For a recovered eigenvector \(c\),

\[ I_i=\sum_{a<b}C_{i,ab}\operatorname{Im}(c_a^*c_b),\qquad N=c^\dagger Gc. \]

The energies are proportional to \(\nu I_i\); \(N\) sets the normalized zero-energy threshold. The common factor \(\Delta\theta/(2\pi)\) cancels. All cross terms remain in the contraction. The matrix cache shares immutable forms between copies, so scan branches and selected roots can reuse them. No trajectory is stored. Repeated selections reuse colors only when the frequency, multiplier, and vector agree.

Frequency-only root probes and scans without diagnostic output skip the forms. A selected vector whose matrix lacks forms, or whose contraction fails the conditioning checks in Numerics, uses direct complex-vector propagation with the same synchronized trapezoidal rule. The two scan vectors share a fallback pass when both need it. Accumulation belongs to matrix integration time; contractions and fallback passes belong to coloring time. The matrix-cache counters exclude these vector passes.

Period-integrated amplitude follows Falessi and is disabled by default. With --period-integrated-alfvenicity, the observer also accumulates two symmetric field-norm forms with kernel \(W=(J_\theta/J_\eta)^2\propto|\nabla\psi|^{-4}\). The coordinate measure and field rescaling each contribute one Jacobian factor. FACS samples the kernel once per surface, without resampling equation coefficients in η. The kernel weights only the amplitude forms. Both period measures share collection, contraction, and any direct fallback pass. Unstable vectors, zero or nonfinite norms and failed Floquet closure leave Falessi unresolved. Without the flag, the solver skips kernel sampling and amplitude sums and writes nan in those fields.

Coupled text output begins with the normalized equilibrium wall flux, \(\psi_{\rm wall}/(R_0^2\lvert B_0\rvert)\), then the comment # label_kind continuum_line. Each later row is

n line_index rho_t Omega alpha_cssc rho_t Omega alpha_cssc ...

Scalar rows instead contain n continuum_zone followed by rho_t Omega pairs. Coupled output uses enough digits to round-trip a double. Rows group points by radial curve ID. Scalar files use the comment # label_kind continuum_zone.

Timers separate equilibrium construction, coefficient caching, scanning, root solving, rank grouping, coloring, and output. Matrix counters distinguish scan integrations from additional root and coloring integrations. Rank grouping performs no integrations. Increasing scan density and enabling full refinement affect these costs in different ways.