Kinetic Forces

KineticForces computes the neoclassical toroidal viscosity (NTV) of a perturbed equilibrium: the toroidal torque and the kinetic energy that a non-axisymmetric field exerts on the plasma through the drift-kinetic response of its particles. It implements the PENTRC formulation of Park et al. (2009), Logan et al. (2013) and Park and Logan (2017).

What it computes

A non-axisymmetric perturbation $\delta B$ breaks the toroidal symmetry that conserves the canonical angular momentum of each particle. The resulting non-ambipolar radial transport, dominated by trapped particles whose bounce and precession motion resonates with the E×B rotation, carries toroidal momentum out of the plasma: the NTV torque $T_\phi$, which brakes or spins up the rotation, together with a kinetic contribution $\delta W_k$ to the perturbed energy that stabilizes or destabilizes the response. Both are halves of one complex quantity, $T = T_\phi + 2in\,\delta W_k$, and the module integrates it over the plasma for one or more torque methods.

The torque enters the pipeline in two ways:

WorkflowDeckWhat it gives
Torque of a perturbed equilibrium[KineticForces] after [PerturbedEquilibrium]$T(\psi)$ integrated over the stored response; the stage of the Workflow
Self-consistent kinetic solve[ForceFreeStates] kinetic = "KineticForces"the drift-kinetic energy matrices replace the ideal ones inside the stability solve, so the response itself carries the torque (see Stability and TorqueResponse/ on the Perturbed Equilibrium page)

Both need the kinetic profiles of [Equilibrium] kinetic_file (ne, Ti, Te, ωE, and ni when it differs from ne) and the ion composition of [[Equilibrium.ion_species]]; the file schema is on the Equilibrium page.

Governing equations

The torque is a sum over species of three nested integrals, over flux $\psi$, over the pitch variable $\Lambda$ separating trapped from passing particles and over the normalized energy $x = \varepsilon/T$, with a sum over the bounce harmonics $\ell$ up to bounce_harmonic_max. The integrand is the bounce-averaged perturbation of the field strength $\langle \delta B_\parallel / B \rangle_\ell$, evaluated from the displacement $\xi$ of the perturbed equilibrium, weighted by the Maxwellian and by the resonance factor $1/(i\Omega(x) - \nu)$: the energy integral is Eq. 8 of Logan et al. (2013) and the torque and its normalization Eq. 19, $\operatorname{Im} T = 2n\,\delta W_k$. The resonance frequency $\Omega(x)$, and the diamagnetic frequencies that relate the E×B rotation $\omega_E$ of the kinetic file to the toroidal rotation, are given with their sign conventions under KineticForces rotation conventions. The collision operator is selected by nutype: "harmonic" (the default), "krook", "small" or "zero" (the collisionless limit), with the collision frequencies computed from the density and temperature profiles; f0type selects the equilibrium distribution, "maxwellian" (the default), "park" or "cgl". The kinetic file may also supply the Coulomb logarithm and collision rates lnLambda, nu_i and nu_e, which then replace the collision model of the NTV calculation (Logan et al. (2013), Eq. 6) that otherwise computes them from $n$ and $T$. Each is optional and must be positive; they are interpolated, and extended past the table's ψ range, in log space, so supply them over the whole range. A supplied nu_i is the first main ion's rate, and the other ions and the impurity keep the model's $(Z_s/Z_1)^2\sqrt{m_1/m_s}$ ratio to it. They feed only the NTV calculation (the tearing layers' resistivity keeps its lnLambda_form closure), the density and temperature scaling factors do not rescale them, and collisionality_factor still multiplies them.

Torque methods

Each method is one evaluation of the same integral under a different model, switched on by its <method>_flag in [KineticForces]; the first letter selects the particle population, f full, t trapped only, p passing only.

MethodModel
fgar (default), tgar, pgargeneral-aspect-ratio calculation of the torque and energy
fcglfluid Chew–Goldberger–Low limit
fwmm, twmm, pwmmenergy from the Euler–Lagrange kinetic matrix
ftmm, ttmm, ptmmtorque from the Euler–Lagrange kinetic matrix
fkmm, tkmm, pkmmnorm of the kinetic energy matrix
frmm, trmm, prmmnorm of the kinetic torque matrix

Running it

From examples/DIIID-like_ideal_example/gpec.toml, after the [PerturbedEquilibrium] section (examples/TJ_kinetic_NTV_example is the same stage on an analytic equilibrium):

[KineticForces]
bounce_harmonic_max = 6          # bounce harmonics summed over ℓ = -max:max
electron = false                 # add the electron NTV to the ion species
nutype = "harmonic"              # collision operator: "zero", "small", "krook", "harmonic"
f0type = "maxwellian"            # distribution function: "maxwellian", "park", "cgl"
atol_pitch = 1e-9                # absolute tolerance of the pitch integration
axis_validity_suppression = true # suppress the near-axis terms where the model is not valid

In a script the stage is one call on the perturbed equilibrium:

using GeneralizedPerturbedEquilibrium

kinetic = kinetic_torque(pe, KineticForcesControl(; bounce_harmonic_max=6, nutype="harmonic"))

The torque is three nested adaptive Gauss–Kronrod integrals, and each inner tolerance is derived from the outer one unless set: rtol_psi (1e-2, the primary knob; two significant figures match the model's validity), rtol_pitch (psi_tolerance_margin × rtol_psi) and rtol_x (nested_tolerance_margin × rtol_pitch). Tightening rtol_psi tightens the whole ladder; tightening an inner level alone only multiplies evaluations. The kinetic matrix build of a kinetic = "KineticForces" solve has no ψ quadrature and uses rtol_pitch (1e-3 when unset).

Profile scaling

Seven factors on KineticForcesControl scale the kinetic inputs for sensitivity studies. density_factor, temperature_factor, ExB_rotation_factor and toroidal_rotation_factor act on the profiles before any physics evaluation: the diamagnetic frequencies are formed from the unscaled profiles, $\omega_E$ is rebuilt from the scaled total rotation $\omega_\phi$ minus the scaled diamagnetic terms and then multiplied by ExB_rotation_factor, and the collision frequencies are recomputed from the scaled density and temperature. magnetic_drift_factor, collisionality_factor and divxi_factor multiply the magnetic drift, the collisionality and $\nabla\cdot\xi_\perp$ at evaluation time; use collisionality_factor to scale the collisionality alone. The four profile factors are not supported together with a multi-ion ion_species list; the three evaluation-time factors are.

Multi-ion runs

With several main-ion species the NTV is computed per species under one shared $Z_\mathrm{eff}$ and summed over the main ions, the quasineutrality-closing impurity and, with electron = true, the electrons (electron always means in addition to the ions). The sum is written to KineticForces/<method>/ as in a single-ion run and each species to KineticForces/PerSpecies/<label>/<method>/, with labels ion_z<z>_m<m>, impurity_z<z>_m<m> and electron; the summed total_torque is the exact quadrature value, the summed profiles a linear interpolation onto the union grid.

Regularization

[PerturbedEquilibrium] regularization_width multiplies $\xi^{\psi\prime}$ and $\xi^\alpha$ by $Q^2/(Q^2 + w^2)$ with $Q = m - nq$ before they drive the NTV integrand. It exists because the ideal response diverges as $1/Q$ at every rational surface, so the torque integral of an ideal solve does not converge; the self-consistent kinetic solve has no such singularity, since the finite torque moves the zeros of the kinetic coefficient off the real $\psi$ axis (Park and Logan (2017)). The default is 0; set it, typically to 0.05, only for the torque of an ideal solve, and leave it at 0 for a kinetic run, where it would suppress a finite physical response.

Outputs

DatasetMeaningUnits
KineticForces/<method>/total_torquethe NTV torque $T_\phi$ on the plasmaN·m
KineticForces/<method>/total_energythe kinetic energy $\delta W_k = \operatorname{Im}(T)/(2n)$J
KineticForces/<method>/n, psi_nstepsthe toroidal mode number and the ψ quadrature count
KineticForces/<method>/dTdpsi, Tthe complex torque density and its cumulative integral in ψ, $T = T_\phi + 2in\,\delta W_k$N·m
KineticForces/<method>/dTdpsi_ellthe torque density resolved by bounce harmonic on the ell scaleN·m
KineticForces/<method>/KineticMatrices/the kinetic energy and torque matrices of the matrix methods
KineticForces/PerSpecies/<label>/<method>/the same layout per species in a multi-ion run

The TorqueResponse/ matrices of a kinetic forward solve, which refer the torque back to the applied field, are described on the Perturbed Equilibrium page.

API reference

GeneralizedPerturbedEquilibrium.KineticForces.METHOD_REGISTRY — Constant
METHOD_REGISTRY

Single source of truth for the NTV calculation methods. Each entry is a NamedTuple (name, flag, kind, doc):

  • name — short method identifier used as the HDF5 group key and in intr.method
  • flag — the KineticForcesControl field symbol that enables the method
  • kind — dispatch routing tag consumed by method_kind / Torque.jl (:gar for the GAR/matrix family, :fcgl for the fluid CGL method)
  • doc — one-line description printed in verbose output

To add a method: append an entry here and add the matching *_flag field to KineticForcesControl.

source
GeneralizedPerturbedEquilibrium.KineticForces.BounceData — Type
BounceData

Bounce-averaged quantities as functions of pitch angle λ, produced by bounce_harmonic and consumed by the pitch integration.

Fields

  • nlmda, lambda: number of pitch-angle points and the λ grid
  • sigma: 0 trapped, 1 passing, per λ
  • wb, wd: bounce frequency ωb(λ) and precession drift ωd(λ), in rad/s
  • dJdJ: ωb|δJ|²/ro² per λ (real; scalar torque path)
  • wmats_vs_lambda: packed W outer products, (nlmda, nqty_matrix(mpert)), in the 3-Hermitian-triangle + 3-full-block layout of nqty_matrix (Logan 2015 Eqs 7.30–7.35); nothing on the scalar path
source
GeneralizedPerturbedEquilibrium.KineticForces.BounceGeometry — Type
BounceGeometry

The bounce-harmonic-independent part of the bounce averaging at one (ψ, n): per λ, the orbit's θ sub-grid samples that every ℓ reuses. Produced by compute_bounce_geometry, consumed by bounce_harmonic, which adds the ℓ-dependent phase and reduces to a BounceData.

Fields

  • nlmda, lambda, sigma: the λ grid, as in BounceData
  • wb, wd: bounce and precession frequencies, in rad/s
  • wbbar::Vector{Float64}: normalized bounce frequency per λ (wb = wbbar·bhat)
  • total_wb::Vector{Float64}: full bounce-action integral per λ, the phase normalization
  • fsi_wb::Matrix{Float64}: ntheta × nlmda cumulative bounce action along the orbit
  • jvtheta::Matrix{ComplexF64}: ntheta × nlmda action integrand samples
  • wmu_mt, wen_mt: mpert × ntheta × nlmda Wμ, WE samples (matrix path, else nothing)
  • valid::Vector{Bool}: false where the bounce integral degenerated; every output of that λ is zero
source
GeneralizedPerturbedEquilibrium.KineticForces.BounceScratch — Type
BounceScratch(ntheta, mpert)

Per-surface scratch for the bounce-averaging inner loops, allocated once per surface in compute_bounce_geometry and bounce_harmonic and reused across every λ. Sizes are fixed for a flux surface (ntheta sub-grid points, mpert Fourier modes). Buffers the loops populate only partially are fill!-reset per λ.

Fields

  • g_wb::Vector{Float64}: length ntheta — bounce-action integrand samples
  • g_wd::Vector{Float64}: length ntheta — drift integrand samples
  • cum_wb_arr::Vector{Float64}: length ntheta — cumulative bounce-action integral
  • jvtheta::Vector{ComplexF64}: length ntheta — action integrand
  • bj_samples::Vector{ComplexF64}: length ntheta — action bounce-integral samples
  • wsamp::Vector{ComplexF64}: length ntheta — per-mode W bounce-integral samples
  • wmu_mt::Matrix{ComplexF64}: mpert × ntheta — W_μ per θ
  • wen_mt::Matrix{ComplexF64}: mpert × ntheta — W_E per θ
  • expm::Vector{ComplexF64}: length mpert — Fourier basis at a θ
  • pl::Vector{ComplexF64}: length ntheta — bounce phase factor
  • wmu_ba::Vector{ComplexF64}: length mpert — bounce-averaged W_μ
  • wen_ba::Vector{ComplexF64}: length mpert — bounce-averaged W_E
  • wmats_lmda::Vector{ComplexF64}: length nqty_matrix(mpert) — packed W outer products
  • tspl_f::Vector{Float64}: length 5 — in-place tspl(θ) evaluation
  • int_w::Vector{Float64}, cumint_W::Matrix{Float64}: precomputed exact-cubic quadrature weights on the fixed unit θ-grid (∫ = int_w·y, cumulative = cumint_W·y); shared read-only across surfaces, see _quadrature_weights
source
GeneralizedPerturbedEquilibrium.KineticForces.KineticForcesControl — Type
KineticForcesControl

User-facing control parameters from the TOML [KineticForces] section. Configures which NTV methods to run, whether electrons join the species sum, and tolerances. The species composition comes from the equilibrium's kinetic data (equil.kinetic).

Constructed via keyword arguments or from a TOML dict:

ctrl = KineticForcesControl(; (Symbol(k) => v for (k, v) in inputs["KineticForces"])...)

Immutable: vary a field by building a new control.

Fields

  • axis_validity_suppression::Bool - Suppress the calculated kinetic terms below ψc, where the zero-orbit-width ordering fails (a thermal orbit width of the widest-orbit species reaches ⟨r⟩; moved clear of rational surfaces), rising to full strength at 2ψc through a C² envelope. No tuning parameters. Default true.
  • Quadrature tolerances form a ladder, outermost in: rtol_psi (default 1e-2) ⊃ rtol_pitch (default psi_tolerance_margin × rtol_psi = 1e-3) ⊃ rtol_x (default nested_tolerance_margin × rtol_pitch = 1e-5). Each inner level is resolved one margin tighter than the outer and no further. Set rtol_pitch/rtol_x explicitly to override (see torque_pitch_rtol, matrix_pitch_rtol).
source
GeneralizedPerturbedEquilibrium.KineticForces.KineticForcesInternal — Type
KineticForcesInternal

Internal working state for KineticForces calculations: equilibrium-derived scalars, mode indexing, and perturbation and geometric-matrix interpolants. Equilibrium and kinetic profiles are read from the PlasmaEquilibrium and KineticProfileSplines, not copied here.

Fields

  • ro, bo, chi1: Equilibrium geometry parameters
  • mthsurf, mfac: Poloidal grid info
  • dbob_m, divx_m: Perturbation mode interpolants
  • sing_psis: Sorted rational-surface ψ locations, used as panel boundaries of the outer ψ torque quadrature so resonant peaks fall on interval endpoints
source
GeneralizedPerturbedEquilibrium.KineticForces.KineticForcesResult — Type
KineticForcesResult

The kinetic torque of a perturbed equilibrium, from kinetic_torque.

Fields

  • total::KineticForcesState - The torque by method, summed over species.
  • species::Vector{Pair{String,KineticForcesState}} - Each species' contribution by label; empty for a single-ion run.
  • axis_psi_c::Float64 - The near-axis validity boundary the ψ quadrature used.
  • pe::PerturbedEquilibrium.PerturbedEquilibriumState - The perturbed equilibrium the torque was evaluated on.
  • control::KineticForcesControl - The kinetic model settings.
source
GeneralizedPerturbedEquilibrium.KineticForces.SurfaceBField — Type
SurfaceBField

The periodic cubic B(θ) of one flux surface, decomposed once and reused for every λ. Holds the per-cell polynomial coefficients, B at every knot, and the stationary points of B. Consecutive stationary points bound intervals on which B is monotone, so each holds at most one bounce point; within such an interval the cached knot values locate the cell by bisection and the cell's cubic is then solved in closed form.

Fields

  • knot::Vector{Float64}: cell boundaries, ascending, knot[1] = 0, knot[end] = 1
  • bknot::Vector{Float64}: B at each knot
  • poly::Vector{NTuple{4,Float64}}: per-cell (d, c, b, a) of S(u) = d + cu + bu² + au³, in the cell-local coordinate u = θ − knot[i]
  • theta::Vector{Float64}: stationary points of B, ascending, in [0,1)
  • bval::Vector{Float64}: B at each stationary point
source
GeneralizedPerturbedEquilibrium.KineticForces._bounce_harmonic_tail — Method
_bounce_harmonic_tail(fsi_wb, jvtheta, wmu_mt, wen_mt, total_wb, wbbar, lnq, sigma, ro,
                      do_matrices, mpert, smat, tmat, xmat, ymat, zmat, scr) → (dJdJ, wmats_lmda)

The bounce-harmonic-dependent end of the bounce integral for one λ: the phase factor exp(−2πi·lnq·fsi_wb/((2−σ)·total_wb)), the action bounce integral |δJ|² and, on the matrix path, the bounce-averaged W vectors and their packed outer products.

source
GeneralizedPerturbedEquilibrium.KineticForces._bounce_points_at_lambda! — Method

Bounce points of v_par(θ) = 1 − (λ/bo)·B(θ) for a trapped particle. B = bo/λ at a bounce point, so a monotone interval between stationary points of B contains one iff bo/λ lies strictly between its endpoint B values; the crossing is then solved from the cell's cubic, with hints carrying each interval's cell over from the previous λ.

Returns roots sorted ascending, as Fortran spline_roots, so the deepest-well search pairs neighbouring roots; fewer than two roots signals a degenerate λ and sends the caller to the fallback. hints is sized length(bf.theta) + 1, the extra slot being the far half of the interval that wraps through the seam.

source
GeneralizedPerturbedEquilibrium.KineticForces._bounce_samples! — Method
_bounce_samples!(fsi_wb, jvtheta, wmu_mt, wen_mt, tdt_pts, tdt_wts, lmda, n, q, bo, tspl, B_vpar,
                 chi1, mfac, dbob_m_f, divx_m_f, divxfac, do_matrices, mpert, scr) → (total_wb, total_wd)

Sample the bounce integrands of one orbit on its θ sub-grid and integrate them: writes the cumulative bounce action into fsi_wb, the action integrand into jvtheta and, on the matrix path, the Wμ/WE samples into wmu_mt/wen_mt; returns the total bounce-action and drift integrals. Nothing here depends on the bounce harmonic.

source
GeneralizedPerturbedEquilibrium.KineticForces._cell_level_root — Method

Solve B(θ) = btarget inside cell ic, restricted to θ ∈ [θlo, θhi]. The cubic is solved in closed form and polished with one Newton step, which recovers the digits the closed form loses when two of its roots are nearly coincident. Returns NaN if no root lies in the restricted range.

source
GeneralizedPerturbedEquilibrium.KineticForces._cell_position — Method

Where btarget sits relative to cell ic of a monotone span: -1 before it, 0 inside, +1 past it. s carries the span's direction so one comparison serves both. The span's first and last cells are entered part-way, at the stationary points bounding it, so their outer edge value comes from ba/bb rather than from a knot.

source
GeneralizedPerturbedEquilibrium.KineticForces._energy_collision_frequency — Method
_energy_collision_frequency(x::Float64, p::EnergyParams) → Float64

Collision frequency ν(x) at normalized energy x = E/T.

  • "zero": collisionless (ν = 0)
  • "small": 1e-5 * |we|, a positive Krook width for either rotation direction
  • "krook": unmodified Krook operator
  • "harmonic": (1 + (l/2)²) * krook * x^(-3/2)
source
GeneralizedPerturbedEquilibrium.KineticForces._energy_integrand_real — Method
_energy_integrand_real(x::Float64, p::EnergyParams) → ComplexF64

Physical energy integrand in x-space, N(x)·exp(-x)/denom(x), evaluated on the real axis. Used both by the production integral (integrate_energy via _integrate_energy_resonant) and for diagnostics (evaluate_energy_integrand).

source
GeneralizedPerturbedEquilibrium.KineticForces._energy_numerator — Method
_energy_numerator(x::Float64, p::EnergyParams) → ComplexF64

Numerator N(x) of the energy integrand, without the resonance denominator and without the Maxwellian weight exp(-x). The physical x-space integrand is N(x)·exp(-x)/denom(x); the residue at a pole uses N(xres)·exp(-xres).

For CGL there is no resonance denominator: N_cgl = x^2.5 / (i·n).

source
GeneralizedPerturbedEquilibrium.KineticForces._integrate_energy_resonant — Function
_integrate_energy_resonant(p, leff, wb, n, we, wd, atol, rtol, segbuf=nothing) → ComplexF64

Energy integral over real x ∈ [0, X_ENERGY_MAX], as in Fortran PENTRC (energy.f90). Each resonance pole x_pole = x_res − i·ν/Ω′ is removed by principal value + residue (Sokhotski-Plemelj) and the smooth remainder is integrated in u = √x. The collisionless case is the exact ν→0⁺ limit: the signed zero of −pole_offset carries its causal branch and the analytic regular-part limit its on-axis 0/0. Poles narrower than NARROW_POLE_FRACTION of their position get extra breakpoints at ±2 and ±10 widths.

source
GeneralizedPerturbedEquilibrium.KineticForces._locate_cell — Method

Cell holding the B = btarget crossing on a monotone span running from cell ia to cell ib. λ ascends, so resuming from the previous λ's cell (hint) usually costs a step or two; bisection is the fallback when the hint is more than HINT_STEP_BUDGET cells off.

source
GeneralizedPerturbedEquilibrium.KineticForces._pitch_gar_kernel_quadgk_wt! — Method
_pitch_gar_kernel_quadgk_wt!(out::Vector{ComplexF64}, lambda, p::PitchGARParams)

Dual-output pitch kernel. Fills a length-2*nqty buffer: out[1:nqty] — fwmm half: fvals * complex(0, imag(xint)) out[nqty+1:2*nqty] — ftmm half: fvals * complex(real(xint), 0)

One energy integration per λ; both halves share it.

source
GeneralizedPerturbedEquilibrium.KineticForces._quadgk_breaks — Method
_quadgk_breaks(f, pts, atol, rtol, segbuf) → (I, E)

quadgk(f, pts...) for a runtime-length sorted breakpoint vector of 2 to MAX_ENERGY_BREAKS points, dispatched on the length so each call is a constant-arity splat (a Vector splat is type-unstable in the hot loop).

source
GeneralizedPerturbedEquilibrium.KineticForces._quadrature_weights — Method
_quadrature_weights(ntheta) → (int_w, cumint_W)

Exact integral of the CubicFit-endpoint spline on the fixed grid range(0,1,ntheta) is a constant linear functional of the node samples, so ∫ = int_w·y and the cumulative integral is cumint_W·y. The weights are obtained once per ntheta by evaluating the public integrate / cumulative_integrate! on the unit basis vectors — bit-faithful to fitting and integrating each sample vector directly, but reducing the per-λ hot loop to a dot/mul!. Cached (build guarded by a lock); the returned arrays are read-only.

source
GeneralizedPerturbedEquilibrium.KineticForces._real_cubic_roots — Method

Real roots of a·u³ + b·u² + c·u + d = 0 as (count, r1, r2, r3), unused slots NaN. The count comes from a conditioned ratio test rather than the sign of the discriminant, which cancels to rounding noise when two roots nearly coincide; three real roots use the trigonometric form. A degenerate leading coefficient falls through to _quadratic_real_roots.

source
GeneralizedPerturbedEquilibrium.KineticForces._real_pole_regular_part — Method
_real_pole_regular_part(xr, p, leff, wb, n, wd) → ComplexF64

Laurent regular part (finite limit at x → x_res) of the pole-subtracted real-axis (ν=0) integrand N(x)·exp(-x)/(i·Ω(x)) − R/(x − x_res), with Ω(x) = leff·wb·√x + n·(we+wd·x) and R = N(x_res)·exp(-x_res)/(i·Ω′).

Writing h(x) = N(x)·exp(-x), the limit is [h′(x_res) − h(x_res)·Ω″/(2Ω′)] / (i·Ω′), with h′ = (N′ − N)·exp(-x), Ω′ = leff·wb/(2√x) + n·wd, Ω″ = −leff·wb/(4·x^{3/2}).

source
GeneralizedPerturbedEquilibrium.KineticForces._resonance_nodes_from_frequencies — Method
_resonance_nodes_from_frequencies(wbhat_f, welec_f, wdhat_f, grid; n, nl, xeval=2.5) → Vector{Float64}

Scan grid for the zeros of the resonance operator Ω_ℓ(x; ψ) = ℓ·ω_b(ψ)·√x + n·(ω_E(ψ) + ω_d(ψ)·x) at energy x = xeval, for every bounce harmonic ℓ ∈ −nl:nl, given per-ψ frequency callables. xeval defaults to 2.5, the peak of the Maxwellian-weighted drive x^2.5·e^−x. Roots from all harmonics are concatenated, not deduplicated.

source
GeneralizedPerturbedEquilibrium.KineticForces._setup_surface_state — Method
_setup_surface_state(psi, zi, mi, electron, equil, intr, kinetic_profiles) → NamedTuple

Per-surface setup shared by the torque and calculated-matrix paths: θ-grid sampling of B and the Jacobian, the periodic fits (tspl, B_vpar) and the decomposed field bf, bounce extrema, flux-function values and the diamagnetic/drift frequencies. Nothing here depends on the toroidal mode or the bounce harmonic, so one bundle serves every (n, ℓ) at a ψ. Reads intr only (own θ buffers and search hints), so surfaces of different ψ may be built concurrently.

source
GeneralizedPerturbedEquilibrium.KineticForces._surface_b_field — Method

Decompose the cubic B_vpar by walking its cells once, recording each cell's polynomial and endpoint value and solving the quadratic dS/dθ = 0 on each to get the exact stationary points. Uses only the public coeffs/CellPoly interface, so it holds for whatever θ grid the surface interpolant was built on.

source
GeneralizedPerturbedEquilibrium.KineticForces._torque_surface — Method
_torque_surface(psi, zi, mi, electron, method, equil, intr, kinetic_profiles;
                need_matrices=false, n=nothing, wdfac=1.0, divxfac=1.0) → NamedTuple

_setup_surface_state plus the perturbation modes and, when need_matrices, the geometric matrices at ψ: everything tpsi! needs before its method dispatch. With the toroidal mode n given, a GAR-family method also gets its harmonic-free bounce geometry (geometry), shared by every bounce harmonic of the surface; otherwise geometry is nothing. Reads intr only.

source
GeneralizedPerturbedEquilibrium.KineticForces.axis_validity_boundary — Function
axis_validity_boundary(kf_ctrl, species, kinetic_profiles, equil, rationals=Float64[]) → Float64

ψc for a run: the widest-orbit species' near-axis validity boundary, cleared of rationals by `clearrational_windows, or0.0` when suppression is disabled or no kinetic profiles were loaded. Falls back to the equilibrium's main ion when the resolved species set is unavailable.

source
GeneralizedPerturbedEquilibrium.KineticForces.bounce_harmonic — Method
bounce_harmonic(geometry::BounceGeometry, l, n, q, ro, mpert;
                smat=nothing, tmat=nothing, xmat=nothing, ymat=nothing, zmat=nothing) → BounceData

Apply bounce harmonic l to a BounceGeometry: per λ the phase factor with lnq = l + σ·n·q, the action bounce integral |δJ|², and (matrix path, when the geometric matrices are given and the geometry carries the W samples) the packed W outer products.

source
GeneralizedPerturbedEquilibrium.KineticForces.calculate_fcgl — Method
calculate_fcgl(psi, n, l, tspl, dbob_m_f, divx_m_f, divxfac, n_s, T_s,
               equil, intr)::ComplexF64

Fluid Chew–Goldberger–Low limit of the kinetic energy: the double-adiabatic δW built from ∇·ξ⊥ and κ·ξ⊥ = -(δB/B + ∇·ξ⊥) on the surface, returned as 2n·i·δW so Im carries the energy like the kinetic methods. Only the l = 0 harmonic is nonzero.

Based on: [Logan et al., Phys. Plasmas 2013]

source
GeneralizedPerturbedEquilibrium.KineticForces.calculate_gar — Method
calculate_gar(psi, n, l, q, epsr, wdian, wdiat, welec, nuk, bo, bmax,
              bmin, n_s, T_s, mass, chrg, tspl, dbob_m_f, divx_m_f,
              divxfac, wdfac, method, op_wmats; kwargs...)::ComplexF64

GAR (General Aspect Ratio) torque, with no aspect-ratio expansion: bounce averages over λ, then an adaptive pitch/energy integration and the Eq. 19 normalization of Logan et al. 2013. Variants FGAR/TGAR/PGAR (full/trapped/passing); the *tmm/*wmm/*kmm/*rmm methods also fill op_wmats with the six kinetic matrices (A, B, C, D, E, H).

Keyword Arguments

  • rex_override::Union{Nothing,Float64}: Override real-part multiplier for resonance operator. When both overrides are provided, bypasses method-string derivation.
  • imx_override::Union{Nothing,Float64}: Override imaginary-part multiplier. Use rex_override=1.0, imx_override=1.0 to get full complex result for simultaneous kwmat/ktmat extraction via compute_kinetic_matrices_at_psi!.

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

source
GeneralizedPerturbedEquilibrium.KineticForces.check_psi_quadrature_convergence — Method
check_psi_quadrature_convergence(total, quad_err, ctrl, method)

Warn when the ψ torque quadrature terminated without satisfying the requested tolerances (hit maxevals_psi), or when a nonzero user-set atol_psi dominated termination — the silent-garbage scenario for weak applied fields, since NTV scales as δB². Error when the torque or its error estimate is not finite, which the tolerance comparisons cannot catch.

source
GeneralizedPerturbedEquilibrium.KineticForces.clear_rational_windows — Method
clear_rational_windows(psi_c, rationals) → Float64

Move the near-axis validity boundary outward until no rational surface lies in the envelope's transition band [ψ_c - RATIONAL_RES_RADIUS, 2ψ_c]. A rational in the band has its near-singular kinetic increments multiplied by a steep near-zero envelope, which the matrix splines cannot represent and which propagates NaNs into the stability solve.

The move is capped at VALIDITY_CLEAR_MAX_FACTOR× the original ψc; past that the uncleared boundary is returned with a warning, and a run that then produces NaNs needs `axisvalidity_suppression = false` or a finer ψ grid.

source
GeneralizedPerturbedEquilibrium.KineticForces.combine_species_states — Method
combine_species_states(states) -> KineticForcesState

Sum per-species KineticForcesState results into a single total (τ = Σs τs). Per method the scalar total_torque/total_energy are summed exactly; dT/dψ is summed by linear interpolation onto the union of the species ψ grids and t_cumulative re-integrated by trapezoid, so its endpoint need not equal the summed total_torque. Per-species diagnostics (torque_profile, records, panel_psis, resonance_psis) are not aggregated and are left at their defaults.

source
GeneralizedPerturbedEquilibrium.KineticForces.compute_bounce_data — Method
compute_bounce_data(psi, n, l, q, bo, bmax, bmin, theta_bmax,
                    tspl, B_vpar, mfac, chi1, ro, dbob_m_f, divx_m_f,
                    divxfac, wdfac, mass, chrg, T_s, method;
                    nlmda=128, ntheta=128,
                    smat=nothing, tmat=nothing, xmat=nothing,
                    ymat=nothing, zmat=nothing) → BounceData

Compute bounce-averaged quantities as functions of pitch angle λ for bounce harmonic l: compute_bounce_geometry followed by bounce_harmonic. A caller looping over harmonics should build the geometry once and call bounce_harmonic per ℓ.

Arguments

  • psi: Normalized poloidal flux
  • n: Toroidal mode number
  • l: Bounce harmonic number
  • q: Safety factor at this ψ
  • bo: On-axis toroidal field [T]
  • bmax, bmin: Max/min of B(θ) at this ψ
  • theta_bmax: θ location of Bmax (nodal knot; the passing-transit start)
  • tspl: Periodic poloidal interpolant: tspl(θ) → [B, dB/dψ, dB/dθ, J, dJ/dψ]
  • B_vpar: Periodic cubic of B(θ) used for v_par and the bounce-point roots
  • mfac: Poloidal mode numbers mlow:mhigh
  • chi1: 2π·ψ₀ flux normalization
  • ro: Major radius [m]
  • dbob_m_f: δB/B Fourier modes at this ψ (ComplexF64 vector, length mpert)
  • divx_m_f: ∇·ξ⊥ Fourier modes at this ψ (ComplexF64 vector, length mpert)
  • divxfac, wdfac: Scaling factors
  • mass: Particle mass [kg]
  • chrg: Particle charge [C]
  • T_s: Species temperature at this ψ [J]
  • method: Method string (first char: f/t/p determines λ range)

Keyword Arguments

  • nlmda: Number of pitch angle grid points (default 128)
  • ntheta: Number of poloidal grid points per bounce (default 128)
  • smat, tmat, xmat, ymat, zmat: Geometric matrices (mpert×mpert) for kinetic matrix path
  • surface_field: Prebuilt _surface_b_field(B_vpar), shared across the harmonics of a surface
source
GeneralizedPerturbedEquilibrium.KineticForces.compute_bounce_geometry — Method
compute_bounce_geometry(psi, n, q, bo, bmax, bmin, theta_bmax, tspl, B_vpar, mfac, chi1, ro,
                        dbob_m_f, divx_m_f, divxfac, wdfac, mass, chrg, T_s, method;
                        nlmda=128, ntheta=128, do_matrices=false, surface_field=nothing) → BounceGeometry

The bounce-harmonic-independent half of compute_bounce_data: for every λ of the grid, locate the orbit, sample the bounce integrands on its θ sub-grid and integrate them. The harmonic enters only through the phase exp(−2πi·lnq·∫J B/v_∥), applied by bounce_harmonic. Arguments as for compute_bounce_data; do_matrices stores the Wμ, WE samples the kinetic matrix path needs.

source
GeneralizedPerturbedEquilibrium.KineticForces.compute_calculated_kinetic_matrices — Method
compute_calculated_kinetic_matrices(ffs_ctrl, equil, ffs_intr, metric, mats;
                                    kf_ctrl=KineticForcesControl(), kinetic_profiles,
                                    species=nothing, psis=Float64[], axis_psi_c=0.0)
    → (kw_flat, kt_flat)

Drive the KineticForces matrix kernel over the ψ grid (metric.xs unless psis is given) and return (kw_flat, kt_flat) arrays of shape (mpsi, np^2, 6) matching the contract that ForceFreeStates._compute_fkg_matrices consumes.

The arrays carry the six bounce-averaged kinetic energy / torque matrices (Logan 2015 Eqs 7.30–7.35) for every ψ on the equilibrium grid, packed as block-diagonal matrices over toroidal mode number n ∈ [nlow, nhigh] and flattened to (np = mpert·npert)². The species contributions are summed.

Arguments

  • ffs_ctrl: ForceFreeStatesControl (unused; kept for the callback signature)
  • equil: PlasmaEquilibrium with 2D interpolants and named profile/geometry splines
  • ffs_intr: ForceFreeStatesInternal (mode indexing)
  • metric: MetricData (default ψ grid metric.xs, Fourier fit for the geometric matrices)
  • mats: MatrixSplines (unused)

Keyword arguments

  • kf_ctrl: KineticForcesControl with the kinetic model settings ForceFreeStatesControl does not expose
  • kinetic_profiles::Equilibrium.KineticProfileSplines: Required. Named kinetic-profile splines built by Equilibrium.kinetic_profile_splines.
  • species: resolved species set to sum; nothing uses the equilibrium's main ion alone
  • psis: ψ grid for the kernel; empty (default) evaluates on metric.xs
  • axis_psi_c: near-axis validity boundary; used when kf_ctrl.axis_validity_suppression is set

Returns

  • kw_flat::Array{ComplexF64,3}: Energy matrices, shape (mpsi, np^2, 6)
  • kt_flat::Array{ComplexF64,3}: Torque matrices, shape (mpsi, np^2, 6)
source
GeneralizedPerturbedEquilibrium.KineticForces.compute_kinetic_matrices_at_psi! — Method
compute_kinetic_matrices_at_psi!(kwmat, ktmat, psi, n, l, zi, mi,
    wdfac, electron, equil, intr, kinetic_profiles)

Compute the six kinetic Euler-Lagrange coefficient matrices (Logan 2015 Eqs 7.30–7.35) at one flux surface, split into kwmat (fwmm half, Fortran rex=0, imx=1) and ktmat (ftmm half, rex=1, imx=0) as the ForceFreeStates kinetic assembly expects for its kwmat ± ktmat combinations. Both halves are complex and come from a single integration. Zero for ψ > 1.

Arguments

  • kwmat::Array{ComplexF64,3}: Output (mpert×mpert×6), fwmm half, overwritten
  • ktmat::Array{ComplexF64,3}: Output (mpert×mpert×6), ftmm half, overwritten
  • psi, n, l, zi, mi, wdfac, electron: Same as tpsi!
  • equil: PlasmaEquilibrium
  • intr::KineticForcesInternal: Internal state with mode indexing, geometric matrices (smats/tmats/xmats/ymats/zmats), and per-surface θ-grid buffers
  • kinetic_profiles::Equilibrium.KineticProfileSplines: Named kinetic-profile splines
  • state, geometry (keywords): precomputed _setup_surface_state bundle and bounce geometry to share across harmonics; built here when nothing

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

source
GeneralizedPerturbedEquilibrium.KineticForces.compute_torque_all_methods! — Method
compute_torque_all_methods!(state::KineticForcesState, intr::KineticForcesInternal,
                            ctrl::KineticForcesControl, equil, kinetic_profiles;
                            axis_psi_c=0.0, z, m, electron)

Calculate torque/energy for all enabled methods by ψ quadrature (integrate_psi_quadgk), summing over toroidal mode numbers and assembling block-diagonal kinetic matrices for the matrix methods.

Arguments

  • state::KineticForcesState: Accumulates results for all methods
  • intr::KineticForcesInternal: Internal state with equilibrium data
  • ctrl::KineticForcesControl: Control parameters specifying which methods to run
  • equil: PlasmaEquilibrium with 2D interpolants
  • kinetic_profiles::Equilibrium.KineticProfileSplines: Named kinetic-profile splines
  • axis_psi_c: the run's near-axis validity boundary, suppressing the torque density below it (KineticForces.axis_validity_boundary); 0 disables the suppression
  • z, m, electron: the species whose torque this is; default the equilibrium's main ion, with ctrl.electron. The species sum calls this once per resolved species.
source
GeneralizedPerturbedEquilibrium.KineticForces.evaluate_energy_integrand — Method
evaluate_energy_integrand(x_grid; wn, wt, we, wd, wb, nuk, leff, n,
                           nutype="harmonic", f0type="maxwellian",
                           nufac=1.0, qt=false) → Vector{ComplexF64}

Diagnostic: evaluate the energy integrand N(x)·exp(-x)/denom(x) (not the integral) at each x = E/T in x_grid.

Example

x = 10 .^ range(-2; stop=2, length=500)
f = KineticForces.evaluate_energy_integrand(x; wn=1e3, wt=2e3, we=5e4,
    wd=1e2, wb=3e4, nuk=1e3, leff=1.0, n=1)
plot(x, real.(f); xscale=:log10, xlabel="x = E/T", ylabel="Re(integrand)")
source
GeneralizedPerturbedEquilibrium.KineticForces.find_resonance_energies — Method
find_resonance_energies(leff, wb, n, we, wd) → Vector{Float64}

Real positive energies x_res where the resonance condition vanishes:

Ω(x) = leff·wb·√x + n·(we + wd·x) = 0

With s = √x this is the quadratic n·wd·s² + leff·wb·s + n·we = 0. Returns the x = s² values for the positive real roots (the locations of the resonance poles of the energy integrand).

source
GeneralizedPerturbedEquilibrium.KineticForces.find_sign_change_roots — Method
find_sign_change_roots(f, grid) → Vector{Float64}

Locate the zeros of a callable f by scanning consecutive grid nodes for strict sign changes (f(x[i])·f(x[i+1]) < 0) and refining each bracket with Roots.Brent. Returns the refined roots in grid order (empty if f never changes sign; a node value of exactly zero is not treated as a crossing).

Single source of truth for the scan-then-Brent idiom — used for dB/dθ extrema in the bounce averaging and for kinetic-resonance surfaces in the ψ quadrature paneling.

source
GeneralizedPerturbedEquilibrium.KineticForces.integrate_energy — Method
integrate_energy(wn, wt, we, wd, wb, nuk, ell, leff, n, psi, lambda, method;
                 nutype="harmonic", f0type="maxwellian", nufac=1.0,
                 qt=false, atol=1e-7, rtol=1e-5) → ComplexF64

Integrate the kinetic resonance operator ∫₀^∞ N(x)·exp(-x)/denom(x) dx over normalized energy x = E/T, with resonance poles handled by _integrate_energy_resonant; CGL has no pole and is integrated directly.

Collision operator types (nutype): "zero", "small", "krook", "harmonic". Distribution function types (f0type): "maxwellian", "park", "cgl".

source
GeneralizedPerturbedEquilibrium.KineticForces.integrate_pitch_gar_quadgk — Method
integrate_pitch_gar_quadgk(wn, wt, we, nuk, bobmax, epsr, q, fbnce, fbnce_norm,
                            nqty, ell, n, rex, imx, psi, method; ...) → Vector{ComplexF64}

Integrate the kinetic resonance operator over pitch angle λ using adaptive Gauss-Kronrod quadrature. Uses QuadGK.quadgk! with an in-place ComplexF64 kernel buffer.

The fbnce interpolant returns [ωb, ωd, f₁, f₂, ...] at each λ, where:

  • f₁ = ωb|δJ|²/ro² (scalar torque)
  • f₂:end = ωb·Wouterproducts/ro² (kinetic matrix elements, if present)

Splits the domain at the trapped/passing boundary so Gauss-Kronrod resolves the kink in leff = ell + n*q (circulating) → ell (trapped). One quadgk! call writes all nqty complex quantities per λ-evaluation.

Returns

  • Vector{ComplexF64} of length nqty: integrated pitch-angle results
source
GeneralizedPerturbedEquilibrium.KineticForces.integrate_pitch_gar_quadgk_wt — Method
integrate_pitch_gar_quadgk_wt(wn, wt, we, nuk, bobmax, epsr, q, fbnce, fbnce_norm,
                               nqty, ell, n, psi, method; ...) → Vector{ComplexF64}

Dual-output variant for the kinetic-matrix path: one pitch integration, sharing each energy integral, yields both the wmm half (rex=0, imx=1; Fortran kwmat) and the tmm half (rex=1, imx=0; Fortran ktmat).

Returns a length-2*nqty packed buffer [wmm | tmm].

source
GeneralizedPerturbedEquilibrium.KineticForces.integrate_psi_quadgk — Method
integrate_psi_quadgk(n, nl, zi, mi, wdfac, divxfac, electron, method,
                      equil, intr, ctrl, kinetic_profiles; psi_min, psi_max, axis_psi_c) → NamedTuple

Integrate torque over ψ using adaptive Gauss-Kronrod quadrature with QuadGK.BatchIntegrand. Every integrand evaluation is logged as a diagnostic T(ψ) profile.

Returns

NamedTuple with:

  • total::ComplexF64: Total integrated torque
  • torque_profile: NamedTuple (psi, dtdpsi, t_cumulative, dtdpsi_ell, ell) from the evaluation points
  • matrix_integrated: Trapezoidal-integrated mpert×mpert×6 matrix (if matrix method)
  • psi_nsteps::Int: Number of integrand evaluations
  • psi_quad_error::Float64: Quadrature error estimate for the total torque
  • panel_psis::Vector{Float64}: Quadrature panel boundaries actually used (bounds + interior resonant surfaces)
  • resonance_psis::Vector{Float64}: Located kinetic-resonance ψ surfaces (Ω_ℓ(x=1)=0), for diagnostics/plotting

The integral is paneled at the rational surfaces (intr.sing_psis) and kinetic resonances, and capped at ctrl.maxevals_psi evaluations; a warning is emitted if the quadrature fails to reach ctrl.rtol_psi/ctrl.atol_psi or if a nonzero atol_psi dominates termination.

source
GeneralizedPerturbedEquilibrium.KineticForces.kinetic_axis_validity_envelope — Method
kinetic_axis_validity_envelope(psi, psi_c) → Float64

C² quintic smoothstep for the near-axis kinetic suppression: 0 for ψ ≤ ψc (drift-kinetic model invalid; kernel evaluation may be skipped), rising over `[ψc, 2ψc]`, 1 above. The transition width is tied to ψc itself, so there is no independent width parameter. psi_c ≤ 0 returns 1 (no suppression).

source
GeneralizedPerturbedEquilibrium.KineticForces.kinetic_axis_validity_psi — Method
kinetic_axis_validity_psi(species, equil) → Float64

Near-axis validity boundary for a resolved multi-species set: the largest single-species ψ_c, so suppression covers every ψ where any species violates the zero-orbit-width ordering. Heavier or less-charged species carry wider orbits (ρ ∝ √(mT)/(Z e B₀)), so the maximum is normally set by the main ion; impurities move it only if their √m/Z exceeds the main ion's.

source
GeneralizedPerturbedEquilibrium.KineticForces.kinetic_axis_validity_psi — Method
kinetic_axis_validity_psi(kinetic_profiles, equil; zi=1, mi=2, electron=false) → Float64

ψN below which the zero-orbit-width drift-kinetic ordering fails: the outermost ψ on the kinetic-profile grid where any of the three thermal orbit-width scales reaches the local minor radius ⟨r⟩ — potato width (q²ρ²R₀)^(1/3), banana width q·ρ/√ε, and poloidal gyroradius q·ρ/ε (ε = ⟨r⟩/⟨R⟩, clamped as in `kineticresonancepsinodes`; thermal gyroradius ρ = √(2·m·T)/(Z·e·B₀) of the computed species). Only the region contiguous with the axis counts; a later re-trigger only warns. Returns 0.0 when no criterion is met at the axis.

source
GeneralizedPerturbedEquilibrium.KineticForces.kinetic_energy_matrices_for_euler_lagrange! — Method
kinetic_energy_matrices_for_euler_lagrange!(kwmat, ktmat, state, psi, n, l, wdfac, intr;
                                            kwargs...) → nothing

Compute the six kinetic Euler-Lagrange coefficient matrices (A, B, C, D, E, H) of Logan 2015 Eqs 7.30–7.35 at one (ψ, n, ℓ) into pre-allocated kwmat[mpert, mpert, 6] (fwmm half, Fortran rex=0, imx=1) and ktmat[mpert, mpert, 6] (ftmm half, rex=1, imx=0). One energy integration per (λ, E) via integrate_pitch_gar_quadgk_wt yields both halves. The upper-triangle-stored A/D/H blocks mirror as Hermitian in kwmat (kwmat[j,i] = conj(kwmat[i,j])) and anti-Hermitian in ktmat (ktmat[j,i] = -conj(ktmat[i,j])).

source
GeneralizedPerturbedEquilibrium.KineticForces.kinetic_resonance_psi_nodes — Method
kinetic_resonance_psi_nodes(kinetic_profiles, equil; n, nl, zi=1, mi=2, electron=false, wdfac=1.0, xeval=2.5) → Vector{Float64}

ψN locations of kinetic resonance surfaces, for use as ψ-quadrature panel boundaries and equilibrium grid knots: the zeros of the trapped-branch resonance denominator `Ω(x) = ℓ·ωb·√x + n·(ωE + ωd·x)atx = xevalfor every ℓ ∈ −nl:nl, where the NTV torque density peaks (Logan & Park, Phys. Plasmas 20, 122507 (2013), §IV–V).xevaldefaults to 2.5, the peak of the Maxwellian-weighted drivex^2.5·e^−x`. The ℓ = 0 node is the ω_d-shifted ExB (superbanana-plateau) resonance.

The frequencies are the cheap large-aspect-ratio closed forms ω_b = (π/4)·√(ε/2)·wtran and ω_d = q·T_s/(2·ε·R₀²·Z·e·B₀)·wdfac, with ε = ⟨r⟩/⟨R⟩ clamped away from the axis; no bounce averaging, which is enough for panel placement.

source
GeneralizedPerturbedEquilibrium.KineticForces.kinetic_torque — Method
kinetic_torque(pe, ctrl::KineticForcesControl; verbose=false) -> KineticForcesResult

The kinetic (NTV) torque of the perturbed equilibrium pe, evaluated with the model settings ctrl on the kinetic profiles attached to its equilibrium. A multi-species plasma adds each species' contribution. Call save_to_hdf5(target, kf) to save the result.

pe = perturbed_equilibrium(plasma_response(ffs), RMPField("forcing.dat"))
kf = kinetic_torque(pe, KineticForcesControl())
source
GeneralizedPerturbedEquilibrium.KineticForces.kinetic_validity_profiles — Method
kinetic_validity_profiles(kinetic_profiles, equil; zi=1, mi=2, electron=false) → NamedTuple

Radial profiles of the drift-kinetic validity diagnostics, on the kinetic-profile ψ grid: psi; the thermal orbit-width scales rho_i (gyroradius √(2mT)/(Z·e·B₀)), rho_banana (q·ρ/√ε), rho_theta (poloidal gyroradius q·ρ/ε), w_potato ((q²ρ²R₀)^(1/3)); the local geometry r_minor (⟨r⟩) and d_separatrix (⟨r⟩(1) − ⟨r⟩(ψ)); the profile gradient lengths L_p and L_q (|X|·|dr/dψ|/|dX/dψ|, Inf where the profile is flat); the near-axis suppression boundary psi_c (kinetic_axis_validity_psi) with its envelope; and is_valid — true where every zero-orbit-width ordering holds at coefficient 1: max orbit width < r, ρbanana < Lp and Lq, and max(ρi, ρbanana, ρθ) < d_separatrix. Validity is diagnostic only — nothing outside the near-axis envelope is suppressed (the far edge and steep-gradient regions are flagged, not zeroed, since they can dominate the physical NTV).

source
GeneralizedPerturbedEquilibrium.KineticForces.matrix_pitch_rtol — Method
matrix_pitch_rtol(ctrl::KineticForcesControl) -> Float64

Relative tolerance of the pitch (λ) quadrature in the calculated kinetic matrix build: ctrl.rtol_pitch when set, otherwise MATRIX_RTOL_PITCH (1e-3). The matrices are splined over ψ and fed to the Euler–Lagrange solve, so there is no outer quadrature tolerance to derive from.

source
GeneralizedPerturbedEquilibrium.KineticForces.ntv_profiles — Method
ntv_profiles(kf_ctrl, equil) → Union{Nothing,KineticProfileSplines}

The NTV view of the kinetic profiles attached to equil (equil.kinetic), with its main-ion and impurity charges and masses and the profile scale factors of kf_ctrl; nothing when the equilibrium carries no kinetic profiles.

source
GeneralizedPerturbedEquilibrium.KineticForces.ntv_species — Method
ntv_species(kf_ctrl, equil) → Union{Nothing,Vector{ResolvedNTVSpecies}}

The resolved NTV species set of the kinetic profiles attached to equil (see Equilibrium.resolve_ntv_species) when the run sums species (several main ions, a main ion with a partial or explicit density, or kf_ctrl.electron); nothing for the single main-ion run or when the equilibrium carries no kinetic profiles.

source
GeneralizedPerturbedEquilibrium.KineticForces.orbit_widths — Method
orbit_widths(psi, T_spline, q_spline, avg_r, avg_R, mass, chrg, ro, bo)

Thermal orbit-width scales of one species at ψ: the minor radius ⟨r⟩ and inverse aspect ratio ε, the gyroradius ρ = √(2mT)/(Z·e·B₀), and the three widths that bound the zero-orbit-width ordering — potato (q²ρ²R₀)^(1/3), banana qρ/√ε, and poloidal gyroradius qρ/ε. Single source of truth for both the validity boundary and the diagnostic profiles.

source
GeneralizedPerturbedEquilibrium.KineticForces.powspace — Method
powspace(xmin, xmax, pow, num, endpoints) → (points, weights)

Generate a grid with power-law concentration near endpoints. Port of Fortran powspace_sub from equil/grid.f90.

Arguments

  • xmin, xmax: Grid bounds
  • pow::Int: Power of grid concentration (higher = more refined near edges)
  • num::Int: Number of grid points
  • endpoints::String: Where to concentrate: "lower", "upper", or "both"

Returns

  • points::Vector{Float64}: Grid point locations
  • weights::Vector{Float64}: Derivatives dx/dnorm (integration weights)
source
GeneralizedPerturbedEquilibrium.KineticForces.psi_panel_points — Method
psi_panel_points(interior, x0, xout) → Vector{Float64}

Build the ψ-quadrature node list [x0, interior points strictly inside (x0, xout), xout]. interior is the unsorted union of resonant-surface locations; points closer than PANEL_MERGE_ATOL to each other or to a bound are dropped to avoid degenerate panels. Paneling at these surfaces puts the narrow resonant torque-density peaks on Gauss-Kronrod interval endpoints.

source
GeneralizedPerturbedEquilibrium.KineticForces.resonance_grid_nodes — Method
resonance_grid_nodes(ctrl, kf_ctrl, kinetic_profiles, species, equil, intr; rationals=Float64[]) → Vector{Float64}

ψN locations to pin into the two-pass equilibrium grid for a self-consistent kinetic run: the Ωℓ = 0 resonance surfaces of every toroidal mode in the run, outside the near-axis validity region. Empty for ideal runs. rationals is the pass-1 rational-surface list the boundary is cleared against; the caller supplies it because intr.sing is not populated until after the grid is built.

source
GeneralizedPerturbedEquilibrium.KineticForces.set_perturbation_data! — Method
set_perturbation_data!(kf_intr, pe_state, ffs, equil, metric)

Populate the perturbation interpolants of kf_intr from the PE Clebsch displacements: xs_m ([ξ^ψ, ∂ξ^ψ/∂ψ, ξ^α] over ψ), and the δB/B (dbob_m) and ∇·ξ⊥ (divx_m) Fourier modes, obtained by applying the S,T,X,Y,Z geometric matrices and removing the J·B² weight (see _jbb_deweight!). Port of Fortran set_peq (pentrc/inputs.f90). Errors unless the run has a single toroidal mode.

source
GeneralizedPerturbedEquilibrium.KineticForces.torque_pitch_rtol — Method
torque_pitch_rtol(ctrl::KineticForcesControl) -> Float64

Relative tolerance of the pitch (λ) quadrature inside the ψ torque quadrature: ctrl.rtol_pitch when set, otherwise ctrl.psi_tolerance_margin × ctrl.rtol_psi, so the λ integrand is resolved one margin tighter than the ψ integral asks for and the ψ error estimate is not polluted by λ quadrature noise.

source
GeneralizedPerturbedEquilibrium.KineticForces.tpsi! — Method
tpsi!(tpsi_var, psi, n, l, zi, mi, wdfac, divxfac, electron, method, equil, intr,
      kinetic_profiles; op_wmats=nothing, surface=nothing, kwargs...) -> nothing

Toroidal torque from nonambipolar transport at one ψ and bounce harmonic l, written to tpsi_var[]. The imaginary part carries the kinetic energy, Im(T) = 2n·δW_k. Zero for ψ > 1.

Arguments

  • tpsi_var::Ref{ComplexF64}: Output torque
  • psi::Float64: Normalized poloidal flux
  • n::Int: Toroidal mode number
  • l::Int: Bounce harmonic number
  • zi::Int: Ion charge in fundamental units (e)
  • mi::Int: Ion mass (units of proton mass)
  • wdfac::Float64: Drift factor
  • divxfac::Float64: Divergence factor
  • electron::Bool: Calculate quantities for electrons (zi,mi ignored)
  • method::String: Integration method (FCGL, *GAR, *TMM, *WMM, *KMM) where * = F,T,P for full,trapped,passing
  • equil: PlasmaEquilibrium with 2D interpolants and named profile/geometry splines
  • intr::KineticForcesInternal: Internal state with mode indexing and perturbation splines
  • kinetic_profiles::Equilibrium.KineticProfileSplines: Named kinetic-profile splines (ni, ne, Ti, Te, ωE, νi, ν_e) loaded from kinetic.dat

Optional Arguments

  • op_wmats::Array{ComplexF64,3}: Store ForceFreeStates matrix elements
  • surface: Per-surface bundle from _torque_surface, shared across the bounce harmonics of one ψ; built here when not given
  • nutype, f0type, nufac: Collision operator, equilibrium distribution and collisionality factor passed to calculate_gar (the [KineticForces] keys nutype, f0type, collisionality_factor)
source
GeneralizedPerturbedEquilibrium.KineticForces.write_validity! — Function
write_validity!(h5file, kf_ctrl, species, kinetic_profiles, equil, rationals=Float64[])

Write KineticForces/Validity: the drift-kinetic validity diagnostics (orbit-width scales, local geometry, profile gradient lengths, the near-axis boundary and its applied envelope, and the is_valid flag). Diagnostic only — nothing outside the near-axis envelope is suppressed, so the far edge and steep-gradient regions are flagged rather than zeroed.

source
GeneralizedPerturbedEquilibrium.Utilities.save_to_hdf5 — Method
save_to_hdf5(h5file::Union{HDF5.File,HDF5.Group}, state::KineticForcesState; dVdpsi_spline=nothing,
               species_label=nothing)

Write KineticForces results to the "KineticForces" group in gpec.h5.

Arguments

  • h5file::Union{HDF5.File,HDF5.Group}: Open HDF5 file handle
  • state::KineticForcesState: Accumulated computation results
  • dVdpsi_spline: Optional dV/dψN profile interpolant; when given, dV/dψN is written at the quadrature points so the torque density dT/dV = (dT/dψ)/(dV/dψ) is directly available
  • species_label: nothing writes the run total to KineticForces/<method>/; a label (e.g. "ion_z1_m2", "electron") writes one species' contribution to KineticForces/PerSpecies/<label>/<method>/. A multi-species run calls this once per species and once for the summed total, so the group is opened-or-created each time.
source