Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
df89520
Add TE10 wave ports, first-order ABC and S-parameter sweeps for Maxwell
Nov 5, 2026
2872585
Document wave ports, absorbing boundaries and sweeps
Nov 5, 2026
71321bb
Use the complex permittivity on absorbing faces and require a PEC por…
Nov 5, 2026
0aca6b3
Reject wave ports whose face is also PEC-constrained
Nov 5, 2026
c313425
Merge maxwell/1-core into maxwell/3-sweep-abc
Nov 5, 2026
b152bb3
Merge maxwell/1-core into maxwell/3-sweep-abc
Nov 5, 2026
66ffe5c
Merge maxwell/1-core into maxwell/3-sweep-abc (PR workflow triggers)
Nov 6, 2026
a892dbd
Merge forge/mwsync-1-core into maxwell/3-sweep-abc
Nov 10, 2026
6ba156b
Merge forge/mwsync-1-core into 3-sweep-abc
Nov 11, 2026
212444f
Throw at exact port cutoff instead of returning NaN S-parameters
Nov 10, 2026
c300959
Sweep and ports: copy stored fields, reject lossy and doubly-assigned…
Nov 11, 2026
39c7c5f
Reject any two overlapping absorbing or wave-port facet sets
Nov 11, 2026
b6d59f1
Merge forge/mwsync-1-core into 3-sweep-abc
Nov 11, 2026
3049c4e
Ports: use the facet node table from the core
Nov 11, 2026
20f6d3e
Wave ports: reject PEC on the interior of the port face
Nov 12, 2026
e734b27
Maxwell model: materialise the ports iterable once before validation
Nov 12, 2026
d17b451
Wave ports: restrict the power interpretation to propagating ports
Nov 12, 2026
8f083be
Tests: qualify propagation_constant in the axial power test
Nov 12, 2026
7119acf
Merge forge/mwsync-1-core into 3-sweep-abc
Nov 12, 2026
912dea7
Wave ports and absorbing boundary: outgoing branch for lossless negat…
Nov 12, 2026
7089122
Absorbing boundary: outgoing branch follows the sign of the frequency
Nov 12, 2026
4141f26
Absorbing boundary and wave ports: one outgoing rule for every sign o…
Nov 12, 2026
c834c97
Wave ports: the operator path rejects negative frequencies only
Nov 12, 2026
fcb0262
Wave ports: require positive real permittivity and positive permeability
Nov 12, 2026
dfef81e
Wave ports: apply the TE10 admittance to the TE10 amplitude only
Nov 12, 2026
edcbb3d
Docstrings: the wave-port term is rank-one, and extra blocks are copi…
Nov 12, 2026
f836a5d
Comment: the port's modal boundary term and its sign
Nov 12, 2026
59959b6
Add adjoint S-parameter sensitivities to material parameters (#80)
xtalax-droid Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions docs/src/maxwell.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,45 @@ that is a function of `ω`, so a frequency sweep only recombines nonzero values
[`maxwell_operator!`](@ref), and further terms (boundary conditions, ports) are added as blocks with
`FiniteElementMethod.add_term!`.

## Wave ports, absorbing boundaries and frequency sweeps

Rectangular-waveguide ports and first-order absorbing boundaries are model keywords. A [`WavePort`](@ref)
on a planar boundary facet set launches and absorbs the TE10 mode of the rectangle it spans; `a_direction`
names the broad wall. Facet sets in `absorbing` get the first-order Silver-Müller condition
`n × (μr⁻¹ ∇ × E) = -i k0 sqrt(εc/μr) n × (n × E)` (`εc = εr - iσ/(ωε0)` of the adjacent material), exact for a plane wave at normal incidence (a TE10 wave
reflects `Γ = (β - k0)/(β + k0)` from it). [`solve_sweep`](@ref) returns the scattering matrix at each
angular frequency; it keeps one operator matrix and one factorisation pattern, and solves every port's
excitation from a single factorisation per frequency. The linear solver is the `solver` keyword (see
[`FiniteElementMethod.umfpack_solver`](@ref)).

```julia
using FiniteElementMethod, Ferrite
# A 50 mm section of WR-90 (22.86 mm × 10.16 mm), mesh in millimetres.
grid = generate_grid(Tetrahedron, (16, 7, 34), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 50.0))
ports = [WavePort("bottom"; a_direction = (1, 0, 0)), WavePort("top"; a_direction = (1, 0, 0))]
model = MaxwellModel(grid; pec = ["left", "right", "front", "back"], ports, length_scale = 1.0e-3)
sweep = solve_sweep(model, 2π .* (8.0e9:0.5e9:12.0e9))
sweep.S[2, 1, 5] # S21 at 10 GHz: |S21| ≈ 1, angle ≈ -93.3°
```

`Sᵢⱼ` is referred to the port faces, or to planes `deembed` mesh units inside them. Ports on different guides
are normalised through the TE10 wave impedance `ωμ0μr/β`. For a propagating port these are power waves. Below cutoff
the propagation constant is `β = -iα`, the evanescent branch, which carries no real axial power: the coefficients
are then generalized traveling-wave coefficients with the same normalisation, still supported, but without an
individual incident or outgoing power, and `S` is not power conserving.

A wave port is a single-mode TE10 termination: its admittance acts on the TE10 amplitude of the trace only (a rank-one
term that couples all the dofs of the port face), and the evanescent higher modes see the natural (magnetic-wall)
boundary at the port plane, so they are reflected, not absorbed, and a lossless single-mode structure conserves
power. Keep about one decay length `1 / sqrt(kc² - k²)` of the first evanescent mode (`kc = 2π/a` for TE20, `π/b` for
TE01) of uniform lead between a discontinuity and the port, otherwise `S` depends on the lead length. Wave ports need positive frequencies; a
zero or negative `ω` is rejected, since a real system has `S(-ω) = conj(S(ω))`.

A port must lie in an ordinary passive material: a complex `eps_r`, a nonzero conductivity, a non-positive `eps_r`
or a non-positive `mu_r` at a port is rejected, because the power-wave normalisation above holds for a real wave
impedance and the outward power of the TE10 mode is `Re(β/μr) > 0` only for positive `μr` and `εr`. Put loss behind the port, not in its face, and a
facet cannot belong to two ports or to both a port and an `absorbing` set.

```@docs
MaxwellModel
MaxwellMaterial
Expand All @@ -42,7 +81,47 @@ MaxwellSolution
field_values
FiniteElementMethod.maxwell_rhs
FiniteElementMethod.add_term!
WavePort
FiniteElementMethod.WavePortData
solve_sweep
MaxwellSweep
FiniteElementMethod.umfpack_solver
FiniteElementMethod.tangential_mass
FiniteElementMethod.port_excitations
FiniteElementMethod.s_parameters
FiniteElementMethod.propagation_constant
FiniteElementMethod.cutoff_frequency
FiniteElementMethod.EPS0
FiniteElementMethod.MU0
FiniteElementMethod.C0
```

## Material sensitivities

[`s_parameter_sensitivities`](@ref) returns the derivatives of the wave-port S-parameters with respect to
material parameters of named cell sets: `:eps_r` (the real part of `εr`), `:eps_r_imag` (its imaginary
part), `:mu_r` and `:sigma`, each shifting that parameter on every cell of the set. They are the exact
derivatives of the discrete S-parameters, by the discrete adjoint: the system matrix is complex symmetric,
so the adjoint field of port `i` is the forward field with port `i` driven, and the sensitivities cost no
linear solve beyond the sweep, only one sparse product per parameter and frequency. A parameter set may
touch an absorbing boundary (its `sqrt(εc/μr)` is differentiated) but not a wave port, whose mode is taken
in fixed material.

```julia
grid = generate_grid(Tetrahedron, (12, 6, 15), Vec(0.0, 0.0, 0.0), Vec(22.86, 10.16, 30.0))
addcellset!(grid, "slab", x -> 10.0 - 1.0e-9 <= x[3] <= 20.0 + 1.0e-9; all = true)
ports = [WavePort(face; a_direction = (1, 0, 0), deembed = 10.0) for face in ("bottom", "top")]
model = MaxwellModel(grid; materials = Dict("slab" => MaxwellMaterial(; eps_r = 2.2)),
pec = ["left", "right", "front", "back"], ports, length_scale = 1.0e-3)
sens = s_parameter_sensitivities(model, [2π * 10.0e9], [(:eps_r, "slab"), (:sigma, "slab")])
sens.dS[1, 1, 1, 1] # dS11/dεr at 10 GHz
```

For a real objective such as `|S11|²`, the gradient is `2 Re(conj(S11) dS11/dp)`. Other real functionals
`J(u)` of the field take one adjoint solve with [`adjoint_gradient`](@ref).

```@docs
s_parameter_sensitivities
MaxwellSensitivities
adjoint_gradient
```
9 changes: 7 additions & 2 deletions src/FiniteElementMethod.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit
using DomainSets: DomainSets
using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron
using ForwardDiff: ForwardDiff
using LinearAlgebra: dot, mul!, norm
using LinearAlgebra: cross, dot, lu, lu!, mul!, norm
using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters,
ProblemTypeCtx, System, complete, getmetadata
using NonlinearSolveFirstOrder: NewtonRaphson
Expand All @@ -22,7 +22,7 @@ using PrecompileTools: PrecompileTools
using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions
using SciMLBase: SciMLBase, DAEFunction, DAEProblem
using SciMLBase.SymbolicIndexingInterface: SymbolicIndexingInterface, getp, parameter_index, variable_index
using SparseArrays: SparseMatrixCSC, nnz, nonzeros, nzrange, rowvals
using SparseArrays: SparseMatrixCSC, dropzeros!, findnz, nnz, nonzeros, nzrange, rowvals, sparse
using SymbolicUtils: SymbolicUtils
using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap

Expand Down Expand Up @@ -53,10 +53,15 @@ export MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative
export Weighted

# Frequency-domain Maxwell: a separate entry point assembled directly on Ferrite, not through the PDESystem front end.
include("maxwell/ports.jl")
include("maxwell/model.jl")
include("maxwell/driven.jl")
include("maxwell/sweep.jl")
include("maxwell/adjoint.jl")
export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator!
export MaxwellSolution, driven_problem, solve_driven, field_values
export WavePort, MaxwellSweep, solve_sweep
export MaxwellSensitivities, s_parameter_sensitivities, adjoint_gradient

include("precompile.jl")

Expand Down
203 changes: 203 additions & 0 deletions src/maxwell/adjoint.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
# Discrete adjoint sensitivities of a MaxwellModel with respect to the material parameters of named cell sets.
# A is complex symmetric (Aᵀ = A), so the adjoint of a wave port's output is the forward field with that port
# driven, and the S-parameter sensitivities need no solve beyond the forward sweep.

const _PARAMETER_KINDS = (:eps_r, :eps_r_imag, :mu_r, :sigma)

# The adjoint of a port is its forward field only for a symmetric A, but `add_term!` takes any block with the
# model's sparsity pattern. Only the free dofs count: the constrained rows and columns are replaced by the identity,
# so a large entry on a constrained dof must not hide the asymmetry of the operator that is solved.
function _check_symmetric(model)
free = setdiff(axes(model.blocks.curlcurl, 1), model.ch.prescribed_dofs)
for (k, term) in pairs(model.terms)
B = term.block[free, free]
norm(B - transpose(B), 1) <= 1.0e-12 * norm(B, 1) ||
throw(ArgumentError("term $k of the model has a nonsymmetric block, so A is not symmetric and the adjoint needs transpose(A); the sensitivities support symmetric terms only"))
end
return nothing
end

# ∫ w ∇×Nᵢ⋅∇×Nⱼ (curl = true) or ∫ w Nᵢ⋅Nⱼ over `cells`, with the real weight `w = weight(cell)`, with the
# zeros outside `cells` dropped.
function _region_block(model, cells, curl::Bool, weight)
block = copy(model.blocks.curlcurl)
asm = Ferrite.start_assemble(block)
cv = model.cellvalues
n = Ferrite.getnbasefunctions(cv)
Ke = zeros(n, n)
for cc in Ferrite.CellIterator(model.dh, collect(cells))
Ferrite.reinit!(cv, cc)
fill!(Ke, 0.0)
for q in 1:Ferrite.getnquadpoints(cv)
dΩ = Ferrite.getdetJdV(cv, q)
for i in 1:n, j in 1:n
Ke[i, j] += dΩ * (
curl ? dot(Ferrite.shape_curl(cv, q, i), Ferrite.shape_curl(cv, q, j)) :
dot(Ferrite.shape_value(cv, q, i), Ferrite.shape_value(cv, q, j))
)
end
end
Ferrite.assemble!(asm, Ferrite.celldofs(cc), weight(Ferrite.cellid(cc)) .* Ke)
end
return dropzeros!(block)
end

# d sqrt(εc/μr) / dp for the material `m`, with εc = εr - iσ/(ωε0).
function _abc_admittance_derivative(kind, m, ω, eps0)
εc = m.eps_r - im * m.sigma / (ω * eps0)
y = _admittance(εc, m.mu_r, ω)
kind === :mu_r && return -y / (2 * m.mu_r)
dεc = kind === :eps_r ? 1.0 + 0.0im : kind === :eps_r_imag ? 1.0im : -im / (ω * eps0)
return y / (2εc) * dεc
end

# dA/dp as MaxwellTerms, for p the parameter `kind` of every cell of the cell set `name` shifted together.
function _parameter_terms(model, (kind, name))
kind in _PARAMETER_KINDS ||
throw(ArgumentError("unknown material parameter $(repr(kind)); use one of $(_PARAMETER_KINDS)"))
name = String(name)
_check_cellset(model.grid, name)
cells = Ferrite.getcellset(model.grid, name)
for data in model.ports, (cell, _) in Ferrite.getfacetset(model.grid, data.port.facetset)
cell in cells && throw(
ArgumentError(
"cell set $(repr(name)) touches wave port $(repr(data.port.facetset)), whose mode depends on its material; " *
"sensitivities need the ports in fixed material"
)
)
end
(; mu0, eps0, length_scale) = model
L2 = length_scale^2
k2 = mu0 * eps0 * L2
terms = if kind === :mu_r
[MaxwellTerm(_region_block(model, cells, true, cell -> -1 / model.materials[cell].mu_r^2), Returns(1.0 + 0.0im))]
else
M = _region_block(model, cells, false, Returns(1.0))
coefficient = kind === :eps_r ? (ω -> complex(-k2 * ω^2)) : kind === :eps_r_imag ? (ω -> -im * k2 * ω^2) :
(ω -> im * mu0 * L2 * ω)
[MaxwellTerm(M, coefficient)]
end
# The absorbing boundary on cells of the set: +i k0 L sqrt(εc/μr) ∮ (n × Nᵢ)⋅(n × Nⱼ) dS, per material.
abc_cells = [facet[1] for facetset in model.absorbing for facet in Ferrite.getfacetset(model.grid, facetset) if facet[1] in cells]
for m in unique(model.materials[abc_cells])
block = _tangential_mass(
model.dh, model.blocks.curlcurl, model.absorbing, cell -> Float64(cell in cells && model.materials[cell] == m)
)
push!(
terms, MaxwellTerm(
dropzeros!(block),
# 0 at ω = 0, as the forward absorbing coefficient is, where εc = εr - iσ/(ωε0) is 0/0 for σ = 0.
ω -> iszero(ω) ? 0.0im : im * ω * sqrt(mu0 * eps0) * length_scale * _abc_admittance_derivative(kind, m, ω, eps0)
)
)
end
return terms
end

# Σₜ cₜ(ω) Bₜ U for the terms of one dA/dp.
_derivative_times(terms, ω, U) = sum(term.coefficient(ω) .* (term.block * U) for term in terms)

"""
MaxwellSensitivities

The result of [`s_parameter_sensitivities`](@ref): `omegas`, the scattering matrices `S[:, :, k]` as in
[`MaxwellSweep`](@ref), `params` and `dS[i, j, k, l]`, the derivative of `S[i, j, k]` with respect to the real
parameter `params[l]`.
"""
struct MaxwellSensitivities
omegas::Vector{Float64}
S::Array{ComplexF64, 3}
params::Vector{Tuple{Symbol, String}}
dS::Array{ComplexF64, 4}
end

_normalise_params(params) = Tuple{Symbol, String}[(Symbol(kind), String(name)) for (kind, name) in params]

"""
s_parameter_sensitivities(model::MaxwellModel, omegas, params; solver = umfpack_solver)
s_parameter_sensitivities(model::MaxwellModel, sweep::MaxwellSweep, params)

The wave-port scattering matrices of `model` at the angular frequencies `omegas` and their derivatives with
respect to the material parameters `params`, as [`MaxwellSensitivities`](@ref). Each parameter is a pair
`(kind, cellset)`: `kind` is `:eps_r` (the real part of `εr`), `:eps_r_imag` (its imaginary part, `-ε''`),
`:mu_r` or `:sigma`, and the derivative is with respect to that parameter of every cell of the named cell set
shifted by the same amount (the set need not be one of the `materials` keys). The second method reuses the
fields of a sweep run with `fields = true`.

These are the exact derivatives of the discrete S-parameters. Since `A(ω)` is complex symmetric, the adjoint
field of port `i` is the forward field `uᵢ` with port `i` driven, so

dSᵢⱼ/dp = -uᵢᵀ (dA/dp) uⱼ / (2iβᵢ L Pᵢ / μr,ᵢ) ⋅ (power-wave and de-embedding factors of Sᵢⱼ),

at no linear solve beyond [`solve_sweep`](@ref). `dA/dp` is assembled once per parameter over the cells of its
set, including the absorbing boundary's `sqrt(εc/μr)` on those cells. A cell set adjacent to a wave port is
rejected: the port's mode, excitation and normalisation depend on its material, and are taken as fixed.
Terms added with [`FiniteElementMethod.add_term!`](@ref) are taken as independent of the parameters, and must have
symmetric blocks (an `ArgumentError` otherwise).
"""
function s_parameter_sensitivities(model::MaxwellModel, omegas, params; solver = umfpack_solver)
params = _normalise_params(params)
_check_symmetric(model)
terms = [_parameter_terms(model, param) for param in params] # validate before solving
return _s_parameter_sensitivities(model, solve_sweep(model, omegas; fields = true, solver), params, terms)
end

function s_parameter_sensitivities(model::MaxwellModel, sweep::MaxwellSweep, params)
sweep.fields === nothing &&
throw(ArgumentError("the sweep has no fields; run solve_sweep with fields = true"))
all(U -> size(U) == (Ferrite.ndofs(model.dh), length(model.ports)), sweep.fields) ||
throw(ArgumentError("the sweep's fields do not match the dofs and ports of the model"))
params = _normalise_params(params)
_check_symmetric(model)
terms = [_parameter_terms(model, param) for param in params]
return _s_parameter_sensitivities(model, sweep, params, terms)
end

function _s_parameter_sensitivities(model, sweep, params, terms)
(; omegas, S, fields) = sweep
ports = model.ports
np = length(ports)
mu0eps0, L = model.mu0 * model.eps0, model.length_scale
dS = zeros(ComplexF64, np, np, length(omegas), length(terms))
for (k, ω) in pairs(omegas)
U = fields[k]
β = [_propagation_constant(data, mu0eps0, ω) for data in ports]
w = [sqrt(data.norm * β[i] / data.mu_r) for (i, data) in pairs(ports)]
shift = [exp(im * β[i] * data.port.deembed * L) for (i, data) in pairs(ports)]
# Aλᵢ = pᵢ gives λᵢ = uᵢ / cᵢ, with cᵢ = 2iβᵢL/μr,ᵢ the excitation scale of port_excitations.
c = [2im * β[i] * L / data.mu_r for (i, data) in pairs(ports)]
for (l, param_terms) in pairs(terms)
G = transpose(U) * _derivative_times(param_terms, ω, U)
for j in 1:np, i in 1:np
dS[i, j, k, l] = -G[i, j] / (c[i] * ports[i].norm) * w[i] / w[j] * shift[i] * shift[j]
end
end
end
return MaxwellSensitivities(omegas, S, params, dS)
end

"""
adjoint_gradient(model::MaxwellModel, ω, u, dJ_du, params; solver = umfpack_solver, cache = nothing)

The gradient of a real functional `J(u)` of the field `u` (edge dofs solving `A(ω) u = b`, with `b`
independent of the parameters, as for [`driven_problem`](@ref) or [`port_excitations`](@ref) away from the
parameter sets) with respect to the material parameters `params` (as for
[`s_parameter_sensitivities`](@ref)), as a vector of real numbers. `dJ_du` is the complex gradient
`∂J/∂Re(u) + i ∂J/∂Im(u)`. One adjoint solve `A λ = conj(dJ_du)` (the transpose of `A` is `A`) gives

dJ/dp = -Re(λᵀ (dA/dp) u).

The solve is `solver(A, B, cache)` on the constrained `A(ω)`; to reuse an existing factorisation `F` of it, pass
`solver = (A, B, F) -> (F \\ B, F)` and `cache = F`.
"""
function adjoint_gradient(model::MaxwellModel, ω::Real, u::AbstractVector, dJ_du::AbstractVector, params; solver = umfpack_solver, cache = nothing)
_check_symmetric(model)
terms = [_parameter_terms(model, param) for param in _normalise_params(params)]
ω = float(ω)
A = maxwell_operator(model, ω)
Ferrite.apply!(A, model.ch)
rhs = conj.(ComplexF64.(dJ_du))
rhs[model.ch.prescribed_dofs] .= 0
λ, _ = solver(A, reshape(rhs, :, 1), cache)
return Float64[-real(dot(conj(vec(λ)), _derivative_times(param_terms, ω, u))) for param_terms in terms]
end
Loading
Loading