diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 227f53c..1bce679 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 5b86fdb..f5e3279 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -30,6 +30,45 @@ 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(ε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 +[`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 through the TE10 wave impedance `ωμ0μr/β`. For a propagating port these are power waves. Below cutoff +the propagation constant is `β = -iα`, the evanescent branch, which carries no real axial power: the coefficients +are then generalized traveling-wave coefficients with the same normalisation, still supported, but without an +individual incident or outgoing power, and `S` is not power conserving. + +A 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` +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 @@ -39,7 +78,7 @@ for the equivalent `MaxwellModel` (in units with `ε0 = μ0 = 1`). The operator and the perfect conductor with [`facet_normal`](@ref). ```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 @@ -56,7 +95,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}) @@ -83,6 +153,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 diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 75182d9..8a52ca6 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: dot, mul!, norm, rank +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 @@ -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 @@ -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 using PDEBase.StrongForm: Weighted include("discretization.jl") include("frontend.jl") @@ -56,9 +57,11 @@ export Weighted # from a PDESystem without the scalar weak form. include("maxwell/model.jl") include("maxwell/driven.jl") +include("maxwell/sweep.jl") include("maxwell/frontend.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! export MaxwellSolution, driven_problem, solve_driven, field_values +export WavePort, MaxwellSweep, solve_sweep export curl, facet_normal, maxwell_model include("precompile.jl") diff --git a/src/discretization.jl b/src/discretization.jl index c004a88..73cb1c4 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 the steady `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,17 @@ 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) && + 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 @@ -239,6 +248,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 33d4aa2..13a9ef0 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -273,6 +273,9 @@ function _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) return nothing end +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 Γ" + # The trace of the field in a boundary condition is E(t, Γ): the time variable and the boundary piece of the condition, # nothing at a fixed or shifted time (an initial condition) and no other argument. function _check_trace_arguments(ex, t, Γ, eq) @@ -282,13 +285,121 @@ function _check_trace_arguments(ex, t, Γ, eq) return nothing 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" +# 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") + ) + _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]]) + 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 + _check_trace_arguments(ex, ctx.t, ctx.piece, eq) + 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 + +# 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 === (-) + 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 === (*) + 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 === (/) + (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 + f = op(first.(parts)...) + return f, eps() * abs(f) + sum(last, parts) * max(1, abs(f)) + end + value = SymbolicUtils.unwrap_const(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 +# 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, :])) + 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) +# 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, `ω` is the angular frequency. +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) @@ -301,52 +412,114 @@ 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) - if f !== nothing - _check_trace_arguments(ex, ctx.t, Γ, eq) - rules[ex] = unwrap(U[fields[f]]) - end - end - end + rules = _boundary_rules!(Dict{Any, Any}(), unwrap(res), eq, slots, (; ctx..., fields, piece = Γ)) 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] + abc_facets = Bool[] 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) + # 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`), + # 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) + for i in eachindex(Bs), j in 1:15 + 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)" + ) + ) + end where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" - # 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)], :] - Cn = Cn ./ norm.(eachrow(Cn)) - maximum(abs, Cn * n; init = 0.0) > 1.0e-10 && throw( - ArgumentError("the conditions $where constrain the normal component of E, unlike n × E = 0; $pform") + # 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)], :] + Cn = Cn ./ norm.(eachrow(Cn)) + maximum(abs, Cn * n; init = 0.0) > 1.0e-10 && 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") ) - rank(Cn) == 2 || throw( - ArgumentError("the conditions $where constrain $(rank(Cn)) of the two tangential components of E; $pform") + c = sqrt(a2 * nu) + # 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)]' + # 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) + # 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") + ) + # A term in E has the weight of E itself, which the field units of the derivative columns can make small. + (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 + 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 - return sort!(String.(collect(keys(byp)))) + # 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 + 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 """ @@ -364,9 +537,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`. The front end works in a window: every nonzero ν, a₀, a₁, a₂ and source amplitude and ω lie in `1e-100 ≤ |c| ≤ 1e100`, and the products `ω² a₂` and `ω a₁` in `1e-250 ≤ |c| ≤ 1e250`. This is far wider than SI-unit physics @@ -409,34 +595,53 @@ 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], t = ctx.t), 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 - _check_window("ω", ω, nothing) - for x in centroids - _check_window_sources(_real_values(source_at(x...), "a source")) - end - 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) || iszero(1 / nu) || !isfinite(1 / nu)) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) for (name, value) in (("ν", nu), ("a₀", a0), ("a₁", a1), ("a₂", a2)) _check_window(name, value, cell) end - for (name, value) in (("ω² a₂", ω^2 * a2), ("ω a₁", ω * a1)) + for (name, value) in (("ω² a₂", disc.omega^2 * a2), ("ω a₁", disc.omega * a1)) _check_product_window(name, value, cell) end + (; nu, a0, a1, a2) + end + _check_window("ω", disc.omega, nothing) + for x in centroids + _check_window_sources(_real_values(source_at(x...), "a source")) + end + (; pec, absorbing) = _recognise_boundaries( + sys.bcs, comps, pvals[keep], (; ops, params = ctx.params[keep], sivs = ctx.sivs, t = ctx.t), disc.domain, cells, disc.omega + ) + 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 = map(enumerate(cells)) do (cell, c) # The net reaction a₀ - ω² a₂ is formed exactly (it cancels when the two are large), then divided once. - all(isfinite, (a0, a2, ω)) || throw( - ArgumentError("the reaction a₀ - ω² a₂ ($a0 - $ω^2 $a2) in cell $cell is not representable as ε = a₂ - a₀/ω²; the coefficients must be finite") + all(isfinite, (c.a0, c.a2, ω)) || throw( + ArgumentError("the reaction a₀ - ω² a₂ ($(c.a0) - $ω^2 $(c.a2)) in cell $cell is not representable as ε = a₂ - a₀/ω²; the coefficients must be finite") ) # Exact rational arithmetic of the Float64 inputs, so that the cancellation does not depend on any BigFloat precision. - net = Rational{BigInt}(a0) - Rational{BigInt}(ω)^2 * Rational{BigInt}(a2) + net = Rational{BigInt}(c.a0) - Rational{BigInt}(ω)^2 * Rational{BigInt}(c.a2) eps_r = Float64(-net / Rational{BigInt}(ω)^2) # Round trip: the reaction -ω² eps_r that assembly forms (with ω² rounded as it rounds it) must be the exact net # reaction to 1e-10, far above the few ulps that two roundings cost and far below the loss when ω² or eps_r is @@ -446,12 +651,13 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio roundtrip = isfinite(eps_r) && isfinite(reaction) && !iszero(ω2) && !issubnormal(ω2) && !issubnormal(eps_r) && !iszero(reaction) && !issubnormal(reaction) && abs(Rational{BigInt}(reaction) - net) <= 1.0e-10 * abs(net) isfinite(eps_r) && isfinite(reaction) && (iszero(net) || roundtrip) || throw( - ArgumentError("the reaction a₀ - ω² a₂ = $(Float64(net)) ($a0 - $ω^2 $a2) in cell $cell is not representable as ε = a₂ - a₀/ω² at this ω; use a frequency nearer 1 or a MaxwellModel directly") + ArgumentError("the reaction a₀ - ω² a₂ = $(Float64(net)) ($(c.a0) - $ω^2 $(c.a2)) in cell $cell is not representable as ε = a₂ - a₀/ω² at this ω; use a frequency nearer 1 or a MaxwellModel directly") ) - MaxwellMaterial(; eps_r, mu_r = 1 / nu, sigma = a1) + MaxwellMaterial(; eps_r, mu_r = 1 / c.nu, sigma = c.a1) end 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), ) # The scalar round trips cannot see underflow during integration and scaling: every entry of the assembled reaction # block that is nonzero must stay nonzero and normal after its coefficient is applied (entries that are exactly zero, @@ -469,6 +675,30 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio return (; model, omega = ω, load = _source_load(model, checked_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...) + # The numeric values given for the parameters of the PDESystem, before `_parameter_values` converts them to Float64: a # nonzero value that converts to zero or a subnormal number is outside the window, and one that converts to Inf or NaN # is not finite, so neither can reach the coefficients and sources as a silent zero. diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index a3deb04..329536e 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(ε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 [`MaxwellMaterial`](@ref)s; cells in no named set are vacuum, and a cell in two named sets is an error. @@ -66,11 +68,16 @@ 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(εc/μr) (n × Nᵢ)⋅(n × Nⱼ) dS` (`k0 = ω sqrt(μ0 ε0)`, material of the adjacent cell) and each +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`, -`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} @@ -85,19 +92,22 @@ 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)) + 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]]) cell_materials = _cell_materials(grid, materials) ip = _NEDELEC @@ -111,7 +121,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 = [ @@ -120,11 +131,27 @@ 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 +# 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))))")) @@ -171,8 +198,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) @@ -207,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) || diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl new file mode 100644 index 0000000..6222bee --- /dev/null +++ b/src/maxwell/ports.jl @@ -0,0 +1,337 @@ +# 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 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 +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. + +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 +way and supported, but without an individual incident or outgoing power; `S` is then not power conserving. +""" +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`), +`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} + 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 + +# 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(ω) * 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 +# ε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)) + # 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 + +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 _TET_FACET_NODES[local_facet]) + end + â, ê = _port_frame(port, normal) + ξ, η, ζ = [dot(x, â) for x in nodes], [dot(x, ê) for x in nodes], [dot(x, normal) for x in nodes] + (ξ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")) + 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)) + 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)) + # 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 _TET_FACET_EDGE_DOFS[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) + 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") + ) + 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")) + 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. +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 + +# 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 +# β 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. +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( + 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, ω) + +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)) + β = _port_betas(model, ω) + for (j, data) in pairs(model.ports) + B[:, j] .= (2im * β[j] * 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ᵢ`. At exactly a port's cutoff `βᵢ = 0`, `Zᵢ` is +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, ω) + # 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) + 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 0000000..e66bd6f --- /dev/null +++ b/src/maxwell/sweep.jl @@ -0,0 +1,63 @@ +# 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`: 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])`). +""" +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)) + 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 + isempty(omegas) && return MaxwellSweep(omegas, S, kept) + 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/frontend_ports.jl b/test/Maxwell/frontend_ports.jl new file mode 100644 index 0000000..732deeb --- /dev/null +++ b/test/Maxwell/frontend_ports.jl @@ -0,0 +1,317 @@ +# 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. +using FiniteElementMethod, Ferrite, ModelingToolkit, DomainSets, LinearAlgebra, Test +using SciMLBase: LinearProblem, discretize +using FiniteElementMethod: PDEBase + +@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 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]) +end + +@testset "absorbing end and a wave port: S11 equals the operator-level model" begin + 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 + +@testset "two-port dielectric guide: the sweep equals the operator-level sweep" begin + 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 + +@testset "equivalent forms of the absorbing condition" begin + 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 + +@testset "the absorbing condition is checked at SI scale too" begin + # ν = 1/μ0 and ε = ε0 make the coefficient of ∂ₜE about 1e-9 of that of curl E; the sign must still be checked. + mu0 = FiniteElementMethod.MU0 + eps0 = 1 / (mu0 * FiniteElementMethod.C0^2) + ω = 1.0e9 + grid = generate_grid(Tetrahedron, (2, 2, 2), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) + Ω = MeshDomain(grid) + Γ = boundarypiece(Ω, :top) + n, Eb = facet_normal(Γ), trace(Γ) + function si(sign) + bcs = cross(n, (1 / mu0) .* curl(Eb, X)) .~ sign * sqrt(eps0 / mu0) .* cross(n, cross(n, Dt.(Eb))) + return discretize(system(Ω, bcs; nu = 1 / mu0, a2 = eps0), edge_disc(Ω; omega = ω)) + end + @test si(-1) isa LinearProblem + @test occursin("are not n × (ν curl E) = -sqrt(ε/μ) n × (n × ∂ₜE) of the adjacent cell", message(() -> si(1))) +end + +@testset "a constraint added to the absorbing condition is seen at a large frequency" begin + Ω = MeshDomain(guide(10.0, 5.0)) + Γ = boundarypiece(Ω, :top) + Eb = trace(Γ) + 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)))) + 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 "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[]) + 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]), 1.0e16 * n[1] * Dt(Eb[3])) + prob = solve_with([vanishing ~ 0]) + @test prob.A == base.A && prob.b == base.b + end +end + +@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(Ω, [walls; bcs]), edge_disc(Ω)) + base = solve_with(bc) + 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, 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 + 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(Γ) + 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 + Ω = 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. + 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"])]) + # 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" + @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 diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl new file mode 100644 index 0000000..1332513 --- /dev/null +++ b/test/Maxwell/ports.jl @@ -0,0 +1,348 @@ +# 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 "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 "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) + ω = 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 + +@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))] + ) + @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 +# 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 + +@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 + +@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 + +@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(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 +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 + +@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(; mu_r = -1.0), MaxwellMaterial(; eps_r = -1.0, mu_r = -1.0), MaxwellMaterial(; eps_r = 2.0, mu_r = 1.5, sigma = 0.3)) + model = MaxwellModel(grid; materials = Dict("all" => material), pec = ["front", "back"], absorbing = ["top"], eps0 = 1.0, mu0 = 1.0) + @test maxwell_operator(model, -1.3).nzval ≈ conj.(maxwell_operator(model, 1.3).nzval) + end +end + +@testset "the absorbing operator is finite at ω = 0" begin + grid = generate_grid(Tetrahedron, (1, 1, 1)) + addcellset!(grid, "all", x -> true) + for material in (MaxwellMaterial(), MaxwellMaterial(; sigma = 0.5)) + m = MaxwellModel(grid; absorbing = ["top"], materials = Dict("all" => material), eps0 = 1.0, mu0 = 1.0) + @test all(isfinite, maxwell_operator(m, 0.0).nzval) + end +end + +@testset "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 "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 + +@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 + +@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