diff --git a/Project.toml b/Project.toml index 6e073bc8..cbd119f3 100644 --- a/Project.toml +++ b/Project.toml @@ -22,10 +22,12 @@ Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" [weakdeps] FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" +KrylovKit = "0b1a1467-8014-51b9-945f-bf0ae24f4b77" Meshes = "eacbb407-ea5a-433e-ab97-5258b1ca43fa" [extensions] FiniteElementMethodFerriteGmshExt = "FerriteGmsh" +FiniteElementMethodKrylovKitExt = "KrylovKit" FiniteElementMethodMeshesExt = "Meshes" [compat] @@ -37,6 +39,7 @@ Ferrite = "1.7" FerriteGmsh = "1.5" ForwardDiff = "1.4" Gmsh = "0.3" +KrylovKit = "0.10" LinearAlgebra = "1.10" ModelingToolkit = "11.34" LinearSolve = "5" @@ -61,6 +64,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" Meshes = "eacbb407-ea5a-433e-ab97-5258b1ca43fa" OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" @@ -71,4 +75,4 @@ SciMLTesting = "09d9d899-5365-40a9-917a-5f67fddea283" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["AllocCheck", "FerriteGmsh", "Gmsh", "LinearSolve", "Meshes", "OrdinaryDiffEqBDF", "OrdinaryDiffEqNonlinearSolve", "Random", "SafeTestsets", "SciMLTesting", "Test"] +test = ["AllocCheck", "FerriteGmsh", "Gmsh", "KrylovKit", "LinearSolve", "Meshes", "OrdinaryDiffEqBDF", "OrdinaryDiffEqNonlinearSolve", "Random", "SafeTestsets", "SciMLTesting", "Test"] diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 01d2277d..e20612cd 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(ω))`. 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 +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 390c330a..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: dot, mul!, norm +using LinearAlgebra: SingularException, Symmetric, dot, eigen, lu, mul!, norm, opnorm 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 @@ -55,8 +55,9 @@ export Weighted # 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..a41b82f0 --- /dev/null +++ b/src/maxwell/eigen.jl @@ -0,0 +1,375 @@ +# 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 + +# 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) + (; 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 + +# 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 + +# 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 + +# 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-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 + 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-11 && 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)) + +# 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 + 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 + end + 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. +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 = 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 +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 `ω`, and returns +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 +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. By default +`nullspace_tol = √eps(Float64)`, the relative precision to which an eigenvalue of the spectrum scale `‖Kc‖₁/‖Mε‖₁` +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 +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 +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, 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. +""" +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::Union{Nothing, Real} = nothing + ) + 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)")) + 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 + 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)) + 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] + # 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). 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 + # 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, 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 + σ0 = max(scale * ωt^2, λ_shift) + 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) + G = Gfull[free, _potential_dofs(dhn, model.grid, model.pec)] + 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))) + # Shift-invert finds the modes nearest σ in λ ∝ ω², which favours those below the target. Every mode with + # |ω - ω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 + # 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) + 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) + 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 + return + end + λ, vecs, keep, dense = search(op, x0, nev) + # 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 + 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) + extract() + end + end + 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 _ 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 + 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 + keep = selected[sortperm(real.(sqrt.(complex.(θ[selected]))))] + + 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.(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))])) + u = zeros(ComplexF64, n) + u[free] = v + MaxwellSolution(model, real(ω), u) + end + return (; frequency = real.(omega) ./ 2π, Q = quality, omega, modes) +end diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index d7fcd1fa..5f2b5d0c 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -147,10 +147,13 @@ end # Ferrite in the tests): Ferrite's own spellings of these are not public. const _TET_FACET_EDGE_DOFS = ((3, 2, 1), (1, 5, 4), (2, 6, 5), (4, 6, 3)) const _TET_FACET_NODES = ((1, 3, 2), (1, 2, 4), (2, 3, 4), (1, 4, 3)) +_tet_facet_dofs(::Ferrite.Nedelec{Ferrite.RefTetrahedron, 1}) = _TET_FACET_EDGE_DOFS +_tet_facet_dofs(::Ferrite.Lagrange{Ferrite.RefTetrahedron, 1}) = _TET_FACET_NODES -# The edge dofs on the PEC facets: the tangential traces there are exactly these dofs. -function _pec_dofs(dh, grid, pec) - local_dofs = _TET_FACET_EDGE_DOFS +# 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 = _tet_facet_dofs(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..f10cfe02 --- /dev/null +++ b/test/Maxwell/eigen.jl @@ -0,0 +1,374 @@ +# Eigenmodes of a PEC rectangular cavity against the analytic TE/TM frequencies. +using FiniteElementMethod, Ferrite, KrylovKit, LinearAlgebra, Random, 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 + # 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 "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 + # 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 = 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 "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 "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 "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 "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 "restart deflation with an indefinite form, and non-passive materials are rejected" begin + # 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) + 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 + +@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 "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 "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 + # 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) + @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 + 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 "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 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) + 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) + 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 diff --git a/test/Maxwell/model.jl b/test/Maxwell/model.jl index ed08d1e8..52b5ab93 100644 --- a/test/Maxwell/model.jl +++ b/test/Maxwell/model.jl @@ -179,3 +179,18 @@ end @test all(trace(j) > 1.0e-3 for j in on_facet) end end + +@testset "the linear Lagrange facet dofs are the facet nodes" begin + 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