Scripting API
A deck runs through GeneralizedPerturbedEquilibrium.main; the scripting API exposes the same stages as Julia functions, so a run can be built, parameterized and looped over without a deck, and a deck can never take a path a script cannot. Every stage is a solve of a problem type with an algorithm, or a function on the previous stage's result; nothing is written until save_to_hdf5 is called.
using GeneralizedPerturbedEquilibrium
eq = PlasmaEquilibrium("input.geqdsk"; jac_type="hamada", kinetic_file="kinetic.h5")
ffs = solve(eq, Forward(); nn=1, delta_mlow=8, delta_mhigh=8, vac_flag=true) # [ForceFreeStates]: Forward, no wall, for the response below
ls = solve(LocalStabilityProblem(eq; alpha_boundary_scan=true), Ballooning()) # [LocalStability]
resp = plasma_response(ffs; compute_singular_coupling=true) # [PerturbedEquilibrium]
pe = perturbed_equilibrium(resp, RMPField("coils.dat")) # with the [ForcingTerms] drive
kf = kinetic_torque(pe, KineticForcesControl()) # [KineticForces]
ef = error_fields(resp, pe.coil_sets, ForcingTerms.CoilConfig(ft_ctrl); # [ErrorFields]; ft_ctrl: the [ForcingTerms] control
tolerances=ErrorFields.read_tolerance_toml("tolerances.toml"))
tear = solve(TearingProblem(ffs), SLAYERModel(); config=TearingConfig()) # [Tearing]
save_to_hdf5("gpec.h5", ffs; local_stability=ls)
foreach(r -> save_to_hdf5("gpec.h5", r), (pe, kf, ef, tear))solve(eq, alg; kwargs...) is sugar for the problem form solve(ForceBalanceProblem(eq; kwargs...), alg): the problem names what is solved (the force-balance equation on this equilibrium, with this mode range, wall and closure) and the algorithm names how. main translates each deck section into the problem, algorithm or control it names, calls these functions for every section present, saves each result into [Run] output_file, and returns (; equil, local_stability, ffs, match, resp, pe, kinetic, error_fields, tearing), each nothing when its section is absent.
| Stage | Deck section | Call | Result |
|---|---|---|---|
| Equilibrium | [Equilibrium] (or [Solovev], [LargeAspectRatio], [TJAnalytic]) | PlasmaEquilibrium(file; kwargs...), PlasmaEquilibrium(config), PlasmaEquilibrium(dd) | PlasmaEquilibrium |
| ForceFreeStates | [ForceFreeStates] + [Forward], [Riccati] or [Galerkin] | solve(ForceBalanceProblem(eq; ...), Forward() | Riccati() | Galerkin()) | ForceFreeStatesResult |
| LocalStability | [LocalStability] + [Ballooning] | solve(LocalStabilityProblem(eq; ...), Ballooning(; ...)) | LocalStabilityResult |
| Match | [Match] + [GGJ] | solve(MatchProblem(ffs; ...), GGJModel()) | ForceFreeStatesResult with closure == :matched |
| Drive | [ForcingTerms] | RMPField(ft_ctrl) (a ForcingTermsControl), RMPField(file), RMPField(modes) | RMPField |
| PerturbedEquilibrium | [PerturbedEquilibrium] | plasma_response(ffs; ...), then perturbed_equilibrium(resp, rmp; ...) | PlasmaResponse, PerturbedEquilibriumState |
| KineticForces | [KineticForces] | kinetic_torque(pe, KineticForcesControl(; ...)) | KineticForcesResult |
| ErrorFields | [ErrorFields] | error_fields(resp, pe.coil_sets, CoilConfig(...); ...) | ErrorFieldsResult |
| Tearing | [Tearing] + [SLAYER] or [GGJ] | solve(TearingProblem(ffs; ...), SLAYERModel() | GGJModel(); config=TearingConfig(...)) | TearingResult |
The Workflow page describes what each stage computes; the module pages document the keywords, which are the deck keys of the matching section.
Inspecting a result
Each result prints a short summary at the REPL: its headline numbers, which optional products it carries and, when one is missing, why. Arrays are summarized by size or range, never printed. Inside a container, such as the named tuple main returns, a result prints on one line.
julia> ffs
ForceFreeStatesResult Riccati, ideal closure
Physics ideal MHD
Modes n = 1, m = -4:3 (8 total)
Domain ψ ∈ [0.0001, 0.9995], q_lim = 3.262
Surfaces 2: 2/1 @ ψ = 0.1221, 3/1 @ ψ = 0.8804
Fixed boundary 8 crit sign changes (unvalidated, not a stability verdict)
Free boundary stable: et₁ = 16.4, ep₁ = 14.04, ev₁ = 2.365, vacuum λ = 2.315
Δ′_ii (ψ_N) 2/1: 0.1781, 3/1: -317.9
Solution ξ profiles stored (448 ψ nodes, el_axis basis)
Wall ConformalWall, standoff = 0.2415 a
Plots 14 of 15 available (see available_plots)The fields themselves are documented in each type's docstring.
Plotting a result
Every plot in Analysis takes the result in memory or the path of the gpec.h5 it was saved to, and draws with the Makie backend the session has loaded (using CairoMakie or using GLMakie). available_plots lists the plots for a result, a path, or the named tuple main returns, and for each one the run cannot draw, what to change:
julia> available_plots(ffs)
Plots for ForceFreeStatesResult (riccati): 14 of 15 available
ForceFreeStates
✓ plot_ffs_summary the stability panels the run supplies
✓ plot_critical_determinant critical determinant against ψ_N
⋮
✗ plot_cond_fbar needs the kinetic singular-surface scan: run with a kinetic source and singfac_min > 0
⋮A plot the source cannot draw throws an ArgumentError with the same reason, and a summary leaves out the panels it cannot draw:
plot_ffs_summary(ffs) # the result in memory
plot_ffs_summary("gpec.h5") # or the file to which it was savedSaving and rerunning
save_to_hdf5(target, result) saves any stage result; target is a path, which opens or creates the file, or an open HDF5 file or group, which stays owned by the caller. Each save records in Input/gpec_toml_raw the deck sections that state the problem, algorithm and controls the result was computed with, so a script run's file replays like a deck run's:
./gpec gpec.h5 # main(["gpec.h5"]) in Julia
./gpec gpec.h5 --coil-source coilsA coil run is replayed either from the stored deck coil configuration (--coil-source forcing-modes, the default, which needs the original geometry files) or from the coil geometry stored under Input/RawInputs/Coils/ (--coil-source coils, which needs no original files and allows the equilibrium to be overridden). A forcing file is replayed from its raw contents under Input/RawInputs/ForcingTerms/, and a forcing no deck can state (a weighted field, a spectrum or a sum) from the control-surface modes the save records.
Equilibrium and kinetic profiles
Analytic equilibria take their parameters from a config object, with the eq_type implied, and IMAS equilibria from a data dictionary:
eq = PlasmaEquilibrium(Equilibrium.SolovevConfig(; elongation=1.5); mpsi=0)
eq = PlasmaEquilibrium(dd; imas_cocos=11)Every equilibrium remembers its source, so with mpsi=0 solve re-forms it on the refined two-pass grid the deck uses; Equilibrium.reform(eq, psi_nodes) re-forms it on any grid. The kinetic_file (and, for HDF5, kinetic_group) keyword reads the kinetic profiles once into equil.kinetic, from which every kinetic stage derives its view; Equilibrium.attach_kinetic_profiles! attaches a file or an in-memory KineticProfileData to an equilibrium built without one.
Combining forcing sources
RMPFields form a vector space: +, - and scalar * build lazy linear combinations that compute nothing until perturbed_equilibrium materializes them, and because the response is linear in the forcing, driving with a combination equals combining the materialized fields; a complex scalar phase-rotates a source.
nominal = RMPField("nominal_efc.dat")
weld_field = RMPField("weld_fields.h5")
pe = perturbed_equilibrium(resp, 2.0 * nominal + 0.5 * weld_field)This is the substrate for error-field workflows: build per-unit sources (a coil set per ampere, a displacement field per millimetre), then assemble physical cases by weighting and summing, with one plasma_response serving every combination. RMPField(modes) wraps a control-surface spectrum computed elsewhere, in the unit-norm $\Phi_x$ convention, as a leaf. The weights are linear-combination coefficients, not physical amplitudes: a coil set with a failed conductor is nominal - failed_coil, not 0.9 * nominal.
Choosing an integrator
The second argument of solve picks the formalism and its fields are that formalism's numerical settings; physical inputs belong on ForceBalanceProblem:
ffs = solve(eq, Forward(; eulerlagrange_tolerance=1e-8); nn=1, vac_flag=true) # dense ξ profiles: the only input plasma_response accepts; kinetic solves
ffs = solve(eq, Riccati(; nchunks=40); nn=1, vac_flag=true) # chunked propagators, Δ′ matrix (default)
ffs = solve(eq, Galerkin(; nx=512); nn=1) # finite-element outer-region Δ′A result carries nothing in the fields its integrator does not produce, and consumers warn and skip rather than erroring; plasma_response in particular needs a Forward() solve with wall=nothing (it errors on a wall or a Galerkin result and skips with a warning on a Riccati one), see Stability. A kinetic solve takes Forward() with the problem's kinetic keyword: kinetic=KineticForcesControl(; ...) evaluates the drift-kinetic matrices on the equilibrium's kinetic profiles, kinetic=TestKineticMatrices(; scale) uses synthetic matrices, kinetic_factor scales either, and km = kinetic_matrices(prob) evaluates the source once for reuse in later solves (KineticMatrices).
Inner-layer matching
A MatchProblem holds the outer Δ′ a solve published plus per-surface layer parameters, and the inner-layer model passed to solve computes the layer response at the prescribed rotation; the result is a new ForceFreeStatesResult with the closure changed from :ideal to :matched and the eigenfunctions replaced, so layer-parameter scans cost one cheap match per point:
ffs = solve(eq, Galerkin(; rpec_flag=true, cut_solution=true); nn=1)
matched = solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=0.0), GGJModel())
bpens = [solve(MatchProblem(ffs; eta=1e-6, rho=1e-7, rotation=f), GGJModel()).bpen for f in 0.0:50.0:500.0]A scalar applies to every surface and a vector gives one value per entry of ffs.surfaces, core to edge. The problem needs a Δ′ payload with coil-response columns, so it accepts Galerkin (rpec_flag=true) and Riccati (vac_flag=true) results. Both publish the outer solutions the match combines in ffs.basis; the composite inner-region profiles need Galerkin's cut_solution=true, and a Riccati basis always carries its cut solution. GGJModel() is the closure-capable model; SLAYERModel() is slab-only and drives the tearing solve instead.
Tearing stability
A TearingProblem holds the outer solution and the surface coupling, the inner-layer model its own closures, and TearingConfig the scan and root-search settings:
tear = solve(TearingProblem(ffs), SLAYERModel(; P_perp_model=:chi_perp_e);
config=TearingConfig(; Q_re_range=(-2.0, 2.0), Q_im_range=(-0.5, 3.0)))
ggj = solve(TearingProblem(ffs; coupling_mode=:coupled), GGJModel(; solver=:ray);
config=TearingConfig(; gamma_range=(1.0, 1e4), omega_range=(-1e4, 1e4)))Both models report lab-frame frequencies (omega in rad/s, gamma in 1/s, positive for instability, with frequency_frame recorded on the roots group); SLAYER searches a normalized Q box and GGJ a physical (γ, ω) box.
Local stability
problem = LocalStabilityProblem(eq; theta_k=0.0, alpha_boundary_scan=true)
ls = solve(problem, Ballooning(; n_scan=64); verbose=false)
ls.psi, ls.D_I, ls.D_R, ls.ballooning_Delta_prime # profiles on the equilibrium ψ grid
ls.ballooning_psi, ls.alpha, ls.alpha_critical # the ballooning boundary, NaN outside its scan windowEntry points
GeneralizedPerturbedEquilibrium.ForceFreeStates.ForceBalanceProblem — Type
ForceBalanceProblem(equil; nn, wall=nothing, kwargs...)The perturbed force-balance problem posed on an equilibrium, whose solutions are the force-free (or, with a kinetic source, kinetic) perturbed states. With kinetic terms the force operator is not self-adjoint, so this is not always an energy extremization. The integrator passed to solve sets the numerics; inner-layer matching is a separate MatchProblem on the finished solve.
nn is the toroidal mode number or range and wall the vacuum wall shape. Remaining keywords describe physics and workflow controls; numerical settings belong on the integrator passed to solve. nn_low/nn_high are rejected — they come from nn.
Fields
equil::Equilibrium.PlasmaEquilibrium- The equilibrium the problem is posed on.wall::Union{Nothing,Vacuum.WallSettings}- Vacuum wall shape for the free-boundary energies.ctrl_kwargs::Dict{Symbol,Any}-ForceFreeStatesControlkeywords,nnalready folded in.
CommonSolve.solve — Function
solve(prob::MatchProblem, model) -> ForceFreeStatesResultMatch prob.ffs to the inner layer of model. The result has closure = :matched (:ideal with ideal=true), bpen, the MatchResult in result.match and the matched ξ. A :matched result drops the ideal δW (wp, free_boundary), so PerturbedEquilibrium skips its response rather than mixing ideal and matched physics.
solve(prob::ForceBalanceProblem, alg; verbose=false) -> ForceFreeStatesResult
solve(equil, alg; nn, verbose=false, kwargs...) -> ForceFreeStatesResultSolve the perturbed-plasma ForceBalanceProblem with the formalism alg — Forward, Riccati or Galerkin — and return the published ForceFreeStatesResult. This is the scripting entry point; it runs the same stages a gpec.toml run of main does and produces the same result object. The second form is sugar building the problem from an equilibrium and the problem keywords in one call.
Knobs owned by alg are rejected as ForceFreeStatesControl keywords. Kinetic runs (a kinetic source) take Forward(). kinetic=KineticForcesControl(; ...) evaluates the KineticForces model with those settings on the equilibrium's kinetic profiles (kinetic_file, or attach_kinetic_profiles!); kinetic=TestKineticMatrices(; scale) uses synthetic test matrices; kinetic=km reuses the KineticMatrices from kinetic_matrices.
eq = PlasmaEquilibrium("input.geqdsk"; jac_type="hamada")
prob = ForceBalanceProblem(eq; nn=1, delta_mlow=8, delta_mhigh=8, vac_flag=true)
ffs = solve(prob, Riccati())
ffs = solve(eq, Riccati(); nn=1, vac_flag=true) # equivalent one-line formsolve(equil::PlasmaEquilibrium, alg; nn, verbose=false, kwargs...) -> ForceFreeStatesResultConvenience form of solve: builds the ForceBalanceProblem from the equilibrium and the problem keywords, then solves it with alg.
GeneralizedPerturbedEquilibrium.ForceFreeStates.kinetic_matrices — Function
kinetic_matrices(prob::ForceBalanceProblem, alg=Forward(); verbose=false) -> KineticMatricesEvaluate the kinetic matrices of prob's kinetic source once, running the part of solve before the Euler-Lagrange integration. Pass them back as the problem's kinetic to solve without evaluating them again: the solve is identical to one with the source itself, and may change kinetic_factor.
km = kinetic_matrices(ForceBalanceProblem(eq; nn=1, kinetic=KineticForcesControl()))
scan = [solve(ForceBalanceProblem(eq; nn=1, kinetic=km, kinetic_factor=f), Forward()) for f in (0.5, 1.0, 2.0)]GeneralizedPerturbedEquilibrium.PerturbedEquilibrium.perturbed_equilibrium — Function
perturbed_equilibrium(resp, rmp; regularization_width=0.0, verbose=false, coil_sets=nothing)
-> PerturbedEquilibriumStateDrive the plasma response resp (from plasma_response) with the external field rmp, an RMPField, and return the perturbed-equilibrium result. One response serves any number of fields, so a scan rebuilds no operator.
regularization_width smooths the ideal 1/(m−nq) divergence in the profile reconstruction (Fortran reg_spot); its default is 0, and 0.05 is typical for driving KineticForces with an ideal solve. Call save_to_hdf5(target, pe) to save the result. coil_sets injects already-built coil geometry (the gpec.h5 replay path), bypassing the geometry read.
resp = plasma_response(ffs)
pe = perturbed_equilibrium(resp, RMPField("forcing.dat"))plasma_response, which builds the PlasmaResponse that perturbed_equilibrium applies, is documented with the Perturbed Equilibrium module.
Integrator selectors
GeneralizedPerturbedEquilibrium.ForceFreeStates.AbstractIntegrator — Type
AbstractIntegratorNumerical algorithms for the force-balance problem. Physical inputs remain on the problem; each integrator carries its own accuracy, storage, and discretization settings.
GeneralizedPerturbedEquilibrium.ForceFreeStates.Forward — Type
Forward(; kwargs...)Serial forward integration with Gaussian reduction and dense solution profiles.
Fields
eulerlagrange_tolerance::Float64- Relative tolerance for ODE integration.renorm_threshold::Float64- Column-norm growth threshold for Gaussian reduction.numsteps_init::Int- Initial capacity for stored ODE solution steps.numunorms_init::Int- Initial capacity for solution-normalization records.save_interval::Int- Save every Nth ODE step; always retain steps near rational surfaces.
GeneralizedPerturbedEquilibrium.ForceFreeStates.Galerkin — Type
Galerkin(; nx=256, ...)RDCON outer-region singular Galerkin solver: solves the same Euler-Lagrange system variationally on a finite-element grid packed around the rational surfaces, producing Δ′ without a radial ODE sweep. Maps onto integrator = "Galerkin"; every field is the corresponding discretization setting. Factorization is selected automatically.
Fields
nx::Int- Elements per interval between singular surfaces.nq::Int- Gauss-Lobatto quadrature order per element.pfac::Float64- Grid packing ratio near singular surfaces.dx0::Float64- Resonant-element integration truncation distance, in units of 1/|n q′|.dx1::Float64- Resonant-element size, in units of 1/|n q′|.dx2::Float64- Extension-element size, in units of 1/|n q′|.cutoff::Int- Number of elements carrying the large solution as driving term.tol::Float64- Resonant-quadrature tolerance.gnstep::Int- Maximum resonant-quadrature evaluations.dx1dx2_flag::Bool- Enable the special dx1/dx2 treatment of resonant and extension elements.frobenius_order_ceiling::Bool- Auto-raise the order per surface for a high Mercier index.rpec_flag::Bool- Append the mpert coil-response columns to the Δ′ solve. Required for a laterMatchProblemsolve on the result.edge_onesided::Bool- Pack the two end intervals one-sided toward their single rational end instead of the Fortran symmetric pack.basis_output::Bool- Save the raw Galerkin basis for development diagnostics.cut_solution::Bool- Also keep the cut solution, for a laterMatchProblem's composite inner profiles.
GeneralizedPerturbedEquilibrium.ForceFreeStates.Riccati — Type
Riccati(; kwargs...)Chunked Riccati integration and the singular-surface boundary-value solve.
Fields
eulerlagrange_tolerance::Float64- Relative tolerance for ODE integration; the error of Δ′ scales with it.save_interval::Int- Store every Nth solver step of each chunk; chunk ends and the edge-dW scan band are always stored.nchunks::Int- Target chunk count; zero derives the count from the singular surfaces.extended_precision_bvp::Bool- Solve the Delta-prime BVP in Complex{Double64} instead of ComplexF64; far slower, and needed only beyond about 150 poloidal harmonics.