API Documentation¶
Backend¶
- class desc.backend.TextColors[source]¶
- ENDC = '\x1b[0m'¶
- FAIL = '\x1b[91m'¶
- HEADER = '\x1b[95m'¶
- OKBLUE = '\x1b[94m'¶
- OKCYAN = '\x1b[96m'¶
- TIMER = '\x1b[32m'¶
- WARNING = '\x1b[93m'¶
- class desc.backend.Timer(ns=True)[source]¶
Simple object for organizing timing info
Create a Timer object, which can then keep track of multiple concurrent performance timers, each associated with a given name.
Individual timers can be started and stopped with
timer.start(name)andtimer.stop(name)The elapsed time can be printed with
timer.disp(name)Raw values of elapsed time (in seconds) can be retrieved with
timer[name]- disp(name)[source]¶
Pretty prints elapsed time
If the timer has been stopped, it reports the time delta between start and stop. If it has not been stopped, it reports the current elapsed time and keeps the timing running.
- Parameters
name (str) – name of the timer to display
- Raises
ValueError – if timer ‘name’ has not been started
- class desc.backend.Tristate(value=None)[source]¶
Tristate to determine type of symmetry for R,Z, and L.
- Possible values are:
True for cos(m*t-n*z) symmetry False for sin(m*t-n*z) symmetry None for no symmetry (Default)
- desc.backend.conditional_decorator(dec, condition, *args, **kwargs)[source]¶
Apply arbitrary decorator to a function if condition is met
- Parameters
dec (decorator) – Decorator to apply
condition (bool) – condition that must be met for decorator to be applied
args (tuple, optional) – Arguments to pass to decorator
kwargs (dict, optional) – Keyword arguments to pass to decorator
- Returns
cond_dec (decorator) – Decorator that acts like
decifcondition,
- desc.backend.cross(a, b, axis)[source]¶
Batched vector cross product
- Parameters
a (array-like) – first array of vectors
b (array-like) – second array of vectors
axis (int) – axis along which vectors are stored
- Returns
y (array-like) – y = a x b
- desc.backend.dot(a, b, axis)[source]¶
Batched vector dot product
- Parameters
a (array-like) – first array of vectors
b (array-like) – second array of vectors
axis (int) – axis along which vectors are stored
- Returns
y (array-like) – y = sum(a*b, axis=axis)
- desc.backend.equals(a, b) → bool[source]¶
Compares dictionaries that have numpy array values
- Parameters
a (dict) – reference dictionary
b (dict) – comparison dictionary
- Returns
bool – a == b
- desc.backend.factorial(n)[source]¶
Factorial function for jax backend
- Parameters
n (array-like of int) – input values. if n<0, returns 0
- Returns
n! (array-like of float) – factorial of n
- desc.backend.flatten_list(x)[source]¶
Flattens a nested list
- Parameters
x (list) – nested list of lists to flatten
- Returns
x (list) – flattened input
- desc.backend.isalmostequal(x, axis=- 1, tol=1e-12)[source]¶
Checks if all values of an array are equal, to within a given tolerance
- Parameters
x (array-like) – input values
axis (int) – axis along which to make comparison. If None, the flattened array is used (Default value = -1)
tol (float) – tolerance for comparison. Array is considered equal if std(x)*len(x)< tol along axis (Default value = 1e-12)
- Returns
isalmostequal (bool) – whether the array is equal along specified axis
- desc.backend.issorted(x, axis=None, tol=1e-12)[source]¶
Checks if an array is sorted, within a given tolerance
Checks whether x[i+1] - x[i] > tol
- Parameters
x (array-like) – input values
axis (int) – axis along which to check if the array is sorted. If None, the flattened array is used. (Default value = None)
tol (float) – tolerance for determining order. Array is still considered sorted if the difference between adjacent values is greater than -tol (Default value = 1e-12)
- Returns
issorted (bool) – whether the array is sorted along specified axis
- desc.backend.put(arr, inds, vals)[source]¶
Functional interface for array “fancy indexing”
basically a way to do arr[inds] = vals in a way that plays nice with jit/autodiff.
- Parameters
arr (array-like) – Array to populate
inds (array-like of int) – Indices to populate
vals (array-like) – Values to insert
- Returns
arr (array-like) – Input array with vals inserted at inds.
Basis¶
- class desc.basis.Basis[source]¶
Basis is an abstract base class for spectral basis sets
- property L: int¶
maximum radial resolution
- Type
int
- property M: int¶
maximum poloidal resolution
- Type
int
- property N: int¶
maximum toroidal resolution
- Type
int
- property NFP: int¶
number of field periods
- Type
int
- __eq__(other) → bool[source]¶
Overloads the == operator
- Parameters
other (Basis) – another Basis object to compare to
- Returns
bool – True if other is a Basis with the same attributes as self False otherwise
- abstract change_resolution() → None[source]¶
Change resolution of the basis to the given resolutions.
- Returns
None
- property modes¶
arrauy of int, shape(Nmodes,3): array of mode numbers [l,m,n], each row is one basis function with modes (l,m,n)
- Type
ndarray
- property num_modes: int¶
- property sym: desc.backend.Tristate¶
Tristate: True for cos(m*t-n*z) symmetry, False for sin(m*t-n*z) symmetry, None for no symmetry (Default)
- class desc.basis.DoubleFourierSeries(M: int = 0, N: int = 0, NFP: int = 1, sym: Optional[desc.backend.Tristate] = None, load_from=None, file_format=None, obj_lib=None)[source]¶
2D basis set for use on a single flux surface. Fourier series in both the poloidal and toroidal coordinates.
- __init__(M: int = 0, N: int = 0, NFP: int = 1, sym: Optional[desc.backend.Tristate] = None, load_from=None, file_format=None, obj_lib=None) → None[source]¶
Initializes a DoubleFourierSeries
- Parameters
M (int) – maximum poloidal resolution
N (int) – maximum toroidal resolution
NFP (int) – number of field periods
sym (Tristate) – True for cos(m*t-n*z) symmetry, False for sin(m*t-n*z) symmetry, None for no symmetry (Default)
- Returns
None
- change_resolution(M: int, N: int) → None[source]¶
Change resolution of the basis to the given resolutions. Overrides parent Basis object’s change_resolution method.
- Parameters
M (int) – maximum poloidal resolution
N (int) – maximum toroidal resolution
- Returns
None
- evaluate(nodes, derivatives=array([0, 0, 0]))[source]¶
Evaluates basis functions at specified nodes
- Parameters
nodes (ndarray of float, size(3,N)) – node coordinates, in (rho,theta,zeta)
derivatives (ndarray of int, shape(3,)) – order of derivatives to compute in (rho,theta,zeta)
- Returns
y (ndarray, shape(N,K)) – basis functions evaluated at nodes
- get_modes(M: int = 0, N: int = 0) → None[source]¶
Gets mode numbers for double fourier series
- Parameters
M (int) – maximum poloidal resolution
N (int) – maximum toroidal resolution
- Returns
modes (ndarray of int, shape(Nmodes,3)) – array of mode numbers [l,m,n] each row is one basis function with modes (l,m,n)
- class desc.basis.FourierZernikeBasis(L: int = - 1, M: int = 0, N: int = 0, NFP: int = 1, sym: Optional[desc.backend.Tristate] = None, index: str = 'ansi', load_from=None, file_format=None, obj_lib=None)[source]¶
3D basis set for analytic functions in a toroidal volume. Zernike polynomials in the radial & poloidal coordinates, and a Fourier series in the toroidal coordinate.
- __init__(L: int = - 1, M: int = 0, N: int = 0, NFP: int = 1, sym: Optional[desc.backend.Tristate] = None, index: str = 'ansi', load_from=None, file_format=None, obj_lib=None) → None[source]¶
Initializes a FourierZernikeBasis
- Parameters
L (int) – maximum radial resolution
M (int) – maximum poloidal resolution
N (int) – maximum toroidal resolution
NFP (int) – number of field periods
sym (Tristate) – True for cos(m*t-n*z) symmetry, False for sin(m*t-n*z) symmetry, None for no symmetry (Default)
index (str) – Indexing method, one of the following options: (‘ansi’,’frige’,’chevron’,’house’). For L=0, all methods are equivalent and give a “chevron” shaped basis (only the outer edge of the zernike pyramid of width M). For L>0, the indexing scheme defines order of the basis functions:
'ansi': ANSI indexing fills in the pyramid with triangles of decreasing size, ending in a triagle shape. The maximum L is M, at which point the traditional ANSI indexing is recovered. Gives a single mode at m=M, and multiple modes at l=L, from m=0 to m=l. Total number of modes = (M-(L//2)+1)*((L//2)+1)'fringe': Fringe indexing fills in the pyramid with chevrons of decreasing size, ending in a diamond shape. The maximum L is 2*M, for which the traditional fringe/U of Arizona indexing is recovered. Gives a single mode at m=M and a single mode at l=L and m=0. Total number of modes = (M+1)*(M+2)/2 - (M-L//2+1)*(M-L//2)/2'chevron': Beginning from the initial chevron of width M, increasing L adds additional chevrons of the same width. Similar to “house” but with fewer modes with high l and low m. Total number of modes = (M+1)*(2*(L//2)+1)'house': Fills in the pyramid row by row, with a maximum horizontal width of M and a maximum radial resolution of L. For L=M, it is equivalent to ANSI, while for L>M it takes on a “house” like shape. Gives multiple modes at m=M and l=L. (Default value = ‘ansi’)
- Returns
modes (ndarray of int, shape(Nmodes,3)) – array of mode numbers [l,m,n] each row is one basis function with modes (l,m,n)
- change_resolution(M: int, N: int, delta_lm: int) → None[source]¶
Change resolution of the basis to the given resolutions. Overrides parent Basis object’s change_resolution method.
- Parameters
M (int) – maximum poloidal resolution
N (int) – maximum toroidal resolution
delta_lm (int) – maximum difference between poloidal and radial resolution (l-m). If < 0, defaults to
Mfor ‘ansi’ or ‘chevron’ indexing, and2*Mfor ‘fringe’ or ‘house’. Unused for ‘fourier’ indexing.
- Returns
None
- evaluate(nodes, derivatives=array([0, 0, 0]))[source]¶
Evaluates basis functions at specified nodes
- Parameters
nodes (ndarray of float, size(3,N)) – node coordinates, in (rho,theta,zeta)
derivatives (ndarray of int, shape(3,)) – order of derivatives to compute in (rho,theta,zeta)
- Returns
y (ndarray, shape(N,K)) – basis functions evaluated at nodes
- get_modes(L: int = - 1, M: int = 0, N: int = 0, index: str = 'ansi')[source]¶
Gets mode numbers for Fourier-Zernike basis functions
- Parameters
L (int) – maximum radial resolution
M (int) – maximum poloidal resolution
N (int) – maximum toroidal resolution
index (str) – Indexing method, one of the following options: (‘ansi’,’frige’,’chevron’,’house’). For L=0, all methods are equivalent and give a “chevron” shaped basis (only the outer edge of the zernike pyramid of width M). For L>0, the indexing scheme defines order of the basis functions:
'ansi': ANSI indexing fills in the pyramid with triangles of decreasing size, ending in a triagle shape. The maximum L is M, at which point the traditional ANSI indexing is recovered. Gives a single mode at m=M, and multiple modes at l=L, from m=0 to m=l. Total number of modes = (M-(L//2)+1)*((L//2)+1)'fringe': Fringe indexing fills in the pyramid with chevrons of decreasing size, ending in a diamond shape. The maximum L is 2*M, for which the traditional fringe/U of Arizona indexing is recovered. Gives a single mode at m=M and a single mode at l=L and m=0. Total number of modes = (M+1)*(M+2)/2 - (M-L//2+1)*(M-L//2)/2'chevron': Beginning from the initial chevron of width M, increasing L adds additional chevrons of the same width. Similar to “house” but with fewer modes with high l and low m. Total number of modes = (M+1)*(2*(L//2)+1)'house': Fills in the pyramid row by row, with a maximum horizontal width of M and a maximum radial resolution of L. For L=M, it is equivalent to ANSI, while for L>M it takes on a “house” like shape. Gives multiple modes at m=M and l=L. (Default value = ‘ansi’)
- Returns
modes (ndarray of int, shape(Nmodes,3)) – array of mode numbers [l,m,n] each row is one basis function with modes (l,m,n)
- class desc.basis.PowerSeries(L: int = 0, load_from=None, file_format=None, obj_lib=None)[source]¶
1D basis set for flux surface quantities. Power series in the radial coordinate.
- __init__(L: int = 0, load_from=None, file_format=None, obj_lib=None) → None[source]¶
Initializes a PowerSeries
- Parameters
L (int) – maximum radial resolution
- Returns
None
- change_resolution(L: int) → None[source]¶
Change resolution of the basis to the given resolution. Overrides parent Basis object’s change_resolution method.
- Parameters
L (int) – maximum radial resolution
- Returns
None
- evaluate(nodes, derivatives=array([0, 0, 0]))[source]¶
Evaluates basis functions at specified nodes
- Parameters
nodes (ndarray of float, size(3,N)) – node coordinates, in (rho,theta,zeta)
derivatives (ndarray of int, shape(3,)) – order of derivatives to compute in (rho,theta,zeta)
- Returns
y (ndarray, shape(N,K)) – basis functions evaluated at nodes
- desc.basis.fourier(theta, m, NFP=1, dt=0)[source]¶
Fourier series
- Parameters
theta (ndarray, shape(N,)) – poloidal/toroidal coordinates to evaluate basis
m (ndarray of int, shape(K,)) – poloidal/toroidal mode number(s)
NFP (int) – number of field periods (Default = 1)
dt (int) – order of derivative (Default = 0)
- Returns
y (ndarray, shape(N,K)) – basis function(s) evaluated at specified points
- desc.basis.jacobi(rho, l, m, dr=0)[source]¶
Jacobi polynomials
- Parameters
rho (ndarray, shape(N,)) – radial coordiantes to evaluate basis
l (ndarray of int, shape(K,)) – radial mode number(s)
m (ndarray of int, shape(K,)) – azimuthal mode number(s)
dr (int) – order of derivative (Default = 0)
- Returns
y (ndarray, shape(N,K)) – basis function(s) evaluated at specified points
- desc.basis.jacobi_coeffs(l, m)[source]¶
Jacobi polynomials
- Parameters
l (ndarray of int, shape(K,)) – radial mode number(s)
m (ndarray of int, shape(K,)) – azimuthal mode number(s)
- Returns
coeffs (ndarray)
- desc.basis.polyder_vec(p, m)[source]¶
Vectorized version of polyder for differentiating multiple polynomials of the same degree
- Parameters
p (ndarray, shape(N,M)) – polynomial coefficients. Each row is 1 polynomial, in descending powers of x, each column is a power of x
m (int >=0) – order of derivative
- Returns
der (ndarray, shape(N,M)) – polynomial coefficients for derivative in descending order
- desc.basis.polyval_vec(p, x)[source]¶
Evaluate a polynomial at specific values, vectorized for evaluating multiple polynomials of the same degree.
- Parameters
p (ndarray, shape(N,M)) – Array of coefficient for N polynomials of order M. Each row is one polynomial, given in descending powers of x.
x (ndarray, shape(K,)) – A number, or 1d array of numbers at which to evaluate p. If greater than 1d it is flattened.
- Returns
y (ndarray, shape(N,K)) – polynomials evaluated at x. Each row corresponds to a polynomial, each column to a value of x
Notes – Horner’s scheme is used to evaluate the polynomial. Even so, for polynomials of high degree the values may be inaccurate due to rounding errors. Use carefully.
- desc.basis.power_coeffs(l)[source]¶
Power series
- Parameters
l (ndarray of int, shape(K,)) – radial mode number(s)
- Returns
coeffsy (ndarray, shape(l+1,))
- desc.basis.powers(rho, l, dr=0)[source]¶
Power series
- Parameters
rho (ndarray, shape(N,)) – radial coordiantes to evaluate basis
l (ndarray of int, shape(K,)) – radial mode number(s)
dr (int) – order of derivative (Default = 0)
- Returns
y (ndarray, shape(N,K)) – basis function(s) evaluated at specified points
Boundary Conditions¶
- desc.boundary_conditions.compute_bdry_err(cR, cZ, cL, cRb, cZb, R1_transform, Z1_transform, L_transform, bdry_ratio)[source]¶
Compute boundary error in (theta,phi) Fourier coefficients from non-uniform interpolation grid
- Parameters
cR (ndarray, shape(RZ_transform.num_modes,)) – spectral coefficients of R
cZ (ndarray, shape(RZ_transform.num_modes,)) – spectral coefficients of Z
cL (ndarray, shape(L_transform.num_modes,)) – spectral coefficients of lambda
cRb (ndarray, shape(bdry_basis.num_modes,)) – spectral coefficients of R boundary
cZb (ndarray, shape(bdry_basis.num_modes,)) – spectral coefficients of Z boundary
bdry_ratio (float) – fraction in range [0,1] of the full non-axisymmetric boundary to use
R1_transform (Transform) – transforms cR to physical space at the boundary
Z1_transform (Transform) – transforms cZ to physical space at the boundary
L_transform (Transform) – transforms cL to physical space
- Returns
errR (ndarray, shape(N_bdry_pts,)) – vector of R errors in boundary spectral coeffs
errZ (ndarray, shape(N_bdry_pts,)) – vector of Z errors in boundary spectral coeffs
- desc.boundary_conditions.compute_bdry_err_sfl(cR, cZ, cL, cRb, cZb, RZ_transform, L_transform, bdry_transform, bdry_ratio)[source]¶
Compute boundary error in (theta,phi) Fourier coefficients from non-uniform interpolation grid
- Parameters
cR (ndarray, shape(RZ_transform.num_modes,)) – spectral coefficients of R
cZ (ndarray, shape(RZ_transform.num_modes,)) – spectral coefficients of Z
cL (ndarray, shape(L_transform.num_modes,)) – spectral coefficients of lambda
cRb (ndarray, shape(bdry_basis.num_modes,)) – spectral coefficients of R boundary
cZb (ndarray, shape(bdry_basis.num_modes,)) – spectral coefficients of Z boundary
bdry_ratio (float) – fraction in range [0,1] of the full non-axisymmetric boundary to use
RZ_transform (Transform) – transforms cR and cZ to physical space
L_transform (Transform) – transforms cL to physical space
bdry_transform (Transform) – transforms cRb and cZb to physical space
- Returns
errR (ndarray, shape(N_bdry_pts,)) – vector of R errors in boundary spectral coeffs
errZ (ndarray, shape(N_bdry_pts,)) – vector of Z errors in boundary spectral coeffs
- desc.boundary_conditions.compute_lambda_err(cL, L_basis: desc.basis.DoubleFourierSeries)[source]¶
Computes the error in the constraint lambda(t=0, p=0) = 0
- Parameters
cL (ndarray, shape(L_basis.num_modes)) – lambda spectral coefficients
L_basis (DoubleFourierSeries) – indices for lambda spectral basis, ie an array of [m,n] for each spectral coefficient
- Returns
errL (float) – sum of cL_mn where m, n > 0
- desc.boundary_conditions.format_bdry(bdry, Rb_basis: desc.basis.DoubleFourierSeries, Zb_basis: desc.basis.DoubleFourierSeries, mode: str = 'spectral')[source]¶
Formats arrays for boundary conditions and converts between real space and fourier representations
- Parameters
bdry (ndarray, shape(Nbdry,4)) – array of fourier coeffs [m,n,Rcoeff, Zcoeff] or array of real space coordinates, [theta,phi,R,Z]
Rb_basis (DoubleFourierSeries) – spectral basis for R boundary coefficients
Zb_basis (DoubleFourierSeries) – spectral basis for Z boundary coefficients
mode (str) – one of ‘real’, ‘spectral’. Whether bdry is specified in real or spectral space.
- Returns
cRb (ndarray) – spectral coefficients for R boundary
cZb (ndarray) – spectral coefficients for Z boundary
- desc.boundary_conditions.get_lambda_constraint_matrix(zern_idx, lambda_idx)[source]¶
Computes a linear constraint matrix to enforce vartheta = 0 at theta=0. We require sum(lambda_mn) = 0, expressed in matrix for as Cx = 0
- Parameters
zern_idx (ndarray, shape(N_coeffs,3)) – indices for R,Z spectral basis, ie an array of [l,m,n] for each spectral coefficient
lambda_idx (ndarray, shape(Nlambda,2)) – indices for lambda spectral basis, ie an array of [m,n] for each spectral coefficient
- Returns
C (ndarray, shape(2*N_coeffs + Nlambda,)) – linear constraint matrix, so
np.matmul(C,x)is the error in the lambda constraint
Configuration¶
- class desc.configuration.Configuration(inputs: Optional[dict] = None, load_from=None, file_format: str = 'hdf5', obj_lib=None)[source]¶
Configuration contains information about a plasma state, including the shapes of flux surfaces and profile inputs. It can compute additional information, such as the magnetic field and plasma currents.
- property I_basis: desc.basis.Basis¶
Spectral basis for iota
- Returns
Basis
- property L_basis: desc.basis.Basis¶
Spectral basis for L
- Returns
Basis
- property NFP: int¶
int, number of field periods
- property P_basis: desc.basis.Basis¶
Spectral basis for pressure
- Returns
Basis
- property Psi: float¶
float, total toroidal flux (in Webers) within LCFS
- property R_basis: desc.basis.Basis¶
Spectral basis for R
- Returns
Basis
- property Rb_basis: desc.basis.Basis¶
Spectral basis for R at the boundary
- Returns
Basis
- property Z_basis: desc.basis.Basis¶
Spectral basis for Z
- Returns
Basis
- property Zb_basis: desc.basis.Basis¶
Spectral basis for Z at the boundary
- Returns
Basis
- __init__(inputs: Optional[dict] = None, load_from=None, file_format: str = 'hdf5', obj_lib=None) → None[source]¶
Initializes a Configuration
- Parameters
inputs (dict) – dict containing keys necessary to define a Configuration. Necessary keys are defined in _init_from_inputs. If None, will attempt to load Configuration from given input file.
load_from (str file path OR file instance) – file to initialize from
file_format (str) – file format of file initializing from. Default is ‘hdf5’
- Returns
None
- property cI¶
spectral coefficients of iota
- property cL¶
spectral coefficients of L
- property cP¶
spectral coefficients of pressure
- property cR¶
spectral coefficients of R
- property cRb¶
spectral coefficients of R at the boundary
- property cZ¶
spectral coefficients of Z
- property cZb¶
spectral coefficients of Z at the boundary
- change_resolution(L: Optional[int] = None, M: Optional[int] = None, N: Optional[int] = None) → None[source]¶
- compute_contravariant_basis(grid: desc.grid.Grid) → dict[source]¶
Computes contravariant basis vectors and jacobian elements by calling
desc.configuration.compute_contravariant_basis()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to find the contravariant basis vectors and the jacobian elements.
- Returns
con_basis (dict) – dictionary of ndarray containing contravariant basis vectors and jacobian elements
- compute_coordinate_derivatives(grid: desc.grid.Grid) → dict[source]¶
Converts from spectral to real space and evaluates derivatives of R,Z wrt to SFL coords by calling
desc.configuration.compute_coordinate_derivatives()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to evaluate derivatives.
- Returns
coord_der (dict) – dictionary of ndarray, shape(N_nodes,) of coordinate derivatives evaluated at node locations. keys are of the form ‘X_y’ meaning the derivative of X wrt to y
- compute_coordinates(grid: desc.grid.Grid) → dict[source]¶
Converts from spectral to real space by calling
desc.configuration.compute_coordinates()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to evaluate R and Z.
- Returns
coords (dict) – dictionary of ndarray, shape(N_nodes,) of coordinates evaluated at node locations. keys are of the form ‘X_y’ meaning the derivative of X wrt to y
- compute_covariant_basis(grid: desc.grid.Grid) → dict[source]¶
Computes covariant basis vectors at grid points by calling
desc.configuration.compute_covariant_basis()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to find the covariant basis vectors.
- Returns
cov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node. Keys are of the form ‘e_x_y’, meaning the unit vector in the x direction, differentiated wrt to y.
- compute_force_magnitude(grid: desc.grid.Grid) → dict[source]¶
Computes force error magnitude at node locations by calling
desc.configuration.compute_force_magnitude()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to evaluate the force error magnitudes
- Returns
force_mag (dict) – dictionary of ndarray, shape(N_nodes,) of force magnitudes
- compute_jacobian(grid: desc.grid.Grid) → dict[source]¶
Computes coordinate jacobian and derivatives by calling
desc.configuration.compute_jacobian()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to find the coordinate jacobian elements and its partial derivatives.
- Returns
jacobian (dict) – dictionary of ndarray, shape(N_nodes,) of coordinate jacobian and partial derivatives. Keys are of the form g_x meaning the x derivative of the coordinate jacobian g
- compute_magnetic_field(grid: desc.grid.Grid) → dict[source]¶
Computes magnetic field components at node locations by calling
desc.configuration.compute_magnetic_field()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to evaluate the magnetic field components
- Returns
magnetic_field (dict) – dictionary of ndarray, shape(N_nodes,) of magnetic field and derivatives. Keys are of the form ‘B_x_y’ or ‘B^x_y’, meaning the covariant (B_x) or contravariant (B^x) component of the magnetic field, with the derivative wrt to y.
- compute_magnetic_field_magnitude(grid: desc.grid.Grid) → dict[source]¶
Computes magnetic field magnitude at node locations by calling
desc.configuration.compute_magnetic_field_magnitude()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to evaluate the magnetic field magnitude and derivatives
- Returns
magnetic_field_mag (dict) – dictionary of ndarray, shape(N_nodes,) of magnetic field magnitude and derivatives
- compute_plasma_current(grid: desc.grid.Grid) → dict[source]¶
Computes current density field at node locations by calling
desc.configuration.compute_plasma_current()- Parameters
grid (Grid) – Collocation grid containing the (rho, theta, zeta) coordinates of the nodes at which to evaluate the plasma current components
- Returns
plasma_current (dict) – dictionary of ndarray, shape(N_nodes,) of current field. Keys are of the form ‘J^x_y’ meaning the contravariant (J^x) component of the current, with the derivative wrt to y.
- property sym: bool¶
- property x¶
- class desc.configuration.EquilibriaFamily(inputs=None, load_from=None, file_format='hdf5')[source]¶
EquilibriaFamily stores a list of Equilibria
- property equilibria¶
- save(save_to=None, file_format=None) → None[source]¶
Save the object.
- Parameters
save_to (str file path OR file instance) – location to save object
file_format (str (Default hdf5)) – format of save file. Only used if save_to is a file path
file_mode (str (Default w - overwrite)) – mode for save file. Only used if save_to is a file path
- Returns
None
- property solver¶
- class desc.configuration.Equilibrium(inputs: Optional[dict] = None, load_from=None, file_format: str = 'hdf5', obj_lib=None)[source]¶
Equilibrium is a decorator design pattern on top of Configuration. It adds information about how the equilibrium configuration was solved.
- property initial: desc.configuration.Configuration¶
- property objective¶
- property optimizer¶
- property solved: bool¶
Boolean, if the Equilibrium has been solved or not
- property x¶
- desc.configuration.compute_contravariant_basis(coord_der, cov_basis, jacobian, axis=DeviceArray([], dtype=float64))[source]¶
Computes contravariant basis vectors and jacobian elements
- Parameters
coord_der (dict) – dictionary of ndarray containing coordinate derivatives evaluated at node locations, such as computed by
compute_coordinate_derivativescov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node, such as computed by
compute_covariant_basisjacobian (dict) – dictionary of ndarray containing coordinate jacobian and partial derivatives, such as computed by
compute_jacobianaxis : ndarray, optional indicies of axis nodesaxis (ndarray, optional) – indicies of axis nodes
- Returns
con_basis (dict) – dictionary of ndarray containing contravariant basis vectors and jacobian elements
- desc.configuration.compute_coordinate_derivatives(cR, cZ, R_transform, Z_transform, zeta_ratio=1.0)[source]¶
Converts from spectral to real space and evaluates derivatives of R,Z wrt to SFL coords
- Parameters
cR (ndarray) – spectral coefficients of R
cZ (ndarray) – spectral coefficients of Z
R_transform (Transform) – transforms R coefficients to real space
Z_transform (Transform) – transforms Z coefficients to real space
zeta_ratio (float) – scale factor for zeta derivatives. Setting to zero effectively solves for individual tokamak solutions at each toroidal plane, setting to 1 solves for a stellarator. (Default value = 1.0)
- Returns
coord_der (dict) – dictionary of ndarray, shape(N_nodes,) of coordinate derivatives evaluated at node locations. keys are of the form ‘X_y’ meaning the derivative of X wrt to y
- desc.configuration.compute_coordinates(cR, cZ, R_transform, Z_transform)[source]¶
Converts from spectral to real space
- Parameters
- Returns
coords (dict) – dictionary of ndarray, shape(N_nodes,) of coordinates evaluated at node locations. keys are of the form ‘X_y’ meaning the derivative of X wrt to y
- desc.configuration.compute_covariant_basis(coord_der, axis=DeviceArray([], dtype=float64), derivs='force')[source]¶
Computes covariant basis vectors at grid points
- Parameters
coord_der (dict) – dictionary of ndarray containing the coordinate derivatives at each node, such as computed by
compute_coordinate_derivativesaxis (ndarray, optional) – indicies of axis nodes
derivs (str) – type of calculation being performed
'force': all of the derivatives needed to calculate an equilibrium from the force balance equations'qs': all of the derivatives needed to calculate quasi- symmetry from the triple-product equation
- Returns
cov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node. Keys are of the form ‘e_x_y’, meaning the unit vector in the x direction, differentiated wrt to y.
- desc.configuration.compute_force_magnitude(coord_der, cov_basis, con_basis, jacobian, magnetic_field, plasma_current, cP, P_transform)[source]¶
Computes force error magnitude at node locations
- Parameters
coord_der (dict) – dictionary of ndarray containing of coordinate derivatives evaluated at node locations, such as computed by
compute_coordinate_derivatives.cov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node, such as computed by
compute_covariant_basis.con_basis (dict) – dictionary of ndarray containing contravariant basis vectors and metric elements at each node, such as computed by
compute_contravariant_basis.jacobian (dict) – dictionary of ndarray containing coordinate jacobian and partial derivatives, such as computed by
compute_jacobian.magnetic_field (dict) – dictionary of ndarray containing magnetic field and derivatives, such as computed by
compute_magnetic_field.plasma_current (dict) – dictionary of ndarray containing current and derivatives, such as computed by
compute_plasma_current.cP (ndarray) – parameters to pass to pressure function
Psi_lcfs (float) – total toroidal flux (in Webers) within LCFS
P_transform (Transform) – object with transform method to go from spectral to physical space with derivatives
- Returns
force_mag (dict) – dictionary of ndarray, shape(N_nodes,) of force magnitudes
- desc.configuration.compute_jacobian(coord_der, cov_basis, axis=DeviceArray([], dtype=float64), derivs='force')[source]¶
Computes coordinate jacobian and derivatives
- Parameters
coord_der (dict) – dictionary of ndarray containing of coordinate derivatives evaluated at node locations, such as computed by
compute_coordinate_derivatives.cov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node, such as computed by
compute_covariant_basis.axis (ndarray, optional) – indicies of axis nodes
derivs (str) – type of calculation being performed
'force': all of the derivatives needed to calculate an equilibrium from the force balance equations'qs': all of the derivatives needed to calculate quasi- symmetry from the triple-product equation
- Returns
jacobian (dict) – dictionary of ndarray, shape(N_nodes,) of coordinate jacobian and partial derivatives. Keys are of the form g_x meaning the x derivative of the coordinate jacobian g
- desc.configuration.compute_magnetic_field(cov_basis, jacobian, cI, Psi, I_transform, derivs='force')[source]¶
Computes magnetic field components at node locations
- Parameters
cov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node, such as computed by
compute_covariant_basis.jacobian (dict) – dictionary of ndarray containing coordinate jacobian and partial derivatives, such as computed by
compute_jacobian.cI (ndarray) – coefficients to pass to rotational transform function
Psi (float) – total toroidal flux (in Webers) within LCFS
I_transform (Transform) – object with transform method to go from spectral to physical space with derivatives
derivs (str) – type of calculation being performed
'force': all of the derivatives needed to calculate an equilibrium from the force balance equations'qs': all of the derivatives needed to calculate quasi- symmetry from the triple-product equation
- Returns
magnetic_field (dict) – dictionary of ndarray, shape(N_nodes,) of magnetic field and derivatives. Keys are of the form ‘B_x_y’ or ‘B^x_y’, meaning the covariant (B_x) or contravariant (B^x) component of the magnetic field, with the derivative wrt to y.
- desc.configuration.compute_magnetic_field_magnitude(cov_basis, magnetic_field, cI, I_transform, derivs='force')[source]¶
Computes magnetic field magnitude at node locations
- Parameters
cov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node, such as computed by
compute_covariant_basis.magnetic_field (dict) – dictionary of ndarray containing magnetic field and derivatives, such as computed by
compute_magnetic_field.cI (ndarray) – coefficients to pass to rotational transform function
I_transform (Transform) – object with transform method to go from spectral to physical space with derivatives
derivs (str) – type of calculation being performed
'force': all of the derivatives needed to calculate an equilibrium from the force balance equations'qs': all of the derivatives needed to calculate quasi- symmetry from the triple-product equation
- Returns
magnetic_field_mag (dict) – dictionary of ndarray, shape(N_nodes,) of magnetic field magnitude and derivatives
- desc.configuration.compute_plasma_current(coord_der, cov_basis, jacobian, magnetic_field, cI, I_transform)[source]¶
Computes current density field at node locations
- Parameters
cov_basis (dict) – dictionary of ndarray containing covariant basis vectors and derivatives at each node, such as computed by
compute_covariant_basis.jacobian (dict) – dictionary of ndarray containing coordinate jacobian and partial derivatives, such as computed by
compute_jacobian.coord_der (dict) – dictionary of ndarray containing of coordinate derivatives evaluated at node locations, such as computed by
compute_coordinate_derivatives.magnetic_field (dict) – dictionary of ndarray containing magnetic field and derivatives, such as computed by
compute_magnetic_field.cI (ndarray) – coefficients to pass to rotational transform function.
I_transform (Transform) – object with transform method to go from spectral to physical space with derivatives
- Returns
plasma_current (dict) – dictionary of ndarray, shape(N_nodes,) of current field. Keys are of the form ‘J^x_y’ meaning the contravariant (J^x) component of the current, with the derivative wrt to y.
- desc.configuration.unpack_state(x, nR, nZ)[source]¶
Unpacks the optimization state vector x into cR, cZ, cL components
- Parameters
x (ndarray) – vector to unpack: x = [cR, cZ, cL]
nR (int) – number of cR coefficients
nZ (int) – number of cZ coefficients
- Returns
cR (ndarray) – spectral coefficients of R
cZ (ndarray) – spectral coefficients of Z
cL (ndarray) – spectral coefficients of lambda
Continuation¶
- desc.continuation.solve_eq_continuation(inputs, checkpoint_filename=None, device=None)[source]¶
Solves for an equilibrium by continuation method
- Follows this procedure to solve the equilibrium:
Creates an initial guess from the given inputs
- Optimizes the equilibrium’s flux surfaces by minimizing
the given objective function.
Step up to higher resolution and perturb the previous solution
Repeat 2 and 3 until at desired resolution
- Parameters
inputs (dict) – dictionary with input parameters defining problem setup and solver options
checkpoint_filename (str or path-like) – file to save checkpoint data (Default value = None)
device (jax.device or None) – device handle to JIT compile to (Default value = None)
- Returns
equil_fam (EquilibriaFamily) –
- Container object that contains a list of the intermediate solutions,
as well as the final solution, stored as Equilibrium objects
timer (Timer) – Timer object containing timing data for individual iterations
Equilibrium IO¶
- class desc.equilibrium_io.Checkpoint(filename, write_ascii=False)[source]¶
Class for periodically saving equilibria during solution
- Parameters
filename (str or path-like) – file to write to. If it does not exist, it will be created
write_ascii (bool) – Whether to also write ascii files. By default, only an hdf5 file is created and appended with each new solution. If write_ascii is True, additional files will be written, each with the same base filename but appeneded with _0, _1,…
- Returns
checkpointer (Checkpoint) – object with methods to periodically save solutions
- write_iteration(equilibrium, iter_num, inputs=None, update_final=True)[source]¶
Write an equilibrium to the checkpoint file
- Parameters
equilibrium (dict) – equilibrium to write
iter_num (int) – iteration number
inputs (dict, optional) – dictionary of input parameters to the solver (Default value = None)
update_final (bool) – whether to update the ‘final’ equilibrium with this entry (Default value = True)
- class desc.equilibrium_io.IO[source]¶
Abstract Base Class (ABC) for readers and writers.
- __del__()[source]¶
Close file upon garbage colleciton or explicit deletion with del function.
- Returns
None
- class desc.equilibrium_io.IOAble[source]¶
Abstract Base Class for savable and loadable objects.
- save(save_to, file_format='hdf5', file_mode='w')[source]¶
Save the object.
- Parameters
save_to (str file path OR file instance) – location to save object
file_format (str (Default hdf5)) – format of save file. Only used if save_to is a file path
file_mode (str (Default w - overwrite)) – mode for save file. Only used if save_to is a file path
- Returns
None
- class desc.equilibrium_io.PickleReader(target)[source]¶
Class specifying a reader with PickleIO.
- __init__(target)[source]¶
Initialize hdf5Reader class.
- Parameters
target (str or file instance) – Path to file OR file instance to be read.
- Returns
None
- class desc.equilibrium_io.PickleWriter(target, file_mode='w')[source]¶
Class specifying a writer with PickleIO.
- __init__(target, file_mode='w')[source]¶
Initializes PickleWriter class.
- Parameters
target (str or file instance) – path OR file instance to write to
file_mode (str) – mode used when opening file.
- Returns
None
- class desc.equilibrium_io.hdf5IO[source]¶
Class to wrap ABC IO for hdf5 file format.
- groups(where=None)[source]¶
Finds groups in location given by ‘where’.
- Parameters
where (None or file instance) –
- Returns
groups (list)
- class desc.equilibrium_io.hdf5Reader(target)[source]¶
Class specifying a Reader with hdf5IO.
- __init__(target)[source]¶
Initialize hdf5Reader class.
- Parameters
target (str or file instance) – Path to file OR file instance to be read.
- Returns
None
- read_dict(thedict=None, where=None)[source]¶
Read dictionary from file in group specified by where argument.
- Parameters
thedict (dictionary (Default None)) – dictionary to update from the file
where (None or file instance) – specifies where to read dict from
- Returns
None
- read_list(thelist=None, where=None)[source]¶
Read list from file in group specified by where argument.
- Parameters
thelist (list (Default None)) – list to update from the file
where (None or file instance) – specifies wehre to read dict from
- Returns
None
- read_obj(obj, where=None, obj_lib=None)[source]¶
Read object from file in group specified by where argument.
- Parameters
obj (python object instance) – object must have _save_attrs_ attribute to have attributes read and loaded
where (None or file insance) – specifies where to read obj from
- Returns
None
- class desc.equilibrium_io.hdf5Writer(target, file_mode='w')[source]¶
Class specifying a writer with hdf5IO.
- __init__(target, file_mode='w')[source]¶
Initializes hdf5Writer class.
- Parameters
target (str or file instance) – path OR file instance to write to
file_mode (str) – mode used when opening file.
- Returns
None
- write_dict(thedict, where=None)[source]¶
Write dictionary to file in group specified by where argument.
- Parameters
thedict (dictionary) – dictionary to write to file
where (None or file instance) – specifies where to write dict to
- Returns
None
- desc.equilibrium_io.output_to_file(fname, equil)[source]¶
Prints the equilibrium solution to a text file
- Parameters
fname (str or path-like) – filename of output file.
equil (dict) – dictionary of equilibrium parameters.
- desc.equilibrium_io.read_desc(filename)[source]¶
reads a previously generated DESC ascii output file
- Parameters
filename (str or path-like) – path to file to read
- Returns
equil (dict) – dictionary of equilibrium parameters.
- desc.equilibrium_io.reader_factory(load_from, file_format)[source]¶
Select and return instance of appropriate reader class for given file format.
- Parameters
load_from (str or file instance) – file path or instance from which to read
file_format (str) – format of file to be read
- Returns
Reader instance
- desc.equilibrium_io.vmec_to_desc_input(vmec_fname, desc_fname)[source]¶
Converts a VMEC input file to an equivalent DESC input file
- Parameters
vmec_fname (str or path-like) – filename of VMEC input file
desc_fname (str or path-like) – filename of DESC input file. If it already exists it is overwritten.
- desc.equilibrium_io.write_desc_h5(filename, equilibrium)[source]¶
Writes a DESC equilibrium to a hdf5 format binary file
- Parameters
filename (str or path-like) – file to write to. If it doesn’t exist, it is created.
equilibrium (dict) – dictionary of equilibrium parameters.
- desc.equilibrium_io.write_hdf5(obj, save_to, file_mode='w')[source]¶
Writes attributes of obj from obj._save_attrs_ list to an hdf5 file.
- Parameters
obj (object to save) – must have _save_attrs_ list attribute. Otherwise AttributeError raised.
save_loc (str or path-like; hdf5 file or group) – file or group to write to. If str or path-like, file is created. If hdf5 file or group instance, datasets are created there.
file_mode='w' (str) – hdf5 file mode. Default is ‘w’.
- desc.equilibrium_io.writer_factory(save_to, file_format, file_mode='w')[source]¶
Select and return instance of appropriate reader class for given file format.
- Parameters
load_from (str or file instance) – file path or instance from which to read
file_format (str) – format of file to be read
- Returns
Reader instance
Grid¶
- class desc.grid.ConcentricGrid(M: int, N: int, NFP: int = 1, sym: bool = False, axis: bool = True, index='ansi', surfs='cheb1', load_from=None, file_format=None, obj_lib=None)[source]¶
ConcentricGrid is a collocation grid in which the nodes are arranged in concentric circles within each toroidal cross-section.
- __init__(M: int, N: int, NFP: int = 1, sym: bool = False, axis: bool = True, index='ansi', surfs='cheb1', load_from=None, file_format=None, obj_lib=None) → None[source]¶
Initializes a ConcentricGrid
- Parameters
M (int) – poloidal grid resolution
N (int) – toroidal grid resolution
NFP (int) – number of field periods (Default = 1)
sym (bool) – True for stellarator symmetry, False otherwise (Default = False)
axis (bool) – True to include the magnetic axis, False otherwise (Default = True)
index (string) –
- Zernike indexing scheme
ansi (Default), chevron, fringe, house
surfs (string) –
- pattern for radial coordinates
cheb1 = Chebyshev-Gauss-Lobatto nodes scaled to r=[0,1] cheb2 = Chebyshev-Gauss-Lobatto nodes scaled to r=[-1,1] anything else defaults to linear spacing in r=[0,1]
- Returns
None
- change_resolution(M: int, N: int) → None[source]¶
- Parameters
M (int) – new poloidal grid resolution
N (int) – new toroidal grid resolution
- Returns
None
- create_nodes(M: int, N: int, NFP: int = 1, axis: bool = True, index='ansi', surfs='cheb1')[source]¶
- Parameters
M (int) – poloidal grid resolution
N (int) – toroidal grid resolution
NFP (int) – number of field periods (Default = 1)
axis (bool) – True to include the magnetic axis, False otherwise (Default = True)
index (string) –
- Zernike indexing scheme
ansi (Default), chevron, fringe, house
surfs (string) –
- pattern for radial coordinates
cheb1 = Chebyshev-Gauss-Lobatto nodes scaled to r=[0,1] cheb2 = Chebyshev-Gauss-Lobatto nodes scaled to r=[-1,1] anything else defaults to linear spacing in r=[0,1]
- Returns
nodes (ndarray of float, size(3,Nnodes)) – node coordinates, in (rho,theta,zeta)
volumes (ndarray of float, size(3,Nnodes)) – node spacing (drho,dtheta,dzeta) at each node coordinate
- class desc.grid.Grid(nodes, load_from=None, file_format=None, obj_lib=None)[source]¶
Grid is a base class for collocation grids
- property L: int¶
radial grid resolution
- Type
int
- property M: int¶
poloidal grid resolution
- Type
int
- property N: int¶
toroidal grid resolution
- Type
int
- property NFP: int¶
number of field periods
- Type
int
- __eq__(other) → bool[source]¶
Overloads the == operator
- Parameters
other (Grid) – another Grid object to compare to
- Returns
bool – True if other is a Grid with the same attributes as self False otherwise
- __init__(nodes, load_from=None, file_format=None, obj_lib=None) → None[source]¶
Initializes a custom grid without a pre-defined pattern
- Parameters
nodes (ndarray of float, size(3,Nnodes)) – node coordinates, in (rho,theta,zeta)
- Returns
None
- property axis¶
- create_nodes(nodes)[source]¶
Allows for custom node creation
- Parameters
nodes (ndarray of float, size(3,Nnodes)) – node coordinates, in (rho,theta,zeta)
- Returns
nodes (ndarray of float, size(3,Nnodes)) – node coordinates, in (rho,theta,zeta)
- property nodes¶
array of float, size(3,Nnodes): node coordinates, in (rho,theta,zeta)
- Type
ndarray
- property num_nodes¶
total number of nodes
- Type
int
- property sym: bool¶
True for stellarator symmetry, False otherwise (Default = False)
- Type
bool
- property volumes¶
array of float, size(3,Nnodes): node spacing (drho,dtheta,dzeta) at each node coordinate
- Type
ndarray
- class desc.grid.LinearGrid(L: int = 1, M: int = 1, N: int = 1, NFP: int = 1, sym: bool = False, endpoint: bool = False, rho=array([1.0]), theta=array([1.0]), zeta=array([1.0]), load_from=None, file_format=None, obj_lib=None)[source]¶
LinearGrid is a collocation grid in which the nodes are linearly spaced in each coordinate.
- __init__(L: int = 1, M: int = 1, N: int = 1, NFP: int = 1, sym: bool = False, endpoint: bool = False, rho=array([1.0]), theta=array([1.0]), zeta=array([1.0]), load_from=None, file_format=None, obj_lib=None) → None[source]¶
Initializes a LinearGrid
- Parameters
L (int) – radial grid resolution (L radial nodes, Defualt = 1)
M (int) – poloidal grid resolution (M poloidal nodes, Default = 1)
N (int) – toroidal grid resolution (N toroidal nodes, Default = 1)
NFP (int) – number of field periods (Default = 1)
sym (bool) – True for stellarator symmetry, False otherwise (Default = False)
endpoint (bool) – if True, theta=0 and zeta=0 are duplicated after a full period. Should be False for use with FFT (Default = False)
rho (ndarray of float) – radial coordinates (if L == rho.size)
theta (ndarray of float) – poloidal coordinates (if M == theta.size)
zeta (ndarray of float) – toroidal coordinates (if N == zeta.size)
- Returns
None
- change_resolution(L: int, M: int, N: int) → None[source]¶
- Parameters
L (int) – new radial grid resolution (L radial nodes)
M (int) – new poloidal grid resolution (2*M+1 poloidal nodes)
N (int) – new toroidal grid resolution (2*N+1 toroidal nodes)
- Returns
None
- create_nodes(L: int = 1, M: int = 1, N: int = 1, NFP: int = 1, endpoint: bool = False, rho=array([1.0]), theta=array([1.0]), zeta=array([1.0]))[source]¶
- Parameters
L (int) – radial grid resolution (L radial nodes, Defualt = 1)
M (int) – poloidal grid resolution (M poloidal nodes, Default = 1)
N (int) – toroidal grid resolution (N toroidal nodes, Default = 1)
NFP (int) – number of field periods (Default = 1)
endpoint (bool) – if True, theta=0 and zeta=0 are duplicated after a full period. Should be False for use with FFT (Default = False)
rho (ndarray of float) – radial coordinates (if L == rho.size)
theta (ndarray of float) – poloidal coordinates (if M == theta.size)
zeta (ndarray of float) – toroidal coordinates (if N == zeta.size)
- Returns
nodes (ndarray of float, size(3,Nnodes)) – node coordinates, in (rho,theta,zeta)
volumes (ndarray of float, size(3,Nnodes)) – node spacing (drho,dtheta,dzeta) at each node coordinate
- desc.grid.cf_to_dec(cf)[source]¶
Compute decimal form of a continued fraction.
- Parameters
cf (array-like) – coefficients of continued fraction.
- Returns
x (float) – floating point representation of cf
- desc.grid.dec_to_cf(x, dmax=6)[source]¶
Compute continued fraction form of a number.
- Parameters
x (float) – floating point form of number
dmax (int) – maximum iterations (ie, number of coefficients of continued fraction). (Default value = 6)
- Returns
cf (ndarray of int) – coefficients of continued fraction form of x.
Initial Guess¶
- desc.init_guess.get_initial_guess_scale_bdry(axis, bdry, bdry_ratio, R_basis: desc.basis.FourierZernikeBasis, Z_basis: desc.basis.FourierZernikeBasis)[source]¶
Generate initial guess by scaling boundary shape
- Parameters
axis (ndarray, shape(Naxis,3)) – array of axis Fourier coeffs [n,Rcoeff, Zcoeff]
bdry (ndarray, shape(Nbdry,4)) – array of boundary Fourier coeffs [m,n,Rcoeff, Zcoeff] OR array of real space coordinates, [theta,phi,R,Z]
bdry_ratio (float) – fraction in range [0,1] of the full non-axisymmetric boundary to use
R_basis (FourierZernikeBasis) – DESCRIPTION
Z_basis (FourierZernikeBasis) – DESCRIPTION
- Returns
cR (ndarray, shape(N_coeffs,)) – Fourier-Zernike coefficients for R, following indexing given in zern_idx
cZ (ndarray, shape(N_coeffs,)) – Fourier-Zernike coefficients for Z, following indexing given in zern_idx
Input Reader¶
- class desc.input_reader.InputReader(cl_args=None)[source]¶
Reads command line arguments and parses input files.
- Parameters
(optional) (cl_args) – explicit command line arguments
- args¶
parsed namespace of all command line arguments
- Type
Namespace
- inputs¶
dictionary of values from input file
- Type
dict
- input_path¶
path to input file
- Type
string
- output_path¶
path to output file
- Type
string
- __init__(cl_args=None)[source]¶
Initialize InputReader instance.
- Parameters
cl_args (None or list (Default = None)) – command line arguments to parse. Default (=None) is to use command line arguments from sys.argv.
- Returns
None
- parse_args(cl_args=None)[source]¶
Parse command line arguments.
- Parameters
cl_args (None or list (Default = None)) – command line arguments to parse. Default (=None) is to use command line arguments from sys.argv.
- Returns
args (namespace) – parsed arguments
Objective Functions¶
- class desc.objective_funs.AccelErrorSpectral(scalar: bool = False, R_transform: Optional[desc.transform.Transform] = None, Z_transform: Optional[desc.transform.Transform] = None, R1_transform: Optional[desc.transform.Transform] = None, Z1_transform: Optional[desc.transform.Transform] = None, L_transform: Optional[desc.transform.Transform] = None, P_transform: Optional[desc.transform.Transform] = None, I_transform: Optional[desc.transform.Transform] = None)[source]¶
Minimizes equilibrium acceleration error in spectral space
- __init__(scalar: bool = False, R_transform: Optional[desc.transform.Transform] = None, Z_transform: Optional[desc.transform.Transform] = None, R1_transform: Optional[desc.transform.Transform] = None, Z1_transform: Optional[desc.transform.Transform] = None, L_transform: Optional[desc.transform.Transform] = None, P_transform: Optional[desc.transform.Transform] = None, I_transform: Optional[desc.transform.Transform] = None) → None[source]¶
Initializes an AccelErrorNodes object
- Parameters
scalar (bool, optional) – True for scalar objectives, False otherwise (Default)
R_transform (Transform, optional) – transforms R coefficients to real space in the volume
Z_transform (Transform, optional) – transforms Z coefficients to real space in the volume
R1_transform (Transform, optional) – transforms R coefficients to real space on the surface
Z1_transform (Transform, optional) – transforms Z coefficients to real space on the surface
L_transform (Transform, optional) – transforms lambda coefficients to real space
P_transform (Transform, optional) – transforms pressure coefficients to real space
I_transform (Transform, optional) – transforms rotational transform coefficients to real space
- Returns
None
- class desc.objective_funs.ForceErrorNodes(scalar: bool = False, R_transform: Optional[desc.transform.Transform] = None, Z_transform: Optional[desc.transform.Transform] = None, R1_transform: Optional[desc.transform.Transform] = None, Z1_transform: Optional[desc.transform.Transform] = None, L_transform: Optional[desc.transform.Transform] = None, P_transform: Optional[desc.transform.Transform] = None, I_transform: Optional[desc.transform.Transform] = None)[source]¶
Minimizes equilibrium force balance error in physical space
- __init__(scalar: bool = False, R_transform: Optional[desc.transform.Transform] = None, Z_transform: Optional[desc.transform.Transform] = None, R1_transform: Optional[desc.transform.Transform] = None, Z1_transform: Optional[desc.transform.Transform] = None, L_transform: Optional[desc.transform.Transform] = None, P_transform: Optional[desc.transform.Transform] = None, I_transform: Optional[desc.transform.Transform] = None) → None[source]¶
Initializes a ForceErrorNodes object
- Parameters
scalar (bool, optional) – True for scalar objectives, False otherwise (Default)
R_transform (Transform, optional) – transforms R coefficients to real space in the volume
Z_transform (Transform, optional) – transforms Z coefficients to real space in the volume
R1_transform (Transform, optional) – transforms R coefficients to real space on the surface
Z1_transform (Transform, optional) – transforms Z coefficients to real space on the surface
L_transform (Transform, optional) – transforms lambda coefficients to real space
P_transform (Transform, optional) – transforms pressure coefficients to real space
I_transform (Transform, optional) – transforms rotational transform coefficients to real space
- Returns
None
- class desc.objective_funs.ObjectiveFunction(scalar: bool = False, R_transform: Optional[desc.transform.Transform] = None, Z_transform: Optional[desc.transform.Transform] = None, R1_transform: Optional[desc.transform.Transform] = None, Z1_transform: Optional[desc.transform.Transform] = None, L_transform: Optional[desc.transform.Transform] = None, P_transform: Optional[desc.transform.Transform] = None, I_transform: Optional[desc.transform.Transform] = None)[source]¶
Objective function used in the optimization of an Equilibrium
- scalar¶
True for scalar objectives, False otherwise (Default)
- Type
bool, optional
- compute(x, bdryR, bdryZ, cP, cI, Psi_lcfs, bdry_ratio=1.0, pres_ratio=1.0, zeta_ratio=1.0, errr_ratio=1.0)[source]¶
compute the equilibrium objective function
- callback(x, bdryR, bdryZ, cP, cI, Psi_lcfs, bdry_ratio=1.0, pres_ratio=1.0, zeta_ratio=1.0, errr_ratio=1.0)[source]¶
function that prints equilibrium errors
- __init__(scalar: bool = False, R_transform: Optional[desc.transform.Transform] = None, Z_transform: Optional[desc.transform.Transform] = None, R1_transform: Optional[desc.transform.Transform] = None, Z1_transform: Optional[desc.transform.Transform] = None, L_transform: Optional[desc.transform.Transform] = None, P_transform: Optional[desc.transform.Transform] = None, I_transform: Optional[desc.transform.Transform] = None) → None[source]¶
Initializes an ObjectiveFunction
- Parameters
scalar (bool, optional) – True for scalar objectives, False otherwise (Default)
R_transform (Transform, optional) – transforms R coefficients to real space in the volume
Z_transform (Transform, optional) – transforms Z coefficients to real space in the volume
R1_transform (Transform, optional) – transforms R coefficients to real space on the surface
Z1_transform (Transform, optional) – transforms Z coefficients to real space on the surface
L_transform (Transform, optional) – transforms lambda coefficients to real space
P_transform (Transform, optional) – transforms pressure coefficients to real space
I_transform (Transform, optional) – transforms rotational transform coefficients to real space
- Returns
None
- class desc.objective_funs.ObjectiveFunctionFactory[source]¶
Factory Class for Objective Functions
- get_equil_obj_fxn(errr_mode, RZ_transform:Transform=None,
RZb_transform:Transform=None, L_transform:Transform=None, pres_transform:Transform=None, iota_transform:Transform=None, stell_sym:bool=True, scalar:bool=False)
Takes type of objective function and attributes of an equilibrium and uses it to compute and return the corresponding objective function
- get_equil_obj_fun(scalar: bool = False, R_transform: Optional[desc.transform.Transform] = None, Z_transform: Optional[desc.transform.Transform] = None, R1_transform: Optional[desc.transform.Transform] = None, Z1_transform: Optional[desc.transform.Transform] = None, L_transform: Optional[desc.transform.Transform] = None, P_transform: Optional[desc.transform.Transform] = None, I_transform: Optional[desc.transform.Transform] = None) → desc.objective_funs.ObjectiveFunction[source]¶
Accepts parameters necessary to create an objective function, and returns the corresponding ObjectiveFunction object
- Parameters
errr_mode (str) – error mode of the objective function one of ‘force’, ‘accel’
scalar (bool, optional) – True for scalar objectives, False otherwise (Default)
R_transform (Transform, optional) – transforms R coefficients to real space in the volume
Z_transform (Transform, optional) – transforms Z coefficients to real space in the volume
R1_transform (Transform, optional) – transforms R coefficients to real space on the surface
Z1_transform (Transform, optional) – transforms Z coefficients to real space on the surface
L_transform (Transform, optional) – transforms lambda coefficients to real space
P_transform (Transform, optional) – transforms pressure coefficients to real space
I_transform (Transform, optional) – transforms rotational transform coefficients to real space
- Returns
obj_fxn (ObjectiveFunction) – equilibrium objective function object, containing the compute and callback method for the objective function
- desc.objective_funs.compute_accel_error_spectral(cR, cZ, cP, cI, Psi_lcfs, R_transform, Z_transform, P_transform, I_transform, pres_ratio, zeta_ratio)[source]¶
Computes acceleration error in spectral space
- Parameters
cR (ndarray, shape(N_coeffs,)) – spectral coefficients of R
cZ (ndarray, shape(N_coeffs,)) – spectral coefficients of Z
cP (ndarray, shape(N_coeffs,)) – spectral coefficients of pressure
cI (ndarray, shape(N_coeffs,)) – spectral coefficients of rotational transform
Psi_lcfs (float) – total toroidal flux within the last closed flux surface
R_transform (Transform) – transforms cR to physical space
Z_transform (Transform) – transforms cZ to physical space
P_transform (Transform) – transforms cP to physical space
I_transform (Transform) – transforms cI to physical space
pres_ratio (float) – fraction in range [0,1] of the full pressure profile to use
zeta_ratio (float) – fraction in range [0,1] of the full toroidal (zeta) derivatives to use
- Returns
cR_zz_err (ndarray, shape(N_coeffs,)) – error in cR_zz
cZ_zz_err (ndarray, shape(N_coeffs,)) – error in cZ_zz
- desc.objective_funs.compute_force_error_RddotZddot(cR, cZ, cP, cI, Psi_lcfs, R_transform, Z_transform, P_transform, I_transform, pres_ratio, zeta_ratio)[source]¶
Computes force balance error at each node, projected back onto zernike coefficients for R and Z.
- Parameters
cR (ndarray, shape(N_coeffs,)) – spectral coefficients of R
cZ (ndarray, shape(N_coeffs,)) – spectral coefficients of Z
cP (ndarray, shape(N_coeffs,)) – spectral coefficients of pressure
cI (ndarray, shape(N_coeffs,)) – spectral coefficients of rotational transform
Psi_lcfs (float) – total toroidal flux within the last closed flux surface
R_transform (Transform) – transforms cR to physical space
Z_transform (Transform) – transforms cZ to physical space
P_transform (Transform) – transforms cP to physical space
I_transform (Transform) – transforms cI to physical space
pres_ratio (float) – fraction in range [0,1] of the full pressure profile to use
zeta_ratio (float) – fraction in range [0,1] of the full toroidal (zeta) derivatives to use
- Returns
cRddot (ndarray, shape(N_coeffs,)) – spectral coefficients for d^2R/dt^2
cZddot (ndarray, shape(N_coeffs,)) – spectral coefficients for d^2Z/dt^2
- desc.objective_funs.compute_force_error_RphiZ(cR, cZ, cP, cI, Psi_lcfs, R_transform, Z_transform, P_transform, I_transform, pres_ratio, zeta_ratio)[source]¶
Computes force balance error at each node, in R, phi, Z components
- Parameters
cR (ndarray, shape(N_coeffs,)) – spectral coefficients of R
cZ (ndarray, shape(N_coeffs,)) – spectral coefficients of Z
cP (ndarray, shape(N_coeffs,)) – spectral coefficients of pressure
cI (ndarray, shape(N_coeffs,)) – spectral coefficients of rotational transform
Psi_lcfs (float) – total toroidal flux within the last closed flux surface
R_transform (Transform) – transforms cR to physical space
Z_transform (Transform) – transforms cZ to physical space
P_transform (Transform) – transforms cP to physical space
I_transform (Transform) – transforms cI to physical space
pres_ratio (float) – fraction in range [0,1] of the full pressure profile to use
zeta_ratio (float) – fraction in range [0,1] of the full toroidal (zeta) derivatives to use
- Returns
F_err (ndarray, shape(3,N_nodes,)) – F_R, F_phi, F_Z at each node
- desc.objective_funs.compute_force_error_nodes(cR, cZ, cP, cI, Psi_lcfs, R_transform, Z_transform, P_transform, I_transform, pres_ratio, zeta_ratio)[source]¶
Computes force balance error at each node, in radial / helical components
- Parameters
cR (ndarray, shape(N_coeffs,)) – spectral coefficients of R
cZ (ndarray, shape(N_coeffs,)) – spectral coefficients of Z
cP (ndarray, shape(N_coeffs,)) – spectral coefficients of pressure
cI (ndarray, shape(N_coeffs,)) – spectral coefficients of rotational transform
Psi_lcfs (float) – total toroidal flux within the last closed flux surface
R_transform (Transform) – transforms cR to physical space
Z_transform (Transform) – transforms cZ to physical space
P_transform (Transform) – transforms cP to physical space
I_transform (Transform) – transforms cI to physical space
pres_ratio (float) – fraction in range [0,1] of the full pressure profile to use
zeta_ratio (float) – fraction in range [0,1] of the full toroidal (zeta) derivatives to use
- Returns
F_rho (ndarray, shape(N_nodes,)) – radial force balance error at each node
F_beta (ndarray, shape(N_nodes,)) – helical force balance error at each node
- desc.objective_funs.compute_qs_error_spectral(cR, cZ, cP, cI, Psi_lcfs, R_transform, Z_transform, P_transform, I_transform, pres_ratio, zeta_ratio)[source]¶
Computes quasisymmetry error in spectral space
- Parameters
cR (ndarray, shape(N_coeffs,)) – spectral coefficients of R
cZ (ndarray, shape(N_coeffs,)) – spectral coefficients of Z
cP (ndarray, shape(N_coeffs,)) – spectral coefficients of pressure
cI (ndarray, shape(N_coeffs,)) – spectral coefficients of rotational transform
Psi_lcfs (float) – total toroidal flux within the last closed flux surface
R_transform (Transform) – transforms cR to physical space
Z_transform (Transform) – transforms cZ to physical space
P_transform (Transform) – transforms cP to physical space
I_transform (Transform) – transforms cI to physical space
pres_ratio (float) – fraction in range [0,1] of the full pressure profile to use
zeta_ratio (float) – fraction in range [0,1] of the full toroidal (zeta) derivatives to use
- Returns
cQS (ndarray) – quasisymmetry error Fourier coefficients
- desc.objective_funs.curve_self_intersects(x, y)[source]¶
Checks if a curve intersects itself
- Parameters
x (ndarray) – x and y coordinates of points along the curve
y (ndarray) – x and y coordinates of points along the curve
- Returns
is_intersected (bool) – whether the curve intersects itself
- desc.objective_funs.get_qisym_obj_fun(stell_sym, M, N, NFP, zernike_transform, zern_idx, lambda_idx, modes_pol, modes_tor)[source]¶
Gets the quasisymmetry objective function
- Parameters
stell_sym (bool) – True if stellarator symmetry is enforced
M (int) – maximum poloidal resolution
N (int) – maximum toroidal resolution
NFP (int) – number of field periods
zernike_transform (ZernikeTransform) – object with transform method to go from spectral to physical space with derivatives
zern_idx (ndarray of int) – mode numbers for Zernike basis
lambda_idx (ndarray of int) – mode numbers for Fourier basis
modes_pol (ndarray) – poloidal Fourier mode numbers
modes_tor (ndarray) – toroidal Fourier mode numbers
- Returns
qsym_obj (function) – quasisymmetry objective function
- desc.objective_funs.is_nested(cR, cZ, R_basis, Z_basis, L=10, M=361, zeta=0)[source]¶
- Checks that an equilibrium has properly nested flux surfaces
in a given toroidal plane
- Parameters
cR (ndarray, shape(RZ_transform.num_modes,)) – spectral coefficients of R
cZ (ndarray, shape(RZ_transform.num_modes,)) – spectral coefficients of Z
basis (FourierZernikeBasis) – spectral basis for R and Z
L (int) – number of surfaces to check (Default value = 10)
M (int) – number of poloidal angles to use for the test (Default value = 361)
zeta (float) – toroidal plane to check (Default value = 0)
- Returns
is_nested (bool) – whether or not the surfaces are nested
Perturbations¶
- desc.perturbations.get_system_derivatives(equil_obj, args, arg_dict, pert_order=1, verbose=False)[source]¶
computes Jacobian and Hessian arrays
- Parameters
equil_obj (function) – objective function to calculate jacobian and hessian of
args (tuple) – additional arguments passed to equil_obj
arg_dict (dict) – dictionary of variable names and arguments to calculate derivatives with respect to.
pert_order (int) – order of perturbation (1=linear, jacobian. 2=quadratic, hessian) (Default value = 1)
verbose (int or bool) – level of text output (Default value = False)
- Returns
Jx (ndarray) – jacobian wrt to state vector
Jc (ndarray) – jacobian wrt to other parameters specified in arg_dict
Jxx (ndarray) – hessian wrt to state vector. Only calculated if pert_order > 1
Jcc (ndarray) – hessian wrt to other parameters specified in arg_dict. Only calculated if pert_order > 1
Jxc (ndarray) – hessian wrt to state vector and other parameters. Only calculated if pert_order > 1
- desc.perturbations.perturb_continuation_params(x, equil_obj, deltas, args, pert_order=1, verbose=False, timer=None)[source]¶
perturbs an equilibrium wrt the continuation parameters
- Parameters
x (ndarray) – state vector
equil_obj (function) – equilibrium objective function
deltas (ndarray) – changes in the continuation parameters
args (tuple) – additional arguments passed to equil_obj
pert_order (int) – order of perturbation (1=linear, 2=quadratic) (Default value = 1)
verbose (int or bool) – level of output to display (Default value = False)
timer (Timer) – Timer object (Default value = None)
- Returns
x (ndarray) – perturbed state vector
timer (Timer) – Timer object with timing data
Plotting¶
- class desc.plotting.Plot[source]¶
Class for plotting instances of Configuration and Equilibria on a linear grid.
- __name_key__(name_dict)[source]¶
Reconstruct name for dictionary key used in Configuration compute methods.
- Parameters
name_dict (dict) – name dictionary created by format_name method
- Returns
name_key (str)
- axis_labels = ['$\\rho$', '$\\theta$', '$\\zeta$']¶
- compute(eq, name, grid)[source]¶
Compute value specified by name on grid for equilibrium eq.
- Parameters
eq (Configuration or Equilibrium) – Configuration or Equilibrium instance
name (str or dict) – formatted string or parsed dictionary from format_name method
grid (Grid) – grid on which to compute value specified by name
- Returns
array of values
- format_ax(ax)[source]¶
Check type of ax argument. If ax is not a matplotlib AxesSubplot, initalize one.
- Parameters
ax (None or matplotlib AxesSubplot instance) –
- Returns
matpliblib Figure instance, matplotlib AxesSubplot instance
- format_name(name)[source]¶
Parse name string into dictionary.
- Parameters
name (str) –
- Returns
parsed name (dict)
- get_grid(NFP, **kwargs)[source]¶
Get grid for plotting.
- Parameters
NFP (int) – number of (?)
kwargs – any arguments taken by LinearGrid (Default L=100, M=1, N=1)
- Returns
LinearGrid
- name_label(name_dict)[source]¶
Create label for name dictionary.
- Parameters
name_dict (dict) – name dictionary created by format_name method
- Returns
label (str)
- plot_1d(eq, name, grid=None, ax=None, **kwargs)[source]¶
Plot 1D slice from Equilibrium or Configuration.
- Parameters
eq (Equilibrium or Configuration) – object from which to plot
name (str) – name of variable to plot
grid (Grid (optional)) – grid object defining coordinates to plot on
ax (matplotlib AxesSubplot (optional)) – axis to plot on
kwargs – any arguments taken by LinearGrid (Default L=100, M=1, N=1)
- Returns
axis
- plot_2d(eq, name, grid=None, ax=None, **kwargs)[source]¶
Plot 2D slice from Equilibrium or Configuration.
- Parameters
eq (Equilibrium or Configuration) – object from which to plot
name (str) – name of variable to plot
grid (Grid (optional)) – grid object defining coordinates to plot on
ax (matplotlib AxesSubplot (optional)) – axis to plot on
kwargs – any arguments taken by LinearGrid (Default L=100, M=100, N=1)
- Returns
axis
- desc.plotting.plot_IC(cR_init, cZ_init, zern_idx, NFP, nodes, cP, cI, **kwargs)[source]¶
Plot initial conditions, such as the initial guess for flux surfaces, node locations, and profiles.
- Parameters
cR_init (ndarray) – spectral coefficients of R
cZ_init (ndarray) – spectral coefficients of Z
zern_idx (ndarray) – array of (l,m,n) indices for each spectral R,Z coeff
NFP (int) – number of field periods
nodes (ndarray) – locations of nodes in SFL coordinates
cI (array-like) – paramters to pass to rotational transform function
cP (array-like) – parameters to pass to pressure function
**kwargs – additional plot formatting parameters
- Returns
fig (matplotlib.figure) – handle to figure used for plotting
ax (ndarray of matplotlib.axes) – handles to axes used for plotting
- desc.plotting.plot_coeffs(cR, cZ, cL, zern_idx, lambda_idx, cR_init=None, cZ_init=None, cL_init=None, **kwargs)[source]¶
Scatter plots of zernike and lambda coefficients, before and after solving
- Parameters
cR (ndarray) – spectral coefficients of R
cZ (ndarray) – spectral coefficients of Z
cL (ndarray) – spectral coefficients of lambda
zern_idx (ndarray) – array of (l,m,n) indices for each spectral R,Z coeff
lambda_idx (ndarray) – indices for lambda spectral basis, ie an array of [m,n] for each spectral coefficient
cR_init (ndarray) – initial spectral coefficients of R (Default value = None)
cZ_init (ndarray) – initial spectral coefficients of Z (Default value = None)
cL_init (ndarray) – initial spectral coefficients of lambda (Default value = None)
**kwargs – additional plot formatting parameters
- Returns
fig (matplotlib.figure) – handle to the figure
ax (ndarray of matplotlib.axes) – handle to axes
- desc.plotting.plot_comparison(equil0, equil1, label0='x0', label1='x1', **kwargs)[source]¶
Plots force balance error
- Parameters
equil0 (dict) – dictionary of two equilibrium solution quantities
equil1 (dict) – dictionary of two equilibrium solution quantities
label0 (str) – labels for each equilibria
label1 (str) – labels for each equilibria
**kwargs – additional plot formatting parameters
- desc.plotting.plot_coord_surfaces(cR, cZ, zern_idx, NFP, nr=10, nt=12, ax=None, bdryR=None, bdryZ=None, **kwargs)[source]¶
Plots solutions (currently only zeta=0 plane)
- Parameters
cR (ndarray) – spectral coefficients of R
cZ (ndarray) – spectral coefficients of Z
zern_idx (ndarray) – indices for R,Z spectral basis, ie an array of [l,m,n] for each spectral coefficient
NFP (int) – number of field periods
nr (int) – number of flux surfaces to show (Default value = 10)
nt (int) – number of theta lines to show (Default value = 12)
ax (matplotlib.axes) – axes to plot on. If None, a new figure is created. (Default value = None)
bdryR – R values of last closed flux surface (Default value = None)
bdryZ – Z values of last closed flux surface (Default value = None)
**kwargs – additional plot formatting parameters
- Returns
ax (matplotlib.axes) – handle to axes used for the plot
- desc.plotting.plot_fb_err(equil, domain='real', normalize='local', log=True, cmap='plasma', **kwargs)[source]¶
Plots force balance error
- Parameters
equil (dict) – dictionary of equilibrium solution quantities
domain (str) – one of ‘real’, ‘sfl’. What basis to use for plotting, real (R,Z) coordinates or straight field line (rho,vartheta) (Default value = ‘real’)
normalize (str) – Whether and how to normalize values None, False - no normalization, values plotted are force error in Newtons/m^3 ‘local’ - normalize by local pressure gradient ‘global’ - normalize by pressure gradient at rho=0.5 True - same as ‘global’ (Default value = ‘local’)
log (bool) – plot logarithm of error or absolute value (Default value = True)
cmap (str) – colormap to use (Default value = ‘plasma’)
**kwargs – additional plot formatting parameters
- desc.plotting.plot_logo(savepath=None, **kwargs)[source]¶
Plots the DESC logo
- Parameters
savepath (str or path-like) – path to save the figure to. File format is inferred from the filename (Default value = None)
**kwargs – additional plot formatting parameters. options include ‘Dcolor’, ‘Dcolor_rho’, ‘Dcolor_theta’, ‘Ecolor’, ‘Scolor’, ‘Ccolor’, ‘BGcolor’, ‘fig_width’
- Returns
fig (matplotlib.figure) – handle to the figure used for plotting
ax (matplotlib.axes) – handle to the axis used for plotting
- desc.plotting.plot_vmec_comparison(vmec_data, equil)[source]¶
Plots comparison of VMEC and DESC solutions
- Parameters
vmec_data (dict) – dictionary of VMEC solution quantities.
equil (dict) – dictionary of DESC equilibrium solution quantities.
- desc.plotting.plot_zernike_basis(M, delta_lm, indexing, **kwargs)[source]¶
Plots spectral basis of zernike basis functions
- Parameters
M (int) – maximum poloidal resolution
delta_lm (int) – maximum difference between radial mode l and poloidal mode m
indexing (str) – zernike indexing method. One of ‘fringe’, ‘ansi’, ‘house’, ‘chevron’
**kwargs – additional plot formatting arguments
- Returns
fig (matplotlib.figure) – handle to figure
ax (dict of matplotlib.axes) – nested dictionary, ax[l][m] is the handle to the axis for radial mode l, poloidal mode m
- desc.plotting.print_coeffs(cR, cZ, cL, zern_idx, lambda_idx)[source]¶
prints coeffs to the terminal
- Parameters
cR – spectral coefficients for R, Z, and lambda
cZ – spectral coefficients for R, Z, and lambda
cL – spectral coefficients for R, Z, and lambda
zern_idx – mode numbers for zernike and fourier spectral basis.
lambda_idx – mode numbers for zernike and fourier spectral basis.
Transform¶
- class desc.transform.Transform(grid: Optional[desc.grid.Grid] = None, basis: Optional[desc.basis.Basis] = None, derivs=0, rcond=1e-06, load_from=None, file_format=None, obj_lib=None)[source]¶
-
- rcond¶
relative cutoff for singular values in least squares fit
- Type
float
- derivatives¶
combinations of derivatives needed Each row is one set, columns represent the order of derivatives for [rho, theta, zeta]
- Type
ndarray
- matrices¶
DESCRIPTION
- Type
ndarray
- pinv¶
DESCRIPTION
- Type
ndarray
- __eq__(other) → bool[source]¶
Overloads the == operator
- Parameters
other (Transform) – another Transform object to compare to
- Returns
bool – True if other is a Transform with the same attributes as self False otherwise
- __init__(grid: Optional[desc.grid.Grid] = None, basis: Optional[desc.basis.Basis] = None, derivs=0, rcond=1e-06, load_from=None, file_format=None, obj_lib=None) → None[source]¶
Initializes a Transform
- gridGrid
DESCRIPTION
- basisBasis
DESCRIPTION
- derivsint or string
order of derivatives needed, if an int (Default = 0) OR type of calculation being performed, if a string
'force': all of the derivatives needed to calculate an equilibrium from the force balance equations'qs': all of the derivatives needed to calculate quasi- symmetry from the triple-product equation
- rcondfloat
relative cutoff for singular values in least squares fit
None
- property basis¶
- change_resolution(grid: Optional[desc.grid.Grid] = None, basis: Optional[desc.basis.Basis] = None) → None[source]¶
Re-builds the matrices with a new grid and basis
- property derivatives¶
- property derivs¶
- fit(x)[source]¶
Transform from physical domain to spectral using least squares fit
- Parameters
x (ndarray, shape(N_nodes,)) – values in real space at coordinates specified by self.grid
- Returns
c (ndarray, shape(N_coeffs,)) – spectral coefficients in self.basis
- property grid¶
- property matrices¶
- property num_modes¶
- property num_nodes¶
- transform(c, dr=0, dt=0, dz=0)[source]¶
Transform from spectral domain to physical
- Parameters
c (ndarray, shape(N_coeffs,)) – spectral coefficients, indexed as (lm,n) flattened in row major order
dr (int) – order of radial derivative
dt (int) – order of poloidal derivative
dz (int) – order of toroidal derivative
- Returns
x (ndarray, shape(N_nodes,)) – array of values of function at node locations
- desc.transform.ansi_to_lm(idx)[source]¶
Convert Zernike ANSI single term to (l,m) two-term index.
- Parameters
idx (int) – ANSI index
- Returns
l,m (int) – radial and azimuthal mode numbers.
- desc.transform.fringe_to_lm(idx)[source]¶
Convert single Zernike Fringe index to (l,m) double index.
- Parameters
idx (int) – Fringe index
- Returns
l,m (int) – radial and azimuthal mode numbers.
- desc.transform.lm_to_ansi(l, m)[source]¶
Convert Zernike (l,m) two term index to ANSI single term index.
- Parameters
l (int) – radial and azimuthal mode numbers.
m (int) – radial and azimuthal mode numbers.
- Returns
idx (int) – ANSI index for l,m
- desc.transform.lm_to_fringe(l, m)[source]¶
Convert Zernike (l,m) double index to single Fringe index.
- Parameters
l (int) – radial and azimuthal mode numbers.
m (int) – radial and azimuthal mode numbers.
- Returns
idx (int) – Fringe index for l,m
- desc.transform.zernike_norm(l, m)[source]¶
Norm of a Zernike polynomial with l, m indexing. Returns the integral (Z^m_l)^2 r dr dt, r=[0,1], t=[0,2*pi]
- Parameters
l (int) – radial and azimuthal mode numbers.
m (int) – radial and azimuthal mode numbers.
- Returns
norm (float) – norm of Zernike polynomial over unit disk.
VMEC¶
- desc.vmec.read_vmec_output(fname)[source]¶
Reads VMEC data from wout nc file
- Parameters
fname (str or path-like) – filename of VMEC output file
- Returns
vmec_data (dict) – the VMEC data fields
- desc.vmec.sfl_err(theta, vartheta, zeta, vmec_data, s, flag=0)[source]¶
f(theta) = vartheta - theta - lambda(theta)
- Parameters
theta (float) – VMEC poloidal angle
vartheta (float) – sfl poloidal angle
zeta (float) – VMEC/sfl toroidal angle
vmec_data (dict) – dictionary of VMEC equilibrium parameters
flag (int) – offsets theta to ensure f(theta) has one zero (Default value = 0)
s –
- Returns
err (float) – vartheta - theta - lambda
- desc.vmec.vmec_error(equil, vmec_data, Nt=8, Nz=4)[source]¶
Computes error in SFL coordinates compared to VMEC solution
- Parameters
equil (dict) – dictionary of DESC equilibrium parameters
vmec_data (dict) – dictionary of VMEC equilibrium parameters
Nt (int) – number of poloidal angles to sample (Default value = 8)
Nz (int) – number of toroidal angles to sample (Default value = 8)
- Returns
err (float) – average Euclidean distance between VMEC and DESC sample points
- desc.vmec.vmec_interpolate(Cmn, Smn, xm, xn, theta, phi, sym=True)[source]¶
Interpolates VMEC data on a flux surface
- Parameters
Cmn (ndarray) – cos(mt-np) Fourier coefficients
Smn (ndarray) – sin(mt-np) Fourier coefficients
xm (ndarray) – poloidal mode numbers
xn (ndarray) – toroidal mode numbers
theta (ndarray) – poloidal angles
phi (ndarray) – toroidal angles
sym (bool) – stellarator symmetry (Default value = True)
- Returns
if sym = True – C, S (tuple of ndarray): VMEC data interpolated at the angles (theta,phi) where C has cosine symmetry and S has sine symmetry
if sym = False – X (ndarray): non-symmetric VMEC data interpolated at the angles (theta,phi)
- desc.vmec.vmec_transf(xmna, xm, xn, theta, phi, trig='sin')[source]¶
Compute Fourier transform of VMEC data
- Parameters
xmns (2d float array) – xmnc[:,i] are the sin coefficients at flux surface i
xm (1d int array) – poloidal mode numbers
xn (1d int array) – toroidal mode numbers
theta (1d float array) – poloidal angles
phi (1d float array) – toroidal angles
trig (string) – type of transform, options are ‘sin’ or ‘cos’ (Default value = ‘sin’)
xmna –
- Returns
f (ndarray) – f[i,j,k] is the transformed data at flux surface i, theta[j], phi[k]