freegsnke.mastu_tools module
Contains various functions required to load MAST-U experimental shot data, ready for simulation in FreeGSNKE. Also contains additional functions that may be of use in the simulations themselves.
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/>.
- freegsnke.mastu_tools.Separatrix(R: ndarray, Z: ndarray, psi: ndarray, ntheta: int, psival: float = 1.0, theta_grid: ndarray | None = None, input_opoint: tuple[float, float] | None = None) tuple[ndarray, ndarray][source]
Compute separatrix coordinates for a given equilibrium flux map.
This function traces the ψ = const surface corresponding to the separatrix (default psival = 1.0 in normalized coordinates) starting from the magnetic axis and marching outwards in poloidal angle.
The separatrix is sampled at equally spaced geometric poloidal angles, with care taken to avoid sampling exactly at the X-point locations.
- Parameters:
R (ndarray) – Radial grid coordinates (2D array).
Z (ndarray) – Vertical grid coordinates (2D array).
psi (ndarray) – Poloidal flux on the (R, Z) grid.
ntheta (int) – Number of poloidal angle samples along the separatrix.
psival (float, optional) – Target normalized flux value defining the separatrix.
theta_grid (ndarray, optional) – User-specified poloidal angle grid. If None, a uniform grid is used.
input_opoint (tuple, optional) – User-specified magnetic axis (R0, Z0). If None, it is inferred.
- Returns:
points (ndarray) – Array of separatrix points (R, Z) sampled along θ.
theta_grid (ndarray) – Poloidal angle grid used for the construction.
- freegsnke.mastu_tools.extract_EFIT_outputs(client: object, shot: int, time_indices: ndarray) tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, dict, dict][source]
Extract the key (magnetics-only) EFIT++ reconstruction output data at each time slice so that we can compare to FreeGSNKE.
- Parameters:
client (object) – The pyUDA client.
shot (int) – MAST-U shot number.
time_indices (np.ndarray) – Array of logicals, same length as the number of EFIT++ reconstruction time slices, at which to extract the EFIT++ output data.
- Returns:
np.ndarray – Total plasma flux map [Webers/(2pi)] at each EFIT++ reconstruction time.
np.ndarray – Total plasma flux on the magnetic axis [Webers/(2pi)] at each EFIT++ reconstruction time.
np.ndarray – Total plasma flux on the plasma boundary [Webers/(2pi)] at each EFIT++ reconstruction time.
np.ndarray – Toroidal plasma current density map [Amps/m^2] at each EFIT++ reconstruction time.
np.ndarray – The (R,Z) location of the magnetic axis at each EFIT++ reconstruction time.
np.ndarray – The inner and outer R location of the plasma boundary at the midplane at each EFIT++ reconstruction time.
np.ndarray – The (R,Z) location of the X-points at each EFIT++ reconstruction time.
np.ndarray – The p’ profile (vs. normalised psi) at each EFIT++ reconstruction time.
np.ndarray – The FF’ profile (vs. normalised psi) at each EFIT++ reconstruction time.
np.ndarray – The strikepoints at each EFIT++ reconstruction time (not always very accurate).
dict – Dictionary of (target and computed) fluxloop readings used by EFIT++ at each reconstruction time.
dict – Dictionary of (target and computed) pickup coil readings used by EFIT++ at each reconstruction time.
- freegsnke.mastu_tools.extract_EFIT_outputs_splines(client: object, shot: int, time_indices: ndarray) tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, dict, dict][source]
Extract the key (magnetics + motional stark effect) EFIT++ reconstruction output data at each time slice so that we can compare to FreeGSNKE.
- Parameters:
client (object) – The pyUDA client.
shot (int) – MAST-U shot number.
time_indices (np.ndarray) – Array of logicals, same length as the number of EFIT++ reconstruction time slices, at which to extract the EFIT++ output data.
- Returns:
np.ndarray – Total plasma flux map [Webers/(2pi)] at each EFIT++ reconstruction time.
np.ndarray – Total plasma flux on the magnetic axis [Webers/(2pi)] at each EFIT++ reconstruction time.
np.ndarray – Total plasma flux on the plasma boundary [Webers/(2pi)] at each EFIT++ reconstruction time.
np.ndarray – Toroidal plasma current density map [Amps/m^2] at each EFIT++ reconstruction time.
np.ndarray – The (R,Z) location of the magnetic axis at each EFIT++ reconstruction time.
np.ndarray – The inner and outer R location of the plasma boundary at the midplane at each EFIT++ reconstruction time.
np.ndarray – The (R,Z) location of the X-points at each EFIT++ reconstruction time.
np.ndarray – The p’ profile (vs. normalised psi) at each EFIT++ reconstruction time.
np.ndarray – The FF’ profile (vs. normalised psi) at each EFIT++ reconstruction time.
np.ndarray – The strikepoints at each EFIT++ reconstruction time (not always very accurate).
dict – Dictionary of (target and computed) fluxloop readings used by EFIT++ at each reconstruction time.
dict – Dictionary of (target and computed) pickup coil readings used by EFIT++ at each reconstruction time.
- freegsnke.mastu_tools.find_psisurface(psifunc: Callable[[...], ndarray], R: ndarray, Z: ndarray, r0: float, z0: float, r1: float, z1: float, psival: float = 1.0, n: int = 100) tuple[float, float][source]
Find an intersection point of a ψ = const surface along a straight line.
This routine samples a straight line from an initial point inside the separatrix to a point outside it, evaluates the flux along the line, and interpolates to locate the position where ψ equals the target value.
- Parameters:
psifunc (callable) – Interpolated flux function ψ(R, Z).
R (ndarray) – Radial grid (used for domain clipping).
Z (ndarray) – Vertical grid (used for domain clipping).
r0 (float) – Starting radial coordinate (assumed inside target surface).
z0 (float) – Starting vertical coordinate (assumed inside target surface).
r1 (float) – Ending radial coordinate (outside target surface).
z1 (float) – Ending vertical coordinate (outside target surface).
psival (float, optional) – Target flux value defining the surface.
n (int, optional) – Number of points sampled along the line.
- Returns:
r (float) – Radial coordinate of ψ = psival intersection.
z (float) – Vertical coordinate of ψ = psival intersection.
- freegsnke.mastu_tools.find_strikepoints(R: ndarray, Z: ndarray, psi: ndarray, psi_boundary: float, wall: ndarray) ndarray | None[source]
Find the strikepoints of an equilibrium with the wall.
- Parameters:
R (np.ndarray (nx, nz)) – 2D array of major radius coordinates [m]
Z (np.ndarray (nx, nz)) – 2D array of vertical coordinates [m]
psi (np.ndarray (nx, nz)) – 2D poloidal flux map [Wb]
psi_boundary (float) – Value of psi at the plasma boundary [Wb]
wall (np.ndarray (N, 2)) – Wall/limiter coordinates as (R, Z) pairs [m]
- Returns:
Array of strikepoint coordinates, shape (M, 2), or None if no intersections are found.
- Return type:
np.ndarray or None
- freegsnke.mastu_tools.get_AMC_currents(t: float, att_dict: dict, data: dict, dt: float = 0.002) ndarray[source]
Extract required AMC currents in the active coils in MAST-U at time ‘t’ from ‘data’ dictionary by taking the average current between [t - dt, t + dt].
- Parameters:
t (float) – Time from which to average current values over [s].
att_dict (dict) – Dictionary containing the attributes corresponding to the data.
data (dict) – Dictionary containing all of the relevant AMC current data.
dt (float) – Time step over which to average the currents: interval will be [t-dt, t+dt].
- Returns:
Returns array of currents in the active coils [Amps].
- Return type:
np.ndarray
- freegsnke.mastu_tools.get_XDC_voltages(t: float, dt: float, att_dict: dict, data: dict, nsteps: int = 1) ndarray[source]
Extract required XDC voltages in the active coils in MAST-U at time ‘t’ from ‘data’ dictionary by taking the average voltage between [t-dt, t+dt].
Returns voltages for ‘nsteps’ (in array); t advances by dt at each step.
- Parameters:
t (float) – Time from which to average voltages values over [s].
dt (float) – Half-width of the averaging window, [t-dt, t+dt], and the step in time between successive returned voltages.
att_dict (dict) – Dictionary containing the attributes corresponding to the data.
data (dict) – Dictionary containing all of the relevant XDC voltage data.
nsteps (int) – Number of time steps to return voltages at.
- Returns:
Returns array (nsteps x 12) of voltages in the active coils [Volts].
- Return type:
np.ndarray
- freegsnke.mastu_tools.get_element_vertices(centreR: float, centreZ: float, dR: float, dZ: float, a1: float, a2: float, version: float = 0.1, close_shape: bool = False) list[source]
Convert EFIT++ description of parallelograms to four vertices (used in FreeGSNKE passive structures).
Code courtesy of Lucy Kogan (UKAEA).
- Parameters:
centreR (float) – Centre (R) of the parallelogram.
centreZ (float) – Centre (Z) of the parallelogram.
dR (float) – Width of the the parallelogram.
dZ (float) – Height of the the parallelogram.
a1 (float) – Angle between the horizontal and the base of the parallelogram (zero for rectangles).
a2 (float) – Angle between the horizontal and the right side of the parallelogram (zero for rectangles).
version (float, optional) – Geometry version (backwards compatibilty for bug in < V0.1). Use default.
close_shape (bool) – Repeat first vertex to close the shape if set to True.
- Returns:
[rr, zz, dR, dZ]: the radial ‘rr’ and vertical ‘zz’ vertex positions and the original width ‘dR’ and height ‘dZ’ of the shape.- Return type:
list
- freegsnke.mastu_tools.get_machine_data(save_path: str | None = None, shot: int = 45425, split_passives: bool = True) None[source]
This functions builds the active coil, passive structure, wall, and limiter machine description pickle files for MAST-U (for a given shot number).
- Parameters:
save_path (str, optional) – Path in which to save the machine pickle files. Despite the default, a value must be supplied.
shot (int, optional) – MAST-U shot number.
split_passives (bool, optional) – If True, we model the passive structures as parallelograms (recommended), if False, we model as point current sources
- Raises:
ValueError – If save_path is None.
ImportError – If the optional pyuda or uda-mast packages are not installed.
Notes
Writes the pickle files for the machine description to save_path.
- freegsnke.mastu_tools.interpolate_data(times: ndarray, data: ndarray, t_start: float | None = None, t_final: float | None = None, order: int = 5) Polynomial[source]
Fit a polynomial to time-series data and return an evaluatable interpolant.
This function selects a time window (if provided), fits a polynomial of specified order to the data within that window, and returns the resulting polynomial object. The output can be evaluated on scalar or array inputs.
- Parameters:
times (ndarray) – Array of time values corresponding to the data samples.
data (ndarray) – Data values sampled at the given times.
t_start (float, optional) – Start of the time window. If None, the full range is used from the beginning.
t_final (float, optional) – End of the time window. If None, the full range is used up to the end.
order (int, optional) – Degree of the polynomial used for fitting.
- Returns:
Polynomial object representing the fitted interpolation, callable on scalar or array inputs.
- Return type:
numpy.polynomial.Polynomial
- freegsnke.mastu_tools.load_currents_voltages_and_TS_signals(client: object, shot: int = 45425) tuple[dict, dict][source]
Extract the (analysed) AMC currents, the (raw) XDC/XCM voltages, and (if available) the (analysed) AYC Thomson scattering information.
- Parameters:
client (object) – The pyUDA client.
shot (int) – MAST-U shot number.
- Returns:
dict – Dictionary containing the attributes corresponding to the data.
dict – Dictionary containing all of the relevant data.
- freegsnke.mastu_tools.load_efit_times_and_status(client: object, shot: int = 45425) tuple[ndarray, ndarray][source]
Extract the (magnetics-only) EFIT++ reconstruction shot status, which tells us whether each time slice converged or not.
- Parameters:
client (object) – The pyUDA client.
shot (int) – MAST-U shot number.
- Returns:
np.ndarray – Shot times at which EFIT++ reconstructions take place.
np.ndarray – Shot status at the times when EFIT++ reconstructions take place.
- freegsnke.mastu_tools.load_efit_times_and_status_splines(client: object, shot: int = 45425) tuple[ndarray, ndarray][source]
Extract the (magnetics + motional stark effect) EFIT++ reconstruction shot status, which tells us whether each time slice converged or not.
- Parameters:
client (object) – The pyUDA client.
shot (int) – MAST-U shot number.
- Returns:
np.ndarray – Shot times at which EFIT++ reconstructions take place.
np.ndarray – Shot status at the times when EFIT++ reconstructions take place.
- freegsnke.mastu_tools.load_static_solver_inputs(client: object, active_coils_path: str, passive_coils_path: str, shot: int = 45425, zero_passives: bool = False) tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, dict, dict, dict][source]
Extract the key (magnetics-only) EFIT++ reconstruction data at each time slice so that we can use it in FreeGSNKE to carry out static forward GS solves.
- Parameters:
client (object) – The pyUDA client.
active_coils_path (str) – Path to active coils pickle.
passive_coils_path (str) – Path to passive coils pickle.
shot (int) – MAST-U shot number.
zero_passives (bool) – If True, we set the currents in the MAST-U passive structures to zero, if False, we use the currents found by EFIT++.
- Returns:
np.ndarray – Total plasma current [Amps] at each EFIT++ reconstruction time.
np.ndarray – Vaccum toroidal field parameter at each EFIT++ reconstruction time.
np.ndarray – Alpha coefficients (for p’) from Lao toroidal current density profile at each EFIT++ reconstruction time.
np.ndarray – Beta coefficients (for FF’) from Lao toroidal current density profile at each EFIT++ reconstruction time.
np.ndarray – Alpha logical parameter (sets p’ edge boundary condition) for Lao toroidal current density profile at each EFIT++ reconstruction time.
np.ndarray – Beta logical parameter (sets FF’ edge boundary condition) for Lao toroidal current density profile at each EFIT++ reconstruction time.
dict – Dictionary of active coil and passive structure currents: within each key is an array of currents (one at each EFIT++ reconstruction time). These are currents for the symmetric active coil set up (upper/lower coil currents averaged).
dict – Dictionary of active coil and passive structure currents, keyed by the individual EFIT++ coil names (upper and lower coils separately): within each key is an array of currents (one at each EFIT++ reconstruction time). These are currents for the non-symmetric active coil set up.
dict – Dictionary of active coil and passive structure current discrepancies: these are between the symmetric and non-symmetric active coil set ups.
- freegsnke.mastu_tools.load_static_solver_inputs_splines(client: object, active_coils_path: str, passive_coils_path: str, shot: int = 45425, zero_passives: bool = False) tuple[ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, ndarray, dict, dict, dict][source]
Extract the key (magnetics + motional stark effect) EFIT++ reconstruction data at each time slice so that we can use it in FreeGSNKE to carry out static forward GS solves.
- Parameters:
client (object) – The pyUDA client.
active_coils_path (str) – Path to active coils pickle.
passive_coils_path (str) – Path to passive coils pickle.
shot (int) – MAST-U shot number.
zero_passives (bool) – If True, we set the currents in the MAST-U passive structures to zero, if False, we use the currents found by EFIT++.
- Returns:
np.ndarray – Total plasma current [Amps] at each EFIT++ reconstruction time.
np.ndarray – Vaccum toroidal field parameter at each EFIT++ reconstruction time.
np.ndarray – Knot points for p’ profile at each EFIT++ reconstruction time.
np.ndarray – Knot points for FF’ profile at each EFIT++ reconstruction time.
np.ndarray – Values of p’ profile at knot points at each EFIT++ reconstruction time.
np.ndarray – Values of FF’ profile at knot points at each EFIT++ reconstruction time.
np.ndarray – Values of second derivative of p’ profile at knot points at each EFIT++ reconstruction time.
np.ndarray – Values of second derivative of FF’ profile at knot points at each EFIT++ reconstruction time.
np.ndarray – Values of tension spline parameter for p’ profile at each EFIT++ reconstruction time.
np.ndarray – Values of tension spline parameter for FF’ profile at each EFIT++ reconstruction time.
dict – Dictionary of active coil and passive structure currents: within each key is an array of currents (one at each EFIT++ reconstruction time). These are currents for the symmetric active coil set up (upper/lower coil currents averaged).
dict – Dictionary of active coil and passive structure currents, keyed by the individual EFIT++ coil names (upper and lower coils separately): within each key is an array of currents (one at each EFIT++ reconstruction time). These are currents for the non-symmetric active coil set up.
dict – Dictionary of active coil and passive structure current discrepancies: these are between the symmetric and non-symmetric active coil set ups.
- freegsnke.mastu_tools.max_euclidean_distance(points1: ndarray, points2: ndarray) float[source]
Compute the maximum Euclidean distance between corresponding points in two sets.
Points containing NaN values are excluded before the distance calculation.
- Parameters:
points1 (ndarray) – First set of (x, y) points.
points2 (ndarray) – Second set of (x, y) points with the same shape as points1.
- Returns:
Maximum Euclidean distance between valid corresponding points. Returns NaN if no valid points remain.
- Return type:
float
- freegsnke.mastu_tools.median_euclidean_distance(points1: ndarray, points2: ndarray) float[source]
Compute the median Euclidean distance between corresponding points in two sets.
Points containing NaN values are excluded before computing distances.
- Parameters:
points1 (ndarray) – First set of (x, y) points.
points2 (ndarray) – Second set of (x, y) points with the same shape as points1.
- Returns:
Median Euclidean distance between valid corresponding points. Returns NaN if no valid points remain.
- Return type:
float
- freegsnke.mastu_tools.plasma_resistivity_controller(t: float, dt: float, target: float, history: list[float], k_prop: float, k_int: float, k_deriv: float, prop_exponent: float, prop_error: float, deriv_threshold: float, int_factor: float, derivative_lag: int = 1, shift_pred: bool = True, Ip_func: Callable[[float], float] | None = None) float[source]
PID controller required to calculate required change in plasma resistivity.
- Parameters:
t (float) – Current time [s].
dt (float) – Time step over which controller should act [s].
target (float) – Target total plasma current to maintain [Amps].
history (list) – List of previous total plasma currents [Amps].
k_prop (float) – Proportional gain controls how strongly the resistivity reacts to deviations from the target.
k_int (float) – Integral gain controls how the controller accumulates error over time (to correct drifts).
k_deriv (float) – Derivative gain controls how the controller reacts to rapid changes in target.
prop_exponent (float) – Exoponent in proportional term.
prop_error (float) – Reference error for the proportional term.
deriv_threshold (float) – Threshold for derivative action - limits effect of sudden jumps in target.
int_factor (float) – Exponential decay factor that limits effect of older values on integral term.
derivative_lag (int) – Number of historical values over which the derivative term acts.
shift_pred (bool) – Shift the predictions using future values of the total plasma current.
Ip_func (Callable[[float], float], optional) – Function that returns the total plasma current at time ‘t’. Required if shift_pred is True.
- Returns:
Plasma resistivity required to maintain the target plasma current.
- Return type:
float
- freegsnke.mastu_tools.separatrix_areas(separatrix_1: ndarray, separatrix_2: ndarray) tuple[float, Polygon, Polygon][source]
Compute a geometric similarity metric between two separatrix shapes.
This function constructs convex hull polygons from two sets of (R, Z) points, then compares their overlap using union and intersection areas. The resulting metric η is based on the non-overlapping area relative to the total area, as defined in Bardsley et al. (2024, Nuclear Fusion).
- Parameters:
separatrix_1 (ndarray) – Array of shape (N, 2) containing (R, Z) points of the first separatrix.
separatrix_2 (ndarray) – Array of shape (M, 2) containing (R, Z) points of the second separatrix.
- Returns:
eta (float) – Normalised non-overlap metric between the two separatrices.
polygon1 (shapely.geometry.Polygon) – Convex hull polygon of separatrix_1.
polygon2 (shapely.geometry.Polygon) – Convex hull polygon of separatrix_2.
- freegsnke.mastu_tools.smooth_data(t_start: float, t_end: float, data: ndarray, t_data_start: float, t_data_end: float, n_data_points: int | None = None) float[source]
Finds the median of the `data’ vector values between [t_start, t_end]. Requires knowledge of the time interval the data is recorded over [t_data_start, t_data_end].
- Parameters:
t_start (float) – Start time from which to average data values over.
t_end (float) – End time from which to average data values over.
data (np.ndarray) – 1D array of data values.
t_data_start (float) – Start time at which data is recorded, i.e. data[0] corresponds to ‘t_data_start’.
t_data_end (float) – End time at which data is recorded, i.e. data[-1] corresponds to ‘t_data_end’.
n_data_points (int, optional) – Number of time steps data recorded over. If None,
len(data)is used.
- Returns:
Returns median of `data’ vector values between [t_start, t_end].
- Return type:
float
- freegsnke.mastu_tools.vertical_controller(dt: float, target: float, history: list[float], k_prop: float, k_int: float, k_deriv: float, prop_exponent: float, prop_error: float, deriv_threshold: float, int_factor: float, Ip: float, Ip_ref: float | None = None, derivative_lag: int = 1) float[source]
PID controller required for plasma vertical position. Computes the required voltage in the vertical stability coil to stabilise the plasma.
- Parameters:
dt (float) – Time step over which controller should act [s].
target (float) – Target vertical position [m].
history (list) – List of previous vertical positions of the effective toroidal current center [m].
k_prop (float) – Proportional gain controls how strongly the voltage reacts to deviations from the target.
k_int (float) – Integral gain controls how the controller accumulates error over time (to correct drifts).
k_deriv (float) – Derivative gain controls how the controller reacts to rapid changes in target.
prop_exponent (float) – Exoponent in proportional term.
prop_error (float) – Reference error for the proportional term.
deriv_threshold (float) – Threshold for derivative action - limits effect of sudden jumps in target.
int_factor (float) – Exponential decay factor that limits effect of older values on integral term.
Ip (float) – Total plasma current at current time [Amps].
Ip_ref (float, optional) – Reference total plasma current [Amps], used to normalise output. If None, the output is not rescaled.
derivative_lag (int) – Number of historical values over which the derivative term acts.
- Returns:
Voltage required for the vertical stability coil to stabilise the plasma [Volts] (0 if history is empty).
- Return type:
float