Forcing Terms
ForcingTerms specifies the external magnetic perturbation that drives the perturbed equilibrium: the spectrum of the normal field on the control surface at psilim, given either as a file of (m, n) amplitudes or computed by Biot–Savart from coil geometry. The [ForcingTerms] section is read when [PerturbedEquilibrium] runs; its result is the RMPField that perturbed_equilibrium applies to the plasma response.
Normalization
Internally every forcing is the unit-norm flux spectrum $\Phi_x$, the Fourier amplitude of $2\pi R\,(B_R\,\partial Z/\partial\theta - B_Z\,\partial R/\partial\theta)$ over the unit-norm angles $\theta, \zeta \in [0, 1]$, the quantity the Fortran GPEC calls Phi_x. A forcing file declares its own normalization by a tag; a coil set needs none, because the Biot–Savart pipeline produces $\Phi_x$ directly.
| Tag | Quantity | Units | On load |
|---|---|---|---|
"normal_field_T" (default) | Fourier modes of $B\cdot\hat n$ over $\theta \in [0, 2\pi]$ | T | weighted by the area element $J\lvert\nabla\psi\rvert$ and projected onto every harmonic of the run; a poloidally varying weight mixes modes, so the file must cover its sidebands (a warning asks for a wider m range when an edge harmonic carries more than 10% of the flux) |
"sfl_flux_Wb" | the straight-field-line flux $R\,(B_R\,\partial Z/\partial\theta - B_Z\,\partial R/\partial\theta)$ over $\theta \in [0, 2\pi]$ | T·m² | multiplied by $(2\pi)^2$ |
"unit_flux" | $\Phi_x$ itself, as a run records its forcing for replay | T·m² | loaded as is |
File formats
ASCII (forcing_data_format = "ascii"): an optional # normalization: <tag> line, comment lines starting with #, and one n m real(amplitude) imag(amplitude) row per mode; all four columns are required:
# normalization: normal_field_T
1 6 1.0e-4 0.0
1 7 5.0e-5 2.0e-5HDF5 (forcing_data_format = "hdf5"): datasets n, m, amplitude_real and amplitude_imag, all required, with the optional root attribute normalization:
using HDF5
h5open("forcing.h5", "w") do f
f["n"] = [1, 1, 1]
f["m"] = [5, 6, 7]
f["amplitude_real"] = [1e-4, 2e-4, 1e-4]
f["amplitude_imag"] = [0.0, 0.0, 0.0]
HDF5.attrs(f)["normalization"] = "normal_field_T"
endCoils
forcing_data_format = "coil" computes the field from coil geometry: the plasma boundary is sampled on an mtheta_coil × nzeta_coil grid, the Biot–Savart field of every coil set is evaluated there, projected onto the normal flux and Fourier decomposed. The toroidal angle of each observation point includes the straight-field-line offset $\nu(\psi, \theta)$ and the helicity $\mathrm{sign}(B_T)\,\mathrm{sign}(I_p)$ of the equilibrium, without which the decomposition would be wrong. Each [[ForcingTerms.coil_set]] block supplies one coil set, selected by source; shifts and tilts (shiftx/y/z, tiltx/y/z, n_tilt, …) apply to every source, which is what the Error Fields stage sweeps. From examples/DIIID-like_ideal_example/gpec.toml (the first block) and the other sources:
[ForcingTerms]
forcing_data_format = "coil"
machine = "d3d"
mtheta_coil = 480
nzeta_coil = 32
# ASCII .dat file, resolved to {dat_dir}/{machine}_{name}.dat
[[ForcingTerms.coil_set]]
name = "c"
currents = [1000.0, 500.0, -500.0, -1000.0, -500.0, 500.0]
# HDF5 file; `name` selects one set of a multi-set file
[[ForcingTerms.coil_set]]
source = "file"
h5_file = "/path/to/my_coils.h5"
name = "il"
currents = [1e4, 1e4, 1e4, 1e4, 1e4, 1e4]
# Analytic PF hoop; a tilt breaks axisymmetry to give n ≠ 0 forcing
[[ForcingTerms.coil_set]]
source = "pf_hoop"
radius = 1.8
height = 0.9
currents = [5e3]
tiltx = [2.0]
# Analytic window-pane array, by two opposite [R, Z] corners ...
[[ForcingTerms.coil_set]]
source = "window_pane"
n_coils = 8
rz_corners = [[2.2, -0.6], [2.2, 0.6]]
gap_fraction = 0.15
currents = [1e3, -1e3, 1e3, -1e3, 1e3, -1e3, 1e3, -1e3]
# ... or by standoff off the plasma surface at a poloidal angle (degrees)
[[ForcingTerms.coil_set]]
source = "window_pane"
n_coils = 2
standoff = 0.25
poloidal_angle = 0.0
poloidal_length = 1.2
poloidal_tilt = 0.0
gap_fraction = 0.15
currents = [1e4, -1e4]
# Analytic helical array on a circular torus, pitch m_hel/n_hel
[[ForcingTerms.coil_set]]
source = "helical"
R0 = 1.7
a = 0.6
m_hel = 4
n_hel = 1
n_coils = 4
currents = [1e3, 1e3, 1e3, 1e3]A coil HDF5 file stores one subgroup per coil set under a parent group (default coils): <group>/<set>/x, y, z as ncoil × s × nsec Cartesian metres, an optional currents dataset, and the winding multiplier as the attribute nw; convert_coil_dat_to_h5 and convert_coil_h5_to_dat translate the ASCII format, read_coil_h5 and write_coil_h5 read and write it.
The field is linear in the coils, so a CoilForcingGrid built once per equilibrium and n evaluates coil sets one at a time, for comparing coil variants against one plasma without re-sampling the boundary:
forcing_grid = CoilForcingGrid(equil, cfg, n; psi=ffs.psilim)
spectra = [coil_forcing_modes(cs, forcing_grid, n, m_low, m_high) for cs in coil_sets]Outputs
The applied spectrum is written with the response: PerturbedEquilibrium/ForcingModes/ (m, n, amplitude) and the control-surface spectra PerturbedEquilibrium/forcing_b, forcing_b_root_area and forcing_b_area (see Perturbed Equilibrium). A forcing file is captured raw with its tag under Input/RawInputs/ForcingTerms/, and the coil geometry as used, after shifts and tilts, under Input/RawInputs/Coils/, so that main(["gpec.h5"]) can replay the run without the original files; see the Scripting API.
API reference
GeneralizedPerturbedEquilibrium.ForcingTerms.BoundaryGrid — Type
BoundaryGridPre-computed plasma boundary grid for evaluating coil fields.
Fields
mtheta,nzeta: grid dimensionsR,Z: cylindrical coordinates[mtheta](same for all ζ, axisymmetric)phi_grid: base toroidal angle grid[nzeta]in radians =-helicity × 2π × j/nzetaphi_offset: per-θ toroidal angle correction[mtheta]from SFL coordinates:ν(ψ, θ)scaled by-helicity, so the physical toroidal angle at(i, j)isphi_grid[j] + phi_offset[i], as Fortran'sphi = -helicity*(2π*ζ + dphi(ψ,θ))dR_dtheta,dZ_dtheta: poloidal derivatives w.r.t. unit-norm angle θnorm ∈ [0,1] `dRdtheta[i] = dR/dθnorm = 2π × dR/dθphys`
GeneralizedPerturbedEquilibrium.ForcingTerms.CoilConfig — Type
CoilConfigTop-level coil configuration from the [ForcingTerms] TOML section when forcing_data_format = "coil".
Fields
machine: machine name prefix for .dat files (e.g. "d3d")dat_dir: directory containing .dat files; defaults to bundledcoil_geometries/mtheta_coil: poloidal grid resolution for boundary field evaluation (default: 480)nzeta_coil: toroidal grid resolution; 0 = auto (32 × n)coil_sets: parsed[[ForcingTerms.coil_set]]blocks
GeneralizedPerturbedEquilibrium.ForcingTerms.CoilConfig — Method
CoilConfig(ft_ctrl::ForcingTermsControl)Construct a CoilConfig from a ForcingTermsControl populated from TOML.
GeneralizedPerturbedEquilibrium.ForcingTerms.CoilForcingGrid — Type
CoilForcingGridThe plasma-boundary sampling that every coil-field evaluation for one equilibrium and toroidal mode number shares: the BoundaryGrid at the control surface and its observation points laid out in cylindrical (R, φ, Z). Build it once and evaluate any number of coil sets against it with coil_forcing_modes.
Fields
grid::BoundaryGrid- boundary geometry and unit-norm metricobs_R,obs_phi,obs_Z- observation points[mtheta × nzeta], θ-major, with the SFL toroidal offset applied
GeneralizedPerturbedEquilibrium.ForcingTerms.CoilForcingGrid — Method
CoilForcingGrid(equil, cfg, n; psi=equil.rzphi_xs[end])Sample the control surface psi at cfg.mtheta_coil × nzeta points, with nzeta taken from cfg.nzeta_coil or NZETA_POINTS_PER_PERIOD per toroidal period of n. Pass psi = psilim whenever a solve is at hand (see sample_boundary_grid).
GeneralizedPerturbedEquilibrium.ForcingTerms.CoilSet — Type
CoilSetGeometry and current data for a single coil set (one .dat file).
Fields
name: coil set identifier (e.g. "il", "iu")ncoil: number of independent conductorss: sub-systems (strand groups) per conductornw: winding multiplier (turns per conductor element)nsec: number of Cartesian points per strandx,y,z: conductor coordinates[ncoil, s, nsec]in meters (Cartesian)currents: current per conductor[ncoil]in Amperes
GeneralizedPerturbedEquilibrium.ForcingTerms.CoilSetConfig — Type
CoilSetConfigPer-coil-set configuration from a [[ForcingTerms.coil_set]] TOML block.
A coil set comes from one of several sources, selected by source:
""or"file": read a geometry file —.dat(legacy ASCII) or.h5(modern), chosen by extension. The file path comes fromdat_file/h5_fileor themachine+nameconvention."pf_hoop": an analytic horizontal circular loop (radius,height)."window_pane": an analytic rectangular picture-frame array, placed EITHER by explicit corners (rz_corners) OR by physical standoff from the plasma surface (standoff,poloidal_angle,poloidal_length,poloidal_tilt); shared toroidal layout vian_coils,gap_fraction,phi0."helical": an analytic helical array on a circular cross-section torus (R0,a,m_hel,n_hel,theta_lo,theta_hi,n_coils,gap_fraction,phi0,offset).
Shifts/tilts apply to every source (the analytic geometry is built first, then transformed).
Fields
name: coil set name; resolves to{dat_dir}/{machine}_{name}.dat, or selects a set by name from a multi-set.h5filesource: coil source discriminator (see above); empty/"file"reads a geometry filedat_file: explicit path to .dat file (overridesmachine+nameconvention)h5_file: explicit path to .h5 file (multi-set;nameselects which set, else the sole set)currents: current [A] per conductor[ncoil]; shorter arrays pad with zerosshiftx,shifty,shiftz: per-conductor translation [m][ncoil]tiltx,tilty,tiltz: per-conductor tilt in degrees (or meters iftilt_in_meters)rotation_center_x,rotation_center_y,rotation_center_z: explicit rotation center [m]; defaults to arc-length-weighted center of massn_tilt: toroidal mode number for tilt/shift modulation; -1 means inherit run's ntilt_in_meters: interpret tilt as displacement [m] instead of angle [degrees]
Analytic-source parameters (used only for the matching source):
radius,height: PF hoop circle radius and Z height [m]rz_corners: window-pane cross-section as two opposite[R, Z]corners in m (corner mode)gap_fraction: toroidal gap between adjacent coils as a fraction of their spacingphi0: toroidal angle offset of the first generated coil [rad]R0,a: helical torus major radius and minor (circle) radius [m]m_hel,n_hel: helical poloidal/toroidal mode numbers setting the pitchtheta_lo,theta_hi: helical poloidal extent in degrees; a full turn whentheta_hi-theta_lo == 360n_coils: number of coils in a generated window-pane or helical arrayoffset: helical coil radial offset from the torus surface [m]points_per_coil: optional override of the generated point count per coil
Window-pane standoff placement (alternative to rz_corners; needs an equilibrium):
standoff: outward-normal distance from the control surface to the frame center [m]poloidal_angle: cylindrical poloidal angle of the frame center, in degreespoloidal_length: poloidal leg span (corner-to-corner) along the surface tangent [m]poloidal_tilt: extra tilt of the legs in degrees; 0 means tangential to the surface
GeneralizedPerturbedEquilibrium.ForcingTerms.ForcingMode — Type
ForcingModeData structure for a single forcing mode.
Fields
n::Int- Toroidal mode numberm::Int- Poloidal mode numberamplitude::ComplexF64- Complex amplitude in unit-norm convention (= Fortran Phi_x, T·m² per unit-norm cell) after loading. File inputs are tagged by their input convention:"normal_field_T": B·n̂ in Tesla (2π-angle); converted to unit-norm on load"sfl_flux_Wb": SFL flux in 2π-angle convention; multiplied by (2π)² on load"unit_flux": already unit-norm (a run's materialized forcing, recorded for replay); loaded as is
GeneralizedPerturbedEquilibrium.ForcingTerms.ForcingTermsControl — Type
ForcingTermsControlUser-facing control parameters from TOML [ForcingTerms] section. A deck run resolves its relative file paths against the deck directory; a script's resolve against the working directory.
Fields
Forcing Data:
forcing_data_file::String- Path to forcing data file (n, m, complex amplitude)forcing_data_format::String- Format: "ascii", "hdf5", or "coil"
Coil settings (used when forcing_data_format = "coil"):
machine::String- Machine name prefix for .dat files (e.g. "d3d")dat_dir::String- Directory containing .dat files; defaults to bundledcoil_geometries/mtheta_coil::Int- Poloidal grid resolution for boundary field evaluation (default: 480)nzeta_coil::Int- Toroidal grid resolution; 0 = auto (32 × n)coil_sets_raw::Vector{Dict{String,Any}}- Parsed[[ForcingTerms.coil_set]]TOML blocks
GeneralizedPerturbedEquilibrium.ForcingTerms.PrecomputedSegments — Type
PrecomputedSegmentsPre-computed segment vectors, lengths and start points for one conductor strand, stored in contiguous arrays for cache-friendly access in the inner Biot-Savart loop.
GeneralizedPerturbedEquilibrium.ForcingTerms.RMPField — Type
RMPFieldAbstract supertype of every external-forcing description the scripting API accepts: a resonant-magnetic-perturbation field, described by where it comes from and how strongly it drives (a forcing-mode file, a coil set with currents, or a precomputed spectrum).
Construction checks the description and throws an ArgumentError naming the problem: a forcing file must exist and parse as a mode table with a known normalization, and every coil set must resolve to geometry and carry currents. The modes are materialized against an equilibrium only when the perturbed-equilibrium stage runs, so one RMPField can drive several solves.
Construction
RMPField(path; format=..., scale=1.0, kwargs...)
RMPField(coil_sets; scale=1.0, kwargs...)
RMPField(ctrl::ForcingTermsControl; scale=1.0)
RMPField(modes::Vector{ForcingMode}; scale=1.0)The first form points at a forcing-mode file, format defaulting to "hdf5" for an .h5 or .hdf5 extension and "ascii" otherwise. The second form takes one coil set or a vector of them, each a NamedTuple or Dict with the [[ForcingTerms.coil_set]] keys, and selects the coil format:
RMPField((name="c", currents=[1e3, 500, -500, -1e3, -500, 500]); machine="d3d") # the DIII-D C-coil, in amperes
RMPField([(name="iu", currents=iu), (name="il", currents=il)]; machine="d3d")
RMPField((source="pf_hoop", radius=12.0, height=1.2, currents=[2e3]))Remaining kwargs are ForcingTermsControl fields. These three return a single-source leaf (RMPSource). The last form takes a control-surface spectrum computed elsewhere, already in the unit-norm Φ_x convention, and returns a spectrum-literal leaf (RMPSpectrum).
Algebra
+, - and multiplication by a real or complex scalar (a complex factor phase-rotates the perturbation) build lazy linear combinations. The response is linear in the forcing, so each term is materialized on the control surface and the mode amplitudes are summed.
nominal = RMPField("nominal_efc.dat")
weld_field = RMPField("weld_fields.h5"; scale=0.5)
total = 2.0 * nominal + weld_field # lazy: records terms and weights, computes nothing
pe = perturbed_equilibrium(plasma_response(ffs), total) # materializes each term, sums, drives PEPhysical amplitude lives in the forcing description (per-conductor currents for coils, ForcingMode.amplitude for files). scale is NOT a physical amplitude: it is the source's weight in a linear combination, applied uniformly to the materialized spectrum of every toroidal mode. A source that is not a scalar multiple of another needs its own description: a coil set with a failed conductor is nominal - failed_coil, not 0.9 * nominal.
GeneralizedPerturbedEquilibrium.ForcingTerms.RMPFieldSum — Type
RMPFieldSumA lazy linear combination of RMPSource and RMPSpectrum leaves, built by +/- on RMPFields. Holds the flattened term list; scalar multiplication distributes onto the leaves. Materialization evaluates each term against the equilibrium and sums the mode amplitudes — valid because the perturbed-equilibrium response is linear in the forcing.
Fields
terms::Vector{Union{RMPSource,RMPSpectrum}}- The flattened weighted leaves.
GeneralizedPerturbedEquilibrium.ForcingTerms.RMPSource — Type
RMPSourceA single-source RMPField leaf: one forcing description plus a complex weight. Built by the RMPField constructors; scalar multiplication rescales the weight.
Fields
ctrl::ForcingTermsControl- The forcing source: format, file path or machine, and the raw coil-set blocks.scale::ComplexF64- The source's weight in a linear combination, applied to the materialized control-surface spectrum (complex = phase rotation). Not a physical amplitude.
GeneralizedPerturbedEquilibrium.ForcingTerms.RMPSpectrum — Type
RMPSpectrumA spectrum-literal RMPField leaf: control-surface forcing modes computed elsewhere, in the unit-norm Φ_x convention the response consumes, plus a complex weight. Built by RMPField(modes::Vector{ForcingMode}); scalar multiplication rescales the weight.
Fields
modes::Vector{ForcingMode}- The control-surface spectrum, copied at construction.scale::ComplexF64- The leaf's weight in a linear combination, as forRMPSource.
GeneralizedPerturbedEquilibrium.ForcingTerms._accumulate_precomputed — Method
_accumulate_precomputed(ox, oy, oz, seg) -> (dbx, dby, dbz)Sum the exact segment fields of one PrecomputedSegments strand at (ox, oy, oz), scaled by its prefactor.
GeneralizedPerturbedEquilibrium.ForcingTerms._arc_length_center — Method
_arc_length_center(x, y, z) -> (x0, y0, z0)Compute the arc-length-weighted centroid of a strand (1D array of points). Matches Fortran center-of-mass convention using midpoints weighted by segment length.
GeneralizedPerturbedEquilibrium.ForcingTerms._build_raw_coil_set — Method
_build_raw_coil_set(cfg::CoilConfig, sc::CoilSetConfig; equil=nothing) -> CoilSetProduce the un-transformed coil set for a config block, dispatching on sc.source: analytic generators (pf_hoop/window_pane/helical) or a geometry file (.h5 → read_coil_h5, else .dat → read_coil_dat). Currents and shifts/tilts are applied by the caller, so all sources share the same downstream path.
GeneralizedPerturbedEquilibrium.ForcingTerms._infer_format — Method
_infer_format(path) -> StringForcing-data format implied by a file extension: "hdf5" for .h5/.hdf5, else "ascii".
GeneralizedPerturbedEquilibrium.ForcingTerms._resolve_coil_path — Method
_resolve_coil_path(cfg::CoilConfig, set_cfg::CoilSetConfig) -> StringResolve the path to a coil geometry file. Prefers set_cfg.h5_file, then set_cfg.dat_file, otherwise constructs {dat_dir}/{machine}_{name}.dat.
GeneralizedPerturbedEquilibrium.ForcingTerms._rmp_terms — Method
Flattened weighted-leaf list of any RMPField.
GeneralizedPerturbedEquilibrium.ForcingTerms._segment_field — Method
_segment_field(rx, ry, rz, dlx, dly, dlz, len) -> (bx, by, bz)Exact field of a straight unit-current filament segment of vector dl⃗ and length len, without the μ₀/4π prefactor, at displacement r⃗ from the segment start (Hanson & Hirshman 2002, Eq. 8). With ε = Rᵢ + Rf - L, the effective squared distance ρ² = 2RᵢRf ε / (Rᵢ + Rf) reduces to the perpendicular distance squared near the segment, so the contribution is zero for ρ² below `BIOTSAVARTMINDIST_SQ`.
GeneralizedPerturbedEquilibrium.ForcingTerms.accumulate_strand_field! — Method
accumulate_strand_field!(Bx, By, Bz, i, obs_x, obs_y, obs_z, xs, ys, zs, current_nw)Accumulate the Biot-Savart contribution from one conductor strand onto observation point i.
Each straight segment from point l to l+1 contributes its exact filament field, see _segment_field.
Arguments
Bx,By,Bz: pre-allocated output arrays (Cartesian field, Tesla); updated in-placei: observation point indexobs_x/y/z: observer Cartesian coordinates [m]xs,ys,zs: strand point coordinates [nsec], Cartesian [m]current_nw: effective current = I × nw [A⋅turns]
GeneralizedPerturbedEquilibrium.ForcingTerms.apply_transforms — Method
apply_transforms(cs::CoilSet, cfg::CoilSetConfig; n_tilt::Int=1) -> CoilSetApply per-conductor shifts and tilts to a coil set, returning a modified copy.
Port of the Fortran coil_read shift/tilt logic (coil.F):
- Tilts are rotations around the arc-length-weighted center of mass (unless
rotation_center_x/_y/_zspecified) n_tiltcontrols the toroidal periodicity of tilt/shift modulation- n_tilt = 0: rigid shift only (no tilts applied)
- n_tilt ≥ 1: n-fold modulated perturbations
GeneralizedPerturbedEquilibrium.ForcingTerms.coil_forcing_modes — Method
coil_forcing_modes(coil_sets, forcing_grid::CoilForcingGrid, n, m_low, m_high; verbose=false) -> Vector{ForcingMode}Fourier mode amplitudes, in the unit-norm Φ_x convention, of the normal flux that coil_sets — a Vector{CoilSet} or a single CoilSet — drive on the boundary sampled by forcing_grid: threaded Biot-Savart at every observation point, projection onto the boundary normal, then the 2D decomposition for toroidal mode n and m_low:m_high. The field is linear in the coils, so evaluating sets one at a time on the same grid gives each set's own spectrum, and the sum of those is the spectrum of the assembly.
GeneralizedPerturbedEquilibrium.ForcingTerms.compute_biot_savart_boundary! — Method
compute_biot_savart_boundary!(B_R, B_phi, B_Z, obs_R, obs_phi, obs_Z, coil_sets)Compute the total Biot-Savart field from all coil sets at every observation point.
Observation points are specified in cylindrical coordinates (R, φ, Z) and the returned field components are also cylindrical.
Threaded over observation points; strands with zero current are skipped.
Arguments
B_R,B_phi,B_Z: output field arrays [Tesla], lengthnobs; overwrittenobs_R,obs_phi,obs_Z: observation point cylindrical coordinates [m, rad, m]coil_sets: conductor geometry and current data
GeneralizedPerturbedEquilibrium.ForcingTerms.compute_coil_forcing_modes! — Method
compute_coil_forcing_modes!(forcing_modes, coil_sets, equil, cfg, n, m_low, m_high; psi, verbose)Top-level entry point: compute Fourier mode amplitudes of the normal magnetic flux from all coil sets on the plasma boundary — a CoilForcingGrid at psi followed by coil_forcing_modes over the whole assembly in one Biot-Savart pass.
Output amplitudes are in unit-norm convention (= Fortran Phi_x) and drive a plasma response directly. forcing_modes is overwritten with the result.
GeneralizedPerturbedEquilibrium.ForcingTerms.conductors — Method
conductors(cs::CoilSet) -> Vector{CoilSet}Split a coil set into one single-conductor set per conductor, each carrying that conductor's own current and named "<name>_<index>". A set that already holds one conductor is returned unchanged in a one-element vector.
Legacy geometry files often pack several physically separate coils into one file, so comparing against a design that names them separately needs them one at a time. Evaluating a split set costs only its own conductor, where zeroing the other currents would compute and discard their fields.
GeneralizedPerturbedEquilibrium.ForcingTerms.convert_coil_dat_to_h5 — Method
convert_coil_dat_to_h5(dat_path, h5_path; group="coils") -> StringConvert a legacy ASCII .dat coil file to the modern HDF5 format (single set).
GeneralizedPerturbedEquilibrium.ForcingTerms.convert_coil_h5_to_dat — Method
convert_coil_h5_to_dat(h5_path, dat_path; group="coils", set=nothing) -> StringConvert one coil set from an HDF5 file to a legacy ASCII .dat file. If the file holds multiple sets, set selects which one by name (required when more than one is present).
GeneralizedPerturbedEquilibrium.ForcingTerms.convert_forcing_normalization — Method
convert_forcing_normalization(modes, from_tag, equil, n, m_out; psi, mtheta) -> Vector{ForcingMode}Convert ForcingMode amplitudes from from_tag normalization to the internal unit-norm convention (= Fortran Phi_x) that perturbed_equilibrium applies the plasma response to.
If from_tag == "sfl_flux_Wb", the user has provided amplitudes in the 2π-angle SFL-flux convention. These are scaled by (2π)² to reach unit-norm, keeping their harmonics.
If from_tag == "normal_field_T", the amplitudes represent Fourier modes of B·n̂ in Tesla (2π-angle convention). Conversion to unit-norm Phi_x:
- Inverse-Fourier reconstruct B·n̂(θ) from every harmonic in the file
- Multiply pointwise by the area weight J|∇ψ| (
Equilibrium.compute_jac_delpsi) - Fourier transform onto every harmonic in
m_out
This conversion is a mode-mixing operation because J|∇ψ| varies poloidally, so the flux has sidebands beyond the file's own harmonics; m_out should be the run's full range. Each output harmonic is an exact projection of the full product, so a file wider than m_out loses nothing. The θ grid is widened past mtheta when the harmonics would otherwise alias.
The file's spectrum is itself a truncation of the true field, and the missing harmonics would mix into m_out too. Following the last-coefficient rule of thumb for spectral series (Boyd, Chebyshev and Fourier Spectral Methods), the first missing harmonic is taken to be comparable to the last one kept, so the flux each edge harmonic drives estimates what the truncation loses. A warning is issued when that exceeds truncation_tol of the total flux. Files with fewer than three harmonics have no edge to judge and are not checked.
Arguments
modes:Vector{ForcingMode}of one toroidal moden(not modified)from_tag: source normalization —"normal_field_T","sfl_flux_Wb", or"unit_flux"for modes already in the unit-norm Φ_x convention the response consumes (a run's materialized forcing, recorded for replay)equil:PlasmaEquilibriumproviding boundary geometryn: toroidal mode numberm_out: poloidal harmonics of the converted fluxpsi: flux surface for boundary geometry (defaultequil.rzphi_xs[end])mtheta: minimum θ grid resolution for the conversion (default 256)truncation_tol: relative flux change from one edge harmonic that triggers the warning
GeneralizedPerturbedEquilibrium.ForcingTerms.fourier_decompose_bn — Method
fourier_decompose_bn(bn, grid, n, m_low, m_high) -> Vector{ForcingMode}2D Fourier decompose bn[mtheta, nzeta] to extract mode amplitudes for toroidal mode number n and poloidal range m_low:m_high.
Coefficients are computed as: bmn = (2 / (mtheta × nzeta)) × Σ_{i,j} bn[i,j] × exp(-i(m×θᵢ - n×ζⱼ))
The factor 2 matches the GPEC/DCON convention for real signals where positive and negative m modes are related by conjugation.
When called after project_normal_flux!, the returned amplitudes are in unit-norm convention equal to Fortran Phi_x (T·m² per unit-norm cell).
GeneralizedPerturbedEquilibrium.ForcingTerms.load_coil_sets — Method
load_coil_sets(cfg::CoilConfig, n_tilt::Int; equil=nothing) -> Vector{CoilSet}Build all coil sets from config (file or analytic source), apply currents and shifts/tilts, and return ready-to-use coil data. n_tilt is the toroidal mode number for modulated perturbations (typically the run's n). equil is required only when a window_pane set uses standoff placement (it locates the surface point and normal).
GeneralizedPerturbedEquilibrium.ForcingTerms.load_coils_from_h5_group! — Method
load_coils_from_h5_group!(coil_sets::Vector{CoilSet}, group) -> Vector{CoilSet}Populate coil_sets from an already-open HDF5 group, reading every subgroup that holds x/y/z datasets as a CoilSet. Any other datasets or subgroups under group are silently ignored, so the group may live inside a larger file (e.g. gpec.h5). Mirror of save_coils_to_h5.
GeneralizedPerturbedEquilibrium.ForcingTerms.load_forcing_ascii! — Method
load_forcing_ascii!(forcing_modes, filepath, verbose) -> StringLoad forcing data from ASCII file. Returns normalization tag ("normal_field_T" by default).
Optional first # normalization: <tag> header line sets the normalization. Remaining #-prefixed lines and blank lines are ignored. Data columns: n, m, amplitudereal, amplitudeimag.
GeneralizedPerturbedEquilibrium.ForcingTerms.load_forcing_data! — Function
load_forcing_data!(forcing_modes, filepath, forcing_data_format, verbose=false) -> StringLoad forcing data from ASCII or HDF5 file. Returns the normalization tag read from the file (or "normal_field_T" by default if no tag is present).
Normalization tags (set in the file, not in the TOML):
"normal_field_T"(default): Fourier modes of B·n̂ [Tesla], 2π-angle convention; converted to unit-norm (Phi_x) on load."sfl_flux_Wb": SFL flux R×(BR·∂Z/∂θ - BZ·∂R/∂θ) [T·m²], 2π-angle convention. Multiplied by (2π)² on load to reach unit-norm (Phi_x)."unit_flux": already unit-norm (Phi_x), as a run records its materialized forcing for replay; loaded as is.
ASCII format — optional # normalization: <tag> header line, then data rows:
# normalization: normal_field_T
1 2 0.5 0.1
1 3 0.3 -0.2Columns: n, m, amplitudereal, amplitudeimag
HDF5 format — optional root attribute normalization (string), plus datasets:
"n": Integer array of toroidal mode numbers"m": Integer array of poloidal mode numbers"amplitude_real": Real parts of amplitudes"amplitude_imag": Imaginary parts of amplitudes
GeneralizedPerturbedEquilibrium.ForcingTerms.load_forcing_from_h5_group! — Method
load_forcing_from_h5_group!(forcing_modes::Vector{ForcingMode}, group) -> StringPopulate forcing_modes from an already-open HDF5 group (or file root) with datasets n, m, amplitude_real, amplitude_imag, and return its normalization attribute ("normal_field_T" when absent). Mirror of save_forcing_to_h5, shared by the forcing-file reader and the rerun path that reads gpec.h5/Input/RawInputs/ForcingTerms/.
GeneralizedPerturbedEquilibrium.ForcingTerms.load_forcing_hdf5! — Method
load_forcing_hdf5!(forcing_modes, filepath, verbose) -> StringLoad forcing data from HDF5 file. Returns normalization tag ("normal_field_T" by default).
Optional root attribute normalization (string) sets the normalization. Required datasets: n, m, amplitude_real, amplitude_imag.
GeneralizedPerturbedEquilibrium.ForcingTerms.make_helical — Method
make_helical(; R0, a, m, n, theta_lo=0.0, theta_hi=360.0, n_coils,
gap_fraction=0.0, phi0=0.0, offset=0.0, npts=720,
name="helical") -> CoilSetBuild an array of n_coils analytic helical coils wound on a circular cross-section torus of major radius R0 and minor radius a [m], offset radially outward by offset [m]. The helical pitch is set by the poloidal/toroidal mode numbers m/n via ζ = (m/n)·θ + φ.
The poloidal extent theta_lo/theta_hi is in degrees. For a full poloidal turn (theta_hi - theta_lo == 360) each coil is a single helical strand. For a partial poloidal range the coil is closed into a loop with two helical legs joined by toroidal arcs (matching OMFIT form_helical_array.py). npts sets the strand resolution. Currents are zeroed; load_coil_sets fills them.
GeneralizedPerturbedEquilibrium.ForcingTerms.make_pf_hoop — Method
make_pf_hoop(; radius, height, nsec=361, name="pf_hoop") -> CoilSetBuild a single horizontal circular loop (PF hoop) of radius [m] centered on the machine axis at vertical position height [m], discretized into nsec points.
The loop is closed (point nsec coincides with point 1). A bare hoop is axisymmetric and produces only an n=0 field; tilting or shifting it (via apply_transforms) breaks axisymmetry to produce n≠0 forcing. Currents are zeroed; load_coil_sets fills them.
GeneralizedPerturbedEquilibrium.ForcingTerms.make_window_pane — Method
make_window_pane(; ncoil, rz_corners, gap_fraction=0.0, phi0=0.0,
np_pol=20, np_tor=40, name="window_pane") -> CoilSetBuild an array of ncoil rectangular "picture-frame" (window-pane) saddle coils, evenly spaced toroidally. The two [R, Z] points in rz_corners are the endpoints of the poloidal legs; the legs run along the straight segment between them at the two toroidal edges of the coil, joined by toroidal arcs at each corner. For a vertical frame give the two corners the same R (legs run in Z); for a horizontal frame give them the same Z. Adjacent coils are separated by a toroidal gap of gap_fraction times their angular spacing; the first coil is centered at toroidal angle phi0 [rad].
Each coil is a closed loop with np_pol points per poloidal leg and np_tor per toroidal arc. Currents are zeroed; load_coil_sets fills them.
GeneralizedPerturbedEquilibrium.ForcingTerms.make_window_pane_standoff — Method
make_window_pane_standoff(equil; standoff, poloidal_angle, poloidal_length,
poloidal_tilt=0.0, ncoil, gap_fraction=0.0, phi0=0.0,
name="window_pane") -> CoilSetBuild a window-pane array placed by physical standoff instead of explicit corners. The frame center sits standoff [m] along the outward surface normal at cylindrical poloidal_angle (degrees); its poloidal legs span poloidal_length [m] along the surface tangent, rotated by poloidal_tilt (degrees, 0 = tangential). The control surface is the boundary equil.rzphi_xs[end]. Toroidal layout (ncoil, gap_fraction, phi0) and the leg/arc construction are delegated to make_window_pane.
The poloidal legs wind in the same sense as make_window_pane's c1 -> c2 ordering (lower-Z to higher-Z at the outboard midplane), so positive current produces positive b_n_x near the coil, matching the corner-built window pane.
GeneralizedPerturbedEquilibrium.ForcingTerms.nominal_major_radius — Method
nominal_major_radius(x, y, z) -> Float64
nominal_major_radius(cs::CoilSet) -> Float64Arc-length-weighted major radius √(x²+y²) of a strand, or of every strand of a coil set: the radius through which a rim displacement in metres converts to a tilt angle, asin(t / R_nom), as apply_transforms does for tilt_in_meters. A strand with no length returns 1.
GeneralizedPerturbedEquilibrium.ForcingTerms.precompute_segments — Method
precompute_segments(cs, j, k, current_nw) → PrecomputedSegmentsBuild contiguous segment-vector, length and start-point arrays for strand (j,k) of coil set cs.
GeneralizedPerturbedEquilibrium.ForcingTerms.project_normal_flux! — Method
project_normal_flux!(bn, B_R, B_Z, grid)Project the cylindrical magnetic field (BR, BZ) onto the plasma boundary normal direction ∇ψ and store in bn[mtheta, nzeta].
Computes the unit-norm flux element Phix per (θnorm, ζnorm) cell [T·m²]: bn(θnorm, ζnorm) = 2π × R(θnorm) × (BR × ∂Z/∂θnorm - BZ × ∂R/∂θnorm)
The 2π factor comes from the toroidal Jacobian ∂r/∂ζnorm = 2π·R·êφ in the cross-product ∂r/∂θnorm × ∂r/∂ζnorm. The derivatives dR/dθnorm and dZ/dθnorm are stored in grid.dR_dtheta and grid.dZ_dtheta (unit-norm convention from sample_boundary_grid).
The output matches Fortran GPEC's Phi_x convention directly (no extra factor needed).
Arguments
bn: output array[mtheta, nzeta]; overwritten in-placeB_R,B_Z: cylindrical field components, lengthmtheta × nzeta(flat, θ-major)grid: pre-computed boundary geometry fromsample_boundary_grid
GeneralizedPerturbedEquilibrium.ForcingTerms.read_coil_dat — Method
read_coil_dat(filepath::String) -> CoilSetParse an ASCII coil geometry file.
Format:
ncoil s nsec nw
X₁ Y₁ Z₁
X₂ Y₂ Z₂
...Data rows are ordered: for each conductor 1:ncoil, for each sub-system 1:s, read nsec points. Coordinates are Cartesian in meters (lab frame).
GeneralizedPerturbedEquilibrium.ForcingTerms.read_coil_h5 — Method
read_coil_h5(filepath; group="coils", set=nothing) -> Vector{CoilSet}Read coil sets from an HDF5 file. Coil data is expected under the group path; all coil-set subgroups there are returned (or, if set names one, just that set). Unrelated content elsewhere in the file is ignored. See save_coils_to_h5 for the layout.
GeneralizedPerturbedEquilibrium.ForcingTerms.reconstruct_bn — Method
reconstruct_bn(amplitudes, m_modes, n_modes; ntheta=256, nzeta=180, theta_range=(-pi, pi)) -> (; theta, zeta, bn)
reconstruct_bn(modes::AbstractVector{ForcingMode}; kwargs...) -> (; theta, zeta, bn)Evaluate the real normal-flux pattern bn(θ, ζ) of a spectrum on an arbitrary angular grid, inverting the basis of fourier_decompose_bn:
bn(θ, ζ) = Re Σ_k amplitudes[k] × exp(+i(m_k×θ - n_k×ζ))The real part rather than a sum over ±m is what the decomposition's factor of 2 already accounts for: each retained (m, n) stands for itself and its conjugate partner (-m, -n).
theta_range defaults to (-π, π) so the outboard midplane falls in the middle of a map rather than being cut in half at its edges. The grid is independent of the one the spectrum was measured on, so a coarse decomposition can still be drawn smoothly.
GeneralizedPerturbedEquilibrium.ForcingTerms.sample_boundary_grid — Method
sample_boundary_grid(equil, mtheta, nzeta; psi=equil.rzphi_xs[end]) -> BoundaryGridEvaluate the plasma geometry on a uniform mtheta × nzeta grid on the flux surface psi, from the equil.rzphi_rsquared, rzphi_offset and rzphi_nu splines. dR/dθnorm and dZ/dθnorm (θ_norm ∈ [0,1]) come from periodic cubic splines of R and Z.
The default psi is the outermost computed surface psihigh, the last knot of the geometry splines; ψN = 1 would extrapolate them and can drive `rzphirsquarednegative. The physical control surface ispsilim(Fortran evaluates the coil field there,fieldbspsi), which lies insidepsihighwhen edge truncation fires: passpsi = psilim` whenever a ForceFreeStates solve is at hand, as the production paths do.
Toroidal grid direction (Fortran GPEC convention): phi_j = -helicity × 2π × j/nzeta, with helicity = sign(Bt) × sign(Ip) from equil.params.bt_sign and equil.params.ip_sign.
GeneralizedPerturbedEquilibrium.ForcingTerms.save_coils_to_h5 — Method
save_coils_to_h5(coil_sets::Vector{CoilSet}, group)Write each coil set as a subgroup (named by CoilSet.name) under an already-open HDF5 group. Inverse of load_coils_from_h5_group!. Used by the gpec.h5 snapshot writer so a coil run can be replayed from the output file alone.
GeneralizedPerturbedEquilibrium.ForcingTerms.save_forcing_to_h5 — Method
save_forcing_to_h5(forcing_modes::Vector{ForcingMode}, group; normalization="normal_field_T")Write forcing modes to an open HDF5 group (or file root) in the layout load_forcing_hdf5! consumes: datasets n, m, amplitude_real, amplitude_imag and the normalization attribute. Used by the gpec.h5 snapshot writer so the replay path can re-read forcing data from the output file with no reference to the original ASCII/HDF5 ingest file.
GeneralizedPerturbedEquilibrium.ForcingTerms.snapshot_forcing_modes — Method
snapshot_forcing_modes(ft_ctrl; verbose=false) -> Union{Nothing,Tuple{Vector{ForcingMode},String}}The raw file-based forcing modes of ft_ctrl and their normalization tag, so they land in Input/RawInputs/ForcingTerms/ alongside the TOML blob; nothing for coil forcing, which is recomputed from the [[coil_set]] TOML blob on replay. They feed only the writer: the PE stage reads and normalizes the forcing file itself.
GeneralizedPerturbedEquilibrium.ForcingTerms.surface_point_and_normal — Method
surface_point_and_normal(equil, theta_cyl; psi=equil.rzphi_xs[end]) -> (R, Z, nR, nZ)Locate the control-surface point at cylindrical poloidal angle theta_cyl (radians) and return it with the outward unit normal (nR, nZ) in the R-Z plane.
The flux-surface splines are parametrized by the SFL angle theta_sfl, related to the cylindrical angle by theta_cyl = 2π*(theta_sfl + rzphi_offset(psi, theta_sfl)). Since the offset is a small smooth perturbation, theta_sfl is recovered by fixed-point iteration. The tangent is taken by central-differencing R(theta_sfl), Z(theta_sfl), and the normal (dZ/dθ, -dR/dθ) is normalized and oriented outward (positive dot with (R-ro, Z-zo)), matching the normal-flux convention of project_normal_flux!.
GeneralizedPerturbedEquilibrium.ForcingTerms.write_coil_dat — Method
write_coil_dat(filepath, cs::CoilSet)Write a single coil set to an ASCII .dat file in the legacy Fortran GPEC format (ncoil s nsec nw header, then ncoil×s×nsec rows of X Y Z).
GeneralizedPerturbedEquilibrium.ForcingTerms.write_coil_h5 — Method
write_coil_h5(filepath, coil_sets; group="coils")Write coil_sets to a new HDF5 file under the group path, one subgroup per set. Convenience file-level wrapper around save_coils_to_h5 for export and the .dat→.h5 converter.