freegsnke.equilibrium module

Defines class that represents the equilibrium state and its associated quantities.

Copyright 2024 Nicola C. Amorisco, Adriano Agnello, George K. Holt, Ben Dudson.

Modified substantially from the original FreeGS code.

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/>.

class freegsnke.equilibrium.Equilibrium(tokamak: object | None = None, Rmin: float = 0.1, Rmax: float = 2.0, Zmin: float = -1.0, Zmax: float = 1.0, nx: int = 65, ny: int = 65, boundary: ~typing.Callable = <function freeBoundary>, psi: ~numpy.ndarray | ~typing.Callable | None = None, current: float = 0.0, order: int | None = None)[source]

Bases: object

Represents the plasma equilibrium state and its associated properties.

Bpol(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Total poloidal magnetic field due to plasma and coils:

Bpol(R, Z) = ( Br(R, Z)^2 + Bz(R, Z)^2 )^(1/2).

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The poloidal magnetic field at the given (R, Z) positions [T].

Return type:

float | np.ndarray

Br(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Total radial magnetic field due to plasma and coils:

Br(R, Z) = -(1 / R) * dψ/dZ (R, Z),

where ψ is the total flux.

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The total radial magnetic field at the given (R, Z) positions [T].

Return type:

float | np.ndarray

Btor(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Total toroidal magnetic field:

Btor(R, Z) = [ I(R, Z) * fpol(ψ_n) + (1 - I(R, Z)) * fvac ] / R,

where:
  • I(R, Z) = 1 inside core plasma, 0 outside.

  • fpol = R*Bt at specified values of normalised psi ψ_n (i.e. inside the plasma core).

  • fvac = R*Bt in vacuum (i.e. outside plasma).

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The toroidal magnetic field at the given (R, Z) positions [T].

Return type:

float | np.ndarray

Raises:
  • AttributeError – If the equilibrium has not been solved yet (no core mask available).

  • ValueError – If R and Z are not both scalars, both 1D arrays, or both 2D arrays.

Bz(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Total vertical magnetic field due to plasma and coils:

Bz(R, Z) = (1 / R) * dψ/dR (R, Z),

where ψ is the total flux.

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The total vertical magnetic field at the given (R, Z) positions [T].

Return type:

float | np.ndarray

Rcurrent() → float | None[source]

The average major radius of the toroidal current distribution.

Returns:

Average major radius [m]; None (with a printed message) if the equilibrium has not been solved yet.

Return type:

float | None

Rgeometric() → float[source]

The major radius of the geometric axis.

Returns:

Major radius of the geometric axis [m].

Return type:

float

Rmagnetic() → float[source]

The major radius of the magnetic axis.

Returns:

Major radius of the magnetic axis [m].

Return type:

float

Zcurrent() → float | None[source]

The average height of the toroidal current distribution.

Returns:

Average height [m]; None (with a printed message) if the equilibrium has not been solved yet.

Return type:

float | None

Zgeometric() → float[source]

The height of the geometric axis.

Returns:

Vertical height of the geometric axis [m].

Return type:

float

Zmagnetic() → float[source]

The height of the magnetic axis.

Returns:

Vertical height of the magnetic axis [m].

Return type:

float

__init__(tokamak: object | None = None, Rmin: float = 0.1, Rmax: float = 2.0, Zmin: float = -1.0, Zmax: float = 1.0, nx: int = 65, ny: int = 65, boundary: ~typing.Callable = <function freeBoundary>, psi: ~numpy.ndarray | ~typing.Callable | None = None, current: float = 0.0, order: int | None = None) → None[source]

Initialise a plasma equilibrium.

Parameters:
  • tokamak (machine.Machine | None) – The set of active coils, passive structures, limiter, and magnetic probes in the tokamak. If None (default), an empty tokamak (machine.EmptyTokamak) is used.

  • Rmin (float) – Minimum major radius [m].

  • Rmax (float) – Maximum major radius [m].

  • Zmin (float) – Minimum height [m].

  • Zmax (float) – Maximum height [m].

  • nx (int) – Number of radial grid points (must be of form 2^n + 1, n=0,1,2,3,4,5,…).

  • ny (int) – Number of vertical grid points (must be of form 2^n + 1, n=0,1,2,3,4,5,…).

  • boundary (callable) – The boundary condition function. Can be either freeBoundary or fixedBoundary.

  • psi (np.ndarray | Callable | None) – Initial guess for plasma flux [Webers/2pi]. If None, default initial Gaussian-shaped guess used. If a callable is provided, it is called with the equilibrium to get the initial guess. The array (returned by the callable) must have the shape (nx, ny).

  • current (float) – Plasma current [A].

  • order (int | None) – Deprecated, passing a value raises a DeprecationWarning. No solver is created at initialization; the value (default 4) is only used as the order of the sparse-LU solver that is lazily created by callSolver.

Raises:

ValueError – If Rmin > Rmax, Zmin > Zmax, nx or ny is negative, or the shape of the initial psi does not match (nx, ny).

aspectRatio() → float[source]

Calculate the aspect ratio of the plasma.

Returns:

Aspect ratio of the plasma.

Return type:

float

callSolver(psi: ndarray, rhs: ndarray) → ndarray[source]

Solve the GS elliptic equation for the given right hand side. The solver (a sparse-LU GSLUSolver of the order given at initialization) is created lazily on first use, so that constructing an Equilibrium carries no factorization cost.

Parameters:
  • psi (np.ndarray) – The initial guess [Webers/2pi] (unused by the LU solver).

  • rhs (np.ndarray) – The right hand side of the GS equation.

Returns:

The solution of the GS equation, with the shape of rhs.

Return type:

np.ndarray

closest_wall_point() → list[ndarray | float][source]

Calculate the point on the last closed flux surface boundary that is closest to the wall (and the corresponding distance).

Returns:

Coordinates array and minimum distance to the wall: [ (R,Z), min_distance ] [m, m, m].

Return type:

list[np.ndarray | float]

create_psi_plasma_default(adaptive_centre: bool = False, gpars: tuple[float, float, float, float] = (0.5, 0.5, 0, 2)) → ndarray[source]

Generate a Gaussian-shaped initial guess for the plasma flux.

Kept for backwards compatibility; it is NOT called by this class anymore.

Parameters:
  • adaptive_centre (bool) – Passed to PsiGuessGaussian; if True the Gaussian is centred adaptively.

  • gpars (tuple[float, float, float, float]) – Gaussian parameters passed to PsiGuessGaussian.

Returns:

Initial guess for the plasma flux on the (R, Z) grid [Webers/2pi].

Return type:

np.ndarray

dr_sep(Z_level: float | None = None, sign_flip: bool = False) → list[float | None][source]

Compute the radial separation (on the inboard and outboard sides) at vertical position Z_level between flux surfaces passing through the lower and upper X-points. This requires two X-points to be located within the vessel region.

The inboard dr_sep is defined as the difference in R (radial position) between the two flux surfaces intersecting Z_level on the inboard side (smaller R values), each corresponding to one of the X-points.

Similarly, the outboard dr_sep is the radial separation of the same flux surfaces on the outboard side (larger R values).

Parameters:
  • Z_level (float | None) – Vertical height at which to calculate dr_sep [m]. Defaults to Zgeometric().

  • sign_flip (bool) – By convention, the function assumes the first X-point corresponds to the lower X-point, and the second to the upper X-point. So for an upper single null plasma, dr_sep_out should be positive and dr_sep_in should be negative. Setting sign_flip=True will do the opposite and reverse the signs of the output values.

Returns:

A list containing the inboard and outboard dr_sep values: [dr_sep_in, dr_sep_out]. Both are None (with a printed message) if the intersections could not be resolved.

Return type:

list[float | None]

Raises:

ValueError – If fewer than two X-points lie inside the wall.

effectiveElongation() → float[source]

Calculate the effective elongation of the plasma, using plasma volume.

Returns:

Effective elongation of the plasma.

Return type:

float

ffprime(psinorm: float | ndarray) → float | ndarray[source]

Return ffprime (F * dF/dψ_n) at normalised flux values.

Parameters:

psinorm (np.ndarray) – Array of normalised psi values between (not including) 0 and 1.

Returns:

ffprime (F * dF/dψ_n) at normalised flux values [T^2 m^2/(Wb/2pi)].

Return type:

np.ndarray

flux_averaged_function(f: Callable[[ndarray, ndarray], ndarray], psi_n: float | ndarray | None = None) → tuple[ndarray, ndarray][source]

Calculate the flux averaged value of a 2D scalar field f on a (normalised) flux surface of psi (denoted by psi_n) within the last closed flux surface according to:

< f >(psi_n) = integral_{psi_n} (f/B_pol) dl / integral_{psi_n} (1/B_pol) dl,

where:
  • f(R,Z) = 2D scalar field function (e.g. jtor).

  • psi_n = value of normalised flux at which to evaluate line integrals.

  • Bpol(R,Z) = 2D scalar poloidal magnetic field function.

  • dl = parameterised line element (distance) along the flux surface.

This definition was taken from https://www.mdpi.com/2571-6182/7/4/45.

Parameters:
  • f (Callable[[np.ndarray, np.ndarray], np.ndarray]) – 2D scalar function f(R, Z) that is to be flux averaged. Must be able to take in arrays of (R,Z) coordinates.

  • psi_n (float | np.ndarray | None) – Range of normalised flux values to average on (values are clipped to [0.01, 0.99]). One value returned for each element in psi_n. If None, 65 values equally spaced in [0.01, 0.99] are used.

Returns:

  • flux_averaged_quantity (np.ndarray) – The flux averaged quantity evaluated at each value in psi_n.

  • psi_n (np.ndarray) – The values of psi_n used to calculate each value in flux_averaged_quantity (may be different to the input psi_n if the input array had values outside [0.01, 0.99]).

fpol(psinorm: float | ndarray) → float | ndarray[source]

Return f = R*Bt at specified values of normalised psi (i.e. inside the plasma core).

Parameters:

psinorm (float | np.ndarray) – Normalised psi value(s) between 0 and 1.

Returns:

fpol at values of normalised psi [Tm].

Return type:

float | np.ndarray

fvac() → float[source]

Return vacuum f = R*Bt (i.e. outside the plasma core).

Returns:

fvac value in vacuum [Tm].

Return type:

float

geometricAxis() → ndarray[source]

The geometric axis (R_geom, Z_geom) of the plasma [m]. Calculated as the centre of a large number of points on the separatrix.

Returns:

Geometric axis (R,Z) position [m].

Return type:

np.ndarray

geometricElongation() → float[source]

Calculate the geometric elongation of the plasma.

Returns:

Geometric elongation of the plasma.

Return type:

float

geometricElongation_lower() → float[source]

Calculate the geometric elongation of the lower part of the plasma.

Returns:

Geometric elongation of the lower part of the plasma.

Return type:

float

geometricElongation_upper() → float[source]

Calculate the geometric elongation of the upper part of the plasma.

Returns:

Geometric elongation of the upper part of the plasma.

Return type:

float

getForces() → dict[source]

Calculate the forces on the coils.

Returns:

Coil labels with the associated force [N] (nested for circuits).

Return type:

dict

getMachine() → object[source]

Return the tokamak (machine) object.

Returns:

The tokamak object this equilibrium was built with.

Return type:

object

innerOuterSeparatrix(Z: float = 0.0) → tuple[float, float][source]

Locate inboard and outboard R co-ordinates of last closed flux surface at a given Z position.

Parameters:

Z (float, optional) – The Z value at which to find the radii. Defaults to 0.0.

Returns:

The inner and outer separatrix major radii (at chosen Z) [m].

Return type:

tuple[float, float]

innerOuterSeparatrix2(Z: float = 0.0) → list[tuple[float, float]][source]

Alternative (simpler) function to find inboard and outboard R co-ordinates of last closed flux surface at any given Z position (using shapely).

Parameters:

Z (float, optional) – The Z value at which to find the radii. Defaults to 0.0.

Returns:

List of the (R, Z) intersection coordinates, normally (R_in, Z) and (R_out, Z) [m]; empty if there is no intersection.

Return type:

list[tuple[float, float]]

Raises:

ValueError – If the intersection of the separatrix with the line is neither a point nor a set of points.

internalInductance1() → float[source]

Calculate plasma internal inductance according to:

li = ( (L * integral(Bpol) dV) / (mu0 * Ip * V) )^2,

where:
  • L = length of the separatrix (LCFS).

  • Bpol(R,Z) = poloidal magnetic field (at each (R,Z)).

  • dV = volume element.

  • mu0 = magnetic permeability in vacuum.

  • Ip = total plasma current.

  • V = total plasma volume.

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

Plasma internal inductance.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

internalInductance2() → float[source]

Calculate plasma internal inductance according to:

li = ( integral(Bpol**2) dV ) / ( ( integral(Bpol) dl / L )**2 * V),

where:
  • L = length of the separatrix (LCFS).

  • Bpol(R,Z) = poloidal magnetic field (at each (R,Z)).

  • dV = volume element.

  • dl = line element (along LCFS).

  • mu0 = magnetic permeability in vacuum.

  • Ip = total plasma current.

  • V = total plasma volume.

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

Plasma internal inductance.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

internalInductance3() → float[source]

Calculate plasma internal inductance according to:

li = (2 * integral(Bpol^2) dV) / (mu0^2 * Ip^2 * R_geom),

where:
  • Bpol(R,Z) = poloidal magnetic field (at each (R,Z)).

  • dV = volume element.

  • mu0 = magnetic permeability in vacuum.

  • Ip = total plasma current.

  • R_geom = radial coords of geometric axis.

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

Plasma internal inductance.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

internalInductance4() → float[source]

Calculate plasma internal inductance according to:

li = (2 * integral(Bpol^2) dV) / (mu0^2 * Ip^2 * R_mag),

where:
  • Bpol(R,Z) = poloidal magnetic field (at each (R,Z)).

  • dV = volume element.

  • mu0 = magnetic permeability in vacuum.

  • Ip = total plasma current.

  • R_mag = radial coords of magnetic axis.

Returns:

Plasma internal inductance.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

internalInductance5() → float[source]

Calculate plasma internal inductance according to:

li = [(2 * integral(Bpol^2) dV) / (mu0^2 * Ip^2 * R_geom)] * [(1 + geom_elon^2)/(2 * eff_elon)],

where:
  • Bpol(R,Z) = poloidal magnetic field (at each (R,Z)).

  • dV = volume element.

  • mu0 = magnetic permeability in vacuum.

  • Ip = total plasma current.

  • R_geom = radial coords of geometric axis.

  • geom_elon = geometric elongation.

  • eff_elon = effective elongation.

Returns:

Plasma internal inductance.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

intersectsWall() → bool[source]

Assess whether or not the core plasma touches the vessel walls.

Returns:

True if they intersect, False if not.

Return type:

bool

magneticAxis() → ndarray[source]

Return the location of the magnetic axis and its total poloidal flux value.

Returns:

[R, Z, ψ(R, Z)] at the magnetic axis location [m, m, Webers/2pi].

Return type:

np.ndarray

minorRadius() → float[source]

Calculate the minor radius of the plasma [m].

Returns:

Minor radius of the plasma [m].

Return type:

float

normalised_total_Beta() → float[source]

Calculate the total beta from the following definition:

normalised_total_Beta = ( (1 / poloidalBeta1) + (1/toroidalBeta1) )^(-1).

Returns:

Returns the normalised total beta value.

Return type:

float

property order: int

Return the deprecated order used by the lazy compatibility solver.

Returns:

Order of the sparse-LU solver created on first use.

Return type:

int

plasmaBr(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Radial magnetic field due to plasma:

Br_p(R, Z) = -(1 / R) * dψ_p/dZ (R, Z),

where ψ_p is the plasma flux.

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The radial magnetic field due to the plasma at the given (R, Z) positions [T].

Return type:

float | np.ndarray

plasmaBz(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Vertical magnetic field Bz due to plasma:

Bz_p(R, Z) = (1 / R) * dψ_p/dR (R, Z),

where ψ_p is the plasma flux.

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The vertical magnetic field due to the plasma at the given (R, Z) positions [T].

Return type:

float | np.ndarray

plasmaCurrent() → float[source]

Return the plasma current [Amps].

Returns:

The total plasma current [Amps].

Return type:

float

plasmaVolume() → float[source]

Plasma volume [m^3] calculated using:

V = 2 * pi * integral(R) dR dZ,

where the integral is evaluated over the plasma core domain.

Returns:

The total plasma volume [m^3].

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

plot(axis: object | None = None, xpoints: bool = True, opoints: bool = True, wall: bool = True, limiter: bool = True, legend: bool = False, show: bool = True) → object[source]

Plot the magnetic equilibrium flux surfaces and key geometric features.

This method provides a convenient interface to visualize the equilibrium stored in the current object. It calls the plotEquilibrium function to display magnetic flux contours, separatrix, magnetic nulls (X- and O-points), and the tokamak boundary geometry (wall and limiter).

Parameters:
  • axis (matplotlib.axes.Axes | None) – Axis object on which to plot. If None, a new figure and axis are created.

  • xpoints (bool) – If True, plot magnetic X-points as red ‘x’ markers.

  • opoints (bool) – If True, plot magnetic O-points as green ‘*’ markers.

  • wall (bool) – If True, plot the tokamak wall outline as a solid black line.

  • limiter (bool) – If True, plot the limiter outline as a dashed black line.

  • legend (bool) – If True, display a legend describing plotted features.

  • show (bool) – If True, call matplotlib.pyplot.show() before returning.

Returns:

axis – The matplotlib axis containing the plotted equilibrium.

Return type:

matplotlib.axes.Axes

Notes

  • This method is a wrapper around plotEquilibrium(self, …).

  • The equilibrium must be solved before plotting; otherwise, a warning will be printed.

Examples

eq.solve(profiles) axis = eq.plot(legend=True) axis.set_title(“Plasma Equilibrium Flux Surfaces”)

poloidalBeta() → float[source]

Backward-compatible alias for poloidalBeta1().

Returns:

The poloidal beta value.

Return type:

float

poloidalBeta1() → float[source]

Calculate poloidal beta from the following definition:

betap = (8 * pi / (mu0 * Ip^2)) * integral(p) dR dZ,

where:
  • mu0 = magnetic permeability in vacuum.

  • Ip = total plasma current.

  • p = plasma pressure (at each (R,Z)).

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The poloidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

poloidalBeta2() → float[source]

Calculate poloidal beta from the following definition:

betap = 2 * mu0 * integral(p) dV / integral(Bpol^2) dV,

where:
  • mu0 = magnetic permeability in vacuum.

  • p = plasma pressure (at each (R,Z)).

  • Bpol(R,Z) = poloidal magnetic field (at each (R,Z)).

  • dV = volume element

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The poloidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

poloidalBeta3() → float[source]

Calculate poloidal beta from the following definition:

betap = 2 * mu0 * ( integral(p) dV / V)

/ (integral(Bpol) dl / L)**2,

where:
  • p = pressure field.

  • dV = volume element.

  • V = total plasma volume.

  • Bpol(R,Z) = poloidal magnetic field (at each (R,Z)).

  • dl = line element (along LCFS).

  • L = length of the separatrix (LCFS).

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The poloidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

poloidalBeta4() → float[source]

Calculate poloidal beta from the following definition:

betap = 4 * integral(p) dV / (mu0 * Ip^2 * integral(R) dV / V),

where:
  • p = plasma pressure (at each (R,Z)).

  • dV = volume element

  • mu0 = magnetic permeability in vacuum.

  • Ip = total plasma current.

  • R = radial grid points.

  • V = total plasma volume.

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The poloidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

pprime(psinorm: float | ndarray) → float | ndarray[source]

Return pprime (dp/dψ_n) at normalised flux values.

Parameters:

psinorm (np.ndarray) – Array of normalised psi values between (not including) 0 and 1.

Returns:

pprime (dp/dψ_n) at normalised flux values [Pa/(Webers/2pi)].

Return type:

np.ndarray

pressure(psinorm: float | ndarray) → float | ndarray[source]

Return pressure (p(ψ_n)) at normalised flux values.

Parameters:

psinorm (np.ndarray) – Array of normalised psi values between (not including) 0 and 1.

Returns:

pressure (p(ψ_n)) at normalised flux values [Pa].

Return type:

np.ndarray

printForces() → None[source]

Print a table of forces on coils.

psi() → ndarray[source]

Total poloidal flux due to plasma and coils on the entire (R,Z) grid:

ψ(R, Z) = ψ_p (R, Z) + ψ_c (R, Z),

where:
  • ψ_p (R, Z) is the plasma flux.

  • ψ_c (R, Z) is the coil flux.

Returns:

The total poloidal flux due to the plasma and the coils [Webers/2pi].

Return type:

np.ndarray

psiNRZ(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Total poloidal flux due to plasma and coils (at chosen R and Z), normalised with respect to the flux on the magnetic axis and last closed flux surface:

ψ_n(R, Z) = (ψ(R, Z) - ψ_a)/(ψ_b - ψ_a),

where:
  • ψ_a is the total flux on the magnetic axis.

  • ψ_b is the total flux on the last closed flux surface.

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The total normalised poloidal flux due to the plasma and the coils at chosen (R,Z) locations.

Return type:

float | np.ndarray

psiN_1D(N: int) → ndarray[source]

Total normalised poloidal flux between magnetic axis and last closed flux surface.

Parameters:

N (int) – Number of discretisation points.

Returns:

The total normalised poloidal flux due to the plasma and the coils between the magnetic axis and last closed flux surface.

Return type:

np.ndarray

psiRZ(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Total poloidal flux due to plasma and coils (at chosen R and Z):

ψ(R, Z) = ψ_p (R, Z) + ψ_c (R, Z),

where:
  • ψ_p (R, Z) is the plasma flux.

  • ψ_c (R, Z) is the coil flux.

Parameters:
  • R (float | np.ndarray) – Radial position(s) to evaluate at.

  • Z (float | np.ndarray) – Vertical position(s) to evaluate at.

Returns:

The total poloidal flux due to the plasma and the coils at chosen (R,Z) locations [Webers/2pi].

Return type:

float | np.ndarray

psi_1D(N: int) → ndarray[source]

Total poloidal flux between magnetic axis and last closed flux surface (at equally spaced locations).

Parameters:

N (int) – Number of discretisation points.

Returns:

The total poloidal flux due to the plasma and the coils between the magnetic axis and last closed flux surface [Webers/2pi].

Return type:

np.ndarray

q(psinorm: ndarray) → float | ndarray[source]

Safety factor q at normalised flux values.

Note that at both psinorm = 0 (magnetic axis) and psinorm = 1 (separatrix), calculating q is problematic (results may be inaccurate).

Parameters:

psinorm (float or np.array) – Normalised psi value(s) between (not including) 0 and 1. Can be a scalar or an array of any shape.

Returns:

Safety factor q at values of normalised psi: a float for a single value, otherwise an array with the same shape as psinorm.

Return type:

float or np.array

rhoN_1D(N: int) → ndarray[source]

Normalised toroidal flux ρ_n (at locations of normalised psi) such that:

ρ_n = sqrt( ρ / ρ_b ),

where ρ_b is the toroidal flux at the last closed flux surface.

Parameters:

N (int) – Number of discretisation points.

Returns:

The normalised toroidal flux (at locations of normalised psi).

Return type:

np.ndarray

rho_1D(N: int) → float | ndarray[source]

Toroidal flux ρ (at locations of normalised psi) such that:

ρ = Φ(ψ) and

Φ = - (1/(2 * pi)) integral(q(ψ)) dψ,

where:
  • q is the safety factor profile as a function of ψ.

Parameters:

N (int) – Number of discretisation points.

Returns:

The toroidal flux (at locations of normalised psi); a scalar if N == 1.

Return type:

float | np.ndarray

separatrix(ntheta: int = 360, IQR_factor: float = 2.0, verbose: bool = False) → ndarray[source]

Return (ntheta x 2) array of (R,Z) points on the last closed flux surface (plasma boundary), equally spaced in the geometric poloidal angle.

Sometimes there may be spurious points far from the core plasma (due to open field lines), we exclude these by finding the minimum distance between points and then excluding those outside of some upper and lower bounds. These bounds can be increased/decreased using IQR_factor.

Parameters:
  • ntheta (int) – Number of points on the boundary to return.

  • IQR_factor (float) – Scaling factor used when excluding spurious points.

  • verbose (bool) – Prints any outliers if True.

Returns:

(R,Z) points on the last closed flux surface (plasma boundary), shape (n, 2) with n <= ntheta (spurious points are removed).

Return type:

np.ndarray

separatrix_area() → float[source]

The area of the last closed flux surface [m^2].

Returns:

Area of the last closed flux surface (plasma boundary) [m^2].

Return type:

float

separatrix_length() → float[source]

The circumference of the last closed flux surface [m].

Returns:

Circumference of the last closed flux surface (plasma boundary) [m].

Return type:

float

setSolver(solver: Callable | None) → None[source]

Deprecated. Set the solver used by callSolver.

Parameters:

solver (Callable | None) – Object callable as solver(x, b), where x is the initial guess and b the right hand side. None restores the default sparse-LU solver (created lazily on next use).

setSolverVcycle(nlevels: int = 1, ncycle: int = 1, niter: int = 1, direct: bool = True, order: int = 4) → None[source]

Deprecated. Equilibrium objects do not contain a multigrid solver.

All arguments are ignored and any previously set solver is discarded, so that the default sparse-LU solver is (lazily) used again.

Parameters:
  • nlevels (int) – Ignored.

  • ncycle (int) – Ignored.

  • niter (int) – Ignored.

  • direct (bool) – Ignored.

  • order (int) – Ignored.

shafranov_shift() → ndarray[source]

Calculate the Shafranov shift of the plasma (i.e. the shift between the magnetic axis and the geometric axis).

Returns:

Shafranov shift of the plasma [del_R, del_Z] [m].

Return type:

np.ndarray

solve(profiles: object, Jtor: ndarray | None = None, psi: ndarray | None = None, psi_bndry: float | None = None) → None[source]

Legacy function that solves for the plasma equilibrium (a linear Grad-Shafranov solve). Modifies the equilibrium in place.

Parameters:
  • profiles (object) – Profiles object containing the toroidal current density profile information.

  • Jtor (np.ndarray | None) – Toroidal current density field over (R,Z) [A/m^2]. If None, it is computed from profiles.

  • psi (np.ndarray | None) – Total poloidal magnetic flux over (R,Z) [Webers/2pi], used to compute Jtor if it is not given. Defaults to the current total flux.

  • psi_bndry (float | None) – Total poloidal magnetic flux on the plasma boundary [Webers/2pi].

squareness() → tuple[float, float, float, float][source]

Calculate the squareness of the plasma core for each of the four quadrants: upper outer, upper inner, lower outer, and lower inner. Method outlined in:

An analytic functional form for characterization and generation of axisymmetric plasma boundaries. Plasma Physics and Controlled Fusion. 2013. T C Luce.

Returns:

Upper outer, upper inner, lower outer and lower inner squareness.

Return type:

tuple[float, float, float, float]

strikepoints(quadrant: str = 'all', loc: tuple[float, float] | None = None) → ndarray | None[source]

Find the strikepoints of an equilibrium (i.e. the points at which the psi_boundary contour intersects the wall).

Parameters:
  • quadrant (str) – Which strikepoints to return to the user, options are “all” (returns all points) or one of “lower left”, “lower right”, “upper left”, or “upper right” quadrants (which returns point(s) in quadrant of poloidal plane with centre given by ‘loc’ (R,Z) pair).

  • loc (tuple[float, float] | None) – (R,Z) point at which to centre the quadrants choice [m]. Required unless quadrant == "all".

Returns:

Array of the (R,Z) strikepoints [m]. None if there are no strikepoints; an array [None, None] if a quadrant is requested and contains none.

Return type:

np.ndarray | None

Raises:

ValueError – If a quadrant other than “all” is requested without loc, or if quadrant is not one of the allowed options.

toroidalBeta1() → float[source]

Calculate a toroidal beta from the following definition:

betat = 2 * mu0 * integral(p) dR dZ / integral(Btor**2) dR dZ,

where:
  • mu0 = magnetic permeability in vacuum.

  • p = plasma pressure (at each (R,Z)).

  • Btor(R,Z) = toroidal magnetic field (at an (R,Z)).

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The toroidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

toroidalBeta2() → float[source]

Calculate a toroidal beta from the following definition:

betat = 2 * mu0 * integral(p) dV / integral(Btor**2) dV,

where:
  • mu0 = magnetic permeability in vacuum.

  • p = plasma pressure (at each (R,Z)).

  • dV = volume element

  • Btor(R,Z) = toroidal magnetic field (at an (R,Z)).

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The toroidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

toroidalBeta3() → float[source]

Calculate a toroidal beta from the following definition:

betat = 2 * mu0 * integral(p) dV / integral(Btor**2 + Bpol**2) dV,

where:
  • mu0 = magnetic permeability in vacuum.

  • p = plasma pressure (at each (R,Z)).

  • dV = volume element

  • Btor(R,Z) = toroidal magnetic field (at an (R,Z)).

  • Bpol(R,Z) = poloidal magnetic field (at an (R,Z)).

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The toroidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

toroidalBeta4() → float[source]

Calculate a toroidal beta from the following definition:

betat = 2 * mu0 * integral(p) dV / Btor_vac(R_geom,Z_geom)^2 * V,

where:
  • mu0 = magnetic permeability in vacuum.

  • p = plasma pressure (at each (R,Z)).

  • dV = volume element.

  • Btor_vac(R,Z) = vacuum toroidal magnetic field (at an (R,Z)).

  • (Rgeom,Zgeom) = geometric axis.

  • V = total plasma volume.

This definition is also used in the Fiesta/Topeol equilibrium codes.

Returns:

The toroidal beta value.

Return type:

float

Raises:

AttributeError – If the equilibrium has not been solved yet (no core mask available).

triangularity() → float[source]

Calculate the triangularity of the plasma.

Returns:

Triangularity of the plasma.

Return type:

float

triangularity_lower() → float[source]

Calculate the lower triangularity of the plasma.

Returns:

Lower triangularity of the plasma.

Return type:

float

triangularity_upper() → float[source]

Calculate the upper triangularity of the plasma.

Returns:

Upper triangularity of the plasma.

Return type:

float

class freegsnke.equilibrium.PsiGuessGaussian(adaptive_centre: bool = False, gpars: tuple[float, ...] = (0.5, 0.5, 0, 2))[source]

Bases: object

Generate a Gaussian initial plasma flux with an optional adaptive centre.

__init__(adaptive_centre: bool = False, gpars: tuple[float, ...] = (0.5, 0.5, 0, 2)) → None[source]

Initialise the Gaussian-shaped initial guess for the plasma flux.

The flux function ψ(R, Z) is given by:

ψ(R, Z) = exp(C - (|x - xc|^p + |y - yc|^p))

where (xc, yc) is the center, C is a shift, and p is a power term. The function ensures the flux is zero on the boundaries.

Parameters:
  • adaptive_centre (bool) – If True, the plasma core position (xc, yc) is adjusted dynamically. If False (default), it remains fixed.

  • gpars (tuple[float, ...]) –

    Parameters (xc, yc, C, p) defining the flux shape, in normalised grid coordinates on [0, 1]:

    • xc, yc : coordinates of the flux centre.

    • C : shift parameter in the exponent.

    • p : power of the distance term.

class freegsnke.equilibrium.PsiGuessParabolicJtor(h: float, k: float, a: float, b: float, Ip: float, *, psi_scale: float = 1.0)[source]

Bases: object

Generate an initial flux estimate from a parabolic current distribution.

__init__(h: float, k: float, a: float, b: float, Ip: float, *, psi_scale: float = 1.0) → None[source]

Initialise the initial psi guess from an elliptic description of the plasma boundary and the plasma current.

We assume a plasma core with a separatrix that can be described by an ellipse. From this, we create an elliptic distribution function E(R, Z) such that E(h, k) = 0 where (h, k) is the centre of the ellipse and E(R, Z) = 1 for all points on the separatrix.

We assume a parabolic distribution of current and calculate Jtor using equation A.7 from [1]:

Jtor = Jhat(1-E(R,Z)^i)^j

Jhat is a constant found to match the calculated plasma current to the desired plasma current (Ip).

Finally, we apply a linear Grad-Shafranov step to find our estimate of the initial plasma psi.

Parameters:
  • h (float) – The radial centre of the ellipse [m].

  • k (float) – The vertical centre of the ellipse [m].

  • a (float) – Half the length of the radial axis of the ellipse (normally the semi-major axis) [m].

  • b (float) – Half the length of the vertical axis of the ellipse (normally the semi-minor axis) [m].

  • Ip (float) – The desired plasma current [A].

  • psi_scale (float) – Multiplies the psi estimate when calling this class before returning.

References

[1] Wai, J. T., et al. “Feedforward equilibrium trajectory optimization with GSPulse.” arXiv preprint arXiv:2506.21760 (2025).

elliptic_distribution_function(R: float | ndarray, Z: float | ndarray) → float | ndarray[source]

Evaluate the elliptic distribution function (E(R, Z)) for the ellipse represented by this class.

Parameters:
  • R (float | np.ndarray) – The radial position(s) to evaluate the distribution function at [m].

  • Z (float | np.ndarray) – The vertical position(s) to evaluate the distribution function at [m].

Returns:

The value of E(R, Z); 0 at the ellipse centre and 1 on the separatrix.

Return type:

float | np.ndarray

classmethod from_separatrix_points(Ip: float, *points: tuple[float, float], psi_scale: float = 1.0) → PsiGuessParabolicJtor[source]

Build the elliptic distribution function that best fits the provided points that describe the desired core’s separatrix.

Parameters:
  • Ip (float) – The desired plasma current [A].

  • *points (tuple[float, float]) – (R, Z) locations on the separatrix [m]; at least 4 are required.

  • psi_scale (float) – Multiplies the psi estimate when calling the returned object.

Returns:

The initial psi guess generator, using the least-squares ellipse fit.

Return type:

PsiGuessParabolicJtor

Raises:

ValueError – If fewer than 4 points are provided.

classmethod from_xpoint_and_midplane(Rx: float, Zx: float, Ri: float, Ro: float, Zm: float, Ip: float, *, psi_scale: float = 1.0) → PsiGuessParabolicJtor[source]

Build the elliptic distribution function that produces a boundary according to the desired X-point location (Rx, Zx), inner midplane (Ri, Zm), and outer midplane (Ro, Zm).

This assumes that the centroid of the ellipse (where the distribution function is 0) occurs radially at the average of Rx, Ri, Ro.

Parameters:
  • Rx (float) – Radial position of the X-point [m].

  • Zx (float) – Vertical position of the X-point [m].

  • Ri (float) – Radial position of the inner midplane point [m].

  • Ro (float) – Radial position of the outer midplane point [m].

  • Zm (float) – Vertical position of the midplane [m].

  • Ip (float) – The desired plasma current [A].

  • psi_scale (float) – Multiplies the psi estimate when calling the returned object.

Returns:

The initial psi guess generator.

Return type:

PsiGuessParabolicJtor

parabolic_jtor(eq: Equilibrium, Ip: float, *, i: float = 1.87, j: float = 1.5) → ndarray[source]

Calculate the Jtor assuming a parabolic current distribution for the given equilibrium.

Solves the equation:

Jtor = Jhat*(1-E(R,Z)^i)^j

where Jhat is calculated according to the desired Ip.

Parameters:
  • eq (Equilibrium) – The equilibrium object to calculate the initial psi for.

  • Ip (float) – The desired plasma current [A].

  • i (float) – First exponent in the current distribution.

  • j (float) – Second exponent in the current distribution.

Returns:

Toroidal current density over the (R, Z) grid [A/m^2], zero outside the ellipse.

Return type:

np.ndarray

freegsnke.equilibrium.ellipse_points(R0: float, Z0: float, A: float, B: float, N: int = 360) → ndarray[source]

Generate the (R,Z) points of an ellipse: ((R-R0)/A)**2 + ((Z-Z0)/B)**2 = 1.

Parameters:
  • R0 (float) – Radial centre of the ellipse [m].

  • Z0 (float) – Vertical centre of the ellipse [m].

  • A (float) – Radial semi-axis of the ellipse [m].

  • B (float) – Vertical semi-axis of the ellipse [m].

  • N (int) – Number of points to generate on the ellipse.

Returns:

(N x 2) numpy array of points on the ellipse.

Return type:

np.ndarray