diff --git a/docs/src/vacuum.md b/docs/src/vacuum.md index bb928c53a..3b7473669 100644 --- a/docs/src/vacuum.md +++ b/docs/src/vacuum.md @@ -66,6 +66,7 @@ With `[ForceFreeStates] nzeta_vacuum > 1` the response is evaluated on a toroida - 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. +- Close walls: plasma–wall rows are integrated about the closest point of the source surface, so the wall's node placement (`equal_arc_wall`, wall files, a revolved wall with ν ≠ 0) does not matter. Both use Gauss nodes on the sinh map of [Johnston & Elliott, Int. J. Numer. Meth. Engng 62 (2005) 564], which follows the kernel peak over the gap: in 2D on ±6 node intervals about the closest point, in 3D radially in the polar patch centred at the closest point. Rows more than 4 source node spacings from the source take the plain trapezoidal rule. ``W^v`` keeps its far-wall convergence down to gaps of a few hundredths of a node spacing; a wall touching the plasma is rejected. Each observer uses its single closest point, so a wall close to two separate parts of the plasma is treated only at the nearer one. ## API reference diff --git a/src/Vacuum/DataTypes.jl b/src/Vacuum/DataTypes.jl index 8559f676b..483596526 100644 --- a/src/Vacuum/DataTypes.jl +++ b/src/Vacuum/DataTypes.jl @@ -187,9 +187,8 @@ Abstract supertype of the vacuum wall shapes: [`ConformalWall`](@ref), [`Ellipti `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. +to equal arc length. Plasma–wall near pairs are found by distance, so any node placement works; +it is ignored for `nzeta_in > 1` walls, as it re-parameterizes a 2D contour. A non-axisymmetric boundary (`nzeta_in > 1`) supports only [`ConformalWall`](@ref); the other shapes are poloidal contours that get revolved and so need `nzeta_in == 1`. @@ -331,13 +330,22 @@ of length `mtheta`, where `mtheta` is the number of poloidal grid points and θ - `x::Vector{Float64}`: Plasma surface R-coordinate on the vacuum (counter-clockwise) theta grid - `z::Vector{Float64}`: Plasma surface Z-coordinate on the vacuum (counter-clockwise) theta grid - `ν::Vector{Float64}`: Toroidal offset ν = ϕ - ζ in radians on the vacuum theta grid + - `dx_dθ`, `dz_dθ::Vector{Float64}`: Poloidal derivatives ∂R/∂θ, ∂Z/∂θ on the vacuum theta grid + - `spline_x`, `spline_z`: Periodic cubic splines of `x(θ)` and `z(θ)` on `[0, 2π)` """ -struct PlasmaGeometry +struct PlasmaGeometry{S} x::Vector{Float64} z::Vector{Float64} ν::Vector{Float64} + dx_dθ::Vector{Float64} + dz_dθ::Vector{Float64} + spline_x::S + spline_z::S end +PlasmaGeometry(x::Vector{Float64}, z::Vector{Float64}, ν::Vector{Float64}=zeros(length(x))) = + PlasmaGeometry(x, z, ν, periodic_splines(x, z)...) + """ WallGeometry @@ -349,13 +357,22 @@ Struct holding wall geometry data for vacuum calculations. Arrays are of length - `nowall::Bool`: Boolean flag indicating if there is no wall - `x::Vector{Float64}`: Wall R-coordinates - `z::Vector{Float64}`: Wall Z-coordinates + - `dx_dθ`, `dz_dθ::Vector{Float64}`: Poloidal derivatives ∂R/∂θ, ∂Z/∂θ on the vacuum theta grid + - `spline_x`, `spline_z`: Periodic cubic splines of `x(θ)` and `z(θ)` on `[0, 2π)` (`nothing` when `nowall`) """ -struct WallGeometry +struct WallGeometry{S} nowall::Bool x::Vector{Float64} z::Vector{Float64} + dx_dθ::Vector{Float64} + dz_dθ::Vector{Float64} + spline_x::S + spline_z::S end +WallGeometry(nowall::Bool, x::Vector{Float64}, z::Vector{Float64}) = + WallGeometry(nowall, x, z, (nowall ? (zero(x), zero(z), nothing, nothing) : periodic_splines(x, z))...) + """ PlasmaGeometry(inputs::VacuumInput) -> PlasmaGeometry @@ -463,7 +480,7 @@ function PlasmaGeometry3D(inputs::VacuumInput) # Tangent and normal vectors of the trigonometric interpolant, which converge spectrally with the grid dr_dθ, dr_dζ = trig_tangents(r, mtheta, nzeta) for idx in 1:num_points - cross3!(normal, dr_dθ, dr_dζ, idx) + normal[idx, :] = cross(SVector{3}(@view dr_dθ[idx, :]), SVector{3}(@view dr_dζ[idx, :])) end # Determine normal orientation (inward for plasma) and enforce it @@ -495,6 +512,7 @@ end WallGeometry(inputs::VacuumInput, plasma_surf::PlasmaGeometry, wall_settings::Union{Nothing,WallSettings}) -> WallGeometry Build the 2D wall contour on the `mtheta` grid from `wall_settings`, counter-clockwise like the plasma. +Throws if the wall touches or crosses the plasma; warns when the gap is under a tenth of a grid cell. # Arguments @@ -633,8 +651,22 @@ function WallGeometry(inputs::VacuumInput, plasma_surf::PlasmaGeometry, wall_set # R ≤ 0 walls would need the extra kernel singularity handling of Chance's Fortran code any(x_wall .<= 0.0) && error("Wall R-coordinates contain non-physical values (R <= 0). Check wall geometry.") assert_counterclockwise(x_wall, z_wall, "Wall") - - return WallGeometry(false, x_wall, z_wall) + wall = WallGeometry(false, x_wall, z_wall) + + # Each surface's kernel rows see the other, so check the clearance from both sides: `cp.d` is signed outward from `src` + # (+1 for the wall outside the plasma, -1 for the plasma inside the wall), and the gap is resolved down to MIN_WALL_GAP_CELLS coarser cells + cells = Inf + for (obs, src, side) in ((wall, plasma_surf, 1), (plasma_surf, wall, -1)) + for i in eachindex(obs.x) + cp = closest_point(src, obs.x[i], obs.z[i]) + side * cp.d > 0 || throw(ArgumentError("plasma and wall touch or cross near (R, Z) = ($(obs.x[i]), $(obs.z[i]))")) + cells = min(cells, abs(cp.d) / max(cp.h, hypot(obs.dx_dθ[i], obs.dz_dθ[i]) * 2π / mtheta)) + end + end + cells < MIN_WALL_GAP_CELLS && + @warn "Plasma–wall gap spans only $((@sprintf "%.2f" cells)) cells of the coarser grid at its narrowest. The near-field " * + "quadrature loses accuracy below a tenth of a cell. Refine mtheta, or move the wall out." + return wall end """ @@ -688,12 +720,12 @@ Expects a full-torus boundary on the same `mtheta`/`nzeta` grid as `plasma_surf` - Axisymmetric boundaries (`nzeta_in == 1`) take `nothing` (no wall), `ConformalWall`, `EllipticalWall`, `DeeWall`, `ModDeeWall` or `FileWall`; non-axisymmetric boundaries take `nothing` or `ConformalWall` - 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 of `compute_3D_kernel_matrices!` assumes. The revolved branch does not share it: the wall sits - on the geometric angle ϕ while `PlasmaGeometry3D` places the plasma on ζ = ϕ − ν(θ), and - `equal_arc_wall` re-parameterizes poloidally on top of that + index `(i, j)` is the closest wall point to plasma index `(i, j)`. The revolved branch does not share + this: the wall sits on the geometric angle ϕ while `PlasmaGeometry3D` places the plasma on ζ = ϕ − ν(θ), + and `equal_arc_wall` re-parameterizes poloidally on top of that. `compute_3D_kernel_matrices!` finds + the closest point itself, so either placement works - 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). + than a tenth of a cell of the coarser grid, where the near-field quadrature needs a finer grid. 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 """ @@ -764,7 +796,7 @@ function WallGeometry3D(inputs::VacuumInput, plasma_surf::PlasmaGeometry3D, wall elseif wall_settings isa ConformalWall # Displace every plasma point outward along its own normal wall_settings.equal_arc_wall && - @info "equal_arc_wall is ignored for non-axisymmetric (nzeta_in > 1) walls: it re-parameterizes a 2D contour and would break the plasma/wall index alignment the near-field patch relies on." + @info "equal_arc_wall is ignored for non-axisymmetric (nzeta_in > 1) walls: it re-parameterizes a 2D contour." # Same logic as 2D, with the extrema taken over the whole torus (see ConformalWall.standoff_fraction) R_plasma = [hypot(plasma_surf.r[idx, 1], plasma_surf.r[idx, 2]) for idx in axes(plasma_surf.r, 1)] @@ -788,7 +820,7 @@ function WallGeometry3D(inputs::VacuumInput, plasma_surf::PlasmaGeometry3D, wall # Tangent and normal vectors of the trigonometric interpolant, as on the plasma dr_dθ, dr_dζ = trig_tangents(r, mtheta, nzeta) for idx in 1:num_points - cross3!(normal, dr_dθ, dr_dζ, idx) + normal[idx, :] = cross(SVector{3}(@view dr_dθ[idx, :]), SVector{3}(@view dr_dζ[idx, :])) end # Determine normal orientation (outward for wall) and enforce it @@ -824,8 +856,8 @@ function WallGeometry3D(inputs::VacuumInput, plasma_surf::PlasmaGeometry3D, wall "(0° when resolved), where a sharp convex edge of the plasma fans out across the gap. Refine mtheta and nzeta until this is below 2°, or reduce the wall distance a." end - # The 3D singular quadrature resolves the double-layer kernel well only while the plasma-wall gap spans a - # grid cell or more. Taken pointwise, so an under-resolved patch is not averaged away by the rest of the surface. + # The closest-point patch of `add_near_correction!` resolves the double-layer kernel down to MIN_WALL_GAP_CELLS cells of the + # coarser grid. Taken pointwise, so an under-resolved patch is not averaged away by the rest of the surface. node_norm(A, idx) = hypot(A[idx, 1], A[idx, 2], A[idx, 3]) cells_per_point = [ gap[idx] / max( @@ -834,12 +866,12 @@ function WallGeometry3D(inputs::VacuumInput, plasma_surf::PlasmaGeometry3D, wall ) for idx in axes(r, 1) ] cells, worst = findmin(cells_per_point) - if cells < 1.0 + if cells < MIN_WALL_GAP_CELLS h_θ = max(node_norm(dr_dθ, worst), node_norm(plasma_surf.dr_dθ, worst)) * dθ h_ζ = max(node_norm(dr_dζ, worst), node_norm(plasma_surf.dr_dζ, worst)) * dζ @warn "Plasma–wall gap $((@sprintf "%.2e" gap[worst])) m spans only $((@sprintf "%.2f" cells)) cells of the coarser grid " * "at its worst-resolved point (h_θ=$((@sprintf "%.2e" h_θ)) m, h_ζ=$((@sprintf "%.2e" h_ζ)) m). The double-layer " * - "near-field quadrature is inaccurate below one cell. Refine the coarser of mtheta/nzeta, or move the wall out." + "near-field quadrature loses accuracy below a tenth of a cell. Refine the coarser of mtheta/nzeta, or move the wall out." end return WallGeometry3D( diff --git a/src/Vacuum/Kernel2D.jl b/src/Vacuum/Kernel2D.jl index 9a2d36004..926d9dcd1 100644 --- a/src/Vacuum/Kernel2D.jl +++ b/src/Vacuum/Kernel2D.jl @@ -1,63 +1,20 @@ -""" - GaussLegendreRule{N,T} - -Allocation-free Gauss–Legendre nodes/weights on the canonical interval [-1, 1]. -Stored as `SVector`s so tight loops can index them efficiently. -""" -struct GaussLegendreRule{N,T} - x::SVector{N,T} - w::SVector{N,T} -end - -@inline function gausslegendre_rule(::Val{N}) where {N} - x, w = gausslegendre(N) # canonical [-1, 1] - return GaussLegendreRule{N,Float64}( - SVector{N,Float64}(ntuple(i -> Float64(x[i]), N)), - SVector{N,Float64}(ntuple(i -> Float64(w[i]), N)) - ) +# 8-point Gauss–Legendre rule on [-1, 1] for the singular panels +const GL8_X, GL8_W = let (x, w) = gausslegendre(8) + SVector{8,Float64}(x), SVector{8,Float64}(w) end -# Precomputed Gauss-Legendre rule -const GL8 = gausslegendre_rule(Val(8)) - -""" - 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. -""" -function precompute_lagrange_stencils(gaussian_points::AbstractVector{<:Real}) - stencil_points = SVector(-2, -1, 0, 1, 2) - npts = length(gaussian_points) - left = Vector{SVector{5,Float64}}(undef, npts) - right = Vector{SVector{5,Float64}}(undef, npts) - - for ig in 1:npts - p_left = -1.0 + gaussian_points[ig] - p_right = 1.0 + gaussian_points[ig] - - left[ig] = ntuple(5) do i - xi = stencil_points[i] - prod(j -> j == i ? 1.0 : (p_left - stencil_points[j]) / (xi - stencil_points[j]), 1:5) - end |> SVector - - right[ig] = ntuple(5) do i - xi = stencil_points[i] - prod(j -> j == i ? 1.0 : (p_right - stencil_points[j]) / (xi - stencil_points[j]), 1:5) - end |> SVector - end - - return left, right -end - -# Precomputed 5-point Lagrange stencils for the 8-point Gaussian nodes. -const GL8_LAGRANGE_STENCILS = precompute_lagrange_stencils(GL8.x) +# 5-point Lagrange stencils (nodes -2:2 about the singular node) at the Gauss points of the left (-1 + x) and right (1 + x) panels; +# shifted by +2 because `lagrange_weights` indexes stencil nodes on 0:4 +const GL8_LAGRANGE_STENCILS = (lagrange_weights.(GL8_X .+ 1.0, Val(5)), lagrange_weights.(GL8_X .+ 3.0, Val(5))) # Pre-computed Gauss quadrature constants (_PN_TG02, _PN_WANUMR, _PN_AGAUS, _PN_BGAUS) # and per-n sinh/cosh cache are defined in PnQuadCache.jl. +# Near plasma–wall rows (gap < NEAR_GAP node spacings) are integrated over ±NEAR_WINDOW node intervals about the source +# point closest to the observer, on sinh-graded Gauss nodes: rules of 8–64 nodes, 8 per unit of the sinh variable +const NEAR_WINDOW = 6 +const NEAR_SINH = sinh_rule(8, 8, 1.0) + """ compute_2D_kernel_matrices!(grad_greenfunction, greenfunction, observer, source, n) @@ -82,11 +39,13 @@ grad_greenfunction is not zeroed since it fills a different block of the # 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] + - Same surface: Simpson's rule away from the singular point, Gaussian quadrature on the panels about it, with + analytical singularity removal [Chance Phys. Plasmas 1997 2161] + - Plasma–wall rows within `NEAR_GAP` node spacings of the source curve: Simpson's rule plus sinh-graded Gauss nodes + about the closest source point ([`add_near_window!`](@ref)), so the wall's node placement does not matter + - Other plasma–wall rows: periodic trapezoidal rule, as in 3D (error ∝ exp(-2πd/h), see `NEAR_GAP`) """ -@with_pool pool function compute_2D_kernel_matrices!( +function compute_2D_kernel_matrices!( grad_greenfunction::AbstractMatrix{Float64}, greenfunction::AbstractMatrix{Float64}, observer::Union{PlasmaGeometry,WallGeometry}, @@ -98,17 +57,15 @@ grad_greenfunction is not zeroed since it fills a different block of the dtheta = 2π / mtheta theta_grid = range(; start=0, length=mtheta, step=dtheta) - # Take a view of the corresponding block of the grad_greenfunction - col_index = (source isa PlasmaGeometry ? 1 : 2) + # Surface sub-block of the operator this call fills; 𝒢ⁿ is only needed for a plasma source (Chance 1997 eqs. 26–27) + populate_greenfunction = source isa PlasmaGeometry + col_index = populate_greenfunction ? 1 : 2 row_index = (observer isa PlasmaGeometry ? 1 : 2) grad_greenfunction_block = view( grad_greenfunction, ((row_index-1)*mtheta+1):(row_index*mtheta), ((col_index-1)*mtheta+1):(col_index*mtheta) ) - - # 𝒢ⁿ only needed for plasma as source term (RHS of eqs. 26/27 in Chance 1997) - populate_greenfunction = source isa PlasmaGeometry populate_greenfunction && fill!(greenfunction, 0.0) # S₁ᵢ logarithmic correction factors [Chance Phys. Plasmas 1997 2161 eq. 78] @@ -122,91 +79,25 @@ grad_greenfunction is not zeroed since it fills a different block of the gamma_prefactor = 2 * sqrt(π) * gamma(0.5 - n) pn_cache = get_pn_quad_cache(n) - # Set up periodic splines used for off-grid Gaussian quadrature points - spline_x = cubic_interp(theta_grid, source.x; bc=PeriodicBC(; endpoint=:exclusive, period=2π)) - spline_z = cubic_interp(theta_grid, source.z; bc=PeriodicBC(; endpoint=:exclusive, period=2π)) - d1_spline_x = deriv1(spline_x) - d1_spline_z = deriv1(spline_z) - - # Precompute 5-point Lagrange stencils for the 8-point Gaussian nodes. - stencils_left, stencils_right = GL8_LAGRANGE_STENCILS - sing_idx = zeros!(pool, Int, 5) - - # Source derivatives on the grid for the Simpson sum; the off-grid Gaussian points use the splines directly - dx_dtheta_grid = acquire!(pool, eltype(source.x), mtheta) - dz_dtheta_grid = acquire!(pool, eltype(source.z), mtheta) - - # Call in-place API to avoid allocations - d1_spline_x(dx_dtheta_grid, theta_grid) - d1_spline_z(dz_dtheta_grid, theta_grid) - for j in 1:mtheta - x_obs, z_obs, theta_obs = observer.x[j], observer.z[j], theta_grid[j] - - # Perform Simpson integration for nonsingular source points - # Nonsingular region endpoints are at j±2, so exclude j-1, j, and j+1. - @inbounds for k in 1:(mtheta-3) - isrc = mod1(j + 1 + k, mtheta) - G_n, gradG_n, gradG_0 = green(x_obs, z_obs, source.x[isrc], source.z[isrc], dx_dtheta_grid[isrc], dz_dtheta_grid[isrc], n; gamma_prefactor, pn_cache) - - # Composite Simpson's 1/3 rule weights, excluding singular points - # Note we set to 4 for even/2 for odd since we index from 1 while the formula assumes indexing from 0 - wsimpson = dtheta / 3 * ((k == 1 || k == mtheta - 3) ? 1 : (iseven(k) ? 4 : 2)) - - # Sum contributions to Green's function matrices using Simpson weight - if populate_greenfunction - greenfunction[j, isrc] += G_n * wsimpson - end - grad_greenfunction_block[j, isrc] += gradG_n * wsimpson - # Subtract regular integral component of δⱼᵢK⁰ [Chance Phys. Plasmas 1997 2161 eq. 83] - grad_greenfunction_block[j, j] -= gradG_0 * wsimpson - end - - # Perform Gaussian quadrature for singular points (source = obs point) - # Indices of the singularity region, [j-2, j-1, j, j+1, j+2] (allocation-free) - for (offset_idx, offset) in enumerate(-2:2) - sing_idx[offset_idx] = mod1(j + offset + mtheta, mtheta) - end - # Integrate region of length 2 * dtheta on left/right of singularity - for leftpanel in (true, false) - gauss_mid = theta_obs + (leftpanel ? -dtheta : dtheta) - @inbounds for ig in 1:8 # 8-point Gaussian quadrature - theta_gauss = gauss_mid + GL8.x[ig] * dtheta - theta_gauss0 = mod(theta_gauss, 2π) - x_gauss = spline_x(theta_gauss0) - dx_dtheta_gauss = d1_spline_x(theta_gauss0) - z_gauss = spline_z(theta_gauss0) - dz_dtheta_gauss = d1_spline_z(theta_gauss0) - G_n, gradG_n, gradG_0 = green(x_obs, z_obs, x_gauss, z_gauss, dx_dtheta_gauss, dz_dtheta_gauss, n; gamma_prefactor, pn_cache) - - # Get stencil and weight for the Gaussian point - s = leftpanel ? stencils_left[ig] : stencils_right[ig] - wgauss = GL8.w[ig] * dtheta - - # First type of singularity: 𝒢ⁿ [Chance Phys. Plasmas 1997 2161 eq. 75] - if populate_greenfunction - if observer isa PlasmaGeometry - # Remove singular behavior by adding on leading-order term - G_n += log((theta_obs - theta_gauss)^2) / x_obs - end - @inbounds for stencil_idx in 1:5 - greenfunction[j, sing_idx[stencil_idx]] += G_n * s[stencil_idx] * wgauss - end - end - - # Second type of singularity: 𝒦ⁿ [Chance Phys. Plasmas 1997 2161 eq. 83, 86] - @inbounds for stencil_idx in 1:5 - grad_greenfunction_block[j, sing_idx[stencil_idx]] += gradG_n * s[stencil_idx] * wgauss - end - # Subtract off the diverging singular n=0 component - grad_greenfunction_block[j, j] -= gradG_0 * wgauss - end - end - - # Subtract off analytic singular integral [Chance Phys. Plasmas 1997 2161 eq. 75] if plasma-plasma block - if populate_greenfunction && observer isa PlasmaGeometry - @inbounds for stencil_idx in 1:5 - greenfunction[j, sing_idx[stencil_idx]] -= log_correction_array[stencil_idx] / x_obs + x_obs, z_obs = observer.x[j], observer.z[j] + # (𝒢ⁿ, 𝒦ⁿ, 𝒦⁰) at this observer from a source point and its tangent + kernel(x, z, dx_dθ, dz_dθ) = green(x_obs, z_obs, x, z, dx_dθ, dz_dθ, n; gamma_prefactor, pn_cache) + rows = (grad_greenfunction_block, greenfunction, j) + if observer === source + # Same surface: Simpson outside [j-2, j+2], Gauss + analytic log removal inside + add_regular_sum!(rows, kernel, source, simpson_nodes(j, 2, mtheta)) + add_singular_panels!(rows, kernel, source, theta_grid[j], log_correction_array, x_obs) + else + cp = closest_point(source, x_obs, z_obs) + if abs(cp.d) < NEAR_GAP * cp.h + # Close cross-surface: Simpson outside ±NEAR_WINDOW, sinh-graded Gauss window about the closest point + jc = mod1(round(Int, cp.θ / dtheta) + 1, mtheta) + add_regular_sum!(rows, kernel, source, simpson_nodes(jc, NEAR_WINDOW, mtheta)) + add_near_window!(rows, kernel, source, jc, cp.θ, x_obs, z_obs) + else + # Far cross-surface: smooth periodic integrand, so the trapezoidal rule converges exponentially + add_regular_sum!(rows, kernel, source, ((isrc, dtheta) for isrc in 1:mtheta)) end end end @@ -229,6 +120,115 @@ grad_greenfunction is not zeroed since it fills a different block of the end end +""" +Composite Simpson nodes `(isrc, w)` from `jc + w` around the loop to `jc - w`, leaving the `2w` intervals about `jc` to +the panel quadrature (requires even `mtheta`). +""" +function simpson_nodes(jc, w, mtheta) + dtheta = 2π / mtheta + nsimp = mtheta - 2w + 1 + # Weights 1, 4, 2, …, 4, 1: 4 on even k since k counts from 1 while the formula counts from 0 + return ((mod1(jc + w - 1 + k, mtheta), dtheta / 3 * ((k == 1 || k == nsimp) ? 1 : (iseven(k) ? 4 : 2))) for k in 1:nsimp) +end + +""" +Add the quadrature sum `Σ w K(source node isrc)` over `nodes = (isrc, w)` to row `j` of `rows = (𝒦 block, 𝒢, j)`: +Simpson's rule off the singular panels, or the periodic trapezoidal rule on a far plasma–wall row. 𝒢 is filled only for a +plasma source. +""" +function add_regular_sum!((grad_greenfunction_block, greenfunction, j), kernel, source, nodes) + @inbounds for (isrc, w) in nodes + G_n, gradG_n, gradG_0 = kernel(source.x[isrc], source.z[isrc], source.dx_dθ[isrc], source.dz_dθ[isrc]) + source isa PlasmaGeometry && (greenfunction[j, isrc] += G_n * w) + grad_greenfunction_block[j, isrc] += gradG_n * w + # Subtract regular integral component of δⱼᵢK⁰ [Chance Phys. Plasmas 1997 2161 eq. 83] + grad_greenfunction_block[j, j] -= gradG_0 * w + end +end + +""" +Add the singular panels of same-surface row `j`: 8-point Gauss on the two panels of 2 node intervals about the observer +at `theta_obs`, with the density from the 5-point Lagrange stencil about it. For the plasma, the log singularity of 𝒢 is +removed and added back analytically (`log_correction_array`) [Chance Phys. Plasmas 1997 2161 eqs. 75, 78]. +""" +function add_singular_panels!((grad_greenfunction_block, greenfunction, j), kernel, source, theta_obs, log_correction_array, x_obs) + mtheta = length(source.x) + dtheta = 2π / mtheta + stencils_left, stencils_right = GL8_LAGRANGE_STENCILS + sing_idx = ntuple(i -> mod1(j + i - 3, mtheta), 5) # [j-2, j-1, j, j+1, j+2] + + # Integrate region of length 2 * dtheta on left/right of singularity + for leftpanel in (true, false) + gauss_mid = theta_obs + (leftpanel ? -dtheta : dtheta) + @inbounds for ig in 1:8 # 8-point Gaussian quadrature + theta_gauss = gauss_mid + GL8_X[ig] * dtheta + G_n, gradG_n, gradG_0 = kernel(curve_point(source, theta_gauss)...) + + # Get stencil and weight for the Gaussian point + s = leftpanel ? stencils_left[ig] : stencils_right[ig] + wgauss = GL8_W[ig] * dtheta + + # First type of singularity: 𝒢ⁿ [Chance Phys. Plasmas 1997 2161 eq. 75] + if source isa PlasmaGeometry + # Remove singular behavior by adding on leading-order term + G_n += log((theta_obs - theta_gauss)^2) / x_obs + @inbounds for stencil_idx in 1:5 + greenfunction[j, sing_idx[stencil_idx]] += G_n * s[stencil_idx] * wgauss + end + end + + # Second type of singularity: 𝒦ⁿ [Chance Phys. Plasmas 1997 2161 eq. 83, 86] + @inbounds for stencil_idx in 1:5 + grad_greenfunction_block[j, sing_idx[stencil_idx]] += gradG_n * s[stencil_idx] * wgauss + end + # Subtract off the diverging singular n=0 component + grad_greenfunction_block[j, j] -= gradG_0 * wgauss + end + end + + # Subtract off analytic singular integral [Chance Phys. Plasmas 1997 2161 eq. 75] for the plasma + if source isa PlasmaGeometry + @inbounds for stencil_idx in 1:5 + greenfunction[j, sing_idx[stencil_idx]] -= log_correction_array[stencil_idx] / x_obs + end + end +end + +""" +Add the near-window integral of a close plasma–wall row `j` over the `2 * NEAR_WINDOW` node intervals about source node +`jc`: each interval, split at the closest point `θc`, on sinh-graded nodes ([`sinh_nodes`](@ref)) of width +`ε = d/|∂r/∂θ|`, with the density from the 5-point Lagrange stencil about the interval's left node. +""" +function add_near_window!((grad_greenfunction_block, greenfunction, j), kernel, source, jc, θc, x_obs, z_obs) + mtheta = length(source.x) + dtheta = 2π / mtheta + θc = (jc - 1) * dtheta + rem2pi(θc - (jc - 1) * dtheta, RoundNearest) # unwrapped next to node jc + X, Z, Xθ, Zθ = curve_point(source, θc) + # |r_obs - r(θc + ρ)|² ≈ d² + |∂r/∂θ|² ρ², so the kernel peak has angular width ε = d / |∂r/∂θ| + ε = hypot(x_obs - X, z_obs - Z) / hypot(Xθ, Zθ) + # 0-based interval k covers [k·dtheta, (k+1)·dtheta] across the 2·NEAR_WINDOW panels around node jc (0-based jc - 1) + for k in (jc-1-NEAR_WINDOW):(jc-2+NEAR_WINDOW) + a, b = k * dtheta - θc, (k + 1) * dtheta - θc + # Interval integrals of 𝒦ⁿ and 𝒢ⁿ against each stencil weight, and of 𝒦⁰; split at ρ = 0 when the interval straddles θc + I_grad, I_G, I_0 = zero(SVector{5,Float64}), zero(SVector{5,Float64}), 0.0 + for (lo, hi) in (a < 0 < b ? ((a, 0.0), (0.0, b)) : ((a, b),)), (ρ, w) in sinh_nodes(ε, lo, hi, NEAR_SINH) + G_n, gradG_n, gradG_0 = kernel(curve_point(source, θc + ρ)...) + # Local 5-point stencil on 0-based nodes (k-2):(k+2) avoids high-order extrapolation across the whole window + ℓ = lagrange_weights((θc + ρ) / dtheta - (k - 2), Val(5)) + I_grad += w * (gradG_n * ℓ) + I_G += w * (G_n * ℓ) + I_0 += w * gradG_0 + end + @inbounds for i in 1:5 + col = mod1(k - 2 + i, mtheta) + grad_greenfunction_block[j, col] += I_grad[i] + source isa PlasmaGeometry && (greenfunction[j, col] += I_G[i]) + end + # Complete the full-contour ∫𝒦⁰ subtraction on [j, j] so it cancels the Gauss's-law `residue` added below + grad_greenfunction_block[j, j] -= I_0 + end +end + # Legendre functions of the first kind P^n_{-1/2} [Chance 1997 eqs. 47-50] """ diff --git a/src/Vacuum/Kernel3D.jl b/src/Vacuum/Kernel3D.jl index 275c1ef39..50a15fdaa 100644 --- a/src/Vacuum/Kernel3D.jl +++ b/src/Vacuum/Kernel3D.jl @@ -10,13 +10,15 @@ # Modifications Copyright (C) 2026 Columbia Fusion Research Center and Seoul National University: # - Julia translation; runtime patch, quadrature and interpolation orders, with the patch clamped on coarse grids # - stencil corner by rounding, so odd orders are equivariant under the patch's pi-rotation -# - one sparse interpolation matrix, applied forward to the geometry and transposed to scatter weights +# - one near-field routine for every row: polar nodes interpolated and their weights scattered by per-node Lagrange +# stencils (no stored interpolation matrix), about the observer or, off the source surface, the closest source point # - VACUUM kernel convention: 1/r and n.grad'(1/r) over 2pi, unit Green's-identity diagonal # - far field by the trapezoidal rule on the collocation grid, without upsampling # - patch geometry upsampled 2x by trigonometric interpolation to refine the polar interpolation stencil, # correction weights folded back to the collocation nodes by its transpose (BIEST instead upsamples the # whole surface and density and shrinks the patch) -# - singular correction applied to plasma-wall cross-surface blocks +# - plasma-wall rows: sinh-mapped radial nodes [Johnston & Elliott, Int. J. Numer. Meth. Engng 62 (2005) 564]; rows +# beyond NEAR_GAP node spacings take the trapezoidal rule alone # - dense operator row assembly, field-period folding, stellarator-symmetric basis, threading # # SPDX-License-Identifier: Apache-2.0 @@ -24,14 +26,12 @@ """ Thread-local scratch for `compute_3D_kernel_matrices!`, one per thread so the parallel observer loop does not race. -`patch` and `polar` hold (r, ∂r/∂θ, ∂r/∂ζ) per node; `T` is the operator row's element type. +`patch` holds the upsampled source patch and `M_grid` the double- and single-layer correction weights on it; +`T` is the operator row's element type. """ struct KernelWorkspace{T<:Number} - patch::Matrix{SVector{9,Float64}} - polar::Matrix{SVector{9,Float64}} - M_polar_single::Matrix{Float64} - M_polar_double::Matrix{Float64} - M_grid_flat::Vector{Float64} + patch::Matrix{SurfacePoint} + M_grid::Array{Float64,3} fold_tmp::Matrix{Float64} folded_patch::Matrix{T} row_single::Vector{T} @@ -39,13 +39,10 @@ struct KernelWorkspace{T<:Number} sym_work::Vector{ComplexF64} end -function KernelWorkspace{T}(UP_DIM::Int, RAD_DIM::Int, ANG_DIM::Int, mtheta::Int, nzeta_fp::Int, nrow::Int, nsym::Int) where {T} +function KernelWorkspace{T}(UP_DIM::Int, mtheta::Int, nzeta_fp::Int, nrow::Int, nsym::Int) where {T} return KernelWorkspace{T}( - zeros(SVector{9,Float64}, UP_DIM, UP_DIM), - zeros(SVector{9,Float64}, RAD_DIM, ANG_DIM), - zeros(RAD_DIM, ANG_DIM), - zeros(RAD_DIM, ANG_DIM), - zeros(UP_DIM^2), + fill(zero(SurfacePoint), UP_DIM, UP_DIM), + zeros(UP_DIM, UP_DIM, 2), zeros(UP_DIM, mtheta), zeros(T, nzeta_fp, mtheta), zeros(T, nrow), @@ -55,264 +52,264 @@ function KernelWorkspace{T}(UP_DIM::Int, RAD_DIM::Int, ANG_DIM::Int, mtheta::Int end """ - SingularQuadratureData + laplace_kernel(x, y, n) -> (single, double) -Precomputed polar singular-correction quadrature (Malhotra JCP 397 (2019) 108791, Sec. 3.2). - -## Fields - - - `Gpou::Matrix{Float64}`: Partition of unity on the Cartesian patch, `Gpou = -χ` (PATCH_DIM × PATCH_DIM) - - `Ppou::Matrix{Float64}`: Partition of unity times polar quadrature weights (RAD_DIM × ANG_DIM) - - `P2G::SparseMatrixCSC{Float64,Int}`: Lagrange interpolation matrix on the 2× upsampled patch: `polar = P2G' * patch`, `grid = P2G * polar` - - `PATCH_DIM::Int`: Patch width `2 * PATCH_RAD + 1` - - `UP_DIM::Int`: Upsampled patch width `2 * PATCH_DIM - 1` - - `PATCH_RAD::Int`: Number of points on each side of the source point treated as singular - - `ANG_DIM::Int`: Number of angular quadrature points - - `RAD_DIM::Int`: Number of radial quadrature points - - `INTERP_ORDER::Int`: Lagrange interpolation order +Laplace kernels at observer `x` from source `y` with normal `n`: `single = 1/r`, `double = (Δx·n)/r³`; `(0, 0)` at +coincidence (`r² < 1e-30`). Written by component: `dot` would let `@fastmath` reorder the sums. """ -struct SingularQuadratureData - Gpou::Matrix{Float64} - Ppou::Matrix{Float64} - P2G::SparseMatrixCSC{Float64,Int} - PATCH_DIM::Int - UP_DIM::Int - PATCH_RAD::Int - ANG_DIM::Int - RAD_DIM::Int - INTERP_ORDER::Int +@fastmath @inline function laplace_kernel(x::SVector{3,Float64}, y::SVector{3,Float64}, n::SVector{3,Float64}) + Δ = x - y + r2 = Δ[1] * Δ[1] + Δ[2] * Δ[2] + Δ[3] * Δ[3] + r2 < 1e-30 && return (0.0, 0.0) + rinv = inv(sqrt(r2)) + return (rinv, (Δ[1] * n[1] + Δ[2] * n[2] + Δ[3] * n[3]) * (rinv * rinv * rinv)) end """ - 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 `≤ 4 * PATCH_RAD + 1`, the upsampled patch width. +Extract a periodically wrapped `PATCH_DIM × PATCH_DIM` patch centered at `(idx_pol_center, idx_tor_center)`. +""" +function extract_patch!(patch::AbstractMatrix, data::AbstractVector, idx_pol_center::Int, idx_tor_center::Int, npol::Int, ntor::Int, PATCH_DIM::Int) + PATCH_RAD = (PATCH_DIM - 1) ÷ 2 + @inbounds for j in 1:PATCH_DIM, i in 1:PATCH_DIM + idx_pol = periodic_wrap(idx_pol_center - PATCH_RAD + i - 1, npol) + idx_tor = periodic_wrap(idx_tor_center - PATCH_RAD + j - 1, ntor) + patch[i, j] = data[idx_pol+npol*(idx_tor-1)] + end +end -# Arguments +""" + SourceQuadrature - - `PATCH_RAD::Int`: Number of points adjacent to source point to treat as singular - - `RAD_DIM::Int`: Radial quadrature order - - `INTERP_ORDER::Int`: Lagrange interpolation order +Read-only source-surface quadrature data for `compute_3D_kernel_matrices!`, built once per call and shared across threads +(per-thread scratch lives in [`KernelWorkspace`](@ref)). -# Returns +## Fields - - `SingularQuadratureData`: Precomputed quadrature data + - `source`: Underlying `PlasmaGeometry3D` or `WallGeometry3D` + - `points_up`: Source `(r, ∂r/∂θ, ∂r/∂ζ)` on the 2× trigonometrically upsampled grid (node `2i - 1` is collocation node `i`) + - `points`, `normals`: Collocation positions and area-weighted normals for the far-field trapezoidal sum + - `period_col`: `(field_period, period_0_col)` of each full-torus collocation node + - `phases`: Field-period Bloch phases `ω^{k(d-1)}` (`d = 1:nfp`) + - `Uθ_patch`, `Uζ_patch`: Upsampling matrices restricted to the patch about node `(1, 1)`, with `Uζ_patch` pre-folded onto field period 0 (see [`fold_patch_to_row!`](@ref)) + - `patch_rad`, `ANG_DIM`: Patch radius (in collocation spacings) and polar angular node count + - `self_radial`, `cross_radial_rule`: Gauss radial rule on `[0, 1]` for same-surface rows, and [`sinh_rule`](@ref) for close plasma–wall rows + - `self_order`, `cross_order`: Lagrange stencil orders (`Val`) on the upsampled patch for self and plasma–wall rows """ -function SingularQuadratureData(PATCH_RAD::Int, RAD_DIM::Int, INTERP_ORDER::Int) +struct SourceQuadrature{T<:Number,P<:AbstractVector{T},S,NS,NC,R} + source::S + points_up::Vector{SurfacePoint} + points::Vector{SVector{3,Float64}} + normals::Vector{SVector{3,Float64}} + period_col::Vector{Tuple{Int,Int}} + phases::P + Uθ_patch::Matrix{Float64} + Uζ_patch::Matrix{T} + patch_rad::Int + ANG_DIM::Int + self_radial::Vector{Tuple{Float64,Float64}} + cross_radial_rule::R + self_order::Val{NS} + cross_order::Val{NC} +end + +# Lagrange order on plasma–wall rows: 9 points match 11 there at 2/3 the cost +const CROSS_INTERP_ORDER = 9 - # Total size of square patch extracted around singular point (odd number: 2*PATCH_RAD+1) - PATCH_DIM = 2 * PATCH_RAD + 1 - # We upsample the patch by 2x in each direction for better accuracy - UP_DIM = 2 * PATCH_DIM - 1 +function SourceQuadrature(source, phases::AbstractVector{<:Number}, patch_rad::Int, RAD_DIM::Int, INTERP_ORDER::Int) + mtheta, nzeta, nfp = source.mtheta, source.nzeta, length(phases) + UP_DIM, nzeta_fp = 4 * patch_rad + 1, nzeta ÷ nfp @assert INTERP_ORDER <= UP_DIM "Must have INTERP_ORDER <= UP_DIM, got INTERP_ORDER=$INTERP_ORDER, UP_DIM=$UP_DIM" - # Number of angular quadrature nodes in polar coordinates (uniformly distributed around circle) - ANG_DIM = 2 * RAD_DIM - - # Setup radial quadrature - qx_raw, qw_raw = gausslegendre(RAD_DIM) # points on [-1,1] - qx = (qx_raw .+ 1) ./ 2 # [-1, 1] → [0, 1] - qw = qw_raw ./ 2 # Adjust weights for interval change - - # χ(r) = exp(-36 r^p), p from PATCH_DIM: χ blends on the collocation grid, so it keys on the coarse patch, not UP_DIM - pou_power = PATCH_DIM > 45 ? 10 : (PATCH_DIM > 20 ? 8 : 6) - pou(r) = r ≥ 1.0 ? 0.0 : exp(-36.0 * r^pou_power) - - # Gpou = -χ on the Cartesian patch - Gpou = zeros(PATCH_DIM, PATCH_DIM) - coords = LinRange(-1.0, 1.0, PATCH_DIM) - for (i, x) in enumerate(coords), (j, y) in enumerate(coords) - Gpou[i, j] = -pou(sqrt(x^2 + y^2)) - end - # Ppou = χ(ρ) M²/4 r dr dθ [Malhotra JCP 397 (2019) 108791 eq. 38] - Ppou = zeros(RAD_DIM, ANG_DIM) - dθ = 2π / ANG_DIM - for j in 1:ANG_DIM, i in 1:RAD_DIM - dr = qw[i] * PATCH_RAD - rdθ = qx[i] * PATCH_RAD * dθ - Ppou[i, j] = pou(qx[i]) * dr * rdθ - end + Uθ, Uζ = trig_interp_matrix(mtheta, 2 * mtheta), trig_interp_matrix(nzeta, 2 * nzeta) + up = trig_upsample(hcat(source.r, source.dr_dθ, source.dr_dζ), Uθ, Uζ, mtheta, nzeta) + points_up = [SurfacePoint(up[k, SVector(1, 2, 3)], up[k, SVector(4, 5, 6)], up[k, SVector(7, 8, 9)]) for k in axes(up, 1)] - # Spacing between Lagrange interpolation nodes in [0,1] for INTERP_ORDER-point stencil - h = 1.0 / (INTERP_ORDER - 1) - - # Compute 2D tensor-product Lagrange basis function at (x0, x1) in local - # stencil coordinates for basis node (i0, i1) on uniform grid with spacing h - @inline function lagrange_interp(x0::Float64, x1::Float64, i0::Int, i1::Int) - Lx = Ly = 1.0 - ξ0 = x0 / h - ξ1 = x1 / h - for j0 in 0:(INTERP_ORDER-1) - j0 != i0 && (Lx *= (ξ0 - j0) / (i0 - j0)) - end - for j1 in 0:(INTERP_ORDER-1) - j1 != i1 && (Ly *= (ξ1 - j1) / (i1 - j1)) - end - return Lx * Ly + # Upsampling rows for the UP_DIM patch centred on collocation node 1 (fine index 1); translation invariance lets + # `fold_patch_to_row!` reuse them for any patch centre, and `Uζ_patch` pre-folds all nfp field periods onto period 0 + Uθ_patch = Uθ[periodic_wrap.((1:UP_DIM) .- 2 * patch_rad, 2 * mtheta), :] + Uζ_patch = zeros(eltype(phases), nzeta_fp, UP_DIM) + for i in 1:UP_DIM, d in eachindex(phases), j in 1:nzeta_fp + Uζ_patch[j, i] += phases[d] * Uζ[periodic_wrap(i - 2 * patch_rad, 2 * nzeta), j+(d-1)*nzeta_fp] end - # grid = P2G * polar, polar = P2G' * grid; each column is the INTERP_ORDER² Lagrange stencil - Ngrid = UP_DIM * UP_DIM - Npolar = RAD_DIM * ANG_DIM - - # Preallocate COO storage: - # I_coo[k], J_coo[k] = (row, column) index of kth nonzero - # V_coo[k] = interpolation weight - nnz_per_polar = INTERP_ORDER^2 - I_coo = Vector{Int}(undef, Npolar * nnz_per_polar) - J_coo = Vector{Int}(undef, Npolar * nnz_per_polar) - V_coo = Vector{Float64}(undef, Npolar * nnz_per_polar) - - idx = 1 - for ir in 1:RAD_DIM, ia in 1:ANG_DIM - # Map polar node to unit square: x0, x1 ∈ [0,1] × [0,1] - x0 = 0.5 + 0.5 * qx[ir] * cos(dθ * (ia - 1)) - x1 = 0.5 + 0.5 * qx[ir] * sin(dθ * (ia - 1)) - - # Lower-left corner indices of INTERP_ORDER × INTERP_ORDER stencil centered on (x0,x1). - # Round, don't truncate, and keep INTERP_ORDER odd: the stencil must be equivariant under the patch's π-rotation or stellarator symmetry is lost. - y0 = clamp(round(Int, x0 * (UP_DIM - 1)) - (INTERP_ORDER - 1) ÷ 2, 0, UP_DIM - INTERP_ORDER) - y1 = clamp(round(Int, x1 * (UP_DIM - 1)) - (INTERP_ORDER - 1) ÷ 2, 0, UP_DIM - INTERP_ORDER) - - # Local coordinates within INTERP_ORDER×INTERP_ORDER stencil, normalized to [0,1] - z0 = (x0 * (UP_DIM - 1) - y0) * h - z1 = (x1 * (UP_DIM - 1) - y1) * h - - # Polar point index (column in P2G) - j_polar = ir + RAD_DIM * (ia - 1) - - # Populate stencil contributions for this polar node - for i0 in 1:INTERP_ORDER, i1 in 1:INTERP_ORDER - # Grid point index (row in P2G), using column-major layout - i_grid = (y0 + i0) + UP_DIM * (y1 + i1 - 1) - I_coo[idx] = i_grid - J_coo[idx] = j_polar - V_coo[idx] = lagrange_interp(z0, z1, i0 - 1, i1 - 1) - idx += 1 - end + num_points = mtheta * nzeta + self_radial = let (t, w) = gausslegendre(RAD_DIM) + collect(zip((t .+ 1) ./ 2, w ./ 2)) end - - # Assemble sparse interpolation matrix - P2G = sparse(I_coo, J_coo, V_coo, Ngrid, Npolar) - - return SingularQuadratureData(Gpou, Ppou, P2G, PATCH_DIM, UP_DIM, PATCH_RAD, ANG_DIM, RAD_DIM, INTERP_ORDER) + return SourceQuadrature( + source, points_up, + [SVector{3}(@view source.r[k, :]) for k in 1:num_points], + [SVector{3}(@view source.normal[k, :]) for k in 1:num_points], + [fldmod1(k, num_points ÷ nfp) for k in 1:num_points], + phases, Uθ_patch, Uζ_patch, patch_rad, 2 * RAD_DIM, + # Plasma–wall rows: 1–8 × RAD_DIM nodes, RAD_DIM per 2 units of the sinh variable + self_radial, sinh_rule(RAD_DIM, 8, 2.0), + Val(INTERP_ORDER), Val(min(INTERP_ORDER, CROSS_INTERP_ORDER)) + ) end -# Cached singular quadrature; rebuilt if PATCH_RAD / RAD_DIM / INTERP_ORDER change -const SINGULAR_QUAD_CACHE = Ref{Union{Nothing,SingularQuadratureData}}(nothing) -const _SINGULAR_QUAD_LOCK = ReentrantLock() - """ - get_singular_quadrature(PATCH_RAD, RAD_DIM, INTERP_ORDER) - -Return the cached [`SingularQuadratureData`](@ref), rebuilding it if the parameters changed. Takes a lock, -so concurrent solves on different grids each get the data for their own parameters. +Add correction weights on the upsampled patch about collocation node `(i_obs, j_obs)` to the operator row: +`Uζ_patch * M_up' * Uθ_patch` (the transposed trigonometric upsampling about the first node, field periods folded into +`Uζ_patch`) maps them onto the collocation nodes, shifted to `(i_obs, j_obs)` by translation invariance. `j_obs` lies +in field period 0; a patch centred in another period passes that period's phase as `phase0`. """ -function get_singular_quadrature(PATCH_RAD::Int, RAD_DIM::Int, INTERP_ORDER::Int) - @lock _SINGULAR_QUAD_LOCK begin - cached = SINGULAR_QUAD_CACHE[] - if !isnothing(cached) && - cached.PATCH_RAD == PATCH_RAD && - cached.RAD_DIM == RAD_DIM && - cached.INTERP_ORDER == INTERP_ORDER - return cached +function fold_patch_to_row!(row::Vector{T}, M_up::AbstractMatrix{Float64}, quad::SourceQuadrature, ws::KernelWorkspace{T}, + i_obs::Int, j_obs::Int, phase0::T) where {T<:Number} + (; fold_tmp, folded_patch) = ws + mul!(fold_tmp, transpose(M_up), quad.Uθ_patch) + mul!(folded_patch, quad.Uζ_patch, fold_tmp) + + # Shifting from node 1 to j_obs wraps entries from the end of period d - 1 into period d when j < j_obs, + # adding one more Bloch step `wrap_phase` (assumes geometric phases, phases[d] = wrap_phase^(d-1)) + wrap_phase = quad.phases[min(2, end)] + nzeta_fp, mtheta = size(folded_patch) + @inbounds for j in 1:nzeta_fp + j_fold = j - j_obs + 1 + phase = j_fold < 1 ? phase0 * wrap_phase : phase0 + j_fold < 1 && (j_fold += nzeta_fp) + for i in 1:mtheta + row[i+mtheta*(j-1)] += phase * folded_patch[j_fold, periodic_wrap(i - i_obs + 1, mtheta)] end - data = SingularQuadratureData(PATCH_RAD, RAD_DIM, INTERP_ORDER) - SINGULAR_QUAD_CACHE[] = data - return data end end """ - laplace_kernel(ox, oy, oz, sx, sy, sz, nx, ny, nz) -> (single, double) + nearest_source_node(quad, r) -> (; i, j, d, h) -Fused Laplace kernels: `single = 1/r`, `double = (Δx·n)/r³`. Shares `√(r²)`; returns `(0, 0)` at coincidence (`r² < 1e-30`). +Collocation node `(i, j)` of `quad.source` nearest to `r`, its distance `d` from `r`, and its larger cell spacing `h`. +Used to screen out far plasma–wall observers (`d ≥ NEAR_GAP * h`) before extracting a patch for Gauss–Newton. """ -@fastmath @inline function laplace_kernel( - ox::Float64, oy::Float64, oz::Float64, - sx::Float64, sy::Float64, sz::Float64, - nx::Float64, ny::Float64, nz::Float64 -) - dx = ox - sx - dy = oy - sy - dz = oz - sz - r2 = dx * dx + dy * dy + dz * dz - r2 < 1e-30 && return (0.0, 0.0) - rinv = inv(sqrt(r2)) - single = rinv - r3inv = rinv * rinv * rinv - double = (dx * nx + dy * ny + dz * nz) * r3inv - return (single, double) +@inline function nearest_source_node(quad::SourceQuadrature, r::SVector{3,Float64}) + (; mtheta, nzeta) = quad.source + k = argmin(k -> sum(abs2, r - quad.points[k]), eachindex(quad.points)) + i, j = mod1(k, mtheta), (k - 1) ÷ mtheta + 1 + q = quad.points_up[2i-1+2mtheta*(2j-2)] + return (; i, j, d=norm(r - q.r), h=max(norm(q.rθ) * (2π / mtheta), norm(q.rζ) * (2π / nzeta))) end """ -Extract a periodically wrapped `PATCH_DIM × PATCH_DIM` patch centered at `(idx_pol_center, idx_tor_center)`. + closest_source_point!(patch, quad, r, i, j) -> (; i, j, U, V, d, hθ, hζ) + +Refine the source point closest to `r` starting from collocation node `(i, j)`. `patch` is left holding the upsampled +patch about the updated `(i, j)`, re-centred as the Gauss–Newton search moves, and `(U, V)` are the point's coordinates +on it; `d` is the distance and `hθ`, `hζ` the local node spacings. """ -function extract_patch!(patch::AbstractMatrix, data::AbstractVector, idx_pol_center::Int, idx_tor_center::Int, npol::Int, ntor::Int, PATCH_DIM::Int) - PATCH_RAD = (PATCH_DIM - 1) ÷ 2 - @inbounds for j in 1:PATCH_DIM, i in 1:PATCH_DIM - idx_pol = periodic_wrap(idx_pol_center - PATCH_RAD + i - 1, npol) - idx_tor = periodic_wrap(idx_tor_center - PATCH_RAD + j - 1, ntor) - patch[i, j] = data[idx_pol+npol*(idx_tor-1)] +function closest_source_point!(patch::Matrix{SurfacePoint}, quad::SourceQuadrature, r::SVector{3,Float64}, i::Int, j::Int) + mtheta, nzeta = quad.source.mtheta, quad.source.nzeta + UP_DIM, val = size(patch, 1), quad.cross_order + c = (UP_DIM - 1) / 2 # patch centre + dθ, dζ = 2π / mtheta, 2π / nzeta + + U, V = c, c + # Re-centre `patch` on the collocation node nearest (U, V) (2 fine spacings per coarse step) so the polar disk stays inside it + for iter in 1:3 + extract_patch!(patch, quad.points_up, 2i - 1, 2j - 1, 2mtheta, 2nzeta, UP_DIM) + U, V = closest_point(patch, r, U, V, dθ / 2, dζ / 2, val) + su, sv = round(Int, (U - c) / 2), round(Int, (V - c) / 2) + (su == sv == 0 || iter == 3) && break + i, j, U, V = mod1(i + su, mtheta), mod1(j + sv, nzeta), U - 2su, V - 2sv end + q = interpolate_patch(patch, U, V, val)[1] + d, hθ, hζ = norm(r - q.r), norm(q.rθ) * dθ, norm(q.rζ) * dζ + d < 1e-3 * min(hθ, hζ) && throw(ArgumentError("plasma and wall touch (gap $(d) m)")) + return (; i, j, U, V, d, hθ, hζ) end """ -Interpolate the patch onto the polar nodes, `polar = P2G' * patch`. Each node carries all nine fields as one `SVector`, -so `P2G` is swept once rather than once per field as `mul!` would. + add_near_correction!(ws, quad, r_obs, i, j, U, V, radial, Val(N)) + +Add the near-field correction of the row in `ws` about source point `(U, V)` of the upsampled patch about collocation +node `(i, j)`, which `ws.patch` already holds: polar quadrature on the radial nodes `radial` +([`foreach_polar_node`](@ref)), folded onto the row, minus the trapezoidal sum it replaces. """ -function interpolate_to_polar!(polar::Matrix{SVector{9,Float64}}, patch::Matrix{SVector{9,Float64}}, P2G::SparseMatrixCSC{Float64,Int}) - rv, nz = rowvals(P2G), nonzeros(P2G) - @inbounds for c in axes(P2G, 2) - # Accumulates (r, ∂r/∂θ, ∂r/∂ζ) at polar node c, no allocations - acc = zero(SVector{9,Float64}) - for p in nzrange(P2G, c) - # Lagrange weight × all nine fields at that patch node - acc += nz[p] * patch[rv[p]] +function add_near_correction!(ws::KernelWorkspace{T}, quad::SourceQuadrature, r_obs::SVector{3,Float64}, i::Int, j::Int, + U::Float64, V::Float64, radial, ::Val{N}) where {T<:Number,N} + (; patch, M_grid, row_single, row_double) = ws + (; source, phases, patch_rad) = quad + populate_greenfunction = source isa PlasmaGeometry3D + UP_DIM, PATCH_DIM = size(patch, 1), 2 * patch_rad + 1 + mtheta, nzeta = source.mtheta, source.nzeta + dθdζ = 4π^2 / (mtheta * nzeta) + + # Polar quadrature, scattered onto the upsampled patch by each node's Lagrange stencil + fill!(M_grid, 0) + M_double, M_single = view(M_grid,:,:,1), view(M_grid,:,:,2) + foreach_polar_node(patch, U, V, radial, patch_rad, quad.ANG_DIM, Val(N)) do q, cu, cv, wu, wv, w + # Area-weighted normal from the interpolated tangents (single layer omits |∂r/∂θ × ∂r/∂ζ| because the RHS carries it) + near_single, near_double = laplace_kernel(r_obs, q.r, source.normal_orient * cross(q.rθ, q.rζ)) + @inbounds for b in 1:N, a in 1:N + L = w * dθdζ * wu[a] * wv[b] + M_double[cu+a, cv+b] += near_double * L + populate_greenfunction && (M_single[cu+a, cv+b] += near_single * L) end - polar[c] = acc + end + # On a plasma–wall row the closest source node (i, j) can cross a seam out of period 0 + period, j_fp = fldmod1(j, nzeta ÷ length(phases)) + fold_patch_to_row!(row_double, M_double, quad, ws, i, j_fp, phases[period]) + populate_greenfunction && fold_patch_to_row!(row_single, M_single, quad, ws, i, j_fp, phases[period]) + + # Remove the trapezoidal sum under the patch: net weight (1 - χ), with χ centred at (U, V) — offset (δu, δv) in + # collocation spacings from (i, j), so ±(patch_rad + 1) covers the ≤0.5-cell shift on plasma–wall rows + δu, δv = (U - (UP_DIM - 1) / 2) / 2, (V - (UP_DIM - 1) / 2) / 2 + @inbounds for b in (-patch_rad-1):(patch_rad+1), a in (-patch_rad-1):(patch_rad+1) + χ = patch_pou(hypot(a - δu, b - δv) / patch_rad, PATCH_DIM) + χ == 0 && continue + idx_src = periodic_wrap(i + a, mtheta) + mtheta * (periodic_wrap(j + b, nzeta) - 1) + d_src, idx_col = quad.period_col[idx_src] + far_single, far_double = laplace_kernel(r_obs, quad.points[idx_src], quad.normals[idx_src]) + populate_greenfunction && (row_single[idx_col] -= phases[d_src] * (far_single * χ * dθdζ)) + row_double[idx_col] -= phases[d_src] * (far_double * χ * dθdζ) end end """ -Add the polar correction weights `M_polar` to the operator row: `P2G` scatters them onto the upsampled patch, and -`Uζ_patch * M_up' * Uθ_patch` (the transposed trigonometric upsampling about the first node, field periods folded into -`Uζ_patch`) onto the collocation nodes, shifted to the observer `(i_obs, j_obs)` by translation invariance. + kernel_row!(ws, quad, observer, idx_obs) + +Fill `ws.row_double` (and `ws.row_single` for a plasma source) with observer `idx_obs`'s operator row: trapezoidal rule +over all sources, then the near-field correction about the observer (same surface) or about the closest source point. """ -function scatter_polar_to_row!( - row::Vector{T}, - M_polar::Matrix{Float64}, - P2G::SparseMatrixCSC{Float64,Int}, - Uθ_patch::Matrix{Float64}, - Uζ_patch::Matrix{T}, - ws::KernelWorkspace{T}, - i_obs::Int, - j_obs::Int, - wrap_phase::T -) where {T<:Number} - - (; M_grid_flat, fold_tmp, folded_patch) = ws - UP_DIM = size(Uθ_patch, 1) - - # Scatter the polar corrections back to the upsampled patch - mul!(M_grid_flat, P2G, vec(M_polar)) - - # Fold the upsampled patch back to the collocation nodes - mul!(fold_tmp, transpose(reshape(M_grid_flat, UP_DIM, UP_DIM)), Uθ_patch) - mul!(folded_patch, Uζ_patch, fold_tmp) +function kernel_row!(ws::KernelWorkspace, quad::SourceQuadrature, observer, idx_obs::Int) + (; patch, row_single, row_double) = ws + (; source, phases) = quad + populate_greenfunction = source isa PlasmaGeometry3D + dθdζ = 4π^2 / (source.mtheta * source.nzeta) + fill!(row_double, 0) + populate_greenfunction && fill!(row_single, 0) + + i_obs = mod1(idx_obs, observer.mtheta) + j_obs = (idx_obs - 1) ÷ observer.mtheta + 1 + r_obs = SVector{3}(@view observer.r[idx_obs, :]) + + # Far field: trapezoidal rule over all sources (the kernels return zero at r_src = r_obs); fold each source's field + # period onto period 0 + @inbounds for idx_src in eachindex(quad.points) + far_single, far_double = laplace_kernel(r_obs, quad.points[idx_src], quad.normals[idx_src]) + d, idx_col = quad.period_col[idx_src] + populate_greenfunction && (row_single[idx_col] += phases[d] * (far_single * dθdζ)) + row_double[idx_col] += phases[d] * (far_double * dθdζ) + end - nzeta_fp, mtheta = size(folded_patch) - @inbounds for j in 1:nzeta_fp - # Columns the shift pushes into the next field period fold back with one more phase step; - # this assumes geometric phases, phases[d] = wrap_phase^(d-1) - j_fold = j - j_obs + 1 - phase = j_fold < 1 ? wrap_phase : one(T) - j_fold < 1 && (j_fold += nzeta_fp) - for i in 1:mtheta - row[i+mtheta*(j-1)] += phase * folded_patch[j_fold, periodic_wrap(i - i_obs + 1, mtheta)] + if observer === source + # Same surface: polar quadrature with singular correction about the observer, at the centre of its upsampled patch + extract_patch!(patch, quad.points_up, 2 * i_obs - 1, 2 * j_obs - 1, 2 * source.mtheta, 2 * source.nzeta, size(patch, 1)) + c = 2.0 * quad.patch_rad + add_near_correction!(ws, quad, r_obs, i_obs, j_obs, c, c, quad.self_radial, quad.self_order) + else + # Cross surface: the periodic trapezoidal sum only needs a correction if the observer is close to a source point + node = nearest_source_node(quad, r_obs) + if node.d <= NEAR_GAP * node.h + # Close cross-surface: polar patch centred on the closest source point, with radial nodes sinh-graded to the gap + cp = closest_source_point!(patch, quad, r_obs, node.i, node.j) + # Kernel peak width in normalized patch radius ρ ∈ [0, 1], using min(hθ, hζ) for the sharpest polar direction + ε = cp.d / (quad.patch_rad * min(cp.hθ, cp.hζ)) + add_near_correction!(ws, quad, r_obs, cp.i, cp.j, cp.U, cp.V, sinh_nodes(ε, 0.0, 1.0, quad.cross_radial_rule), quad.cross_order) end end + + # Normalize so the Green's-identity term is a unit shift and the exterior/interior jump is 2I, as in the 2D kernel + row_double ./= 2π + populate_greenfunction && (row_single ./= 2π) end """ @@ -320,8 +317,10 @@ end 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, on source data -upsampled 2× by trigonometric interpolation. +Far field: trapezoidal rule. Near field ([`kernel_row!`](@ref), [`add_near_correction!`](@ref)): polar quadrature blended +by a partition of unity, on source data upsampled 2× by trigonometric interpolation, about the observer on Gauss radial +nodes, or for a plasma–wall row about the closest source point on sinh-mapped ones. Plasma–wall rows more than `NEAR_GAP` +source node spacings away keep the trapezoidal rule alone, as in 2D. 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. @@ -346,124 +345,39 @@ function compute_3D_kernel_matrices!( num_points = observer.mtheta * observer.nzeta @assert num_points % length(phases) == 0 "full-torus grid ($num_points points) is not divisible by nfp ($(length(phases)))" num_points_per_fp = num_points ÷ length(phases) # observer/source points in one field period - dθdζ = 4π^2 / num_points - # Surface sub-block of the operator this call fills - col_index = (source isa PlasmaGeometry3D ? 1 : 2) - row_index = (observer isa PlasmaGeometry3D ? 1 : 2) - - # 𝒢ⁿ only needed for plasma as source term (RHS of eqs. 26/27 in Chance 1997) + # Surface sub-block of the operator this call fills; 𝒢 is only needed for a plasma source (Chance 1997 eqs. 26–27) populate_greenfunction = source isa PlasmaGeometry3D + col_index = populate_greenfunction ? 1 : 2 + row_index = (observer isa PlasmaGeometry3D ? 1 : 2) # Each reflection pair's second row follows from its first, so only the representatives are evaluated observers = sym_basis === nothing ? (1:num_points_per_fp) : sym_basis.pair_reps sym_basis === nothing || @assert isodd(INTERP_ORDER) "stellarator symmetry needs an odd INTERP_ORDER; an even stencil is not π-rotation equivariant" - # Clamp the patch on coarse grids, with a warning. - # Bound once into a new name: reassigning PATCH_RAD inside the branch would box it in the threaded closure below. + # Clamp the patch on coarse grids, with a warning patch_rad = min(PATCH_RAD, (min(source.mtheta, source.nzeta) - 1) ÷ 2) if patch_rad < PATCH_RAD @warn "PATCH_RAD=$(PATCH_RAD) is greater than half the number of points in the toroidal or poloidal direction, which is not supported. Setting PATCH_RAD to $(patch_rad), be sure to check if outputs are converged. This can be avoided by setting mtheta and nzeta to be greater than $(2 * PATCH_RAD + 1)." end - - quad_data = get_singular_quadrature(patch_rad, RAD_DIM, INTERP_ORDER) - (; PATCH_DIM, UP_DIM, ANG_DIM, Ppou, Gpou, P2G) = quad_data - - # Source r, ∂r/∂θ, ∂r/∂ζ on the 2× upsampled grid, where node 2i-1 is collocation node i - Uθ, Uζ = trig_interp_matrix(source.mtheta, 2 * source.mtheta), trig_interp_matrix(source.nzeta, 2 * source.nzeta) - src_up = SVector{9}.(eachrow(trig_upsample(hcat(source.r, source.dr_dθ, source.dr_dζ), Uθ, Uζ, source.mtheta, source.nzeta))) - - # Upsampling restricted to the patch about the first node, with the field periods folded onto period 0 in ζ (see `scatter_polar_to_row!`) - Trow = eltype(phases) - nzeta_fp = source.nzeta ÷ length(phases) - Uθ_patch = Uθ[periodic_wrap.((1:UP_DIM) .- 2 * patch_rad, 2 * source.mtheta), :] - Uζ_patch = zeros(Trow, nzeta_fp, UP_DIM) - for i in 1:UP_DIM, d in eachindex(phases), j in 1:nzeta_fp - Uζ_patch[j, i] += phases[d] * Uζ[periodic_wrap(i - 2 * patch_rad, 2 * source.nzeta), j+(d-1)*nzeta_fp] - end - wrap_phase = phases[min(2, end)] - - # Source point and normal packed per node, and each node's (field period, period-0 column), read on every observer row - src = [SVector{6}(source.r[k, 1], source.r[k, 2], source.r[k, 3], source.normal[k, 1], source.normal[k, 2], source.normal[k, 3]) for k in 1:num_points] - period_col = [fldmod1(k, num_points_per_fp) for k in 1:num_points] + quad = SourceQuadrature(source, phases, patch_rad, RAD_DIM, INTERP_ORDER) # One operator row is accumulated per observer, so the field-period fold and the basis change both happen before anything is stored. # `store_kernel_row!` needs two rows of scratch: the reconstructed partner and their combination. nsym = sym_basis === nothing ? 0 : 2 * num_points_per_fp - workspaces = [KernelWorkspace{Trow}(UP_DIM, RAD_DIM, ANG_DIM, source.mtheta, nzeta_fp, num_points_per_fp, nsym) for _ in 1:Threads.maxthreadid()] + workspaces = [KernelWorkspace{eltype(phases)}(4 * patch_rad + 1, source.mtheta, source.nzeta ÷ length(phases), num_points_per_fp, nsym) + for _ in 1:Threads.maxthreadid()] # :static pins each task to its thread, so the threadid()-indexed scratch below stays private Threads.@threads :static for i_pair in eachindex(observers) ws = workspaces[Threads.threadid()] - (; patch, polar, M_polar_single, M_polar_double, row_single, row_double, sym_work) = ws - fill!(row_double, 0) - populate_greenfunction && fill!(row_single, 0) - - # Convert linear index to 2D indices - idx_obs = observers[i_pair] - i_obs = mod1(idx_obs, observer.mtheta) - j_obs = (idx_obs - 1) ÷ observer.mtheta + 1 - r_obs = SVector(observer.r[idx_obs, 1], observer.r[idx_obs, 2], observer.r[idx_obs, 3]) - - # Far field: trapezoidal rule over all sources (the kernels return zero at r_src = r_obs) - @inbounds for idx_src in 1:num_points - # Evaluate kernels at grid points - s = src[idx_src] - far_single, far_double = laplace_kernel(r_obs[1], r_obs[2], r_obs[3], s[1], s[2], s[3], s[4], s[5], s[6]) - - # Periodic trapezoidal rule (constant weights); fold this source's field period onto period 0 - d, idx_col = period_col[idx_src] - populate_greenfunction && (row_single[idx_col] += phases[d] * (far_single * dθdζ)) - row_double[idx_col] += phases[d] * (far_double * dθdζ) - end - - # Near field: polar quadrature with singular correction, on the upsampled patch about the observer - extract_patch!(patch, src_up, 2 * i_obs - 1, 2 * j_obs - 1, 2 * source.mtheta, 2 * source.nzeta, UP_DIM) - - # Interpolate the geometry onto the polar nodes - interpolate_to_polar!(polar, patch, P2G) - - # Evaluate kernels and apply quadrature weights: area element × POU, where POU contains rdrdθ already - @inbounds for ia in 1:ANG_DIM, ir in 1:RAD_DIM - q = polar[ir, ia] # = (r, ∂r/∂θ, ∂r/∂ζ) at this polar node - # n = ∂r/∂θ × ∂r/∂ζ from the interpolated tangents, need to reapply orientation - n = source.normal_orient * cross(q[SVector(4, 5, 6)], q[SVector(7, 8, 9)]) - near_single, near_double = laplace_kernel(r_obs[1], r_obs[2], r_obs[3], q[1], q[2], q[3], n[1], n[2], n[3]) - - M_polar_single[ir, ia] = near_single * Ppou[ir, ia] * dθdζ - M_polar_double[ir, ia] = near_double * Ppou[ir, ia] * dθdζ - end - - # Scatter the singular correction on the polar nodes back to the collocation nodes - scatter_polar_to_row!(row_double, M_polar_double, P2G, Uθ_patch, Uζ_patch, ws, i_obs, j_obs, wrap_phase) - populate_greenfunction && scatter_polar_to_row!(row_single, M_polar_single, P2G, Uθ_patch, Uζ_patch, ws, i_obs, j_obs, wrap_phase) - - # Remove the trapezoidal far field where the polar correction applies: Gpou = -χ, net weight is (1 - χ) - @inbounds for j in 1:PATCH_DIM, i in 1:PATCH_DIM - # Map back to global indices - idx_pol = periodic_wrap(i_obs - patch_rad + i - 1, source.mtheta) - idx_tor = periodic_wrap(j_obs - patch_rad + j - 1, source.nzeta) - idx_src = idx_pol + source.mtheta * (idx_tor - 1) - d, idx_col = period_col[idx_src] - - # Far field at this patch node (weighted by Gpou = −χ) - s = src[idx_src] - far_single, far_double = laplace_kernel(r_obs[1], r_obs[2], r_obs[3], s[1], s[2], s[3], s[4], s[5], s[6]) - - populate_greenfunction && (row_single[idx_col] += phases[d] * (far_single * Gpou[i, j] * dθdζ)) - row_double[idx_col] += phases[d] * (far_double * Gpou[i, j] * dθdζ) - end - - # Normalize so the Green's-identity term below is a unit shift and the exterior/interior jump is 2I, as in the 2D kernel - row_double ./= 2π - populate_greenfunction && (row_single ./= 2π) - - store_kernel_row!(grad_blocks, sym_basis, row_double, sym_work, i_pair, row_index, col_index) - populate_greenfunction && store_kernel_row!(green_blocks, sym_basis, row_single, sym_work, i_pair, row_index, 1) + kernel_row!(ws, quad, observer, observers[i_pair]) + store_kernel_row!(grad_blocks, sym_basis, ws.row_double, ws.sym_work, i_pair, row_index, col_index) + populate_greenfunction && store_kernel_row!(green_blocks, sym_basis, ws.row_single, ws.sym_work, i_pair, row_index, 1) end # Volume-integral term of Green's identity; invariant under the basis change, so it is the same unit shift on every block - if typeof(source) == typeof(observer) + if observer === source for (b, H) in enumerate(grad_blocks) nsize = sym_basis === nothing ? num_points_per_fp : sym_basis.block_sizes[b] for i in 1:nsize diff --git a/src/Vacuum/PnQuadCache.jl b/src/Vacuum/PnQuadCache.jl index 0bb58ca23..babfde458 100644 --- a/src/Vacuum/PnQuadCache.jl +++ b/src/Vacuum/PnQuadCache.jl @@ -40,13 +40,11 @@ const _PN_CACHE_LOCK = Threads.SpinLock() """ 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 +Empty Vacuum's run-filled module-level cache of per-n Legendre quadrature entries. Called after the precompile workload so no run state is serialized into the package image. """ function reset_caches!() @lock _PN_CACHE_LOCK empty!(_PN_CACHE) - @lock _SINGULAR_QUAD_LOCK SINGULAR_QUAD_CACHE[] = nothing return nothing end diff --git a/src/Vacuum/Utilities.jl b/src/Vacuum/Utilities.jl index 0c32d5976..f7c79b744 100644 --- a/src/Vacuum/Utilities.jl +++ b/src/Vacuum/Utilities.jl @@ -1,3 +1,62 @@ +# Shared quadrature and close-wall utilities (2D and 3D) + +""" + periodic_wrap(x, n) -> Int + +`mod1(x, n)` without a division. Only valid for `1 - n ≤ x ≤ 2n`. +""" +@inline periodic_wrap(x::Int, n::Int) = x < 1 ? x + n : (x > n ? x - n : x) + +# cᵢ = 1/∏_{j≠i}(i - j) on the nodes 0:N-1, for every order up to 21 (factorial(21) overflows Int) +const LAGRANGE_DENOMINATORS = ntuple(N -> ntuple(i -> (-1)^(N - i) / (factorial(i - 1) * factorial(N - i)), N), 21) + +""" + lagrange_weights(ξ, Val(N)) -> SVector{N,Float64} + +Lagrange cardinal weights at `ξ` on the uniform nodes `0:(N - 1)`: wᵢ = cᵢ ∏_{j≠i} (ξ - j + 1). +""" +@inline function lagrange_weights(ξ, ::Val{N}) where {N} + c = LAGRANGE_DENOMINATORS[N] + return SVector(ntuple(i -> foldl(*, ntuple(j -> j == i ? 1.0 : ξ - (j - 1), Val(N)); init=c[i]), Val(N))) +end + +# Plasma–wall rows whose observer is more than NEAR_GAP source node spacings h from the source surface take the periodic +# trapezoidal rule alone, in 2D and 3D: its error ∝ exp(-2πd/h) is ~1e-11 there. Nearer rows are integrated about the +# closest source point, which stays accurate down to MIN_WALL_GAP_CELLS cells of the coarser grid +const NEAR_GAP = 4.0 +const MIN_WALL_GAP_CELLS = 0.1 + +""" + sinh_rule(Q, nmax, step) -> (; rules, step) + +Gauss–Legendre rules on [0, 1] with `Q, 2Q, …, nmax Q` nodes for [`sinh_nodes`](@ref), which takes `⌈Δs/step⌉ Q` nodes +on a span `Δs` of the sinh variable. +""" +function sinh_rule(Q::Int, nmax::Int, step::Float64) + rules = map(1:nmax) do m + t, w = gausslegendre(m * Q) + return (t .+ 1) ./ 2, w ./ 2 + end + return (; rules, step) +end + +""" + sinh_nodes(ε, a, b, rule) -> iterator of (ρ, w) + +Quadrature nodes and weights on `[a, b]` for a kernel peaked at `ρ = 0` with width `ε`: `ρ = ε sinh(s)`, Gauss in `s` +between `asinh(a/ε)` and `asinh(b/ε)` [Johnston & Elliott, Int. J. Numer. Meth. Engng 62 (2005) 564], from a +[`sinh_rule`](@ref). +""" +@inline function sinh_nodes(ε::Float64, a::Float64, b::Float64, rule) + sa, sb = asinh(a / ε), asinh(b / ε) + Δs = sb - sa + # Δs grows as log(1/ε) for small gaps, so scale the Gauss order to keep a roughly uniform node density in s (dρ = ε cosh(s) ds) + t_nodes, t_weights = rule.rules[clamp(ceil(Int, Δs / rule.step), 1, length(rule.rules))] + return ((ε * sinh(sa + Δs * t_nodes[i]), t_weights[i] * Δs * ε * cosh(sa + Δs * t_nodes[i])) for i in eachindex(t_nodes)) +end + +# 2D contour and spline utilities + """ extract_plasma_surface_at_psi(equil::Equilibrium.PlasmaEquilibrium, ψ::Float64) -> (r, z, ν) @@ -82,6 +141,53 @@ function distribute_to_equal_arc_grid(xin::Vector{Float64}, zin::Vector{Float64} return xout, zout end +""" + periodic_splines(x, z) -> (dx_dθ, dz_dθ, spline_x, spline_z) + +Periodic cubic splines of a closed curve sampled on the uniform grid `θ = 2π(k - 1)/M`, and their derivatives on it. +""" +function periodic_splines(x::Vector{Float64}, z::Vector{Float64}) + θ = range(; start=0, length=length(x), step=2π / length(x)) + bc = PeriodicBC(; endpoint=:exclusive, period=2π) + spline_x, spline_z = cubic_interp(θ, x; bc), cubic_interp(θ, z; bc) + return spline_x.(θ; deriv=DerivOp(1)), spline_z.(θ; deriv=DerivOp(1)), spline_x, spline_z +end + +""" + curve_point(curve, θ) -> (x, z, ∂x/∂θ, ∂z/∂θ) + +Point and tangent of a 2D geometry's spline at any angle `θ`. +""" +@inline function curve_point(curve, θ) + θ = mod(θ, 2π) + return curve.spline_x(θ), curve.spline_z(θ), curve.spline_x(θ; deriv=DerivOp(1)), curve.spline_z(θ; deriv=DerivOp(1)) +end + +""" + closest_point(curve, x, z) -> (; θ, d, h) + +Point of a counter-clockwise 2D geometry closest to `(x, z)`, by Newton on its spline from the nearest node: its angle `θ`, +the signed distance `d` along the outward normal, and the local node spacing `h`. +""" +function closest_point(curve, x, z) + M = length(curve.x) + θ = 2π / M * (argmin(@. (curve.x - x)^2 + (curve.z - z)^2) - 1) + for _ in 1:30 + X, Z, Xθ, Zθ = curve_point(curve, θ) + Xθθ, Zθθ = curve.spline_x(mod(θ, 2π); deriv=DerivOp(2)), curve.spline_z(mod(θ, 2π); deriv=DerivOp(2)) + # Newton step on ½|(x, z) - (X(θ), Z(θ))|², clamped to one grid spacing + Δ = clamp(((x - X) * Xθ + (z - Z) * Zθ) / (Xθ^2 + Zθ^2 - (x - X) * Xθθ - (z - Z) * Zθθ), -2π / M, 2π / M) + θ += Δ + abs(Δ) < 1e-14 && break + end + X, Z, Xθ, Zθ = curve_point(curve, θ) + J = hypot(Xθ, Zθ) + # Outward unit normal of a counter-clockwise (R, Z) contour is (Zθ, -Xθ) / J, so d > 0 outside and d < 0 inside + return (; θ=mod(θ, 2π), d=((x - X) * Zθ - (z - Z) * Xθ) / J, h=J * 2π / M) +end + +# 3D spectral grid and singular-patch utilities + """ trig_derivative_matrix(n) -> Matrix{Float64} @@ -155,33 +261,93 @@ function trig_upsample(a::AbstractMatrix{Float64}, Uθ::Matrix{Float64}, Uζ::Ma end """ - periodic_wrap(x, n) -> Int + SurfacePoint(r, rθ, rζ) -`mod1(x, n)` without a division. Only valid for `1 - n ≤ x ≤ 2n`. +A 3D surface point with its tangents ∂r/∂θ, ∂r/∂ζ, interpolated together on the singular-correction patch. """ -@inline periodic_wrap(x::Int, n::Int) = x < 1 ? x + n : (x > n ? x - n : x) +struct SurfacePoint + r::SVector{3,Float64} + rθ::SVector{3,Float64} + rζ::SVector{3,Float64} +end + +Base.:+(a::SurfacePoint, b::SurfacePoint) = SurfacePoint(a.r + b.r, a.rθ + b.rθ, a.rζ + b.rζ) +Base.:*(w::Real, a::SurfacePoint) = SurfacePoint(w * a.r, w * a.rθ, w * a.rζ) +Base.zero(::Type{SurfacePoint}) = SurfacePoint(zero(SVector{3,Float64}), zero(SVector{3,Float64}), zero(SVector{3,Float64})) """ - cross3!(c, a, b, idx) +Partition of unity `χ(r) = exp(-36 r^p)` of the singular-correction patch, `r` in patch radii. `p` keys on `PATCH_DIM`, the +collocation patch, since χ blends on the collocation grid. +""" +@inline function patch_pou(r::Float64, PATCH_DIM::Int) + pou_power = PATCH_DIM > 45 ? 10 : (PATCH_DIM > 20 ? 8 : 6) + return r ≥ 1.0 ? 0.0 : exp(-36.0 * r^pou_power) +end -Write the cross product of rows `idx` of the `(N, 3)` matrices `a` and `b` into row `idx` of `c`. """ -@inline function cross3!( - c::AbstractMatrix, - a::AbstractMatrix, - b::AbstractMatrix, - idx::Int -) - @inbounds begin - a1 = a[idx, 1] - a2 = a[idx, 2] - a3 = a[idx, 3] - b1 = b[idx, 1] - b2 = b[idx, 2] - b3 = b[idx, 3] + patch_stencil(U, V, UP_DIM, Val(N)) -> (cu, cv, wu, wv) - c[idx, 1] = a2 * b3 - a3 * b2 - c[idx, 2] = a3 * b1 - a1 * b3 - c[idx, 3] = a1 * b2 - a2 * b1 +0-based corner and Lagrange weights of the `N × N` interpolation stencil at 0-based upsampled-patch coordinates `(U, V)`. +The corner is rounded, not truncated, so an odd `N` is equivariant under the patch's π-rotation (stellarator symmetry), +and clamped to the patch. +""" +@inline function patch_stencil(U::Float64, V::Float64, UP_DIM::Int, val::Val{N}) where {N} + cu = clamp(round(Int, U) - (N - 1) ÷ 2, 0, UP_DIM - N) + cv = clamp(round(Int, V) - (N - 1) ÷ 2, 0, UP_DIM - N) + return cu, cv, lagrange_weights(U - cu, val), lagrange_weights(V - cv, val) +end + +""" + interpolate_patch(patch, U, V, Val(N)) -> (q, cu, cv, wu, wv) + +`N × N` Lagrange interpolant of the patch at 0-based coordinates `(U, V)`, with its stencil. +""" +@inline function interpolate_patch(patch::Matrix{SurfacePoint}, U::Float64, V::Float64, val::Val{N}) where {N} + cu, cv, wu, wv = patch_stencil(U, V, size(patch, 1), val) + q = zero(SurfacePoint) + @inbounds for b in 1:N, a in 1:N + q += (wu[a] * wv[b]) * patch[cu+a, cv+b] + end + return q, cu, cv, wu, wv +end + +""" + closest_point(patch, r, U, V, dU, dV, Val(N)) -> (U, V) + +Patch coordinates of the surface point closest to `r`, by Gauss–Newton on the patch interpolant from `(U, V)`; `dU`, `dV` +are the patch's node spacings in θ and ζ. Steps are capped at 2 nodes. +""" +function closest_point(patch::Matrix{SurfacePoint}, r::SVector{3,Float64}, U::Float64, V::Float64, dU::Float64, dV::Float64, val::Val) + for _ in 1:20 + q = interpolate_patch(patch, U, V, val)[1] + # 2×2 Gauss–Newton step (JᵀJ) Δ = Jᵀ(r - q.r) in patch-node coordinates ∂r/∂U = rθ dU, ∂r/∂V = rζ dV + e, ru, rv = r - q.r, q.rθ * dU, q.rζ * dV + g1, g2, h11, h12, h22 = dot(ru, e), dot(rv, e), dot(ru, ru), dot(ru, rv), dot(rv, rv) + ΔU = clamp((h22 * g1 - h12 * g2) / (h11 * h22 - h12^2), -2.0, 2.0) + ΔV = clamp((h11 * g2 - h12 * g1) / (h11 * h22 - h12^2), -2.0, 2.0) + U, V = U + ΔU, V + ΔV + abs(ΔU) + abs(ΔV) < 1e-10 && break + end + return U, V +end + +""" + foreach_polar_node(f, patch, U, V, radial, patch_rad, ANG_DIM, Val(N)) + +Polar quadrature of radius `patch_rad` collocation nodes about patch point `(U, V)`, on radial nodes `(ρ, dρ)` in +`radial` (ρ in patch radii). Calls `f(q, cu, cv, wu, wv, w)` at each node with the interpolated patch data, its stencil, +and the area weight χ(ρ) ρ dρ dα in collocation-node units [Malhotra JCP 397 (2019) 108791 eq. 38]. +""" +function foreach_polar_node(f, patch::Matrix{SurfacePoint}, U::Float64, V::Float64, radial, patch_rad::Int, ANG_DIM::Int, val::Val) + # One patch radius = patch_rad collocation cells (area scale patch_rad²) = c = 2·patch_rad upsampled-patch spacings + PATCH_DIM, c = 2 * patch_rad + 1, 2.0 * patch_rad + # The radial weights do not depend on the angle, so the POU and sinh map are evaluated once per row + rings = [(ρ, patch_pou(ρ, PATCH_DIM) * patch_rad^2 * ρ * dρ * (2π / ANG_DIM)) for (ρ, dρ) in radial] + @inbounds for ia in 1:ANG_DIM + sα, cα = sincos(2π * (ia - 1) / ANG_DIM) + for (ρ, w) in rings + q, cu, cv, wu, wv = interpolate_patch(patch, U + c * ρ * cα, V + c * ρ * sα, val) + f(q, cu, cv, wu, wv, w) + end end end diff --git a/test/runtests_vacuum.jl b/test/runtests_vacuum.jl index a79fd29e1..b1959d17f 100644 --- a/test/runtests_vacuum.jl +++ b/test/runtests_vacuum.jl @@ -1,4 +1,5 @@ using GeneralizedPerturbedEquilibrium: Vacuum +using QuadGK: quadgk using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, DeeWall, ModDeeWall, FileWall @testset "Vacuum.jl Unit Tests" begin @@ -113,8 +114,8 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee _circle_inputs(mtheta) = VacuumInput(; mtheta_in=mtheta, nzeta_in=1, - x=1.7 .+ 0.3 .* cos.(range(0, 2π; length=mtheta)), - z=0.3 .* sin.(range(0, 2π; length=mtheta)), + x=1.7 .+ 0.3 .* cos.(range(0, 2π; length=mtheta + 1)[1:mtheta]), + z=0.3 .* sin.(range(0, 2π; length=mtheta + 1)[1:mtheta]), ν=zeros(mtheta), mtheta=mtheta, nzeta=1 @@ -195,8 +196,8 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee VacuumInput(; mtheta_in=16, nzeta_in=1, - x=0.05 .+ 0.03 .* cos.(range(0, 2π; length=16)), - z=0.03 .* sin.(range(0, 2π; length=16)), + x=0.05 .+ 0.03 .* cos.(range(0, 2π; length=17)[1:16]), + z=0.03 .* sin.(range(0, 2π; length=17)[1:16]), ν=zeros(16), mtheta=16, nzeta=1 @@ -374,8 +375,8 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee _make_inputs(; mtheta=128, mtheta_eq=17, m_modes=1:2, n_modes=[1]) = VacuumInput(; mtheta_in=mtheta_eq, nzeta_in=1, - x=collect(1.7 .+ 0.3 .* cos.(range(0, 2π; length=mtheta_eq))), - z=collect(0.3 .* sin.(range(0, 2π; length=mtheta_eq))), + x=collect(1.7 .+ 0.3 .* cos.(2π .* (0:(mtheta_eq-1)) ./ mtheta_eq)), + z=collect(0.3 .* sin.(2π .* (0:(mtheta_eq-1)) ./ mtheta_eq)), ν=zeros(mtheta_eq), m_modes=collect(Int, m_modes), n_modes=collect(Int, n_modes), @@ -434,6 +435,55 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee @test isapprox(wv, wv', rtol=1e-12) end + @testset "close wall: near plasma–wall pairs found by distance" begin + # Shaped plasma, conformal wall 0.3 node spacings off at M = 128 (the old index-anchored panels erred by + # O(1) on misaligned nodes). Wall offset along the analytic normal, so every node placement is the same curve. + M, ms = 128, collect(-6:6) + p(θ) = (1.7 + 0.6cos(θ + 0.41sin(θ)), 1.08sin(θ)) + dp(θ) = (-0.6sin(θ + 0.41sin(θ)) * (1 + 0.41cos(θ)), 1.08cos(θ)) + wallpt(θ, g) = (d=dp(θ); J=hypot(d...); (p(θ)[1] + g * d[2] / J, p(θ)[2] - g * d[1] / J)) + θ = 2π .* (0:(M-1)) ./ M + g = 0.3 * sum(t -> hypot(dp(t)...), θ) * 2π / M / M + inputs = VacuumInput(; x=first.(p.(θ)), z=last.(p.(θ)), ν=zeros(M), mtheta_in=M, m_modes=ms, n_modes=[1], mtheta=M) + # No non-Hermitian warning: the solve itself is accurate, not just symmetrized + wv_of(u; ea=false) = mktemp() do path, io + println(io, M, "\n1.7\ni R Z") + foreach(((k, t),) -> println(io, k, " ", join(wallpt(t, g), " ")), enumerate(u)) + close(io) + @test_logs min_level = Base.CoreLogging.Warn compute_vacuum_response(inputs, FileWall(; file=path, equal_arc_wall=ea)).wv + end + wvs = [wv_of(θ), wv_of(θ .+ π / M), wv_of(θ .+ 0.3 .* sin.(θ)), wv_of(θ; ea=true)] + for w in wvs[2:end] + @test norm(w - wvs[1]) < 3e-5 * norm(wvs[1]) + end + + # The wall is checked against the plasma when built: a crossing throws, a gap under a tenth of a cell warns + wall_of(gap) = mktemp() do path, io + println(io, M, "\n1.7\ni R Z") + foreach(((k, t),) -> println(io, k, " ", join(wallpt(t, gap), " ")), enumerate(θ)) + close(io) + Vacuum.WallGeometry(inputs, PlasmaGeometry(inputs), FileWall(; file=path, equal_arc_wall=false)) + end + @test_throws ArgumentError wall_of(-g) + @test_logs (:warn, r"tenth of a cell") wall_of(g / 100) + + # One near row against direct adaptive quadrature of the same kernel; (σ, res) are the normal sign and + # Gauss's-law diagonal residue applied at the end of `compute_2D_kernel_matrices!` + P = PlasmaGeometry(inputs.x, inputs.z, zeros(M)) + W = Vacuum.WallGeometry(false, first.(wallpt.(θ .+ π / M, g)), last.(wallpt.(θ .+ π / M, g))) + χ(t) = cos(3t) + 0.5sin(t) + for (obs, src, σ, res) in ((P, W, -1, -2.0), (W, P, 1, 0.0)) + grad, green_mat = zeros(2M, 2M), zeros(M, M) + Vacuum.compute_2D_kernel_matrices!(grad, green_mat, obs, src, 1) + rows, cols = obs isa PlasmaGeometry ? (1:M) : ((M+1):2M), src isa PlasmaGeometry ? (1:M) : ((M+1):2M) + j = 5 + kern(t) = Vacuum.green(obs.x[j], obs.z[j], Vacuum.curve_point(src, t)..., 1; pn_cache=Vacuum.get_pn_quad_cache(1)) + I = quadgk(t -> (k=kern(t); [k[2] * χ(t), k[3], k[1] * χ(t)]), range(0, 2π, 65)...; rtol=1e-12)[1] + @test grad[rows, cols][j, :]' * χ.(θ) ≈ σ * (I[1] - χ(θ[j]) * I[2]) + res * χ(θ[j]) rtol = 1e-5 + src isa PlasmaGeometry && @test green_mat[j, :]' * χ.(θ) ≈ I[3] / 2π rtol = 1e-5 + end + end + @testset "edge: single poloidal mode mpert=1" begin inputs = _make_inputs(; m_modes=[1], n_modes=[1]) wall_settings = nothing @@ -548,8 +598,8 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee _make_3d_inputs(; mtheta=32, mtheta_eq=17, m_modes=1:2, n_modes=0:1, nzeta=32) = VacuumInput(; mtheta_in=mtheta_eq, nzeta_in=1, - x=collect(1.7 .+ 0.3 .* cos.(range(0, 2π; length=mtheta_eq))), - z=collect(0.3 .* sin.(range(0, 2π; length=mtheta_eq))), + x=collect(1.7 .+ 0.3 .* cos.(range(0, 2π; length=mtheta_eq + 1)[1:mtheta_eq])), + z=collect(0.3 .* sin.(range(0, 2π; length=mtheta_eq + 1)[1:mtheta_eq])), ν=zeros(mtheta_eq), m_modes=collect(Int, m_modes), n_modes=collect(Int, n_modes), @@ -881,6 +931,41 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee @test norm(imag.(r3d.I_v) - imag.(r2d.I_v)) < norm(imag.(r3d.I_v) + imag.(r2d.I_v)) end + # Plasma–wall rows take a polar patch centred at the closest source point, with sinh-mapped radial nodes that resolve + # the kernel peak over the gap (here 0.16 toroidal spacings), so the wall's node placement does not matter. + @testset "close wall: 3D plasma–wall rows centred at the closest point" begin + M, nz = 32, 32 + p(θ) = (1.7 + 0.6cos(θ + 0.41sin(θ)), 1.08sin(θ)) + dp(θ) = (-0.6sin(θ + 0.41sin(θ)) * (1 + 0.41cos(θ)), 1.08cos(θ)) + θ = 2π .* (0:(M-1)) ./ M + make(M, nzeta) = (t=2π .* (0:(M-1)) ./ M; + VacuumInput(; x=first.(p.(t)), z=last.(p.(t)), ν=zeros(M), mtheta_in=M, m_modes=collect(-4:4), n_modes=[1], mtheta=M, nzeta)) + wall = ConformalWall(; standoff_fraction=0.1, equal_arc_wall=false) + wv2d = compute_vacuum_response(make(512, 1), wall).wv + @test norm(compute_vacuum_response(make(M, nz), wall).wv - wv2d) / norm(wv2d) < 3e-3 + + # Same wall curve on aligned and half-node-shifted nodes: rows applied to one smooth density agree + P = Vacuum.PlasmaGeometry3D(make(M, nz)) + g = 0.3 * sum(t -> hypot(dp(t)...), θ) * 2π / M / M + wallpt(t) = (d=dp(t); J=hypot(d...); (p(t)[1] + g * d[2] / J, p(t)[2] - g * d[1] / J)) + function revolve(shift) + r, rθ, rζ, n = (zeros(M * nz, 3) for _ in 1:4) + for j in 1:nz, i in 1:M + k, t, ζ = i + M * (j - 1), θ[i] + shift, 2π * (j - 1) / nz + (R, Z), (Rp, Zp) = wallpt(t), (wallpt(t + 1e-6) .- wallpt(t - 1e-6)) ./ 2e-6 + r[k, :], rθ[k, :], rζ[k, :] = [R * cos(ζ), R * sin(ζ), Z], [Rp * cos(ζ), Rp * sin(ζ), Zp], [-R * sin(ζ), R * cos(ζ), 0] + n[k, :] = cross(rθ[k, :], rζ[k, :]) + end + return Vacuum.WallGeometry3D(false, M, nz, r, rθ, rζ, n, 1) + end + rows = map((0.0, π / M)) do shift + G, S = [zeros(2M * nz, 2M * nz)], [zeros(2M * nz, M * nz)] + Vacuum.compute_3D_kernel_matrices!(G, S, P, revolve(shift), M ÷ 3, 16, 11, [1.0]) + G[1][1:(M*nz), (M*nz+1):end] * vec([cos(θ[i] + shift) * cos(2π * (j - 1) / nz) for i in 1:M, j in 1:nz]) + end + @test maximum(abs, rows[1] - rows[2]) < 1e-4 * maximum(abs, rows[1]) + end + # ν enters the 3D path only through the geometry (ϕ = ζ + ν) and the 2D path only through the basis (ζ = -ν at ϕ = 0), # so the two agree only if both use the same relation. Negating ν in 2D alone misses by O(0.1). @testset "2D and 3D paths agree for a nonzero ν" begin @@ -1168,7 +1253,8 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee end @testset "Kernel3D laplace_kernel" begin - G, K = GeneralizedPerturbedEquilibrium.Vacuum.laplace_kernel(1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 0.0, 0.0) + SV = GeneralizedPerturbedEquilibrium.Vacuum.SVector + G, K = GeneralizedPerturbedEquilibrium.Vacuum.laplace_kernel(SV(1.0, 0.0, 0.0), SV(2.0, 0.0, 0.0), SV(1.0, 0.0, 0.0)) # Kernel returns 1/|r_obs - r_src| (4π factor applied elsewhere in BIE) dist = sqrt((2.0 - 1.0)^2 + 0 + 0) @test isapprox(G, 1.0 / dist) @@ -1177,17 +1263,6 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee @test isfinite(K) end - @testset "Kernel3D get_singular_quadrature" begin - quad = GeneralizedPerturbedEquilibrium.Vacuum.get_singular_quadrature(3, 8, 5) - @test quad.PATCH_RAD == 3 - @test quad.RAD_DIM == 8 - @test quad.INTERP_ORDER == 5 - @test quad.PATCH_DIM == 2 * 3 + 1 - # Cached: second call returns same object - quad2 = GeneralizedPerturbedEquilibrium.Vacuum.get_singular_quadrature(3, 8, 5) - @test quad === quad2 - end - @testset "Kernel3D extract_patch!" begin # 4×4 grid (npol=4, ntor=4), PATCH_DIM=3, center at (2,2) data = collect(1.0:16.0) @@ -1237,14 +1312,11 @@ using GeneralizedPerturbedEquilibrium.Vacuum: ConformalWall, EllipticalWall, Dee VAC = GeneralizedPerturbedEquilibrium.Vacuum KF = GeneralizedPerturbedEquilibrium.KineticForces VAC.get_pn_quad_cache(3) - VAC.get_singular_quadrature(3, 8, 5) KF._quadrature_weights(8) @test !isempty(VAC._PN_CACHE) - @test VAC.SINGULAR_QUAD_CACHE[] !== nothing @test !isempty(KF._QUAD_WEIGHTS) @test VAC.reset_caches!() === nothing @test isempty(VAC._PN_CACHE) - @test VAC.SINGULAR_QUAD_CACHE[] === nothing @test KF.reset_caches!() === nothing @test isempty(KF._QUAD_WEIGHTS) end