freegsnke.nonlinear_solve module
Implements the core non-linear solver for the evolutive GS problem. Also handles the linearised evolution capabilities.
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.nonlinear_solve.nl_solver(profiles: object, eq: object, GSStaticSolver: NKGSsolver, custom_coil_resist: ndarray | None = None, custom_self_ind: ndarray | None = None, full_timestep: float = 0.0001, max_internal_timestep: float = 0.0001, automatic_timestep: tuple[float, float] | bool = False, plasma_resistivity: float = 1e-06, plasma_norm_factor: float = 1000.0, blend_hatJ: float = 0, max_mode_frequency: float | None = 100.0, fix_n_vessel_modes: int = -1, threshold_dIy_dI: float = 0.025, min_dIy_dI: float = 0.01, mode_removal: bool = True, linearize: bool = True, dIydI: ndarray | None = None, dIydtheta: ndarray | None = None, target_relative_tolerance_linearization: float = 1e-08, target_dIy: float = 0.001, force_core_mask_linearization: bool = False, l2_reg: float = 1e-06, collinearity_reg: float = 1e-06, verbose: bool = False, plasma_descriptor_function: Callable[[object], ndarray] | None = None, mode_selection: str = 'coupling', n_linearization_workers: int = 1, force_up_down_symmetric: bool = False, passive_reflection_operator: ndarray | None = None, remove_odd_passive_modes: bool = True, symmetry_tolerance: float = 1e-08, myy_type: str = 'reduced', cache_myy: bool = True)[source]
Bases:
objectNonlinear solver for time-evolution of plasma equilibria and circuit dynamics.
This class provides an interface to evolve both the linearised and nonlinear dynamic problems. It sets up plasma and metal circuit equations, handles vessel mode decomposition and selection, and enables coupled nonlinear simulation of plasma and machine dynamics.
Notes
Main features:
Linear and nonlinear timestepping of equilibrium dynamics
Automatic timestep control based on growth rates
Passive vessel mode decomposition and mode selection
Coupling to FreeGSNKE profiles and equilibria
Support for regularization in nonlinear solves
Interfaces to Newton–Krylov solvers for plasma flux and circuit equations
- F_function_curr(trial_currents: ndarray, active_voltage_vec: ndarray) ndarray[source]
Evaluates the residual of the full non-linear plasma + circuit system for a given guess of currents at time t+dt.
This function casts the coupled plasma and circuit dynamics as a root-finding problem in the space of current values. The residual is defined as the difference between the currents predicted by the simplified circuit equations (given a plasma current distribution) and the input trial currents. A zero residual indicates that the trial currents and the corresponding plasma flux form a self-consistent solution of the full non-linear system.
The evaluation proceeds in two steps: 1. Compute the normalized plasma current distribution hatIy1 corresponding to the input trial_currents and the current plasma flux self.trial_plasma_psi. 2. Compute the iterated currents using the simplified circuit equations and the plasma distribution hatIy1. The residual is then: residual = iterated_currents - trial_currents.
- Parameters:
trial_currents (np.ndarray) – Vector of current values at time t+dt. The format matches self.currents_vec, typically including active coil currents, vessel mode currents, and the total plasma current (normalized by plasma_norm_factor).
active_voltage_vec (np.ndarray) – Vector of voltages applied to the active coils over the timestep.
- Returns:
Residual vector of currents, same format as self.currents_vec. Zero residual indicates a self-consistent solution of the plasma + circuit system for the timestep.
- Return type:
np.ndarray
- F_function_curr_GS(trial_currents: ndarray, active_voltage_vec: ndarray, rtol_NK: float) ndarray[source]
Full non-linear system of circuit eqs written as root problem in the vector of current values at time t+dt. Note that, differently from self.F_function_curr, here the plasma flux is not imposed, but self-consistently solved for based on the input trial_currents. Iteration consists of: trial_currents -> plasma flux, through static GS [trial_currents, plasma_flux] -> hatIy1, through calculating plasma distribution hatIy1 -> iterated_currents, through ‘simplified’ circuit eqs Residual: iterated_currents - trial_currents Residual is zero if trial_currents solve the full non-linear problem.
- Parameters:
trial_currents (np.ndarray) – Vector of current values. Same format as self.currents_vec.
active_voltage_vec (np.ndarray) – Vector of active voltages for the active coils, applied between t and t+dt.
rtol_NK (float) – Relative tolerance to be used in the static GS problem.
- Returns:
Residual in current values. Same format as self.currents_vec.
- Return type:
np.ndarray
- F_function_psi(trial_plasma_psi: ndarray, active_voltage_vec: ndarray, rtol_NK: float) ndarray[source]
Evaluate the residual of the plasma flux for the full non-linear system.
The coupled plasma and circuit dynamics are written as a root-finding problem in the (flattened) plasma flux at time t+dt. Given a trial plasma flux, the currents consistent with the circuit equations are computed and the static Grad-Shafranov (GS) problem is solved for these currents. A zero residual indicates that the trial flux is a self-consistent solution of the plasma + circuit system.
Iteration steps:
Compute the toroidal current density from trial_plasma_psi plus the tokamak flux (self.tokamak_psi), and from it the normalized plasma current distribution hatIy1.
Compute the currents from the simplified circuit equations using hatIy1 and solve the static GS problem for these currents (see hatIy1_iterative_cycle), updating self.eq2.plasma_psi.
Residual:
residual = self.eq2.plasma_psi - trial_plasma_psi.
- Parameters:
trial_plasma_psi (np.ndarray) – Flattened trial plasma flux at time t+dt, shape (nx * ny,).
active_voltage_vec (np.ndarray) – Vector of voltages applied to the active coils over the timestep.
rtol_NK (float) – Relative tolerance to be used in the static GS solver for the plasma flux.
- Returns:
Flattened residual of the plasma flux, shape (nx * ny,). Zero residual indicates a self-consistent solution of the plasma + circuit system.
- Return type:
np.ndarray
- M_coils_plasma(eq: object, greens: Callable[[...], ndarray]) ndarray[source]
Calculates the mutual inductance matrix between all tokamak coils and plasma grid points.
The matrix represents either the first or second derivative of the mutual inductance with respect to the vertical coordinate z, depending on the Greens function provided. This is used in stability and force calculations involving coil-plasma interactions.
- Parameters:
eq (FreeGSNKE equilibrium Object) – The equilibrium containing plasma and tokamak coil information.
greens (Callable[..., np.ndarray]) – The Greens function used for the calculation: - GreensBr for the first z-derivative of the mutual inductance. - GreensdBrdz for the second z-derivative of the mutual inductance.
- Returns:
M – Mutual inductance matrix between each coil (rows) and plasma grid point (columns), including coil polarity, multipliers, and R-coordinate weighting. The returned matrix is multiplied by -2π as per the standard formulation.
- Return type:
np.ndarray, shape (n_coils, n_plasma_pts)
Notes
plasma_pts are taken from eq.limiter_handler.plasma_pts, i.e., the reduced plasma domain.
Coil contributions are summed over all filaments in each coil.
- __init__(profiles: object, eq: object, GSStaticSolver: NKGSsolver, custom_coil_resist: ndarray | None = None, custom_self_ind: ndarray | None = None, full_timestep: float = 0.0001, max_internal_timestep: float = 0.0001, automatic_timestep: tuple[float, float] | bool = False, plasma_resistivity: float = 1e-06, plasma_norm_factor: float = 1000.0, blend_hatJ: float = 0, max_mode_frequency: float | None = 100.0, fix_n_vessel_modes: int = -1, threshold_dIy_dI: float = 0.025, min_dIy_dI: float = 0.01, mode_removal: bool = True, linearize: bool = True, dIydI: ndarray | None = None, dIydtheta: ndarray | None = None, target_relative_tolerance_linearization: float = 1e-08, target_dIy: float = 0.001, force_core_mask_linearization: bool = False, l2_reg: float = 1e-06, collinearity_reg: float = 1e-06, verbose: bool = False, plasma_descriptor_function: Callable[[object], ndarray] | None = None, mode_selection: str = 'coupling', n_linearization_workers: int = 1, force_up_down_symmetric: bool = False, passive_reflection_operator: ndarray | None = None, remove_odd_passive_modes: bool = True, symmetry_tolerance: float = 1e-08, myy_type: str = 'reduced', cache_myy: bool = True) None[source]
Initialize the nonlinear solver.
Sets up the equilibrium, profiles, circuit equations, vessel modes, Jacobians, and linearization for the coupled plasma–machine system.
- Parameters:
profiles (object) – Initial plasma profiles used to set up the linearisation.
eq (object) – Equilibrium object providing grid, machine geometry, and limiter info.
GSStaticSolver (NKGSsolver) – Static Grad–Shafranov solver for equilibrium solves.
custom_coil_resist (np.ndarray, optional) – Resistances for all coils (active + passive). Defaults to tokamak values.
custom_self_ind (np.ndarray, optional) – Mutual inductance matrix for coils. Defaults to tokamak values.
full_timestep (float, default=1e-4) – Time increment for full steps (dt).
max_internal_timestep (float, default=1e-4) – Maximum sub-step size for advancing circuit equations.
automatic_timestep (tuple[float, float] or False, default=False) – If set, determines the timestep from the instability timescale t_u:
full_timestep = |t_u * automatic_timestep[0]|andmax_internal_timestep = full_timestep / automatic_timestep[1].plasma_resistivity (float, default=1e-6) – Plasma resistivity value.
plasma_norm_factor (float, default=1e3) – Normalization factor for plasma current.
blend_hatJ (float, default=0) – Coefficient for blending plasma current distributions at t and t+dt.
max_mode_frequency (float or None, optional) – Maximum passive-mode frequency retained when mode_selection=”timescale” and fix_n_vessel_modes=-1. In coupling mode it provides the initial frequency mask before the coupling criteria are applied.
fix_n_vessel_modes (int, default=-1) – Fix the number of passive vessel modes; -1 uses the criteria selected by mode_selection. With mode_selection=”coupling”, a non-negative value retains the strongest-coupled modes. With mode_selection=”timescale”, it retains the lowest-frequency (longest-timescale) modes.
mode_selection ({"coupling", "timescale"}, default="coupling") – Strategy used to select passive vessel modes. “coupling” preserves the existing plasma-response-based selection. “timescale” uses only the passive modes’ electromagnetic frequencies: no coupling metric is used to include or exclude modes, including after the full Jacobian is built. The no-GS response is still evaluated to calibrate finite- difference perturbation sizes. Coupling-based selection is evaluated about the equilibrium supplied at initialisation. Use it with caution when the plasma position or shape is expected to change substantially, because the mode coupling can evolve with the equilibrium and the initially retained set may cease to be representative. In such cases, prefer timescale-only selection or validate the coupling-selected set across representative equilibria.
threshold_dIy_dI (float, default=0.025) – Relative coupling threshold for including vessel modes (must be a number in [0,1]).
min_dIy_dI (float, default=0.01) – Minimum coupling threshold for excluding vessel modes (must be a number in [0,1]).
mode_removal (bool, default=True) – If True, remove weakly coupled vessel modes after Jacobian calculation. This option applies only when mode_selection=”coupling”; it is disabled for timescale-only selection.
linearize (bool, default=True) – Whether to set up the linearised problem.
dIydI (np.ndarray, optional) – Plasma current Jacobian wrt coil and plasma currents.
dIydtheta (np.ndarray, optional) – Plasma current Jacobian wrt profile parameters.
target_relative_tolerance_linearization (float, default=1e-8) – Relative tolerance for GS solve during Jacobian computation.
target_dIy (float, default=1e-3) – Target perturbation size for Jacobian finite differences.
force_core_mask_linearization (bool, default=False) – Enforce same core mask during finite-difference Jacobian evaluation.
l2_reg (float, default=1e-6) – L2 Tikhonov regularization for nonlinear solver.
collinearity_reg (float, default=1e-6) – Additional penalty for collinear terms in nonlinear solver.
verbose (bool, default=False) – Print diagnostic output during initialization.
force_up_down_symmetric (bool, default=False) – Restrict every Grad-Shafranov solve and plasma-response Jacobian to the even-in-Z subspace. This strict path requires a grid symmetric about Z=0, a symmetric limiter mask, and an even plasma initial condition. Invalid grids and masks are rejected before the machine operators are modified. Retained active circuits must be even. Small residual asymmetries in the machine resistance, inductance, sampled Green functions (
eq._vgreenis updated in place, along with any un-mirrored passive filament refinements oneq.tokamak), and metal-plasma coupling are removed by reflection averaging.passive_reflection_operator (ndarray, optional) – Reflection map for passive currents. Required with
force_up_down_symmetric=Truewhen passive structures are present; by default odd passive modes are removed before plasma coupling is calculated. Useprepare_up_down_symmetric_machineto infer this map from a standard machine description.remove_odd_passive_modes (bool, default=True) – Whether to remove odd-in-Z passive modes when
force_up_down_symmetric=True. Set False to retain the full passive-mode basis as a reference while still constraining all Grad-Shafranov solves and plasma-response Jacobians to be even.symmetry_tolerance (float, default=1e-8) – Maximum relative commutator error permitted between passive dynamics and reflection.
plasma_descriptor_function (Callable[[object], np.ndarray] or None, optional) – Function taking an equilibrium and returning a 1D array of plasma descriptors (e.g. shape parameters), whose linear response to the currents and profile parameters is also recorded during linearisation. Defaults to a function returning
np.array([0.0]).n_linearization_workers (int, default=1) – Number of worker processes used to build independent
dIydIanddIydthetacolumns during initial and later linearisations. A value of 1 retains the serial calculation.myy_type (str, default="reduced") – Either “reduced” to define Myy over reduced domain in real space, or “fft” to define Myy over the full domain in Fourier space.
cache_myy (bool, default=True) – Controls whether the Myy matrix is cached at initialization or rebuilt for every product.
- Raises:
ValueError – If mode_selection is not “coupling” or “timescale”, if min_dIy_dI > threshold_dIy_dI (when coupling-based selection is used with fix_n_vessel_modes < 0), if automatic_timestep is not a pair of numbers, or if n_linearization_workers is not a positive integer.
- assign_currents(currents_vec: ndarray, eq: object, profiles: object) None[source]
Assigns the input currents to the equilibrium and plasma profiles.
The function updates: - The total plasma current in eq and profiles. - The metal (vessel + active coil) currents in the tokamak, converting
from normal mode representation to physical coil currents.
- Parameters:
currents_vec (np.ndarray) –
- Vector of current values to assign. Format:
(active coil currents, vessel normal mode currents, total plasma current / plasma_norm_factor)
eq (FreeGSNKE equilibrium Object) – Equilibrium object to be modified. Its _current attribute and tokamak coil currents are updated.
profiles (FreeGSNKE profiles Object) – Profiles object to be modified. Its total plasma current Ip is updated.
Notes
Side effects:
Updates self.vessel_currents_vec with the reconstructed physical currents.
Modifies the input eq and profiles in-place.
- assign_currents_solve_GS(currents_vec: ndarray, rtol_NK: float) None[source]
Assigns the input currents to the auxiliary equilibrium (self.eq2) and profiles (self.profiles2), then solves the static Grad-Shafranov (GS) problem to find the resulting plasma flux and current distribution.
- Parameters:
currents_vec (np.ndarray) –
- Vector of current values to assign. Format matches self.assign_currents:
(active coil currents, vessel normal mode currents, total plasma current / plasma_norm_factor)
rtol_NK (float) – Relative tolerance to be used in the static GS solver.
Notes
Side effects:
Updates self.eq2._current and self.profiles2.Ip.
Updates self.eq2.tokamak.current_vec with the reconstructed physical currents.
Solves the GS equation, updating self.eq2.plasma_psi and self.profiles2.jtor.
- assign_trial_solution_state(from_linear: bool = False) None[source]
Copy the current trial solution (self.trial_currents, and self.trial_plasma_psi if from_linear=False) into self.currents_vec, self.eq1, self.profiles1, self.Iy, and self.hatIy.
This is the state-synchronisation portion of step_complete_assign, factored out so it can be used on its own (e.g. to sync self.eq1/self.profiles1 to the just-solved trial state before relinearising) without also completing an externally-requested timestep – i.e. without advancing self.time/self.step_no or overwriting the self.currents_vec_m1/self.Iy_m1 “previous step” history.
- Parameters:
from_linear (bool, default=False) – If True, only the linearised solution is applied. Reduces the number of full GS solves by copying auxiliary equilibrium and profiles to the main state.
Notes
Side effects:
Updates self.currents_vec, self.Iy, and self.hatIy.
Modifies self.eq1 and self.profiles1 to reflect the trial solution.
- build_current_vec(eq: object, profiles: object) None[source]
Constructs the vector of currents for the dynamics solver.
The vector self.currents_vec includes, in order: - Active coil currents - Selected vessel normal mode currents - Total plasma current normalized by plasma_norm_factor
- Parameters:
eq (FreeGSNKE equilibrium object) – The equilibrium used to extract all metal currents before any mode truncation.
profiles (FreeGSNKE profiles object) – Profiles of the initial equilibrium. Used to extract the total plasma current.
- build_dIydI_j(j: int, rtol_NK: float) tuple[ndarray, float][source]
Compute the finite-difference derivative d(Iy)/dI_j using the prepared perturbation.
Uses the perturbation ΔI_j inferred by prepare_build_dIydI_j to compute the actual finite-difference derivative of the poloidal current vector Iy with respect to coil current I_j. Solves the Grad–Shafranov equilibrium at the perturbed current.
- Parameters:
j (int) – Index of the coil current to be varied, corresponding to self.currents_vec.
rtol_NK (float) – Relative tolerance for the static Grad–Shafranov solver.
- Returns:
dIydIj (np.ndarray) – Finite-difference derivative d(Iy)/dI_j, a 1D array over all grid points in the reduced plasma domain.
rel_ndIy (float) – Relative norm of the induced change in Iy, normalized by self.nIy.
- build_dIydI_noGS(force_core_mask_linearization: bool, starting_dI: ndarray, core_mask: ndarray, verbose: bool) None[source]
Compute a first estimate of the Jacobian norm dIy/dI without solving GS.
This routine evaluates the plasma current response to perturbations in each coil or mode current using only the modified tokamak Green’s functions (no Grad–Shafranov solves). It calibrates the perturbation amplitudes used by the full linearisation. When mode_selection=”coupling”, the resulting Jacobian norms are also used for an initial sifting of passive vessel modes; timescale-only selection deliberately ignores those norms.
If force_core_mask_linearization is True, the perturbation size for each mode is adjusted to ensure that the diverted core mask of the perturbed equilibrium matches the reference core mask. In that case, self.starting_dI and self.approved_target_dIy are updated accordingly.
- Parameters:
force_core_mask_linearization (bool) – Whether to enforce identical core masks between perturbed and reference equilibria when computing finite-difference derivatives. If True, perturbation amplitudes are reduced until the core mask matches.
starting_dI (np.ndarray) – Initial perturbation amplitudes for each independent coil/mode current. This array is updated in place depending on the masking strategy.
core_mask (np.ndarray of bool) – Boolean mask indicating the core region of the reference equilibrium.
verbose (bool) – If True, print diagnostic information about mode perturbations and accepted perturbation sizes.
Notes
Updates the following attributes:
- self.dIydI_noGSnp.ndarray, shape (n_plasma_points, n_coils)
Approximate Jacobian of plasma current distribution wrt coil currents, computed without GS solves.
- self.ndIydI_no_GSnp.ndarray, shape (n_coils,)
Norm of the finite-difference dIy/dI column for each coil/mode, used in coupling-based mode selection. Each norm uses the same perturbation as its corresponding response, before preparing the next perturbation.
- self.rel_ndIynp.ndarray, shape (n_coils,)
Relative plasma current perturbation norms for each mode.
- self.starting_dInp.ndarray
Adjusted perturbation amplitudes after enforcing masking strategy.
- self.approved_target_dIynp.ndarray
Updated target norms for plasma current perturbations (if core mask enforcement applied).
- build_dIydtheta(profiles: object, rtol_NK: float, plasma_descriptor_function: Callable[[object], ndarray], verbose: bool = False) tuple[ndarray, ndarray, ndarray][source]
Compute the finite-difference Jacobian d(Iy)/dθ using pre-scaled perturbations.
This function calculates the derivative of the poloidal current vector Iy with respect to the plasma profile parameters θ. Perturbations Δθ are taken from self.final_dtheta_record, which are inferred previously by prepare_build_dIydtheta to produce controlled changes in Iy. For each perturbed profile, the Grad–Shafranov equilibrium is solved and the resulting Iy change is measured. The final Jacobian is the normalized change per unit Δθ.
- Parameters:
profiles (FreeGSNKE profiles object) – Profiles object of the linearization-point equilibrium.
rtol_NK (float) – Relative tolerance for the Newton–Krylov Grad–Shafranov solver.
plasma_descriptor_function (Callable[[object], np.ndarray]) – Function returning the 1D array of plasma descriptors of an equilibrium.
verbose (bool, optional) – If True, print intermediate diagnostic information (default: False).
- Returns:
dIydtheta (np.ndarray, shape (len(Iy), n_profiles_parameters)) – Finite-difference derivative of Iy with respect to each profile parameter.
rel_ndIy (np.ndarray, shape (n_profiles_parameters,)) – Relative norm of ΔIy induced by each perturbation, normalized by self.nIy.
dvdtheta (np.ndarray, shape (n_descriptors, n_profiles_parameters)) – Finite-difference derivative of the plasma descriptors with respect to each profile parameter.
Notes
This function modifies the plasma profiles temporarily during the finite-difference calculation, then resets them to the original state.
Supports both the standard (alpha_m, alpha_n, paxis/betap/Beta0) parameters and Lao-style profile coefficients (multiple alpha and beta terms).
- build_linearization(eq: object, profiles: object, dIydI: ndarray | None, dIydtheta: ndarray | None, target_relative_tolerance_linearization: float, force_core_mask_linearization: bool, verbose: bool, plasma_descriptor_function: Callable[[object], ndarray] | None) None[source]
Builds the Jacobians d(Iy)/dI and d(Iy)/dtheta for linearizing the plasma-current response around a given equilibrium. These Jacobians are used to set up the solver for the linearised problem, providing initial slopes for both coil currents and plasma profile parameters.
This function optionally computes dIydI and dIydtheta if they are not provided. Perturbations are applied to coil currents and profile parameters, and the corresponding changes in the poloidal current vector Iy are used to form finite-difference derivatives. The perturbations are adjusted to ensure stability and, if requested, to maintain the plasma core mask.
- Parameters:
eq (FreeGSNKE equilibrium object) – Equilibrium around which to linearize.
profiles (FreeGSNKE profiles object) – Plasma profiles associated with the equilibrium.
dIydI (np.ndarray or None) – Optional input Jacobian of plasma current density with respect to metal currents. If None, it will be computed internally.
dIydtheta (np.ndarray or None) – Optional input Jacobian of plasma current density with respect to plasma profile parameters. If None, it will be computed internally.
target_relative_tolerance_linearization (float) – Relative tolerance used in the static Grad–Shafranov solver during finite-difference calculations.
force_core_mask_linearization (bool) – If True, adjusts the perturbations so that the perturbed plasma core mask remains identical to the original mask.
verbose (bool) – If True, prints intermediate results including initial and final perturbations, relative changes in Iy, and Grad–Shafranov residuals.
plasma_descriptor_function (Callable[[object], np.ndarray] or None) – Function returning the 1D array of plasma descriptors of an equilibrium (used to build the descriptor Jacobians). If None, the descriptors are not recomputed.
Notes
This function updates self.dIydI and self.dIydtheta (or copies from initial conditions
if already computed) and stores final perturbation magnitudes in self.final_dI_record and self.final_dtheta_record. - The core mask consistency is checked when force_core_mask_linearization is True. - The function also updates the derivatives of coil positions with respect to currents in self.dRZdI.
- calc_lumped_plasma_resistance(norm_red_Iy0: ndarray, norm_red_Iy1: ndarray) float[source]
Compute the lumped plasma resistance using the plasma resistance matrix R_yy.
The lumped resistance is calculated by contracting the 1D plasma resistance vector (self.plasma_resistance_1d) with two normalized plasma current distribution vectors. This provides an effective scalar resistance for the given current profiles.
- Parameters:
norm_red_Iy0 (np.ndarray) – Normalized plasma current distribution vector at time t_0. The entries should be normalized so that their sum equals 1.
norm_red_Iy1 (np.ndarray) – Normalized plasma current distribution vector at time t_1. The entries should be normalized so that their sum equals 1.
- Returns:
Lumped plasma resistance corresponding to the given current distributions.
- Return type:
float
- calculate_Leuer_parameter() None[source]
Calculates the Leuer stability parameter for the plasma, which quantifies the passive vertical stability provided by surrounding metals and active coils.
The Leuer parameter, as defined in Leuer (1989, “Passive Vertical Stability in the Next Generation Tokamaks”, Eq. 6), is the ratio of stabilising force gradients induced by metals to the de-stabilising force gradients caused by the plasma and coil currents.
The calculation involves: - Mutual inductance derivatives between coils and plasma points (first and second z-derivatives). - Mutual inductances between metal coils themselves. - Plasma current distribution and coil currents. - Stabilising forces (from active and passive coils) and de-stabilising forces. - Computation of Leuer parameters in different configurations.
Notes
Updates the following attributes:
- actives_stab_forcefloat
Stabilising force due to active coils.
- passives_stab_forcefloat
Stabilising force due to passive coils.
- all_coils_stab_forcefloat
Stabilising force due to all metal coils (active + passive).
- actives_destab_forcefloat
De-stabilising force due to active coils.
- passives_destab_forcefloat
De-stabilising force due to passive coils.
- all_coils_destab_forcefloat
De-stabilising force due to all metal coils.
- Leuer_passive_stab_over_active_destabfloat
Ratio of passive stabilising force to active coil de-stabilising force.
- Leuer_metals_stab_over_active_destabfloat
Ratio of total metal stabilising force to active coil de-stabilising force.
- Leuer_metals_stab_over_metals_destabfloat
Ratio of total metal stabilising force to total metal de-stabilising force.
References
Leuer, J. A., “Passive Vertical Stability in the Next Generation Tokamaks,” 1989, 10.13182/FST89-A39747.
- calculate_hatIy(trial_currents: ndarray, plasma_psi: ndarray) ndarray[source]
Computes the normalized plasma current distribution (hatIy) corresponding to a given set of currents and plasma flux.
- Parameters:
trial_currents (np.ndarray) – Full vector of currents (active coils, vessel modes, plasma current).
plasma_psi (np.ndarray) – Plasma flux on the full grid (2D array).
- Returns:
Normalized plasma current distribution on the reduced domain.
- Return type:
np.ndarray
- calculate_hatIy_GS(trial_currents: ndarray, rtol_NK: float, record_for_updates: bool = False) ndarray[source]
Computes the normalized plasma current distribution (hatIy) corresponding to a given set of currents by solving the static Grad-Shafranov problem.
- Parameters:
trial_currents (np.ndarray) – Full vector of currents (active coils, vessel modes, plasma current).
rtol_NK (float) – Relative tolerance for the static GS solver.
record_for_updates (bool, optional) – If True, records auxiliary updates (not always needed).
- Returns:
Normalized plasma current distribution on the reduced plasma domain.
- Return type:
np.ndarray
- calculate_rel_tolerance_GS(trial_plasma_psi: ndarray, a_res_GS: ndarray | None = None) float[source]
Computes the relative residual of the plasma flux for the static Grad-Shafranov (GS) problem, comparing the GS residual to the actual change in plasma flux due to dynamics. This metric quantifies the convergence of the timestepper for the plasma flux update.
The relative residual is defined as:
r_res_GS = max(|GS_residual|) / max(|Δpsi|)
where Δpsi = psi(t+dt) - psi(t). If the GS residual a_res_GS is not provided, it is computed internally using the static GS solver.
- Parameters:
trial_plasma_psi (np.ndarray) – Plasma flux at the current timestep, psi(t+dt), shape (nx, ny).
a_res_GS (np.ndarray, optional) – Residual of the static GS problem at t+dt. If None, it will be calculated internally. Shape should match the flattened plasma flux.
- Returns:
Relative plasma flux residual. Values close to 0 indicate good convergence of the plasma flux update.
- Return type:
float
- calculate_rel_tolerance_currents(current_residual: ndarray, curr_eps: float) ndarray[source]
Computes the relative residual of the current update compared to the actual step taken in the currents. This quantifies the convergence of the timestepper by comparing the residual to the magnitude of the current change.
The relative residual is defined as:
relative_residual_i = |current_residual_i / max(|ΔI_i|, curr_eps)|
where ΔI_i = trial_currents_i - currents_vec_m1_i, and curr_eps prevents division by very small steps.
- Parameters:
current_residual (np.ndarray) – Residual of the current values at the current timestep. Same format as self.currents_vec.
curr_eps (float) – Minimum allowable step size in the currents. Used to avoid artificially large relative residuals when the step is very small.
- Returns:
Relative residual of the current update. Same format as self.currents_vec. Values close to 0 indicate good convergence of the timestep.
- Return type:
np.ndarray
- check_and_change_active_coil_resistances(active_coil_resistances: ndarray | None) None[source]
Checks if new active coil resistances are provided and updates them if needed.
This method compares the input array of active coil resistances with the current resistances stored in self.evol_metal_curr. If the input is different, it resets the resistances, updates the solvers accordingly, and prints the new coil resistances.
- Parameters:
active_coil_resistances (np.ndarray or None) – Array of new resistances for the active coils. If None, no changes are made.
Notes
If the input resistances are identical to the current ones, the method does nothing.
When resistances are updated, self.set_solvers() is called to ensure the
solvers reflect the new electrical properties. - The updated resistances are printed for confirmation.
- check_and_change_plasma_resistivity(plasma_resistivity: float | None, relative_threshold_difference: float = 1e-05) None[source]
Check if the plasma resistivity differs from the current value and update it if necessary.
Compares the new plasma_resistivity with the current self.plasma_resistivity. If the relative difference exceeds relative_threshold_difference, the resistivity is reset using reset_plasma_resistivity, which also updates the associated solver objects.
- Parameters:
plasma_resistivity (float or None) –
New scalar value of the plasma resistivity [Ohm·m] (None leaves it unchanged). The resistance at each grid point in the reduced domain is computed as
R_yy = 2 * π * plasma_resistivity * R / (dR * dZ)
where R is the major radius of the grid point and dR*dZ is the area of the corresponding domain element.
relative_threshold_difference (float, optional) – Relative threshold for updating the resistivity. Default is 1e-5. If the relative change in resistivity exceeds this value, the resistivity is reset.
- check_and_change_profiles(profiles_parameters: dict | None = None) None[source]
Updates the plasma current profile parameters at time t+dt if new values are provided.
This method checks whether a dictionary of new profile parameters is supplied. If so, it updates both the evolving equilibrium profiles (self.profiles1) and the auxiliary profiles (self.profiles2) accordingly. For profiles of type “Lao85”, the internal profile initialization routine is called after updating the parameters. A flag is set to indicate that a change occurred.
- Parameters:
profiles_parameters (dict or None, optional) – Dictionary of profile parameters to update. Keys and values should match the attributes of the profile object (see get_profiles_values for structure). If None, no changes are made and the profiles remain unchanged.
Notes
Sets self.profiles_change_flag = 1 if parameters are updated, otherwise 0.
Both the main (profiles1) and auxiliary (profiles2) profiles are updated
to ensure consistency during timestep calculations.
- currents_from_hatIy(hatIy1: ndarray, active_voltage_vec: ndarray) ndarray[source]
Computes the full set of currents at time t+dt from a guess of the normalized plasma current distribution, using the simplified circuit solver.
- Parameters:
hatIy1 (np.ndarray) – Guess for the normalized plasma current distribution at time t+dt (sum=1, reduced plasma domain).
active_voltage_vec (np.ndarray) – Voltages applied to the active coils between t and t+dt.
- Returns:
Full current vector at t+dt, matching the format of self.currents_vec.
- Return type:
np.ndarray
Notes
Workflow:
Computes a blended plasma distribution using make_blended_hatIy.
Computes Myy_hatIy_left = self.handleMyy.dot(blended_hatIy).
3. Calls self.simplified_solver_J1.stepper to solve for all currents, given the blended distribution and applied coil voltages.
- get_profiles_values(profiles: object) None[source]
Extracts and stores relevant properties from a FreeGSNKE profiles object.
Sets internal attributes describing the profile type, number of independent parameters, and their values, which are used in linearisation and stepper calculations.
- Parameters:
profiles (FreeGSNKE profiles object) – The profiles object of the initial equilibrium. This provides the parameters defining the plasma current density profile, e.g., alpha_m, alpha_n, paxis, betap, Beta0, or Lao coefficients.
- get_vessel_currents(eq: object) None[source]
Extracts and stores all metal currents from a given equilibrium.
Retrieves currents for both active coils and passive vessel structures from the input equilibrium’s tokamak object. The values are stored in self.vessel_currents_vec.
- Parameters:
eq (FreeGSNKE equilibrium object) – The equilibrium from which to extract metal currents. Uses eq.tokamak to access current values.
- hatIy1_iterative_cycle(hatIy1: ndarray, active_voltage_vec: ndarray, rtol_NK: float) None[source]
Performs one iteration of the cycle: 1. Uses a guessed plasma current distribution at t+dt (hatIy1) to compute all currents. 2. Solves the static Grad-Shafranov (GS) problem to find the resulting plasma flux and updated plasma current distribution.
- Parameters:
hatIy1 (np.ndarray) – Guess for the normalized plasma current distribution at t+dt. Must sum to 1 (reduced plasma domain only).
active_voltage_vec (np.ndarray) – Voltages applied to the active coils between t and t+dt.
rtol_NK (float) – Relative tolerance for the static GS solver.
- initialize_from_ICs(eq: object, profiles: object, target_relative_tolerance_linearization: float = 1e-07, dIydI: ndarray | None = None, dIydtheta: ndarray | None = None, force_core_mask_linearization: bool = False, verbose: bool = False, plasma_descriptor_function: Callable[[object], ndarray] | None = None, cache_myy: bool | None = None) None[source]
Initialize the dynamics solver from a given equilibrium and plasma profiles.
This method prepares all internal structures required for advancing the coupled plasma–vessel dynamics, including:
Building the vector of currents (self.currents_vec) comprising
active coil currents, selected vessel normal modes, and normalized plasma current. - Setting up auxiliary equilibrium (eq2) and profile (profiles2) objects for intermediate calculations. - Computing the linearized Jacobians d(Iy)/dI and d(Iy)/dtheta if not provided, and transferring them to the linear solver.
- Parameters:
eq (FreeGSNKE equilibrium object) – The initial equilibrium, used to assign all metal currents.
profiles (FreeGSNKE profiles object) – Profiles of the initial equilibrium, used to assign the total plasma current.
target_relative_tolerance_linearization (float, default=1e-7) – Relative tolerance for static Grad–Shafranov solves during initialization and Jacobian computation. This does not affect the solver’s runtime tolerance.
dIydI (np.ndarray, optional) – Jacobian of plasma current distribution with respect to metal currents and total plasma current. Shape (np.sum(plasma_domain_mask), n_metal_modes+1). If not provided, it is computed from the given equilibrium.
dIydtheta (np.ndarray, optional) – Jacobian of plasma current distribution with respect to plasma profile parameters. If not provided, it is computed from the given equilibrium.
force_core_mask_linearization (bool, default=False) – If True, enforces that the perturbed plasma core mask remains identical when computing d(Iy)/dI.
verbose (bool, default=False) – Enables progress printouts during initialization.
plasma_descriptor_function (Callable[[object], np.ndarray] or None, optional) – Function returning the 1D array of plasma descriptors of an equilibrium. Defaults to
self.plasma_descriptor_function.cache_myy (bool, default=None) – Used to change the caching behavior of Myy: if True, will (re)compute the Myy matrix and make it so that it is calculated and cached only when its value changes. If False, the Myy matrix will be discarded (if it had been cached previously) and will be recalculated every time a product with Myy is computed. If None, no action is taken and whatever behavior was preset is preserved.
Notes
Side effects:
Sets up self.eq1, self.profiles1, self.eq2, self.profiles2.
Initializes self.currents_vec, self.Iy, self.hatIy, self.blended_hatIy.
Builds the linearization and transfers it to the linear solver (self.linearised_sol).
Updates the Myy matrix through self.handleMyy.
- make_blended_hatIy_(hatIy1: ndarray, blend: float) None[source]
Produces a weighted average of the current plasma distribution at time t (self.hatIy) and a guess for the distribution at time t+dt (hatIy1).
- Parameters:
hatIy1 (np.ndarray) – Guess for the normalized plasma current distribution at time t+dt. Must sum to 1. Only covers the reduced plasma domain.
blend (float) – Weighting factor between 0 and 1. - blend=0 → only uses hatIy1 - blend=1 → only uses hatIy (current time)
Notes
Side effects:
- Sets self.blended_hatIy to the weighted combination:
blended_hatIy = (1 - blend) * hatIy1 + blend * self.hatIy
- new_plasma_descriptors(new_currents: ndarray, new_profiles: ndarray) ndarray[source]
Estimate the plasma descriptors vector v from the linearisation.
- Parameters:
new_currents (np.ndarray) – Currents (in the format of self.currents_vec) at which to evaluate the descriptors.
new_profiles (np.ndarray) – Independent profile parameters at which to evaluate the descriptors.
- Returns:
Linear estimate of the plasma descriptors, i.e. the initial descriptors plus the current and profile contributions.
- Return type:
np.ndarray
- nlstepper(active_voltage_vec: ndarray, profiles_parameters: dict | None = None, plasma_resistivity: float | None = None, target_relative_tol_currents: float = 0.005, target_relative_tol_GS: float = 0.003, working_relative_tol_GS: float = 0.001, target_relative_unexplained_residual: float = 0.5, max_n_directions: int = 3, step_size_psi: float = 2.0, step_size_curr: float = 0.8, scaling_with_n: float = 0, blend_GS: float = 0.5, curr_eps: float = 1e-05, max_no_NK_psi: float = 5.0, clip: float = 5, verbose: int = 0, linear_only: bool = False, max_solving_iterations: int = 50, custom_active_coil_resistances: ndarray | None = None, no_GS: bool = False, relinearise_threshold: float | list[float] | None = None) None[source]
Advance the system by one timestep using a nonlinear Newton–Krylov solver.
This method advances the plasma and coil current state from time
ttot + dt_stepby solving the coupled dynamic–static inverse equilibrium problem. The solver uses a Newton–Krylov (NK) strategy alternating between:A static Grad–Shafranov (GS) solve at fixed currents.
A dynamic current solve at fixed plasma flux.
If
linear_only=True, only the linearised dynamic problem is evolved and no nonlinear fixed-point or NK iterations are executed.On successful convergence, the method updates:
self.currents_vec: advanced coil currents,self.eq1: updated GS equilibrium,self.profiles1: updated plasma profiles.
The nonlinear step proceeds as:
1. Solve the linearised dynamic problem to produce initial guesses for currents and plasma flux (
trial_currents,trial_plasma_psi). 2. Optionally (ifno_GS=False), solve the GS equation and blend the result with the trial flux usingblend_GS. 3. At fixed currents, perform NK iterations on the plasma flux until the GS residual meets the working tolerance. 4. At fixed plasma flux, perform NK iterations on the currents until the current residual meets the required tolerance. 5. Repeat steps 2–4 until both the current convergence criterion and the GS convergence criterion are satisfied. 6. Ifrelinearise_thresholdis set and the baseline toroidal current changes sufficiently, trigger a full relinearisation before continuing. 7. On convergence, commit the solution to the object’s internal state.- Parameters:
active_voltage_vec (np.ndarray) – Voltages applied to the active coils between
tandt + dt_step.profiles_parameters (dict or None, optional) – Parameters to update the profile model. If None, profiles are unchanged.
plasma_resistivity (float, optional) – New plasma resistivity. If None, resistivity remains unchanged.
target_relative_tol_currents (float, default=0.005) – Convergence tolerance for the dynamic current solve.
target_relative_tol_GS (float, default=0.003) – Convergence tolerance for the final GS solve.
working_relative_tol_GS (float, default=0.001) – Tighter intermediate tolerance for GS updates inside NK cycles.
target_relative_unexplained_residual (float, default=0.5) – NK termination threshold based on unexplained residual fraction.
max_n_directions (int, default=3) – Maximum Krylov basis size for each NK update.
step_size_psi (float, default=2.0) – Exploratory finite-difference step size for NK updates in flux space.
step_size_curr (float, default=0.8) – Exploratory step size for NK updates in current space.
scaling_with_n (float, default=0) – Exponent for scaling candidate steps by
(1 + n_iter)**scaling_with_n.blend_GS (float, default=0.5) – Blending factor for updating trial GS solutions.
curr_eps (float, default=1e-5) – Regularisation term to avoid division by small current differences.
max_no_NK_psi (float, default=5.0) – Threshold for enabling NK flux updates.
clip (float, default=5) – Maximum allowed NK update magnitude (per direction).
verbose (int, default=0) – Verbosity level: 0 = silent, 1 = coarse, 2 = detailed.
linear_only (bool, default=False) – If True, perform only the linearised update and skip nonlinear solves.
max_solving_iterations (int, default=50) – Maximum allowed NK cycles.
custom_active_coil_resistances (np.ndarray or None, optional) – Custom resistances for active coils. If provided, overrides defaults.
no_GS (bool, default=False) – If True, skip all GS solves (current-only evolution). Intended mainly for specialised debugging or reduced models. Works with linear_only=True only.
relinearise_threshold (float or list[float] or None, optional) – If None or linear_only=False, no relinearisation occurs. If no_GS=False, triggers a relinearisation when the change in toroidal current since the last linearisation exceeds this relative threshold (float). If no_GS=True, triggers a relinearisation when the absolute change in the descriptors exceeds this threshold(s). If this threshold is scalar then the maximum absolute change is considered otherwise an elementwise comparison occurs.
- Raises:
ValueError – If no_GS is True while linear_only is False.
Notes
The solver simultaneously advances plasma equilibrium and circuit dynamics, using the linearised operators built by
relinearise(). If convergence is not achieved, the method stops aftermax_solving_iterationsiterations, prints a warning and setsself.convergedto False (no exception is raised).
- prepare_build_dIydI_j(j: int, rtol_NK: float | None, target_dIy: float, starting_dI: float, GS: bool = True) tuple[ndarray, float][source]
Prepare the finite-difference derivative d(Iy)/dI_j by estimating the perturbation ΔI_j.
This function determines the size of a current perturbation ΔI_j that produces a target change in the poloidal current vector Iy with norm ||ΔIy|| = target_dIy. Optionally, the full Grad–Shafranov (GS) problem can be solved to update the equilibrium, or a simplified approach using the modified tokamak flux can be used.
- Parameters:
j (int) – Index of the coil current to be varied, corresponding to self.currents_vec.
rtol_NK (float or None) – Relative tolerance for the static Grad–Shafranov solver (unused if GS is False, in which case None may be passed).
target_dIy (float) – Target norm of the induced change in Iy used to scale the perturbation.
starting_dI (float) – Initial guess for the coil current perturbation ΔI_j.
GS (bool, optional) – If True, solve the full Grad–Shafranov problem; if False, use modified tokamak flux without solving GS (default: True).
- Returns:
dIy_scaled (np.ndarray) – Initial finite-difference estimate of ΔIy / ΔI_j.
rel_ndIy (float) – Relative norm of the induced change in Iy, normalized by self.nIy.
- prepare_build_dIydtheta(profiles: object, rtol_NK: float, target_dIy: ndarray, starting_dtheta: ndarray, plasma_descriptor_function: Callable[[object], ndarray], verbose: bool = False) tuple[ndarray, ndarray, ndarray][source]
Prepare finite-difference evaluation of d(Iy)/dθ, where θ parameterises the plasma current density profile.
Perturbs the profile parameters by small trial shifts starting_dtheta, solves the Grad–Shafranov equilibrium for each perturbed profile, and measures the corresponding change in Iy (poloidal current distribution). The trial perturbations are then rescaled so that the induced change in Iy has prescribed norm target_dIy. This sets up consistent perturbation sizes for later derivative calculations.
- Parameters:
profiles (FreeGSNKE profiles object) – Profiles object of the linearisation-point equilibrium.
rtol_NK (float) – Relative tolerance for the Newton–Krylov GS solves.
target_dIy (np.ndarray) – Desired norms of ΔIy for each perturbed direction.
starting_dtheta (np.ndarray) – Initial perturbations of the profile parameters, used to infer the scaling between Δθ and ΔIy.
plasma_descriptor_function (Callable[[object], np.ndarray]) – Function returning the 1D array of plasma descriptors of an equilibrium.
verbose (bool, optional) – If True, print intermediate diagnostic information (default: False).
- Returns:
dIy_0 (np.ndarray, shape (len(Iy), n_profiles_parameters)) – Raw changes in Iy from the initial perturbations.
rel_ndIy_0 (np.ndarray, shape (n_profiles_parameters,)) – Relative norms of ΔIy per unit perturbation, normalised by self.nIy.
dvdtheta_0 (np.ndarray, shape (n_descriptors, n_profiles_parameters)) – Initial finite-difference response of the plasma descriptors to each profile parameter.
Notes
Updates the following attributes:
- self.final_dtheta_recordnp.ndarray
Adjusted perturbations Δθ that will yield ΔIy with the target norms.
- relinearise(*, verbose: bool = False) None[source]
Recompute (relinearise) the linearisation of the equilibrium problem around the current plasma state.
This method temporarily constructs auxiliary equilibria and profile objects in order to rebuild all linearised operators and sensitivity matrices used by the solver. After the linearisation operators are rebuilt, the original equilibria and profiles are restored so that the nonlinear state of the main solver remains unchanged.
- Parameters:
verbose (bool, optional) – If True, print progress messages during the relinearisation process. Default is False.
- remove_modes(eq: object, selected_modes_mask: ndarray) None[source]
Remove unselected normal modes and update circuit equations.
Given an equilibrium and a mask over the current mode set, this method reduces the dimensionality of the system by discarding modes marked as inactive in selected_modes_mask. The circuit equations, current vector, and nonlinear solver are reinitialized consistently with the reduced system size.
- Parameters:
eq (FreeGSNKE equilibrium) – Equilibrium object containing plasma state information.
selected_modes_mask (np.ndarray of bool, shape (n_modes,)) – Boolean mask indicating which modes to keep. Entries corresponding to True are retained, and those corresponding to False are removed. Must have the same shape as self.currents_vec at the time of call.
Notes
Updates the following attributes:
- self.n_metal_modesint
Number of remaining independent modes after reduction.
- self.extensive_currents_dimint
Dimension of the reduced current vector (n_metal_modes + 1).
- self.arange_currentsnp.ndarray
Index array for the reduced system, ranging from 0 to self.extensive_currents_dim - 1.
- self.currents_vecnp.ndarray
Zero-initialized current vector of reduced dimensionality.
- self.circuit_eq_residualnp.ndarray
Residual vector for the reduced circuit equations.
- self.currents_nk_solvernk_solver.nksolver
Nonlinear solver instance reinitialized for the reduced system size.
- self.simplified_solver_J1simplified_solver_J1
Rebuilt solver instance consistent with reduced system.
- self.linearised_sollinear_solver
Rebuilt linearised solver instance consistent with reduced system.
- reset_plasma_resistivity(plasma_resistivity: float) None[source]
Reset the plasma resistivity and update all relevant solver objects.
This updates self.plasma_resistance_1d, the diagonal of the plasma resistance matrix restricted to the reduced domain (inside the limiter), and also propagates the updated resistivity to the linearized and simplified solvers.
- Parameters:
plasma_resistivity (float) –
Scalar value of the plasma resistivity [Ohm·m]. The resistance at each grid point in the reduced domain is computed as
R_yy = 2 * π * plasma_resistivity * R / (dR * dZ)
where R is the major radius of the grid point and dR*dZ is the area of the corresponding domain element.
- reset_timestep(full_timestep: float, max_internal_timestep: float) None[source]
Reset the timestep parameters for the simulation.
Updates the full timestep used to advance the dynamics and the maximum allowed internal sub-timestep used for circuit equation integration. Resets the corresponding timesteps in all relevant solver objects.
- Parameters:
full_timestep (float) – The time interval dt over which the stepper advances the full system dynamics. Applies to both linear and nonlinear steppers. A Grad-Shafranov (GS) equilibrium is recalculated at every full_timestep.
max_internal_timestep (float) – Maximum size of sub-steps when advancing a single full_timestep. These sub-steps are used to integrate the circuit equations.
- set_linear_solution(active_voltage_vec: ndarray, dtheta_dt: ndarray, no_GS: bool = False) None[source]
Compute an initial nonlinear solve guess using the linearised dynamics.
Advances the system one timestep using the linearised solver to generate a trial current vector at t + Δt, starting from self.currents_vec at time t. This trial solution is then used as the initial guess for the nonlinear solver, which updates the Grad–Shafranov (GS) equilibrium at t + Δt.
- Parameters:
active_voltage_vec (np.ndarray) – External voltage applied to the active coils during the timestep.
dtheta_dt (np.ndarray) – Time derivatives of the plasma current density profile parameters.
no_GS (bool, optional) – If True, skip the Grad–Shafranov solve for the trial currents (only trial_currents and trial_plasma_psi are set).
Notes
Updates the following attributes:
- self.trial_currentsnp.ndarray
Trial coil/mode currents at t + Δt obtained from the linearised solver.
- self.eq2.plasma_psinp.ndarray
Plasma poloidal flux after solving GS with the trial currents.
- self.trial_plasma_psinp.ndarray
Copy of the GS solution for the plasma flux surface configuration corresponding to the trial currents.
- set_plasma_resistivity(plasma_resistivity: float) None[source]
Set the resistivity of the plasma and update the corresponding diagonal plasma resistance vector used in circuit calculations.
The vector self.plasma_resistance_1d represents the diagonal of the plasma resistance matrix R_yy, restricted to the reduced domain defined by plasma_domain_mask (grid points inside the limiter).
- Parameters:
plasma_resistivity (float) –
Scalar value of the plasma resistivity [Ohm·m]. The resistance at each grid point in the reduced domain is computed as
R_yy = 2 * π * plasma_resistivity * R / (dR * dZ)
where R is the major radius of the grid point and dR*dZ is the area of the corresponding domain element.
- set_solvers() None[source]
Initialize and configure the time-integration solvers.
Creates solver instances for both the simplified nonlinear system (simplified_solver_J1) and the linearised system (linear_solver). Both solvers are constructed using machine inductance/resistance matrices and plasma parameters, and are configured to advance currents consistently with the timestep settings.
After creation, the linearised solver is set to operate around the current linearisation point, using the Jacobians and reference plasma state.
Notes
Updates the following attributes:
- self.simplified_solver_J1simplified_solver_J1
Nonlinear solver instance for reduced-order plasma–circuit dynamics.
- self.linearised_sollinear_solver
Linear solver instance for coupled plasma–circuit dynamics.
- classmethod starting_dI_requires_rescaling(starting_dI: float, scaled_dI: float, max_ratio: float | None = None) bool[source]
Return whether a calibrated perturbation requires a second GS solve.
- Parameters:
starting_dI (float) – Perturbation amplitude used in the first GS solve.
scaled_dI (float) – Perturbation amplitude rescaled to reach the target change in Iy.
max_ratio (float, optional) – Largest tolerated ratio between scaled_dI and starting_dI (or its inverse). Defaults to
cls._MAX_STARTING_DI_RATIO.
- Returns:
True if either amplitude is non-finite, starting_dI is zero, or the ratio
|scaled_dI / starting_dI|lies outside[1/max_ratio, max_ratio].- Return type:
bool
- step_complete_assign(working_relative_tol_GS: float, from_linear: bool = False) None[source]
Finalize the timestep advancement and update the equilibrium and current state.
This function completes the evolution over a timestep dt_step by: - Recording the time-evolved currents (self.trial_currents) in self.currents_vec. - Updating the equilibrium (self.eq1) and plasma profiles (self.profiles1) with the corresponding plasma flux (self.trial_plasma_psi) and derived current distribution. - Updating the normalized plasma current distribution (self.hatIy).
- Parameters:
working_relative_tol_GS (float) – Fractional tolerance for the Grad–Shafranov solver during this timestep. The effective GS tolerance is set relative to the maximum change in plasma flux.
from_linear (bool, default=False) – If True, only the linearised solution is applied. Reduces the number of full GS solves by copying auxiliary equilibrium and profiles to the main state.
Notes
This method represents completion of an externally-requested timestep and must be called exactly once per nlstepper call. To sync self.eq1/self.profiles1 to the current trial solution without completing a timestep (e.g. before relinearising), use assign_trial_solution_state directly instead.
Side effects:
Advances self.time and increments self.step_no.
Updates self.currents_vec_m1 and self.Iy_m1 to store previous step values.
Updates self.currents_vec, self.Iy, self.hatIy, and self.rtol_NK.
Modifies self.eq1 and self.profiles1 to reflect the timestep-evolved state.
- unstable_mode_deformations(starting_dI: float = 50, rtol_NK: float = 1e-07, target_dIy: float = 0.002) None[source]
Applies the first unstable mode to evaluate plasma centroid deformations and the corresponding plasma current distribution response.
This method calculates the derivatives of the current-averaged plasma coordinates (R, Z) with respect to the magnitude of the current in the unstable mode (Im), i.e., dR/dIm and dZ/dIm. It also records the plasma current distribution after applying Im and constructs a “rigidly displaced” version of the original current map for comparison.
- Parameters:
starting_dI (float, optional) – Initial perturbation amplitude in the unstable mode used to estimate the slope of ||delta(Iy)|| / delta(Im). Default is 50.
rtol_NK (float, optional) – Relative tolerance to be used in the static Grad-Shafranov (GS) problem. Default is 1e-7.
target_dIy (float, optional) – Target norm of the plasma current change vector (delta(Iy)) used to scale the mode perturbation. Default is 2e-3.
Notes
Updates the following attributes:
- dRZd_unstable_modenp.ndarray
Array [dR/dIm, dZ/dIm] representing the sensitivity of the plasma centroid to the applied unstable mode current.
- deformable_vs_rigid_jtortuple of np.ndarray
Tuple containing: - The plasma current distribution with the unstable mode applied. - The “rigidly displaced” plasma current distribution obtained by shifting the original distribution to match the new centroid (R, Z) positions.
- update_starting_dI() ndarray[source]
Reuse perturbations accepted by the previous linearisation.
The first linearisation retains the geometry-based perturbations prepared during solver construction. Each rebuilt column subsequently records its accepted finite-difference amplitude in
final_dI_record. Reusing that value gives the next relinearisation a state-informed initial guess without extrapolating from a stale Jacobian.Missing, zero, or incompatible accepted amplitudes leave the existing perturbations unchanged.
- Returns:
Mask identifying perturbations updated from the stored Jacobian.
- Return type:
ndarray of bool