"""
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/>.
"""
from __future__ import annotations
import logging
import multiprocessing
import warnings
from concurrent.futures import ProcessPoolExecutor
from copy import deepcopy
from typing import Callable, Sequence
import matplotlib.pyplot as plt
import numpy as np
import numpy.typing as npt
from scipy.signal import convolve2d
from threadpoolctl import threadpool_limits
from . import bilinear_interpolation
from . import nk_solver_H as nk_solver
from .build_machine import _symmetrise_passive_refinement, build_tokamak_R_and_M
from .circuit_eq_metal import metal_currents
from .gradshafranov import GreensBr, GreensdBrdz
from .GSstaticsolver import NKGSsolver
from .linear_solve import linear_solver
from .Myy_builder import make_Myy_handler
from .normal_modes import _validate_passive_reflection
from .simplified_solve import simplified_solver_J1
from .up_down_symmetry import _symmetrise_greens, _symmetrise_square_operator
logger = logging.getLogger(__name__)
_parallel_linearization_solver = None
def _build_dIydI_column_worker(arguments: tuple) -> tuple:
"""
Build one current-response column in an isolated worker process.
Parameters
----------
arguments : tuple
Positional arguments unpacked and passed to
``_parallel_linearization_solver._build_dIydI_column``.
Returns
-------
tuple
The column data returned by ``nl_solver._build_dIydI_column``.
"""
return _parallel_linearization_solver._build_dIydI_column(*arguments)
def _build_dIydtheta_column_worker(arguments: tuple) -> tuple:
"""
Build one profile-response column in an isolated worker process.
Parameters
----------
arguments : tuple
Positional arguments unpacked and passed to
``_parallel_linearization_solver._build_dIydtheta_column``.
Returns
-------
tuple
The column data returned by ``nl_solver._build_dIydtheta_column``.
"""
return _parallel_linearization_solver._build_dIydtheta_column(*arguments)
[docs]
class nl_solver:
"""
Nonlinear 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
"""
_MAX_STARTING_DI_RATIO = np.sqrt(10.0)
_MAX_REUSED_STARTING_DI_RATIO = 4.0 / 3.0
[docs]
def __init__(
self,
profiles: object,
eq: object,
GSStaticSolver: NKGSsolver,
custom_coil_resist: np.ndarray | None = None,
custom_self_ind: np.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-6,
plasma_norm_factor: float = 1e3,
blend_hatJ: float = 0,
max_mode_frequency: float | None = 10**2.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: np.ndarray | None = None,
dIydtheta: np.ndarray | None = None,
target_relative_tolerance_linearization: float = 1e-8,
target_dIy: float = 1e-3,
force_core_mask_linearization: bool = False,
l2_reg: float = 1e-6,
collinearity_reg: float = 1e-6,
verbose: bool = False,
plasma_descriptor_function: Callable[[object], np.ndarray] | None = None,
mode_selection: str = "coupling",
n_linearization_workers: int = 1,
force_up_down_symmetric: bool = False,
passive_reflection_operator: np.ndarray | None = None,
remove_odd_passive_modes: bool = True,
symmetry_tolerance: float = 1e-8,
myy_type: str = "reduced",
cache_myy: bool = True,
) -> None:
"""
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]|`` and
``max_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._vgreen`` is updated in
place, along with any un-mirrored passive filament refinements on
``eq.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=True`` when passive structures are present;
by default odd passive modes are removed before plasma coupling is
calculated.
Use ``prepare_up_down_symmetric_machine`` to 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 ``dIydI`` and
``dIydtheta`` columns 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.
"""
# grid parameters
self.nx = eq.nx
self.ny = eq.ny
self.nxny = self.nx * self.ny
self.eqR = eq.R
self.eqZ = eq.Z
# area factor for Iy
dR = eq.dR
dZ = eq.dZ
self.dRdZ = dR * dZ
# store number of coils and their names/order
self.n_active_coils = eq.tokamak.n_active_coils
self.n_coils = eq.tokamak.n_coils
self.n_passive_coils = eq.tokamak.n_coils - eq.tokamak.n_active_coils
self.coils_order = list(eq.tokamak.coils_dict.keys())
self.currents_vec = np.zeros(self.n_coils + 1)
self.force_up_down_symmetric = force_up_down_symmetric
self.remove_odd_passive_modes = remove_odd_passive_modes
if (
force_up_down_symmetric
and self.n_passive_coils
and passive_reflection_operator is None
):
raise ValueError(
"'passive_reflection_operator' is required for symmetric "
"evolution with passive structures."
)
if force_up_down_symmetric:
if not np.allclose(eq.Z, -eq.Z[:, ::-1], rtol=0.0, atol=1e-12):
raise ValueError(
"Symmetric evolution requires a Z grid symmetric about Z=0: "
"reversing its indices must map each Z coordinate to -Z."
)
limiter_mask = eq.limiter_handler.mask_inside_limiter
if not np.array_equal(limiter_mask, limiter_mask[:, ::-1]):
raise ValueError(
"Symmetric evolution requires a limiter mask symmetric "
"about Z=0."
)
metal_reflection = np.eye(self.n_coils)
if self.n_passive_coils:
passive_reflection_operator = _validate_passive_reflection(
passive_reflection_operator, self.n_passive_coils
)
partners = np.argmax(passive_reflection_operator, axis=1)
permutation = np.eye(self.n_passive_coils)[partners]
if not np.allclose(passive_reflection_operator, permutation):
raise ValueError(
"Passive reflection must permute the physical passive elements."
)
passive_reflection_operator = permutation
metal_reflection[self.n_active_coils :, self.n_active_coils :] = (
passive_reflection_operator
)
passive_names = self.coils_order[self.n_active_coils :]
pairs = [
(passive_names[i], passive_names[j])
for i, j in enumerate(partners)
if i <= j
]
if _symmetrise_passive_refinement(
eq.tokamak.coils, eq.tokamak.coils_dict, pairs
):
build_tokamak_R_and_M(eq.tokamak)
eq._pgreen = eq.tokamak.createPsiGreens(eq.R, eq.Z)
eq._vgreen = eq.tokamak.createPsiGreensVec(eq.R, eq.Z)
# Reflection-average the machine operators:
# R_sym = (R + S_m R) / 2,
# L_sym = (L + S_m L S_m) / 2,
# G_sym(R, Z) = (G(R, Z) + S_m G(R, -Z)) / 2.
# These forms commute with reflection and leave the even and odd
# metal-current subspaces dynamically independent.
resistance = (
eq.tokamak.coil_resist
if custom_coil_resist is None
else np.asarray(custom_coil_resist)
)
inductance = (
eq.tokamak.coil_self_ind
if custom_self_ind is None
else np.asarray(custom_self_ind)
)
custom_coil_resist = 0.5 * (resistance + metal_reflection @ resistance)
custom_self_ind = _symmetrise_square_operator(inductance, metal_reflection)
eq._vgreen = _symmetrise_greens(eq._vgreen, metal_reflection)
# setting up reduced domain for plasma circuit eq.:
self.limiter_handler = eq.limiter_handler
self.plasma_domain_size = np.sum(self.limiter_handler.mask_inside_limiter)
valid_mode_selections = ("coupling", "timescale")
if mode_selection not in valid_mode_selections:
raise ValueError(
f"mode_selection must be one of {valid_mode_selections}; "
f"received {mode_selection!r}."
)
self.mode_selection = mode_selection
# Coupling-based removal after the full Jacobian would violate the
# contract of timescale-only mode selection.
if mode_selection == "timescale":
mode_removal = False
# check threshold values
if mode_selection == "coupling" and fix_n_vessel_modes < 0:
if min_dIy_dI > threshold_dIy_dI:
raise ValueError(
"Inputs require that 'min_dIy_dI' <= 'threshold_dIy_dI', please adjust parameters."
)
# check number of passives
if self.n_passive_coils < fix_n_vessel_modes:
logger.warning(
"'fix_n_vessel_modes' (%s) exceeds number of passive structures (%s), setting 'fix_n_vessel_modes' to %s",
fix_n_vessel_modes,
self.n_passive_coils,
self.n_passive_coils,
)
fix_n_vessel_modes = self.n_passive_coils
# check input eq and profiles are a GS solution
logger.info(
"Checking that the provided 'eq' and 'profiles' are a GS solution..."
)
# storing the static solver
self.NK = GSStaticSolver
if self.NK.greenfunc is None:
warnings.warn(
"The GSStaticSolver provided seems to have been initialized with `cache_greens=False`. "
"Evolutive solves without cached greens are discouraged: a heavy performance cost is expected."
)
self.NK.forward_solve(
eq,
profiles,
target_relative_tolerance=target_relative_tolerance_linearization,
verbose=False,
force_up_down_symmetric=self.force_up_down_symmetric,
)
# set internal copy of the equilibrium and profile
self.eq1 = eq.create_auxiliary_equilibrium()
self.profiles1 = profiles.copy()
self.eq2 = eq.create_auxiliary_equilibrium()
self.profiles2 = profiles.copy()
self.Iy = self.limiter_handler.Iy_from_jtor(profiles.jtor).copy()
self.nIy = np.linalg.norm(self.Iy)
# instantiate the Myy_handler object
self.handleMyy = make_Myy_handler(
myy_type, eq.limiter_handler, cache_myy=cache_myy
)
# Extract relevant information on the type of profiles function used and on the actual value of associated parameters
self.get_profiles_values(profiles)
self.plasma_norm_factor = plasma_norm_factor
self.dt_step = full_timestep
self.max_internal_timestep = max_internal_timestep
self.set_plasma_resistivity(plasma_resistivity)
self.target_dIy = target_dIy
if (
isinstance(n_linearization_workers, (bool, np.bool_))
or not isinstance(n_linearization_workers, (int, np.integer))
or n_linearization_workers < 1
):
raise ValueError("'n_linearization_workers' must be a positive integer.")
self.n_linearization_workers = int(n_linearization_workers)
# prepare for mode selection
if max_mode_frequency is None:
self.max_mode_frequency = 1 / (5 * full_timestep)
logger.info(
"Value of 'max_mode_frequency' has not been provided. Set to %s based on value of 'full_timestep' as provided.",
self.max_mode_frequency,
)
else:
self.max_mode_frequency = max_mode_frequency
logger.info("Instantiating nonlinear solver objects...")
# handles the metal circuit eq, mode properties, and performs the vessel mode decomposition
self.evol_metal_curr = metal_currents(
eq=eq,
flag_vessel_eig=1,
flag_plasma=1,
plasma_pts=self.limiter_handler.plasma_pts,
max_mode_frequency=self.max_mode_frequency,
max_internal_timestep=self.max_internal_timestep,
full_timestep=self.dt_step,
coil_resist=custom_coil_resist,
coil_self_ind=custom_self_ind,
passive_reflection_operator=(
passive_reflection_operator if force_up_down_symmetric else None
),
remove_odd_passive_modes=remove_odd_passive_modes,
symmetry_tolerance=symmetry_tolerance,
)
self.n_metal_modes = self.evol_metal_curr.n_independent_vars
n_available_passive_modes = self.n_metal_modes - self.n_active_coils
if fix_n_vessel_modes > n_available_passive_modes:
logger.warning(
"'fix_n_vessel_modes' (%s) exceeds the number of available passive modes (%s); setting it to %s.",
fix_n_vessel_modes,
n_available_passive_modes,
n_available_passive_modes,
)
fix_n_vessel_modes = n_available_passive_modes
# prepare the vectorised green functions of the vessel modes
self.vessel_modes_greens = (
self.evol_metal_curr.normal_modes.normal_modes_greens(
eq._vgreen,
self.evol_metal_curr.P if self.force_up_down_symmetric else None,
)
)
# build full vector of vessel mode currents
self.build_current_vec(eq, profiles)
# prepare initial current shifts for the linearization using a
# vanilla metric for the coupling between modes and plasma
mode_coupling_metric = np.linalg.norm(
self.vessel_modes_greens * profiles.jtor,
axis=(1, 2),
)
mode_coupling_metric /= np.linalg.norm(
eq.tokamak.getPsitokamak(vgreen=eq._vgreen) * profiles.jtor
)
self.mode_coupling_metric = mode_coupling_metric
self.starting_dI = target_dIy / mode_coupling_metric
self.final_dI_record = np.zeros_like(self.starting_dI)
self.approved_target_dIy = target_dIy * np.ones_like(self.starting_dI)
logger.info("Identifying mode selection criteria...")
if self.n_passive_coils > 0:
# prepare ndIydI_no_GS for mode selection
self.build_dIydI_noGS(
force_core_mask_linearization,
self.starting_dI,
profiles.diverted_core_mask,
verbose,
)
fixed_n_timescale_modes = None
if mode_selection == "timescale":
# build_dIydI_noGS above calibrates the finite-difference steps,
# but its coupling norms deliberately do not enter this mask.
mode_coupling_masks = None
if fix_n_vessel_modes >= 0:
fixed_n_timescale_modes = fix_n_vessel_modes
logger.info(
" 'mode_selection=timescale' selected: retaining the %s lowest-frequency passive modes.",
fix_n_vessel_modes,
)
else:
logger.info(
" 'mode_selection=timescale' selected: retaining only passive modes below 'max_mode_frequency'."
)
logger.info(
" Plasma-coupling metrics are not used for mode selection or subsequent mode removal."
)
else:
# Coupling selection starts from the no-GS response norm. The
# frequency mask may also include slow modes in the threshold mode.
ordered_ndIydI_no_GS = np.sort(self.ndIydI_no_GS[self.n_active_coils :])
strongest_coupling_vessel_mode = ordered_ndIydI_no_GS[-1]
if mode_selection == "coupling" and fix_n_vessel_modes >= 0:
# select modes based on ndIydI_no_GS up to fix_n_modes exactly
logger.info(
" 'fix_n_vessel_modes' option selected --> passive structure modes that couple most to the strongest passive structure mode are being selected."
)
if fix_n_vessel_modes > 0:
threshold_value = ordered_ndIydI_no_GS[-fix_n_vessel_modes]
else: # zero modes to be selected
threshold_value = (
strongest_coupling_vessel_mode * 1.1
) # scale up so no modes are selected
mode_coupling_mask_include = np.concatenate(
(
[True] * self.n_active_coils,
self.ndIydI_no_GS[self.n_active_coils :] >= threshold_value,
)
)
mode_coupling_mask_exclude = np.concatenate(
(
[True] * self.n_active_coils,
self.ndIydI_no_GS[self.n_active_coils :] >= threshold_value,
)
)
# the number of modes is being fixed:
mode_removal = False
elif mode_selection == "coupling":
logger.info(
" 'threshold_dIy_dI', 'min_dIy_dI', and 'max_mode_frequency' options selected --> passive structure modes are selected according to these thresholds."
)
# select modes based on ndIydI_no_GS using values of threshold_dIy_dI
mode_coupling_mask_include = np.concatenate(
(
[True] * self.n_active_coils,
self.ndIydI_no_GS[self.n_active_coils :]
>= threshold_dIy_dI * strongest_coupling_vessel_mode,
)
)
# exclude all modes that couple less than min_dIy_dI
odd_passive_mask = (
(
self.evol_metal_curr.normal_modes.passive_mode_parity[
self.evol_metal_curr.available_modes_mask[
self.n_active_coils :
]
]
< 0
)
if (
self.force_up_down_symmetric
and not self.remove_odd_passive_modes
and self.evol_metal_curr.normal_modes.passive_mode_parity
is not None
)
else np.zeros(self.n_metal_modes - self.n_active_coils, dtype=bool)
)
mode_coupling_mask_exclude = np.concatenate(
(
[True] * self.n_active_coils,
(
self.ndIydI_no_GS[self.n_active_coils :]
>= min_dIy_dI * strongest_coupling_vessel_mode
)
| odd_passive_mask,
)
)
if mode_selection == "coupling":
mode_coupling_masks = (
mode_coupling_mask_include,
mode_coupling_mask_exclude,
)
else:
logger.info(" no passive modes present!")
# only active coils selected
mode_coupling_mask_include = [True] * self.n_active_coils
# exclude all modes that couple less than min_dIy_dI
mode_coupling_mask_exclude = mode_coupling_mask_include
# set mode removal to false
mode_removal = False
mode_coupling_masks = None
fixed_n_timescale_modes = None
logger.info("Initial mode selection:")
# enact the mode selection
selected_available_modes = self.evol_metal_curr.initialize_for_eig(
selected_modes_mask=None,
mode_coupling_masks=mode_coupling_masks,
verbose=(mode_selection == "timescale" or fix_n_vessel_modes < 0),
fixed_n_passive_modes=fixed_n_timescale_modes,
)
if mode_selection == "coupling" and fix_n_vessel_modes >= 0:
logger.info(" Active coils")
logger.info(
" total selected = %d (out of %d)",
self.n_active_coils,
self.n_active_coils,
)
logger.info(" Passive structures")
logger.info(
" %s selected using 'fix_n_vessel_modes'", fix_n_vessel_modes
)
logger.info(
" Total number of modes = %d (%d active coils + %s passive structures)",
self.evol_metal_curr.n_independent_vars,
self.n_active_coils,
fix_n_vessel_modes,
)
logger.info(
" (Note: some additional modes may be removed after Jacobian calculation if 'mode_removal=True')"
)
# this is the number of independent normal mode currents being used
self.n_metal_modes = self.evol_metal_curr.n_independent_vars
self.n_passive_modes = self.n_metal_modes - self.n_active_coils
self.arange_currents = np.arange(self.n_metal_modes + 1)
# re-build vector of vessel mode currents after mode selection
self.build_current_vec(eq, profiles)
# select modes accordingly
self.starting_dI = self.starting_dI[selected_available_modes]
self.approved_target_dIy = self.approved_target_dIy[selected_available_modes]
# add the plasma
self.starting_dI = np.concatenate(
(self.starting_dI, [target_dIy * profiles.Ip / plasma_norm_factor])
)
self.approved_target_dIy = np.concatenate(
(self.approved_target_dIy, [target_dIy])
)
self.initial_starting_dI = np.copy(self.starting_dI)
# starting dtheta values for Jacobian calculation
self.approved_target_dtheta = target_dIy * np.ones(self.n_profiles_parameters)
self.starting_dtheta = np.zeros(self.n_profiles_parameters)
self.final_dtheta_record = np.zeros(self.n_profiles_parameters)
# for setting profile parameters starting shifts (for Jacobians)
if self.profiles_param is not None:
# alpha_m
self.starting_dtheta[0] = max(profiles.alpha_m * 1e-2, 1e-2)
# alpha_n
self.starting_dtheta[1] = max(profiles.alpha_n * 1e-2, 1e-2)
# paxis/betap/Beta0
if self.profiles_param == "paxis":
self.starting_dtheta[2] = max(
getattr(profiles, self.profiles_param) * 1e-2, 1e1
)
elif self.profiles_param == "betap":
self.starting_dtheta[2] = max(
getattr(profiles, self.profiles_param) * 1e-2, 1e-4
)
elif self.profiles_param == "Beta0":
self.starting_dtheta[2] = max(
getattr(profiles, self.profiles_param) * 1e-2, 1e-4
)
else: # lao
# alpha coeffs
self.starting_dtheta[0 : self.n_profiles_parameters_alpha] = (
self.profiles_parameters_vec[self.profiles_alpha_indices] * 1e-3
)
self.starting_dtheta[0 : self.n_profiles_parameters_alpha][
self.starting_dtheta[0 : self.n_profiles_parameters_alpha] == 0
] = 1e-3
# beta coeffs
self.starting_dtheta[self.n_profiles_parameters_alpha :] = (
self.profiles_parameters_vec[self.profiles_beta_indices] * 1e-3
)
self.starting_dtheta[self.n_profiles_parameters_alpha :][
self.starting_dtheta[self.n_profiles_parameters_alpha :] == 0
] = 1e-3
# This solves the system of circuit eqs based on an assumption
# for the direction of the plasma current distribution at time t+dt
self.simplified_solver_J1 = simplified_solver_J1(
coil_numbers=(self.n_active_coils, self.n_coils),
Lambdam1=self.evol_metal_curr.Lambdam1,
P=self.evol_metal_curr.P,
Pm1=self.evol_metal_curr.Pm1,
Rm1=np.diag(self.evol_metal_curr.Rm1),
Mey=self.evol_metal_curr.Mey_matrix,
# limiter_handler=self.limiter_handler,
plasma_norm_factor=self.plasma_norm_factor,
plasma_resistance_1d=self.plasma_resistance_1d,
full_timestep=self.dt_step,
)
# self.vessel_currents_vec is the vector of tokamak coil currents (the metal values, not the normal modes)
# initial self.vessel_currents_vec values are taken from eq.tokamak
# does not include plasma current
vessel_currents_vec = np.zeros(self.n_coils)
eq_currents = eq.tokamak.getCurrents()
for i, labeli in enumerate(self.coils_order):
vessel_currents_vec[i] = eq_currents[labeli]
self.vessel_currents_vec = vessel_currents_vec.copy()
# self.currents_vec is the vector of current values in which the dynamics is actually solved for
# it includes: active coils, vessel normal modes, total plasma current
# the total plasma current is divided by plasma_norm_factor to improve homogeneity of current values
self.extensive_currents_dim = self.n_metal_modes + 1
self.currents_vec = np.zeros(self.extensive_currents_dim)
self.circuit_eq_residual = np.zeros(self.extensive_currents_dim)
# Handles the linearised dynamic problem
self.linearised_sol = linear_solver(
coil_numbers=(self.n_active_coils, self.n_coils),
Lambdam1=self.evol_metal_curr.Lambdam1,
P=self.evol_metal_curr.P,
Pm1=self.evol_metal_curr.Pm1,
Rm1=np.diag(self.evol_metal_curr.Rm1),
Mey=self.evol_metal_curr.Mey_matrix,
plasma_norm_factor=self.plasma_norm_factor,
plasma_resistance_1d=self.plasma_resistance_1d,
max_internal_timestep=self.max_internal_timestep,
full_timestep=self.dt_step,
)
# sets up NK solver on the full grid, to be used when solving the
# circuits equations as a problem in the plasma flux
self.psi_nk_solver = nk_solver.nksolver(
self.nxny, l2_reg=l2_reg, collinearity_reg=collinearity_reg
)
# sets up NK solver for the currents
self.currents_nk_solver = nk_solver.nksolver(
self.extensive_currents_dim,
l2_reg=l2_reg,
collinearity_reg=collinearity_reg,
)
# counter for the step advancement of the dynamics
self.step_no = 0
# set default blend for contracting the plasma lumped eq
self.make_blended_hatIy = lambda x: self.make_blended_hatIy_(
x, blend=blend_hatJ
)
# self.dIydI is the Jacobian of the plasma current distribution
# with respect to the independent currents (as in self.currents_vec)
self.dIydI_ICs = dIydI
self.dRZdI_ICs = None
self.dIydI = dIydI
# self.dIydtheta is the Jacobian of the plasma current distribution
# with respect to the plasma current density profile parameters
self.dIydtheta_ICs = dIydtheta
self.dIydtheta = dIydtheta
# initialize and set up the linearization
# input value for dIydI is used when available
if automatic_timestep == False:
automatic_timestep_flag = False
else:
if len(automatic_timestep) != 2:
raise ValueError(
"The input for 'automatic_timestep' should be of the form (float, float). Please revise."
)
automatic_timestep_flag = True
self.plasma_descriptor_function = plasma_descriptor_function or (
lambda _: np.array([0.0])
)
if automatic_timestep_flag + mode_removal + linearize:
# builds the linearization and sets everything up for the stepper
self.initialize_from_ICs(
eq,
profiles,
target_relative_tolerance_linearization=target_relative_tolerance_linearization,
dIydI=dIydI,
dIydtheta=dIydtheta,
verbose=verbose,
force_core_mask_linearization=force_core_mask_linearization,
plasma_descriptor_function=plasma_descriptor_function,
)
# remove passive normal modes that have norm(dIydI) < min_dIy_dI*strongest mode
if mode_removal:
# selected based on full calculation of the coupling
ndIydI = np.linalg.norm(self.dIydI, axis=0)
selected_modes_mask = ndIydI > min_dIy_dI * max(
ndIydI[self.n_active_coils : -1]
)
# force that active coils, explicitly retained odd passive modes, and plasma are kept
actives_and_plasma_mask = [
j < self.n_active_coils or self._is_odd_passive_mode_column(j)
for j in range(self.n_metal_modes)
] + [True]
self.retained_modes_mask = (
selected_modes_mask + np.array(actives_and_plasma_mask)
).astype(bool)
# apply mask to dIydI, dRZdI and final_dI_record
self.dIydI = self.dIydI[:, self.retained_modes_mask]
self.dIydI_ICs = np.copy(self.dIydI)
self.dRZdI = self.dRZdI[:, self.retained_modes_mask]
self.dRZdI_ICs = np.copy(self.dRZdI)
self.final_dI_record = self.final_dI_record[self.retained_modes_mask]
self.dvdId = self.dvdId[:, self.retained_modes_mask]
self.initial_currents_plasma_descriptor = (
self.initial_currents_plasma_descriptor[self.retained_modes_mask]
)
# apply mask in case of re-linearisation
self.approved_target_dIy = self.approved_target_dIy[
self.retained_modes_mask
]
self.starting_dI = self.starting_dI[self.retained_modes_mask]
self.initial_starting_dI = self.initial_starting_dI[
self.retained_modes_mask
]
self.remove_modes(eq, self.retained_modes_mask[:-1])
logger.info(
" Re-sizing the Jacobian matrix to account for any removed modes (if required)."
)
# check if input equilibrium and associated linearization have an instability, and its timescale
if automatic_timestep_flag + mode_removal + linearize:
logger.info("Stability parameters:")
self.linearised_sol.calculate_linear_growth_rate()
self.linearised_sol.calculate_stability_margin()
self.calculate_Leuer_parameter()
if len(self.linearised_sol.growth_rates):
self.unstable_mode_deformations()
# deformable plasma metrics
logger.info(" Deformable plasma metrics:")
logger.info(
" Growth rate = %s [1/s]", self.linearised_sol.growth_rates
)
logger.info(
" Instability timescale = %s [s]",
self.linearised_sol.instability_timescale,
)
logger.info(
" Inductive stability margin = %s",
self.linearised_sol.stability_margin,
)
# rigid plasma metrics
logger.info(" Rigid plasma metrics:")
logger.info(
" Leuer parameter (ratio of stabilising to de-stabilising force gradients):"
)
logger.info(
" between all metals and all metals = %s",
self.Leuer_metals_stab_over_metals_destab,
)
logger.info(
" between all metals and active metals = %s",
self.Leuer_metals_stab_over_active_destab,
)
logger.info(
" between passive metals and active metals = %s",
self.Leuer_passive_stab_over_active_destab,
)
else:
if self.force_up_down_symmetric and self.remove_odd_passive_modes:
logger.info(
" No unstable modes found in the retained even-in-Z subspace."
)
elif self.force_up_down_symmetric:
logger.info(
" No unstable modes found with the plasma constrained to be even in Z."
)
else:
logger.warning(
" No unstable modes found: either plasma stable, or more likely, it is Alfven unstable (i.e. needs more stabilisation from coils and passives)."
)
if fix_n_vessel_modes >= 0:
logger.warning(
" Try adding more passive modes (by increasing 'fix_n_vessel_modes')."
)
else:
logger.warning(
" Try adding more passive modes (by increasing 'max_mode_frequency' and/or 'threshold_dIy_dI' and/or reducing 'min_dIy_dI')."
)
# if automatic_timestep, reset the timestep accordingly,
# note that this requires having found an instability
logger.info("Evolutive solver timestep:")
if automatic_timestep_flag is False:
logger.info(
" Solver timestep 'dt_step' has been set to %s as requested.",
self.dt_step,
)
if self.force_up_down_symmetric and self.remove_odd_passive_modes:
logger.info(
" Odd-in-Z modes are excluded; ensure the timestep resolves the retained even dynamics."
)
elif self.force_up_down_symmetric:
logger.info(
" The plasma is constrained to be even in Z, but odd passive modes remain in the metal-current basis."
)
else:
logger.info(
" Ensure it is smaller than the growth rate else you may find numerical instability in any subsequent evolutive simulations!"
)
else:
if len(self.linearised_sol.growth_rates):
dt_step = abs(
self.linearised_sol.instability_timescale[0] * automatic_timestep[0]
)
self.reset_timestep(
full_timestep=dt_step,
max_internal_timestep=dt_step / automatic_timestep[1],
)
logger.info(
" Solver timestep 'dt_step' has been reset to %s using the growth rate and scaling factors in 'automatic_timestep'.",
self.dt_step,
)
else:
logger.warning(
" Given no unstable modes found, it is impossible to automatically set the timestep! Please do so manually."
)
# text for verbose mode
self.text_nk_cycle = "This is NK cycle no {nkcycle}."
self.text_psi_0 = "NK on psi has been skipped {skippedno} times. The residual on psi is {psi_res:.8f}."
self.text_psi_1 = "The coefficients applied to psi are"
[docs]
def build_dIydI_noGS(
self,
force_core_mask_linearization: bool,
starting_dI: np.ndarray,
core_mask: np.ndarray,
verbose: bool,
) -> None:
"""
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_noGS : np.ndarray, shape (n_plasma_points, n_coils)
Approximate Jacobian of plasma current distribution wrt coil currents,
computed without GS solves.
self.ndIydI_no_GS : np.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_ndIy : np.ndarray, shape (n_coils,)
Relative plasma current perturbation norms for each mode.
self.starting_dI : np.ndarray
Adjusted perturbation amplitudes after enforcing masking strategy.
self.approved_target_dIy : np.ndarray
Updated target norms for plasma current perturbations (if core mask
enforcement applied).
"""
self.dIydI_noGS = np.zeros((len(self.Iy), self.n_metal_modes))
self.ndIydI_no_GS = np.zeros(self.n_metal_modes)
self.rel_ndIy = np.zeros(self.n_metal_modes)
for j in range(self.n_metal_modes):
dIydInoGS, rel_ndIy = self.prepare_build_dIydI_j(
j, None, self.approved_target_dIy[j], starting_dI[j], GS=False
)
core_check = (
np.sum(
np.abs(
core_mask.astype(float)
- self.profiles2.diverted_core_mask.astype(float)
)
)
== 0
)
if force_core_mask_linearization:
while core_check == False:
starting_dI[j] /= 1.5
dIydInoGS, rel_ndIy = self.prepare_build_dIydI_j(
j, None, self.approved_target_dIy[j], starting_dI[j], GS=False
)
core_check = (
np.sum(
np.abs(
core_mask.astype(float)
- self.profiles2.diverted_core_mask.astype(float)
)
)
== 0
)
self.approved_target_dIy[j] = rel_ndIy
else:
starting_dI[j] = 1.0 * self.final_dI_record[j]
self.dIydI_noGS[:, j] = dIydInoGS
self.rel_ndIy[j] = rel_ndIy
self.ndIydI_no_GS[j] = np.linalg.norm(dIydInoGS)
self.starting_dI = 1.0 * starting_dI
def _is_odd_passive_mode_column(self, j: int) -> bool:
"""
Return whether independent-current column ``j`` is an odd passive mode.
Parameters
----------
j : int
Column index in the retained independent-current basis.
Returns
-------
bool
True if ``force_up_down_symmetric`` is enabled and column ``j``
corresponds to a retained passive mode with odd parity.
"""
if not getattr(self, "force_up_down_symmetric", False):
return False
if j < self.n_active_coils or j >= self.n_metal_modes:
return False
parity = self.evol_metal_curr.normal_modes.passive_mode_parity
if parity is None:
return False
retained_full_indices = np.flatnonzero(self.evol_metal_curr.selected_modes_mask)
full_mode_index = int(retained_full_indices[j])
return bool(parity[full_mode_index - self.n_active_coils] < 0)
def _project_plasma_vectors_even(self, vectors: npt.ArrayLike) -> np.ndarray:
"""Apply ``(I + S_y) / 2`` to reduced-domain plasma vectors.
Parameters
----------
vectors : array-like
1D plasma vector or 2D matrix of columns defined on the reduced
limiter domain.
Returns
-------
np.ndarray
Even-in-Z projected vector or matrix on the reduced limiter domain.
"""
if not self.force_up_down_symmetric:
return vectors
vectors = np.asarray(vectors)
was_vector = vectors.ndim == 1
columns = vectors[:, np.newaxis] if was_vector else vectors
fields = np.zeros((self.nx, self.ny, columns.shape[1]))
fields[self.limiter_handler.mask_inside_limiter] = columns
fields = 0.5 * (fields + fields[:, ::-1])
projected = fields[self.limiter_handler.mask_inside_limiter]
return projected[:, 0] if was_vector else projected
[docs]
def set_solvers(self) -> None:
"""
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_J1 : simplified_solver_J1
Nonlinear solver instance for reduced-order plasma–circuit dynamics.
self.linearised_sol : linear_solver
Linear solver instance for coupled plasma–circuit dynamics.
"""
self.simplified_solver_J1 = simplified_solver_J1(
coil_numbers=(self.n_active_coils, self.n_coils),
Lambdam1=self.evol_metal_curr.Lambdam1,
P=self.evol_metal_curr.P,
Pm1=self.evol_metal_curr.Pm1,
Rm1=np.diag(self.evol_metal_curr.Rm1),
Mey=self.evol_metal_curr.Mey_matrix,
plasma_norm_factor=self.plasma_norm_factor,
plasma_resistance_1d=self.plasma_resistance_1d,
full_timestep=self.dt_step,
)
self.linearised_sol = linear_solver(
coil_numbers=(self.n_active_coils, self.n_coils),
Lambdam1=self.evol_metal_curr.Lambdam1,
P=self.evol_metal_curr.P,
Pm1=self.evol_metal_curr.Pm1,
Rm1=np.diag(self.evol_metal_curr.Rm1),
Mey=self.evol_metal_curr.Mey_matrix,
plasma_norm_factor=self.plasma_norm_factor,
plasma_resistance_1d=self.plasma_resistance_1d,
max_internal_timestep=self.max_internal_timestep,
full_timestep=self.dt_step,
)
self.linearised_sol.set_linearization_point(
dIydI=self.dIydI,
dIydtheta=self.dIydtheta,
hatIy0=self.blended_hatIy,
Myy_hatIy0=self.Myy_hatIy0,
)
[docs]
def remove_modes(self, eq: object, selected_modes_mask: np.ndarray) -> None:
"""
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_modes : int
Number of remaining independent modes after reduction.
self.extensive_currents_dim : int
Dimension of the reduced current vector (n_metal_modes + 1).
self.arange_currents : np.ndarray
Index array for the reduced system, ranging from 0 to
`self.extensive_currents_dim - 1`.
self.currents_vec : np.ndarray
Zero-initialized current vector of reduced dimensionality.
self.circuit_eq_residual : np.ndarray
Residual vector for the reduced circuit equations.
self.currents_nk_solver : nk_solver.nksolver
Nonlinear solver instance reinitialized for the reduced system size.
self.simplified_solver_J1 : simplified_solver_J1
Rebuilt solver instance consistent with reduced system.
self.linearised_sol : linear_solver
Rebuilt linearised solver instance consistent with reduced system.
"""
self.evol_metal_curr.initialize_for_eig(selected_modes_mask)
self.n_metal_modes = self.evol_metal_curr.n_independent_vars
self.n_passive_modes = self.n_metal_modes - self.n_active_coils
self.extensive_currents_dim = self.n_metal_modes + 1
self.arange_currents = np.arange(self.n_metal_modes + 1)
self.currents_vec = np.zeros(self.extensive_currents_dim)
self.circuit_eq_residual = np.zeros(self.extensive_currents_dim)
self.currents_nk_solver = nk_solver.nksolver(self.extensive_currents_dim)
self.build_current_vec(self.eq1, self.profiles1)
self.set_solvers()
[docs]
def set_linear_solution(
self,
active_voltage_vec: np.ndarray,
dtheta_dt: np.ndarray,
no_GS: bool = False,
) -> None:
"""
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_currents : np.ndarray
Trial coil/mode currents at t + Δt obtained from the linearised solver.
self.eq2.plasma_psi : np.ndarray
Plasma poloidal flux after solving GS with the trial currents.
self.trial_plasma_psi : np.ndarray
Copy of the GS solution for the plasma flux surface configuration
corresponding to the trial currents.
"""
self.trial_currents = self.linearised_sol.stepper(
It=self.currents_vec,
active_voltage_vec=active_voltage_vec,
dtheta_dt=dtheta_dt,
)
if not no_GS:
self.assign_currents_solve_GS(self.trial_currents, self.rtol_NK)
self.trial_plasma_psi = np.copy(self.eq2.plasma_psi)
[docs]
def prepare_build_dIydtheta(
self,
profiles: object,
rtol_NK: float,
target_dIy: np.ndarray,
starting_dtheta: np.ndarray,
plasma_descriptor_function: Callable[[object], np.ndarray],
verbose: bool = False,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
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_record : np.ndarray
Adjusted perturbations Δθ that will yield ΔIy with the target norms.
"""
current_ = np.copy(self.currents_vec)
# storage
dIy_0 = np.zeros((len(self.Iy), self.n_profiles_parameters))
rel_ndIy_0 = np.zeros(self.n_profiles_parameters)
dv = np.zeros(
(self.initial_plasma_descriptors.shape[0], self.n_profiles_parameters)
)
# carry out the initial perturbations
if self.profiles_param is not None:
self.initial_profiles_plasma_descriptor = np.array(
[
profiles.alpha_m,
profiles.alpha_n,
getattr(profiles, self.profiles_param),
]
)
# vary alpha_m
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m + starting_dtheta[0],
"alpha_n": profiles.alpha_n,
self.profiles_param: getattr(profiles, self.profiles_param),
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_0[:, 0] = (
self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
)
dv[:, 0] = (
plasma_descriptor_function(self.eq2) - self.initial_plasma_descriptors
)
rel_ndIy_0[0] = np.linalg.norm(dIy_0[:, 0]) / self.nIy
self.final_dtheta_record[0] = (
starting_dtheta[0] * target_dIy[0] / rel_ndIy_0[0]
)
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: alpha_m:")
logger.log(
log_level, " Initial delta parameter = %s", starting_dtheta[0]
)
logger.log(
log_level, " Initial relative Iy change = %s", rel_ndIy_0[0]
)
logger.log(
log_level,
" Final delta parameter = %s",
self.final_dtheta_record[0],
)
# vary alpha_n
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n + starting_dtheta[1],
self.profiles_param: getattr(profiles, self.profiles_param),
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_0[:, 1] = (
self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
)
dv[:, 1] = (
plasma_descriptor_function(self.eq2) - self.initial_plasma_descriptors
)
rel_ndIy_0[1] = np.linalg.norm(dIy_0[:, 1]) / self.nIy
self.final_dtheta_record[1] = (
starting_dtheta[1] * target_dIy[1] / rel_ndIy_0[1]
)
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: alpha_n:")
logger.log(
log_level, " Initial delta parameter = %s", starting_dtheta[1]
)
logger.log(
log_level, " Initial relative Iy change = %s", rel_ndIy_0[1]
)
logger.log(
log_level,
" Final delta parameter = %s",
self.final_dtheta_record[1],
)
# vary paxis, betap or Beta0
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
self.profiles_param: getattr(profiles, self.profiles_param)
+ starting_dtheta[2],
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_0[:, 2] = (
self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
)
dv[:, 2] = (
plasma_descriptor_function(self.eq2) - self.initial_plasma_descriptors
)
rel_ndIy_0[2] = np.linalg.norm(dIy_0[:, 2]) / self.nIy
self.final_dtheta_record[2] = (
starting_dtheta[2] * target_dIy[2] / rel_ndIy_0[2]
)
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: %s:", self.profiles_param)
logger.log(
log_level, " Initial delta parameter = %s", starting_dtheta[2]
)
logger.log(
log_level, " Initial relative Iy change = %s", rel_ndIy_0[2]
)
logger.log(
log_level,
" Final delta parameter = %s",
self.final_dtheta_record[2],
)
# reset profiles in profiles1 and profiles2 objects
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
self.profiles_param: getattr(profiles, self.profiles_param),
}
)
else: # this is particular to the Lao profile coefficients (which there may be few or many of)
# extract parameters for the plasma descriptor function
self.initial_profiles_plasma_descriptor = np.concatenate(
(
self.profiles_parameters_vec[self.profiles_alpha_indices],
self.profiles_parameters_vec[self.profiles_beta_indices],
)
)
self.profiles_alpha_indices = slice(0, self.n_profiles_parameters_alpha)
alpha_shift = 0
if profiles.alpha_logic:
alpha_shift += 1
self.profiles_beta_indices = slice(
self.n_profiles_parameters_alpha + alpha_shift,
self.n_profiles_parameters_alpha
+ alpha_shift
+ self.n_profiles_parameters_beta,
)
self.profiles_parameters = {"alpha": profiles.alpha, "beta": profiles.beta}
self.profiles_param = None
self.profiles_parameters_vec = np.concatenate(
(profiles.alpha, profiles.beta)
)
# for each alpha coefficient
alpha_base = profiles.alpha.copy()
for i in range(0, self.n_profiles_parameters_alpha):
alpha_shift = alpha_base.copy()
alpha_shift[i] += starting_dtheta[i] # perturb the term
if profiles.alpha_logic:
alpha_shift[-1] -= starting_dtheta[
i
] # final alpha term needs perturbing too
self.check_and_change_profiles(
profiles_parameters={
"alpha": alpha_shift,
"beta": profiles.beta,
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_0[:, i] = (
self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
)
dv[:, i] = (
plasma_descriptor_function(self.eq2)
- self.initial_plasma_descriptors
)
rel_ndIy_0[i] = np.linalg.norm(dIy_0[:, i]) / self.nIy
self.final_dtheta_record[i] = (
starting_dtheta[i] * target_dIy[i] / rel_ndIy_0[i]
)
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: alpha_%s:", i)
logger.log(
log_level, " Initial delta parameter = %s", starting_dtheta[i]
)
logger.log(
log_level, " Initial relative Iy change = %s", rel_ndIy_0[i]
)
logger.log(
log_level,
" Final delta parameter = %s",
self.final_dtheta_record[i],
)
# for each beta coefficient
beta_base = profiles.beta.copy()
for i in range(0, self.n_profiles_parameters_beta):
beta_shift = beta_base.copy()
beta_shift[i] += starting_dtheta[
i + self.n_profiles_parameters_alpha
] # perturb the term required
if profiles.beta_logic:
beta_shift[-1] -= starting_dtheta[
i + self.n_profiles_parameters_alpha
] # final beta term needs perturbing too
self.check_and_change_profiles(
profiles_parameters={
"alpha": profiles.alpha,
"beta": beta_shift,
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_0[:, i + self.n_profiles_parameters_alpha] = (
self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
)
dv[:, i + self.n_profiles_parameters_alpha] = (
plasma_descriptor_function(self.eq2)
- self.initial_plasma_descriptors
)
rel_ndIy_0[i + self.n_profiles_parameters_alpha] = (
np.linalg.norm(dIy_0[:, i + self.n_profiles_parameters_alpha])
/ self.nIy
)
self.final_dtheta_record[i + self.n_profiles_parameters_alpha] = (
starting_dtheta[i + self.n_profiles_parameters_alpha]
* target_dIy[i]
/ rel_ndIy_0[i + self.n_profiles_parameters_alpha]
)
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: beta_%s:", i)
logger.log(
log_level,
" Initial delta parameter = %s",
starting_dtheta[i + self.n_profiles_parameters_alpha],
)
logger.log(
log_level,
" Initial relative Iy change = %s",
rel_ndIy_0[i + self.n_profiles_parameters_alpha],
)
logger.log(
log_level,
" Final delta parameter = %s",
self.final_dtheta_record[i + self.n_profiles_parameters_alpha],
)
# reset profiles in profiles1 and profiles2 objects
self.check_and_change_profiles(
profiles_parameters={
"alpha": profiles.alpha,
"beta": profiles.beta,
}
)
return dIy_0 / starting_dtheta, rel_ndIy_0, dv / starting_dtheta
[docs]
def build_dIydtheta(
self,
profiles: object,
rtol_NK: float,
plasma_descriptor_function: Callable[[object], np.ndarray],
verbose: bool = False,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
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).
"""
# the final perturbations to calc the Jacobian with
final_theta = 1.0 * self.final_dtheta_record
current_ = np.copy(self.currents_vec)
# storage
dIydtheta = np.zeros((len(self.Iy), self.n_profiles_parameters))
rel_ndIy = np.zeros(self.n_profiles_parameters)
dvdtheta = np.zeros(
(self.initial_plasma_descriptors.shape[0], self.n_profiles_parameters)
)
# carry out the initial perturbations
if self.profiles_param is not None:
# vary alpha_m
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m + final_theta[0],
"alpha_n": profiles.alpha_n,
self.profiles_param: getattr(profiles, self.profiles_param),
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_1 = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
rel_ndIy[0] = np.linalg.norm(dIy_1) / self.nIy
dIydtheta[:, 0] = dIy_1 / final_theta[0]
dv = plasma_descriptor_function(self.eq2) - self.initial_plasma_descriptors
dvdtheta[:, 0] = dv / final_theta[0]
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: alpha_m:")
logger.log(log_level, " Final relative Iy change = %s", rel_ndIy[0])
logger.log(
log_level,
" Initial vs. Final GS residual: %s vs. %s",
self.NK.initial_rel_residual,
self.NK.relative_change,
)
# vary alpha_n
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n + final_theta[1],
self.profiles_param: getattr(profiles, self.profiles_param),
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_1 = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
rel_ndIy[1] = np.linalg.norm(dIy_1) / self.nIy
dIydtheta[:, 1] = dIy_1 / final_theta[1]
dv = plasma_descriptor_function(self.eq2) - self.initial_plasma_descriptors
dvdtheta[:, 1] = dv / final_theta[1]
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: alpha_n:")
logger.log(log_level, " Final relative Iy change = %s", rel_ndIy[1])
logger.log(
log_level,
" Initial vs. Final GS residual: %s vs. %s",
self.NK.initial_rel_residual,
self.NK.relative_change,
)
# vary paxis, betap or Beta0
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
self.profiles_param: getattr(profiles, self.profiles_param)
+ final_theta[2],
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_1 = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
rel_ndIy[2] = np.linalg.norm(dIy_1) / self.nIy
dIydtheta[:, 2] = dIy_1 / final_theta[2]
dv = plasma_descriptor_function(self.eq2) - self.initial_plasma_descriptors
dvdtheta[:, 2] = dv / final_theta[2]
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: %s:", self.profiles_param)
logger.log(log_level, " Final relative Iy change = %s", rel_ndIy[2])
logger.log(
log_level,
" Initial vs. Final GS residual: %s vs. %s",
self.NK.initial_rel_residual,
self.NK.relative_change,
)
# reset profiles in profiles1 and profiles2 objects
self.check_and_change_profiles(
profiles_parameters={
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
self.profiles_param: getattr(profiles, self.profiles_param),
}
)
else: # this is particular to the Lao profile coefficients (which there may be few or many of)
# for each alpha coefficient
alpha_base = profiles.alpha.copy()
for i in range(0, self.n_profiles_parameters_alpha):
alpha_shift = alpha_base.copy()
alpha_shift[i] += final_theta[i] # perturb the term
if profiles.alpha_logic:
alpha_shift[-1] -= final_theta[
i
] # final alpha term needs perturbing too
self.check_and_change_profiles(
profiles_parameters={
"alpha": alpha_shift,
"beta": profiles.beta,
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_1 = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
rel_ndIy[i] = np.linalg.norm(dIy_1) / self.nIy
dIydtheta[:, i] = dIy_1 / final_theta[i]
dv = (
plasma_descriptor_function(self.eq2)
- self.initial_plasma_descriptors
)
dvdtheta[:, i] = dv / final_theta[i]
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: alpha_%s:", i)
logger.log(
log_level, " Final relative Iy change = %s", rel_ndIy[i]
)
logger.log(
log_level,
" Initial vs. Final GS residual: %s vs. %s",
self.NK.initial_rel_residual,
self.NK.relative_change,
)
# for each beta coefficient
beta_base = profiles.beta.copy()
for i in range(0, self.n_profiles_parameters_beta):
beta_shift = beta_base.copy()
beta_shift[i] += final_theta[
i + self.n_profiles_parameters_alpha
] # perturb the term required
if profiles.beta_logic:
beta_shift[-1] -= final_theta[
i + self.n_profiles_parameters_alpha
] # final beta term needs perturbing too
self.check_and_change_profiles(
profiles_parameters={
"alpha": profiles.alpha,
"beta": beta_shift,
}
)
# reset plasma flux map to original
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_1 = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
rel_ndIy[i + self.n_profiles_parameters_alpha] = (
np.linalg.norm(dIy_1) / self.nIy
)
dIydtheta[:, i + self.n_profiles_parameters_alpha] = (
dIy_1 / final_theta[i + self.n_profiles_parameters_alpha]
)
dv = (
plasma_descriptor_function(self.eq2)
- self.initial_plasma_descriptors
)
dvdtheta[:, i + self.n_profiles_parameters_alpha] = (
dv / final_theta[i + self.n_profiles_parameters_alpha]
)
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(log_level, "Profile parameter: beta_%s:", i)
logger.log(
log_level,
" Final relative Iy change = %s",
rel_ndIy[i + self.n_profiles_parameters_alpha],
)
logger.log(
log_level,
" Initial vs. Final GS residual: %s vs. %s",
self.NK.initial_rel_residual,
self.NK.relative_change,
)
# reset profiles in profiles1 and profiles2 objects
self.check_and_change_profiles(
profiles_parameters={
"alpha": profiles.alpha,
"beta": profiles.beta,
}
)
return dIydtheta, rel_ndIy, dvdtheta
def _reset_linearization_solve_state(self) -> None:
"""
Reset auxiliary plasma state before a finite-difference GS solve.
Copies the reference profiles and plasma flux into the auxiliary
objects and restores the stored random number generator state, if any.
"""
self.profiles2 = self.profiles1.copy()
self.eq2.plasma_psi = np.copy(self.eq1.plasma_psi)
if hasattr(self, "_linearization_rng_state"):
self.NK.rng.bit_generator.state = deepcopy(self._linearization_rng_state)
[docs]
def prepare_build_dIydI_j(
self,
j: int,
rtol_NK: float | None,
target_dIy: float,
starting_dI: float,
GS: bool = True, # , min_curr=1e-4, max_curr=300
) -> tuple[np.ndarray, float]:
"""
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.
"""
if self._is_odd_passive_mode_column(j):
self._reset_linearization_solve_state()
self.final_dI_record[j] = starting_dI
return np.zeros_like(self.Iy), 0.0
current_ = np.copy(self.currents_vec)
current_[j] += starting_dI
self._reset_linearization_solve_state()
if GS:
# solve
self.assign_currents_solve_GS(current_, rtol_NK)
else:
# just use modified tokamak_psi
self.assign_currents(current_, self.eq2, self.profiles2)
self.profiles2.Jtor(
self.eqR,
self.eqZ,
self.eq2.plasma_psi + self.eq2.tokamak.getPsitokamak(self.eq1._vgreen),
)
dIy_0 = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
dIy_0 = self._project_plasma_vectors_even(dIy_0)
rel_ndIy_0 = np.linalg.norm(dIy_0) / self.nIy
final_dI = starting_dI * target_dIy / rel_ndIy_0
# final_dI = np.clip(final_dI, min_curr, max_curr)
self.final_dI_record[j] = final_dI
return dIy_0 / starting_dI, rel_ndIy_0
[docs]
def update_starting_dI(self) -> np.ndarray:
"""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
-------
ndarray of bool
Mask identifying perturbations updated from the stored Jacobian.
"""
updated = np.zeros_like(self.starting_dI, dtype=bool)
if np.shape(self.final_dI_record) != np.shape(self.starting_dI):
return updated
accepted = np.abs(np.asarray(self.final_dI_record))
updated = np.isfinite(accepted) & (accepted > 0)
self.starting_dI[updated] = accepted[updated]
return updated
[docs]
@classmethod
def starting_dI_requires_rescaling(
cls,
starting_dI: float,
scaled_dI: float,
max_ratio: float | None = None,
) -> bool:
"""
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
-------
bool
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]``.
"""
if max_ratio is None:
max_ratio = cls._MAX_STARTING_DI_RATIO
if (
not np.isfinite(starting_dI)
or not np.isfinite(scaled_dI)
or starting_dI == 0
):
return True
ratio = np.abs(scaled_dI / starting_dI)
return ratio < 1.0 / max_ratio or ratio > max_ratio
[docs]
def build_dIydI_j(self, j: int, rtol_NK: float) -> tuple[np.ndarray, float]:
"""
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.
"""
final_dI = 1.0 * self.final_dI_record[j]
self.current_at_last_linearization[j] = self.currents_vec[j]
current_ = np.copy(self.currents_vec)
current_[j] += final_dI
self._reset_linearization_solve_state()
# solve
self.assign_currents_solve_GS(current_, rtol_NK)
dIy_1 = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
dIydIj = dIy_1 / final_dI
rel_ndIy = np.linalg.norm(dIy_1) / self.nIy
return dIydIj, rel_ndIy
[docs]
def new_plasma_descriptors(
self, new_currents: np.ndarray, new_profiles: np.ndarray
) -> np.ndarray:
"""
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
-------
np.ndarray
Linear estimate of the plasma descriptors, i.e. the initial descriptors
plus the current and profile contributions.
"""
current_contribution = (
self.dvdId
@ (new_currents - self.initial_currents_plasma_descriptor)[:, np.newaxis]
).squeeze()
profile_contribution = (
self.dvdtheta
@ (new_profiles - self.initial_profiles_plasma_descriptor)[:, np.newaxis]
).squeeze()
return (
self.initial_plasma_descriptors
+ current_contribution
+ profile_contribution
)
def _core_mask_matches(self) -> bool:
"""
Return whether the reference and perturbed plasma masks match.
Returns
-------
bool
True if ``profiles1.diverted_core_mask`` equals
``profiles2.diverted_core_mask``.
"""
return np.array_equal(
self.profiles1.diverted_core_mask,
self.profiles2.diverted_core_mask,
)
def _accept_linearization_GS(self, rtol_NK: float, label: str) -> None:
"""Continue an unconverged final GS solve once, then reject the column.
The continuation uses the same perturbed equilibrium, profiles, tolerance
and symmetry constraint. Failure raises RuntimeError before a response is
accepted, including when the solver returns a non-finite residual.
"""
if (
not np.isfinite(self.NK.relative_change)
or self.NK.relative_change > rtol_NK
):
self.NK.forward_solve(
self.eq2,
self.profiles2,
target_relative_tolerance=rtol_NK,
suppress=True,
force_up_down_symmetric=self.force_up_down_symmetric,
)
if (
not np.isfinite(self.NK.relative_change)
or self.NK.relative_change > rtol_NK
):
raise RuntimeError(
f"GS solve for {label} did not converge after one continuation: "
f"relative residual {self.NK.relative_change:.6g}, requested "
f"{rtol_NK:.6g}; linearization rejected"
)
def _build_dIydI_column(
self,
j: int,
target_relative_tolerance_linearization: float,
force_core_mask_linearization: bool,
reused_starting_dI: bool,
) -> tuple[
int,
np.ndarray,
np.ndarray,
np.ndarray,
np.ndarray,
float,
float,
float,
float,
float,
float,
float,
]:
"""
Build and return one independent current-response column.
Parameters
----------
j : int
Index of the independent current being perturbed.
target_relative_tolerance_linearization : float
Relative tolerance for the static GS solves.
force_core_mask_linearization : bool
If True, shrink the perturbation until the perturbed core mask matches
the reference one.
reused_starting_dI : bool
Whether the starting perturbation was reused from a previous
linearisation (and so may be discarded if no longer predictive).
Returns
-------
tuple
``(j, dIydI_j, perturbed_psi, dRZdI_j, dvdI_j, starting_dI, final_dI,
ndIy, rel_ndIy, initial_rel_residual, relative_change,
current_at_last_linearization)``, where `dIydI_j` is the column of the
Jacobian, `perturbed_psi` the total flux of the perturbed equilibrium,
`dRZdI_j` the response of the current-weighted (R, Z) centroid,
`dvdI_j` the response of the plasma descriptors and the remaining
entries are floats recording the perturbation sizes and GS solver
diagnostics.
"""
this_target_dIy = float(self.approved_target_dIy[j])
if self._is_odd_passive_mode_column(j):
starting_dI = float(self.starting_dI[j])
self.final_dI_record[j] = starting_dI
self.current_at_last_linearization[j] = self.currents_vec[j]
return (
j,
np.zeros_like(self.Iy),
np.copy(self.eq1.psi()),
np.zeros(2),
np.zeros_like(self.initial_plasma_descriptors, dtype=float),
starting_dI,
starting_dI,
0.0,
0.0,
0.0,
0.0,
float(self.current_at_last_linearization[j]),
)
_, ndIy = self.prepare_build_dIydI_j(
j,
target_relative_tolerance_linearization,
this_target_dIy,
self.starting_dI[j],
GS=True,
)
if force_core_mask_linearization:
while not self._core_mask_matches():
self.starting_dI[j] /= 1.5
this_target_dIy /= 1.5
_, ndIy = self.prepare_build_dIydI_j(
j,
target_relative_tolerance_linearization,
this_target_dIy,
self.starting_dI[j],
)
if reused_starting_dI and self.starting_dI_requires_rescaling(
self.starting_dI[j],
self.final_dI_record[j],
max_ratio=self._MAX_REUSED_STARTING_DI_RATIO,
):
# Discard a stale amplitude that is no longer predictive and use
# the original geometry-based path.
self.starting_dI[j] = self.initial_starting_dI[j]
_, ndIy = self.prepare_build_dIydI_j(
j,
target_relative_tolerance_linearization,
this_target_dIy,
self.starting_dI[j],
GS=True,
)
reused_starting_dI = False
valid_scaled_dI = (
np.isfinite(self.final_dI_record[j]) and self.final_dI_record[j] != 0
)
if valid_scaled_dI and self.starting_dI_requires_rescaling(
self.starting_dI[j],
self.final_dI_record[j],
max_ratio=(
self._MAX_REUSED_STARTING_DI_RATIO
if reused_starting_dI
else self._MAX_STARTING_DI_RATIO
),
):
self.build_dIydI_j(
j,
target_relative_tolerance_linearization,
)
if force_core_mask_linearization:
while not self._core_mask_matches():
self.final_dI_record[j] /= 1.2
self.build_dIydI_j(
j,
target_relative_tolerance_linearization,
)
else:
self.final_dI_record[j] = self.starting_dI[j]
self._accept_linearization_GS(
target_relative_tolerance_linearization, f"current column {j}"
)
if force_core_mask_linearization and not self._core_mask_matches():
raise RuntimeError(
f"GS continuation changed the core mask for current column {j}; "
"linearization rejected"
)
# A continuation can change the final state. Derive every returned
# response from that same accepted equilibrium.
dIy = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
dIydIj = dIy / self.final_dI_record[j]
rel_ndIy = np.linalg.norm(dIy) / self.nIy
starting_dI = float(self.starting_dI[j])
final_dI = float(self.final_dI_record[j])
self.starting_dI[j] = final_dI
self.current_at_last_linearization[j] = self.currents_vec[j]
perturbed_psi = np.copy(self.eq2.psi())
dRZdI = np.array(
(
(self.eq2.Rcurrent() - self.R0) / final_dI,
(self.eq2.Zcurrent() - self.Z0) / final_dI,
)
)
dvdI = (
np.asarray(self._column_plasma_descriptor_function(self.eq2))
- self.initial_plasma_descriptors
) / final_dI
return (
j,
np.copy(dIydIj),
perturbed_psi,
dRZdI,
dvdI,
starting_dI,
final_dI,
float(ndIy),
float(rel_ndIy),
float(self.NK.initial_rel_residual),
float(self.NK.relative_change),
float(self.current_at_last_linearization[j]),
)
def _build_dIydI_columns(
self,
target_relative_tolerance_linearization: float,
force_core_mask_linearization: bool,
reused_starting_dI: np.ndarray,
plasma_descriptor_function: Callable[[object], np.ndarray],
) -> list[tuple]:
"""
Build current-response columns serially or in isolated processes.
Parameters
----------
target_relative_tolerance_linearization : float
Relative tolerance for the static GS solves.
force_core_mask_linearization : bool
If True, enforce matching core masks for the perturbed equilibria.
reused_starting_dI : np.ndarray
Boolean array, one entry per independent current, flagging starting
perturbations reused from a previous linearisation.
plasma_descriptor_function : Callable[[object], np.ndarray]
Function returning the 1D array of plasma descriptors of an equilibrium.
Returns
-------
list of tuple
One tuple per column, as returned by `_build_dIydI_column`.
Raises
------
RuntimeError
If more than one worker is requested but the 'fork' multiprocessing
start method is unavailable.
"""
arguments = [
(
int(j),
target_relative_tolerance_linearization,
force_core_mask_linearization,
bool(reused_starting_dI[j]),
)
for j in self.arange_currents
]
self._column_plasma_descriptor_function = plasma_descriptor_function
self._linearization_rng_state = deepcopy(self.NK.rng.bit_generator.state)
try:
if self.n_linearization_workers == 1 or len(arguments) < 2:
return [self._build_dIydI_column(*argument) for argument in arguments]
if "fork" not in multiprocessing.get_all_start_methods():
raise RuntimeError(
"Parallel linearization requires multiprocessing support for "
"the 'fork' start method. Set n_linearization_workers=1."
)
global _parallel_linearization_solver
_parallel_linearization_solver = self
# Each worker gets one native BLAS/OpenMP thread so the requested
# worker count is also the total CPU-thread budget.
with threadpool_limits(limits=1):
with ProcessPoolExecutor(
max_workers=min(self.n_linearization_workers, len(arguments)),
mp_context=multiprocessing.get_context("fork"),
) as executor:
return list(
executor.map(
_build_dIydI_column_worker,
arguments,
chunksize=1,
)
)
finally:
_parallel_linearization_solver = None
self.NK.rng.bit_generator.state = self._linearization_rng_state
del self._linearization_rng_state
del self._column_plasma_descriptor_function
def _profile_parameters_for_column(
self, profiles: object, j: int, delta: float
) -> dict[str, float | np.ndarray]:
"""
Return independent profile parameters with column ``j`` perturbed.
Parameters
----------
profiles : object
Reference profiles object.
j : int
Index of the independent profile parameter to perturb.
delta : float
Perturbation added to parameter `j`.
Returns
-------
dict
Profile parameters in the format accepted by `check_and_change_profiles`.
"""
if self.profiles_param is not None:
parameters = {
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
self.profiles_param: getattr(profiles, self.profiles_param),
}
parameter_name = ("alpha_m", "alpha_n", self.profiles_param)[j]
parameters[parameter_name] += delta
return parameters
alpha = profiles.alpha[: self.n_profiles_parameters_alpha].copy()
beta = profiles.beta[: self.n_profiles_parameters_beta].copy()
if j < self.n_profiles_parameters_alpha:
alpha[j] += delta
else:
beta_index = j - self.n_profiles_parameters_alpha
beta[beta_index] += delta
return {"alpha": alpha, "beta": beta}
def _profile_parameter_name(self, j: int) -> str:
"""
Return the user-facing name of independent profile parameter ``j``.
Parameters
----------
j : int
Index of the independent profile parameter.
Returns
-------
str
Parameter name, e.g. "alpha_m" or "beta_1".
"""
if self.profiles_param is not None:
return ("alpha_m", "alpha_n", self.profiles_param)[j]
if j < self.n_profiles_parameters_alpha:
return f"alpha_{j}"
return f"beta_{j - self.n_profiles_parameters_alpha}"
def _build_dIydtheta_column(
self, j: int, delta: float, rtol_NK: float, check_convergence: bool = True
) -> tuple[int, np.ndarray, float, np.ndarray, float, float]:
"""
Build and return one independent profile-response column.
Parameters
----------
j : int
Index of the independent profile parameter being perturbed.
delta : float
Perturbation of the profile parameter.
rtol_NK : float
Relative tolerance for the static GS solve.
check_convergence : bool, optional
Require convergence before returning a final column. Set False only
for perturbation-calibration probes that may be discarded.
Returns
-------
tuple
``(j, dIydtheta_j, rel_ndIy, dvdtheta_j, initial_rel_residual,
relative_change)``: the Jacobian column, the relative norm of the
induced change in Iy, the plasma descriptor response and the GS solver
diagnostics.
"""
self._reset_linearization_solve_state()
self.check_and_change_profiles(
self._profile_parameters_for_column(self._column_profiles, j, delta)
)
self.assign_currents_solve_GS(np.copy(self.currents_vec), rtol_NK)
if check_convergence:
self._accept_linearization_GS(
rtol_NK, f"profile column {j} ({self._profile_parameter_name(j)})"
)
dIy = self.limiter_handler.Iy_from_jtor(self.profiles2.jtor) - self.Iy
dv = (
np.asarray(self._column_plasma_descriptor_function(self.eq2))
- self.initial_plasma_descriptors
)
return (
j,
dIy / delta,
float(np.linalg.norm(dIy) / self.nIy),
dv / delta,
float(self.NK.initial_rel_residual),
float(self.NK.relative_change),
)
def _build_dIydtheta_columns(
self,
profiles: object,
rtol_NK: float,
perturbations: np.ndarray,
plasma_descriptor_function: Callable[[object], np.ndarray],
check_convergence: bool = True,
columns: Sequence[int] | None = None,
) -> list[tuple]:
"""
Build profile-response columns serially or in isolated processes.
Parameters
----------
profiles : object
Profiles object of the linearisation-point equilibrium.
rtol_NK : float
Relative tolerance for the static GS solves.
perturbations : np.ndarray
Perturbation of each independent profile parameter.
plasma_descriptor_function : Callable[[object], np.ndarray]
Function returning the 1D array of plasma descriptors of an equilibrium.
check_convergence : bool, optional
Require converged final columns; False permits calibration probes.
columns : Sequence of int or None, optional
Subset of independent profile-column indices to build. Defaults to
all ``n_profiles_parameters`` columns.
Returns
-------
list of tuple
One tuple per column, as returned by `_build_dIydtheta_column`.
Raises
------
RuntimeError
If more than one worker is requested but the 'fork' multiprocessing
start method is unavailable.
"""
column_indices = (
range(self.n_profiles_parameters) if columns is None else columns
)
arguments = [
(int(j), float(perturbations[j]), rtol_NK, check_convergence)
for j in column_indices
]
self._column_profiles = profiles.copy()
self._column_plasma_descriptor_function = plasma_descriptor_function
self._linearization_rng_state = deepcopy(self.NK.rng.bit_generator.state)
try:
if self.n_linearization_workers == 1 or len(arguments) < 2:
return [
self._build_dIydtheta_column(*argument) for argument in arguments
]
if "fork" not in multiprocessing.get_all_start_methods():
raise RuntimeError(
"Parallel linearization requires multiprocessing support for "
"the 'fork' start method. Set n_linearization_workers=1."
)
global _parallel_linearization_solver
_parallel_linearization_solver = self
with threadpool_limits(limits=1):
with ProcessPoolExecutor(
max_workers=min(self.n_linearization_workers, len(arguments)),
mp_context=multiprocessing.get_context("fork"),
) as executor:
return list(
executor.map(
_build_dIydtheta_column_worker,
arguments,
chunksize=1,
)
)
finally:
_parallel_linearization_solver = None
self.NK.rng.bit_generator.state = self._linearization_rng_state
del self._linearization_rng_state
self.check_and_change_profiles(
self._profile_parameters_for_column(self._column_profiles, 0, 0.0)
)
del self._column_profiles
del self._column_plasma_descriptor_function
[docs]
def build_linearization(
self,
eq: object,
profiles: object,
dIydI: np.ndarray | None,
dIydtheta: np.ndarray | None,
target_relative_tolerance_linearization: float,
force_core_mask_linearization: bool,
verbose: bool,
plasma_descriptor_function: Callable[[object], np.ndarray] | None,
) -> None:
"""
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.
"""
# if (dIydI is None) and (self.dIydI is None):
self.build_current_vec(eq, profiles)
self.Iy = self.limiter_handler.Iy_from_jtor(profiles.jtor).copy()
self.nIy = np.linalg.norm(self.Iy)
self.initial_plasma_descriptors = np.array(plasma_descriptor_function(eq))
self.plasma_descriptors_vec = np.copy(self.initial_plasma_descriptors)
self.R0 = eq.Rcurrent()
self.Z0 = eq.Zcurrent()
self.dRZdI = np.zeros((2, self.n_metal_modes + 1))
# compose the vector of initial delta_currents to be used for the finite difference calculation
# this uses the variation to Jtor caused by the coil's contribution to the flux, ignoring the response of the plasma
# build/update dIydI
# dIydI = 1
if dIydI is None:
if self.dIydI_ICs is None:
if force_core_mask_linearization:
self.starting_dI = np.copy(self.initial_starting_dI)
reused_starting_dI = np.zeros_like(
self.starting_dI,
dtype=bool,
)
else:
reused_starting_dI = self.update_starting_dI()
logger.info(
"Building the %s x %s Jacobian (dIy/dI) of plasma current density (inside the LCFS) with respect to all metal currents and the total plasma current.",
self.plasma_domain_size,
self.n_metal_modes + 1,
)
self.dIydI = np.zeros((self.plasma_domain_size, self.n_metal_modes + 1))
self.psideltaI = np.zeros((self.n_metal_modes + 1, self.nx, self.ny))
self.ddIyddI = np.zeros(self.n_metal_modes + 1)
self.final_dI_record = np.zeros(self.n_metal_modes + 1)
self.dvdId = np.zeros(
(self.initial_plasma_descriptors.shape[0], self.n_metal_modes + 1)
)
self.initial_currents_plasma_descriptor = np.copy(self.currents_vec)
column_results = self._build_dIydI_columns(
target_relative_tolerance_linearization,
force_core_mask_linearization,
reused_starting_dI,
plasma_descriptor_function,
)
for (
j,
dIydIj,
perturbed_psi,
dRZdI,
dvdI,
starting_dI,
final_dI,
ndIy,
rel_ndIy,
initial_rel_residual,
relative_change,
current_at_last_linearization,
) in column_results:
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(log_level, "Mode: %s", j)
logger.log(
log_level, " Initial delta_current = %s", starting_dI
)
logger.log(log_level, " Initial relative Iy change = %s", ndIy)
logger.log(log_level, " Final delta_current = %s", final_dI)
logger.log(
log_level, " Final relative Iy change = %s", rel_ndIy
)
logger.log(
log_level,
" Initial vs. Final GS residual: %s vs. %s",
initial_rel_residual,
relative_change,
)
self.dIydI[:, j] = dIydIj
self.psideltaI[j] = perturbed_psi
self.dRZdI[:, j] = dRZdI
self.dvdId[:, j] = dvdI
self.starting_dI[j] = final_dI
self.final_dI_record[j] = final_dI
self.current_at_last_linearization[j] = (
current_at_last_linearization
)
self.dIydI_ICs = np.copy(self.dIydI)
self.dRZdI_ICs = np.copy(self.dRZdI)
else:
self.dIydI = np.copy(self.dIydI_ICs)
if self.dRZdI_ICs is not None:
self.dRZdI = np.copy(self.dRZdI_ICs)
else:
self.dIydI = dIydI
self.dIydI_ICs = np.copy(self.dIydI)
self.dRZdI_ICs = None
self.dIydI = self._project_plasma_vectors_even(self.dIydI)
self.dIydI_ICs = np.copy(self.dIydI)
# compose the vector of initial delta_theta (profile parameters) to be used for the finite difference calculation
# - this uses the variation to Jtor caused by the parameter's contribution to the change in poloidal flux, ignoring the response of the plasma
# build/update dIydtheta
if dIydtheta is None and force_core_mask_linearization is False:
if self.dIydtheta_ICs is None:
logger.info(
"Building the %s x %s Jacobian (dIy/dtheta) of plasma current density (inside the LCFS) with respect to all plasma current density profile parameters within Jtor.",
self.plasma_domain_size,
self.n_profiles_parameters,
)
built_dIydtheta = np.zeros(
(self.plasma_domain_size, self.n_profiles_parameters)
)
built_dvdtheta = np.zeros(
(
self.initial_plasma_descriptors.shape[0],
self.n_profiles_parameters,
)
)
profiles_copy = profiles.copy()
if self.profiles_param is not None:
self.initial_profiles_plasma_descriptor = np.array(
[
profiles.alpha_m,
profiles.alpha_n,
getattr(profiles, self.profiles_param),
]
)
else:
self.initial_profiles_plasma_descriptor = np.concatenate(
(
profiles.alpha[: self.n_profiles_parameters_alpha],
profiles.beta[: self.n_profiles_parameters_beta],
)
)
# First estimate perturbations that produce the requested Iy change.
column_results = self._build_dIydtheta_columns(
profiles_copy,
target_relative_tolerance_linearization,
self.starting_dtheta,
plasma_descriptor_function,
check_convergence=False,
)
for j, _, ndIy, _, _, _ in column_results:
if np.isfinite(ndIy) and ndIy > 0:
scaled_dtheta = (
self.starting_dtheta[j]
* self.approved_target_dtheta[j]
/ ndIy
)
else:
scaled_dtheta = self.starting_dtheta[j]
if not np.isfinite(scaled_dtheta) or scaled_dtheta == 0:
scaled_dtheta = self.starting_dtheta[j]
self.final_dtheta_record[j] = scaled_dtheta
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(
log_level,
"Profile parameter: %s:",
self._profile_parameter_name(j),
)
logger.log(
log_level,
" Initial delta parameter = %s",
self.starting_dtheta[j],
)
logger.log(log_level, " Initial relative Iy change = %s", ndIy)
logger.log(
log_level,
" Final delta parameter = %s",
self.final_dtheta_record[j],
)
rescale = (
np.abs(np.log10(self.final_dtheta_record / self.starting_dtheta))
> 0.5
).any()
unconverged_columns = [
row[0]
for row in column_results
if not np.isfinite(row[5])
or row[5] > target_relative_tolerance_linearization
]
if not rescale:
self.final_dtheta_record = np.copy(self.starting_dtheta)
if rescale or unconverged_columns:
checked_results = self._build_dIydtheta_columns(
profiles_copy,
target_relative_tolerance_linearization,
self.final_dtheta_record,
plasma_descriptor_function,
columns=None if rescale else unconverged_columns,
)
checked_by_column = {row[0]: row for row in checked_results}
column_results = [
checked_by_column.get(row[0], row) for row in column_results
]
for (
j,
_,
rel_ndIy,
_,
initial_rel_residual,
relative_change,
) in checked_results:
log_level = logging.INFO if verbose else logging.DEBUG
if logger.isEnabledFor(log_level):
logger.log(
log_level,
"Profile parameter: %s:",
self._profile_parameter_name(j),
)
logger.log(
log_level, " Final relative Iy change = %s", rel_ndIy
)
logger.log(
log_level,
" Initial vs. Final GS residual: %s vs. %s",
initial_rel_residual,
relative_change,
)
for j, column, _, descriptor_column, _, _ in column_results:
built_dIydtheta[:, j] = column
built_dvdtheta[:, j] = descriptor_column
self.dIydtheta = built_dIydtheta
self.dvdtheta = built_dvdtheta
self.dIydtheta_ICs = np.copy(self.dIydtheta)
if plasma_descriptor_function is not None:
logger.info(
"Built the %s x %s Jacobian (ds/dI) of plasma descriptors with respect to all metal currents and the total plasma current.",
len(self.initial_plasma_descriptors),
self.n_metal_modes + 1,
)
logger.info(
"Built the %s x %s Jacobian (ds/dtheta) of plasma descriptors with respect to all plasma current density profile parameters within Jtor.",
len(self.initial_plasma_descriptors),
self.n_profiles_parameters,
)
else:
self.dIydtheta = np.copy(self.dIydtheta_ICs)
else:
self.dIydtheta = dIydtheta
self.dIydtheta_ICs = np.copy(self.dIydtheta)
if self.dIydtheta is not None:
self.dIydtheta = self._project_plasma_vectors_even(self.dIydtheta)
self.dIydtheta_ICs = np.copy(self.dIydtheta)
[docs]
def set_plasma_resistivity(self, plasma_resistivity: float) -> None:
"""
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.
"""
self.plasma_resistivity = plasma_resistivity
plasma_resistance_matrix = (
self.eqR * (2 * np.pi / self.dRdZ) * self.plasma_resistivity
)
self.plasma_resistance_1d = plasma_resistance_matrix[
self.limiter_handler.mask_inside_limiter
]
[docs]
def reset_plasma_resistivity(self, plasma_resistivity: float) -> None:
"""
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.
"""
self.plasma_resistivity = plasma_resistivity
plasma_resistance_matrix = (
self.eqR * (2 * np.pi / self.dRdZ) * self.plasma_resistivity
)
self.plasma_resistance_1d = plasma_resistance_matrix[
self.limiter_handler.mask_inside_limiter
]
self.linearised_sol.reset_plasma_resistivity(self.plasma_resistance_1d)
self.simplified_solver_J1.reset_plasma_resistivity(self.plasma_resistance_1d)
[docs]
def check_and_change_plasma_resistivity(
self,
plasma_resistivity: float | None,
relative_threshold_difference: float = 1e-5,
) -> None:
"""
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.
"""
if plasma_resistivity is not None:
# check how different
check = (
np.abs(plasma_resistivity - self.plasma_resistivity)
/ np.abs(self.plasma_resistivity)
) > relative_threshold_difference
if check:
self.reset_plasma_resistivity(plasma_resistivity=plasma_resistivity)
[docs]
def calc_lumped_plasma_resistance(
self, norm_red_Iy0: np.ndarray, norm_red_Iy1: np.ndarray
) -> float:
"""
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
-------
float
Lumped plasma resistance corresponding to the given current distributions.
"""
lumped_plasma_resistance = np.sum(
self.plasma_resistance_1d * norm_red_Iy0 * norm_red_Iy1
)
return lumped_plasma_resistance
[docs]
def reset_timestep(
self, full_timestep: float, max_internal_timestep: float
) -> None:
"""
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.
"""
self.dt_step = full_timestep
self.max_internal_timestep = max_internal_timestep
self.evol_metal_curr.reset_timesteps(
max_internal_timestep=max_internal_timestep,
full_timestep=full_timestep,
)
self.simplified_solver_J1.reset_timesteps(
full_timestep=full_timestep, max_internal_timestep=full_timestep
)
self.linearised_sol.reset_timesteps(
full_timestep=full_timestep, max_internal_timestep=max_internal_timestep
)
[docs]
def get_profiles_values(self, profiles: object) -> None:
"""
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.
"""
self.fvac = profiles.fvac
self.profiles_type = type(profiles).__name__
# note the parameters here are the same that should be provided
# to the stepper if these are time evolving
if self.profiles_type == "ConstrainPaxisIp":
self.n_profiles_parameters = 3
self.profiles_parameters = {
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
"paxis": profiles.paxis,
}
self.profiles_param = "paxis"
self.profiles_parameters_vec = np.array(
[profiles.alpha_m, profiles.alpha_n, profiles.paxis]
)
elif self.profiles_type == "ConstrainBetapIp":
self.n_profiles_parameters = 3
self.profiles_parameters = {
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
"betap": profiles.betap,
}
self.profiles_param = "betap"
self.profiles_parameters_vec = np.array(
[profiles.alpha_m, profiles.alpha_n, profiles.betap]
)
elif self.profiles_type == "Fiesta_Topeol":
self.n_profiles_parameters = 3
self.profiles_parameters = {
"alpha_m": profiles.alpha_m,
"alpha_n": profiles.alpha_n,
"Beta0": profiles.Beta0,
}
self.profiles_param = "Beta0"
self.profiles_parameters_vec = np.array(
[profiles.alpha_m, profiles.alpha_n, profiles.Beta0]
)
elif self.profiles_type == "Lao85":
self.n_profiles_parameters_alpha = len(profiles.alpha)
self.n_profiles_parameters_beta = len(profiles.beta)
if profiles.alpha_logic:
self.n_profiles_parameters_alpha -= 1
if profiles.beta_logic:
self.n_profiles_parameters_beta -= 1
self.n_profiles_parameters = (
self.n_profiles_parameters_alpha + self.n_profiles_parameters_beta
)
self.profiles_alpha_indices = slice(0, self.n_profiles_parameters_alpha)
alpha_shift = 0
if profiles.alpha_logic:
alpha_shift += 1
self.profiles_beta_indices = slice(
self.n_profiles_parameters_alpha + alpha_shift,
self.n_profiles_parameters_alpha
+ alpha_shift
+ self.n_profiles_parameters_beta,
)
self.profiles_parameters = {"alpha": profiles.alpha, "beta": profiles.beta}
self.profiles_param = None
self.profiles_parameters_vec = np.concatenate(
(profiles.alpha, profiles.beta)
)
[docs]
def get_vessel_currents(self, eq: object) -> None:
"""
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.
"""
self.vessel_currents_vec = eq.tokamak.getCurrentsVec()
[docs]
def build_current_vec(self, eq: object, profiles: object) -> None:
"""
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.
"""
# gets metal currents, note these are before mode truncation!
self.get_vessel_currents(eq)
# transforms in normal modes (including truncation)
mode_currents = self.evol_metal_curr.IvesseltoId(
Ivessel=self.vessel_currents_vec
)
# append the total plasma current value
self.currents_vec = np.concatenate(
(mode_currents, [profiles.Ip / self.plasma_norm_factor])
)
# this is currents_vec(t-dt):
self.currents_vec_m1 = np.copy(self.currents_vec)
[docs]
def initialize_from_ICs(
self,
eq: object,
profiles: object,
target_relative_tolerance_linearization: float = 1e-7,
dIydI: np.ndarray | None = None,
dIydtheta: np.ndarray | None = None,
force_core_mask_linearization: bool = False,
verbose: bool = False,
plasma_descriptor_function: Callable[[object], np.ndarray] | None = None,
cache_myy: bool | None = None,
) -> None:
"""
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`.
"""
self.step_counter = 0
self.currents_guess = False
self.rtol_NK = target_relative_tolerance_linearization
# get profiles parametrization
# this is not currently used, as the linearised evolution
# does not currently account for the evolving profiles coefficients
self.get_profiles_values(profiles)
# set internal copy of the equilibrium and profile
# note that at this stage, the equilibrium may have vessel currents.
# These can not be reproduced exactly if modes are truncated.
self.eq1 = eq.create_auxiliary_equilibrium()
self.profiles1 = profiles.copy()
# The pair self.eq1 and self.profiles1 is the pair that is advanced at each timestep.
# Their properties evolve according to the dynamics.
# Note that the input eq and profiles are NOT modified by the evolution object.
# this builds the vector of extensive current values 'currents_vec'
# comprising (active coil currents, vessel normal modes, plasma current)
# this vector is evolved in place when the stepper is called
self.build_current_vec(self.eq1, self.profiles1)
self.current_at_last_linearization = np.copy(self.currents_vec)
# This has truncated the vessel currents, which needs to be mirrored in the equilibrium
# First, the modified currents are assigned
self.assign_currents(self.currents_vec, profiles=self.profiles1, eq=self.eq1)
# Then the equilibrium is solved again to ensure it is the solution relevant to the truncated currents,
# and not to the full set of vessel currents!
self.NK.forward_solve(
self.eq1,
self.profiles1,
target_relative_tolerance=target_relative_tolerance_linearization,
suppress=True,
force_up_down_symmetric=self.force_up_down_symmetric,
)
# self.eq2 and self.profiles2 are used as auxiliary objects when solving for the dynamics
# They are used for all intermediate calculations, so
# they should not be used to extract properties of the evolving equilibrium
self.eq2 = self.eq1.create_auxiliary_equilibrium()
self.profiles2 = self.profiles1.copy()
# self.Iy is the instantaneous 1d vector representing the plasma current distribution
# on the reduced plasma domain, as from plasma_domain_mask
# self.Iy is updated every timestep
self.Iy = self.limiter_handler.Iy_from_jtor(self.profiles1.jtor)
# self.hatIy is the normalised plasma current distribution. This vector sums to 1.
self.hatIy = self.limiter_handler.normalize_sum(self.Iy)
# self.hatIy1 is the normalised plasma current distribution at time t+dt
self.hatIy1 = np.copy(self.hatIy)
self.make_blended_hatIy(self.hatIy1)
# store norm of jtor for use if relinearising in future time steps
self.jtor0 = self.profiles1.jtor
self.time = 0
self.step_no = -1
# build the linearization if not provided
self._force_core_mask_linearization = force_core_mask_linearization
self._target_relative_tolerance_linearization = (
target_relative_tolerance_linearization
)
self.build_linearization(
self.eq1,
self.profiles1,
dIydI=dIydI,
dIydtheta=dIydtheta,
target_relative_tolerance_linearization=target_relative_tolerance_linearization,
force_core_mask_linearization=force_core_mask_linearization,
verbose=verbose,
plasma_descriptor_function=plasma_descriptor_function
or self.plasma_descriptor_function,
)
# set Myy matrix in place through the handling object
self.handleMyy.update_caching_behavior(cache_myy)
self.handleMyy.force_build_Myy(self.hatIy)
# transfer linearization to linear solver:
self.Myy_hatIy0 = self.handleMyy.dot(self.hatIy)
self.linearised_sol.set_linearization_point(
dIydI=self.dIydI_ICs,
dIydtheta=self.dIydtheta_ICs,
hatIy0=self.blended_hatIy,
Myy_hatIy0=self.Myy_hatIy0,
)
[docs]
def relinearise(self, *, verbose: bool = False) -> None:
"""
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.
"""
log_level = logging.INFO if verbose else logging.DEBUG
logger.log(log_level, "Relinearising around the current plasma")
# create and store auxiliary copies of eq and profiles
original_eq1 = self.eq1.create_auxiliary_equilibrium()
original_eq2 = self.eq2.create_auxiliary_equilibrium()
original_profiles1 = self.profiles1.copy()
original_profiles2 = self.profiles2.copy()
original_state = self.__dict__.copy()
# Outputs are replaced during rebuilding; isolate the inputs edited in place.
self.starting_dI = self.starting_dI.copy()
self.current_at_last_linearization = self.current_at_last_linearization.copy()
self.final_dtheta_record = self.final_dtheta_record.copy()
# reset previous linearisations
self.dIydI_ICs = None
self.dRZdI_ICs = None
self.dIydtheta_ICs = None
try:
# recompute the linearisations
self.build_linearization(
self.eq1.create_auxiliary_equilibrium(),
self.profiles1.copy(),
dIydI=None,
dIydtheta=None,
target_relative_tolerance_linearization=self._target_relative_tolerance_linearization,
force_core_mask_linearization=self._force_core_mask_linearization,
verbose=verbose,
plasma_descriptor_function=self.plasma_descriptor_function,
)
# rebuild operators based on new linearisations
self.handleMyy.force_build_Myy(self.hatIy)
self.Myy_hatIy0 = self.handleMyy.dot(self.hatIy)
# update internal linearisation point object
self.linearised_sol.set_linearization_point(
dIydI=self.dIydI_ICs,
dIydtheta=self.dIydtheta_ICs,
hatIy0=self.blended_hatIy,
Myy_hatIy0=self.Myy_hatIy0,
)
except BaseException:
self.__dict__ = original_state
raise
finally:
# reset internal objects in case modified by above
self.eq1 = original_eq1
self.eq2 = original_eq2
self.profiles1 = original_profiles1
self.profiles2 = original_profiles2
# store norm of jtor at relinearisation point (used for next relinearisation triggering)
self.jtor0 = self.profiles1.jtor
[docs]
def step_complete_assign(
self, working_relative_tol_GS: float, from_linear: bool = False
) -> None:
"""
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.
"""
self.time += self.dt_step
self.step_no += 1
self.currents_vec_m1 = np.copy(self.currents_vec)
self.Iy_m1 = np.copy(self.Iy)
plasma_psi_step = self.eq2.plasma_psi - self.eq1.plasma_psi
self.d_plasma_psi_step = np.amax(plasma_psi_step) - np.amin(plasma_psi_step)
self.assign_trial_solution_state(from_linear=from_linear)
self.rtol_NK = working_relative_tol_GS * self.d_plasma_psi_step
[docs]
def assign_trial_solution_state(self, from_linear: bool = False) -> None:
"""
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.
"""
self.currents_vec = np.copy(self.trial_currents)
self.assign_currents(self.currents_vec, self.eq1, self.profiles1)
self.eq1.tokamak.set_all_coil_currents(self.vessel_currents_vec)
self.eq2.tokamak.set_all_coil_currents(self.vessel_currents_vec)
if from_linear:
self.profiles1 = self.profiles2.copy()
self.eq1 = self.eq2.create_auxiliary_equilibrium()
else:
self.eq1.set_plasma_psi(self.trial_plasma_psi)
self.profiles1.Ip = self.trial_currents[-1] * self.plasma_norm_factor
if self.force_up_down_symmetric:
self.tokamak_psi = self.eq1.tokamak.getPsitokamak(self.eq1._vgreen)
else:
self.tokamak_psi = self.eq1.tokamak.calcPsiFromGreens(self.eq1._pgreen)
self.profiles1.Jtor(
self.eqR, self.eqZ, self.tokamak_psi + self.trial_plasma_psi
)
self.NK.port_critical(self.eq1, self.profiles1)
self.Iy = self.limiter_handler.Iy_from_jtor(self.profiles1.jtor)
self.hatIy = self.limiter_handler.normalize_sum(self.Iy)
[docs]
def assign_currents(
self, currents_vec: np.ndarray, eq: object, profiles: object
) -> None:
"""
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 plasma current to equilibrium
eq._current = self.plasma_norm_factor * currents_vec[-1]
profiles.Ip = self.plasma_norm_factor * currents_vec[-1]
# calculate vessel currents from normal modes and assign
self.vessel_currents_vec = self.evol_metal_curr.IdtoIvessel(
Id=currents_vec[:-1]
)
eq.tokamak.set_all_coil_currents(self.vessel_currents_vec)
[docs]
def assign_currents_solve_GS(
self, currents_vec: np.ndarray, rtol_NK: float
) -> None:
"""
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`.
"""
self.assign_currents(currents_vec, profiles=self.profiles2, eq=self.eq2)
self.NK.forward_solve(
self.eq2,
self.profiles2,
target_relative_tolerance=rtol_NK,
suppress=True,
force_up_down_symmetric=self.force_up_down_symmetric,
)
[docs]
def make_blended_hatIy_(self, hatIy1: np.ndarray, blend: float) -> None:
"""
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
"""
self.blended_hatIy = (1 - blend) * hatIy1 + blend * self.hatIy
[docs]
def currents_from_hatIy(
self, hatIy1: np.ndarray, active_voltage_vec: np.ndarray
) -> np.ndarray:
"""
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
-------
np.ndarray
Full current vector at t+dt, matching the format of self.currents_vec.
Notes
-----
Workflow:
1. Computes a blended plasma distribution using `make_blended_hatIy`.
2. 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.
"""
self.make_blended_hatIy(hatIy1)
Myy_hatIy_left = self.handleMyy.dot(self.blended_hatIy)
current_from_hatIy = self.simplified_solver_J1.stepper(
It=self.currents_vec,
hatIy_left=self.blended_hatIy,
hatIy_0=self.hatIy,
hatIy_1=hatIy1,
active_voltage_vec=active_voltage_vec,
Myy_hatIy_left=Myy_hatIy_left,
)
return current_from_hatIy
[docs]
def hatIy1_iterative_cycle(
self, hatIy1: np.ndarray, active_voltage_vec: np.ndarray, rtol_NK: float
) -> None:
"""
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.
"""
current_from_hatIy = self.currents_from_hatIy(hatIy1, active_voltage_vec)
self.assign_currents_solve_GS(currents_vec=current_from_hatIy, rtol_NK=rtol_NK)
[docs]
def calculate_hatIy(
self, trial_currents: np.ndarray, plasma_psi: np.ndarray
) -> np.ndarray:
"""
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
-------
np.ndarray
Normalized plasma current distribution on the reduced domain.
"""
self.assign_currents(trial_currents, profiles=self.profiles2, eq=self.eq2)
self.tokamak_psi = self.eq2.tokamak.getPsitokamak(vgreen=self.eq2._vgreen)
jtor_ = self.profiles2.Jtor(self.eqR, self.eqZ, self.tokamak_psi + plasma_psi)
hat_Iy1 = self.limiter_handler.hat_Iy_from_jtor(jtor_)
return hat_Iy1
[docs]
def calculate_hatIy_GS(
self,
trial_currents: np.ndarray,
rtol_NK: float,
record_for_updates: bool = False,
) -> np.ndarray:
"""
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
-------
np.ndarray
Normalized plasma current distribution on the reduced plasma domain.
"""
self.assign_currents_solve_GS(
trial_currents, rtol_NK=rtol_NK, record_for_updates=record_for_updates
)
hatIy1 = self.limiter_handler.hat_Iy_from_jtor(self.profiles2.jtor)
return hatIy1
[docs]
def F_function_curr(
self, trial_currents: np.ndarray, active_voltage_vec: np.ndarray
) -> np.ndarray:
"""
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
-------
np.ndarray
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.
"""
self.hatIy1_last = self.calculate_hatIy(trial_currents, self.trial_plasma_psi)
iterated_currs = self.currents_from_hatIy(self.hatIy1_last, active_voltage_vec)
current_res = iterated_currs - trial_currents
return current_res
[docs]
def F_function_curr_GS(
self, trial_currents: np.ndarray, active_voltage_vec: np.ndarray, rtol_NK: float
) -> np.ndarray:
"""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
-------
np.ndarray
Residual in current values. Same format as self.currents_vec.
"""
self.hatIy1_last = self.calculate_hatIy_GS(
trial_currents, rtol_NK=rtol_NK, record_for_updates=False
)
iterated_currs = self.currents_from_hatIy(self.hatIy1_last, active_voltage_vec)
current_res = iterated_currs - trial_currents
return current_res
[docs]
def F_function_psi(
self,
trial_plasma_psi: np.ndarray,
active_voltage_vec: np.ndarray,
rtol_NK: float,
) -> np.ndarray:
"""
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:
1. 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`.
2. 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`.
3. 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
-------
np.ndarray
Flattened residual of the plasma flux, shape (nx * ny,).
Zero residual indicates a self-consistent solution of the plasma + circuit system.
"""
jtor_ = self.profiles2.Jtor(
self.eqR,
self.eqZ,
(self.tokamak_psi + trial_plasma_psi).reshape(self.nx, self.ny),
)
hatIy1 = self.limiter_handler.hat_Iy_from_jtor(jtor_)
self.hatIy1_iterative_cycle(
hatIy1=hatIy1, active_voltage_vec=active_voltage_vec, rtol_NK=rtol_NK
)
psi_residual = self.eq2.plasma_psi.reshape(-1) - trial_plasma_psi
return psi_residual
[docs]
def calculate_rel_tolerance_currents(
self, current_residual: np.ndarray, curr_eps: float
) -> np.ndarray:
"""
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
-------
np.ndarray
Relative residual of the current update. Same format as `self.currents_vec`.
Values close to 0 indicate good convergence of the timestep.
"""
curr_step = abs(self.trial_currents - self.currents_vec_m1)
self.curr_step = np.where(curr_step > curr_eps, curr_step, curr_eps)
rel_curr_res = abs(current_residual / self.curr_step)
return rel_curr_res
[docs]
def calculate_rel_tolerance_GS(
self, trial_plasma_psi: np.ndarray, a_res_GS: np.ndarray | None = None
) -> float:
"""
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
-------
float
Relative plasma flux residual. Values close to 0 indicate good convergence
of the plasma flux update.
"""
plasma_psi_step = trial_plasma_psi - self.eq1.plasma_psi
self.d_plasma_psi_step = np.amax(plasma_psi_step) - np.amin(plasma_psi_step)
if a_res_GS is None:
a_res_GS = self.NK.F_function(
trial_plasma_psi.reshape(-1),
self.tokamak_psi.reshape(-1),
self.profiles2,
)
a_res_GS = np.amax(abs(a_res_GS))
r_res_GS = a_res_GS / self.d_plasma_psi_step
return r_res_GS
[docs]
def check_and_change_profiles(
self, profiles_parameters: dict | None = None
) -> None:
"""
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.
"""
self.profiles_change_flag = 0
if profiles_parameters is not None:
for par in profiles_parameters:
setattr(self.profiles1, par, profiles_parameters[par])
setattr(self.profiles2, par, profiles_parameters[par])
if self.profiles_type == "Lao85":
self.profiles1.initialize_profile()
self.profiles2.initialize_profile()
self.profiles_change_flag = 1
[docs]
def check_and_change_active_coil_resistances(
self, active_coil_resistances: np.ndarray | None
) -> None:
"""
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.
"""
if active_coil_resistances is None:
return
else:
if np.allclose(
active_coil_resistances,
self.evol_metal_curr.active_coil_resistances,
atol=1e-5,
rtol=1e-3,
):
return
else:
self.evol_metal_curr.reset_active_coil_resistances(
active_coil_resistances
)
self.set_solvers()
[docs]
def nlstepper(
self,
active_voltage_vec: np.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-5,
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: np.ndarray | None = None,
no_GS: bool = False,
relinearise_threshold: float | list[float] | None = None,
) -> None:
"""
Advance the system by one timestep using a nonlinear Newton–Krylov solver.
This method advances the plasma and coil current state from time ``t`` to
``t + dt_step`` by 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 (if ``no_GS=False``), solve the GS equation and blend the
result with the trial flux using ``blend_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. If ``relinearise_threshold`` is 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 ``t`` and ``t + 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 :meth:`relinearise`. If convergence
is not achieved, the method stops after ``max_solving_iterations`` iterations,
prints a warning and sets ``self.converged`` to False (no exception is raised).
"""
# GS can only be disabled in linear-only mode
if no_GS and not linear_only:
raise ValueError(
"The flag 'no_GS' can only be True when 'linear_only=True'."
)
if not linear_only and not self.handleMyy.cache_myy:
warnings.warn(
"Non-linear solves without cached Myy are discouraged: a heavy performance cost is expected.\t"
"Consider setting `cache_myy=True` when creating the nonlinear solver or when calling `initialize_from_ICs`, "
"or alternatively, set `linear_only=True` when creating the nlstepper."
)
# evaluate whether relinearisation criterion met or not
relinearise = False
self.relinearise_criteria = 0.0
if relinearise_threshold is not None:
# compare relative change in plasma descriptors since last linearisation for noGS
if no_GS:
if isinstance(relinearise_threshold, list):
relinearise_threshold = [
np.inf if r is None else r for r in relinearise_threshold
]
relinearise_threshold = np.atleast_1d(np.array(relinearise_threshold))
if len(relinearise_threshold) == 1:
self.relinearise_criteria = np.max(
np.abs(
self.plasma_descriptors_vec
- self.initial_plasma_descriptors
)
# / (np.abs(self.initial_plasma_descriptors) + 1e-16)
)
relinearise = (
self.relinearise_criteria >= relinearise_threshold.item()
)
else:
self.relinearise_criteria = np.abs(
self.plasma_descriptors_vec - self.initial_plasma_descriptors
)
# / (np.abs(self.initial_plasma_descriptors) + 1e-16)
relinearise = (
self.relinearise_criteria >= relinearise_threshold
).any()
# compare relative change in jtor since last linearisation otherwise
else:
self.relinearise_criteria = np.linalg.norm(
self.profiles1.jtor - self.jtor0
) / np.linalg.norm(self.jtor0)
relinearise = self.relinearise_criteria >= relinearise_threshold
if linear_only and relinearise:
logger.info("Re-linearising around current equilibrium!")
# before relinearisation we need to solve GS to update the eq object and obtain new plasma descriptors
if no_GS:
self.assign_currents_solve_GS(self.trial_currents, 1e-7)
# sync eq1/profiles1 to the trial solution for relinearise() to use,
# without completing a timestep (this is not a real time advancement)
self.assign_trial_solution_state(from_linear=True)
logger.info(
" Absolute relinearisation criteria change = %s (threshold = %s)",
np.round(self.relinearise_criteria, 3),
np.round(relinearise_threshold, 3),
)
else:
logger.info(
" Relative relinearisation criteria change = %s%% (threshold = %s%%)",
np.round(self.relinearise_criteria * 100, 3),
np.round(relinearise_threshold * 100, 3),
)
self.relinearise(verbose=verbose)
# we need to update the initial descriptors to the values at the relinearisation time
if no_GS:
self.initial_plasma_descriptors = self.plasma_descriptors_vec
# retrieve the old profile parameter values
self.get_profiles_values(self.profiles1)
old_params = self.profiles_parameters_vec
# check if profiles parameters are being evolved
# and action the change where necessary
self.check_and_change_profiles(
profiles_parameters=profiles_parameters,
)
self.check_and_change_active_coil_resistances(
active_coil_resistances=custom_active_coil_resistances
)
# retrieve the new profile parameter values (if present)
self.get_profiles_values(self.profiles1)
new_params = self.profiles_parameters_vec
# calculate change in profiles across timestep: (profiles(t+dt)-profiles(t))/dt
# should be zero if no change
if self.profiles_type == "Lao85":
old_alphas = old_params[self.profiles_alpha_indices]
old_betas = old_params[self.profiles_beta_indices]
new_alphas = new_params[self.profiles_alpha_indices]
new_betas = new_params[self.profiles_beta_indices]
self.dtheta_dt = (
np.concatenate((new_alphas, new_betas))
- np.concatenate((old_alphas, old_betas))
) / self.dt_step
else:
self.dtheta_dt = (new_params - old_params) / self.dt_step
# check if plasma resistivity is being evolved
# and action the change where necessary
self.check_and_change_plasma_resistivity(
plasma_resistivity,
)
# solves the linearised problem for the currents and assigns
# results in preparation for the nonlinear calculations
# Solution and GS equilibrium are assigned to self.trial_currents and self.trial_plasma_psi
self.set_linear_solution(
active_voltage_vec=active_voltage_vec, dtheta_dt=self.dtheta_dt, no_GS=no_GS
)
# check Matrix is still applicable
myy_flag = self.handleMyy.check_Myy(self.hatIy)
if linear_only:
# assign currents and plasma flux to self.currents_vec, self.eq1 and self.profiles1 and complete step
self.step_complete_assign(working_relative_tol_GS, from_linear=True)
if myy_flag:
logger.warning(
"The plasma used for calculating the adopted linearization and the plasma in this evolution have departed by more than %s domain pixels. The linearization may not be accurate.",
self.handleMyy.tolerance,
)
# when not solving GS, evolve the plasma descriptors
if no_GS:
# extract correct profile parameters
if self.profiles_type == "Lao85":
new_alphas = new_params[self.profiles_alpha_indices]
new_betas = new_params[self.profiles_beta_indices]
self.profiles_vec = np.concatenate((new_alphas, new_betas))
else:
self.profiles_vec = new_params
# solve for new descriptors
self.plasma_descriptors_vec = self.new_plasma_descriptors(
new_currents=self.currents_vec,
new_profiles=self.profiles_vec,
)
else:
# seek solution of the full nonlinear problem
log_level = logging.INFO if verbose else logging.DEBUG
if myy_flag:
logger.log(log_level, "The Myy matrix is being recalculated.")
# recalculate Myy
self.handleMyy.force_build_Myy(self.hatIy)
# this assigns to self.eq2 and self.profiles2
# also records self.tokamak_psi corresponding to self.trial_currents in 2d
res_curr = self.F_function_curr(
self.trial_currents, active_voltage_vec
).copy()
# uses self.trial_currents and self.currents_vec_m1 to relate res_curr above to step advancement in the currents
rel_curr_res = self.calculate_rel_tolerance_currents(
res_curr, curr_eps=curr_eps
).copy()
control = np.any(rel_curr_res > target_relative_tol_currents)
# pair self.trial_currents and self.trial_plasma_psi are a GS solution
r_res_GS = self.calculate_rel_tolerance_GS(self.trial_plasma_psi).copy()
control_GS = 0
args_nk = [active_voltage_vec, self.rtol_NK]
if logger.isEnabledFor(log_level):
logger.log(
log_level,
"starting numerical solve: max(residual on current eqs) = %s mean(residual on current eqs) = %s",
np.amax(rel_curr_res),
np.mean(rel_curr_res),
)
log = []
# counter for number of solution cycles
iterations = 0
while control and (iterations < max_solving_iterations):
if logger.isEnabledFor(log_level):
for _ in log:
logger.log(log_level, "%s", _)
log = [self.text_nk_cycle.format(nkcycle=iterations)]
# update plasma flux if trial_currents and plasma_flux exceedingly far from GS solution
if control_GS:
self.NK.forward_solve(
self.eq2,
self.profiles2,
self.rtol_NK,
suppress=True,
force_up_down_symmetric=self.force_up_down_symmetric,
)
self.trial_plasma_psi *= 1 - blend_GS
self.trial_plasma_psi += blend_GS * self.eq2.plasma_psi
# prepare for NK algorithms: 1d vectors needed for independent variable
self.trial_plasma_psi = self.trial_plasma_psi.reshape(-1)
self.tokamak_psi = self.tokamak_psi.reshape(-1)
# calculate initial residual for the root dynamic problem in psi
res_psi = self.F_function_psi(
trial_plasma_psi=self.trial_plasma_psi,
active_voltage_vec=active_voltage_vec,
rtol_NK=self.rtol_NK,
).copy()
del_res_psi = np.amax(res_psi) - np.amin(res_psi)
relative_psi_res = del_res_psi / self.d_plasma_psi_step
log.append(["relative_psi_res", relative_psi_res])
control_NK_psi = (
relative_psi_res > target_relative_tol_GS * max_no_NK_psi
)
if control_NK_psi:
# NK algorithm to solve the root dynamic problem in psi
self.psi_nk_solver.Arnoldi_iteration(
x0=self.trial_plasma_psi.copy(),
dx=res_psi.copy(),
R0=res_psi.copy(),
F_function=self.F_function_psi,
args=args_nk,
step_size=step_size_psi,
scaling_with_n=scaling_with_n,
target_relative_unexplained_residual=target_relative_unexplained_residual,
max_n_directions=max_n_directions,
clip=clip,
# clip_quantiles=clip_quantiles,
)
# update trial_plasma_psi according to NK solution
self.trial_plasma_psi += self.psi_nk_solver.dx
log.append([self.text_psi_1, self.psi_nk_solver.coeffs])
# prepare for NK solver on the currents, 2d plasma flux needed
self.trial_plasma_psi = self.trial_plasma_psi.reshape(self.nx, self.ny)
# calculates initial residual for the root dynamic problem in the currents
# uses the just updated self.trial_plasma_psi
res_curr = self.F_function_curr(
self.trial_currents, active_voltage_vec
).copy()
# NK algorithm to solve the root problem in the currents
self.currents_nk_solver.Arnoldi_iteration(
x0=self.trial_currents,
dx=res_curr.copy(),
R0=res_curr,
F_function=self.F_function_curr,
args=[active_voltage_vec],
step_size=step_size_curr,
scaling_with_n=scaling_with_n,
target_relative_unexplained_residual=target_relative_unexplained_residual,
max_n_directions=max_n_directions,
clip=clip,
# clip_quantiles=clip_quantiles,
)
# update trial_currents according to NK solution
self.trial_currents += self.currents_nk_solver.dx
# check convergence properties of the pair [trial_currents, trial_plasma_psi]:
# relative convergence on the currents:
res_curr = self.F_function_curr(
self.trial_currents, active_voltage_vec
).copy()
rel_curr_res = self.calculate_rel_tolerance_currents(
res_curr, curr_eps=curr_eps
)
control = np.any(rel_curr_res > target_relative_tol_currents)
# relative convergence on the GS problem
r_res_GS = self.calculate_rel_tolerance_GS(self.trial_plasma_psi).copy()
control_GS = r_res_GS > target_relative_tol_GS
control += control_GS
log.append(
[
"The coeffs applied to the current vec = ",
self.currents_nk_solver.coeffs,
]
)
log.append(
[
"The final residual on the current (relative): max =",
np.amax(rel_curr_res),
"mean =",
np.mean(rel_curr_res),
]
)
log.append(["Residuals on static GS eq (relative): ", r_res_GS])
# one full cycle completed
iterations += 1
# convergence checks succeeded, complete step
self.step_complete_assign(working_relative_tol_GS)
# if max_iterations exceeded, log warning
if iterations >= max_solving_iterations:
logger.warning("Forward evolutive solve DID NOT CONVERGE.")
self.converged = False
else:
logger.info("Forward evolutive solve SUCCESS.")
self.converged = True
logger.info(
" Last max. relative currents change: %.2e (vs. requested %.2e).",
np.max(rel_curr_res),
target_relative_tol_currents,
)
logger.info(
" Last max. relative flux change: %.2e (vs. requested %.2e).",
np.max(r_res_GS),
target_relative_tol_GS,
)
logger.info(
" Iterations taken: %d/%d.",
int(iterations),
int(max_solving_iterations),
)
[docs]
def calculate_Leuer_parameter(self) -> None:
"""
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_force : float
Stabilising force due to active coils.
passives_stab_force : float
Stabilising force due to passive coils.
all_coils_stab_force : float
Stabilising force due to all metal coils (active + passive).
actives_destab_force : float
De-stabilising force due to active coils.
passives_destab_force : float
De-stabilising force due to passive coils.
all_coils_destab_force : float
De-stabilising force due to all metal coils.
Leuer_passive_stab_over_active_destab : float
Ratio of passive stabilising force to active coil de-stabilising force.
Leuer_metals_stab_over_active_destab : float
Ratio of total metal stabilising force to active coil de-stabilising force.
Leuer_metals_stab_over_metals_destab : float
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 z derivative of mutual inductance matrix (between coils and plasma points)
M_prime_all_coils_plasma = self.M_coils_plasma(eq=self.eq1, greens=GreensBr)
M_prime_actives_plasma = M_prime_all_coils_plasma[0 : self.n_active_coils, :]
M_prime_passives_plasma = M_prime_all_coils_plasma[self.n_active_coils :, :]
# extract mutual inductances between metals
M_coils_coils = self.evol_metal_curr.coil_self_ind
M_actives_active = M_coils_coils[
0 : self.n_active_coils, 0 : self.n_active_coils
]
M_passives_passives = M_coils_coils[
self.n_active_coils :, self.n_active_coils :
]
# calculate second z derivative of mutual inductance matrix (between coils and plasma points)
M_prime_prime_all_coils_plasma = self.M_coils_plasma(
eq=self.eq1, greens=GreensdBrdz
)
M_prime_prime_actives_plasma = M_prime_prime_all_coils_plasma[
0 : self.n_active_coils, :
]
M_prime_prime_passives_plasma = M_prime_prime_all_coils_plasma[
self.n_active_coils :, :
]
# extract plasma current density vector and currents in the metals
I_all_coils = self.eq1.tokamak.getCurrentsVec()
I_actives = I_all_coils[0 : self.n_active_coils]
I_passives = I_all_coils[self.n_active_coils :]
# calculate stabilising force gradients created by actives, passives, and all metals
self.actives_stab_force = (
self.Iy @ M_prime_actives_plasma.T
) @ np.linalg.solve(M_actives_active, M_prime_actives_plasma @ self.Iy)
self.passives_stab_force = (
self.Iy @ M_prime_passives_plasma.T
) @ np.linalg.solve(M_passives_passives, M_prime_passives_plasma @ self.Iy)
self.all_coils_stab_force = (
self.Iy @ M_prime_all_coils_plasma.T
) @ np.linalg.solve(M_coils_coils, M_prime_all_coils_plasma @ self.Iy)
# calculate de-stabilising force gradients created by actives, passives, and all metals
self.actives_destab_force = self.Iy @ (
M_prime_prime_actives_plasma.T @ I_actives
)
self.passives_destab_force = self.Iy @ (
M_prime_prime_passives_plasma.T @ I_passives
)
self.all_coils_destab_force = self.Iy @ (
M_prime_prime_all_coils_plasma.T @ I_all_coils
)
# use these to return the Leuer parameters in different cases
self.Leuer_passive_stab_over_active_destab = (
self.passives_stab_force / self.actives_destab_force
)
self.Leuer_metals_stab_over_active_destab = (
self.all_coils_stab_force / self.actives_destab_force
)
self.Leuer_metals_stab_over_metals_destab = (
self.all_coils_stab_force / self.all_coils_destab_force
)
[docs]
def M_coils_plasma(
self,
eq: object,
greens: Callable[..., np.ndarray],
) -> np.ndarray:
"""
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 : np.ndarray, shape (n_coils, n_plasma_pts)
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.
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.
"""
# plasma grid points (inside limiter)
plasma_pts = eq.limiter_handler.plasma_pts
# create mutual inductance matrix
M = np.zeros((len(eq.tokamak.coils_list), len(plasma_pts)))
for j, labelj in enumerate(eq.tokamak.coils_list):
greenm = greens(
plasma_pts[:, 0, np.newaxis],
plasma_pts[:, 1, np.newaxis],
eq.tokamak.coils_dict[labelj]["coords"][0][np.newaxis, :],
eq.tokamak.coils_dict[labelj]["coords"][1][np.newaxis, :],
)
greenm *= eq.tokamak.coils_dict[labelj]["polarity"][
np.newaxis, :
] # multiply by polarity of filaments
greenm *= eq.tokamak.coils_dict[labelj]["multiplier"][
np.newaxis, :
] # multiply by multitplier of filaments
greenm *= eq.tokamak.coils_dict[labelj]["coords"][0][
np.newaxis, :
] # multiply by R co-ords
M[j] = np.sum(greenm, axis=-1) # sum over filaments
return -2 * np.pi * M