From df895202bede635a188bbe9a53a2bb066faae979 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:13:23 +0000 Subject: [PATCH 01/34] 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/34] 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/34] 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/34] 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 b52e5be1fac29af248bde123f0ef2fcc5df8947c Mon Sep 17 00:00:00 2001 From: t Date: Fri, 6 Nov 2026 01:42:06 +0000 Subject: [PATCH 05/34] Recognise the absorbing boundary, wave ports and sweeps in the Maxwell PDESystem front end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The time-domain Silver-Müller condition cross(n, ν curl E) = -sqrt(ε/μ) cross(n, cross(n, Dt E)) is recognised per piece by comparing its row space with the matched condition of the adjacent lossless cell at the actual normal of every facet, and maps to MaxwellModel's absorbing block. Wave ports are a ports keyword on FEMDiscretization, and solve_sweep(pdesys, disc, omegas) sweeps the model. Tests check S-parameters against the operator-level model exactly. 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/boundary_conditions.md | 2 +- docs/src/maxwell.md | 35 +++++- src/FiniteElementMethod.jl | 4 +- src/discretization.jl | 16 ++- src/maxwell/frontend.jl | 215 +++++++++++++++++++++++++------- test/Maxwell/frontend_ports.jl | 177 ++++++++++++++++++++++++++ 6 files changed, 397 insertions(+), 52 deletions(-) create mode 100644 test/Maxwell/frontend_ports.jl diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index b42b62af..4cf45f21 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -33,7 +33,7 @@ Restrictions of this release: - Where two Dirichlet pieces of one field meet, the condition listed last in the `PDESystem` wins. - Every field with a time derivative needs an initial condition, linear in that one field and finite at every node. - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected. - - With `omega`, a time-domain curl-curl equation for a 3-component unknown in a Nédélec space becomes a frequency-domain `LinearProblem` (see `maxwell_model`); its only boundary condition is the perfect conductor `n × E = 0`, other pieces get `n × (ν curl E) = 0`, and its coefficients are real. + - With `omega`, a time-domain curl-curl equation for a 3-component unknown in a Nédélec space becomes a frequency-domain `LinearProblem` (see `maxwell_model`); its boundary conditions are the perfect conductor `n × E = 0` and the matched first-order absorbing condition `n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE)` on lossless cells, wave ports are the `ports` keyword, other pieces get `n × (ν curl E) = 0`, and its coefficients are real. "Time-dependent" means boundary data that varies with time, for every condition kind. diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index f5c2fe2a..1a077f50 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -64,7 +64,7 @@ for the equivalent `MaxwellModel` (in units with `ε0 = μ0 = 1`). The operator and the perfect conductor with [`facet_normal`](@ref), which needs a PDEBase with facet normals. ```julia -using FiniteElementMethod, Ferrite, ModelingToolkit, LinearAlgebra, LinearSolve +using FiniteElementMethod, Ferrite, ModelingToolkit, DomainSets, LinearAlgebra, LinearSolve grid = generate_grid(Tetrahedron, (8, 8, 8), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) Ω = MeshDomain(grid) @parameters x y z t @@ -81,7 +81,38 @@ field_values(MaxwellSolution(model, omega, sol.u), [Vec(0.5, 0.5, 0.5)]).E ``` Coefficients are real, so a complex permittivity `ε' - iε''` is only available on the operator-level -`MaxwellModel`. Absorbing boundaries and ports are not yet part of the `PDESystem` path. +`MaxwellModel`. + +### Absorbing boundaries, ports and sweeps + +The first-order absorbing condition is written in its time-domain form, +`n × (ν ∇ × E) = -sqrt(ε/μ) n × (n × ∂ₜE)` with `ε = a₂` and `ν = 1/μ` of the cells next to the piece. With +`∂ₜ = iω` and `ε0 = μ0 = 1` this is the model's `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εr/μr) n × (n × E)`, so the +piece goes to `absorbing`. Any equivalent set of equations is accepted; at the actual normal of every facet the +conditions must span exactly the two tangential equations of this one, and a different coefficient of +`curl E`, a different impedance, the opposite sign or an added term is an error. The cells next to the piece +must be lossless (`a₁ = a₀ = 0`); a lossy one has no time-domain form here and needs `MaxwellModel`'s +`absorbing` keyword. + +A [`WavePort`](@ref) is modal data rather than a local condition, so ports are the `ports` keyword of +`FEMDiscretization`, on pieces without a condition in the `PDESystem`. `discretize` treats them as matched +terminations of the source problem; `solve_sweep(pdesys, disc, omegas)` drives them and returns the scattering +matrices, as `solve_sweep(maxwell_model(pdesys, disc).model, omegas)` does. With ports `a₀` must be zero, so +that the model does not depend on `omega`, and a sweep rejects a volume source. + +```julia +grid = generate_grid(Tetrahedron, (12, 6, 15), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 30.0)) # WR-90, mm +Ω = MeshDomain(grid) +n, Eb = facet_normal(boundarypiece(Ω, :top)), [E(t, boundarypiece(Ω, :top))[c] for c in 1:3] +abc = cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.(Eb))) +pec = reduce(vcat, [cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0 for Γ in boundarypiece.(Ref(Ω), [:left, :right, :front, :back])]) +eqs = [curl(curl(Ev, X), X)[c] + Dt(Dt(Ev[c])) ~ 0 for c in 1:3] +@named sys = PDESystem(eqs, [pec; abc], [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [E(t, x, y, z)]) +k0 = 2π * 10.0e9 / FiniteElementMethod.C0 * 1.0e-3 # 10 GHz in rad/mm +ports = [WavePort(boundarypiece(Ω, :bottom); a_direction = (1, 0, 0))] +disc = FEMDiscretization(Ω, t; omega = k0, spaces = Dict(E => Nedelec{RefTetrahedron, 1}()), ports) +solve_sweep(sys, disc, k0 .* [0.8, 1.0, 1.2]).S # |S11| ≈ 0.14 at 10 GHz, the reflection of the absorbing end +``` ```@docs curl(::AbstractVector, ::NTuple{3, Any}) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index a47aaa85..13d47daf 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, curl using ForwardDiff: ForwardDiff -using LinearAlgebra: cross, dot, lu, lu!, mul!, norm, rank +using LinearAlgebra: cross, dot, lu, lu!, mul!, norm, rank, svd using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -43,6 +43,7 @@ export FieldInfo, FEMMetadata, piece_nodes, normal_flux, write_vtk, facet_dofs, export Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using PDEBase: StrongForm, MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative +include("maxwell/ports.jl") # before the discretization, which holds WavePorts include("discretization.jl") include("frontend.jl") _is_normal_derivative(op) = op isa NormalDerivative @@ -51,7 +52,6 @@ export MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative # Frequency-domain Maxwell: a separate entry point assembled directly on Ferrite; `FEMDiscretization(…; omega)` reaches it # from a PDESystem without the scalar weak form. -include("maxwell/ports.jl") include("maxwell/model.jl") include("maxwell/driven.jl") include("maxwell/sweep.jl") diff --git a/src/discretization.jl b/src/discretization.jl index 82647de5..3f31d0a0 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -8,7 +8,7 @@ PDEBase.contains_point(grid::Ferrite.Grid, x) = _contains_point(grid, x) FEMDiscretization(Ω::MeshDomain, t = nothing; spaces = Dict(), regions = Dict(), quadrature = nothing, test_space = Galerkin(), ibp = Dict(), pairing = Dict(), codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check = :warn, - omega = nothing, kwargs...) + omega = nothing, ports = [], kwargs...) Finite-element discretization of a `PDESystem` whose spatial domain is the mesh domain `Ω` (of a `Ferrite.Grid`), with time variable `t`. `discretize(pdesys, disc)` assembles the @@ -81,6 +81,9 @@ gives a `PDENoTimeSolution`. see [`maxwell_model`](@ref) for the equations it accepts. `omega` must be positive and finite and needs the time variable `t`, which the `PDESystem` is written in; `test_space`, `regions`, `ibp` and `pairing` do not apply to it and must keep their defaults. A Nédélec space needs `omega`. + - `ports`: [`WavePort`](@ref)s of the frequency-domain Maxwell path (with `omega`), on boundary pieces that + have no condition in the `PDESystem`; [`solve_sweep`](@ref) drives them, and `discretize` treats them as + matched terminations. - `codegen = :mtk` is reserved and raises; remaining keywords are passed to the `DAEProblem` (or `NonlinearProblem`), where a keyword given at the `discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters` are set @@ -118,6 +121,7 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization boundary_check::Symbol algebraic_abstol::Union{Symbol, Nothing, Float64} omega::Union{Nothing, Float64} + ports::Vector{WavePort} kwargs::NamedTuple end @@ -151,7 +155,7 @@ function FEMDiscretization( domain::PDEBase.MeshDomain, time = nothing; spaces = Dict(), regions = Dict(), quadrature = nothing, test_space = Galerkin(), ibp = Dict(), pairing = Dict(), codegen::Symbol = :numeric, dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check::Symbol = :warn, - omega = nothing, kwargs... + omega = nothing, ports = WavePort[], kwargs... ) domain.mesh isa Ferrite.Grid || throw(ArgumentError("FEMDiscretization needs a MeshDomain of a Ferrite.Grid, got a mesh of type $(typeof(domain.mesh))")) @@ -178,12 +182,16 @@ function FEMDiscretization( ) _check_reserved(kwargs) _check_omega(omega, time, spaces, test_space, regions, ibp, pairing) + all(p -> p isa WavePort, ports) || + throw(ArgumentError("ports must be WavePorts, as ports = [WavePort(Γ; a_direction = (1, 0, 0))]; got $(repr(ports))")) + omega === nothing && !isempty(ports) && + throw(ArgumentError("ports belong to the frequency-domain Maxwell path; give the angular frequency omega")) return FEMDiscretization{typeof(time)}( domain, time, Dict{Any, Ferrite.Interpolation}(_field_op(k) => ip for (k, ip) in spaces), Dict{Any, Any}(_field_op(k) => r for (k, r) in regions), quadrature, test_space, Dict{Any, StrongForm.IBPPolicy}(ibp), Dict{Equation, Any}(pairing), codegen, dirichlet, unique(natural), boundary_check, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, - omega === nothing ? nothing : Float64(omega), NamedTuple(kwargs) + omega === nothing ? nothing : Float64(omega), WavePort[ports...], NamedTuple(kwargs) ) end @@ -237,6 +245,6 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Where two Dirichlet pieces of one field meet, the condition listed last in the `PDESystem` wins. - Every field with a time derivative needs an initial condition, linear in that one field and finite at every node. - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected. - - With `omega`, a time-domain curl-curl equation for a 3-component unknown in a Nédélec space becomes a frequency-domain `LinearProblem` (see `maxwell_model`); its only boundary condition is the perfect conductor `n × E = 0`, other pieces get `n × (ν curl E) = 0`, and its coefficients are real. + - With `omega`, a time-domain curl-curl equation for a 3-component unknown in a Nédélec space becomes a frequency-domain `LinearProblem` (see `maxwell_model`); its boundary conditions are the perfect conductor `n × E = 0` and the matched first-order absorbing condition `n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE)` on lossless cells, wave ports are the `ports` keyword, other pieces get `n × (ν curl E) = 0`, and its coefficients are real. """ ) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index daf3cb07..427e87c8 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -194,13 +194,71 @@ function _recognise_volume(an, s, fixed, xs) return (; nu, a..., sources = sources[invperm(comps)]) end -# n × E = 0 conditions: each residual is linear in the traces and the normal, tangential (C n = 0) and of rank 2 -# together on its piece. -function _recognise_pec(bcs, fields, pvals, ctx, domain) - U = [Symbolics.variable(:U, c) for c in 1:3] - N = [Symbolics.variable(:N, d) for d in 1:3] - byp = Dict{Symbol, Vector{Num}}() - pform = "write the perfect conductor as cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0" +const _PEC_FORM = "write the perfect conductor as cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0" +const _ABC_FORM = "write the absorbing condition as cross(n, ν * curl(Eb, X)) .~ -sqrt(ε / μ) .* cross(n, cross(n, Dt.(Eb))) with n = facet_normal(Γ), Eb = [E(t, Γ)[c] for c in 1:3] and the ν = 1/μ and ε (the coefficient of ∂ₜ²E) of the cells next to Γ" + +# Slot form of a boundary residual: the trace of E_c becomes U[c], ∂ₜ of it V[c], ∂ⱼ of it G[c, j] and component d of +# the facet normal N[d]. A derivative of anything but a trace, of order above one, or a normal derivative is an error. +function _boundary_rules!(rules, ex, eq, slots, ctx) + SymbolicUtils.iscall(ex) || return rules + op = SymbolicUtils.operation(ex) + if op isa Differential + inner = _unwrap_arg(only(SymbolicUtils.arguments(ex))) + f = SymbolicUtils.iscall(inner) ? findfirst(isequal(SymbolicUtils.operation(inner)), ctx.ops) : nothing + f !== nothing && op.order == 1 || throw( + ArgumentError("$eq has the derivative $(Num(ex)); a boundary condition with omega may only take first derivatives of the components of E(t, Γ) themselves; $_ABC_FORM") + ) + j = findfirst(isequal(op.x), ctx.sivs) + if isequal(op.x, ctx.t) + rules[ex] = unwrap(slots.V[ctx.fields[f]]) + elseif j !== nothing + rules[ex] = unwrap(slots.G[ctx.fields[f], j]) + else + throw(ArgumentError("$eq has a derivative in $(op.x), which is neither time nor a coordinate")) + end + elseif op isa PDEBase.NormalDerivative + throw(ArgumentError("$eq has a normal derivative; with omega the boundary conditions are the perfect conductor ($_PEC_FORM) and the first-order absorbing condition ($_ABC_FORM)")) + elseif op isa _FacetNormal + rules[ex] = unwrap(slots.N[Int(SymbolicUtils.unwrap_const(only(SymbolicUtils.arguments(ex))))]) + elseif (f = findfirst(isequal(op), ctx.ops)) !== nothing + rules[ex] = unwrap(slots.U[ctx.fields[f]]) + else + foreach(a -> _boundary_rules!(rules, _unwrap_arg(a), eq, slots, ctx), SymbolicUtils.arguments(ex)) + end + return rules +end + +# The residual r of n × (ν curl E) = -c n × (n × ∂ₜE), as the 3×15 matrix acting on [vec(G); V; U]. +function _absorbing_target(n, ν, c) + return reduce( + hcat, map(1:15) do k + w = zeros(15) + w[k] = 1 + G, V = reshape(w[1:9], 3, 3), w[10:12] + curlE = [G[3, 2] - G[2, 3], G[1, 3] - G[3, 1], G[2, 1] - G[1, 2]] + cross(n, ν .* curlE) + c .* cross(n, cross(n, V)) + end + ) +end + +# An orthonormal basis of the row space of M, as rows. +function _rowspace(M) + F = svd(M) + return F.Vt[1:count(>(1.0e-10 * maximum(F.S; init = 0.0)), F.S), :] +end + +# The boundary conditions on each piece: the perfect conductor n × E = 0 (the residuals are linear in the traces and +# the normal, tangential (C n = 0) and of rank 2 together) or, when they hold derivatives of the traces, the +# first-order absorbing condition, whose residuals must span exactly the rows of n × (ν curl E) + c n × (n × ∂ₜE) +# with ν and c = sqrt(ε ν) of the adjacent lossless cell. Both are checked at the actual normal of every facet of the +# piece. `cells` holds ν, a₀, a₁ and a₂ per cell. +function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells) + slots = ( + U = [Symbolics.variable(:U, c) for c in 1:3], V = [Symbolics.variable(:V, c) for c in 1:3], + G = [Symbolics.variable(:G, c, j) for c in 1:3, j in 1:3], N = [Symbolics.variable(:N, d) for d in 1:3], + ) + W = [vec(slots.G); slots.V; slots.U] + byp = Dict{Symbol, Vector{Tuple{Equation, Num}}}() for eq in bcs res = eq.lhs - eq.rhs pieces = _trace_pieces(res) @@ -213,46 +271,62 @@ function _recognise_pec(bcs, fields, pvals, ctx, domain) ) Γ = only(pieces) Γ.parent === domain || throw(ArgumentError("the boundary piece $(Γ.name) of $eq is not a piece of the FEMDiscretization's MeshDomain")) - rules = Dict{Any, Any}() - _walk(res) do ex - SymbolicUtils.iscall(ex) || return - op = SymbolicUtils.operation(ex) - if op isa Union{Differential, PDEBase.NormalDerivative} - throw(ArgumentError("$eq has a derivative; with omega only the perfect conductor n × E = 0 is supported: $pform")) - elseif op isa _FacetNormal - rules[ex] = unwrap(N[Int(SymbolicUtils.unwrap_const(only(SymbolicUtils.arguments(ex))))]) - else - f = findfirst(isequal(op), ctx.ops) - f === nothing || (rules[ex] = unwrap(U[fields[f]])) - end - end + rules = _boundary_rules!(Dict{Any, Any}(), unwrap(res), eq, slots, (; ctx..., fields)) for (p, value) in zip(ctx.params, pvals) rules[p] = value end B = substitute(res, rules) - extra = [x for x in Symbolics.get_variables(B) if !any(isequal(x), unwrap.([U; N]))] - isempty(extra) || throw(ArgumentError("$eq depends on $(join(Num.(extra), ", ")); $pform")) - push!(get!(byp, Γ.name, Num[]), B) + # Coefficients may depend on the normal but not on the coordinates, so that each facet is checked whole. + extra = [x for x in Symbolics.get_variables(B) if !any(isequal(x), unwrap.([W; slots.N]))] + isempty(extra) || throw(ArgumentError("$eq depends on $(join(Num.(extra), ", ")); $_PEC_FORM, or $_ABC_FORM")) + push!(get!(byp, Γ.name, Tuple{Equation, Num}[]), (eq, B)) end check_facetsets(domain.mesh, collect(keys(byp)); disjoint = false) - for (name, Bs) in byp - C = [Symbolics.derivative(B, u) for B in Bs, u in U] - any(ex -> _depends(unwrap(ex), U), C) && throw(ArgumentError("the conditions on $name are nonlinear in E; $pform")) - any(B -> !_iszero_expr(substitute(B, Dict(unwrap(u) => 0 for u in U))), Bs) && - throw(ArgumentError("the conditions on $name prescribe a nonzero tangential field, which is not supported; $pform")) - C_at = Symbolics.build_function(vec(C), N...; expression = Val(false))[1] + pec, absorbing = String[], String[] + for (name, eqBs) in byp + Bs = last.(eqBs) + C = [Symbolics.derivative(B, w) for B in Bs, w in W] + isabc = any(!_iszero_expr, C[:, 1:12]) + form = isabc ? _ABC_FORM : _PEC_FORM + any(ex -> _depends(unwrap(ex), W), C) && throw(ArgumentError("the conditions on $name are nonlinear in E; $form")) + any(B -> !_iszero_expr(substitute(B, Dict(unwrap(w) => 0 for w in W))), Bs) && throw( + ArgumentError(isabc ? "the absorbing condition on $name has a source (a term without E), which is not supported; drive the field with a WavePort or a volume source; $form" : "the conditions on $name prescribe a nonzero tangential field, which is not supported; $form") + ) + C_at = Symbolics.build_function(vec(C), slots.N...; expression = Val(false))[1] for (n, facet) in _facet_normals(domain.mesh, String(name)) - Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 3) + Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 15) where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" - maximum(abs, Cn * n; init = 0.0) > 1.0e-10 * maximum(abs, Cn; init = 0.0) && throw( - ArgumentError("the conditions $where constrain the normal component of E, unlike n × E = 0; $pform") + if !isabc + Cn = Cn[:, 13:15] + maximum(abs, Cn * n; init = 0.0) > 1.0e-10 * maximum(abs, Cn; init = 0.0) && throw( + ArgumentError("the conditions $where constrain the normal component of E, unlike n × E = 0; $form") + ) + rank(Cn) == 2 || throw( + ArgumentError("the conditions $where constrain $(rank(Cn)) of the two tangential components of E; $form") + ) + continue + end + (; nu, a0, a1, a2) = cells[facet[1]] + a0 == 0 && a1 == 0 && a2 > 0 && nu > 0 || throw( + ArgumentError("the absorbing condition $where borders cell $(facet[1]) with ν = $nu, a₂ = $a2, a₁ = $a1 and a₀ = $a0; the time-domain absorbing condition needs a lossless cell (a₁ = a₀ = 0, a₂ = ε > 0, ν = 1/μ > 0), so build a MaxwellModel with `absorbing` for a lossy one") + ) + c = sqrt(a2 * nu) + Q, P = _rowspace(Cn), _rowspace(_absorbing_target(n, nu, c)) + size(Q, 1) == 2 || throw( + ArgumentError("the conditions $where have $(size(Q, 1)) independent equations; the absorbing condition n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) has 2; $form") ) - rank(Cn) == 2 || throw( - ArgumentError("the conditions $where constrain $(rank(Cn)) of the two tangential components of E; $pform") + norm(Q' * Q - P' * P) <= 1.0e-8 || throw( + ArgumentError("the conditions $where are not n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) of the adjacent cell (ν = $nu, sqrt(ε/μ) = $c): the coefficient of curl E, the impedance or the sign differs, or a term in E is added; $form") ) end + push!(isabc ? absorbing : pec, String(name)) end - return sort!(String.(collect(keys(byp)))) + grid = domain.mesh + for a in absorbing, p in pec + isdisjoint(Ferrite.getfacetset(grid, a), Ferrite.getfacetset(grid, p)) || + throw(ArgumentError("the absorbing piece $a shares facets with the perfect-conductor piece $p; give each facet one condition")) + end + return (; pec = sort!(pec), absorbing = sort!(absorbing)) end """ @@ -270,9 +344,22 @@ one equation per component, written with [`curl`](@ref). ν, a₀, a₁ and a₂ the coordinates and parameters, and the source `f(x)` is read as the phasor amplitude of `exp(+iωt)`. Each cell gets `MaxwellMaterial(eps_r = a₂ - a₀/ω², mu_r = 1/ν, sigma = a₁)` sampled at its centroid, with `eps0 = mu0 = length_scale = 1`, so the system is `Kc - ω² Mε + iω Mσ` of the model and the load is -`∫ f ⋅ Nᵢ`. Boundary conditions are the perfect conductor `cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0`; -pieces without a condition get the natural `n × (ν curl E) = 0`. A complex permittivity has no real -time-domain form here; build a `MaxwellModel` directly for it. +`∫ f ⋅ Nᵢ`. A complex permittivity has no real time-domain form here; build a `MaxwellModel` directly for it. + +With `n = facet_normal(Γ)` and `Eb = [E(t, Γ)[c] for c in 1:3]`, the boundary conditions on a piece `Γ` are + + - the perfect conductor `cross(n, Eb) .~ 0`, the model's `pec`; + - the first-order absorbing (Silver-Müller) condition `cross(n, ν * curl(Eb, X)) .~ -sqrt(ε / μ) .* + cross(n, cross(n, Dt.(Eb)))`, with `ε = a₂` and `ν = 1/μ` of the cells next to `Γ`, the model's `absorbing`. + `Dt` becomes `iω`, so this is the model's `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εr/μr) n × (n × E)` with `k0 = ω`. + Any equivalent set of equations is accepted (a multiple, the other cross order, a linear combination): + at every facet the conditions must span exactly the two tangential equations of this one. The cells next to + `Γ` must be lossless (`a₁ = a₀ = 0`); a mismatched coefficient, impedance or sign is an error, since the + model implements only the matched condition. + +Pieces without a condition get the natural `n × (ν curl E) = 0`, except those carrying the +[`WavePort`](@ref)s of `disc.ports`, which must have no condition. With ports, `a₀` must be zero, so that the +model holds at every frequency and `solve_sweep(model, omegas)` is the sweep of the `PDESystem`. """ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) disc.omega === nothing && @@ -309,25 +396,67 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio fixed = Dict{Any, Any}(unwrap(an.slots.P[j]) => pvals[j] for j in keep) centroids = [sum(Ferrite.getcoordinates(grid, cell)) / 4 for cell in 1:Ferrite.getncells(grid)] coeffs = _recognise_volume(an, slot_s, fixed, centroids) - pec = _recognise_pec(sys.bcs, comps, pvals[keep], (; ops, params = ctx.params[keep]), disc.domain) # Compile the coefficients and sources as functions of the mesh coordinate. X = an.slots.X compile(exs) = Symbolics.build_function([substitute(ex, fixed) for ex in exs], X...; expression = Val(false))[1] coefficient_at = compile([coeffs.nu, coeffs.a0, coeffs.a1, coeffs.a2]) source_at = compile(coeffs.sources) - ω = disc.omega - materials = map(enumerate(centroids)) do (cell, x) + cells = map(enumerate(centroids)) do (cell, x) nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") iszero(nu) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero")) - MaxwellMaterial(; eps_r = a2 - a0 / ω^2, mu_r = 1 / nu, sigma = a1) + (; nu, a0, a1, a2) end + (; pec, absorbing) = _recognise_boundaries( + sys.bcs, comps, pvals[keep], (; ops, params = ctx.params[keep], sivs = ctx.sivs, t = ctx.t), disc.domain, cells + ) + ports = disc.ports + if !isempty(ports) + # A port's modal data and the sweep use the cell materials at every frequency, so they must not depend on ω. + cell = findfirst(c -> !iszero(c.a0), cells) + cell === nothing || throw( + ArgumentError("a₀ = $(cells[cell].a0) in cell $cell, but with wave ports the coefficient of E must be zero: eps_r = a₂ - a₀/ω² would depend on the frequency, which the ports and solve_sweep do not follow") + ) + for port in ports, name in [pec; absorbing] + _check_facetset(grid, port.facetset) + isdisjoint(Ferrite.getfacetset(grid, port.facetset), Ferrite.getfacetset(grid, name)) || throw( + ArgumentError("the wave port on $(port.facetset) is the boundary condition of its facets, but the PDESystem also has a condition on $name, which shares facets with it; remove that condition") + ) + end + end + ω = disc.omega + materials = [MaxwellMaterial(; eps_r = c.a2 - c.a0 / ω^2, mu_r = 1 / c.nu, sigma = c.a1) for c in cells] model = MaxwellModel( - grid; materials, pec, eps0 = 1.0, mu0 = 1.0, length_scale = 1.0, quadrature = something(disc.quadrature, 2) + grid; materials, pec, absorbing, ports, eps0 = 1.0, mu0 = 1.0, length_scale = 1.0, + quadrature = something(disc.quadrature, 2), ) return (; model, omega = ω, load = _source_load(model, x -> _real_values(source_at(x...), "a source"))) end +""" + solve_sweep(pdesys::PDESystem, disc::FEMDiscretization, omegas; kwargs...) + +The wave-port scattering matrices of the `PDESystem` at the angular frequencies `omegas`: `solve_sweep` of +the model of [`maxwell_model`](@ref)`(pdesys, disc)`, which `disc.ports` drive. The `PDESystem` must have no +source, since the sweep excites the ports only; `disc.omega` builds the model but does not enter the result. +""" +function solve_sweep(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization, omegas; kwargs...) + isempty(disc.ports) && + throw(ArgumentError("solve_sweep needs wave ports; give them as FEMDiscretization(Ω, t; omega, spaces, ports = [WavePort(...)])")) + (; model, load) = maxwell_model(pdesys, disc) + any(!iszero, load) && throw( + ArgumentError("solve_sweep drives the wave ports only, but the PDESystem has a source; solve a source with discretize(pdesys, disc) at each omega") + ) + return solve_sweep(model, omegas; kwargs...) +end + +""" + WavePort(Γ::BoundaryPiece; a_direction, e_direction = nothing, deembed = 0.0) + +The [`WavePort`](@ref) on the facet set of the boundary piece `Γ`, for `FEMDiscretization(…; ports)`. +""" +WavePort(Γ::PDEBase.BoundaryPiece; kwargs...) = WavePort(String(Γ.name); kwargs...) + function _real_values(values, what) all(v -> v isa Real && isfinite(v), values) || throw(ArgumentError("$what of the Maxwell equation evaluates to $values; it must be real and finite")) diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl new file mode 100644 index 00000000..5a1aec1b --- /dev/null +++ b/test/Maxwell/frontend_ports.jl @@ -0,0 +1,177 @@ +# The PDESystem front end with the first-order absorbing boundary, wave ports and frequency sweeps, against the +# operator-level MaxwellModel as oracle. A WR-90 guide in millimetres with ε0 = μ0 = 1, so ω is k0 in rad/mm. +# The boundary conditions need PDEBase's facet normal (SciML/PDEBase.jl#164); without it those tests are skipped. +using FiniteElementMethod, Ferrite, ModelingToolkit, DomainSets, LinearAlgebra, Test +using SciMLBase: LinearProblem, discretize +using FiniteElementMethod: PDEBase + +const HAS_NORMAL = hasmethod(PDEBase.normal, Tuple{PDEBase.BoundaryPiece}) +HAS_NORMAL || @warn "PDEBase has no facet normal (SciML/PDEBase.jl#164); the absorbing-boundary and port tests are skipped" + +@parameters x y z t +@variables E(..)[1:3] +const X = (x, y, z) +const Dt = Differential(t) +Ev = [E(t, x, y, z)[c] for c in 1:3] + +const WR90_A, WR90_B = 22.86, 10.16 +const K0 = 2π * 10.0e9 / FiniteElementMethod.C0 * 1.0e-3 # rad/mm at 10 GHz +const WALLS = ["left", "right", "front", "back"] + +guide(len, h) = generate_grid(Tetrahedron, ceil.(Int, (WR90_A, WR90_B, len) ./ h), Vec(0.0, 0.0, 0.0), Vec(WR90_A, WR90_B, float(len))) +trace(Γ) = [E(t, Γ)[c] for c in 1:3] +pec(Ω, names) = reduce(vcat, [cross(facet_normal(Γ), trace(Γ)) .~ 0 for Γ in boundarypiece.(Ref(Ω), Symbol.(names))]) +# n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE), the matched first-order absorbing condition. +function abc(Γ; nu = 1, eps = 1) + n, Eb = facet_normal(Γ), trace(Γ) + return cross(n, nu .* curl(Eb, X)) .~ -sqrt(eps * nu) .* cross(n, cross(n, Dt.(Eb))) +end +function system(Ω, bcs; nu = 1, a2 = 1, a1 = 0, a0 = 0, f = zeros(3)) + cc = curl(nu .* curl(Ev, X), X) + eqs = [cc[c] + a2 * Dt(Dt(Ev[c])) + a1 * Dt(Ev[c]) + a0 * Ev[c] ~ f[c] for c in 1:3] + return PDESystem(eqs, bcs, [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [E(t, x, y, z)]; name = :guide) +end +port(name) = WavePort(name; a_direction = (1, 0, 0)) +edge_disc(Ω, ports = WavePort[]; omega = K0) = FEMDiscretization(Ω, t; omega, spaces = Dict(E => Nedelec{RefTetrahedron, 1}()), ports) + +function message(f) + try + f() + catch err + err isa ArgumentError && return err.msg + rethrow() + end + return "no error" +end + +@testset "ports keyword" begin + Ω = MeshDomain(guide(10.0, 5.0)) + @test edge_disc(Ω, [port("bottom")]).ports == [port("bottom")] + @test WavePort(boundarypiece(Ω, :bottom); a_direction = (1, 0, 0)) == port("bottom") + @test_throws ArgumentError("ports belong to the frequency-domain Maxwell path; give the angular frequency omega") FEMDiscretization(Ω, t; ports = [port("bottom")]) + @test_throws ArgumentError("ports must be WavePorts, as ports = [WavePort(Γ; a_direction = (1, 0, 0))]; got [\"bottom\"]") edge_disc(Ω, ["bottom"]) + @test_throws ArgumentError("solve_sweep needs wave ports; give them as FEMDiscretization(Ω, t; omega, spaces, ports = [WavePort(...)])") solve_sweep(system(Ω, Equation[]), edge_disc(Ω), [K0]) +end + +@testset "absorbing end and a wave port: S11 equals the operator-level model" begin + if !HAS_NORMAL + @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" + else + grid = guide(30.0, 2.0) + Ω = MeshDomain(grid) + sys = system(Ω, [pec(Ω, WALLS); abc(boundarypiece(Ω, :top))]) + disc = edge_disc(Ω, [WavePort(boundarypiece(Ω, :bottom); a_direction = (1, 0, 0))]) + (; model) = maxwell_model(sys, disc) + @test model.pec == sort(WALLS) && model.absorbing == ["top"] + oracle = MaxwellModel(grid; pec = WALLS, absorbing = ["top"], ports = [port("bottom")], eps0 = 1.0, mu0 = 1.0) + S = solve_sweep(sys, disc, [K0]).S + @test S == solve_sweep(oracle, [K0]).S + β = sqrt(K0^2 - (π / WR90_A)^2) + Γ = (β - K0) / (β + K0) + @info "Maxwell front end: WR-90 with an absorbing end" S11 = S[1] abs(S[1]) Γ + @test Γ ≈ -0.1396 atol = 1.0e-4 + @test abs(S[1]) ≈ abs(Γ) rtol = 0.03 + # discretize keeps the port as a matched termination, with the load of the (zero) source. + prob = discretize(sys, disc) + expected = driven_problem(oracle, K0; load = zeros(ndofs(oracle.dh))) + @test prob.A == expected.A && prob.b == expected.b + end +end + +@testset "two-port dielectric guide: the sweep equals the operator-level sweep" begin + if !HAS_NORMAL + @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" + else + grid = guide(20.0, 2.5) + Ω = MeshDomain(grid) + sys = system(Ω, pec(Ω, WALLS); nu = 0.5, a2 = 2.0) + ωs = K0 .* [0.8, 1.0, 1.2] + sweep = solve_sweep(sys, edge_disc(Ω, port.(["bottom", "top"])), ωs) + material = MaxwellMaterial(; eps_r = 2.0, mu_r = 2.0) + oracle = MaxwellModel(grid; materials = fill(material, getncells(grid)), pec = WALLS, ports = port.(["bottom", "top"]), eps0 = 1.0, mu0 = 1.0) + expected = solve_sweep(oracle, ωs) + @test size(sweep.S) == (2, 2, 3) + @test sweep.S == expected.S && sweep.omegas == expected.omegas + # The model does not depend on the omega of the discretization. + @test solve_sweep(sys, edge_disc(Ω, port.(["bottom", "top"]); omega = 0.3), ωs).S == expected.S + end +end + +@testset "equivalent forms of the absorbing condition" begin + if !HAS_NORMAL + @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" + else + grid = guide(10.0, 5.0) + Ω = MeshDomain(grid) + Γ = boundarypiece(Ω, :top) + n, Eb = facet_normal(Γ), trace(Γ) + oracle = MaxwellModel( + grid; materials = fill(MaxwellMaterial(; eps_r = 3.0, mu_r = 2.0), getncells(grid)), pec = WALLS, absorbing = ["top"], eps0 = 1.0, mu0 = 1.0 + ) + expected = driven_problem(oracle, K0; load = zeros(ndofs(oracle.dh))).A + forms = [ + abc(Γ; nu = 0.5, eps = 3.0), + # multiplied by μ = 2 + cross(n, curl(Eb, X)) .~ -sqrt(6.0) .* cross(n, cross(n, Dt.(Eb))), + # the other cross order on both sides + cross(curl(Eb, X) ./ 2, n) .~ -sqrt(1.5) .* cross(cross(n, Dt.(Eb)), n), + ] + for bc in forms + prob = discretize(system(Ω, [pec(Ω, WALLS); bc]; nu = 0.5, a2 = 3.0), edge_disc(Ω)) + @test prob.A == expected + end + end +end + +@testset "rejections of absorbing conditions and ports" begin + if !HAS_NORMAL + @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" + else + grid = guide(10.0, 5.0) + addfacetset!(grid, "lid", x -> x[3] ≈ 10.0) # the facets of top again + Ω = MeshDomain(grid) + Γ = boundarypiece(Ω, :top) + n, Eb = facet_normal(Γ), trace(Γ) + walls = pec(Ω, WALLS) + bad(bcs; ports = WavePort[], kw...) = discretize(system(Ω, [walls; bcs]; kw...), edge_disc(Ω, ports)) + @test bad(abc(Γ)) isa LinearProblem + mismatch = r"^the conditions on top at facet \(\d+, \d+\) with normal \(-?0\.0, -?0\.0, 1\.0\) are not n × \(ν curl E\) = -sqrt\(ε/μ\) n × \(n × ∂ₜE\) of the adjacent cell \(ν = 1\.0, sqrt\(ε/μ\) = 1\.0\)" + @test occursin(mismatch, message(() -> bad(abc(Γ; eps = 2.0)))) # impedance + @test occursin(mismatch, message(() -> bad(cross(n, curl(Eb, X)) .~ cross(n, cross(n, Dt.(Eb)))))) # sign + @test occursin(mismatch, message(() -> bad(cross(n, curl(Eb, X) ./ 2) .~ -cross(n, cross(n, Dt.(Eb)))))) # ν + # An impedance condition in E instead of ∂ₜE, and the absorbing condition plus a term in E. + @test occursin(mismatch, message(() -> bad(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Eb))))) + @test occursin(mismatch, message(() -> bad(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.(Eb) .+ Eb))))) + @test occursin(r"^the conditions on top at facet .* have 1 independent equations; the absorbing condition", message(() -> bad([abc(Γ)[1]]))) + @test occursin(r"^the conditions on top at facet .* have 4 independent equations", message(() -> bad([abc(Γ); cross(n, Eb) .~ 0]))) + # The third row vanishes at the actual normal e₃ of top, so two rows are the whole condition there, and a + # term added to that row is a third equation. + @test bad(abc(Γ)[1:2]) isa LinearProblem + @test occursin(r"^the conditions on top at facet .* have 3 independent equations", message(() -> bad([abc(Γ)[1:2]; abc(Γ)[3].lhs + Eb[3] ~ abc(Γ)[3].rhs]))) + @test occursin("has the derivative", message(() -> bad([abc(Γ)[1:2]; Dt(Dt(Eb[1])) ~ 0]))) + @test occursin("has the derivative", message(() -> bad([abc(Γ)[1:2]; Differential(x)(Differential(y)(Eb[1])) ~ 0]))) + @test occursin("has the derivative", message(() -> bad([abc(Γ)[1:2]; Differential(x)(2 * Eb[1]) ~ 0]))) + @test occursin("has a normal derivative", message(() -> bad([abc(Γ)[1:2]; NormalDerivative(Γ)(Eb[1]) ~ 0]))) + @test occursin(r"depends on t;", message(() -> bad(cross(n, curl(Eb, X)) .~ -(1 + t) .* cross(n, cross(n, Dt.(Eb)))))) + @test occursin(r"^the absorbing condition on top has a source", message(() -> bad(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.(Eb))) .+ [1.0, 0, 0]))) + @test occursin(r"^the absorbing condition on top at facet .* borders cell \d+ with ν = 1\.0, a₂ = 1\.0, a₁ = 0\.1 and a₀ = 0\.0", message(() -> bad(abc(Γ); a1 = 0.1))) + @test occursin(r"borders cell \d+ with ν = 1\.0, a₂ = 1\.0, a₁ = 0\.0 and a₀ = 0\.2", message(() -> bad(abc(Γ); a0 = 0.2))) + @test occursin(r"borders cell \d+ with ν = 1\.0, a₂ = -1\.0", message(() -> bad(abc(Γ); a2 = -1.0))) + # Coefficients of the condition are constants on the piece, checked whole at every facet. + @test occursin(r"depends on x;", message(() -> bad(cross(n, curl(Eb, X)) .~ -(1 + 0.1x) .* cross(n, cross(n, Dt.(Eb)))))) + # A second piece on the same facets with the other condition. + @test_throws ArgumentError("the absorbing piece top shares facets with the perfect-conductor piece lid; give each facet one condition") bad( + [abc(Γ); pec(Ω, ["lid"])] + ) + + # Ports carry their own condition and need a frequency-independent model. + portmsg(name) = "the wave port on bottom is the boundary condition of its facets, but the PDESystem also has a condition on $name, which shares facets with it; remove that condition" + @test_throws ArgumentError(portmsg("bottom")) bad(pec(Ω, ["bottom"]); ports = [port("bottom")]) + @test_throws ArgumentError(portmsg("bottom")) bad(abc(boundarypiece(Ω, :bottom)); ports = [port("bottom")]) + @test bad(Equation[]; ports = [port("bottom")]) isa LinearProblem + @test occursin(r"^a₀ = 0\.2 in cell 1, but with wave ports the coefficient of E must be zero", message(() -> bad(Equation[]; ports = [port("bottom")], a0 = 0.2))) + @test_throws ArgumentError("solve_sweep drives the wave ports only, but the PDESystem has a source; solve a source with discretize(pdesys, disc) at each omega") solve_sweep( + system(Ω, walls; f = [0, 1.0, 0]), edge_disc(Ω, [port("bottom")]), [K0] + ) + end +end From ca442fa84a00a80f0b08d0bad2e0dbad256ae99f Mon Sep 17 00:00:00 2001 From: t Date: Fri, 6 Nov 2026 01:48:04 +0000 Subject: [PATCH 06/34] Reject facets that would carry two absorbing or port terms Codex r1: two absorbing pieces on the same facets each passed recognition and MaxwellModel added their tangential mass twice. The front end now rejects any overlap involving an absorbing piece, and MaxwellModel rejects shared facets among its absorbing sets and port faces, including a name given twice. Overlapping PEC pieces stay allowed since they only constrain the same dofs. 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/frontend.jl | 10 +++++++--- src/maxwell/model.jl | 13 +++++++++++++ test/Maxwell/frontend_ports.jl | 15 ++++++++++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 427e87c8..3600cdf2 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -321,10 +321,14 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells) end push!(isabc ? absorbing : pec, String(name)) end + # Overlapping perfect-conductor pieces only constrain the same dofs again; any other overlap would add a + # boundary term twice or give a facet two conditions. grid = domain.mesh - for a in absorbing, p in pec - isdisjoint(Ferrite.getfacetset(grid, a), Ferrite.getfacetset(grid, p)) || - throw(ArgumentError("the absorbing piece $a shares facets with the perfect-conductor piece $p; give each facet one condition")) + pieces = [sort(pec); sort(absorbing)] + for i in eachindex(pieces), j in (i + 1):lastindex(pieces) + a, b = pieces[i], pieces[j] + (a in absorbing || b in absorbing) && !isdisjoint(Ferrite.getfacetset(grid, a), Ferrite.getfacetset(grid, b)) && + throw(ArgumentError("the pieces $a and $b share facets and one of them is absorbing; give each facet one condition")) end return (; pec = sort!(pec), absorbing = sort!(absorbing)) end diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 7965b6ac..0b4979a6 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -104,6 +104,7 @@ function MaxwellModel( absorbing = String.(collect(absorbing)) foreach(name -> _check_facetset(grid, name), pec) foreach(name -> _check_facetset(grid, name), absorbing) + _check_disjoint_boundary_terms(grid, [absorbing; [String(port.facetset) for port in ports]]) cell_materials = _cell_materials(grid, materials) ip = _NEDELEC @@ -135,6 +136,18 @@ function MaxwellModel( ) end +# Each absorbing facet set and port face adds a term over its facets, so a facet in two of them (or a name given +# twice) would be counted twice. +function _check_disjoint_boundary_terms(grid, names) + for i in eachindex(names), j in (i + 1):lastindex(names) + _check_facetset(grid, names[j]) + isdisjoint(Ferrite.getfacetset(grid, names[i]), Ferrite.getfacetset(grid, names[j])) || throw( + ArgumentError("the facet sets $(repr(names[i])) and $(repr(names[j])) of `absorbing` and `ports` share facets, whose boundary terms would be added twice; give each facet one absorbing condition or port") + ) + end + return nothing +end + function _check_cellset(grid, name) return haskey(grid.cellsets, name) || throw(ArgumentError("no cell set $(repr(name)) in the grid; it has $(sort!(collect(keys(grid.cellsets))))")) diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index 5a1aec1b..2976fb08 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -160,9 +160,18 @@ end # Coefficients of the condition are constants on the piece, checked whole at every facet. @test occursin(r"depends on x;", message(() -> bad(cross(n, curl(Eb, X)) .~ -(1 + 0.1x) .* cross(n, cross(n, Dt.(Eb)))))) # A second piece on the same facets with the other condition. - @test_throws ArgumentError("the absorbing piece top shares facets with the perfect-conductor piece lid; give each facet one condition") bad( - [abc(Γ); pec(Ω, ["lid"])] - ) + overlap = "the pieces lid and top share facets and one of them is absorbing; give each facet one condition" + @test_throws ArgumentError(overlap) bad([abc(Γ); pec(Ω, ["lid"])]) + # Codex r1: the matched condition on two pieces with the same facets would double the admittance. + @test_throws ArgumentError(overlap) bad([abc(Γ); abc(boundarypiece(Ω, :lid))]) + # Two perfect-conductor pieces on the same facets constrain the same dofs and are fine. + @test bad(pec(Ω, ["top", "lid"])) isa LinearProblem + # The operator-level model refuses the same overlaps among absorbing sets and ports. + twice = "the facet sets \"top\" and \"lid\" of `absorbing` and `ports` share facets, whose boundary terms would be added twice; give each facet one absorbing condition or port" + @test_throws ArgumentError(twice) MaxwellModel(grid; pec = WALLS, absorbing = ["top", "lid"]) + @test_throws ArgumentError(replace(twice, "\"lid\"" => "\"top\"")) MaxwellModel(grid; pec = WALLS, absorbing = ["top", "top"]) + @test_throws ArgumentError(twice) MaxwellModel(grid; pec = WALLS, absorbing = ["top"], ports = [port("lid")]) + @test_throws ArgumentError(replace(twice, "\"top\"" => "\"bottom\"", "\"lid\"" => "\"bottom\"")) MaxwellModel(grid; pec = WALLS, ports = [port("bottom"), port("bottom")]) # Ports carry their own condition and need a frequency-independent model. portmsg(name) = "the wave port on bottom is the boundary condition of its facets, but the PDESystem also has a condition on $name, which shares facets with it; remove that condition" From cabdd93fa2f5d8e3aedc53e525a6b954ef27ef13 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 21:10:18 +0000 Subject: [PATCH 07/34] 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 --- 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 9393413edd5e1928c8fb727503c0c161a529d9da Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:21:21 +0000 Subject: [PATCH 08/34] Absorbing condition: scale-free row-space comparison Rows are normalised before the rank test, a row counts as vanishing relative to its own size at generic normals, so scaling an equation neither hides an added constraint nor rejects a valid condition. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/FiniteElementMethod.jl | 2 +- src/maxwell/frontend.jl | 22 +++++++++++++++------- test/Maxwell/frontend_ports.jl | 6 ++++++ 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 1bab8d42..7b20c967 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, curl using ForwardDiff: ForwardDiff -using LinearAlgebra: cross, dot, lu, lu!, mul!, norm, rank, svd +using LinearAlgebra: cross, dot, lu, lu!, mul!, norm, normalize, rank, svd using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index d3569674..a38c2470 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -289,16 +289,19 @@ function _absorbing_target(n, ν, c) ) end -# An orthonormal basis of the row space of M, as rows. The rows are scaled to unit length first (rows below 1e-12 of -# the longest are roundoff of a vanishing one and are dropped), so that a row of large coefficients cannot hide an -# independent row of small ones from the relative singular value threshold. -function _rowspace(M) - lengths = norm.(eachrow(M)) - M = M[lengths .> 1.0e-12 * maximum(lengths; init = 0.0), :] ./ lengths[lengths .> 1.0e-12 * maximum(lengths; init = 0.0)] +# An orthonormal basis of the row space of M, as rows. Each row is scaled to unit length first, so that the result +# does not depend on how the equations are scaled; a row counts as zero when it is below 1e-12 of `ref[i]`, the size +# the same row has at generic normals (a row can vanish at the actual normal of a facet). +function _rowspace(M, ref) + keep = findall(i -> norm(M[i, :]) > 1.0e-12 * ref[i], axes(M, 1)) + M = M[keep, :] ./ norm.(eachrow(M[keep, :])) F = svd(M) return F.Vt[1:count(>(1.0e-10 * maximum(F.S; init = 0.0)), F.S), :] end +# Generic unit directions, at which no row of a boundary condition vanishes for a reason of geometry. +const _GENERIC_NORMALS = [normalize([1.0, 2.0, 3.0]), normalize([-2.0, 1.0, 0.5]), normalize([0.3, -1.0, 2.0])] + # The boundary conditions on each piece: the perfect conductor n × E = 0 (the residuals are linear in the traces and # the normal, tangential (C n = 0) and of rank 2 together) or, when they hold derivatives of the traces, the # first-order absorbing condition, whose residuals must span exactly the rows of n × (ν curl E) + c n × (n × ∂ₜE) @@ -366,7 +369,12 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) # The columns act on G ~ k E, V = ∂ₜE ~ ω E and U = E; in these units the curl and impedance parts are of # the same size (ν k = c ω) whatever the unit system, where the raw coefficients can differ by many orders. scale = [fill(ω * sqrt(a2 / nu), 9); fill(ω, 3); ones(3)]' - Q, P = _rowspace(Cn .* scale), _rowspace(_absorbing_target(n, nu, c) .* scale) + rows(ns) = [maximum(norm((reshape(C_at(m...), length(Bs), 15) .* scale)[i, :]) for m in ns) for i in eachindex(Bs)] + Q = _rowspace(Cn .* scale, rows(_GENERIC_NORMALS)) + P = _rowspace( + _absorbing_target(n, nu, c) .* scale, + [maximum(norm((_absorbing_target(m, nu, c) .* scale)[i, :]) for m in _GENERIC_NORMALS) for i in 1:3] + ) size(Q, 1) == 2 || throw( ArgumentError("the conditions $where have $(size(Q, 1)) independent equations; the absorbing condition n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) has 2; $form") ) diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index 68eb8c14..cca25ca5 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -131,6 +131,12 @@ end bcs = [pec(Ω, WALLS); abc(Γ); Eb[3] ~ 0] @test occursin("independent equations", message(() -> discretize(system(Ω, bcs), edge_disc(Ω; omega = 1.0e12)))) @test occursin("independent equations", message(() -> discretize(system(Ω, bcs), edge_disc(Ω; omega = 1.0)))) + # Scaling an equation changes nothing: a tiny extra constraint is still one, and a tiny valid row is still valid. + tiny = [pec(Ω, WALLS); abc(Γ); 1.0e-13 .* [Eb[3]] .~ 0] + @test occursin("independent equations", message(() -> discretize(system(Ω, tiny), edge_disc(Ω; omega = 1.0)))) + scaled = abc(Γ) + scaled[1] = scaled[1].lhs * 1.0e-13 ~ scaled[1].rhs * 1.0e-13 + @test discretize(system(Ω, [pec(Ω, WALLS); scaled]), edge_disc(Ω; omega = 1.0)) isa LinearProblem end @testset "rejections of absorbing conditions and ports" begin From 743daaddfc624514f978429530db9c69141174f3 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:55:20 +0000 Subject: [PATCH 09/34] Absorbing condition: a term in E is rejected symbolically, independent of the frequency 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/frontend.jl | 3 ++- test/Maxwell/frontend_ports.jl | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index d42a84da..a22478ba 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -378,7 +378,8 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) size(Q, 1) == 2 || throw( ArgumentError("the conditions $where have $(size(Q, 1)) independent equations; the absorbing condition n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) has 2; $form") ) - norm(Q' * Q - P' * P) <= 1.0e-8 || throw( + # A term in E has the weight of E itself, which the field units of the derivative columns can make small. + (any(!_iszero_expr, C[:, 13:15]) || norm(Q' * Q - P' * P) > 1.0e-8) && throw( ArgumentError("the conditions $where are not n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) of the adjacent cell (ν = $nu, sqrt(ε/μ) = $c): the coefficient of curl E, the impedance or the sign differs, or a term in E is added; $form") ) end diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index cca25ca5..a5af9ba7 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -131,6 +131,9 @@ end bcs = [pec(Ω, WALLS); abc(Γ); Eb[3] ~ 0] @test occursin("independent equations", message(() -> discretize(system(Ω, bcs), edge_disc(Ω; omega = 1.0e12)))) @test occursin("independent equations", message(() -> discretize(system(Ω, bcs), edge_disc(Ω; omega = 1.0)))) + # A term in E next to the time derivative at a frequency where it is tiny in field units is still a term. + withE = cross(facet_normal(Γ), curl(Eb, X)) .~ -cross(facet_normal(Γ), cross(facet_normal(Γ), Dt.(Eb) .+ Eb)) + @test occursin("are not n × (ν curl E)", message(() -> discretize(system(Ω, [pec(Ω, WALLS); withE]), edge_disc(Ω; omega = 1.0e12)))) # Scaling an equation changes nothing: a tiny extra constraint is still one, and a tiny valid row is still valid. tiny = [pec(Ω, WALLS); abc(Γ); 1.0e-13 .* [Eb[3]] .~ 0] @test occursin("independent equations", message(() -> discretize(system(Ω, tiny), edge_disc(Ω; omega = 1.0)))) From 5a8413ae1d87293a2dfdb09d2ebe94205d7559ef Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:57:48 +0000 Subject: [PATCH 10/34] Maxwell front end: reject a nu whose reciprocal is not representable (same check as on the front-end base) 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/frontend.jl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index a22478ba..7e3ff5bc 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -472,7 +472,8 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio source_at = compile(coeffs.sources) cells = map(enumerate(centroids)) do (cell, x) nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") - iszero(nu) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero")) + (iszero(nu) || iszero(1 / nu) || !isfinite(1 / nu)) && + throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) (; nu, a0, a1, a2) end (; pec, absorbing) = _recognise_boundaries( From 40d2e453d13d689d8bab42165e5a60d521169053 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 02:04:51 +0000 Subject: [PATCH 11/34] 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 5c67f3e8..544cb07d 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -182,6 +182,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 4b7da5d7..85318b38 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 5a4505f0208b50f5e928f5c1690e3e377a45e259 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 02:11:36 +0000 Subject: [PATCH 12/34] Maxwell front end: reject a reaction coefficient lost to underflow in eps (same check as on the front-end base) 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/frontend.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 7e3ff5bc..934d2b4e 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -496,7 +496,7 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio ω = disc.omega materials = map(enumerate(cells)) do (cell, c) eps_r = c.a2 - c.a0 / ω^2 - isfinite(eps_r) || throw( + isfinite(eps_r) && (iszero(c.a0) || abs(c.a0 / ω^2) >= floatmin()) || throw( ArgumentError("ε = a₂ - a₀/ω² = $(c.a2) - $(c.a0)/$ω^2 in cell $cell is not representable at this tiny ω; use a larger frequency or a MaxwellModel directly") ) MaxwellMaterial(; eps_r, mu_r = 1 / c.nu, sigma = c.a1) From 819a8c0e4c05fee5b2e16ca689a393cbec888a40 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:18:02 +0000 Subject: [PATCH 13/34] Wave ports: state that the port needs real permittivity and zero conductivity The docstring said lossless-or-dielectric, which reads as allowing a lossy dielectric; a complex eps_r or a nonzero conductivity is rejected. 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 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 544cb07d..eaf7ae2a 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 From 6a7115b60ad61e4c99abcbad6529201c4fa4a86b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:18:02 +0000 Subject: [PATCH 14/34] 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 + test/Maxwell/ports.jl | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 983a4ef3..5ee4afe3 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -102,6 +102,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) _check_disjoint_boundary_terms(grid, [absorbing; [String(port.facetset) for port in ports]]) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 85318b38..8a762c3a 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -191,3 +191,11 @@ end @test abs(S11 - expected) < 0.01 @test abs(ignoring_σ - expected) > 0.03 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 7482a1bc80606d7caa811c1e85e40e871370400b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:37:40 +0000 Subject: [PATCH 15/34] Wave ports: reject a complex permittivity at the port The docstring promises a lossless port material, but only conductivity was checked here; the check now matches the other branches of the stack. 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 | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index eaf7ae2a..64402264 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -35,7 +35,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 @@ -152,6 +152,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)) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 8a762c3a..d8eac13b 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -199,3 +199,12 @@ end model = MaxwellModel(grid; pec = walls, ports = Iterators.Stateful(ports), eps0 = 1.0, mu0 = 1.0) @test length(model.ports) == 2 end + +@testset "a wave port in a material with complex permittivity is 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, "fill", x -> true) + materials = Dict("fill" => MaxwellMaterial(; eps_r = 2 - 0.2im, sigma = 0.0)) + walls = ["left", "right", "front", "back"] + ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + @test_throws "lossy material" MaxwellModel(grid; materials, pec = walls, ports, eps0 = 1.0, mu0 = 1.0) +end From 7b123bc90eb3c2d5eb96278f8a936ae296096524 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:37:40 +0000 Subject: [PATCH 16/34] Front end: materialise the ports keyword once before validation all(...) consumed a one-pass iterator before the ports were stored, so the discretization silently had none. 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/discretization.jl | 1 + test/Maxwell/frontend_ports.jl | 1 + 2 files changed, 2 insertions(+) diff --git a/src/discretization.jl b/src/discretization.jl index b9b87744..73cb1c44 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -182,6 +182,7 @@ function FEMDiscretization( ) _check_reserved(kwargs) _check_omega(omega, time, spaces, test_space, regions, ibp, pairing) + ports = collect(ports) all(p -> p isa WavePort, ports) || throw(ArgumentError("ports must be WavePorts, as ports = [WavePort(Γ; a_direction = (1, 0, 0))]; got $(repr(ports))")) omega === nothing && !isempty(ports) && diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index a5af9ba7..ff99412f 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -44,6 +44,7 @@ end Ω = MeshDomain(guide(10.0, 5.0)) @test edge_disc(Ω, [port("bottom")]).ports == [port("bottom")] @test WavePort(boundarypiece(Ω, :bottom); a_direction = (1, 0, 0)) == port("bottom") + @test edge_disc(Ω, Iterators.Stateful([port("bottom")])).ports == [port("bottom")] @test_throws ArgumentError("ports belong to the frequency-domain Maxwell path; give the angular frequency omega") FEMDiscretization(Ω, t; ports = [port("bottom")]) @test_throws ArgumentError("ports must be WavePorts, as ports = [WavePort(Γ; a_direction = (1, 0, 0))]; got [\"bottom\"]") edge_disc(Ω, ["bottom"]) @test_throws ArgumentError("solve_sweep needs wave ports; give them as FEMDiscretization(Ω, t; omega, spaces, ports = [WavePort(...)])") solve_sweep(system(Ω, Equation[]), edge_disc(Ω), [K0]) From 548c6f8d889dec9a20515edaddbf86c25496ac28 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:05:56 +0000 Subject: [PATCH 17/34] 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 25576d93..69ccf771 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. ## From a PDESystem diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 64402264..e48539e0 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 @@ -257,12 +262,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 cfa7b01c..8d04f730 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 d8eac13b..5308d216 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -208,3 +208,20 @@ end ports = [WavePort("bottom"; a_direction = (1, 0, 0))] @test_throws "lossy material" MaxwellModel(grid; materials, pec = walls, ports, eps0 = 1.0, mu0 = 1.0) 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 ecb7a800225df9985dc5aeec255d731c87ffbcd4 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:09:01 +0000 Subject: [PATCH 18/34] 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 5308d216..ed6a0615 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -219,8 +219,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 a44e2f762d6adf1db3cdf3b2bdec09487599aa61 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:41:50 +0000 Subject: [PATCH 19/34] 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 69ccf771..1d82e9e8 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(ω))`. ## From a PDESystem diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 5ee4afe3..03cdc8f4 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 e48539e0..43fc3e06 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -99,13 +99,21 @@ 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) 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)) + MaxwellTerm(block, ω -> im * ω * sqrt(mu0 * eps0) * L * _admittance(m.eps_r - im * m.sigma / (ω * eps0), m.mu_r)) end end @@ -233,6 +241,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 8d04f730..e5ed1d84 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -41,6 +41,7 @@ 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)) + 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 ed6a0615..f212ebc7 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -225,3 +225,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 68d8d82c65fbe2ba1544c6ef8b1c8f9d69cf05d6 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:46:19 +0000 Subject: [PATCH 20/34] Front end: judge normal-dependent boundary factors at the actual normal A row was discarded as vanishing when it was below 1e-12 of its size at generic normals, so a 1e-13 multiple of an independent constraint disappeared and a whole condition scaled by 1e-13 was rejected; the cutoff is now roundoff of the normal. The E-term guard looked at the symbolic coefficients and rejected an equation that vanishes on the facet; it now looks at the coefficients at the actual normal. 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/frontend.jl | 14 ++++++++++---- test/Maxwell/frontend_ports.jl | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 934d2b4e..7e9ddac2 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -290,10 +290,12 @@ function _absorbing_target(n, ν, c) end # An orthonormal basis of the row space of M, as rows. Each row is scaled to unit length first, so that the result -# does not depend on how the equations are scaled; a row counts as zero when it is below 1e-12 of `ref[i]`, the size -# the same row has at generic normals (a row can vanish at the actual normal of a facet). +# does not depend on how the equations are scaled; a row counts as zero when it is below `_ROW_ZERO` of `ref[i]`, the +# size the same row has at generic normals: a row vanishes at the actual normal of a facet only by roundoff in the +# normal, so a tiny factor that is really there (1e-13) still makes a row. +const _ROW_ZERO = 1.0e-14 function _rowspace(M, ref) - keep = findall(i -> norm(M[i, :]) > 1.0e-12 * ref[i], axes(M, 1)) + keep = findall(i -> norm(M[i, :]) > _ROW_ZERO * ref[i], axes(M, 1)) M = M[keep, :] ./ norm.(eachrow(M[keep, :])) F = svd(M) return F.Vt[1:count(>(1.0e-10 * maximum(F.S; init = 0.0)), F.S), :] @@ -370,6 +372,10 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) # the same size (ν k = c ω) whatever the unit system, where the raw coefficients can differ by many orders. scale = [fill(ω * sqrt(a2 / nu), 9); fill(ω, 3); ones(3)]' rows(ns) = [maximum(norm((reshape(C_at(m...), length(Bs), 15) .* scale)[i, :]) for m in ns) for i in eachindex(Bs)] + # A term in E is judged at the actual normal too: n[1] * E vanishes on a facet with n[1] = 0. + e_rows(ns) = [maximum(norm(reshape(C_at(m...), length(Bs), 15)[i, 13:15]) for m in ns) for i in eachindex(Bs)] + e_ref = e_rows(_GENERIC_NORMALS) + has_e_term = any(i -> norm(Cn[i, 13:15]) > _ROW_ZERO * e_ref[i], eachindex(Bs)) Q = _rowspace(Cn .* scale, rows(_GENERIC_NORMALS)) P = _rowspace( _absorbing_target(n, nu, c) .* scale, @@ -379,7 +385,7 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) ArgumentError("the conditions $where have $(size(Q, 1)) independent equations; the absorbing condition n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) has 2; $form") ) # A term in E has the weight of E itself, which the field units of the derivative columns can make small. - (any(!_iszero_expr, C[:, 13:15]) || norm(Q' * Q - P' * P) > 1.0e-8) && throw( + (has_e_term || norm(Q' * Q - P' * P) > 1.0e-8) && throw( ArgumentError("the conditions $where are not n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) of the adjacent cell (ν = $nu, sqrt(ε/μ) = $c): the coefficient of curl E, the impedance or the sign differs, or a term in E is added; $form") ) end diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index ff99412f..6f300764 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -143,6 +143,26 @@ end @test discretize(system(Ω, [pec(Ω, WALLS); scaled]), edge_disc(Ω; omega = 1.0)) isa LinearProblem end +@testset "normal-dependent factors are judged at the actual normal" begin + Ω = MeshDomain(guide(10.0, 5.0)) + Γ = boundarypiece(Ω, :top) # n = (0, 0, 1), so n[1] = 0 on it + n, Eb = facet_normal(Γ), trace(Γ) + walls = pec(Ω, WALLS) + solve_with(extra) = discretize(system(Ω, [walls; abc(Γ); extra]), edge_disc(Ω)) + base = solve_with(Equation[]) + # (n[1] + 1e-13) ∂ₜE_z = 0 is a 1e-13 multiple of an independent constraint, not a vanishing row. + @test occursin("independent equations", message(() -> solve_with([(n[1] + 1.0e-13) * Dt(Eb[3]) ~ 0]))) + @test occursin("independent equations", message(() -> solve_with([(n[1] + 1.0e-8) * Dt(Eb[3]) ~ 0]))) + # The whole absorbing condition times a tiny factor is still the absorbing condition. + factor = n[1] + 1.0e-13 + @test discretize(system(Ω, [walls; [factor * e.lhs ~ factor * e.rhs for e in abc(Γ)]]), edge_disc(Ω)) isa LinearProblem + # n[1] E_z = 0 and n[1] ∂ₜE_z = 0 vanish identically on top and change nothing. + for vanishing in (n[1] * Eb[3], n[1] * Dt(Eb[3])) + prob = solve_with([vanishing ~ 0]) + @test prob.A == base.A && prob.b == base.b + end +end + @testset "rejections of absorbing conditions and ports" begin grid = guide(10.0, 5.0) addfacetset!(grid, "lid", x -> x[3] ≈ 10.0) # the facets of top again From 74015bfb76b64426e43c432d2df8620fdca1de15 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:01:08 +0000 Subject: [PATCH 21/34] Absorbing boundary: outgoing branch follows the sign of the frequency; finite at zero frequency Same root choice as the other stack, and the coefficient is 0 at omega = 0 instead of 0/0 for a lossless material. 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 | 14 +++++++++----- test/Maxwell/ports.jl | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 03cdc8f4..dddea95f 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 43fc3e06..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 @@ -113,7 +113,11 @@ 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 * _admittance(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 * _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 f212ebc7..f86fb6de 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -250,3 +250,21 @@ 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 + +@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 From 749e3ff11356aaae8aafb3289d7cdf6368d1f703 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:16:06 +0000 Subject: [PATCH 22/34] 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 dddea95f..9ce3c98e 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 f86fb6de..8bafa96f 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -254,7 +254,7 @@ 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 @@ -268,3 +268,29 @@ end @test all(isfinite, maxwell_operator(m, 0.0).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 cb5014feaa6e086699d45a5d306db6094eaea61b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:22:20 +0000 Subject: [PATCH 23/34] 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 8bafa96f..66a0ac25 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -291,6 +291,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 af0312f201aa06c9d13ea747e15f31b31470de61 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:33:06 +0000 Subject: [PATCH 24/34] 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, 24 insertions(+), 2 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 1d82e9e8..a378b069 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -58,6 +58,11 @@ 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 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. + ## From a PDESystem `FEMDiscretization(Ω, t; omega, spaces = Dict(E => Nedelec{RefTetrahedron, 1}()))` discretizes the 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 66a0ac25..27839c13 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -294,3 +294,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 a39574a5362bd52cd9e80093a4f9aab4aa292979 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 21:13:35 +0000 Subject: [PATCH 25/34] 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 a378b069..5671d97a 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 7b20c967..8a52ca6c 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 9ce3c98e..f4dd2808 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -119,7 +119,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 = [ @@ -195,8 +196,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 e5ed1d84..df5283b7 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -41,7 +41,8 @@ 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)) - 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 27839c13..d7a61ff3 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -306,3 +306,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 cb5d36a6acbd777e925906d489a6c23098242543 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 21:23:29 +0000 Subject: [PATCH 26/34] Front end: judge boundary equations at the snapped actual normal, without generic-normal thresholds Both the vanishing-row filter and the E-term guard compared coefficients at the actual normal with unrelated magnitudes at generic normals, so a factor that is exactly 1 at the facet (1e16 n[1] + 1) or 1e-16 was discarded or rejected wrongly. Normals are snapped to exact zeros below 1e-14, a row vanishes only when exactly zero there, rows are normalised by their own norm, and a term in E counts in a surviving row only. 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/frontend.jl | 28 ++++++++++++---------------- test/Maxwell/frontend_ports.jl | 17 ++++++++++------- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 7e9ddac2..e6c6ee78 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -290,12 +290,10 @@ function _absorbing_target(n, ν, c) end # An orthonormal basis of the row space of M, as rows. Each row is scaled to unit length first, so that the result -# does not depend on how the equations are scaled; a row counts as zero when it is below `_ROW_ZERO` of `ref[i]`, the -# size the same row has at generic normals: a row vanishes at the actual normal of a facet only by roundoff in the -# normal, so a tiny factor that is really there (1e-13) still makes a row. -const _ROW_ZERO = 1.0e-14 -function _rowspace(M, ref) - keep = findall(i -> norm(M[i, :]) > _ROW_ZERO * ref[i], axes(M, 1)) +# does not depend on how the equations are scaled; a row is zero only when all its entries are exactly zero at the +# actual (snapped) normal of the facet, so a tiny factor that is really there (1e-13, 1e-20) still makes a row. +function _rowspace(M) + keep = findall(i -> norm(M[i, :]) > 0, axes(M, 1)) M = M[keep, :] ./ norm.(eachrow(M[keep, :])) F = svd(M) return F.Vt[1:count(>(1.0e-10 * maximum(F.S; init = 0.0)), F.S), :] @@ -351,6 +349,9 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) ) C_at = Symbolics.build_function(vec(C), slots.N...; expression = Val(false))[1] for (n, facet) in _facet_normals(domain.mesh, String(name)) + # The roundoff of a normal that lies in a coordinate plane is not a coefficient: snap it to exactly 0, so + # that n[1] * E vanishes there while n[1] + 1e-16 does not. + n = [abs(x) < 1.0e-14 ? 0.0 : x for x in n] Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 15) where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" if !isabc @@ -371,16 +372,11 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) # The columns act on G ~ k E, V = ∂ₜE ~ ω E and U = E; in these units the curl and impedance parts are of # the same size (ν k = c ω) whatever the unit system, where the raw coefficients can differ by many orders. scale = [fill(ω * sqrt(a2 / nu), 9); fill(ω, 3); ones(3)]' - rows(ns) = [maximum(norm((reshape(C_at(m...), length(Bs), 15) .* scale)[i, :]) for m in ns) for i in eachindex(Bs)] - # A term in E is judged at the actual normal too: n[1] * E vanishes on a facet with n[1] = 0. - e_rows(ns) = [maximum(norm(reshape(C_at(m...), length(Bs), 15)[i, 13:15]) for m in ns) for i in eachindex(Bs)] - e_ref = e_rows(_GENERIC_NORMALS) - has_e_term = any(i -> norm(Cn[i, 13:15]) > _ROW_ZERO * e_ref[i], eachindex(Bs)) - Q = _rowspace(Cn .* scale, rows(_GENERIC_NORMALS)) - P = _rowspace( - _absorbing_target(n, nu, c) .* scale, - [maximum(norm((_absorbing_target(m, nu, c) .* scale)[i, :]) for m in _GENERIC_NORMALS) for i in 1:3] - ) + # Rows are judged at the actual normal alone; a term in E counts in a surviving row only. + survives = [norm(Cn[i, :] .* vec(scale)) > 0 for i in eachindex(Bs)] + has_e_term = any(i -> survives[i] && any(!iszero, Cn[i, 13:15]), eachindex(Bs)) + Q = _rowspace(Cn .* scale) + P = _rowspace(_absorbing_target(n, nu, c) .* scale) size(Q, 1) == 2 || throw( ArgumentError("the conditions $where have $(size(Q, 1)) independent equations; the absorbing condition n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) has 2; $form") ) diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index 6f300764..540d3730 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -150,14 +150,17 @@ end walls = pec(Ω, WALLS) solve_with(extra) = discretize(system(Ω, [walls; abc(Γ); extra]), edge_disc(Ω)) base = solve_with(Equation[]) - # (n[1] + 1e-13) ∂ₜE_z = 0 is a 1e-13 multiple of an independent constraint, not a vanishing row. - @test occursin("independent equations", message(() -> solve_with([(n[1] + 1.0e-13) * Dt(Eb[3]) ~ 0]))) - @test occursin("independent equations", message(() -> solve_with([(n[1] + 1.0e-8) * Dt(Eb[3]) ~ 0]))) - # The whole absorbing condition times a tiny factor is still the absorbing condition. - factor = n[1] + 1.0e-13 - @test discretize(system(Ω, [walls; [factor * e.lhs ~ factor * e.rhs for e in abc(Γ)]]), edge_disc(Ω)) isa LinearProblem + independent(eq) = occursin("independent equations", message(() -> solve_with([eq]))) + # A factor that is 1e-13, 1e-16, 1e-20 or exactly 1 at the actual normal, however it is written, is a factor. + for factor in (n[1] + 1.0e-8, n[1] + 1.0e-13, n[1] + 1.0e-16, n[1] + 1.0e-20, 1.0e16 * n[1] + 1) + @test independent(factor * Dt(Eb[3]) ~ 0) + # The same factor on the whole absorbing condition is still the absorbing condition. + @test discretize(system(Ω, [walls; [factor * e.lhs ~ factor * e.rhs for e in abc(Γ)]]), edge_disc(Ω)) isa LinearProblem + end + # A nonzero E_z equation is a third equation, whichever way its factor is written. + @test message(() -> solve_with([(1.0e16 * n[1] + 1) * Eb[3] ~ 0])) != "no error" # n[1] E_z = 0 and n[1] ∂ₜE_z = 0 vanish identically on top and change nothing. - for vanishing in (n[1] * Eb[3], n[1] * Dt(Eb[3])) + for vanishing in (n[1] * Eb[3], n[1] * Dt(Eb[3]), 1.0e16 * n[1] * Dt(Eb[3])) prob = solve_with([vanishing ~ 0]) @test prob.A == base.A && prob.b == base.b end From 1575baa55a2bf1f804512e7ae42904d4bd6eea26 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 22:12:33 +0000 Subject: [PATCH 27/34] 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 f4dd2808..329536e3 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -70,7 +70,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`, @@ -246,7 +248,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 50279b29dad673b222024fff175ffcb199e235e7 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 22:52:42 +0000 Subject: [PATCH 28/34] Front end: judge vanishing boundary equations against their cancellation-free size An entry now counts as zero when it is at most 64 eps of the absolute sum of the terms that cancel in it, so an explicit linear combination of the absorbing equations is redundant on an oblique face, while a 1e-16 or 1e-20 factor, or an exactly-1 coefficient written as 1e16 n[1] + 1, still makes an equation. The absorbing condition's own two equations are taken as its tangential components, which are exact at any normal. 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/frontend.jl | 38 ++++++++++++++++++++++++++++------ test/Maxwell/frontend_ports.jl | 16 ++++++++++++++ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 44a967f5..15b014c8 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -292,9 +292,28 @@ function _absorbing_target(n, ν, c) ) end +# The expression with every term replaced by its absolute value, so that sums add where they would cancel: the size +# that a coefficient has before cancellation, against which roundoff is judged. +function _magnitude(ex) + if SymbolicUtils.iscall(ex) + op, args = SymbolicUtils.operation(ex), SymbolicUtils.arguments(ex) + if op === (+) || op === (-) + return sum(_magnitude, args) + elseif op === (*) + return prod(_magnitude, args) + elseif op === (/) + return _magnitude(args[1]) / _magnitude(args[2]) + end + return abs(Num(ex)) + end + value = SymbolicUtils.unwrap_const(ex) + return value isa Number ? abs(value) : abs(Num(ex)) +end + # An orthonormal basis of the row space of M, as rows. Each row is scaled to unit length first, so that the result -# does not depend on how the equations are scaled; a row is zero only when all its entries are exactly zero at the -# actual (snapped) normal of the facet, so a tiny factor that is really there (1e-13, 1e-20) still makes a row. +# does not depend on how the equations are scaled; a row is zero only when all its entries are exactly zero, which +# the caller makes of the entries that are roundoff of their own cancelling terms (see `_magnitude`), so a tiny +# factor that is really there (1e-13, 1e-20) still makes a row. function _rowspace(M) keep = findall(i -> norm(M[i, :]) > 0, axes(M, 1)) M = M[keep, :] ./ norm.(eachrow(M[keep, :])) @@ -351,11 +370,15 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) ArgumentError(isabc ? "the absorbing condition on $name has a source (a term without E), which is not supported; drive the field with a WavePort or a volume source; $form" : "the conditions on $name prescribe a nonzero tangential field, which is not supported; $form") ) C_at = Symbolics.build_function(vec(C), slots.N...; expression = Val(false))[1] + B_at = Symbolics.build_function(vec(Num.(_magnitude.(unwrap.(C)))), slots.N...; expression = Val(false))[1] for (n, facet) in _facet_normals(domain.mesh, String(name)) # The roundoff of a normal that lies in a coordinate plane is not a coefficient: snap it to exactly 0, so # that n[1] * E vanishes there while n[1] + 1e-16 does not. n = [abs(x) < 1.0e-14 ? 0.0 : x for x in n] Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 15) + # An entry is zero when it is roundoff of the terms that cancel in it: at most 64 eps of their absolute sum. + Bn = reshape(_real_values(B_at(n...), "a coefficient of the condition"), length(Bs), 15) + Cn = ifelse.(abs.(Cn) .<= 64eps() .* Bn, 0.0, Cn) where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" if !isabc Cn = Cn[:, 13:15] @@ -375,11 +398,14 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) # The columns act on G ~ k E, V = ∂ₜE ~ ω E and U = E; in these units the curl and impedance parts are of # the same size (ν k = c ω) whatever the unit system, where the raw coefficients can differ by many orders. scale = [fill(ω * sqrt(a2 / nu), 9); fill(ω, 3); ones(3)]' - # Rows are judged at the actual normal alone; a term in E counts in a surviving row only. - survives = [norm(Cn[i, :] .* vec(scale)) > 0 for i in eachindex(Bs)] - has_e_term = any(i -> survives[i] && any(!iszero, Cn[i, 13:15]), eachindex(Bs)) + # A row that vanishes (all its entries zero above) is no equation; a term in E counts in a surviving row. + has_e_term = any(i -> any(!iszero, Cn[i, 13:15]), eachindex(Bs)) Q = _rowspace(Cn .* scale) - P = _rowspace(_absorbing_target(n, nu, c) .* scale) + # The absorbing condition has two equations, its tangential components. + axis = argmin(abs.(n)) + t1 = normalize(cross(n, [k == axis for k in 1:3])) + tangents = [t1'; cross(n, t1)'] + P = _rowspace((tangents * _absorbing_target(n, nu, c)) .* scale) size(Q, 1) == 2 || throw( ArgumentError("the conditions $where have $(size(Q, 1)) independent equations; the absorbing condition n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) has 2; $form") ) diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index 540d3730..64a4fc51 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -166,6 +166,22 @@ end end end +@testset "a linear combination of the absorbing equations is redundant on an oblique face" begin + grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + for i in eachindex(grid.nodes) + x = grid.nodes[i].x + grid.nodes[i] = Node(Vec(x[1], x[2], x[3] + 0.2x[1] + 0.3x[2])) + end + Ω = MeshDomain(grid) + Γ = boundarypiece(Ω, :top) + bc = abc(Γ) + r = [e.lhs - e.rhs for e in bc] + solve_with(bcs) = discretize(system(Ω, bcs), edge_disc(Ω; omega = 2.0)) + base = solve_with(bc) + combination = solve_with([bc; -0.2 * r[1] - 0.3 * r[2] + r[3] ~ 0]) + @test combination.A == base.A && combination.b == base.b +end + @testset "rejections of absorbing conditions and ports" begin grid = guide(10.0, 5.0) addfacetset!(grid, "lid", x -> x[3] ≈ 10.0) # the facets of top again From 6f565c4cbeec0de5557eb3449ff2a5bc2710c976 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 22:52:42 +0000 Subject: [PATCH 29/34] 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 39b132d10e3d8500c22189d31dce9ff3f4b0232b Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 00:22:10 +0000 Subject: [PATCH 30/34] Front end: zero entries by their own evaluation error, not by the size of their terms The absolute-term-sum bound treated a coefficient 1e15 (n[1] + 0.25 n[3]) + 1 as roundoff because its terms are large, which deleted a real independent constraint. A running forward error bound of the evaluation (the normal and constants uncertain by an ulp, each operation by a rounding) now decides: an entry is zero when it is within 4 times that bound, which still removes the residue of an explicit linear combination of the absorbing equations on an oblique face. 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/frontend.jl | 54 ++++++++++++++++++++++++++-------- test/Maxwell/frontend_ports.jl | 17 +++++++++++ 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 15b014c8..64df7f5f 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -292,22 +292,47 @@ function _absorbing_target(n, ν, c) ) end -# The expression with every term replaced by its absolute value, so that sums add where they would cancel: the size -# that a coefficient has before cancellation, against which roundoff is judged. -function _magnitude(ex) +# The value of the coefficient expression `ex` at the normal `normal` (a Dict from the normal's slots to numbers) with +# a running forward bound on its rounding error: err(a ± b) = err(a) + err(b) + ε|a ± b|, err(a b) = |a| err(b) + +# |b| err(a) + ε|a b|, and likewise for quotients and powers. The normal and the constants of the equation are +# uncertain by a rounding each (a constant by half an ulp, the normal of a facet by an ulp), so a coefficient is as +# uncertain as its evaluation, not as large as its terms. +function _value_error(ex, normal) if SymbolicUtils.iscall(ex) op, args = SymbolicUtils.operation(ex), SymbolicUtils.arguments(ex) + parts = [_value_error(a, normal) for a in args] if op === (+) || op === (-) - return sum(_magnitude, args) + v, e = parts[1] + if op === (-) && length(parts) == 1 + return -v, e + end + for (w, f) in parts[2:end] + s = op === (+) ? v + w : v - w + v, e = s, e + f + eps() * abs(s) + end + return v, e elseif op === (*) - return prod(_magnitude, args) + v, e = parts[1] + for (w, f) in parts[2:end] + p = v * w + v, e = p, abs(v) * f + abs(w) * e + eps() * abs(p) + end + return v, e elseif op === (/) - return _magnitude(args[1]) / _magnitude(args[2]) + (v, e), (w, f) = parts + q = v / w + return q, (e + abs(q) * f) / abs(w) + eps() * abs(q) + elseif op === (^) + (v, e), (k, _) = parts + p = v^k + return p, abs(k * v^(k - 1)) * e + eps() * abs(p) end - return abs(Num(ex)) + f = op(first.(parts)...) + return f, eps() * abs(f) + sum(last, parts) * max(1, abs(f)) end value = SymbolicUtils.unwrap_const(ex) - return value isa Number ? abs(value) : abs(Num(ex)) + value isa Number && return Float64(value), eps() / 2 * abs(value) # a decimal constant is rounded + return normal[ex], eps() * abs(normal[ex]) # the normal of an oblique facet carries its own roundoff end # An orthonormal basis of the row space of M, as rows. Each row is scaled to unit length first, so that the result @@ -370,15 +395,20 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) ArgumentError(isabc ? "the absorbing condition on $name has a source (a term without E), which is not supported; drive the field with a WavePort or a volume source; $form" : "the conditions on $name prescribe a nonzero tangential field, which is not supported; $form") ) C_at = Symbolics.build_function(vec(C), slots.N...; expression = Val(false))[1] - B_at = Symbolics.build_function(vec(Num.(_magnitude.(unwrap.(C)))), slots.N...; expression = Val(false))[1] for (n, facet) in _facet_normals(domain.mesh, String(name)) # The roundoff of a normal that lies in a coordinate plane is not a coefficient: snap it to exactly 0, so # that n[1] * E vanishes there while n[1] + 1e-16 does not. n = [abs(x) < 1.0e-14 ? 0.0 : x for x in n] Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 15) - # An entry is zero when it is roundoff of the terms that cancel in it: at most 64 eps of their absolute sum. - Bn = reshape(_real_values(B_at(n...), "a coefficient of the condition"), length(Bs), 15) - Cn = ifelse.(abs.(Cn) .<= 64eps() .* Bn, 0.0, Cn) + # An entry is zero when it is within a few ulps of its own evaluation error (see `_value_error`): a residue + # of cancelling terms is no larger than that error, whereas a coefficient that is large only through its + # terms (1e15 (n[1] + 0.25 n[3]) + 1) is as certain as its error and keeps its real part. The factor 4 + # allows for the order of the compiled evaluation differing from that of the bound. + normal = Dict(unwrap(slots.N[d]) => n[d] for d in 1:3) + for i in eachindex(Bs), j in 1:15 + value, error = _value_error(unwrap(C[i, j]), normal) + abs(value) <= 4error && (Cn[i, j] = 0.0) + end where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" if !isabc Cn = Cn[:, 13:15] diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index 64a4fc51..eabe23c6 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -182,6 +182,23 @@ end @test combination.A == base.A && combination.b == base.b end +@testset "a unit offset on a large cancelling term is a coefficient" begin + grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + for i in eachindex(grid.nodes) + x = grid.nodes[i].x + grid.nodes[i] = Node(Vec(x[1], x[2], x[3] + 0.25x[1] + 0.5x[2])) + end + Ω = MeshDomain(grid) + Γ = boundarypiece(Ω, :top) # n = (-1, -2, 4) / sqrt(21), so n[1] + 0.25n[3] = 0 + n, Eb = facet_normal(Γ), trace(Γ) + bc = abc(Γ) + solve_with(extra) = discretize(system(Ω, [bc; extra]; f = [1.0, 0.0, 0.0]), edge_disc(Ω; omega = 2.0)) + q = 1.0e15 * (n[1] + 0.25n[3]) + 1 + @test occursin("independent equations", message(() -> solve_with([q * dot(n, Dt.(Eb)) ~ 0]))) + @test message(() -> solve_with([q * dot(n, Eb) ~ 0])) != "no error" + @test occursin("independent equations", message(() -> solve_with([dot(n, Dt.(Eb)) ~ 0]))) +end + @testset "rejections of absorbing conditions and ports" begin grid = guide(10.0, 5.0) addfacetset!(grid, "lid", x -> x[3] ≈ 10.0) # the facets of top again From e01f846708cec21174222368f365793899c00f11 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 03:26:28 +0000 Subject: [PATCH 31/34] Front end: validate the trace arguments inside boundary derivatives The derivative branch replaced the trace inside Differential(t) or a coordinate derivative with a slot without checking its arguments, so a delayed trace E(t - tau, Gamma) was accepted as the ordinary matched absorber although it carries a phasor factor. The same E(t, Gamma) check now runs for every trace, with regressions for shifted, fixed and scaled time, including nested in a cross product or a component. 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/frontend.jl | 1 + test/Maxwell/frontend_ports.jl | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index ad263b4c..8a3c3e5f 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -272,6 +272,7 @@ function _boundary_rules!(rules, ex, eq, slots, ctx) f !== nothing && op.order == 1 || throw( ArgumentError("$eq has the derivative $(Num(ex)); a boundary condition with omega may only take first derivatives of the components of E(t, Γ) themselves; $_ABC_FORM") ) + _check_trace_arguments(inner, ctx.t, ctx.piece, eq) j = findfirst(isequal(op.x), ctx.sivs) if isequal(op.x, ctx.t) rules[ex] = unwrap(slots.V[ctx.fields[f]]) diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index eabe23c6..d4270761 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -199,6 +199,25 @@ end @test occursin("independent equations", message(() -> solve_with([dot(n, Dt.(Eb)) ~ 0]))) end +@testset "every trace in a boundary condition must be E(t, Γ)" begin + Ω = MeshDomain(guide(10.0, 5.0)) + Γ = boundarypiece(Ω, :top) + n = facet_normal(Γ) + Eb = trace(Γ) + solve_with(bcs) = discretize(system(Ω, [pec(Ω, WALLS); bcs]), edge_disc(Ω)) + @test solve_with(abc(Γ)) isa LinearProblem + τ = π / (2K0) + delayed = [E(t - τ, Γ)[c] for c in 1:3] + # The delayed derivative carries a phasor factor exp(-iωτ): it is not the matched absorber. + shifted = cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.(delayed))) + @test occursin("not a condition at one time", message(() -> solve_with(shifted))) + # A shifted trace nested in a cross product or a component, and a fixed or scaled time, are rejected too. + @test occursin("not a condition at one time", message(() -> solve_with(cross(n, cross(n, delayed)) .~ cross(n, curl(Eb, X))))) + @test occursin("not a condition at one time", message(() -> solve_with([cross(n, delayed)[1] ~ 0; abc(Γ)[2:3]]))) + @test occursin("not a condition at one time", message(() -> solve_with(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.([E(0.0, Γ)[c] for c in 1:3])))))) + @test occursin("not a condition at one time", message(() -> solve_with(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.([E(2t, Γ)[c] for c in 1:3])))))) +end + @testset "rejections of absorbing conditions and ports" begin grid = guide(10.0, 5.0) addfacetset!(grid, "lid", x -> x[3] ≈ 10.0) # the facets of top again From c175b6a7c6479b23f3cc9626f58e220ce72baa7d Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 03:54:22 +0000 Subject: [PATCH 32/34] Sweeps: an empty frequency collection gives an empty sweep solve_sweep passed validation for an empty collection and then threw a BoundsError at first(omegas); it returns the empty result like the other branches of the stack. 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/sweep.jl | 1 + test/Maxwell/ports.jl | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl index df5283b7..e66bd6fb 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -46,6 +46,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 diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index d7a61ff3..1332513a 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -341,3 +341,8 @@ end @test_throws "finite positive frequencies" solve_sweep(model, [2π * 10.0e9, ω]) end 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 From 276749af90d96ae32ec3103ffc5b5bb5adbfc7ae Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 06:12:50 +0000 Subject: [PATCH 33/34] Front end: classify boundary coefficients clearly zero, clearly nonzero or ambiguous An error interval containing zero does not show that a coefficient is zero: 1e15 (n[1] + 0.25 n[3]) + 1 is exactly 1 but evaluates with a rounding error of the size of 1 and was silently deleted. An entry within 4 err of zero is now zero only when it is also tiny next to the largest clearly nonzero entry (a cancellation residue, as in an explicit combination of the equations); an O(1) coefficient dominated by rounding error is rejected with an error naming the equation and the coefficient. A coefficient of the size of its own tiny error (n[1] + 0.25 n[3] + 1e-16) is still taken as a residue, a documented limitation. 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/frontend.jl | 28 +++++++++++++++++++----- test/Maxwell/frontend_ports.jl | 40 +++++++++++++++------------------- 2 files changed, 39 insertions(+), 29 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 6f88de50..5d5395ad 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -415,14 +415,30 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) # that n[1] * E vanishes there while n[1] + 1e-16 does not. n = [abs(x) < 1.0e-14 ? 0.0 : x for x in n] Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 15) - # An entry is zero when it is within a few ulps of its own evaluation error (see `_value_error`): a residue - # of cancelling terms is no larger than that error, whereas a coefficient that is large only through its - # terms (1e15 (n[1] + 0.25 n[3]) + 1) is as certain as its error and keeps its real part. The factor 4 - # allows for the order of the compiled evaluation differing from that of the bound. + # Each entry is classified by its value v and the running error bound err of its evaluation (`_value_error`): + # clearly nonzero, |v| > 4 err: kept. The factor 4 allows for the compiled evaluation summing in another + # order than the bound; + # clearly zero, |v| <= 4 err and |v| <= 1e-12 times the largest clearly nonzero entry: the residue of + # cancelling terms (an explicit linear combination of the equations), taken as 0; + # ambiguous, |v| <= 4 err but |v| is not tiny: the coefficient is O(1) yet dominated by rounding error + # (1e15 (n[1] + 0.25 n[3]) + 1), so it is neither kept nor dropped silently but rejected. + # A coefficient of the size of its own rounding error and tiny next to the equation (n[1] + 0.25 n[3] + 1e-16 + # is about 1e-16 with an error of the same size) cannot be told from a cancellation residue and is taken as 0. normal = Dict(unwrap(slots.N[d]) => n[d] for d in 1:3) + evaluated = [_value_error(unwrap(C[i, j]), normal) for i in eachindex(Bs), j in 1:15] + nonzero = [abs(v) > 4e for (v, e) in evaluated] + natural = maximum((abs(v) for ((v, e), keep) in zip(evaluated, nonzero) if keep); init = 0.0) for i in eachindex(Bs), j in 1:15 - value, error = _value_error(unwrap(C[i, j]), normal) - abs(value) <= 4error && (Cn[i, j] = 0.0) + nonzero[i, j] && continue + value, error = evaluated[i, j] + abs(value) <= 1.0e-12 * natural || throw( + ArgumentError( + "the coefficient of $(W[j]) in equation $(eqBs[i][1]) of the conditions on $name at facet $((facet[1], facet[2])) " * + "evaluates to $value with a rounding error bound of $error: it cannot be distinguished from rounding error at the " * + "working precision; write the equation without cancelling terms (for example without a large multiple of a quantity that vanishes)" + ) + ) + Cn[i, j] = 0.0 end where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" if !isabc diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index d4270761..654cf61e 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -182,7 +182,7 @@ end @test combination.A == base.A && combination.b == base.b end -@testset "a unit offset on a large cancelling term is a coefficient" begin +@testset "a coefficient dominated by rounding error is rejected, not dropped" begin grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) for i in eachindex(grid.nodes) x = grid.nodes[i].x @@ -193,29 +193,23 @@ end n, Eb = facet_normal(Γ), trace(Γ) bc = abc(Γ) solve_with(extra) = discretize(system(Ω, [bc; extra]; f = [1.0, 0.0, 0.0]), edge_disc(Ω; omega = 2.0)) - q = 1.0e15 * (n[1] + 0.25n[3]) + 1 - @test occursin("independent equations", message(() -> solve_with([q * dot(n, Dt.(Eb)) ~ 0]))) - @test message(() -> solve_with([q * dot(n, Eb) ~ 0])) != "no error" + base = solve_with(Equation[]) + # q is exactly 1 but evaluates with a rounding error of the size of 1: the constraint can be neither kept nor dropped. + for multiplier in (1.0e15, 2.0e15, 1.0e16, 1.0e17) + q = multiplier * (n[1] + 0.25n[3]) + 1 + # Rejected either as ambiguous or, where the evaluation is resolvable, as the independent equation it is. + rejected(msg) = occursin("cannot be distinguished from rounding error", msg) || occursin("independent equations", msg) + @test rejected(message(() -> solve_with([q * dot(n, Dt.(Eb)) ~ 0]))) + @test rejected(message(() -> solve_with([q * dot(n, Eb) ~ 0]))) + end + # Without the cancelling term it is an independent constraint. @test occursin("independent equations", message(() -> solve_with([dot(n, Dt.(Eb)) ~ 0]))) -end - -@testset "every trace in a boundary condition must be E(t, Γ)" begin - Ω = MeshDomain(guide(10.0, 5.0)) - Γ = boundarypiece(Ω, :top) - n = facet_normal(Γ) - Eb = trace(Γ) - solve_with(bcs) = discretize(system(Ω, [pec(Ω, WALLS); bcs]), edge_disc(Ω)) - @test solve_with(abc(Γ)) isa LinearProblem - τ = π / (2K0) - delayed = [E(t - τ, Γ)[c] for c in 1:3] - # The delayed derivative carries a phasor factor exp(-iωτ): it is not the matched absorber. - shifted = cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.(delayed))) - @test occursin("not a condition at one time", message(() -> solve_with(shifted))) - # A shifted trace nested in a cross product or a component, and a fixed or scaled time, are rejected too. - @test occursin("not a condition at one time", message(() -> solve_with(cross(n, cross(n, delayed)) .~ cross(n, curl(Eb, X))))) - @test occursin("not a condition at one time", message(() -> solve_with([cross(n, delayed)[1] ~ 0; abc(Γ)[2:3]]))) - @test occursin("not a condition at one time", message(() -> solve_with(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.([E(0.0, Γ)[c] for c in 1:3])))))) - @test occursin("not a condition at one time", message(() -> solve_with(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.([E(2t, Γ)[c] for c in 1:3])))))) + # A tiny offset is of the size of the rounding error of its own cancelling terms and is taken as the cancellation + # residue it cannot be told from (a documented limitation): the problem is the one without it. + for offset in (1.0e-16, 1.0e-20) + prob = solve_with([(n[1] + 0.25n[3] + offset) * dot(n, Dt.(Eb)) ~ 0]) + @test prob.A == base.A && prob.b == base.b + end end @testset "rejections of absorbing conditions and ports" begin From 38594a221f70c19583e4b6dc439797e82c4c878c Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 07:32:27 +0000 Subject: [PATCH 34/34] Front end: classify boundary equations after the normal, and never infer zero from an error interval An entry is now zero only when it evaluates to exactly 0 on the snapped normal, nonzero when it exceeds 4 times its error bound, and otherwise ambiguous and rejected, with no comparison against the other equations, so rescaling them cannot change the outcome. A redundant combination of the absorbing equations is recognised where it cancels exactly (axis-aligned faces) and rejected as ambiguous where it leaves a rounding residue. Absorbing or perfect conductor is decided per facet from the equations at the actual normal, so a derivative equation that vanishes there (n[1] Dt(E) with n[1] = 0) no longer turns a perfect conductor into an absorber. The deleted trace-time regression is restored. 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/frontend.jl | 42 ++++++++------ test/Maxwell/frontend_ports.jl | 100 ++++++++++++++++++++++++--------- 2 files changed, 97 insertions(+), 45 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 606f5c97..c051c3b3 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -434,38 +434,41 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) ArgumentError(isabc ? "the absorbing condition on $name has a source (a term without E), which is not supported; drive the field with a WavePort or a volume source; $form" : "the conditions on $name prescribe a nonzero tangential field, which is not supported; $form") ) C_at = Symbolics.build_function(vec(C), slots.N...; expression = Val(false))[1] + abc_facets = Bool[] for (n, facet) in _facet_normals(domain.mesh, String(name)) # The roundoff of a normal that lies in a coordinate plane is not a coefficient: snap it to exactly 0, so # that n[1] * E vanishes there while n[1] + 1e-16 does not. n = [abs(x) < 1.0e-14 ? 0.0 : x for x in n] Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 15) - # Each entry is classified by its value v and the running error bound err of its evaluation (`_value_error`): - # clearly nonzero, |v| > 4 err: kept. The factor 4 allows for the compiled evaluation summing in another - # order than the bound; - # clearly zero, |v| <= 4 err and |v| <= 1e-12 times the largest clearly nonzero entry: the residue of - # cancelling terms (an explicit linear combination of the equations), taken as 0; - # ambiguous, |v| <= 4 err but |v| is not tiny: the coefficient is O(1) yet dominated by rounding error - # (1e15 (n[1] + 0.25 n[3]) + 1), so it is neither kept nor dropped silently but rejected. - # A coefficient of the size of its own rounding error and tiny next to the equation (n[1] + 0.25 n[3] + 1e-16 - # is about 1e-16 with an error of the same size) cannot be told from a cancellation residue and is taken as 0. + # Each entry is classified by its value v and the running error bound err of its evaluation (`_value_error`), + # and by nothing else, so that no other equation can change the outcome: + # v == 0 exactly (a truly vanishing coefficient such as n[1] * E at n[1] = 0 on the snapped normal): zero; + # |v| > 4 err: nonzero, kept (the factor 4 allows for the compiled evaluation summing in another order + # than the bound); + # 0 < |v| <= 4 err: ambiguous, rejected. An error interval that contains zero does not show that the + # coefficient is zero (1e15 (n[1] + 0.25 n[3]) + 1 is exactly 1, n[1] + 0.25 n[3] + 1e-16 is 1e-16), and + # dropping it would silently delete an independent equation. + # So a redundant combination of the equations is recognised only where it cancels exactly; one whose + # cancellation leaves a rounding-level residue (r3 - 0.2 r1 - 0.3 r2 on an oblique face) is rejected as + # ambiguous, and should be written without cancelling terms. normal = Dict(unwrap(slots.N[d]) => n[d] for d in 1:3) - evaluated = [_value_error(unwrap(C[i, j]), normal) for i in eachindex(Bs), j in 1:15] - nonzero = [abs(v) > 4e for (v, e) in evaluated] - natural = maximum((abs(v) for ((v, e), keep) in zip(evaluated, nonzero) if keep); init = 0.0) for i in eachindex(Bs), j in 1:15 - nonzero[i, j] && continue - value, error = evaluated[i, j] - abs(value) <= 1.0e-12 * natural || throw( + value, error = _value_error(unwrap(C[i, j]), normal) + iszero(value) && (Cn[i, j] = 0.0) + iszero(value) || abs(value) > 4error || throw( ArgumentError( "the coefficient of $(W[j]) in equation $(eqBs[i][1]) of the conditions on $name at facet $((facet[1], facet[2])) " * "evaluates to $value with a rounding error bound of $error: it cannot be distinguished from rounding error at the " * "working precision; write the equation without cancelling terms (for example without a large multiple of a quantity that vanishes)" ) ) - Cn[i, j] = 0.0 end where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" - if !isabc + # Absorbing or perfect conductor is decided here, from the equations at the actual normal: a derivative whose + # coefficient vanishes there (n[1] * Dt(E) on a face with n[1] = 0) does not make the condition absorbing. + facet_abc = any(!iszero, Cn[:, 1:12]) + push!(abc_facets, facet_abc) + if !facet_abc Cn = Cn[:, 13:15] # Each equation is judged by its own size, so that one written with a large coefficient hides no other. Cn = Cn[[norm(Cn[i, :]) > 0 for i in axes(Cn, 1)], :] @@ -502,7 +505,10 @@ function _recognise_boundaries(bcs, fields, pvals, ctx, domain, cells, ω) ArgumentError("the conditions $where are not n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) of the adjacent cell (ν = $nu, sqrt(ε/μ) = $c): the coefficient of curl E, the impedance or the sign differs, or a term in E is added; $form") ) end - push!(isabc ? absorbing : pec, String(name)) + all(abc_facets) || !any(abc_facets) || throw( + ArgumentError("the conditions on $name are absorbing on some of its facets and a perfect conductor on others; give each piece one kind of condition") + ) + push!(all(abc_facets) ? absorbing : pec, String(name)) end # Overlapping perfect-conductor pieces only constrain the same dofs again; any other overlap would add a # boundary term twice or give a facet two conditions. diff --git a/test/Maxwell/frontend_ports.jl b/test/Maxwell/frontend_ports.jl index 654cf61e..732deeba 100644 --- a/test/Maxwell/frontend_ports.jl +++ b/test/Maxwell/frontend_ports.jl @@ -166,23 +166,33 @@ end end end -@testset "a linear combination of the absorbing equations is redundant on an oblique face" begin - grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) - for i in eachindex(grid.nodes) - x = grid.nodes[i].x - grid.nodes[i] = Node(Vec(x[1], x[2], x[3] + 0.2x[1] + 0.3x[2])) - end - Ω = MeshDomain(grid) +@testset "redundant combinations are recognised where they cancel exactly" begin + ambiguous(msg) = occursin("cannot be distinguished from rounding error", msg) + # An axis-aligned face: the coefficients are exact, so a linear combination of the equations is redundant. + Ω = MeshDomain(guide(10.0, 5.0)) Γ = boundarypiece(Ω, :top) + walls = pec(Ω, WALLS) bc = abc(Γ) r = [e.lhs - e.rhs for e in bc] - solve_with(bcs) = discretize(system(Ω, bcs), edge_disc(Ω; omega = 2.0)) + solve_with(bcs) = discretize(system(Ω, [walls; bcs]), edge_disc(Ω)) base = solve_with(bc) - combination = solve_with([bc; -0.2 * r[1] - 0.3 * r[2] + r[3] ~ 0]) + combination = solve_with([bc; r[1] + 2r[2] ~ 0]) @test combination.A == base.A && combination.b == base.b + # An oblique face: the cancellation leaves a rounding-level residue, which cannot be told from a small constraint + # and is rejected as ambiguous rather than dropped. + grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + for i in eachindex(grid.nodes) + x = grid.nodes[i].x + grid.nodes[i] = Node(Vec(x[1], x[2], x[3] + 0.2x[1] + 0.3x[2])) + end + Ωs = MeshDomain(grid) + Γs = boundarypiece(Ωs, :top) + bcs_ = abc(Γs) + rs = [e.lhs - e.rhs for e in bcs_] + @test ambiguous(message(() -> discretize(system(Ωs, [bcs_; -0.2 * rs[1] - 0.3 * rs[2] + rs[3] ~ 0]), edge_disc(Ωs; omega = 2.0)))) end -@testset "a coefficient dominated by rounding error is rejected, not dropped" begin +@testset "a coefficient dominated by rounding error is rejected, not dropped, whatever the other equations" begin grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) for i in eachindex(grid.nodes) x = grid.nodes[i].x @@ -192,26 +202,62 @@ end Γ = boundarypiece(Ω, :top) # n = (-1, -2, 4) / sqrt(21), so n[1] + 0.25n[3] = 0 n, Eb = facet_normal(Γ), trace(Γ) bc = abc(Γ) - solve_with(extra) = discretize(system(Ω, [bc; extra]; f = [1.0, 0.0, 0.0]), edge_disc(Ω; omega = 2.0)) - base = solve_with(Equation[]) - # q is exactly 1 but evaluates with a rounding error of the size of 1: the constraint can be neither kept nor dropped. - for multiplier in (1.0e15, 2.0e15, 1.0e16, 1.0e17) - q = multiplier * (n[1] + 0.25n[3]) + 1 - # Rejected either as ambiguous or, where the evaluation is resolvable, as the independent equation it is. - rejected(msg) = occursin("cannot be distinguished from rounding error", msg) || occursin("independent equations", msg) - @test rejected(message(() -> solve_with([q * dot(n, Dt.(Eb)) ~ 0]))) - @test rejected(message(() -> solve_with([q * dot(n, Eb) ~ 0]))) - end - # Without the cancelling term it is an independent constraint. - @test occursin("independent equations", message(() -> solve_with([dot(n, Dt.(Eb)) ~ 0]))) - # A tiny offset is of the size of the rounding error of its own cancelling terms and is taken as the cancellation - # residue it cannot be told from (a documented limitation): the problem is the one without it. - for offset in (1.0e-16, 1.0e-20) - prob = solve_with([(n[1] + 0.25n[3] + offset) * dot(n, Dt.(Eb)) ~ 0]) - @test prob.A == base.A && prob.b == base.b + ambiguous(msg) = occursin("cannot be distinguished from rounding error", msg) + independent(msg) = occursin("independent equations", msg) + # The standard condition, unscaled and scaled: the outcome must not depend on the other equations. + for scale in (1.0, 1.0e13) + equations = [scale * e.lhs ~ scale * e.rhs for e in bc] + solve_with(extra) = discretize(system(Ω, [equations; extra]; f = [1.0, 0.0, 0.0]), edge_disc(Ω; omega = 2.0)) + base = solve_with(Equation[]) + # q is exactly 1 but evaluates with a rounding error of the size of 1: neither kept nor dropped silently. + for multiplier in (1.0e15, 2.0e15, 1.0e16, 1.0e17) + q = multiplier * (n[1] + 0.25n[3]) + 1 + for equation in (q * dot(n, Dt.(Eb)) ~ 0, q * dot(n, Eb) ~ 0) + msg = message(() -> solve_with([equation])) + @test ambiguous(msg) || independent(msg) + end + end + # Without the cancelling term it is an independent constraint. + @test independent(message(() -> solve_with([dot(n, Dt.(Eb)) ~ 0]))) + # An offset of the size of its own rounding error is ambiguous, never dropped. (An offset of 1e-20 is absorbed + # by the first addition, which then evaluates to exactly 0.0: that coefficient is indistinguishable from the + # truly vanishing n[1] * E, a limitation of floating-point evaluation.) + msg = message(() -> solve_with([(n[1] + 0.25n[3] + 1.0e-16) * dot(n, Dt.(Eb)) ~ 0])) + @test ambiguous(msg) || independent(msg) end end +@testset "every trace in a boundary condition must be E(t, Γ)" begin + Ω = MeshDomain(guide(10.0, 5.0)) + Γ = boundarypiece(Ω, :top) + n = facet_normal(Γ) + Eb = trace(Γ) + solve_with(bcs) = discretize(system(Ω, [pec(Ω, WALLS); bcs]), edge_disc(Ω)) + @test solve_with(abc(Γ)) isa LinearProblem + τ = π / (2K0) + delayed = [E(t - τ, Γ)[c] for c in 1:3] + # The delayed derivative carries a phasor factor exp(-iωτ): it is not the matched absorber. + shifted = cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.(delayed))) + @test occursin("not a condition at one time", message(() -> solve_with(shifted))) + # A shifted trace nested in a cross product or a component, and a fixed or scaled time, are rejected too. + @test occursin("not a condition at one time", message(() -> solve_with(cross(n, cross(n, delayed)) .~ cross(n, curl(Eb, X))))) + @test occursin("not a condition at one time", message(() -> solve_with([cross(n, delayed)[1] ~ 0; abc(Γ)[2:3]]))) + @test occursin("not a condition at one time", message(() -> solve_with(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.([E(0.0, Γ)[c] for c in 1:3])))))) + @test occursin("not a condition at one time", message(() -> solve_with(cross(n, curl(Eb, X)) .~ -cross(n, cross(n, Dt.([E(2t, Γ)[c] for c in 1:3])))))) +end + +@testset "a vanishing derivative equation does not make a perfect conductor absorbing" begin + Ω = MeshDomain(guide(10.0, 5.0)) + Γ = boundarypiece(Ω, :top) # n[1] = 0 on it + n, Eb = facet_normal(Γ), trace(Γ) + plain = [pec(Ω, WALLS); cross(n, Eb) .~ 0] + extended = [pec(Ω, WALLS); cross(n, Eb) .~ 0; n[1] * Dt(Eb[3]) ~ 0] + @test (; model = maxwell_model(system(Ω, extended), edge_disc(Ω)).model).model.pec == maxwell_model(system(Ω, plain), edge_disc(Ω)).model.pec + a, b = discretize(system(Ω, extended), edge_disc(Ω)), discretize(system(Ω, plain), edge_disc(Ω)) + @test a.A == b.A && a.b == b.b + @test isempty(maxwell_model(system(Ω, extended), edge_disc(Ω)).model.absorbing) +end + @testset "rejections of absorbing conditions and ports" begin grid = guide(10.0, 5.0) addfacetset!(grid, "lid", x -> x[3] ≈ 10.0) # the facets of top again