diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index e024f87..5dec635 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -69,6 +69,36 @@ or a non-positive `mu_r` at a port is rejected, because the power-wave normalisa 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. +## Perfectly matched layers + +A [`CartesianPML`](@ref) on the `pml` keyword turns the cells of named cell sets, outside an axis-aligned +inner box (by default the bounding box of the other cells), into the uniaxial absorber +`εr Λ`, `σ Λ`, `μr Λ` with `Λ = diag(s_y s_z/s_x, s_x s_z/s_y, s_x s_y/s_z)` and `s_j = 1 - iα_j`. On each face +of the box, `α` grows as `α_max (ξ/d)^order` with the depth `ξ` into a layer of thickness `d`, and +`α_max = -(order + 1) ln R / (2 k_ref d)` sets the normal-incidence round-trip reflection `R` of a PEC-backed +layer at the reference angular frequency `omega`. Name the outer faces of the layer in `pec`. +The layer must be filled with materials of positive real `eps_r` and positive `mu_r` (loss is allowed); a +negative-index filling is rejected, because the stretching would amplify its outgoing wave. + +The stretching is frequency-independent (the usual `s = 1 - iσ/ω` frozen at `ω = omega`), so the layer is a +fixed set of real blocks with polynomial coefficients in `ω`, like the rest of the operator, and a sweep still +only recombines them. The price is that the attenuation scales with the wavenumber: at `ω` the layer +reflects about `R^(k/k_ref)` (`R^(β/k_ref)` for a guided mode), which is stronger above the reference and +weaker below it. In practice the mesh reflection of the graded layer, not `R`, sets the floor: on the WR-90 +example below, `|S11|` stays between 0.002 and 0.004 from 8 to 12 GHz with the reference at 10 GHz, within +about 20 % of a layer re-tuned to each frequency, and falls with the cells across the layer (0.018, 0.009, 0.004 and +0.002 for 4, 6, 10 and 15 cells). A layer of only a few cells absorbs better with a milder `R` (`1e-3`). + +```julia +grid = generate_grid(Tetrahedron, (12, 6, 20), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 40.0)) +addcellset!(grid, "pml", x -> x[3] >= 19.99) # the last 20 mm absorb +model = MaxwellModel( + grid; pec = ["left", "right", "front", "back", "top"], ports = [WavePort("bottom"; a_direction = (1, 0, 0))], + pml = CartesianPML("pml"; omega = 2π * 10.0e9, R = 1.0e-6), length_scale = 1.0e-3, +) +abs(only(solve_sweep(model, [2π * 10.0e9]).S)) # |S11| ≈ 0.004, against 0.1396 for the first-order ABC +``` + ```@docs MaxwellModel MaxwellMaterial @@ -91,6 +121,7 @@ FiniteElementMethod.port_excitations FiniteElementMethod.s_parameters FiniteElementMethod.propagation_constant FiniteElementMethod.cutoff_frequency +CartesianPML FiniteElementMethod.EPS0 FiniteElementMethod.MU0 FiniteElementMethod.C0 @@ -105,7 +136,7 @@ derivatives of the discrete S-parameters, by the discrete adjoint: the system ma 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. +in fixed material, and not a PML cell, whose stretched blocks also depend on the material: either is an `ArgumentError`. ```julia grid = generate_grid(Tetrahedron, (12, 6, 15), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 30.0)) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 967f4a7..a5c0bbc 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -55,12 +55,14 @@ 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/pml.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 CartesianPML export MaxwellSensitivities, s_parameter_sensitivities, adjoint_gradient include("precompile.jl") diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index c8d7b8a..ba81a1e 100644 --- a/src/maxwell/adjoint.jl +++ b/src/maxwell/adjoint.jl @@ -58,6 +58,14 @@ function _parameter_terms(model, (kind, name)) name = String(name) _check_cellset(model.grid, name) cells = Ferrite.getcellset(model.grid, name) + for pml_set in model.pml_cellsets + isdisjoint(cells, Ferrite.getcellset(model.grid, pml_set)) || throw( + ArgumentError( + "the $(repr(kind)) parameter of cell set $(repr(name)) overlaps the PML cell set $(repr(pml_set)), whose stretched " * + "blocks depend on the material; sensitivities need the PML cells in fixed material" + ) + ) + end for data in model.ports, (cell, _) in Ferrite.getfacetset(model.grid, data.port.facetset) cell in cells && throw( ArgumentError( @@ -131,7 +139,8 @@ field of port `i` is the forward field `uᵢ` with port `i` driven, so 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. +rejected: the port's mode, excitation and normalisation depend on its material, and are taken as fixed. So is a cell set +that overlaps a PML cell set (the stretched blocks of the layer depend on the material). Terms added with [`FiniteElementMethod.add_term!`](@ref) are taken as independent of the parameters, and must have symmetric blocks (an `ArgumentError` otherwise). """ diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index d53890a..c5a3620 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -44,7 +44,7 @@ end """ MaxwellModel(grid; materials = Dict(), pec = String[], absorbing = String[], ports = WavePort[], - length_scale = 1.0, eps0 = EPS0, mu0 = MU0, quadrature = 2) + pml = nothing, 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 @@ -54,7 +54,8 @@ The time-harmonic electric-field model on a Ferrite `grid` of `Tetrahedron` cell with `n × E = 0` on the facet sets named in `pec` and the natural condition `n × (μr⁻¹ ∇ × E) = 0` on the rest of the boundary, except for the facet sets named in `absorbing`, which carry the first-order Silver-Müller absorbing condition `n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)` (the outgoing root: for a negative real `εc/μr`, `-i sign(ω) sign(μr) sqrt(|εc/μr|)`), and the -[`WavePort`](@ref)s in `ports`. +[`WavePort`](@ref)s in `ports`. `pml` is `nothing` or a [`CartesianPML`](@ref), whose cells become an anisotropic +absorbing layer. `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. @@ -93,11 +94,12 @@ struct MaxwellModel{G, DH, CH, CV} terms::Vector{MaxwellTerm} absorbing::Vector{String} ports::Vector{WavePortData} + pml_cellsets::Vector{String} end function MaxwellModel( 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 + ports = WavePort[], pml = nothing, 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))")) @@ -136,11 +138,16 @@ function MaxwellModel( MaxwellTerm(blocks.sigma, ω -> im * mu0 * L2 * ω), ] L = float(length_scale) + if pml !== nothing + boundary_sets = ("absorbing" => absorbing, "wave port" => [port.facetset for port in ports]) + append!(terms, _pml_terms(pml, dh, cv, blocks.curlcurl, cell_materials, mu0, eps0, L, boundary_sets)) + end 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), L, blocks, terms, absorbing, port_data + grid, dh, ch, cv, cell_materials, pec, float(eps0), float(mu0), L, blocks, terms, absorbing, port_data, + pml === nothing ? String[] : copy(pml.cellsets) ) end diff --git a/src/maxwell/pml.jl b/src/maxwell/pml.jl new file mode 100644 index 0000000..1c70414 --- /dev/null +++ b/src/maxwell/pml.jl @@ -0,0 +1,156 @@ +# Cartesian uniaxial perfectly matched layer (UPML) of a MaxwellModel, with the frequency-independent +# coordinate stretching s = 1 - iα(x), so that the layer is a fixed set of real blocks with polynomial +# coefficients in ω. + +""" + CartesianPML(cellsets; omega, R = 1e-6, order = 2, box = nothing) + +A Cartesian perfectly matched layer for the `pml` keyword of [`MaxwellModel`](@ref): the cells of the named +cell set(s) of the grid, outside an axis-aligned inner box, become the uniaxial anisotropic absorber +`εr → εr Λ`, `σ → σ Λ`, `μr → μr Λ` with + + Λ = diag(s_y s_z / s_x, s_x s_z / s_y, s_x s_y / s_z), s_j = 1 - i α_j(x_j) (exp(+iωt)), + +which is reflectionless at every angle of incidence on the continuum level and attenuates an outgoing wave of +wavenumber `k` by `exp(-k ∫ α dx)`. `Λ` is diagonal, so the operator stays complex symmetric. + +`box = (lo, hi)` gives the corners of the inner (physical) box in mesh units; by default it is the bounding +box of the cells not in the layer. Each of the six faces of the box has the layer thickness `d` from the box +to the bounding box of the layer cells (zero means no stretching across that face), and on it +`α = α_max (ξ/d)^order` at depth `ξ`, with `α_max = -(order + 1) ln R / (2 k_ref d)` and +`k_ref = omega sqrt(μ0 ε0)`: a plane wave of the reference angular frequency `omega` (rad/s) at normal +incidence in vacuum comes back from a PEC-backed layer with amplitude `R`. Edges and corners of the layer +multiply the stretchings of their faces. + +The stretching is frequency-independent (`α = σ/omega` frozen at the reference) and is conjugated for `ω < 0`, so +that the operator satisfies `A(-ω) = conj(A(ω))`; the attenuation scales with `k`: at `ω` the round trip is `R^(k/k_ref)` (in a waveguide `R^(β/k_ref)`). Name the outer faces of the +layer in `pec` to back it with a conductor. The layer must be filled with materials of positive real `eps_r` and positive +`mu_r` (loss is allowed): for a negative-index filling the stretching would amplify the outgoing wave, so it is an +`ArgumentError`. Wave ports and absorbing facet sets cannot touch layer cells. +""" +struct CartesianPML + cellsets::Vector{String} + omega::Float64 + R::Float64 + order::Float64 + box::Union{Nothing, NTuple{2, Ferrite.Vec{3, Float64}}} +end +function CartesianPML(cellsets; omega::Real, R::Real = 1.0e-6, order::Real = 2, box = nothing) + names = cellsets isa AbstractString ? [String(cellsets)] : String.(collect(cellsets)) + isempty(names) && throw(ArgumentError("CartesianPML needs at least one cell set")) + omega > 0 || throw(ArgumentError("the PML reference angular frequency must be positive, got $omega")) + 0 < R < 1 || throw(ArgumentError("the PML reflection R must be in (0, 1), got $R")) + order >= 0 || throw(ArgumentError("the PML grading order must be nonnegative, got $order")) + corners = box === nothing ? nothing : map(c -> Ferrite.Vec{3, Float64}(Tuple(c)), (box[1], box[2])) + corners === nothing || all(corners[1] .< corners[2]) || + throw(ArgumentError("the PML box needs lo < hi in every coordinate, got $box")) + return CartesianPML(names, float(omega), float(R), float(order), corners) +end + +function _bounding_box(grid, cells) + lo, hi = fill(Inf, 3), fill(-Inf, 3) + for cell in cells, x in Ferrite.getcoordinates(grid, cell) + lo .= min.(lo, x) + hi .= max.(hi, x) + end + return lo, hi +end + +_centroid(grid, cell) = sum(Ferrite.getcoordinates(grid, cell)) / 4 + +# The stretching α(x) of the layer, from the inner box (lo, hi), the face thicknesses and their α_max. +function _pml_profile(pml::CartesianPML, grid, in_pml, k_ref, L) + pml_cells = findall(in_pml) + isempty(pml_cells) && throw(ArgumentError("the PML cell sets $(pml.cellsets) are empty")) + outer_lo, outer_hi = _bounding_box(grid, pml_cells) + pml.box === nothing && all(in_pml) && throw(ArgumentError("every cell is in the PML; give its inner `box`")) + lo, hi = pml.box === nothing ? _bounding_box(grid, findall(!, in_pml)) : (collect(pml.box[1]), collect(pml.box[2])) + tol = 1.0e-9 * maximum(outer_hi .- outer_lo) + thickness(t) = t > tol ? t : 0.0 + d_lo, d_hi = thickness.(lo .- outer_lo), thickness.(outer_hi .- hi) + all(iszero, d_lo) && all(iszero, d_hi) && + throw(ArgumentError("the PML cells do not extend beyond the inner box $((lo, hi)); the layer has zero thickness")) + for cell in eachindex(in_pml) + x = _centroid(grid, cell) + outside = any((x .< lo .- tol) .| (x .> hi .+ tol)) + outside == in_pml[cell] || + throw(ArgumentError("cell $cell is $(outside ? "outside" : "inside") the inner PML box but $(outside ? "not " : "")in the PML cell sets")) + end + α_max(d) = d > 0 ? -(pml.order + 1) * log(pml.R) / (2 * k_ref * L * d) : 0.0 + a_lo, a_hi = α_max.(d_lo), α_max.(d_hi) + m = pml.order + return function (x) + return ntuple(3) do j + x[j] < lo[j] ? a_lo[j] * min((lo[j] - x[j]) / d_lo[j], 1.0)^m : + x[j] > hi[j] ? a_hi[j] * min((x[j] - hi[j]) / d_hi[j], 1.0)^m : 0.0 + end + end +end + +# The layer as additions to the isotropic blocks of its cells: (Λ⁻¹ - I)/μr in the curl-curl term and +# (Λ - I) εr, (Λ - I) σ in the mass terms, each split into real blocks for the real and imaginary parts. +function _pml_terms(pml::CartesianPML, dh, cv, pattern, cell_materials, mu0, eps0, L, boundary_sets) + grid = dh.grid + in_pml = falses(Ferrite.getncells(grid)) + for name in pml.cellsets + _check_cellset(grid, name) + in_pml[collect(Ferrite.getcellset(grid, name))] .= true + end + for (kind, names) in boundary_sets, name in names, facet in get(grid.facetsets, name, ()) + in_pml[facet[1]] && throw(ArgumentError("$kind facet set $(repr(name)) touches PML cells")) + end + for cell in findall(in_pml) + (; eps_r, mu_r) = cell_materials[cell] + real(eps_r) > 0 && mu_r > 0 || throw( + ArgumentError("PML cell $cell has eps_r = $eps_r and mu_r = $mu_r; a PML must be filled with materials of positive real permittivity and positive permeability (any loss is fine), because the stretching s = 1 - iα attenuates only the outgoing wave of an ordinary medium") + ) + end + α = _pml_profile(pml, grid, in_pml, pml.omega * sqrt(mu0 * eps0), L) + + names = (:curl_re, :curl_im, :eps_rr, :eps_ri, :eps_ir, :eps_ii, :sigma_re, :sigma_im) + mats = NamedTuple{names}(ntuple(_ -> copy(pattern), 8)) + assemblers = map(Ferrite.start_assemble, mats) + n = Ferrite.getnbasefunctions(cv) + kc, m = zeros(ComplexF64, n, n), zeros(ComplexF64, n, n) + for cc in Ferrite.CellIterator(dh, findall(in_pml)) + Ferrite.reinit!(cv, cc) + fill!(kc, 0) + fill!(m, 0) + x = Ferrite.getcoordinates(cc) + for q in 1:Ferrite.getnquadpoints(cv) + s = 1 .- im .* α(Ferrite.spatial_coordinate(cv, q, x)) + Λ = (s[2] * s[3] / s[1], s[1] * s[3] / s[2], s[1] * s[2] / s[3]) + dΩ = Ferrite.getdetJdV(cv, q) + for i in 1:n + Ni, Ci = Ferrite.shape_value(cv, q, i), Ferrite.shape_curl(cv, q, i) + for j in 1:n + Nj, Cj = Ferrite.shape_value(cv, q, j), Ferrite.shape_curl(cv, q, j) + kc[i, j] += sum(k -> (1 / Λ[k] - 1) * (Ci[k] * Cj[k]), 1:3) * dΩ + m[i, j] += sum(k -> (Λ[k] - 1) * (Ni[k] * Nj[k]), 1:3) * dΩ + end + end + end + (; eps_r, mu_r, sigma) = cell_materials[Ferrite.cellid(cc)] + dofs = Ferrite.celldofs(cc) + Ferrite.assemble!(assemblers.curl_re, dofs, real.(kc) ./ mu_r) + Ferrite.assemble!(assemblers.curl_im, dofs, imag.(kc) ./ mu_r) + # eps_r (m_re + i m_im) with eps_r = er + i ei: the material is not conjugated when the stretching is. + Ferrite.assemble!(assemblers.eps_rr, dofs, real(eps_r) .* real.(m)) + Ferrite.assemble!(assemblers.eps_ri, dofs, real(eps_r) .* imag.(m)) + Ferrite.assemble!(assemblers.eps_ir, dofs, imag(eps_r) .* real.(m)) + Ferrite.assemble!(assemblers.eps_ii, dofs, imag(eps_r) .* imag.(m)) + Ferrite.assemble!(assemblers.sigma_re, dofs, sigma .* real.(m)) + Ferrite.assemble!(assemblers.sigma_im, dofs, sigma .* imag.(m)) + end + k2, μL2 = mu0 * eps0 * L^2, mu0 * L^2 + # For ω < 0 the stretching m = m_re + i m_im is conjugated (its imaginary blocks change sign) and the supplied + # material is not, so that the layer still attenuates the outgoing wave and equivalent descriptions of loss agree: + # -k2 ω² (er + i ei)(m_re + i s m_im) = -k2 ω² (er m_re + i s er m_im + i ei m_re - s ei m_im). + sgn(ω) = ω < 0 ? -1.0 : 1.0 + coefficients = ( + Returns(1.0 + 0.0im), ω -> im * sgn(ω), ω -> complex(-k2 * ω^2), ω -> -im * k2 * ω^2 * sgn(ω), + ω -> -im * k2 * ω^2, ω -> complex(k2 * ω^2 * sgn(ω)), ω -> im * μL2 * ω, ω -> complex(-μL2 * ω * sgn(ω)), + ) + terms = [MaxwellTerm(block, c) for (block, c) in zip(mats, coefficients)] + return filter(term -> any(!iszero, nonzeros(term.block)), terms) +end diff --git a/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl index 9cdb448..9f7ef72 100644 --- a/test/Maxwell/adjoint.jl +++ b/test/Maxwell/adjoint.jl @@ -209,3 +209,25 @@ end @test isfinite(term.coefficient(0.0)) end end + +@testset "sensitivities reject a parameter region that overlaps the PML" begin + len = 2SLAB_LEAD + SLAB_D + n = ceil.(Int, (SLAB_A, SLAB_B, len) ./ 3.0) + 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, "pml", x -> x[3] >= 25.0 - 1.0e-9; all = true) + addcellset!(grid, "lossy", x -> x[3] >= 20.0 - 1.0e-9; all = true) # reaches into the PML + model = MaxwellModel( + grid; materials = Dict("lossy" => MaxwellMaterial(; sigma = 0.5)), pec = [SLAB_WALLS; "top"], + ports = [WavePort("bottom"; a_direction = (1, 0, 0))], pml = CartesianPML("pml"; omega = SLAB_F), length_scale = 1.0e-3, + ) + sweep = solve_sweep(model, [SLAB_F]; fields = true) + n_dofs = ndofs(model.dh) + for kind in (:sigma, :eps_r, :eps_r_imag, :mu_r) + @test_throws "overlaps the PML cell set" s_parameter_sensitivities(model, [SLAB_F], [(kind, "lossy")]) + @test_throws "overlaps the PML cell set" s_parameter_sensitivities(model, sweep, [(kind, "lossy")]) + @test_throws "overlaps the PML cell set" adjoint_gradient(model, SLAB_F, zeros(ComplexF64, n_dofs), zeros(n_dofs), [(kind, "lossy")]) + end + # A region that does not touch the layer still works. + @test size(s_parameter_sensitivities(model, [SLAB_F], [(:eps_r, "slab")]).dS) == (1, 1, 1, 1) +end diff --git a/test/Maxwell/pml.jl b/test/Maxwell/pml.jl new file mode 100644 index 0000000..a60fd2d --- /dev/null +++ b/test/Maxwell/pml.jl @@ -0,0 +1,152 @@ +# Cartesian UPML: a PEC-backed layer terminating a WR-90 guide, a conducting filling continued into the layer, +# a radiating source in a PML-truncated vacuum box against a larger domain, and input validation. +using FiniteElementMethod, Ferrite, SparseArrays, LinearAlgebra, Random, Test + +const PML_A, PML_B = 22.86, 10.16 # mm +const PML_F10 = 2π * 10.0e9 +const PML_WALLS = ["left", "right", "front", "back"] + +# A WR-90 guide of `len` mm with a wave port at z = 0, continued by a `d` mm PML backed by PEC at its end. +# Cells from `lossy_from` on form the cell set "lossy". +function wr90_pml(h, len, d; lossy_from = len, materials = Dict{String, MaxwellMaterial}(), kwargs...) + n = (ceil(Int, PML_A / h), ceil(Int, PML_B / h), round(Int, (len + d) / h)) + grid = generate_grid(Tetrahedron, n, Vec(0.0, 0.0, 0.0), Vec(PML_A, PML_B, len + d)) + addcellset!(grid, "pml", x -> x[3] >= len - 1.0e-9) + addcellset!(grid, "lossy", x -> x[3] >= lossy_from - 1.0e-9) + return MaxwellModel( + grid; materials, pec = [PML_WALLS; "top"], ports = [WavePort("bottom"; a_direction = (1, 0, 0))], + pml = CartesianPML("pml"; omega = PML_F10, kwargs...), length_scale = 1.0e-3, + ) +end + +@testset "PEC-backed PML terminating WR-90" begin + model = wr90_pml(2.0, 20.0, 20.0) + A = maxwell_operator(model, PML_F10) + @test issymmetric(A) && !ishermitian(A) + # The layer adds blocks for the real and imaginary parts of its curl and permittivity terms only. + @test length(model.terms) == 4 + 4 + 1 + sweep = solve_sweep(model, 2π .* [8.0e9, 10.0e9, 12.0e9]) + S11 = abs.(sweep.S[1, 1, :]) + @info "WR-90 terminated by a PML" S11 + @test all(<(0.01), S11) # the first-order ABC reflects 0.1396 at 10 GHz +end + +@testset "conducting filling continued into the PML" begin + # The guide is vacuum to z = 20 mm, then conducting through the PML: a matched lossy half-space, which + # reflects (β0 - β1)/(β0 + β1) at the interface. + σ = 0.2 + model = wr90_pml(2.0, 30.0, 20.0; lossy_from = 20.0, materials = Dict("lossy" => MaxwellMaterial(; sigma = σ))) + @test length(model.terms) == 4 + 6 + 1 + kc = π / (PML_A * 1.0e-3) + k0 = PML_F10 / FiniteElementMethod.C0 + β0 = sqrt(k0^2 - kc^2) + β1 = sqrt(complex(k0^2 * (1 - im * σ / (PML_F10 * FiniteElementMethod.EPS0)) - kc^2)) + β1 = imag(β1) > 0 ? -β1 : β1 + expected = (β0 - β1) / (β0 + β1) * exp(-2im * β0 * 20.0e-3) + S11 = only(solve_sweep(model, [PML_F10]).S) + @info "WR-90 conducting load in the PML" S11 expected abs(S11 - expected) + @test abs(S11 - expected) < 0.01 +end + +@testset "radiating source in a PML-truncated box" begin + # λ = 1 and a Gaussian current at the centre of the box [-a, a]³: the layer meets the radiated field at + # every angle, corners included. The reference is the same mesh with the layer twice as far out; the + # discretisation error itself (h = λ/10) is far larger and common to both. + k, w, a, d, h = 2π, 0.08, 0.4, 0.3, 0.1 + J(x) = [0.0, 0.0, exp(-sum(abs2, x) / w^2)] + faces = ["left", "right", "bottom", "top", "front", "back"] + function box_model(inner, ext; kwargs...) + n = round(Int, 2ext / h) + grid = generate_grid(Tetrahedron, (n, n, n), Vec(-ext, -ext, -ext), Vec(ext, ext, ext)) + # By centroid: a tetrahedron with every node on the box surface can still lie inside the box. + inner < ext && addcellset!(grid, "pml", Set(c for c in 1:getncells(grid) if maximum(abs.(sum(getcoordinates(grid, c)) / 4)) > inner)) + return MaxwellModel(grid; eps0 = 1.0, mu0 = 1.0, quadrature = 4, kwargs...) + end + pml_model(inner) = box_model(inner, inner + d; pec = faces, pml = CartesianPML("pml"; omega = k, R = 1.0e-3)) + Random.seed!(1) + points = [Vec(Tuple(r * normalize(randn(3)))) for r in range(0.2, 0.38; length = 200)] + field(model) = field_values(solve_driven(model, k, J), points).E + relative(E, ref) = sqrt(sum(e -> sum(abs2, e), E .- ref) / sum(e -> sum(abs2, e), ref)) + model = pml_model(a) + ref = field(pml_model(a + 0.2)) + errors = (pml = relative(field(model), ref), abc = relative(field(box_model(a, a; absorbing = faces)), ref)) + @info "radiating source in a box, against a larger domain" ndofs(model.dh) errors + @test issymmetric(maxwell_operator(model, k)) + @test errors.pml < 0.03 + @test errors.pml < errors.abc / 3 +end + +@testset "PML input validation" begin + @test_throws "positive" CartesianPML("pml"; omega = 0.0) + @test_throws "in (0, 1)" CartesianPML("pml"; omega = 1.0, R = 1.0) + @test_throws "nonnegative" CartesianPML("pml"; omega = 1.0, order = -1) + @test_throws "at least one" CartesianPML(String[]; omega = 1.0) + @test_throws "lo < hi" CartesianPML("pml"; omega = 1.0, box = ((0, 0, 0), (1, 0, 1))) + grid() = (g = generate_grid(Tetrahedron, (2, 2, 4)); addcellset!(g, "pml", x -> x[3] >= 0.5 - 1.0e-9); g) + @test_throws "no cell set" MaxwellModel(grid(); pml = CartesianPML("nope"; omega = 1.0)) + g = grid() + addcellset!(g, "none", Int[]) + @test_throws "are empty" MaxwellModel(g; pml = CartesianPML("none"; omega = 1.0)) + g = grid() + addcellset!(g, "all", x -> true) + @test_throws "every cell is in the PML" MaxwellModel(g; pml = CartesianPML("all"; omega = 1.0)) + # An explicit box: zero thickness when it holds every cell, and cells on the wrong side of it are errors. + @test_throws "zero thickness" MaxwellModel(g; pml = CartesianPML("all"; omega = 1.0, box = ((-1, -1, -1), (1, 1, 1)))) + @test_throws "inside the inner PML box but in" MaxwellModel( + grid(); pml = CartesianPML("pml"; omega = 1.0, box = ((-1, -1, -1), (1, 1, 0.8))) + ) + @test_throws "outside the inner PML box but not" MaxwellModel( + grid(); pml = CartesianPML("pml"; omega = 1.0, box = ((-1, -1, -1), (1, 1, -0.2))) + ) + @test_throws "absorbing facet set \"top\" touches PML cells" MaxwellModel( + grid(); absorbing = ["top"], pml = CartesianPML("pml"; omega = 1.0) + ) + @test_throws "wave port facet set \"top\" touches PML cells" MaxwellModel( + grid(); pec = ["left", "right", "front", "back"], ports = [WavePort("top"; a_direction = (1, 0, 0))], + pml = CartesianPML("pml"; omega = 1.0) + ) + # A box given explicitly equal to the inferred one builds the same operator. + inferred = MaxwellModel(grid(); pec = ["top"], pml = CartesianPML("pml"; omega = 2.0)) + explicit = MaxwellModel(grid(); pec = ["top"], pml = CartesianPML("pml"; omega = 2.0, box = ((-1, -1, -1), (1, 1, 0.5)))) + @test maxwell_operator(inferred, 2.0) == maxwell_operator(explicit, 2.0) +end + +@testset "the PML operator is conjugate symmetric in ω" begin + grid = generate_grid(Tetrahedron, (1, 1, 4), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 4.0)) + addcellset!(grid, "pml", x -> x[3] >= 3.0 - 1.0e-9) + model = MaxwellModel( + grid; pec = ["left", "right", "front", "back", "top"], pml = CartesianPML("pml"; omega = 2.0), eps0 = 1.0, mu0 = 1.0 + ) + A, Aneg = maxwell_operator(model, 2.0), maxwell_operator(model, -2.0) + @test norm(Aneg - conj(A)) / norm(A) < 1.0e-12 +end + +@testset "equivalent descriptions of dielectric loss give the same PML operator at both signs of ω" begin + grid = generate_grid(Tetrahedron, (1, 1, 4), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 4.0)) + addcellset!(grid, "pml", x -> x[3] >= 3.0 - 1.0e-9) + addcellset!(grid, "all", x -> true) + walls = ["left", "right", "front", "back", "top"] + operator(material, ω) = maxwell_operator( + MaxwellModel(grid; materials = Dict("all" => material), pec = walls, pml = CartesianPML("pml"; omega = 2.0, R = 1.0e-3), eps0 = 1.0, mu0 = 1.0), ω + ) + for ω in (2.0, -2.0) + # εc = eps_r - iσ/ω: a conductivity 0.6 is the permittivity 2 - 0.6i/ω at this frequency. + A = operator(MaxwellMaterial(; eps_r = 2 - 0.6im / ω, mu_r = 1.5), ω) + B = operator(MaxwellMaterial(; eps_r = 2.0, mu_r = 1.5, sigma = 0.6), ω) + @test norm(A - B) / norm(A) < 1.0e-12 + end +end + +@testset "a PML needs positive real permittivity and permeability" begin + grid = generate_grid(Tetrahedron, (1, 1, 4), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 4.0)) + addcellset!(grid, "pml", x -> x[3] >= 3.0 - 1.0e-9) + addcellset!(grid, "all", x -> true) + build(material) = MaxwellModel( + grid; materials = Dict("all" => material), pec = ["left", "right", "front", "back", "top"], + pml = CartesianPML("pml"; omega = 2.0), 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 positive permeability" build(MaxwellMaterial(; eps_r, mu_r)) + end + @test build(MaxwellMaterial(; eps_r = 2.0 - 0.3im, mu_r = 1.5, sigma = 0.2)) isa MaxwellModel +end