Stability

ForceFreeStates determines the ideal MHD stability of the equilibrium and produces the force-free states, the displacement fields that every later stage builds on. It implements the direct Newcomb criterion of the Fortran DCON (Glasser (2016)): rather than solving an eigenvalue problem for the growth rate, it integrates the Euler–Lagrange equations of the perturbed potential energy across the plasma and reads stability from the solutions themselves.

What it computes

For a toroidal mode number n, the perturbation is expanded in poloidal harmonics m over a window around the resonant range, and the displacement $\xi(\psi)$ becomes a vector of harmonic amplitudes. The ideal MHD potential energy $\delta W[\xi]$ is a quadratic functional of $\xi$, and its extrema satisfy a linear system of ODEs in $\psi$ whose coefficients are singular at every rational surface q = m/n, where the resonant harmonic decouples from the field-line bending. Integrating that system from the axis outward with the prescribed crossing of each rational surface gives the force-free states: the set of displacements that satisfy force balance everywhere inside the plasma for arbitrary boundary values.

Three results follow from them:

  • Fixed-boundary stability. A zero of the determinant of the solution matrix between the axis and the edge means a displacement vanishing at the boundary with negative energy, so the plasma is unstable even with a perfectly conducting wall on its surface (the crit scan).
  • Free-boundary stability. With vac_flag = true, the Vacuum module supplies the vacuum energy of the [Wall] section (no wall when the section is absent), and the total energy $W = W_\mathrm{plasma} + W_\mathrm{vacuum}$ on the control surface is a Hermitian matrix in the boundary harmonics. Its generalized eigenvalues with respect to the power norm are the free-boundary eigenmode energies; a negative least eigenvalue means an ideal external kink.
  • The tearing index Δ′. Across each rational surface the solution has a large and a small asymptotic part. The Δ′ matrix of the outer region, assembled from the force-free states, gives the jump of the small solution driven by a unit tearing perturbation at each surface; it is the outer-region input of every resistive calculation (Tearing, [Match]).

Governing equations

Ideal stability is decided by the sign of the perturbed potential energy

\[\delta W[\xi] = \int_0^{\psi_\mathrm{lim}} \mathcal{F}(\xi, \xi')\, d\psi ,\]

whose extrema over all admissible $\xi$ satisfy a first-order system in the harmonic amplitudes $U_1 = \xi$ and their conjugate momenta $U_2$ (Glasser 2016, Eq. 24):

\[\frac{d}{d\psi}\begin{pmatrix} U_1 \\ U_2 \end{pmatrix} = \mathbf{L}(\psi)\begin{pmatrix} U_1 \\ U_2 \end{pmatrix},\]

where $\mathbf{L}$ is built from the Fourier-space metric matrices $\bar{F}$, $\bar{K}$ and $\bar{G}$ of the equilibrium and the resonance factor $Q = \mathrm{diag}(m - nq)$. The resonance factor vanishes at each rational surface, so the solutions there behave as $|\psi - \psi_s|^{-1/2 \pm \sqrt{-D_I}}$, a large and a small solution governed by the Mercier index $D_I$; GPEC assembles the right-hand side from reduced matrices that carry explicit $(m - nq)$ factors rather than their inverses, the convention used on every page. The Newcomb criterion states that the plasma is fixed-boundary stable if and only if the solution that is regular at the axis remains nonsingular across every rational surface and up to the edge.

The Riccati integrator works with the matrix $S = U_1 U_2^{-1}$ (Glasser, Kolemen and Glasser (2018), Eq. 36), which obeys a quadratic matrix ODE and stays bounded where $U_1$ and $U_2$ grow exponentially, so that the rational surfaces can be crossed without the Gaussian reduction of the forward integration. Its global boundary-value problem over all surfaces gives the Δ′ matrix of Glasser and Kolemen (2018), stored in the PEST-3 convention: the diagonal entry of each surface is its outer-region Δ′, positive when the outer region drives the tearing mode, and the off-diagonal entries couple the surfaces.

Integrators

[ForceFreeStates] integrator selects the radial method; its numerical settings sit in a section of the same name.

  • "Riccati" (the default; [Riccati]) splits the domain into independent chunks integrated in parallel, crosses each rational surface in its asymptotic basis and assembles the Δ′ matrix. It stores the solution at every solver step, like Forward, so its result carries $\xi$ profiles; plasma_response does not accept a Riccati result yet.
  • "Forward" ([Forward]) integrates the system directly in $(U_1, U_2)$ with Gaussian reduction as the solutions grow, crossing each rational surface in its asymptotic basis as Riccati does. It returns dense displacement profiles, and is the only integrator whose result plasma_response accepts (the response operators are built from the dense $\xi$ solution; a wall is refused too) and the only one that supports the kinetic solve.
  • "Galerkin" ([Galerkin]) solves the outer region variationally on a finite-element basis, giving the resistive Δ′ matrix and the PEST-3 blocks but no free-boundary energies; see Galerkin Solver.

kinetic = "KineticForces" replaces the ideal energy matrices by their drift-kinetic form, which needs [Equilibrium] kinetic_file; see Kinetic Forces.

Running it

From examples/DIIID-like_ideal_example/gpec.toml (abridged):

[ForceFreeStates]
nn = 1                   # toroidal mode number, or consecutive numbers as a list ([1, 2, 3])
vac_flag = true          # free-boundary energies with the [Wall] vacuum response
qlow = 1.02              # inner edge of the integration domain
qhigh = 1e3              # outer bound of qlim (see Integration domain)
delta_mlow = 8           # extra poloidal modes below the resonant range
delta_mhigh = 8          # extra poloidal modes above it
integrator = "Forward"   # "Riccati" is the default; "Forward" (and no [Wall]) is required for [PerturbedEquilibrium]
truncate_at_rational_offset = true
rational_offset_fraction = 0.2

[Forward]
eulerlagrange_tolerance = 1e-10
save_interval = 1        # save every Nth ODE step; steps near rational surfaces are always saved
renorm_threshold = 1e3   # renormalize the solution basis above this column norm

examples/DIIID-like_riccati_deltaprime_example sets eulerlagrange_tolerance and save_interval under [Riccati]; renorm_threshold belongs to [Forward] only.

The same solve from a script takes the deck keys as keywords of the problem and the integrator:

using GeneralizedPerturbedEquilibrium

eq  = PlasmaEquilibrium("examples/DIIID-like_ideal_example/TkMkr_D3Dlike_Hmode.geqdsk"; jac_type="hamada")
ffs = solve(eq, Riccati(; eulerlagrange_tolerance=1e-10); nn=1, delta_mlow=8, delta_mhigh=8, vac_flag=true, qlow=1.02)

real(ffs.free_boundary.et[1])                 # least free-boundary eigenmode energy: negative is unstable
for (s, sing) in enumerate(ffs.surfaces)
    println("q = $(sing.m[1])/$(sing.n[1]) at ψ_N = $(sing.psifac): Δ′ = $(real(ffs.delta_prime.matrix[s, s]))")
end

main(["examples/DIIID-like_riccati_deltaprime_example"]).ffs returns the same result from a deck. The number of Julia threads is set at startup (-t N or JULIA_NUM_THREADS); the chunking never depends on it, so threads change the wall-clock time only.

Outputs

DatasetMeaning
ForceFreeStates/FreeBoundaryStability/W_plasma, W_vacuum, W_freeboundaryplasma, vacuum and total energy matrices on the control surface, power-normalized (per unit ⟨|ξ|²⟩)
ForceFreeStates/FreeBoundaryStability/eigenmode_energiesgeneralized eigenvalues of $W$, most unstable first; eigenmode_plasma_energies and eigenmode_vacuum_energies split each one
ForceFreeStates/FreeBoundaryStability/W_freeboundary_eigenmodesthe eigenvectors, unit power norm
ForceFreeStates/FreeBoundaryStability/vacuum_eigenvalueleast eigenvalue of the vacuum energy matrix
ForceFreeStates/EdgeScan/total_energy, plasma_energy, vacuum_energy and vacuum_eigenvalue against psi and q as the control surface moves outward from dW_edge_scan_start
ForceFreeStates/Solutions/ForwardIntegration/the forward integrator's psi, q, xi_psi, xi_s, dxi_psidpsi profiles and the crit scan whose zero crossings mark fixed-boundary instability
ForceFreeStates/EulerLagrangeMatrices/the $\bar{F}$, $\bar{K}$, $\bar{G}$ matrices on psi, written when write_el_matrices = true
ForceFreeStates/LayerOverlap/the resistive-layer overlap scan, when psilim_from_layer_overlap is set (table below)
SingularSurfaces/rational_psi, rational_q, rational_m, rational_n, dqdpsithe rational surfaces of the domain, core to edge
SingularSurfaces/D_I, E, F, G, H, K, Mthe Mercier index and the Glasser–Greene–Johnson layer coefficients at each surface
SingularSurfaces/ca_left, ca_rightthe asymptotic (large, small) coefficients on either side of each surface, from ideal crossings
SingularSurfaces/Delta_prime_matrixthe Δ′ matrix in the PEST-3 convention, from "Riccati" or "Galerkin"; Delta_prime_raw is the side-major (left, right) matrix it is folded from, Delta_coil the edge coil-response columns
SingularSurfaces/Kinetic/the surfaces of a kinetic solve

The energy matrices are power-normalized: the eigenmode energies are the generalized eigenvalues of the pencil $W v = \lambda N v$, with $N$ the surface-norm matrix $\xi^\dagger N \xi = \langle|\xi|^2\rangle$ built from the Jacobian Fourier coefficients, so each is an energy per unit surface-averaged squared displacement rather than joules, and the spectrum is invariant to the working coordinate because $W$ and $N$ transform by the same congruence. Info/psilim and Info/qlim record the outer edge of the integration domain.

Integration domain

The integration runs from the axis (qlow sets the inner edge) to psilim, the flux of the target safety factor qlim. qlim starts at min(qmax, qhigh), with qmax the value of q at the equilibrium's psihigh. With truncate_at_rational_offset = true (the default, for diverted equilibria where q diverges at the separatrix), qlim moves to (m_last + rational_offset_fraction)/n, a fixed fraction of a rational spacing past the last surface, stepped back by 1/n until it no longer exceeds the bound it started from; a bound that falls on a rational, or less than rational_offset_fraction/n above one, therefore excludes that surface. With truncate_at_rational_offset = false (limited or analytic equilibria with finite edge q), qhigh and psihigh set the domain directly.

Resistive-layer overlap cap

Near the separatrix the rational surfaces crowd faster than their resistive layers narrow, and past the point where adjacent layers touch the matched-asymptotic treatment is not defined (the diverted-plasma response paper of Fitzpatrick (2025), listed under Tearing). psilim_from_layer_overlap = true locates that point: each rational surface of each n in the run, including surfaces beyond the equilibrium grid placed on the logarithmic divergence of q at the X-points, gets a layer width from the kinetic profiles with the closures of [SLAYER] (a SLAYERModel in a script), and the domain is cut at the last surface before two adjacent layers overlap. The cap needs kinetic profiles, acts before the rational_offset_fraction step, and can only narrow the domain; examples/DIIID-like_truncation_example exercises it. The scan is written to ForceFreeStates/LayerOverlap/:

DatasetContents
psi, m, n, r_sscanned surfaces and their minor radius √(2ψ_t/B₀)
delta_s_abs, width_delta_sRiccati layer thickness, in metres and as a Δψ width
width_visco, width_drvisco-resistive and diffusive-resistive Δψ widths; width_dr sets the cut
extrapolated1 where the surface lies beyond the equilibrium grid
psilim_overlap, first_overlap_indexthe cut, and the first surface whose layer overlaps its neighbour
applied1 when the cap was passed to the truncation

The perpendicular diffusivities that set the layer widths are described with the SLAYER inputs on the Tearing page.

Numerical notes

  • The Riccati integrator splits the domain into chunks whose count is derived from the number of singular surfaces ([Riccati] nchunks overrides the target, 0 is automatic); every chunk integrates from its own start (the identity, or the asymptotic solutions of Glasser and Kolemen (2018) for the two chunks next to a rational surface), so the result is independent of the thread count.
  • The chunk ending at each rational surface is integrated backward, from the surface inward, because the forward propagator is ill-conditioned there; the Δ′ boundary-value problem is assembled from products of the same propagators, matched midway between the surfaces.
  • With vac_flag = true the solutions of that boundary-value problem are rebuilt on the stored grid from the same propagators and published as ffs.basis, the outer solutions a [Match] combines.
  • Both integrators use the adaptive ninth-order Vern9 solver at eulerlagrange_tolerance; the Riccati integrator reduces its state to $(S, I)$ after every chunk, and Forward applies Gaussian reduction whenever a solution norm grows past renorm_threshold.
  • Both ODE integrators cross a rational surface in its asymptotic series: the solutions are expanded in the series on the near side, the one carrying the large solution ends there, and the nonresonant coefficients continue into the series on the far side (Glasser and Kolemen (2018), Eq. 36). Their energies therefore agree and do not depend on singfac_min, the distance at which the crossing is made. The default, 5e-4, keeps the crossing inside the radial-grid cell that holds the surface, where the series matches the splined equilibrium; much smaller values cost steps and lose accuracy in Δ′. Inside that distance the stored solution is filled in from the series, at crossing_fill_points log-spaced distances per side down to crossing_fill_min. Kinetic crossings still take a trapezoidal step and get no fill.

Local stability (Mercier, resistive interchange and ballooning) is a separate stage on the same equilibrium; see Local Stability.

API reference

The Galerkin solver's functions are documented on the Galerkin Solver page.

GeneralizedPerturbedEquilibrium.ForceFreeStates.ForceFreeStatesControl — Type
ForceFreeStatesControl

Physical and workflow controls for a force-balance solve, together with its selected algorithm.

Fields

  • algorithm::AbstractIntegrator - Selected integrator and its numerical settings.
  • vac_flag::Bool - Enable vacuum region calculation
  • mtheta_vacuum::Int - Number of vacuum poloidal grid points (corresponds to mtheta in VacuumInput)
  • nzeta_vacuum::Int - Number of vacuum toroidal grid points (corresponds to nzeta in VacuumInput3D)
  • frobenius_psi_max::Float64 - Largest starting ψ_N at which the opt-in diagonal Frobenius start is used; default 0 always uses the fixed start U₁ = 0, U₂ = I. The Frobenius start is currently unreliable (warns when used); leave at 0 unless testing it.
  • nn_low::Int - Lower bound for toroidal modes
  • nn_high::Int - Upper bound for toroidal modes
  • delta_mlow::Int - Expands lower bound of Fourier harmonics by delta_mlow
  • delta_mhigh::Int - Expands upper bound of Fourier harmonics by delta_mhigh
  • singfac_min::Float64 - Distance |m − nq| from each rational surface at which the ideal integration stops and the surface is crossed through its asymptotic series. Energies do not depend on it; Δ′ loses accuracy below about 1e-5, and the series does beyond the first radial-grid knot. Default 5e-4. A kinetic run stops this far from each kinetic singular surface and steps across by a trapezoidal rule, whose error grows as the distance cubed, so its default is 1e-5.
  • crossing_fill_points::Int - Stored states added on each side of each crossed rational surface from its asymptotic series, log-spaced in distance between singfac_min and crossing_fill_min. Zero adds none.
  • crossing_fill_min::Float64 - Distance |m − nq| from the surface of the closest of those states.
  • truncate_at_rational_offset::Bool - Truncate the domain at (last_rational_q + rational_offset_fraction) / n instead of at qhigh / psihigh, avoiding a spurious δW kink when the integration ends just below a rational. Right for diverted equilibria (default true); set false for limited/analytic equilibria with finite edge q (Solovev, LAR), where it cuts too much edge. Multi-n runs warn and fall back to qhigh / psihigh.
  • psilim_from_layer_overlap::Union{Bool,InnerLayer.SLAYERModel} - Cap qlim where adjacent rational surfaces' resistive layers overlap (Fitzpatrick, Nucl. Fusion 2025 Sect. 5.9); rational_offset_fraction / qhigh still pick the final surface inside the cap. true uses the default SLAYERModel() closures, a SLAYERModel(; ...) its own (a deck's [SLAYER] section). Requires the equilibrium's kinetic data; the result carries the scan as layer_overlap. Default false.
  • rational_offset_fraction::Float64 - Distance beyond the last rational surface, in units of 1/n, in [0, 1). Used only when truncate_at_rational_offset is true. Default 0.2.
  • frobenius_order::Int - Order of the Frobenius expansion at rational surfaces. Default 6.
  • qhigh::Float64 - Integration terminated at q limit determined by minimum of qhigh and qa from equil
  • kinetic - Kinetic source of the force operator: nothing (ideal), a KineticForces.KineticForcesControl (the drift-kinetic matrices of the KineticForces model evaluated on the equilibrium's kinetic profiles; needs Forward()), TestKineticMatrices (synthetic test matrices), or the KineticMatrices of an earlier evaluation, reused. A deck selects the KineticForces model with kinetic = "KineticForces", using its [KineticForces] section.
  • kinetic_factor::Float64 - Uniform scale on the kinetic matrices of a kinetic run. Default 1.
  • qlow::Float64 - Integration starts at the outermost crossing of q = qlow, excluding the q < qlow region inside it (a core, or a reversed-shear ring); no effect when q ≥ qlow everywhere
  • dW_edge_scan_start::Float64 - If below psilim, records a dW(ψ) diagnostic scan over [dWedgescanstart, psilim] on `odet.edgescan. Does not change the domain unlesstruncateatdW_peak` is set.
  • truncate_at_dW_peak::Bool - When true and dW_edge_scan_start < psilim, adopt the edge-dW scan's peak as the plasma edge, equivalent to setting psihigh to the peak by hand. Δ' then depends on where the peak falls in the edge band. Default false.
  • write_el_matrices::Bool - Write the ideal (and on a kinetic run, kinetic) Euler-Lagrange matrices on the ψ grid to ForceFreeStates/EulerLagrangeMatrices; scales as numpert_total²·npsi and dominates the file size. Default false.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.ForceFreeStatesInternal — Type
ForceFreeStatesInternal

Solve-time scratch state for a force-balance solve: the resolved mode space, singular surfaces and integration limits.

Fields

  • mlow::Int - Lowest poloidal mode number
  • mhigh::Int - Highest poloidal mode number
  • mpert::Int - Number of poloidal modes (mhigh - mlow + 1)
  • nlow::Int - Lowest toroidal mode number, resolved from ctrl.nn_low/nn_high
  • nhigh::Int - Highest toroidal mode number, resolved from ctrl.nn_low/nn_high
  • npert::Int - Number of toroidal modes (nhigh - nlow + 1)
  • numpert_total::Int - Total number of modes (mpert × npert)
  • msing::Int - Number of ideal singular surfaces
  • kmsing::Int - Number of kinetic singular surfaces (det(F̄) near-zeros)
  • sing::Vector{SingType} - Vector of ideal singular surface data
  • kinsing::Vector{SingType} - Vector of kinetic singular surface data
  • kinsing_scan_psi::Vector{Float64} - ψ grid used by find_kinetic_singular_surfaces! for the cond(F̄) scan (empty unless the finder has run)
  • kinsing_scan_cond::Vector{Float64} - cond(F̄) values on that grid; the finder locates peaks that exceed kinsing_scan_threshold
  • kinsing_scan_threshold::Float64 - Threshold on cond(F̄) used to accept a peak as a kinetic singular surface
  • psilim::Float64 - Flux limit for integration
  • qlim::Float64 - Safety factor at psilim
  • q1lim::Float64 - Safety factor derivative at psilim
  • wall_settings::Union{Nothing,Vacuum.WallSettings} - Wall shape settings for vacuum calculations
  • verbose::Bool - Log solve progress; set from the verbose keyword of solve
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.ModeIndices — Type
ModeIndices(modes::ModeSpace)

Immutable copy of a mode space's indexing, for code that must not see the rest of its source.

Fields

  • mlow::Int, mhigh::Int, mpert::Int - Lowest and highest poloidal harmonic and their count.
  • nlow::Int, nhigh::Int, npert::Int - Lowest and highest toroidal harmonic and their count.
  • numpert_total::Int - Number of (m, n) harmonics, mpert * npert.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.SingAsymptotics — Type
SingAsymptotics

Frobenius asymptotic expansion at one side of a singular surface, built by compute_sing_asymptotics.

Fields

  • sing_order::Int - Frobenius expansion order
  • alpha::Vector{ComplexF64} - Mercier exponent α = √(tr²/4 − det) of each resonant block.
  • r1::Vector{Int} - Resonant indices along first index
  • r2::Vector{Int} - Resonant indices along second index
  • power::Vector{ComplexF64} - Frobenius power of each column in |ψ − ψ_s| (0 off resonance). Resonant powers are sig·λ of that side's M₀ block, big solution (more negative real part) first.
  • vmat::Array{ComplexF64,4} - Power series of V matrix for asymptotic analysis
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.SingType — Type
SingType

A mutable struct holding data related to the singular surfaces in the equilibrium.

Fields

  • psifac::Float64 - Normalized flux coordinate at the singular surface
  • rho::Float64 - Radial coordinate (√ψ)
  • m::Vector{Int} - Poloidal mode number(s)
  • n::Vector{Int} - Toroidal mode number(s)
  • q::Float64 - Safety factor (= m/n)
  • q1::Float64 - Derivative of safety factor with respect to ψ
  • delta_prime::Vector{ComplexF64} - Debug stub, not physically valid. Per-surface ca-based Δ' estimate; use ForceFreeStatesResult.delta_prime (STRIDE global BVP, Glasser & Kolemen 2018, Phys. Plasmas 25, 082502) for tearing stability.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.ChunkPropagator — Type
ChunkPropagator

Fundamental matrix of one integration chunk: column j is the solution started from column j of the chunk's start basis (propagator_start).

Fields

  • u::Array{ComplexF64,3} - The matrix at the end of the integration, (N, 2N, 2): U₁ in slice 1, U₂ in slice 2.
  • psi::Vector{Float64} - ψ of every solver step, in integration order.
  • steps::Vector{Array{ComplexF64,3}} - The matrix at each psi.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.IntegrationChunk — Type
IntegrationChunk

A struct representing a region of integration in the Euler-Lagrange solver.

Fields

  • psi_start::Float64 - Starting ψ coordinate for this integration region
  • psi_end::Float64 - Ending ψ coordinate for this integration region
  • needs_crossing::Bool - Whether a rational surface crossing is needed after this chunk
  • ising::Int - Index of the singular surface associated with this chunk (0 if none)
  • direction::Int - +1 forward, -1 backward. A backward chunk still has psi_start < psi_end but its propagator maps the state at psi_end to psi_start; used for well-conditioned crossing chunks.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.DeltaPrimeData — Type
DeltaPrimeData

The solve's Δ′/outer-region matching payload, in the PEST-3 convention shared by the Riccati boundary-value problem and the Galerkin solve, so consumers never branch on which integrator ran.

Matrices are indexed by the surfaces the formalism solved across, core→edge: result.surfaces for Riccati, its in-domain in-band subset for Galerkin (gal_resonant_surfaces). Side-major orderings run [L_s1, R_s1, L_s2, R_s2, …].

Fields

  • matrix::Matrix{ComplexF64} - Inter-surface Δ′ of shape (msing × msing) in PEST3 convention, the tearing↔tearing parity projection of raw. Same as Delta of the PEST-3 block set. Both formalisms.
  • raw::Matrix{ComplexF64} - Raw outer-region matching matrix D′ of shape (2msing × 2msing), side-major on both axes. Both formalisms.
  • coil::Matrix{ComplexF64} - Edge coil-response matrix of shape (2msing × numperttotal); column k is the resonant small-solution response at each surface side to a unit source on edge poloidal mode k. Riccati fills it from the vacuum-edge BVP, Galerkin from its `rpecflag` columns. Empty when neither ran.
  • A::Union{Nothing,Matrix{ComplexF64}} - PEST-3 interchange↔interchange block (msing × msing). Galerkin only; nothing for Riccati, which persists only raw and recovers the blocks on demand via pest3_decompose.
  • B::Union{Nothing,Matrix{ComplexF64}} - PEST-3 interchange↔tearing block; see A.
  • Gamma::Union{Nothing,Matrix{ComplexF64}} - PEST-3 tearing↔interchange block; see A.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.OuterSolutionBasis — Type
OuterSolutionBasis

Outer-region solutions ξ(ψ) that a MatchProblem combines into the matched solution, from the Riccati Δ′ boundary-value problem or the Galerkin solve. Solution 2j-1 (2j) carries a unit big solution left (right) of surface j and none elsewhere; the rest, when present, carry no big solution and a unit displacement of one edge mode each.

Fields

  • psi::Vector{Float64}, q::Vector{Float64} - Radial grid, core to edge, and its safety factor.
  • issing::Vector{Bool} - Grid points on a singular surface, where the solutions are left zero.
  • xi::Array{ComplexF64,3}, xi_deriv::Array{ComplexF64,3} - (mpert, ngrid, nsol) ξ and dξ/dψ.
  • xi_cut::Array{ComplexF64,3} - (mpert, ngrid, nsol) ξ without the leading-order big and small resonant terms near each surface, the background the inner-layer solution is added to. Empty when not computed.
  • cut_range::Matrix{Float64} - (msing, 2) ψ bounds around each surface outside which xi_cut equals xi. Empty when not computed.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.ForceFreeStatesResult — Type
ForceFreeStatesResult

The published product of a force-free-states solve: everything downstream stages (PerturbedEquilibrium, KineticForces, SLAYER, the HDF5 writer) are allowed to read. ForceFreeStatesInternal remains solve-time scratch and does not cross a module boundary once this has been built.

Optional fields are Union{Nothing,T} and follow a presence-equals-capability rule: a consumer that needs one gates on require (or require_solution for the ξ profiles) and warns-and-skips rather than erroring, so a result from an integrator that cannot supply a given product still flows through the pipeline. PerturbedEquilibrium refuses Galerkin and :matched results instead, since they publish no wp or free_boundary yet.

Every final result records how its basis crosses the rational surfaces, so bpen and closure are always present.

Fields

  • integrator::Symbol - :forward, :riccati, or :galerkin.
  • control::ForceFreeStatesControl - Provenance snapshot of the controls the solve ran with.
  • equil::Equilibrium.PlasmaEquilibrium - The equilibrium actually integrated against (the re-formed one on the two-pass path).
  • mlow, mhigh, mpert, nlow, nhigh, npert, numpert_total - Resolved (m, n) mode space; see ModeSpace.
  • psilow, psilim, qlim, q1lim - Integration bounds, and q with its ψ-derivative at psilim.
  • problem, algorithm - Problem and integrator retained by the public solve for reproducible output.
  • wall_settings::Union{Nothing,Vacuum.WallSettings} - Wall shape used by the vacuum calculation.
  • metric::MetricData, mats::MatrixSplines - Metric data and Euler-Lagrange matrix interpolants.
  • surfaces::Vector{SingType} - Ideal singular surfaces in the integration domain, with asymptotic bases and GGJ coefficients.
  • kinetic::NamedTuple - Kinetic singular-surface scan (kmsing, kinsing, scan_psi, scan_cond, scan_threshold); empty unless the finder ran.
  • closure::Symbol - How the basis crosses the rationals: :ideal (the ideal jump condition was imposed), :regular (kinetic terms regularize the force balance equations so no closure is needed) or :matched (an inner-layer solution was matched in). A :matched result carries no ideal δW: wp and free_boundary are nothing.
  • bpen::Matrix{ComplexF64} - (msing × numpert_total) penetrated resonant field from the inner layer, per surface (rows follow surfaces) and driving mode; all zeros under :ideal and :regular closure.
  • match::Union{Nothing,MatchResult} - The MatchResult of a MatchProblem solve; nothing otherwise.
  • solution::Union{Nothing,SolutionProfiles} - THE solve's ξ solution; nothing when the formalism produced none (Galerkin without a match).
  • basis::Union{Nothing,OuterSolutionBasis} - The outer-region solutions a MatchProblem combines, from a Galerkin solve or a Riccati solve that computed Δ′ with a vacuum edge; nothing otherwise.
  • diagnostics::Union{Nothing,OdeState} - The integrator's raw ODE state (ψ trace, crit, edge scan, asymptotic coefficients). Written to HDF5; not a consumable solution.
  • wp::Union{Nothing,Matrix{ComplexF64}} - Fixed-boundary plasma energy matrix W_p = (U₂·U₁⁻¹)/ψ₀² at psilim. Present for any Euler-Lagrange sweep regardless of vac_flag; equals free_boundary.wp when that ran.
  • free_boundary::Union{Nothing,FreeBoundaryResult} - Free-boundary energies and eigenmodes; nothing when the vacuum step was skipped or the formalism computes none.
  • delta_prime::Union{Nothing,DeltaPrimeData} - Δ′/outer-region matching payload from whichever formalism ran (Riccati BVP or Galerkin); nothing when neither produced one.
  • galerkin::Union{Nothing,GalerkinResult} - RDCON Galerkin solver internals and FEM diagnostics. Its Δ′ payload lives in delta_prime, not here.
  • layer_overlap - The binding resistive-layer overlap scan (Tearing.LayerOverlapScan) when psilim_from_layer_overlap capped the domain; nothing otherwise.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.SolutionProfiles — Type
SolutionProfiles

The solve's ξ solution on its radial grid, in the exact shape PerturbedEquilibrium consumes. Field names mirror the OdeState store subset so the consumers read the same names whichever formalism produced the solution.

Fields

  • basis::Symbol - The basis the profiles are in: :el_axis (an ODE integrator's solution columns) or :unit_edge (a MatchProblem solution; each column has unit displacement of one edge mode).
  • step::Int - Number of stored radial nodes.
  • psi_store::Vector{Float64} - ψ at each node.
  • q_store::Vector{Float64} - Safety factor at each node.
  • u_store::Array{ComplexF64,4} - (N, N, 2, step) solution state: Ξ_ψ in the first component and its conjugate momentum in the second.
  • du_store::Array{ComplexF64,3} - (N, N, step) dΞ_ψ/dψ.
  • xi_s_store::Array{ComplexF64,3} - (N, N, step) Clebsch displacement Ξ_s.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.build_result — Method
build_result(integrator, ctrl, equil, intr, metric, mats, odet, free_energies, gal_data, delta_prime, basis)
    -> ForceFreeStatesResult

Assemble the published result once the solve is finished, with the ideal or regular closure (a MatchProblem solve transforms it afterwards). Materializes the forward path's derivative stores and forms W_p when the free-boundary stage did not run; everything else is copied or aliased.

odet is the ODE state (nothing for Galerkin), gal_data the Galerkin internals (nothing otherwise), and delta_prime and basis the Δ′ payload and outer solutions of a Riccati or Galerkin solve (nothing otherwise).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.require — Method
require(result::ForceFreeStatesResult, field::Symbol, calc::AbstractString) -> Bool

Warn-and-skip gate: true iff the optional field field was populated by the integrator that produced result. Warns naming the calculation being skipped otherwise.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.ResistGeometry — Type
ResistGeometry

Per-singular-surface Glasser-Greene-Johnson geometric coefficients and supporting flux-surface averages. All averages ⟨·⟩ are normalized flux-surface averages (⟨1⟩ = 1), and ‖∇ψ_N‖ is the gradient of the normalized poloidal flux.

fieldmeaning
E, FGlasser interchange parameters (enter D_I = E+F+H-¼)
GCoupling coefficient (curvature × pressure gradient)
HPfirsch-Schlüter coefficient
KGlasser parameter
MMass factor
avg_bsq_over_dpsisq⟨B²/‖∇ψN‖²⟩ — needed for τR
avg_bsq⟨B²⟩ — needed for τ_R
avg_dpsisq⟨‖∇ψ_N‖²⟩ — needed for the toroidal critical-Δ
f_trapLin-Liu & Miller 1995 trapped-particle fraction
R_majormajor radius (Rmax + Rmin)/2 over the surface, in m
eps_local(Rmax − Rmin)/2 / R_major — local inverse aspect ratio
p_localPlasma pressure at this surface [Pa]
p1_localdp/dψ at this surface
v1_localdV/dψ at this surface

H equals the H from mercier_scan! (LocalStability/h). f_trap, R_major and eps_local feed NeoclassicalResistivity.eta_neoclassical (Sauter, Angioni & Lin-Liu 1999, Phys. Plasmas 6, 2834; Lin-Liu & Miller 1995, Phys. Plasmas 2, 1666).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.resist_geometry — Method
resist_geometry(equil, psifac, q1; gamma=5/3) -> ResistGeometry

Glasser, Greene & Johnson 1975 (Phys. Fluids 18, 875) resistive-layer coefficients at psifac, geometric part only (no η or ρ); InnerLayer.GGJ.ggj_parameters adds τA and τR. Port of Fortran RDCON resist_eval.

Arguments

  • equil::PlasmaEquilibrium — the fully-solved equilibrium
  • psifac — normalized flux coordinate of the singular surface
  • q1 — dq/dψ at this surface (from SingType.q1)

Keyword arguments

  • gamma — adiabatic index (default 5/3)
Contract

psifac must be an interior surface (0 < ψ < 1) with nonzero q1, p1 = dp/dψ and p; the axis, a flat-pressure or a zero-shear surface gives Inf/NaN.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.MatchResult — Type
MatchResult

Matching coefficients and matched profiles, found in result.match. The profile fields are empty when the solve kept no Galerkin basis; the inner fields are empty with ideal.

Fields

  • cout, cin: (2msing, ncoil) outer and inner coefficients.
  • deltar: (msing, 2) inner-layer Δ per surface, columns (Δ₊, Δ₋) = (interchange, tearing).
  • rpec_eig: forced eigenvalue γ = 2πi·n·f per surface.
  • residual: relative residual of the linear solve.
  • bpen: (msing, ncoil) penetrated resonant field at each layer center.
  • reconnected_flux: (2msing, ncoil) Δ_coil + Δ_outᵀ·cout.
  • xi, xi_deriv: (mpert, ngrid, ncoil) matched outer ξ and ξ′, one column per coil.
  • inner_psi, inner_xi, inner_b: per surface, the inner ψ grid and the composite ξψ and b^ψ on it; empty unless the inner model returns real-ψ profiles (GGJModel(; solver=:galerkin) or `GGJModel(; realprofiles=true)`).
  • inner_params: per-surface layer parameters used (GGJParameters, CCCParameters).
  • model: the inner-layer model solved, with its backend options.
  • problem: the MatchProblem solved, with its per-surface η, ρ and rotation.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.MatchProblem — Type
MatchProblem(ffs; eta=nothing, rho=nothing, rotation=nothing, gamma=5/3, ideal=false)

Driven inner-layer matching on a finished force-free-states solve ffs: each rational surface is matched at the forced eigenvalue γ = 2πi·n·f, with f the plasma rotation frequency there. solve(prob, GGJModel()) (or another toroidal layer model, e.g. CCCModel()) returns a copy of ffs with the matched solution and the penetrated field bpen. ffs needs the Δ′ coil block, from Galerkin(; rpec_flag=true) or Riccati() with vac_flag=true.

Keywords

  • eta, rho, rotation: resistivity in Ω·m, mass density in kg/m³ and rotation frequency in Hz, a scalar for every surface or one value per ffs.surfaces entry (core to edge). Each one not given comes from the equilibrium's kinetic data, as the tearing problem's do: η from InnerLayer.layer_eta, ρ from InnerLayer.layer_rho, and the rotation f = ΩE/2π from the E×B rotation of [`InnerLayer.layeromega_E](@ref). Unused withideal=true`.
  • gamma: ratio of specific heats.
  • ideal: skip the inner layer and return the perfectly shielding solution.

Fields

  • ffs - The outer solve being matched; held by reference, not copied.
  • eta, rho, rotation - Per-surface η in Ω·m, ρ in kg/m³ and rotation frequency in Hz, following ffs.surfaces.
  • gamma - Ratio of specific heats.
  • ideal - Whether the inner layer is skipped.

Ref: Fortran rmatch match_rpec (match.f).

source
CommonSolve.solve — Method
solve(prob::MatchProblem, model) -> ForceFreeStatesResult

Match prob.ffs to the inner layer of model. The result has closure = :matched (:ideal with ideal=true), bpen, the MatchResult in result.match and the matched ξ. A :matched result drops the ideal δW (wp, free_boundary), so PerturbedEquilibrium skips its response rather than mixing ideal and matched physics.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.EdgeScanState — Type

EdgeScanState

Holds the state and results for the edge dW stability scan over ψ ∈ [dWedgescanstart, psilim]. Initialized and populated by `findmaxdWedge!; results written to HDF5 underEdgeScan/. The energies are generalized (W, N) pencil values: power-normalized and invariant to the working (Jacobian) coordinate (seepowernorm_matrix!`).

Fields

  • wvmat - Precomputed wv matrix spline (raw, no singfac); singfac applied analytically in free_compute_total.
  • wv_hint::Base.RefValue{Int} - Search hint for wvmat spline (different grid from equilibrium profiles).
  • psi, q - ψ and q values at each edge scan step.
  • total_eigenvalue, plasma_energy, vacuum_energy, vacuum_eigenvalue - Power-normalized energy components at each step (NaN for steps where the wp solve was singular). These drive the truncation choice and are written to EdgeScan/.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.OdeState — Type

OdeState

Mutable state of a Forward Euler-Lagrange integration: the stored solution, Gaussian-reduction records needed to undo it, and singular-surface asymptotic coefficients.

Fields

  • numpert_total::Int - Total number of (m, n) modes.
  • numunorms_init::Int - Allocated number of Gaussian-reduction records.
  • msing::Int - Number of singular surfaces (sizes ca_l/ca_r).
  • numsteps_init::Int - Initial allocation of stored steps.
  • step::Int - Index of the next stored step (1-based).
  • total_steps::Int - Total ODE steps taken, saved or not.
  • psi_store::Vector{Float64} - ψ at each stored step.
  • q_store::Vector{Float64} - q at each stored step.
  • u_store::Array{ComplexF64,4} - Solution (u₁, u₂) at each stored step, shape (numpert_total, numpert_total, 2, nstep).
  • du_store::Array{ComplexF64,3} - du₁/dψ at each stored step, shape (numpert_total, numpert_total, step); empty until materialize_derivative_stores! fills it (the galerkin-matched path supplies it at construction).
  • xi_s_store::Array{ComplexF64,3} - Clebsch displacement Ξs (Glasser 2016 Eq. 18) at each stored step; empty until materialized, like `dustore`.
  • du_store_populated::Bool - True once du_store/xi_s_store hold valid data in the final basis.
  • crit_store::Vector{Float64} - Critical eigenvalue (smallest eigenvalue of W⁻¹) at each stored step.
  • ca_r::Array{ComplexF64,4} - Asymptotic coefficients right of each singular surface, shape (numpert_total, numpert_total, 2, msing).
  • ca_l::Array{ComplexF64,4} - Asymptotic coefficients left of each singular surface, same shape.
  • ca_populated::Bool - True once an ideal crossing has filled ca_l/ca_r; false on kinetic and galerkin-matched runs, where the writer emits zero-extent datasets.
  • edge_scan::EdgeScanState - Edge dW scan results; a disabled sentinel (N_edge = 0) unless findmax_dW_edge! ran.
  • psifac::Float64 - Current ψ of the integrator.
  • q::Float64 - q at psifac.
  • u::Array{ComplexF64,3} - Current solution, shape (numpert_total, numpert_total, 2).
  • ising_start::Int - Index of the last singular surface inside the starting ψ.
  • needs_crossing::Bool - Whether a rational surface must be crossed after the current region.
  • nzero::Int - Number of detected zero crossings of the critical eigenvalue.
  • new::Bool - Whether the next norm call records fresh reference norms unorm0.
  • unorm::Vector{Float64} - Current solution-column norms.
  • unorm0::Vector{Float64} - Reference norms since the last reduction.
  • ifix::Int - Number of Gaussian reductions performed.
  • index::Array{Int,2} - Pivot column order for each reduction, shape (numpert_total, numunorms_init).
  • sing_flag::Vector{Bool} - Whether each reduction was at a singular surface.
  • zeroed_idx::Vector{Vector{Int}} - For each ideal crossing, the positions in index of the zeroed resonant solutions.
  • fixfac::Array{ComplexF64,3} - Gaussian-reduction factors, shape (numpert_total, numpert_total, numunorms_init).
  • fixstep::Vector{Int64} - Last stored step before each reduction.
  • spline_hint::Base.RefValue{Int} - Shared interval hint for profile splines evaluated at the same ψ.
  • mats_hint::Base.RefValue{Int} - Interval hint for the matrix splines; per OdeState, so per-thread copies do not race.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.column_abstol! — Method
column_abstol!(abstol, u, rtol) -> abstol

Per-column absolute tolerance max|u[:, j, k]|·rtol for each column j of U₁ (k = 1) and U₂ (k = 2), so each solution column's error is controlled relative to its own magnitude. An all-zero block (e.g. U₁ = 0 at a fixed start) takes the scale of its column's other block; the blocks differ in units, so this is a first-step safeguard.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_axis_init — Method
compute_axis_init(mats, profiles, intr, psi_low) -> (U1_init, U2_init)

Opt-in diagonal approximation to the axis Frobenius problem [Glasser Phys. Plasmas 2016 112506 Eq. 51], evaluated at finite psi_low rather than in the limit ψ → 0. Used only when frobenius_psi_max is positive and the integration starts at or below it.

For each mode, forms the 2×2 diagonal block of ψlow · M from the diagonal entries of F̄⁻¹, K̄, and Ḡ, discards mode coupling, and returns that block's eigenvector normalized so that U₂ = I (or U₁ = 1, U₂ = 0 when the momentum component underflows). The component ratio does not scale as a positive power of `psilow`. A negative Ḡ diagonal, including the m = 0 block, gives an imaginary conjugate pair, so the returned U₁ is non-real and which branch is stored follows the eigen-solver's column order.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_delta_prime_from_ca! — Method
compute_delta_prime_from_ca!(odet, intr, equil)

Stub, not physically valid. Fill each surface's delta_prime with the per-surface estimate (1 - ca_l[i,c,2,s]) / (4π²·psio) from the asymptotic coefficients, c being the column in which the small solution of resonance i starts. It ignores inter-surface coupling and the vacuum, so it does not agree with the physical ForceFreeStatesResult.delta_prime.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_node_xi_s! — Method
compute_node_xi_s!(xi_s, du1, u1, mats, psieval; kinetic=false, hint=Ref(1))

Evaluate Ξs = -A⁻¹(B·Ξ′ψ + C·Ξψ) [Glasser Phys. Plasmas 2016 112506 Eq. 18] at psieval into `xis.du1andu1are the Ξ′_ψ and Ξ_ψ blocks at that ψ (anel_derivatives!result and its input). Withkinetic=true` the non-Hermitian kinetic A is used.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_solution_norms! — Method
compute_solution_norms!(u::Array{ComplexF64,3}, odet::OdeState, ctrl::ForceFreeStatesControl, intr::ForceFreeStatesInternal, sing_flag::Bool)

Compute the column norms of u₁ and apply apply_gaussian_reduction! to u in place when their growth since the last reduction exceeds ctrl.algorithm.renorm_threshold, and always when sing_flag is set. The first call after a reduction records reference norms; if sing_flag forces a reduction there, it keeps the previous reduction's pivot order. Errors if any norm is zero. Port of Fortran ode_unorm.

Arguments

  • u - Solution array, updated in place (the integrator state, to avoid copies)
  • sing_flag - Whether this call is at a singular surface
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.cross_ideal_singular_surf! — Method
cross_ideal_singular_surf!(odet, ctrl, equil, intr, ising, basis)

Cross ideal singular surface ising in its asymptotic basis [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 36]: the solutions are expanded in the left basis, the column carrying each resonance's big solution ends at the surface, the nonresonant coefficients continue into the right basis, and each small solution starts there in the freed column. basis is the surface's entry of asymptotic_bases. Records both coefficient sets in odet.ca_l and odet.ca_r, and the column reduction for transform_u!. Fortran ode_ideal_cross steps across with a trapezoidal rule instead.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.el_derivatives! — Method
el_derivatives!(du, u, kinetic, equil, mats, intr, psieval, spline_hint, mats_hint) -> q

Euler-Lagrange (or, when kinetic is true, FKG) derivative kernel: writes du₁/dψ and du₂/dψ at psieval into du and returns q there, for any number of solution columns. Holds no state of its own — the two hints are the caller's interval-search accelerators, so concurrent callers just pass their own.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.findmax_dW_edge! — Method
findmax_dW_edge!(odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal)

Fill odet.edge_scan with the total dW at every stored step in [ctrl.dW_edge_scan_start, intr.psilim] and return the stored-step index of the peak total eigenvalue (NaN steps ignored).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.forward_eulerlagrange_integration — Method
forward_eulerlagrange_integration(ctrl, equil, mats, intr; verbose=intr.verbose) -> (odet, nothing)

Forward branch of eulerlagrange_integration: integrates chunk by chunk from the axis, applying Gaussian reduction whenever a solution norm ratio exceeds ctrl.algorithm.renorm_threshold and undoing it via transform_u! at the end, so odet.u_store comes back dense in the axis basis. ctrl.algorithm must be a Forward, whose settings it reads; verbose overrides intr.verbose for progress logging.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.initialize_el_at_axis! — Method
initialize_el_at_axis!(odet::OdeState, ctrl::ForceFreeStatesControl, mats::MatrixSplines, profiles::Equilibrium.ProfileSplines, intr::ForceFreeStatesInternal)

Initialize the OdeState at the axis start: psifac, ising_start and u. The default ctrl.frobenius_psi_max = 0 uses the fixed start, U₁ = 0, U₂ = I, with no warning. The Frobenius start is used only when frobenius_psi_max is positive and the starting surface lies at or below it.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.integrate_el_region! — Method
integrate_el_region!(odet, ctrl, equil, mats, intr, chunk)

Integrate the Euler-Lagrange equations over chunk, applying Gaussian reduction and storing steps in odet from a per-step callback. Steps are stored densely near both chunk ends (in q), in the edge-scan band, and every save_interval steps otherwise.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.ode_itime_cost — Method
ode_itime_cost(psi1, psi2, intr) -> Float64

Relative ODE integration cost of [ψ₁, ψ₂] from STRIDE's empirical log-divergent model (Glasser 2018), with coefficients ODE_COST_AXIS, ODE_COST_RAT, ODE_COST_EDGE. Additive over sub-intervals, so balance_integration_chunks can bisect for equal cost.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.scan_edge_dW! — Method
scan_edge_dW!(odet, ctrl, equil, mats, intr; verbose=intr.verbose) -> Bool

Record the edge-dW scan over [dWedgescanstart, psilim] on `odet.edgescan. WithtruncateatdWpeak, the scan's peak becomes the plasma edge viatruncateintegration!`; otherwise the integration is left untouched. Returns whether it truncated.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_der! — Method
sing_der!(
    du::Array{ComplexF64,3},
    u::Array{ComplexF64,3},
    params::Tuple{ForceFreeStatesControl, Equilibrium.PlasmaEquilibrium, MatrixSplines, ForceFreeStatesInternal, OdeState, IntegrationChunk},
    psieval::Float64
)

In-place Euler-Lagrange derivative du/dψ at psieval [Glasser Phys. Plasmas 2016 112506 Eq. 24], ideal or kinetic, in the (du, u, p, t) form the ODE solver calls; du and u have shape (numpert_total, ncolumns, 2). Ξs is not computed here; see [`computenodexis!`](@ref).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.solve_el — Method
solve_el(prob, rtol; callback=COLUMN_ABSTOL_CALLBACK, save_everystep=false)

Vern9 solve of an Euler-Lagrange problem with the per-column abstol of column_abstol!, returning the end state or, with save_everystep, the state at every solver step. A custom callback must refresh that abstol itself, after any reduction or renormalization of the state. Errors when the solver stops short of the interval's end (e.g. the step size underflows), naming the ψ reached.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates._find_rational_surfaces — Method
_find_rational_surfaces(equil::Equilibrium.PlasmaEquilibrium, nlow::Int, nhigh::Int)

Locate all rational q-surfaces q = m/n for n in nlow:nhigh by Brent bisection between consecutive extrema of the q-profile (reverse shear gives one root per monotone segment). Returns a vector of (m, n, psifac) named tuples in discovery order (n outer, ψ-interval inner). Requires equilibrium_qfind! to have populated equil.params.qextrema_*.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.fbar_block_conditions — Method
fbar_block_conditions(psi, kin, equil, intr; hint=Ref(1)) -> Vector{Float64}

Condition number of each toroidal-mode block of the kinetic F̄ matrix at ψ, one entry per n in intr.nlow:intr.nhigh.

F̄(i,j) = q₁·f0(i,j)·q₂ - q₁·P(i,j) - conj(P†(j,i))·q₂ + R1(i,j)

where q₁ = m₁ - n·q(ψ), q₂ = m₂ - n·q(ψ) are the direct singularity factors. The axisymmetric F̄ is block-diagonal in n, so each block is conditioned on its own; the condition number of the whole matrix would mix the scales of different n.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.find_kinetic_singular_surfaces! — Method
find_kinetic_singular_surfaces!(mats, equil, intr; ngrid=2000, cond_threshold=1e8)

Find kinetically displaced singular surfaces, where cond(F̄) of the kinetic F̄ matrix peaks, and populate intr.kinsing, intr.kmsing and the intr.kinsing_scan_* diagnostics. Condition-number peaks are used instead of det(F̄) zeros for scale invariance.

Each toroidal-mode block of F̄ is scanned on a dense ψ grid on its own; its local maxima are refined by golden-section minimization of -cond and filtered by threshold and the resonance condition. Each surface records the (m, n) of the blocks that produced it, and peaks of different n within one scan spacing of each other are merged into a single surface.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.qlow_start_psi — Method
qlow_start_psi(qlow, equil) -> ψ

Lower integration bound set by qlow: the outermost crossing of q = qlow, so the whole q < qlow region inside it is excluded, whether a monotonic core (q ≤ 1 sawtooth surfaces) or a reversed-shear ring around qmin. Read from the same spline q extrema `singfind!` brackets its roots with, so a dip between grid nodes counts; the root is bracketed on the monotone stretch past the outermost extremum below qlow. Returns the first grid node when q ≥ qlow everywhere.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.rational_psi_nodes — Method
rational_psi_nodes(equil::Equilibrium.PlasmaEquilibrium; nlow::Int, nhigh::Int=nlow)

Unique ψ_N locations of all rational surfaces q = m/n for n in nlow:nhigh, sorted increasing. Used as mandatory knots for the two-pass equilibrium grid refinement. Roots are deduplicated by (q, ψ), so several (m, n) of equal ratio collapse to one node while the two crossings of one rational on a reverse-shear profile stay distinct.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_find! — Method
sing_find!(intr::ForceFreeStatesInternal, equil::Equilibrium.PlasmaEquilibrium)

Locate singular rational q-surfaces (q = m/n) by bisection between extrema of the q-profile, and store their properties in intr.sing, sorted by increasing ψ. Roots of equal ratio m/n at the same ψ (e.g. (2,1) and (4,2)) merge into one surface carrying all its (m, n); the two crossings of one rational on a reverse-shear profile stay separate surfaces with opposite-sign q′.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_lim! — Method
sing_lim!(intr::ForceFreeStatesInternal, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium;
          psilim_cap=nothing)

Set the outer integration limits intr.psilim, intr.qlim and intr.q1lim.

The target qlim starts at min(equil.params.qmax, ctrl.qhigh). When psilim_cap is given and lies inside the domain, qlim is further capped at q(psilim_cap): the resistive-layer overlap point of Fitzpatrick, Nucl. Fusion 2025 Sect. 5.9, past which no surface retains a well-separated inner region. The cap only ever narrows the domain; one beyond psihigh is inert.

If truncate_at_rational_offset is true, qlim is then moved to (last rational + rational_offset_fraction) / n and stepped back by 1/n until it no longer exceeds the bound above, so rational_offset_fraction never extends the domain past qmax, qhigh or the cap. A bound that falls exactly on, or less than rational_offset_fraction / n above, a rational excludes that rational. If qlim < qmax, a Newton iteration finds the matching psilim (outer crossing on a reversed-shear profile); otherwise the equilibrium edge values are used.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_min! — Method
sing_min!(intr::ForceFreeStatesInternal, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium)

Set the lower integration bound intr.psilow to qlow_start_psi, the one bound every integrator starts from. Excluding the q < qlow region matters most for the outer-region Galerkin solve, whose Hermite FEM would otherwise integrate through unhandled q ≤ 1 ideal singularities and contaminate Δ′ at the innermost kept surface.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_sing_asymptotics — Method
compute_sing_asymptotics(singp, ctrl, equil, mats, intr; sig=1.0, sing_order=ctrl.frobenius_order) -> SingAsymptotics

Frobenius power series (vmat) of the asymptotic solutions on one side of a singular surface, Glasser Phys. Plasmas 2016 112506 Eqs. 41-48.

Arguments

  • singp::SingType: Singular surface parameters
  • sig: Side of the surface, -1.0 left or +1.0 right
  • sing_order: Expansion order, defaulting to ctrl.frobenius_order. The Galerkin path overrides it per surface (frobenius_order, raised for high-Mercier-index surfaces).

Warns once per surface when a resonant block has abs(tr(M₀))/2 above both 1e-3 * abs(α) and the round-off floor 64 * Base.eps(Float64) * opnorm(M₀, Inf).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_sing_mmat! — Method
compute_sing_mmat!(mmat, singp, ctrl, profiles, mats, intr; sig=1.0, sing_order=ctrl.frobenius_order)

Fill mmat with the Taylor coefficients Mk of the matrix M at a singular surface (Glasser 2016 Eqs. 43-44), with sig flipping odd ψ-derivatives for the left side. Port of Fortran `singmmat, with dense matrices; Hermitian matrices store only their lower triangle (suffix_lower) and are used throughHermitian(·, :L)`.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.resonant_block_exponents — Method
resonant_block_exponents(m0, sig) -> (α, p_big, p_small)

Eigenvalues λ = tr/2 ∓ √(tr²/4 − det) of one resonant 2×2 M₀ block. α = √(tr²/4 − det) is the Mercier half-separation. Powers are sig·λ, big solution (more negative real part) first. A traceless block returns α = √(−det) and (−α, +α). When tr²/4 − det is negative (Mercier-unstable), α is taken with Im α > 0, so both sides of the surface get the same α and the same big root whatever the round-off sign.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_get_ca — Method
sing_get_ca(u::Array{ComplexF64,3}, ua::Array{ComplexF64,3}, intr::ForceFreeStatesInternal)

Asymptotic expansion coefficients ca of u in the basis ua (Glasser 2016 Eq. 50). Port of Fortran sing_get_ca.

Arguments

  • u::Array{ComplexF64,3}: Current solution matrix, shape (numperttotal, numperttotal, 2)
  • ua::Array{ComplexF64,3}: Asymptotic solution matrix, shape (numperttotal, 2·numperttotal, 2)
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_get_dua_res! — Method
sing_get_dua_res!(out, sing_asymp, dpsi) -> out

Derivative of the asymptotic series with respect to the positive distance dpsi = |ψ − ψ_res|, for the big (col 1) and small (col 2) resonant columns only, into the caller-provided out of shape (numpert_total, 2, 2); Fortran sing_get_dua restricted to those columns. Direction is carried by the left or right SingAsymptotics, so dpsi is positive and the caller applies the d/dψ sign on the left. Allocation-free; scalar per-term exponents replace a full power array. See the section comment.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_get_ua — Method
sing_get_ua(sing_asymp::SingAsymptotics, dpsi::Float64) -> ua

Evaluate the asymptotic solutions at distance dpsi from the surface, on the side sing_asymp was built for. Port of Fortran STRIDE sing_get_ua.

Arguments

  • sing_asymp::SingAsymptotics: Pre-computed asymptotic data (must be left or right specific)
  • dpsi::Float64: Positive distance from singular surface = |ψ - ψ_res|
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_get_ua_res_cut! — Method
sing_get_ua_res_cut!(out, sing_asymp, dpsi) -> out

Leading-order ("cut") form of sing_get_ua_res!: keeps only the t = 0 term of the Frobenius series instead of summing all 2·sing_order terms, then applies the same unshear.

Used for the cut outer solution, the background the resistive inner-layer solution is added to in the composite solution; full minus cut is the higher-order content the layer solution replaces.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.sing_matvec! — Method
sing_matvec!(matvec, kmat, gmat, d1, tmp, sfvec, mats, intr, psi, q, ua, dua) -> matvec

Apply the Euler-Lagrange residual operator L u = -(F u' + K u)' + (K† u' + G u) to the asymptotic solutions ua and their ψ-derivatives dua, as Fortran sing_matvec (sing.f), for the resonant-quadrature integrand. It uses the reduced K̄ and Ḡ splines with the direct singular factor sfvec = m − n q on u' = dua[:,:,1]; ua[:,:,2] is the canonical momentum F u' + K u, so -dua[:,:,2] = -(F u' + K u)'. All scratch is caller-owned: kmat/gmat are N×N, d1/tmp/sfvec are length-N, matvec is N×size(ua,2). The accumulation order (separate gmat*ua into tmp, then add) is kept on purpose: a fused 5-arg mul! would round differently, and the ill-conditioned near-singular resonant solve amplifies a 1e-16 change into ~1e-3 in Δ′.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.solve_higher_order_vmat! — Method
solve_higher_order_vmat!(vmat, mmat, m0mat, alpha, r1, r2, n1, n2, power, intr, k; sig=1.0)

Solve for order k of the power series vmat (Glasser 2016 Eq. 47). Port of Fortran sing_solve.

Arguments

  • vmat::Array{ComplexF64,4}: V matrix power series (modified in-place)
  • mmat::Array{ComplexF64,4}: M matrix power series
  • m0mat::Matrix{ComplexF64}: Zeroth order M matrix
  • alpha::Vector{ComplexF64}: Mercier exponent of each resonant block
  • r1, r2, n1, n2::Vector{Int}: Resonant and nonresonant indices
  • power::Vector{ComplexF64}: Frobenius power of each solution column (0 for nonresonant)
  • k::Int: The current order in the power series expansion
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.asymptotic_bases — Method
asymptotic_bases(chunks, ctrl, equil, mats, intr) -> Dict{Int,NamedTuple}

For every crossed surface, keyed by its index in intr.sing: the distance dpsi from it at which its crossing chunk ends, the asymptotic series on each side (left_series, right_series), and those series evaluated at dpsi (left, right, each N × 2N × 2).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.crossing_fill — Method
crossing_fill(series, coefficients, psifac, sig, dpsi, fractions) -> Vector{Tuple{Float64,Array{ComplexF64,3}}}

ψ and state (N × ncol × 2), at the distances fractions .* dpsi from the surface at psifac on side sig (-1 left, +1 right), of the solutions with asymptotic coefficients (2N × ncol) in the series of that side [Glasser 2016, Phys. Plasmas 23, 112506, Eq. 45].

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.eliminate_big_solutions! — Method
eliminate_big_solutions!(ca, ipert_res) -> (pivots, factors)

Column-reduce the asymptotic coefficients ca (N × N × 2: basis solution, solution, big or small half of the basis) so that one column, pivots[i], carries the big solution of each resonance ipert_res[i]. factors[i, j] is the multiple of that column added to column j.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.fill_crossings! — Method
fill_crossings!(odet, bases, fractions, equil, intr)

Add states to the integrator's stored solution inside the crossing distance of every crossed surface, on both sides, at fractions of that distance (crossing_fill). That solution is the ideal one, so its big-solution coefficient is set to zero; solutions that carry a big solution are filled by outer_solution_basis. crit_store is interpolated linearly across each surface.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.start_small_solutions! — Method
start_small_solutions!(ca, ipert_res, pivots)

Turn reduced left-side coefficients ca into right-side ones [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 36]: the resonant coefficients vanish and column pivots[i], which carried the big solution of resonance i, becomes its small solution.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.FKGMatrices — Type
FKGMatrices

Kinetic-MHD matrix ψ-splines assembled by build_kinetic_matrix_splines. Present on a MatrixSplines only for kinetic runs; its presence means the solution obeys the FKG ODE rather than the ideal Euler-Lagrange relation.

The FKG system is non-Hermitian, so the adjoint side of each reduced block is a distinct matrix rather than a transpose of the forward one. The _adj suffix marks those adjoint-side counterparts (Fortran's aat arrays); they must be evaluated, never derived from their unsuffixed partner.

Fields

  • A_spline, B_spline, C_spline - the kinetic-modified A, B, C consumed by sing_der!. Unlike their ideal counterparts, A here is non-Hermitian and requires an LU rather than a Cholesky.
  • F0_spline - reduced F̄ of the kinetic system, F₀ = Fprim − D†Akin⁻¹D.
  • P_spline, P_spline_adj - P = (iD)†Akin⁻¹Bk and its adjoint-side counterpart.
  • Kk_spline, Kk_spline_adj - kinetic K̄ = E − (iD)†Akin⁻¹Ckin and its adjoint-side counterpart.
  • R1_spline, R2_spline, R3_spline - blocks built from the D- and E-perturbation kinetic components of the kinetic energy and torque matrices, which have no ideal counterpart. R3 is the adjoint-side partner of R2.
  • G_spline_adj - adjoint-side Ḡ, Ḡadj = Hkin − Cadj†Akin⁻¹C_kin.

All nine reduced blocks are pre-computed per ψ by the FKG Schur complement (Logan 2015 Appendix C, Eqs C.1-C.11) so sing_der! can assemble the ODE right-hand side with explicit (m−nq) factors instead of 1/(m−nq).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.IdealMatrices — Type
IdealMatrices

Ideal-MHD stability matrix ψ-splines assembled by build_matrix_splines. Each field flattens a numpert_total × numpert_total matrix to numpert_total^2 complex series (J_spline to 2·mpert−1), following the appendix of Glasser Phys. Plasmas 2016 112506.

Suffixes: _prim is a primitive (pre-Schur-complement) form, kept because the kinetic reduction needs the unreduced matrix; _lower is a Cholesky factor rather than the matrix itself; _gal is the Galerkin solver's variant of the same matrix.

Fields

  • A_spline, B_spline, C_spline - the ideal A, B, C. In a kinetic run these are NOT what the ODE integrates; see FKGMatrices.
  • D_spline_prim, E_spline_prim - pre-Schur-reduction geometric forms (D = χ₁·(g23 + q·g33·m/n); E = (-χ₁/n)·(q'·χ₁·g33 - 2π·i·χ₁·g31·singfac + jθ·I)). Downstream kinetic FKG Schur complements consume these primitive forms.
  • H_spline - primitive Ḡ before the Schur complement (Ḡ = H − C†A⁻¹C), also consumed by the kinetic reduction.
  • F_spline_lower - reduced F̄ as its lower-triangular Cholesky factor L, F̄ = L·Lᴴ. The ideal Euler-Lagrange kernel only ever solves against F̄, so the factor is stored instead of F̄ itself.
  • F_spline_prim - primitive F before the Schur complement (for kinetic).
  • F_spline_gal - independently interpolated reduced Hermitian F̄, retained for coefficient diagnostics.
  • K_spline, G_spline - reduced K̄ and Ḡ of the Euler-Lagrange system d/dψ(F̄·ξ′ + K̄·ξ) = K̄†·ξ′ + Ḡ·ξ (Eqs A5-A7).
  • J_spline - Jacobian Fourier band (2·mpert−1 conjugate-symmetric coefficients per surface), used to assemble the power-normalization matrix N in Free.jl.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.MatrixSplines — Type
MatrixSplines

Fourier-fitted stability matrices for one run. kinetic === nothing marks an ideal run; otherwise the kinetic matrices are authoritative for the ODE and the ideal ones remain available for output and for the Galerkin/vacuum paths that are defined only in the ideal basis.

Fields

  • ideal::IdealMatrices - always present.
  • kinetic::Union{Nothing,FKGMatrices} - present iff the solve is kinetic (ctrl.kinetic !== nothing).
  • _hint::Base.RefValue{Int} - shared bracket-search hint for sequential (single-threaded) evaluation. Not thread-safe: parallel paths must pass their own hint.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.MetricData — Type
MetricData

Metric tensor components on the (ψ, θ) grid and their Fourier representation.

Fields

  • mpsi::Int: Number of radial grid points minus one.
  • mtheta::Int: Number of poloidal grid points minus one.
  • xs::Vector{Float64}: Radial coordinates (normalized poloidal flux ψ_norm).
  • ys::Vector{Float64}: Poloidal angle coordinates θ in radians (0 to 2π).
  • fs::Array{Float64, 3}: The raw metric data on the grid, size (mpsi, mtheta, 8). The 8 quantities are: g¹¹, g²², g³³, g²³, g³¹, g¹², J, ∂J/∂ψ.
  • fourier_coeffs::Utilities.FourierCoefficients: The FFT coefficients (no spline interpolation needed).
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.build_kinetic_metric_matrices — Method
build_kinetic_metric_matrices(equil, intr, metric) → NamedTuple

Compute the 5 kinetic geometric matrices (s, t, x, y, z) needed by KineticForces.BounceAveraging for kinetic W vector outer products, for every toroidal mode n in intr.nlow:intr.nhigh. Only Y (through m - nq) and Z (through n) depend on n; S, T and X are repeated in each block so all five share one layout.

Returns

NamedTuple (smats, tmats, xmats, ymats, zmats) of CubicSeriesInterpolants, each mapping ψ → a complex vector of npert stacked mpert×mpert blocks (column-major, length mpert²·npert); block k holds n = nlow + k - 1. Use kinetic_metric_block to extract one block.

Reference: [Logan et al., Phys. Plasmas 20, 122507 (2013)]

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.build_matrix_splines — Method
build_matrix_splines(equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal, metric::MetricData) -> MatrixSplines

Assemble the ideal-MHD stability matrices on every ψ surface of metric and fit them as ψ-splines (Glasser Phys. Plasmas 2016 112506 Appendix A). F̄ is stored as its lower Cholesky factor (F̄ = L·Lᴴ), since sing_der! only solves against it; see IdealMatrices for the fields.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.core_capped_knots — Method
core_capped_knots(xs, rationals) -> Vector{Int}

Indices of xs the EL coefficient splines keep. Below the innermost rational (or ψ = 0.1, whichever is smaller) knots are thinned to log-uniform spacing Δψ ≥ 0.05·ψ, which resolves the near-axis Frobenius power laws at constant relative accuracy and stops dense core packing from amplifying node error into spline third-derivative jumps that throttle the Euler-Lagrange step size. Knots inside a rational's resolution window (Equilibrium.RATIONAL_RES_RADIUS) are always kept.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.make_metric — Method
make_metric(equil::Equilibrium.PlasmaEquilibrium, mpert::Int) -> MetricData

Construct the metric tensor data on the (ψ, θ) grid of equil, Fourier-decomposed up to harmonic mpert - 1. The coefficients stored in metric.fs are:

  1. g_ψψ / J
  2. g_θθ / J
  3. g_ζζ / J
  4. g_θζ / J
  5. g_ζψ / J
  6. g_ψθ / J
  7. J (Jacobian)
  8. ∂J/∂ψ
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.KineticMatrices — Type
KineticMatrices

The kinetic energy and torque matrices of one perturbed-plasma problem, from kinetic_matrices or computed inside solve. Pass them back as ForceBalanceProblem(eq; kinetic=km) to solve again without evaluating the kinetic model, for example in a kinetic_factor scan; solve rejects matrices made for another ψ grid or mode range. The matrices are stored unscaled and solve applies its own kinetic_factor, but the knots the build added where F̄ is near-singular were placed at the kinetic_factor recorded here.

Fields

  • source - The kinetic source evaluated: a KineticForces.KineticForcesControl or a TestKineticMatrices.
  • kinetic_factor::Float64 - The kinetic_factor the ψ grid was refined at.
  • psi::Vector{Float64} - The ψ grid of the matrices: the problem's grid plus the knots the build added.
  • problem_psi::Vector{Float64} - The problem's own ψ grid, which a solve reusing the matrices must have.
  • nlow, nhigh, mlow, mhigh - The toroidal and poloidal mode ranges.
  • axis_psi_c::Float64 - The near-axis validity boundary of the kinetic model; 0 for test matrices.
  • kw::Array{ComplexF64,3}, kt::Array{ComplexF64,3} - The energy (W) and torque (T) matrices, indexed (ψ, mode pair, component) with the six components A, B, C, D, E, H.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates._compute_fkg_matrices — Method
_compute_fkg_matrices(mats, equil, intr, metric, kw_flat, kt_flat) -> MatrixSplines

Pre-compute the derived F, K, G kinetic matrices at each ψ grid point and return a new MatrixSplines whose kinetic field holds them alongside the kinetic-modified A/B/C; mats.ideal is carried over. These are the Schur-complement reductions of the ideal (A,B,C,D,E,H) and kinetic (W,T) primitives for the non-Hermitian kinetic ODE system (Logan 2015 Appendix C, Eqs C.1-C.11). Port of Fortran fourfit_kinetic_matrix method=0 (fourfit.F).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.evaluate_kinetic_matrices — Method
evaluate_kinetic_matrices(ctrl, equil, mats, intr, metric; calculated_source=nothing, axis_validity_psi_c=0.0)
    -> KineticMatrices

Evaluate the kinetic energy (W) and torque (T) matrices of ctrl.kinetic on the problem's ψ grid:

  • TestKineticMatrices: X-shaped test matrices of its scale relative to ideal matrix Frobenius norms (Ak, Dk, Hk Hermitian; Bk, Ck, Ek non-Hermitian)
  • a KineticForcesControl: compute via the calculated_source callback, which receives (ctrl, equil, intr, metric, mats) and returns (kw_flat, kt_flat) of shape (mpsi, np^2, 6). solve injects KineticForces.compute_calculated_kinetic_matrices, because ForceFreeStates is loaded before KineticForces. Knots are added across the near-axis validity band and where F̄ at ctrl.kinetic_factor has near-singular structure the grid does not resolve.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.refine_grid_at_fbar_peaks — Method
refine_grid_at_fbar_peaks(xs, kw, kt, evaluate, kin, equil, intr, psi_c;
                          ngrid=1000, relaxed_frac=0.01, target=3, max_add=24) → (xs, kw, kt)

Insert kinetic evaluation knots across near-singular structure of F̄ that the grid does not resolve. Scans cond(F̄) (the same operator find_kinetic_singular_surfaces! searches — Park & Logan Eq. 70, so shifted and split resonances are included), takes peaks between relaxed_frac·threshold and the singular threshold, measures each peak's FWHM, and adds knots only where fewer than target knots lie inside it. New points respect MIN_KNOT_SPACING, stay above the near-axis validity band, and are capped at max_add; each costs one kernel evaluation and the existing values are reused. A well-resolved grid inserts nothing.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.TestKineticMatrices — Type
TestKineticMatrices(; scale)

Synthetic X-shaped kinetic matrices for exercising the kinetic code path in tests, with no physical meaning: scale times the ideal matrices' Frobenius norms (Ak, Dk, Hk Hermitian; Bk, Ck, Ek not). Pass it as ForceBalanceProblem(eq; kinetic=TestKineticMatrices(; scale)); a deck cannot select it.

Fields

  • scale::Float64 - Size of the test matrices relative to the ideal matrix norms.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates._build_x_matrix — Method
_build_x_matrix(mpert, mlow, sigma; hermitian=true)

Build an mpert×mpert X-shaped matrix: σ on the diagonal, and on the m ↔ -m anti-diagonal i·sign(m)·σ (hermitian=true, for Ak, Dk, Hk; Logan 2015 Eqs 7.30, 7.33, 7.35) or sign(m)·σ (hermitian=false, for Bk, Ck, Ek; Eqs 7.31, 7.32, 7.34).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.fixed_kinetic_matrices — Method
fixed_kinetic_matrices(mpert, np, mpsi, sigma, mlow, mats, xs)

Build X-shaped test kinetic energy matrices for all 6 components, each scaled by sigma times the Frobenius norm of the corresponding ideal matrix at each ψ, so σ is a dimensionless strength:

ComponentMatrixCouplingHermitianRelative to
1AkWz†·WzYes‖A(ψ)‖_F
2BkWz†·WxNo‖B(ψ)‖_F
3CkWz†·WyNo‖C(ψ)‖_F
4DkWx†·WxYes‖D(ψ)‖_F
5EkWx†·WyNo‖E(ψ)‖_F
6HkWy†·WyYes‖H(ψ)‖_F

Torque matrices are zero. Returns (kw_flat, kt_flat), each of shape (mpsi, np^2, 6).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_smallest_eigenvalue — Method
compute_smallest_eigenvalue(u) -> crit, nonherm

Form W⁻¹ = U₁U₂⁻¹ from the solution u, symmetrize it, and return its signed eigenvalue of smallest magnitude. Also flags whether W⁻¹ was non-Hermitian beyond tolerance before symmetrizing.

Returns

  • crit::Float64: the computed scaled critical eigenvalue
  • nonherm::Bool: true if W⁻¹ was non-Hermitian beyond tolerance (> 1e-3)
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.is_zero_crossing — Method
is_zero_crossing(odet, profiles, istep) -> Bool

Whether odet.crit_store (the smallest-magnitude eigenvalue of W⁻¹, scaled by (dV/dψ)²) changes sign between steps istep - 1 and istep at a genuine crossing rather than noise: its value at the interpolated crossing must lie between its two neighbors and well below both.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.materialize_derivative_stores! — Method
materialize_derivative_stores!(odet, equil, mats, intr) -> Bool

Fill odet.du_store (dΞψ/dψ) and `odet.xisstorefrom the stored solution, returning whether they hold valid data afterwards. Idempotent: a no-op whendustore_populated` is already true, so the galerkin-matched path keeps its analytic derivatives.

Derivatives are recomputed rather than accumulated during integration because they are needed only at saved nodes, not at every Runge-Kutta stage. Recomputing after the Gaussian fixup transforms and the free-boundary normalization is exact rather than merely close: the Euler-Lagrange system is linear in u, and both operations right-multiply the solution by a mixing matrix T, so du(ψ, u·T) = du(ψ, u)·T.

Returns false without allocating when there is nothing to work from: no mats or no stored steps.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.store_ode_data! — Method
store_ode_data!(odet::OdeState, psi::Float64, u)

Save the current integration state at psi: u plus odet.q, which callers set for the accepted point. Derivatives are not stored — materialize_derivative_stores! recomputes them from (psi_store, u_store) after integration, where they are actually consumed.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.FreeBoundaryResult — Type
FreeBoundaryResult

Result of the free-boundary calculation, returned by free_run. All matrices are in the ξ Fourier basis and are numpert_total × numpert_total; the energies are generalized (W, N) pencil values, power-normalized and invariant to the working (Jacobian) coordinate.

Fields

  • wt::Matrix{ComplexF64} - Eigenvector matrix of W·v = λ·N·v. Columns are eigenmodes sorted most-unstable first, normalized to unit power norm v†·N·v = 1.
  • wt0::Matrix{ComplexF64} - Total-energy matrix W = wp + wv before diagonalisation
  • wp::Matrix{ComplexF64} - Plasma energy matrix
  • wv::Matrix{ComplexF64} - Vacuum energy matrix, singfac-scaled at qlim
  • ep::Vector{ComplexF64} - Plasma energy per eigenmode (power quotient v†·wp·v with v†·N·v = 1)
  • ev::Vector{ComplexF64} - Vacuum energy per eigenmode (power quotient v†·wv·v with v†·N·v = 1)
  • et::Vector{ComplexF64} - Total energy eigenvalues of the pencil (W, N); et = ep + ev per mode
  • n_tor_idx::Vector{Int} - 0-based toroidal mode number index of each sorted eigenvalue
  • vacuum_eigenvalue::Float64 - Least stable (minimum) eigenvalue of the pencil (wv, N), clamped to zero
  • plasma_pts, wall_pts::Matrix{Float64} - Cartesian (x, y, z) surface coordinates, numpoints × 3, retained for HDF5 output
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_scaled_wv — Method
compute_scaled_wv(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal) -> (wv, vac)

Vacuum response matrix at the control surface intr.psilim, scaled by the singular factors (m - n·q)(m' - n'·q) [Chance Phys. Plasmas 1997 2161 eq. 126]. Handles 2D single-n, 2D multi-n block-diagonal and 3D vacuum problems through Vacuum.compute_vacuum_response.

Needs no ODE state, so both the free-boundary calculation and the standalone Galerkin solve share it. Returns the scaled wv alongside the full vacuum response vac, whose surface point clouds the free-boundary result carries to HDF5. wv aliases vac.wv, which is scaled in place.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.free_compute_total — Method
free_compute_total(equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal, odet::OdeState) -> NamedTuple

Energies of the least stable mode at odet.psifac: a trimmed free_run called by findmax_dW_edge! at each step of the edge dW scan. The raw vacuum matrix comes from odet.edge_scan.wvmat (see free_compute_wv_spline) and is singfac-scaled here.

Returns

NamedTuple (total_eigenvalue, plasma_energy, vacuum_energy, vacuum_eigenvalue).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.free_compute_wv_spline — Method
free_compute_wv_spline(ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, intr::ForceFreeStatesInternal)

Cubic ψ-spline of the raw (not singfac-scaled) vacuum response matrices from ctrl.dW_edge_scan_start to intr.psilim, sampled evenly in q with at least 4 points per q-window, for fast evaluation in free_compute_total during the edge dW scan.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.free_run — Method
free_run(odet::OdeState, ctrl::ForceFreeStatesControl, equil::Equilibrium.PlasmaEquilibrium, mats::MatrixSplines, intr::ForceFreeStatesInternal) -> FreeBoundaryResult

Free-boundary energies at intr.psilim: the plasma response from the ODE edge state plus the singfac-scaled vacuum matrix, diagonalized as the pencil (W, N). Returns the eigenmodes and their plasma/vacuum/total energies as a FreeBoundaryResult.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.normalize_eigenfunctions! — Method
normalize_eigenfunctions!(odet::OdeState, wt::AbstractMatrix{ComplexF64}, psio::Float64) -> OdeState

Rescale the stored EL solution vectors in odet.u_store (and du_store/xi_s_store when a path has already filled them) so the edge displacement matches the free-boundary eigenvectors wt (scaled by 2π·psio·1e-3). Modifies odet in place. Call after free_run when downstream code consumes the stored ξ profiles.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.power_norm_matrix! — Method
power_norm_matrix!(Nmat, jmat, mpert, npert, dV_dpsi) -> Nmat

Assemble the power-normalization (surface-norm) matrix N from the conjugate-symmetric Jacobian Fourier band jmat (length 2·mpert−1, evaluated from the mats.ideal.J_spline spline), such that

ξ†·N·ξ = ∮ J |ξ(θ)|² dθ / (dV/dψ) = ⟨|ξ|²⟩

is the flux-surface average of the squared boundary displacement. N is Hermitian Toeplitz within each n-block, block-diagonal over n, and positive definite. It is the metric of the pencil W·v = λ·N·v in free_run and free_compute_total, whose eigenvalues are therefore invariant to the working (Jacobian) coordinate.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.propagator_start — Method
propagator_start(chunks, i, bases, N) -> Array{ComplexF64,3}

Start basis (N × 2N × 2) of chunk i's propagator: the left basis of its surface for a crossing chunk, the right basis for the chunk after one [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 33], else the identity.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.cross_singular_surface! — Method
cross_singular_surface!(odet, intr, ising) -> Matrix{ComplexF64}

Cross singular surface ising [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 36]. odet.u holds asymptotic coefficients, in the left basis on entry and the right basis on return, with no big solution on either side; both sets are recorded in odet.ca_l and odet.ca_r. Returns the N × N matrix that takes the columns on return to their continuation left of the surface, in the columns on entry.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.compute_delta_prime_matrix — Method
compute_delta_prime_matrix(intr, propagators, chunks, axis_state; wv=nothing, wp=nothing, psio=0.0, extended_precision=false) -> (delta_prime, coefficients)

Solve the STRIDE boundary-value problem for the inter-surface Δ' matrix [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37].

Arguments

  • intr: Read for its mode space and singular surfaces.
  • propagators, chunks, axis_state: From riccati_eulerlagrange_integration.
  • wv: Singfac-scaled vacuum response for the edge condition wp + wv = 0; nothing puts a conducting wall there.
  • wp: The run's plasma response, used only as a check: a warning is issued when the edge momentum of the ΔEF solve differs from it by more than `DELTAPRIMERESPONSEMISMATCH`.
  • psio: Poloidal flux normalization.
  • extended_precision: Solve in Complex{Double64}.

Returns

  • delta_prime: A DeltaPrimeData whose coil is Δ_EF (empty without wv).
  • coefficients: The BVP's solution vectors, one column per solution: the 2·msing Δ' solves, side-major, then the N of ΔEF. Input of `outersolution_basis;nothingwithoutwv`.

Both are nothing when no surface is crossed or, with a warning, when a surface carries more than one resonant mode.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.pest3_decompose — Method
pest3_decompose(dp_raw::AbstractMatrix) -> NamedTuple{(:A, :B, :Γ, :Δ)}

Rotate the raw 2m×2m outer-region matching matrix dp_raw (side-major ordering [L_s1, R_s1, L_s2, R_s2, …]) into the Pletzer–Dewar 1991 parity blocks. Given rows and columns paired by surface (odd index = left, even index = right), the Fortran RDCON parity combination is

A'(i,j) = RR + RL + LR + LL    (even-i, even-j)   — interchange↔interchange
B'(i,j) = RR − RL + LR − LL    (even-i, odd-j)    — interchange↔tearing
Γ'(i,j) = RR + RL − LR − LL    (odd-i,  even-j)   — tearing↔interchange
Δ'(i,j) = RR − RL − LR + LL    (odd-i,  odd-j)    — tearing↔tearing

where RR = dp_raw[2i, 2j], RL = dp_raw[2i, 2j−1], LR = dp_raw[2i−1, 2j], LL = dp_raw[2i−1, 2j−1]. Each block is m×m.

No Pletzer–Dewar ½ prefactor, matching Fortran RDCON; it cancels in det(D' − D(γ)) = 0.

The Δ' block returned here equals DeltaPrimeData.matrix.

Arguments

  • dp_raw — 2m×2m complex matrix (typically DeltaPrimeData.raw).

Returns

Named tuple (A, B, Γ, Δ) of m×m matrices, the blocks of D' = [[A' B'] [Γ' Δ']] in the det(D' − D(γ)) = 0 problem (interchange upper-left, tearing lower-right).

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.warn_unresolved_surfaces — Method
warn_unresolved_surfaces(bases, surfaces, rtol)

Warn for each crossed surface whose big asymptotic solution exceeds its small one, at the crossing distance, by more than the integration tolerance rtol resolves, so that Δ' and the outer solutions there are unreliable. bases is from asymptotic_bases; surfaces are the singular surfaces it indexes.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.outer_solution_basis — Method
outer_solution_basis(coefficients, propagators, chunks, columns, bases, surfaces, equil, mats, modes, fill_fractions)
    -> OuterSolutionBasis

Rebuild the solutions of the Δ' boundary-value problem [Glasser & Kolemen 2018, Phys. Plasmas 25, 082502, Eq. 37] at every stored step of the chunk propagators and, inside the crossing distance of each surface, from its asymptotic series at the fractions fill_fractions of that distance, big solution included. The cut solution leaves out the leading-order big and small terms over the two chunks next to each surface.

Arguments

  • coefficients: The BVP's solution vectors, one column per solution, from compute_delta_prime_matrix.
  • propagators, chunks, columns, bases: From riccati_eulerlagrange_integration.
  • surfaces: The singular surfaces chunks index.
  • modes: Mode indexing.
  • fill_fractions: From crossing_fill_fractions.
source
GeneralizedPerturbedEquilibrium.ForceFreeStates.riccati_eulerlagrange_integration — Method
riccati_eulerlagrange_integration(ctrl, equil, mats, intr) -> (odet, riccati)

Integrate the Euler-Lagrange equations from the axis to intr.psilim with parallel chunk propagators [Glasser, Kolemen & Glasser 2018, Phys. Plasmas 25, 032507; Glasser & Kolemen 2018, Phys. Plasmas 25, 082502].

Returns odet, whose stores hold the solution at every stored solver step in columns that are continuous in ψ and equal (S, I), S = U₁U₂⁻¹, at the edge, and riccati, the inputs of compute_delta_prime_matrix and outer_solution_basis: (; propagators, chunks, columns, bases), with columns from _assemble_propagators_serially! and bases from asymptotic_bases.

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.truncate_chunks! — Method
truncate_chunks!(chunks, psi_edge, msing) -> Union{Int,Nothing}

Cut chunks back to an edge at psi_edge: drop those past it, end the straddling one at it, and turn a crossing chunk whose surface is no longer in the plasma into a forward chunk. An edge at the right boundary of a surface keeps the chunk after its crossing, at zero width. Returns the index of a chunk that changed and so must be re-integrated.

source