Skip to content

API

from agnimhd import (
    EquilibriumData, Basis, DiffMat, AssemblyConfig, SolverConfig,
    load, solve, from_desc, desc_from_eqdsk,
    growth_rate, eigenpair, growth_rate_and_grad, FORMAT_VERSION,
)

Docstrings in the source are the full reference.

Solve mode

solve(src, basis, solver="dense", family=0, assembly=None, density=False, coarse=None, **knobs) evaluates a source on basis and returns eigenpair's (γ², v, residual) for one family. src is anything load takes. solver is a name with SolverConfig fields as knobs, or a SolverConfig. With "jd" the source is evaluated on coarse too (default basis.coarse()).

load(path_or_object) returns the source of a DESC file or Equilibrium (evaluated on any basis) or of an agnimhd file or EquilibriumData (its own nodes only). load(x).evaluate(basis, density=False) is the EquilibriumData.

growth_rate(eq, diffmat, assembly=None, solver=None, v_fixed=None, v_guess=None, coarse=None) returns the squared growth rate γ² = λ, positive when unstable, for one stored equilibrium. jax.grad raises (see Solve mode and optimize mode). Under jax.jit, make the two configs static: jax.jit(growth_rate, static_argnums=(2, 3)).

  • v_guess: start vector, for example the previous step's eigenvector.
  • v_fixed: skip the eigensolve and use this vector. Valid only at the same equilibrium it came from.
  • coarse: the coarse level eigensolver="jd" requires, basis.coarse_level(eq_coarse, family) (or from_desc(..., coarse=...)), or the (v0, Z) that agnimhd.objective.coarse_space(eq, diffmat, coarse, assembly, solver) returned for it.

eigenpair(eq, diffmat, assembly=None, solver=None, v_guess=None, coarse=None) returns (γ², v, residual) with residual = ‖Av − γ²v‖ / (|γ²| ‖v‖). Check the residual: it is the quality measure.

Optimize mode

growth_rate(params, diffmat, ..., equilibrium_map=f, on_vector=None, sigma=None) is the same γ² as a function of params, with f a JAX function params → EquilibriumData that evaluates geometry and profiles and contains no equilibrium solve. jax.grad returns a pytree shaped like params (Hellmann-Feynman: the eigensolve has a zero backward rule, the Rayleigh quotient carries the derivative). An EquilibriumData as params, or a non-callable equilibrium_map, is refused. Under jax.jit the map is static too: jax.jit(jax.grad(growth_rate), static_argnums=(2, 3), static_argnames="equilibrium_map").

growth_rate_and_grad(params, equilibrium_map, diffmat, ...): value and gradient from one eigensolve.

from_desc(eq_or_path, basis, family=0, density=False, coarse=None) returns (EquilibriumData, DiffMat) on the nodes of basis, the DiffMat of toroidal mode family family, then the JD coarse level on the nodes of coarse=basis.coarse(...). With density=True the normalized ni is stored as EquilibriumData.density, the mass weighting every solver uses. Needs DESC. desc_from_eqdsk(path, psi_n_edge=0.99, L=24, M=24, profile_L=24, solve=True, solve_options=None) returns a fixed-boundary DESC Equilibrium from an EFIT g-file, solved at the g-file's pressure and ι = 1/q (a port of D. Panici's efit2desc). Needs DESC. agnimhd.adapters.eqdsk.read_eqdsk(path) and eqdsk_profiles(g, psi_n_edge) are its numpy-only reader and boundary/profiles. AgniStability(eq, basis, family=0, assembly=None, solver=None, coarse=None, density=False, ...) (agnimhd.adapters.desc_objective) is the DESC objective for one family. With solver.eigensolver="jd" it also evaluates the equilibrium on the coarse level coarse=basis.coarse(n_theta, n_zeta) (default basis.coarse()) at every call. density=True weights both levels as from_desc(..., density=True) does, and the equilibrium needs a density profile.

Configuration

Frozen dataclasses, passed as static arguments.

AssemblyConfig: gamma=5/3, incompressible=False, axisym=False, n_mode_axisym=1, parity=None ("even" or "odd": one block under stellarator symmetry, Stellarators).

SolverConfig:

field default used by
eigensolver "dense" "eigsh", "dense", "jd", "dense_mg"
sigma 1e-3 all, set above the largest γ² (the solvers shift A by −σ)
eigsh_tol 1e-8 eigsh
num_matvecs, factor 50, "cholesky" dense
seed 0 eigsh, dense, dense_mg (the random start vector)
sigma_mode, sigma_factor "fixed", 2.5 dense
jd_outer, jd_inner, jd_maxdim, jd_keep 200, 100, 60, 10 jd
jd_tol, jd_theta_tol 0.0, 1e-8 jd stop tests (residual of the returned vector, Ritz change)
ring_batch 24 jd: rings of the coarse level assembled at once
coarse_num_matvecs, k_defl 100, 50 jd coarse level
mg_tile, mg_block, mg_iters, mg_tol, mg_theta_tol 1024, 16, 6, 1e-6, 1e-8 dense_mg: tile width, block size, iterations, residual stop, relative γ² change stop

See Choosing options for how to set them.

Grid operators: agnimhd.basis, agnimhd.quadrature

  • Basis(n_rho, n_theta, n_zeta, *, radial="zernike", alpha=-0.35, beta=-0.65, automorphism="default", mpol=None, ntor=None, penalty=None, restrict=None), a frozen dataclass on one field period (Choosing the basis). nodes_and_diffmat(nfp, family=0) returns (nodes, diffmat) for the toroidal modes n = family + k·nfp, families(nfp) the families to solve (0 ... nfp // 2), coarse(n_theta=None, n_zeta=None) the Jacobi-Davidson coarse level (fewer angular nodes, and it needs mpol and ntor) and coarse_level(eq_coarse, family=0) the coarse argument made from the equilibrium on its nodes (Toroidal mode families).
  • One-dimensional bases, each returning (D, W) on the same nodes: legendre_diffmat, jacobi_diffmat, fourier_diffmat, fourier_diffmat_truncated, bspline_diffmat, finite_difference_diffmat. zernike_fourier_diffmat(rho, theta, L=-1, M=-1) returns the coupled (D_rho, D_theta) on the (ρ, θ) grid instead.
  • Nodes and maps: leggauss_lob, gauss_radau_jacobi, zernike_nodes_weights, automorphism_staircase1. interpolatory_weights(nodes) gives the weights of ∫ f dx on any nodes, the radial weights of "gauss_radau_jacobi".
  • DiffMat(D_rho=, W_rho=, D_theta=, W_theta=, D_zeta=, W_zeta=) holds the pairs, and w_rho, w_theta, w_zeta are the weights as 1-D vectors. With a penalty it also holds penalty_complement and penalty_complement_zeta, the orthonormal bases U of the content the penalty acts on, and penalty_projector, UUᴴ (Penalty).
  • unrepresented_space(D_rho, D_theta) returns (U, rank): U from a complete QR of the orthonormal basis of what the two derivative matrices represent, and rank the dimension of that space. coupled_rt is True when D_rho, D_theta act on the coupled (ρ, θ) grid (Zernike), larger than their 1-D weights.
  • Mode caps are checked: fourier_diffmat_truncated and zernike_fourier_diffmat raise if M > (n - 1) // 2.

Lower level

  • agnimhd.assemble: assemble_dense (the reduced whitened matrix), assemble_rows (any block of its rows, from the matrix-free operator), matfree_operator (the same operator as a function), keep_indices, operator_dtype(config, diffmat) (complex for axisym=True or a complex D_zeta).
  • agnimhd.adapters.desc_vacuum: DESC's boundary vacuum response, phi_scaffold (the static, resolution-only part, once) and phi_matrix(eq, params, scaffold, bnd_rtz) (the matrix at params, jit- and grad-safe), which from_desc(..., free_boundary=True) calls.
  • agnimhd.solvers: jacobi_davidson, the Fourier-mode preconditioner of every basis (make_mode_precond, SHIFT_LADDER), the ring preconditioner of the coarse level (build_ring_blocks, factor_ring_blocks_traced, make_block_precond), the coarse level (coarse_seed_and_deflation, fourier_interp_matrix).
  • agnimhd.multigpu: shifted_rows, solve_shifted, dense_mg, the pieces of eigensolver="dense_mg" (Dense solves on several GPUs).
  • agnimhd.plotting: mode_components, mode_displacement, mode_plot_displacement, mode_delta_v, mode_speed return arrays. plot_* need matplotlib. mode_delta_b(eq, diffmat, op, v, assembly) returns the perturbed magnetic field δB = ∇×(ξ×B) of an eigenvector, its contravariant PEST components (δBρ, δBθ, δBζ) in units of BN per unit length a. δBρ is the part normal to the flux surfaces. plot_mode_cross_section draws (R, Z) contours on one toroidal plane k (default ζ = 0). plot_eigenfunction_cross_sections draws ζ = 0 and, for 3D cases, also ζ = π/NFP.

Command line

agnimhd info                              # list the EquilibriumData fields
agnimhd validate FILE [BASIS] [-v]       # check a saved or DESC equilibrium
agnimhd solve FILE [BASIS] [--family X] [--gamma G] [--sigma S] [--eigensolver E]
              [--coarse T,Z]             # E: eigsh, dense, jd (DESC file)

BASIS: [--res R,T,Z]
       [--radial zernike|gauss_radau_jacobi|lobatto] [--mpol M] [--ntor N]
       [--penalty P] [--restrict true|false]
       [--automorphism '{"eps": 0.001, "x_0": 0.6, "m_1": 2.5, "m_2": 3.0}']

FILE is an agnimhd .npz or .h5, or a DESC .h5 (then --res is required, with Z nodes per field period). For an agnimhd file, --radial and --automorphism must match the nodes the file was exported on. --automorphism null is no map. --penalty is Basis(penalty=...) and --restrict is Basis(restrict=...). --penalty 0 --restrict false is the plain nodal operator. solve reports every toroidal mode family x = 0 … ⌊NFP/2⌋ and the most unstable, or only family X with --family. A family whose eigensolve fails (ARPACK finds no converged eigenpair when no eigenvalue lies below round-off) is reported as such, the others are still solved, and the exit status is 1.