Tearing

Tearing solves the resistive tearing stability of each rational surface by matching the outer-region Δ′ of the force-free states to the response of a resistive inner layer. The outer region, ideal MHD everywhere except at the rational surfaces, gives the tearing drive Δ′; the inner layer, where resistivity, two-fluid effects and rotation act, gives the response Δ(Q) as a function of the complex mode frequency; the roots of Δ′ = Δ(Q) are the tearing modes, with their growth rates and real frequencies.

What it computes

Three layer models are available, selected by [Tearing] inner_model:

  • "SLAYER", the two-fluid drift-MHD slab layer equations of Cole and Fitzpatrick (2006), in the form Park's SLAYER solver takes them with a few terms dropped (Park (2022), Burgess et al. (2026)), with resistivity, perpendicular and toroidal transport, diamagnetic drifts and E×B rotation taken from the kinetic profiles of the equilibrium; its options are in [SLAYER].
  • "GGJ", the toroidal resistive-MHD layer of Glasser, Greene and Johnson (Glasser, Wang and Park (2016), Glasser and Wang (2020)), whose coefficients E, F, G, H, K are the flux-surface averages stored under SingularSurfaces/; its solver options are in [GGJ].
  • "CCC", the GGJ layer with electron diamagnetic drift and perpendicular transport of Cho, Choi and Choi (1987) (see CCC below); its solver options, Q* and M⊥/M are in [CCC].

For each surface the Dispersion search scans the complex frequency plane, extracts the roots of the dispersion relation and classifies them, and [Tearing.search] sets the scan. With [Tearing.CriticalResonantField] the stage also computes, for the SLAYER layer, the resonant field at which a static error field overcomes the layer's shielding: the error-field penetration threshold.

The same GGJ layer, or the CCC layer, serves the [Match] stage of the Workflow, which does the complementary job: instead of finding the free modes it imposes the layer response on the driven force-free states and writes the matched solution to SingularSurfaces/Match/.

Governing equations

The GGJ layer equations couple the perturbed flux $\Psi$ and the layer variables $\Xi$, $\Upsilon$ in the scaled distance $x$ from the rational surface (Glasser, Wang and Park (2016), Eq. 11). A physical growth rate $\gamma$ maps to the scaled frequency $Q$ by inner_Q, the model requires Mercier stability $D_I < 0$ (mercier_di), and at large $x$ the solutions contain the two power laws of the outer region. The matching datum $\Delta$ is the ratio of the large to the small power-law coefficient; imposing the two parities at $x = 0$ gives the pair $(\Delta_+, \Delta_-)$: $\Delta_+$ even in the displacement $\Xi$, the interchange channel, $\Delta_-$ odd, the tearing channel. Positional pairs are always ordered $(\Delta_+, \Delta_-)$, and InnerLayerResponse names them interchange and tearing. The dispersion relation of a surface is then $\Delta'_s = \Delta_-(Q)$ with $\Delta'_s$ the surface's diagonal of SingularSurfaces/Delta_prime_matrix converted to the layer's normalization (PerSurface/Delta_prime_norm); coupling_mode = "coupled" solves the determinant of the full matrix over up to msing_max surfaces instead.

The SLAYER layer is a slab with the Lundquist number $S$, the temperature ratio $\tau = T_i/T_e$, the compressibility $c_\beta$, the perpendicular and toroidal Prandtl numbers $P_\perp$, $P_\mathrm{tor}$ and the diamagnetic frequencies $Q_e$, $Q_i$ of each surface (all stored under Tearing/PerSurface/), solved by a Riccati integration across the layer; its layer thickness $\delta_s$ is written to Tearing/LayerWidths/ and feeds the layer-overlap cap of Stability.

Critical resonant field

With [Tearing.CriticalResonantField] each SLAYER surface gets the critical resonant field for error-field penetration, from the steady-state torque balance of Cole and Fitzpatrick (2006): the electromagnetic torque on the layer balances the viscous restoring torque when

\[\frac{\operatorname{Im}\hat\Delta(Q)}{|\alpha + \hat\Delta(Q)|^2} = \frac{2P\,(Q_0 - Q)}{S\hat\kappa\,(b_r/B_\phi)^2}, \qquad \hat\kappa = \left[\frac{2}{s}\right]^2 \int_{r_s}^{a} \frac{\mu(r_s)}{\mu(r)}\,\frac{dr}{r},\]

and balance is lost above

\[\left(\frac{b_r}{B_\phi}\right)^2_\mathrm{crit} = \max_Q \frac{2P\,(Q_0 - Q)}{S\hat\kappa\,\operatorname{Im}[-1/(\alpha + \hat\Delta(Q))]} .\]

$P$ is the layer's P_tor, $S$ its Lundquist number, $Q_0 = \tau_k n \omega_E$ the natural E×B rotation of the mode (from the kinetic file's omega_E or the omega_E_kHz override, a [Tearing] table keyed by surface such as omega_E_kHz = { "2/1" = 3.0 }; a surface without one is skipped), and the viscosity integral is taken as 1/2, so $\hat\kappa = 2/s^2$. Each surface uses its own stability parameter $\alpha = S^{-1/3}(\Delta_\mathrm{crit} - r_s\Delta')$, so the torque balance shares its poles with the free modes; the threshold needs a tearing-stable surface, and one with $\alpha \le 0$ is skipped with a warning. Penetration is the first resolved saddle-node bifurcation on the path from $Q_0$ toward the electron fluid at $Q_e$, above which the shielded branch no longer exists; small numerical extrema and the unshielded zone next to $Q_e$ are excluded, and a surface without a resolved bifurcation reports NaN. br_crit is normalized by the toroidal field, and br_crit_tesla = br_crit·|B0| is the quantity to compare with PerturbedEquilibrium/SingularCoupling/resonant_area_weighted_field, the total resonant field of the ideal response; the comparison is approximate, since the theory's $b_r$ is a cylindrical field at the layer.

Running it

From examples/DIIID-like_SLAYER_example/gpec.toml, after a [ForceFreeStates] solve with integrator = "Riccati" and vac_flag = true (or "Galerkin" with rpec_flag = true), which provides the Δ′ matrix, and with a kinetic file on the equilibrium:

[Tearing]
inner_model = "SLAYER"            # or "GGJ", "CCC"
coupling_mode = "uncoupled"       # one dispersion relation per surface; "coupled" uses the full Δ′ matrix

[Tearing.search]
scan_mode = "amr"                 # adaptively refined scan of the complex Q plane
Q_re_range = [-2.0, 2.0]
Q_im_range = [-0.5, 3.0]
nre = 41
nim = 31
pole_threshold_adaptive = true
filter_above_poles = true
filter_outside_re = true
polish_roots = true
store_scan = false                # true: write Tearing/Scan/Surface_<k>/

[Tearing.CriticalResonantField]
n = 2000                          # Q samples of the torque balance
store_scan = false

[SLAYER]
D_c_type = "none"                 # critical-Δ offset from parallel transport ("none": zero)
P_perp_model = "D_perp"           # how the perpendicular Prandtl number is built (below)

In a script, solve(TearingProblem(ffs; critical_resonant_field=CriticalResonantFieldControl()), SLAYERModel(); config=TearingConfig(...)) runs the same stage, and solve_inner(GGJModel(), p, γ) evaluates one GGJ layer at a growth rate $\gamma$. GGJ's η and ρ default from the kinetic data (η by the resistivity closure SLAYER uses, ρ = μ·mp·ne); pass eta and rho to TearingProblem to override them.

SLAYER inputs: perpendicular diffusivities

The layer widths and the critical island width of SLAYER take perpendicular diffusivities from the kinetic file (chi_e, chi_i, chi_phi profiles in m²/s). Two formulas want different quantities: the layer width goes through P_perp, the diffusion of the total pressure, while the critical island width $W_d \propto (\chi_\perp/\chi_\parallel)^{1/4}$ is set by the electron heat transport that flattens the electron temperature across the island. [SLAYER] P_perp_model selects how P_perp is built: from the perpendicular particle diffusivity $D_\perp$ that weights the electron and ion channels by their share of the pressure gradient ("D_perp", the default), from chi_e alone ("chi_perp_e", the single-χ convention of Fitzpatrick's TJ code), from chi_i, from the toroidal Prandtl number, from its $c_\beta^2$ floor, or from a whole-plasma confinement time ("tau_E", for a plasma without χ profiles). [SLAYER] chi_perp_Dc sets the electron diffusivity of the critical island width alone, one value for every surface, for a run in which one χ⊥,e cannot serve both formulas; where an interpretive power balance cannot separate the species, treat it as a modeling choice and scan it. Since the widths scale as $\chi^{1/4}$, a factor-two change in χ moves them by about 19%, which can be enough to move the resistive-layer overlap cut of Stability by one surface. The DIII-D-like kinetic file of the examples carries analytic χ profiles of the order of power-balance values for DIII-D H-modes; they are not fits to a measured discharge, do not resolve the pedestal transport barrier, and chi_e is raised by a factor of two so that the default deck exercises the layer-overlap cut.

Outputs

DatasetMeaning
Tearing/PerSurface/rational_psi, rational_q, m, nthe analyzed surfaces
Tearing/PerSurface/S, tau, c_beta, P_perp, P_tor, Q_e, Q_i, tau_k, tau_R, eta, rs, …the layer parameters of each surface (SLAYER); E, F, G, H, K, M, tau_A and tau_R for GGJ, with Q_star and M_perp_ratio for CCC
Tearing/PerSurface/Delta_prime_raw and Delta_prime_matrix_rs (SLAYER) or Delta_prime_matrix (GGJ, CCC)the outer matrix each layer was matched to
Tearing/PerSurface/Delta_prime_norm, delta_prime_conversionthe Δ′ normalization of the SLAYER layer
Tearing/Roots/Q_root, omega, gamma, no_rootthe dispersion root of each surface in the lab frame (frequency_frame attribute), its real frequency and growth rate, and the flag of a surface with no usable root
Tearing/LayerWidths/delta_s, delta_s_abs, d_betathe complex resistive layer thickness, its magnitude in metres, and the ion drift scale
Tearing/Diagnostics/ValidRoots, Poles, FilteredRootsthe root classification of the scan
Tearing/Scan/Surface_<k>/the scanned Δ(Q) with store_scan = true
Tearing/CriticalResonantField/br_crit, br_crit_tesla, Q_peak, Q0the penetration threshold as $b_r/B_\phi$ and in tesla, the Q of the balance maximum and the natural rotation

Numerical notes

The GGJ model exposes three solvers through the solver type parameter of GGJModel, all returning $\Delta$ in the same convention:

backendmethodrobust regime
:shootingbackward stable shoot from $X_\mathrm{max}\to 0$$\lvert Q\rvert \ll 1$
:galerkinHermite-cubic finite-element solve on the real axissurface- and $\arg Q$-dependent; see Choosing a backend
:ray (default)rotated contour: inward-marched far-field condition and a Hermite-cubic BVP$\lvert Q\rvert \sim 500$ on or near the imaginary axis

:ray continues the layer equations analytically onto the ray $x = e^{i\theta}s$ with $\theta = \arg(Q)/4$, which makes the exponent of the outer solutions real and lifts the pseudo-resonance at $x^2 = -Q^2(G + KF)$ off the contour; it takes the far-field data from the asymptotic series where its residual is below tolerance (pick_smax), marches the power pair inward by an implicit Radau scheme that damps the growing exponential directions, and solves the Hermite-cubic boundary-value problem with the parity conditions at $s = 0$. $\Delta$ does not depend on the contour angle, so delta_convergence re-solves with each numerical knob perturbed and reports the spread as an error bar.

Relative error of the :shooting and :galerkin backends against the :ray reference along the imaginary-Q axis, on the q = 4 DIII-D-like benchmark surface; each curve's crossing of the 1% line marks that method's practical reach.

Validation: at the real operating point $Q = 0.1234$ of Glasser and Wang (2020) the :galerkin backend reproduces the Fortran rmatch solver to $\sim 10^{-8}$ and :ray agrees to $4\times10^{-7}$ in $\Delta_-$ ($1.3\times10^{-4}$ in $\Delta_+$, which sits near a pole); on the $q = 4$ benchmark surface (q4_surface_benchmark, $S \approx 4.6\times10^6$, $D_I \approx -0.31$) :ray is pinned at $Q = 500i$ to $\Delta_+ = 2.4720 + 13.3540\,i$, $\Delta_- = 0.13750 + 0.74275\,i$, with a knob-perturbation error bar of $\sim 5\times10^{-6}$ and $6\times10^{-7}$. The critical-field torque balance reproduces the Fortran SLAYER's balance to all printed digits when fed the same Δ(Q) table; the thresholds differ through the layer model (Park's reduced form of the layer equations against Cole and Fitzpatrick's full ones) and the selection rule above.

Fortran and Julia inner-layer Δ(Q) and torque balance on the DIII-D-like example.

Choosing a backend

:ray is the default and the recommended backend for every $Q$: it resolves the local WKB rate in every cell and holds $\sim 2\times10^{-6}$ for $|Q|$ from 0.01 to 1 on every surface tested. :galerkin takes a few milliseconds per solve, 3–60 times less than :ray, but its accuracy depends on the surface and on $\arg Q$ even at small $|Q|$, erring by order unity near $\arg Q = 157.5^\circ$. The backends take disjoint numerical keywords: pass GGJModel(solver=:galerkin) explicitly when supplying its nx/xfac knobs.

using GeneralizedPerturbedEquilibrium.InnerLayer

p = GGJ.q4_surface_benchmark()      # GGJParameters for the q = 4 benchmark surface
γ = 500im * GGJ.q0(p)               # physical rate placing Q on the imaginary axis at 500i
Δ = solve_inner(GGJModel(), p, γ)   # Δ.interchange, Δ.tearing with the default :ray backend

CCC: diamagnetic drift and perpendicular transport

CCCModel solves the drift-resistive layer equations of Cho, Choi and Choi (1987), in the form of Kim, Cho and Choi (1988), Eqs. (1a)–(1c): the GGJ equations with the electron diamagnetic frequency $Q_* = \omega_{*e}/Q_0$ in Ohm's law and vorticity and the perpendicular-transport weight $M_\perp/M$ on the pressure equation. CCCParameters holds a GGJParameters plus Qstar and mperp; $Q_* = 0$, $M_\perp/M = 1$ give the GGJ equations, and the GGJ scales, Mercier exponents and Δ normalization carry over unchanged. Its far field splits GGJ's double exponential pair into two families with scales $\sigma_j$ set by Kim's Eq. (2) (parabolic_scales), so the asymptotic basis uses a general Sylvester splitting solve and the ray is centred between the families, $\theta = (\arg\sigma_1 + \arg\sigma_2)/4$; an angle at which either family stops decaying between the real axis and the ray is refused. Only the :ray backend is available. In a deck, [Tearing] or [Match] takes inner_model = "CCC", and [CCC] holds the solver options with Qstar and mperp, each a scalar or one value per surface, as the CCCModel keywords of the same names; without Qstar, Q* = n·ω*ₑ/Q₀ comes from the kinetic data (layer_omega_star_e), and mperp defaults to 1.

[Tearing]
inner_model = "CCC"

[CCC]
Qstar = 0.05                      # Q* = n·ω*ₑ/Q₀; omit to take it from the kinetic data
mperp = 1.2                       # M⊥/M

A [CCC] section without inner_model = "CCC" under [Tearing] or [Match] stops the run. When the two families decay at very different rates (large $K Q Q_*^2$) the march resolves the faster one across the slower one's whole band, and a solve can take tens of seconds.

p = CCCParameters(GGJ.q4_surface_benchmark(), 0.5, 1.4)   # GGJ coefficients, Q*, M⊥/M
Δ = solve_inner(CCCModel(), p, 5im * GGJ.q0(p.ggj))

API reference

Tearing

GeneralizedPerturbedEquilibrium.Tearing.CriticalResonantFieldControl — Type
CriticalResonantFieldControl

Configuration for the critical resonant field (torque-balance) analysis, passed as TearingProblem(ffs; critical_resonant_field=CriticalResonantFieldControl(; ...)); a deck states it as [Tearing.CriticalResonantField]. The magnetic Prandtl number is the per-surface P_tor of the SLAYER layer parameters, and the natural rotation is each surface's resolved ΩE (the kinetic file's `omegaE, or theomegaEkHz` override), which it therefore requires.

Fields

  • Qmin, Qmax – override the sampled real-Q range; nothing samples from Q0 toward Q_e per surface
  • n – number of Q samples per surface
  • store_scan – write the per-surface Q, torque balance and Δ samples to gpec.h5
source
GeneralizedPerturbedEquilibrium.Tearing.CriticalResonantFieldResult — Type
CriticalResonantFieldResult

Output of run_critical_resonant_field, one entry per SLAYER surface.

Fields

  • enabled – the analysis ran
  • rational_index – rational-surface index of each entry
  • Q_peak – normalized frequency Q at the torque-balance maximum (NaN if none or skipped)
  • br_crit – critical normalized resonant field br/Bφ (NaN if none or skipped)
  • br_crit_tesla – br_crit·|B0| in tesla, with the layer's B0, approximately comparable to the total resonant field resonant_area_weighted_field (Park et al., PRL 99, 195003 (2007))
  • Q0 – normalized natural E×B rotation τk·n·ΩE (NaN where Ω_E is unknown)
  • scan – per-surface Q scans; empty unless store_scan
source
GeneralizedPerturbedEquilibrium.Tearing.LayerOverlapScan — Type
LayerOverlapScan

Per-surface resistive layer widths and the psihigh they imply, from resistive_layer_overlap.

All widths are in normalized flux, converted from metres by Δψ = w / |da/dψ| so they compare against surface separations in ψ.

Fields

  • m, n – resonant mode numbers per surface, ordered by increasing ψ
  • psi – surface location in normalized flux
  • rs – minor radius at the surface in meters
  • delta_s_m – |δ_s|, the Riccati resistive layer width, in meters
  • width_delta_s – the same width in normalized flux, |δ_s|/|da/dψ|
  • width_visco – the visco-resistive comparison scale as a Δψ width
  • width_dr – the diffusive-resistive width of Fitzpatrick (2025) Eq. (100) as a Δψ width; the criterion the recommendation uses (Sect. 5.6: strong shear near the separatrix puts every layer in the DR regime)
  • extrapolated – true when the surface was located outside the equilibrium's ψ grid via the edge q-law
  • psihigh_delta_s, psihigh_visco, psihigh_dr – domain implied by each width channel, nothing when that channel never overlaps within the scanned range
  • psihigh – the recommendation, equal to psihigh_dr; the other two channels are reported for comparison and do not set the domain
  • first_overlap – index of the first surface that overlaps its inner neighbour, nothing when none do
  • caveats – reasons the verdict itself is qualified: an overlap that could not be established or excluded, or one decided by a surface placed on the separatrix law
  • notes – per-surface and bookkeeping detail that does not qualify the verdict
source
GeneralizedPerturbedEquilibrium.Tearing.TearingConfig — Type
TearingConfig(; kwargs...)

Numerical scan and root-search settings for solve(TearingProblem(...), model; config). The toroidal-layer models (GGJ, CCC) use physical gamma_range and omega_range, with positive growth rates and frequencies in the result's convention: lab-frame ω for a coupled solve, each surface's E×B-frame ω for an uncoupled one. SLAYER uses its normalized Q box. The default classification selects threshold classification for SLAYER and winding classification for the toroidal-layer models.

Fields

  • gamma_range, omega_range - Toroidal-layer search bounds in 1/s and rad/s; both required for a GGJ or CCC solve.
  • scan_mode - SLAYER scan method, :amr or :brute_force; the toroidal-layer models use AMR.
  • Q_re_range, Q_im_range - SLAYER normalized frequency search box.
  • nre, nim - Initial scan resolution.
  • amr_passes, amr_max_cells - AMR depth and cell cap.
  • boxes, multi_box_prescreen_n - Optional SLAYER multi-box scan and prescreen resolution.
  • pole_threshold, pole_threshold_adaptive - SLAYER threshold-classification controls.
  • filter_above_poles, filter_outside_re - SLAYER contour filters.
  • gamma_gap_threshold - SLAYER growth-rate separation threshold in 1/s.
  • polish_roots, validity_rtol - Root polishing and SLAYER residual acceptance tolerance.
  • root_classification - :auto, :threshold, or :winding; the toroidal-layer models require winding.
  • store_scan - Retain scan data in the result and HDF5 output.
source
GeneralizedPerturbedEquilibrium.Tearing.TearingProblem — Type
TearingProblem(ffs; eta=nothing, rho=nothing, gamma=5/3, kwargs...)

Tearing stability of a finished force-balance solve. Keywords describe surface coupling and the GGJ layer inputs; the SLAYER layer closures belong to SLAYERModel and scan settings to TearingConfig. The plasma itself (profiles, species, Zeff and transport defaults, confinement time and resistivity closure) is the equilibrium's kinetic data, ffs.equil.kinetic (see KineticProfileData), so every layer model sees one plasma. Solve with solve(problem, model; config) for a toroidal layer model (GGJModel(), CCCModel()) or SLAYERModel(). A toroidal layer model needs the raw Δ′ matrix (Riccati with `vacflag=true, or Galerkin withrpec_flag=true`). Both models report lab-frame roots from each surface's E×B rotation.

Fields

  • ffs - Outer solution, retained by reference.
  • coupling_mode, msing_max - Uncoupled or coupled analysis and its maximum number of surfaces.
  • omega_E_kHz - Per-surface E×B rotation overrides keyed by m/n, replacing the kinetic data's omega_E.
  • critical_resonant_field - The SLAYER penetration-threshold calculation, a CriticalResonantFieldControl; nothing (default) skips it.
  • eta, rho - GGJ resistivity in Ω·m and mass density in kg/m³, a scalar or one value per surface (core to edge), as in MatchProblem. nothing (default) derives them from the kinetic data: η from its resistivity closure, the one SLAYER uses, and ρ = μ·mp·ne as SLAYER takes it. Unused by SLAYERModel.
  • gamma - GGJ ratio of specific heats.
source
GeneralizedPerturbedEquilibrium.Tearing.TearingResult — Type
TearingResult

Output of the tearing solve: summary eigenvalues (ω, γ) and the full root-extraction diagnostics.

Fields

  • enabled – true only when the analysis actually ran

  • problem – producing TearingProblem, or nothing for a low-level scan

  • config – resolved scan configuration used by the model

  • model – the inner-layer model solved; nothing when the analysis did not run

  • params – SLAYER or GGJ layer parameters, one per surface

  • rational_psi, rational_q – ψ_N and q of each surface, aligned with params; empty when built from bare parameters, and then not written to HDF5

  • dp_matrix – outer-region Δ' matrix used: rs-referenced for SLAYER (`deltaprimetorsreference, written asPerSurface/Deltaprimematrixrs), the ψ_N matrix for GGJ (PerSurface/Deltaprimematrix`)

  • Q_root – tearing eigenvalue(s) in normalized Q

    • length nsurfaces in :uncoupled mode
    • length 1 in :coupled mode (global eigenvalue normalized by params[1].tauk)
  • omega, gamma – lab-frame angular frequency Re(Q)/τk in rad/s and growth rate Im(Q)/τk in 1/s; positive gamma is unstable. An uncoupled root is moved from its layer's E×B frame by n·ΩE (ΩE = 0 where unknown); a coupled GGJ layer sees s + i·n·Ω_E

  • per_surface_extraction – Vector{GrowthRateResult}, one per surface in uncoupled mode, in each surface's E×B frame. Empty in coupled mode.

  • coupled_extraction – single GrowthRateResult in coupled mode. nothing otherwise.

  • layer_widths – Vector{LayerWidths}, one per SLAYER surface: the del_s Riccati layer thickness in meters plus FKR / visco-resistive scales. Empty for GGJ.

  • omega_E – E×B angular frequency ΩE per unit n in rad/s on each surface: the kinetic file's value or the `problem.omegaE_kHz` override; NaN where neither gives one

  • q_shift – real Doppler offset −τ_k·n·Ω_E applied to each surface's inner-layer Q; zero outside :coupled mode, where rotation does not enter. Zero for GGJ, whose shift n·Ω_E acts on the growth-rate variable

  • scan_data – scan results (per-surface in uncoupled, single entry in coupled). Empty unless config.store_scan == true.

  • critical_resonant_field – CriticalResonantFieldResult; enabled=false when problem.critical_resonant_field is nothing

source
GeneralizedPerturbedEquilibrium.ForceFreeStates.layer_overlap_scan — Method
layer_overlap_scan(equil, model::SLAYERModel, ns) -> Union{Nothing,LayerOverlapScan}

The binding resistive-layer overlap scan over the toroidal mode numbers ns: the one with the innermost overlap point, or the first scan when none overlaps. Uses the equilibrium's kinetic data and model's layer closures, as the SLAYER tearing solve does, in the flux label Fitzpatrick (2025) Eq. (100) is anchored to. Caveats are logged as warnings and notes as info.

source
GeneralizedPerturbedEquilibrium.Tearing._q_shift — Method
_q_shift(p::SLAYERParameters, Ω_E) -> Float64

Real offset added to a surface's scanned inner-layer Q for E×B rotation Ω_E per unit n [rad/s]. The layer's Q is the mode frequency in the local E×B frame (Burgess et al. 2026, Table 1), while the coupled scan runs in the lab frame, so

Q_layer = τ_k·ω_lab − τ_k·n·Ω_E    ⇒    q_shift = −τ_k·n·Ω_E
source
GeneralizedPerturbedEquilibrium.Tearing.delta_prime_to_rs_reference — Method
delta_prime_to_rs_reference(dp_matrix, params) -> Matrix{ComplexF64}

Convert the outer-region Δ' matrix from its ψN reference length (STRIDE/BVP convention) to the rs-based x̂ = (r − r_s)/r_s reference of the slab layer (Fitzpatrick 2023 convention, shared by dc_tmp and the S^(1/3) Δ(Q) scale). With the Mercier exponent α = √(−D_I) (Glasser, Greene & Johnson 1975, Eqs. 16, 24; Glasser, Wang & Park 2016, Eq. 26) and K = r_s·(dψ_N/dr)|_s,

Δ̂_ij = K_i^(1/2+α_i) · Δ'_ij · K_j^(α_j−1/2)

which reduces to Δ̂ = r_s·Δ' at α = 1/2. The off-diagonal split is a similarity transform that leaves every dispersion root unchanged. K and α come from SLAYERParameters.k_ref / .alpha_mercier; hand-built parameters default to k_ref = 1, making this the identity.

source
GeneralizedPerturbedEquilibrium.Tearing.resistive_layer_overlap — Method
resistive_layer_overlap(equil, profiles::KineticProfiles; n_tor, kwargs...)
    -> LayerOverlapScan

Locate the q = m/n_tor rational surfaces, compute each one's resistive layer width, and report the outermost psihigh at which adjacent layers are still separated.

Surfaces beyond the grid come from the inverse equilibrium's own q, or from separatrix_q_law on the direct path, when extrapolate=true; only the first rational past ψ = 1 is placed, and it is scored only if the kinetic profiles reach it. The recommendation never exceeds ψ = 1, and when no overlap is established the domain keeps its requested limit. Widths come from slayer_algebraic_widths via build_slayer_inputs, with the same plasma inputs and resistivity closure as the SLAYER analysis; delta_s is a Riccati comparison only.

Arguments

  • equil – a formed PlasmaEquilibrium
  • profiles – KineticProfiles spanning the scanned ψ range

Keyword arguments

  • n_tor – toroidal mode number; surfaces are q = m/n_tor

  • m_max – runaway backstop on the poloidal mode number (default 2000), not a physics limit; if it stops the outward search, caveats says so

  • max_layer_solves – maximum number of surfaces scored, innermost kept (default 64); caveats records when it truncates

  • psihigh_safe – treat this as the outer edge of trusted equilibrium data (default equil.profiles.xs[end])

  • psi_gap – minimum distance from the separatrix flux for a placed surface on the direct path (default 1e-9, numerical); inverse equilibria ignore it

  • extrapolate – search past psihigh_safe on the separatrix q-law (default true)

  • theta – poloidal angle for the minor-radius chord, used only by rs_method=:midplane (default 0.0)

  • rs_method – radial label of the widths and their ψ Jacobian (default :flux, the label Fitzpatrick Eq. (100) is anchored to; see radial_label)

  • bt, mu_i, mu_rho, zeff, chi_perp_e, chi_perp_i, chi_tor, tau_E, P_perp_model, resistivity_model, lnLambda_form – passed through to build_slayer_inputs. The defaults are placeholders: pass the run's own values

Surface k overlaps its inner neighbour when ψ_k − w_k/2 < ψ_{k-1} + w_{k-1}/2. Both surfaces are then contaminated, so the recommendation is surface k-1's own ψ.

source
GeneralizedPerturbedEquilibrium.Tearing.run_critical_resonant_field — Method
run_critical_resonant_field(model, params, omega_E, dp_diag, ctrl) -> CriticalResonantFieldResult

Critical normalized resonant field br/Bφ for error-field penetration at each SLAYER surface, from the torque balance of Cole and Fitzpatrick, Phys. Plasmas 13, 032503 (2006), Eq. 62. The magnetic Prandtl number is the layer's P_tor, and the natural rotation is the E×B frequency of the m/n mode, Q0 = τk·n·ΩE, with omega_E the resolved ΩE per unit n at each surface [rad/s]. The outer stability is α = S^(-1/3)·(Δcrit − rs Δ'), with `dpdiag` the rs-referenced Δ' diagonal and Δcrit the layer's critical-Δ offset, as in the dispersion relation. A surface whose ΩE is unknown (NaN), or that is tearing-unstable (α ≤ 0), is skipped with a warning; if no surface has a known ΩE, the analysis cannot run and this throws.

source
GeneralizedPerturbedEquilibrium.Tearing.run_slayer_from_inputs — Method
run_slayer_from_inputs(model::InnerLayerModel, params, dp_matrix, problem, config;
                       rational_psi, rational_q, omega_E) -> TearingResult

Run the tearing scan and root extraction for SLAYER model on pre-built per-surface parameters and the outer-region Δ' matrix, skipping the TearingProblem setup. omega_E is the E×B angular frequency per unit n at each surface in rad/s, overridden by problem.omega_E_kHz; empty means unknown (no shift, reported as NaN). In coupled mode it Doppler-shifts each surface's Q; an uncoupled layer is solved in its own E×B frame and its root moved by τk·n·ΩE. Roots are reported in the lab frame.

source

InnerLayer

GeneralizedPerturbedEquilibrium.InnerLayer.InnerLayerModel — Type
InnerLayerModel

Abstract supertype for resistive inner-layer models. Each concrete model is a small, parameter-free type tag (often parameterized by a solver-choice symbol) that selects a solve_inner method.

Implementations live in submodules of InnerLayer, e.g. InnerLayer.GGJ.

source
GeneralizedPerturbedEquilibrium.InnerLayer.InnerLayerResponse — Type
InnerLayerResponse

Parity-projected inner-layer matching data at one rational surface. The two components correspond to the homogeneous parity solutions of the half-domain inner-layer problem (parity boundary conditions imposed at X = 0). They are the Δ_{j,±}(γ) of Glasser, Wang & Park, Phys. Plasmas 23, 112506 (2016), Eqs. (34)–(35).

Fields

  • tearing — odd-parity matching coefficient Δ₋: Ξ odd, Ψ even, the reconnecting channel whose Δ is the constant-ψ tearing Δ′ (Pletzer, Bondeson & Dewar, J. Comput. Phys. 115, 530 (1994), Eqs. 77, 86–87, 89). Every resistive inner-layer model populates it.
  • interchange — even-parity matching coefficient Δ₊: Ξ even, Ψ odd, the non-reconnecting interchange channel carrying the Glasser, Greene & Johnson (1975) stabilization. Pressureless models (SLAYER) set it to zero.

Parity is that of the displacement Ξ, matched to the outer ξ (GWP2016 Eq. 34; Pletzer, Bondeson & Dewar Eqs. 32–33), with + even and − odd. The fields are named by the physics channel because the parity of the flux Ψ is the opposite. Positional pairs elsewhere in InnerLayer (e.g. the Δ of solve_inner_profile) are ordered (Δ₊, Δ₋) = (interchange, tearing).

source
GeneralizedPerturbedEquilibrium.InnerLayer.layer_omega_star_e — Method
layer_omega_star_e(equil, surfaces) -> Vector{Float64}

Electron diamagnetic frequency per unit n, (2π/χ₁)(Te ne′/ne + Te′) in rad/s with Te in eV and ′ = d/dψN, at each rational surface of surfaces, from the equilibrium's kinetic data; the SLAYER layer's ω*ₑ divided by n.

source
GeneralizedPerturbedEquilibrium.InnerLayer.layer_rho — Method
layer_rho(equil, surfaces) -> Vector{Float64}

Ion mass density ρ = μ·mp·ne in kg/m³ at each rational surface of surfaces, from the equilibrium's kinetic data: μ is the mean ion mass per electron of the main ions and the impurity at the layer Z_eff, the density the SLAYER layer uses.

source
GeneralizedPerturbedEquilibrium.InnerLayer.solve_inner — Function
solve_inner(model::InnerLayerModel, params, s::Number; kwargs...) -> InnerLayerResponse

Compute the parity-projected matching data (the tearing and interchange fields of InnerLayerResponse) for the given inner-layer model, physical parameters params, and complex growth rate s = γ − iω in 1/s, in the surface's E×B frame. Every model takes this same s. Concrete models specialize this function.

See InnerLayerResponse for the physics-oriented field definitions. Pressureless models (SLAYER) populate only tearing and leave interchange at zero; finite-pressure models (GGJ) populate both.

source
GeneralizedPerturbedEquilibrium.InnerLayer.solve_inner_profile — Function
solve_inner_profile(model::InnerLayerModel, params, γ::Number; kwargs...)
    -> (; Δ, x, Ψ, Ξ, dψdx, rescale, ...)

Compute the inner-layer matching data and the reconstructed layer field profiles for the given model — everything an outer↔inner matching driver needs from the layer, so drivers never touch model internals. Returns a named tuple with at least:

  • Δ — the same matching data as solve_inner, as the pair (Δ₊, Δ₋) = (interchange, tearing)
  • x — real ascending grid in the model's stretched inner coordinate, x ≥ 0 with the rational surface at x = 0
  • Ψ, Ξ — length(x) × 2 profiles, columns in the order of Δ, in the model's inner normalization: Ψ the normal-field (reconnected-flux) variable, Ξ the displacement
  • dψdx — conversion to poloidal-flux distance, δψ = dψdx · x
  • rescale — amplitude factor converting the inner-normalized profiles to the outer δψ-normalized convention (companion of the Δ rescale)

Concrete models may return additional diagnostic fields (e.g. a solve-quality certificate). Solver-knob keywords are model-specific.

source

GGJ

GeneralizedPerturbedEquilibrium.InnerLayer.GGJ.GGJModel — Type
GGJModel{S,O} <: ToroidalLayerModel{S}
GGJModel(; solver=:ray, options...)

Glasser–Greene–Johnson resistive inner-layer model. S selects the solver backend: :ray (default; rotated contour with an inward-marched far-field condition, robust at large |Q|), :galerkin (real-axis Hermite FEM with resonant/extension matching cells; accuracy depends on the surface and arg Q, even at small |Q|), or :shooting (|Q| ≪ 1 only). Backend keywords given at construction, e.g. GGJModel(; solver=:galerkin, nx=1280), apply to every solve; a keyword the backend does not take is an error here, not at the first solve.

Fields

  • options::NamedTuple - Backend keywords forwarded to every solve; call-site keywords win.
source
GeneralizedPerturbedEquilibrium.InnerLayer.GGJ.GGJParameters — Type
GGJParameters

Dimensionless parameters of the Glasser–Greene–Johnson inner-layer model at a single rational surface, plus the local Alfvén/resistive timescales needed to scale the matching data back to physical Δ. The equilibrium coefficients E, F, G, H, K, M are the flux-surface averages defined in GWP2016 Eq. (A8); E, F, G, H, K enter the inner-region equations (Eq. 11).

Fields

fieldmeaning
EGlasser interchange parameter (enters Mercier D_I = E+F+H−¼)
FGlasser interchange parameter
GCoupling coefficient (curvature × pressure gradient)
HPfirsch–Schlüter coefficient
KGlasser parameter
MInertia factor (A8; enters K and Q₀, X₀); held, not used here
tauaLocal Alfvén time at the rational surface
taurLocal resistive time at the rational surface
v1Coordinate scale: inner X = v₁·δψ/X₀; enters rescale_delta
isingIndex of the singular surface (traceability only)

The growth rate γ is not stored here; it is a separate argument to solve_inner.

source
GeneralizedPerturbedEquilibrium.InnerLayer.GGJ.GGJShootingSystem — Type
GGJShootingSystem

Precomputed origin- and infinity-side arrays for the backward shoot. Construct via _build_shooting_system.

Fields

  • params, Q - Layer parameters and scaled growth rate.
  • p1, pplus - p₁ = √(−D_I) and p₁ − 1/2.
  • al0 - Origin Frobenius exponents (p₁, 1/2, −p₁, −1/2), the diagonal of the origin exponent matrix.
  • al1 - First-order coupling in the origin-diagonalized basis.
  • d0, d0inv - Origin diagonalizing matrix and its inverse.
  • ups - (4, 4, nps) origin power-series coefficients in t², ups[:, :, 1] = I.
  • nps - Origin series length.
  • d1 - Diagonalizing matrix at large t.
  • pexp - Logarithmic exponents of the large-t asymptotic basis.
  • bl1 - Coefficients ±√Q of t²/2 in the large-t exponentials.
  • tmax, tmin - Shoot start (large t) and end (small t).
source
GeneralizedPerturbedEquilibrium.InnerLayer.GGJ.ggj_parameters — Method
ggj_parameters(surface, equil; eta, rho, gamma=5/3, ising=0) -> GGJParameters

GGJ layer parameters at the singular surface surface of equil, from its resistive geometry surface.restype, the local resistivity eta in Ω·m, the mass density rho in kg/m³ and the ratio of specific heats gamma.

source
GeneralizedPerturbedEquilibrium.InnerLayer.GGJ.glasser_wang_2020_eq55 — Method
glasser_wang_2020_eq55(; taua=1.0, taur=1e6, v1=1.0) -> GGJParameters

D-shaped aspect-ratio-2, q = 2 surface from Glasser & Wang, Phys. Plasmas 27, 012506 (2020), Eq. 55 (coefficients transcribed verbatim), the benchmark of their inps Wasow-basis convergence study (Figs. 1–3). At its operating point Q = 1.234e-1 (Fig. 1) the GGJ backends are cross-checked against the Fortran rmatch deltac; the paper's Δ_± (Eq. 54) is a series-convergence norm, not matching data.

taua, taur, v1 default to a unit normalization; override them for physical cases.

source
GeneralizedPerturbedEquilibrium.InnerLayer.GGJ.q4_surface_benchmark — Method
q4_surface_benchmark() -> GGJParameters

Physical q = 4 rational-surface benchmark point (S = τR/τA ≈ 4.58×10⁶, DI ≈ −0.31166, p₁ = √(−DI) ≈ 0.5583). Primary validation point for the rotated-ray backend on the imaginary-Q axis (pinned at Q = 500i in the test suite).

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.rescale_delta — Method
rescale_delta(Δ, p::GGJParameters) -> SVector{2,ComplexF64}

Rescale the matching data to physical Δ by S^(2√(−D_I)/3) · v₁^(2√(−D_I)), element-wise on the pair (Δ₊, Δ₋). The factor X₀^(−2√(−DI)) = S^(2√(−DI)/3) is Wang et al., Phys. Plasmas 27, 122503 (2020), text after Eq. 11.

source
GeneralizedPerturbedEquilibrium.InnerLayer.solve_inner — Method
solve_inner(::GGJModel{:shooting}, params::GGJParameters, γ::Number;
            reltol::Float64=1e-6, abstol::Float64=1e-6,
            rtol_origin::Float64=1e-6, nps::Int=8,
            fmax::Float64=1.0, solver=Tsit5()) -> InnerLayerResponse

Solve the GGJ inner-layer matching problem by stable backward shooting in the origin-diagonalized 4×4 basis.

Returns an InnerLayerResponse rescaled by rescale_delta, with interchange = Δ₊ (Ξ even) and tearing = Δ₋ (Ξ odd), the same convention as the other GGJ backends.

Tolerances reltol/abstol are the integrator tolerances; rtol_origin controls the truncation error of the origin Frobenius series and the choice of tmin.

source

CCC

GeneralizedPerturbedEquilibrium.InnerLayer.CCC.CCCModel — Type
CCCModel{S,O,Q,M} <: ToroidalLayerModel{S}
CCCModel(; solver=:ray, Qstar=nothing, mperp=1.0, options...)

Drift-resistive inner-layer model of Cho, Choi & Choi (1987) in the form of Kim, Cho & Choi (1988), solved on CCCParameters. S selects the solver backend; only :ray (the rotated-contour solver of solve_ray) is available. Backend keywords given at construction, e.g. CCCModel(; cfl=0.1), apply to every solve; a keyword the backend does not take is an error here, not at the first solve. Qstar and mperp set the parameters the tearing and matching stages build (layer_parameters); a solve on given CCCParameters uses theirs.

Fields

  • options::NamedTuple - Backend keywords forwarded to every solve; call-site keywords win.
  • Qstar - Scaled electron diamagnetic frequency Q* at every surface (a number), at each surface core to edge (a vector), or nothing to take Q* = n·ω*ₑ/Q₀ from the equilibrium's kinetic data (layer_omega_star_e).
  • mperp - Perpendicular-transport weight M⊥/M at every surface (a number) or at each surface core to edge (a vector); positive.
source
GeneralizedPerturbedEquilibrium.InnerLayer.CCC.CCCParameters — Type
CCCParameters

Parameters of the drift-resistive layer of Cho, Choi & Choi, IEEE Trans. Plasma Sci. PS-15, 418 (1987), in the form of Kim, Cho & Choi, Phys. Fluids 31, 2659 (1988), Eqs. (1a)–(1c), at one rational surface. Its Γ is Υ here. Q* = 0 and M⊥/M = 1 give the GGJ equations.

Fields

  • ggj::GGJParameters - GGJ coefficients E, F, G, H, K, M and local times; Kim's coefficients are GGJ's, and so are the time and length scales, the Mercier exponents of the far field and the Δ normalization.
  • Qstar::Float64 - Electron diamagnetic frequency of the mode scaled like Q, Q* = ωₑ/Q₀, with ωₑ = n times layer_omega_star_e, SLAYER's. With the growth rate s = γ − iω, Kim's Ohm's law carries Q + iQ, which vanishes at ω = ωₑ in the E×B frame, where the layer co-rotates with the electrons.
  • mperp::Float64 - Perpendicular-transport weight M⊥/M of the QΥ'' term; must be positive.
source
GeneralizedPerturbedEquilibrium.InnerLayer.CCC.parabolic_scales — Method
parabolic_scales(params::CCCParameters, Q) -> SVector{2,ComplexF64}

Scales σⱼ of the two exponential families exp(±x²/(2σⱼ)) at large x: the roots σ² = z of z² − (1 + m + KQQ²)Q z + mQ² = 0, Kim, Cho & Choi (1988) Eq. (2) with m = M⊥/M; (√Q, √m·√Q) at Q = 0. σⱼ = √Q·√wⱼ with wⱼ = z/Q, so σⱼ is continuous in Q off the negative real axis, as GGJ's √Q is.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.layer_rows — Method
layer_rows([CT,] params::CCCParameters, Q, x) -> (Ũ, Ṽ)

Kim, Cho & Choi (1988) Eqs. (1a)–(1c) solved for the second derivatives, u'' = Ũ·u + Ṽ·u' for u = (Ψ, Ξ, Υ): GWP2016 Eq. 11 with the electron diamagnetic terms iQ(Ψ − xΥ) in Ohm's law and vorticity, the weight M⊥/M on QΥ'' and the coupling iQKQ³Ξ'' in the pressure equation, which enters the Υ'' row through Ξ''.

source

ToroidalLayer

The shared library behind the GGJ :ray and :galerkin backends: the Wasow far-field construction, the rotated-ray solver and the Hermite assembly. A layer model supplies its equations through the interface on ToroidalLayerParameters.

GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.GalerkinCell — Type
GalerkinCell

One finite element of the Galerkin grid.

Fields

  • etype - Cell type (CT_NONE, CT_EXT2, CT_EXT1, CT_EXT, CT_RES).
  • x_left, x_right - Cell end points.
  • x_lsode - Upper limit of the resonant-cell integral and the xmax surface term (`CTRES` only).
  • np - Highest local Hermite slot per component: 3 for Hermite cells, 1 for CT_EXT (left node only), −1 for CT_RES.
  • map - (mpert, np+1) local-to-global DOF map; CT_EXT appends a column of asymptotic DOFs, CT_RES holds only those.
  • emap - Asymptotic DOF indices shared by CT_EXT and CT_RES; only emap[1] is active (noexp).
source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.GalerkinWorkspace — Type
GalerkinWorkspace

Grid, banded system and scratch buffers of one Galerkin solve.

Fields

  • cells - Grid cells from x = 0 outward.
  • ndim - Number of global unknowns.
  • nx - Number of cells.
  • kl - Banded half-bandwidth (ku = kl).
  • mat - (2kl+ku+1, ndim, 2) LAPACK banded matrices, one per parity (1 = even/Δ₊, 2 = odd/Δ₋).
  • rhs, sol - (ndim, 2) right-hand sides and solutions per parity.
  • cell_mat_buf, cell_mat_ext_buf - (3, 3, 4, 4) per-cell scratch for the Hermite and extension terms.
  • cell_rhs_ext_buf - (3, 4) per-cell extension RHS scratch.
  • ab_buf, rhs_buf - Scratch copies for the banded LU solve.
source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.InnerAsymptoticsCache — Type
InnerAsymptoticsCache

Frozen inps Wasow asymptotic-basis construction for one (params, Q) pair, stored as SMatrix/SVector for allocation-free evaluation. Index convention: P[k+1] holds the k-th-order matrix P_k, etc.

Fields

  • params, Q, kmax — input parameters and series truncation order.
  • R = (r₊, r₋) — exponents of the power-like solutions at infinity (Eq. 49).
  • T — 6×6 eigenvector basis of A₀ (Eq. 7).
  • J — (J₀, J₁, J₂), the J-rotated coefficient matrices (Eqs. 9–10).
  • P — splitting matrices, k = 0..kmax+2 (Eqs. 16, 22).
  • Qmat — 2×2 inner-block transformation matrices, k = 0..kmax+2 (Eqs. 32–39).
  • Y — 2×2 series matrices Yk = Y₀Zk, k = 0..kmax (Eqs. 50–52).
source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.RaySolveResult — Type
RaySolveResult

Output of solve_ray.

Fields

  • Δ: rescaled matching data (Δ₊, Δ₋) = (interchange, tearing), the even (isol = 1) and odd (isol = 2) parities of the displacement Ξ.
  • Δraw: the same pair in raw inps normalization, before rescale_delta.
  • cexp: decaying-pair coefficients (c₁, c₂) at s_m, one column per parity.
  • Q, θ: scaled eigenvalue and contour angle.
  • S: series radius where the far-field data were taken.
  • series_ok: whether pick_smax reached its residual tolerance.
  • bc_cond: condition number of the column-normalized boundary basis [Us, Ub, E].
  • breaks: Hermite cell boundaries on [0, s_m].
  • cfl, min_cells: mesh resolution parameters used by ray_breaks.
  • ws: the full Galerkin workspace of the BVP (system buffers included); the nodal solution is ws.sol, both parities.
source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.ToroidalLayerParameters — Type
ToroidalLayerParameters <: InnerLayerParameters

Abstract supertype of the per-surface parameters of a ToroidalLayerModel. The shared solvers read a subtype only through this interface, so each model keeps whatever numbers its equations need:

A model builds its parameters with layer_parameters and checks its own inputs with check_layer_inputs.

Both backends impose parity at x = 0 (GWP2016 Sec. III): a model's equations must be invariant under x → −x with Ψ of opposite parity to Ξ and Υ, so the even solution (Ψ(0) = Ξ′(0) = Υ′(0) = 0) and the odd one (Ψ′(0) = Ξ(0) = Υ(0) = 0) decouple. A model with x-odd terms, such as flow shear, does not fit this interface.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer._assemble_and_solve_point! — Method
_assemble_and_solve_point!(ws, params, Q, θ, Us, Ub, E; nq=6) -> (Δraw, cexp)

Hermite Galerkin solve on the all-CT_NONE grid of ws along the ray x = e^{iθ}s, with the far-field condition imposed strongly at the last node: its state is v = Us + Δ·Ub + c₁E₁ + c₂E₂, with Us, Ub, E given as (Ψ, Ξ, Υ, Ψ', Ξ', Υ') in x-derivatives; the last node's six DOFs are replaced by (Δ, c₁, c₂). Returns the raw Δ and decaying-pair coefficients per parity (isol = 1 even/Δ₊, 2 odd/Δ₋); ws.sol holds the full nodal solution afterwards.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.asymptotic_residual — Method
asymptotic_residual(cache::InnerAsymptoticsCache, x::Number) -> SVector{2,Float64}

Convergence measure of the asymptotic basis at real or complex x for each of the two algebraic columns, the analogue of GW2020 Eq. 54 in the J-rotated basis. Returns ‖dU − x·matrix·U‖∞ / max(‖dU‖∞, ‖x·matrix·U‖∞) per column, where matrix = J₀ + xfac·J₁ + xfac²·J₂ is the J-rotated coefficient matrix (the residual of v' = xJv, GW2020 Eq. 6).

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.boundary_basis — Method
boundary_basis(params, Q, cache, θ, S; growth=30.0, seed=20260707, dp_res=20.0)
    -> (Us, Ub, E, cond_est)

Boundary data at s = S taken directly from the inps series, used when the BVP edge is S itself (sm ≳ S): Us, Ub are the small/large power-like solutions as 6-component states in the inps normalization, E the numerically generated decaying pair, `condest` the condition number of the column-normalized basis.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.decaying_pair — Method
decaying_pair(params, Q, θ, S; growth=30.0, seed=20260707, dp_res=20.0) -> E (6×2)

Orthonormal basis of the forward-decaying pair at s = S on the ray: random seeds integrated backward over [S, S+ΔS] with fully-resolved RK4, ΔS sized so the pair separates from everything else by ≈ growth e-folds.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.delta_convergence — Method
delta_convergence(params, Q; verbose=true, kwargs...) -> (; Δ, spread, base, table)

Error bar for the matching data: re-solve with each numerical knob perturbed in turn (contour angle, mesh, series order and radius, march tolerance, BVP edge sm, decaying-pair separation) and report the relative change of (Δ₊, Δ₋); spread is the worst case per parity. θ moves outward, away from the pseudo-resonance x² = −Q²(G+KF), or inward when the outward angle is not [`rayangle_admissible`](@ref).

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.evaluate_asymptotics — Method
evaluate_asymptotics(cache::InnerAsymptoticsCache, x::Number; derivative=true, apply_T=true) -> (U, dU)

Evaluate the inps asymptotic basis at x, real (x > 0) or complex on a rotated contour (principal branch of x^r; the series is in 1/x², so valid for |arg x| < π/2). Returns the 6×2 complex matrix U whose two columns are the power-like (Mercier) solutions of the layer system (column 1 large, column 2 small), and (if derivative=true) the 6×2 matrix dU of their derivatives dU/dx.

If apply_T=false, the result is left in the J-rotated basis (used by asymptotic_residual). The default apply_T=true returns it in the GW2020 Eq. (2) state basis, which physical_ua_dua converts to (Ψ, Ξ, Υ).

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.galerkin_response — Method
galerkin_response(params, γ::Number; kmax::Int=8, nx::Int=512, nq::Int=4, pfac::Float64=1.0,
                  cutoff::Int=5, xfac::Float64=1.0, tol_res::Float64=1e-5) -> InnerLayerResponse

Solve the inner-layer matching problem with the Hermite-cubic finite element (Galerkin) method (GWP2016 Sec. III), in the "resonant + noexp + inps" configuration.

Returns the parity-projected matching data (GWP2016 Eqs. 34–35), rescaled by rescale_delta, as an InnerLayerResponse: interchange is the even-parity Δ₊ (isol = 1), tearing the odd-parity Δ₋ (isol = 2).

Knobs: kmax series order; nx cell count; nq Gauss–Lobatto order; pfac grid packing; cutoff extension-cell span (cells nx−cutoff−1 … nx−1); xfac scale on the two inner matching radii; tol_res resonant-cell quadrature tolerance.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.layer_parameters — Function
layer_parameters(model, surface, equil; eta, rho, gamma=5/3, ising=0) -> ToroidalLayerParameters

The per-surface parameters model solves on at the singular surface surface of equil, from its resistive geometry surface.restype, the local resistivity eta in Ω·m, the mass density rho in kg/m³, the ratio of specific heats gamma and the surface's index ising, core to edge.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.march_boundary — Method
march_boundary(params, Q, θ, S, s_m, Us, Ub; rtol=1e-9, ztrk=0.3, purge_budget=2.5,
               growth=30.0, seed=20260707, dp_res=20.0)
    -> (Us_m, Ub_m, F)

Transport the power-pair boundary data from the series radius S inward to s_m along the ray, modulo the decaying exponential pair (the quotient in which Δ is defined): 2-stage Radau IIA with purges against a carried decaying frame. rtol sets the step factor c = (rtol/100)^{1/3}; ztrk caps resolved-band steps at ztrk/gmax; `purgebudgetis the e-folds between purges;growth,seed,dpresgo to [decayingpair`](@ref).

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.ode_matrix — Method
ode_matrix([CT,] p::ToroidalLayerParameters, Q, x) -> SMatrix{6,6,CT}

Coefficient matrix M(x) of the layer equations (GWP2016 Eq. 11 for GGJ) as dv/dx = M v, v = (Ψ, Ξ, Υ, Ψ', Ξ', Υ'), for real or complex x, built from the model's layer_rows. M is polynomial in x, so x = 0 is an ordinary point and the system continues analytically to complex x. CT selects the element type (default ComplexF64; Complex{Double64} for the extended-precision march).

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.physical_ua_dua — Method
physical_ua_dua(cache, x::Number) -> (ua, dua)

Convert the inps 6×2 basis at real or complex x to physical (Ψ, Ξ, Υ) values and x-derivatives, each 3×2 (column 1 = large power solution, 2 = small). The inps columns are in the GW2020 Eq. (2) state u = (xΨ, Ξ, Υ, (xΨ)'/x, Ξ'/x, Υ'/x), hence the /x and ·x factors; same map as the deltac inpso_get_ua/dua convention.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.pick_smax — Method
pick_smax(params, Q; θ=default_ray_angle(params, Q), eps=1e-9, kmax=12, cache=nothing,
          slogmin=-1.0, slogmax=6.5, dslog=0.01) -> (S, cache, achieved)

Sweep s log-uniformly upward and return the smallest s at which the series residual (GW2020 Eq. 54) along x = e^{iθ}s drops below eps. If never reached, returns the residual-minimizing s with achieved = false.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.power_exponents — Function
power_exponents(params) -> SVector{2,Float64}

Exponents (r₊, r₋) of the two power-like far-field solutions in the Wasow state, x^r for xΨ (GW2020 Eq. 49); r₊ the large solution, r₋ the small one. They must be the roots of r² − 3r − c₂²¹ = 0, with c₂²¹ the power block of the model's wasow_basis (GW2020 Eqs. 39, 48): r₊ + r₋ = 3 and r₊r₋ = −c₂²¹. Otherwise the asymptotic series do not solve the equations.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.ray_breaks — Method
ray_breaks(params, Q, θ, S; cfl=0.2, min_cells=1024) -> Vector{Float64}

Cell boundaries 0 = s₀ < s₁ < … = S for the Hermite BVP: each cell resolves the full local WKB rate μ + ρs, the model's fast_rates μ (for GGJ the Ohm and Υ-family pairs |√Q| + √(|Q|·|G+KF|)) and its parabolic_resolution_rate ρ (Re(e^{2iθ}/√Q) for GGJ), whether or not the mode is present, since unresolved dormant modes alias into spurious discrete ones. min_cells floors the resolution where the local rates are small (|Q| ≪ 1).

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.ray_profile — Method
ray_profile(params, γ::Number; real_profiles=false, npc=8, certify_rtol=1e-3, kwargs...)
    -> (; Δ, x, Ψ, Ξ, dψdx, rescale, certΔ)

Rotated-ray implementation of the solve_inner_profile interface. Δ and the layer-center fields come from the solve at the model's default contour angle; x = 0 lies on every contour, so Ψ(0), Ξ(0) are the real-axis values, and by default only they are returned (x = [0.0], certΔ = NaN). With real_profiles = true the fields across the layer (x > 0) come from an extra θ = 0 solve (npc points per cell), a diagnostic; the x = 0 row stays the rotated solve's, and certΔ is the largest relative difference of the two solves' Δ₊, Δ₋, warned above certify_rtol. Other keywords forward to solve_ray, except θ.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.solution_profile — Method
solution_profile(res::RaySolveResult; npc=8) -> (; s, x, Ψ, Ξ, Υ)

Reconstruct (Ψ, Ξ, Υ) on the solution contour from the Hermite nodal solution, npc points per cell; each field is npts × 2 with columns (even, odd) as in Δ, and x = e^{iθ}s. For rotated solves the fields live on the ray, not the real axis.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.solve_ray — Method
solve_ray(params, Q; θ=default_ray_angle(params, Q), kmax=12, S=nothing, smax_tol=1e-9,
          cfl=0.2, min_cells=1024, warn_cells=6000, nq=6, verbose=false, …) -> RaySolveResult

Solve the inner-layer problem of params' model on the rotated ray x = e^{iθ}s. Δ is the rescaled pair (Δ₊, Δ₋) = (interchange, tearing), directly comparable to the :galerkin backend; θ = 0 is a real-axis solve.

S defaults to the smallest radius where the series residual is below smax_tol at order kmax (pick_smax; warns and uses the best point otherwise). The BVP edge sm is where every exponential family has decayed 45 e-folds from the origin, scaled by `smfac.cfl,mincellsset the Hermite grid ([raybreaks](@ref)) andnqits quadrature. The grid is not residual-refined and no error estimate is returned (at small |Q| Δ is good to about 1e-8–2e-7 relative); use [deltaconvergence](@ref) for an error bar. More thanwarncellscells warns once (cost guard).marchrtolis [marchboundary](@ref)'srtol;growth,seed,ztrk,purgebudget,dpresgo tomarchboundary/[decayingpair](@ref);handoff` (diagnostic) supplies (Us, Ub) at S.

source
GeneralizedPerturbedEquilibrium.InnerLayer.ToroidalLayer.wasow_basis — Function
wasow_basis(params, Q::ComplexF64) -> (T, (J₀, J₁, J₂), splitter)

The far-field system u' = x(A₀ + A₁/x² + A₂/x⁴)u in the state u = (xΨ, Ξ, Υ, (xΨ)'/x, Ξ'/x, Υ'/x) (GW2020 Eqs. 2–5), as a basis T whose first two columns span the power-like subspace and last four the exponential one, the rotated Jₖ = T⁻¹AₖT (GW2020 Eqs. 9–10), and the splitter passed to split_block.

source
GeneralizedPerturbedEquilibrium.InnerLayer.solve_inner — Method
solve_inner(m::ToroidalLayerModel{:ray}, params, γ::Number; kwargs...) -> InnerLayerResponse
solve_inner(m::ToroidalLayerModel{:galerkin}, params, γ::Number; kwargs...) -> InnerLayerResponse

Matching data (Δ₊, Δ₋) from ray_response or galerkin_response, with the model's options and then kwargs (call-site keywords win). γ is the growth rate in the surface's E×B frame, in 1/s.

source

SLAYER

GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.LayerWidths — Type
LayerWidths

Resistive inner-layer length scales at one rational surface, in meters. The primary quantity is delta_s_m, the resistive layer thickness from the SLAYER del_s Riccati solve; d_beta is the β-weighted ion scale it is built from, retained as a drift-scale reference.

Fields

  • ising, m, n – surface index and mode numbers (traceability)
  • dels_db – dimensionless δ_s / d_β from riccati_del_s
  • delta_s – complex layer thickness δ_s = dels_db · d_β [m]
  • delta_s_m – |δ_s|, the resistive layer thickness in meters (primary)
  • d_beta – β-weighted ion scale c_β·d_i in meters (drift reference)
  • delta_norm – layer normalization length r_s · S^(-1/3) in meters (Δ̂' = Δ'·delta_norm), the reciprocal of SLAYERParameters.delta_n, shared by all four regimes of Burgess et al. (2026) Eqs. (10)-(13); not the Furth-Killeen-Rosenbluth S^(-2/5) tearing width
  • delta_dr – diffusive-resistive layer thickness in meters, Fitzpatrick (2025) Eq. (100), equal to rs · lu^(-1/2) P_perp^(1/4) / d_beta_hat^(1/2) with d_beta_hat = d_beta/rs (SLAYER's lu already carries the paper's (n|s|)^(1/2)). Strong shear forces edge layers into this (nu = 1/4) regime, so it is the width the edge overlap criterion compares against surface spacing
  • delta_visco – viscous-resistive scale delta_norm · P_perp^(1/6) in meters, from the P^(1/6) broadening of the VR-regime growth rate, Burgess et al. (2026) Eq. (11). The paper gives the growth rate rather than an explicit width; this is the corresponding length

delta_s_m should sit within a few orders of magnitude of d_beta for a well-posed surface (dels_db is O(1)); a large gap flags a normalisation or input problem.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.SLAYERModel — Type
SLAYERModel(; variant=:fitzpatrick, P_perp_model=:D_perp, D_c_type=:none, D_R=nothing, D_geo=nothing, chi_perp_Dc=nothing,
            theta_sample=0.0)

SLAYER inner-layer model: the Riccati formulation and the layer closures that turn the plasma (the equilibrium's kinetic data) into layer parameters. The type parameter S of SLAYERModel{S} is the formulation:

  • :fitzpatrick – Pperp/Ptor Fitzpatrick formulation (default; Fitzpatrick 2023 two-fluid drift-MHD layer)

The del_s formulation is exposed separately as the layer-thickness diagnostic slayer_layer_thickness, not as a dispersion solve_inner path.

Fields

  • P_perp_model - How the perpendicular Prandtl number is built: :D_perp (default; needs χ⊥,i), :chi_perp_e, :chi_perp_i, :P_phi, :c_beta or :tau_E; see slayer_parameters.
  • D_c_type - Critical-Δ offset: :none (default), :lar, :fitzpatrick or :toroidal (χ_‖-matching formulas of Connor, Ham, Hastie & Liu 2015).
  • D_R, D_geo - Critical-Δ inputs; nothing (default) derives them per surface from the equilibrium: D_R = E + F + H², and D_geo the Connor et al. 2015 Eq. 59 toroidal geometric factor in the r_s reference (consumed only by :toroidal, which also takes its parallel wavenumber from the equilibrium, toroidal_kpar). An explicit D_R = 0.0 disables the offset for every D_c_type; D_geo = 0.0 only for :toroidal.
  • chi_perp_Dc - Electron perpendicular heat diffusivity [m²/s] used only by the critical Δ; nothing (default) uses the χ⊥,e that Pperp sees. Set it when Pperp is built from a diffusivity the critical Δ should not use. It replaces χ⊥,e in the critical Δ at every surface, over any chi_e profile, reaches the critical resonant field through the critical Δ, and has no effect with D_c_type = :none.
  • theta_sample - Poloidal angle (normalized to [0, 1)) of the minor-radius chord of the :midplane radial label, used only by API callers that pass rs_method = :midplane; the default toroidal-flux label does not depend on angle, so a nonzero value warns (default 0, the outboard midplane).
source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.SLAYERParameters — Type
SLAYERParameters

Dimensionless layer-physics parameters at one rational surface for the Fitzpatrick two-fluid drift-MHD SLAYER inner-layer model (Fitzpatrick 2023; Park 2022), plus dimensional auxiliaries required for de-normalization.

fieldmeaning
isingSingular-surface index (traceability only)
m, nPoloidal / toroidal mode numbers at this surface
tauTi / Te
luLundquist number S = τR / τH
c_betaCompressibility √(βlocal / (1 + βlocal))
D_norm(dβ/rs) · S^(1/3) · √ι_e (Fitzpatrick normalized scale)
P_perpPerpendicular Prandtl number τR / τ⊥ (set by P_perp_model)
P_torMomentum Prandtl number τR / τφ, τφ = rs²/χ_φ
Q_eNormalized electron diamagnetic: −tauk · ω_*e
Q_iNormalized ion diamagnetic: −tauk · ω_*i
iota_eQe / (Qe − Q_i)
taukQ-conversion factor S^(1/3) · τ_H [s] — multiplies ω to get Q
tau_rResistive diffusion time [s]
delta_nΔ-normalization factor S^(1/3) / r_s [m⁻¹]
rsMinor radius at this surface [m]
R0Major radius [m]
btToroidal field [T]
sval_rr-based magnetic shear r_s · (dq/dr) / q (Fitzpatrick convention)
dr_valResistive interchange D_R = E + F + H² (critical-Δ input; auto-derived from GGJ coefficients unless overridden)
dgeo_valConnor et al. 2015 Eq. 59 toroidal critical-Δ geometric factor in the rs reference (see `toroidaldgeo`)
kpar_valParallel-wavenumber gradient K∥ [1/m] of the :toroidal χ∥ closure, k∥ = K∥·Wd (see `toroidalkpar`); the cylindrical n·abs(s)/R₀ when not derived
etaParallel resistivity entering τR = μ₀rs²/η [Ω·m]
d_betaBeta-weighted ion length scale cβ · di [m]
dc_tmpCritical-Δ offset from chiparallel matching (for :toroidal, Wd and the free-streaming χ∥ use dgeo_val and kpar_val)
dc_typeSelector for dc_tmp formula
k_refReference-length ratio K = rs · (dψN/dr) at this surface (1 = no Δ' conversion)
alpha_mercierMercier Frobenius exponent α = √(−D_I) (Glasser-Greene-Johnson 1975 Eq. 48) governing the Δ' reference-length conversion (1/2 = slab/cylindrical value)

k_ref and alpha_mercier convert the ψN-referenced outer Δ' to the `x̂ = (r−rs)/rsreference of the layer (deltaprimetorsreferencein the Tearing runner); the defaultkref = 1` makes that the identity.

The complex normalized growth rate Q = ω + iγ is not stored here; it is passed as a separate argument to solve_inner.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.build_slayer_inputs — Method
build_slayer_inputs(equil, sings, profiles; …) -> Vector{SLAYERParameters}

Build a SLAYERParameters for each rational surface in sings from the in-memory equil::PlasmaEquilibrium (geometry, q, dq/dψ, R₀) and profiles::KineticProfiles (ne, Te, Ti, and ω\*e, ω_*i from their gradients). Keywords documented as scalar-or-callable are evaluated per surface at ψ.

Arguments

  • equil – PlasmaEquilibrium
  • sings – Vector{SingType}, one per resonant surface
  • profiles – KineticProfiles valid across all sings ψ values

Keyword arguments

  • bt – toroidal field in T, scalar or callable; nothing (default) uses BT = F(ψ)/(2π·R₀). `equil.config.b0norm` is a normalization, not this field
  • R0 – major radius in m (default equil.ro)
  • rs_method – radial label of the whole layer stack: :flux (default), :midplane, :halfwidth, :fsa or :volume; see radial_label. Programmatic only, not exposed via TOML
  • q_beyond – callable q(ψ) the :flux label uses beyond the ψ grid (default nothing)
  • mu_i – main-ion mass in proton masses (default 2.0, D)
  • mu_rho – mean ion mass per electron in proton masses for the mass density, scalar or callable (default mu_i)
  • zeff – effective charge, scalar or callable (default 1.0)
  • z_i – main-ion charge entering ω_*i (default 1.0)
  • chi_perp_e – electron perpendicular heat diffusivity in m²/s, scalar or callable (default 1.0)
  • chi_perp_i – ion perpendicular heat diffusivity in m²/s, scalar or callable; needed by P_perp_model = :chi_perp_i and :D_perp
  • chi_perp_Dc – electron χ⊥ in m²/s used only by the critical Δ, scalar or callable; nothing (default) uses chi_perp_e
  • tau_E – whole-plasma energy confinement time τ̄E in s, needed by `Pperpmodel = :tauE, which takesafrom the:flux` label
  • P_perp_model – how P_perp is built (default :D_perp); see slayer_parameters
  • chi_tor – toroidal momentum diffusivity χφ in m²/s, scalar or callable, setting Ptor = τR/τφ with τφ = rs²/χ_φ (Fitzpatrick, Phys. Plasmas 30, 092512 (2023)) (default 1.0)
  • dr_val – resistive interchange index DR = E + F + H² (Glasser-Greene-Johnson 1975) of the critical Δ, not the Mercier DI; nothing (default) derives it from sing.restype, a scalar or callable overrides it
  • dgeo_val – Connor et al. 2015 (PPCF 57 065001) Eq. 59 factor in the r_s reference (toroidal_dgeo), used only by dc_type = :toroidal; nothing (default) derives it from sing.restype (required then). A prescribed value must already be in the r_s reference, i.e. Eq. 59 times k_ref·v1/V_s (≈ 2 at large aspect ratio)
  • dc_type – critical-Δ formula: :none (default), :lar, :fitzpatrick or :toroidal; :toroidal takes K∥ from toroidal_kpar, or the cylindrical n·|s|/R₀ with a warning when the surface has no ResistGeometry
  • theta – poloidal angle of the minor-radius chord, used only by rs_method = :midplane (default 0.0, outboard midplane)
  • resistivity_model – SauterNeoModel() (default), RedlNeoModel(), SpitzerModel() or SpitzerHarmModel(); the neoclassical f_trap and ν*_e come from sing.restype when populated, else the ε-only forms
  • lnLambda_form – Coulomb-log form (default :nrl; :wesson with SpitzerHarmModel() reproduces the legacy SLAYER)
source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.layer_resistivity — Method
layer_resistivity(equil, sings, profiles::KineticProfiles; zeff=1.0, R0=nothing, rs_method=:midplane,
                  theta=0.0, q_beyond=nothing, resistivity_model=SauterNeoModel(), lnLambda_form=:nrl) -> Vector{Float64}

Parallel resistivity η in Ω·m at each surface of sings, with the same closure and per-surface inputs build_slayer_inputs gives the SLAYER layer, so every resistive inner layer of a run sees one η. zeff is a scalar or a callable of ψ.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.r_based_shear — Method
r_based_shear(rs, q, dq_dpsi, da_dpsi) -> Float64

Convert a ψ-based shear to the r-based (Fitzpatrick) convention used throughout SLAYER:

s_r = r_s · (dq/dr) / q  =  r_s · (dq/dψ) / (q · da/dψ)

dq_dpsi and da_dpsi (minor radius) must be taken with respect to the same ψ, normalized or physical; the conversion factor cancels in the ratio.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.radial_label — Method
radial_label(equil; rs_method=:flux, theta=0.0, q_beyond=nothing) -> (r_at, dr_dpsi_at)

Build the pair of closures r_at(ψ) and dr_dpsi_at(ψ) defining one radial label for the layer stack. Both closures must come from the same label, because the r-based shear (r/q)dq/dr, τ_R = μ₀r²/η, τ_E = r²/χ, the d_β/r normalization, the Δ' reference-length factor k_ref = r_s/(da/dψ), and any metre-to-ψ width conversion all have to live in one coordinate; a mismatched r and dr/dψ silently corrupts every one of them. All derivatives are analytic — no label carries a finite-difference stencil.

Labels

  • :midplane – outboard-midplane chord from the magnetic axis at theta natural for comparison with midplane diagnostics.
  • :halfwidth – midplane half-chord, the mean of the outboard and inboard chords at θ = 0 and θ = 0.5; shift-free. Coincides with the flux label on circular equilibria but is its own convention on shaped ones.
  • :fsa – θ-mean surface radius, a 128-point midpoint mean of the local minor radius; the closest geometric approximation to :flux at interior surfaces of shaped equilibria.
  • :volume – cylinder-equivalent label √(V(ψ)/(2π²R₀)), the Rutherford-literature convention.
  • :flux – toroidal-flux label. Fitzpatrick, Nucl. Fusion (2025), Eq. 30: dψ_p/dr = B₀ r g/q integrates to ψ_t = B₀r²/2, so r = √(2ψ_t/B₀) with ψ_t = psio·∫₀^ψ (q/g) dψ′ and g = F/(B₀R₀), F = R·B_tor. Note profiles.F_spline stores 2πF, so the implementation divides it by 2π to form g. Defined from flux alone, it carries no circular-cross-section assumption, and its derivative dr/dψ ∝ q grows toward a separatrix where the geometric labels' da/dψ collapses. Beyond the ψ grid the q spline is a cubic extrapolation that does not follow that growth, so q_beyond, a callable of ψ, supplies q there when the caller knows it.

On shaped equilibria the labels agree at low-q surfaces and diverge strongly near the edge, where the slab-layer matching is label-ambiguous regardless of choice. The label is selected programmatically; it is not exposed via TOML.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.riccati_del_s — Method
riccati_del_s(p::SLAYERParameters;
              q_start=5*p.D_norm, q_min=1e-5,
              reltol=1e-10, abstol=1e-10, maxiters=50_000,
              solver=Rodas5P(autodiff=false)) -> ComplexF64

Solve the SLAYER del_s inner-layer Riccati ODE and return the dimensionless layer-thickness ratio δ_s / d_β at one rational surface.

Integrates dW/dq = W/q − W²/q + q·E/F inward from q_start = 5·D_norm to q_min, with asymptotic boundary value W = −α·q_start² − 0.5, α = √(P̂_⊥ / (1 + 1/τ)). The result is −(π / √(1 + 1/τ)) · W′(q_min), evaluated from a single RHS call at the inner endpoint.

Returns NaN + NaN·im if the stiff integration does not converge (the caller treats this as a missing diagnostic rather than a hard error).

Multiply the result by p.d_beta to obtain the resistive layer thickness in meters (see slayer_layer_thickness).

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.slayer_layer_thickness — Method
slayer_layer_thickness(p::SLAYERParameters; kwargs...) -> LayerWidths

Compute the resistive inner-layer thickness in meters at one rational surface.

Runs riccati_del_s for the dimensionless δ_s / d_β and scales by p.d_beta to obtain δ_s in meters. Keyword arguments are forwarded to riccati_del_s.

The algebraic comparison scales delta_norm, delta_visco and delta_dr come from p directly and do not depend on the Riccati solve; slayer_algebraic_widths returns just those, for callers that do not need delta_s.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.slayer_parameters — Method
slayer_parameters(; n_e, t_e, t_i, omega_e, omega_i, qval, sval_r, bt, rs, R0, mu_i, zeff, chi_perp_e, chi_tor, m, n,
                    mu_rho=mu_i, chi_perp_i=nothing, tau_E=nothing, a_minor=nothing, dlnn=nothing, dlnTe=nothing, dlnTi=nothing,
                    P_perp_model=:D_perp, chi_perp_Dc=nothing, dr_val=0.0, dgeo_val=0.0, kpar_val=nothing,
                    dc_type=:none, ising=0, resistivity_model=SauterNeoModel(), f_trap=nothing, nu_e_star=nothing,
                    R_major_eff=nothing, lnLambda_form=:nrl, k_ref=1.0, alpha_mercier=0.5) -> SLAYERParameters

Build the SLAYERParameters of one rational surface from dimensional equilibrium and kinetic-profile inputs, in the Fitzpatrick two-fluid layer parametrization. The diamagnetic frequencies normalize as Q_e = -tauk·ω_*e, Q_i = -tauk·ω_*i, so the usual ω*e < 0 < ω*i gives Q_e > 0 > Q_i; they must have opposite signs (iota_e > 0). An input the selected model does not use may be left nothing; one it uses must be given, positive and finite.

Arguments

  • n_e – electron density in m⁻³

  • t_e, t_i – electron and ion temperatures in eV

  • omega_e, omega_i – electron and ion diamagnetic frequencies in rad/s

  • qval – safety factor at the surface

  • sval_r – r-based magnetic shear r·(dq/dr)/q (Fitzpatrick); convert a ψ-based shear with r_based_shear

  • bt – toroidal field in T

  • rs, R0 – minor radius at the surface and major radius, in m

  • mu_i – main-ion mass in proton masses (2.0 for D), for the ion sound radius and skin depth

  • mu_rho – mean ion mass per electron in proton masses, for the mass density ρ = murho·mp·ne (default `mui`)

  • zeff – effective charge

  • chi_perp_e, chi_tor – electron perpendicular heat and toroidal momentum diffusivities in m²/s

  • m, n – poloidal and toroidal mode numbers

  • chi_perp_i – ion perpendicular heat diffusivity in m²/s; needed by P_perp_model = :chi_perp_i and :D_perp

  • tau_E – whole-plasma energy confinement time τ̄E in s; needed by `:tauE`

  • a_minor – plasma minor radius a in m; needed by :tau_E

  • dlnn, dlnTe, dlnTi – radial log-gradients of n, Te, Ti in any common radial variable (only ratios enter); needed by :D_perp

  • P_perp_model – how P_perp is built (default :D_perp, as in the [SLAYER] deck):

    • :D_perp – τR/τ⊥ with τ⊥ = rs²/D⊥, Fitzpatrick, Phys. Plasmas 29, 032507 (2022), Eq. 16 (with Eqs. 4-6 and η⊥ = η∥); its τ = (Te/Ti)(1+ηe)/(1+ηi) is the inverse of the tau field; flat temperatures give the `:cbeta` value
    • :chi_perp_e, :chi_perp_i – τR·χ⊥/rs² with the electron or ion χ⊥
    • :P_phi – Pperp = Ptor (Fitzpatrick, Phys. Plasmas 30, 092512 (2023), Eq. 143)
    • :c_beta – Pperp = cβ² (J.-K. Park, Phys. Plasmas 29, 072506 (2022), Eq. 9 with K = 0), the χ⊥ → 0 limit of :D_perp
    • :tau_E – Pperp = Ptor = τR/τE(rs) from a uniform χE = κe a²/τ̄E with κe = 3/16 for Te ∝ 1 − r̂² (Fitzpatrick 2023, Eqs. 37-38, 81-83 and 131; other profile shapes change κe by a factor 2-3); `chitor` is ignored
  • chi_perp_Dc – electron χ⊥ in m²/s used only by the critical Δ; nothing uses chi_perp_e, which otherwise sets dc_tmp in every mode

  • dr_val – resistive interchange index D_R of the critical Δ

  • dgeo_val – Connor et al. 2015 Eq. 59 toroidal geometric factor in the r_s reference (toroidal_dgeo)

  • kpar_val – parallel-wavenumber gradient K∥ in 1/m of the :toroidal χ∥ closure (toroidal_kpar); nothing uses n·|s|/R₀

  • dc_type – critical-Δ formula: :none, :lar, :fitzpatrick or :toroidal

  • ising – singular-surface index, for traceability

  • resistivity_model – η closure setting τR = μ₀rs²/η and hence S: SauterNeoModel() (default, Sauter 1999 F33), RedlNeoModel(), SpitzerModel() or SpitzerHarmModel() (with `lnLambdaform = :wesson` reproduces the legacy SLAYER τ_R)

  • f_trap, nu_e_star – trapped fraction and ν*e for the neoclassical models; nothing uses the Lin-Liu-Miller ε-only form and Sauter 1999 Eq. 18b with ε = `rs / Rmajor_eff`

  • R_major_eff – ⟨R⟩ at the surface for the ν*_e formula (default R0)

  • lnLambda_form – Coulomb-log form: :nrl (default), :sauter or :wesson

  • k_ref – K = rs·(dψN/dr), converting the ψN-referenced outer Δ' to the rs reference (default 1, no conversion)

  • alpha_mercier – Mercier exponent α = √(−D_I) of the same conversion (default 0.5, the slab value)

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.surface_da_dpsi — Method
surface_da_dpsi(equil, psi; theta=0.0) -> Float64

Analytic ψ-derivative of the minor radius at psi and poloidal angle theta, taken from the rzphi_rsquared interpolant's own ψ-derivative as da/dψ = (∂r²/∂ψ) / (2a). Valid wherever the interpolant is, including under extrapolation past the ψ grid. Diverges at the magnetic axis, where a ~ √ψ; callers evaluating near ψ = 0 must check isfinite.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.surface_minor_radius — Method
surface_minor_radius(equil, psi; theta=0.0) -> Float64

Minor radius at normalized flux psi and poloidal angle theta, computed from equil.rzphi_rsquared as √((R − R₀)² + (Z − Z₀)²). theta is normalized to [0, 1): 0.0 (outboard midplane) is the default and 0.5 is the inboard midplane.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.surface_resistivity — Method
surface_resistivity(; n_e, t_e, zeff, qval, rs, R0, resistivity_model=SauterNeoModel(), lnLambda_form=:nrl,
                    f_trap=nothing, nu_e_star=nothing, R_major_eff=nothing, lnLamb=nothing) -> Float64

Parallel resistivity η in Ω·m at a rational surface, the closure every resistive inner layer shares (ne in m⁻³, te in eV). The model selects it:

  • SpitzerHarmModel() – Fitzpatrick Spitzer-Härm σ∥; with `lnLambdaform = :wesson` this is bit-identical to the legacy SLAYER η
  • SpitzerModel() – Sauter 18a fit (the legacy 1.65e-9 form under :wesson)
  • SauterNeoModel() / RedlNeoModel() – the F33 trapped-particle correction using `ftrapand ν*_e, each from the caller (ResistGeometry) or else the ε = r_s/R form with R =Rmajoreff(defaultR0`)
source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.toroidal_dgeo — Method
toroidal_dgeo(; chi1, v1, q, q1, n, avg_bsq, avg_dpsisq, k_ref) -> Float64

Geometric factor of the toroidal critical-Δ, Connor, Ham, Hastie & Liu 2015 (PPCF 57 065001) Eq. 59, V_s·(α²Λ²/(⟨B²⟩⟨|∇V|²⟩))^{1/4}, converted from the paper's Y = (V−V_s)/V_s reference to the x̂ = (r−r_s)/r_s reference shared by the slab layer, the :fitzpatrick critical-Δ, and the reference-length-converted outer Δ'. In GPEC quantities, with V the flux-surface volume, ψ_N the normalized poloidal flux, and ' = d/dV:

  • α = 2πn/χ' with χ' = chi1/v1 (χ the full poloidal flux, chi1 = 2π·psio, v1 = dV/dψ_N)
  • Λ = ψ_t'²·(ι/2π)' with ψ_t' = q·chi1/v1 (toroidal flux) and (ι/2π)' = −q1/(q²·v1) (q1 = dq/dψ_N)
  • ⟨|∇V|²⟩ = v1²·⟨|∇ψ_N|²⟩, both averages being normalized flux-surface averages (⟨1⟩ = 1)
  • the reference conversion r_s·(dV/dr)/V_s = k_ref·v1/V_s with k_ref = r_s·dψ_N/dr, so V_s cancels and is never integrated.

At large aspect ratio this reduces to √(n·s·r_s/R₀) with s = (r_s/q)·dq/dr, so dc_type=:toroidal coincides with :fitzpatrick there; the paper's own Eq. 61 is recovered after dividing by r_s.

The reference conversion is deliberately linear (Frobenius exponent ½, the paper's H = 0 ordering): the critical-Δ is a layer-side quantity like the slab Δ̂(Q) and Wd, whereas the outer Δ' carries the Mercier exponent `αM = √(−DI)and is converted withK^(2αM)`.

source
GeneralizedPerturbedEquilibrium.InnerLayer.SLAYER.toroidal_kpar — Method
toroidal_kpar(; chi1, v1, q, q1, n, avg_bsq, k_ref) -> Float64

Parallel-wavenumber gradient K∥ [1/m] of the toroidal critical-Δ closure: an island of normalized width W (in the x̂ = (r−r_s)/r_s reference) sees k∥ = K∥·W. From Connor, Ham, Hastie & Liu 2015 (PPCF 57 065001) Eq. 20, whose transport balance reads χ⊥⟨|∇V|²⟩ ∂²_x = χ∥ (α²Λ²/⟨B²⟩) x² in x = V − V_s, the parallel wavenumber is k∥ = |αΛ|·x/√⟨B²⟩; with x = W·r_s·(dV/dr) = W·k_ref·v1,

K∥ = |α·Λ|·k_ref·v1 / √⟨B²⟩,

with α, Λ as in toroidal_dgeo. At large aspect ratio it reduces to Fitzpatrick's (1995, Phys. Plasmas 2 825, Eq. 132) cylindrical n·s/R₀. It is not a function of D_geo alone: K∥ = (D_geo²/r_s)·r_s√⟨|∇ψ_N|²⟩/k_ref, and the last factor is 1 only in a cylinder.

source
GeneralizedPerturbedEquilibrium.InnerLayer.solve_inner — Method
solve_inner(::SLAYERModel{:fitzpatrick}, p::SLAYERParameters, s::Number;
            pmin=1e-6, p_floor=6.0, reltol=1e-10, abstol=1e-10, maxiters=50_000,
            solver=Rodas5P(autodiff=false)) -> InnerLayerResponse

Solve the Fitzpatrick SLAYER inner-layer Riccati ODE at the complex growth rate s = γ − iω in 1/s, in the surface's E×B frame. The layer is evaluated at Fitzpatrick's normalized eigenvalue ĝ = s·τk (Fitzpatrick 2023: γ = Re(ĝ)/τk, ω = −Im(ĝ)/τk), and the diamagnetic drifts enter as ĝ − i·Qe and ĝ − i·Qi, so the layer co-rotates with the electron fluid at ω = ω*e. Returns an InnerLayerResponse with tearing = Δ and interchange = 0: SLAYER's pressureless layer produces only the tearing channel.

Integrates dW/dp = -(fA'/p)·W − W²/p + (fB/(fA·fC))·p³ (Fitzpatrick 2023; Park 2022) from a large p_start inward to pmin and returns Δ = π / W'(pmin).

Solver swaps: tiny differences between ODE solvers change the outer AMR's cell flagging and hence the classified root/pole inventory, so validate a new solver against n_valid_roots and n_poles, not just γ.

Keyword arguments

  • pmin – inner-layer cutoff (default 1e-6)
  • p_floor – floor on p_start (default 6.0)
  • reltol,abstol,maxiters – stiff-solver tolerance/iteration limits
  • solver – any OrdinaryDiffEq algorithm; pass Tsit5() for the non-stiff path (rarely needed here)
source

Dispersion

GeneralizedPerturbedEquilibrium.Tearing.Dispersion.AMRResult — Type
AMRResult

Output of amr_scan.

fieldmeaning
cellsFinal list of AMRCell after all refinement passes
QFlat Vector{ComplexF64} of every unique residual eval
ΔCorresponding Vector{ComplexF64} of residual values
truncatedtrue if max_cells was hit under :warn_truncate; the scan is then not converged
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.GGJDispersion — Type
GGJDispersion(mc::MultiSurfaceCouplingFull)

The full-matching determinant on the scan plane, g(Q) = mc(−i·Q·Q₀), where Q₀ = S^(−1/3)/τ_A of the reference surface mc.surfaces[mc.ref_idx]. Every surface must use a ToroidalLayerModel; GGJ names the determinant's origin, not a restriction on the model.

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.GrowthRateResult — Type
GrowthRateResult

Output of find_growth_rates.

Fields

  • Q_root - selected (highest-γ surviving) root, normalized; NaN when :no_root
  • omega, gamma - Re(Q_root)/tauk and Im(Q_root)/tauk in physical units; 0 when :no_root
  • Q_root_secondary - next root down, set when warning_flags is non-empty; else NaN + NaN*im
  • omega_secondary, gamma_secondary - physical ω and γ of the secondary root, 0 if none
  • warning_flags - :geom/:gap (root kept with a caveat), :spurious (a candidate was filtered), :winding_unresolved, or :no_root (no usable root; check it to tell a failed extraction from γ ≈ 0); empty if clean
  • valid_roots - intersections classified as roots (:threshold: also those the above-pole filter rejected)
  • poles - intersections classified as poles
  • filtered_roots - rejected candidates: validity-gate and above-pole/outside-Re rejections (:threshold), or zero and unresolved winding counts (:winding)
  • re_contours, im_contours - Re(Δ)=re_target and Im(Δ)=im_target polylines
  • pole_threshold - pole threshold used (:threshold mode only)
  • classification - :threshold or :winding
  • valid_roots_winding, poles_winding, filtered_roots_winding - winding number of each entry of valid_roots, poles and filtered_roots (NaN where unresolved); empty in :threshold mode
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.MultiBoxAMRResult — Type
MultiBoxAMRResult

Output of multi_box_amr_scan. Per-box AMRResults plus the aggregated cells/Q/Δ across all active boxes. Pre-screen-inactive boxes have nothing for their AMRResult and contribute nothing to the aggregated arrays.

fieldmeaning
box_resultsper-box AMRResult, or nothing if box was skipped
box_activityper-box BoxActivity enum
cellsconcatenated AMRCells from all active boxes
Qunion of all unique Q evaluations (active + skipped)
Δcorresponding Δ values
prescreen_evalstotal f(Q) evaluations spent on pre-screening

The aggregated (cells, Q, Δ) are suitable for direct consumption by find_growth_rates. Pre-screen evaluations are still included in Q/Δ even for skipped boxes, so any downstream pole-magnitude diagnostic that uses the flat residual list sees the full sample.

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.MultiSurfaceCoupling — Type
MultiSurfaceCoupling{V<:AbstractVector{<:SurfaceCoupling}}

Multi-surface dispersion data: a vector of SurfaceCoupling, the full Δ' matrix, the index of the reference surface (whose tauk defines the Q normalization), and the truncation msing_max (number of surfaces actually participating in the determinant). Calling mc(Q) returns det(M(Q)) where

M[k,k] = dp_matrix[k,k] - scale_k · Δ_inner_k(Q · ratio_k + q_shift_k) - dc_k
M[i,j] = dp_matrix[i,j]      for i ≠ j        (off-diagonal Δ' couplings)

A root of mc in the complex Q plane is a coupled tearing eigenvalue.

ratio_k = tauk_k/tauk_ref: Q is defined as tauk·ω, so one shared physical ω reaches surface k as Q_k = tauk_k·ω, on the same scaling as its Q_e/Q_i.

q_shift_k is the E×B Doppler offset carried on each SurfaceCoupling (zero by default), applied in the layer's own frequency variable (see SurfaceCoupling).

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.MultiSurfaceCouplingFull — Type
MultiSurfaceCouplingFull{V<:AbstractVector{<:SurfaceCoupling}}

Full 4m × 4m tearing+interchange Pletzer-Dewar dispersion matrix (Wang et al. 2020, Phys. Plasmas 27, 122503).

Calling mc(Q) assembles the matching matrix from the raw outer-region matrix and the per-surface inner layers and returns its determinant. For pure-tearing (pressureless SLAYER) studies use the reduced m × m MultiSurfaceCoupling.

Fields

  • surfaces::V — per-surface SurfaceCoupling.
  • dp_raw::Matrix{ComplexF64} — 2m × 2m outer-region matrix, side-major [L_s1, R_s1, L_s2, R_s2, …].
  • ref_idx::Int — reference surface for Q rescaling (1-based).
  • msing_max::Int — number of leading surfaces included.
  • inner_kwargs::K — kwargs forwarded to solve_inner, e.g. (pfac=0.1, nx=128, nq=5).
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.ScanResult — Type
ScanResult

Output of a brute-force or AMR Q-plane scan.

fieldmeaning
QComplex Q values (Matrix for grid, Vector for AMR)
ΔResidual values, same shape as Q
re_axisReal-axis grid (only for regular-grid ScanResult)
im_axisImaginary-axis grid (only for regular-grid ScanResult)
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.SurfaceCoupling — Type
SurfaceCoupling{M<:InnerLayerModel, P}

Per-surface dispersion data: (model, params, dp_diag, dc, scale, tauk, q_shift). Calling sc(Q) returns the complex residual

r(Q) = dp_diag - scale * layer_response(model, params, Q + q_shift).tearing - dc

q_shift is the surface's E×B Doppler shift, a real frequency offset in the layer's own frequency variable, zero by default. SLAYER's argument is the normalized Q, so the shift is added to Q; a toroidal layer's argument is the growth rate s = γ − iω, so the layer frequency ω − qshift enters as `s + i·qshift`. The SLAYER and coupled toroidal-layer Tearing runs set it.

A root of sc in the complex Q plane is an uncoupled tearing eigenvalue at this surface (tearing channel only); coupled eigenvalues, including the interchange channel, come from MultiSurfaceCoupling.

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.amr_scan — Method
amr_scan(f, Q_re_range, Q_im_range;
          nre0, nim0, passes,
          max_cells=10_000_000,
          max_cells_action=:error,
          snapshot_callback=nothing,
          parallel=Threads.nthreads() > 1) -> AMRResult

Adaptively refine a Q-plane scan of the residual f(Q). Starting from an nre0 × nim0 grid of cells over Q_re_range × Q_im_range, each of passes passes splits every cell whose corner residuals straddle zero in Re(Δ) or Im(Δ) into 4 quadrants. Evaluations are cached, so shared corners cost one evaluation. The AMRResult holds the final cells and every unique Q/Δ evaluation.

Keyword arguments

  • nre0, nim0 – initial grid cell counts along each axis
  • passes – number of refinement passes
  • max_cells – cap on total cells
  • max_cells_action – on hitting the cap, :error throws and :warn_truncate warns and returns the partial result with truncated = true
  • snapshot_callback – if set, called as (pass, cells, cache) after the initial grid (pass 0) and each pass; the arguments are live references, so copy them to keep them
  • parallel – evaluate f with Threads.@threads; f must be thread-safe. The result does not depend on the thread count.
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.brute_force_scan — Method
brute_force_scan(f, Q_re_range, Q_im_range; nre, nim,
                  threaded::Bool=true) -> ScanResult

Evaluate the Q-callable residual f on a regular nre × nim grid spanning the rectangle Q_re_range × Q_im_range in the complex Q plane. f must accept a single Complex argument and return a Complex value (typically a SurfaceCoupling or MultiSurfaceCoupling, but any callable works).

Use find_growth_rates(scan, tauk; ...) to extract growth-rate eigenvalues from the result.

Arguments

  • f – Q-callable residual (e.g. SurfaceCoupling, MultiSurfaceCoupling)
  • Q_re_range – (re_min, re_max) tuple
  • Q_im_range – (im_min, im_max) tuple

Keyword arguments

  • nre, nim – grid resolution along each axis
  • threaded – distribute Q evaluations across Threads.@threads
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.find_growth_rates — Method
find_growth_rates(scan::ScanResult, tauk::Real; re_target=0.0, im_target=0.0, pole_threshold=10.0,
                  filter_above_poles=true, filter_outside_re=true, gamma_gap_threshold=1e3, residual=nothing,
                  polish_maxit=20, validity_rtol=1e-3, polish=true, classification=:threshold,
                  winding_rfrac=0.5) -> GrowthRateResult

Extract tearing eigenvalues from a brute-force ScanResult by intersecting the Re(Δ) and Im(Δ) contours. tauk converts Q to physical units (SurfaceCoupling.tauk for one surface; mc.surfaces[mc.ref_idx].tauk for coupled scans).

Keyword arguments

  • re_target, im_target - contour levels (zero for root finding; nonzero probes iso-residual contours)
  • pole_threshold - an intersection is a pole when max(|Re(Δ)|) on the nearby Im=0 contour exceeds this
  • filter_above_poles - reject roots whose γ exceeds the highest pole's
  • filter_outside_re - restrict that rejection to roots whose +γ step along Im=0 leaves a closed Re=0 loop; an open Re=0 contour lets spurious roots through, which :geom/:gap then flag
  • gamma_gap_threshold - :gap warning when the top root is unstable and its γ exceeds the next by more than this, in 1/s
  • residual - optional callable f(Q); when given, each root is polished to a true zero of f within a neighbour-aware trust region, making it resolution- and thread-independent
  • polish_maxit - max polish iterations per root; a failed polish keeps the contour point
  • validity_rtol - with residual, keep a polished root only if |f| < validity_rtol · median(|Δ|); the rest go to filtered_roots with :spurious
  • polish - polish roots when residual is given
  • classification - :threshold (default) or :winding
  • winding_rfrac - :winding circle radius in units of the local contour-segment length, capped at 0.45 × the distance to the nearest other intersection

Root selection

Surviving roots are sorted by descending γ and the highest is taken. It is flagged :geom when the Re=0 contour is a downward-concave hill there and :gap per gamma_gap_threshold; flags warn but never discard, and any warning exposes the next root as Q_root_secondary.

Winding classification

With classification = :winding (requires residual), each intersection is classified by the counter-clockwise winding number of residual on a small circle around it: positive is a root, negative a pole, and zero or unresolved goes to filtered_roots. This needs residual single-valued and meromorphic inside the circle, and the sampled count is not certified (fast phase turns between samples can be missed). pole_threshold, validity_rtol, filter_above_poles and filter_outside_re have no effect in this mode. Each intersection costs 64 to a few thousand residual evaluations.

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.ggj_growth_rates — Method
ggj_growth_rates(mc::MultiSurfaceCouplingFull;
                 gamma_range, omega_range,
                 nre0=40, nim0=40, passes=4, max_cells=2_000_000,
                 polish=true, winding_rfrac=0.5,
                 parallel=Threads.nthreads() > 1) -> (GrowthRateResult, AMRResult)

Tearing growth rates of any ToroidalLayerModel inner layer matched through the full 4m × 4m determinant mc (one surface gives the uncoupled 2 × 2 block of its raw Δ'). With s = γ − iω, the box gamma_range × omega_range bounds γ in 1/s and ω in rad/s, and is scanned adaptively in the plane of GGJDispersion; each contour intersection is classified by winding number (see find_growth_rates). In the result gamma is γ, omega is ω, Q_root is (ω + iγ)/Q₀, and the reported root is the least stable zero in the box. Each surface's layer is evaluated in its own E×B frame, s_k = s + i·n·Ω_E,k, so with rotation omega_range must cover the lab-frame ω. Without drifts or rotation the roots come in ±ω pairs and either member may be reported.

gamma_range must lie at γ > 0: the GGJ layer has a branch cut on the negative real s-axis, and classification circles and polishing stay in γ > 0. A solver failure inside the layer (e.g. near Mercier marginality) is not caught and stops the scan.

nre0 × nim0 is the initial AMR grid and passes the refinement passes. Every evaluation solves the inner layer at every surface: the default grid is about 1,600 evaluations, and each contour intersection adds 64–4096 for classification plus about 120 for polishing. :no_root and :winding_unresolved results warn; gamma is then not a growth rate.

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.multi_box_amr_scan — Method
multi_box_amr_scan(f, boxes;
                   pole_magnitude_threshold,
                   prescreen_nre=25, prescreen_nim=25,
                   nre0=25, nim0=25, passes=4,
                   max_cells=10_000_000,
                   max_cells_action=:error,
                   parallel=Threads.nthreads() > 1) -> MultiBoxAMRResult

Run amr_scan over several Q-plane boxes, skipping boxes that a coarse pre-screen finds inactive. A box is active if any prescreen_nre × prescreen_nim pre-screen cell has a sign change of Re(Δ) or Im(Δ) across its corners, or a corner with |Δ| ≥ pole_magnitude_threshold. Active boxes get a full amr_scan; inactive ones get nothing.

Arguments

  • f: residual Q::ComplexF64 → Δ::ComplexF64; must be thread-safe if parallel=true.
  • boxes: vector of (Q_re_range, Q_im_range) tuples; boxes may overlap or share edges.
  • pole_magnitude_threshold: |Δ| activity threshold, e.g. the adaptive pole_threshold used in find_growth_rates.
  • nre0, nim0, passes, max_cells, max_cells_action, parallel: forwarded to each amr_scan.

Pass the result through as_amr_result for find_growth_rates.

Example

boxes = [((-75.0, -25.0), (-25.0, 25.0)),
    ((-25.0, 25.0), (-25.0, 25.0)),
    ((25.0, 75.0), (-25.0, 25.0))]
result = multi_box_amr_scan(f_residual, boxes;
    pole_magnitude_threshold=1e-3,
    prescreen_nre=25, prescreen_nim=25,
    nre0=25, nim0=25, passes=4)
roots = find_growth_rates(as_amr_result(result), tauk; pole_threshold=1e-3)
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.multi_surface_coupling — Method
multi_surface_coupling(surfaces, dp_matrix;
                        ref_idx=1,
                        msing_max=min(3, length(surfaces)))
    -> MultiSurfaceCoupling

Construct a multi-surface coupling from a vector of SurfaceCoupling and the full outer-region Δ' matrix. dp_matrix must be square with side length length(surfaces) (it is the same matrix returned by PerturbedEquilibrium.SingularCoupling's Δ' boundary-value problem).

Keyword arguments

  • ref_idx – reference surface whose tauk defines the Q normalization.
  • msing_max – number of leading surfaces in the determinant; off-diagonal Δ' couplings beyond the third surface tend to be erratic, hence the default of at most 3.
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.multi_surface_coupling_full — Method
multi_surface_coupling_full(surfaces, dp_raw;
                            ref_idx=1,
                            msing_max=length(surfaces),
                            inner_kwargs=NamedTuple()) -> MultiSurfaceCouplingFull

Construct the 4m × 4m dispersion matrix driver. dp_raw must be the 2m × 2m matrix in side-major ordering (the DeltaPrimeData.raw field of a Riccati solve). Surface k's inner layer is evaluated at Q·ratio_k Doppler-shifted by its E×B offset q_shift_k, exactly as in the reduced multi_surface_coupling: added to Q for a SLAYER surface, and as i·q_shift_k to the growth rate s for a GGJ surface (see SurfaceCoupling).

Keyword arguments

  • ref_idx — reference surface whose tauk defines the Q normalization.
  • msing_max — truncate to the leading msing_max surfaces (and the matching block of dp_raw).
  • inner_kwargs — NamedTuple forwarded to solve_inner at every evaluation, e.g. (pfac=0.1, nx=128).
source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.surface_coupling — Method
surface_coupling(model::InnerLayerModel, params, dp_diag::Number;
                 dc::Real=0.0, scale::Real=1.0, tauk::Real=1.0,
                 q_shift::Real=0.0) -> SurfaceCoupling

Generic fallback constructor. Use this when wiring a new inner-layer model into the dispersion solver — pass the appropriate inner→outer-units scale and per-surface tauk explicitly.

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.surface_coupling — Method
surface_coupling(model::ToroidalLayerModel, params::ToroidalLayerParameters,
                 dp_diag::Number; omega_E::Real=0.0, n::Integer=0) -> SurfaceCoupling

Toroidal-layer (GGJ, CCC) convenience constructor. scale = 1 (GGJ's rescale_delta already returns Δ in outer units) and tauk = 1.

omega_E is the surface's E×B rotation per unit toroidal mode number, in rad/s, and n the toroidal mode number (required when omega_E is nonzero). GGJ is a plasma-frame layer (Johnson & Greene 1967, Plasma Phys. 9, 611, Appendix B), so with s = γ − iω a rotating surface sees the Doppler-shifted growth rate s + i·n·omega_E, the frequency ω − n·omegaE, and `qshift = n·omega_E`.

There is no dc keyword: the GGJ residual already includes the interchange channel, so a Δ_crit offset would double-count it; dc is 0.

source
GeneralizedPerturbedEquilibrium.Tearing.Dispersion.surface_coupling — Method
surface_coupling(model::SLAYERModel, params::SLAYERParameters,
                 dp_diag::Number; dc::Real=0.0, q_shift::Real=0.0)
    -> SurfaceCoupling

SLAYER convenience constructor. Sets scale = params.lu^(1/3) (S^(1/3), mapping the normalized inner-layer Δ to the rs-referenced outer convention) and tauk = params.tauk. `dpdiagmust already be r_s-referenced (seedeltaprimetorsreference`).

source

CriticalResonantField

GeneralizedPerturbedEquilibrium.Tearing.CriticalResonantField.TorqueBalance — Type
TorqueBalance{M<:InnerLayerModel,T}

Torque-balance inputs at one rational surface.

Fields

  • model – inner-layer model whose layer_response gives Δ
  • params – that model's layer parameters at the surface; must carry Q_e, Q_i, m, n
  • Q0 – normalized natural E×B rotation of the m/n mode, τk·n·ωE
  • prandtl – magnetic Prandtl number τR/τV (the layer's P_φ)
  • lu – Lundquist number S
  • kappa_hat – Cole's slab-to-tokamak factor κ̂ (Eq. 61)
  • alpha – outer stability α = S^(-1/3)·(−rs Δ's) (Eq. 61), positive on a tearing-stable surface
source
GeneralizedPerturbedEquilibrium.Tearing.CriticalResonantField.torque_balance_scan — Method
torque_balance_scan(tb::TorqueBalance; Qmin=nothing, Qmax=nothing, n=2000)
    -> (Qs, bal, Qpeak, br_crit, idx_peak, Δs)

Sample torque_balance_value on n uniform real Q points and return the critical normalized field br_crit = b_r/B_φ (Cole Eq. 62) at the first resolved saddle-node bifurcation on the path from Q0 along fold_search_range. Both the rise to and fall from an interior maximum must exceed TORQUE_BALANCE_FOLD_DROP times its value within a contiguous retained interval. Above this threshold the shielded branch followed from Q0 no longer exists as the field grows. Points where |Δ| ≤ α, the unshielded zone next to Qe, are not on the path. With no resolved saddle-node bifurcation there is no discrete threshold. Qmin/Qmax override the sampled range, but the search stays between Q0 and the end of `foldsearchrange. Returns NaN forQpeak,brcritand 0 foridxpeak, with a warning, when no saddle-node bifurcation is resolved, whenQ0` is not finite, when the surface is tearing-unstable (α ≤ 0), or when the diamagnetic ordering Qi ≤ 0 ≤ Q_e does not hold.

source