freegsnke.inverse module
Implements the optimiser for the inverse Grad-Shafranov problem.
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.inverse.Inverse_optimizer(isoflux_set: ndarray | list | None = None, null_points: ndarray | list | None = None, null_points_2nd_order: ndarray | list | None = None, psi_vals: ndarray | list | None = None, coil_current_limits: list | None = None, psi_norm_limits: ndarray | list | None = None, *, weight_isoflux: float = 1.0, weight_nulls: float = 1.0, weight_psi: float = 1.0, mu_coils: float = 100000.0, mu_psi_norm: float = 1000000.0)[source]
Bases:
objectThis class implements a gradient based optimiser for the coil currents, used to perform (static) inverse Grad-Shafranov solves.
- __init__(isoflux_set: ndarray | list | None = None, null_points: ndarray | list | None = None, null_points_2nd_order: ndarray | list | None = None, psi_vals: ndarray | list | None = None, coil_current_limits: list | None = None, psi_norm_limits: ndarray | list | None = None, *, weight_isoflux: float = 1.0, weight_nulls: float = 1.0, weight_psi: float = 1.0, mu_coils: float = 100000.0, mu_psi_norm: float = 1000000.0) None[source]
Initialise magnetic constraint definitions for inverse equilibrium optimisation.
This object stores magnetic configuration constraints that are enforced during inverse Grad-Shafranov optimisation.
Constraints supported include:
Isoflux constraints
Magnetic axis (O-point) and X-point constraints
Direct flux value constraints
Coil current bound constraints
Normalised flux inequality constraints
These constraints are used to construct objective and penalty terms during nonlinear current optimisation.
- Parameters:
isoflux_set (list or np.ndarray, optional) – Isoflux constraints. Each constraint set is
[Rcoords, Zcoords, weights](or a list of such sets), where Rcoords and Zcoords are 1D arrays of coordinates and weights is an optional 1D array (ones if not provided) used to increase/decrease the influence of each point on the solution. All points within a set are required to share the same poloidal flux.null_points (list or np.ndarray, optional) – Magnetic null point (X-point and O-point) constraints, specified as
[Rcoords, Zcoords].null_points_2nd_order (list or np.ndarray, optional) – Second-order magnetic null point constraints (typically used for snowflake divertor configurations), specified as
[Rcoords, Zcoords]. Do not repeat coordinates already provided in null_points.psi_vals (list or np.ndarray, optional) – Direct flux value constraints
[Rcoords, Zcoords, psi_values], where the three entries have identical flattened shapes. Enforces ψ(R,Z) = ψ_target at the specified locations.coil_current_limits (list, optional) – Hard inequality bounds on coil currents,
[upper_limits, lower_limits], where each entry is a list with length equal to the number of controllable coils, e.g.[[Imax1, Imax2, ...], [Imin1, Imin2, ...]]. Use None within a list to indicate no bound.psi_norm_limits (list or np.ndarray, optional) – Normalised flux inequality constraints, with one row per constraint
[Rcoord, Zcoord, normalised_psi_value, constraint_sign]. A constraint_sign of 1 enforces ψ_norm ≥ ψ_target and -1 enforces ψ_norm ≤ ψ_target, where ψ_norm = (ψ - ψ_axis) / (ψ_boundary - ψ_axis).weight_isoflux (float, optional) – Weight of the isoflux constraints in the least-squares optimisation problem (default = 1.0).
weight_nulls (float, optional) – Weight of the null point (X-point) constraints in the least-squares optimisation problem (default = 1.0).
weight_psi (float, optional) – Weight of the psi value constraints in the least-squares optimisation problem (default = 1.0).
mu_coils (float, optional) – Penalty factor applied to violation of the coil current limits (default = 1e5).
mu_psi_norm (float, optional) – Penalty factor applied to violation of the normalised psi limits (default = 1e6).
Notes
Increasing the weights/penalty factors causes the least-squares optimisation to prioritise satisfying the higher-weighted/penalised constraints. Constraint weights multiply residual rows before squaring, so their contribution to the objective scales with the square of the supplied value.
- build_control_coils(eq: object) None[source]
Identify and cache coil systems available for active control.
This method constructs internal indexing and masking structures that separate:
Control coils (actively optimised)
Passive coils (fixed currents or structures)
These mappings are required for:
Current optimisation
Jacobian construction
Constraint enforcement
Vectorised current updates
- Parameters:
eq (object) – Equilibrium providing the tokamak coil system. Each coil in
eq.tokamak.coilsmust have a booleancontrolattribute indicating controllability.
- build_control_currents(eq: object) None[source]
Extract coil current values for controllable coils from the equilibrium object.
This method builds a reduced current vector containing only the currents of actively optimised control coils.
- Parameters:
eq (object) – Equilibrium object providing the coil current state via
eq.tokamak.getCurrentsVec. The result is stored in control_currents.
- build_control_currents_Vec(full_currents_vec: ndarray) None[source]
Extract controllable coil currents from a full coil current vector.
This function performs projection:
I_control = M_control I_full
where M_control is a boolean masking operator selecting controllable coils.
- Parameters:
full_currents_vec (np.ndarray) – Full vector of coil currents, e.g. as returned by
eq.tokamak.getCurrentsVec(). The result is stored in control_currents.
- build_full_current_vec(eq: object) None[source]
Build full coil current vector from equilibrium object.
This retrieves all coil currents, including:
Control coils
Passive structure coils
- Parameters:
eq (object) – Equilibrium providing the coil current state via
eq.tokamak.getCurrentsVec. The result is stored in full_currents_vec.
- build_greens(eq: object) None[source]
Construct and cache magnetic Green’s function response operators.
This method precomputes magnetic response matrices used for:
Flux matching constraints
Null point field constraints
Isoflux surface optimisation
Flux inequality constraints
Green’s functions represent linear mappings between:
Coil current perturbations → Magnetic field / flux perturbations
- These operators are used during:
Constraint optimisation
Jacobian approximation
Inverse equilibrium solving
- Parameters:
eq (object) – Equilibrium providing access to tokamak geometry and magnetic response calculation routines.
- build_isoflux_lsq(full_currents_vec: ndarray) tuple[list[ndarray], list[ndarray], list[float]][source]
Construct linear least-squares system for enforcing isoflux magnetic constraints.
This method assembles the linear optimisation problem:
A I_control ≈ b
where:
A = Green’s function response matrix I_control = vector of controllable coil currents b = plasma + vacuum flux vector
The least-squares system is derived from:
ψ_total = ψ_tokamak + ψ_plasma
and enforcing:
ψ_i − ψ_j ≈ constant (equal-flux constraints along magnetic surfaces)
- Parameters:
full_currents_vec (np.ndarray) – Full vector of all coil currents, e.g. as returned by
eq.tokamak.getCurrentsVec().- Returns:
A (list of np.ndarray) – List of arrays for each isoflux constraint set.
b (list of np.ndarray) – Right-hand side residual vectors.
loss (list of float) – Constraint violation magnitudes (L2 norms).
Notes
For each isoflux constraint set:
A_i = (dG_i)ᵀ P_control
b_i = − ( Σ_k dG_i I_k + Δψ_plasma )
- where:
dG_i = pairwise Green’s function flux differences P_control = coil control projection operator
- build_lsq(full_currents_vec: ndarray) None[source]
Assemble the global least-squares optimisation system combining all active magnetic and control constraints.
This method aggregates all available constraint types into a single linear optimisation problem of the form:
A I_control ≈ b
where:
A = stacked Jacobian / response matrices b = stacked residual constraint vectors
The constraint types that can be combined include:
Isoflux surface constraints
Magnetic null-point field constraints
Direct flux value constraints
Direct coil current constraints
- Parameters:
full_currents_vec (np.ndarray) – Full vector of coil currents, e.g. as returned by
eq.tokamak.getCurrentsVec().
Notes
The assembled system is stored as A, b and loss.
This formulation solves the global constrained optimisation problem:
min_I || A I − b ||²
where each constraint type contributes a block to the system.
Constraint dimensional bookkeeping is stored as:
self.isoflux_dim self.nullp_dim self.psiv_dim self.curr_dim
- build_null_points_2nd_order_lsq(full_currents_vec: ndarray) tuple[ndarray, ndarray, list[float]][source]
Construct the linear least-squares system enforcing second-order null point constraints.
This method assembles a linear system of the form:
A ΔI = b
where ΔI represents corrections to the control coil currents, such that the magnetic field and its first spatial derivatives vanish (or match desired values) at the specified second-order null points.
The constraints enforced at each null point are:
B_R = 0
B_Z = 0
∂B_R/∂R = 0
∂B_Z/∂Z = 0
∂B_R/∂Z = 0
∂B_Z/∂R = 0
Each constraint is written as a linear combination of coil currents using precomputed Green’s function matrices (G* terms), with an additional contribution from the plasma.
The right-hand side vector b represents the negative residual of the total field (coil + plasma) at the null points, so that solving the system drives the residuals toward zero.
- Parameters:
full_currents_vec (np.ndarray) – Array of shape (n_coils,) containing the full set of coil currents. This includes both controlled and fixed coils, e.g. as returned by eq.tokamak.getCurrentsVec().
- Returns:
A (np.ndarray) – Least-squares matrix of shape (n_constraints, n_control_coils), mapping control coil current corrections to changes in the magnetic field quantities at the null points.
b (np.ndarray) – Right-hand side vector of shape (n_constraints,), representing the negative residuals of the current field configuration (coil + plasma).
loss (list of float) – L2 norms of each individual constraint residual before solving, in the order
[||B_R||, ||B_Z||, ||∂B_R/∂R||, ||∂B_Z/∂Z||, ||∂B_R/∂Z||, ||∂B_Z/∂R||].
Notes
The matrices G* encode the linear response of the magnetic field (and
its derivatives) to coil currents. - Contributions are split into:
coil contribution: G * I
plasma contribution: precomputed field values at null points
Only coils selected by self.control_mask are treated as control variables.
The system is typically overdetermined and intended to be solved in a
least-squares sense.
- build_null_points_lsq(full_currents_vec: ndarray) tuple[ndarray, ndarray, list[float]][source]
Construct a least-squares system enforcing magnetic null-point constraints.
This method builds the linear optimisation system:
A I_control ≈ b
for magnetic field cancellation at prescribed null points.
Null point constraints enforce:
B_R(R_i, Z_i) ≈ 0 B_Z(R_i, Z_i) ≈ 0
- where:
B_R = radial magnetic field component B_Z = vertical magnetic field component
These fields are expressed using Green’s function response matrices:
B(R,Z) = Σ_k G_k(R,Z) I_k + B_plasma
- Parameters:
full_currents_vec (np.ndarray) – Full vector of coil currents, e.g. as returned by
eq.tokamak.getCurrentsVec().- Returns:
A (np.ndarray) – Combined Jacobian matrix for null-point field constraints.
b (np.ndarray) – Residual field mismatch vector (negated for optimisation solving).
loss (list of float) – Constraint violation magnitudes
[ ||B_R||₂ , ||B_Z||₂ ].
Notes
This formulation is used to stabilise:
Magnetic axis positioning
X-point control
Divertor topology shaping
The optimisation problem solved is:
min_I || G I + B_plasma ||²
- where:
G = magnetic Green’s response operator I = coil current vector
- build_plasma_isoflux_lsq(full_currents_vec: ndarray, trial_plasma_psi: ndarray) None[source]
Assemble the least-squares system for plasma-only isoflux optimisation.
This method constructs a linearised least-squares problem of the form:
A_plasma x ≈ b_plasma
where x ∈ ℝ² represents plasma transformation parameters (e.g. normalisation and nonlinear shaping terms).
The residual enforces pairwise isoflux constraints:
Δψ_total = Δψ_coils + Δψ_plasma ≈ 0
using both raw flux differences and nonlinear transformed (ψ̂ log ψ̂) contributions.
- Parameters:
full_currents_vec (np.ndarray) – Full vector of coil currents.
trial_plasma_psi (np.ndarray) – Plasma flux array defined on the equilibrium grid.
Notes
The constructed system solves for two plasma parameters:
x[0] → linear normalisation scaling x[1] → nonlinear shaping contribution
Results are stored internally:
self.A_plasma self.b_plasma self.loss_plasma
- build_plasma_vals(trial_plasma_psi: ndarray) None[source]
Compute and cache plasma-dependent magnetic quantities from a candidate flux solution.
This method evaluates the plasma flux field and derives quantities required for constraint optimisation and nonlinear solve diagnostics, including:
Magnetic field components at null points
Isoflux surface flux differences
Pointwise flux constraint values
The plasma flux field is interpolated using bicubic spline interpolation.
- Parameters:
trial_plasma_psi (np.ndarray) – Candidate plasma poloidal flux solution, with the shape of the equilibrium grid (
len(self.eqR) × len(self.eqZ)).
Notes
Updates the internal state variables brp, bzp, the 2nd-order null point field quantities, d_psi_plasma_vals_iso and psi_plasma_vals, depending on which constraints are configured.
- build_psi_vals_lsq(full_currents_vec: ndarray) tuple[ndarray, ndarray, list[float]][source]
Construct a least-squares system enforcing direct flux value constraints.
This method builds the optimisation system:
A I_control ≈ b
where:
ψ_model(R_i, Z_i) = ψ_target(R_i, Z_i)
is enforced by matching magnetic flux values at specified locations.
The optimisation residual is defined as:
- b = ψ_tokamak(I) + ψ_plasma
ψ_target
⟨b⟩
Mean flux removal is applied to remove arbitrary vertical flux offsets, since the Grad–Shafranov equation is invariant under constant flux shifts. The same mean removal is applied to each coil-response column in
A.- Parameters:
full_currents_vec (np.ndarray) – Full coil current vector, e.g. as returned by
eq.tokamak.getCurrentsVec().- Returns:
A (np.ndarray) – Jacobian matrix mapping coil current perturbations → flux changes.
b (np.ndarray) – Flux mismatch residual vector.
list of float – Single-element list with the normalised constraint violation magnitude.
Notes
This constraint formulation is commonly used for:
Magnetic axis pinning
Boundary flux matching
Profile shape control
Solve:
min_I || G I + ψ_plasma − ψ_target ||²
- optimize_currents(eq: object, profiles: object, full_currents_vec: ndarray, trial_plasma_psi: ndarray, l2_reg: float | ndarray) tuple[ndarray, float][source]
Solve the constrained least-squares optimisation problem for coil current updates.
This method computes optimal coil current corrections by solving:
min_I || A I − b ||² + Iᵀ R I
where:
A = combined constraint Jacobian matrix b = combined constraint residual vector R = diagonal Tikhonov regularisation matrix
The optimisation accounts for:
Magnetic topology constraints
Flux surface matching
Null point field cancellation
Hardware current constraints
- Parameters:
eq (object) – Equilibrium providing geometry and tokamak configuration.
profiles (object) – Plasma profile properties used for constraint evaluation.
full_currents_vec (np.ndarray) – Full vector of all coil currents, e.g. as returned by
eq.tokamak.getCurrentsVec().trial_plasma_psi (np.ndarray) – Candidate plasma flux solution, with the same shape as
eq.R.l2_reg (float or np.ndarray) – Tikhonov regularisation parameter. If a float, R is the scalar value times the identity matrix; if an array (one entry per controlled coil), R contains the supplied coil-wise values on its diagonal.
- Returns:
delta_current (np.ndarray) – Optimal coil current update vector.
loss (float) – Residual loss norm.
- Raises:
ValueError – If l2_reg is an array whose length differs from the number of controlled coils.
- optimize_currents_grad(full_currents_vec: ndarray, trial_plasma_psi: ndarray, isoflux_weight: float = 1.0, null_points_weight: float = 1.0, null_points_2nd_order_weight: float = 1.0, psi_vals_weight: float = 1.0) tuple[ndarray, float][source]
Compute the gradient of the magnetic least-squares objective with respect to control coil currents.
This method evaluates the gradient of the unconstrained objective:
J(ΔI) = ½ || A ΔI − b ||²
evaluated at ΔI = 0, i.e.
∇J = Aᵀ b
Optional weighting factors allow different constraint classes (isoflux, null points, direct flux values) to be scaled prior to gradient evaluation.
- Parameters:
full_currents_vec (np.ndarray) – Full vector of all coil current values, e.g. as returned by
eq.tokamak.getCurrentsVec().trial_plasma_psi (np.ndarray) – Plasma flux contribution. Must have same shape as eq.R.
isoflux_weight (float, optional) – Weight applied to isoflux constraint residuals.
null_points_weight (float, optional) – Weight applied to null-point field constraint residuals.
null_points_2nd_order_weight (float, optional) – Weight applied to second-order null-point constraint residuals.
psi_vals_weight (float, optional) – Weight applied to direct flux value constraint residuals.
- Returns:
grad (np.ndarray) – Gradient of the weighted least-squares objective with respect to control coil current updates.
loss (float) – Combined magnetic constraint loss (unweighted).
- optimize_currents_quadratic(eq: object, profiles: object, full_currents_vec: ndarray, reg_matrix: ndarray, *, mu_coils: float | None = None, mu_psi_norm: float | None = None, A: ndarray | None = None, b: ndarray | None = None) tuple[ndarray, float][source]
Solve the regularised constrained least-squares problem using convex optimisation.
This method computes coil current updates by solving the quadratic program:
minimise_ΔI
|| A ΔI − b ||²
ΔIᵀ R ΔI
penalty(slack variables)
subject to optional inequality constraints:
Coil current upper/lower bounds
Normalised flux (ψ_norm) inequality constraints
Slack variables are introduced to allow temporary constraint violation, penalised in the objective function. This improves optimisation robustness and prevents infeasibility during nonlinear solve iterations.
- Parameters:
eq (object) – Equilibrium object used to evaluate plasma quantities and ψ_norm.
profiles (object) – Provides boundary flux (psi_bndry) and related quantities.
full_currents_vec (np.ndarray) – Full vector of coil currents.
reg_matrix (np.ndarray) – Regularisation matrix (n_control_coils × n_control_coils), typically diagonal, encoding Tikhonov L2 regularisation.
mu_coils (float or None, optional) – Currently unused: the coil limit slack penalty always uses
self.mu_coils.mu_psi_norm (float or None, optional) – Scaling factor for ψ_norm slack penalties. If None (or zero), defaults to
self.mu_psi_norm.A (np.ndarray or None, optional) – Sensitivity matrix. If None, uses
self.A.b (np.ndarray or None, optional) – Target residual vector. If None, uses
self.b.
- Returns:
delta (np.ndarray) – Optimal coil current update vector ΔI.
loss (float) – Combined loss: the magnetic constraint residual norm plus the sum of the slack variable values.
- Raises:
ValueError – If a ψ_norm constraint sign in psi_norm_limits is not 1 or -1.
Notes
The optimisation problem solved is a convex quadratic program (QP).
Base objective:
min_ΔI ||A ΔI − b||² + ΔIᵀ R ΔI
With optional inequality constraints:
I_min ≤ I_current + ΔI ≤ I_max ψ_norm constraints (≥ or ≤ type)
Slack variables s ≥ 0 allow:
constraint_violation ≤ s
with large quadratic penalties to discourage violation.
- optimize_plasma_psi(full_currents_vec: ndarray, trial_plasma_psi: ndarray, l2_reg: float | ndarray) tuple[ndarray, float][source]
Solve the regularised least-squares problem for plasma parameters.
This solves:
min_x || A_plasma x − b_plasma ||² + xᵀ R x
where:
x ∈ ℝ² R = Tikhonov regularisation matrix
- Parameters:
full_currents_vec (np.ndarray) – Full vector of coil currents.
trial_plasma_psi (np.ndarray) – Plasma flux array defined on the equilibrium grid.
l2_reg (float or np.ndarray) – Tikhonov regularisation strength. If a float, uniform regularisation is applied; if an array (length 2), its entries are the diagonal regularisation weights.
- Returns:
delta_current (np.ndarray) – Optimal update vector for plasma parameters (length 2).
loss_plasma (float) – Isoflux constraint violation norm (pre-update).
Notes
The regularisation is appended to the least-squares system before solving, avoiding the condition-number squaring of normal equations.
- plot(axis: Axes | None = None, show: bool = True) Axes[source]
Visualise the active coil control constraints.
This method provides a graphical representation of the magnetic and operational constraints currently configured in the object.
- Parameters:
axis (matplotlib.axes.Axes | None, optional) – Axis object on which to draw the plot. If None, a new figure and axis are created internally.
show (bool, optional) – If True, calls matplotlib.pyplot.show() before returning.
- Returns:
Axis containing the generated plot.
- Return type:
matplotlib.axes.Axes
Notes
This is a thin wrapper around:
freegsnke.plotting.plotIOConstraints
and exists primarily for convenience and API consistency.
- prepare_for_plasma_optimization(eq: object) None[source]
Prepare geometry- and Green’s-function-dependent quantities required for plasma optimisation.
This method ensures that:
Source-domain geometric properties are updated
Magnetic Green’s operators are constructed
- Parameters:
eq (object) – Equilibrium providing geometry, coil configuration, and grid data.
Notes
This is typically called prior to plasma-only optimisation steps to ensure response operators and geometric mappings are consistent with the current equilibrium configuration.
- prepare_for_solve(eq: object) None[source]
Prepare constraint solver quantities after object instantiation.
This method must be called before performing optimisation or nonlinear solve steps. It builds:
Control coil selection masks
Green’s function response operators
- These quantities are required for computing:
Constraint residuals
Gradient/Jacobian approximations
Loss function evaluations during optimisation
- Parameters:
eq (object) – Equilibrium object providing the coil geometry, coil current state and magnetic Green’s function operators.
- prepare_plasma_psi(trial_plasma_psi: ndarray) None[source]
Preprocess plasma flux values for normalisation and constraint evaluation.
This method computes shifted plasma flux extrema used for normalised flux calculations and ψ_norm-based constraints.
- Parameters:
trial_plasma_psi (np.ndarray) – Plasma flux array.
Notes
Sets the attributes min_psi and psi0.
- prepare_plasma_vals_for_plasma(trial_plasma_psi: ndarray) None[source]
Precompute plasma-dependent quantities required for plasma optimisation.
This method evaluates the plasma flux at constraint locations and constructs pairwise flux-difference terms used in isoflux constraints.
In addition to raw flux differences, a nonlinear transformed version of the normalised flux is computed:
ψ̂ = (ψ − ψ_min) / ψ0 f(ψ̂) = ψ̂ log(ψ̂)
which is then used to build weighted pairwise differences.
- Parameters:
trial_plasma_psi (np.ndarray) – Plasma flux array defined on the equilibrium grid (eqR, eqZ).
Notes
Sets d_psi_plasma_vals_iso and d_psi_for_plasma_iso.
For each isoflux constraint set:
Interpolate ψ at constraint coordinates.
- Construct pairwise differences:
ψ_i − ψ_j
- Construct transformed differences:
ψ0 [ f(ψ̂_i) − f(ψ̂_j) ]
These quantities are cached for use in plasma optimisation routines.
The logarithmic transform enhances sensitivity near ψ̂ → 0 and improves conditioning when enforcing plasma-based constraints.
- rebuild_full_current_vec(control_currents: ndarray, filling: float = 0) ndarray[source]
Reconstruct a full coil current vector from control coil values.
This performs the inverse mapping:
I_full = P I_control + I_background
- where:
- P = projection operator embedding control currents
into full coil system ordering.
- Non-controlled coils are assigned the value specified by:
filling
- Parameters:
control_currents (np.ndarray) – Current values for actively controlled coils.
filling (float, optional) – Default value used to fill non-controlled coil entries.
- Returns:
Complete coil current vector in system ordering.
- Return type:
np.ndarray
- source_domain_properties(eq: object) None[source]
Source and cache computational domain geometry from the equilibrium object.
This method extracts and stores the spatial grid coordinates used for solving the Grad–Shafranov equation.
- Parameters:
eq (object) – Equilibrium object providing the computational domain grids
eq.Randeq.Z(2D radial and vertical coordinates). Stored as eqR and eqZ.