From df895202bede635a188bbe9a53a2bb066faae979 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:13:23 +0000 Subject: [PATCH 01/21] Add TE10 wave ports, first-order ABC and S-parameter sweeps for Maxwell Rectangular-waveguide ports and Silver-Mueller absorbing facet sets enter the MaxwellModel as extra real blocks with frequency coefficients on the shared pattern. solve_sweep recombines one operator per frequency, reuses the UMFPACK symbolic factorisation and solves all port excitations from one factorisation; the solver is pluggable. Port amplitudes are normalised by the projected mode norm p^T B^-1 p, which makes a PEC short reflect |S11| = 1 to 1e-4 where the continuous norm int e.e gives 1e-2 errors. Validated against WR-90 closed forms. 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 | 5 +- src/maxwell/model.jl | 34 +++-- src/maxwell/ports.jl | 245 +++++++++++++++++++++++++++++++++++++ src/maxwell/sweep.jl | 59 +++++++++ test/Maxwell/ports.jl | 130 ++++++++++++++++++++ 5 files changed, 460 insertions(+), 13 deletions(-) create mode 100644 src/maxwell/ports.jl create mode 100644 src/maxwell/sweep.jl create mode 100644 test/Maxwell/ports.jl diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index f25a7a4e..9926afc6 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: cross, dot, lu, lu!, mul!, norm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -50,10 +50,13 @@ export FEMDiscretization, Galerkin, SUPG, add_boundary_pieces! 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/ports.jl") include("maxwell/model.jl") include("maxwell/driven.jl") +include("maxwell/sweep.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! export MaxwellSolution, driven_problem, solve_driven, field_values +export WavePort, MaxwellSweep, solve_sweep include("precompile.jl") diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index cf45c560..9cc61c74 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -43,8 +43,8 @@ struct MaxwellTerm end """ - MaxwellModel(grid; materials = Dict(), pec = String[], length_scale = 1.0, eps0 = EPS0, mu0 = MU0, - quadrature = 2) + MaxwellModel(grid; materials = Dict(), pec = String[], absorbing = String[], ports = WavePort[], + length_scale = 1.0, eps0 = EPS0, mu0 = MU0, quadrature = 2) The time-harmonic electric-field model on a Ferrite `grid` of `Tetrahedron` cells, with the field `:E` in `Nedelec{RefTetrahedron, 1}`. The equation, for fields varying as `exp(+iωt)`, is @@ -52,7 +52,9 @@ The time-harmonic electric-field model on a Ferrite `grid` of `Tetrahedron` cell ∇ × (μr⁻¹ ∇ × E) + iωμ0 σ E - ω² μ0 ε0 εr E = -iωμ0 J, with `n × E = 0` on the facet sets named in `pec` and the natural condition `n × (μr⁻¹ ∇ × E) = 0` on the -rest of the boundary. +rest of the boundary, except for the facet sets named in `absorbing`, which carry the first-order +Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εr/μr) n × (n × E)`, and the +[`WavePort`](@ref)s in `ports`. `materials` maps cell set names of `grid` (as `FerriteGmsh.togrid` makes from Gmsh physical groups) to [`MaxwellMaterial`](@ref)s; cells in no named set are vacuum, and a cell in two named sets is an error. @@ -65,11 +67,14 @@ sparse blocks on one sparsity pattern, each with a complex coefficient that is a A(ω) = Kc - ω² μ0 ε0 L² (Mε' + i Mε'') + iω μ0 L² Mσ, `Kc = ∫ μr⁻¹ ∇×Nᵢ ⋅ ∇×Nⱼ`, `Mε' = ∫ Re(εr) Nᵢ⋅Nⱼ`, `Mε'' = ∫ Im(εr) Nᵢ⋅Nⱼ` and `Mσ = ∫ σ Nᵢ⋅Nⱼ` over the -mesh (so `Im(εr) = -ε''` gives the `+iω²μ0ε0L² ε''` loss term). `A` is complex symmetric, not Hermitian. +mesh (so `Im(εr) = -ε''` gives the `+iω²μ0ε0L² ε''` loss term). The absorbing boundary adds +`+i k0 L ∮ sqrt(εr/μr) (n × Nᵢ)⋅(n × Nⱼ) dS` (`k0 = ω sqrt(μ0 ε0)`, material of the adjacent cell) and each +wave port `+i (β(ω)/μr) L ∮ (n × Nᵢ)⋅(n × Nⱼ) dS` over its face. `A` is complex symmetric, not Hermitian. Fields: `grid`, `dh`, `ch` (zero `AffineConstraint`s on the PEC edge dofs), `cellvalues`, `materials` (one per cell), `pec`, `eps0`, `mu0`, `length_scale`, `blocks` (the volume blocks `curlcurl`, `eps_real`, -`eps_imag` and `sigma` above) and `terms`, the [`MaxwellTerm`](@ref)s that [`maxwell_operator!`](@ref) +`eps_imag` and `sigma` above), `absorbing`, `ports` (the [`FiniteElementMethod.WavePortData`](@ref) in the +order given) and `terms`, the [`MaxwellTerm`](@ref)s that [`maxwell_operator!`](@ref) combines; [`FiniteElementMethod.add_term!`](@ref) appends further blocks, such as boundary terms. """ struct MaxwellModel{G, DH, CH, CV} @@ -84,19 +89,20 @@ struct MaxwellModel{G, DH, CH, CV} length_scale::Float64 blocks::NamedTuple{(:curlcurl, :eps_real, :eps_imag, :sigma), NTuple{4, SparseMatrixCSC{Float64, Int}}} terms::Vector{MaxwellTerm} + absorbing::Vector{String} + ports::Vector{WavePortData} end function MaxwellModel( - grid::Ferrite.Grid; materials = Dict{String, MaxwellMaterial}(), pec = String[], - length_scale::Real = 1.0, eps0::Real = EPS0, mu0::Real = MU0, quadrature::Int = 2 + grid::Ferrite.Grid; materials = Dict{String, MaxwellMaterial}(), pec = String[], absorbing = String[], + ports = WavePort[], length_scale::Real = 1.0, eps0::Real = EPS0, mu0::Real = MU0, quadrature::Int = 2 ) Ferrite.getcelltype(grid) === Ferrite.Tetrahedron || throw(ArgumentError("MaxwellModel needs a grid of Tetrahedron cells, got $(Ferrite.getcelltype(grid))")) pec = String.(collect(pec)) - for name in pec - haskey(grid.facetsets, name) || - throw(ArgumentError("no facet set $(repr(name)) in the grid; it has $(sort!(collect(keys(grid.facetsets))))")) - end + absorbing = String.(collect(absorbing)) + foreach(name -> _check_facetset(grid, name), pec) + foreach(name -> _check_facetset(grid, name), absorbing) cell_materials = _cell_materials(grid, materials) ip = _NEDELEC @@ -119,8 +125,12 @@ function MaxwellModel( MaxwellTerm(blocks.eps_imag, ω -> -im * k2 * ω^2), MaxwellTerm(blocks.sigma, ω -> im * mu0 * L2 * ω), ] + L = float(length_scale) + isempty(absorbing) || append!(terms, _absorbing_terms(dh, blocks.curlcurl, absorbing, cell_materials, mu0, eps0, L)) + port_data = WavePortData[_wave_port(port, dh, blocks.curlcurl, cell_materials, L, ch.prescribed_dofs) for port in ports] + append!(terms, [_port_term(data, mu0 * eps0, L) for data in port_data]) return MaxwellModel( - grid, dh, ch, cv, cell_materials, pec, float(eps0), float(mu0), float(length_scale), blocks, terms + grid, dh, ch, cv, cell_materials, pec, float(eps0), float(mu0), L, blocks, terms, absorbing, port_data ) end diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl new file mode 100644 index 00000000..2d5f07d6 --- /dev/null +++ b/src/maxwell/ports.jl @@ -0,0 +1,245 @@ +# Boundary terms of a MaxwellModel: tangential facet mass blocks, the first-order absorbing boundary and +# rectangular-waveguide TE10 wave ports. + +""" + WavePort(facetset; a_direction, e_direction = nothing, deembed = 0.0) + +A TE10 wave port of a rectangular waveguide on the planar boundary facet set `facetset` of a +[`MaxwellModel`](@ref). The port face must be the full guide cross-section, a rectangle with PEC on its rim, +filled with one lossless-or-dielectric material (no conductivity). + +`a_direction` is a vector along the broad wall (the side of length `a`); the mode is +`e = ê sin(π ξ / a)`, with `ξ` the distance from the edge of the rectangle along `a_direction` and `ê` the +in-plane unit vector perpendicular to it. By default `ê` is `n × â` with its sign chosen so that its largest +Cartesian component is positive, which gives both ends of a straight guide the same polarisation; pass +`e_direction` to fix it explicitly. `deembed` moves the reference plane of the port a distance (in mesh units) +from the port face into the device. +""" +struct WavePort + facetset::String + a_direction::Ferrite.Vec{3, Float64} + e_direction::Union{Nothing, Ferrite.Vec{3, Float64}} + deembed::Float64 +end +function WavePort(facetset; a_direction, e_direction = nothing, deembed::Real = 0.0) + e = e_direction === nothing ? nothing : Ferrite.Vec{3, Float64}(Tuple(e_direction)) + return WavePort(String(facetset), Ferrite.Vec{3, Float64}(Tuple(a_direction)), e, float(deembed)) +end + +""" + WavePortData + +A [`WavePort`](@ref) assembled on a [`MaxwellModel`](@ref), in `model.ports`. Fields: `port`, `block` (the +tangential mass `∮ (n × Nᵢ)⋅(n × Nⱼ) dS` of the port face), `profile` (`pᵢ = ∮ e⋅Nᵢ dS`), `norm` +(`pᵀ B⁻¹ p` over the unconstrained edge dofs of the face: `∮ e_h⋅e_h dS` of the L² projection `e_h` of the +mode onto the discrete tangential traces, so that a port-face field `c e_h` gives exactly `pᵀu / norm = c`), +`normal` (outward), `a`, `b` (mesh units), `kc` (`π / (a L)`, rad/m), +`eps_r` and `mu_r` of the port material. +""" +struct WavePortData + port::WavePort + block::SparseMatrixCSC{Float64, Int} + profile::Vector{Float64} + norm::Float64 + normal::Ferrite.Vec{3, Float64} + a::Float64 + b::Float64 + kc::Float64 + eps_r::ComplexF64 + mu_r::Float64 +end + +function _check_facetset(grid, name) + return haskey(grid.facetsets, name) || + throw(ArgumentError("no facet set $(repr(name)) in the grid; it has $(sort!(collect(keys(grid.facetsets))))")) +end + +_facet_values() = Ferrite.FacetValues(Ferrite.FacetQuadratureRule{RefTetrahedron}(2), _NEDELEC) + +# ∮ w (n × Nᵢ)⋅(n × Nⱼ) dS over the named facet sets, with a real weight per cell, on the pattern of `pattern`. +# Every edge dof of a facet belongs to the facet's cell, so the cell-based pattern holds every entry. +function _tangential_mass(dh, pattern, names, weight) + block = copy(pattern) + asm = Ferrite.start_assemble(block) + fv = _facet_values() + n = Ferrite.getnbasefunctions(fv) + Be = zeros(n, n) + for name in names, fc in Ferrite.FacetIterator(dh, Ferrite.getfacetset(dh.grid, name)) + Ferrite.reinit!(fv, fc) + fill!(Be, 0.0) + for q in 1:Ferrite.getnquadpoints(fv) + nq = Ferrite.getnormal(fv, q) + dS = Ferrite.getdetJdV(fv, q) + for i in 1:n, j in 1:n + Ni, Nj = Ferrite.shape_value(fv, q, i), Ferrite.shape_value(fv, q, j) + Be[i, j] += (dot(Ni, Nj) - dot(nq, Ni) * dot(nq, Nj)) * dS + end + end + Ferrite.assemble!(asm, Ferrite.celldofs(fc), weight(Ferrite.cellid(fc)) .* Be) + end + return block +end + +""" + tangential_mass(model::MaxwellModel, facetsets; weight = cell -> 1.0) + +The real block `∮ w (n × Nᵢ)⋅(n × Nⱼ) dS` over the named facet sets of `model.grid` (in mesh units), with the +weight `w = weight(cellid)` of the cell each facet belongs to, on the sparsity pattern of `model.blocks`, ready +for [`FiniteElementMethod.add_term!`](@ref). +""" +function tangential_mass(model, facetsets; weight = Returns(1.0)) + names = String.(collect(facetsets)) + foreach(name -> _check_facetset(model.grid, name), names) + return _tangential_mass(model.dh, model.blocks.curlcurl, names, weight) +end + +# First-order absorbing boundary n × (μr⁻¹ ∇ × E) = -i k0 ηr⁻¹ n × (n × E), ηr⁻¹ = sqrt(εr / μr) of the +# adjacent cell: the term +i k0 L ηr⁻¹ ∮ (n × E)⋅(n × v) dS, split into real blocks for real and imaginary ηr⁻¹. +function _absorbing_terms(dh, pattern, names, cell_materials, mu0, eps0, L) + y(cell) = sqrt(cell_materials[cell].eps_r / cell_materials[cell].mu_r) + k0L(ω) = ω * sqrt(mu0 * eps0) * L + terms = [MaxwellTerm(_tangential_mass(dh, pattern, names, real ∘ y), ω -> im * k0L(ω))] + imag_block = _tangential_mass(dh, pattern, names, imag ∘ y) + any(!iszero, nonzeros(imag_block)) && push!(terms, MaxwellTerm(imag_block, ω -> -k0L(ω) + 0im)) + return terms +end + +function _port_frame(port, normal) + a_dir = port.a_direction + abs(dot(a_dir, normal)) <= 1.0e-8 * norm(a_dir) || + throw(ArgumentError("a_direction of port $(repr(port.facetset)) is not in the port plane")) + â = a_dir / norm(a_dir) + if port.e_direction === nothing + ê = cross(normal, â) + ê = ê[argmax(abs.(Tuple(ê)))] < 0 ? -ê : ê + else + ê = port.e_direction / norm(port.e_direction) + abs(dot(ê, normal)) + abs(dot(ê, â)) <= 1.0e-8 || + throw(ArgumentError("e_direction of port $(repr(port.facetset)) must be in the port plane and normal to a_direction")) + end + return â, ê +end + +function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, constrained) + grid = dh.grid + _check_facetset(grid, port.facetset) + facets = Ferrite.getfacetset(grid, port.facetset) + isempty(facets) && throw(ArgumentError("port facet set $(repr(port.facetset)) is empty")) + fv = _facet_values() + # Geometry: one outward normal, the facet nodes and the area. + normal = nothing + nodes = Ferrite.Vec{3, Float64}[] + area = 0.0 + for fc in Ferrite.FacetIterator(dh, facets) + Ferrite.reinit!(fv, fc) + nq = Ferrite.getnormal(fv, 1) + normal === nothing && (normal = nq) + norm(nq - normal) <= 1.0e-8 || throw(ArgumentError("port facet set $(repr(port.facetset)) is not planar")) + area += sum(q -> Ferrite.getdetJdV(fv, q), 1:Ferrite.getnquadpoints(fv)) + end + for (cell, local_facet) in facets + x = Ferrite.getcoordinates(grid, cell) + append!(nodes, x[i] for i in Ferrite.reference_facets(RefTetrahedron)[local_facet]) + end + â, ê = _port_frame(port, normal) + ξ, η, ζ = [dot(x, â) for x in nodes], [dot(x, ê) for x in nodes], [dot(x, normal) for x in nodes] + (ξ0, ξ1), (η0, η1) = extrema(ξ), extrema(η) + a, b = ξ1 - ξ0, η1 - η0 + if maximum(ζ) - minimum(ζ) > 1.0e-8 * a || abs(area - a * b) > 1.0e-6 * a * b + throw(ArgumentError("port facet set $(repr(port.facetset)) is not a planar rectangle with a side along a_direction")) + end + materials = unique(cell_materials[f[1]] for f in facets) + length(materials) == 1 || throw(ArgumentError("port $(repr(port.facetset)) touches more than one material")) + material = only(materials) + iszero(material.sigma) || throw(ArgumentError("port $(repr(port.facetset)) is in a conducting material")) + + e(x) = ê * sin(π * (dot(x, â) - ξ0) / a) + profile = zeros(Ferrite.ndofs(dh)) + n = Ferrite.getnbasefunctions(fv) + pe = zeros(n) + for fc in Ferrite.FacetIterator(dh, facets) + Ferrite.reinit!(fv, fc) + x = Ferrite.getcoordinates(fc) + fill!(pe, 0.0) + for q in 1:Ferrite.getnquadpoints(fv) + eq = e(Ferrite.spatial_coordinate(fv, q, x)) + dS = Ferrite.getdetJdV(fv, q) + for i in 1:n + pe[i] += dot(eq, Ferrite.shape_value(fv, q, i)) * dS + end + end + Ferrite.assemble!(profile, Ferrite.celldofs(fc), pe) + end + block = _tangential_mass(dh, pattern, [port.facetset], Returns(1.0)) + free = setdiff(_pec_dofs(dh, grid, [port.facetset]), constrained) + norm_h = dot(profile[free], block[free, free] \ profile[free]) + return WavePortData(port, block, profile, norm_h, normal, a, b, π / (a * length_scale), material.eps_r, material.mu_r) +end + +# β = sqrt(k² - kc²) on the branch Im β ≤ 0, so that the outgoing exp(-iβζ) decays below cutoff. +function _propagation_constant(data::WavePortData, mu0eps0, ω) + β = sqrt(complex(ω^2 * mu0eps0 * data.eps_r * data.mu_r - data.kc^2)) + return imag(β) > 0 ? -β : β +end + +""" + propagation_constant(model::MaxwellModel, port, ω) + +The TE10 propagation constant `β` (rad/m) of wave port number `port` of `model` at angular frequency `ω`. +Below cutoff `β = -iα` with `α > 0`, so the mode `exp(-iβζ)` decays away from the port. +""" +propagation_constant(model, port::Integer, ω::Real) = + _propagation_constant(model.ports[port], model.mu0 * model.eps0, float(ω)) + +""" + cutoff_frequency(model::MaxwellModel, port) + +The TE10 cutoff frequency in Hz, `kc / (2π sqrt(μ0 ε0 Re(εr) μr))`, of wave port number `port` of `model`. +""" +function cutoff_frequency(model, port::Integer) + data = model.ports[port] + return data.kc / (2π * sqrt(model.mu0 * model.eps0 * real(data.eps_r) * data.mu_r)) +end + +# n × μr⁻¹∇ × E = -(iβ/μr) n × (n × E) - 2(iβ/μr) E0 e on the port gives +(iβ/μr) L B on the operator and +# +2(iβ/μr) L E0 p on the load, with E0 = 1. +function _port_term(data::WavePortData, mu0eps0, L) + return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, ω) * L / data.mu_r) +end + +""" + port_excitations(model::MaxwellModel, ω) + +The load vectors of the wave ports of `model` at `ω`, one column per port: the TE10 mode of unit amplitude +incident on that port, without the PEC constraints. +""" +function port_excitations(model, ω::Real) + B = zeros(ComplexF64, Ferrite.ndofs(model.dh), length(model.ports)) + for (j, data) in pairs(model.ports) + β = _propagation_constant(data, model.mu0 * model.eps0, float(ω)) + B[:, j] .= (2im * β * model.length_scale / data.mu_r) .* data.profile + end + return B +end + +""" + s_parameters(model::MaxwellModel, ω, U) + +The scattering matrix from the solutions `U[:, j]` with port `j` driven by [`port_excitations`](@ref): +`Sᵢⱼ = (pᵢᵀ uⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ Zⱼ / (Pⱼ Zᵢ)) exp(iβᵢdᵢ + iβⱼdⱼ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave +impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. +""" +function s_parameters(model, ω::Real, U::AbstractMatrix) + mu0eps0 = model.mu0 * model.eps0 + ports = model.ports + β = [_propagation_constant(data, mu0eps0, float(ω)) for data in ports] + # Power-wave scale: |a|² P / Z, with Z ∝ μr / β. + w = [sqrt(data.norm * β[i] / data.mu_r) for (i, data) in pairs(ports)] + shift = [exp(im * β[i] * data.port.deembed * model.length_scale) for (i, data) in pairs(ports)] + np = length(ports) + S = zeros(ComplexF64, np, np) + for j in 1:np, i in 1:np + S[i, j] = (dot(ports[i].profile, view(U, :, j)) / ports[i].norm - (i == j)) * w[i] / w[j] * shift[i] * shift[j] + end + return S +end diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl new file mode 100644 index 00000000..cfa7b01c --- /dev/null +++ b/src/maxwell/sweep.jl @@ -0,0 +1,59 @@ +# Frequency sweep of the wave-port scattering matrix of a MaxwellModel: one operator matrix recombined per +# frequency, one factorisation per frequency for all port excitations. + +""" + umfpack_solver(A, B, cache) -> (X, cache) + +The default linear solver of [`solve_sweep`](@ref): an UMFPACK LU factorisation of `A`, reusing the symbolic +analysis of the previous frequency (`cache`, `nothing` on the first call) since the pattern never changes, +applied to all columns of `B`. A replacement solver has the same signature. +""" +function umfpack_solver(A, B, cache) + F = cache === nothing ? lu(A) : lu!(cache, A) + return F \ B, F +end + +""" + MaxwellSweep + +The result of [`solve_sweep`](@ref): `omegas`, the scattering matrices `S[:, :, k]` at `omegas[k]` +(`S[i, j, k]` is the wave leaving port `i` for a unit wave incident on port `j`) and `fields`, either +`nothing` or, per frequency, the matrix whose column `j` is the edge-dof vector with port `j` driven (wrap it +with `MaxwellSolution(model, omegas[k], fields[k][:, j])`). +""" +struct MaxwellSweep + omegas::Vector{Float64} + S::Array{ComplexF64, 3} + fields::Union{Nothing, Vector{Matrix{ComplexF64}}} +end + +""" + solve_sweep(model::MaxwellModel, omegas; fields = false, solver = umfpack_solver) + +The scattering matrix of the [`WavePort`](@ref)s of `model` at each angular frequency in `omegas` (rad/s), +as a [`MaxwellSweep`](@ref). Each frequency recombines the nonzero values of one operator matrix with +[`maxwell_operator!`](@ref), applies the PEC constraints, and solves for all port excitations at once with +`solver(A, B, cache)` (see [`FiniteElementMethod.umfpack_solver`](@ref)), which may keep its factorisation +between frequencies in `cache`. `fields = true` keeps the solutions (`ndofs × nports` complex values per +frequency). +""" +function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = umfpack_solver) + isempty(model.ports) && throw(ArgumentError("the model has no wave ports")) + omegas = float.(collect(omegas)) + np = length(model.ports) + S = zeros(ComplexF64, np, np, length(omegas)) + kept = fields ? Matrix{ComplexF64}[] : nothing + A = maxwell_operator(model, first(omegas)) + prescribed = model.ch.prescribed_dofs + cache = nothing + for (k, ω) in pairs(omegas) + maxwell_operator!(A, model, ω) + Ferrite.apply!(A, model.ch) + B = port_excitations(model, ω) + B[prescribed, :] .= 0 # the PEC constraints are homogeneous + U, cache = solver(A, B, cache) + S[:, :, k] .= s_parameters(model, ω, U) + fields && push!(kept, U) + end + return MaxwellSweep(omegas, S, kept) +end diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl new file mode 100644 index 00000000..458f5e38 --- /dev/null +++ b/test/Maxwell/ports.jl @@ -0,0 +1,130 @@ +# WR-90 waveguide checks of the TE10 wave ports, the first-order absorbing boundary and the frequency sweep, +# against closed forms (exp(+iωt), ports at z = 0 and z = L, broad wall along x). +using FiniteElementMethod, Ferrite, SparseArrays, LinearAlgebra, Test + +const WR90_A, WR90_B = 22.86, 10.16 # mm +const F10 = 2π * 10.0e9 +const BETA10 = 158.2383 # rad/m, TE10 at 10 GHz +const K010 = F10 / FiniteElementMethod.C0 + +# A WR-90 section of length `len` mm with cells of about `h` mm; the bottom face z = 0 is a wave port, the top +# face a wave port too unless `top` names another termination. +function wr90(h, len; top = :port, kwargs...) + n = ceil.(Int, (WR90_A, WR90_B, len) ./ h) + grid = generate_grid(Tetrahedron, Tuple(n), Vec(0.0, 0.0, 0.0), Vec(WR90_A, WR90_B, float(len))) + walls = ["left", "right", "front", "back"] + ports = [WavePort("bottom"; a_direction = (1, 0, 0), kwargs...)] + top === :port && push!(ports, WavePort("top"; a_direction = (1, 0, 0), kwargs...)) + return MaxwellModel( + grid; pec = top === :pec ? [walls; "top"] : walls, absorbing = top === :abc ? ["top"] : String[], + ports, length_scale = 1.0e-3, + ) +end + +phase_deg(z) = rad2deg(angle(z)) +wrap_deg(x) = mod(x + 180, 360) - 180 + +@testset "facet blocks share the cell pattern" begin + model = wr90(5.0, 10.0) + B = FiniteElementMethod.tangential_mass(model, ["bottom", "top"]) + @test B.colptr == model.blocks.curlcurl.colptr && rowvals(B) == rowvals(model.blocks.curlcurl) + @test issymmetric(B) + # Each port block is the tangential mass of its own face. + @test model.ports[1].block + model.ports[2].block ≈ B + # The norm of the projected mode approaches ∮ e⋅e = ab/2 from below. + port = model.ports[1] + @test port.a ≈ WR90_A && port.b ≈ WR90_B && port.normal ≈ Vec(0.0, 0.0, -1.0) + @test 0.97 * WR90_A * WR90_B / 2 < port.norm < WR90_A * WR90_B / 2 +end + +@testset "TE10 mode constants" begin + model = wr90(5.0, 10.0) + @test FiniteElementMethod.cutoff_frequency(model, 1) ≈ 6.5571e9 rtol = 1.0e-4 + @test FiniteElementMethod.propagation_constant(model, 1, F10) ≈ BETA10 rtol = 1.0e-5 + # Below cutoff the mode decays away from the port: β = -iα. + β5 = FiniteElementMethod.propagation_constant(model, 2, 2π * 5.0e9) + @test real(β5) == 0 && imag(β5) ≈ -sqrt((π / 22.86e-3)^2 - (2π * 5.0e9 / FiniteElementMethod.C0)^2) + @test_throws "not in the port plane" wr90(5.0, 10.0; a_direction = (0, 0, 1)) + @test_throws "not a planar rectangle" MaxwellModel( + generate_grid(Tetrahedron, (2, 2, 2)); ports = [WavePort("bottom"; a_direction = (1, 1, 0))] + ) + @test_throws "no facet set" MaxwellModel(generate_grid(Tetrahedron, (2, 2, 2)); absorbing = ["nope"]) +end + +@testset "empty WR-90 guide, two ports" begin + len = 50.0 + for (h, tol_deg) in ((2.0, 2.0), (1.5, 1.0)) + model = wr90(h, len) + S = solve_sweep(model, [F10]).S[:, :, 1] + err = wrap_deg(phase_deg(S[2, 1]) - wrap_deg(-rad2deg(BETA10 * len * 1.0e-3))) + @info "WR-90 straight guide" h ndofs(model.dh) S[1, 1] abs(S[2, 1]) phase_deg(S[2, 1]) err + @test abs(S[1, 1]) < 0.05 && abs(S[2, 2]) < 0.05 + @test abs(S[2, 1]) ≈ 1 atol = 0.01 + @test abs(err) < tol_deg + @test S[1, 2] ≈ S[2, 1] rtol = 1.0e-8 + @test abs2(S[1, 1]) + abs2(S[2, 1]) ≈ 1 atol = 1.0e-3 + end + # De-embedding both reference planes to the middle of the guide leaves no transmission phase. + model = wr90(2.0, len; deembed = len / 2) + S = solve_sweep(model, [F10]).S[:, :, 1] + @test abs(S[2, 1] - 1) < 0.05 +end + +@testset "evanescent TE10 below cutoff" begin + len = 10.0 + model = wr90(2.0, len) + ω = 2π * 5.0e9 + α = -imag(FiniteElementMethod.propagation_constant(model, 1, ω)) + S = solve_sweep(model, [ω]).S[:, :, 1] + @info "WR-90 below cutoff" S exp(-α * len * 1.0e-3) + @test S[2, 1] ≈ exp(-α * len * 1.0e-3) rtol = 0.03 + @test abs(S[1, 1]) < 0.03 +end + +@testset "absorbing boundary terminating a guide" begin + len = 30.0 + model = wr90(2.0, len; top = :abc) + S11 = only(solve_sweep(model, [F10]).S) + Γ = (BETA10 - K010) / (BETA10 + K010) + expected = Γ * exp(-2im * BETA10 * len * 1.0e-3) + @info "WR-90 with ABC" S11 abs(S11) Γ expected wrap_deg(phase_deg(S11) - phase_deg(expected)) + @test Γ ≈ -0.1396 atol = 1.0e-4 + @test abs(S11) ≈ abs(Γ) rtol = 0.03 + @test abs(wrap_deg(phase_deg(S11) - phase_deg(expected))) < 3 + # A PEC short instead reflects everything: S11 = -exp(-2iβL). + S11 = only(solve_sweep(wr90(2.0, len; top = :pec), [F10]).S) + @test abs(S11) ≈ 1 atol = 1.0e-3 + @test abs(wrap_deg(phase_deg(S11) - phase_deg(-exp(-2im * BETA10 * len * 1.0e-3)))) < 3 +end + +@testset "sweep equals single-frequency solves" begin + model = wr90(3.0, 30.0) + ωs = 2π .* [8.0e9, 10.0e9, 12.0e9] + calls = Symbol[] + function counting(A, B, cache) + push!(calls, cache === nothing ? :lu : :refactor) + return FiniteElementMethod.umfpack_solver(A, B, cache) + end + sweep = solve_sweep(model, ωs; fields = true, solver = counting) + @test calls == [:lu, :refactor, :refactor] + @test size(sweep.S) == (2, 2, 3) && length(sweep.fields) == 3 + @test solve_sweep(model, ωs).fields === nothing + for (k, ω) in pairs(ωs) + # An independent solve: a fresh operator, constraints and factorisation. + A = maxwell_operator(model, ω) + B = FiniteElementMethod.port_excitations(model, ω) + for j in axes(B, 2) + b = B[:, j] + Aj = copy(A) + apply!(Aj, b, model.ch) + @test Aj \ b ≈ sweep.fields[k][:, j] rtol = 1.0e-10 + end + @test solve_sweep(model, [ω]).S[:, :, 1] ≈ sweep.S[:, :, k] rtol = 1.0e-10 + end + # The driven field is the TE10 mode, E_y ∝ sin(πx/a). + sol = MaxwellSolution(model, ωs[2], sweep.fields[2][:, 1]) + E = field_values(sol, [Vec(WR90_A / 2, WR90_B / 2, 0.0), Vec(WR90_A / 8, WR90_B / 2, 0.0)]).E + @test abs(E[1][2]) ≈ abs(1 + sweep.S[1, 1, 2]) rtol = 0.05 # incident plus reflected at the port face + @test abs(E[2][2]) / abs(E[1][2]) ≈ sin(π / 8) rtol = 0.1 + @test_throws "no wave ports" solve_sweep(MaxwellModel(generate_grid(Tetrahedron, (1, 1, 1))), [1.0]) +end From 2872585aba35e884997701467d09bf39c3f44607 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:13:23 +0000 Subject: [PATCH 02/21] Document wave ports, absorbing boundaries and sweeps A short WR-90 example of the sweep API in docs/src/maxwell.md. 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 --- docs/src/maxwell.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 01d2277d..b20c3ebb 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -30,6 +30,31 @@ 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!`. +## Wave ports, absorbing boundaries and frequency sweeps + +Rectangular-waveguide ports and first-order absorbing boundaries are model keywords. A [`WavePort`](@ref) +on a planar boundary facet set launches and absorbs the TE10 mode of the rectangle it spans; `a_direction` +names the broad wall. Facet sets in `absorbing` get the first-order Silver-Müller condition +`n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εr/μr) n × (n × E)`, exact for a plane wave at normal incidence (a TE10 wave +reflects `Γ = (β - k0)/(β + k0)` from it). [`solve_sweep`](@ref) returns the scattering matrix at each +angular frequency; it keeps one operator matrix and one factorisation pattern, and solves every port's +excitation from a single factorisation per frequency. The linear solver is the `solver` keyword (see +[`FiniteElementMethod.umfpack_solver`](@ref)). + +```julia +using FiniteElementMethod, Ferrite +# A 50 mm section of WR-90 (22.86 mm × 10.16 mm), mesh in millimetres. +grid = generate_grid(Tetrahedron, (16, 7, 34), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 50.0)) +ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("top"; a_direction = (1, 0, 0))] +model = MaxwellModel(grid; pec = ["left", "right", "front", "back"], ports, length_scale = 1.0e-3) +sweep = solve_sweep(model, 2π .* (8.0e9:0.5e9:12.0e9)) +sweep.S[2, 1, 5] # S21 at 10 GHz: |S21| ≈ 1, angle ≈ -93.3° +``` + +`Sᵢⱼ` is referred to the port faces, or to planes `deembed` mesh units inside them. Ports on different guides +are normalised to power waves through the TE10 wave impedance `ωμ0μr/β`. Below cutoff the propagation +constant is `β = -iα`, the evanescent branch. + ```@docs MaxwellModel MaxwellMaterial @@ -42,6 +67,16 @@ MaxwellSolution field_values FiniteElementMethod.maxwell_rhs FiniteElementMethod.add_term! +WavePort +FiniteElementMethod.WavePortData +solve_sweep +MaxwellSweep +FiniteElementMethod.umfpack_solver +FiniteElementMethod.tangential_mass +FiniteElementMethod.port_excitations +FiniteElementMethod.s_parameters +FiniteElementMethod.propagation_constant +FiniteElementMethod.cutoff_frequency FiniteElementMethod.EPS0 FiniteElementMethod.MU0 FiniteElementMethod.C0 From 71321bb097de56f9e6474fcf0e59e68b82f20ad3 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:27:25 +0000 Subject: [PATCH 03/21] Use the complex permittivity on absorbing faces and require a PEC port rim The ABC admittance now uses eps_c = eps_r - i sigma/(omega eps0) of each adjacent material, one block per material, so a conducting load sees the same impedance in the volume and on the ABC; validated against a transmission-line closed form for a WR-90 guide with a conducting section. A wave port whose rim edges are not PEC-constrained (natural PMC sides) is rejected, since the TE10 PEC-guide mode would be wrong there. Addresses review findings. 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 --- docs/src/maxwell.md | 2 +- src/maxwell/model.jl | 4 ++-- src/maxwell/ports.jl | 25 +++++++++++++++++-------- test/Maxwell/ports.jl | 35 +++++++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 11 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index b20c3ebb..d8a26f53 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 Rectangular-waveguide ports and first-order absorbing boundaries are model keywords. A [`WavePort`](@ref) on a planar boundary facet set launches and absorbs the TE10 mode of the rectangle it spans; `a_direction` names the broad wall. Facet sets in `absorbing` get the first-order Silver-Müller condition -`n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εr/μr) n × (n × E)`, exact for a plane wave at normal incidence (a TE10 wave +`n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` (`εc = εr - iσ/(ωε0)` of the adjacent material), exact for a plane wave at normal incidence (a TE10 wave reflects `Γ = (β - k0)/(β + k0)` from it). [`solve_sweep`](@ref) returns the scattering matrix at each angular frequency; it keeps one operator matrix and one factorisation pattern, and solves every port's excitation from a single factorisation per frequency. The linear solver is the `solver` keyword (see diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 9cc61c74..a64fabe7 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -53,7 +53,7 @@ The time-harmonic electric-field model on a Ferrite `grid` of `Tetrahedron` cell with `n × E = 0` on the facet sets named in `pec` and the natural condition `n × (μr⁻¹ ∇ × E) = 0` on the rest of the boundary, except for the facet sets named in `absorbing`, which carry the first-order -Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εr/μr) n × (n × E)`, and the +Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)`, and the [`WavePort`](@ref)s in `ports`. `materials` maps cell set names of `grid` (as `FerriteGmsh.togrid` makes from Gmsh physical groups) to @@ -68,7 +68,7 @@ sparse blocks on one sparsity pattern, each with a complex coefficient that is a `Kc = ∫ μr⁻¹ ∇×Nᵢ ⋅ ∇×Nⱼ`, `Mε' = ∫ Re(εr) Nᵢ⋅Nⱼ`, `Mε'' = ∫ Im(εr) Nᵢ⋅Nⱼ` and `Mσ = ∫ σ Nᵢ⋅Nⱼ` over the mesh (so `Im(εr) = -ε''` gives the `+iω²μ0ε0L² ε''` loss term). The absorbing boundary adds -`+i k0 L ∮ sqrt(εr/μr) (n × Nᵢ)⋅(n × Nⱼ) dS` (`k0 = ω sqrt(μ0 ε0)`, material of the adjacent cell) and each +`+i k0 L ∮ sqrt(εc/μr) (n × Nᵢ)⋅(n × Nⱼ) dS` (`k0 = ω sqrt(μ0 ε0)`, material of the adjacent cell) and each wave port `+i (β(ω)/μr) L ∮ (n × Nᵢ)⋅(n × Nⱼ) dS` over its face. `A` is complex symmetric, not Hermitian. Fields: `grid`, `dh`, `ch` (zero `AffineConstraint`s on the PEC edge dofs), `cellvalues`, `materials` (one diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 2d5f07d6..0f81fdeb 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -93,15 +93,14 @@ function tangential_mass(model, facetsets; weight = Returns(1.0)) return _tangential_mass(model.dh, model.blocks.curlcurl, names, weight) end -# First-order absorbing boundary n × (μr⁻¹ ∇ × E) = -i k0 ηr⁻¹ n × (n × E), ηr⁻¹ = sqrt(εr / μr) of the -# adjacent cell: the term +i k0 L ηr⁻¹ ∮ (n × E)⋅(n × v) dS, split into real blocks for real and imaginary ηr⁻¹. +# First-order absorbing boundary n × (μr⁻¹ ∇ × E) = -i k0 ηr⁻¹ n × (n × E), with ηr⁻¹ = sqrt(εc / μr) and +# εc = εr - iσ/(ωε0) of the adjacent cell: the term +i k0 L ηr⁻¹ ∮ (n × E)⋅(n × v) dS, one block per material. function _absorbing_terms(dh, pattern, names, cell_materials, mu0, eps0, L) - y(cell) = sqrt(cell_materials[cell].eps_r / cell_materials[cell].mu_r) - k0L(ω) = ω * sqrt(mu0 * eps0) * L - terms = [MaxwellTerm(_tangential_mass(dh, pattern, names, real ∘ y), ω -> im * k0L(ω))] - imag_block = _tangential_mass(dh, pattern, names, imag ∘ y) - any(!iszero, nonzeros(imag_block)) && push!(terms, MaxwellTerm(imag_block, ω -> -k0L(ω) + 0im)) - return terms + materials = unique(cell_materials[facet[1]] for name in names for facet in Ferrite.getfacetset(dh.grid, name)) + return map(materials) do m + block = _tangential_mass(dh, pattern, names, cell -> Float64(cell_materials[cell] == m)) + MaxwellTerm(block, ω -> im * ω * sqrt(mu0 * eps0) * L * sqrt((m.eps_r - im * m.sigma / (ω * eps0)) / m.mu_r)) + end end function _port_frame(port, normal) @@ -171,6 +170,16 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c Ferrite.assemble!(profile, Ferrite.celldofs(fc), pe) end block = _tangential_mass(dh, pattern, [port.facetset], Returns(1.0)) + # The TE10 mode needs a PEC rim: every edge dof on just one port facet must be constrained. + count = Dict{Int, Int}() + for (cell, local_facet) in facets + cell_dofs = Ferrite.celldofs(dh, cell) + for i in Ferrite.dirichlet_facetdof_indices(_NEDELEC)[local_facet] + count[cell_dofs[i]] = get(count, cell_dofs[i], 0) + 1 + end + end + all(dof -> count[dof] > 1 || dof in constrained, keys(count)) || + throw(ArgumentError("the rim of port $(repr(port.facetset)) is not PEC; name the guide walls in `pec`")) free = setdiff(_pec_dofs(dh, grid, [port.facetset]), constrained) norm_h = dot(profile[free], block[free, free] \ profile[free]) return WavePortData(port, block, profile, norm_h, normal, a, b, π / (a * length_scale), material.eps_r, material.mu_r) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 458f5e38..b739026f 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -128,3 +128,38 @@ end @test abs(E[2][2]) / abs(E[1][2]) ≈ sin(π / 8) rtol = 0.1 @test_throws "no wave ports" solve_sweep(MaxwellModel(generate_grid(Tetrahedron, (1, 1, 1))), [1.0]) end + +@testset "port rim must be PEC" begin + grid = generate_grid(Tetrahedron, (4, 2, 4), Vec(0.0, 0.0, 0.0), Vec(WR90_A, WR90_B, 20.0)) + @test_throws "is not PEC" MaxwellModel(grid; ports = [WavePort("bottom"; a_direction = (1, 0, 0))]) + @test_throws "is not PEC" MaxwellModel( + grid; pec = ["left", "right", "front"], ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + ) +end + +# Transmission-line answer for a vacuum guide (port at z = 0) with a lossy filling over the last `len2` mm and +# the ABC of admittance `y_abc` (k0 sqrt(εc) for the correct ABC) at its end; E-field admittances scale with β. +function lossy_abc_s11(len1, len2, εc, y_abc = K010 * sqrt(εc)) + β2 = sqrt(complex(K010^2 * εc - (π / (WR90_A * 1.0e-3))^2)) + β2 = imag(β2) > 0 ? -β2 : β2 + Γ2 = (β2 - y_abc) / (β2 + y_abc) * exp(-2im * β2 * len2 * 1.0e-3) + y = β2 * (1 - Γ2) / (1 + Γ2) + return (BETA10 - y) / (BETA10 + y) * exp(-2im * BETA10 * len1 * 1.0e-3) +end + +@testset "absorbing boundary on a conducting material" begin + len1, len2, σ = 20.0, 10.0, 0.2 + εc = 1 - im * σ / (F10 * FiniteElementMethod.EPS0) + grid = generate_grid(Tetrahedron, (12, 6, 15), Vec(0.0, 0.0, 0.0), Vec(WR90_A, WR90_B, len1 + len2)) + addcellset!(grid, "lossy", x -> x[3] >= len1 - 1.0e-9) + model = MaxwellModel( + grid; materials = Dict("lossy" => MaxwellMaterial(; sigma = σ)), pec = ["left", "right", "front", "back"], + absorbing = ["top"], ports = [WavePort("bottom"; a_direction = (1, 0, 0))], length_scale = 1.0e-3, + ) + S11 = only(solve_sweep(model, [F10]).S) + expected = lossy_abc_s11(len1, len2, εc) + ignoring_σ = lossy_abc_s11(len1, len2, εc, K010) # an ABC blind to the conductivity of its cells + @info "WR-90 ABC on a conducting load" εc S11 expected abs(S11 - expected) abs(ignoring_σ - expected) + @test abs(S11 - expected) < 0.01 + @test abs(ignoring_σ - expected) > 0.03 +end From 0aca6b3e76e216bdec058eba125f1873971ba456 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:34:06 +0000 Subject: [PATCH 04/21] Reject wave ports whose face is also PEC-constrained A port facet set that is also listed in pec has no free edge dofs, so its projected mode norm is zero and the sweep returned NaN. Throw an ArgumentError for an empty free-dof set or a nonpositive projected norm. Addresses a review finding. 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/ports.jl | 2 ++ test/Maxwell/ports.jl | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 0f81fdeb..94a5d973 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -181,7 +181,9 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c all(dof -> count[dof] > 1 || dof in constrained, keys(count)) || throw(ArgumentError("the rim of port $(repr(port.facetset)) is not PEC; name the guide walls in `pec`")) free = setdiff(_pec_dofs(dh, grid, [port.facetset]), constrained) + isempty(free) && throw(ArgumentError("every edge dof of port $(repr(port.facetset)) is PEC-constrained; a port face cannot also be in `pec`")) norm_h = dot(profile[free], block[free, free] \ profile[free]) + norm_h > 0 || throw(ArgumentError("the TE10 mode of port $(repr(port.facetset)) has no projection onto its free edge dofs")) return WavePortData(port, block, profile, norm_h, normal, a, b, π / (a * length_scale), material.eps_r, material.mu_r) end diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index b739026f..bcfefd5e 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -135,6 +135,10 @@ end @test_throws "is not PEC" MaxwellModel( grid; pec = ["left", "right", "front"], ports = [WavePort("bottom"; a_direction = (1, 0, 0))] ) + @test_throws "cannot also be in `pec`" MaxwellModel( + generate_grid(Tetrahedron, (2, 2, 2)); pec = ["left", "right", "front", "back", "bottom"], + ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + ) end # Transmission-line answer for a vacuum guide (port at z = 0) with a lossy filling over the last `len2` mm and From 212444fb852242b3f0535d0386ddcf2ed8807e34 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 21:10:18 +0000 Subject: [PATCH 05/21] Throw at exact port cutoff instead of returning NaN S-parameters At beta = 0 the TE10 wave impedance is infinite and the power-wave scale of s_parameters is 0/0, which filled the scattering matrix with NaN. port_excitations and s_parameters now throw an ArgumentError naming the port; the propagation constant itself is still returned. 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 (cherry picked from commit cabdd93fa2f5d8e3aedc53e525a6b954ef27ef13) --- src/maxwell/ports.jl | 21 ++++++++++++++++----- test/Maxwell/ports.jl | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 94a5d973..722b7097 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -218,6 +218,17 @@ function _port_term(data::WavePortData, mu0eps0, L) return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, ω) * L / data.mu_r) end +# The propagation constants of all ports at ω. At exact cutoff β = 0, the wave impedance ωμ/β is infinite and the +# power-wave scale of the S-parameters is 0/0, so it is an error rather than a NaN matrix. +function _port_betas(model, ω) + β = [_propagation_constant(data, model.mu0 * model.eps0, float(ω)) for data in model.ports] + j = findfirst(iszero, β) + j === nothing || throw( + ArgumentError("ω = $ω is exactly the TE10 cutoff of wave port $j, where its wave impedance is infinite and its S-parameters are undefined; use a nearby frequency") + ) + return β +end + """ port_excitations(model::MaxwellModel, ω) @@ -226,9 +237,9 @@ incident on that port, without the PEC constraints. """ function port_excitations(model, ω::Real) B = zeros(ComplexF64, Ferrite.ndofs(model.dh), length(model.ports)) + β = _port_betas(model, ω) for (j, data) in pairs(model.ports) - β = _propagation_constant(data, model.mu0 * model.eps0, float(ω)) - B[:, j] .= (2im * β * model.length_scale / data.mu_r) .* data.profile + B[:, j] .= (2im * β[j] * model.length_scale / data.mu_r) .* data.profile end return B end @@ -238,12 +249,12 @@ end The scattering matrix from the solutions `U[:, j]` with port `j` driven by [`port_excitations`](@ref): `Sᵢⱼ = (pᵢᵀ uⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ Zⱼ / (Pⱼ Zᵢ)) exp(iβᵢdᵢ + iβⱼdⱼ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave -impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. +impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. At exactly a port's cutoff `βᵢ = 0`, `Zᵢ` is +infinite and the S-parameters are undefined, so this throws an `ArgumentError`. """ function s_parameters(model, ω::Real, U::AbstractMatrix) - mu0eps0 = model.mu0 * model.eps0 ports = model.ports - β = [_propagation_constant(data, mu0eps0, float(ω)) for data in ports] + β = _port_betas(model, ω) # Power-wave scale: |a|² P / Z, with Z ∝ μr / β. w = [sqrt(data.norm * β[i] / data.mu_r) for (i, data) in pairs(ports)] shift = [exp(im * β[i] * data.port.deembed * model.length_scale) for (i, data) in pairs(ports)] diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index bcfefd5e..4b7da5d7 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -70,6 +70,20 @@ end @test abs(S[2, 1] - 1) < 0.05 end +@testset "exactly at cutoff the wave impedance is infinite: a clear error, not NaN" begin + # With eps0 = mu0 = 1 and unit scale, ω = kc is exactly the cutoff and β is exactly zero. + grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + model = MaxwellModel( + grid; pec = ["left", "right", "front", "back"], eps0 = 1.0, mu0 = 1.0, + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("top"; a_direction = (1, 0, 0))], + ) + ωc = model.ports[1].kc + @test FiniteElementMethod.propagation_constant(model, 1, ωc) == 0 + @test_throws "cutoff of wave port 1" solve_sweep(model, [ωc]) + @test_throws "cutoff of wave port 1" FiniteElementMethod.port_excitations(model, ωc) + @test all(isfinite, solve_sweep(model, [ωc * (1 + 1.0e-6)]).S) +end + @testset "evanescent TE10 below cutoff" begin len = 10.0 model = wr90(2.0, len) From c300959f765d0cd7394d9378ebadc89acd97a5af Mon Sep 17 00:00:00 2001 From: t Date: Wed, 11 Nov 2026 23:00:23 +0000 Subject: [PATCH 06/21] Sweep and ports: copy stored fields, reject lossy and doubly-assigned port faces, finite absorbing operator at zero frequency solve_sweep stores a copy of each solution, so a solver that reuses its output matrix cannot alias the frequencies; an empty frequency vector gives an empty sweep. A wave port in a material with complex eps_r is rejected with an ArgumentError (the power-wave normalisation holds only for a real wave impedance), as is a facet set that is both absorbing and a port. The absorbing coefficient is 0 at omega = 0 instead of 0/0. The tetrahedron facet tables replace the non-public Ferrite.reference_facets and dirichlet_facetdof_indices in ports.jl. 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 | 4 ++++ src/maxwell/model.jl | 4 ++++ src/maxwell/ports.jl | 17 +++++++++---- src/maxwell/sweep.jl | 5 ++-- test/Maxwell/ports.jl | 56 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 80 insertions(+), 6 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index d8a26f53..6e553687 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -55,6 +55,10 @@ sweep.S[2, 1, 5] # S21 at 10 GHz: |S21| ≈ 1, angle ≈ -93.3° are normalised to power waves through the TE10 wave impedance `ωμ0μr/β`. Below cutoff the propagation constant is `β = -iα`, the evanescent branch. +A port must lie in a lossless material: a complex `eps_r` or a nonzero conductivity at a port is rejected, because the +power-wave normalisation above holds for a real wave impedance. Put loss behind the port, not in its face, and a +facet set cannot be both a port and `absorbing`. + ```@docs MaxwellModel MaxwellMaterial diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index c5c8d15c..6497336e 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -103,6 +103,10 @@ function MaxwellModel( absorbing = String.(collect(absorbing)) foreach(name -> _check_facetset(grid, name), pec) foreach(name -> _check_facetset(grid, name), absorbing) + for port in ports, name in absorbing + isdisjoint(Ferrite.getfacetset(grid, name), Ferrite.getfacetset(grid, port.facetset)) || + throw(ArgumentError("facet sets $(repr(name)) and $(repr(port.facetset)) share facets: a facet cannot be both absorbing and a wave port")) + end cell_materials = _cell_materials(grid, materials) ip = _NEDELEC diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 722b7097..d95188d7 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -34,7 +34,7 @@ tangential mass `∮ (n × Nᵢ)⋅(n × Nⱼ) dS` of the port face), `profile` (`pᵀ B⁻¹ p` over the unconstrained edge dofs of the face: `∮ e_h⋅e_h dS` of the L² projection `e_h` of the mode onto the discrete tangential traces, so that a port-face field `c e_h` gives exactly `pᵀu / norm = c`), `normal` (outward), `a`, `b` (mesh units), `kc` (`π / (a L)`, rad/m), -`eps_r` and `mu_r` of the port material. +`eps_r` and `mu_r` of the port material (lossless: complex `eps_r` is rejected). """ struct WavePortData port::WavePort @@ -99,10 +99,17 @@ function _absorbing_terms(dh, pattern, names, cell_materials, mu0, eps0, L) materials = unique(cell_materials[facet[1]] for name in names for facet in Ferrite.getfacetset(dh.grid, name)) return map(materials) do m block = _tangential_mass(dh, pattern, names, cell -> Float64(cell_materials[cell] == m)) - MaxwellTerm(block, ω -> im * ω * sqrt(mu0 * eps0) * L * sqrt((m.eps_r - im * m.sigma / (ω * eps0)) / m.mu_r)) + # The coefficient is ω √εc with εc ~ 1/ω for a conductor, so it tends to 0 as ω → 0. + MaxwellTerm( + block, + ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * L * sqrt((m.eps_r - im * m.sigma / (ω * eps0)) / m.mu_r) + ) end end +# The local nodes of each face of a tetrahedron, in Ferrite's facet order (checked against Ferrite in the tests). +const _TET_FACET_NODES = ((1, 3, 2), (1, 2, 4), (2, 3, 4), (1, 4, 3)) + function _port_frame(port, normal) a_dir = port.a_direction abs(dot(a_dir, normal)) <= 1.0e-8 * norm(a_dir) || @@ -138,7 +145,7 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c end for (cell, local_facet) in facets x = Ferrite.getcoordinates(grid, cell) - append!(nodes, x[i] for i in Ferrite.reference_facets(RefTetrahedron)[local_facet]) + append!(nodes, x[i] for i in _TET_FACET_NODES[local_facet]) end â, ê = _port_frame(port, normal) ξ, η, ζ = [dot(x, â) for x in nodes], [dot(x, ê) for x in nodes], [dot(x, normal) for x in nodes] @@ -151,6 +158,8 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c length(materials) == 1 || throw(ArgumentError("port $(repr(port.facetset)) touches more than one material")) material = only(materials) iszero(material.sigma) || throw(ArgumentError("port $(repr(port.facetset)) is in a conducting material")) + iszero(imag(material.eps_r)) || + throw(ArgumentError("port $(repr(port.facetset)) is in a lossy material (complex eps_r); the S-parameter power normalisation of a wave port assumes a lossless one")) e(x) = ê * sin(π * (dot(x, â) - ξ0) / a) profile = zeros(Ferrite.ndofs(dh)) @@ -174,7 +183,7 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c count = Dict{Int, Int}() for (cell, local_facet) in facets cell_dofs = Ferrite.celldofs(dh, cell) - for i in Ferrite.dirichlet_facetdof_indices(_NEDELEC)[local_facet] + for i in _TET_FACET_EDGE_DOFS[local_facet] count[cell_dofs[i]] = get(count, cell_dofs[i], 0) + 1 end end diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl index cfa7b01c..d539403c 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -35,7 +35,7 @@ as a [`MaxwellSweep`](@ref). Each frequency recombines the nonzero values of one [`maxwell_operator!`](@ref), applies the PEC constraints, and solves for all port excitations at once with `solver(A, B, cache)` (see [`FiniteElementMethod.umfpack_solver`](@ref)), which may keep its factorisation between frequencies in `cache`. `fields = true` keeps the solutions (`ndofs × nports` complex values per -frequency). +frequency). An empty `omegas` gives an empty sweep. """ function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = umfpack_solver) isempty(model.ports) && throw(ArgumentError("the model has no wave ports")) @@ -43,6 +43,7 @@ function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = np = length(model.ports) S = zeros(ComplexF64, np, np, length(omegas)) kept = fields ? Matrix{ComplexF64}[] : nothing + isempty(omegas) && return MaxwellSweep(omegas, S, kept) A = maxwell_operator(model, first(omegas)) prescribed = model.ch.prescribed_dofs cache = nothing @@ -53,7 +54,7 @@ function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = B[prescribed, :] .= 0 # the PEC constraints are homogeneous U, cache = solver(A, B, cache) S[:, :, k] .= s_parameters(model, ω, U) - fields && push!(kept, U) + fields && push!(kept, copy(U)) end return MaxwellSweep(omegas, S, kept) end diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 4b7da5d7..c60634e6 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -181,3 +181,59 @@ end @test abs(S11 - expected) < 0.01 @test abs(ignoring_σ - expected) > 0.03 end + +@testset "sweep keeps an independent field per frequency, even from a solver that reuses its output" begin + model = wr90(5.0, 10.0) + ωs = F10 .* [0.9, 1.1] + reused = Matrix{ComplexF64}(undef, 0, 0) + function one_buffer_solver(A, B, cache) + U, cache = FiniteElementMethod.umfpack_solver(A, B, cache) + size(reused) == size(U) || (reused = similar(U)) + copyto!(reused, U) + return reused, cache + end + sweep = solve_sweep(model, ωs; fields = true, solver = one_buffer_solver) + fresh = [solve_sweep(model, [ω]; fields = true).fields[1] for ω in ωs] + @test sweep.fields[1] !== sweep.fields[2] + @test sweep.fields[1] ≈ fresh[1] && sweep.fields[2] ≈ fresh[2] +end + +@testset "an empty frequency vector gives an empty sweep" begin + sweep = solve_sweep(wr90(5.0, 10.0), Float64[]; fields = true) + @test isempty(sweep.omegas) && size(sweep.S) == (2, 2, 0) && isempty(sweep.fields) +end + +@testset "the absorbing operator is finite at ω = 0" begin + grid = generate_grid(Tetrahedron, (1, 1, 1)) + addcellset!(grid, "all", x -> true) + for material in (MaxwellMaterial(), MaxwellMaterial(; sigma = 0.5)) + m = MaxwellModel(grid; absorbing = ["top"], materials = Dict("all" => material), eps0 = 1.0, mu0 = 1.0) + @test all(isfinite, maxwell_operator(m, 0.0).nzval) + end +end + +@testset "lossy port materials are rejected" begin + grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + addcellset!(grid, "lossy", x -> x[3] >= 0.0) + walls = ["left", "right", "front", "back"] + @test_throws "lossy" MaxwellModel( + grid; pec = walls, eps0 = 1.0, mu0 = 1.0, materials = Dict("lossy" => MaxwellMaterial(; eps_r = 1 - 2im)), + ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + ) +end + +@testset "a facet set cannot be both absorbing and a wave port" begin + grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + addfacetset!(grid, "bottom_alias", x -> x[3] ≈ 0.0) + walls = ["left", "right", "front", "back"] + for name in ("bottom", "bottom_alias") + @test_throws "absorbing and a wave port" MaxwellModel( + grid; pec = walls, eps0 = 1.0, mu0 = 1.0, absorbing = [name], + ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + ) + end +end + +@testset "tetrahedron facet tables match Ferrite" begin + @test FiniteElementMethod._TET_FACET_NODES == Ferrite.reference_facets(RefTetrahedron) +end From 39c7c5f35fc72257fb1e780d7909bd0cc5694323 Mon Sep 17 00:00:00 2001 From: t Date: Wed, 11 Nov 2026 23:24:06 +0000 Subject: [PATCH 07/21] Reject any two overlapping absorbing or wave-port facet sets A facet in two boundary conditions got both terms; pairwise facet overlap (including aliases and two ports on one face) is now an ArgumentError. 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/model.jl | 8 +++++--- test/Maxwell/ports.jl | 8 ++++++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 6e553687..69f560a8 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -57,7 +57,7 @@ constant is `β = -iα`, the evanescent branch. A port must lie in a lossless material: a complex `eps_r` or a nonzero conductivity at a port is rejected, because the power-wave normalisation above holds for a real wave impedance. Put loss behind the port, not in its face, and a -facet set cannot be both a port and `absorbing`. +facet cannot belong to two ports or to both a port and an `absorbing` set. ```@docs MaxwellModel diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 6497336e..ba9d13e5 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -103,9 +103,11 @@ function MaxwellModel( absorbing = String.(collect(absorbing)) foreach(name -> _check_facetset(grid, name), pec) foreach(name -> _check_facetset(grid, name), absorbing) - for port in ports, name in absorbing - isdisjoint(Ferrite.getfacetset(grid, name), Ferrite.getfacetset(grid, port.facetset)) || - throw(ArgumentError("facet sets $(repr(name)) and $(repr(port.facetset)) share facets: a facet cannot be both absorbing and a wave port")) + # Each boundary condition assembles its own term, so a facet in two of them would get both. + conditions = [[("absorbing", name) for name in absorbing]; [("wave port", port.facetset) for port in ports]] + for (i, (kind_i, name_i)) in pairs(conditions), (kind_j, name_j) in conditions[(i + 1):end] + isdisjoint(Ferrite.getfacetset(grid, name_i), Ferrite.getfacetset(grid, name_j)) || + throw(ArgumentError("facet sets $(repr(name_i)) ($kind_i) and $(repr(name_j)) ($kind_j) share facets: a facet can carry only one absorbing or wave port condition")) end cell_materials = _cell_materials(grid, materials) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index c60634e6..726c9bfd 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -222,16 +222,20 @@ end ) end -@testset "a facet set cannot be both absorbing and a wave port" begin +@testset "a facet cannot carry two absorbing or wave port conditions" begin grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) addfacetset!(grid, "bottom_alias", x -> x[3] ≈ 0.0) walls = ["left", "right", "front", "back"] for name in ("bottom", "bottom_alias") - @test_throws "absorbing and a wave port" MaxwellModel( + @test_throws "share facets" MaxwellModel( grid; pec = walls, eps0 = 1.0, mu0 = 1.0, absorbing = [name], ports = [WavePort("bottom"; a_direction = (1, 0, 0))] ) end + @test_throws "share facets" MaxwellModel( + grid; pec = walls, eps0 = 1.0, mu0 = 1.0, + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("bottom_alias"; a_direction = (1, 0, 0))] + ) end @testset "tetrahedron facet tables match Ferrite" begin From 3049c4ea06b81096e676c708622dabf3e1b31d2c Mon Sep 17 00:00:00 2001 From: t Date: Wed, 11 Nov 2026 23:54:01 +0000 Subject: [PATCH 08/21] Ports: use the facet node table from the core The table now lives in model.jl on the core branch and is tested there. 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/ports.jl | 3 --- test/Maxwell/ports.jl | 4 ---- 2 files changed, 7 deletions(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index d95188d7..d75db09f 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -107,9 +107,6 @@ function _absorbing_terms(dh, pattern, names, cell_materials, mu0, eps0, L) end end -# The local nodes of each face of a tetrahedron, in Ferrite's facet order (checked against Ferrite in the tests). -const _TET_FACET_NODES = ((1, 3, 2), (1, 2, 4), (2, 3, 4), (1, 4, 3)) - function _port_frame(port, normal) a_dir = port.a_direction abs(dot(a_dir, normal)) <= 1.0e-8 * norm(a_dir) || diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 726c9bfd..d3a1e690 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -237,7 +237,3 @@ end ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("bottom_alias"; a_direction = (1, 0, 0))] ) end - -@testset "tetrahedron facet tables match Ferrite" begin - @test FiniteElementMethod._TET_FACET_NODES == Ferrite.reference_facets(RefTetrahedron) -end From 20f6d3ed84b977c6ee29548d1b0d808729aa26b2 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 02:04:51 +0000 Subject: [PATCH 09/21] Wave ports: reject PEC on the interior of the port face An interior edge of the port face in pec blocks part of the aperture while the TE10 mode and propagation constant describe the full rectangle. Same hunk on both branches. 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/ports.jl | 4 ++++ test/Maxwell/ports.jl | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index d75db09f..04cdc51c 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -188,6 +188,10 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c throw(ArgumentError("the rim of port $(repr(port.facetset)) is not PEC; name the guide walls in `pec`")) free = setdiff(_pec_dofs(dh, grid, [port.facetset]), constrained) isempty(free) && throw(ArgumentError("every edge dof of port $(repr(port.facetset)) is PEC-constrained; a port face cannot also be in `pec`")) + # An interior edge of the face in `pec` blocks part of the aperture, which the full-rectangle TE10 mode ignores. + any(dof -> count[dof] > 1 && dof in constrained, keys(count)) && throw( + ArgumentError("part of the face of port $(repr(port.facetset)) is in `pec`; only its rim may be PEC") + ) norm_h = dot(profile[free], block[free, free] \ profile[free]) norm_h > 0 || throw(ArgumentError("the TE10 mode of port $(repr(port.facetset)) has no projection onto its free edge dofs")) return WavePortData(port, block, profile, norm_h, normal, a, b, π / (a * length_scale), material.eps_r, material.mu_r) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index d3a1e690..e6030161 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -84,6 +84,16 @@ end @test all(isfinite, solve_sweep(model, [ωc * (1 + 1.0e-6)]).S) end +@testset "PEC covering part of a port face is rejected" begin + n = (5, 3, 4) + grid = generate_grid(Tetrahedron, n, Vec(0.0, 0.0, 0.0), Vec(WR90_A, WR90_B, 10.0)) + addfacetset!(grid, "patch", [first(Ferrite.getfacetset(grid, "bottom"))]) + walls = ["left", "right", "front", "back"] + @test_throws "part of the face of port" MaxwellModel( + grid; pec = [walls; "patch"], ports = [WavePort("bottom"; a_direction = (1, 0, 0))], length_scale = 1.0e-3 + ) +end + @testset "evanescent TE10 below cutoff" begin len = 10.0 model = wr90(2.0, len) From e734b27f0af6ec5cf347853c56c71c2213de6298 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:16:32 +0000 Subject: [PATCH 10/21] Maxwell model: materialise the ports iterable once before validation Validation consumed one-pass iterators such as Iterators.Stateful before assembly, leaving the model with no ports. The ports are now collected into a vector and reused. 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/model.jl | 1 + src/maxwell/ports.jl | 3 ++- test/Maxwell/ports.jl | 8 ++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index b40e326f..f0df15d9 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -101,6 +101,7 @@ function MaxwellModel( throw(ArgumentError("MaxwellModel needs a grid of Tetrahedron cells, got $(Ferrite.getcelltype(grid))")) pec = String.(collect(pec)) absorbing = String.(collect(absorbing)) + ports = collect(ports) foreach(name -> _check_facetset(grid, name), pec) foreach(name -> _check_facetset(grid, name), absorbing) # Each boundary condition assembles its own term, so a facet in two of them would get both. diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 04cdc51c..88544821 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -6,7 +6,8 @@ A TE10 wave port of a rectangular waveguide on the planar boundary facet set `facetset` of a [`MaxwellModel`](@ref). The port face must be the full guide cross-section, a rectangle with PEC on its rim, -filled with one lossless-or-dielectric material (no conductivity). +filled with one material of real permittivity and zero conductivity: a complex `eps_r` (a lossy dielectric) or a +nonzero conductivity is rejected. `a_direction` is a vector along the broad wall (the side of length `a`); the mode is `e = ê sin(π ξ / a)`, with `ξ` the distance from the edge of the rectangle along `a_direction` and `ê` the diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index e6030161..3712db13 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -247,3 +247,11 @@ end ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("bottom_alias"; a_direction = (1, 0, 0))] ) end + +@testset "one-pass port iterators are materialised once" begin + grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("top"; a_direction = (1, 0, 0))] + walls = ["left", "right", "front", "back"] + model = MaxwellModel(grid; pec = walls, ports = Iterators.Stateful(ports), eps0 = 1.0, mu0 = 1.0) + @test length(model.ports) == 2 +end From d17b4518d279920acd7f2c234698f427d43750d8 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:05:55 +0000 Subject: [PATCH 11/21] Wave ports: restrict the power interpretation to propagating ports Below cutoff the incident mode carries no real axial power, so its coefficients are generalized traveling-wave coefficients rather than power waves. The docstrings, the manual and the normalisation comment now say so, and a test integrates the axial flux of the projected incident mode above and below cutoff. No behaviour change. 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 | 6 ++++-- src/maxwell/ports.jl | 10 ++++++++-- src/maxwell/sweep.jl | 3 ++- test/Maxwell/ports.jl | 17 +++++++++++++++++ 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 69f560a8..8c49dc9c 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -52,8 +52,10 @@ sweep.S[2, 1, 5] # S21 at 10 GHz: |S21| ≈ 1, angle ≈ -93.3° ``` `Sᵢⱼ` is referred to the port faces, or to planes `deembed` mesh units inside them. Ports on different guides -are normalised to power waves through the TE10 wave impedance `ωμ0μr/β`. Below cutoff the propagation -constant is `β = -iα`, the evanescent branch. +are normalised through the TE10 wave impedance `ωμ0μr/β`. For a propagating port these are power waves. Below cutoff +the propagation constant is `β = -iα`, the evanescent branch, which carries no real axial power: the coefficients +are then generalized traveling-wave coefficients with the same normalisation, still supported, but without an +individual incident or outgoing power, and `S` is not power conserving. A port must lie in a lossless material: a complex `eps_r` or a nonzero conductivity at a port is rejected, because the power-wave normalisation above holds for a real wave impedance. Put loss behind the port, not in its face, and a diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 88544821..6f4362ad 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -15,6 +15,11 @@ in-plane unit vector perpendicular to it. By default `ê` is `n × â` with its Cartesian component is positive, which gives both ends of a straight guide the same polarisation; pass `e_direction` to fix it explicitly. `deembed` moves the reference plane of the port a distance (in mesh units) from the port face into the device. + +Above cutoff the wave coefficients are power waves: the incident mode carries real axial power, and a lossless +structure with only propagating ports has a unitary `S`. Below cutoff (`β = -iα`) the mode is evanescent and +carries no real axial power, so the coefficients are generalized traveling-wave coefficients, normalised the same +way and supported, but without an individual incident or outgoing power; `S` is then not power conserving. """ struct WavePort facetset::String @@ -261,12 +266,13 @@ end The scattering matrix from the solutions `U[:, j]` with port `j` driven by [`port_excitations`](@ref): `Sᵢⱼ = (pᵢᵀ uⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ Zⱼ / (Pⱼ Zᵢ)) exp(iβᵢdᵢ + iβⱼdⱼ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. At exactly a port's cutoff `βᵢ = 0`, `Zᵢ` is -infinite and the S-parameters are undefined, so this throws an `ArgumentError`. +infinite and the S-parameters are undefined, so this throws an `ArgumentError`. The wave coefficients are power +waves for propagating ports only; below cutoff they are generalized traveling-wave coefficients (see [`WavePort`](@ref)). """ function s_parameters(model, ω::Real, U::AbstractMatrix) ports = model.ports β = _port_betas(model, ω) - # Power-wave scale: |a|² P / Z, with Z ∝ μr / β. + # Wave scale |a|² P / Z, with Z ∝ μr / β: a power for a propagating port, a generalized coefficient below cutoff. w = [sqrt(data.norm * β[i] / data.mu_r) for (i, data) in pairs(ports)] shift = [exp(im * β[i] * data.port.deembed * model.length_scale) for (i, data) in pairs(ports)] np = length(ports) diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl index d539403c..ecc078fc 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -17,7 +17,8 @@ end MaxwellSweep The result of [`solve_sweep`](@ref): `omegas`, the scattering matrices `S[:, :, k]` at `omegas[k]` -(`S[i, j, k]` is the wave leaving port `i` for a unit wave incident on port `j`) and `fields`, either +(`S[i, j, k]` is the wave leaving port `i` for a unit wave incident on port `j`: a power wave for a propagating +port, a generalized traveling-wave coefficient below cutoff) and `fields`, either `nothing` or, per frequency, the matrix whose column `j` is the edge-dof vector with port `j` driven (wrap it with `MaxwellSolution(model, omegas[k], fields[k][:, j])`). """ diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 3712db13..78af9cf2 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -255,3 +255,20 @@ end model = MaxwellModel(grid; pec = walls, ports = Iterators.Stateful(ports), eps0 = 1.0, mu0 = 1.0) @test length(model.ports) == 2 end + +@testset "axial power of the incident mode: propagating ports carry it, evanescent ones do not" begin + # Normalised guide with broad dimension a = 2, cutoff ω = π/2; the incident mode of unit amplitude is the + # L² projection of the TE10 mode onto the discrete traces, with H = β/(ωμ) n × E. + grid = generate_grid(Tetrahedron, (4, 2, 4), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("top"; a_direction = (1, 0, 0))] + model = MaxwellModel(grid; pec = ["left", "right", "front", "back"], ports, eps0 = 1.0, mu0 = 1.0) + data = first(model.ports) + face = setdiff(findall(!iszero, diag(data.block)), model.ch.prescribed_dofs) + c = Matrix(data.block[face, face]) \ data.profile[face] + @test dot(data.profile[face], c) ≈ data.norm + flux(ω) = real(propagation_constant(model, 1, ω)) / ω / 2 * real(dot(c, data.block[face, face] * c)) + wave_power(ω) = data.norm * abs(propagation_constant(model, 1, ω)) / ω / 2 # |a|²/2 + @test flux(2.0) ≈ wave_power(2.0) rtol = 1.0e-12 + @test flux(1.0) == 0 + @test wave_power(1.0) > 0.1 +end From 8f083be8fba749a732e73fc4440b49fa5ccbe956 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:09:01 +0000 Subject: [PATCH 12/21] Tests: qualify propagation_constant in the axial power test The function is not exported. 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/ports.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 78af9cf2..a864fee2 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -266,8 +266,8 @@ end face = setdiff(findall(!iszero, diag(data.block)), model.ch.prescribed_dofs) c = Matrix(data.block[face, face]) \ data.profile[face] @test dot(data.profile[face], c) ≈ data.norm - flux(ω) = real(propagation_constant(model, 1, ω)) / ω / 2 * real(dot(c, data.block[face, face] * c)) - wave_power(ω) = data.norm * abs(propagation_constant(model, 1, ω)) / ω / 2 # |a|²/2 + flux(ω) = real(FiniteElementMethod.propagation_constant(model, 1, ω)) / ω / 2 * real(dot(c, data.block[face, face] * c)) + wave_power(ω) = data.norm * abs(FiniteElementMethod.propagation_constant(model, 1, ω)) / ω / 2 # |a|²/2 @test flux(2.0) ≈ wave_power(2.0) rtol = 1.0e-12 @test flux(1.0) == 0 @test wave_power(1.0) > 0.1 From 912dea7e7143e29c9c0861cd7888db0b1dbb74d0 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:41:50 +0000 Subject: [PATCH 13/21] Wave ports and absorbing boundary: outgoing branch for lossless negative permittivity; positive frequencies only The absorbing coefficient took the principal square root, which is the incoming branch for a negative real eps_r/mu_r with no loss and jumped when a vanishing loss was added; it now takes the limit from the lossy side. A wave port's propagation constant squares omega, so a negative frequency returned the same S instead of its conjugate; wave ports and sweeps now reject non-positive frequencies before any solve. 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 | 3 ++- src/maxwell/model.jl | 2 +- src/maxwell/ports.jl | 13 ++++++++++++- src/maxwell/sweep.jl | 1 + test/Maxwell/ports.jl | 25 +++++++++++++++++++++++++ 5 files changed, 41 insertions(+), 3 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 8c49dc9c..cf7adcc6 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -55,7 +55,8 @@ sweep.S[2, 1, 5] # S21 at 10 GHz: |S21| ≈ 1, angle ≈ -93.3° are normalised through the TE10 wave impedance `ωμ0μr/β`. For a propagating port these are power waves. Below cutoff the propagation constant is `β = -iα`, the evanescent branch, which carries no real axial power: the coefficients are then generalized traveling-wave coefficients with the same normalisation, still supported, but without an -individual incident or outgoing power, and `S` is not power conserving. +individual incident or outgoing power, and `S` is not power conserving. Wave ports need positive frequencies; a +zero or negative `ω` is rejected, since a real system has `S(-ω) = conj(S(ω))`. A port must lie in a lossless material: a complex `eps_r` or a nonzero conductivity at a port is rejected, because the power-wave normalisation above holds for a real wave impedance. Put loss behind the port, not in its face, and a diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index f0df15d9..df3c76d9 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -53,7 +53,7 @@ The time-harmonic electric-field model on a Ferrite `grid` of `Tetrahedron` cell with `n × E = 0` on the facet sets named in `pec` and the natural condition `n × (μr⁻¹ ∇ × E) = 0` on the rest of the boundary, except for the facet sets named in `absorbing`, which carry the first-order -Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)`, and the +Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)` (the outgoing root: for a negative real `εc/μr`, `-i sqrt(|εc/μr|)`), and the [`WavePort`](@ref)s in `ports`. `materials` maps cell set names of `grid` (as `FerriteGmsh.togrid` makes from Gmsh physical groups) to diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 6f4362ad..3f359c38 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -99,6 +99,14 @@ function tangential_mass(model, facetsets; weight = Returns(1.0)) return _tangential_mass(model.dh, model.blocks.curlcurl, names, weight) end +# sqrt(εc / μr) on the outgoing branch: the principal root, except for a negative real εc / μr (no loss), where it is +# the limit from the lossy side, -i sqrt(|εc / μr|), so that the exterior field decays and the term is continuous +# in the loss. +function _admittance(εc, μr) + z = εc / μr + return imag(z) == 0 && real(z) < 0 ? -im * sqrt(-real(z)) : sqrt(z) +end + # First-order absorbing boundary n × (μr⁻¹ ∇ × E) = -i k0 ηr⁻¹ n × (n × E), with ηr⁻¹ = sqrt(εc / μr) and # εc = εr - iσ/(ωε0) of the adjacent cell: the term +i k0 L ηr⁻¹ ∮ (n × E)⋅(n × v) dS, one block per material. function _absorbing_terms(dh, pattern, names, cell_materials, mu0, eps0, L) @@ -108,7 +116,7 @@ function _absorbing_terms(dh, pattern, names, cell_materials, mu0, eps0, L) # The coefficient is ω √εc with εc ~ 1/ω for a conductor, so it tends to 0 as ω → 0. MaxwellTerm( block, - ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * L * sqrt((m.eps_r - im * m.sigma / (ω * eps0)) / m.mu_r) + ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * L * _admittance(m.eps_r - im * m.sigma / (ω * eps0), m.mu_r) ) end end @@ -237,6 +245,9 @@ end # The propagation constants of all ports at ω. At exact cutoff β = 0, the wave impedance ωμ/β is infinite and the # power-wave scale of the S-parameters is 0/0, so it is an error rather than a NaN matrix. function _port_betas(model, ω) + ω > 0 || throw( + ArgumentError("ω = $ω is not supported for wave ports: the propagation constant and the S-parameter normalisation are defined for positive frequencies only, and a real system has S(-ω) = conj(S(ω))") + ) β = [_propagation_constant(data, model.mu0 * model.eps0, float(ω)) for data in model.ports] j = findfirst(iszero, β) j === nothing || throw( diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl index ecc078fc..f3e5ddcc 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -41,6 +41,7 @@ frequency). An empty `omegas` gives an empty sweep. function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = umfpack_solver) isempty(model.ports) && throw(ArgumentError("the model has no wave ports")) omegas = float.(collect(omegas)) + all(>(0), omegas) || throw(ArgumentError("wave ports need positive frequencies, got ω = $(omegas[findfirst(<=(0), omegas)])")) np = length(model.ports) S = zeros(ComplexF64, np, np, length(omegas)) kept = fields ? Matrix{ComplexF64}[] : nothing diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index a864fee2..b3c6657b 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -272,3 +272,28 @@ end @test flux(1.0) == 0 @test wave_power(1.0) > 0.1 end + +@testset "wave ports reject non-positive frequencies before any solve" begin + model = wr90(5.0, 10.0) + @test_throws "positive frequencies" solve_sweep(model, [2π * 10.0e9, -2π * 10.0e9]) + @test_throws "positive frequencies" solve_sweep(model, [-2.0]) + @test_throws "not supported for wave ports" FiniteElementMethod.port_excitations(model, -2.0) +end + +@testset "the absorbing boundary of a lossless negative-permittivity material is outgoing" begin + # eps_r = -1 at ω = 1: -E'' + E = 1, E'(0) = 0, E'(1) + E(1) = 0, so E(z) = 1 - exp(-1) cosh(z). + grid = generate_grid(Tetrahedron, (4, 4, 8), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + addcellset!(grid, "all", x -> true) + midpoint(eps_r) = begin + model = MaxwellModel( + grid; materials = Dict("all" => MaxwellMaterial(; eps_r)), pec = ["front", "back"], absorbing = ["top"], + eps0 = 1.0, mu0 = 1.0 + ) + sol = solve_driven(model, 1.0, x -> (0.0, 1.0im, 0.0)) + return field_values(sol, [Vec(0.5, 0.5, 0.5)]).E[1][2] + end + exact = 1 - exp(-1) * cosh(0.5) + @test midpoint(-1.0) ≈ exact atol = 0.015 # the discretisation error; the incoming branch gives -2.08 + @test midpoint(-1.0 - 1.0e-12im) ≈ exact atol = 0.015 + @test midpoint(-1.0) ≈ midpoint(-1.0 - 1.0e-12im) atol = 1.0e-6 +end From 7089122619e4fd628a9fcc4dbef1482b32d8868b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:01:08 +0000 Subject: [PATCH 14/21] Absorbing boundary: outgoing branch follows the sign of the frequency For a lossless negative real eps_r/mu_r the coefficient chose the same root at both signs of omega, so the operator at -omega was not the conjugate of the one at omega; the root is now the limit from the lossy side at each sign. 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/model.jl | 2 +- src/maxwell/ports.jl | 10 +++++----- test/Maxwell/ports.jl | 9 +++++++++ 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index df3c76d9..7cc5ccae 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -53,7 +53,7 @@ The time-harmonic electric-field model on a Ferrite `grid` of `Tetrahedron` cell with `n × E = 0` on the facet sets named in `pec` and the natural condition `n × (μr⁻¹ ∇ × E) = 0` on the rest of the boundary, except for the facet sets named in `absorbing`, which carry the first-order -Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)` (the outgoing root: for a negative real `εc/μr`, `-i sqrt(|εc/μr|)`), and the +Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)` (the outgoing root: for a negative real `εc/μr`, `-i sign(ω) sqrt(|εc/μr|)`), and the [`WavePort`](@ref)s in `ports`. `materials` maps cell set names of `grid` (as `FerriteGmsh.togrid` makes from Gmsh physical groups) to diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 3f359c38..f07c1640 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -100,11 +100,11 @@ function tangential_mass(model, facetsets; weight = Returns(1.0)) end # sqrt(εc / μr) on the outgoing branch: the principal root, except for a negative real εc / μr (no loss), where it is -# the limit from the lossy side, -i sqrt(|εc / μr|), so that the exterior field decays and the term is continuous -# in the loss. -function _admittance(εc, μr) +# the limit from the lossy side at the sign of ω, -i sign(ω) sqrt(|εc / μr|), so that the exterior field decays, the +# term is continuous in the loss and A(-ω) = conj(A(ω)). +function _admittance(εc, μr, ω) z = εc / μr - return imag(z) == 0 && real(z) < 0 ? -im * sqrt(-real(z)) : sqrt(z) + return imag(z) == 0 && real(z) < 0 ? -im * sign(ω) * sqrt(-real(z)) : sqrt(z) end # First-order absorbing boundary n × (μr⁻¹ ∇ × E) = -i k0 ηr⁻¹ n × (n × E), with ηr⁻¹ = sqrt(εc / μr) and @@ -116,7 +116,7 @@ function _absorbing_terms(dh, pattern, names, cell_materials, mu0, eps0, L) # The coefficient is ω √εc with εc ~ 1/ω for a conductor, so it tends to 0 as ω → 0. MaxwellTerm( block, - ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * L * _admittance(m.eps_r - im * m.sigma / (ω * eps0), m.mu_r) + ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * L * _admittance(m.eps_r - im * m.sigma / (ω * eps0), m.mu_r, ω) ) end end diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index b3c6657b..1a1e5f5d 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -297,3 +297,12 @@ end @test midpoint(-1.0 - 1.0e-12im) ≈ exact atol = 0.015 @test midpoint(-1.0) ≈ midpoint(-1.0 - 1.0e-12im) atol = 1.0e-6 end + +@testset "the absorbing operator is conjugate symmetric in ω" begin + grid = generate_grid(Tetrahedron, (2, 2, 2)) + addcellset!(grid, "all", x -> true) + for material in (MaxwellMaterial(), MaxwellMaterial(; eps_r = -1.0), MaxwellMaterial(; eps_r = 2.0, mu_r = 1.5, sigma = 0.3)) + model = MaxwellModel(grid; materials = Dict("all" => material), pec = ["front", "back"], absorbing = ["top"], eps0 = 1.0, mu0 = 1.0) + @test maxwell_operator(model, -1.3).nzval ≈ conj.(maxwell_operator(model, 1.3).nzval) + end +end From 4141f26764428c0dab303fd3532dfdcb076de510 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:16:06 +0000 Subject: [PATCH 15/21] Absorbing boundary and wave ports: one outgoing rule for every sign of eps_r, mu_r and omega The lossless root now follows the passive limit for negative permeability too, y = -i sign(omega) sign(mu_r) sqrt(|eps_c/mu_r|) where eps_c/mu_r is a negative real, with a table regression over the sign combinations and the decaying-exterior check. A wave port's term in the operator path now rejects non-positive frequencies like the sweeps, since its propagation constant depends on omega squared. 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/model.jl | 2 +- src/maxwell/ports.jl | 15 ++++++++++----- test/Maxwell/ports.jl | 28 +++++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 7cc5ccae..5622788d 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -53,7 +53,7 @@ The time-harmonic electric-field model on a Ferrite `grid` of `Tetrahedron` cell with `n × E = 0` on the facet sets named in `pec` and the natural condition `n × (μr⁻¹ ∇ × E) = 0` on the rest of the boundary, except for the facet sets named in `absorbing`, which carry the first-order -Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)` (the outgoing root: for a negative real `εc/μr`, `-i sign(ω) sqrt(|εc/μr|)`), and the +Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)` (the outgoing root: for a negative real `εc/μr`, `-i sign(ω) sign(μr) sqrt(|εc/μr|)`), and the [`WavePort`](@ref)s in `ports`. `materials` maps cell set names of `grid` (as `FerriteGmsh.togrid` makes from Gmsh physical groups) to diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index f07c1640..bd4b1e8d 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -99,12 +99,15 @@ function tangential_mass(model, facetsets; weight = Returns(1.0)) return _tangential_mass(model.dh, model.blocks.curlcurl, names, weight) end -# sqrt(εc / μr) on the outgoing branch: the principal root, except for a negative real εc / μr (no loss), where it is -# the limit from the lossy side at the sign of ω, -i sign(ω) sqrt(|εc / μr|), so that the exterior field decays, the -# term is continuous in the loss and A(-ω) = conj(A(ω)). +# y = sqrt(εc / μr), the admittance of the outgoing wave of the exterior medium, which is passive: Re y ≥ 0. That is +# the principal root, except when εc / μr is a negative real (no loss), where the root is the limit of the lossy +# side. A loss -iε'' in εc, -iμ'' in μr (their signs flip with ω) moves εc / μr off the axis by +# -i sign(ω) (ε'' μr - εc μ'') / μr², whose sign is -sign(ω) sign(μr) when εc and μr have opposite signs. So +# y = -i sign(ω) sign(μr) sqrt(|εc / μr|) there, which makes the exterior field decay, the term continuous in the loss +# and A(-ω) = conj(A(ω)). function _admittance(εc, μr, ω) z = εc / μr - return imag(z) == 0 && real(z) < 0 ? -im * sign(ω) * sqrt(-real(z)) : sqrt(z) + return imag(z) == 0 && real(z) < 0 ? -im * sign(ω) * sign(real(μr)) * sqrt(-real(z)) : sqrt(z) end # First-order absorbing boundary n × (μr⁻¹ ∇ × E) = -i k0 ηr⁻¹ n × (n × E), with ηr⁻¹ = sqrt(εc / μr) and @@ -239,8 +242,10 @@ end # n × μr⁻¹∇ × E = -(iβ/μr) n × (n × E) - 2(iβ/μr) E0 e on the port gives +(iβ/μr) L B on the operator and # +2(iβ/μr) L E0 p on the load, with E0 = 1. function _port_term(data::WavePortData, mu0eps0, L) - return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, ω) * L / data.mu_r) + return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, _positive_frequency(ω)) * L / data.mu_r) end +# β depends on ω², so it is the outgoing condition for ω > 0 only; the operator path enforces it like the sweeps do. +_positive_frequency(ω) = ω > 0 ? ω : throw(ArgumentError("wave ports need positive frequencies, got ω = $ω")) # The propagation constants of all ports at ω. At exact cutoff β = 0, the wave impedance ωμ/β is infinite and the # power-wave scale of the S-parameters is 0/0, so it is an error rather than a NaN matrix. diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 1a1e5f5d..73734d25 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -301,8 +301,34 @@ end @testset "the absorbing operator is conjugate symmetric in ω" begin grid = generate_grid(Tetrahedron, (2, 2, 2)) addcellset!(grid, "all", x -> true) - for material in (MaxwellMaterial(), MaxwellMaterial(; eps_r = -1.0), MaxwellMaterial(; eps_r = 2.0, mu_r = 1.5, sigma = 0.3)) + for material in (MaxwellMaterial(), MaxwellMaterial(; eps_r = -1.0), MaxwellMaterial(; mu_r = -1.0), MaxwellMaterial(; eps_r = -1.0, mu_r = -1.0), MaxwellMaterial(; eps_r = 2.0, mu_r = 1.5, sigma = 0.3)) model = MaxwellModel(grid; materials = Dict("all" => material), pec = ["front", "back"], absorbing = ["top"], eps0 = 1.0, mu0 = 1.0) @test maxwell_operator(model, -1.3).nzval ≈ conj.(maxwell_operator(model, 1.3).nzval) end end + +@testset "the lossless absorbing admittance is the lossy-side limit for every sign of eps_r, mu_r and ω" begin + admittance(eps_r, mu_r, ω, σ) = FiniteElementMethod._admittance(eps_r - im * σ / ω, mu_r, ω) + for (eps_r, mu_r, ω) in ((1.0, -1.0, 1.0), (1.0, -1.0, -1.0), (-1.0, 1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, -1.0, 1.0), (-1.0, -1.0, -1.0), (2.0, 1.5, 1.0), (2.0, 1.5, -1.0)) + y = admittance(eps_r, mu_r, ω, 0.0) + @test y ≈ admittance(eps_r, mu_r, ω, 1.0e-12) atol = 1.0e-9 + @test real(y) >= 0 # passive: the exterior wave carries power outwards or decays + @test y ≈ conj(admittance(eps_r, mu_r, -ω, 0.0)) + end + # eps_r = 1, mu_r = -1: -E'' / mu_r - E = E'' - E = 1, E'(0) = 0 and the decaying exterior E'(1) = -E(1) give + # E(z) = -1 + exp(-1) cosh(z); the wrong sign would impose E'(1) = +E(1). + grid = generate_grid(Tetrahedron, (4, 4, 8), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + addcellset!(grid, "all", x -> true) + model = MaxwellModel( + grid; materials = Dict("all" => MaxwellMaterial(; mu_r = -1.0)), pec = ["front", "back"], absorbing = ["top"], + eps0 = 1.0, mu0 = 1.0 + ) + sol = solve_driven(model, 1.0, x -> (0.0, 1.0im, 0.0)) + @test field_values(sol, [Vec(0.5, 0.5, 0.5)]).E[1][2] ≈ -1 + exp(-1) * cosh(0.5) atol = 0.015 +end + +@testset "wave-port operators reject non-positive frequencies like the sweeps" begin + model = wr90(5.0, 10.0) + @test_throws "positive frequencies" maxwell_operator(model, -2.0) + @test_throws "positive frequencies" solve_driven(model, -2.0, x -> (0.0, 1.0, 0.0)) +end From c834c973cbf542fa2961f1fb58952116521d82c6 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:22:20 +0000 Subject: [PATCH 16/21] Wave ports: the operator path rejects negative frequencies only The operator is finite at omega = 0, where an existing adjoint test evaluates it; only the S-parameter normalisation is singular there, and the sweeps keep rejecting zero. 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/ports.jl | 7 ++++--- test/Maxwell/ports.jl | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index bd4b1e8d..088a0f13 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -242,10 +242,11 @@ end # n × μr⁻¹∇ × E = -(iβ/μr) n × (n × E) - 2(iβ/μr) E0 e on the port gives +(iβ/μr) L B on the operator and # +2(iβ/μr) L E0 p on the load, with E0 = 1. function _port_term(data::WavePortData, mu0eps0, L) - return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, _positive_frequency(ω)) * L / data.mu_r) + return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, _nonnegative_frequency(ω)) * L / data.mu_r) end -# β depends on ω², so it is the outgoing condition for ω > 0 only; the operator path enforces it like the sweeps do. -_positive_frequency(ω) = ω > 0 ? ω : throw(ArgumentError("wave ports need positive frequencies, got ω = $ω")) +# β depends on ω², so it is the outgoing condition for ω ≥ 0 only; the operator is finite at ω = 0 (the S-parameter +# normalisation is not, and the sweeps reject it). +_nonnegative_frequency(ω) = ω >= 0 ? ω : throw(ArgumentError("wave ports are not defined for negative frequencies (ω = $ω): their propagation constant depends on ω² and is the outgoing condition for ω ≥ 0 only")) # The propagation constants of all ports at ω. At exact cutoff β = 0, the wave impedance ωμ/β is infinite and the # power-wave scale of the S-parameters is 0/0, so it is an error rather than a NaN matrix. diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 73734d25..32cf0c20 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -329,6 +329,6 @@ end @testset "wave-port operators reject non-positive frequencies like the sweeps" begin model = wr90(5.0, 10.0) - @test_throws "positive frequencies" maxwell_operator(model, -2.0) - @test_throws "positive frequencies" solve_driven(model, -2.0, x -> (0.0, 1.0, 0.0)) + @test_throws "negative frequencies" maxwell_operator(model, -2.0) + @test_throws "negative frequencies" solve_driven(model, -2.0, x -> (0.0, 1.0, 0.0)) end From fcb0262f43858ee006d234b2df352424c4be1e6e Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:33:06 +0000 Subject: [PATCH 17/21] Wave ports: require positive real permittivity and positive permeability A port filled with a double-negative or single-negative material has an outward power that does not follow beta/mu_r, so the port injects energy and the transmission phase has the wrong sign; such a port is now an ArgumentError at construction, documented with the real-permittivity requirement. 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 | 5 +++-- src/maxwell/ports.jl | 9 +++++++-- test/Maxwell/ports.jl | 12 ++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index cf7adcc6..51d4a2ca 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -58,8 +58,9 @@ are then generalized traveling-wave coefficients with the same normalisation, st individual incident or outgoing power, and `S` is not power conserving. Wave ports need positive frequencies; a zero or negative `ω` is rejected, since a real system has `S(-ω) = conj(S(ω))`. -A port must lie in a lossless material: a complex `eps_r` or a nonzero conductivity at a port is rejected, because the -power-wave normalisation above holds for a real wave impedance. Put loss behind the port, not in its face, and a +A port must lie in an ordinary passive material: a complex `eps_r`, a nonzero conductivity, a non-positive `eps_r` +or a non-positive `mu_r` at a port is rejected, because the power-wave normalisation above holds for a real wave +impedance and the outward power of the TE10 mode is `Re(β/μr) > 0` only for positive `μr` and `εr`. Put loss behind the port, not in its face, and a facet cannot belong to two ports or to both a port and an `absorbing` set. ```@docs diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 088a0f13..c728d72f 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -6,8 +6,10 @@ A TE10 wave port of a rectangular waveguide on the planar boundary facet set `facetset` of a [`MaxwellModel`](@ref). The port face must be the full guide cross-section, a rectangle with PEC on its rim, -filled with one material of real permittivity and zero conductivity: a complex `eps_r` (a lossy dielectric) or a -nonzero conductivity is rejected. +filled with one ordinary passive material: positive real permittivity (`real(eps_r) > 0`, no imaginary part), positive +permeability (`mu_r > 0`) and zero conductivity. A complex `eps_r` (a lossy dielectric), a nonzero conductivity and a +non-positive `eps_r` or `mu_r` (a negative-index or double-negative filling, whose outward power does not follow +`β/μr`) are rejected. `a_direction` is a vector along the broad wall (the side of length `a`); the mode is `e = ê sin(π ξ / a)`, with `ξ` the distance from the edge of the rectangle along `a_direction` and `ê` the @@ -174,6 +176,9 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c iszero(material.sigma) || throw(ArgumentError("port $(repr(port.facetset)) is in a conducting material")) iszero(imag(material.eps_r)) || throw(ArgumentError("port $(repr(port.facetset)) is in a lossy material (complex eps_r); the S-parameter power normalisation of a wave port assumes a lossless one")) + real(material.eps_r) > 0 && material.mu_r > 0 || throw( + ArgumentError("port $(repr(port.facetset)) is in a material with eps_r = $(material.eps_r) and mu_r = $(material.mu_r); a wave port needs a positive real permittivity and a positive permeability") + ) e(x) = ê * sin(π * (dot(x, â) - ξ0) / a) profile = zeros(Ferrite.ndofs(dh)) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 32cf0c20..3db73afa 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -332,3 +332,15 @@ end @test_throws "negative frequencies" maxwell_operator(model, -2.0) @test_throws "negative frequencies" solve_driven(model, -2.0, x -> (0.0, 1.0, 0.0)) end + +@testset "a wave port needs positive permittivity and permeability" begin + grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + addcellset!(grid, "fill", x -> true) + walls = ["left", "right", "front", "back"] + ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + build(eps_r, mu_r) = MaxwellModel(grid; materials = Dict("fill" => MaxwellMaterial(; eps_r, mu_r)), pec = walls, ports, eps0 = 1.0, mu0 = 1.0) + for (eps_r, mu_r) in ((-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0)) + @test_throws "positive real permittivity and a positive permeability" build(eps_r, mu_r) + end + @test build(2.0, 1.5) isa MaxwellModel +end From dfef81e5568802d0777ec54577684b404965e67c Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 21:13:35 +0000 Subject: [PATCH 18/21] Wave ports: apply the TE10 admittance to the TE10 amplitude only The propagating admittance acted on the whole tangential mass of the port face, so the evanescent higher modes absorbed real power: a lossless taper, dielectric insert and short inclusion lost 23%, 11% and 27% of the incident power. The port term is now the rank-one p p^T / norm of the TE10 projection (the same one s_parameters and the excitation use), which couples the dofs of the face and adds them to the model's sparsity pattern; the complement keeps the natural boundary condition, so power is conserved. Frequencies that are not finite are rejected with one predicate, and the single-mode limitation is documented. 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 | 8 +++++++- src/FiniteElementMethod.jl | 2 +- src/maxwell/model.jl | 19 ++++++++++++++++-- src/maxwell/ports.jl | 41 +++++++++++++++++++++++++++++++++----- src/maxwell/sweep.jl | 3 ++- test/Maxwell/ports.jl | 35 ++++++++++++++++++++++++++++++++ 6 files changed, 98 insertions(+), 10 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 51d4a2ca..62b5110e 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -55,7 +55,13 @@ sweep.S[2, 1, 5] # S21 at 10 GHz: |S21| ≈ 1, angle ≈ -93.3° are normalised through the TE10 wave impedance `ωμ0μr/β`. For a propagating port these are power waves. Below cutoff the propagation constant is `β = -iα`, the evanescent branch, which carries no real axial power: the coefficients are then generalized traveling-wave coefficients with the same normalisation, still supported, but without an -individual incident or outgoing power, and `S` is not power conserving. Wave ports need positive frequencies; a +individual incident or outgoing power, and `S` is not power conserving. + +A wave port is a single-mode TE10 termination: its admittance acts on the TE10 amplitude of the trace only (a rank-one +term that couples all the dofs of the port face), and the evanescent higher modes see the natural (magnetic-wall) +boundary at the port plane, so they are reflected, not absorbed, and a lossless single-mode structure conserves +power. Keep about one decay length `1 / sqrt(kc² - k²)` of the first evanescent mode (`kc = 2π/a` for TE20, `π/b` for +TE01) of uniform lead between a discontinuity and the port, otherwise `S` depends on the lead length. Wave ports need positive frequencies; a zero or negative `ω` is rejected, since a real system has `S(-ω) = conj(S(ω))`. A port must lie in an ordinary passive material: a complex `eps_r`, a nonzero conductivity, a non-positive `eps_r` diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 969cc845..c3ef7bbd 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -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, findnz, nnz, nonzeros, nzrange, rowvals, sparse using SymbolicUtils: SymbolicUtils using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 5622788d..78f40745 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -123,7 +123,8 @@ function MaxwellModel( Ferrite.close!(ch) cv = Ferrite.CellValues(Ferrite.QuadratureRule{RefTetrahedron}(quadrature), ip) - blocks = _assemble_blocks(dh, cv, cell_materials) + pattern = _sparsity_pattern(dh, [_wave_port_dofs(port, dh) for port in ports]) + blocks = _assemble_blocks(pattern, dh, cv, cell_materials) L2 = float(length_scale)^2 k2 = mu0 * eps0 * L2 terms = [ @@ -180,8 +181,22 @@ function _pec_dofs(dh, grid, pec) return sort!(collect(dofs)) end -function _assemble_blocks(dh, cv, cell_materials) +# The cell pattern of `dh` plus every pair of edge dofs within each port face: a wave port couples its whole face. +function _sparsity_pattern(dh, port_dofs) pattern = Ferrite.allocate_matrix(dh) + isempty(port_dofs) && return pattern + rows, cols, _ = findnz(pattern) + for dofs in port_dofs, i in dofs, j in dofs + push!(rows, i) + push!(cols, j) + end + n = Ferrite.ndofs(dh) + pattern = sparse(rows, cols, ones(length(rows)), n, n) + fill!(nonzeros(pattern), 0.0) + return pattern +end + +function _assemble_blocks(pattern, dh, cv, cell_materials) mats = (curlcurl = pattern, eps_real = copy(pattern), eps_imag = copy(pattern), sigma = copy(pattern)) assemblers = map(Ferrite.start_assemble, mats) n = Ferrite.getnbasefunctions(cv) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index c728d72f..c0bc838e 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -18,6 +18,14 @@ Cartesian component is positive, which gives both ends of a straight guide the s `e_direction` to fix it explicitly. `deembed` moves the reference plane of the port a distance (in mesh units) from the port face into the device. +The port is a single-mode termination: the outgoing TE10 admittance acts on the TE10 amplitude of the trace only, +through the rank-one term `p pᵀ / norm` (see [`FiniteElementMethod.WavePortData`](@ref)), which couples all the dofs of +the port face. The rest of the trace, the evanescent higher modes, sees the natural (magnetic-wall) boundary at the port +plane: it is reflected, not absorbed, so a lossless single-mode structure conserves power. A discontinuity near the +port then excites evanescent modes that the port does not terminate, and `S` depends on the lead length unless at +least about one decay length of uniform guide, `1 / sqrt(kc² - k²)` for the first evanescent mode (`kc = 2π/a` for TE20, +`π/b` for TE01, `k = ω sqrt(μ0 ε0 εr μr)`), separates the discontinuity from the port. + Above cutoff the wave coefficients are power waves: the incident mode carries real axial power, and a lossless structure with only propagating ports has a unitary `S`. Below cutoff (`β = -iα`) the mode is evanescent and carries no real axial power, so the coefficients are generalized traveling-wave coefficients, normalised the same @@ -41,12 +49,14 @@ A [`WavePort`](@ref) assembled on a [`MaxwellModel`](@ref), in `model.ports`. Fi tangential mass `∮ (n × Nᵢ)⋅(n × Nⱼ) dS` of the port face), `profile` (`pᵢ = ∮ e⋅Nᵢ dS`), `norm` (`pᵀ B⁻¹ p` over the unconstrained edge dofs of the face: `∮ e_h⋅e_h dS` of the L² projection `e_h` of the mode onto the discrete tangential traces, so that a port-face field `c e_h` gives exactly `pᵀu / norm = c`), -`normal` (outward), `a`, `b` (mesh units), `kc` (`π / (a L)`, rad/m), +`coupling` (the rank-one `p pᵀ / norm` on the face dofs, the port's boundary term: it acts on the TE10 amplitude +`pᵀu / norm` only), `normal` (outward), `a`, `b` (mesh units), `kc` (`π / (a L)`, rad/m), `eps_r` and `mu_r` of the port material (lossless: complex `eps_r` is rejected). """ struct WavePortData port::WavePort block::SparseMatrixCSC{Float64, Int} + coupling::SparseMatrixCSC{Float64, Int} profile::Vector{Float64} norm::Float64 normal::Ferrite.Vec{3, Float64} @@ -214,9 +224,28 @@ function _wave_port(port::WavePort, dh, pattern, cell_materials, length_scale, c any(dof -> count[dof] > 1 && dof in constrained, keys(count)) && throw( ArgumentError("part of the face of port $(repr(port.facetset)) is in `pec`; only its rim may be PEC") ) + face = _wave_port_dofs(port, dh) + keep = falses(length(profile)) + keep[face] .= true + profile[.!keep] .= 0 # the traces of the other edge functions vanish on the face, up to roundoff norm_h = dot(profile[free], block[free, free] \ profile[free]) norm_h > 0 || throw(ArgumentError("the TE10 mode of port $(repr(port.facetset)) has no projection onto its free edge dofs")) - return WavePortData(port, block, profile, norm_h, normal, a, b, π / (a * length_scale), material.eps_r, material.mu_r) + coupling = copy(pattern) + fill!(nonzeros(coupling), 0.0) + for j in face, k in nzrange(coupling, j) + i = rowvals(coupling)[k] + keep[i] && (nonzeros(coupling)[k] = profile[i] * profile[j] / norm_h) + end + return WavePortData(port, block, coupling, profile, norm_h, normal, a, b, π / (a * length_scale), material.eps_r, material.mu_r) +end + +# The edge dofs of the facets of the port. +function _wave_port_dofs(port, dh) + dofs = Set{Int}() + for (cell, local_facet) in Ferrite.getfacetset(dh.grid, port.facetset), i in _TET_FACET_EDGE_DOFS[local_facet] + push!(dofs, Ferrite.celldofs(dh, cell)[i]) + end + return sort!(collect(dofs)) end # β = sqrt(k² - kc²) on the branch Im β ≤ 0, so that the outgoing exp(-iβζ) decays below cutoff. @@ -244,10 +273,12 @@ function cutoff_frequency(model, port::Integer) return data.kc / (2π * sqrt(model.mu0 * model.eps0 * real(data.eps_r) * data.mu_r)) end -# n × μr⁻¹∇ × E = -(iβ/μr) n × (n × E) - 2(iβ/μr) E0 e on the port gives +(iβ/μr) L B on the operator and -# +2(iβ/μr) L E0 p on the load, with E0 = 1. +# n × μr⁻¹∇ × E = -(iβ/μr) c e - 2(iβ/μr) E0 e on the port, with c = pᵀu / norm the TE10 amplitude of the trace and +# e the mode, gives +(iβ/μr) L p pᵀ / norm on the operator and +2(iβ/μr) L E0 p on the load, with E0 = 1. Only the +# TE10 amplitude sees the port: the rest of the trace, which is evanescent, has the natural boundary condition and +# absorbs no power. function _port_term(data::WavePortData, mu0eps0, L) - return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, _nonnegative_frequency(ω)) * L / data.mu_r) + return MaxwellTerm(data.coupling, ω -> im * _propagation_constant(data, mu0eps0, _nonnegative_frequency(ω)) * L / data.mu_r) end # β depends on ω², so it is the outgoing condition for ω ≥ 0 only; the operator is finite at ω = 0 (the S-parameter # normalisation is not, and the sweeps reject it). diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl index f3e5ddcc..eb526ca3 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -41,7 +41,8 @@ frequency). An empty `omegas` gives an empty sweep. function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = umfpack_solver) isempty(model.ports) && throw(ArgumentError("the model has no wave ports")) omegas = float.(collect(omegas)) - all(>(0), omegas) || throw(ArgumentError("wave ports need positive frequencies, got ω = $(omegas[findfirst(<=(0), omegas)])")) + bad = findfirst(ω -> !(isfinite(ω) && ω > 0), omegas) + bad === nothing || throw(ArgumentError("wave ports need finite positive frequencies, got ω = $(omegas[bad])")) np = length(model.ports) S = zeros(ComplexF64, np, np, length(omegas)) kept = fields ? Matrix{ComplexF64}[] : nothing diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 3db73afa..c48179f9 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -344,3 +344,38 @@ end end @test build(2.0, 1.5) isa MaxwellModel end + +@testset "a wave port conserves power in lossless single-mode structures" begin + walls = ["left", "right", "front", "back"] + ports = [WavePort(f; a_direction = (1, 0, 0)) for f in ("bottom", "top")] + function power(grid, materials = Dict{String, MaxwellMaterial}()) + model = MaxwellModel(grid; materials, pec = walls, ports, eps0 = 1.0, mu0 = 1.0) + S = solve_sweep(model, [2.0]).S[:, :, 1] # only TE10 propagates at ω = 2 + @test S[1, 2] ≈ S[2, 1] atol = 1.0e-12 + return sum(abs2, S[:, 1]) + end + # A taper from width 2 to 3. + n = 2 + taper = generate_grid(Tetrahedron, (2n, n, n), Vec(0.0, 0.0, 0.0), Vec(2.0, 0.5, 0.5)) + for i in eachindex(taper.nodes) + x = taper.nodes[i].x + taper.nodes[i] = Node(Vec(x[1] * (1 + x[3]), x[2], x[3])) + end + @test power(taper) ≈ 1 atol = 1.0e-8 + # A dielectric insert in a guide. + guide = generate_grid(Tetrahedron, (8, 4, 8), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + addcellset!(guide, "insert", x -> x[1] <= 1 && 0.25 <= x[3] <= 1.75) + @test power(guide) ≈ 1 atol = 1.0e-8 + @test power(guide, Dict("insert" => MaxwellMaterial(; eps_r = 4.0))) ≈ 1 atol = 1.0e-8 + # A short inclusion next to the ports. + short = generate_grid(Tetrahedron, (6, 3, 4), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 1.0)) + addcellset!(short, "load", x -> x[1] <= 1 + 1.0e-10 && 0.25 - 1.0e-10 <= x[3] <= 0.75 + 1.0e-10; all = true) + @test power(short, Dict("load" => MaxwellMaterial(; eps_r = 9.0))) ≈ 1 atol = 1.0e-8 +end + +@testset "frequencies that are not finite are rejected before any solve" begin + model = wr90(5.0, 10.0) + for ω in (NaN, Inf, -Inf) + @test_throws "finite positive frequencies" solve_sweep(model, [2π * 10.0e9, ω]) + end +end From edcbb3d4da93c3c68fb04df86bb7a84e97929414 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 22:12:33 +0000 Subject: [PATCH 19/21] Docstrings: the wave-port term is rank-one, and extra blocks are copies of a model block The port term is i beta L / mu_r p p^T / norm on the widened pattern, so a matrix from Ferrite.allocate_matrix no longer has the model's pattern. 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/model.jl | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 78f40745..d53890ae 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -69,7 +69,9 @@ sparse blocks on one sparsity pattern, each with a complex coefficient that is a `Kc = ∫ μr⁻¹ ∇×Nᵢ ⋅ ∇×Nⱼ`, `Mε' = ∫ Re(εr) Nᵢ⋅Nⱼ`, `Mε'' = ∫ Im(εr) Nᵢ⋅Nⱼ` and `Mσ = ∫ σ Nᵢ⋅Nⱼ` over the mesh (so `Im(εr) = -ε''` gives the `+iω²μ0ε0L² ε''` loss term). The absorbing boundary adds `+i k0 L ∮ sqrt(εc/μr) (n × Nᵢ)⋅(n × Nⱼ) dS` (`k0 = ω sqrt(μ0 ε0)`, material of the adjacent cell) and each -wave port `+i (β(ω)/μr) L ∮ (n × Nᵢ)⋅(n × Nⱼ) dS` over its face. `A` is complex symmetric, not Hermitian. +wave port `+i (β(ω)/μr) L p pᵀ / norm`, the rank-one term of the TE10 projection of its face (see [`WavePort`](@ref) and +[`FiniteElementMethod.WavePortData`](@ref)), whose dof pairs widen the cell-based sparsity pattern. `A` is complex +symmetric, not Hermitian. Fields: `grid`, `dh`, `ch` (zero `AffineConstraint`s on the PEC edge dofs), `cellvalues`, `materials` (one per cell), `pec`, `eps0`, `mu0`, `length_scale`, `blocks` (the volume blocks `curlcurl`, `eps_real`, @@ -231,7 +233,8 @@ _same_pattern(A, B) = A.colptr == B.colptr && rowvals(A) == rowvals(B) add_term!(model::MaxwellModel, block, coefficient) Append the term `coefficient(ω) * block` to the system matrix of `model`. `block` must have the sparsity -pattern of `model.blocks`, as every matrix from `Ferrite.allocate_matrix(model.dh)` does. +pattern of `model.blocks`, which a wave port widens beyond that of `Ferrite.allocate_matrix(model.dh)`: make it as a copy +of `model.blocks.curlcurl` with its values zeroed, or with `tangential_mass` for a boundary term. """ function add_term!(model::MaxwellModel, block::SparseMatrixCSC{Float64, Int}, coefficient) _same_pattern(block, model.blocks.curlcurl) || From f836a5d8bb7a4b459088ba627a76e321814b22ab Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 22:52:42 +0000 Subject: [PATCH 20/21] Comment: the port's modal boundary term and its sign The comment now states the boundary residual +(i beta/mu_r) c e - 2 (i beta/mu_r) E0 e that the operator and load implement. 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/ports.jl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index c0bc838e..6222bee4 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -273,10 +273,10 @@ function cutoff_frequency(model, port::Integer) return data.kc / (2π * sqrt(model.mu0 * model.eps0 * real(data.eps_r) * data.mu_r)) end -# n × μr⁻¹∇ × E = -(iβ/μr) c e - 2(iβ/μr) E0 e on the port, with c = pᵀu / norm the TE10 amplitude of the trace and -# e the mode, gives +(iβ/μr) L p pᵀ / norm on the operator and +2(iβ/μr) L E0 p on the load, with E0 = 1. Only the -# TE10 amplitude sees the port: the rest of the trace, which is evanescent, has the natural boundary condition and -# absorbs no power. +# For the outgoing exp(-iβζ) convention the port adds +(iβ/μr) c e - 2(iβ/μr) E0 e to the boundary residual, with +# c = pᵀu / norm the TE10 amplitude of the trace, e the mode and E0 = 1 the incident amplitude: +(iβ/μr) L p pᵀ / norm +# on the operator and +2(iβ/μr) L E0 p on the load. Only the TE10 amplitude sees the port: the rest of the trace, which +# is evanescent, has the natural boundary condition and absorbs no power. function _port_term(data::WavePortData, mu0eps0, L) return MaxwellTerm(data.coupling, ω -> im * _propagation_constant(data, mu0eps0, _nonnegative_frequency(ω)) * L / data.mu_r) end From 59959b6efed4417d6bd20a3308757d899494d37d Mon Sep 17 00:00:00 2001 From: xtalax-droid Date: Fri, 13 Nov 2026 01:24:58 +0000 Subject: [PATCH 21/21] Add adjoint S-parameter sensitivities to material parameters (#80) Add discrete adjoint material sensitivities for Maxwell S-parameters Antenna and filter optimisation needs gradients of S-parameters with respect to material parameters. A(omega) is complex symmetric, so the adjoint of each wave port's output is the forward field with that port driven: s_parameter_sensitivities gives dS/dp for eps_r, Im eps_r, mu_r and sigma of named cell sets from the sweep's fields with no extra solve, including the absorbing boundary's dependence on the adjacent material. adjoint_gradient covers real field functionals with one adjoint solve through the pluggable solver interface. Validated against central finite differences of the forward sweep (relative agreement 1e-10 to 2e-8) and against the closed-form WR-90 dielectric slab. Agent-Review: unreviewed Merge maxwell/3-sweep-abc into maxwell/8-adjoint (PR workflow triggers) Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into maxwell/8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Adjoint sensitivities: reject nonsymmetric added terms The adjoint of a port is its forward field, and the adjoint solve uses A, only when A is symmetric; add_term! accepts any block of the right pattern, so the three entry points now check the blocks are symmetric and throw an ArgumentError otherwise. Agent-Review: unreviewed Adjoint sensitivities: scale-free symmetry check The absolute floor accepted a tiny nonsymmetric block with a huge coefficient; the check is now relative to the block. Agent-Review: unreviewed Adjoint: absorbing coefficient derivative is 0 at omega = 0 Consistent with the forward absorbing coefficient. Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Adjoint: check symmetry on the free dofs only A large symmetric entry on a constrained dof could hide a nonsymmetric free operator, so the sensitivities accepted models whose adjoint is wrong. The relative skew is now measured on the unconstrained sub-block, with the same tolerance. Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Adjoint: differentiate the outgoing-branch absorbing admittance The absorbing term now takes the outgoing root for a lossless negative eps_r/mu_r; the derivative uses the same branch. Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Adjoint: the absorbing admittance derivative follows the sign of omega Uses the same outgoing branch as the operator. Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Merge forge/mwsync-3-sweep-abc into 8-adjoint Agent-Review: unreviewed Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Co-authored-by: Claude Code Agent-Harness: Claude Code 2.1.319 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Harness: Claude Code 2.1.322 --- docs/src/maxwell.md | 30 ++++++ src/FiniteElementMethod.jl | 4 +- src/maxwell/adjoint.jl | 203 +++++++++++++++++++++++++++++++++++ test/Maxwell/adjoint.jl | 211 +++++++++++++++++++++++++++++++++++++ 4 files changed, 447 insertions(+), 1 deletion(-) create mode 100644 src/maxwell/adjoint.jl create mode 100644 test/Maxwell/adjoint.jl diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 62b5110e..e024f871 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -95,3 +95,33 @@ FiniteElementMethod.EPS0 FiniteElementMethod.MU0 FiniteElementMethod.C0 ``` + +## Material sensitivities + +[`s_parameter_sensitivities`](@ref) returns the derivatives of the wave-port S-parameters with respect to +material parameters of named cell sets: `:eps_r` (the real part of `εr`), `:eps_r_imag` (its imaginary +part), `:mu_r` and `:sigma`, each shifting that parameter on every cell of the set. They are the exact +derivatives of the discrete S-parameters, by the discrete adjoint: the system matrix is complex symmetric, +so the adjoint field of port `i` is the forward field with port `i` driven, and the sensitivities cost no +linear solve beyond the sweep, only one sparse product per parameter and frequency. A parameter set may +touch an absorbing boundary (its `sqrt(εc/μr)` is differentiated) but not a wave port, whose mode is taken +in fixed material. + +```julia +grid = generate_grid(Tetrahedron, (12, 6, 15), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 30.0)) +addcellset!(grid, "slab", x -> 10.0 - 1.0e-9 <= x[3] <= 20.0 + 1.0e-9; all = true) +ports = [WavePort(face; a_direction = (1, 0, 0), deembed = 10.0) for face in ("bottom", "top")] +model = MaxwellModel(grid; materials = Dict("slab" => MaxwellMaterial(; eps_r = 2.2)), + pec = ["left", "right", "front", "back"], ports, length_scale = 1.0e-3) +sens = s_parameter_sensitivities(model, [2π * 10.0e9], [(:eps_r, "slab"), (:sigma, "slab")]) +sens.dS[1, 1, 1, 1] # dS11/dεr at 10 GHz +``` + +For a real objective such as `|S11|²`, the gradient is `2 Re(conj(S11) dS11/dp)`. Other real functionals +`J(u)` of the field take one adjoint solve with [`adjoint_gradient`](@ref). + +```@docs +s_parameter_sensitivities +MaxwellSensitivities +adjoint_gradient +``` diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index c3ef7bbd..967f4a72 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -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, findnz, nnz, nonzeros, nzrange, rowvals, sparse +using SparseArrays: SparseMatrixCSC, dropzeros!, findnz, nnz, nonzeros, nzrange, rowvals, sparse using SymbolicUtils: SymbolicUtils using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap @@ -57,9 +57,11 @@ include("maxwell/ports.jl") include("maxwell/model.jl") include("maxwell/driven.jl") include("maxwell/sweep.jl") +include("maxwell/adjoint.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! export MaxwellSolution, driven_problem, solve_driven, field_values export WavePort, MaxwellSweep, solve_sweep +export MaxwellSensitivities, s_parameter_sensitivities, adjoint_gradient include("precompile.jl") diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl new file mode 100644 index 00000000..c8d7b8ad --- /dev/null +++ b/src/maxwell/adjoint.jl @@ -0,0 +1,203 @@ +# Discrete adjoint sensitivities of a MaxwellModel with respect to the material parameters of named cell sets. +# A is complex symmetric (Aᵀ = A), so the adjoint of a wave port's output is the forward field with that port +# driven, and the S-parameter sensitivities need no solve beyond the forward sweep. + +const _PARAMETER_KINDS = (:eps_r, :eps_r_imag, :mu_r, :sigma) + +# The adjoint of a port is its forward field only for a symmetric A, but `add_term!` takes any block with the +# model's sparsity pattern. Only the free dofs count: the constrained rows and columns are replaced by the identity, +# so a large entry on a constrained dof must not hide the asymmetry of the operator that is solved. +function _check_symmetric(model) + free = setdiff(axes(model.blocks.curlcurl, 1), model.ch.prescribed_dofs) + for (k, term) in pairs(model.terms) + B = term.block[free, free] + norm(B - transpose(B), 1) <= 1.0e-12 * norm(B, 1) || + throw(ArgumentError("term $k of the model has a nonsymmetric block, so A is not symmetric and the adjoint needs transpose(A); the sensitivities support symmetric terms only")) + end + return nothing +end + +# ∫ w ∇×Nᵢ⋅∇×Nⱼ (curl = true) or ∫ w Nᵢ⋅Nⱼ over `cells`, with the real weight `w = weight(cell)`, with the +# zeros outside `cells` dropped. +function _region_block(model, cells, curl::Bool, weight) + block = copy(model.blocks.curlcurl) + asm = Ferrite.start_assemble(block) + cv = model.cellvalues + n = Ferrite.getnbasefunctions(cv) + Ke = zeros(n, n) + for cc in Ferrite.CellIterator(model.dh, collect(cells)) + Ferrite.reinit!(cv, cc) + fill!(Ke, 0.0) + for q in 1:Ferrite.getnquadpoints(cv) + dΩ = Ferrite.getdetJdV(cv, q) + for i in 1:n, j in 1:n + Ke[i, j] += dΩ * ( + curl ? dot(Ferrite.shape_curl(cv, q, i), Ferrite.shape_curl(cv, q, j)) : + dot(Ferrite.shape_value(cv, q, i), Ferrite.shape_value(cv, q, j)) + ) + end + end + Ferrite.assemble!(asm, Ferrite.celldofs(cc), weight(Ferrite.cellid(cc)) .* Ke) + end + return dropzeros!(block) +end + +# d sqrt(εc/μr) / dp for the material `m`, with εc = εr - iσ/(ωε0). +function _abc_admittance_derivative(kind, m, ω, eps0) + εc = m.eps_r - im * m.sigma / (ω * eps0) + y = _admittance(εc, m.mu_r, ω) + kind === :mu_r && return -y / (2 * m.mu_r) + dεc = kind === :eps_r ? 1.0 + 0.0im : kind === :eps_r_imag ? 1.0im : -im / (ω * eps0) + return y / (2εc) * dεc +end + +# dA/dp as MaxwellTerms, for p the parameter `kind` of every cell of the cell set `name` shifted together. +function _parameter_terms(model, (kind, name)) + kind in _PARAMETER_KINDS || + throw(ArgumentError("unknown material parameter $(repr(kind)); use one of $(_PARAMETER_KINDS)")) + name = String(name) + _check_cellset(model.grid, name) + cells = Ferrite.getcellset(model.grid, name) + for data in model.ports, (cell, _) in Ferrite.getfacetset(model.grid, data.port.facetset) + cell in cells && throw( + ArgumentError( + "cell set $(repr(name)) touches wave port $(repr(data.port.facetset)), whose mode depends on its material; " * + "sensitivities need the ports in fixed material" + ) + ) + end + (; mu0, eps0, length_scale) = model + L2 = length_scale^2 + k2 = mu0 * eps0 * L2 + terms = if kind === :mu_r + [MaxwellTerm(_region_block(model, cells, true, cell -> -1 / model.materials[cell].mu_r^2), Returns(1.0 + 0.0im))] + else + M = _region_block(model, cells, false, Returns(1.0)) + coefficient = kind === :eps_r ? (ω -> complex(-k2 * ω^2)) : kind === :eps_r_imag ? (ω -> -im * k2 * ω^2) : + (ω -> im * mu0 * L2 * ω) + [MaxwellTerm(M, coefficient)] + end + # The absorbing boundary on cells of the set: +i k0 L sqrt(εc/μr) ∮ (n × Nᵢ)⋅(n × Nⱼ) dS, per material. + abc_cells = [facet[1] for facetset in model.absorbing for facet in Ferrite.getfacetset(model.grid, facetset) if facet[1] in cells] + for m in unique(model.materials[abc_cells]) + block = _tangential_mass( + model.dh, model.blocks.curlcurl, model.absorbing, cell -> Float64(cell in cells && model.materials[cell] == m) + ) + push!( + terms, MaxwellTerm( + dropzeros!(block), + # 0 at ω = 0, as the forward absorbing coefficient is, where εc = εr - iσ/(ωε0) is 0/0 for σ = 0. + ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * length_scale * _abc_admittance_derivative(kind, m, ω, eps0) + ) + ) + end + return terms +end + +# Σₜ cₜ(ω) Bₜ U for the terms of one dA/dp. +_derivative_times(terms, ω, U) = sum(term.coefficient(ω) .* (term.block * U) for term in terms) + +""" + MaxwellSensitivities + +The result of [`s_parameter_sensitivities`](@ref): `omegas`, the scattering matrices `S[:, :, k]` as in +[`MaxwellSweep`](@ref), `params` and `dS[i, j, k, l]`, the derivative of `S[i, j, k]` with respect to the real +parameter `params[l]`. +""" +struct MaxwellSensitivities + omegas::Vector{Float64} + S::Array{ComplexF64, 3} + params::Vector{Tuple{Symbol, String}} + dS::Array{ComplexF64, 4} +end + +_normalise_params(params) = Tuple{Symbol, String}[(Symbol(kind), String(name)) for (kind, name) in params] + +""" + s_parameter_sensitivities(model::MaxwellModel, omegas, params; solver = umfpack_solver) + s_parameter_sensitivities(model::MaxwellModel, sweep::MaxwellSweep, params) + +The wave-port scattering matrices of `model` at the angular frequencies `omegas` and their derivatives with +respect to the material parameters `params`, as [`MaxwellSensitivities`](@ref). Each parameter is a pair +`(kind, cellset)`: `kind` is `:eps_r` (the real part of `εr`), `:eps_r_imag` (its imaginary part, `-ε''`), +`:mu_r` or `:sigma`, and the derivative is with respect to that parameter of every cell of the named cell set +shifted by the same amount (the set need not be one of the `materials` keys). The second method reuses the +fields of a sweep run with `fields = true`. + +These are the exact derivatives of the discrete S-parameters. Since `A(ω)` is complex symmetric, the adjoint +field of port `i` is the forward field `uᵢ` with port `i` driven, so + + dSᵢⱼ/dp = -uᵢᵀ (dA/dp) uⱼ / (2iβᵢ L Pᵢ / μr,ᵢ) ⋅ (power-wave and de-embedding factors of Sᵢⱼ), + +at no linear solve beyond [`solve_sweep`](@ref). `dA/dp` is assembled once per parameter over the cells of its +set, including the absorbing boundary's `sqrt(εc/μr)` on those cells. A cell set adjacent to a wave port is +rejected: the port's mode, excitation and normalisation depend on its material, and are taken as fixed. +Terms added with [`FiniteElementMethod.add_term!`](@ref) are taken as independent of the parameters, and must have +symmetric blocks (an `ArgumentError` otherwise). +""" +function s_parameter_sensitivities(model::MaxwellModel, omegas, params; solver = umfpack_solver) + params = _normalise_params(params) + _check_symmetric(model) + terms = [_parameter_terms(model, param) for param in params] # validate before solving + return _s_parameter_sensitivities(model, solve_sweep(model, omegas; fields = true, solver), params, terms) +end + +function s_parameter_sensitivities(model::MaxwellModel, sweep::MaxwellSweep, params) + sweep.fields === nothing && + throw(ArgumentError("the sweep has no fields; run solve_sweep with fields = true")) + all(U -> size(U) == (Ferrite.ndofs(model.dh), length(model.ports)), sweep.fields) || + throw(ArgumentError("the sweep's fields do not match the dofs and ports of the model")) + params = _normalise_params(params) + _check_symmetric(model) + terms = [_parameter_terms(model, param) for param in params] + return _s_parameter_sensitivities(model, sweep, params, terms) +end + +function _s_parameter_sensitivities(model, sweep, params, terms) + (; omegas, S, fields) = sweep + ports = model.ports + np = length(ports) + mu0eps0, L = model.mu0 * model.eps0, model.length_scale + dS = zeros(ComplexF64, np, np, length(omegas), length(terms)) + for (k, ω) in pairs(omegas) + U = fields[k] + β = [_propagation_constant(data, mu0eps0, ω) for data in ports] + w = [sqrt(data.norm * β[i] / data.mu_r) for (i, data) in pairs(ports)] + shift = [exp(im * β[i] * data.port.deembed * L) for (i, data) in pairs(ports)] + # Aλᵢ = pᵢ gives λᵢ = uᵢ / cᵢ, with cᵢ = 2iβᵢL/μr,ᵢ the excitation scale of port_excitations. + c = [2im * β[i] * L / data.mu_r for (i, data) in pairs(ports)] + for (l, param_terms) in pairs(terms) + G = transpose(U) * _derivative_times(param_terms, ω, U) + for j in 1:np, i in 1:np + dS[i, j, k, l] = -G[i, j] / (c[i] * ports[i].norm) * w[i] / w[j] * shift[i] * shift[j] + end + end + end + return MaxwellSensitivities(omegas, S, params, dS) +end + +""" + adjoint_gradient(model::MaxwellModel, ω, u, dJ_du, params; solver = umfpack_solver, cache = nothing) + +The gradient of a real functional `J(u)` of the field `u` (edge dofs solving `A(ω) u = b`, with `b` +independent of the parameters, as for [`driven_problem`](@ref) or [`port_excitations`](@ref) away from the +parameter sets) with respect to the material parameters `params` (as for +[`s_parameter_sensitivities`](@ref)), as a vector of real numbers. `dJ_du` is the complex gradient +`∂J/∂Re(u) + i ∂J/∂Im(u)`. One adjoint solve `A λ = conj(dJ_du)` (the transpose of `A` is `A`) gives + + dJ/dp = -Re(λᵀ (dA/dp) u). + +The solve is `solver(A, B, cache)` on the constrained `A(ω)`; to reuse an existing factorisation `F` of it, pass +`solver = (A, B, F) -> (F \\ B, F)` and `cache = F`. +""" +function adjoint_gradient(model::MaxwellModel, ω::Real, u::AbstractVector, dJ_du::AbstractVector, params; solver = umfpack_solver, cache = nothing) + _check_symmetric(model) + terms = [_parameter_terms(model, param) for param in _normalise_params(params)] + ω = float(ω) + A = maxwell_operator(model, ω) + Ferrite.apply!(A, model.ch) + rhs = conj.(ComplexF64.(dJ_du)) + rhs[model.ch.prescribed_dofs] .= 0 + λ, _ = solver(A, reshape(rhs, :, 1), cache) + return Float64[-real(dot(conj(vec(λ)), _derivative_times(param_terms, ω, u))) for param_terms in terms] +end diff --git a/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl new file mode 100644 index 00000000..9cdb4487 --- /dev/null +++ b/test/Maxwell/adjoint.jl @@ -0,0 +1,211 @@ +# Discrete adjoint material sensitivities of the WR-90 dielectric slab: against central finite differences of +# the forward sweep (both discrete, so they agree to many digits) and against the closed-form slab. +using FiniteElementMethod, Ferrite, LinearAlgebra, SparseArrays, Test + +const SLAB_A, SLAB_B = 22.86, 10.16 # mm +const SLAB_LEAD, SLAB_D = 10.0, 10.0 # mm of vacuum guide on each side of the slab, and the slab +const SLAB_F = 2π * 10.0e9 +const SLAB_WALLS = ["left", "right", "front", "back"] + +# The slab fills the cross-section over SLAB_LEAD <= z <= SLAB_LEAD + SLAB_D; ports at both ends, de-embedded to +# the slab faces. With `abc = true` the guide ends in an absorbing boundary just behind the slab instead. +function slab_grid(h; abc = false) + len = abc ? SLAB_LEAD + SLAB_D : 2SLAB_LEAD + SLAB_D + n = ceil.(Int, (SLAB_A, SLAB_B, len) ./ h) + grid = generate_grid(Tetrahedron, Tuple(n), Vec(0.0, 0.0, 0.0), Vec(SLAB_A, SLAB_B, len)) + addcellset!(grid, "slab", x -> SLAB_LEAD - 1.0e-9 <= x[3] <= SLAB_LEAD + SLAB_D + 1.0e-9; all = true) + addcellset!(grid, "lead", x -> x[3] <= SLAB_LEAD + 1.0e-9; all = true) + return grid +end + +function slab_model(grid, material; abc = false) + ports = [WavePort("bottom"; a_direction = (1, 0, 0), deembed = SLAB_LEAD)] + abc || push!(ports, WavePort("top"; a_direction = (1, 0, 0), deembed = SLAB_LEAD)) + return MaxwellModel( + grid; materials = Dict("slab" => material), pec = SLAB_WALLS, absorbing = abc ? ["top"] : String[], ports, + length_scale = 1.0e-3, + ) +end + +function shifted(m::MaxwellMaterial, kind, δ) + kind === :eps_r && return MaxwellMaterial(m.eps_r + δ, m.mu_r, m.sigma) + kind === :eps_r_imag && return MaxwellMaterial(m.eps_r + im * δ, m.mu_r, m.sigma) + kind === :mu_r && return MaxwellMaterial(m.eps_r, m.mu_r + δ, m.sigma) + return MaxwellMaterial(m.eps_r, m.mu_r, m.sigma + δ) +end + +# Central differences of S with respect to the slab's `kind`, step δ. +function fd_dS(grid, material, kind, ωs, δ; abc = false) + S(δ) = solve_sweep(slab_model(grid, shifted(material, kind, δ); abc), ωs).S + return (S(δ) - S(-δ)) / 2δ +end + +relerr(a, b) = norm(a - b) / norm(b) + +# Closed form for a lossless slab εr in an otherwise empty guide, referenced to the slab faces. +function slab_closed_form(εr; ω = SLAB_F) + k0, kc = ω / FiniteElementMethod.C0, π / (SLAB_A * 1.0e-3) + β, β2 = sqrt(k0^2 - kc^2), sqrt(εr * k0^2 - kc^2) + Γ, P = (β - β2) / (β + β2), exp(-im * β2 * SLAB_D * 1.0e-3) + return (S11 = Γ * (1 - P^2) / (1 - Γ^2 * P^2), S21 = P * (1 - Γ^2) / (1 - Γ^2 * P^2)) +end + +const SLAB_KINDS = (:eps_r, :eps_r_imag, :mu_r, :sigma) +const SLAB_STEPS = Dict(:eps_r => 1.0e-4, :eps_r_imag => 1.0e-4, :mu_r => 1.0e-4, :sigma => 1.0e-5) + +@testset "closed-form slab" begin + cf = slab_closed_form(2.2) + @test cf.S11 ≈ -0.07985 + 0.18593im atol = 1.0e-4 + @test cf.S21 ≈ -0.89984 - 0.38644im atol = 1.0e-4 + δ = 1.0e-6 + dcf = (slab_closed_form(2.2 + δ).S11 - slab_closed_form(2.2 - δ).S11) / 2δ + grid = slab_grid(2.0) + sens = s_parameter_sensitivities(slab_model(grid, MaxwellMaterial(; eps_r = 2.2)), [SLAB_F], [(:eps_r, "slab")]) + S11, dS11 = sens.S[1, 1, 1], sens.dS[1, 1, 1, 1] + @info "slab against the closed form" S11 cf.S11 dS11 dcf + @test abs(S11 - cf.S11) < 0.01 + @test abs(dS11 - dcf) < 0.05 * abs(dcf) +end + +@testset "adjoint against finite differences: $label" for (label, material) in ( + ("lossless slab", MaxwellMaterial(; eps_r = 2.2)), + ("lossy slab", MaxwellMaterial(; eps_r = 2.2 - 0.05im, mu_r = 1.3, sigma = 0.1)), + ) + grid = slab_grid(2.0) + ωs = 2π .* [9.0e9, 11.0e9] + params = [(kind, "slab") for kind in SLAB_KINDS] + sens = s_parameter_sensitivities(slab_model(grid, material), ωs, params) + @test size(sens.dS) == (2, 2, 2, 4) && sens.params == params + for (l, kind) in pairs(SLAB_KINDS) + fd = fd_dS(grid, material, kind, ωs, SLAB_STEPS[kind]) + err = relerr(sens.dS[:, :, :, l], fd) + @info "dS/d$kind, $label" sens.dS[:, :, 1, l] err + @test err < 1.0e-6 + @test sens.dS[1, 2, :, l] ≈ sens.dS[2, 1, :, l] rtol = 1.0e-8 # reciprocity + end + # The derivative with respect to the imaginary part of εr is i times that of its real part (S is holomorphic in εr). + @test sens.dS[:, :, :, 2] ≈ im .* sens.dS[:, :, :, 1] rtol = 1.0e-10 + # Lossless: dS is then also constrained by unitarity, S'ᴴS + SᴴS' = 0 for real-εr perturbations. + if iszero(material.sigma) + for k in 1:2 + S, dS = sens.S[:, :, k], sens.dS[:, :, k, 1] + @test norm(dS' * S + S' * dS) < 1.0e-3 * norm(dS) + end + end +end + +@testset "absorbing boundary on the parameter set" begin + grid = slab_grid(2.0; abc = true) + material = MaxwellMaterial(; eps_r = 2.2 - 0.05im, mu_r = 1.3, sigma = 0.1) + params = [(kind, "slab") for kind in SLAB_KINDS] + sens = s_parameter_sensitivities(slab_model(grid, material; abc = true), [SLAB_F], params) + for (l, kind) in pairs(SLAB_KINDS) + fd = fd_dS(grid, material, kind, [SLAB_F], SLAB_STEPS[kind]; abc = true) + err = relerr(sens.dS[:, :, :, l], fd) + @info "dS11/d$kind with the ABC on the slab" only(sens.dS[:, :, :, l]) err + @test err < 1.0e-6 + end +end + +@testset "adjoint gradient of a field functional" begin + grid = slab_grid(2.0) + material = MaxwellMaterial(; eps_r = 2.2 - 0.05im, mu_r = 1.3, sigma = 0.1) + params = [(kind, "slab") for kind in SLAB_KINDS] + # J = Σ|u|² over the field with port 1 driven: dJ/du = ∂J/∂Re u + i ∂J/∂Im u = 2u. + J(model) = sum(abs2, solve_sweep(model, [SLAB_F]; fields = true).fields[1][:, 1]) + model = slab_model(grid, material) + u = solve_sweep(model, [SLAB_F]; fields = true).fields[1][:, 1] + grad = adjoint_gradient(model, SLAB_F, u, 2 .* u, params) + for (l, kind) in pairs(SLAB_KINDS) + δ = SLAB_STEPS[kind] + fd = (J(slab_model(grid, shifted(material, kind, δ))) - J(slab_model(grid, shifted(material, kind, -δ)))) / 2δ + @info "dJ/d$kind" grad[l] fd + @test grad[l] ≈ fd rtol = 1.0e-6 + end + # The same through a supplied factorisation of the constrained operator. + A = maxwell_operator(model, SLAB_F) + apply!(A, model.ch) + F = lu(A) + @test adjoint_gradient(model, SLAB_F, u, 2 .* u, params; solver = (A, B, F) -> (F \ B, F), cache = F) ≈ grad +end + +@testset "sensitivity inputs" begin + grid = slab_grid(3.0) + model = slab_model(grid, MaxwellMaterial(; eps_r = 2.2)) + @test_throws "no cell set" s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "nope")]) + @test_throws "unknown material parameter" s_parameter_sensitivities(model, [SLAB_F], [(:epsilon, "slab")]) + @test_throws "touches wave port" s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "lead")]) + sweep = solve_sweep(model, [SLAB_F]) + @test_throws "no fields" s_parameter_sensitivities(model, sweep, [(:eps_r, "slab")]) + @test_throws "do not match" s_parameter_sensitivities( + model, MaxwellSweep(sweep.omegas, sweep.S, [zeros(ComplexF64, 3, 2)]), [(:eps_r, "slab")] + ) + @test size(s_parameter_sensitivities(model, [SLAB_F], []).dS) == (2, 2, 1, 0) + @test adjoint_gradient(model, SLAB_F, zeros(ComplexF64, ndofs(model.dh)), zeros(ndofs(model.dh)), []) == Float64[] + # A sweep with fields gives the same as solving inside; a set with no free dofs has zero sensitivity. + sweep = solve_sweep(model, [SLAB_F]; fields = true) + @test s_parameter_sensitivities(model, sweep, [("eps_r", "slab")]).dS ≈ + s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "slab")]).dS + addcellset!(grid, "empty", Int[]) + @test iszero(s_parameter_sensitivities(model, sweep, [(:sigma, "empty")]).dS) +end + +@testset "sensitivities reject a model with a nonsymmetric term" begin + model = slab_model(slab_grid(3.0), MaxwellMaterial(; eps_r = 2.2)) + extra = copy(model.blocks.sigma) + nonzeros(extra) .= rand(nnz(extra)) + FiniteElementMethod.add_term!(model, extra, ω -> 1.0) + # A tiny block with a huge coefficient is as nonsymmetric as a large one. + tiny = copy(model.blocks.sigma) + nonzeros(tiny) .= 0 + rows, cols = findnz(tiny) + scaled = slab_model(slab_grid(3.0), MaxwellMaterial(; eps_r = 2.2)) + i = findfirst(k -> rows[k] != cols[k] && rows[k] ∉ scaled.ch.prescribed_dofs && cols[k] ∉ scaled.ch.prescribed_dofs, eachindex(rows)) + nonzeros(tiny)[i] = 1.0e-13 + FiniteElementMethod.add_term!(scaled, tiny, ω -> 1.0e13) + @test_throws "nonsymmetric" s_parameter_sensitivities(scaled, [SLAB_F], [(:eps_r, "slab")]) + u = zeros(ComplexF64, ndofs(model.dh)) + @test_throws "nonsymmetric" s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "slab")]) + @test_throws "nonsymmetric" adjoint_gradient(model, SLAB_F, u, zeros(ndofs(model.dh)), [(:eps_r, "slab")]) + @test_throws "nonsymmetric" s_parameter_sensitivities( + model, MaxwellSweep([SLAB_F], zeros(ComplexF64, 2, 2, 1), [zeros(ComplexF64, ndofs(model.dh), 2)]), [(:eps_r, "slab")] + ) +end + +@testset "the symmetry check ignores constrained dofs" begin + grid = generate_grid(Tetrahedron, (4, 2, 6), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 3.0)) + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("top"; a_direction = (1, 0, 0))] + addcellset!(grid, "core", x -> 1.0 - 1.0e-9 <= x[3] <= 2.0 + 1.0e-9; all = true) + model = MaxwellModel(grid; pec = SLAB_WALLS, ports, eps0 = 1.0, mu0 = 1.0) + ω = 2.5 + # A nonsymmetric block on the free dofs, padded with a huge symmetric entry on a PEC dof. + padded = copy(model.blocks.eps_real) + rows = rowvals(padded) + for j in axes(padded, 2), k in nzrange(padded, j) + nonzeros(padded)[k] *= 1 + 0.7 * sin(rows[k]) + end + pec_dof = first(model.ch.prescribed_dofs) + padded[pec_dof, pec_dof] = 1.0e16 + FiniteElementMethod.add_term!(model, padded, _ -> 3.0) + u = zeros(ComplexF64, ndofs(model.dh)) + @test_throws "nonsymmetric" s_parameter_sensitivities(model, [ω], [(:eps_r, "core")]) + @test_throws "nonsymmetric" s_parameter_sensitivities( + model, MaxwellSweep([ω], zeros(ComplexF64, 2, 2, 1), [zeros(ComplexF64, ndofs(model.dh), 2)]), [(:eps_r, "core")] + ) + @test_throws "nonsymmetric" adjoint_gradient(model, ω, u, zeros(ndofs(model.dh)), [(:eps_r, "core")]) +end + +@testset "the absorbing boundary's derivative is finite at ω = 0" begin + grid = slab_grid(3.0; abc = true) + model = slab_model(grid, MaxwellMaterial(; eps_r = 2.2); abc = true) + n = ndofs(model.dh) + # The static operator is singular, so the adjoint solve is stubbed: only dA/dp u is under test. + stub(A, B, cache) = (zeros(ComplexF64, size(B)), cache) + for kind in SLAB_KINDS + g = adjoint_gradient(model, 0.0, ones(ComplexF64, n), ones(n), [(kind, "slab")]; solver = stub) + @test all(isfinite, g) + end + for kind in SLAB_KINDS, term in FiniteElementMethod._parameter_terms(model, (kind, "slab")) + @test isfinite(term.coefficient(0.0)) + end +end