Example: Static forward free-boundary equilibrium calculations (in MAST)
Here we will show how to solve for equilibria on MAST, the predecessor of MAST-U.
The machine geometry (active coils, passive structures, limiter, and wall) comes from the public FAIR-MAST database (which also contains lots of other open-source shot data from MAST!).
In this notebook, the coil currents, passive structure currents, and profiles come from FAIR-MAST but are stored locally for easy access. They are based on the EFIT reconstruction of MAST shot 30421 at 0.25 s.
The local data is stored in data/MAST_30421_0.25s.json, together with the EFIT data for comparison.
Other recent work using FreeGSNKE on MAST equilibria can be found here:
Import packages
import json
import matplotlib.pyplot as plt
import numpy as np
Create the machine object
# build machine
from freegsnke import build_machine
tokamak = build_machine.tokamak(
active_coils_path="../machine_configs/MAST/MAST_active_coils.pickle",
passive_coils_path="../machine_configs/MAST/MAST_passive_coils.pickle",
limiter_path="../machine_configs/MAST/MAST_limiter.pickle",
wall_path="../machine_configs/MAST/MAST_wall.pickle",
)
Active coils --> built from pickle file.
Passive structures --> built from pickle file.
Limiter --> built from pickle file.
Wall --> built from pickle file.
Magnetic probes --> none provided.
Resistance (R) and inductance (M) matrices --> built using actives (and passives if present).
Tokamak built.
/opt/hostedtoolcache/Python/3.10.22/x64/lib/python3.10/site-packages/freegsnke/build_machine.py:575: UserWarning: Overlapping coil elements detected:
- P3L[0] and P3L[1] (R=1.068 m, Z=-1.093 m, area=0.2951 cm^2)
- P3L[6] and P3L[7] (R=1.137 m, Z=-1.093 m, area=0.2951 cm^2)
- P3U[0] and P3U[1] (R=1.069 m, Z=1.100 m, area=0.2951 cm^2)
- P3U[6] and P3U[7] (R=1.138 m, Z=1.100 m, area=0.2951 cm^2)
- mid_MID2 and mid_MID3 (R=1.658 m, Z=2.007 m, area=0.09488 cm^2)
- mid_MID5 and mid_MID6 (R=1.658 m, Z=-2.007 m, area=0.09488 cm^2)
- mid_MID8 and mid_MID9 (R=0.792 m, Z=2.007 m, area=0.09394 cm^2)
- mid_MID11 and mid_MID12 (R=0.792 m, Z=-2.007 m, area=0.09394 cm^2)
- p2larm_P2LARM1 and p2ldivpl_P2LDIVPL1 (R=0.415 m, Z=-1.583 m, area=0.35 cm^2)
- P3L[6] and coil_cases_coil_cases_P3L_5 (R=1.146 m, Z=-1.052 m, area=0.4946 cm^2)
- P3U[6] and coil_cases_coil_cases_P3U_5 (R=1.146 m, Z=1.056 m, area=0.2406 cm^2)
- P3U[7] and coil_cases_coil_cases_P3U_3 (R=1.146 m, Z=1.144 m, area=0.2265 cm^2)
_report_overlaps(deferred_overlaps, strict_overlap_check=False)
# plot the machine
fig, ax = plt.subplots(figsize=(6, 10), dpi=80)
tokamak.plot(axis=ax, show=False) # plots the active coils and passive structures
ax.plot(tokamak.limiter.R, tokamak.limiter.Z, "k-", linewidth=1.2) # plots the limiter
ax.grid(alpha=0.5)
ax.set_aspect("equal")
ax.set_xlim(0.0, 2.15)
ax.set_ylim(-2.6, 2.6)
ax.set_xlabel(r"Major radius, $R$ [m]")
ax.set_ylabel(r"Height, $Z$ [m]")
Text(0, 0.5, 'Height, $Z$ [m]')
Instantiate an equilibrium
from freegsnke import equilibrium_update
eq = equilibrium_update.Equilibrium(
tokamak=tokamak, # provide tokamak object
Rmin=0.06, Rmax=1.98, # radial range (same as the EFIT grid)
Zmin=-2.0, Zmax=2.0, # vertical range (same as the EFIT grid)
nx=129, # number of radial grid points (needs to be of the form 2**n + 1)
ny=129, # number of vertical grid points (needs to be of the form 2**n + 1)
)
Load the EFIT data and instantiate a profile object
# EFIT reconstruction of MAST shot 30421 at 0.25 s
with open("data/MAST_30421_0.25s.json") as f:
efit = json.load(f)
from freegsnke.jtor_update import GeneralPprimeFFprime
profiles = GeneralPprimeFFprime(
eq=eq, # equilibrium object
Ip=efit["Ip"], # plasma current [A]
fvac=efit["fvac"], # fvac = R * B_tor [T m]
psi_n=np.array(efit["psi_n"]), # normalised poloidal flux
pprime_data=np.array(efit["pprime"]), # pressure derivative profile
ffprime_data=np.array(efit["ffprime"]), # FF' profile
p_data=np.array(efit["pressure"]), # pressure profile (optional)
f_data=np.array(efit["f"]), # F profile (optional)
Ip_logic=True,
)
Set the coil currents
EFIT gives one current for each circuit. We convert these currents to FreeGSNKE coil currents as follows:
The shaping coil currents (P2 to P6) are in ampere-turns, so we divide them by the number of turns in each coil.
The solenoid (SOL) current is multiplied by 0.5 because of its wiring.
Each PF coil case is one EFIT circuit, but it is made of a number of separate elements in FreeGSNKE. We split the case current across these elements in proportion to their areas.
All other passive structure currents are used as they are.
currents = efit["currents"]
# active coils
for name in efit["actives_order"]:
if name == "SOL":
value = 0.5 * currents[name]
else:
value = currents[name] / len(tokamak.coils_dict[name]["coords"][0])
tokamak.set_coil_current(coil_label=name, current_value=value)
# passive structures
for name in efit["passives_order"]:
if name.startswith("coil_cases"):
case = "coil_cases_" + name[-3:] # e.g. "coil_cases_P2U"
elements = [c for c in tokamak.coil_names if case in c]
areas = np.array([tokamak.coils_dict[e]["area"] for e in elements])
for element, area in zip(elements, areas):
tokamak.set_coil_current(coil_label=element, current_value=currents[name] * area / areas.sum())
else:
tokamak.set_coil_current(coil_label=name, current_value=currents[name])
The forward solve
# load the static nonlinear solver
from freegsnke import GSstaticsolver
from freegsnke.equilibrium import PsiGuessParabolicJtor
GSStaticSolver = GSstaticsolver.NKGSsolver(eq, seed=42)
# put the initial guess near the EFIT magnetic axis (below the midplane),
# so that the solver finds the lower X-point configuration
psi_guess = PsiGuessParabolicJtor(
h=efit["axis"][0], # radial centre of ellipse
k=efit["axis"][1], # vertical centre of ellipse
a=0.5, # approximate radial minor radius of the plasma
b=0.9, # approximate vertical minor radius of the plasma
Ip=profiles.Ip, # plasma current used to scale the guess
psi_scale=1.0, # scaling factor for the initial flux guess
)
eq.plasma_psi = psi_guess(eq=eq)
# carry out the forward solve with fixed coil currents
GSStaticSolver.forward_solve(
eq=eq,
profiles=profiles,
target_relative_tolerance=1e-7,
max_solving_iterations=100,
verbose=True, # print output
)
-----
Forward static solve starting...
Initial guess for plasma_psi successful, residual found.
Initial relative error = 6.18e-01
-----
Forward static solve starting...
Initial guess for plasma_psi successful, residual found.
Initial relative error = 6.18e-01
-----
Picard iteration: 0
Update too large, resized.
...relative error = 4.09e-01
-----
Picard iteration: 1
Update too large, resized.
...relative error = 2.37e-01
-----
Picard iteration: 2
...relative error = 9.68e-02
-----
-----
Newton-Krylov iteration: 3
...number of Krylov vectors used = 2
...relative error = 1.54e-02
-----
-----
Newton-Krylov iteration: 4
...number of Krylov vectors used = 2
...relative error = 4.69e-03
-----
-----
Newton-Krylov iteration: 5
...number of Krylov vectors used = 3
...relative error = 9.65e-04
-----
-----
Newton-Krylov iteration: 6
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 7.85e-04
-----
-----
Newton-Krylov iteration: 7
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 5.52e-04
-----
-----
Newton-Krylov iteration: 8
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 3.59e-04
-----
-----
Newton-Krylov iteration: 9
...number of Krylov vectors used = 17
...relative error = 4.99e-04
-----
-----
Newton-Krylov iteration: 10
...number of Krylov vectors used = 1
...relative error = 6.26e-05
-----
-----
Newton-Krylov iteration: 11
...number of Krylov vectors used = 5
...relative error = 1.35e-05
-----
-----
Newton-Krylov iteration: 12
...number of Krylov vectors used = 17
...relative error = 1.01e-05
-----
-----
Newton-Krylov iteration: 13
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 9.67e-06
-----
-----
Newton-Krylov iteration: 14
...number of Krylov vectors used = 17
...relative error = 6.98e-06
-----
-----
Newton-Krylov iteration: 15
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 6.47e-06
-----
-----
Newton-Krylov iteration: 16
...number of Krylov vectors used = 17
...relative error = 4.70e-06
-----
-----
Newton-Krylov iteration: 17
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 4.31e-06
-----
-----
Newton-Krylov iteration: 18
...number of Krylov vectors used = 17
...relative error = 3.23e-06
-----
-----
Newton-Krylov iteration: 19
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 2.96e-06
-----
-----
Newton-Krylov iteration: 20
...number of Krylov vectors used = 17
...relative error = 2.21e-06
-----
-----
Newton-Krylov iteration: 21
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 1.99e-06
-----
-----
Newton-Krylov iteration: 22
...number of Krylov vectors used = 17
...relative error = 1.61e-06
-----
-----
Newton-Krylov iteration: 23
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 1.45e-06
-----
-----
Newton-Krylov iteration: 24
...number of Krylov vectors used = 17
...relative error = 1.12e-06
-----
-----
Newton-Krylov iteration: 25
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 1.08e-06
-----
-----
Newton-Krylov iteration: 26
...number of Krylov vectors used = 17
...relative error = 6.94e-07
-----
-----
Newton-Krylov iteration: 27
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 5.70e-07
-----
-----
Newton-Krylov iteration: 28
...number of Krylov vectors used = 17
New starting_direction used due to collinear residuals.
...relative error = 3.82e-07
-----
-----
Newton-Krylov iteration: 29
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 5.13e-07
-----
-----
Newton-Krylov iteration: 30
...number of Krylov vectors used = 17
...relative error = 3.01e-07
-----
-----
Newton-Krylov iteration: 31
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 2.80e-07
-----
-----
Newton-Krylov iteration: 32
...number of Krylov vectors used = 17
...relative error = 2.00e-07
-----
-----
Newton-Krylov iteration: 33
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 1.93e-07
-----
-----
Newton-Krylov iteration: 34
...number of Krylov vectors used = 17
...relative error = 2.35e-07
-----
-----
Newton-Krylov iteration: 35
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 1.80e-07
-----
-----
Newton-Krylov iteration: 36
...number of Krylov vectors used = 17
Increase in residual, update reduction triggered.
...relative error = 1.07e-07
-----
-----
Newton-Krylov iteration: 37
...number of Krylov vectors used = 4
...relative error = 1.64e-08
-----
Forward static solve SUCCESS. Tolerance 1.64e-08 (vs. requested 1.00e-07) reached in 38/100 iterations.
Plot the equilibrium and compare with EFIT
efit_lcfs = np.array(efit["lcfs"])
efit_xpoints = np.array(efit["xpoints"])
fig, ax = plt.subplots(figsize=(6, 10), dpi=80)
ax.grid(zorder=0, alpha=0.75)
ax.set_aspect("equal")
eq.tokamak.plot(axis=ax, show=False) # plots the active coils and passive structures
eq.plot(axis=ax, show=False) # plots the equilibrium
ax.plot(tokamak.limiter.R, tokamak.limiter.Z, "k-", linewidth=1.2) # plots the limiter
ax.plot(efit_lcfs[:, 0], efit_lcfs[:, 1], "m--", linewidth=1.5, label="EFIT LCFS")
ax.plot(efit_xpoints[:, 0], efit_xpoints[:, 1], "mx", markersize=10, label="EFIT X-points")
ax.legend(loc="upper right")
ax.set_xlim(0.0, 2.15)
ax.set_ylim(-2.6, 2.6)
ax.set_xlabel(r"Major radius, $R$ [m]")
ax.set_ylabel(r"Height, $Z$ [m]")
Text(0, 0.5, 'Height, $Z$ [m]')
from scipy.spatial.distance import cdist
# --- Extract FreeGSNKE and EFIT quantities ---
fg_sep = eq.separatrix(ntheta=360)
efit_axis = np.array(efit["axis"])
# Match EFIT X-points to the nearest FreeGSNKE X-points
fg_xpt_low = eq.xpt[np.argmin(np.linalg.norm(eq.xpt[:, :2] - efit_xpoints[0], axis=1)), :2]
fg_xpt_up = eq.xpt[np.argmin(np.linalg.norm(eq.xpt[:, :2] - efit_xpoints[1], axis=1)), :2]
# Geometric & shaping parameters from EFIT LCFS
Rmin_e, Rmax_e = efit_lcfs[:, 0].min(), efit_lcfs[:, 0].max()
Zmin_e, Zmax_e = efit_lcfs[:, 1].min(), efit_lcfs[:, 1].max()
Rgeo_e = 0.5 * (Rmax_e + Rmin_e)
Zgeo_e = 0.5 * (Zmax_e + Zmin_e)
a_e = 0.5 * (Rmax_e - Rmin_e)
A_e = Rgeo_e / a_e
kappa_e = (Zmax_e - Zmin_e) / (Rmax_e - Rmin_e)
delta_u_e = (Rgeo_e - efit_lcfs[np.argmax(efit_lcfs[:, 1]), 0]) / a_e
delta_l_e = (Rgeo_e - efit_lcfs[np.argmin(efit_lcfs[:, 1]), 0]) / a_e
# Cross-sectional area of EFIT LCFS (shoelace formula)
efit_area = 0.5 * np.abs(
np.dot(efit_lcfs[:, 0], np.roll(efit_lcfs[:, 1], -1))
- np.dot(efit_lcfs[:, 1], np.roll(efit_lcfs[:, 0], -1))
)
# Nearest-point distances between FreeGSNKE separatrix and EFIT LCFS
dist_matrix = cdist(fg_sep, efit_lcfs)
d_fg_to_efit = dist_matrix.min(axis=1)
d_efit_to_fg = dist_matrix.min(axis=0)
hausdorff_dist = max(d_fg_to_efit.max(), d_efit_to_fg.max())
# --- Print summary comparison table ---
print("=" * 74)
print(f"FreeGSNKE vs EFIT Comparison (MAST shot {efit['shot']}, t = {efit['time']:.2f} s)")
print("=" * 74)
print(f"{'Quantity':<28} {'FreeGSNKE':>14} {'EFIT':>14} {'Diff':>14}")
print("-" * 74)
print(f"{'Plasma current Ip [kA]':<28} {eq.plasmaCurrent()*1e-3:>14.2f} {efit['Ip']*1e-3:>14.2f} {(eq.plasmaCurrent() - efit['Ip'])*1e-3:>+14.2f}")
print(f"{'R_axis [m]':<28} {eq.opt[0, 0]:>14.4f} {efit_axis[0]:>14.4f} {eq.opt[0, 0] - efit_axis[0]:>+14.4f}")
print(f"{'Z_axis [m]':<28} {eq.opt[0, 1]:>14.4f} {efit_axis[1]:>14.4f} {eq.opt[0, 1] - efit_axis[1]:>+14.4f}")
print(f"{'R_X,low [m]':<28} {fg_xpt_low[0]:>14.4f} {efit_xpoints[0, 0]:>14.4f} {fg_xpt_low[0] - efit_xpoints[0, 0]:>+14.4f}")
print(f"{'Z_X,low [m]':<28} {fg_xpt_low[1]:>14.4f} {efit_xpoints[0, 1]:>14.4f} {fg_xpt_low[1] - efit_xpoints[0, 1]:>+14.4f}")
print(f"{'R_X,up [m]':<28} {fg_xpt_up[0]:>14.4f} {efit_xpoints[1, 0]:>14.4f} {fg_xpt_up[0] - efit_xpoints[1, 0]:>+14.4f}")
print(f"{'Z_X,up [m]':<28} {fg_xpt_up[1]:>14.4f} {efit_xpoints[1, 1]:>14.4f} {fg_xpt_up[1] - efit_xpoints[1, 1]:>+14.4f}")
print(f"{'R_geo [m]':<28} {eq.Rgeometric():>14.4f} {Rgeo_e:>14.4f} {eq.Rgeometric() - Rgeo_e:>+14.4f}")
print(f"{'Z_geo [m]':<28} {eq.Zgeometric():>14.4f} {Zgeo_e:>14.4f} {eq.Zgeometric() - Zgeo_e:>+14.4f}")
print(f"{'Minor radius a [m]':<28} {eq.minorRadius():>14.4f} {a_e:>14.4f} {eq.minorRadius() - a_e:>+14.4f}")
print(f"{'Aspect ratio A':<28} {eq.aspectRatio():>14.4f} {A_e:>14.4f} {eq.aspectRatio() - A_e:>+14.4f}")
print(f"{'Elongation kappa':<28} {eq.geometricElongation():>14.4f} {kappa_e:>14.4f} {eq.geometricElongation() - kappa_e:>+14.4f}")
print(f"{'Upper triangularity delta_u':<28} {eq.triangularity_upper():>14.4f} {delta_u_e:>14.4f} {eq.triangularity_upper() - delta_u_e:>+14.4f}")
print(f"{'Lower triangularity delta_l':<28} {eq.triangularity_lower():>14.4f} {delta_l_e:>14.4f} {eq.triangularity_lower() - delta_l_e:>+14.4f}")
print(f"{'Separatrix area [m^2]':<28} {eq.separatrix_area():>14.4f} {efit_area:>14.4f} {eq.separatrix_area() - efit_area:>+14.4f}")
print("-" * 74)
print(f"Magnetic axis separation : {np.linalg.norm(eq.opt[0, :2] - efit_axis)*1e3:.2f} mm")
print(f"Lower X-point separation : {np.linalg.norm(fg_xpt_low - efit_xpoints[0])*1e3:.2f} mm")
print(f"Upper X-point separation : {np.linalg.norm(fg_xpt_up - efit_xpoints[1])*1e3:.2f} mm")
print(f"LCFS distance (FG -> EFIT) : mean = {d_fg_to_efit.mean()*1e3:.2f} mm, RMS = {np.sqrt(np.mean(d_fg_to_efit**2))*1e3:.2f} mm, max = {d_fg_to_efit.max()*1e3:.2f} mm")
print(f"LCFS Hausdorff distance : {hausdorff_dist*1e3:.2f} mm")
print(f"FreeGSNKE derived metrics : beta_p = {eq.poloidalBeta():.3f}, li(1) = {eq.internalInductance1():.3f}, V_p = {eq.plasmaVolume():.3f} m^3")
print("=" * 74)
==========================================================================
FreeGSNKE vs EFIT Comparison (MAST shot 30421, t = 0.25 s)
==========================================================================
Quantity FreeGSNKE EFIT Diff
--------------------------------------------------------------------------
Plasma current Ip [kA] 640.84 640.84 +0.00
R_axis [m] 0.9590 0.9655 -0.0064
Z_axis [m] -0.1871 -0.2164 +0.0293
R_X,low [m] 0.5701 0.5830 -0.0129
Z_X,low [m] -1.2311 -1.2558 +0.0247
R_X,up [m] 0.3515 0.3315 +0.0200
Z_X,up [m] 0.9582 0.9414 +0.0168
R_geo [m] 0.8582 0.8672 -0.0090
Z_geo [m] -0.3219 -0.3591 +0.0372
Minor radius a [m] 0.5873 0.5819 +0.0054
Aspect ratio A 1.4611 1.4902 -0.0291
Elongation kappa 1.5383 1.5408 -0.0025
Upper triangularity delta_u 0.2536 0.2411 +0.0124
Lower triangularity delta_l 0.4717 0.4884 -0.0167
Separatrix area [m^2] 1.4985 1.4694 +0.0291
--------------------------------------------------------------------------
Magnetic axis separation : 29.97 mm
Lower X-point separation : 27.83 mm
Upper X-point separation : 26.12 mm
LCFS distance (FG -> EFIT) : mean = 23.51 mm, RMS = 25.78 mm, max = 51.02 mm
LCFS Hausdorff distance : 85.73 mm
FreeGSNKE derived metrics : beta_p = 0.435, li(1) = 1.115, V_p = 7.555 m^3
==========================================================================