The Open FUSION Toolkit 26.9
An open-source framework for fusion and plasma science and engineering
Loading...
Searching...
No Matches
TokaMaker Example: Equilibrium reconstruction for ARC V3A

This is based on the ARC V3A digital assets as described in Appendix A of Hillesheim et al, "Overview of the physics basis for the ARC fusion power plant" Journal of Plasma Physics (2026). https://doi.org/10.1017/S0022377826101706

All files available on Zenodo at: https://zenodo.org/records/19498373

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize']=(6,6)
plt.rcParams['font.weight']='bold'
plt.rcParams['axes.labelweight']='bold'
plt.rcParams['lines.linewidth']=2
plt.rcParams['lines.markeredgewidth']=2
%matplotlib inline
%config InlineBackend.figure_format = "retina"

Load TokaMaker library

To load the TokaMaker python module we need to tell python where to the module is located. This can be done either through the PYTHONPATH environment variable or using within a script using sys.path.append() as below, where we look for the environement variable OFT_ROOTPATH to provide the path to where the OpenFUSIONToolkit is installed (/Applications/OFT on macOS).

tokamaker_python_path = os.getenv('OFT_ROOTPATH')
if tokamaker_python_path is not None:
sys.path.append(os.path.join(tokamaker_python_path,'python'))
from OpenFUSIONToolkit import OFT_env
from OpenFUSIONToolkit.TokaMaker import TokaMaker
from OpenFUSIONToolkit.TokaMaker.meshing import load_gs_mesh
from OpenFUSIONToolkit.TokaMaker.util import create_isoflux, read_eqdsk
TokaMaker utilities for mesh generation and manipulation.
Definition meshing.py:1
General utility and supporting functions for TokaMaker.
Definition util.py:1
Python interface for TokaMaker Grad-Shafranov functionality.
Definition __init__.py:1

Read equilibrium from gEQDSK file

A dictionary containing the equilibrium information is obtained using read_eqdsk(). The dictionary contains multiple key quantities useful for reproducing the equilibrium in TokaMaker:

  • eqdsk['rcentr']: R coordinate of the plasma center
  • eqdsk['bcentr']: magnetic field at the plasma center
  • eqdsk['ip']: total plasma current
  • eqdsk['pres']: pressure profile
  • eqdsk['pprime']: P' profile
  • eqdsk['ffprim']: F*F' profile
  • eqdsk['rzout']: RZ coordinates of the last closed flux surface

The ARC gEQDSK is sourced from Zenodo and downloaded automatically below if not already present locally.

import urllib.request
_ZENODO = 'https://zenodo.org/records/19498373/files'
def _fetch(filename):
if not os.path.exists(filename):
print(f'Downloading {filename} from Zenodo...', end=' ', flush=True)
urllib.request.urlretrieve(f'{_ZENODO}/{filename}?download=1', filename)
print('done.')
_fetch('geqdsk-ARCv3a')
eqdsk = read_eqdsk('geqdsk-ARCv3a')
Downloading geqdsk-ARCv3a from Zenodo... done.

Compute equilibria

Initialize TokaMaker object

We now create a OFT_env instance for execution using two threads and a TokaMaker instance to use for equilibrium calculations. Note at present only a single TokaMaker instance can be used per python kernel, so this command should only be called once in a given Jupyter notebook or python script. In the future this restriction may be relaxed.

myOFT = OFT_env(nthreads=2)
mygs = TokaMaker(myOFT)
#----------------------------------------------
Open FUSION Toolkit Initialized
Development branch:    arc_v3a
Revision id:           04589ca
Parallelization Info:
  Not compiled with MPI
  # of OpenMP threads =    2
Integer Precisions    =    4   8
Float Precisions      =    4   8  16
Complex Precisions    =    4   8
LA backend            = native
#----------------------------------------------

Update default settings

Sometimes it is useful to modify the default TokaMaker settings. Here we update one setting to help with convergence:

  • mygs.settings.maxits: This sets the maximum non-linear iteration count for G-S solver, and should often be increased from the default setting of 40 iterations.

Settings can be modified before running setup() or at any time during execution by adjusting desired values and then calling update_settings().

mygs.settings.maxits = 200

Load mesh into TokaMaker

Now we load the mesh generated in TokaMaker Meshing Example: Building a mesh for ARC V3A using load_gs_mesh() and setup_mesh. Then we use setup_regions(), passing the conductor and coil dictionaries for the mesh, to define the different region types. Finally, we call setup() to setup the required solver objects. During this call we can specify the desired element order (min=2, max=4) and the toroidal field through F0 = B0*R0, where B0 is the toroidal field at a reference location R0.

mesh_pts,mesh_lc,mesh_reg,coil_dict,cond_dict = load_gs_mesh('arc_v3a_mesh.h5')
mygs.setup_mesh(mesh_pts, mesh_lc, mesh_reg)
mygs.setup_regions(cond_dict=cond_dict,coil_dict=coil_dict)
mygs.setup(order=2,F0=eqdsk['rcentr']*eqdsk['bcentr'])
**** Loading OFT surface mesh

**** Generating surface grid level  1
  Generating boundary domain linkage
  Mesh statistics:
    Area         =  1.060E+02
    # of points  =    9281
    # of edges   =   27632
    # of cells   =   18352
    # of boundary points =     208
    # of boundary edges  =     208
    # of boundary cells  =     208
  Resolution statistics:
    hmin =  1.000E-02
    hrms =  1.236E-01
    hmax =  3.005E-01
  Surface grounded at vertex    2770


**** Creating Lagrange FE space
  Order  =    2
  Minlev =   -1

 Computing flux BC matrix 
 Inverting real matrix
   Time =    6.0089999999999996E-003

Define a vertical stability coil

Like many elongated equilibria, the equilibrium we seek to compute below is vertically unstable. In this case we use the outermost pair of poloidal field coils for vertical stability in order to help with convergence using the set_coil_vsc() method.

mygs.set_coil_vsc({'PF5U': 1.0, 'PF5L': -1.0})

Compute Inverse Equilibrium

Define global quantities and targets

For the inverse case we define a target for the plasma current and the peak plasma pressure, which occurs on the magnetic axis.

Note
These constraints can be considered "hard" constraints, where they will be matched to good tolerance as long as the calculation converges.
mygs.set_targets(Ip = abs(eqdsk['ip']), pax=eqdsk['pres'][0])

Define shape targets

In order to constrain the shape of the plasma we can utilize two types of constraints:

  1. isoflux points, which are points we want to lie on the same flux surface (eg. the LCFS)
  2. saddle points, where we want the poloidal magnetic field to vanish (eg. X-points).
Note
These constraints can be considered "soft" constraints, where the calculation attempts to minimize error in satisfying these constraints subject to other constraints and regularization.

Here we use the contour defining the last closed flux surface as our isoflux constraint, and do not set any saddle targets.

isoflux_pts = eqdsk['rzout'].copy()
mygs.set_isoflux_constraints(isoflux_pts)

Define coil regularization matrix

coil_names = list(mygs.coil_sets)
target_currents = {}
for name in coil_names:
target_currents[name] = 0
# Set regularization weights
regularization_terms = []
for name, target_current in target_currents.items():
# Set specific target currents from input equilibrium and different weights depending on the coil set
if name.startswith('ECOIL'):
regularization_terms.append(mygs.coil_reg_term({name: 1.0},target=target_current,weight=1.E-2))
elif name.startswith('F'):
if name.startswith('F5'):
regularization_terms.append(mygs.coil_reg_term({name: 1.0},target=target_current,weight=1.E2))
else:
regularization_terms.append(mygs.coil_reg_term({name: 1.0},target=target_current,weight=1.E0))
# Set zero target current and small weight on virtual VSC to allow up-down adjustment
regularization_terms.append(mygs.coil_reg_term({'#VSC': 1.0},target=0.0,weight=1.E-2))
# Pass regularization terms to TokaMaker
mygs.set_coil_reg(reg_terms=regularization_terms)

Define flux functions

Although TokaMaker has a "default" profile for the F*F' and P' terms this should almost never be used and one should instead choose an appropriate flux function for their application. In this case we use the P' and F*F' profiles directly from the gEQDSK we are working to reproduce.

ffprim = eqdsk['ffprim']
pprime = eqdsk['pprime']
psi_eqdsk = np.linspace(0.0,1.0,np.size(ffprim))
psi_sample = np.linspace(0.0,1.0,50)
psi_prof = np.copy(psi_sample)
ffp_prof = np.transpose(np.vstack((psi_prof,np.interp(psi_sample,psi_eqdsk,ffprim)))).copy()
pp_prof = np.transpose(np.vstack((psi_prof,np.interp(psi_sample,psi_eqdsk,pprime)))).copy()
mygs.set_profiles(ffp_prof={'type': 'linterp', 'y': ffp_prof[:,1], 'x': psi_sample},pp_prof={'type': 'linterp', 'y': pp_prof[:,1], 'x': psi_sample})

Compute equilibrium

We can now compute a free-boundary equilibrium using these constraints. Note that before running a calculation for the first time we must initialize the flux function \(\psi\), which can be done using init_psi(). This subroutine initializes the flux using the specified Ip_target from above, which is evenly distributed over the entire plasma region or only with a boundary defined using a center point (R,Z), minor radius (a), and elongation and triangularity. Coil currents are also initialized at this point using the constraints above and this uniform plasma current initialization.

solve() is then called to compute a self-consitent Grad-Shafranov equilibrium. If the result variable (err_flag) is zero then the solution has converged to the desired tolerance ( \(10^{-6}\) by default).

R0 = 3.7
Z0 = 0.0
a = 1.0
kappa = 1.8
delta = 0.6
mygs.init_psi(R0, Z0, a, kappa, delta)
_ = mygs.solve()
Starting non-linear GS solver
     1 -7.8405E-02 -1.8456E-06  1.3172E+01  4.5199E+00 -6.0737E-05  4.6313E-01
     2 -1.2450E+00 -1.4088E-06  6.5348E+00  4.6202E+00 -1.0823E-03  1.0411E-01
     3 -1.5817E+00 -1.3126E-06  3.3361E+00  4.6659E+00 -5.1629E-04  1.4231E-01
     4 -1.7322E+00 -1.2813E-06  1.6938E+00  4.6864E+00 -2.5360E-04  1.6578E-01
     5 -1.8093E+00 -1.2685E-06  8.6285E-01  4.6957E+00 -1.2505E-04  5.7803E-02
     6 -1.8510E+00 -1.2624E-06  4.3967E-01  4.6999E+00 -6.0630E-05  1.3214E-01
     7 -1.8746E+00 -1.2595E-06  2.2517E-01  4.7018E+00 -2.7571E-05  1.2943E-01
     8 -1.8883E+00 -1.2578E-06  1.1525E-01  4.7026E+00 -9.8268E-06  9.3758E-02
     9 -1.8959E+00 -1.2568E-06  5.8724E-02  4.7030E+00 -1.8454E-07  7.2300E-02
    10 -1.9000E+00 -1.2563E-06  2.9759E-02  4.7032E+00  5.2268E-06  1.3333E-01
    11 -1.9022E+00 -1.2560E-06  1.4973E-02  4.7032E+00  8.2234E-06  1.4071E-01
    12 -1.9034E+00 -1.2558E-06  7.4940E-03  4.7033E+00  1.0150E-05  2.7377E-02
    13 -1.9040E+00 -1.2558E-06  3.7072E-03  4.7033E+00  1.1323E-05  2.0171E-01
    14 -1.9043E+00 -1.2557E-06  1.8186E-03  4.7033E+00  1.2003E-05  1.3826E-01
    15 -1.9044E+00 -1.2557E-06  8.8342E-04  4.7033E+00  1.2387E-05  1.1598E-01
    16 -1.9045E+00 -1.2557E-06  4.2554E-04  4.7033E+00  1.2636E-05  1.7556E-02
    17 -1.9046E+00 -1.2557E-06  2.0338E-04  4.7033E+00  1.2838E-05  1.9519E-01
    18 -1.9046E+00 -1.2557E-06  9.5360E-05  4.7033E+00  1.2955E-05  5.1097E-02
    19 -1.9046E+00 -1.2557E-06  4.5538E-05  4.7033E+00  1.3022E-05  1.6222E-01
    20 -1.9046E+00 -1.2557E-06  2.0036E-05  4.7033E+00  1.2991E-05  1.2499E-01
    21 -1.9046E+00 -1.2557E-06  7.9677E-06  4.7033E+00  1.3017E-05  1.0073E-01
    22 -1.9046E+00 -1.2557E-06  4.6999E-06  4.7033E+00  1.2975E-05  1.8938E-01
    23 -1.9046E+00 -1.2557E-06  2.1121E-06  4.7033E+00  1.2939E-05  1.3223E-01
    24 -1.9046E+00 -1.2557E-06  9.5317E-07  4.7033E+00  1.2910E-05  1.5097E-01
 Timing:  0.17632499989122152     
   Source:     3.7091000005602837E-002
   Solve:      6.5606000367552042E-002
   Boundary:   7.5199995189905167E-003
   Other:      6.6107999999076128E-002

Plot equilibrium

Flux surfaces of the computed equilibrium can be plotted using the plot_psi() method. The additional plotting methods plot_machine() and plot_constraints() are also used to show context and other information. Each method has a large number of optional arguments for formatting and other options.

fig, ax = plt.subplots(1,1)
mygs.plot_machine(fig,ax,coil_colormap='seismic',coil_symmap=True,coil_scale=1.E-6,coil_clabel=r'$I_C$ [MA]')
mygs.plot_psi(fig,ax,vacuum_nlevels=4)
_ = ax.plot(eqdsk['rzout'][:,0][::2], eqdsk['rzout'][:,1][::2],'r--')

Print equilibrium information and coil currents

Basic parameters can be displayed using the print_info() method. For access to these quantities as variables instead the get_stats() can be used.

The final coil currents can also be retrieved using the get_coil_currents() method. Here, we plot the deviation of the TokaMaker currents from the desired target currents set above.

mygs.print_info()
currents, _ = mygs.get_coil_currents()
err = []
keys = []
for key in currents:
if key.startswith('A') or key.startswith('B'):
continue
err.append(100*(target_currents[key]-currents[key])/max(1.E3,abs(target_currents[key])))
keys.append(key)
print(' {0:10} {1:10.2F} {2:10.2F} {3:10.2F}'.format(key+":",currents[key]/1.E3,target_currents[key]/1.E3,100*abs((target_currents[key]-currents[key]))/max(1.E3,abs(target_currents[key]))))
Equilibrium Statistics:
  Topology                =   Diverted
  Toroidal Current [A]    =    1.2000E+07
  Current Centroid [m]    =    4.617  0.000
  Magnetic Axis [m]       =    4.703  0.000
  Elongation              =    1.884 (U:  1.904, L:  1.864)
  Triangularity           =    0.595 (U:  0.606, L:  0.583)
  Plasma Volume [m^3]     =   196.109
  q_0, q_95               =   -0.885 -3.381
  Plasma Pressure [Pa]    =   Axis:  3.1984E+06, Peak:  3.1984E+06
  Stored Energy [J]       =    2.1071E+08
  <Beta_pol> [%]          =   90.2877
  <Beta_tor> [%]          =    1.3867
  <Beta_n>   [%]          =    1.5549
  Diamagnetic flux [Wb]   =   -2.0094E-01
  Toroidal flux [Wb]      =   -8.4118E+01
  l_i                     =    1.3666
  CS1U:          -20.37       0.00    2037.31
  CS1L:          -17.17       0.00    1717.46
  CS2U:           44.23       0.00    4422.94
  CS2L:           25.92       0.00    2592.12
  CS3U:           15.45       0.00    1544.79
  CS3L:           48.69       0.00    4868.80
  PF1U:           58.60       0.00    5860.32
  PF1L:           13.21       0.00    1320.86
  PF2U:           31.28       0.00    3127.55
  PF2L:           45.20       0.00    4520.09
  PF3U:           29.73       0.00    2973.38
  PF3L:           29.37       0.00    2936.87
  PF4U:          -34.48       0.00    3447.96
  PF4L:          -34.36       0.00    3436.29
  PF5U:          -12.40       0.00    1240.32
  PF5L:          -12.38       0.00    1238.33

Retrieve profile information

Here, we use get_profiles() and get_q()to obtain the profiles of our equilibrium and compare them to the profiles of the target gEQDSK.

psi,f,fp,p,pp = mygs.get_profiles()
psi_q,qvals, _,_,_,_ = mygs.get_q(psi_pad=0.01)
fig, ax = plt.subplots(3,1,sharex=True)
psi_eqdsk = np.linspace(0.0,1.0,eqdsk['nr'])
psi_sample = np.linspace(0.0,1.0,10)
# Plot F*F'
ax[0].plot(psi_eqdsk,-eqdsk['ffprim'],'+')
ax[0].plot(psi,f*fp)
ax[0].set_ylabel("FF'")
# Plot P'
ax[1].plot(psi_eqdsk,-eqdsk['pprime'],'+')
ax[1].plot(psi,pp)
ax[1].set_ylabel("P'")
# Plot q
ax[2].plot(psi_eqdsk,eqdsk['qpsi'],'+')
ax[2].plot(psi_q,abs(qvals))
ax[2].set_ylabel("q")
_ = ax[-1].set_xlabel(r"$\hat{\psi}$")