From 902b087fd1e0b743eb498410b1a8cb8d4ec02a5d Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 22:57:58 +0000 Subject: [PATCH 1/6] Add a Cartesian UPML to the Maxwell model CartesianPML turns named cell sets outside an axis-aligned box into the uniaxial absorber Lambda = diag(sy sz/sx, sx sz/sy, sx sy/sz) with frequency-independent stretching s = 1 - i alpha, graded as (xi/d)^m with alpha_max from a target reflection R at a reference frequency. Frozen stretching keeps every term a real block with a polynomial coefficient in omega, so sweeps still only recombine values; on WR-90 it reflects 0.002-0.004 over 8-12 GHz, within about 20% of a layer re-tuned per frequency. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/maxwell.md | 29 ++++++++ src/FiniteElementMethod.jl | 2 + src/maxwell/model.jl | 11 ++- src/maxwell/pml.jl | 146 +++++++++++++++++++++++++++++++++++++ test/Maxwell/pml.jl | 112 ++++++++++++++++++++++++++++ 5 files changed, 297 insertions(+), 3 deletions(-) create mode 100644 src/maxwell/pml.jl create mode 100644 test/Maxwell/pml.jl diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index d8a26f53..a7f38c5e 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -55,6 +55,34 @@ sweep.S[2, 1, 5] # S21 at 10 GHz: |S21| ≈ 1, angle ≈ -93.3° are normalised to power waves through the TE10 wave impedance `ωμ0μr/β`. Below cutoff the propagation constant is `β = -iα`, the evanescent branch. +## 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 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 @@ -77,6 +105,7 @@ FiniteElementMethod.port_excitations FiniteElementMethod.s_parameters FiniteElementMethod.propagation_constant FiniteElementMethod.cutoff_frequency +CartesianPML FiniteElementMethod.EPS0 FiniteElementMethod.MU0 FiniteElementMethod.C0 diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 9926afc6..b366c086 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -52,11 +52,13 @@ export MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative # Frequency-domain Maxwell: a separate entry point assembled directly on Ferrite, not through the PDESystem front end. include("maxwell/ports.jl") include("maxwell/model.jl") +include("maxwell/pml.jl") include("maxwell/driven.jl") include("maxwell/sweep.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! export MaxwellSolution, driven_problem, solve_driven, field_values export WavePort, MaxwellSweep, solve_sweep +export CartesianPML include("precompile.jl") diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index a64fabe7..09944845 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)`, 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. @@ -95,7 +96,7 @@ 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))")) @@ -126,6 +127,10 @@ 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]) diff --git a/src/maxwell/pml.jl b/src/maxwell/pml.jl new file mode 100644 index 00000000..7e1aa426 --- /dev/null +++ b/src/maxwell/pml.jl @@ -0,0 +1,146 @@ +# 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), so 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. 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) + if pml.box === nothing + inner = findall(!, in_pml) + isempty(inner) && throw(ArgumentError("every cell is in the PML; give its inner `box`")) + lo, hi = _bounding_box(grid, inner) + else + lo, hi = collect(pml.box[1]), collect(pml.box[2]) + end + 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 + α = _pml_profile(pml, grid, in_pml, pml.omega * sqrt(mu0 * eps0), L) + + names = (:curl_re, :curl_im, :eps_re, :eps_im, :sigma_re, :sigma_im) + mats = NamedTuple{names}(ntuple(_ -> copy(pattern), 6)) + 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) + Ferrite.assemble!(assemblers.eps_re, dofs, real.(eps_r .* m)) + Ferrite.assemble!(assemblers.eps_im, dofs, imag.(eps_r .* 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 + coefficients = ( + Returns(1.0 + 0.0im), Returns(1.0im), ω -> complex(-k2 * ω^2), ω -> -im * k2 * ω^2, + ω -> im * μL2 * ω, ω -> complex(-μL2 * ω), + ) + 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/pml.jl b/test/Maxwell/pml.jl new file mode 100644 index 00000000..27e83623 --- /dev/null +++ b/test/Maxwell/pml.jl @@ -0,0 +1,112 @@ +# 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 From 01be5e1d508d54580f14148fed76c7cc97d4b65b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 23:05:15 +0000 Subject: [PATCH 2/6] Assign the PML inner box once so JET sees it defined JET's typo mode reported lo and hi as possibly undefined in the stretching closure when they were assigned in two branches. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: ee6a670e-e4ec-446c-b941-3ebb999c45c5 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/pml.jl | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/maxwell/pml.jl b/src/maxwell/pml.jl index 7e1aa426..327c4e69 100644 --- a/src/maxwell/pml.jl +++ b/src/maxwell/pml.jl @@ -61,13 +61,8 @@ 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) - if pml.box === nothing - inner = findall(!, in_pml) - isempty(inner) && throw(ArgumentError("every cell is in the PML; give its inner `box`")) - lo, hi = _bounding_box(grid, inner) - else - lo, hi = collect(pml.box[1]), collect(pml.box[2]) - end + 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) From 1755c7416928742cb899d84e7c312d37896935eb Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:35:30 +0000 Subject: [PATCH 3/6] PML: conjugate the stretching for negative frequencies The stretching used the positive-frequency signs at every omega, so at negative omega the layer amplified the outgoing wave; the imaginary blocks now change sign with the frequency, giving A(-omega) = conj(A(omega)) and leaving the omega = 0 operator unchanged. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/pml.jl | 11 +++++++---- test/Maxwell/pml.jl | 10 ++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/maxwell/pml.jl b/src/maxwell/pml.jl index 327c4e69..b44d6241 100644 --- a/src/maxwell/pml.jl +++ b/src/maxwell/pml.jl @@ -22,8 +22,8 @@ to the bounding box of the layer cells (zero means no stretching across that fac 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), so 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 +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. Wave ports and absorbing facet sets cannot touch layer cells. """ struct CartesianPML @@ -132,9 +132,12 @@ function _pml_terms(pml::CartesianPML, dh, cv, pattern, cell_materials, mu0, eps Ferrite.assemble!(assemblers.sigma_im, dofs, sigma .* imag.(m)) end k2, μL2 = mu0 * eps0 * L^2, mu0 * L^2 + # For ω < 0 the stretching is conjugated (the imaginary blocks change sign), so that A(-ω) = conj(A(ω)) and the layer + # still attenuates the outgoing wave. + sgn(ω) = ω < 0 ? -1.0 : 1.0 coefficients = ( - Returns(1.0 + 0.0im), Returns(1.0im), ω -> complex(-k2 * ω^2), ω -> -im * k2 * ω^2, - ω -> im * μL2 * ω, ω -> complex(-μL2 * ω), + Returns(1.0 + 0.0im), ω -> im * sgn(ω), ω -> complex(-k2 * ω^2), ω -> -im * 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) diff --git a/test/Maxwell/pml.jl b/test/Maxwell/pml.jl index 27e83623..061b7cc8 100644 --- a/test/Maxwell/pml.jl +++ b/test/Maxwell/pml.jl @@ -110,3 +110,13 @@ end 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 From 85735a160bed252f41ab19fb245c924a8cff8951 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 21:17:44 +0000 Subject: [PATCH 4/6] PML: do not conjugate the material when the stretching is conjugated At negative omega the imaginary block of eps_r (Lambda - 1) was flipped as a whole, which conjugated the supplied permittivity too, so a complex permittivity and the equivalent conductivity assembled different operators. The permittivity blocks are now split by the real and imaginary parts of eps_r and of the stretching, and only the stretching changes sign. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/pml.jl | 18 +++++++++++------- test/Maxwell/pml.jl | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/maxwell/pml.jl b/src/maxwell/pml.jl index b44d6241..fa86465c 100644 --- a/src/maxwell/pml.jl +++ b/src/maxwell/pml.jl @@ -99,8 +99,8 @@ function _pml_terms(pml::CartesianPML, dh, cv, pattern, cell_materials, mu0, eps end α = _pml_profile(pml, grid, in_pml, pml.omega * sqrt(mu0 * eps0), L) - names = (:curl_re, :curl_im, :eps_re, :eps_im, :sigma_re, :sigma_im) - mats = NamedTuple{names}(ntuple(_ -> copy(pattern), 6)) + 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) @@ -126,18 +126,22 @@ function _pml_terms(pml::CartesianPML, dh, cv, pattern, cell_materials, mu0, eps dofs = Ferrite.celldofs(cc) Ferrite.assemble!(assemblers.curl_re, dofs, real.(kc) ./ mu_r) Ferrite.assemble!(assemblers.curl_im, dofs, imag.(kc) ./ mu_r) - Ferrite.assemble!(assemblers.eps_re, dofs, real.(eps_r .* m)) - Ferrite.assemble!(assemblers.eps_im, dofs, imag.(eps_r .* m)) + # 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 is conjugated (the imaginary blocks change sign), so that A(-ω) = conj(A(ω)) and the layer - # still attenuates the outgoing wave. + # 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 * μL2 * ω, ω -> complex(-μL2 * ω * 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) diff --git a/test/Maxwell/pml.jl b/test/Maxwell/pml.jl index 061b7cc8..6a76dde0 100644 --- a/test/Maxwell/pml.jl +++ b/test/Maxwell/pml.jl @@ -120,3 +120,19 @@ end 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 From 6c1c83b1b2a343858bc337c8ceb8dfc122753554 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 21:57:50 +0000 Subject: [PATCH 5/6] PML: require positive real permittivity and permeability in the layer For a negative-index filling the outward-power wave has a negative phase wavenumber and the stretching s = 1 - i alpha amplifies it, so such a PML is rejected at construction, consistent with the wave-port decision. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/maxwell.md | 2 ++ src/maxwell/pml.jl | 10 +++++++++- test/Maxwell/pml.jl | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 4da94d72..afae83b4 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -77,6 +77,8 @@ inner box (by default the bounding box of the other cells), into the uniaxial ab 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 diff --git a/src/maxwell/pml.jl b/src/maxwell/pml.jl index fa86465c..1c70414f 100644 --- a/src/maxwell/pml.jl +++ b/src/maxwell/pml.jl @@ -24,7 +24,9 @@ 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. Wave ports and absorbing facet sets cannot touch layer cells. +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} @@ -97,6 +99,12 @@ function _pml_terms(pml::CartesianPML, dh, cv, pattern, cell_materials, mu0, eps 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) diff --git a/test/Maxwell/pml.jl b/test/Maxwell/pml.jl index 6a76dde0..a60fd2dd 100644 --- a/test/Maxwell/pml.jl +++ b/test/Maxwell/pml.jl @@ -136,3 +136,17 @@ end @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 From 3950348cb88e934b3435bd1cca72e74983d17fcf Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 01:43:27 +0000 Subject: [PATCH 6/6] Sensitivities: reject a parameter region that overlaps the PML The PML blocks depend on the supplied material in the layer, but the parameter derivative assembled only the isotropic terms, so the sensitivity of a region reaching into the PML differed from finite differences. The model records its PML cell sets and all three entry points reject an overlapping region, documented in the adjoint docstring and the manual. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/maxwell.md | 2 +- src/maxwell/adjoint.jl | 11 ++++++++++- src/maxwell/model.jl | 4 +++- test/Maxwell/adjoint.jl | 22 ++++++++++++++++++++++ 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index d0aa0ab1..5dec6351 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -136,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/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index c8d7b8ad..ba81a1e4 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 30f1490c..c5a36203 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -94,6 +94,7 @@ struct MaxwellModel{G, DH, CH, CV} terms::Vector{MaxwellTerm} absorbing::Vector{String} ports::Vector{WavePortData} + pml_cellsets::Vector{String} end function MaxwellModel( @@ -145,7 +146,8 @@ function MaxwellModel( 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/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl index 9cdb4487..9f7ef725 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