From 3e48a00f5ce449557e7c65cfd0302bbd3478cfff Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 23:20:33 +0000 Subject: [PATCH 1/7] Add discrete adjoint material sensitivities for Maxwell S-parameters Antenna and filter optimisation needs gradients of S-parameters with respect to material parameters. A(omega) is complex symmetric, so the adjoint of each wave port's output is the forward field with that port driven: s_parameter_sensitivities gives dS/dp for eps_r, Im eps_r, mu_r and sigma of named cell sets from the sweep's fields with no extra solve, including the absorbing boundary's dependence on the adjacent material. adjoint_gradient covers real field functionals with one adjoint solve through the pluggable solver interface. Validated against central finite differences of the forward sweep (relative agreement 1e-10 to 2e-8) and against the closed-form WR-90 dielectric slab. 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 | 30 ++++++ src/FiniteElementMethod.jl | 4 +- src/maxwell/adjoint.jl | 185 +++++++++++++++++++++++++++++++++++++ test/Maxwell/adjoint.jl | 151 ++++++++++++++++++++++++++++++ 4 files changed, 369 insertions(+), 1 deletion(-) create mode 100644 src/maxwell/adjoint.jl create mode 100644 test/Maxwell/adjoint.jl diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index d8a26f53..8d74818f 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -81,3 +81,33 @@ 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 9926afc6..b1cf0f9f 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -22,7 +22,7 @@ using PrecompileTools: PrecompileTools using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions using SciMLBase: SciMLBase, DAEFunction, DAEProblem using SciMLBase.SymbolicIndexingInterface: SymbolicIndexingInterface, getp, parameter_index, variable_index -using SparseArrays: SparseMatrixCSC, nnz, nonzeros, nzrange, rowvals +using SparseArrays: SparseMatrixCSC, dropzeros!, nnz, nonzeros, nzrange, rowvals using SymbolicUtils: SymbolicUtils using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap @@ -54,9 +54,11 @@ 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..7ca8f5a3 --- /dev/null +++ b/src/maxwell/adjoint.jl @@ -0,0 +1,185 @@ +# 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) + +# ∫ 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 = sqrt(ε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), + ω -> 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. +""" +function s_parameter_sensitivities(model::MaxwellModel, omegas, params; solver = umfpack_solver) + params = _normalise_params(params) + 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) + 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) + 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/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl new file mode 100644 index 00000000..1d0b5c0b --- /dev/null +++ b/test/Maxwell/adjoint.jl @@ -0,0 +1,151 @@ +# 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, 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 From 6b24db051c7f7adc01e7413e5da50f789290ab86 Mon Sep 17 00:00:00 2001 From: t Date: Wed, 11 Nov 2026 23:57:45 +0000 Subject: [PATCH 2/7] Adjoint sensitivities: reject nonsymmetric added terms The adjoint of a port is its forward field, and the adjoint solve uses A, only when A is symmetric; add_term! accepts any block of the right pattern, so the three entry points now check the blocks are symmetric and throw an ArgumentError otherwise. 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/adjoint.jl | 17 ++++++++++++++++- test/Maxwell/adjoint.jl | 13 +++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index 7ca8f5a3..75f30008 100644 --- a/src/maxwell/adjoint.jl +++ b/src/maxwell/adjoint.jl @@ -4,6 +4,17 @@ 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. +function _check_symmetric(model) + for (k, term) in pairs(model.terms) + B = term.block + norm(B - transpose(B), 1) <= 1.0e-12 * max(norm(B, 1), 1.0) || + 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) @@ -118,10 +129,12 @@ 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. -Terms added with [`FiniteElementMethod.add_term!`](@ref) are taken as independent of the parameters. +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 @@ -132,6 +145,7 @@ function s_parameter_sensitivities(model::MaxwellModel, sweep::MaxwellSweep, par 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 @@ -174,6 +188,7 @@ The solve is `solver(A, B, cache)` on the constrained `A(ω)`; to reuse an exist `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, ω) diff --git a/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl index 1d0b5c0b..2169bf20 100644 --- a/test/Maxwell/adjoint.jl +++ b/test/Maxwell/adjoint.jl @@ -149,3 +149,16 @@ end 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) + 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 From f3a68993e5f9e46d536e510a92be4b40a952e340 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:16:54 +0000 Subject: [PATCH 3/7] Adjoint sensitivities: scale-free symmetry check The absolute floor accepted a tiny nonsymmetric block with a huge coefficient; the check is now relative to the block. 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/adjoint.jl | 2 +- test/Maxwell/adjoint.jl | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index 75f30008..81e1e6af 100644 --- a/src/maxwell/adjoint.jl +++ b/src/maxwell/adjoint.jl @@ -9,7 +9,7 @@ const _PARAMETER_KINDS = (:eps_r, :eps_r_imag, :mu_r, :sigma) function _check_symmetric(model) for (k, term) in pairs(model.terms) B = term.block - norm(B - transpose(B), 1) <= 1.0e-12 * max(norm(B, 1), 1.0) || + 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 diff --git a/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl index 2169bf20..6e3b8cc4 100644 --- a/test/Maxwell/adjoint.jl +++ b/test/Maxwell/adjoint.jl @@ -1,6 +1,6 @@ # 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, Test +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 @@ -155,6 +155,15 @@ end 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")]) From 3eda379e03e3532fa207ff3d6d093daa37bb8506 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 02:13:58 +0000 Subject: [PATCH 4/7] Adjoint: absorbing coefficient derivative is 0 at omega = 0 Consistent with the forward absorbing coefficient. 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/adjoint.jl | 3 ++- test/Maxwell/adjoint.jl | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index 81e1e6af..20c779f1 100644 --- a/src/maxwell/adjoint.jl +++ b/src/maxwell/adjoint.jl @@ -84,7 +84,8 @@ function _parameter_terms(model, (kind, name)) push!( terms, MaxwellTerm( dropzeros!(block), - ω -> im * ω * sqrt(mu0 * eps0) * length_scale * _abc_admittance_derivative(kind, m, ω, eps0) + # 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 diff --git a/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl index 6e3b8cc4..61dcd0a1 100644 --- a/test/Maxwell/adjoint.jl +++ b/test/Maxwell/adjoint.jl @@ -171,3 +171,18 @@ end model, MaxwellSweep([SLAB_F], zeros(ComplexF64, 2, 2, 1), [zeros(ComplexF64, ndofs(model.dh), 2)]), [(:eps_r, "slab")] ) 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 From 21dc1eee109ed4bddada3d01e1caecc1d9902fc7 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:20:11 +0000 Subject: [PATCH 5/7] Adjoint: check symmetry on the free dofs only A large symmetric entry on a constrained dof could hide a nonsymmetric free operator, so the sensitivities accepted models whose adjoint is wrong. The relative skew is now measured on the unconstrained sub-block, with the same tolerance. 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/adjoint.jl | 6 ++++-- test/Maxwell/adjoint.jl | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index 20c779f1..cbbf1cfc 100644 --- a/src/maxwell/adjoint.jl +++ b/src/maxwell/adjoint.jl @@ -5,10 +5,12 @@ 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. +# 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 + 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 diff --git a/test/Maxwell/adjoint.jl b/test/Maxwell/adjoint.jl index 61dcd0a1..9cdb4487 100644 --- a/test/Maxwell/adjoint.jl +++ b/test/Maxwell/adjoint.jl @@ -172,6 +172,29 @@ end ) 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) From d8c29a0de42b09e14a087b671093d50cde9b9e87 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:43:07 +0000 Subject: [PATCH 6/7] Adjoint: differentiate the outgoing-branch absorbing admittance The absorbing term now takes the outgoing root for a lossless negative eps_r/mu_r; the derivative uses the same branch. 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/adjoint.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index cbbf1cfc..6093cd4b 100644 --- a/src/maxwell/adjoint.jl +++ b/src/maxwell/adjoint.jl @@ -45,7 +45,7 @@ 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 = sqrt(εc / m.mu_r) + 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 From f9c28453a0fe9b0a004dafa93c945f0fac6e0dc3 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:01:08 +0000 Subject: [PATCH 7/7] Adjoint: the absorbing admittance derivative follows the sign of omega Uses the same outgoing branch as the operator. 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/adjoint.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/maxwell/adjoint.jl b/src/maxwell/adjoint.jl index 6093cd4b..c8d7b8ad 100644 --- a/src/maxwell/adjoint.jl +++ b/src/maxwell/adjoint.jl @@ -45,7 +45,7 @@ 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) + 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