freegsnke.GSstaticsolver module

Module for solving the static forward and inverse GS problems.

Copyright 2025 UKAEA, UKRI-STFC, and The Authors, as per the COPYRIGHT and README files.

This file is part of FreeGSNKE.

FreeGSNKE is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

FreeGSNKE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with FreeGSNKE. If not, see <http://www.gnu.org/licenses/>.

class freegsnke.GSstaticsolver.NKGSsolver(eq: object, l2_reg: float = 1e-06, collinearity_reg: float = 1e-06, seed: int = 42, gs_operator_order: int | None = None, cache_greens: bool = True, solver_type: str = 'LUsparse', mg_kwargs: dict | None = None, max_batch_size: int | float = 2000000000)[source]

Bases: object

Newton–Krylov solver for the nonlinear static Grad–Shafranov equilibrium problem.

This class solves the nonlinear free-boundary Grad–Shafranov equation:

Δψ = − μ₀ R Jtor(ψ)

written as a nonlinear root-finding problem:

F(ψ) = 0

where:

ψ : plasma poloidal flux Jtor(ψ) : toroidal plasma current density profile μ₀ R : geometric operator coefficients

The solver supports:

  • Forward equilibrium solving (fixed coil currents)

  • Inverse magnetic configuration optimisation

Solver structure:
The nonlinear system is solved using:
  • Newton–Krylov nonlinear iteration

  • Finite difference Jacobian approximations

Solution domain:

The spatial grid is fixed at instantiation using the provided equilibrium object.

Notes

The solver assumes:
  • Fixed computational domain

  • Fixed grid spacing

  • Compatible equilibrium geometry

F_function(plasma_psi: ndarray, tokamak_psi: ndarray, profiles: object) → ndarray[source]

Compute the nonlinear Grad–Shafranov residual written as a root-finding problem.

The Grad–Shafranov equation is solved in residual form:

F(ψ_plasma) = ψ_plasma − G(ψ_boundary, Jtor(ψ_plasma))

where:

G(…) represents the solution of the linearised GS operator with given boundary conditions and toroidal current source.

The equilibrium solution satisfies:

F(ψ_plasma) = 0

Physically, this measures the mismatch between:
  • The current plasma flux field

  • The flux predicted by solving the linear GS equation with the computed toroidal current density.

Parameters:
  • plasma_psi (np.ndarray) – Flattened plasma poloidal flux vector, shape (nx * ny,).

  • tokamak_psi (np.ndarray) – Flattened vacuum flux contribution from the active coils and passive conducting structures, same shape as plasma_psi.

  • profiles (object) – Plasma profile model used to compute the toroidal current density Jtor(ψ).

Returns:

Nonlinear GS residual vector (flattened). Root of this function corresponds to GS equilibrium.

Return type:

np.ndarray

Notes

This formulation is used for:
  • Newton–Krylov nonlinear solves

  • Picard fixed-point iterations

  • Residual diagnostics during equilibrium solving

__init__(eq: object, l2_reg: float = 1e-06, collinearity_reg: float = 1e-06, seed: int = 42, gs_operator_order: int | None = None, cache_greens: bool = True, solver_type: str = 'LUsparse', mg_kwargs: dict | None = None, max_batch_size: int | float = 2000000000) → None[source]

Initialise the Grad–Shafranov nonlinear solver.

The constructor prepares all numerical operators required for nonlinear GS solving, including:

  • Direct sparse linear GS solver

  • Green’s function boundary response operator

  • Newton–Krylov nonlinear solver backend

  • Random generator for Krylov direction perturbations

Parameters:
  • eq (object) – Equilibrium object defining the computational domain and geometry. Must provide the 2D grids eq.R (radial) and eq.Z (vertical) and eq.limiter_handler. The solver grid is fixed to this domain.

  • l2_reg (float, optional) – Tikhonov regularisation coefficient applied to nonlinear least-squares systems.

  • collinearity_reg (float, optional) – Additional regularisation penalising collinear search directions in Krylov space. Improves numerical stability of NK iteration.

  • seed (int, optional) – Random number generator seed used for Krylov perturbation generation and directional exploration in the nonlinear solve.

  • gs_operator_order ({2, 4, None}, optional (default=None)) – Finite-difference order of the linear Grad-Shafranov operator. Fourth order is more accurate; second order may reduce execution time. Default is the highest value supported by solver_type. It is STRONGLY recommended to leave the default value.

  • cache_greens (bool, optional (default=True)) – Determines whether the Greens function should be pre-calculated and stored, or re-calculated every time the boundary flux is computed (reducing memory usage by up to an order of magnitude).

  • solver_type (str, optional (default='LUsparse')) – The type of linear solver to use for the GS equation. Supported options are ‘LUsparse’, ‘DST’, ‘multigrid’. ‘LUsparse’ supports order 2,4. The ‘DST’ solver is faster, but only supports order 2. Use of ‘multigrid’ is discouraged and is planned to be deprecated.

  • mg_kwargs (dict|None, optional (default = None)) – dict with optional keyword arguments to pass to freegsnke.multigrid.createMultigridSolver during multigrid solver initialization. Ignored whenever solver_type != ‘multigrid’.

  • max_batch_size (int|float, optional (default=2_000_000_000)) – Sets a maximum size (number of entries) for the batches of the Greens function when calculating the boundary flux, allowing for further reduction in memory footprint. Only applicable when cache_greens=False, ignored otherwise. Float type values supported for convenience (to allow for use of scientific notation, e.g. max_batch_size=2e9).

Raises:

ValueError – If gs_operator_order is not 2 or 4.

self.R, self.Z

Computational grid coordinates.

Type:

np.ndarray

self.nx, self.ny

Grid dimensions.

Type:

int

self.dRdZ

Differential area element used for integration.

Type:

float

self.linear_GS_solver

Numerical solver for linearised GS equation.

self.greenfunc

Boundary response Green’s function matrix for source points inside the limiter, where the plasma current is confined.

self.nksolver

Newton–Krylov nonlinear solver backend.

Notes

The solver domain cannot be changed after construction. A new solver instance must be created for different grids.

configureLinearSolver(solver_type: str, order: int | None, mg_kwargs: dict | None) → GSLUSolver | GSDSTSolver | MGJacobi | MGDirect[source]

Creates and assigns the linear solver self.linear_GS_solver using the arguments provided.

Also sets the attribute self.gs_operator_order.

Parameters:
  • solver_type (str) – The type of linear solver to use for the GS equation. Supported options are ‘LUsparse’, ‘DST’, ‘multigrid’.

  • order (int|None) – Order of differential operators used in calculations. Must be either 2 or 4, or None to use the selected solver’s default.

  • mg_kwargs (dict|None) – dict with kwargs to pass to freegsnke.multigrid.createMultigridSolver during multigrid solver initialization. Ignored whenever solver_type != ‘multigrid’.

forward_solve(eq: object, profiles: object, target_relative_tolerance: float, max_solving_iterations: int = 100, Picard_handover: float = 0.11, step_size: float = 2.5, scaling_with_n: float = -1.0, target_relative_unexplained_residual: float = 0.2, max_n_directions: int = 16, max_rel_update_size: float = 0.2, clip: float = 10, force_up_down_symmetric: bool = False, verbose: bool = False, suppress: bool = False) → None[source]

Solve the forward static Grad–Shafranov (GS) equilibrium problem.

This method computes the plasma poloidal flux ψ_plasma that satisfies the nonlinear static Grad–Shafranov equation:

F(ψ_plasma; ψ_tokamak, profiles) = 0

where:

ψ_tokamak : vacuum flux generated by metal currents profiles : plasma current profile specification (Jtor(ψ))

The total flux is:

ψ_total = ψ_tokamak + ψ_plasma

The nonlinear system is solved using a hybrid scheme:
  • Picard iterations when far from convergence

  • Newton–Krylov (NK) iterations when close to solution

The final solution is written to:

eq.plasma_psi

Parameters:
  • eq (object) – Equilibrium object providing the metal currents (via eq.tokamak), the initial guess eq.plasma_psi and the Green’s functions eq._vgreen. Updated in-place.

  • profiles (object) – Profiles object defining the plasma current model Jtor(ψ).

  • target_relative_tolerance (float) – Iterations stop when the relative nonlinear residual falls below this value.

  • max_solving_iterations (int, optional) – Maximum allowed nonlinear iterations.

  • Picard_handover (float) – Relative residual threshold above which Picard iteration is used instead of Newton–Krylov.

  • step_size (float) – Proposed NK step magnitude scaling factor.

  • scaling_with_n (float) – Additional scaling applied to NK step depending on iteration count: (1 + n_it)**scaling_with_n.

  • target_relative_unexplained_residual (float in (0,1)) – NK internal Arnoldi iteration stops once this fraction of the initial residual is explained.

  • max_n_directions (int) – Maximum number of Krylov directions explored.

  • max_rel_update_size (float) – Maximum allowed relative update to ψ_plasma. Larger updates are rescaled.

  • clip (float) – Maximum magnitude of update contribution from each explored Krylov direction.

  • force_up_down_symmetric (bool) – If True, enforces up-down symmetry at each step.

  • verbose (bool) – Enables detailed iteration logging.

  • suppress (bool) – Suppresses all print output.

Notes

Updates eq.plasma_psi, the profiles (via Jtor) and the internal convergence diagnostics.

Geometry backtracking uses at most 32 trials per update. If no valid step is found, the accepted equilibrium is restored and a RuntimeError is raised. The final residual is evaluated on the returned field.

This solver includes:
  • Adaptive initialisation

  • Residual-based step control

  • Trust-region-style update limiting

  • Automatic fallback between Picard and NK

  • Residual collinearity detection

  • Symmetry enforcement (optional)

The algorithm is designed for robustness in highly nonlinear free-boundary equilibrium problems.

freeboundary(plasma_psi: ndarray, tokamak_psi: ndarray, profiles: object) → None[source]

Apply free-boundary Grad–Shafranov boundary conditions and compute plasma current source terms.

This routine constructs the nonlinear source term and boundary flux conditions required to solve the Grad–Shafranov equation:

Δψ = − μ₀ R Jtor(ψ)

in free-boundary form.

The algorithm performs three main tasks:

  1. Compute toroidal current density:

    Jtor(ψ_total)

  2. Compute RHS source term for linear GS solve

  3. Compute boundary flux contributions using Green’s functions

The total flux used is:

ψ_total = ψ_tokamak + ψ_plasma

Parameters:
  • plasma_psi (np.ndarray) – Flattened plasma poloidal flux vector, shape (nx * ny,).

  • tokamak_psi (np.ndarray) – Flattened vacuum flux contribution generated by the active coils and passive structures, shape (nx * ny,).

  • profiles (object) – Profiles object providing the plasma current model Jtor(ψ).

Notes

  • Updates the internal solver state jtor, rhs and psi_boundary.

  • This method is called before solving the linearised GS equation.

  • Boundary flux is computed using Green’s function convolution.

get_rel_delta_psi(new_psi: ndarray, previous_psi: ndarray, profiles: object) → float[source]

Compute the relative change between two flux states in the plasma core.

This function measures the relative difference between two poloidal flux fields, restricted to the plasma core region. It is used as a convergence and stability metric in both forward and inverse solves.

The relative change is defined as:

rel_delta = || (ψ_new − ψ_old) * M ||₂

|| (ψ_new + ψ_old) * M ||₂

where:

ψ_new, ψ_old : flattened flux vectors M : binary core-region mask ||·||₂ : Euclidean (L2) norm

The mask ensures that only the plasma core region contributes to the norm. If no core mask is available, the full domain is used.

This symmetric normalisation (using ψ_new + ψ_old in the denominator) prevents bias when one field is small and provides a scale-invariant measure of change.

Parameters:
  • new_psi (np.ndarray) – Flattened array of the updated poloidal flux values.

  • previous_psi (np.ndarray) – Flattened array of the previous poloidal flux values. Must be the same shape as new_psi.

  • profiles (object) – Profiles object used to obtain the plasma core mask (profiles.diverted_core_mask if available, otherwise the entire computational domain is used).

Returns:

rel_delta_psit – Relative L2 change between the two flux fields restricted to the plasma core region.

Return type:

float

Notes

  • If profiles.diverted_core_mask is None or not present, the relative change is computed over the full domain.

  • This quantity is dimensionless.

  • Used to:
    • Detect convergence of forward solves

    • Limit coil-induced flux changes in inverse solves

    • Control damping and adaptive tolerances

get_rel_delta_psit(delta_current: ndarray, profiles: object, vgreen: ndarray) → float[source]

Estimate the relative core-region flux perturbation induced by a requested coil current change.

This function computes the magnitude of the poloidal flux perturbation Δψ generated by a proposed change in coil currents, and expresses it relative to the magnitude of the existing tokamak flux.

The induced flux perturbation is computed using the coil Green’s functions:

Δψ(R, Z) = Σ_i ΔI_i G_i(R, Z)

where:

ΔI_i : requested current change in coil i G_i(R, Z) : Green’s function of coil i (R, Z) : spatial grid coordinates

The relative change metric is then defined as:

rel_delta = || Δψ_core ||₂

|| ψ_tokamak ||₂ + ε

where:

ψ_tokamak : current total flux field Δψ_core : Δψ restricted to the plasma core ||·||₂ : Euclidean (L2) norm ε : small regularisation constant (1e-6)

If a diverted core mask is available, only the plasma core region contributes to the numerator. Otherwise, the full domain is used.

Parameters:
  • delta_current (np.ndarray) – One-dimensional array of requested coil current changes. Shape (n_coils,).

  • profiles (object) – Profiles object providing the plasma core mask via profiles.diverted_core_mask, if available.

  • vgreen (np.ndarray) – Array of coil Green’s functions. Shape (n_coils, Nx, Ny), where each slice vgreen[i] corresponds to the flux response of coil i per unit current.

Returns:

rel_delta_psit – Dimensionless estimate of the relative magnitude of the induced flux perturbation.

Return type:

float

Notes

  • This quantity measures how large the requested current update is

in terms of its effect on the plasma core flux.

  • It is typically used to:
    • Control step sizes in inverse solves,

    • Enforce trust-region constraints,

    • Prevent excessively large coil updates,

    • Provide stabilisation in iterative current optimisation.

  • The denominator is computed over the full domain

(not masked), matching the current implementation.

inverse_solve(eq: object, profiles: object, constrain: Inverse_optimizer, target_relative_tolerance: float, target_relative_psit_update: float = 0.001, max_solving_iterations: int = 100, max_iter_per_update: int = 5, Picard_handover: float = 0.15, step_size: float = 2.5, scaling_with_n: float = -1.0, target_relative_unexplained_residual: float = 0.3, max_n_directions: int = 16, clip: float = 10, max_rel_update_size: float = 0.15, threshold_val: float = 0.18, l2_reg: float | ndarray = 1e-09, forward_tolerance_increase: float = 100, max_rel_psit: float = 0.02, damping_factor: float = 0.995, use_full_Jacobian: bool = True, full_jacobian_handover: list[float] = [1e-05, 0.007], l2_reg_fj: float = 1e-08, force_up_down_symmetric: bool = False, verbose: bool = False, suppress: bool = False) → None[source]

Inverse solver for static free-boundary Grad–Shafranov equilibria.

This routine solves a coupled inverse problem:

  • Unknowns:
    • Control coil currents

    • Plasma poloidal flux (plasma_psi)

  • Constraints:
    • Magnetic constraints provided via constrain

    • Grad–Shafranov equation consistency

    • Target plasma profiles (via profiles)

The algorithm alternates between:
  1. Updating coil currents to better satisfy magnetic constraints.

  2. Performing a forward GS solve to update plasma_psi for the new currents.

Two Jacobian models are available for the current update:
  • Green’s function Jacobian (plasma fixed)

  • Full Jacobian (plasma response included)

Convergence requires BOTH:
  • GS residual < target_relative_tolerance

  • Relative tokamak flux update < target_relative_psit_update

The solve is therefore a nonlinear block-iterative scheme coupling:
  • Coil optimisation

  • Forward equilibrium solve

Upon success:
  • eq.plasma_psi contains the converged plasma flux

  • eq.tokamak currents contain the converged coil currents

Parameters:
  • eq (object) – Equilibrium object containing the tokamak geometry and coil system: eq.tokamak holds the coil currents and eq.plasma_psi holds the plasma poloidal flux. This object is updated in-place.

  • profiles (object) – Profiles object specifying the desired plasma profiles (total plasma current, pressure p(psi) and F(psi)), which define the toroidal current density Jtor(psi).

  • constrain (Inverse_optimizer) – Defines which coils are controllable, the magnetic constraints to be satisfied and the loss function measuring constraint violation.

  • target_relative_tolerance (float) – Target relative tolerance for the GS residual. The forward GS problem must satisfy this tolerance for the inverse problem to be considered solved.

  • target_relative_psit_update (float, optional (default=1e-3)) – Maximum allowed relative change in tokamak flux (in the plasma core) between successive inverse iterations. Acts as a stability criterion.

  • max_solving_iterations (int, optional (default=100)) – Maximum number of outer inverse iterations.

  • max_iter_per_update (int, optional (default=5)) – Maximum number of forward GS iterations performed after each coil current update.

  • Picard_handover (float, optional (default=0.15)) – Relative residual threshold above which Picard iteration is used instead of Newton–Krylov in the forward solve.

  • step_size (float, optional (default=2.5)) – Scaling of exploratory steps in the forward nonlinear solve. Expressed in units of the residual norm.

  • scaling_with_n (float, optional (default=-1.0)) –

    Additional scaling factor applied to exploratory steps:

    (1 + iteration_number)**scaling_with_n

  • target_relative_unexplained_residual (float, optional (default=0.3)) – Forward solver termination criterion based on how much of the residual can be explained by current search directions.

  • max_n_directions (int, optional (default=16)) – Maximum number of search directions used in forward solve.

  • clip (float, optional (default=10)) – Maximum update magnitude allowed per direction (in units of exploratory finite-difference step).

  • max_rel_update_size (float, optional (default=0.15)) – Maximum allowed relative update to plasma_psi in forward solve. If exceeded, the update is rescaled.

  • threshold_val (float, optional (default=0.18)) – Threshold relative GS residual below which the solver switches to more conservative update logic.

  • l2_reg (float or np.ndarray, optional (default=1e-9)) – L2 regularisation factor applied when using the Green’s function Jacobian (simplified current optimisation). If array, must match number of control coils.

  • forward_tolerance_increase (float, optional (default=100)) – Controls how tightly the forward problem is solved relative to the size of the coil-induced flux change. Smaller flux changes trigger tighter forward tolerances.

  • max_rel_psit (float, optional (default=0.02)) – Maximum relative change in tokamak flux allowed due to coil current updates. Used as a step limiter.

  • damping_factor (float, optional (default=0.995)) –

    Exponential damping applied to allowed tokamak flux change across iterations:

    allowed_change *= damping_factor**iteration

  • use_full_Jacobian (bool, optional (default=True)) – If True, enables switching to full Jacobian optimisation when sufficiently close to convergence.

  • full_jacobian_handover (list[float], optional (default=[1e-5, 7e-3])) –

    Two thresholds:

    [GS_residual_threshold, tokamak_flux_update_threshold]

    Below these values, the solver switches to full Jacobian mode.

  • l2_reg_fj (float, optional (default=1e-8)) – L2 regularisation factor applied when using the full Jacobian.

  • force_up_down_symmetric (bool, optional (default=False)) – If True, projects the initial plasma flux and enforces up-down symmetry in all main and full-Jacobian forward solves.

  • verbose (bool, optional (default=False)) – If True, prints iteration progress and diagnostic information.

  • suppress (bool, optional (default=False)) – If True, suppresses all output (overrides verbose).

Raises:

RuntimeError – If the GS residual cannot be computed for the initial plasma_psi and coil currents, or if geometry backtracking fails to find a valid step within 32 trials (after restoring the accepted equilibrium).

Notes

  • The solution is written in-place into eq.plasma_psi and the eq.tokamak coil currents.

  • The method is a nonlinear block-iterative inverse solver.

  • Early iterations use a frozen-plasma approximation for robustness and efficiency.

  • Close to convergence, the full Jacobian is used for quadratic-like convergence.

  • For diverted equilibria, current updates are automatically resized to prevent loss of X-points or O-points.

optimize_currents(eq: object, profiles: object, constrain: Inverse_optimizer, target_relative_tolerance: float, relative_psit_size: float = 0.001, l2_reg: float | ndarray = 1e-12, verbose: bool = False, force_up_down_symmetric: bool = False) → tuple[ndarray, float][source]

Compute coil current updates using the full (plasma-aware) Jacobian.

This routine builds the Jacobian of the magnetic constraint residual vector with respect to the control coil currents:

A = d b / d I

where:

b = constraint residual vector I = control coil currents

Unlike the simplified Green’s-function approach (which assumes the plasma response is frozen), this method recomputes the full plasma equilibrium for each finite-difference perturbation of the control currents. Therefore the Jacobian includes:

  • Direct magnetic effect of coil current changes

  • Indirect effect via plasma response (GS equation)

The Jacobian is constructed using forward finite differences:

A[:, i] ≈ (b(I + δI_i) − b(I)) / δI_i

Once A is constructed, the Newton step is computed by solving the Tikhonov-regularised least-squares problem:

min || A ΔI + b0 ||² + ΔIᵀ R ΔI

where:

b0 = current constraint residual R = regularisation matrix

Without inequality limits, this is solved as an augmented least-squares system. If current or flux limits are active, a constrained quadratic optimisation routine is used instead.

Parameters:
  • eq (object) – Equilibrium object containing the current coil currents and plasma_psi. Perturbed solves use auxiliary copies, but the baseline forward solve updates eq in-place.

  • profiles (object) – Profiles object providing the plasma properties required to solve the forward Grad–Shafranov problem.

  • constrain (Inverse_optimizer) – Defines the control coils, the constraint residual vector b, the loss function and any optional current or flux limits.

  • target_relative_tolerance (float) – Forward GS tolerance used when recomputing equilibria for each Jacobian column.

  • relative_psit_size (float, optional) – Target relative change in tokamak flux used to scale the finite-difference perturbations δI. A zero component in the preliminary current step is replaced by a response-based fallback. Ensures perturbations are neither too small (noise-dominated) nor too large (nonlinear).

  • l2_reg (float or np.ndarray, optional) – Tikhonov regularisation factor. If a float, isotropic regularisation; if an array, per-coil regularisation weights.

  • verbose (bool, optional) – If True, prints progress during Jacobian construction.

  • force_up_down_symmetric (bool, optional) – If True, enforce up-down symmetry in the baseline and perturbed forward solves used to construct the full Jacobian.

Returns:

  • Newton_delta_current (np.ndarray) – Optimal Newton update for control coil currents.

  • loss (float) – Norm of the constraint residual after applying the computed Newton step (predicted reduction).

Raises:

ValueError – If relative_psit_size is not finite and positive, or if the preliminary current step, its flux response or the response of any control coil is non-finite (or zero for a coil with no preliminary step).

Notes

  • Computational cost scales with number of control coils because one full GS solve is required per column.

  • Provides quadratic convergence when close to solution.

  • Intended to be used only when already near equilibrium.

port_critical(eq: object, profiles: object) → None[source]

Transfer critical equilibrium and topology information from the plasma profile solver to the equilibrium object after solving the Grad–Shafranov equation.

This function synchronises diagnostic and structural information between the profile model and equilibrium container. It is typically called after a successful GS solve.

The following information is transferred:

  • Magnetic axis (O-point)

  • X-point locations (if present)

  • Plasma boundary and limiter flags

  • Total plasma current estimate

  • Plasma profile state snapshot

  • Tokamak vacuum flux (if available)

Parameters:
  • eq (object) – Equilibrium object that will be updated in-place.

  • profiles (object) – Profile object used during GS solution. Must provide xpt (X-point locations), opt (O-point / magnetic axis data), psi_bndry (boundary flux value), flag_limiter (limiter configuration flag), jtor (toroidal current density profile), copy and, optionally, has_relevant_xpoint (whether an X-point defines a relevant separatrix in the solution domain).

Notes

Updates are performed in-place on the equilibrium object.

This routine ensures consistency between:
  • Plasma topology diagnostics

  • Flux solution storage

  • Current profile bookkeeping

It is primarily used internally by forward and inverse solvers.

relative_del_residual(res: ndarray, psi: ndarray) → tuple[float, float][source]

Compute a relative residual measure based on the range (max − min) of the residual and flux field.

This metric measures relative variation using amplitude range rather than L2 norms, and is useful for detecting large-scale flux structure errors.

The relative residual is defined as:

relative_residual =

( max(ψ) − min(ψ) )

where:

ψ = plasma poloidal flux field res = nonlinear GS residual vector

This quantity is dimensionless and provides a scale-invariant measure of solution error magnitude.

Parameters:
  • res (np.ndarray) – Flattened nonlinear Grad–Shafranov residual vector.

  • psi (np.ndarray) – Flattened plasma poloidal flux field.

Returns:

  • rel_residual (float) – Relative residual defined using amplitude range normalisation.

  • del_psi (float) – Flux amplitude range, max(ψ) − min(ψ).

Notes

  • Range-based metrics are less sensitive to localised spikes than pointwise residuals.

  • If ψ has very small dynamic range, this metric may become ill-conditioned.

  • Used internally as a convergence and stability diagnostic.

relative_norm_residual(res: ndarray, psi: ndarray) → float[source]

Compute a relative residual using Euclidean (L2) norm normalisation.

This function measures the magnitude of the nonlinear GS residual relative to the magnitude of the plasma flux field using:

relative_residual =

||ψ||₂

where:

res = nonlinear Grad–Shafranov residual vector ψ = plasma poloidal flux field

This provides a scale-invariant convergence metric for nonlinear equilibrium solves.

Parameters:
  • res (np.ndarray) – Flattened nonlinear Grad–Shafranov residual vector.

  • psi (np.ndarray) – Flattened plasma poloidal flux field.

Returns:

Dimensionless relative L2 residual.

Return type:

float

Notes

  • This metric is sensitive to small ||ψ|| values.

  • Used as a primary convergence indicator during nonlinear solves.

solve(eq: object, profiles: object, constrain: Inverse_optimizer | None = None, target_relative_tolerance: float = 1e-05, target_relative_psit_update: float = 0.001, max_solving_iterations: int = 100, max_iter_per_update: int = 5, Picard_handover: float = 0.1, step_size: float = 2.5, scaling_with_n: float = -1.0, target_relative_unexplained_residual: float = 0.3, max_n_directions: int = 16, clip: float = 10, max_rel_update_size: float = 0.15, l2_reg: float | ndarray = 1e-09, forward_tolerance_increase: float = 100, max_rel_psit: float = 0.01, damping_factor: float = 0.98, use_full_Jacobian: bool = True, full_jacobian_handover: list[float] = [1e-05, 0.007], l2_reg_fj: float = 1e-08, force_up_down_symmetric: bool = False, verbose: bool = False, suppress: bool = False) → None[source]

Unified entry point for solving Grad–Shafranov problems (forward or inverse).

This method dispatches to either:

  • forward_solve — fixed coil currents, solve for plasma equilibrium

  • inverse_solve — adjust control coil currents to satisfy magnetic constraints

The mode is determined by the constrain argument:

constrain is None → Forward equilibrium solve constrain is provided → Inverse free-boundary optimisation

FORWARD MODE (constrain=None)

Solves the nonlinear free-boundary Grad–Shafranov equation:

F(ψ, I) = 0

for the plasma poloidal flux ψ, with fixed coil currents I.

The solve terminates when the relative GS residual falls below target_relative_tolerance or when max_solving_iterations is reached.

The result is written in-place into:

eq.plasma_psi

INVERSE MODE (constrain provided)

Solves the PDE-constrained optimisation problem:

min_I ½ || b(ψ(I), I) ||² subject to F(ψ(I), I) = 0

where:

ψ = plasma flux I = control coil currents b = magnetic constraint residual vector

The algorithm alternates between:
  1. Optimising control coil currents

  2. Performing forward GS solves to update plasma response

Convergence requires BOTH:
  • GS residual < target_relative_tolerance

  • Relative tokamak flux update < target_relative_psit_update

Upon convergence:

eq.plasma_psi contains the final plasma solution eq.tokamak contains the optimised coil currents

param eq:

Equilibrium object containing the tokamak geometry and coils, the current coil currents and the current plasma flux (initial guess). Modified in-place.

type eq:

object

param profiles:

Profiles object defining the plasma profiles (pressure p(ψ), F(ψ) and total plasma current) used to compute the toroidal current density.

type profiles:

object

param constrain:

If None, a forward equilibrium solve is performed. If provided, it specifies the control coils and magnetic constraints for inverse optimisation.

type constrain:

Inverse_optimizer or None, optional

param target_relative_tolerance:

Target relative GS residual tolerance for forward solves. In inverse mode, this is the required final equilibrium accuracy.

type target_relative_tolerance:

float, optional (default=1e-5)

param target_relative_psit_update:

(Inverse mode only) Maximum allowed relative change in tokamak flux between successive current updates.

type target_relative_psit_update:

float, optional (default=1e-3)

param max_solving_iterations:

Maximum number of outer iterations. In forward mode: maximum GS iterations. In inverse mode: maximum inverse iterations.

type max_solving_iterations:

int, optional (default=100)

param max_iter_per_update:

(Inverse mode only) Maximum forward GS iterations performed after each coil current update.

type max_iter_per_update:

int, optional (default=5)

param Picard_handover:

Relative GS residual threshold above which Picard iteration is used instead of Newton–Krylov in forward solves.

type Picard_handover:

float, optional (default=0.1)

param step_size:

Scaling factor for nonlinear update steps in forward solve. Expressed in units of residual norm.

type step_size:

float, optional (default=2.5)

param scaling_with_n:
Additional scaling of nonlinear steps as:

(1 + iteration_number)**scaling_with_n

type scaling_with_n:

float, optional (default=-1.0)

param target_relative_unexplained_residual:

Forward solver termination criterion based on how much of the residual is explained by accumulated search directions.

type target_relative_unexplained_residual:

float, optional (default=0.3)

param max_n_directions:

Maximum number of search directions in forward solve.

type max_n_directions:

int, optional (default=16)

param clip:

Maximum update magnitude per search direction in forward solve.

type clip:

float, optional (default=10)

param max_rel_update_size:

Maximum allowed relative change in plasma_psi per forward iteration. Updates exceeding this are rescaled.

type max_rel_update_size:

float, optional (default=0.15)

param l2_reg:

(Inverse mode only) Tikhonov regularisation applied when using Green’s-function Jacobians for coil optimisation.

type l2_reg:

float or np.ndarray, optional (default=1e-9)

param forward_tolerance_increase:

(Inverse mode only) Controls how tightly forward problems are solved relative to the magnitude of coil-induced flux changes.

type forward_tolerance_increase:

float, optional (default=100)

param max_rel_psit:

(Inverse mode only) Maximum allowed relative tokamak flux change due to a single coil current update.

type max_rel_psit:

float, optional (default=0.01)

param damping_factor:

(Inverse mode only) Exponential damping applied to the allowed tokamak flux change across iterations to encourage convergence.

type damping_factor:

float, optional (default=0.98)

param use_full_Jacobian:

(Inverse mode only) If True, switches to full plasma-aware Jacobian when sufficiently close to convergence.

type use_full_Jacobian:

bool, optional (default=True)

param full_jacobian_handover:

(Inverse mode only) Thresholds [GS_residual, tokamak_flux_update] below which full Jacobian optimisation is activated.

type full_jacobian_handover:

list[float], optional (default=[1e-5, 7e-3])

param l2_reg_fj:

(Inverse mode only) Regularisation factor applied when full Jacobian is used.

type l2_reg_fj:

float, optional (default=1e-8)

param force_up_down_symmetric:

If True, enforces up–down symmetry during forward solves.

type force_up_down_symmetric:

bool, optional (default=False)

param verbose:

If True, prints iteration progress information.

type verbose:

bool, optional (default=False)

param suppress:

If True, suppresses all printed output.

type suppress:

bool, optional (default=False)

Notes

  • The solution is written in-place into eq.plasma_psi (and, in inverse mode only, the eq.tokamak coil currents).

  • This is the recommended high-level API for solving equilibria.

  • Forward mode solves a nonlinear free-boundary PDE.

  • Inverse mode solves a nonlinear PDE-constrained least-squares problem.

  • Internally dispatches to forward_solve or inverse_solve.