Utilities
Utilities holds the helpers shared by the physics modules: Fourier transforms and adaptive sampling, physical constants, the neoclassical resistivity closures, the HDF5 annotation layer of gpec.h5, the Hermite finite-element basis, and the IMAS export.
Fourier transforms and sampling
GeneralizedPerturbedEquilibrium.Utilities — Module
UtilitiesShared mathematical and computational utilities for GPEC modules.
This module provides common functionality used across multiple GPEC modules, including efficient Fourier transforms, numerical integration, and other mathematical utilities.
Submodules
FourierTransforms: Efficient Fourier transforms with pre-computed basis functionsPhysicalConstants: SI physical constants matching Fortran GPEC/SLAYER valuesNeoclassicalResistivity: Spitzer/Sauter/Redl resistivity closures shared by the GGJ and SLAYER inner-layer modelsHDF5Annotations: self-describing metadata (long_name/units/dims attributes and HDF5 Dimension Scales) for the gpec.h5 outputHermiteFEM: the Hermite-cubic basis and packed grid shared by the Galerkin solvers
GeneralizedPerturbedEquilibrium.Utilities.FourierCoefficients — Type
FourierCoefficientsLightweight container for Fourier coefficients without spline interpolation. Use this when you only need to access coefficients at original grid points.
Fields
xs::Vector{Float64}: Radial coordinatesmmax::Int: Highest retained poloidal Fourier mode (modes 0:mmax inclusive)nqty::Int: Number of quantitiescos_coeffs::Array{Float64,3}: Cosine coefficients (npsi × nmodes × nqty)sin_coeffs::Array{Float64,3}: Sine coefficients (npsi × nmodes × nqty)
GeneralizedPerturbedEquilibrium.Utilities.FourierCoefficients — Method
FourierCoefficients(xs, ys, fs, mmax)Compute Fourier coefficients via FFT without creating splines.
Arguments
xs::Vector{Float64}: Radial coordinatesys::Vector{Float64}: Poloidal coordinates (periodic domain)fs::Array{Float64,3}: Function values (npsi × ntheta × nqty)mmax::Int: Highest poloidal Fourier mode to retain
GeneralizedPerturbedEquilibrium.Utilities.KineticProfiles — Type
KineticProfilesRadial kinetic-profile container. All four profiles are 1D cubic splines of the normalized poloidal flux ψ ∈ [0, 1].
| field | meaning | units |
|---|---|---|
n_e | electron density | m⁻³ |
T_e | electron temperature | eV |
T_i | ion temperature | eV |
omega_E | E×B rotation Ω_E, per unit n | rad/s |
Construct via the keyword constructor KineticProfiles(; psi, n_e, T_e, T_i, omega_E) with matched-length vectors. Diamagnetic frequencies are not carried here; callers derive ω*e and ω*i from the density and temperature splines.
Evaluate all profiles at a given ψ via the call operator:
vals = kp(0.5) # NamedTuple(n_e=..., T_e=..., T_i=..., omega_E=...)GeneralizedPerturbedEquilibrium.Utilities.KineticProfiles — Method
(kp::KineticProfiles)(psi::Real) -> NamedTupleEvaluate all profiles at psi and return them as a NamedTuple with fields (n_e, T_e, T_i, omega_E).
GeneralizedPerturbedEquilibrium.Utilities.apply_main_h5_metadata! — Method
apply_main_h5_metadata!(out_h5)Apply the self-describing metadata contract to the datasets written by save_to_hdf5: long_name/units/dims attributes plus HDF5 Dimension Scales for the shared coordinate datasets (ψ_N grids, rational-surface ψ).
GeneralizedPerturbedEquilibrium.Utilities.deck_sections — Function
deck_sections(result) -> Dict{String,Any}The deck sections stating the inputs result was computed from, so a saved run records a deck that reproduces it. The methods live with the deck translation of the top module, the inverse of its section parser.
GeneralizedPerturbedEquilibrium.Utilities.empty_FourierCoefficients — Method
empty_FourierCoefficients()Create an empty FourierCoefficients for initialization purposes.
GeneralizedPerturbedEquilibrium.Utilities.get_complex_coeff — Method
get_complex_coeff(fc::FourierCoefficients, ipsi, mode, qty) -> ComplexF64Normalized complex FFT coefficient FFT/ntheta of mode mode at grid point ipsi: c[0] = cos_coeffs[0], c[m] = cos_coeffs[m]/2 - i*sin_coeffs[m]/2 for m > 0.
GeneralizedPerturbedEquilibrium.Utilities.get_complex_coeffs! — Method
get_complex_coeffs!(out, fc::FourierCoefficients, ipsi, qty)Fill vector with normalized complex FFT coefficients for modes 0:mmax.
GeneralizedPerturbedEquilibrium.Utilities.record_inputs! — Method
record_inputs!(target, result)Merge the deck sections of result into the run record Input/gpec_toml_raw of target, replacing any section of the same name, so every saved result adds the deck it was computed from.
GeneralizedPerturbedEquilibrium.Utilities.save_to_hdf5 — Function
save_to_hdf5(target, result; kwargs...)Save a computed result to an HDF5 path, open file, or group. Each producing module implements the method for its result type and an open HDF5.File or HDF5.Group. The path method opens or creates the file, preserves existing contents, and closes its handle after saving. An open target remains owned by the caller.
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms — Module
FourierTransformsPre-computed complex Fourier basis and functor interface for θ ↔ mode transforms.
basis[ℓ, i] = exp(-i(m_ℓ θ_i - n ζ_i)) with shape (mpert, mtheta). Forward: basis * data / mtheta; inverse: adjoint(basis) * modes (Fortran iscdftf/iscdftb; see docs/src/conventions.md).
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.FourierTransform — Type
FourierTransformStruct with precomputed complex Fourier basis for repeated θ ↔ mode transforms.
Fields
mtheta: poloidal grid sizempert: number of poloidal modesmlow: lowest poloidal mode numberbasis: $\exp(-i(m\theta - n\zeta))$, size(mpert, mtheta)
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.FourierTransform — Method
(ft::FourierTransform)(data)Forward transform from θ-space to mode space.
Arguments
data: real or complex samples on the poloidal grid —Vector{mtheta}orMatrix{mtheta, :}
Returns
- Mode coefficients —
Vector{mpert}orMatrix{mpert, :}
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.FourierTransform — Method
FourierTransform(mtheta, mpert, mlow; n=0, ζ=zeros(mtheta))Construct a transform with precomputed basis for contiguous modes mlow:(mlow+mpert-1).
Arguments
mtheta: number of poloidal grid pointsmpert: number of poloidal modesmlow: lowest poloidal mode number
Keyword Arguments
n: toroidal mode number (default 0)ζ: toroidal angle of each grid point in radians, lengthmtheta
Returns
FourierTransformready for forward and inverse transforms
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.compute_fourier_coefficients — Method
compute_fourier_coefficients(mtheta, m_modes, nzeta, n_modes; nfp=1)Build 3D basis for every (m, n) in m_modes × n_modes (rows m-fast, n-slow).
Arguments
mtheta: poloidal grid points per toroidal planem_modes: poloidal mode numbersnzeta: full-torus toroidal grid points (must be divisible bynfp)n_modes: toroidal mode numbers
Keyword Arguments
nfp: number of field periods; when> 1, emits one period only (nzeta ÷ nfpplanes)
Returns
- Basis matrix, size
(length(m_modes) * length(n_modes), mtheta * (nzeta ÷ nfp))
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.compute_fourier_coefficients — Method
compute_fourier_coefficients(mtheta, m_modes, n, ζ)Build complex basis $\exp(-i(m\theta - n\zeta))$ at the points $(\theta_i, \zeta_i)$ of the uniform poloidal grid.
Arguments
mtheta: number of poloidal grid pointsm_modes: poloidal mode numbers (one row per mode)n: toroidal mode numberζ: toroidal angle of each grid point in radians, lengthmtheta
Returns
- Basis matrix, size
(length(m_modes), mtheta)
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.inverse — Method
inverse(ft, modes)Inverse transform from mode space to θ-space.
Arguments
ft: precomputed transformmodes: complex mode coefficients —Vector{mpert}orMatrix{mpert, :}
Returns
- θ-space data —
Vector{mtheta}orMatrix{mtheta, :}
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.inverse_transform! — Method
inverse_transform!(output, ft, modes)In-place inverse transform (mode → θ-space) writing into output: output .= adjoint(basis) * modes.
Allocation-free wrapper over inverse for reuse in hot loops. output must have first dimension mtheta and match the column count of modes (whose first dimension is mpert).
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms.transform! — Method
transform!(output, ft, data)In-place forward transform (θ-space → mode) writing into output: output .= (basis * data) / mtheta.
Allocation-free wrapper over the FourierTransform functor for reuse in hot loops. output must have first dimension mpert and match the column count of data (whose first dimension is mtheta).
GeneralizedPerturbedEquilibrium.Utilities.AdaptiveSampling — Module
AdaptiveSamplingSample an expensive function on a one-dimensional grid that refines itself where the function changes fastest, so that sharp features (a resonance, a zero crossing) are resolved without paying for a fine uniform grid. Intended for scans whose every point is a full physics evaluation, e.g. a torque against a rotation shift.
GeneralizedPerturbedEquilibrium.Utilities.AdaptiveSampling.adaptive_sample — Method
adaptive_sample(f, xs0; max_points=21, rtol=0.05, min_width=0.0, crossing_width=nothing, feature_ratio=10.0) -> (x, y)Evaluate the vector-valued f(x) -> AbstractVector{<:Real} on the initial grid xs0 (keep 0 in it when the unshifted point must be reproduced exactly), then bisect the interval whose midpoint is predicted worst (linear vs Catmull-Rom estimate, relative to each component's range) until every interval's error is below rtol, narrower than min_width, or max_points evaluations are spent.
Arguments
crossing_width: intervals where a component changes sign are refined first until narrower than this (default: an eighth of the initial spacing).feature_ratio: an interval whose error exceeds this multiple of the median error is refined even belowrtol, to catch a narrow feature on a large smooth background.
A feature invisible at the initial spacing cannot be found; the initial grid sets that resolution.
Returns the sorted sample points x and the matrix y (length(x) × ncomponents).
Physical constants
GeneralizedPerturbedEquilibrium.Utilities.PhysicalConstants — Module
PhysicalConstantsShared physical constants used across GPEC modules. Values match the Fortran GPEC/SLAYER conventions (sglobal_mod) so numerical results can be directly compared.
All quantities in SI units.
Neoclassical resistivity
Parallel-resistivity closures (Spitzer, Spitzer-Härm, and the Sauter and Redl neoclassical models) used to set the Lundquist number in the tearing stack.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity — Module
NeoclassicalResistivitySpitzer + Sauter / Redl neoclassical resistivity closures, shared between the GGJ and SLAYER inner-layer models so both see identical plasma-input physics when the same NeoResistivityModel is selected.
Exports
| symbol | role |
|---|---|
NeoResistivityModel | abstract tag |
SpitzerModel | plain Spitzer (no trapped-particle correction) |
SpitzerHarmModel | Fitzpatrick/TJ Spitzer-Härm σ∥ (legacy SLAYER τR) |
SauterNeoModel | Sauter 1999 F_33 neoclassical correction |
RedlNeoModel | Redl 2021 F_33 neoclassical correction |
coulomb_log_e | ln Λ_e (NRL or Sauter form) |
eta_spitzer | Sauter 18a Spitzer resistivity [Ω·m] |
tau_ee_spitzer_harm | electron-electron collision time τ_ee [s] |
eta_spitzer_harm | Fitzpatrick/TJ Spitzer-Härm resistivity 1/σ_∥ [Ω·m] |
trapped_fraction | Lin-Liu & Miller 1995 ft from ⟨B⟩, ⟨B²⟩, Bmin, B_max |
trapped_fraction_eps | simple ε-only f_t fallback |
nu_star_e | Sauter 18b electron collisionality |
eta_neoclassical | dispatched: Spitzer(-Härm) or F_33 · Spitzer |
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.NeoResistivityModel — Type
Abstract tag for a neoclassical-resistivity closure.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.RedlNeoModel — Type
Redl et al. 2021 F_33 neoclassical correction (Eqs. 17-18). Improved high-collisionality fit vs SauterNeoModel.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.SauterNeoModel — Type
Sauter, Angioni & Lin-Liu 1999 F_33 neoclassical correction (Eqs. 13a,b).
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.SpitzerHarmModel — Type
Spitzer-Härm parallel resistivity 1/σ∥ as used by Fitzpatrick's TJ (LayerParameters.tex Eqs. 7-8) and legacy SLAYER for τR. No trapped-particle correction. Pair with lnLambda_form=:wesson to reproduce legacy SLAYER behaviour bit-identically.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.SpitzerModel — Type
Plain Spitzer resistivity — no trapped-particle correction.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.coulomb_log_e — Method
coulomb_log_e(n_e, T_e; form=:nrl) -> Float64Electron Coulomb logarithm. n_e in m⁻³, T_e in eV.
form=:nrl (default) uses the NRL Plasma Formulary 2009 expression, form=:sauter the simpler Sauter 1999 Eq. 18d form, and form=:wesson the Wesson form of the legacy SLAYER.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.eta_neoclassical — Method
eta_neoclassical(model, n_e, T_e, Z_eff, f_t, nu_e_star;
lnLamb=nothing) -> Float64Neoclassical resistivity η in Ω·m under the chosen closure.
SpitzerModel()– returnseta_spitzer(n_e, T_e, Z_eff; lnLamb)unchanged;f_tandnu_e_starare ignored.SpitzerHarmModel()– returnseta_spitzer_harm(n_e, T_e, Z_eff; lnLamb)(Fitzpatrick/TJ legacy);f_tandnu_e_starare ignored.SauterNeoModel()– Sauter 1999 Eq. 13: η = ηSp / F33(Sauter).RedlNeoModel()– Redl 2021 Eq. 17: η = ηSp / F33(Redl).
σneo = σSp · F33, so ηneo = ηSp / F33 (about 2 ηSp in the banana regime at ft ≈ 0.5).
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.eta_spitzer — Method
eta_spitzer(n_e, T_e, Z_eff; lnLamb=nothing) -> Float64Spitzer resistivity in Ω·m, using the Sauter 1999 Eq. 18a form
σ_Sp = 1.9012e4 · T_e^1.5 / (Z_eff · N(Z_eff) · lnΛ_e)
N(Z) = 0.58 + 0.74 / (0.76 + Z)
η_Sp = 1 / σ_Spn_e in m⁻³, T_e in eV. lnLamb defaults to coulomb_log_e(n_e, T_e) (NRL).
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.eta_spitzer_harm — Method
eta_spitzer_harm(n_e, T_e, Z_eff; lnLamb=nothing) -> Float64Spitzer-Härm parallel resistivity η∥ = 1/σ∥ in Ω·m, per Fitzpatrick TJ LayerParameters.tex Eq. 8:
σ_∥ = (√2 + 13 Z_eff/4) / (Z_eff (√2 + Z_eff)) · n_e e² τ_ee / m_eThis is the resistivity entering the legacy SLAYER / TJ resistive diffusion time τR = μ₀ rs² σ∥ (LayerParameters.tex Eq. 17). Agrees with `etaspitzer` to the fit accuracy of the two formulas (~1% at Z=1).
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.nu_star_e — Method
nu_star_e(n_e, T_e, R_major, eps, q, Z_eff; lnLamb=nothing) -> Float64Electron collisionality ν*_e per Sauter 1999 Eq. 18b:
ν*_e = 6.921e-18 · |q| · R · n_e · Z_eff · lnΛ_e / (T_e² · ε^1.5)n_e in m⁻³, T_e in eV, R_major in m.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.tau_ee_spitzer_harm — Method
tau_ee_spitzer_harm(n_e, T_e; lnLamb=nothing) -> Float64Electron-electron collision time per Fitzpatrick TJ LayerParameters.tex Eq. 7:
τ_ee = 6√2 π^1.5 ε₀² √m_e T_e^1.5 / (lnΛ e^2.5 n_e)n_e in m⁻³, T_e in eV (the e^2.5 denominator absorbs the eV→J conversion). lnLamb defaults to coulomb_log_e(n_e, T_e) (NRL).
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.trapped_fraction — Method
trapped_fraction(avg_B, avg_Bsq, B_min, B_max) -> Float64Lin-Liu & Miller 1995, Phys. Plasmas 2, 1666, Eq. (6):
f_t = 1 − ⟨B⟩² / ⟨B²⟩ · (1 − √(1 − h) · (1 + h/2)), h = B_min / B_maxArguments are flux-surface averages and extrema of |B| on the surface.
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.trapped_fraction_eps — Method
trapped_fraction_eps(eps) -> Float64Simple ε-only trapped-fraction approximation (OMFIT f_t):
f_c ≈ (1 − ε)² / (√(1 − ε²) · (1 + 1.46·√ε + 0.2·ε))
f_t = 1 − f_cFallback for when the (⟨B⟩, ⟨B²⟩, Bmin, Bmax) moments of trapped_fraction are unavailable.
HDF5 annotations
Self-describing metadata for gpec.h5 (long_name/units/dims attributes and HDF5 Dimension Scales); see the metadata contract in docs/development/hdf5-conventions.md.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations — Module
HDF5AnnotationsSelf-describing metadata for gpec.h5 (the contract in docs/development/hdf5-conventions.md): every dataset carries a long_name and units attribute, array datasets carry a dims axis-name attribute, and coordinate datasets are marked as HDF5 Dimension Scales (netCDF-4 coordinate variables) attached to the arrays that share their axis, so h5py/xarray/HDFView read the file unaided.
Writers stay table-driven: each writer keeps a table of path => (; long_name, units, dims) entries next to it and calls annotate! once after its datasets are written. Paths absent from the file are skipped silently (many writes are conditional).
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.annotate! — Method
annotate!(parent, table)Apply a metadata table to datasets under parent (an open HDF5.File or group). table iterates path => meta pairs where meta is a NamedTuple with fields long_name (required), units (default "1" = dimensionless), and optionally:
dims— tuple of axis names in Julia (column-major) order, axis 1 first, stored as the greppable string attributedims = "(psi, m)".scale— mark this dataset as an HDF5 Dimension Scale with the given name (netCDF-4 coordinate variable).attach— tuple ofaxis => scale_pathpairs attaching declared scales to this dataset's Julia axes;scale_pathis relative toparentand its dimension label comes from that entry'sscalename (falling back to the path basename).
Scales are marked in a first pass so attachments within the same table resolve. Missing paths are skipped throughout.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.attach_scale! — Method
attach_scale!(parent, path, julia_axis, scale_path, label)Attach the Dimension Scale at scale_path to Julia axis julia_axis (axis 1 first) of the dataset at path, and label that dimension. The H5DS C API indexes file (row-major) dimensions, so Julia axis k of an N-d dataset is C index N - k. No-op when either path is absent or the axis lengths disagree.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.ensure_group — Method
ensure_group(parent, name)Open an existing group or create it under parent.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.make_scale! — Method
make_scale!(parent, path, name)Mark the dataset at path as an HDF5 Dimension Scale named name. No-op when the path is absent.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.replace_group! — Method
replace_group!(parent, name)Replace a result group, discarding datasets from an earlier save of that result.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.write_fields! — Method
write_fields!(parent, result, fields)Write the selected fields using their field names as dataset names.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.write_ragged! — Method
write_ragged!(parent, name, rows)Write a group containing flattened rows and zero-based offsets delimiting each row.
GeneralizedPerturbedEquilibrium.Utilities.HDF5Annotations.write_root_attrs! — Method
write_root_attrs!(file; title)Stamp the file-level contract: schema_version, Conventions, references, title (run description), date_created (ISO 8601 UTC). The code version lives in Info/git_version.
Hermite FEM
The Hermite-cubic basis and packed grid shared by the outer-region and inner-layer Galerkin solvers.
GeneralizedPerturbedEquilibrium.Utilities.HermiteFEM — Module
HermiteFEMThe Hermite-cubic finite-element pieces shared by the two Galerkin solvers: the outer-region ForceFreeStates solver and the GGJ inner-layer solver. Both are ports of the Fortran gal.f / GGJ deltac kernels.
GeneralizedPerturbedEquilibrium.Utilities.HermiteFEM.hermite_basis — Method
hermite_basis(x, x0, x1) -> (pb, qb)Hermite cubic basis on [x0, x1]: values pb and derivatives qb, slots 1:4 ↔ (u₀, u₀', u₁, u₁'). Port of Fortran gal_hermite (gal.f).
GeneralizedPerturbedEquilibrium.Utilities.HermiteFEM.pack_grid — Method
pack_grid(nx, pfac, side) -> Vector{Float64}Packed logical grid on [-1, 1], port of Fortran gal_pack (gal.f). side = "both" gives 2nx+1 nodes (Fortran -nx:nx); "left" and "right" give 2nx+1 nodes mapped onto [-1, 1] from one side. pfac > 1 packs toward the centre (GWP2016 Eq. 33), pfac == 1 is uniform, 0 < pfac < 1 packs toward the ends (Eq. 5).
IMAS output
GeneralizedPerturbedEquilibrium.write_imas — Function
write_imas(dd, result)Write one dd.mhd_linear toroidal_mode entry per toroidal mode number, with the least-stable (minimum real part) free-boundary energy_perturbed of that n. result is the named tuple main returns.