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
Utilities

Shared 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 functions
  • PhysicalConstants: SI physical constants matching Fortran GPEC/SLAYER values
  • NeoclassicalResistivity: Spitzer/Sauter/Redl resistivity closures shared by the GGJ and SLAYER inner-layer models
  • HDF5Annotations: self-describing metadata (long_name/units/dims attributes and HDF5 Dimension Scales) for the gpec.h5 output
  • HermiteFEM: the Hermite-cubic basis and packed grid shared by the Galerkin solvers
source
GeneralizedPerturbedEquilibrium.Utilities.FourierCoefficients — Type
FourierCoefficients

Lightweight 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 coordinates
  • mmax::Int: Highest retained poloidal Fourier mode (modes 0:mmax inclusive)
  • nqty::Int: Number of quantities
  • cos_coeffs::Array{Float64,3}: Cosine coefficients (npsi × nmodes × nqty)
  • sin_coeffs::Array{Float64,3}: Sine coefficients (npsi × nmodes × nqty)
source
GeneralizedPerturbedEquilibrium.Utilities.FourierCoefficients — Method
FourierCoefficients(xs, ys, fs, mmax)

Compute Fourier coefficients via FFT without creating splines.

Arguments

  • xs::Vector{Float64}: Radial coordinates
  • ys::Vector{Float64}: Poloidal coordinates (periodic domain)
  • fs::Array{Float64,3}: Function values (npsi × ntheta × nqty)
  • mmax::Int: Highest poloidal Fourier mode to retain
source
GeneralizedPerturbedEquilibrium.Utilities.KineticProfiles — Type
KineticProfiles

Radial kinetic-profile container. All four profiles are 1D cubic splines of the normalized poloidal flux ψ ∈ [0, 1].

fieldmeaningunits
n_eelectron densitym⁻³
T_eelectron temperatureeV
T_iion temperatureeV
omega_EE×B rotation Ω_E, per unit nrad/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=...)
source
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.

source
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.

source
GeneralizedPerturbedEquilibrium.Utilities.FourierTransforms — Module
FourierTransforms

Pre-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).

source
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 points
  • mpert: number of poloidal modes
  • mlow: lowest poloidal mode number

Keyword Arguments

  • n: toroidal mode number (default 0)
  • ζ: toroidal angle of each grid point in radians, length mtheta

Returns

  • FourierTransform ready for forward and inverse transforms
source
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 plane
  • m_modes: poloidal mode numbers
  • nzeta: full-torus toroidal grid points (must be divisible by nfp)
  • n_modes: toroidal mode numbers

Keyword Arguments

  • nfp: number of field periods; when > 1, emits one period only (nzeta ÷ nfp planes)

Returns

  • Basis matrix, size (length(m_modes) * length(n_modes), mtheta * (nzeta ÷ nfp))
source
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 points
  • m_modes: poloidal mode numbers (one row per mode)
  • n: toroidal mode number
  • ζ: toroidal angle of each grid point in radians, length mtheta

Returns

  • Basis matrix, size (length(m_modes), mtheta)
source
GeneralizedPerturbedEquilibrium.Utilities.AdaptiveSampling — Module
AdaptiveSampling

Sample 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.

source
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 below rtol, 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).

source

Physical constants

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
NeoclassicalResistivity

Spitzer + 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

symbolrole
NeoResistivityModelabstract tag
SpitzerModelplain Spitzer (no trapped-particle correction)
SpitzerHarmModelFitzpatrick/TJ Spitzer-Härm σ∥ (legacy SLAYER τR)
SauterNeoModelSauter 1999 F_33 neoclassical correction
RedlNeoModelRedl 2021 F_33 neoclassical correction
coulomb_log_eln Λ_e (NRL or Sauter form)
eta_spitzerSauter 18a Spitzer resistivity [Ω·m]
tau_ee_spitzer_harmelectron-electron collision time τ_ee [s]
eta_spitzer_harmFitzpatrick/TJ Spitzer-Härm resistivity 1/σ_∥ [Ω·m]
trapped_fractionLin-Liu & Miller 1995 ft from ⟨B⟩, ⟨B²⟩, Bmin, B_max
trapped_fraction_epssimple ε-only f_t fallback
nu_star_eSauter 18b electron collisionality
eta_neoclassicaldispatched: Spitzer(-Härm) or F_33 · Spitzer
source
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.eta_neoclassical — Method
eta_neoclassical(model, n_e, T_e, Z_eff, f_t, nu_e_star;
                 lnLamb=nothing) -> Float64

Neoclassical resistivity η in Ω·m under the chosen closure.

  • SpitzerModel() – returns eta_spitzer(n_e, T_e, Z_eff; lnLamb) unchanged; f_t and nu_e_star are ignored.
  • SpitzerHarmModel() – returns eta_spitzer_harm(n_e, T_e, Z_eff; lnLamb) (Fitzpatrick/TJ legacy); f_t and nu_e_star are 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).

source
GeneralizedPerturbedEquilibrium.Utilities.NeoclassicalResistivity.eta_spitzer_harm — Method
eta_spitzer_harm(n_e, T_e, Z_eff; lnLamb=nothing) -> Float64

Spitzer-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_e

This 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).

source

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
HDF5Annotations

Self-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).

source
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 attribute dims = "(psi, m)".
  • scale — mark this dataset as an HDF5 Dimension Scale with the given name (netCDF-4 coordinate variable).
  • attach — tuple of axis => scale_path pairs attaching declared scales to this dataset's Julia axes; scale_path is relative to parent and its dimension label comes from that entry's scale name (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.

source
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.

source

Hermite FEM

The Hermite-cubic basis and packed grid shared by the outer-region and inner-layer Galerkin solvers.

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).

source

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.

source