Example: High resolution static solves


This notebook showcases how to leverage several optional features of FreeGSNKE when carrying out static equilibrium solves on much larger computational grids (i.e. when high resolution is required).

The resolution of the grid is generally limited by two factors:

  1. the amount of memory demanded from the system (usually a hard limit).

  2. the execution time required for the calculation to compute (soft limit).

In the following, we will go through some of the following features that can address these issues, with some considerations the user may want to take into account before using them:

  • Multithreading in critical computations

    • Can substantially reduce execution time in static solves

    • May hamper performance if used on small grids

    • On personal computers performance may vary drastically due to other running processes

  • On-the-fly computation of the boundary Green’s function

    • Significantly reduces memory required, allowing to run larger systems

    • Noticeably increases execution time due to recalculation

    • Reduction in memory use can be tuned

    • Strongly discouraged for evolutive solves (see later examples)

  • Use of frequency-based DST solver

    • Faster than the default sparse LU solver

    • Uses less memory than the default sparse solver

    • Is less accurate (\(O(\delta^2)\)) than the default (\(O(\delta^4)\))

Import packages

import pickle
import matplotlib.pyplot as plt
import numpy as np
from time import perf_counter

Initialise the openSTEP machine

First, let’s initialise the openSTEP machine geometry (as in example07h).

from freegsnke import build_machine

# build the machine
tokamak = build_machine.tokamak(
    active_coils_path=f"../machine_configs/OpenSTEP/OpenSTEP_simple_active_coils.pickle",
    limiter_path=f"../machine_configs/OpenSTEP/OpenSTEP_simple_limiter.pickle",
    wall_path=f"../machine_configs/OpenSTEP/OpenSTEP_simple_limiter.pickle",
)

# plot the machine
fig1, ax1 = plt.subplots(1, 1, figsize=(3, 8), dpi=80)
ax1.grid(zorder=0, alpha=0.75)
ax1.set_aspect('equal')
tokamak.plot(axis=ax1,show=False)
ax1.fill(tokamak.wall.R, tokamak.wall.Z, color='k', linewidth=1.2, facecolor='w', zorder=0) 
ax1.set_xlabel("Major radius [m]")
ax1.set_ylabel("Height [m]")
plt.show()
Active coils --> built from pickle file.
Passive structures --> none provided.
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.
../_images/b06e00ea1f0216c1b798a320bcb4f6e4b74c5fc7173240c540b924f2d6976dd1.png

Initialise profiles and eq objects

Let’s start by initialising the usual objects on a “small” computational grid - later we will show this is not enough to resolve the STEP equilibrium with its complex internal \(p'\) and \(FF'\) profiles.

# load the p' and FF' profile data from file
with open('../machine_configs/OpenSTEP/OpenSTEP_profiles.pickle', 'rb') as f:
    profiles_data = pickle.load(f)
from freegsnke import equilibrium_update
from freegsnke.jtor_update import GeneralPprimeFFprime
from freegsnke.equilibrium import PsiGuessParabolicJtor

# reference coil currents
currents = np.array([
    -4790870.39240653,
     5155466.64491291,
     2254704.04332795,
     5458947.31403196,
    -7854367.88994826,
     5100000.0,
    -2274646.53005716,
])

# initial plasma flux guess factory
parabolic_plasma_psi = PsiGuessParabolicJtor(
    Ip=2.2767e7,    # plasma current (to scale the guess)
    h=4.0,          # centre of ellipse (R)
    k=0.0,          # centre of ellipse (Z)
    a=1.0,          # approximate minor radius of the plasma
    b=5.0,          # approximate minor radius times elongation
    psi_scale=1.0,
)

# function for building the eq and profiles repeatedly
def setup_openstep(nx: int, ny: int):
    """Build an OpenSTEP Equilibrium and GeneralPprimeFFprime profile on an (nx, ny) grid."""
    eq = equilibrium_update.Equilibrium(
        tokamak=tokamak,
        Rmin=0.5,
        Rmax=9.0,
        Zmin=-10.0,
        Zmax=10.0,
        nx=nx,  # must be of the form 2**n + 1
        ny=ny,  # must be of the form 2**n + 1
    )
    profiles = GeneralPprimeFFprime(
        eq=eq,
        Ip=2.2767e7,
        fvac=0.5,
        psi_n=np.linspace(0, 1, 256),
        pprime_data=profiles_data['pprime'],
        ffprime_data=profiles_data['ffprime'],
    )
    eq.tokamak.set_all_coil_currents(currents)
    eq.plasma_psi = parabolic_plasma_psi(eq=eq)
    return eq, profiles

# initialise and build the plasma flux guess
eq, profiles = setup_openstep(nx=65, ny=129)
_plasma_psi = eq.plasma_psi.copy()

Solve equilibrium using defaults

We’ll first solve for the equilibrium using all of the default solver settings for comparison later on.

from freegsnke import GSstaticsolver

GSStaticSolver = GSstaticsolver.NKGSsolver(
    eq=eq,
    solver_type="LUsparse",
    gs_operator_order=4,
)
# solve
GSStaticSolver.solve(
    eq=eq,
    profiles=profiles,
    target_relative_tolerance=1e-10,
    force_up_down_symmetric=True,
    verbose=False,
)
Forward static solve SUCCESS. Tolerance 1.43e-11 (vs. requested 1.00e-10) reached in 36/100 iterations.

Store results and plot

# some array to store results
resolutions = []
psi_results = []
x_points = []
o_points = []
jtor_results = []

# save the results
resolutions.append((eq.nx,eq.ny))
psi_results.append(eq.psi())
x_points.append(profiles.xpt)
o_points.append(profiles.opt)
jtor_results.append(profiles.jtor)

# plot initial plasma flux guess
fig0, (ax01,ax02) = plt.subplots(1, 2, figsize=(8, 8), dpi=80)
ax01.grid(zorder=0, alpha=0.75)
ax01.set_aspect('equal')
eq.tokamak.plot(axis=ax01,show=False)
ax01.plot(tokamak.wall.R, tokamak.wall.Z, 'k')
ax01.contour(eq.R, eq.Z, _plasma_psi)
ax01.set_title("Initial plasma flux guess")

# plot the equilibrium
plt.ion()
ax02.grid(zorder=0, alpha=0.75)
ax02.set_aspect('equal')
eq.tokamak.plot(axis=ax02,show=False)                                                          # plots the active coils and passive structures
ax02.fill(tokamak.wall.R, tokamak.wall.Z, color='k', linewidth=1.2, facecolor='w', zorder=0)   # plots the limiter
eq.plot(axis=ax02,show=False)
ax02.set_title("Final (total) poloidal flux")
plt.tight_layout()
# plt.legend()
../_images/dfdfd085891fee77a9a16b48f80d4d51aaa7bf350ea16a311add8a649934a648.png

Benchmark 1: Setting the number of threads

We can use multithreading to solve on much larger grids.

This is useful when creating Equilibrium, NKGSsolver, or calling solve() with larger grids.

1. Default settings

When you import freegsnke, the defaults are:

  • FreeGSNKE’s internal parallel loops: 1 thread (serial).

  • NumPy / SciPy (linear algebra): uses your system’s OpenMP/BLAS default (typically all available CPU cores, unless OMP_NUM_THREADS is set).

# first inspect the current settings
from freegsnke import parallel

print("Current freegsnke threads:", parallel.get_num_threads())
Current freegsnke threads: 1

2. How to change them

Option A — Inside your Python script or notebook (most common):

Call parallel.set_num_threads(n) before creating Equilibrium, NKGSsolver, or calling solve():

from freegsnke import parallel
parallel.set_num_threads(4)  # use 4 threads for FreeGSNKE

(Alternatively, call parallel.set_max_threads() to set the maximum number of threads based on FreeGSNKE’s assessment of the physical resources available)

Option B — Before starting Python (for terminal / HPC runs):

Set OMP_NUM_THREADS before launching Python or Jupyter to control both FreeGSNKE and NumPy/SciPy together:

OMP_NUM_THREADS=4 python my_script.py

3. When should you change them?

Situation

What to do

Why

Normal / small grids (e.g. 65x65, 65x129)

Do nothing (leave at 1).

Starting extra threads adds overhead; on small grids, 1 thread is often faster.

Large grids on a laptop/workstation (e.g. 257x513 or cache_greens=False)

Call parallel.set_num_threads(n) with n up to your physical CPU core count (e.g. 4 or 8).

The grid calculations are large enough that multiple threads give a real speedup.

Running on an HPC cluster (e.g. SLURM)

Set OMP_NUM_THREADS=<allocated CPUs> before launching Python.

Prevents NumPy/SciPy and FreeGSNKE from trying to use more CPUs than your job was allocated.

In this experiment, we benchmark nt = [1, 2, 4, 8] threads on two grid resolutions (65x129 and 129x257) across three linear GS solver configurations: LUsparse (2nd order), LUsparse (4th order), and DST (2nd order).

Warning: The following cell is intentionally computationally expensive and may take several minutes to complete.

from freegsnke.parallel import set_num_threads

grids = [(65, 129), (129, 257)]
num_threads = [1, 2, 4, 8]
solvers = [
    ('LUsparse (2nd order)', 'LUsparse', 2),
    ('LUsparse (4th order)', 'LUsparse', 4),
    ('DST (2nd order)', 'DST', 2),
]

# store solver times: solve_times[(nx, ny)][label] = [t_nt1, t_nt2, ...]
solve_times = {grid: {label: [] for label, _, _ in solvers} for grid in grids}

for nx, ny in grids:
    print(f'=== Grid {nx}x{ny} ===')
    for label, solver_type, order in solvers:
        for nt in num_threads:
            # use 2 threads for equilibrium & coil Green's initialisation
            set_num_threads(2)
            eq, profiles = setup_openstep(nx=nx, ny=ny)

            # set requested thread count for solver initialisation and solve
            set_num_threads(nt)
            t1 = perf_counter()
            GSStaticSolver = GSstaticsolver.NKGSsolver(
                eq=eq,
                solver_type=solver_type,
                gs_operator_order=order,
                cache_greens=True,
            )
            GSStaticSolver.solve(
                eq=eq,
                profiles=profiles,
                target_relative_tolerance=1e-6,
                force_up_down_symmetric=True,
                verbose=False,
            )
            elapsed = perf_counter() - t1
            solve_times[(nx, ny)][label].append(elapsed)
            print(f'  {label:22s} | nt={nt} | {elapsed:.2f}s')

            if (nx, ny) == (129, 257) and label == 'LUsparse (4th order)' and nt == num_threads[-1]:
                resolutions.append((eq.nx, eq.ny))
                psi_results.append(eq.psi())
                x_points.append(profiles.xpt)
                o_points.append(profiles.opt)
                jtor_results.append(GSStaticSolver.jtor)

# reset to default thread count
set_num_threads(1)
=== Grid 65x129 ===
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  LUsparse (2nd order)   | nt=1 | 0.81s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  LUsparse (2nd order)   | nt=2 | 0.79s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  LUsparse (2nd order)   | nt=4 | 0.85s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  LUsparse (2nd order)   | nt=8 | 0.86s
Forward static solve SUCCESS. Tolerance 4.95e-07 (vs. requested 1.00e-06) reached in 31/100 iterations.
  LUsparse (4th order)   | nt=1 | 0.65s
Forward static solve SUCCESS. Tolerance 4.95e-07 (vs. requested 1.00e-06) reached in 31/100 iterations.
  LUsparse (4th order)   | nt=2 | 0.66s
Forward static solve SUCCESS. Tolerance 4.95e-07 (vs. requested 1.00e-06) reached in 31/100 iterations.
  LUsparse (4th order)   | nt=4 | 0.64s
Forward static solve SUCCESS. Tolerance 4.95e-07 (vs. requested 1.00e-06) reached in 31/100 iterations.
  LUsparse (4th order)   | nt=8 | 0.64s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  DST (2nd order)        | nt=1 | 0.95s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  DST (2nd order)        | nt=2 | 0.90s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  DST (2nd order)        | nt=4 | 0.92s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  DST (2nd order)        | nt=8 | 0.92s
=== Grid 129x257 ===
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  LUsparse (2nd order)   | nt=1 | 2.38s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  LUsparse (2nd order)   | nt=2 | 2.43s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  LUsparse (2nd order)   | nt=4 | 2.01s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  LUsparse (2nd order)   | nt=8 | 2.00s
Forward static solve SUCCESS. Tolerance 7.05e-07 (vs. requested 1.00e-06) reached in 22/100 iterations.
  LUsparse (4th order)   | nt=1 | 2.69s
Forward static solve SUCCESS. Tolerance 7.05e-07 (vs. requested 1.00e-06) reached in 22/100 iterations.
  LUsparse (4th order)   | nt=2 | 2.31s
Forward static solve SUCCESS. Tolerance 7.05e-07 (vs. requested 1.00e-06) reached in 22/100 iterations.
  LUsparse (4th order)   | nt=4 | 2.20s
Forward static solve SUCCESS. Tolerance 7.05e-07 (vs. requested 1.00e-06) reached in 22/100 iterations.
  LUsparse (4th order)   | nt=8 | 2.28s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  DST (2nd order)        | nt=1 | 1.94s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  DST (2nd order)        | nt=2 | 1.63s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  DST (2nd order)        | nt=4 | 1.62s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  DST (2nd order)        | nt=8 | 1.66s
fig, axes = plt.subplots(1, len(grids), figsize=(10, 4), dpi=100, sharey=False)

for ax, (nx, ny) in zip(axes, grids):
    for label, _, _ in solvers:
        ax.plot(num_threads, solve_times[(nx, ny)][label], marker='o', label=label)
    ax.set_title(f'Grid {nx}x{ny}')
    ax.set_xlabel('Number of threads (set_num_threads)')
    ax.set_ylabel('Solver init + solve time [s]')
    ax.set_xticks(num_threads)
    ax.grid(alpha=0.4)
    ax.legend()

plt.tight_layout()
../_images/35f47462063c8049953db70d8c62ef0f5b617a253e099bcd7e90912e22d8c55b.png

The results show:

  • Small grid (65x129): nt=1 is fastest (~0.7–1.0s). Increasing nt slightly slows the solve (~0.8–1.2s) because thread-management overhead outweighs the parallel work on small arrays.

  • Larger grid (129x257): Multithreading speeds up all three solvers when moving from nt=1 to nt=4–8 (roughly a 25–30% reduction in runtime), with diminishing returns beyond nt=4 as serial work and physical core count limit scaling.

  • Solver comparison: DST (2nd order) is faster than LUsparse (4th order) on the 129x257 grid and matches LUsparse (2nd order) iteration-for-iteration (23 iterations).

  • Determinism: For each solver and grid, the iteration count and final relative error are identical across all nt values.

It should be noted that the number of iterations above is consistent between runs: FreeGSNKE’s implementation of threading for static solves is fully deterministic: numerical results are exactly replicated independently of the number of threads.

The same is not true of the parallel backends used by numpy, so results will present differences if parallelism is varied with environment variables, but not if controlled with the freegsnke.parallel API.

Benchmark 2: Effect of on-the-fly Green’s functions

By default (cache_greens=True), NKGSsolver pre-computes and stores the boundary Green’s function matrix in RAM. On very fine grids this matrix can exceed available system memory. Setting cache_greens=False avoids storing it by recomputing the boundary flux on-the-fly at each iteration—reducing memory usage by up to an order of magnitude at the cost of extra computation (and making multithreading much more impactful). Because of this runtime cost, cache_greens=False should be avoided for evolutive solves.

Next, we repeat the thread sweep (nt = [1, 2, 4, 8]) on 65x129 and 129x257 using the DST solver with cache_greens=False, and compare the runtimes against the cache_greens=True results from Benchmark 1.

otf_times = {grid: [] for grid in grids}

for nx, ny in grids:
    print(f"=== Grid {nx}x{ny} (DST, cache_greens=False) ===")
    for nt in num_threads:
        set_num_threads(2)
        eq, profiles = setup_openstep(nx=nx, ny=ny)

        set_num_threads(nt)
        t1 = perf_counter()
        GSStaticSolver = GSstaticsolver.NKGSsolver(
            eq=eq,
            solver_type="DST",
            cache_greens=False,
        )
        GSStaticSolver.solve(
            eq=eq,
            profiles=profiles,
            target_relative_tolerance=1e-6,
            force_up_down_symmetric=True,
            verbose=False,
        )
        elapsed = perf_counter() - t1
        otf_times[(nx, ny)].append(elapsed)
        print(f"  nt={nt} | {elapsed:.2f}s")

set_num_threads(1)
=== Grid 65x129 (DST, cache_greens=False) ===
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  nt=1 | 12.25s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  nt=2 | 8.33s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  nt=4 | 8.44s
Forward static solve SUCCESS. Tolerance 1.46e-07 (vs. requested 1.00e-06) reached in 37/100 iterations.
  nt=8 | 9.63s
=== Grid 129x257 (DST, cache_greens=False) ===
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  nt=1 | 67.04s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  nt=2 | 62.16s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  nt=4 | 52.64s
Forward static solve SUCCESS. Tolerance 9.00e-07 (vs. requested 1.00e-06) reached in 23/100 iterations.
  nt=8 | 47.32s
fig, axes = plt.subplots(2, len(grids), figsize=(10, 7), dpi=100, sharex=True)

for col, (nx, ny) in enumerate(grids):
    t_cached = np.array(solve_times[(nx, ny)]["DST (2nd order)"])
    t_otf = np.array(otf_times[(nx, ny)])

    # Top row: raw runtime
    axes[0, col].plot(num_threads, t_cached, marker="o", label="cache_greens=True")
    axes[0, col].plot(num_threads, t_otf, marker="s", label="cache_greens=False")
    axes[0, col].set_title(f"Grid {nx}x{ny} (DST)")
    axes[0, col].set_ylabel("Solver init + solve time [s]")
    axes[0, col].grid(alpha=0.4)
    axes[0, col].legend()

    # Bottom row: speedup relative to nt=1
    axes[1, col].plot(num_threads, t_cached[0] / t_cached, marker="o", label="cache_greens=True")
    axes[1, col].plot(num_threads, t_otf[0] / t_otf, marker="s", label="cache_greens=False")
    axes[1, col].axhline(1.0, color="k", linestyle="--", linewidth=0.8, alpha=0.6)
    axes[1, col].set_xlabel("Number of threads (set_num_threads)")
    axes[1, col].set_ylabel("Speedup vs nt=1")
    axes[1, col].set_xticks(num_threads)
    axes[1, col].grid(alpha=0.4)
    axes[1, col].legend()

plt.tight_layout()
../_images/292c2d1ab71d7e4fc265b4526556cafbf4ed5601bd2a1183d5404f4a30b05780.png

Initially it appears as if setting cache_greens=False is always a bad option but this is not the case:

  • Memory-vs-runtime trade-off: cache_greens=True is always faster and should be used whenever the boundary Green’s matrix fits in RAM. Setting cache_greens=False is strictly a workaround for large grids that would otherwise exceed available memory.

  • Stronger thread scaling: Although cache_greens=False has a higher total runtime, recomputing the boundary flux on-the-fly is heavily parallelisable, so its relative speedup with set_num_threads (bottom row) is much steeper than with cache_greens=True.

Additionally, cache_greens=False should be avoided completely when the intention is to perform an evolutive solve: in this case, the performance cost will become prohibitively expensive and the memory savings will be less significant. There are other tools for reducing memory use in evolutive solves, some of which are explained in example 05a.

The flag max_batch_size can also be used when initialising the solver object to allow for a further decrease in memory, by reducing the size of the portion of the Green’s function that can be held in memory at a time.

Its main intended use is for very resolved grids on HPC systems — here, the default is 2_000_000_000 maximum batch size which puts an upper ceiling of ~64GB on the memory. This value can be reduced if needed to fit the computer you are using.

Finally, let’s try an even larger solve using all of the above functionality — checking how much memory it would have required vs. without.

# higher-resolution solve without caching the full boundary Green's matrix (you can go higher if you wish!)
nx = 257
ny = 513
max_batch_size = 100_000_000  # set ~3.2 GB max per temporary batch (float64)

# print memory that has been saved
n_bndry = 2 * (nx + ny) - 4
full_greens_gb = n_bndry * nx * ny * 8 / 1e9
batch_gb = max_batch_size * 8 / 1e9
print(f"Grid {nx}x{ny}: full cached greenfunc would require {full_greens_gb:.2f} GB "
      f"(batch limit set to {batch_gb:.2f} GB)")

# monitor performance (setting up machine)
t0 = perf_counter()
set_num_threads(4)
eq, profiles = setup_openstep(nx=nx, ny=ny)
t1 = perf_counter()
print(f"Equilibrium and profiles built in {t1 - t0:.2f}s", flush=True)

# monitor peformance (initialising + solving equilibrium)
GSStaticSolver = GSstaticsolver.NKGSsolver(
    eq=eq,
    solver_type="LUsparse",
    gs_operator_order=4,
    cache_greens=False,
    max_batch_size=max_batch_size,
)

GSStaticSolver.solve(
    eq=eq,
    profiles=profiles,
    target_relative_tolerance=1e-6,
    force_up_down_symmetric=True,
    verbose=True,
)
t2 = perf_counter()
print(f"Equilibrium solved in {t2 - t1:.2f}s (total {t2 - t0:.2f}s)")

# reset thread count and store results for the resolution comparison below
set_num_threads(1)
resolutions.append((nx, ny))
psi_results.append(eq.psi())
x_points.append(profiles.xpt)
o_points.append(profiles.opt)
jtor_results.append(GSStaticSolver.jtor)
Grid 257x513: full cached greenfunc would require 1.62 GB (batch limit set to 0.80 GB)
Equilibrium and profiles built in 12.94s
-----
Forward static solve starting...
Initial guess for plasma_psi successful, residual found.
Initial relative error = 7.79e-01
-----
Forward static solve starting...
Initial guess for plasma_psi successful, residual found.
Initial relative error = 7.79e-01
-----
Picard iteration: 0
Forcing up-dpwn symmetry of the plasma.
Update too large, resized.
...relative error =  6.57e-01
-----
Picard iteration: 1
Forcing up-dpwn symmetry of the plasma.
Update too large, resized.
...relative error =  5.30e-01
-----
Picard iteration: 2
Forcing up-dpwn symmetry of the plasma.
Update too large, resized.
...relative error =  3.99e-01
-----
Picard iteration: 3
Forcing up-dpwn symmetry of the plasma.
Update too large, resized.
...relative error =  2.63e-01
-----
Picard iteration: 4
Forcing up-dpwn symmetry of the plasma.
Update too large, resized.
...relative error =  1.28e-01
-----
Picard iteration: 5
Forcing up-dpwn symmetry of the plasma.
...relative error =  5.61e-02
-----
-----
Newton-Krylov iteration: 6
...number of Krylov vectors used =  1
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  3.36e-02
-----
-----
Newton-Krylov iteration: 7
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  4.54e-02
-----
-----
Newton-Krylov iteration: 8
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
Update too large, resized.
New starting_direction used due to collinear residuals.
...relative error =  3.09e-02
-----
-----
Newton-Krylov iteration: 9
...number of Krylov vectors used =  7
Forcing up-dpwn symmetry of the plasma.
Update too large, resized.
New starting_direction used due to collinear residuals.
...relative error =  4.35e-02
-----
-----
Newton-Krylov iteration: 10
...number of Krylov vectors used =  10
Forcing up-dpwn symmetry of the plasma.
...relative error =  2.58e-02
-----
-----
Newton-Krylov iteration: 11
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  5.74e-03
-----
-----
Newton-Krylov iteration: 12
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
...relative error =  5.77e-03
-----
-----
Newton-Krylov iteration: 13
...number of Krylov vectors used =  14
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  6.26e-03
-----
-----
Newton-Krylov iteration: 14
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  5.70e-03
-----
-----
Newton-Krylov iteration: 15
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  5.69e-03
-----
-----
Newton-Krylov iteration: 16
...number of Krylov vectors used =  6
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  4.92e-03
-----
-----
Newton-Krylov iteration: 17
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  4.40e-03
-----
-----
Newton-Krylov iteration: 18
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  4.90e-03
-----
-----
Newton-Krylov iteration: 19
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  4.86e-03
-----
-----
Newton-Krylov iteration: 20
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  4.80e-03
-----
-----
Newton-Krylov iteration: 21
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  4.80e-03
-----
-----
Newton-Krylov iteration: 22
...number of Krylov vectors used =  5
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  5.33e-03
-----
-----
Newton-Krylov iteration: 23
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  5.66e-03
-----
-----
Newton-Krylov iteration: 24
...number of Krylov vectors used =  5
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  5.53e-03
-----
-----
Newton-Krylov iteration: 25
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  5.50e-03
-----
-----
Newton-Krylov iteration: 26
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  5.49e-03
-----
-----
Newton-Krylov iteration: 27
...number of Krylov vectors used =  7
Forcing up-dpwn symmetry of the plasma.
...relative error =  4.79e-03
-----
-----
Newton-Krylov iteration: 28
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
...relative error =  3.70e-03
-----
-----
Newton-Krylov iteration: 29
...number of Krylov vectors used =  6
Forcing up-dpwn symmetry of the plasma.
...relative error =  4.00e-03
-----
-----
Newton-Krylov iteration: 30
...number of Krylov vectors used =  12
Forcing up-dpwn symmetry of the plasma.
...relative error =  8.61e-03
-----
-----
Newton-Krylov iteration: 31
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  1.64e-02
-----
-----
Newton-Krylov iteration: 32
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  8.90e-03
-----
-----
Newton-Krylov iteration: 33
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
...relative error =  2.57e-03
-----
-----
Newton-Krylov iteration: 34
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.37e-03
-----
-----
Newton-Krylov iteration: 35
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
...relative error =  5.36e-04
-----
-----
Newton-Krylov iteration: 36
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  4.24e-04
-----
-----
Newton-Krylov iteration: 37
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  3.85e-04
-----
-----
Newton-Krylov iteration: 38
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  6.40e-04
-----
-----
Newton-Krylov iteration: 39
...number of Krylov vectors used =  1
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  1.03e-03
-----
-----
Newton-Krylov iteration: 40
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  1.58e-03
-----
-----
Newton-Krylov iteration: 41
...number of Krylov vectors used =  5
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.67e-03
-----
-----
Newton-Krylov iteration: 42
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  1.75e-03
-----
-----
Newton-Krylov iteration: 43
...number of Krylov vectors used =  5
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  2.83e-03
-----
-----
Newton-Krylov iteration: 44
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
...relative error =  2.74e-03
-----
-----
Newton-Krylov iteration: 45
...number of Krylov vectors used =  6
Forcing up-dpwn symmetry of the plasma.
...relative error =  4.57e-03
-----
-----
Newton-Krylov iteration: 46
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.53e-03
-----
-----
Newton-Krylov iteration: 47
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  1.92e-03
-----
-----
Newton-Krylov iteration: 48
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  1.42e-03
-----
-----
Newton-Krylov iteration: 49
...number of Krylov vectors used =  7
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  1.61e-03
-----
-----
Newton-Krylov iteration: 50
...number of Krylov vectors used =  5
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  2.85e-03
-----
-----
Newton-Krylov iteration: 51
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
...relative error =  5.62e-03
-----
-----
Newton-Krylov iteration: 52
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.19e-03
-----
-----
Newton-Krylov iteration: 53
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.74e-03
-----
-----
Newton-Krylov iteration: 54
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.84e-03
-----
-----
Newton-Krylov iteration: 55
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  8.26e-04
-----
-----
Newton-Krylov iteration: 56
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  4.97e-04
-----
-----
Newton-Krylov iteration: 57
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
Increase in residual, update reduction triggered.
...relative error =  3.91e-04
-----
-----
Newton-Krylov iteration: 58
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
New starting_direction used due to collinear residuals.
...relative error =  4.81e-04
-----
-----
Newton-Krylov iteration: 59
...number of Krylov vectors used =  3
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.40e-04
-----
-----
Newton-Krylov iteration: 60
...number of Krylov vectors used =  4
Forcing up-dpwn symmetry of the plasma.
...relative error =  6.12e-05
-----
-----
Newton-Krylov iteration: 61
...number of Krylov vectors used =  1
Forcing up-dpwn symmetry of the plasma.
...relative error =  7.35e-06
-----
-----
Newton-Krylov iteration: 62
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  1.34e-06
-----
-----
Newton-Krylov iteration: 63
...number of Krylov vectors used =  2
Forcing up-dpwn symmetry of the plasma.
...relative error =  3.10e-07
-----
Forward static solve SUCCESS. Tolerance 3.10e-07 (vs. requested 1.00e-06) reached in 64/100 iterations.
Equilibrium solved in 974.06s (total 987.00s)

Comparison of the equilibria

At this point we have saved results for 3 different grid resolutions (all LUsparse 4th order results), so we can now compare them, in order to see the effect of using more resolved grids.

First, let’s look at the plasma equilibrium - you can see some slight changes in the plasma shape and boundary with increasing resolution.

# plot
num_figs = len(resolutions)+1
fig1, axes = plt.subplots(1, num_figs, figsize=(3.5*num_figs*1.2, 7), dpi=80)

# plot initial guess
ax0 = axes[0]
ax0.grid(zorder=0, alpha=0.75)
ax0.set_aspect('equal')
eq.tokamak.plot(axis=ax0,show=False)
ax0.plot(tokamak.wall.R, tokamak.wall.Z, 'k')
R, Z = np.meshgrid(
    np.linspace(eq.Rmin,eq.Rmax,_plasma_psi.shape[0]),
    np.linspace(eq.Zmin,eq.Zmax,_plasma_psi.shape[1]),
    indexing="ij"
)
ax0.contour(R, Z, _plasma_psi)
ax0.set_title("Initial plasma flux guess")

for i in range(len(resolutions)):

    nr,nz = resolutions[i]
    axes[i+1].set_title(f"Total flux (${nr}\\times{nz}$)")
    axes[i+1].grid(zorder=0, alpha=0.75)
    axes[i+1].set_aspect('equal')
    eq.tokamak.plot(axis=axes[i+1],show=False)                                                          # plots the active coils and passive structures
    axes[i+1].fill(tokamak.wall.R, tokamak.wall.Z, color='k', linewidth=1.2, facecolor='w', zorder=0)   # plots the limiter
    R, Z = np.meshgrid(
        np.linspace(eq.Rmin,eq.Rmax,nr),
        np.linspace(eq.Zmin,eq.Zmax,nz),
        indexing="ij"
    )
    axes[i+1].contour(R, Z, psi_results[i],levels=np.linspace(np.amin(psi_results[i]), np.amax(psi_results[i]), 35))

    
    axes[i+1].contour(R,Z,psi_results[i],levels=[x_points[i][0][2]],colors='r')
    for r, z, _ in x_points[i]:
        axes[i+1].plot(r, z, "rx", markersize=9)
        axes[i+1].plot(x_points[i][0][0], x_points[i][0][1], "rx", markersize=9, markeredgewidth=2.5)
    for r, z, _ in o_points[i]:
        axes[i+1].plot(r, z, "g2", markersize=9)

    axes[i+1].set_yticklabels([])
    axes[i+1].set_ylabel("")
../_images/d54eaa30beca009b665a465b4dd1721950342ac7d07e323e19c0313757456030.png

This can be seen further if we plot jtor at a few different \(Z\) levels.

The results show that the bootstrap current at the plasma edge is still not fully resolved - in addition to the outboard midplane boundary!

This highlights the importance of fully resolving complex equilibria! In this particular case, it looks like we would need even more resolution at the edge!

def extract_jtor(jtor,z_vals):
    midline = jtor.shape[-1]//2
    return tuple(jtor[:,midline + int(z_val/20.*jtor.shape[-1])] for z_val in z_vals)


num_figs = len(resolutions)
fig2, axes2 = plt.subplots(1, num_figs, figsize=(3.5*num_figs*1.2, 7), dpi=80)
max_jtor = max([jtor.max() for jtor in jtor_results])

for i in range(len(resolutions)):

    nr,nz = resolutions[i]
    axes2[i].set_title(f"${nr}\\times{nz}$")
    img = axes2[i].imshow(jtor_results[i].T,vmin=0,vmax=max_jtor,extent=(0.5,9.,-10,10),cmap='inferno')
    axes2[i].fill(tokamak.wall.R, tokamak.wall.Z, color='b', linewidth=1.2, facecolor=('w',0), zorder=0)   # plots the limiter
    axes2[i].grid(zorder=0, alpha=0.75)
    eq.tokamak.plot(axis=axes2[i],show=False)                                                          # plots the active coils and passive structures
    if i!=0:
        axes2[i].set_yticklabels([])
        axes2[i].set_ylabel("")
        img0 = img

fig2.colorbar(img0,ax=axes2,orientation="vertical",fraction=0.1)

z_vals = [6,5,4,0]
num_figs = len(z_vals)
fig1, axes = plt.subplots(num_figs, 1, figsize=(12, 3*num_figs), dpi=80)

for jtor_field,(nr,nz) in zip(jtor_results,resolutions):
    jtor_curves = extract_jtor(jtor_field,z_vals)
    n_curves = len(jtor_curves)
    for i in range(n_curves):
        jtor = jtor_curves[i]
        axes[i].plot(np.linspace(0.5,9.,len(jtor)),jtor,label=f"${nr}\\times{nz}$")
        axes[i].set_ylim(0,max(1e6,jtor.max()*1.05))

for i in range(num_figs):
    axes[i].set_ylabel(f"$z={z_vals[i]}$")
    axes[i].grid()
    axes[i].set_xlim(1.0,6.5)

axes[0].legend(title='Resolution')
axes[num_figs//2].set_ylabel("Jtor\n"+axes[num_figs//2].get_ylabel())
axes[-1].set_xlabel("Major radius [m]")
plt.show()
../_images/1d8682259eb1514f3aaaedca41deab9a081eb357e2d79d1cb3fcdf39f1eb0563.png ../_images/a25a6efb1715a967505fa4a459dd0e4718d199aa3c301bd9383a4657bcd02e29.png