The Open FUSION Toolkit 26.9
An open-source framework for fusion and plasma science and engineering
Loading...
Searching...
No Matches
TokaMaker Example: Baseline flattop scenario for MANTA

In this example we show how to recompute the baseline flattop operating point for the MANTA device based on an gEQDSK file.

This example utilizes the mesh built in TokaMaker Meshing Example: Building a mesh for MANTA.

Note
Running this example requires the h5py python package, which is installable using pip or other standard methods.
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

Setup Device

Initialize TokaMaker object

First we create a TokaMaker instance to use for equilibrium calculations. Note at present only a single 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)
#----------------------------------------------
             ____  ____________
            / __ \/ ____/_  __/
           / / / / /_    / /
          / /_/ / __/   / /
          \____/_/     /_/

Base release:        v1.0.0-beta7
Development branch:  release_26_06
Revision id:         978c4b9f

Parallelization Info:
  Not compiled with MPI
  # of OpenMP threads =    2

Linear Algebra backend: native

#----------------------------------------------

Read equilibrium from gEQDSK file

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

  • gEQDSK_in['rcentr']: The R coordinate of the machine reference point (usually geometric center)
  • gEQDSK_in['bcentr']: The magnetic field at the machine reference point (usually geometric center)
  • gEQDSK_in['ip']: Total plasma current
  • gEQDSK_in['pres']: \(P(\psi)\) profile
  • gEQDSK_in['pprime']: \(dP/d\psi\) profile
  • gEQDSK_in['ffprim']: \(F dF'/d\psi\) profile
  • gEQDSK_in['rzout']: R,Z coordinates of the last closed flux surface
gEQDSK_in = read_eqdsk('MANTA_posCS_final')

Load mesh into TokaMaker

Now we load the mesh generated in doc_gs_mesh_ex2 using load_gs_mesh and setup_mesh. Then we use setup_regions 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('MANTA_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=gEQDSK_in['bcentr']*gEQDSK_in['rcentr'])
**** Loading OFT surface mesh

**** Generating surface grid level  1
  Generating boundary domain linkage
  Mesh statistics:
    Area         =  7.741E+01
    # of points  =    8001
    # of edges   =   23766
    # of cells   =   15766
    # of boundary points =     234
    # of boundary edges  =     234
    # of boundary cells  =     234
  Resolution statistics:
    hmin =  1.185E-02
    hrms =  1.130E-01
    hmax =  2.363E-01
  Surface grounded at vertex    1202


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

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

Plot input mesh

The input mesh can be plotted using plot_mesh to view the grid for each region type.

fig, ax = plt.subplots(2,2,figsize=(10,10))
mygs.plot_mesh(fig,ax)

Define hard limits on coil currents

Hard limits on coil currents can be set using set_coil_bounds. In this case we use the PF coil limits provided in the MANTA paper and simple and approximate bi-directional limit of 20 MA and 100 kA in each CS and VSC coil respectively.

coil_bounds = {
'PF1U': [-7.74E6,7.74E6],
'PF1L': [-7.74E6,7.74E6],
'PF2U': [-7.51E6,7.51E6],
'PF2L': [-7.51E6,7.51E6],
'PF3U': [-5.13E6,5.13E6],
'PF3L': [-5.13E6,5.13E6],
'CS1U': [-20.E6, 20.E6],
'CS1L': [-20.E6, 20.E6],
'CS2U': [-20.E6, 20.E6],
'CS2L': [-20.E6, 20.E6],
'VSC': [-100.E3, 100.E3]
}
mygs.set_coil_bounds(coil_bounds)

Re-solve 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.
Ip_target=gEQDSK_in['ip']
P0_target=gEQDSK_in['pres'][0]
mygs.set_targets(Ip=Ip_target, pax=P0_target)

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 define isoflux constraints to match the LCFS of the input gEQDSK file as well as hardcoded X-point locations that are used both for the isoflux and saddle constraints. For double null equilibria it is often useful to provide additional constraint of the up-down symmetry of the flux surfaces. To do this we repeat the isoflux points twice, using the inner most isoflux point as the reference location for the first set and the vertical mirror of each point for the second set with a higher weight. This adds additional weight to the up-down symmetry of the equilibrium.

x_points = np.array([
[5.15369, 1.69138],
[5.15369, -1.67138]
])
# Set isoflux target points for LCFS contour and X-points
lcfs_contour = gEQDSK_in['rzout'][:-1,:][::20]
isoflux_points = np.vstack((lcfs_contour,x_points))
isoflux_points = np.vstack((isoflux_points,isoflux_points)) # Repeat list of points twice to be used with different references
# Use outermost point (hopefully near midplane) as reference point for first half
ref_points = isoflux_points.copy()
iref = ref_points[:isoflux_points.shape[0]//2,0].argmax()
ref_points[:isoflux_points.shape[0]//2,0] = ref_points[iref,0]
ref_points[:isoflux_points.shape[0]//2,1] = ref_points[iref,1]
# Use mirrored points as reference for second half
ref_points[isoflux_points.shape[0]//2:,1] *= -1
# Weight mirrored point part more to more strongly enforce up-down symmetry
weights = np.ones_like(ref_points[:,0])
weights[isoflux_points.shape[0]//2:] = 10.0
mygs.set_isoflux_constraints(isoflux_points,ref_points=ref_points,weights=weights)
mygs.set_saddle_constraints(x_points)

Define coil regularization matrix

In general, for a given coil set a given plasma shape cannot be exactly reproduced, which generally yields large amplitude coil currents if no constraint on the coil currents is applied. As a result, it is useful to include regularization terms for the coils to balance minimization of the shape error with the amplitude of current in the coils. In TokaMaker, these regularization terms have the general form, where each term corresponds to a set of coil coefficients, target value, and weight. The coil_reg_term() method is provided to aid in defining these terms.

In this case, one regularization term is added for each upper coil with a single unit coefficient for that coil and target of zero with modest weights. This regularization acts to penalize the amplitude of current in each coil, acting to balance coil current with error in the shape targets. We also add a regularization term to regularize the matching upper and lower coils to have the same current to support the up-down symmetry as above.

Note
While it may appear that one can very strongly enforce up-down symmetry in the coils to ensure an up-down symmetric equilibrium this does not work due to numerical vertical instability in the solver, for equilibria with physical vertical instability, that requires some up-down flexibility in the coil currents.
# Set regularization weights
regularization_terms = []
for name, coil in mygs.coil_sets.items():
if name.endswith('L'):
continue
if name.startswith('CS'):
regularization_terms.append(mygs.coil_reg_term({name: 1.0},target=0.0,weight=2.E0))
elif name.startswith('VS'):
regularization_terms.append(mygs.coil_reg_term({name: 1.0},target=0.0,weight=1.E0))
continue
else:
regularization_terms.append(mygs.coil_reg_term({name: 1.0},target=0.0,weight=1.E-2))
# Vertical symmetry regularization
regularization_terms.append(mygs.coil_reg_term({name: 1.0, name[:-1] + 'L': -1.0},target=0.0,weight=1.E1))
# Pass regularization terms to TokaMaker
mygs.set_coil_reg(reg_terms=regularization_terms)

Define flux functions

Here we simply use the profiles obtained through transport analysis in the original MANTA paper.

n_sample = 40
psi_sample = np.linspace(0.0025,1.0,n_sample)
psi_eqdsk = np.linspace(0.0,1.0,gEQDSK_in['nr'])
psi_prof = psi_sample.copy(); psi_prof[0]=0.0 # Extend profile to core
# Set F*F' profile
ffp_prof = {
'type': 'linterp',
'x': psi_prof,
'y': np.interp(psi_sample,psi_eqdsk,gEQDSK_in['ffprim'])
}
ffp_prof['y'] /= ffp_prof['y'][0] # Normalize profile (not required but convienient)
# Set P' profile
pp_prof = {
'type': 'linterp',
'x': psi_prof,
'y': np.interp(psi_sample,psi_eqdsk,gEQDSK_in['ffprim'])
}
pp_prof['y'] /= pp_prof['y'][0] # Normalize profile (not required but convienient)
fig, ax = plt.subplots(2,1,sharex=True)
ax[0].plot(ffp_prof['x'],ffp_prof['y'],'+-')
ax[0].set_ylabel("FF'")
ax[1].plot(pp_prof['x'],pp_prof['y'],'+-')
ax[1].set_ylabel("P'")
_ = ax[-1].set_xlabel(r"$\hat{\psi}$")
mygs.set_profiles(ffp_prof=ffp_prof,pp_prof=pp_prof)

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 when no arguments are specified. For close-fitting limiters like MANTA this is often sufficient. 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).

mygs.init_psi()
EQ_out = mygs.solve()
Starting non-linear GS solver
     1 -1.2117E+00  1.2674E+00  8.9554E-02  4.7708E+00  1.4364E-05 -0.0000E+00
     2  2.6593E+01  7.5258E-01  1.6930E-02  4.7609E+00 -1.8012E-05 -0.0000E+00
     3  3.0345E+01  6.9850E-01  7.3870E-03  4.7526E+00 -7.0188E-05 -0.0000E+00
     4  3.1181E+01  6.8886E-01  3.8095E-03  4.7469E+00 -2.8730E-05 -0.0000E+00
     5  3.1386E+01  6.8711E-01  2.0031E-03  4.7434E+00  2.0449E-06 -0.0000E+00
     6  3.1437E+01  6.8689E-01  1.0217E-03  4.7414E+00  2.3187E-05 -0.0000E+00
     7  3.1450E+01  6.8685E-01  6.2153E-04  4.7402E+00  3.4250E-05 -0.0000E+00
     8  3.1449E+01  6.8682E-01  3.9401E-04  4.7396E+00  4.0717E-05 -0.0000E+00
     9  3.1449E+01  6.8688E-01  6.7035E-04  4.7392E+00  4.5582E-05 -0.0000E+00
    10  3.1446E+01  6.8686E-01  3.7427E-04  4.7390E+00  4.8017E-05 -0.0000E+00
    11  3.1447E+01  6.8687E-01  2.9795E-04  4.7389E+00  5.2031E-05 -0.0000E+00
    12  3.1445E+01  6.8684E-01  2.5925E-04  4.7389E+00  5.5609E-05 -0.0000E+00
    13  3.1443E+01  6.8685E-01  5.6180E-05  4.7388E+00  5.8270E-05 -0.0000E+00
    14  3.1442E+01  6.8686E-01  1.3056E-05  4.7388E+00  6.0132E-05 -0.0000E+00
    15  3.1441E+01  6.8686E-01  3.8974E-06  4.7388E+00  6.1387E-05 -0.0000E+00
    16  3.1441E+01  6.8686E-01  1.6119E-06  4.7388E+00  6.2212E-05 -0.0000E+00
    17  3.1441E+01  6.8687E-01  7.9745E-07  4.7388E+00  6.2749E-05 -0.0000E+00
 Timing:  0.14703700004611164     
   Source:     5.3658000193536282E-002
   Solve:      4.8613000137265772E-002
   Boundary:   3.6259998450987041E-003
   Other:      4.1139999870210886E-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,xpoint_color=None,vacuum_nlevels=4,plasma_nlevels=10)
ax.plot(gEQDSK_in['rzout'][:,0], gEQDSK_in['rzout'][:,1], color='r', linestyle='--', label='Target LCFS')
ax.set_xlabel('$R$ [m]')
ax.set_ylabel('$Z$ [m]')
_ = ax.legend()

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, which are all within the approximate coil limits imposed above.

mygs.print_info()
print()
print("Coil Currents:")
coil_currents, currents_reg = mygs.get_coil_currents()
total_pf_current = 0.0
for name in mygs.coil_sets:
if name.startswith("PF"):
total_pf_current += abs(coil_currents[name])
if name.startswith("VSC"):
print(' {0:10} {1:6.2F} [kA]'.format(name+":",coil_currents[name]/1.E3))
else:
print(' {0:10} {1:6.2F} [MA]'.format(name+":",coil_currents[name]/1.E6))
print()
print("Total PF current: {0:6.2F} [MA]".format(total_pf_current/1.E6))
Equilibrium Statistics:
  Topology                =   Diverted
  Toroidal Current [A]    =    1.0000E+07
  Current Centroid [m]    =    4.678 -0.000
  Magnetic Axis [m]       =    4.739  0.000
  Elongation              =    1.459 (U:  1.445, L:  1.472)
  Triangularity           =   -0.531 (U: -0.518, L: -0.543)
  Plasma Volume [m^3]     =   150.446
  q_0, q_95               =    0.699  2.372
  Plasma Pressure [Pa]    =   Axis:  1.6355E+06, Peak:  1.6355E+06
  Stored Energy [J]       =    9.7480E+07
  <Beta_pol> [%]          =   53.7740
  <Beta_tor> [%]          =    0.8865
  <Beta_n>   [%]          =    1.1525
  Diamagnetic flux [Wb]   =    2.6897E-01
  Toroidal flux [Wb]      =    5.6704E+01
  l_i                     =    0.9488

Coil Currents:
  PF1U:       -6.57 [MA]
  PF2U:        5.83 [MA]
  PF3U:       -4.40 [MA]
  PF1L:       -6.57 [MA]
  PF2L:        5.83 [MA]
  PF3L:       -4.40 [MA]
  CS2L:        0.00 [MA]
  CS1L:       -0.00 [MA]
  CS1U:       -0.00 [MA]
  CS2U:        0.00 [MA]
  VSC:        -1.19 [kA]

Total PF current:  33.60 [MA]

Save equilibrium as a gEQDSK file

We save our TokaMaker equilibrium as a gEQDSK file using the save_eqdsk() method. We modify the resolution of the equilibrium file by increasing the nr and nz parameters and decreasing the padding on the last closed flux surface (lcfs_pad).

EQ_out.save_eqdsk('gMANTA_tkmkr',nr=150,nz=150,lcfs_pad=1.E-3)
Saving gEQDSK: gMANTA_tkmkr