Vacuum
Vacuum computes the magnetostatic response of the region between the plasma boundary and a conducting wall, or of free space when there is no wall, following Chance (1997) and Chance et al. (2007). It runs inside ForceFreeStates whenever vac_flag = true, and its matrices are shared with PerturbedEquilibrium.
What it computes
For a normal displacement $\xi$ of the plasma boundary, expanded in the poloidal harmonics of the run, the perturbed vacuum field is found from a Green's-function integral over the boundary and the wall, and the vacuum energy is the quadratic form $\delta W_v = \xi^\dagger W_v \xi$. $W_v$ is the vacuum part of the free-boundary energy, $W = W_\mathrm{plasma} + W_\mathrm{vacuum}$, whose eigenvalues decide the ideal kink stability on the Stability page: a close conducting wall raises $W_v$ and stabilizes external modes, no wall gives the free-space limit. ForceFreeStates scales wv by the resonance factors $(m - nq)(m' - nq)$ of its row and column harmonics, the convention of Chance (1997), before adding it to the plasma energy; compute_vacuum_response returns it unscaled. When the run needs it, the module also returns the vacuum surface-current matrix $I_v$, which PerturbedEquilibrium inverts into the surface inductance $L$ of the plasma response.
Running it
The wall is the optional [Wall] section of the deck; omit it for no wall. shape selects one of five shapes, each with its own keys, and equal_arc_wall (default true) distributes the wall nodes by equal arc length:
# one [Wall] section per deck; the five shapes:
[Wall]
shape = "conformal" # the plasma boundary expanded by standoff_fraction minor radii
standoff_fraction = 0.3
[Wall]
shape = "elliptical" # an ellipse of the given minor radius
minor_radius = 0.3
[Wall]
shape = "dee" # a D-shaped wall: standoff_fraction, half_thickness, elongation, center_offset, triangularity, corner_sharpness
standoff_fraction = 0.3
elongation = 1.5
triangularity = 0.5
[Wall]
shape = "mod_dee" # the same shape placed by minor_radius instead of standoff_fraction
minor_radius = 0.3
[Wall]
shape = "file" # a wall contour read from a file
file = "wall.dat"examples/Solovev_ideal_example holds a near-marginal kink by a conformal wall; the DIII-D-like examples run without one. In a script the shapes are ConformalWall, EllipticalWall, DeeWall, ModDeeWall and FileWall, passed as the wall keyword of the solve (nothing for no wall), and the response itself is
using GeneralizedPerturbedEquilibrium
inputs = Vacuum.VacuumInput(eq, 0.995, 256, 1, 1:10, [1]) # the surface at ψ_N = 0.995: mtheta, nzeta, m_modes, n_modes
vac = Vacuum.compute_vacuum_response(inputs, Vacuum.ConformalWall(; standoff_fraction=0.3); compute_Iv=true)
vac.wv, vac.I_v, vac.plasma_pts, vac.wall_pts # I_v is zero unless compute_Iv=truewith eq a PlasmaEquilibrium; VacuumInput(; x, z, ν, mtheta_in, m_modes, n_modes, mtheta, nzeta) takes a boundary given point by point instead, where ν(ψ, θ) is the toroidal-angle offset of the straight-field-line coordinates, $\phi = 2\pi\zeta + \nu$ with $\phi$ the internal toroidal angle of the Conventions Reference (the laboratory angle carries the helicity sign). With [ForceFreeStates] nzeta_vacuum > 1 the response is evaluated on a toroidal grid, with the singular correction of the 3D kernel (examples/Solovev_ideal_example_3D).
Outputs
| Dataset | Meaning |
|---|---|
ForceFreeStates/FreeBoundaryStability/W_vacuum, vacuum_eigenvalue | the vacuum energy matrix on the control surface and its least eigenvalue |
PerturbedEquilibrium/ResponseMatrices/surface_inductance | the surface inductance $L$ derived from $I_v$ |
SurfaceGeometries/Plasma/x, y, z and SurfaceGeometries/Wall/x, y, z | the plasma boundary and wall point clouds, for visualization |
Numerical notes
- The Legendre functions of the Green's function are evaluated from Bulirsch's elliptic integrals, and by 32-point Gaussian quadrature for large arguments ($n\hat\rho \geq 0.1$).
- For n = 0 with a closed wall the kernel is regularized automatically.
API reference
GeneralizedPerturbedEquilibrium.Vacuum.ConformalWall — Type
ConformalWall(; standoff_fraction=0.3, equal_arc_wall=true)Wall offset from the plasma surface along its normal.
Fields
standoff_fraction::Float64: Distance of the wall from the plasma in units of the minor radius0.5(max R - min R). On a non-axisymmetric boundary the extrema are taken over the whole torus, sostandoff_fractionscales with half the global R-extent rather than a cross-section minor radius.equal_arc_wall::Bool: Equal arc length node distribution, seeWallSettings
GeneralizedPerturbedEquilibrium.Vacuum.DeeWall — Type
DeeWall(; standoff_fraction=0.3, half_thickness=0.05, elongation=1.5, center_offset=0.0, triangularity=0.5, corner_sharpness=0.05, equal_arc_wall=true)Dee-shaped wall scaled to the plasma: minor radius r_minor (1 + standoff_fraction - center_offset), centered at r_major + center_offset r_minor.
Fields
standoff_fraction::Float64: Distance of the wall from the plasma in units of the minor radius0.5(max R - min R)half_thickness::Float64: Half-thickness parameterelongation::Float64: Elongation parametercenter_offset::Float64: Offset of the wall center from the major radius, in units of the minor radiustriangularity::Float64: Triangularity parametercorner_sharpness::Float64: Sharpness of the corners (try 0.05 as initial value)equal_arc_wall::Bool: Equal arc length node distribution, seeWallSettings
GeneralizedPerturbedEquilibrium.Vacuum.EllipticalWall — Type
EllipticalWall(; minor_radius=0.3, equal_arc_wall=true)Ellipse confocal with the plasma's bounding ellipse.
Fields
minor_radius::Float64: Horizontal semi-axis in meters; the vertical semi-axis follows from the confocalityequal_arc_wall::Bool: Equal arc length node distribution, seeWallSettings
GeneralizedPerturbedEquilibrium.Vacuum.FileWall — Type
FileWall(; file, equal_arc_wall=true)Wall contour read from a text file: the point count, a reference major radius and a header line, then one index R Z row per point, with at least mtheta points.
Fields
file::String: Path to the wall fileequal_arc_wall::Bool: Equal arc length node distribution, seeWallSettings
GeneralizedPerturbedEquilibrium.Vacuum.GaussLegendreRule — Type
GaussLegendreRule{N,T}Allocation-free Gauss–Legendre nodes/weights on the canonical interval [-1, 1]. Stored as SVectors so tight loops can index them efficiently.
GeneralizedPerturbedEquilibrium.Vacuum.KernelWorkspace — Type
Thread-local scratch for compute_3D_kernel_matrices!. One instance per thread so the parallel observer loop does not race.
GeneralizedPerturbedEquilibrium.Vacuum.KernelWorkspace — Method
KernelWorkspace(PATCH_DIM, RAD_DIM, ANG_DIM)Preallocated patch, polar, and grid buffers for one observer row.
GeneralizedPerturbedEquilibrium.Vacuum.ModDeeWall — Type
ModDeeWall(; minor_radius=0.3, half_thickness=0.05, elongation=1.5, center_offset=0.0, triangularity=0.5, corner_sharpness=0.05, equal_arc_wall=true)Dee-shaped wall in absolute coordinates, independent of the plasma. Same shape parameters as DeeWall, except that minor_radius and center_offset are lengths in meters.
Fields
minor_radius::Float64: Minor radius of the wall in metershalf_thickness::Float64: Half-thickness parameterelongation::Float64: Elongation parametercenter_offset::Float64: Major radius of the wall center in meterstriangularity::Float64: Triangularity parametercorner_sharpness::Float64: Sharpness of the corners (try 0.05 as initial value)equal_arc_wall::Bool: Equal arc length node distribution, seeWallSettings
GeneralizedPerturbedEquilibrium.Vacuum.PlasmaGeometry — Type
PlasmaGeometryStruct holding plasma geometry data on the mtheta grid for vacuum calculations. Arrays are of length mtheta, where mtheta is the number of poloidal grid points and θ ∈ [0, 1).
Fields
x::Vector{Float64}: Plasma surface R-coordinate on the vacuum (counter-clockwise) theta gridz::Vector{Float64}: Plasma surface Z-coordinate on the vacuum (counter-clockwise) theta gridν::Vector{Float64}: Toroidal offset ν = ϕ - ζ in radians on the vacuum theta grid
GeneralizedPerturbedEquilibrium.Vacuum.PlasmaGeometry — Method
PlasmaGeometry(inputs::VacuumInput) -> PlasmaGeometryInterpolate the input plasma boundary onto the mtheta grid with periodic cubic splines.
Arguments
inputs::VacuumInput: Struct containing plasma boundary data
Returns
PlasmaGeometry: Plasma surfacex,zandνon the vacuum grid
GeneralizedPerturbedEquilibrium.Vacuum.PlasmaGeometry3D — Type
PlasmaGeometry3D3D plasma surface for the vacuum boundary integral: Cartesian points, tangent vectors and normals on the mtheta × nzeta grid, poloidal index fastest.
Fields
mtheta::Int: Number of poloidal grid pointsnzeta::Int: Number of toroidal grid pointsr::Matrix{Float64}: Surface points in Cartesian (X,Y,Z), shape (num_points, 3)dr_dθ::Matrix{Float64}: Poloidal tangent vector ∂r/∂θ, shape (num_points, 3)dr_dζ::Matrix{Float64}: Toroidal tangent vector ∂r/∂ζ, shape (num_points, 3)normal::Matrix{Float64}: Unnormalized normals ∂r/∂θ × ∂r/∂ζ, oriented into the plasma (out of the vacuum), shape (num_points, 3)normal_orient::Int: Sign (+1 or -1) applied to ∂r/∂θ × ∂r/∂ζ to getnormal
GeneralizedPerturbedEquilibrium.Vacuum.PlasmaGeometry3D — Method
PlasmaGeometry3D(inputs::VacuumInput) -> PlasmaGeometry3DBuild the 3D plasma surface on the mtheta × nzeta grid in (θ, ζ). An axisymmetric boundary (nzeta_in == 1) is revolved from its 2D contour, placing each point at ϕ = ζ + ν(θ); a 3D boundary is interpolated from its input grid. Tangents come from periodic bicubic splines and normals point into the plasma.
Arguments
inputs::VacuumInput: Struct containing plasma boundary data and the vacuum grid size
Returns
PlasmaGeometry3D: Struct containing surface points, tangents, and oriented normals
GeneralizedPerturbedEquilibrium.Vacuum.PnQuadEntry — Type
PnQuadEntryCached sinh/cosh values for the 32-point Gaussian quadrature at toroidal mode number n, as 32-element vectors indexed by Gauss node ig, plus the n-only scale factors of the final Legendre values: gauss_norm_n = √2 / (n √π Γ(1/2 - n)) for P^n{-1/2} and `gaussnormnp1 = √2 / ((n+1) √π Γ(-1/2 - n))` for P^{n+1}{-1/2}.
GeneralizedPerturbedEquilibrium.Vacuum.SingularQuadratureData — Type
SingularQuadratureDataPrecomputed polar singular-correction quadrature (Malhotra JCP 397 (2019) 108791, Sec. 3.2).
Fields
Gpou::Matrix{Float64}: Partition of unity on the Cartesian patch,Gpou = -χ(PATCHDIM × PATCHDIM)Ppou::Matrix{Float64}: Partition of unity times polar quadrature weights (RADDIM × ANGDIM)P2G::SparseMatrixCSC{Float64,Int}: Lagrange interpolation matrix (Ngrid × Npolar):polar = P2G' * patch,grid = P2G * polarPATCH_DIM::Int: Patch width2 * PATCH_RAD + 1PATCH_RAD::Int: Number of points on each side of the source point treated as singularANG_DIM::Int: Number of angular quadrature pointsRAD_DIM::Int: Number of radial quadrature pointsINTERP_ORDER::Int: Lagrange interpolation order
GeneralizedPerturbedEquilibrium.Vacuum.SingularQuadratureData — Method
SingularQuadratureData(PATCH_RAD, RAD_DIM, INTERP_ORDER)Build the polar quadrature, partitions of unity, and Lagrange interpolant for the singular patch. ANG_DIM = 2 * RAD_DIM. INTERP_ORDER must be ≤ 2 * PATCH_RAD + 1.
Arguments
PATCH_RAD::Int: Number of points adjacent to source point to treat as singularRAD_DIM::Int: Radial quadrature orderINTERP_ORDER::Int: Lagrange interpolation order
Returns
SingularQuadratureData: Precomputed quadrature data
GeneralizedPerturbedEquilibrium.Vacuum.StellSymBasis — Type
StellSymBasisUnitary change of basis U for residue class k making U†D̂ₖU real, and block-diagonal when the class is self-conjugate. Both Laplace kernels depend only on |r_obs − r_src| and n_src·(r_obs − r_src), so a stellarator-symmetric boundary gives
D̂ₖ[σp, σq] = ω^{k(a_p − a_q)} · conj(D̂ₖ[p, q]), ω = exp(-2πi/nfp),with σ the within-period reflection (θ, ζ) → (−θ, −ζ) and a_p = 0 on the ζ = 0 plane, 1 elsewhere. Pairing p with σp into a symmetric and an antisymmetric column makes the result real; a self-conjugate class (is_self_conjugate) has real D̂ₖ and splits by the sign of ω^{k a_p}.
Fields
σ_map:σas a grid-index map of1:num_points_per_fpσ_phase:ω^{k a_p}, relating a pair's two operator rowspair_reps: one grid index per reflection pair (partner isσ_map[p])columns,pair_columns: basis columns, and the range each pair contributesblock_sizes: columns per surface in each block (lengthis 1 or 2)
GeneralizedPerturbedEquilibrium.Vacuum.StellSymBasis — Method
StellSymBasis(σ_map, mtheta, k, nfp)Build the symmetry-adapted basis for toroidal residue class k.
GeneralizedPerturbedEquilibrium.Vacuum.SymmetryColumn — Type
Column cp·e_p + cq·e_q of the symmetry-adapted basis, at slot of block. A grid point the reflection fixes has q == p and cq == 0.
GeneralizedPerturbedEquilibrium.Vacuum.VacuumInput — Type
VacuumInputPlasma boundary, mode numbers and grid sizes for a vacuum calculation. An axisymmetric boundary (nzeta_in = 1) needs x, z and toroidal offset ν; a non-axisymmetric one (nzeta_in > 1) needs x, y and z. Either runs as a 2D (nzeta = 1) or 3D (nzeta > 1) calculation. Arrays cover one field period with endpoints excluded. A 2D contour, or the ζ = 0 cross-section of a 3D boundary, must run counter-clockwise in the (R, Z) plane (GPEC's θ direction); the returned operators are in the Fourier frame of the grid passed in.
Fields
x::Vector{Float64}: Plasma boundary X-coordinate (length mthetain * nzetain)y::Vector{Float64}: Plasma boundary Y-coordinate (length mthetain * nzetain)z::Vector{Float64}: Plasma boundary Z-coordinate (length mthetain * nzetain)ν::Vector{Float64}: Toroidal offset ν = ϕ - ζ in radians (GPEC'srzphi_nu; ζ here is in radians, not turns) on input theta grid (axisymmetric only, length mtheta_in)mtheta_in::Int: Number of input poloidal grid pointsnzeta_in::Int: Number of input toroidal grid points (1 for axisymmetric, > 1 for non-axisymmetric)m_modes::Vector{Int}: Vector of poloidal mode numbers. E.g.collect(mlow:mhigh)for a contiguous range.n_modes::Vector{Int}: Vector of toroidal mode numbers. E.g.collect(nlow:nhigh)for a contiguous range orcollect(nlow:n_stride:nhigh)for a strided list for stellarator mode-family calculations.mtheta::Int: Number of vacuum calculation poloidal grid pointsnzeta::Int: Number of vacuum calculation toroidal grid points (1 for 2D vacuum calculation, > 1 for 3D vacuum calculation)nfp::Int: Number of field periods
GeneralizedPerturbedEquilibrium.Vacuum.VacuumInput — Method
VacuumInput(
equil::Equilibrium.PlasmaEquilibrium,
ψ::Float64,
mtheta::Int,
nzeta::Int,
m_modes::AbstractVector{<:Integer},
n_modes::AbstractVector{<:Integer};
) -> VacuumInputBuild a VacuumInput from the plasma surface of equil at flux surface ψ.
Arguments
equil: Equilibrium solutionψ: Normalized flux coordinatemtheta: Number of vacuum calculation poloidal pointsnzeta: Number of vacuum calculation toroidal points (1 for 2D, >1 for 3D)m_modes: Poloidal mode numbers (e.g.mlow:mhigh)n_modes: Toroidal mode numbers (e.g.[n]for a single mode, ornlow:nhigh)
Returns
VacuumInput ready for compute_vacuum_response.
GeneralizedPerturbedEquilibrium.Vacuum.VacuumResponse — Type
VacuumResponseOutput of compute_vacuum_response: the vacuum energy matrix and the surface data the boundary-integral solve produces along the way.
Fields
wv::Matrix{ComplexF64}: Vacuum energy matrix Wᵛ (num_modes × num_modes), block-diagonal in n for 2D and inmod(n, nfp)for 3DI_v::Matrix{ComplexF64}: Vacuum surface-current matrix Iᵛ (num_modes × num_modes), left zeroed unlesscompute_vacuum_responseis called withcompute_Iv=true. Stored without theμ₀/4π²normalization: the physical surface inductance isμ₀(2π)²·I_v⁻¹(seePerturbedEquilibrium.calc_surface_inductance). In 3D it differences two solves, so it needs a finer toroidal grid thanwvto converge.plasma_pts,wall_pts::Matrix{Float64}: Cartesian surface coordinates (num_points × 3)
GeneralizedPerturbedEquilibrium.Vacuum.VacuumResponse — Method
VacuumResponse(inputs::VacuumInput) -> VacuumResponseAllocate zeroed output arrays sized for inputs (full torus, so nfp field periods).
GeneralizedPerturbedEquilibrium.Vacuum.WallGeometry — Type
WallGeometryStruct holding wall geometry data for vacuum calculations. Arrays are of length mtheta, where mtheta is the number of poloidal grid points and θ ∈ [0, 1).
Fields
nowall::Bool: Boolean flag indicating if there is no wallx::Vector{Float64}: Wall R-coordinatesz::Vector{Float64}: Wall Z-coordinates
GeneralizedPerturbedEquilibrium.Vacuum.WallGeometry — Method
WallGeometry(inputs::VacuumInput, plasma_surf::PlasmaGeometry, wall_settings::Union{Nothing,WallSettings}) -> WallGeometryBuild the 2D wall contour on the mtheta grid from wall_settings, counter-clockwise like the plasma.
Arguments
inputs::VacuumInput: Struct containing vacuum calculation parametersplasma_surf::PlasmaGeometry: Struct with plasma surface geometry (used for reference)wall_settings::Union{Nothing,WallSettings}: Wall shape settings, ornothingfor no wall
Returns
WallGeometry: Wall R and Z coordinates (nowall = trueand zeroed arrays whenwall_settingsisnothing)
GeneralizedPerturbedEquilibrium.Vacuum.WallGeometry3D — Type
WallGeometry3D3D wall surface for the vacuum boundary integral. Arrays have mtheta * nzeta rows, poloidal index fastest.
Fields
nowall::Bool:truewhen there is no wall (all arrays zero)mtheta::Int: Number of poloidal grid pointsnzeta::Int: Number of toroidal grid pointsr::Matrix{Float64}: Cartesian (x, y, z) wall coordinates, shape (num_points, 3)dr_dθ::Matrix{Float64}: Poloidal tangent vector ∂r/∂θ, shape (num_points, 3)dr_dζ::Matrix{Float64}: Toroidal tangent vector ∂r/∂ζ, shape (num_points, 3)normal::Matrix{Float64}: Unnormalized normals, oriented outward (out of the vacuum), shape (num_points, 3)normal_orient::Int: Sign (+1 or -1) applied to ∂r/∂θ × ∂r/∂ζ to getnormal
GeneralizedPerturbedEquilibrium.Vacuum.WallGeometry3D — Method
WallGeometry3D(inputs::VacuumInput, plasma_surf::PlasmaGeometry3D, wall_settings::Union{Nothing,WallSettings}) -> WallGeometry3D3D counterpart of WallGeometry, selecting the shape the same way: an axisymmetric boundary builds the 2D poloidal contour and revolves it, so every shape WallGeometry offers is available; a non-axisymmetric boundary offsets the plasma surface.
Expects a full-torus boundary on the same mtheta/nzeta grid as plasma_surf, and nfp == 1; expand_field_periods produces both from a per-period non-axisymmetric boundary.
Arguments
inputs::VacuumInput: Struct containing vacuum calculation parametersplasma_surf::PlasmaGeometry3D: Plasma surface the wall is built around (used by the conformal wall)wall_settings::Union{Nothing,WallSettings}: Wall shape settings, ornothingfor no wall
Returns
WallGeometry3D: Wall surface coordinates, tangents and outward normals
Notes
- Axisymmetric boundaries (
nzeta_in == 1) takenothing(no wall),ConformalWall,EllipticalWall,DeeWall,ModDeeWallorFileWall; non-axisymmetric boundaries takenothingorConformalWall - The non-axisymmetric conformal wall displaces each plasma point along its own normal, so wall grid index
(i, j)is the closest wall point to plasma index(i, j)— the correspondence the near-field patch ofcompute_3D_kernel_matrices!assumes. The revolved branch does not share it: the wall sits on the geometric angle ϕ whilePlasmaGeometry3Dplaces the plasma on ζ = ϕ − ν(θ), andequal_arc_wallre-parameterizes poloidally on top of that - Rejects a conformal offset that folds the surface, and warns when the plasma–wall gap is smaller than one cell of the coarser grid (the double-layer near-field quadrature cannot resolve it). Both fold tests are local, so a global self-intersection between distant lobes — where the offset surface meets itself with aligned normals and a positive area element — passes them
GeneralizedPerturbedEquilibrium.Vacuum.WallSettings — Type
WallSettingsAbstract supertype of the vacuum wall shapes: ConformalWall, EllipticalWall, DeeWall, ModDeeWall and FileWall. A run with no wall has no WallSettings at all; the wall is nothing, and the deck omits its [Wall] section.
Every shape carries equal_arc_wall::Bool (default true), which redistributes the wall nodes to equal arc length (recommended unless the wall is very close to the plasma). Re-parameterizing the contour breaks the plasma/wall grid index correspondence that the singular quadrature relies on, so it is ignored outright for nzeta_in > 1 walls.
A non-axisymmetric boundary (nzeta_in > 1) supports only ConformalWall; the other shapes are poloidal contours that get revolved and so need nzeta_in == 1.
GeneralizedPerturbedEquilibrium.Vacuum.Pn_minus_half_1997 — Method
Pn_minus_half_1997(s, n) -> Vector{Float64}Legendre functions of the first kind P^n_{-1/2}(s) by upward recurrence (Chance 1997 eq. 47) from the elliptic-integral base cases (eqs. 48-50, with the eq. 50 exponent typo corrected).
Arguments
s::Real: Legendre function parameter (s > 1)n::Int: Maximum order n (n ≥ 0)
Returns
P::Vector{Float64}: Array of values P^0{-1/2}(s) through P^{n+1}{-1/2}(s)
GeneralizedPerturbedEquilibrium.Vacuum.Pn_minus_half_2007 — Method
Pn_minus_half_2007(s, n) -> Vector{Float64}Legendre functions of the first kind P^n{-1/2}(s) by the method of Chance, J. Comput. Phys. 221 (2007) 330-348: Bulirsch elliptic integrals for the base cases, then Gaussian integration when n * rhohat >= 0.1 (rhohat = 1/√(2yw)) and upward recurrence otherwise. More accurate than `Pnminushalf1997` at large n.
Arguments
s::Real: Legendre function parameter (s > 1)n::Int: Maximum order n (n ≥ 0)
Returns
P::Vector{Float64}: P^0{-1/2}(s), P^1{-1/2}(s), then P^n{-1/2}(s) and P^{n+1}{-1/2}(s) in the last two slots (rest zero)
GeneralizedPerturbedEquilibrium.Vacuum._compute_vacuum_response_2d! — Method
_compute_vacuum_response_2d!(vac_data::VacuumResponse, inputs::VacuumInput, wall_settings::Union{Nothing,WallSettings}; compute_Iv=false)2D (axisymmetric) vacuum response. Each toroidal mode n decouples, so each is one exterior solve for its wv block, plus an interior solve for I_v when compute_Iv=true.
GeneralizedPerturbedEquilibrium.Vacuum._compute_vacuum_response_3d! — Method
_compute_vacuum_response_3d!(vac_data, inputs, wall_settings; compute_Iv=false)3D (inputs.nzeta > 1) vacuum response via block-circulant field-period reduction.
The nfp-periodic boundary makes the layer operators block-circulant in the field-period index, so the problem block-diagonalizes by toroidal residue class k = mod(n, nfp):
D̂ₖ = Σ_d D_d ω^{k d}, Ŝₖ = Σ_d S_d ω^{k d}, ω = exp(-2πi/nfp),with D_d, S_d coupling observers in field period 0 to sources in period d. Each class is one solve wv[k] = (4π²/M)·Ẽᴴ·(D̂ₖ \ Ŝₖ)|_plasma·Ẽ, the 3D analogue of the 2D loop over decoupled n. The phase sum is folded into the kernel write, so only the reduced operator is stored.
Real D_d, S_d give D̂₋ₖ = conj(D̂ₖ), so class mod(nfp - k, nfp) reuses this factorization with a conjugated mode basis. A stellarator-symmetric boundary gets a StellSymBasis, making the class operator real and splitting a self-conjugate class into two half-size blocks.
GeneralizedPerturbedEquilibrium.Vacuum._solve_projected_rhs! — Method
_solve_projected_rhs!(grre, grri, Ẽ, op, scratch)Form S Ẽᴴ and solve D \ · into grre (exterior) and optionally grri (interior). op = (; green, lu_ext, lu_int) with lu_int === nothing when I_v is not needed. scratch = (; basis_real, rhs_real, rhs_real_int) holds the [Re Im] workspace for a real operator. A real green uses that split because BLAS has no mixed real/complex product.
GeneralizedPerturbedEquilibrium.Vacuum._unsplit! — Method
_unsplit!(dest, split)Recombine a real [Re Im] column pair into the complex dest.
GeneralizedPerturbedEquilibrium.Vacuum._warn_and_symmetrize! — Method
_warn_and_symmetrize!(mat, name)Replace mat by its Hermitian part in place, warning first if the anti-Hermitian residual exceeds _HERMITICITY_WARN_TOL.
The matrices passed here are Hermitian in exact arithmetic — δW_v = ξ†Wᵛξ is a real energy, and Iᵛ is the inverse of the Hermitian surface inductance up to a real scalar — so any anti-Hermitian part is a discretization artifact that vanishes as the vacuum grid is refined.
GeneralizedPerturbedEquilibrium.Vacuum.assert_counterclockwise — Method
assert_counterclockwise(x, z, name)Throw unless the closed (x, z) contour runs counter-clockwise. The 2D kernel takes its normals from the direction of travel, so a clockwise contour would give a wrong operator silently.
GeneralizedPerturbedEquilibrium.Vacuum.compute_2D_kernel_matrices! — Method
compute_2D_kernel_matrices!(grad_greenfunction, greenfunction, observer, source, n)Compute kernels of integral equation for Laplace's equation in a torus. WARNING: This kernel only supports closed toroidal walls currently. The residue calculation needs to be updated for open walls.
Arguments
grad_greenfunction: Gradient Green's function matrix (output)greenfunction: Green's function matrix (output)observer: Observer geometry struct (PlasmaGeometry or WallGeometry)source: Source geometry struct (PlasmaGeometry or WallGeometry)n: Toroidal mode number
Returns
Modifies grad_greenfunction and greenfunction in place. Note that greenfunction is zeroed only when the source is plasma; grad_greenfunction is not zeroed since it fills a different block of the (2 * mtheta, 2 * mtheta) depending on the source/observer.
Notes
- Uses Simpson's rule for integration away from singular points
- Uses Gaussian quadrature near singular points for improved accuracy
- Implements analytical singularity removal [Chance Phys. Plasmas 1997 2161]
GeneralizedPerturbedEquilibrium.Vacuum.compute_3D_kernel_matrices! — Function
compute_3D_kernel_matrices!(grad_blocks, green_blocks, observer, source, PATCH_RAD, RAD_DIM, INTERP_ORDER, phases, sym_basis=nothing)3D single- and double-layer kernels with Malhotra's polar singular correction (PPCF 62 (2020) 024004).
Far field: trapezoidal rule. Near field: polar quadrature blended by a partition of unity.
A source in field period d is accumulated onto the period-0 column with weight phases[d+1], so the block-circulant reduction is written in and the full-torus source blocks are never stored. phases = [1.0] is the single-period (real) case.
grad_blocks is ∇_{x_src} φ · n_src; green_blocks is φ, filled only when source is the plasma (Chance 1997 eqs. 26–27). sym_basis evaluates one point per reflection pair and emits the real reduced operator; omit it for the untransformed matrix.
GeneralizedPerturbedEquilibrium.Vacuum.compute_polar_normal! — Method
compute_polar_normal!(n_polar, dr_dθ, dr_dζ, normal_orient)n = ∂r/∂θ × ∂r/∂ζ at the polar nodes. Re-apply normal_orient: these normals are rebuilt from interpolated tangents, so they do not inherit the stored surface orientation.
GeneralizedPerturbedEquilibrium.Vacuum.compute_vacuum_response! — Method
compute_vacuum_response!(vac_data::VacuumResponse, inputs::VacuumInput, wall_settings::Union{Nothing,WallSettings}; compute_Iv=false)Compute the vacuum response into vac_data. 2D (inputs.nzeta == 1) and 3D otherwise. Pass compute_Iv=true to also fill the surface-current matrix I_v.
GeneralizedPerturbedEquilibrium.Vacuum.compute_vacuum_response — Method
compute_vacuum_response(inputs::VacuumInput, wall_settings::Union{Nothing,WallSettings}; compute_Iv=false) -> VacuumResponseAllocating version of compute_vacuum_response!.
GeneralizedPerturbedEquilibrium.Vacuum.cross3! — Method
cross3!(c, a, b, idx)Write the cross product of rows idx of the (N, 3) matrices a and b into row idx of c.
GeneralizedPerturbedEquilibrium.Vacuum.distribute_to_equal_arc_grid — Method
distribute_to_equal_arc_grid(xin, zin)Resample the closed curve (xin, zin) (endpoint not repeated) to the same number of points equally spaced in arc length, returning (xout, zout). Same role as Fortran eqarcw, using periodic cubic splines.
GeneralizedPerturbedEquilibrium.Vacuum.elliptic_integral_e — Method
elliptic_integral_e(m1) -> Float64Polynomial approximation of the complete elliptic integral of the second kind at parameter 1 - m1. Takes the complementary parameter m1, not the modulus k.
GeneralizedPerturbedEquilibrium.Vacuum.elliptic_integral_k — Method
elliptic_integral_k(m1) -> Float64Polynomial approximation of the complete elliptic integral of the first kind at parameter 1 - m1. Takes the complementary parameter m1, not the modulus k.
GeneralizedPerturbedEquilibrium.Vacuum.elliptic_integrals_bulirsch — Method
elliptic_integrals_bulirsch(m1; error=1e-8, maxit=10)Complete elliptic integrals K and E at complementary parameter m1 by Bulirsch's algorithm. Port of Fortran ek3.
Arguments
m1::Float64: Complementary parameter (1 - k²), where k is the elliptic moduluserror::Float64: Convergence tolerance (default 1e-8)maxit::Int: Maximum iterations (default 10)
Returns
K::Float64: Complete elliptic integral of the first kind K(m1)E::Float64: Complete elliptic integral of the second kind E(m1)convergence::Float64: Convergence metriciterations::Int: Number of iterations performed
Precision is approximately error². See Chance, J. Comput. Phys. 221 (2007) 330-348.
GeneralizedPerturbedEquilibrium.Vacuum.expand_field_periods — Method
expand_field_periods(inputs::VacuumInput) -> VacuumInputReconstruct the full-torus boundary from a single field period using the device field periodicity. When inputs.nfp > 1 (and the boundary is 3D), the input x, y, z arrays describe one field period spanning ζ ∈ [0, 2π/nfp) on an mtheta_in × nzeta_in grid; the full torus is generated by nfp rigid rotations about the Z-axis by 2π·k/nfp. The toroidal counts nzeta_in and nzeta are scaled to their full-torus totals and nfp is reset to 1, so all downstream code operates on the full surface unchanged.
The result is identical (to floating point) to passing the whole torus directly.
Returns inputs unchanged for axisymmetric (nzeta_in == 1) or single-period (nfp <= 1) cases.
GeneralizedPerturbedEquilibrium.Vacuum.extract_patch! — Method
Extract a periodically wrapped PATCH_DIM × PATCH_DIM patch centered at (idx_pol_center, idx_tor_center).
GeneralizedPerturbedEquilibrium.Vacuum.extract_plasma_surface_at_psi — Method
extract_plasma_surface_at_psi(equil::Equilibrium.PlasmaEquilibrium, ψ::Float64) -> (r, z, ν)Evaluate the rzphi splines on the straight-field-line θ grid at normalized flux ψ (0 at axis, 1 at edge), returning the surface R, Z and toroidal angle offset ν, each of length mtheta. R = R₀ + r cos θ_cyl, Z = Z₀ + r sin θ_cyl with r = √rzphi_rsquared and θ_cyl = 2π(θ + rzphi_offset). Reference: Chance, Phys. Plasmas 1997 2161. Follows Fortran gpvacuum_flxsurf (gpvacuum.f).
GeneralizedPerturbedEquilibrium.Vacuum.get_conjugate_groups — Method
get_conjugate_groups(classes, nfp) -> Vector{Vector{Int}}Each class is a mode family k = mod(n, nfp). Group each with its conjugate family mod(nfp - k, nfp) when that class is present. Self-conjugate families (is_self_conjugate) never pair.
Returns a vector of groups; each group is a vector of indices into classes, with the representative first and its conjugate partner second when paired ([i] or [i, j]).
GeneralizedPerturbedEquilibrium.Vacuum.get_pn_quad_cache — Method
get_pn_quad_cache(n::Int) -> PnQuadEntryReturn cached sinh/cosh values for toroidal mode n, computing on first access. Takes a lock, so call it once per kernel call and pass the entry down.
GeneralizedPerturbedEquilibrium.Vacuum.get_singular_quadrature — Method
get_singular_quadrature(PATCH_RAD, RAD_DIM, INTERP_ORDER)Return the cached SingularQuadratureData, rebuilding it if the parameters changed. Takes a lock, so concurrent solves on different grids each get the data for their own parameters.
GeneralizedPerturbedEquilibrium.Vacuum.green — Method
green(x_obs, z_obs, x_source, z_source, dx_dtheta, dz_dtheta, n; gamma_prefactor, pn_cache, uselegacygreenfunction=false)Axisymmetric Green's function and its normal-derivative coupling terms, Chance 1997 eqs. 36-42. Port of Fortran green.
Arguments
x_obs: Observation point R-coordinate (Float64)z_obs: Observation point Z-coordinate (Float64)x_source: Source point R-coordinate (Float64)z_source: Source point Z-coordinate (Float64)dx_dtheta: Derivative ∂R'/∂θ at source point (Float64)dz_dtheta: Derivative ∂Z'/∂θ at source point (Float64)n: Toroidal mode number (Int)gamma_prefactor:2√π · Γ(1/2 - n)(Chance 1997 eq. 40); tight-loop callers compute it once and pass it in.pn_cache:get_pn_quad_cache(n); takes a lock, so tight-loop callers look it up once and pass it in.uselegacygreenfunction::Bool: Flag to use the 1997 version of the Legendre function (default false, uses 2007 version)
Returns
G_n: 2π𝒢ⁿ(θ,θ′) — Green's function valuecoupling_n: 𝒥 ∇'𝒢ⁿ∇'ℒ — Coupling term for mode ncoupling_0: 1/(2π) 𝒥 ∇'𝒢⁰∇'ℒ — Coupling term for mode 0
GeneralizedPerturbedEquilibrium.Vacuum.interpolate_to_polar! — Method
Interpolate a Cartesian patch onto polar quadrature nodes: polar = P2G' * patch.
GeneralizedPerturbedEquilibrium.Vacuum.is_self_conjugate — Method
Whether residue class k is its own conjugate (ω^k = ±1), so D̂ₖ and the field-period phases are real.
GeneralizedPerturbedEquilibrium.Vacuum.laplace_kernel — Method
laplace_kernel(ox, oy, oz, sx, sy, sz, nx, ny, nz) -> (single, double)Fused Laplace kernels: single = 1/r, double = (Δx·n)/r³. Shares √(r²); returns (0, 0) at coincidence (r² < 1e-30).
GeneralizedPerturbedEquilibrium.Vacuum.parse_wall — Method
parse_wall(section) -> Union{Nothing,WallSettings}Build the wall from the [Wall] section of a deck, or return nothing (no wall) when there is no section. The section's shape picks the WallSettings type. Keys that type does not use are rejected with an error, and a parameter it requires (such as file for FileWall) is an error if missing.
GeneralizedPerturbedEquilibrium.Vacuum.periodic_wrap — Method
periodic_wrap(x, n) -> Intmod1(x, n) without a division. Only valid for 1 - n ≤ x ≤ 2n.
GeneralizedPerturbedEquilibrium.Vacuum.precompute_lagrange_stencils — Method
precompute_lagrange_stencils(gaussian_points)Precompute 5-point Lagrange interpolation stencils for Gaussian quadrature points.
Returns a tuple (left, right) where each entry is a Vector of SVector{5,Float64} containing the stencil weights for points on the left/right panel.
GeneralizedPerturbedEquilibrium.Vacuum.reflect_index — Method
Grid index of (θ, ζ) → (−θ, −ζ) for the linear index p = i_θ + mtheta·(i_ζ − 1).
GeneralizedPerturbedEquilibrium.Vacuum.reset_caches! — Method
reset_caches!()Empty Vacuum's run-filled module-level caches: the per-n Legendre quadrature entries and the singular-quadrature data. Called after the precompile workload so no run state is serialized into the package image.
GeneralizedPerturbedEquilibrium.Vacuum.signed_area — Method
signed_area(x, z)Shoelace area of the closed (x, z) contour: positive when it runs counter-clockwise.
GeneralizedPerturbedEquilibrium.Vacuum.stell_sym_map — Method
stell_sym_map(plasma, wall, nfp) -> Union{Vector{Int},Nothing}Within-period map of (θ, ζ) → (−θ, −ζ) if both surfaces are stellarator symmetric to 1e-10 of the largest coordinate, nothing otherwise. A nearly symmetric boundary (e.g. one extracted from an equilibrium, off by ~1e-3) is rejected and takes the general path; this test is the only guard on the symmetric path.
GeneralizedPerturbedEquilibrium.Vacuum.store_kernel_row! — Method
store_kernel_row!(blocks, sym_basis, kernel_row, scratch, i_pair, row_index, col_index)Write one accumulated kernel row into blocks. With a StellSymBasis, reconstruct the partner row from the reflection identity and emit U†DU; sym_basis === nothing stores the row as-is. i_pair indexes the observer list (every period-0 point, or one representative per pair). row_index/col_index are 1 = plasma, 2 = wall. scratch needs 2·npts when a basis is present.
GeneralizedPerturbedEquilibrium.Vacuum.transform_mode_basis! — Method
transform_mode_basis!(E_out, E, sym_basis; conjugate=false)Write E_out = E·U into E_out[b] per block. U is unitary, so substituting E_out for E leaves the RHS, the wv projection and I_v unchanged. conjugate=true gives conj(E)·U for this class's conjugate partner. sym_basis === nothing is the identity.
GeneralizedPerturbedEquilibrium.Vacuum.compute_vacuum_response — Function
compute_vacuum_response(inputs::VacuumInput, wall_settings::Union{Nothing,WallSettings}; compute_Iv=false) -> VacuumResponseAllocating version of compute_vacuum_response!.