From 59d7714a95ec5d6c7338750f1bb848753fc3a233 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:00:57 +0000 Subject: [PATCH 01/22] Add Maxwell eigenmode solve via a KrylovKit extension MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit maxwell_eigenmodes(model; nev, target_frequency) solves Kc u = λ Mε u on the dofs off the PEC facets (eliminated, not constrained by apply!) by shift-invert Arnoldi: one sparse LU of Kc - σ Mε, real or complex when lossy, and KrylovKit eigsolve on u -> (Kc - σ Mε) \ (Mε u). Each Krylov vector is projected, along the discrete gradients of the hat functions off the PEC facets, onto discretely divergence-free fields, so the λ = 0 null space never enters even for a target below the lowest mode; residual |λ| < nullspace_tol·σ is filtered. It returns frequencies, Q = Re(ω)/(2 Im(ω)), complex ω and MaxwellSolution modes. KrylovKit is a weak dependency; without it a fallback hook names the package to load. Tests check the PEC box against the analytic TE/TM list (15 modes with multiplicities, rate ~2 over three meshes), a dielectric fill, Q = 1/tan δ and the SI 100x50x75 mm box. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- Project.toml | 6 +- docs/src/maxwell.md | 18 ++++ ext/FiniteElementMethodKrylovKitExt.jl | 12 +++ src/FiniteElementMethod.jl | 7 +- src/maxwell/eigen.jl | 126 +++++++++++++++++++++++++ src/maxwell/model.jl | 7 +- test/Maxwell/eigen.jl | 119 +++++++++++++++++++++++ 7 files changed, 288 insertions(+), 7 deletions(-) create mode 100644 ext/FiniteElementMethodKrylovKitExt.jl create mode 100644 src/maxwell/eigen.jl create mode 100644 test/Maxwell/eigen.jl diff --git a/Project.toml b/Project.toml index fc7c0189..cb78e4a1 100644 --- a/Project.toml +++ b/Project.toml @@ -22,9 +22,11 @@ Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" [weakdeps] FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" +KrylovKit = "0b1a1467-8014-51b9-945f-bf0ae24f4b77" [extensions] FiniteElementMethodFerriteGmshExt = "FerriteGmsh" +FiniteElementMethodKrylovKitExt = "KrylovKit" [compat] ADTypes = "1.24" @@ -35,6 +37,7 @@ Ferrite = "1.7" FerriteGmsh = "1.5" ForwardDiff = "1.4" Gmsh = "0.3" +KrylovKit = "0.9, 0.10" LinearAlgebra = "1.10" ModelingToolkit = "11.34" LinearSolve = "5" @@ -58,6 +61,7 @@ julia = "1.10" AllocCheck = "9b6a8646-10ed-4001-bbdc-1d2f46dfbb1a" FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" Gmsh = "705231aa-382f-11e9-3f0c-b7cb4346fdeb" +KrylovKit = "0b1a1467-8014-51b9-945f-bf0ae24f4b77" LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae" OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" OrdinaryDiffEqNonlinearSolve = "127b3ac7-2247-4354-8eb6-78cf4e7c58e8" @@ -67,4 +71,4 @@ SciMLTesting = "09d9d899-5365-40a9-917a-5f67fddea283" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["AllocCheck", "FerriteGmsh", "Gmsh", "LinearSolve", "OrdinaryDiffEqBDF", "OrdinaryDiffEqNonlinearSolve", "Random", "SafeTestsets", "SciMLTesting", "Test"] +test = ["AllocCheck", "FerriteGmsh", "Gmsh", "KrylovKit", "LinearSolve", "OrdinaryDiffEqBDF", "OrdinaryDiffEqNonlinearSolve", "Random", "SafeTestsets", "SciMLTesting", "Test"] diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 01d2277d..fef6f73b 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -30,6 +30,23 @@ that is a function of `ω`, so a frequency sweep only recombines nonzero values [`maxwell_operator!`](@ref), and further terms (boundary conditions, ports) are added as blocks with `FiniteElementMethod.add_term!`. +## Resonant modes + +[`maxwell_eigenmodes`](@ref) finds the modes nearest a target frequency by shift-invert Arnoldi, with the +PEC dofs eliminated and the `ω = 0` gradient null space of the edge elements projected out, so any target +works, including one below the lowest mode. It needs `using KrylovKit`. A lossy material gives complex +`ω`; the quality factor is `Q = Re(ω) / (2 Im(ω))`. An air-filled 100 × 50 × 75 mm box has its TE101 mode +at 2.498 GHz: + +```julia +using FiniteElementMethod, Ferrite, KrylovKit +grid = generate_grid(Tetrahedron, (12, 6, 9), Vec(0.0, 0.0, 0.0), Vec(100.0, 50.0, 75.0)) +model = MaxwellModel(grid; pec = ["left", "right", "bottom", "top", "front", "back"], length_scale = 1.0e-3) +modes = maxwell_eigenmodes(model; nev = 4, target_frequency = 2.0e9) +modes.frequency, modes.Q # Hz; Q is Inf without loss +field_values(modes.modes[1], [Vec(50.0, 25.0, 37.5)]).E +``` + ```@docs MaxwellModel MaxwellMaterial @@ -40,6 +57,7 @@ driven_problem solve_driven MaxwellSolution field_values +maxwell_eigenmodes FiniteElementMethod.maxwell_rhs FiniteElementMethod.add_term! FiniteElementMethod.EPS0 diff --git a/ext/FiniteElementMethodKrylovKitExt.jl b/ext/FiniteElementMethodKrylovKitExt.jl new file mode 100644 index 00000000..934596b1 --- /dev/null +++ b/ext/FiniteElementMethodKrylovKitExt.jl @@ -0,0 +1,12 @@ +module FiniteElementMethodKrylovKitExt + +using FiniteElementMethod: FiniteElementMethod, KrylovKitEigensolver +using KrylovKit: eigsolve + +function FiniteElementMethod._eigsolve(::KrylovKitEigensolver, op, x0, nev; krylovdim, tol, maxiter) + vals, vecs, info = eigsolve(op, x0, nev, :LM; ishermitian = false, krylovdim, tol, maxiter) + info.converged < nev && @warn "KrylovKit.eigsolve converged $(info.converged) of $nev eigenpairs" + return vals, vecs +end + +end # module diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index f25a7a4e..8bce5214 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: dot, mul!, norm +using LinearAlgebra: dot, lu, mul!, norm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -22,7 +22,7 @@ using PrecompileTools: PrecompileTools using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions using SciMLBase: SciMLBase, DAEFunction, DAEProblem using SciMLBase.SymbolicIndexingInterface: SymbolicIndexingInterface, getp, parameter_index, variable_index -using SparseArrays: SparseMatrixCSC, nnz, nonzeros, nzrange, rowvals +using SparseArrays: SparseMatrixCSC, nnz, nonzeros, nzrange, rowvals, sparse using SymbolicUtils: SymbolicUtils using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap @@ -52,8 +52,9 @@ export MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative # Frequency-domain Maxwell: a separate entry point assembled directly on Ferrite, not through the PDESystem front end. include("maxwell/model.jl") include("maxwell/driven.jl") +include("maxwell/eigen.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! -export MaxwellSolution, driven_problem, solve_driven, field_values +export MaxwellSolution, driven_problem, solve_driven, field_values, maxwell_eigenmodes include("precompile.jl") diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl new file mode 100644 index 00000000..07dfd259 --- /dev/null +++ b/src/maxwell/eigen.jl @@ -0,0 +1,126 @@ +# Resonant modes of a MaxwellModel: shift-invert on the PEC-free dofs with the gradient null space deflated. + +# Dispatch tag for the eigensolver of the KrylovKit extension. +struct KrylovKitEigensolver end + +# `_eigsolve(solver, op, x0, nev; krylovdim, tol, maxiter) -> (values, vectors)`: the `nev` eigenpairs of +# largest magnitude of the linear map `op` from the start vector `x0`. The KrylovKit extension implements it for +# `KrylovKitEigensolver()`; without that package loaded only this fallback exists. +function _eigsolve(solver, op, x0, nev; kwargs...) + throw(ArgumentError("maxwell_eigenmodes needs an eigensolver: run `using KrylovKit` first")) +end + +# The discrete gradient: column j holds the Nédélec dofs of the gradient of the j-th nodal hat function (each +# entry is ±1 or 0, with Ferrite's edge orientation), together with the Lagrange DofHandler of the columns. +function _discrete_gradient(model) + (; grid, dh) = model + ip = Ferrite.Lagrange{RefTetrahedron, 1}() + dhn = Ferrite.DofHandler(grid) + Ferrite.add!(dhn, :phi, ip) + Ferrite.close!(dhn) + qr = Ferrite.QuadratureRule{RefTetrahedron}(2) + cve, cvn = Ferrite.CellValues(qr, _NEDELEC), Ferrite.CellValues(qr, ip) + nq, ne, nn = Ferrite.getnquadpoints(qr), Ferrite.getnbasefunctions(cve), Ferrite.getnbasefunctions(cvn) + N, g = zeros(3nq, ne), zeros(3nq) + rows, cols, vals = Int[], Int[], Float64[] + for (ce, cn) in zip(Ferrite.CellIterator(dh), Ferrite.CellIterator(dhn)) + Ferrite.reinit!(cve, ce) + Ferrite.reinit!(cvn, cn) + for q in 1:nq, i in 1:ne + N[(3q - 2):(3q), i] .= Ferrite.shape_value(cve, q, i) + end + for a in 1:nn + for q in 1:nq + g[(3q - 2):(3q)] .= Ferrite.shape_gradient(cvn, q, a) + end + # The gradient lies in the Nédélec space exactly, so the least-squares coefficients are integers. + c = round.(N \ g) + for i in 1:ne + iszero(c[i]) && continue + push!(rows, Ferrite.celldofs(ce)[i]) + push!(cols, Ferrite.celldofs(cn)[a]) + push!(vals, c[i]) + end + end + end + G = sparse(rows, cols, vals, Ferrite.ndofs(dh), Ferrite.ndofs(dhn), (x, y) -> x) + return G, dhn +end + +""" + maxwell_eigenmodes(model::MaxwellModel; nev, target_frequency, krylovdim = max(30, 2nev + 10), + tol = 1e-10, maxiter = 300, nullspace_tol = 1e-6) + +The `nev` resonant modes of `model` with eigenfrequencies nearest `target_frequency` (Hz, real and positive), +sorted by frequency. Requires `using KrylovKit`. + +Source-free modes satisfy `Kc u = λ (Mε' + i Mε'') u` (see [`MaxwellModel`](@ref)) on the dofs off the PEC +facets, which are eliminated rather than constrained, with `λ = ω² μ0 ε0 L²`. The problem is solved by +shift-invert Arnoldi: one sparse LU of `Kc - σ Mε` at `σ` from `target_frequency` (complex when a material is +lossy), with KrylovKit's `eigsolve` on `u ↦ (Kc - σ Mε) \\ (Mε u)`. + +Edge elements carry the gradients of the nodal hat functions as an exact `λ = 0` null space (one mode per node +off the PEC facets), which would swamp the shift-invert for any target below the lowest physical mode. Every +Krylov vector is therefore projected, along those gradients, onto the discretely divergence-free fields, so the +null space never enters; eigenvalues with `|λ| < nullspace_tol |σ|` (such as the one constant mode of each +further disconnected PEC body) are dropped as well. + +Returns `(; frequency, Q, omega, modes)`: `omega` the complex angular frequencies `ω = √λ / (L √(μ0 ε0))`, +`frequency = Re(ω) / 2π` in Hz, `Q = Re(ω) / (2 Im(ω))` (`Inf` for a lossless model; with `exp(+iωt)` a passive +mode has `Im(ω) > 0` and decays as `exp(-Im(ω) t)`), and `modes` the [`MaxwellSolution`](@ref)s at +`Re(ω)`, with zeros on the PEC dofs, scaled to `∫ Re(εr) |E|² = 1` over the mesh (mesh units) with the +largest dof real. Conductivity and terms added with [`FiniteElementMethod.add_term!`](@ref) make the problem +nonlinear in `ω` and are rejected. +""" +function maxwell_eigenmodes( + model::MaxwellModel; nev::Integer, target_frequency::Real, krylovdim::Integer = max(30, 2nev + 10), + tol::Real = 1.0e-10, maxiter::Integer = 300, nullspace_tol::Real = 1.0e-6 + ) + target_frequency > 0 || throw(ArgumentError("target_frequency must be positive, got $target_frequency")) + all(iszero, nonzeros(model.blocks.sigma)) || + throw(ArgumentError("maxwell_eigenmodes does not support conductivity (the problem is quadratic in ω); model it as Im(eps_r)")) + length(model.terms) == 4 || + throw(ArgumentError("maxwell_eigenmodes supports only the volume terms of MaxwellModel, not terms added with add_term!")) + (; blocks, eps0, mu0, length_scale) = model + scale = mu0 * eps0 * length_scale^2 # λ = scale ω² + lossy = !all(iszero, nonzeros(blocks.eps_imag)) + T = lossy ? ComplexF64 : Float64 + n = Ferrite.ndofs(model.dh) + free = setdiff(1:n, _pec_dofs(model.dh, model.grid, model.pec)) + K = blocks.curlcurl[free, free] + M = lossy ? blocks.eps_real[free, free] + im * blocks.eps_imag[free, free] : blocks.eps_real[free, free] + σ = scale * (2π * target_frequency)^2 + F = lu(K - σ * M) + + # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them + # with x ↦ x - G (GᵀMG)⁻¹ GᵀM x (transposes, not adjoints: M is complex symmetric when lossy). + Gfull, dhn = _discrete_gradient(model) + nodes = setdiff(1:Ferrite.ndofs(dhn), _pec_dofs(dhn, model.grid, model.pec, Ferrite.Lagrange{RefTetrahedron, 1}())) + G = Gfull[free, nodes] + GtM = sparse(transpose(G) * M) + FG = lu(GtM * G) + project(x) = x - G * (FG \ (GtM * x)) + op(x) = project(F \ (M * x)) + + x0 = project(T.(sin.(1.3 .* (1:length(free)) .^ 1.1))) + θ, vecs = _eigsolve(KrylovKitEigensolver(), op, x0, nev; krylovdim, tol, maxiter) + λ = σ .+ 1 ./ θ + lossy || (λ = real.(λ)) + keep = findall(l -> abs(l) >= nullspace_tol * σ, λ) + length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" + keep = keep[sortperm(abs.(θ[keep]); rev = true)][1:min(nev, end)] # nearest the shift + keep = keep[sortperm(real.(λ[keep]))] + + omega = sqrt.(complex.(λ[keep])) ./ sqrt(scale) + Q = [iszero(imag(ω)) ? Inf : real(ω) / (2imag(ω)) for ω in omega] + Mr = blocks.eps_real[free, free] + modes = map(keep, omega) do j, ω + v = ComplexF64.(vecs[j]) + v ./= sqrt(real(dot(v, Mr * v))) + v .*= conj(sign(v[argmax(abs.(v))])) + u = zeros(ComplexF64, n) + u[free] = v + MaxwellSolution(model, real(ω), u) + end + return (; frequency = real.(omega) ./ 2π, Q, omega, modes) +end diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index f3f81ab8..f24cb5b9 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -143,9 +143,10 @@ function _cell_materials(grid, materials) return cell_materials end -# The edge dofs on the PEC facets: the tangential traces there are exactly these dofs. -function _pec_dofs(dh, grid, pec) - local_dofs = Ferrite.dirichlet_facetdof_indices(_NEDELEC) +# The edge dofs on the PEC facets: the tangential traces there are exactly these dofs. With another +# interpolation `ip` of the single field of `dh`, its dofs on those facets. +function _pec_dofs(dh, grid, pec, ip = _NEDELEC) + local_dofs = Ferrite.dirichlet_facetdof_indices(ip) dofs = Set{Int}() cell_dofs = zeros(Int, Ferrite.ndofs_per_cell(dh)) for name in pec, facet in Ferrite.getfacetset(grid, name) diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl new file mode 100644 index 00000000..5bc64077 --- /dev/null +++ b/test/Maxwell/eigen.jl @@ -0,0 +1,119 @@ +# Eigenmodes of a PEC rectangular cavity against the analytic TE/TM frequencies. +using FiniteElementMethod, Ferrite, KrylovKit, LinearAlgebra, Test +include(joinpath(@__DIR__, "..", "shared", "maxwell.jl")) + +const BOX = (1.0, 0.5, 0.75) + +# f_mnp = (c/2) sqrt((m/a)^2 + (n/b)^2 + (p/d)^2): TE needs p >= 1 and at most one of m, n zero; TM needs m, n >= 1. +function cavity_frequencies(a, b, d; c = 1.0, count = 15) + f = Float64[] + for m in 0:6, n in 0:6, p in 0:6 + fmnp = c / 2 * sqrt((m / a)^2 + (n / b)^2 + (p / d)^2) + p >= 1 && (m == 0) + (n == 0) <= 1 && push!(f, fmnp) + m >= 1 && n >= 1 && push!(f, fmnp) + end + return sort!(f)[1:count] +end + +# k cells per quarter unit along x, so the mesh size is h = 1 / (4k) in every direction. +box_grid(k; scale = 1.0) = generate_grid(Tetrahedron, (4k, 2k, 3k), Vec(0.0, 0.0, 0.0), Vec((scale .* BOX)...)) +box_model(k; kwargs...) = MaxwellModel(box_grid(k); pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0, kwargs...) + +const EXACT = cavity_frequencies(BOX...) + +@testset "analytic cavity list" begin + @test round.(EXACT; digits = 4) == [ + 0.8333, 1.118, 1.2019, 1.2019, 1.3017, 1.3017, 1.4142, 1.424, 1.5635, 1.5635, 1.6415, 1.6667, 1.6667, + 1.7401, 1.7401, + ] +end + +@testset "PEC box: 15 modes with multiplicities, O(h^2) convergence, no spurious modes" begin + ks = (3, 4, 6) + computed = map(ks) do k + # A target below the first mode: the k = 0 gradient null space is closer to the shift than any physical + # mode, so this fails unless it is deflated. + modes = maxwell_eigenmodes(box_model(k); nev = length(EXACT), target_frequency = 0.4) + @test length(modes.frequency) == length(EXACT) + @test issorted(modes.frequency) + @test all(isinf, modes.Q) + modes.frequency + end + errs = [abs.(f .- EXACT) ./ EXACT for f in computed] + @test maximum(errs[end]) < 0.01 + hs = [1 / (4k) for k in ks] + @test minimum(rates(first.(errs), hs)) >= 1.7 + @test minimum(rates(sum.(errs) ./ length(EXACT), hs)) >= 1.7 + # Nothing between the filtered null space and the lowest physical mode, at every refinement. + @test all(f -> f[1] > 0.95 * EXACT[1], computed) + for (k, f, e) in zip(ks, computed, errs) + println("k = $k: ", join(string.(round.(f; digits = 5)), " "), " max rel err ", maximum(e)) + end +end + +@testset "a target among the modes returns those nearest to it" begin + modes = maxwell_eigenmodes(box_model(3); nev = 4, target_frequency = 1.3) + @test length(modes.frequency) == 4 + # The four exact modes nearest 1.3: 1.2019 (x2) and 1.3017 (x2). + @test modes.frequency ≈ EXACT[3:6] rtol = 0.02 +end + +@testset "eigenvectors are fields: PEC trace, field_values, residual" begin + model = box_model(3) + modes = maxwell_eigenmodes(model; nev = 1, target_frequency = 0.8) + sol = modes.modes[1] + @test sol isa MaxwellSolution + @test sol.omega ≈ 2π * modes.frequency[1] + # Zero on the PEC dofs, and A(ω) u = 0 at the eigenfrequency. + @test all(iszero, sol.u[model.ch.prescribed_dofs]) + A = maxwell_operator(model, sol.omega) + free = setdiff(1:ndofs(model.dh), model.ch.prescribed_dofs) + @test norm((A * sol.u)[free]) / norm(model.blocks.curlcurl * sol.u) < 1.0e-6 + # TE101: E along y only, E_y ∝ sin(πx/a) sin(πz/d). + E = field_values(sol, [Vec(0.5, 0.25, 0.375), Vec(0.25, 0.25, 0.375)]).E + @test abs(E[1][2]) > 10 * max(abs(E[1][1]), abs(E[1][3])) + @test abs(E[2][2]) / abs(E[1][2]) ≈ sin(π / 4) rtol = 0.05 +end + +@testset "uniform dielectric fill scales every frequency by 1/sqrt(eps_r)" begin + vacuum = maxwell_eigenmodes(box_model(3); nev = 6, target_frequency = 0.4).frequency + grid = box_grid(3) + addcellset!(grid, "fill", x -> true) + filled = MaxwellModel( + grid; materials = Dict("fill" => MaxwellMaterial(; eps_r = 2.2)), pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0 + ) + f = maxwell_eigenmodes(filled; nev = 6, target_frequency = 0.4 / sqrt(2.2)).frequency + @test f ./ vacuum ≈ fill(1 / sqrt(2.2), 6) rtol = 1.0e-8 +end + +@testset "lossy fill: Q = 1/tan δ" begin + tand = 1.0e-3 + grid = box_grid(3) + addcellset!(grid, "fill", x -> true) + lossy = MaxwellModel( + grid; materials = Dict("fill" => MaxwellMaterial(; eps_r = 2.2 * (1 - im * tand))), + pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0, + ) + modes = maxwell_eigenmodes(lossy; nev = 3, target_frequency = 0.5) + @test all(q -> isapprox(q, 1 / tand; rtol = 0.01), modes.Q) + @test all(ω -> imag(ω) > 0, modes.omega) # exp(+iωt) decays + @test modes.frequency ≈ real.(modes.omega) ./ 2π +end + +@testset "SI units: 100 x 50 x 75 mm box" begin + model = MaxwellModel(box_grid(3; scale = 100.0); pec = CUBE_FACES, length_scale = 1.0e-3) + f1 = maxwell_eigenmodes(model; nev = 1, target_frequency = 2.0e9).frequency[1] + @test f1 ≈ FiniteElementMethod.C0 / 2 * sqrt(1 / 0.1^2 + 1 / 0.075^2) rtol = 0.01 + @test round(FiniteElementMethod.C0 / 2 * sqrt(1 / 0.1^2 + 1 / 0.075^2) / 1.0e9; digits = 3) == 2.498 +end + +@testset "argument checks" begin + model = box_model(2) + @test_throws ArgumentError maxwell_eigenmodes(model; nev = 2, target_frequency = 0.0) + grid = box_grid(2) + addcellset!(grid, "all", x -> true) + conductor = MaxwellModel(grid; pec = CUBE_FACES, materials = Dict("all" => MaxwellMaterial(; sigma = 1.0))) + @test_throws "conductivity" maxwell_eigenmodes(conductor; nev = 1, target_frequency = 1.0e9) + # Without KrylovKit the eigensolver hook has only its fallback, which names the package to load. + @test_throws "KrylovKit" FiniteElementMethod._eigsolve(nothing, identity, zeros(2), 1) +end From 1d30d098449831575abeaa7a1e905ee412a9f682 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:10:25 +0000 Subject: [PATCH 02/22] Fix Maxwell eigenmodes without PEC and rank modes by frequency Without PEC (or on any connected part of the mesh with no PEC node) the gradients of all nodal hat functions sum to zero, so G'MG was singular and maxwell_eigenmodes threw SingularException; one potential dof per such part is now dropped. Shift-invert ranks modes by distance in lambda ~ omega^2, which favours modes below the target; it now computes at least 2nev candidates, grows the count until every mode within the nev-th frequency distance must be among them, and returns the nev nearest in frequency, as documented. Found in review. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 68 ++++++++++++++++++++++++++++++++++++------- test/Maxwell/eigen.jl | 13 +++++++++ 2 files changed, 70 insertions(+), 11 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 07dfd259..75da1012 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -47,20 +47,52 @@ function _discrete_gradient(model) return G, dhn end +# The potential dofs whose hat-function gradients span the gradient null space on the free edge dofs, without +# dependence: every node off the PEC facets, less one node of each connected part of the mesh with no PEC node +# (there the gradients of all its hat functions sum to zero). +function _potential_dofs(dhn, grid, pec) + on_pec = falses(Ferrite.ndofs(dhn)) + on_pec[_pec_dofs(dhn, grid, pec, Ferrite.Lagrange{RefTetrahedron, 1}())] .= true + root = collect(1:Ferrite.ndofs(dhn)) + find(i) = ( + while root[i] != i + i = root[i] = root[root[i]] + end; i + ) + for cell in 1:Ferrite.getncells(grid) + dofs = Ferrite.celldofs(dhn, cell) + for d in dofs + root[find(d)] = find(dofs[1]) + end + end + pinned = falses(length(root)) + for i in eachindex(root) + on_pec[i] && (pinned[find(i)] = true) + end + drop = copy(on_pec) + for i in eachindex(root) + r = find(i) + pinned[r] || (drop[i] = pinned[r] = true) # the first node met in an unpinned part + end + return findall(!, drop) +end + """ maxwell_eigenmodes(model::MaxwellModel; nev, target_frequency, krylovdim = max(30, 2nev + 10), tol = 1e-10, maxiter = 300, nullspace_tol = 1e-6) -The `nev` resonant modes of `model` with eigenfrequencies nearest `target_frequency` (Hz, real and positive), -sorted by frequency. Requires `using KrylovKit`. +The `nev` resonant modes of `model` with eigenfrequencies `Re(ω) / 2π` nearest `target_frequency` (Hz, real and +positive), sorted by frequency. Requires `using KrylovKit`. Source-free modes satisfy `Kc u = λ (Mε' + i Mε'') u` (see [`MaxwellModel`](@ref)) on the dofs off the PEC facets, which are eliminated rather than constrained, with `λ = ω² μ0 ε0 L²`. The problem is solved by shift-invert Arnoldi: one sparse LU of `Kc - σ Mε` at `σ` from `target_frequency` (complex when a material is -lossy), with KrylovKit's `eigsolve` on `u ↦ (Kc - σ Mε) \\ (Mε u)`. +lossy), with KrylovKit's `eigsolve` on `u ↦ (Kc - σ Mε) \\ (Mε u)`. Shift-invert ranks modes by distance in +`λ ∝ ω²`, so it computes at least `2nev` candidates, enough to contain the `nev` nearest in frequency, and +returns those; `krylovdim` grows with the candidate count. Edge elements carry the gradients of the nodal hat functions as an exact `λ = 0` null space (one mode per node -off the PEC facets), which would swamp the shift-invert for any target below the lowest physical mode. Every +off the PEC facets, less one per connected part of the mesh without PEC), which would swamp the shift-invert for any target below the lowest physical mode. Every Krylov vector is therefore projected, along those gradients, onto the discretely divergence-free fields, so the null space never enters; eigenvalues with `|λ| < nullspace_tol |σ|` (such as the one constant mode of each further disconnected PEC body) are dropped as well. @@ -95,20 +127,34 @@ function maxwell_eigenmodes( # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them # with x ↦ x - G (GᵀMG)⁻¹ GᵀM x (transposes, not adjoints: M is complex symmetric when lossy). Gfull, dhn = _discrete_gradient(model) - nodes = setdiff(1:Ferrite.ndofs(dhn), _pec_dofs(dhn, model.grid, model.pec, Ferrite.Lagrange{RefTetrahedron, 1}())) - G = Gfull[free, nodes] + G = Gfull[free, _potential_dofs(dhn, model.grid, model.pec)] GtM = sparse(transpose(G) * M) FG = lu(GtM * G) project(x) = x - G * (FG \ (GtM * x)) op(x) = project(F \ (M * x)) x0 = project(T.(sin.(1.3 .* (1:length(free)) .^ 1.1))) - θ, vecs = _eigsolve(KrylovKitEigensolver(), op, x0, nev; krylovdim, tol, maxiter) - λ = σ .+ 1 ./ θ - lossy || (λ = real.(λ)) - keep = findall(l -> abs(l) >= nullspace_tol * σ, λ) + # Shift-invert finds the modes nearest σ in λ ∝ ω², which favours those below the target. Every mode within + # frequency distance d of the target lies within λ distance (2ωt + d) d scale of σ, so the candidates (all + # modes within the largest λ distance R found) hold the nev nearest in frequency once R reaches that bound. + ωt = 2π * target_frequency + howmany = 2nev + local λ, vecs, keep + while true + θ, vecs = _eigsolve(KrylovKitEigensolver(), op, x0, howmany; krylovdim = max(krylovdim, howmany + 20), tol, maxiter) + λ = σ .+ 1 ./ θ + lossy || (λ = real.(λ)) + keep = findall(l -> abs(l) >= nullspace_tol * σ, λ) + dist = abs.(real.(sqrt.(complex.(λ[keep]) ./ scale)) .- ωt) + keep = keep[sortperm(dist)] + length(keep) < nev && break + d = sort(dist)[nev] + maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale && break + howmany >= length(free) && break + howmany = min(2howmany, length(free)) + end length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" - keep = keep[sortperm(abs.(θ[keep]); rev = true)][1:min(nev, end)] # nearest the shift + keep = keep[1:min(nev, end)] keep = keep[sortperm(real.(λ[keep]))] omega = sqrt.(complex.(λ[keep])) ./ sqrt(scale) diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 5bc64077..e78c323e 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -56,6 +56,19 @@ end @test length(modes.frequency) == 4 # The four exact modes nearest 1.3: 1.2019 (x2) and 1.3017 (x2). @test modes.frequency ≈ EXACT[3:6] rtol = 0.02 + # Nearest in frequency, not in ω²: from 0.98, TM110 (1.118, 0.138 away) beats TE101 (0.833, 0.147 away). + @test maxwell_eigenmodes(box_model(3); nev = 1, target_frequency = 0.98).frequency[1] ≈ EXACT[2] rtol = 0.01 +end + +@testset "no PEC: the constant potential is removed from the gradient basis" begin + # Natural (magnetic-wall) conditions everywhere: the dual of the PEC cube, lowest at √2/2 (x3). + single = MaxwellModel(generate_grid(Tetrahedron, (1, 1, 1)); eps0 = 1.0, mu0 = 1.0) + @test length(maxwell_eigenmodes(single; nev = 1, target_frequency = 0.4).frequency) == 1 + f = maxwell_eigenmodes(MaxwellModel(unit_cube(4); eps0 = 1.0, mu0 = 1.0); nev = 3, target_frequency = 0.4).frequency + @test f ≈ fill(sqrt(2) / 2, 3) rtol = 0.02 + # PEC on one face only: the potential is pinned there, so no node is removed and the basis is still full. + f = maxwell_eigenmodes(MaxwellModel(unit_cube(4); pec = ["left"], eps0 = 1.0, mu0 = 1.0); nev = 2, target_frequency = 0.4).frequency + @test length(f) == 2 && all(>(0.1), f) end @testset "eigenvectors are fields: PEC trace, field_values, residual" begin From 20cab172bd6c5285a4721ac0bee89266b58d8a15 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:16:23 +0000 Subject: [PATCH 03/22] Raise the KrylovKit compat floor to 0.10 LinearSolve 3.27 through 5 declares KrylovKit = "0.10" for its KrylovKit extension, and LinearSolve is always installed (NonlinearSolveFirstOrder 2.10 depends on it), so KrylovKit 0.9 cannot resolve and the Downgrade job would fail. Checked on Julia 1.10 with every dependency at its compat floor: KrylovKit 0.10.0 resolves next to LinearSolve 5.18.3, and the eigenmode solve and Q check run. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- Project.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index cb78e4a1..c41b23a7 100644 --- a/Project.toml +++ b/Project.toml @@ -37,7 +37,7 @@ Ferrite = "1.7" FerriteGmsh = "1.5" ForwardDiff = "1.4" Gmsh = "0.3" -KrylovKit = "0.9, 0.10" +KrylovKit = "0.10" LinearAlgebra = "1.10" ModelingToolkit = "11.34" LinearSolve = "5" From a17f68c93ef8bd9f3be5739b20745b2f01379cc6 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:21:40 +0000 Subject: [PATCH 04/22] Rank Maxwell eigenmodes by complex angular frequency distance The candidate stopping rule bounded |lambda - sigma| from the distance in Re(omega), which does not bound it when damping is large: with eps_r = 1 - 100i it stopped before the mode it should return. Modes are now ranked by |omega - omega_t| for the real target omega_t, for which |lambda - sigma| <= scale d (2 omega_t + d) holds for complex omega too; for a lossless model this is still the nearest eigenfrequency. The result is now sorted by Re(omega) rather than Re(lambda), which differ under heavy loss. Found in review. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 20 +++++++++++--------- test/Maxwell/eigen.jl | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 75da1012..07375676 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -81,15 +81,17 @@ end maxwell_eigenmodes(model::MaxwellModel; nev, target_frequency, krylovdim = max(30, 2nev + 10), tol = 1e-10, maxiter = 300, nullspace_tol = 1e-6) -The `nev` resonant modes of `model` with eigenfrequencies `Re(ω) / 2π` nearest `target_frequency` (Hz, real and -positive), sorted by frequency. Requires `using KrylovKit`. +The `nev` resonant modes of `model` whose complex angular frequencies `ω` are nearest `ωt = 2π target_frequency` +(`target_frequency` in Hz, real and positive), that is with the least `|ω - ωt|`, sorted by `Re(ω)`. For a +lossless model this is the nearest eigenfrequency; with loss a strongly damped mode counts as further from the +target than its real frequency alone suggests. Requires `using KrylovKit`. Source-free modes satisfy `Kc u = λ (Mε' + i Mε'') u` (see [`MaxwellModel`](@ref)) on the dofs off the PEC facets, which are eliminated rather than constrained, with `λ = ω² μ0 ε0 L²`. The problem is solved by shift-invert Arnoldi: one sparse LU of `Kc - σ Mε` at `σ` from `target_frequency` (complex when a material is lossy), with KrylovKit's `eigsolve` on `u ↦ (Kc - σ Mε) \\ (Mε u)`. Shift-invert ranks modes by distance in -`λ ∝ ω²`, so it computes at least `2nev` candidates, enough to contain the `nev` nearest in frequency, and -returns those; `krylovdim` grows with the candidate count. +`λ ∝ ω²`, so it computes at least `2nev` candidates, enough to contain the `nev` nearest in `ω`, and returns +those; `krylovdim` grows with the candidate count. Edge elements carry the gradients of the nodal hat functions as an exact `λ = 0` null space (one mode per node off the PEC facets, less one per connected part of the mesh without PEC), which would swamp the shift-invert for any target below the lowest physical mode. Every @@ -134,9 +136,9 @@ function maxwell_eigenmodes( op(x) = project(F \ (M * x)) x0 = project(T.(sin.(1.3 .* (1:length(free)) .^ 1.1))) - # Shift-invert finds the modes nearest σ in λ ∝ ω², which favours those below the target. Every mode within - # frequency distance d of the target lies within λ distance (2ωt + d) d scale of σ, so the candidates (all - # modes within the largest λ distance R found) hold the nev nearest in frequency once R reaches that bound. + # Shift-invert finds the modes nearest σ in λ ∝ ω², which favours those below the target. Every mode with + # |ω - ωt| ≤ d has |λ - σ| = scale |ω - ωt| |ω + ωt| ≤ scale d (2ωt + d), complex ω included, so the + # candidates (all modes within the largest λ distance found) hold the nev nearest in ω once it reaches that. ωt = 2π * target_frequency howmany = 2nev local λ, vecs, keep @@ -145,7 +147,7 @@ function maxwell_eigenmodes( λ = σ .+ 1 ./ θ lossy || (λ = real.(λ)) keep = findall(l -> abs(l) >= nullspace_tol * σ, λ) - dist = abs.(real.(sqrt.(complex.(λ[keep]) ./ scale)) .- ωt) + dist = abs.(sqrt.(complex.(λ[keep]) ./ scale) .- ωt) keep = keep[sortperm(dist)] length(keep) < nev && break d = sort(dist)[nev] @@ -155,7 +157,7 @@ function maxwell_eigenmodes( end length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" keep = keep[1:min(nev, end)] - keep = keep[sortperm(real.(λ[keep]))] + keep = keep[sortperm(real.(sqrt.(complex.(λ[keep]))))] omega = sqrt.(complex.(λ[keep])) ./ sqrt(scale) Q = [iszero(imag(ω)) ? Inf : real(ω) / (2imag(ω)) for ω in omega] diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index e78c323e..7c157452 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -60,6 +60,24 @@ end @test maxwell_eigenmodes(box_model(3); nev = 1, target_frequency = 0.98).frequency[1] ≈ EXACT[2] rtol = 0.01 end +@testset "lossy: nearest in complex ω, and the candidate bound holds" begin + # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with + # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first + # two ahead of the third in λ, so a bound on Re ω alone would stop too early. + grid = box_grid(2) + addcellset!(grid, "fill", x -> true) + model = MaxwellModel( + grid; materials = Dict("fill" => MaxwellMaterial(; eps_r = 1 - 100im)), pec = CUBE_FACES, + eps0 = 1.0, mu0 = 1.0, + ) + ωt = 2π * 0.085405 + one = maxwell_eigenmodes(model; nev = 1, target_frequency = 0.085405) + six = maxwell_eigenmodes(model; nev = 6, target_frequency = 0.085405) + @test issorted(six.frequency) + @test one.omega[1] ≈ six.omega[argmin(abs.(six.omega .- ωt))] + @test one.omega[1] ≈ 2π * EXACT[1] / sqrt(1 - 100im) rtol = 0.02 +end + @testset "no PEC: the constant potential is removed from the gradient basis" begin # Natural (magnetic-wall) conditions everywhere: the dual of the PEC cube, lowest at √2/2 (x3). single = MaxwellModel(generate_grid(Tetrahedron, (1, 1, 1)); eps0 = 1.0, mu0 = 1.0) From 56e5dc9c9cdac6af8bb4598a9ac9424efec58707 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:38:06 +0000 Subject: [PATCH 05/22] Handle degenerate sizes in Maxwell eigenmodes A model whose nodes all lie on PEC facets has no gradient basis, and lu(G'MG) of a zero-column G threw; the projection is now the identity there. A problem smaller than the Krylov dimension (KrylovKit would otherwise get krylovdim > n) is solved densely, dropping the projected-out gradients at theta = 0. nev < 1, nev above the number of modes outside the gradient null space, a model with no free edge dof and a non-finite target now raise clear ArgumentErrors, and the eigenvector normalisation falls back to the unit dof norm where Re(eps_r) <= 0 makes the weighted norm non-positive. Found in review. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/FiniteElementMethod.jl | 2 +- src/maxwell/eigen.jl | 55 +++++++++++++++++++++++++++----------- test/Maxwell/eigen.jl | 20 ++++++++++++++ 3 files changed, 61 insertions(+), 16 deletions(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 8bce5214..7c1c85bc 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: dot, lu, mul!, norm +using LinearAlgebra: dot, eigen, lu, mul!, norm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 07375676..eace6dbc 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -10,6 +10,13 @@ function _eigsolve(solver, op, x0, nev; kwargs...) throw(ArgumentError("maxwell_eigenmodes needs an eigensolver: run `using KrylovKit` first")) end +# Every eigenpair of the linear map `op` on vectors of length `m` and type `T`, from its dense matrix: for problems +# too small for a Krylov space of the requested dimension. +function _dense_eigs(op, m, T) + E = eigen(reduce(hcat, [op(setindex!(zeros(T, m), one(T), j)) for j in 1:m])) + return E.values, collect.(eachcol(E.vectors)) +end + # The discrete gradient: column j holds the Nédélec dofs of the gradient of the j-th nodal hat function (each # entry is ±1 or 0, with Ferrite's edge orientation), together with the Lagrange DofHandler of the columns. function _discrete_gradient(model) @@ -77,6 +84,13 @@ function _potential_dofs(dhn, grid, pec) return findall(!, drop) end +# x ↦ x - G (GᵀMG)⁻¹ GᵀM x, with transposes, not adjoints: M is complex symmetric when lossy. +function _gradient_projection(G, M) + GtM = sparse(transpose(G) * M) + FG = lu(GtM * G) + return x -> x - G * (FG \ (GtM * x)) +end + """ maxwell_eigenmodes(model::MaxwellModel; nev, target_frequency, krylovdim = max(30, 2nev + 10), tol = 1e-10, maxiter = 300, nullspace_tol = 1e-6) @@ -102,15 +116,19 @@ further disconnected PEC body) are dropped as well. Returns `(; frequency, Q, omega, modes)`: `omega` the complex angular frequencies `ω = √λ / (L √(μ0 ε0))`, `frequency = Re(ω) / 2π` in Hz, `Q = Re(ω) / (2 Im(ω))` (`Inf` for a lossless model; with `exp(+iωt)` a passive mode has `Im(ω) > 0` and decays as `exp(-Im(ω) t)`), and `modes` the [`MaxwellSolution`](@ref)s at -`Re(ω)`, with zeros on the PEC dofs, scaled to `∫ Re(εr) |E|² = 1` over the mesh (mesh units) with the -largest dof real. Conductivity and terms added with [`FiniteElementMethod.add_term!`](@ref) make the problem -nonlinear in `ω` and are rejected. +`Re(ω)`, with zeros on the PEC dofs, scaled to `∫ Re(εr) |E|² = 1` over the mesh (mesh units; to a unit dof +norm where that integral is not positive) with the largest dof real. Conductivity and terms added with +[`FiniteElementMethod.add_term!`](@ref) make the problem nonlinear in `ω` and are rejected. A problem too +small for a Krylov space of dimension `krylovdim` is solved densely, and `nev` may not exceed the number of +modes outside the gradient null space. """ function maxwell_eigenmodes( model::MaxwellModel; nev::Integer, target_frequency::Real, krylovdim::Integer = max(30, 2nev + 10), tol::Real = 1.0e-10, maxiter::Integer = 300, nullspace_tol::Real = 1.0e-6 ) - target_frequency > 0 || throw(ArgumentError("target_frequency must be positive, got $target_frequency")) + nev >= 1 || throw(ArgumentError("nev must be positive, got $nev")) + 0 < target_frequency < Inf || + throw(ArgumentError("target_frequency must be positive and finite, got $target_frequency")) all(iszero, nonzeros(model.blocks.sigma)) || throw(ArgumentError("maxwell_eigenmodes does not support conductivity (the problem is quadratic in ω); model it as Im(eps_r)")) length(model.terms) == 4 || @@ -121,18 +139,20 @@ function maxwell_eigenmodes( T = lossy ? ComplexF64 : Float64 n = Ferrite.ndofs(model.dh) free = setdiff(1:n, _pec_dofs(model.dh, model.grid, model.pec)) + isempty(free) && throw(ArgumentError("every edge dof of the model is on a PEC facet, so it has no modes")) K = blocks.curlcurl[free, free] M = lossy ? blocks.eps_real[free, free] + im * blocks.eps_imag[free, free] : blocks.eps_real[free, free] σ = scale * (2π * target_frequency)^2 F = lu(K - σ * M) - # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them - # with x ↦ x - G (GᵀMG)⁻¹ GᵀM x (transposes, not adjoints: M is complex symmetric when lossy). + # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them. Gfull, dhn = _discrete_gradient(model) G = Gfull[free, _potential_dofs(dhn, model.grid, model.pec)] - GtM = sparse(transpose(G) * M) - FG = lu(GtM * G) - project(x) = x - G * (FG \ (GtM * x)) + nphysical = length(free) - size(G, 2) # the dimension of the discretely divergence-free fields + nev <= nphysical || + throw(ArgumentError("nev = $nev exceeds the $nphysical modes of the model outside the gradient null space")) + # With every node on a PEC facet no gradient lies in the free dofs, and there is nothing to project out. + project = size(G, 2) == 0 ? identity : _gradient_projection(G, M) op(x) = project(F \ (M * x)) x0 = project(T.(sin.(1.3 .* (1:length(free)) .^ 1.1))) @@ -143,17 +163,21 @@ function maxwell_eigenmodes( howmany = 2nev local λ, vecs, keep while true - θ, vecs = _eigsolve(KrylovKitEigensolver(), op, x0, howmany; krylovdim = max(krylovdim, howmany + 20), tol, maxiter) + dim = max(krylovdim, howmany + 20) + dense = dim >= length(free) + θ, vecs = dense ? _dense_eigs(op, length(free), T) : + _eigsolve(KrylovKitEigensolver(), op, x0, howmany; krylovdim = dim, tol, maxiter) λ = σ .+ 1 ./ θ lossy || (λ = real.(λ)) - keep = findall(l -> abs(l) >= nullspace_tol * σ, λ) + # The dense spectrum also holds the projected-out gradients, at θ = 0 up to roundoff. + θmax = maximum(abs, θ) + keep = findall(j -> abs(θ[j]) > 1.0e-8 * θmax && abs(λ[j]) >= nullspace_tol * σ, eachindex(λ)) dist = abs.(sqrt.(complex.(λ[keep]) ./ scale) .- ωt) keep = keep[sortperm(dist)] length(keep) < nev && break d = sort(dist)[nev] - maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale && break - howmany >= length(free) && break - howmany = min(2howmany, length(free)) + (dense || maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale) && break + howmany = 2howmany end length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" keep = keep[1:min(nev, end)] @@ -164,7 +188,8 @@ function maxwell_eigenmodes( Mr = blocks.eps_real[free, free] modes = map(keep, omega) do j, ω v = ComplexF64.(vecs[j]) - v ./= sqrt(real(dot(v, Mr * v))) + w = real(dot(v, Mr * v)) + v ./= w > 0 ? sqrt(w) : norm(v) # Re(εr) ≤ 0 somewhere can make the weighted norm vanish v .*= conj(sign(v[argmax(abs.(v))])) u = zeros(ComplexF64, n) u[free] = v diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 7c157452..fab554dd 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -138,6 +138,26 @@ end @test round(FiniteElementMethod.C0 / 2 * sqrt(1 / 0.1^2 + 1 / 0.075^2) / 1.0e9; digits = 3) == 2.498 end +@testset "degenerate sizes: no gradient basis, dense fallback, too many modes" begin + # One PEC hexahedron of six tets: every node is on the PEC boundary, the body diagonal is the one free edge. + cube = MaxwellModel(generate_grid(Tetrahedron, (1, 1, 1)); pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + f = maxwell_eigenmodes(cube; nev = 1, target_frequency = 0.4).frequency + @test length(f) == 1 && isfinite(f[1]) && f[1] > 0 + @test_throws "exceeds the 1 modes" maxwell_eigenmodes(cube; nev = 2, target_frequency = 0.4) + # A problem smaller than the Krylov dimension is solved densely, and agrees with the Krylov path. + small = box_model(1) + dense = maxwell_eigenmodes(small; nev = 4, target_frequency = 0.9, krylovdim = 10_000) + krylov = maxwell_eigenmodes(small; nev = 4, target_frequency = 0.9, krylovdim = 30) + @test dense.frequency ≈ krylov.frequency rtol = 1.0e-8 + # A single tetrahedron with every face PEC has no free dof at all. + nodes = Node.([Vec(0.0, 0.0, 0.0), Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0), Vec(0.0, 0.0, 1.0)]) + tet = Grid([Tetrahedron((1, 2, 3, 4))], nodes) + addfacetset!(tet, "all", x -> true) + @test_throws "no modes" maxwell_eigenmodes(MaxwellModel(tet; pec = ["all"]); nev = 1, target_frequency = 1.0) + @test_throws "nev must be positive" maxwell_eigenmodes(cube; nev = 0, target_frequency = 0.4) + @test_throws "finite" maxwell_eigenmodes(cube; nev = 1, target_frequency = Inf) +end + @testset "argument checks" begin model = box_model(2) @test_throws ArgumentError maxwell_eigenmodes(model; nev = 2, target_frequency = 0.0) From 5f5e6c2a79b18efccff3410a024061f761c1133c Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:46:41 +0000 Subject: [PATCH 06/22] Identify projected gradient modes by their eigenvectors The dense path dropped eigenvalues with |theta| below 1e-8 of the largest, which also dropped physical modes when the target sat on a resonance and made one theta huge. The projected-out gradients are now recognised structurally: their eigenvectors lie in the range of G, which the projection annihilates, while it leaves every other eigenvector unchanged. Found in review. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 7 ++++--- test/Maxwell/eigen.jl | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index eace6dbc..5b392e0f 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -169,9 +169,10 @@ function maxwell_eigenmodes( _eigsolve(KrylovKitEigensolver(), op, x0, howmany; krylovdim = dim, tol, maxiter) λ = σ .+ 1 ./ θ lossy || (λ = real.(λ)) - # The dense spectrum also holds the projected-out gradients, at θ = 0 up to roundoff. - θmax = maximum(abs, θ) - keep = findall(j -> abs(θ[j]) > 1.0e-8 * θmax && abs(λ[j]) >= nullspace_tol * σ, eachindex(λ)) + # The dense spectrum also holds the projected-out gradients (θ = 0): their eigenvectors lie in the range of + # G, which the projection annihilates, while every other eigenvector is left unchanged by it. + physical(v) = norm(project(v)) > norm(v) / 2 + keep = findall(j -> physical(vecs[j]) && abs(λ[j]) >= nullspace_tol * σ, eachindex(λ)) dist = abs.(sqrt.(complex.(λ[keep]) ./ scale) .- ωt) keep = keep[sortperm(dist)] length(keep) < nev && break diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index fab554dd..2eca338d 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -149,6 +149,14 @@ end dense = maxwell_eigenmodes(small; nev = 4, target_frequency = 0.9, krylovdim = 10_000) krylov = maxwell_eigenmodes(small; nev = 4, target_frequency = 0.9, krylovdim = 30) @test dense.frequency ≈ krylov.frequency rtol = 1.0e-8 + # A target on a resonance makes one θ huge; the gradient modes are still told apart by their eigenvectors. + cube2 = MaxwellModel(generate_grid(Tetrahedron, (2, 2, 2)); pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + f0 = maxwell_eigenmodes(cube2; nev = 3, target_frequency = 0.3, krylovdim = 10_000).frequency + ft = f0[1] * (1 + 1.0e-10) + near = maxwell_eigenmodes(cube2; nev = 3, target_frequency = ft, krylovdim = 10_000).frequency + @test length(near) == 3 + @test near ≈ maxwell_eigenmodes(cube2; nev = 3, target_frequency = ft, krylovdim = 30).frequency rtol = 1.0e-8 + @test near[1] ≈ f0[1] rtol = 1.0e-10 # A single tetrahedron with every face PEC has no free dof at all. nodes = Node.([Vec(0.0, 0.0, 0.0), Vec(1.0, 0.0, 0.0), Vec(0.0, 1.0, 0.0), Vec(0.0, 0.0, 1.0)]) tet = Grid([Tetrahedron((1, 2, 3, 4))], nodes) From 7b5b914aca7dcaea7307ac897f98068b3e3c6050 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 21:20:05 +0000 Subject: [PATCH 07/22] Make the eigenmode null-space cutoff independent of a high target and widen the search past dropped modes The cutoff |lambda| >= nullspace_tol * sigma discarded the lowest physical modes once the target frequency was high enough (a 0.83 Hz mode against a 1000 Hz target), and the candidate search stopped as soon as the filter left fewer than nev of them. The cutoff is now relative to min(sigma, ||K||_1/||M||_1), and the candidate count doubles until the dense solve if fewer than nev survive. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/FiniteElementMethod.jl | 2 +- src/maxwell/eigen.jl | 15 +++++++++++---- test/Maxwell/eigen.jl | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 9b6d5153..c5a19d80 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: dot, eigen, lu, mul!, norm +using LinearAlgebra: dot, eigen, lu, mul!, norm, opnorm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 5b392e0f..9f363438 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -110,8 +110,8 @@ those; `krylovdim` grows with the candidate count. Edge elements carry the gradients of the nodal hat functions as an exact `λ = 0` null space (one mode per node off the PEC facets, less one per connected part of the mesh without PEC), which would swamp the shift-invert for any target below the lowest physical mode. Every Krylov vector is therefore projected, along those gradients, onto the discretely divergence-free fields, so the -null space never enters; eigenvalues with `|λ| < nullspace_tol |σ|` (such as the one constant mode of each -further disconnected PEC body) are dropped as well. +null space never enters; eigenvalues with `|λ| < nullspace_tol min(σ, ‖Kc‖₁/‖Mε‖₁)` (such as the one constant mode of +each further disconnected PEC body) are dropped as well, and the search widens until `nev` modes survive. Returns `(; frequency, Q, omega, modes)`: `omega` the complex angular frequencies `ω = √λ / (L √(μ0 ε0))`, `frequency = Re(ω) / 2π` in Hz, `Q = Re(ω) / (2 Im(ω))` (`Inf` for a lossless model; with `exp(+iωt)` a passive @@ -144,6 +144,9 @@ function maxwell_eigenmodes( M = lossy ? blocks.eps_real[free, free] + im * blocks.eps_imag[free, free] : blocks.eps_real[free, free] σ = scale * (2π * target_frequency)^2 F = lu(K - σ * M) + # The cutoff for the null space is relative to the spectrum of the model, ‖K‖/‖M‖ of the order of its largest λ, + # and to σ when that is smaller; relative to σ alone, a high target would discard the lowest physical modes. + λ_null = nullspace_tol * min(σ, opnorm(K, 1) / opnorm(M, 1)) # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them. Gfull, dhn = _discrete_gradient(model) @@ -172,10 +175,14 @@ function maxwell_eigenmodes( # The dense spectrum also holds the projected-out gradients (θ = 0): their eigenvectors lie in the range of # G, which the projection annihilates, while every other eigenvector is left unchanged by it. physical(v) = norm(project(v)) > norm(v) / 2 - keep = findall(j -> physical(vecs[j]) && abs(λ[j]) >= nullspace_tol * σ, eachindex(λ)) + keep = findall(j -> physical(vecs[j]) && abs(λ[j]) >= λ_null, eachindex(λ)) dist = abs.(sqrt.(complex.(λ[keep]) ./ scale) .- ωt) keep = keep[sortperm(dist)] - length(keep) < nev && break + if length(keep) < nev + dense && break + howmany = 2howmany # the filter took too many of the candidates, so look further out + continue + end d = sort(dist)[nev] (dense || maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale) && break howmany = 2howmany diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 2eca338d..376a61c4 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -60,6 +60,22 @@ end @test maxwell_eigenmodes(box_model(3); nev = 1, target_frequency = 0.98).frequency[1] ≈ EXACT[2] rtol = 0.01 end +@testset "null-space cutoff: not relative to a high target, and the search widens past what it drops" begin + # box_model(1) has 93 modes outside the gradient null space; the lowest is 0.83, below 1e-3 of the target. + small = box_model(1) + high = maxwell_eigenmodes(small; nev = 93, target_frequency = 1000.0) + @test length(high.frequency) == 93 + @test high.frequency[1] ≈ maxwell_eigenmodes(small; nev = 1, target_frequency = 0.9).frequency[1] rtol = 1.0e-8 + # A cutoff of 12σ drops every mode below 1.39 Hz from a target of 0.4: the 2nev = 6 nearest candidates are all + # dropped, and the search must go on to find the next three rather than stop with fewer. + model = box_model(2) + krylov = maxwell_eigenmodes(model; nev = 3, target_frequency = 0.4, nullspace_tol = 12.0) + dense = maxwell_eigenmodes(model; nev = 3, target_frequency = 0.4, nullspace_tol = 12.0, krylovdim = 10_000) + @test length(krylov.frequency) == 3 + @test all(>(sqrt(12) * 0.4), krylov.frequency) + @test krylov.frequency ≈ dense.frequency rtol = 1.0e-8 +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From caff864e3b431fb2999f8d5a6105b36341c95726 Mon Sep 17 00:00:00 2001 From: t Date: Wed, 11 Nov 2026 22:55:51 +0000 Subject: [PATCH 08/22] Eigenmodes: reject static modes for low targets; survive a target on a resonance The null-space cutoff is now relative to the model's spectrum scale only, and a target below it is raised to it, so gradient modes are rejected for any target. A shift that makes the factorisation exactly singular is nudged by 1e-8 relative and retried. The high-cutoff test passes the same cutoff through a spectrum-relative nullspace_tol. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/FiniteElementMethod.jl | 2 +- src/maxwell/eigen.jl | 21 +++++++++++++++------ test/Maxwell/eigen.jl | 28 +++++++++++++++++++++++++--- 3 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index c5a19d80..12d3d661 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: dot, eigen, lu, mul!, norm, opnorm +using LinearAlgebra: SingularException, dot, eigen, lu, mul!, norm, opnorm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 9f363438..ba1f442f 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -110,7 +110,7 @@ those; `krylovdim` grows with the candidate count. Edge elements carry the gradients of the nodal hat functions as an exact `λ = 0` null space (one mode per node off the PEC facets, less one per connected part of the mesh without PEC), which would swamp the shift-invert for any target below the lowest physical mode. Every Krylov vector is therefore projected, along those gradients, onto the discretely divergence-free fields, so the -null space never enters; eigenvalues with `|λ| < nullspace_tol min(σ, ‖Kc‖₁/‖Mε‖₁)` (such as the one constant mode of +null space never enters; eigenvalues with `|λ| < nullspace_tol ‖Kc‖₁/‖Mε‖₁` (such as the one constant mode of each further disconnected PEC body) are dropped as well, and the search widens until `nev` modes survive. Returns `(; frequency, Q, omega, modes)`: `omega` the complex angular frequencies `ω = √λ / (L √(μ0 ε0))`, @@ -142,11 +142,21 @@ function maxwell_eigenmodes( isempty(free) && throw(ArgumentError("every edge dof of the model is on a PEC facet, so it has no modes")) K = blocks.curlcurl[free, free] M = lossy ? blocks.eps_real[free, free] + im * blocks.eps_imag[free, free] : blocks.eps_real[free, free] - σ = scale * (2π * target_frequency)^2 - F = lu(K - σ * M) # The cutoff for the null space is relative to the spectrum of the model, ‖K‖/‖M‖ of the order of its largest λ, - # and to σ when that is smaller; relative to σ alone, a high target would discard the lowest physical modes. - λ_null = nullspace_tol * min(σ, opnorm(K, 1) / opnorm(M, 1)) + # not to the target: relative to a high target it would discard the lowest physical modes, and relative to a + # low one it would admit the static modes, whose roundoff λ is far above it. A target below the cutoff is + # raised to it, which also keeps `K - σ M` from being numerically singular; it then has the same nearest modes. + λ_null = nullspace_tol * opnorm(K, 1) / opnorm(M, 1) + ωt = max(2π * target_frequency, sqrt(λ_null / scale)) + σ = scale * ωt^2 + # A shift exactly on a discrete eigenvalue makes the factorisation singular; nudge it off. + F = try + lu(K - σ * M) + catch err + err isa SingularException || rethrow() + σ *= 1 + 1.0e-8 + lu(K - σ * M) + end # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them. Gfull, dhn = _discrete_gradient(model) @@ -162,7 +172,6 @@ function maxwell_eigenmodes( # Shift-invert finds the modes nearest σ in λ ∝ ω², which favours those below the target. Every mode with # |ω - ωt| ≤ d has |λ - σ| = scale |ω - ωt| |ω + ωt| ≤ scale d (2ωt + d), complex ω included, so the # candidates (all modes within the largest λ distance found) hold the nev nearest in ω once it reaches that. - ωt = 2π * target_frequency howmany = 2nev local λ, vecs, keep while true diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 376a61c4..77237e13 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -66,16 +66,38 @@ end high = maxwell_eigenmodes(small; nev = 93, target_frequency = 1000.0) @test length(high.frequency) == 93 @test high.frequency[1] ≈ maxwell_eigenmodes(small; nev = 1, target_frequency = 0.9).frequency[1] rtol = 1.0e-8 - # A cutoff of 12σ drops every mode below 1.39 Hz from a target of 0.4: the 2nev = 6 nearest candidates are all + # The cutoff is relative to the spectrum scale ‖K‖₁/‖M‖₁ = 1412.4 of this model; nullspace_tol = 0.0537 makes it + # 75.85 = 12σ of a target of 0.4, which drops every mode below 1.39 Hz: the 2nev = 6 nearest candidates are all # dropped, and the search must go on to find the next three rather than stop with fewer. model = box_model(2) - krylov = maxwell_eigenmodes(model; nev = 3, target_frequency = 0.4, nullspace_tol = 12.0) - dense = maxwell_eigenmodes(model; nev = 3, target_frequency = 0.4, nullspace_tol = 12.0, krylovdim = 10_000) + krylov = maxwell_eigenmodes(model; nev = 3, target_frequency = 0.4, nullspace_tol = 0.0537) + dense = maxwell_eigenmodes(model; nev = 3, target_frequency = 0.4, nullspace_tol = 0.0537, krylovdim = 10_000) @test length(krylov.frequency) == 3 @test all(>(sqrt(12) * 0.4), krylov.frequency) @test krylov.frequency ≈ dense.frequency rtol = 1.0e-8 end +@testset "null-space cutoff: static modes are rejected for a low target too" begin + grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + model = MaxwellModel(grid; pec = ["left", "right"], eps0 = 1.0, mu0 = 1.0) + # First three nonzero eigenfrequencies of the generalised problem K u = λ M u on the free dofs. + truth = [0.4695153184, 0.4907674018, 0.6775122733] + krylov = maxwell_eigenmodes(model; nev = 3, target_frequency = 1.0e-5) + dense = maxwell_eigenmodes(model; nev = 3, target_frequency = 1.0e-7, krylovdim = 10_000) + @test krylov.frequency ≈ truth rtol = 1.0e-8 + @test dense.frequency ≈ truth rtol = 1.0e-8 +end + +@testset "a target exactly on a discrete resonance" begin + # One free edge dof with K / M = 20 = mu0 eps0 ω², so the shifted matrix is exactly [0.0]. + model = MaxwellModel( + generate_grid(Tetrahedron, (1, 1, 1), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)); + pec = CUBE_FACES, eps0 = 20.0, mu0 = 1.0 + ) + modes = maxwell_eigenmodes(model; nev = 1, target_frequency = 1 / (2π)) + @test modes.frequency[1] ≈ 1 / (2π) rtol = 1.0e-6 +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From 4445f190b2173d3c197afce4556cf5ad534057e6 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 02:11:31 +0000 Subject: [PATCH 09/22] Eigenmodes: warn about strongly contrasting materials The global null-space cutoff and the shifted solve degrade with high material contrast (reproduced: mu_r = 1e-12 in half of a cavity returns modes near 6.7e5 where the lowest physical one is 0.75). No small robust fix exists, so a warning above a contrast of 1e6 and a docstring note. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 13 +++++++++++++ test/Maxwell/eigen.jl | 8 ++++++++ 2 files changed, 21 insertions(+) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index ba1f442f..6a7368ff 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -91,6 +91,12 @@ function _gradient_projection(G, M) return x -> x - G * (FG \ (GtM * x)) end +# The largest ratio between the εr (real part) or μr values of the cells. +function _material_contrast(materials) + spread(values) = maximum(values) / minimum(values) + return max(spread(abs.(real.(getfield.(materials, :eps_r)))), spread(getfield.(materials, :mu_r))) +end + """ maxwell_eigenmodes(model::MaxwellModel; nev, target_frequency, krylovdim = max(30, 2nev + 10), tol = 1e-10, maxiter = 300, nullspace_tol = 1e-6) @@ -113,6 +119,10 @@ Krylov vector is therefore projected, along those gradients, onto the discretely null space never enters; eigenvalues with `|λ| < nullspace_tol ‖Kc‖₁/‖Mε‖₁` (such as the one constant mode of each further disconnected PEC body) are dropped as well, and the search widens until `nev` modes survive. +The cutoff is a property of the whole model, and the shifted solve is ill-conditioned with it: where `εr` or `μr` +differ by more than a factor 1e6 between cells (a warning says so), `‖Kc‖₁/‖Mε‖₁` can exceed the lowest physical +`λ` by many orders and the modes returned may be missing or inaccurate. This limitation is not removed. + Returns `(; frequency, Q, omega, modes)`: `omega` the complex angular frequencies `ω = √λ / (L √(μ0 ε0))`, `frequency = Re(ω) / 2π` in Hz, `Q = Re(ω) / (2 Im(ω))` (`Inf` for a lossless model; with `exp(+iωt)` a passive mode has `Im(ω) > 0` and decays as `exp(-Im(ω) t)`), and `modes` the [`MaxwellSolution`](@ref)s at @@ -147,6 +157,9 @@ function maxwell_eigenmodes( # low one it would admit the static modes, whose roundoff λ is far above it. A target below the cutoff is # raised to it, which also keeps `K - σ M` from being numerically singular; it then has the same nearest modes. λ_null = nullspace_tol * opnorm(K, 1) / opnorm(M, 1) + # Both the cutoff and the conditioning of the shifted solve follow the spread of the material coefficients. + contrast = _material_contrast(model.materials) + contrast > 1.0e6 && @warn "maxwell_eigenmodes: the materials of the model differ by a factor $contrast in εr or μr; the null-space cutoff $λ_null then exceeds low physical modes and the shift-invert is ill-conditioned, so modes may be missing or inaccurate (see the nullspace_tol keyword)" ωt = max(2π * target_frequency, sqrt(λ_null / scale)) σ = scale * ωt^2 # A shift exactly on a discrete eigenvalue makes the factorisation singular; nudge it off. diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 77237e13..ed2b8125 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -98,6 +98,14 @@ end @test modes.frequency[1] ≈ 1 / (2π) rtol = 1.0e-6 end +@testset "strongly contrasting materials are warned about" begin + grid = unit_cube(3) + addcellset!(grid, "left", x -> x[1] <= 0.5) + model = MaxwellModel(grid; materials = Dict("left" => MaxwellMaterial(; mu_r = 1.0e-12)), pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + @test_logs (:warn, r"differ by a factor 1\.0e12") match_mode = :any maxwell_eigenmodes(model; nev = 1, target_frequency = 0.5) + @test_logs min_level = Base.CoreLogging.Warn maxwell_eigenmodes(box_model(2); nev = 1, target_frequency = 1.0) +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From 86187479775f70b6ddaf5512809644b633940817 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:25:56 +0000 Subject: [PATCH 10/22] Eigenmodes: classify static modes by precision, not by the shift floor The null-space cutoff doubled as the shift floor and was 1e-6 of the spectrum scale, so a model with strongly contrasting materials silently lost resolved physical modes below it. Static modes are now classified against sqrt(eps) of the spectrum scale (nullspace_tol overrides it), the shift keeps its own floor, and modes are ranked by distance from the requested target rather than the raised shift. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 45 ++++++++++++++++++++++++++----------------- test/Maxwell/eigen.jl | 17 ++++++++++++++++ 2 files changed, 44 insertions(+), 18 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 6a7368ff..8b69358e 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -99,7 +99,7 @@ end """ maxwell_eigenmodes(model::MaxwellModel; nev, target_frequency, krylovdim = max(30, 2nev + 10), - tol = 1e-10, maxiter = 300, nullspace_tol = 1e-6) + tol = 1e-10, maxiter = 300, nullspace_tol = nothing) The `nev` resonant modes of `model` whose complex angular frequencies `ω` are nearest `ωt = 2π target_frequency` (`target_frequency` in Hz, real and positive), that is with the least `|ω - ωt|`, sorted by `Re(ω)`. For a @@ -117,11 +117,14 @@ Edge elements carry the gradients of the nodal hat functions as an exact `λ = 0 off the PEC facets, less one per connected part of the mesh without PEC), which would swamp the shift-invert for any target below the lowest physical mode. Every Krylov vector is therefore projected, along those gradients, onto the discretely divergence-free fields, so the null space never enters; eigenvalues with `|λ| < nullspace_tol ‖Kc‖₁/‖Mε‖₁` (such as the one constant mode of -each further disconnected PEC body) are dropped as well, and the search widens until `nev` modes survive. +each further disconnected PEC body) are dropped as well, and the search widens until `nev` modes survive. By default +`nullspace_tol = √eps(Float64)`, the relative precision to which an eigenvalue of the spectrum scale `‖Kc‖₁/‖Mε‖₁` +can be told from zero, so every resolved physical mode is kept; a larger value discards modes below it. -The cutoff is a property of the whole model, and the shifted solve is ill-conditioned with it: where `εr` or `μr` -differ by more than a factor 1e6 between cells (a warning says so), `‖Kc‖₁/‖Mε‖₁` can exceed the lowest physical -`λ` by many orders and the modes returned may be missing or inaccurate. This limitation is not removed. +The shift `σ` is raised to at least `1e-6 ‖Kc‖₁/‖Mε‖₁`, which keeps `Kc - σ Mε` from being numerically singular; the +modes are still ranked by distance from the target itself. Where `εr` or `μr` differ by more than a factor 1e6 between cells, the shifted +solve is ill-conditioned and the modes returned may be inaccurate; a warning says so, and also when an explicit +`nullspace_tol` puts the cutoff above the target. Returns `(; frequency, Q, omega, modes)`: `omega` the complex angular frequencies `ω = √λ / (L √(μ0 ε0))`, `frequency = Re(ω) / 2π` in Hz, `Q = Re(ω) / (2 Im(ω))` (`Inf` for a lossless model; with `exp(+iωt)` a passive @@ -134,7 +137,7 @@ modes outside the gradient null space. """ function maxwell_eigenmodes( model::MaxwellModel; nev::Integer, target_frequency::Real, krylovdim::Integer = max(30, 2nev + 10), - tol::Real = 1.0e-10, maxiter::Integer = 300, nullspace_tol::Real = 1.0e-6 + tol::Real = 1.0e-10, maxiter::Integer = 300, nullspace_tol::Union{Nothing, Real} = nothing ) nev >= 1 || throw(ArgumentError("nev must be positive, got $nev")) 0 < target_frequency < Inf || @@ -152,16 +155,21 @@ function maxwell_eigenmodes( isempty(free) && throw(ArgumentError("every edge dof of the model is on a PEC facet, so it has no modes")) K = blocks.curlcurl[free, free] M = lossy ? blocks.eps_real[free, free] + im * blocks.eps_imag[free, free] : blocks.eps_real[free, free] - # The cutoff for the null space is relative to the spectrum of the model, ‖K‖/‖M‖ of the order of its largest λ, - # not to the target: relative to a high target it would discard the lowest physical modes, and relative to a - # low one it would admit the static modes, whose roundoff λ is far above it. A target below the cutoff is - # raised to it, which also keeps `K - σ M` from being numerically singular; it then has the same nearest modes. - λ_null = nullspace_tol * opnorm(K, 1) / opnorm(M, 1) - # Both the cutoff and the conditioning of the shifted solve follow the spread of the material coefficients. + # Classifying a mode as static is a question of precision: its λ is zero up to roundoff in the spectrum scale + # ‖K‖/‖M‖, so the cutoff is relative to that scale, not to the target (a high target would discard the lowest + # physical modes) and not to a conditioning bound (the shift floor below, which is far above the lowest modes + # of a model with strongly contrasting materials). + spectrum_scale = opnorm(K, 1) / opnorm(M, 1) + λ_null = something(nullspace_tol, sqrt(eps())) * spectrum_scale + # A shift near zero makes K - σ M numerically singular, because K itself is: raise a low target to a floor. It + # has the same nearest modes. + λ_shift = 1.0e-6 * spectrum_scale contrast = _material_contrast(model.materials) - contrast > 1.0e6 && @warn "maxwell_eigenmodes: the materials of the model differ by a factor $contrast in εr or μr; the null-space cutoff $λ_null then exceeds low physical modes and the shift-invert is ill-conditioned, so modes may be missing or inaccurate (see the nullspace_tol keyword)" - ωt = max(2π * target_frequency, sqrt(λ_null / scale)) - σ = scale * ωt^2 + contrast > 1.0e6 && @warn "maxwell_eigenmodes: the materials of the model differ by a factor $contrast in εr or μr, so the shift-invert is ill-conditioned and modes may be inaccurate" + nullspace_tol !== nothing && λ_null > scale * (2π * target_frequency)^2 && @warn "maxwell_eigenmodes: nullspace_tol puts the null-space cutoff $λ_null above the target, so the modes there are discarded" + ωt = 2π * target_frequency + σ = max(scale * ωt^2, λ_shift) + shift_offset = σ - scale * ωt^2 # A shift exactly on a discrete eigenvalue makes the factorisation singular; nudge it off. F = try lu(K - σ * M) @@ -183,8 +191,9 @@ function maxwell_eigenmodes( x0 = project(T.(sin.(1.3 .* (1:length(free)) .^ 1.1))) # Shift-invert finds the modes nearest σ in λ ∝ ω², which favours those below the target. Every mode with - # |ω - ωt| ≤ d has |λ - σ| = scale |ω - ωt| |ω + ωt| ≤ scale d (2ωt + d), complex ω included, so the - # candidates (all modes within the largest λ distance found) hold the nev nearest in ω once it reaches that. + # |ω - ωt| ≤ d has |λ - σ| ≤ scale |ω - ωt| |ω + ωt| + |σ - scale ωt²| ≤ scale d (2ωt + d) + shift_offset, + # complex ω included, so the candidates (all modes within the largest λ distance found) hold the nev nearest + # in ω once it reaches that. howmany = 2nev local λ, vecs, keep while true @@ -206,7 +215,7 @@ function maxwell_eigenmodes( continue end d = sort(dist)[nev] - (dense || maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale) && break + (dense || maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale + shift_offset) && break howmany = 2howmany end length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index ed2b8125..2f43a618 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -106,6 +106,23 @@ end @test_logs min_level = Base.CoreLogging.Warn maxwell_eigenmodes(box_model(2); nev = 1, target_frequency = 1.0) end +@testset "physical modes below the material-warning cutoff are kept" begin + # mu_r = 5e-6 on half the cube puts ‖K‖₁/‖M‖₁ near 3.5e7, so a cutoff of 1e-6 of it (35.4) is above the first + # three physical eigenvalues, which are still resolved: the generalised eigenvalues are checked against a dense solve. + grid = unit_cube(3) + addcellset!(grid, "left", x -> x[1] <= 0.5) + model = MaxwellModel(grid; materials = Dict("left" => MaxwellMaterial(; mu_r = 5.0e-6)), pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + free = setdiff(1:ndofs(model.dh), FiniteElementMethod._pec_dofs(model.dh, model.grid, model.pec)) + λ = eigvals(Symmetric(Matrix(model.blocks.curlcurl[free, free])), Symmetric(Matrix(model.blocks.eps_real[free, free]))) + λ_physical = filter(>(1.0e4 * eps() * maximum(λ)), λ) + @test λ_physical[1:3] ≈ [22.48440197, 29.81579099, 32.07272248] rtol = 1.0e-7 + truth = sqrt(λ_physical[1]) / 2π + for kwargs in ((;), (; krylovdim = 10_000)) + found = maxwell_eigenmodes(model; nev = 1, target_frequency = 0.5, kwargs...) + @test found.frequency[1] ≈ truth rtol = 1.0e-8 + end +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From 39c4c297d3c9db9f3e951c0c9c69334d84a77c10 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:17:28 +0000 Subject: [PATCH 11/22] Tests: check the Lagrange facet node table through public shape values The comparison used an internal Ferrite function; a linear Lagrange basis function is nonzero on a facet exactly at the facet's nodes. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Maxwell/model.jl | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/test/Maxwell/model.jl b/test/Maxwell/model.jl index 98b56d13..52b5ab93 100644 --- a/test/Maxwell/model.jl +++ b/test/Maxwell/model.jl @@ -181,5 +181,16 @@ end end @testset "the linear Lagrange facet dofs are the facet nodes" begin - @test FiniteElementMethod._TET_FACET_NODES == Ferrite.dirichlet_facetdof_indices(Ferrite.Lagrange{RefTetrahedron, 1}()) + ip = Lagrange{RefTetrahedron, 1}() + fv = FacetValues(FacetQuadratureRule{RefTetrahedron}(2), ip) + grid = Grid([Tetrahedron((1, 2, 3, 4))], Node.([(0.1, 0.0, 0.0), (1.2, 0.2, 0.0), (0.0, 0.9, 0.1), (0.3, 0.2, 1.1)])) + dh = DofHandler(grid) + add!(dh, :u, ip) + close!(dh) + cell = first(CellIterator(dh)) + for lf in 1:4 + reinit!(fv, cell, lf) + nonzero = [j for j in 1:4 if any(abs(shape_value(fv, q, j)) > 1.0e-12 for q in 1:getnquadpoints(fv))] + @test Set(FiniteElementMethod._TET_FACET_NODES[lf]) == Set(nonzero) + end end From 7726ae02fbc5d808a79cdc8c3181c1418f524922 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:43:17 +0000 Subject: [PATCH 12/22] Eigenmodes: describe the static-mode cutoff as a heuristic At a material contrast of 1e7 a resolved physical mode can lie below the default cutoff; an explicit smaller nullspace_tol recovers it. The docstring and the comment no longer claim that every resolved mode is kept. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 8b69358e..95f688c6 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -119,7 +119,10 @@ Krylov vector is therefore projected, along those gradients, onto the discretely null space never enters; eigenvalues with `|λ| < nullspace_tol ‖Kc‖₁/‖Mε‖₁` (such as the one constant mode of each further disconnected PEC body) are dropped as well, and the search widens until `nev` modes survive. By default `nullspace_tol = √eps(Float64)`, the relative precision to which an eigenvalue of the spectrum scale `‖Kc‖₁/‖Mε‖₁` -can be told from zero, so every resolved physical mode is kept; a larger value discards modes below it. +can be told from zero. This cutoff is a heuristic: a physical mode below it is discarded although it is still +resolved, which happens when the spectrum scale exceeds the lowest mode by more than about `1/√eps`, as with strongly +contrasting materials (a warning says so). A smaller explicit `nullspace_tol`, down to the floating-point zero bound +of about `1e4 eps(Float64)`, recovers such modes; a larger value discards more. The shift `σ` is raised to at least `1e-6 ‖Kc‖₁/‖Mε‖₁`, which keeps `Kc - σ Mε` from being numerically singular; the modes are still ranked by distance from the target itself. Where `εr` or `μr` differ by more than a factor 1e6 between cells, the shifted @@ -158,7 +161,8 @@ function maxwell_eigenmodes( # Classifying a mode as static is a question of precision: its λ is zero up to roundoff in the spectrum scale # ‖K‖/‖M‖, so the cutoff is relative to that scale, not to the target (a high target would discard the lowest # physical modes) and not to a conditioning bound (the shift floor below, which is far above the lowest modes - # of a model with strongly contrasting materials). + # of a model with strongly contrasting materials). It is a heuristic: sqrt(eps) of the scale can still lie above + # a resolved mode, which a smaller explicit nullspace_tol recovers. spectrum_scale = opnorm(K, 1) / opnorm(M, 1) λ_null = something(nullspace_tol, sqrt(eps())) * spectrum_scale # A shift near zero makes K - σ M numerically singular, because K itself is: raise a low target to a floor. It From 28e5f3f463304c1346e587da4278fec98980ecb5 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 22:24:23 +0000 Subject: [PATCH 13/22] Eigenmodes: preserve the multiplicity of repeated eigenvalues A Krylov space from one starting vector holds one vector per distinct eigenvalue, so a repeated nearest eigenvalue could be reported once, with a farther mode in its place and tiny residuals. After the first pass the search is restarted from vectors M-orthogonal to everything found, until a restart finds nothing nearer than the current nev-th mode (at most nev restarts). Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 53 +++++++++++++++++++++++++++++++++++++++---- test/Maxwell/eigen.jl | 23 +++++++++++++++++++ 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 95f688c6..8f3d0ffe 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -91,6 +91,21 @@ function _gradient_projection(G, M) return x -> x - G * (FG \ (GtM * x)) end +# The columns of `vecs` made orthonormal in the bilinear form xᵀ M y (the eigenvectors of the complex symmetric +# pencil are orthogonal in it), skipping any that are already in the span. +function _orthonormal_basis(vecs, M) + basis = Vector{eltype(first(vecs))}[] + for v in vecs + w = copy(v) + for _ in 1:2, b in basis + w .-= b .* (transpose(b) * (M * w)) + end + s = transpose(w) * (M * w) + abs(s) > 1.0e-10 * abs(transpose(v) * (M * v)) && push!(basis, w ./ sqrt(s)) + end + return reduce(hcat, basis) +end + # The largest ratio between the εr (real part) or μr values of the cells. function _material_contrast(materials) spread(values) = maximum(values) / minimum(values) @@ -111,7 +126,11 @@ facets, which are eliminated rather than constrained, with `λ = ω² μ0 ε0 L shift-invert Arnoldi: one sparse LU of `Kc - σ Mε` at `σ` from `target_frequency` (complex when a material is lossy), with KrylovKit's `eigsolve` on `u ↦ (Kc - σ Mε) \\ (Mε u)`. Shift-invert ranks modes by distance in `λ ∝ ω²`, so it computes at least `2nev` candidates, enough to contain the `nev` nearest in `ω`, and returns -those; `krylovdim` grows with the candidate count. +those; `krylovdim` grows with the candidate count. A Krylov space from one starting vector holds one vector per +distinct eigenvalue, so repeated eigenvalues (such as those of disconnected or symmetric parts) would be found once; +after the first pass the search is therefore restarted from vectors M-orthogonal to everything found, until a restart +finds nothing nearer than the current `nev`-th mode (at most `nev` restarts), which preserves multiplicities. The +extra restart costs about one more Krylov solve with the same factorisation. Edge elements carry the gradients of the nodal hat functions as an exact `λ = 0` null space (one mode per node off the PEC facets, less one per connected part of the mesh without PEC), which would swamp the shift-invert for any target below the lowest physical mode. Every @@ -198,8 +217,11 @@ function maxwell_eigenmodes( # |ω - ωt| ≤ d has |λ - σ| ≤ scale |ω - ωt| |ω + ωt| + |σ - scale ωt²| ≤ scale d (2ωt + d) + shift_offset, # complex ω included, so the candidates (all modes within the largest λ distance found) hold the nev nearest # in ω once it reaches that. + # The dense spectrum also holds the projected-out gradients (θ = 0): their eigenvectors lie in the range of G, + # which the projection annihilates, while every other eigenvector is left unchanged by it. + physical(v) = norm(project(v)) > norm(v) / 2 howmany = 2nev - local λ, vecs, keep + local λ, vecs, keep, dense while true dim = max(krylovdim, howmany + 20) dense = dim >= length(free) @@ -207,9 +229,6 @@ function maxwell_eigenmodes( _eigsolve(KrylovKitEigensolver(), op, x0, howmany; krylovdim = dim, tol, maxiter) λ = σ .+ 1 ./ θ lossy || (λ = real.(λ)) - # The dense spectrum also holds the projected-out gradients (θ = 0): their eigenvectors lie in the range of - # G, which the projection annihilates, while every other eigenvector is left unchanged by it. - physical(v) = norm(project(v)) > norm(v) / 2 keep = findall(j -> physical(vecs[j]) && abs(λ[j]) >= λ_null, eachindex(λ)) dist = abs.(sqrt.(complex.(λ[keep]) ./ scale) .- ωt) keep = keep[sortperm(dist)] @@ -222,6 +241,30 @@ function maxwell_eigenmodes( (dense || maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale + shift_offset) && break howmany = 2howmany end + if !dense && length(keep) >= nev + # A Krylov space from one starting vector holds one vector per distinct eigenvalue, so a repeated eigenvalue + # may have been found once only. Restart from vectors M-orthogonal to everything found until a pass finds + # nothing nearer than the current nev-th mode: each pass can add one copy of a repeated eigenvalue. + pool_λ, pool_vecs = λ[keep], vecs[keep] + pool_dist = abs.(sqrt.(complex.(pool_λ) ./ scale) .- ωt) + for pass in 1:nev + d_nev = sort(pool_dist)[nev] + V = _orthonormal_basis(pool_vecs, M) + deflate(x) = x - V * (transpose(V) * (M * x)) + start = deflate(project(T.(cos.(2.399963 .* pass .* (1:length(free)) .^ 1.37 .+ pass)))) + θ, found = _eigsolve(KrylovKitEigensolver(), x -> deflate(op(x)), start, 2nev; krylovdim = max(krylovdim, 2nev + 20), tol, maxiter) + λ_found = σ .+ 1 ./ θ + lossy || (λ_found = real.(λ_found)) + new = findall(j -> isfinite(λ_found[j]) && physical(found[j]) && abs(λ_found[j]) >= λ_null, eachindex(λ_found)) + dist_new = abs.(sqrt.(complex.(λ_found[new]) ./ scale) .- ωt) + any(<(d_nev * (1 - 1.0e-8)), dist_new) || break + append!(pool_λ, λ_found[new]) + append!(pool_vecs, found[new]) + append!(pool_dist, dist_new) + end + λ, vecs = pool_λ, pool_vecs + keep = sortperm(pool_dist) + end length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" keep = keep[1:min(nev, end)] keep = keep[sortperm(real.(sqrt.(complex.(λ[keep]))))] diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 2f43a618..5af2922c 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -123,6 +123,29 @@ end end end +@testset "repeated eigenvalues of disconnected cavities keep their multiplicity" begin + # 32 disconnected PEC unit cubes of one free edge each, with εr cycling through 1, 2, 4, 8: the eigenvalues are + # 20/εr, eight times each, and the nearest to a low target is 20/8 (0.25164606 Hz) eight times over. + cube = generate_grid(Tetrahedron, (1, 1, 1), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + ncell, nnode = length(cube.cells), length(cube.nodes) + nodes = [Node(Vec(x.x[1] + 2i, x.x[2], x.x[3])) for i in 0:31 for x in cube.nodes] + cells = [Tetrahedron(ntuple(k -> c.nodes[k] + nnode * i, 4)) for i in 0:31 for c in cube.cells] + grid = Grid(cells, nodes) + for (k, eps_r) in enumerate((1.0, 2.0, 4.0, 8.0)) + addcellset!(grid, "eps$k", Set(ncell * i + c for i in 0:31 if mod(i, 4) == k - 1 for c in 1:ncell)) + end + rim = union(values(cube.facetsets)...) # the six outer faces of one cube + addfacetset!(grid, "wall", Set(FacetIndex(ncell * i + f[1], f[2]) for i in 0:31 for f in rim)) + materials = Dict("eps$k" => MaxwellMaterial(; eps_r) for (k, eps_r) in enumerate((1.0, 2.0, 4.0, 8.0))) + model = MaxwellModel(grid; materials, pec = ["wall"], eps0 = 1.0, mu0 = 1.0) + f(eps_r) = sqrt(20 / eps_r) / 2π + found = maxwell_eigenmodes(model; nev = 2, target_frequency = 0.01) + @test found.frequency ≈ fill(f(8), 2) rtol = 1.0e-8 + @test maxwell_eigenmodes(model; nev = 3, target_frequency = 0.01).frequency ≈ fill(f(8), 3) rtol = 1.0e-8 + @test maxwell_eigenmodes(model; nev = 9, target_frequency = 0.01).frequency ≈ [fill(f(8), 8); f(4)] rtol = 1.0e-8 + @test issorted(maxwell_eigenmodes(model; nev = 12, target_frequency = 0.01).frequency) +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From 5c3d3f0b6b811b624e4d95c6fb8fb4ca97efc3f1 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 23:25:36 +0000 Subject: [PATCH 14/22] Eigenmodes: restarts widen their candidates like the first search A restart asked for a fixed number of candidates, which can all lie below the static cutoff and then count as nothing nearer found. The widening loop of the first search is now a helper used by every restart pass, which only stops without survivors once the candidate budget is exhausted. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 55 +++++++++++++++++++++++-------------------- test/Maxwell/eigen.jl | 28 ++++++++++++++++++++++ 2 files changed, 58 insertions(+), 25 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 8f3d0ffe..85eb1c09 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -220,31 +220,39 @@ function maxwell_eigenmodes( # The dense spectrum also holds the projected-out gradients (θ = 0): their eigenvectors lie in the range of G, # which the projection annihilates, while every other eigenvector is left unchanged by it. physical(v) = norm(project(v)) > norm(v) / 2 - howmany = 2nev - local λ, vecs, keep, dense - while true - dim = max(krylovdim, howmany + 20) - dense = dim >= length(free) - θ, vecs = dense ? _dense_eigs(op, length(free), T) : - _eigsolve(KrylovKitEigensolver(), op, x0, howmany; krylovdim = dim, tol, maxiter) - λ = σ .+ 1 ./ θ - lossy || (λ = real.(λ)) - keep = findall(j -> physical(vecs[j]) && abs(λ[j]) >= λ_null, eachindex(λ)) - dist = abs.(sqrt.(complex.(λ[keep]) ./ scale) .- ωt) - keep = keep[sortperm(dist)] - if length(keep) < nev - dense && break - howmany = 2howmany # the filter took too many of the candidates, so look further out - continue + # The candidates of the operator `op_s` from `start`, widened until at least `need` of them survive the filters + # and, with the distance `d` (by default that of the `need`-th), they reach the bound above, or the space is + # exhausted (dense). + function search(op_s, start, need, d_fixed = nothing) + howmany = 2nev + while true + dim = max(krylovdim, howmany + 20) + dense = dim >= length(free) + θ, vecs = dense ? _dense_eigs(op_s, length(free), T) : + _eigsolve(KrylovKitEigensolver(), op_s, start, howmany; krylovdim = dim, tol, maxiter) + λ = σ .+ 1 ./ θ + lossy || (λ = real.(λ)) + keep = findall(j -> isfinite(λ[j]) && physical(vecs[j]) && abs(λ[j]) >= λ_null, eachindex(λ)) + dist = abs.(sqrt.(complex.(λ[keep]) ./ scale) .- ωt) + keep = keep[sortperm(dist)] + if length(keep) < need + dense && return λ, vecs, keep, dense + howmany = 2howmany # the filter took too many of the candidates, so look further out + continue + end + d = something(d_fixed, sort(dist)[need]) + (dense || maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale + shift_offset) && + return λ, vecs, keep, dense + howmany = 2howmany end - d = sort(dist)[nev] - (dense || maximum(l -> abs(l - σ), λ[keep]) >= (2ωt + d) * d * scale + shift_offset) && break - howmany = 2howmany + return end + λ, vecs, keep, dense = search(op, x0, nev) if !dense && length(keep) >= nev # A Krylov space from one starting vector holds one vector per distinct eigenvalue, so a repeated eigenvalue - # may have been found once only. Restart from vectors M-orthogonal to everything found until a pass finds - # nothing nearer than the current nev-th mode: each pass can add one copy of a repeated eigenvalue. + # may have been found once only. Restart from vectors M-orthogonal to everything found, widening the + # candidates like the first search, until a pass finds nothing nearer than the current nev-th mode: each pass + # can add one copy of a repeated eigenvalue. pool_λ, pool_vecs = λ[keep], vecs[keep] pool_dist = abs.(sqrt.(complex.(pool_λ) ./ scale) .- ωt) for pass in 1:nev @@ -252,10 +260,7 @@ function maxwell_eigenmodes( V = _orthonormal_basis(pool_vecs, M) deflate(x) = x - V * (transpose(V) * (M * x)) start = deflate(project(T.(cos.(2.399963 .* pass .* (1:length(free)) .^ 1.37 .+ pass)))) - θ, found = _eigsolve(KrylovKitEigensolver(), x -> deflate(op(x)), start, 2nev; krylovdim = max(krylovdim, 2nev + 20), tol, maxiter) - λ_found = σ .+ 1 ./ θ - lossy || (λ_found = real.(λ_found)) - new = findall(j -> isfinite(λ_found[j]) && physical(found[j]) && abs(λ_found[j]) >= λ_null, eachindex(λ_found)) + λ_found, found, new, _ = search(x -> deflate(op(x)), start, 1, d_nev) dist_new = abs.(sqrt.(complex.(λ_found[new]) ./ scale) .- ωt) any(<(d_nev * (1 - 1.0e-8)), dist_new) || break append!(pool_λ, λ_found[new]) diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 5af2922c..a4e1937c 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -146,6 +146,34 @@ end @test issorted(maxwell_eigenmodes(model; nev = 12, target_frequency = 0.01).frequency) end +@testset "restarts widen past the discarded static modes like the first search" begin + # 64 disconnected one-free-edge cubes with the eigenvalues 1..6 once, 10 and 20 twice and 54 distinct ones above, and + # a cutoff of 8: the six lowest are discarded, so a restart asking for a few candidates may see only those. + eigenvalues = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 10.0, 10.0, 20.0, 20.0, (40.0 + 3i for i in 1:54)...] + cube = generate_grid(Tetrahedron, (1, 1, 1), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + ncell, nnode = length(cube.cells), length(cube.nodes) + ncubes = length(eigenvalues) + grid = Grid( + [Tetrahedron(ntuple(k -> c.nodes[k] + nnode * i, 4)) for i in 0:(ncubes - 1) for c in cube.cells], + [Node(Vec(x.x[1] + 2i, x.x[2], x.x[3])) for i in 0:(ncubes - 1) for x in cube.nodes], + ) + rim = union(values(cube.facetsets)...) + addfacetset!(grid, "wall", Set(FacetIndex(ncell * i + f[1], f[2]) for i in 0:(ncubes - 1) for f in rim)) + materials = Dict{String, MaxwellMaterial}() + for λ in unique(eigenvalues) + addcellset!(grid, "λ$λ", Set(ncell * (i - 1) + c for (i, v) in enumerate(eigenvalues) if v == λ for c in 1:ncell)) + materials["λ$λ"] = MaxwellMaterial(; eps_r = 20 / λ) + end + model = MaxwellModel(grid; materials, pec = ["wall"], eps0 = 1.0, mu0 = 1.0) + free = setdiff(1:ndofs(model.dh), FiniteElementMethod._pec_dofs(model.dh, model.grid, model.pec)) + K, M = model.blocks.curlcurl[free, free], model.blocks.eps_real[free, free] + nullspace_tol = 8 / (opnorm(K, 1) / opnorm(M, 1)) + f(λ) = sqrt(λ) / 2π + found = maxwell_eigenmodes(model; nev = 2, target_frequency = 0.001, nullspace_tol) + @test found.frequency ≈ fill(f(10.0), 2) rtol = 1.0e-8 + @test maxwell_eigenmodes(model; nev = 3, target_frequency = 0.001, nullspace_tol).frequency ≈ [f(10.0), f(10.0), f(20.0)] rtol = 1.0e-8 +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From b54c319901fd8e2e996208c8ca42909ca4dcd3ac Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 23:38:58 +0000 Subject: [PATCH 15/22] Eigenmodes: restart deflation with an indefinite mass form The restart basis normalised by sqrt(v^T M v), which throws for a negative mass norm (lossless negative permittivity) and divides by a vanishing one. It now scales by sqrt(|s|), deflates with the biorthogonal pair (b, M b / sign), and falls back to the Euclidean projection for an isotropic vector. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 37 ++++++++++++++++++++++++++----------- test/Maxwell/eigen.jl | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 11 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 85eb1c09..1b3eb0b4 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -91,19 +91,34 @@ function _gradient_projection(G, M) return x -> x - G * (FG \ (GtM * x)) end -# The columns of `vecs` made orthonormal in the bilinear form xᵀ M y (the eigenvectors of the complex symmetric -# pencil are orthogonal in it), skipping any that are already in the span. +# A deflation basis for `vecs`: columns `B` and `U` with Uᵀ B = I, so that x - B (Uᵀ x) removes the span of `vecs` from x. +# The vectors are made orthogonal in the bilinear form xᵀ M y (the eigenvectors of the complex symmetric pencil are), +# which may be indefinite (negative Re(εr)): they are scaled by sqrt(|s|) with s = bᵀ M b, not sqrt(s). A vector that is +# nearly isotropic in the form (|s| tiny) is deflated in the Euclidean form instead, and one already in the span is +# skipped. function _orthonormal_basis(vecs, M) - basis = Vector{eltype(first(vecs))}[] + T = promote_type(eltype(first(vecs)), eltype(M)) + n = length(first(vecs)) + B, U = Vector{T}[], Vector{T}[] + mscale = opnorm(M, 1) for v in vecs - w = copy(v) - for _ in 1:2, b in basis - w .-= b .* (transpose(b) * (M * w)) + w = T.(v) + for _ in 1:2, (b, u) in zip(B, U) + w .-= b .* (transpose(u) * w) + end + norm(w) > 1.0e-10 * norm(v) || continue + sw = transpose(w) * (M * w) + if abs(sw) > 1.0e-10 * mscale * norm(w)^2 + σ = sw / abs(sw) + b = w ./ sqrt(abs(sw)) + push!(B, b) + push!(U, (M * b) ./ σ) + else + push!(B, w) + push!(U, w ./ (transpose(w) * w)) end - s = transpose(w) * (M * w) - abs(s) > 1.0e-10 * abs(transpose(v) * (M * v)) && push!(basis, w ./ sqrt(s)) end - return reduce(hcat, basis) + return isempty(B) ? (zeros(T, n, 0), zeros(T, n, 0)) : (reduce(hcat, B), reduce(hcat, U)) end # The largest ratio between the εr (real part) or μr values of the cells. @@ -257,8 +272,8 @@ function maxwell_eigenmodes( pool_dist = abs.(sqrt.(complex.(pool_λ) ./ scale) .- ωt) for pass in 1:nev d_nev = sort(pool_dist)[nev] - V = _orthonormal_basis(pool_vecs, M) - deflate(x) = x - V * (transpose(V) * (M * x)) + B, U = _orthonormal_basis(pool_vecs, M) + deflate(x) = x - B * (transpose(U) * x) start = deflate(project(T.(cos.(2.399963 .* pass .* (1:length(free)) .^ 1.37 .+ pass)))) λ_found, found, new, _ = search(x -> deflate(op(x)), start, 1, d_nev) dist_new = abs.(sqrt.(complex.(λ_found[new]) ./ scale) .- ωt) diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index a4e1937c..bd0aa2c6 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -174,6 +174,45 @@ end @test maxwell_eigenmodes(model; nev = 3, target_frequency = 0.001, nullspace_tol).frequency ≈ [f(10.0), f(10.0), f(20.0)] rtol = 1.0e-8 end +@testset "restart deflation works with an indefinite mass form" begin + basis = FiniteElementMethod._orthonormal_basis + # A negative mass norm, an isotropic vector (zero norm), a vector already in the span and a complex one. + B, U = basis([[1.0]], reshape([-1.0], 1, 1)) + @test transpose(U) * B ≈ [1.0;;] + M = [1.0 0.0; 0.0 -1.0] + B, U = basis([[1.0, 1.0], [2.0, 2.0], [1.0, -1.0]], M) + @test size(B, 2) == 2 && transpose(U) * B ≈ [1.0 0.0; 0.0 1.0] + @test B - B * (transpose(U) * B) ≈ zeros(2, 2) + B, U = basis([[1.0 + 0.5im, 2.0]], [-2.0 0.0; 0.0 1.0]) + @test transpose(U) * B ≈ [1.0;;] + # Lossless negative-permittivity cavities: 63 cubes of eigenvalues 2..64 and one with εr = -200 (λ = -0.1). + cube = generate_grid(Tetrahedron, (1, 1, 1), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + ncell, nnode = length(cube.cells), length(cube.nodes) + epss = [-200.0; [20 / λ for λ in 2.0:64.0]] + ncubes = length(epss) + grid = Grid( + [Tetrahedron(ntuple(k -> c.nodes[k] + nnode * i, 4)) for i in 0:(ncubes - 1) for c in cube.cells], + [Node(Vec(x.x[1] + 2i, x.x[2], x.x[3])) for i in 0:(ncubes - 1) for x in cube.nodes], + ) + rim = union(values(cube.facetsets)...) + addfacetset!(grid, "wall", Set(FacetIndex(ncell * i + f[1], f[2]) for i in 0:(ncubes - 1) for f in rim)) + materials = Dict{String, MaxwellMaterial}() + for (i, eps_r) in enumerate(epss) + addcellset!(grid, "cube$i", Set(ncell * (i - 1) + c for c in 1:ncell)) + materials["cube$i"] = MaxwellMaterial(; eps_r) + end + model = MaxwellModel(grid; materials, pec = ["wall"], eps0 = 1.0, mu0 = 1.0) + free = setdiff(1:ndofs(model.dh), FiniteElementMethod._pec_dofs(model.dh, model.grid, model.pec)) + λ = real.(eigvals(Matrix(model.blocks.curlcurl[free, free]), Matrix(model.blocks.eps_real[free, free]))) + ω = sqrt.(complex.(sort(λ))) + target = 0.01 + nearest = sort(ω; by = x -> abs(x - 2π * target)) + for nev in 1:3 + found = maxwell_eigenmodes(model; nev, target_frequency = target) + @test sort(abs.(found.omega .- 2π * target)) ≈ sort(abs.(nearest[1:nev] .- 2π * target)) rtol = 1.0e-8 + end +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From 4c9806f545c8fd3ccd11bf9d40887c2f9c9b40d1 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 23:46:37 +0000 Subject: [PATCH 16/22] Eigenmodes: deflate restarts with a Gram-matrix projector The restart basis mixed Euclidean and mass-form duals for isotropic vectors, which left earlier modes in the start vector, and divided by a vanishing transpose(w) w for complex ones. The projector x - B pinv(Bt M B) Bt M x has no orthonormalisation, square root or division: the rank-revealing pseudo-inverse absorbs indefinite, isotropic and dependent directions. A restart whose start vector deflates to nothing stops. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/FiniteElementMethod.jl | 2 +- src/maxwell/eigen.jl | 45 ++++++++++++-------------------------- test/Maxwell/eigen.jl | 31 ++++++++++++++++---------- 3 files changed, 35 insertions(+), 43 deletions(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 12d3d661..82708d9a 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: SingularException, dot, eigen, lu, mul!, norm, opnorm +using LinearAlgebra: SingularException, dot, eigen, lu, mul!, norm, opnorm, pinv using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 1b3eb0b4..e114052c 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -91,34 +91,16 @@ function _gradient_projection(G, M) return x -> x - G * (FG \ (GtM * x)) end -# A deflation basis for `vecs`: columns `B` and `U` with Uᵀ B = I, so that x - B (Uᵀ x) removes the span of `vecs` from x. -# The vectors are made orthogonal in the bilinear form xᵀ M y (the eigenvectors of the complex symmetric pencil are), -# which may be indefinite (negative Re(εr)): they are scaled by sqrt(|s|) with s = bᵀ M b, not sqrt(s). A vector that is -# nearly isotropic in the form (|s| tiny) is deflated in the Euclidean form instead, and one already in the span is -# skipped. -function _orthonormal_basis(vecs, M) - T = promote_type(eltype(first(vecs)), eltype(M)) - n = length(first(vecs)) - B, U = Vector{T}[], Vector{T}[] - mscale = opnorm(M, 1) - for v in vecs - w = T.(v) - for _ in 1:2, (b, u) in zip(B, U) - w .-= b .* (transpose(u) * w) - end - norm(w) > 1.0e-10 * norm(v) || continue - sw = transpose(w) * (M * w) - if abs(sw) > 1.0e-10 * mscale * norm(w)^2 - σ = sw / abs(sw) - b = w ./ sqrt(abs(sw)) - push!(B, b) - push!(U, (M * b) ./ σ) - else - push!(B, w) - push!(U, w ./ (transpose(w) * w)) - end - end - return isempty(B) ? (zeros(T, n, 0), zeros(T, n, 0)) : (reduce(hcat, B), reduce(hcat, U)) +# The projector that removes the span of `vecs` from a vector in the bilinear form xᵀ M y (the form of the symmetric +# pencil, with the transpose also for complex data): x ↦ x - B G⁺ Bᵀ M x with B the vectors as columns and +# G = Bᵀ M B their Gram matrix. There is no orthonormalisation, so an indefinite form (negative Re(εr)), a vector +# isotropic in it or a dependent one needs no square root or division: the rank-revealing pseudo-inverse G⁺ drops the +# directions that G cannot resolve. +function _deflator(vecs, M) + B = reduce(hcat, vecs) + MB = M * B + Gp = pinv(transpose(B) * MB; rtol = 4 * sqrt(eps())) + return x -> x - B * (Gp * (transpose(MB) * x)) end # The largest ratio between the εr (real part) or μr values of the cells. @@ -272,9 +254,10 @@ function maxwell_eigenmodes( pool_dist = abs.(sqrt.(complex.(pool_λ) ./ scale) .- ωt) for pass in 1:nev d_nev = sort(pool_dist)[nev] - B, U = _orthonormal_basis(pool_vecs, M) - deflate(x) = x - B * (transpose(U) * x) - start = deflate(project(T.(cos.(2.399963 .* pass .* (1:length(free)) .^ 1.37 .+ pass)))) + deflate = _deflator(pool_vecs, M) + raw = project(T.(cos.(2.399963 .* pass .* (1:length(free)) .^ 1.37 .+ pass))) + start = deflate(raw) + norm(start) > 1.0e-8 * norm(raw) || break # nothing is left outside the span of what was found λ_found, found, new, _ = search(x -> deflate(op(x)), start, 1, d_nev) dist_new = abs.(sqrt.(complex.(λ_found[new]) ./ scale) .- ωt) any(<(d_nev * (1 - 1.0e-8)), dist_new) || break diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index bd0aa2c6..efeb47c7 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -1,5 +1,5 @@ # Eigenmodes of a PEC rectangular cavity against the analytic TE/TM frequencies. -using FiniteElementMethod, Ferrite, KrylovKit, LinearAlgebra, Test +using FiniteElementMethod, Ferrite, KrylovKit, LinearAlgebra, Random, Test include(joinpath(@__DIR__, "..", "shared", "maxwell.jl")) const BOX = (1.0, 0.5, 0.75) @@ -175,16 +175,25 @@ end end @testset "restart deflation works with an indefinite mass form" begin - basis = FiniteElementMethod._orthonormal_basis - # A negative mass norm, an isotropic vector (zero norm), a vector already in the span and a complex one. - B, U = basis([[1.0]], reshape([-1.0], 1, 1)) - @test transpose(U) * B ≈ [1.0;;] - M = [1.0 0.0; 0.0 -1.0] - B, U = basis([[1.0, 1.0], [2.0, 2.0], [1.0, -1.0]], M) - @test size(B, 2) == 2 && transpose(U) * B ≈ [1.0 0.0; 0.0 1.0] - @test B - B * (transpose(U) * B) ≈ zeros(2, 2) - B, U = basis([[1.0 + 0.5im, 2.0]], [-2.0 0.0; 0.0 1.0]) - @test transpose(U) * B ≈ [1.0;;] + deflator = FiniteElementMethod._deflator + # The Gram identity Bᵀ M (x - P x) = 0, finite output, for an indefinite M, isotropic and dependent vectors. + gram_residual(B, M, x) = norm(transpose(B) * (M * deflator(collect(eachcol(B)), M)(x))) / (norm(B) * norm(M * x)) + M = [1.0 0.0 0.0; 0.0 -1.0 0.0; 0.0 0.0 2.0] + B = [1.0 1.0; 1.0 -1.0; 0.0 1.0] # the first column is isotropic in M + @test gram_residual(B, M, [0.3, -0.7, 1.1]) < 1.0e-12 + x = deflator([[1.0, im]], Matrix(1.0I, 2, 2))([2.0, 3.0]) # an isotropic complex vector: Gram matrix 0 + @test all(isfinite, x) + rng = Random.Xoshiro(7) + for T in (Float64, ComplexF64) + A = randn(rng, T, 6, 6) + M = A + transpose(A) # symmetric, indefinite (complex symmetric for T = ComplexF64) + B = randn(rng, T, 6, 3) + B = [B B[:, 1]] # a repeated column + x = randn(rng, T, 6) + P = deflator(collect(eachcol(B)), M) + @test all(isfinite, P(x)) + @test gram_residual(B, M, x) < 1.0e-9 + end # Lossless negative-permittivity cavities: 63 cubes of eigenvalues 2..64 and one with εr = -200 (λ = -0.1). cube = generate_grid(Tetrahedron, (1, 1, 1), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) ncell, nnode = length(cube.cells), length(cube.nodes) From 1ffb42d110fdba370d578f8bc411a77a36a2a1a1 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 00:32:49 +0000 Subject: [PATCH 17/22] Eigenmodes: keep the search helper's variables local and the shift single-assigned The helper assigned names that the enclosing function defines later (lambda, vecs, keep, dense) and the shift was reassigned after being captured, so both were boxed and JET reported them as possibly undefined, failing the QA group. They are now declared local and the shift is bound once. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index e114052c..63992c82 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -188,15 +188,15 @@ function maxwell_eigenmodes( contrast > 1.0e6 && @warn "maxwell_eigenmodes: the materials of the model differ by a factor $contrast in εr or μr, so the shift-invert is ill-conditioned and modes may be inaccurate" nullspace_tol !== nothing && λ_null > scale * (2π * target_frequency)^2 && @warn "maxwell_eigenmodes: nullspace_tol puts the null-space cutoff $λ_null above the target, so the modes there are discarded" ωt = 2π * target_frequency - σ = max(scale * ωt^2, λ_shift) - shift_offset = σ - scale * ωt^2 + σ0 = max(scale * ωt^2, λ_shift) + shift_offset = σ0 - scale * ωt^2 # A shift exactly on a discrete eigenvalue makes the factorisation singular; nudge it off. - F = try - lu(K - σ * M) + F, σ = try + lu(K - σ0 * M), σ0 catch err err isa SingularException || rethrow() - σ *= 1 + 1.0e-8 - lu(K - σ * M) + σ1 = σ0 * (1 + 1.0e-8) + lu(K - σ1 * M), σ1 end # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them. @@ -221,6 +221,7 @@ function maxwell_eigenmodes( # and, with the distance `d` (by default that of the `need`-th), they reach the bound above, or the space is # exhausted (dense). function search(op_s, start, need, d_fixed = nothing) + local θ, λ, vecs, keep, dense, dist # not the variables of the same names of the enclosing function howmany = 2nev while true dim = max(krylovdim, howmany + 20) From 717958e92b08c803716f34c578ab5aae9a041a19 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 00:40:53 +0000 Subject: [PATCH 18/22] Eigenmodes: support ordinary passive materials only The gradient projection needs a definite mass form: with negative permittivity (for example half a cube at -1, half at 1) the potential Gram matrix can cancel to a singular one. A material with real(eps_r) <= 0 or mu_r <= 0 is rejected naming its cell sets; loss as Im(eps_r) stays supported. The negative-permittivity cavity regressions of the restart work become rejection tests. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/maxwell.md | 2 +- src/maxwell/eigen.jl | 11 ++++++++++- test/Maxwell/eigen.jl | 37 +++++++++++-------------------------- 3 files changed, 22 insertions(+), 28 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index fef6f73b..e20612cd 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -35,7 +35,7 @@ that is a function of `ω`, so a frequency sweep only recombines nonzero values [`maxwell_eigenmodes`](@ref) finds the modes nearest a target frequency by shift-invert Arnoldi, with the PEC dofs eliminated and the `ω = 0` gradient null space of the edge elements projected out, so any target works, including one below the lowest mode. It needs `using KrylovKit`. A lossy material gives complex -`ω`; the quality factor is `Q = Re(ω) / (2 Im(ω))`. An air-filled 100 × 50 × 75 mm box has its TE101 mode +`ω`; the quality factor is `Q = Re(ω) / (2 Im(ω))`. Only ordinary passive materials are supported: `real(εr)` and `μr` must be positive (the gradient projection needs a definite mass form), otherwise an `ArgumentError` names the cell set. An air-filled 100 × 50 × 75 mm box has its TE101 mode at 2.498 GHz: ```julia diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index 63992c82..a1cbd237 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -150,7 +150,8 @@ Returns `(; frequency, Q, omega, modes)`: `omega` the complex angular frequencie mode has `Im(ω) > 0` and decays as `exp(-Im(ω) t)`), and `modes` the [`MaxwellSolution`](@ref)s at `Re(ω)`, with zeros on the PEC dofs, scaled to `∫ Re(εr) |E|² = 1` over the mesh (mesh units; to a unit dof norm where that integral is not positive) with the largest dof real. Conductivity and terms added with -[`FiniteElementMethod.add_term!`](@ref) make the problem nonlinear in `ω` and are rejected. A problem too +[`FiniteElementMethod.add_term!`](@ref) make the problem nonlinear in `ω` and are rejected, and so is any material +with `real(εr) ≤ 0` or `μr ≤ 0` (the gradient projection needs a definite mass form; loss as `Im(εr)` is fine). A problem too small for a Krylov space of dimension `krylovdim` is solved densely, and `nev` may not exceed the number of modes outside the gradient null space. """ @@ -163,6 +164,14 @@ function maxwell_eigenmodes( throw(ArgumentError("target_frequency must be positive and finite, got $target_frequency")) all(iszero, nonzeros(model.blocks.sigma)) || throw(ArgumentError("maxwell_eigenmodes does not support conductivity (the problem is quadratic in ω); model it as Im(eps_r)")) + bad = findfirst(m -> !(real(m.eps_r) > 0 && m.mu_r > 0), model.materials) + bad === nothing || throw( + ArgumentError( + "maxwell_eigenmodes supports ordinary passive materials only: cell $bad (cell sets " * + "$(sort!([name for (name, cells) in model.grid.cellsets if bad in cells]))) has eps_r = $(model.materials[bad].eps_r) " * + "and mu_r = $(model.materials[bad].mu_r), but real(eps_r) and mu_r must be positive (loss as Im(eps_r) is fine)" + ) + ) length(model.terms) == 4 || throw(ArgumentError("maxwell_eigenmodes supports only the volume terms of MaxwellModel, not terms added with add_term!")) (; blocks, eps0, mu0, length_scale) = model diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index efeb47c7..3e46f5ac 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -174,7 +174,7 @@ end @test maxwell_eigenmodes(model; nev = 3, target_frequency = 0.001, nullspace_tol).frequency ≈ [f(10.0), f(10.0), f(20.0)] rtol = 1.0e-8 end -@testset "restart deflation works with an indefinite mass form" begin +@testset "restart deflation with an indefinite form, and non-passive materials are rejected" begin deflator = FiniteElementMethod._deflator # The Gram identity Bᵀ M (x - P x) = 0, finite output, for an indefinite M, isotropic and dependent vectors. gram_residual(B, M, x) = norm(transpose(B) * (M * deflator(collect(eachcol(B)), M)(x))) / (norm(B) * norm(M * x)) @@ -194,32 +194,17 @@ end @test all(isfinite, P(x)) @test gram_residual(B, M, x) < 1.0e-9 end - # Lossless negative-permittivity cavities: 63 cubes of eigenvalues 2..64 and one with εr = -200 (λ = -0.1). - cube = generate_grid(Tetrahedron, (1, 1, 1), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) - ncell, nnode = length(cube.cells), length(cube.nodes) - epss = [-200.0; [20 / λ for λ in 2.0:64.0]] - ncubes = length(epss) - grid = Grid( - [Tetrahedron(ntuple(k -> c.nodes[k] + nnode * i, 4)) for i in 0:(ncubes - 1) for c in cube.cells], - [Node(Vec(x.x[1] + 2i, x.x[2], x.x[3])) for i in 0:(ncubes - 1) for x in cube.nodes], - ) - rim = union(values(cube.facetsets)...) - addfacetset!(grid, "wall", Set(FacetIndex(ncell * i + f[1], f[2]) for i in 0:(ncubes - 1) for f in rim)) - materials = Dict{String, MaxwellMaterial}() - for (i, eps_r) in enumerate(epss) - addcellset!(grid, "cube$i", Set(ncell * (i - 1) + c for c in 1:ncell)) - materials["cube$i"] = MaxwellMaterial(; eps_r) - end - model = MaxwellModel(grid; materials, pec = ["wall"], eps0 = 1.0, mu0 = 1.0) - free = setdiff(1:ndofs(model.dh), FiniteElementMethod._pec_dofs(model.dh, model.grid, model.pec)) - λ = real.(eigvals(Matrix(model.blocks.curlcurl[free, free]), Matrix(model.blocks.eps_real[free, free]))) - ω = sqrt.(complex.(sort(λ))) - target = 0.01 - nearest = sort(ω; by = x -> abs(x - 2π * target)) - for nev in 1:3 - found = maxwell_eigenmodes(model; nev, target_frequency = target) - @test sort(abs.(found.omega .- 2π * target)) ≈ sort(abs.(nearest[1:nev] .- 2π * target)) rtol = 1.0e-8 + # Materials that are not ordinary and passive are rejected, naming the cell set. + for (eps_r, mu_r) in ((-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)) + grid = unit_cube(2) + addcellset!(grid, "left", x -> x[1] <= 0.5) + model = MaxwellModel(grid; materials = Dict("left" => MaxwellMaterial(; eps_r, mu_r)), pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + @test_throws "ordinary passive materials only" maxwell_eigenmodes(model; nev = 1, target_frequency = 0.8) + @test_throws "left" maxwell_eigenmodes(model; nev = 1, target_frequency = 0.8) end + ordinary = MaxwellModel(unit_cube(2); materials = Dict{String, MaxwellMaterial}(), pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + @test length(maxwell_eigenmodes(ordinary; nev = 1, target_frequency = 0.8).frequency) == 1 +end end @testset "lossy: nearest in complex ω, and the candidate bound holds" begin From 24988ae20cb77dbfe86baa2c02eb4bce6a624738 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 00:47:24 +0000 Subject: [PATCH 19/22] Tests: fix a stray end in the eigenmode rejection testset A parse error from the previous commit. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Maxwell/eigen.jl | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 3e46f5ac..08d2f612 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -205,7 +205,6 @@ end ordinary = MaxwellModel(unit_cube(2); materials = Dict{String, MaxwellMaterial}(), pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) @test length(maxwell_eigenmodes(ordinary; nev = 1, target_frequency = 0.8).frequency) == 1 end -end @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with From 62fe9660f2bb248782345bdbaf4f67945aec0a90 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 03:37:52 +0000 Subject: [PATCH 20/22] Eigenmodes: keep the shifted solve accurate near a resonance and check the pairs against the pencil A target on a discrete eigenvalue could still factorise, with a condition number of 1/eps that corrupted the other requested pairs (residuals up to 0.2 on a (3,3,3) cube) without a warning. The shift now moves up by a growing relative step until a solve-based condition estimate times eps is below 1e-8, and every returned pair is checked against K v = lambda M v and refined by inverse iteration, with a warning if it still exceeds the tolerance. A regression compares all four modes of the cube at targets on the first frequency and 1e-12, 1e-9 and 1e-6 off it with the dense eigensolve. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 51 +++++++++++++++++++++++++++++++++++-------- test/Maxwell/eigen.jl | 14 ++++++++++++ 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index a1cbd237..c92f9562 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -103,6 +103,32 @@ function _deflator(vecs, M) return x -> x - B * (Gp * (transpose(MB) * x)) end +# The factorisation of K - σ M at a shift σ ≥ σ0 that is not so close to an eigenvalue that the solves are inaccurate: a +# shift on (or within roundoff of) an eigenvalue can still factorise, with a condition number of 1/eps that corrupts +# every Ritz pair, not only the one at the shift. The solve of a fixed vector estimates the condition number +# (‖K - σM‖ ‖x‖ / ‖b‖ ≤ κ), and the shift moves up by a growing relative step until eps times it is below 1e-8. +function _accurate_shifted_lu(K, M, σ0) + b = cos.(1.7 .* (1:size(K, 1))) + σ, F = σ0, nothing + for attempt in 0:8 + σ = σ0 * (1 + (attempt == 0 ? 0.0 : 10.0^(attempt - 9))) + F = try + lu(K - σ * M) + catch err + err isa SingularException || rethrow() + nothing + end + F === nothing && continue + x = F \ b + (opnorm(K, 1) + abs(σ) * opnorm(M, 1)) * norm(x) / norm(b) * eps() < 1.0e-8 && return F, σ + end + F === nothing && throw(SingularException(0)) + return F, σ +end + +# The relative residual of the pair (λ, v) of the original pencil K v = λ M v. +_pencil_residual(K, M, λ, v) = norm(K * v - λ * (M * v)) / (norm(K * v) + abs(λ) * norm(M * v)) + # The largest ratio between the εr (real part) or μr values of the cells. function _material_contrast(materials) spread(values) = maximum(values) / minimum(values) @@ -198,15 +224,8 @@ function maxwell_eigenmodes( nullspace_tol !== nothing && λ_null > scale * (2π * target_frequency)^2 && @warn "maxwell_eigenmodes: nullspace_tol puts the null-space cutoff $λ_null above the target, so the modes there are discarded" ωt = 2π * target_frequency σ0 = max(scale * ωt^2, λ_shift) - shift_offset = σ0 - scale * ωt^2 - # A shift exactly on a discrete eigenvalue makes the factorisation singular; nudge it off. - F, σ = try - lu(K - σ0 * M), σ0 - catch err - err isa SingularException || rethrow() - σ1 = σ0 * (1 + 1.0e-8) - lu(K - σ1 * M), σ1 - end + F, σ = _accurate_shifted_lu(K, M, σ0) + shift_offset = abs(σ - scale * ωt^2) # The gradients of the hat functions of nodes off the PEC facets vanish on the PEC edges; project along them. Gfull, dhn = _discrete_gradient(model) @@ -280,6 +299,20 @@ function maxwell_eigenmodes( end length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" keep = keep[1:min(nev, end)] + # Every pair returned is checked against the original pencil, and refined by inverse iteration with the shifted + # factorisation when its residual is above what tol allows for. + residual_tol = max(1.0e3 * tol, 1.0e-8) + for j in keep + vecs[j] = ComplexF64.(vecs[j]) |> v -> lossy ? v : real.(v) + for _ in 1:5 + _pencil_residual(K, M, λ[j], vecs[j]) <= residual_tol && break + w = op(vecs[j]) + vecs[j] = w ./ norm(w) + λ[j] = (transpose(vecs[j]) * (K * vecs[j])) / (transpose(vecs[j]) * (M * vecs[j])) + end + r = _pencil_residual(K, M, λ[j], vecs[j]) + r <= residual_tol || @warn "maxwell_eigenmodes: a returned pair has the relative residual $r of the original pencil, above $residual_tol; the shifted solve is ill-conditioned" + end keep = keep[sortperm(real.(sqrt.(complex.(λ[keep]))))] omega = sqrt.(complex.(λ[keep])) ./ sqrt(scale) diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 08d2f612..2c82d2ee 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -206,6 +206,20 @@ end @test length(maxwell_eigenmodes(ordinary; nev = 1, target_frequency = 0.8).frequency) == 1 end +@testset "a target on a resonance keeps every requested mode accurate" begin + model = MaxwellModel(unit_cube(3); pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + free = setdiff(1:ndofs(model.dh), FiniteElementMethod._pec_dofs(model.dh, model.grid, model.pec)) + K, M = Matrix(model.blocks.curlcurl[free, free]), Matrix(model.blocks.eps_real[free, free]) + λ = filter(>(1.0e-6), real.(eigvals(Symmetric(K), Symmetric(M)))) + reference = sqrt.(sort(λ)[1:4]) ./ 2π + residual(m, f) = (v = m.u[free]; norm(K * v - (2π * f)^2 * (M * v)) / (norm(K * v) + (2π * f)^2 * norm(M * v))) + for rel in (0.0, 1.0e-12, 1.0e-9, 1.0e-6), kwargs in ((;), (; krylovdim = 10_000)) + found = maxwell_eigenmodes(model; nev = 4, target_frequency = reference[1] * (1 + rel), kwargs...) + @test found.frequency ≈ reference rtol = 1.0e-8 + @test maximum(residual.(found.modes, found.frequency)) < 1.0e-6 + end +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From 26f468e6ea000ba53e7271d8f008aba273f9dbc9 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 04:18:40 +0000 Subject: [PATCH 21/22] Eigenmodes: real modes of a repeated eigenvalue are built per cluster A real shifted operator can return a complex-conjugate pair inside a repeated real eigenspace; taking the real part of each vector made them one vector, so fewer independent modes than requested came back without a warning (the first two modes of a (2,2,2) cube were identical). Per cluster of equal eigenvalues the real and imaginary parts are now orthonormalised in the mass form with a relative rank test, and as many independent real vectors as the cluster has replace them. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/eigen.jl | 39 ++++++++++++++++++++++++++++++++++++++- test/Maxwell/eigen.jl | 20 ++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index c92f9562..edea3461 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -129,6 +129,42 @@ end # The relative residual of the pair (λ, v) of the original pencil K v = λ M v. _pencil_residual(K, M, λ, v) = norm(K * v - λ * (M * v)) / (norm(K * v) + abs(λ) * norm(M * v)) +# The M-orthonormal real vectors of a lossless problem. A real shifted operator can return a complex-conjugate pair +# inside a repeated real eigenspace, whose real parts are the same vector, so the real parts of the returned vectors are +# not taken one by one: per cluster of equal eigenvalues (to 1e-6 relative), the real and imaginary parts of all its +# vectors are orthonormalised in the form xᵀ M y (positive for passive materials) with a relative rank test, and as many +# independent ones as the cluster has vectors replace them. A cluster that does not yield that many keeps its vectors. +function _real_cluster_vectors!(vecs, λ, keep, M) + order = sort(keep; by = j -> real(λ[j])) + i = 1 + while i <= length(order) + k = i + while k < length(order) && abs(λ[order[k + 1]] - λ[order[i]]) <= 1.0e-6 * max(abs(λ[order[i]]), eps()) + k += 1 + end + cluster = order[i:k] + basis = Vector{Float64}[] + for j in cluster, part in (real(vecs[j]), imag(vecs[j])) + length(basis) == length(cluster) && break + size0 = real(dot(part, M * part)) + size0 > 0 || continue + w = copy(part) + for _ in 1:2, b in basis + w .-= b .* dot(b, M * w) + end + s = real(dot(w, M * w)) + s > 1.0e-12 * size0 && push!(basis, w ./ sqrt(s)) + end + if length(basis) == length(cluster) + for (j, b) in zip(cluster, basis) + vecs[j] = ComplexF64.(b) + end + end + i = k + 1 + end + return vecs +end + # The largest ratio between the εr (real part) or μr values of the cells. function _material_contrast(materials) spread(values) = maximum(values) / minimum(values) @@ -303,7 +339,7 @@ function maxwell_eigenmodes( # factorisation when its residual is above what tol allows for. residual_tol = max(1.0e3 * tol, 1.0e-8) for j in keep - vecs[j] = ComplexF64.(vecs[j]) |> v -> lossy ? v : real.(v) + vecs[j] = ComplexF64.(vecs[j]) for _ in 1:5 _pencil_residual(K, M, λ[j], vecs[j]) <= residual_tol && break w = op(vecs[j]) @@ -313,6 +349,7 @@ function maxwell_eigenmodes( r = _pencil_residual(K, M, λ[j], vecs[j]) r <= residual_tol || @warn "maxwell_eigenmodes: a returned pair has the relative residual $r of the original pencil, above $residual_tol; the shifted solve is ill-conditioned" end + lossy || _real_cluster_vectors!(vecs, λ, keep, M) keep = keep[sortperm(real.(sqrt.(complex.(λ[keep]))))] omega = sqrt.(complex.(λ[keep])) ./ sqrt(scale) diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 2c82d2ee..2adf7963 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -220,6 +220,26 @@ end end end +@testset "repeated eigenvalues return independent real modes" begin + # A real shifted operator can return a complex-conjugate pair inside a repeated real eigenspace, whose real parts + # are one vector: the modes must be independent and M-orthonormal, with the frequencies of the dense eigensolve. + for (n, nev) in ((2, 4), (3, 4)) + model = MaxwellModel(unit_cube(n); pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + free = setdiff(1:ndofs(model.dh), FiniteElementMethod._pec_dofs(model.dh, model.grid, model.pec)) + K, M = Matrix(model.blocks.curlcurl[free, free]), Matrix(model.blocks.eps_real[free, free]) + λ = sort(filter(>(1.0), real.(eigvals(Symmetric(K), Symmetric(M))))) + target = sqrt(λ[nev]) * (1 + 1.0e-12) / 2π + reference = sort(sqrt.(λ) ./ 2π; by = f -> abs(f - target))[1:nev] + for kwargs in ((;), (; krylovdim = 10_000)) + found = maxwell_eigenmodes(model; nev, target_frequency = target, kwargs...) + V = reduce(hcat, [m.u[free] for m in found.modes]) + @test found.frequency ≈ sort(reference) rtol = 1.0e-8 + @test minimum(svdvals(V)) / maximum(svdvals(V)) > 1.0e-6 + @test norm(V' * M * V - I) < 1.0e-6 + end + end +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first From ae83adc40b7f6e2c14e5e122a890e64316333f27 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 05:59:18 +0000 Subject: [PATCH 22/22] Eigenmodes: extract the modes by Rayleigh-Ritz on the span of every vector found The per-vector refinement, real-part conversion and per-cluster patches on a single Krylov chain left nearly repeated modes dependent, threw on a complex lossless Rayleigh quotient and could amplify imaginary roundoff. The modes are now the Ritz pairs of the pencil on the M-orthonormalised span of the real and imaginary parts of all candidates (a real symmetric small problem for lossless data, the complex symmetric pair for lossy), so they are real, independent and M-orthonormal by construction; pairs above the residual tolerance get shift-invert powers of their vectors added and then a warning, restarts deflate against the basis, and the shifted solve must be accurate to 1e-11. The deflator, the cluster basis and the inverse-iteration refinement are removed. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/FiniteElementMethod.jl | 2 +- src/maxwell/eigen.jl | 161 +++++++++++++++++++------------------ test/Maxwell/eigen.jl | 54 ++++++++----- 3 files changed, 120 insertions(+), 97 deletions(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 82708d9a..ca3f86d2 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: SingularException, dot, eigen, lu, mul!, norm, opnorm, pinv +using LinearAlgebra: SingularException, Symmetric, dot, eigen, lu, mul!, norm, opnorm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson diff --git a/src/maxwell/eigen.jl b/src/maxwell/eigen.jl index edea3461..a41b82f0 100644 --- a/src/maxwell/eigen.jl +++ b/src/maxwell/eigen.jl @@ -91,22 +91,10 @@ function _gradient_projection(G, M) return x -> x - G * (FG \ (GtM * x)) end -# The projector that removes the span of `vecs` from a vector in the bilinear form xᵀ M y (the form of the symmetric -# pencil, with the transpose also for complex data): x ↦ x - B G⁺ Bᵀ M x with B the vectors as columns and -# G = Bᵀ M B their Gram matrix. There is no orthonormalisation, so an indefinite form (negative Re(εr)), a vector -# isotropic in it or a dependent one needs no square root or division: the rank-revealing pseudo-inverse G⁺ drops the -# directions that G cannot resolve. -function _deflator(vecs, M) - B = reduce(hcat, vecs) - MB = M * B - Gp = pinv(transpose(B) * MB; rtol = 4 * sqrt(eps())) - return x -> x - B * (Gp * (transpose(MB) * x)) -end - # The factorisation of K - σ M at a shift σ ≥ σ0 that is not so close to an eigenvalue that the solves are inaccurate: a # shift on (or within roundoff of) an eigenvalue can still factorise, with a condition number of 1/eps that corrupts # every Ritz pair, not only the one at the shift. The solve of a fixed vector estimates the condition number -# (‖K - σM‖ ‖x‖ / ‖b‖ ≤ κ), and the shift moves up by a growing relative step until eps times it is below 1e-8. +# (‖K - σM‖ ‖x‖ / ‖b‖ ≤ κ), and the shift moves up by a growing relative step until eps times it is below 1e-11, so that the solves leave residuals of the other modes at 1e-11. function _accurate_shifted_lu(K, M, σ0) b = cos.(1.7 .* (1:size(K, 1))) σ, F = σ0, nothing @@ -120,7 +108,7 @@ function _accurate_shifted_lu(K, M, σ0) end F === nothing && continue x = F \ b - (opnorm(K, 1) + abs(σ) * opnorm(M, 1)) * norm(x) / norm(b) * eps() < 1.0e-8 && return F, σ + (opnorm(K, 1) + abs(σ) * opnorm(M, 1)) * norm(x) / norm(b) * eps() < 1.0e-11 && return F, σ end F === nothing && throw(SingularException(0)) return F, σ @@ -129,40 +117,48 @@ end # The relative residual of the pair (λ, v) of the original pencil K v = λ M v. _pencil_residual(K, M, λ, v) = norm(K * v - λ * (M * v)) / (norm(K * v) + abs(λ) * norm(M * v)) -# The M-orthonormal real vectors of a lossless problem. A real shifted operator can return a complex-conjugate pair -# inside a repeated real eigenspace, whose real parts are the same vector, so the real parts of the returned vectors are -# not taken one by one: per cluster of equal eigenvalues (to 1e-6 relative), the real and imaginary parts of all its -# vectors are orthonormalised in the form xᵀ M y (positive for passive materials) with a relative rank test, and as many -# independent ones as the cluster has vectors replace them. A cluster that does not yield that many keeps its vectors. -function _real_cluster_vectors!(vecs, λ, keep, M) - order = sort(keep; by = j -> real(λ[j])) - i = 1 - while i <= length(order) - k = i - while k < length(order) && abs(λ[order[k + 1]] - λ[order[i]]) <= 1.0e-6 * max(abs(λ[order[i]]), eps()) - k += 1 - end - cluster = order[i:k] - basis = Vector{Float64}[] - for j in cluster, part in (real(vecs[j]), imag(vecs[j])) - length(basis) == length(cluster) && break - size0 = real(dot(part, M * part)) - size0 > 0 || continue - w = copy(part) - for _ in 1:2, b in basis - w .-= b .* dot(b, M * w) - end - s = real(dot(w, M * w)) - s > 1.0e-12 * size0 && push!(basis, w ./ sqrt(s)) +# An orthonormal basis of the span of `vectors`, in the form xᵀ M y for a lossless problem (M is positive definite on +# the free dofs for passive materials) and in the Euclidean form for a lossy one. Two Gram-Schmidt sweeps; a vector whose +# part outside the basis has under 1e-6 of its own norm is dependent and dropped. +function _orthonormal_basis(vectors, M, lossy) + basis = Vector{eltype(first(vectors))}[] + mbasis = similar(basis) + form(b, mb, w) = lossy ? dot(b, w) : dot(mb, w) + for v in vectors + size0 = real(lossy ? dot(v, v) : dot(v, M * v)) + size0 > 0 || continue + w = copy(v) + for _ in 1:2, (b, mb) in zip(basis, mbasis) + w .-= b .* form(b, mb, w) end - if length(basis) == length(cluster) - for (j, b) in zip(cluster, basis) - vecs[j] = ComplexF64.(b) - end + mw = lossy ? w : M * w + s = real(lossy ? dot(w, w) : dot(w, mw)) + s > 1.0e-12 * size0 || continue + push!(basis, w ./ sqrt(s)) + push!(mbasis, mw ./ sqrt(s)) + end + return reduce(hcat, basis) +end + +# Rayleigh-Ritz of the pencil K v = λ M v on the span of `vectors`: the Ritz values and vectors (as columns) and the +# orthonormal basis. For a lossless problem the real and imaginary parts of each vector are separate candidates, the +# small problem is real symmetric, and the Ritz vectors are real, independent and M-orthonormal by construction; for a +# lossy one the vectors are complex and the small problem is the complex symmetric pair (QᵀKQ, QᵀMQ). +function _ritz(K, M, vectors, lossy) + candidates = Vector{lossy ? ComplexF64 : Float64}[] + for v in vectors + if lossy + push!(candidates, ComplexF64.(v)) + else + push!(candidates, real.(v)) + eltype(v) <: Complex && push!(candidates, imag.(v)) end - i = k + 1 end - return vecs + Q = _orthonormal_basis(candidates, M, lossy) + KQ, MQ = K * Q, M * Q + E = lossy ? eigen(transpose(Q) * KQ, transpose(Q) * MQ) : + eigen(Symmetric(transpose(Q) * KQ), Symmetric(transpose(Q) * MQ)) + return E.values, Q * E.vectors, Q end # The largest ratio between the εr (real part) or μr values of the cells. @@ -310,53 +306,64 @@ function maxwell_eigenmodes( return end λ, vecs, keep, dense = search(op, x0, nev) - if !dense && length(keep) >= nev - # A Krylov space from one starting vector holds one vector per distinct eigenvalue, so a repeated eigenvalue - # may have been found once only. Restart from vectors M-orthogonal to everything found, widening the - # candidates like the first search, until a pass finds nothing nearer than the current nev-th mode: each pass - # can add one copy of a repeated eigenvalue. - pool_λ, pool_vecs = λ[keep], vecs[keep] - pool_dist = abs.(sqrt.(complex.(pool_λ) ./ scale) .- ωt) + # Rayleigh-Ritz on the span of every vector the searches return: real, independent and M-orthonormal modes of a + # lossless problem by construction, whatever the multiplicities and near-multiplicities of the Krylov chains. + pool = collect(vecs) + local θ, V, Q, selected, d_nev + function extract() + θ, V, Q = _ritz(K, M, pool, lossy) + usable = findall(j -> isfinite(θ[j]) && abs(θ[j]) >= λ_null && physical(V[:, j]), eachindex(θ)) + dist = abs.(sqrt.(complex.(θ[usable]) ./ scale) .- ωt) + order = sortperm(dist) + selected = usable[order[1:min(nev, end)]] + d_nev = length(order) >= nev ? dist[order[nev]] : Inf + return + end + extract() + if !dense && length(selected) >= nev + # A Krylov space from one starting vector holds one vector per distinct eigenvalue and mixes nearly repeated + # ones, so restart from vectors M-orthogonal to the basis until a pass finds nothing nearer than the current + # nev-th Ritz value: each pass can add one more direction of a (nearly) repeated eigenvalue. for pass in 1:nev - d_nev = sort(pool_dist)[nev] - deflate = _deflator(pool_vecs, M) + deflate(x) = x - Q * (lossy ? Q' * x : transpose(Q) * (M * x)) raw = project(T.(cos.(2.399963 .* pass .* (1:length(free)) .^ 1.37 .+ pass))) start = deflate(raw) norm(start) > 1.0e-8 * norm(raw) || break # nothing is left outside the span of what was found λ_found, found, new, _ = search(x -> deflate(op(x)), start, 1, d_nev) dist_new = abs.(sqrt.(complex.(λ_found[new]) ./ scale) .- ωt) any(<(d_nev * (1 - 1.0e-8)), dist_new) || break - append!(pool_λ, λ_found[new]) - append!(pool_vecs, found[new]) - append!(pool_dist, dist_new) + append!(pool, found) + extract() end - λ, vecs = pool_λ, pool_vecs - keep = sortperm(pool_dist) end - length(keep) < nev && @warn "maxwell_eigenmodes found $(length(keep)) of $nev modes" - keep = keep[1:min(nev, end)] - # Every pair returned is checked against the original pencil, and refined by inverse iteration with the shifted - # factorisation when its residual is above what tol allows for. + length(selected) < nev && @warn "maxwell_eigenmodes found $(length(selected)) of $nev modes" + # Every Ritz pair is checked against the original pencil; a pair above what tol allows for gets the shift-invert + # image of its vector added to the subspace, a few times, and then a warning. residual_tol = max(1.0e3 * tol, 1.0e-8) - for j in keep - vecs[j] = ComplexF64.(vecs[j]) - for _ in 1:5 - _pencil_residual(K, M, λ[j], vecs[j]) <= residual_tol && break - w = op(vecs[j]) - vecs[j] = w ./ norm(w) - λ[j] = (transpose(vecs[j]) * (K * vecs[j])) / (transpose(vecs[j]) * (M * vecs[j])) + for _ in 1:6 + failing = [j for j in selected if _pencil_residual(K, M, θ[j], V[:, j]) > residual_tol] + isempty(failing) && break + for j in failing + w = V[:, j] + for _ in 1:3 + w = op(w) + w ./= norm(w) + push!(pool, w) + end end - r = _pencil_residual(K, M, λ[j], vecs[j]) + extract() + end + for j in selected + r = _pencil_residual(K, M, θ[j], V[:, j]) r <= residual_tol || @warn "maxwell_eigenmodes: a returned pair has the relative residual $r of the original pencil, above $residual_tol; the shifted solve is ill-conditioned" end - lossy || _real_cluster_vectors!(vecs, λ, keep, M) - keep = keep[sortperm(real.(sqrt.(complex.(λ[keep]))))] + keep = selected[sortperm(real.(sqrt.(complex.(θ[selected]))))] - omega = sqrt.(complex.(λ[keep])) ./ sqrt(scale) - Q = [iszero(imag(ω)) ? Inf : real(ω) / (2imag(ω)) for ω in omega] + omega = sqrt.(complex.(θ[keep])) ./ sqrt(scale) + quality = [iszero(imag(ω)) ? Inf : real(ω) / (2imag(ω)) for ω in omega] Mr = blocks.eps_real[free, free] modes = map(keep, omega) do j, ω - v = ComplexF64.(vecs[j]) + v = ComplexF64.(V[:, j]) w = real(dot(v, Mr * v)) v ./= w > 0 ? sqrt(w) : norm(v) # Re(εr) ≤ 0 somewhere can make the weighted norm vanish v .*= conj(sign(v[argmax(abs.(v))])) @@ -364,5 +371,5 @@ function maxwell_eigenmodes( u[free] = v MaxwellSolution(model, real(ω), u) end - return (; frequency = real.(omega) ./ 2π, Q, omega, modes) + return (; frequency = real.(omega) ./ 2π, Q = quality, omega, modes) end diff --git a/test/Maxwell/eigen.jl b/test/Maxwell/eigen.jl index 2adf7963..f10cfe02 100644 --- a/test/Maxwell/eigen.jl +++ b/test/Maxwell/eigen.jl @@ -175,25 +175,20 @@ end end @testset "restart deflation with an indefinite form, and non-passive materials are rejected" begin - deflator = FiniteElementMethod._deflator - # The Gram identity Bᵀ M (x - P x) = 0, finite output, for an indefinite M, isotropic and dependent vectors. - gram_residual(B, M, x) = norm(transpose(B) * (M * deflator(collect(eachcol(B)), M)(x))) / (norm(B) * norm(M * x)) - M = [1.0 0.0 0.0; 0.0 -1.0 0.0; 0.0 0.0 2.0] - B = [1.0 1.0; 1.0 -1.0; 0.0 1.0] # the first column is isotropic in M - @test gram_residual(B, M, [0.3, -0.7, 1.1]) < 1.0e-12 - x = deflator([[1.0, im]], Matrix(1.0I, 2, 2))([2.0, 3.0]) # an isotropic complex vector: Gram matrix 0 - @test all(isfinite, x) - rng = Random.Xoshiro(7) - for T in (Float64, ComplexF64) - A = randn(rng, T, 6, 6) - M = A + transpose(A) # symmetric, indefinite (complex symmetric for T = ComplexF64) - B = randn(rng, T, 6, 3) - B = [B B[:, 1]] # a repeated column - x = randn(rng, T, 6) - P = deflator(collect(eachcol(B)), M) - @test all(isfinite, P(x)) - @test gram_residual(B, M, x) < 1.0e-9 - end + # Rayleigh-Ritz of perturbed inputs: two M-orthonormal eigenvectors a, b of a repeated eigenvalue and a tiny + # imaginary part of another eigenvector c must give independent modes with small residuals, not normalised noise. + cube2 = MaxwellModel(unit_cube(2); pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + free2 = setdiff(1:ndofs(cube2.dh), FiniteElementMethod._pec_dofs(cube2.dh, cube2.grid, cube2.pec)) + K2, M2 = cube2.blocks.curlcurl[free2, free2], cube2.blocks.eps_real[free2, free2] + E = eigen(Symmetric(Matrix(K2)), Symmetric(Matrix(M2))) + physical = findall(>(1.0), E.values) + pair = findfirst(j -> abs(E.values[physical[j + 1]] - E.values[physical[j]]) < 1.0e-8 * E.values[physical[j]], 1:(length(physical) - 1)) + other = first(setdiff(1:length(physical), (pair, pair + 1))) + a, b, c = E.vectors[:, physical[pair]], E.vectors[:, physical[pair + 1]], E.vectors[:, physical[other]] + θ, V, _ = FiniteElementMethod._ritz(K2, M2, [a + 1.0e-12im * c, b], false) + residuals = [norm(K2 * V[:, j] - θ[j] * (M2 * V[:, j])) / (norm(K2 * V[:, j]) + abs(θ[j]) * norm(M2 * V[:, j])) for j in eachindex(θ)] + @test maximum(residuals) < 1.0e-8 + @test norm(V' * M2 * V - I) < 1.0e-8 # Materials that are not ordinary and passive are rejected, naming the cell set. for (eps_r, mu_r) in ((-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)) grid = unit_cube(2) @@ -240,6 +235,27 @@ end end end +@testset "nearly repeated modes, and a vacuum box at a resonance, return independent accurate modes" begin + function dense_check(height, target, nev; kwargs...) + grid = generate_grid(Tetrahedron, (3, 3, 3), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, height)) + model = MaxwellModel(grid; pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0) + free = setdiff(1:ndofs(model.dh), FiniteElementMethod._pec_dofs(model.dh, model.grid, model.pec)) + K, M = Matrix(model.blocks.curlcurl[free, free]), Matrix(model.blocks.eps_real[free, free]) + λ = filter(>(1.0), real.(eigvals(Symmetric(K), Symmetric(M)))) + reference = sort(sort(sqrt.(λ) ./ 2π; by = f -> abs(f - target))[1:nev]) + found = maxwell_eigenmodes(model; nev, target_frequency = target, kwargs...) + V = reduce(hcat, [m.u[free] for m in found.modes]) + residual(v, f) = norm(K * v - (2π * f)^2 * (M * v)) / (norm(K * v) + (2π * f)^2 * norm(M * v)) + @test found.frequency ≈ reference rtol = 1.0e-8 + @test maximum(residual(V[:, j], found.frequency[j]) for j in 1:nev) < 1.0e-8 + @test minimum(svdvals(V)) / maximum(svdvals(V)) > 1.0e-6 + @test norm(V' * M * V - I) < 1.0e-6 + end + dense_check(1.0000005, 0.8777626842989034, 4; tol = 1.0e-12) # nearly repeated: the box is 5e-7 too tall + dense_check(1.0, 0.8777628447553723, 4; tol = 1.0e-12) # a lossless Rayleigh quotient with an imaginary roundoff + dense_check(1.0, 0.8777628447544944, 4; tol = 1.0e-12, krylovdim = 10_000) +end + @testset "lossy: nearest in complex ω, and the candidate bound holds" begin # eps_r = 1 - 100i scales ω by 1/√(1 - 100i): the lowest modes sit at Re f = 0.0592, 0.0794, 0.0854 with # Im f about as large. From 0.0854 the nearest in complex ω is the first, and shift-invert ranks the first