diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 01d2277d..e024f871 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, and a +facet cannot belong to two ports or to both a port and an `absorbing` set. + ```@docs MaxwellModel MaxwellMaterial @@ -42,7 +81,47 @@ 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 ``` + +## Material sensitivities + +[`s_parameter_sensitivities`](@ref) returns the derivatives of the wave-port S-parameters with respect to +material parameters of named cell sets: `:eps_r` (the real part of `εr`), `:eps_r_imag` (its imaginary +part), `:mu_r` and `:sigma`, each shifting that parameter on every cell of the set. They are the exact +derivatives of the discrete S-parameters, by the discrete adjoint: the system matrix is complex symmetric, +so the adjoint field of port `i` is the forward field with port `i` driven, and the sensitivities cost no +linear solve beyond the sweep, only one sparse product per parameter and frequency. A parameter set may +touch an absorbing boundary (its `sqrt(εc/μr)` is differentiated) but not a wave port, whose mode is taken +in fixed material. + +```julia +grid = generate_grid(Tetrahedron, (12, 6, 15), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 30.0)) +addcellset!(grid, "slab", x -> 10.0 - 1.0e-9 <= x[3] <= 20.0 + 1.0e-9; all = true) +ports = [WavePort(face; a_direction = (1, 0, 0), deembed = 10.0) for face in ("bottom", "top")] +model = MaxwellModel(grid; materials = Dict("slab" => MaxwellMaterial(; eps_r = 2.2)), + pec = ["left", "right", "front", "back"], ports, length_scale = 1.0e-3) +sens = s_parameter_sensitivities(model, [2π * 10.0e9], [(:eps_r, "slab"), (:sigma, "slab")]) +sens.dS[1, 1, 1, 1] # dS11/dεr at 10 GHz +``` + +For a real objective such as `|S11|²`, the gradient is `2 Re(conj(S11) dS11/dp)`. Other real functionals +`J(u)` of the field take one adjoint solve with [`adjoint_gradient`](@ref). + +```@docs +s_parameter_sensitivities +MaxwellSensitivities +adjoint_gradient +``` diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 390c330a..967f4a72 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: dot, mul!, norm +using LinearAlgebra: cross, dot, lu, lu!, mul!, norm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -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, dropzeros!, findnz, nnz, nonzeros, nzrange, rowvals, sparse using SymbolicUtils: SymbolicUtils using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap @@ -53,10 +53,15 @@ export MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative export Weighted # Frequency-domain Maxwell: a separate entry point assembled directly on Ferrite, not through the PDESystem front end. +include("maxwell/ports.jl") include("maxwell/model.jl") include("maxwell/driven.jl") +include("maxwell/sweep.jl") +include("maxwell/adjoint.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! export MaxwellSolution, driven_problem, solve_driven, field_values +export WavePort, MaxwellSweep, solve_sweep +export MaxwellSensitivities, s_parameter_sensitivities, adjoint_gradient include("precompile.jl") diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl new file mode 100644 index 00000000..c8d7b8ad --- /dev/null +++ b/src/maxwell/adjoint.jl @@ -0,0 +1,203 @@ +# Discrete adjoint sensitivities of a MaxwellModel with respect to the material parameters of named cell sets. +# A is complex symmetric (Aᵀ = A), so the adjoint of a wave port's output is the forward field with that port +# driven, and the S-parameter sensitivities need no solve beyond the forward sweep. + +const _PARAMETER_KINDS = (:eps_r, :eps_r_imag, :mu_r, :sigma) + +# The adjoint of a port is its forward field only for a symmetric A, but `add_term!` takes any block with the +# model's sparsity pattern. Only the free dofs count: the constrained rows and columns are replaced by the identity, +# so a large entry on a constrained dof must not hide the asymmetry of the operator that is solved. +function _check_symmetric(model) + free = setdiff(axes(model.blocks.curlcurl, 1), model.ch.prescribed_dofs) + for (k, term) in pairs(model.terms) + B = term.block[free, free] + norm(B - transpose(B), 1) <= 1.0e-12 * norm(B, 1) || + throw(ArgumentError("term $k of the model has a nonsymmetric block, so A is not symmetric and the adjoint needs transpose(A); the sensitivities support symmetric terms only")) + end + return nothing +end + +# ∫ w ∇×Nᵢ⋅∇×Nⱼ (curl = true) or ∫ w Nᵢ⋅Nⱼ over `cells`, with the real weight `w = weight(cell)`, with the +# zeros outside `cells` dropped. +function _region_block(model, cells, curl::Bool, weight) + block = copy(model.blocks.curlcurl) + asm = Ferrite.start_assemble(block) + cv = model.cellvalues + n = Ferrite.getnbasefunctions(cv) + Ke = zeros(n, n) + for cc in Ferrite.CellIterator(model.dh, collect(cells)) + Ferrite.reinit!(cv, cc) + fill!(Ke, 0.0) + for q in 1:Ferrite.getnquadpoints(cv) + dΩ = Ferrite.getdetJdV(cv, q) + for i in 1:n, j in 1:n + Ke[i, j] += dΩ * ( + curl ? dot(Ferrite.shape_curl(cv, q, i), Ferrite.shape_curl(cv, q, j)) : + dot(Ferrite.shape_value(cv, q, i), Ferrite.shape_value(cv, q, j)) + ) + end + end + Ferrite.assemble!(asm, Ferrite.celldofs(cc), weight(Ferrite.cellid(cc)) .* Ke) + end + return dropzeros!(block) +end + +# d sqrt(εc/μr) / dp for the material `m`, with εc = εr - iσ/(ωε0). +function _abc_admittance_derivative(kind, m, ω, eps0) + εc = m.eps_r - im * m.sigma / (ω * eps0) + y = _admittance(εc, m.mu_r, ω) + kind === :mu_r && return -y / (2 * m.mu_r) + dεc = kind === :eps_r ? 1.0 + 0.0im : kind === :eps_r_imag ? 1.0im : -im / (ω * eps0) + return y / (2εc) * dεc +end + +# dA/dp as MaxwellTerms, for p the parameter `kind` of every cell of the cell set `name` shifted together. +function _parameter_terms(model, (kind, name)) + kind in _PARAMETER_KINDS || + throw(ArgumentError("unknown material parameter $(repr(kind)); use one of $(_PARAMETER_KINDS)")) + name = String(name) + _check_cellset(model.grid, name) + cells = Ferrite.getcellset(model.grid, name) + for data in model.ports, (cell, _) in Ferrite.getfacetset(model.grid, data.port.facetset) + cell in cells && throw( + ArgumentError( + "cell set $(repr(name)) touches wave port $(repr(data.port.facetset)), whose mode depends on its material; " * + "sensitivities need the ports in fixed material" + ) + ) + end + (; mu0, eps0, length_scale) = model + L2 = length_scale^2 + k2 = mu0 * eps0 * L2 + terms = if kind === :mu_r + [MaxwellTerm(_region_block(model, cells, true, cell -> -1 / model.materials[cell].mu_r^2), Returns(1.0 + 0.0im))] + else + M = _region_block(model, cells, false, Returns(1.0)) + coefficient = kind === :eps_r ? (ω -> complex(-k2 * ω^2)) : kind === :eps_r_imag ? (ω -> -im * k2 * ω^2) : + (ω -> im * mu0 * L2 * ω) + [MaxwellTerm(M, coefficient)] + end + # The absorbing boundary on cells of the set: +i k0 L sqrt(εc/μr) ∮ (n × Nᵢ)⋅(n × Nⱼ) dS, per material. + abc_cells = [facet[1] for facetset in model.absorbing for facet in Ferrite.getfacetset(model.grid, facetset) if facet[1] in cells] + for m in unique(model.materials[abc_cells]) + block = _tangential_mass( + model.dh, model.blocks.curlcurl, model.absorbing, cell -> Float64(cell in cells && model.materials[cell] == m) + ) + push!( + terms, MaxwellTerm( + dropzeros!(block), + # 0 at ω = 0, as the forward absorbing coefficient is, where εc = εr - iσ/(ωε0) is 0/0 for σ = 0. + ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * length_scale * _abc_admittance_derivative(kind, m, ω, eps0) + ) + ) + end + return terms +end + +# Σₜ cₜ(ω) Bₜ U for the terms of one dA/dp. +_derivative_times(terms, ω, U) = sum(term.coefficient(ω) .* (term.block * U) for term in terms) + +""" + MaxwellSensitivities + +The result of [`s_parameter_sensitivities`](@ref): `omegas`, the scattering matrices `S[:, :, k]` as in +[`MaxwellSweep`](@ref), `params` and `dS[i, j, k, l]`, the derivative of `S[i, j, k]` with respect to the real +parameter `params[l]`. +""" +struct MaxwellSensitivities + omegas::Vector{Float64} + S::Array{ComplexF64, 3} + params::Vector{Tuple{Symbol, String}} + dS::Array{ComplexF64, 4} +end + +_normalise_params(params) = Tuple{Symbol, String}[(Symbol(kind), String(name)) for (kind, name) in params] + +""" + s_parameter_sensitivities(model::MaxwellModel, omegas, params; solver = umfpack_solver) + s_parameter_sensitivities(model::MaxwellModel, sweep::MaxwellSweep, params) + +The wave-port scattering matrices of `model` at the angular frequencies `omegas` and their derivatives with +respect to the material parameters `params`, as [`MaxwellSensitivities`](@ref). Each parameter is a pair +`(kind, cellset)`: `kind` is `:eps_r` (the real part of `εr`), `:eps_r_imag` (its imaginary part, `-ε''`), +`:mu_r` or `:sigma`, and the derivative is with respect to that parameter of every cell of the named cell set +shifted by the same amount (the set need not be one of the `materials` keys). The second method reuses the +fields of a sweep run with `fields = true`. + +These are the exact derivatives of the discrete S-parameters. Since `A(ω)` is complex symmetric, the adjoint +field of port `i` is the forward field `uᵢ` with port `i` driven, so + + dSᵢⱼ/dp = -uᵢᵀ (dA/dp) uⱼ / (2iβᵢ L Pᵢ / μr,ᵢ) ⋅ (power-wave and de-embedding factors of Sᵢⱼ), + +at no linear solve beyond [`solve_sweep`](@ref). `dA/dp` is assembled once per parameter over the cells of its +set, including the absorbing boundary's `sqrt(εc/μr)` on those cells. A cell set adjacent to a wave port is +rejected: the port's mode, excitation and normalisation depend on its material, and are taken as fixed. +Terms added with [`FiniteElementMethod.add_term!`](@ref) are taken as independent of the parameters, and must have +symmetric blocks (an `ArgumentError` otherwise). +""" +function s_parameter_sensitivities(model::MaxwellModel, omegas, params; solver = umfpack_solver) + params = _normalise_params(params) + _check_symmetric(model) + terms = [_parameter_terms(model, param) for param in params] # validate before solving + return _s_parameter_sensitivities(model, solve_sweep(model, omegas; fields = true, solver), params, terms) +end + +function s_parameter_sensitivities(model::MaxwellModel, sweep::MaxwellSweep, params) + sweep.fields === nothing && + throw(ArgumentError("the sweep has no fields; run solve_sweep with fields = true")) + all(U -> size(U) == (Ferrite.ndofs(model.dh), length(model.ports)), sweep.fields) || + throw(ArgumentError("the sweep's fields do not match the dofs and ports of the model")) + params = _normalise_params(params) + _check_symmetric(model) + terms = [_parameter_terms(model, param) for param in params] + return _s_parameter_sensitivities(model, sweep, params, terms) +end + +function _s_parameter_sensitivities(model, sweep, params, terms) + (; omegas, S, fields) = sweep + ports = model.ports + np = length(ports) + mu0eps0, L = model.mu0 * model.eps0, model.length_scale + dS = zeros(ComplexF64, np, np, length(omegas), length(terms)) + for (k, ω) in pairs(omegas) + U = fields[k] + β = [_propagation_constant(data, mu0eps0, ω) for data in ports] + w = [sqrt(data.norm * β[i] / data.mu_r) for (i, data) in pairs(ports)] + shift = [exp(im * β[i] * data.port.deembed * L) for (i, data) in pairs(ports)] + # Aλᵢ = pᵢ gives λᵢ = uᵢ / cᵢ, with cᵢ = 2iβᵢL/μr,ᵢ the excitation scale of port_excitations. + c = [2im * β[i] * L / data.mu_r for (i, data) in pairs(ports)] + for (l, param_terms) in pairs(terms) + G = transpose(U) * _derivative_times(param_terms, ω, U) + for j in 1:np, i in 1:np + dS[i, j, k, l] = -G[i, j] / (c[i] * ports[i].norm) * w[i] / w[j] * shift[i] * shift[j] + end + end + end + return MaxwellSensitivities(omegas, S, params, dS) +end + +""" + adjoint_gradient(model::MaxwellModel, ω, u, dJ_du, params; solver = umfpack_solver, cache = nothing) + +The gradient of a real functional `J(u)` of the field `u` (edge dofs solving `A(ω) u = b`, with `b` +independent of the parameters, as for [`driven_problem`](@ref) or [`port_excitations`](@ref) away from the +parameter sets) with respect to the material parameters `params` (as for +[`s_parameter_sensitivities`](@ref)), as a vector of real numbers. `dJ_du` is the complex gradient +`∂J/∂Re(u) + i ∂J/∂Im(u)`. One adjoint solve `A λ = conj(dJ_du)` (the transpose of `A` is `A`) gives + + dJ/dp = -Re(λᵀ (dA/dp) u). + +The solve is `solver(A, B, cache)` on the constrained `A(ω)`; to reuse an existing factorisation `F` of it, pass +`solver = (A, B, F) -> (F \\ B, F)` and `cache = F`. +""" +function adjoint_gradient(model::MaxwellModel, ω::Real, u::AbstractVector, dJ_du::AbstractVector, params; solver = umfpack_solver, cache = nothing) + _check_symmetric(model) + terms = [_parameter_terms(model, param) for param in _normalise_params(params)] + ω = float(ω) + A = maxwell_operator(model, ω) + Ferrite.apply!(A, model.ch) + rhs = conj.(ComplexF64.(dJ_du)) + rhs[model.ch.prescribed_dofs] .= 0 + λ, _ = solver(A, reshape(rhs, :, 1), cache) + return Float64[-real(dot(conj(vec(λ)), _derivative_times(param_terms, ω, u))) for param_terms in terms] +end diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index d7fcd1fa..d53890ae 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. @@ -65,11 +67,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} @@ -84,18 +91,26 @@ 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))))")) + absorbing = String.(collect(absorbing)) + ports = collect(ports) + foreach(name -> _check_facetset(grid, name), pec) + foreach(name -> _check_facetset(grid, name), absorbing) + # Each boundary condition assembles its own term, so a facet in two of them would get both. + conditions = [[("absorbing", name) for name in absorbing]; [("wave port", port.facetset) for port in ports]] + for (i, (kind_i, name_i)) in pairs(conditions), (kind_j, name_j) in conditions[(i + 1):end] + isdisjoint(Ferrite.getfacetset(grid, name_i), Ferrite.getfacetset(grid, name_j)) || + throw(ArgumentError("facet sets $(repr(name_i)) ($kind_i) and $(repr(name_j)) ($kind_j) share facets: a facet can carry only one absorbing or wave port condition")) end cell_materials = _cell_materials(grid, materials) @@ -110,7 +125,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 = [ @@ -119,8 +135,12 @@ function MaxwellModel( MaxwellTerm(blocks.eps_imag, ω -> -im * k2 * ω^2), MaxwellTerm(blocks.sigma, ω -> im * mu0 * L2 * ω), ] + L = float(length_scale) + isempty(absorbing) || append!(terms, _absorbing_terms(dh, blocks.curlcurl, absorbing, cell_materials, mu0, eps0, L)) + port_data = WavePortData[_wave_port(port, dh, blocks.curlcurl, cell_materials, L, ch.prescribed_dofs) for port in ports] + append!(terms, [_port_term(data, mu0 * eps0, L) for data in port_data]) return MaxwellModel( - grid, dh, ch, cv, cell_materials, pec, float(eps0), float(mu0), float(length_scale), blocks, terms + grid, dh, ch, cv, cell_materials, pec, float(eps0), float(mu0), L, blocks, terms, absorbing, port_data ) end @@ -163,8 +183,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) @@ -199,7 +233,8 @@ _same_pattern(A, B) = A.colptr == B.colptr && rowvals(A) == rowvals(B) add_term!(model::MaxwellModel, block, coefficient) Append the term `coefficient(ω) * block` to the system matrix of `model`. `block` must have the sparsity -pattern of `model.blocks`, as every matrix from `Ferrite.allocate_matrix(model.dh)` does. +pattern of `model.blocks`, which a wave port widens beyond that of `Ferrite.allocate_matrix(model.dh)`: make it as a copy +of `model.blocks.curlcurl` with its values zeroed, or with `tangential_mass` for a boundary term. """ function add_term!(model::MaxwellModel, block::SparseMatrixCSC{Float64, Int}, coefficient) _same_pattern(block, model.blocks.curlcurl) || diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl new file mode 100644 index 00000000..6222bee4 --- /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 00000000..eb526ca3 --- /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). An empty `omegas` gives an empty sweep. +""" +function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = umfpack_solver) + isempty(model.ports) && throw(ArgumentError("the model has no wave ports")) + omegas = float.(collect(omegas)) + 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, copy(U)) + end + return MaxwellSweep(omegas, S, kept) +end diff --git a/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl new file mode 100644 index 00000000..9cdb4487 --- /dev/null +++ b/test/Maxwell/adjoint.jl @@ -0,0 +1,211 @@ +# Discrete adjoint material sensitivities of the WR-90 dielectric slab: against central finite differences of +# the forward sweep (both discrete, so they agree to many digits) and against the closed-form slab. +using FiniteElementMethod, Ferrite, LinearAlgebra, SparseArrays, Test + +const SLAB_A, SLAB_B = 22.86, 10.16 # mm +const SLAB_LEAD, SLAB_D = 10.0, 10.0 # mm of vacuum guide on each side of the slab, and the slab +const SLAB_F = 2π * 10.0e9 +const SLAB_WALLS = ["left", "right", "front", "back"] + +# The slab fills the cross-section over SLAB_LEAD <= z <= SLAB_LEAD + SLAB_D; ports at both ends, de-embedded to +# the slab faces. With `abc = true` the guide ends in an absorbing boundary just behind the slab instead. +function slab_grid(h; abc = false) + len = abc ? SLAB_LEAD + SLAB_D : 2SLAB_LEAD + SLAB_D + n = ceil.(Int, (SLAB_A, SLAB_B, len) ./ h) + grid = generate_grid(Tetrahedron, Tuple(n), Vec(0.0, 0.0, 0.0), Vec(SLAB_A, SLAB_B, len)) + addcellset!(grid, "slab", x -> SLAB_LEAD - 1.0e-9 <= x[3] <= SLAB_LEAD + SLAB_D + 1.0e-9; all = true) + addcellset!(grid, "lead", x -> x[3] <= SLAB_LEAD + 1.0e-9; all = true) + return grid +end + +function slab_model(grid, material; abc = false) + ports = [WavePort("bottom"; a_direction = (1, 0, 0), deembed = SLAB_LEAD)] + abc || push!(ports, WavePort("top"; a_direction = (1, 0, 0), deembed = SLAB_LEAD)) + return MaxwellModel( + grid; materials = Dict("slab" => material), pec = SLAB_WALLS, absorbing = abc ? ["top"] : String[], ports, + length_scale = 1.0e-3, + ) +end + +function shifted(m::MaxwellMaterial, kind, δ) + kind === :eps_r && return MaxwellMaterial(m.eps_r + δ, m.mu_r, m.sigma) + kind === :eps_r_imag && return MaxwellMaterial(m.eps_r + im * δ, m.mu_r, m.sigma) + kind === :mu_r && return MaxwellMaterial(m.eps_r, m.mu_r + δ, m.sigma) + return MaxwellMaterial(m.eps_r, m.mu_r, m.sigma + δ) +end + +# Central differences of S with respect to the slab's `kind`, step δ. +function fd_dS(grid, material, kind, ωs, δ; abc = false) + S(δ) = solve_sweep(slab_model(grid, shifted(material, kind, δ); abc), ωs).S + return (S(δ) - S(-δ)) / 2δ +end + +relerr(a, b) = norm(a - b) / norm(b) + +# Closed form for a lossless slab εr in an otherwise empty guide, referenced to the slab faces. +function slab_closed_form(εr; ω = SLAB_F) + k0, kc = ω / FiniteElementMethod.C0, π / (SLAB_A * 1.0e-3) + β, β2 = sqrt(k0^2 - kc^2), sqrt(εr * k0^2 - kc^2) + Γ, P = (β - β2) / (β + β2), exp(-im * β2 * SLAB_D * 1.0e-3) + return (S11 = Γ * (1 - P^2) / (1 - Γ^2 * P^2), S21 = P * (1 - Γ^2) / (1 - Γ^2 * P^2)) +end + +const SLAB_KINDS = (:eps_r, :eps_r_imag, :mu_r, :sigma) +const SLAB_STEPS = Dict(:eps_r => 1.0e-4, :eps_r_imag => 1.0e-4, :mu_r => 1.0e-4, :sigma => 1.0e-5) + +@testset "closed-form slab" begin + cf = slab_closed_form(2.2) + @test cf.S11 ≈ -0.07985 + 0.18593im atol = 1.0e-4 + @test cf.S21 ≈ -0.89984 - 0.38644im atol = 1.0e-4 + δ = 1.0e-6 + dcf = (slab_closed_form(2.2 + δ).S11 - slab_closed_form(2.2 - δ).S11) / 2δ + grid = slab_grid(2.0) + sens = s_parameter_sensitivities(slab_model(grid, MaxwellMaterial(; eps_r = 2.2)), [SLAB_F], [(:eps_r, "slab")]) + S11, dS11 = sens.S[1, 1, 1], sens.dS[1, 1, 1, 1] + @info "slab against the closed form" S11 cf.S11 dS11 dcf + @test abs(S11 - cf.S11) < 0.01 + @test abs(dS11 - dcf) < 0.05 * abs(dcf) +end + +@testset "adjoint against finite differences: $label" for (label, material) in ( + ("lossless slab", MaxwellMaterial(; eps_r = 2.2)), + ("lossy slab", MaxwellMaterial(; eps_r = 2.2 - 0.05im, mu_r = 1.3, sigma = 0.1)), + ) + grid = slab_grid(2.0) + ωs = 2π .* [9.0e9, 11.0e9] + params = [(kind, "slab") for kind in SLAB_KINDS] + sens = s_parameter_sensitivities(slab_model(grid, material), ωs, params) + @test size(sens.dS) == (2, 2, 2, 4) && sens.params == params + for (l, kind) in pairs(SLAB_KINDS) + fd = fd_dS(grid, material, kind, ωs, SLAB_STEPS[kind]) + err = relerr(sens.dS[:, :, :, l], fd) + @info "dS/d$kind, $label" sens.dS[:, :, 1, l] err + @test err < 1.0e-6 + @test sens.dS[1, 2, :, l] ≈ sens.dS[2, 1, :, l] rtol = 1.0e-8 # reciprocity + end + # The derivative with respect to the imaginary part of εr is i times that of its real part (S is holomorphic in εr). + @test sens.dS[:, :, :, 2] ≈ im .* sens.dS[:, :, :, 1] rtol = 1.0e-10 + # Lossless: dS is then also constrained by unitarity, S'ᴴS + SᴴS' = 0 for real-εr perturbations. + if iszero(material.sigma) + for k in 1:2 + S, dS = sens.S[:, :, k], sens.dS[:, :, k, 1] + @test norm(dS' * S + S' * dS) < 1.0e-3 * norm(dS) + end + end +end + +@testset "absorbing boundary on the parameter set" begin + grid = slab_grid(2.0; abc = true) + material = MaxwellMaterial(; eps_r = 2.2 - 0.05im, mu_r = 1.3, sigma = 0.1) + params = [(kind, "slab") for kind in SLAB_KINDS] + sens = s_parameter_sensitivities(slab_model(grid, material; abc = true), [SLAB_F], params) + for (l, kind) in pairs(SLAB_KINDS) + fd = fd_dS(grid, material, kind, [SLAB_F], SLAB_STEPS[kind]; abc = true) + err = relerr(sens.dS[:, :, :, l], fd) + @info "dS11/d$kind with the ABC on the slab" only(sens.dS[:, :, :, l]) err + @test err < 1.0e-6 + end +end + +@testset "adjoint gradient of a field functional" begin + grid = slab_grid(2.0) + material = MaxwellMaterial(; eps_r = 2.2 - 0.05im, mu_r = 1.3, sigma = 0.1) + params = [(kind, "slab") for kind in SLAB_KINDS] + # J = Σ|u|² over the field with port 1 driven: dJ/du = ∂J/∂Re u + i ∂J/∂Im u = 2u. + J(model) = sum(abs2, solve_sweep(model, [SLAB_F]; fields = true).fields[1][:, 1]) + model = slab_model(grid, material) + u = solve_sweep(model, [SLAB_F]; fields = true).fields[1][:, 1] + grad = adjoint_gradient(model, SLAB_F, u, 2 .* u, params) + for (l, kind) in pairs(SLAB_KINDS) + δ = SLAB_STEPS[kind] + fd = (J(slab_model(grid, shifted(material, kind, δ))) - J(slab_model(grid, shifted(material, kind, -δ)))) / 2δ + @info "dJ/d$kind" grad[l] fd + @test grad[l] ≈ fd rtol = 1.0e-6 + end + # The same through a supplied factorisation of the constrained operator. + A = maxwell_operator(model, SLAB_F) + apply!(A, model.ch) + F = lu(A) + @test adjoint_gradient(model, SLAB_F, u, 2 .* u, params; solver = (A, B, F) -> (F \ B, F), cache = F) ≈ grad +end + +@testset "sensitivity inputs" begin + grid = slab_grid(3.0) + model = slab_model(grid, MaxwellMaterial(; eps_r = 2.2)) + @test_throws "no cell set" s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "nope")]) + @test_throws "unknown material parameter" s_parameter_sensitivities(model, [SLAB_F], [(:epsilon, "slab")]) + @test_throws "touches wave port" s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "lead")]) + sweep = solve_sweep(model, [SLAB_F]) + @test_throws "no fields" s_parameter_sensitivities(model, sweep, [(:eps_r, "slab")]) + @test_throws "do not match" s_parameter_sensitivities( + model, MaxwellSweep(sweep.omegas, sweep.S, [zeros(ComplexF64, 3, 2)]), [(:eps_r, "slab")] + ) + @test size(s_parameter_sensitivities(model, [SLAB_F], []).dS) == (2, 2, 1, 0) + @test adjoint_gradient(model, SLAB_F, zeros(ComplexF64, ndofs(model.dh)), zeros(ndofs(model.dh)), []) == Float64[] + # A sweep with fields gives the same as solving inside; a set with no free dofs has zero sensitivity. + sweep = solve_sweep(model, [SLAB_F]; fields = true) + @test s_parameter_sensitivities(model, sweep, [("eps_r", "slab")]).dS ≈ + s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "slab")]).dS + addcellset!(grid, "empty", Int[]) + @test iszero(s_parameter_sensitivities(model, sweep, [(:sigma, "empty")]).dS) +end + +@testset "sensitivities reject a model with a nonsymmetric term" begin + model = slab_model(slab_grid(3.0), MaxwellMaterial(; eps_r = 2.2)) + extra = copy(model.blocks.sigma) + nonzeros(extra) .= rand(nnz(extra)) + FiniteElementMethod.add_term!(model, extra, ω -> 1.0) + # A tiny block with a huge coefficient is as nonsymmetric as a large one. + tiny = copy(model.blocks.sigma) + nonzeros(tiny) .= 0 + rows, cols = findnz(tiny) + scaled = slab_model(slab_grid(3.0), MaxwellMaterial(; eps_r = 2.2)) + i = findfirst(k -> rows[k] != cols[k] && rows[k] ∉ scaled.ch.prescribed_dofs && cols[k] ∉ scaled.ch.prescribed_dofs, eachindex(rows)) + nonzeros(tiny)[i] = 1.0e-13 + FiniteElementMethod.add_term!(scaled, tiny, ω -> 1.0e13) + @test_throws "nonsymmetric" s_parameter_sensitivities(scaled, [SLAB_F], [(:eps_r, "slab")]) + u = zeros(ComplexF64, ndofs(model.dh)) + @test_throws "nonsymmetric" s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "slab")]) + @test_throws "nonsymmetric" adjoint_gradient(model, SLAB_F, u, zeros(ndofs(model.dh)), [(:eps_r, "slab")]) + @test_throws "nonsymmetric" s_parameter_sensitivities( + model, MaxwellSweep([SLAB_F], zeros(ComplexF64, 2, 2, 1), [zeros(ComplexF64, ndofs(model.dh), 2)]), [(:eps_r, "slab")] + ) +end + +@testset "the symmetry check ignores constrained dofs" begin + grid = generate_grid(Tetrahedron, (4, 2, 6), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 3.0)) + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("top"; a_direction = (1, 0, 0))] + addcellset!(grid, "core", x -> 1.0 - 1.0e-9 <= x[3] <= 2.0 + 1.0e-9; all = true) + model = MaxwellModel(grid; pec = SLAB_WALLS, ports, eps0 = 1.0, mu0 = 1.0) + ω = 2.5 + # A nonsymmetric block on the free dofs, padded with a huge symmetric entry on a PEC dof. + padded = copy(model.blocks.eps_real) + rows = rowvals(padded) + for j in axes(padded, 2), k in nzrange(padded, j) + nonzeros(padded)[k] *= 1 + 0.7 * sin(rows[k]) + end + pec_dof = first(model.ch.prescribed_dofs) + padded[pec_dof, pec_dof] = 1.0e16 + FiniteElementMethod.add_term!(model, padded, _ -> 3.0) + u = zeros(ComplexF64, ndofs(model.dh)) + @test_throws "nonsymmetric" s_parameter_sensitivities(model, [ω], [(:eps_r, "core")]) + @test_throws "nonsymmetric" s_parameter_sensitivities( + model, MaxwellSweep([ω], zeros(ComplexF64, 2, 2, 1), [zeros(ComplexF64, ndofs(model.dh), 2)]), [(:eps_r, "core")] + ) + @test_throws "nonsymmetric" adjoint_gradient(model, ω, u, zeros(ndofs(model.dh)), [(:eps_r, "core")]) +end + +@testset "the absorbing boundary's derivative is finite at ω = 0" begin + grid = slab_grid(3.0; abc = true) + model = slab_model(grid, MaxwellMaterial(; eps_r = 2.2); abc = true) + n = ndofs(model.dh) + # The static operator is singular, so the adjoint solve is stubbed: only dA/dp u is under test. + stub(A, B, cache) = (zeros(ComplexF64, size(B)), cache) + for kind in SLAB_KINDS + g = adjoint_gradient(model, 0.0, ones(ComplexF64, n), ones(n), [(kind, "slab")]; solver = stub) + @test all(isfinite, g) + end + for kind in SLAB_KINDS, term in FiniteElementMethod._parameter_terms(model, (kind, "slab")) + @test isfinite(term.coefficient(0.0)) + end +end diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl new file mode 100644 index 00000000..c48179f9 --- /dev/null +++ b/test/Maxwell/ports.jl @@ -0,0 +1,381 @@ +# 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 "sweep keeps an independent field per frequency, even from a solver that reuses its output" begin + model = wr90(5.0, 10.0) + ωs = F10 .* [0.9, 1.1] + reused = Matrix{ComplexF64}(undef, 0, 0) + function one_buffer_solver(A, B, cache) + U, cache = FiniteElementMethod.umfpack_solver(A, B, cache) + size(reused) == size(U) || (reused = similar(U)) + copyto!(reused, U) + return reused, cache + end + sweep = solve_sweep(model, ωs; fields = true, solver = one_buffer_solver) + fresh = [solve_sweep(model, [ω]; fields = true).fields[1] for ω in ωs] + @test sweep.fields[1] !== sweep.fields[2] + @test sweep.fields[1] ≈ fresh[1] && sweep.fields[2] ≈ fresh[2] +end + +@testset "an empty frequency vector gives an empty sweep" begin + sweep = solve_sweep(wr90(5.0, 10.0), Float64[]; fields = true) + @test isempty(sweep.omegas) && size(sweep.S) == (2, 2, 0) && isempty(sweep.fields) +end + +@testset "the absorbing operator is finite at ω = 0" begin + grid = generate_grid(Tetrahedron, (1, 1, 1)) + addcellset!(grid, "all", x -> true) + for material in (MaxwellMaterial(), MaxwellMaterial(; sigma = 0.5)) + m = MaxwellModel(grid; absorbing = ["top"], materials = Dict("all" => material), eps0 = 1.0, mu0 = 1.0) + @test all(isfinite, maxwell_operator(m, 0.0).nzval) + end +end + +@testset "lossy port materials are rejected" begin + grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + addcellset!(grid, "lossy", x -> x[3] >= 0.0) + walls = ["left", "right", "front", "back"] + @test_throws "lossy" MaxwellModel( + grid; pec = walls, eps0 = 1.0, mu0 = 1.0, materials = Dict("lossy" => MaxwellMaterial(; eps_r = 1 - 2im)), + ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + ) +end + +@testset "a facet cannot carry two absorbing or wave port conditions" begin + grid = generate_grid(Tetrahedron, (2, 1, 2), Vec(0.0, 0.0, 0.0), Vec(2.0, 1.0, 2.0)) + addfacetset!(grid, "bottom_alias", x -> x[3] ≈ 0.0) + walls = ["left", "right", "front", "back"] + for name in ("bottom", "bottom_alias") + @test_throws "share facets" MaxwellModel( + grid; pec = walls, eps0 = 1.0, mu0 = 1.0, absorbing = [name], + ports = [WavePort("bottom"; a_direction = (1, 0, 0))] + ) + end + @test_throws "share facets" MaxwellModel( + grid; pec = walls, eps0 = 1.0, mu0 = 1.0, + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("bottom_alias"; a_direction = (1, 0, 0))] + ) +end + +@testset "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 "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 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