From d3c44c0acfe1907a412698647fa981a4f98c47d6 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 23:08:42 +0000 Subject: [PATCH 01/11] Add lumped ports with Z- and S-parameters for Maxwell MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A LumpedPort is a rectangular facet sheet across a gap carrying a uniform sheet current; its Z0 load (iωμ0 L/(w²Z0) g gᵀ), Norton source and gap voltage V = L gᵀu/w share one functional g, so the circuit identities hold exactly for the discrete system. Wave and lumped ports mix in one model and one solve_sweep, both normalised to power waves. Validated against transmission-line closed forms on a PMC-sided parallel-plate line. 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 | 7 +- src/maxwell/lumped.jl | 161 +++++++++++++++++++++++++++++++++ src/maxwell/model.jl | 35 +++++--- src/maxwell/ports.jl | 64 +++++++++---- src/maxwell/sweep.jl | 8 +- test/Maxwell/lumped.jl | 179 +++++++++++++++++++++++++++++++++++++ test/Maxwell/ports.jl | 2 +- 8 files changed, 445 insertions(+), 40 deletions(-) create mode 100644 src/maxwell/lumped.jl create mode 100644 test/Maxwell/lumped.jl diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index b20c3ebb..a79355de 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -55,6 +55,30 @@ 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. +## Lumped ports + +A [`LumpedPort`](@ref) is a rectangular facet sheet bridging a gap between two conductors, of length `l` +along `direction` and width `w` across it, on the boundary or inside the mesh. It carries a uniform sheet +current `I/w` along `direction`; its voltage is the sheet average of the line integral of `E` across the gap, +`V = (1/w) ∮ E⋅l̂ dS`. Every port is loaded by its reference impedance `Z0`, which adds +`iωμ0 L/(w² Z0) g gᵀ` (`gᵢ = ∮ l̂⋅Nᵢ dS`) to the operator, and the driven port adds a 1 A current source in +parallel, so `Sᵢⱼ = 2Vᵢ/sqrt(Z0ᵢZ0ⱼ) - δᵢⱼ`. Because the load, the source and the voltage use the same `g`, +these circuit identities hold exactly for the discrete system: a lossless structure gives a unitary `S`. +Wave and lumped ports can share one model and one sweep, both normalised to power waves. + +```julia +using FiniteElementMethod, Ferrite +# A parallel-plate line (PEC plates at y = 0 and y = 5 mm, open sides) with a 50 Ω port at each end. +grid = generate_grid(Tetrahedron, (2, 2, 20), Vec(0.0, 0.0, 0.0), Vec(10.0, 5.0, 20.0)) +ports = [LumpedPort("bottom"; direction = (0, 1, 0)), LumpedPort("top"; direction = (0, 1, 0))] +model = MaxwellModel(grid; pec = ["front", "back"], ports, length_scale = 1.0e-3) +S = solve_sweep(model, [2π * 3.0e9]).S[:, :, 1] # S11 ≈ 0.846 + 0.136i, S21 ≈ 0.082 - 0.508i +Z = FiniteElementMethod.z_parameters(model, S) +``` + +The port couples all its edge dofs to each other, which widens the sparsity pattern, so keep the sheet a +few elements across. + ```@docs MaxwellModel MaxwellMaterial @@ -69,6 +93,11 @@ FiniteElementMethod.maxwell_rhs FiniteElementMethod.add_term! WavePort FiniteElementMethod.WavePortData +LumpedPort +FiniteElementMethod.LumpedPortData +FiniteElementMethod.port_voltage +FiniteElementMethod.port_current +FiniteElementMethod.z_parameters solve_sweep MaxwellSweep FiniteElementMethod.umfpack_solver diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 9926afc6..150eb72f 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: cross, dot, lu, lu!, mul!, norm +using LinearAlgebra: Diagonal, I, cross, dot, lu, lu!, mul!, norm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -22,7 +22,7 @@ using PrecompileTools: PrecompileTools using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions using SciMLBase: SciMLBase, DAEFunction, DAEProblem using SciMLBase.SymbolicIndexingInterface: SymbolicIndexingInterface, getp, parameter_index, variable_index -using SparseArrays: SparseMatrixCSC, nnz, nonzeros, nzrange, rowvals +using SparseArrays: SparseMatrixCSC, findnz, nnz, nonzeros, nzrange, rowvals, sparse using SymbolicUtils: SymbolicUtils using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap @@ -50,13 +50,14 @@ export FEMDiscretization, Galerkin, SUPG, add_boundary_pieces! 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/lumped.jl") include("maxwell/ports.jl") include("maxwell/model.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 WavePort, LumpedPort, MaxwellSweep, solve_sweep include("precompile.jl") diff --git a/src/maxwell/lumped.jl b/src/maxwell/lumped.jl new file mode 100644 index 00000000..75282e69 --- /dev/null +++ b/src/maxwell/lumped.jl @@ -0,0 +1,161 @@ +# Lumped ports of a MaxwellModel: a uniform sheet current across a planar gap, loaded by its reference +# impedance and driven by a Norton current source. + +""" + LumpedPort(facetset; direction, Z0 = 50.0) + +A lumped port on the planar facet set `facetset` of a [`MaxwellModel`](@ref): a rectangular sheet of length +`l` along `direction` (in the sheet plane, from one conductor to the other) and width `w` across it, +bridging a gap. The sheet may lie on the boundary or inside the mesh; a facet listed from both of its cells +counts once. + +The port carries a uniform sheet current `I / w` along `direction`, so the gap voltage is the sheet average +of the line integral of `E` along `direction`, `V = (1/w) ∮ E⋅l̂ dS` (positive when the start of `direction` +is the + terminal). Every port is loaded by its real reference impedance `Z0` (ohm) and the driven port adds a +1 A current source in parallel (see [`FiniteElementMethod.port_excitations`](@ref)). The port couples all of +its edge dofs to each other, so keep the sheet a few elements across. +""" +struct LumpedPort + facetset::String + direction::Ferrite.Vec{3, Float64} + Z0::Float64 +end +function LumpedPort(facetset; direction, Z0::Real = 50.0) + Z0 > 0 || throw(ArgumentError("the reference impedance Z0 of a lumped port must be positive, got $Z0")) + return LumpedPort(String(facetset), Ferrite.Vec{3, Float64}(Tuple(direction)), float(Z0)) +end + +""" + LumpedPortData + +A [`LumpedPort`](@ref) assembled on a [`MaxwellModel`](@ref), in `model.ports`. Fields: `port`, `profile` +(`gᵢ = ∮ l̂⋅Nᵢ dS` over the sheet, so that `V = L gᵀu / w`), `dofs` (the edge dofs of the sheet), `block` +(`g gᵀ` on the model's sparsity pattern), `normal`, `length` and `width` (`l` and `w`, mesh units). +""" +struct LumpedPortData + port::LumpedPort + profile::Vector{Float64} + dofs::Vector{Int} + block::SparseMatrixCSC{Float64, Int} + normal::Ferrite.Vec{3, Float64} + length::Float64 + width::Float64 +end + +# The facets of a set with each geometric facet once, whichever of its two cells lists it. +function _unique_facets(grid, facets) + seen = Set{Vector{Int}}() + unique_facets = Ferrite.FacetIndex[] + for facet in facets + cell, local_facet = facet[1], facet[2] + cell_nodes = Ferrite.getcells(grid, cell).nodes + nodes = sort!([cell_nodes[i] for i in Ferrite.reference_facets(RefTetrahedron)[local_facet]]) + nodes in seen && continue + push!(seen, nodes) + push!(unique_facets, Ferrite.FacetIndex(cell, local_facet)) + end + return unique_facets +end + +# Profile, dofs and geometry of a lumped port; the block needs the model's pattern, which needs the dofs. +function _lumped_port_geometry(port::LumpedPort, dh) + grid = dh.grid + _check_facetset(grid, port.facetset) + facets = _unique_facets(grid, Ferrite.getfacetset(grid, port.facetset)) + isempty(facets) && throw(ArgumentError("port facet set $(repr(port.facetset)) is empty")) + fv = _facet_values() + local_dofs = Ferrite.dirichlet_facetdof_indices(_NEDELEC) + profile = zeros(Ferrite.ndofs(dh)) + normal = nothing + nodes = Ferrite.Vec{3, Float64}[] + area = 0.0 + l̂ = port.direction / norm(port.direction) + for (cell, local_facet) in facets + x = Ferrite.getcoordinates(grid, cell) + Ferrite.reinit!(fv, Ferrite.getcells(grid, cell), x, local_facet) + nq = Ferrite.getnormal(fv, 1) + normal === nothing && (normal = nq) + abs(dot(nq, normal)) >= 1 - 1.0e-8 || throw(ArgumentError("port facet set $(repr(port.facetset)) is not planar")) + dofs = Ferrite.celldofs(dh, cell) + for q in 1:Ferrite.getnquadpoints(fv) + dS = Ferrite.getdetJdV(fv, q) + area += dS + # l̂ is tangential, so only the edges of this facet contribute. + for i in local_dofs[local_facet] + profile[dofs[i]] += dot(l̂, Ferrite.shape_value(fv, q, i)) * dS + end + end + append!(nodes, x[i] for i in Ferrite.reference_facets(RefTetrahedron)[local_facet]) + end + abs(dot(l̂, normal)) <= 1.0e-8 || throw(ArgumentError("direction of port $(repr(port.facetset)) is not in the port plane")) + t̂ = cross(normal, l̂) + (s0, s1), (t0, t1) = extrema(dot(x, l̂) for x in nodes), extrema(dot(x, t̂) for x in nodes) + len, width = s1 - s0, t1 - t0 + abs(area - len * width) <= 1.0e-6 * len * width || + throw(ArgumentError("port facet set $(repr(port.facetset)) is not a rectangle with a side along direction")) + dofs = sort!(unique(Ferrite.celldofs(dh, f[1])[i] for f in facets for i in local_dofs[f[2]])) + return (; profile, dofs, normal, len, width) +end + +# The cell pattern of `dh` plus every pair of edge dofs within each lumped port. +function _sparsity_pattern(dh, port_dofs) + pattern = Ferrite.allocate_matrix(dh) + isempty(port_dofs) && return pattern + rows, cols, _ = findnz(pattern) + for dofs in port_dofs, i in dofs, j in dofs + push!(rows, i) + push!(cols, j) + end + n = Ferrite.ndofs(dh) + pattern = sparse(rows, cols, ones(length(rows)), n, n) + fill!(nonzeros(pattern), 0.0) + return pattern +end + +function _lumped_port(port::LumpedPort, geometry, pattern) + (; profile, dofs, normal, len, width) = geometry + block = copy(pattern) + Ferrite.assemble!(Ferrite.start_assemble(block), dofs, profile[dofs] * profile[dofs]') + return LumpedPortData(port, profile, dofs, block, normal, len, width) +end + +# The sheet current I = V/Z0 = L gᵀu / (w Z0) gives +iωμ0 L / (w² Z0) g gᵀ on the operator. +function _port_term(data::LumpedPortData, mu0, eps0, L) + scale = mu0 * L / (data.width^2 * data.port.Z0) + return MaxwellTerm(data.block, ω -> im * ω * scale) +end + +function _lumped(model, port::Integer) + data = model.ports[port] + data isa LumpedPortData || throw(ArgumentError("port $port of the model is not a lumped port")) + return data +end + +""" + port_voltage(model::MaxwellModel, port, u) + +The gap voltage `V = (1/w) ∮ E⋅l̂ dS` (volt) of lumped port number `port` of `model` in the edge-dof vector `u`. +""" +port_voltage(model, port::Integer, u::AbstractVector) = + (data = _lumped(model, port); model.length_scale * dot(data.profile, u) / data.width) + +""" + port_current(model::MaxwellModel, port, u; source = 0) + +The current (ampere) that lumped port number `port` delivers into the structure in the solution `u`, +`source - V / Z0`, with `source` the current of its Norton source: 1 for the driven port of a +[`solve_sweep`](@ref) column, 0 for the others. +""" +port_current(model, port::Integer, u::AbstractVector; source::Number = 0) = + source - port_voltage(model, port, u) / _lumped(model, port).port.Z0 + +""" + z_parameters(model::MaxwellModel, S) + +The impedance matrix (ohm) `Z = G^½ (I + S)(I - S)⁻¹ G^½`, `G = diag(Z0)`, of a scattering matrix `S` of a +model whose ports are all lumped ports, inverting `Sᵢⱼ = 2 Vᵢ / sqrt(Z0ᵢ Z0ⱼ) - δᵢⱼ` for a 1 A source at port `j`. +""" +function z_parameters(model, S::AbstractMatrix) + sqrtZ0 = Diagonal([sqrt(_lumped(model, i).port.Z0) for i in eachindex(model.ports)]) + return sqrtZ0 * ((I + S) / (I - S)) * sqrtZ0 +end diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 9cc61c74..08c9610a 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -43,7 +43,7 @@ struct MaxwellTerm end """ - MaxwellModel(grid; materials = Dict(), pec = String[], absorbing = String[], ports = WavePort[], + MaxwellModel(grid; materials = Dict(), pec = String[], absorbing = String[], ports = [], 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 @@ -54,7 +54,7 @@ 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(εr/μr) n × (n × E)`, and the -[`WavePort`](@ref)s in `ports`. +[`WavePort`](@ref)s and [`LumpedPort`](@ref)s in `ports`, numbered in the order given. `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. @@ -69,13 +69,15 @@ sparse blocks on one sparsity pattern, each with a complex coefficient that is a `Kc = ∫ μr⁻¹ ∇×Nᵢ ⋅ ∇×Nⱼ`, `Mε' = ∫ Re(εr) Nᵢ⋅Nⱼ`, `Mε'' = ∫ Im(εr) Nᵢ⋅Nⱼ` and `Mσ = ∫ σ Nᵢ⋅Nⱼ` over the mesh (so `Im(εr) = -ε''` gives the `+iω²μ0ε0L² ε''` loss term). The absorbing boundary adds `+i k0 L ∮ sqrt(εr/μr) (n × Nᵢ)⋅(n × Nⱼ) dS` (`k0 = ω sqrt(μ0 ε0)`, material of the adjacent cell) and each -wave port `+i (β(ω)/μr) L ∮ (n × Nᵢ)⋅(n × Nⱼ) dS` over its face. `A` is complex symmetric, not Hermitian. +wave port `+i (β(ω)/μr) L ∮ (n × Nᵢ)⋅(n × Nⱼ) dS` over its face; each lumped port adds +`+iω μ0 L / (w² Z0) g gᵀ` (see [`FiniteElementMethod.LumpedPortData`](@ref)), whose dof pairs widen the +cell-based sparsity pattern. `A` is complex symmetric, not Hermitian. Fields: `grid`, `dh`, `ch` (zero `AffineConstraint`s on the PEC edge dofs), `cellvalues`, `materials` (one per cell), `pec`, `eps0`, `mu0`, `length_scale`, `blocks` (the volume blocks `curlcurl`, `eps_real`, -`eps_imag` and `sigma` above), `absorbing`, `ports` (the [`FiniteElementMethod.WavePortData`](@ref) in the -order given) and `terms`, the [`MaxwellTerm`](@ref)s that [`maxwell_operator!`](@ref) -combines; [`FiniteElementMethod.add_term!`](@ref) appends further blocks, such as boundary terms. +`eps_imag` and `sigma` above), `absorbing`, `ports` (the [`FiniteElementMethod.WavePortData`](@ref) and +[`FiniteElementMethod.LumpedPortData`](@ref) in the order given) and `terms`, the [`MaxwellTerm`](@ref)s +that [`maxwell_operator!`](@ref) combines; [`FiniteElementMethod.add_term!`](@ref) appends further blocks, such as boundary terms. """ struct MaxwellModel{G, DH, CH, CV} grid::G @@ -90,12 +92,12 @@ struct MaxwellModel{G, DH, CH, CV} blocks::NamedTuple{(:curlcurl, :eps_real, :eps_imag, :sigma), NTuple{4, SparseMatrixCSC{Float64, Int}}} terms::Vector{MaxwellTerm} absorbing::Vector{String} - ports::Vector{WavePortData} + ports::Vector{Union{WavePortData, LumpedPortData}} 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 = [], 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))")) @@ -116,7 +118,9 @@ function MaxwellModel( Ferrite.close!(ch) cv = Ferrite.CellValues(Ferrite.QuadratureRule{RefTetrahedron}(quadrature), ip) - blocks = _assemble_blocks(dh, cv, cell_materials) + lumped = Dict(i => _lumped_port_geometry(port, dh) for (i, port) in pairs(ports) if port isa LumpedPort) + pattern = _sparsity_pattern(dh, [geometry.dofs for geometry in values(lumped)]) + blocks = _assemble_blocks(pattern, dh, cv, cell_materials) L2 = float(length_scale)^2 k2 = mu0 * eps0 * L2 terms = [ @@ -127,8 +131,11 @@ function MaxwellModel( ] L = float(length_scale) isempty(absorbing) || append!(terms, _absorbing_terms(dh, blocks.curlcurl, absorbing, cell_materials, mu0, eps0, L)) - port_data = WavePortData[_wave_port(port, dh, blocks.curlcurl, cell_materials, L, ch.prescribed_dofs) for port in ports] - append!(terms, [_port_term(data, mu0 * eps0, L) for data in port_data]) + port_data = Union{WavePortData, LumpedPortData}[ + port isa LumpedPort ? _lumped_port(port, lumped[i], pattern) : + _wave_port(port, dh, pattern, cell_materials, L, ch.prescribed_dofs) for (i, port) in pairs(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 ) @@ -168,8 +175,7 @@ function _pec_dofs(dh, grid, pec) return sort!(collect(dofs)) end -function _assemble_blocks(dh, cv, cell_materials) - pattern = Ferrite.allocate_matrix(dh) +function _assemble_blocks(pattern, dh, cv, cell_materials) mats = (curlcurl = pattern, eps_real = copy(pattern), eps_imag = copy(pattern), sigma = copy(pattern)) assemblers = map(Ferrite.start_assemble, mats) n = Ferrite.getnbasefunctions(cv) @@ -204,7 +210,8 @@ _same_pattern(A, B) = A.colptr == B.colptr && rowvals(A) == rowvals(B) add_term!(model::MaxwellModel, block, coefficient) Append the term `coefficient(ω) * block` to the system matrix of `model`. `block` must have the sparsity -pattern of `model.blocks`, as every matrix from `Ferrite.allocate_matrix(model.dh)` does. +pattern of `model.blocks`, such as a copy of `model.blocks.curlcurl` (without lumped ports, every matrix from +`Ferrite.allocate_matrix(model.dh)` has it). """ function add_term!(model::MaxwellModel, block::SparseMatrixCSC{Float64, Int}, coefficient) _same_pattern(block, model.blocks.curlcurl) || diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 2d5f07d6..07673c61 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -182,6 +182,12 @@ function _propagation_constant(data::WavePortData, mu0eps0, ω) return imag(β) > 0 ? -β : β end +function _wave(model, port::Integer) + data = model.ports[port] + data isa WavePortData || throw(ArgumentError("port $port of the model is not a wave port")) + return data +end + """ propagation_constant(model::MaxwellModel, port, ω) @@ -189,7 +195,7 @@ The TE10 propagation constant `β` (rad/m) of wave port number `port` of `model` Below cutoff `β = -iα` with `α > 0`, so the mode `exp(-iβζ)` decays away from the port. """ propagation_constant(model, port::Integer, ω::Real) = - _propagation_constant(model.ports[port], model.mu0 * model.eps0, float(ω)) + _propagation_constant(_wave(model, port), model.mu0 * model.eps0, float(ω)) """ cutoff_frequency(model::MaxwellModel, port) @@ -197,49 +203,71 @@ propagation_constant(model, port::Integer, ω::Real) = The TE10 cutoff frequency in Hz, `kc / (2π sqrt(μ0 ε0 Re(εr) μr))`, of wave port number `port` of `model`. """ function cutoff_frequency(model, port::Integer) - data = model.ports[port] + data = _wave(model, port) return data.kc / (2π * sqrt(model.mu0 * model.eps0 * real(data.eps_r) * data.mu_r)) end # n × μr⁻¹∇ × E = -(iβ/μr) n × (n × E) - 2(iβ/μr) E0 e on the port gives +(iβ/μr) L B on the operator and # +2(iβ/μr) L E0 p on the load, with E0 = 1. -function _port_term(data::WavePortData, mu0eps0, L) - return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0eps0, ω) * L / data.mu_r) +function _port_term(data::WavePortData, mu0, eps0, L) + return MaxwellTerm(data.block, ω -> im * _propagation_constant(data, mu0 * eps0, ω) * L / data.mu_r) end +_excitation(model, data::WavePortData, ω) = + (2im * _propagation_constant(data, model.mu0 * model.eps0, ω) * model.length_scale / data.mu_r) .* data.profile +# A 1 A Norton source, -(1/w) l̂ sheet current, gives +iωμ0 L² g / (w L) after division by L. +_excitation(model, data::LumpedPortData, ω) = (im * ω * model.mu0 / data.width) .* data.profile + """ port_excitations(model::MaxwellModel, ω) -The load vectors of the wave ports of `model` at `ω`, one column per port: the TE10 mode of unit amplitude -incident on that port, without the PEC constraints. +The load vectors of the ports of `model` at `ω`, one column per port, without the PEC constraints: for a +wave port the TE10 mode of unit amplitude (1 V/m) incident on it, for a lumped port a 1 A current source in +parallel with its `Z0`. """ function port_excitations(model, ω::Real) B = zeros(ComplexF64, Ferrite.ndofs(model.dh), length(model.ports)) for (j, data) in pairs(model.ports) - β = _propagation_constant(data, model.mu0 * model.eps0, float(ω)) - B[:, j] .= (2im * β * model.length_scale / data.mu_r) .* data.profile + B[:, j] .= _excitation(model, data, float(ω)) end return B end +# Power waves (peak phasors, |a|²/2 watts) of a port for the excitation of `port_excitations`: the incident +# wave `a` when the port is driven and the outgoing wave `b` in the solution `u`, `driven` or not. +function _power_waves(model, data::WavePortData, ω, u, driven::Bool) + β = _propagation_constant(data, model.mu0 * model.eps0, ω) + # sqrt(∮ e⋅e dS / Z) with the TE10 wave impedance Z = ωμ0μr / β. + w = sqrt(data.norm * model.length_scale^2 * β / (ω * model.mu0 * data.mu_r)) + shift = exp(im * β * data.port.deembed * model.length_scale) + return w / shift, (dot(data.profile, u) / data.norm - driven) * w * shift +end +function _power_waves(model, data::LumpedPortData, ω, u, driven::Bool) + # a = (V + Z0 I)/(2 sqrt Z0) with I = driven - V/Z0 delivered into the structure. + Z0 = data.port.Z0 + V = model.length_scale * dot(data.profile, u) / data.width + return sqrt(Z0) / 2, (2V - Z0 * driven) / (2 * sqrt(Z0)) +end + """ s_parameters(model::MaxwellModel, ω, U) -The scattering matrix from the solutions `U[:, j]` with port `j` driven by [`port_excitations`](@ref): -`Sᵢⱼ = (pᵢᵀ uⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ Zⱼ / (Pⱼ Zᵢ)) exp(iβᵢdᵢ + iβⱼdⱼ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave -impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. +The scattering matrix `Sᵢⱼ = bᵢ / aⱼ` from the solutions `U[:, j]` with port `j` driven by +[`port_excitations`](@ref), in power waves. A wave port has `aⱼ = sqrt(Pⱼ / Zⱼ) exp(-iβⱼdⱼ)` and +`bᵢ = (pᵢᵀuⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ / Zᵢ) exp(iβᵢdᵢ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave impedance +`Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. A lumped port has `aⱼ = sqrt(Z0ⱼ) / 2` and +`bᵢ = (2Vᵢ - Z0ᵢ δᵢⱼ) / (2 sqrt(Z0ᵢ))`, so between lumped ports `Sᵢⱼ = 2Vᵢ / sqrt(Z0ᵢ Z0ⱼ) - δᵢⱼ`. """ function s_parameters(model, ω::Real, U::AbstractMatrix) - mu0eps0 = model.mu0 * model.eps0 + ω = float(ω) ports = model.ports - β = [_propagation_constant(data, mu0eps0, float(ω)) for data in ports] - # Power-wave scale: |a|² P / Z, with Z ∝ μr / β. - w = [sqrt(data.norm * β[i] / data.mu_r) for (i, data) in pairs(ports)] - shift = [exp(im * β[i] * data.port.deembed * model.length_scale) for (i, data) in pairs(ports)] np = length(ports) S = zeros(ComplexF64, np, np) - for j in 1:np, i in 1:np - S[i, j] = (dot(ports[i].profile, view(U, :, j)) / ports[i].norm - (i == j)) * w[i] / w[j] * shift[i] * shift[j] + for j in 1:np + a = first(_power_waves(model, ports[j], ω, view(U, :, j), true)) + for i in 1:np + S[i, j] = last(_power_waves(model, ports[i], ω, view(U, :, j), i == j)) / a + end end return S end diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl index cfa7b01c..f31f15f3 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -1,4 +1,4 @@ -# Frequency sweep of the wave-port scattering matrix of a MaxwellModel: one operator matrix recombined per +# Frequency sweep of the port scattering matrix of a MaxwellModel: one operator matrix recombined per # frequency, one factorisation per frequency for all port excitations. """ @@ -17,7 +17,7 @@ end MaxwellSweep The result of [`solve_sweep`](@ref): `omegas`, the scattering matrices `S[:, :, k]` at `omegas[k]` -(`S[i, j, k]` is the wave leaving port `i` for a unit wave incident on port `j`) and `fields`, either +(`S[i, j, k]` is the power wave leaving port `i` for a unit power wave incident on port `j`) and `fields`, either `nothing` or, per frequency, the matrix whose column `j` is the edge-dof vector with port `j` driven (wrap it with `MaxwellSolution(model, omegas[k], fields[k][:, j])`). """ @@ -30,7 +30,7 @@ end """ solve_sweep(model::MaxwellModel, omegas; fields = false, solver = umfpack_solver) -The scattering matrix of the [`WavePort`](@ref)s of `model` at each angular frequency in `omegas` (rad/s), +The scattering matrix of the [`WavePort`](@ref)s and [`LumpedPort`](@ref)s of `model` at each angular frequency in `omegas` (rad/s), as a [`MaxwellSweep`](@ref). Each frequency recombines the nonzero values of one operator matrix with [`maxwell_operator!`](@ref), applies the PEC constraints, and solves for all port excitations at once with `solver(A, B, cache)` (see [`FiniteElementMethod.umfpack_solver`](@ref)), which may keep its factorisation @@ -38,7 +38,7 @@ between frequencies in `cache`. `fields = true` keeps the solutions (`ndofs × n frequency). """ function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = umfpack_solver) - isempty(model.ports) && throw(ArgumentError("the model has no wave ports")) + isempty(model.ports) && throw(ArgumentError("the model has no ports")) omegas = float.(collect(omegas)) np = length(model.ports) S = zeros(ComplexF64, np, np, length(omegas)) diff --git a/test/Maxwell/lumped.jl b/test/Maxwell/lumped.jl new file mode 100644 index 00000000..72facccc --- /dev/null +++ b/test/Maxwell/lumped.jl @@ -0,0 +1,179 @@ +# Lumped ports against transmission-line closed forms (exp(+iωt)): a parallel-plate line with PMC sides, +# x ∈ [0, W], y ∈ [0, h], z ∈ [0, len] mm, PEC plates at y = 0 and y = h, carries an exact TEM wave of +# impedance Zc = η0 h / (W sqrt(εr)), and lumped ports across the plates (direction +y) are its terminals. +using FiniteElementMethod, Ferrite, SparseArrays, LinearAlgebra, Test + +const ETA0 = FiniteElementMethod.MU0 * FiniteElementMethod.C0 +const F3 = 2π * 3.0e9 +const PLATE_W, PLATE_H, PLATE_LEN = 10.0, 5.0, 20.0 # mm + +function plates(hz; ncross = 2, len = PLATE_LEN, Z0 = (50.0, 50.0), top = :port, materials = Dict{String, MaxwellMaterial}()) + grid = generate_grid(Tetrahedron, (ncross, ncross, ceil(Int, len / hz)), Vec(0.0, 0.0, 0.0), Vec(PLATE_W, PLATE_H, len)) + isempty(materials) || addcellset!(grid, "fill", x -> true) + ports = [LumpedPort("bottom"; direction = (0, 1, 0), Z0 = Z0[1])] + top === :port && push!(ports, LumpedPort("top"; direction = (0, 1, 0), Z0 = Z0[2])) + pec = top === :pec ? ["front", "back", "top"] : ["front", "back"] + return MaxwellModel(grid; pec, ports, length_scale = 1.0e-3, materials) +end + +# ABCD matrix of a line of length `len` mm with relative permittivity `eps_r` (complex for loss). +function line_abcd(ω, len, eps_r = 1.0) + θ = ω / FiniteElementMethod.C0 * sqrt(complex(eps_r)) * len * 1.0e-3 + Zc = ETA0 * PLATE_H / (PLATE_W * sqrt(complex(eps_r))) + return [cos(θ) im * Zc * sin(θ); im * sin(θ) / Zc cos(θ)] +end +# Scattering matrix of a two-port ABCD matrix with real reference impedances Z0. +function abcd_to_s(T, Z0) + (A, B), (C, D) = T[1, :], T[2, :] + Z = [A / C (A * D - B * C) / C; 1 / C D / C] + G = Diagonal(collect(float.(Z0))) + return sqrt(G) \ (Z - G) / (Z + G) * sqrt(G) +end + +lumped_S(model, ω) = solve_sweep(model, [ω]).S[:, :, 1] +passive(S) = maximum(eigvals(Hermitian(S' * S))) <= 1 + 1.0e-8 + +@testset "transmission-line closed forms of the self-check" begin + # The numbers quoted for W = 10 mm, h = 5 mm, Z0 = 50 Ω, L = 20 mm at 3 GHz. + Zc = ETA0 * PLATE_H / PLATE_W + @test Zc ≈ 188.365 atol = 1.0e-3 + S = abcd_to_s(line_abcd(F3, PLATE_LEN), (50, 50)) + @test S[1, 1] ≈ 0.84651 + 0.136im atol = 1.0e-5 + @test S[2, 1] ≈ 0.08165 - 0.5082im atol = 1.0e-5 + θ = F3 / FiniteElementMethod.C0 * PLATE_LEN * 1.0e-3 + Γ, P = (Zc - 50) / (Zc + 50), exp(-im * θ) + @test S[1, 1] ≈ Γ * (1 - P^2) / (1 - Γ^2 * P^2) && S[2, 1] ≈ P * (1 - Γ^2) / (1 - Γ^2 * P^2) + @test im * Zc * tan(θ) ≈ 581.45im atol = 1.0e-2 +end + +@testset "parallel-plate two-port" begin + expected = abcd_to_s(line_abcd(F3, PLATE_LEN), (50, 50)) + errs = Float64[] + # Refined in all three directions: the dispersion of the tetrahedra depends on their transverse size too. + for (ncross, hz) in ((2, 4.0), (4, 2.0), (8, 1.0)) + model = plates(hz; ncross) + S = lumped_S(model, F3) + push!(errs, maximum(abs, S - expected)) + @info "PMC parallel plates, lumped ports" hz ndofs(model.dh) S[1, 1] S[2, 1] errs[end] + @test S[1, 2] ≈ S[2, 1] rtol = 1.0e-8 + @test S[1, 1] ≈ S[2, 2] rtol = 1.0e-6 + @test passive(S) + # Lossless: the two Z0 loads take all the source power. + @test abs2(S[1, 1]) + abs2(S[2, 1]) ≈ 1 atol = 1.0e-8 + end + @test errs[end] < 2.0e-4 + @test errs[1] / errs[3] > 10 # dispersion error O(h²) + # Z = G^½(I + S)(I - S)⁻¹G^½ recovers the line's open-circuit impedances, -iZc cot θ and -iZc / sin θ. + model = plates(1.0) + T = line_abcd(F3, PLATE_LEN) + Z = FiniteElementMethod.z_parameters(model, lumped_S(model, F3)) + @test Z ≈ [T[1, 1] / T[2, 1] 1 / T[2, 1]; 1 / T[2, 1] T[2, 2] / T[2, 1]] rtol = 3.0e-3 +end + +@testset "matched and short-circuited lines" begin + # Ports referred to Zc: no reflection, transmission exp(-ik0 L). + Zc = ETA0 * PLATE_H / PLATE_W + model = plates(1.0; Z0 = (Zc, Zc)) + sweep = solve_sweep(model, [F3]; fields = true) + S = sweep.S[:, :, 1] + @info "matched parallel plates" S + @test abs(S[1, 1]) < 2.0e-3 && abs(S[2, 2]) < 2.0e-3 + @test S[2, 1] ≈ exp(-im * F3 / FiniteElementMethod.C0 * PLATE_LEN * 1.0e-3) atol = 2.0e-3 + # The driven port sees Zc: V = Zc I_in with I_in = 1 A - V/Z0 = 1/2 A. + u = sweep.fields[1][:, 1] + V = FiniteElementMethod.port_voltage(model, 1, u) + @test V ≈ Zc / 2 rtol = 2.0e-3 + @test FiniteElementMethod.port_current(model, 1, u; source = 1) ≈ 0.5 rtol = 2.0e-3 + @test abs(FiniteElementMethod.port_voltage(model, 2, u)) ≈ Zc / 2 rtol = 2.0e-3 + # One port, PEC short at z = L: Zin = iZc tan(k0 L). + model = plates(1.0; top = :pec) + Zin = only(FiniteElementMethod.z_parameters(model, lumped_S(model, F3))) + @info "shorted parallel plates" Zin + @test Zin ≈ im * Zc * tan(F3 / FiniteElementMethod.C0 * PLATE_LEN * 1.0e-3) rtol = 5.0e-3 +end + +@testset "lossy line with unequal reference impedances" begin + lossy = MaxwellMaterial(; eps_r = 2.2 - 0.3im, sigma = 0.05) + model = plates(1.0; Z0 = (50.0, 75.0), materials = Dict("fill" => lossy)) + S = lumped_S(model, F3) + eps_eff = lossy.eps_r - im * lossy.sigma / (F3 * FiniteElementMethod.EPS0) + expected = abcd_to_s(line_abcd(F3, PLATE_LEN, eps_eff), (50, 75)) + @info "lossy parallel plates" S expected + @test S[1, 2] ≈ S[2, 1] rtol = 1.0e-8 + @test passive(S) && maximum(eigvals(Hermitian(S' * S))) < 0.9 + @test S ≈ expected atol = 5.0e-3 +end + +@testset "lumped port inside the mesh" begin + # Port 2 on the plane z = L inside the line, listed from the cells on both sides; beyond it an open stub + # of length d (the natural condition at z = L + d is a PMC: an open circuit) in parallel with its load. + len, d, hz = PLATE_LEN, 6.0, 1.0 + grid = generate_grid(Tetrahedron, (2, 2, round(Int, (len + d) / hz)), Vec(0.0, 0.0, 0.0), Vec(PLATE_W, PLATE_H, len + d)) + plane = FacetIndex[] + for cell in 1:getncells(grid), (k, facet) in pairs(Ferrite.reference_facets(RefTetrahedron)) + x = getcoordinates(grid, cell) + all(i -> x[i][3] ≈ len, facet) && push!(plane, FacetIndex(cell, k)) + end + addfacetset!(grid, "gap", plane) + ports = [LumpedPort("bottom"; direction = (0, 1, 0)), LumpedPort("gap"; direction = (0, 1, 0))] + model = MaxwellModel(grid; pec = ["front", "back"], ports, length_scale = 1.0e-3) + gap = model.ports[2] + @test length(plane) == 2 * 8 # 2 × 2 squares of 2 triangles, each from both sides + @test gap.length ≈ PLATE_H && gap.width ≈ PLATE_W && abs(gap.normal[3]) ≈ 1 + @test length(FiniteElementMethod._unique_facets(grid, plane)) == 8 + S = lumped_S(model, F3) + Zc = ETA0 * PLATE_H / PLATE_W + Ystub = im * tan(F3 / FiniteElementMethod.C0 * d * 1.0e-3) / Zc + expected = abcd_to_s(line_abcd(F3, len) * [1 0; Ystub 1], (50, 50)) + @info "interior lumped port with an open stub" S expected + @test S[1, 2] ≈ S[2, 1] rtol = 1.0e-8 + @test S ≈ expected atol = 3.0e-3 +end + +@testset "mixed wave and lumped ports in one sweep" begin + # WR-90, 30 mm long: the TE10 wave port at z = 0, a lumped port across the guide (along y) at z = L. + a, b, len = 22.86, 10.16, 30.0 + grid = generate_grid(Tetrahedron, (8, 4, 15), Vec(0.0, 0.0, 0.0), Vec(a, b, len)) + ports = [WavePort("bottom"; a_direction = (1, 0, 0)), LumpedPort("top"; direction = (0, 1, 0), Z0 = 100.0)] + model = MaxwellModel(grid; pec = ["left", "right", "front", "back"], ports, length_scale = 1.0e-3) + ωs = 2π .* [9.0e9, 10.0e9, 11.0e9] + calls = Symbol[] + function counting(A, B, cache) + push!(calls, cache === nothing ? :lu : :refactor) + return FiniteElementMethod.umfpack_solver(A, B, cache) + end + sweep = solve_sweep(model, ωs; fields = true, solver = counting) + @test calls == [:lu, :refactor, :refactor] + for (k, ω) in pairs(ωs) + S = sweep.S[:, :, k] + @info "WR-90 wave port to lumped port" ω / 2π S abs2(S[1, 1]) + abs2(S[2, 1]) + # Reciprocity holds only if both kinds of port are normalised to the same power waves. + @test S[1, 2] ≈ S[2, 1] rtol = 1.0e-8 + @test passive(S) + @test abs2(S[1, 1]) + abs2(S[2, 1]) ≈ 1 atol = 1.0e-2 + # Every column from the one factorisation equals an independent solve. + A = maxwell_operator(model, ω) + B = FiniteElementMethod.port_excitations(model, ω) + for j in axes(B, 2) + bj = B[:, j] + Aj = copy(A) + apply!(Aj, bj, model.ch) + @test Aj \ bj ≈ sweep.fields[k][:, j] rtol = 1.0e-10 + end + end + @test_throws "not a lumped port" FiniteElementMethod.z_parameters(model, sweep.S[:, :, 1]) + @test_throws "not a wave port" FiniteElementMethod.propagation_constant(model, 2, ωs[1]) +end + +@testset "lumped port arguments" begin + grid = generate_grid(Tetrahedron, (2, 2, 2)) + @test_throws "must be positive" LumpedPort("bottom"; direction = (0, 1, 0), Z0 = 0) + @test_throws "not in the port plane" MaxwellModel(grid; ports = [LumpedPort("bottom"; direction = (0, 0, 1))]) + @test_throws "not a rectangle" MaxwellModel(grid; ports = [LumpedPort("bottom"; direction = (1, 1, 0))]) + @test_throws "no facet set" MaxwellModel(grid; ports = [LumpedPort("nope"; direction = (0, 1, 0))]) + # Lumped ports widen the pattern; every block and further term shares it. + model = MaxwellModel(grid; ports = [LumpedPort("bottom"; direction = (0, 1, 0))]) + @test nnz(model.blocks.curlcurl) > nnz(allocate_matrix(model.dh)) + @test model.ports[1].block.colptr == model.blocks.sigma.colptr + @test FiniteElementMethod.tangential_mass(model, ["top"]).colptr == model.blocks.curlcurl.colptr +end diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index 458f5e38..e8fd6719 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -126,5 +126,5 @@ end E = field_values(sol, [Vec(WR90_A / 2, WR90_B / 2, 0.0), Vec(WR90_A / 8, WR90_B / 2, 0.0)]).E @test abs(E[1][2]) ≈ abs(1 + sweep.S[1, 1, 2]) rtol = 0.05 # incident plus reflected at the port face @test abs(E[2][2]) / abs(E[1][2]) ≈ sin(π / 8) rtol = 0.1 - @test_throws "no wave ports" solve_sweep(MaxwellModel(generate_grid(Tetrahedron, (1, 1, 1))), [1.0]) + @test_throws "no ports" solve_sweep(MaxwellModel(generate_grid(Tetrahedron, (1, 1, 1))), [1.0]) end From 8b163cf9f3578c403bd46eb8720bbf4f4b71b3cb Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 23:15:15 +0000 Subject: [PATCH 02/11] Reject lumped-port sheets whose facets lie at different heights Parallel normals and a matching projected area do not make a sheet planar: two half-faces at different heights passed. Check the spread of the facet nodes along the normal, as WavePort already does. 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/lumped.jl | 3 +++ test/Maxwell/lumped.jl | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/src/maxwell/lumped.jl b/src/maxwell/lumped.jl index 75282e69..f712c37d 100644 --- a/src/maxwell/lumped.jl +++ b/src/maxwell/lumped.jl @@ -91,6 +91,9 @@ function _lumped_port_geometry(port::LumpedPort, dh) t̂ = cross(normal, l̂) (s0, s1), (t0, t1) = extrema(dot(x, l̂) for x in nodes), extrema(dot(x, t̂) for x in nodes) len, width = s1 - s0, t1 - t0 + heights = [dot(x, normal) for x in nodes] + maximum(heights) - minimum(heights) <= 1.0e-8 * max(len, width) || + throw(ArgumentError("port facet set $(repr(port.facetset)) is not planar")) abs(area - len * width) <= 1.0e-6 * len * width || throw(ArgumentError("port facet set $(repr(port.facetset)) is not a rectangle with a side along direction")) dofs = sort!(unique(Ferrite.celldofs(dh, f[1])[i] for f in facets for i in local_dofs[f[2]])) diff --git a/test/Maxwell/lumped.jl b/test/Maxwell/lumped.jl index 72facccc..98a36de4 100644 --- a/test/Maxwell/lumped.jl +++ b/test/Maxwell/lumped.jl @@ -170,6 +170,14 @@ end @test_throws "must be positive" LumpedPort("bottom"; direction = (0, 1, 0), Z0 = 0) @test_throws "not in the port plane" MaxwellModel(grid; ports = [LumpedPort("bottom"; direction = (0, 0, 1))]) @test_throws "not a rectangle" MaxwellModel(grid; ports = [LumpedPort("bottom"; direction = (1, 1, 0))]) + # Parallel normals and a matching projected area, but two halves at different heights. + split = generate_grid(Tetrahedron, (2, 1, 1)) + halves = [ + [f for f in getfacetset(split, "bottom") if all(x -> x[1] <= 0, getcoordinates(split, f[1])[collect(Ferrite.reference_facets(RefTetrahedron)[f[2]])])]; + [f for f in getfacetset(split, "top") if all(x -> x[1] >= 0, getcoordinates(split, f[1])[collect(Ferrite.reference_facets(RefTetrahedron)[f[2]])])] + ] + addfacetset!(split, "steps", halves) + @test_throws "not planar" MaxwellModel(split; ports = [LumpedPort("steps"; direction = (0, 1, 0))]) @test_throws "no facet set" MaxwellModel(grid; ports = [LumpedPort("nope"; direction = (0, 1, 0))]) # Lumped ports widen the pattern; every block and further term shares it. model = MaxwellModel(grid; ports = [LumpedPort("bottom"; direction = (0, 1, 0))]) From eebeaee9f7a2a945b9e74dc92629563acfbf1fe4 Mon Sep 17 00:00:00 2001 From: t Date: Wed, 11 Nov 2026 23:25:11 +0000 Subject: [PATCH 03/11] Lumped ports: use local tetrahedron facet tables instead of non-public Ferrite API Ferrite.reference_facets and dirichlet_facetdof_indices are not public; lumped.jl now uses the tables defined for the wave ports and the PEC edge dofs. 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/lumped.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/maxwell/lumped.jl b/src/maxwell/lumped.jl index f712c37d..1e3fafa6 100644 --- a/src/maxwell/lumped.jl +++ b/src/maxwell/lumped.jl @@ -49,7 +49,7 @@ function _unique_facets(grid, facets) for facet in facets cell, local_facet = facet[1], facet[2] cell_nodes = Ferrite.getcells(grid, cell).nodes - nodes = sort!([cell_nodes[i] for i in Ferrite.reference_facets(RefTetrahedron)[local_facet]]) + nodes = sort!([cell_nodes[i] for i in _TET_FACET_NODES[local_facet]]) nodes in seen && continue push!(seen, nodes) push!(unique_facets, Ferrite.FacetIndex(cell, local_facet)) @@ -64,7 +64,7 @@ function _lumped_port_geometry(port::LumpedPort, dh) facets = _unique_facets(grid, Ferrite.getfacetset(grid, port.facetset)) isempty(facets) && throw(ArgumentError("port facet set $(repr(port.facetset)) is empty")) fv = _facet_values() - local_dofs = Ferrite.dirichlet_facetdof_indices(_NEDELEC) + local_dofs = _TET_FACET_EDGE_DOFS profile = zeros(Ferrite.ndofs(dh)) normal = nothing nodes = Ferrite.Vec{3, Float64}[] @@ -85,7 +85,7 @@ function _lumped_port_geometry(port::LumpedPort, dh) profile[dofs[i]] += dot(l̂, Ferrite.shape_value(fv, q, i)) * dS end end - append!(nodes, x[i] for i in Ferrite.reference_facets(RefTetrahedron)[local_facet]) + append!(nodes, x[i] for i in _TET_FACET_NODES[local_facet]) end abs(dot(l̂, normal)) <= 1.0e-8 || throw(ArgumentError("direction of port $(repr(port.facetset)) is not in the port plane")) t̂ = cross(normal, l̂) From ca02a47b1d305228c68d27bd84c52de006451a97 Mon Sep 17 00:00:00 2001 From: t Date: Wed, 11 Nov 2026 23:56:16 +0000 Subject: [PATCH 04/11] Test that a sweep keeps independent fields on a lumped-port model A solver that reuses its output buffer must not alias the stored frequencies; each stored field is checked against its own equation. 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 --- test/Maxwell/lumped.jl | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/Maxwell/lumped.jl b/test/Maxwell/lumped.jl index 98a36de4..32bccff0 100644 --- a/test/Maxwell/lumped.jl +++ b/test/Maxwell/lumped.jl @@ -185,3 +185,22 @@ end @test model.ports[1].block.colptr == model.blocks.sigma.colptr @test FiniteElementMethod.tangential_mass(model, ["top"]).colptr == model.blocks.curlcurl.colptr end + +@testset "sweep fields survive a solver that reuses its output buffer" begin + model = plates(5.0) + ωs = 2π .* [2.0e9, 3.0e9] + function buffer_reusing_solver(A, B, cache) + U = cache === nothing ? similar(B) : cache + copyto!(U, lu(A) \ B) + return U, U + end + sweep = solve_sweep(model, ωs; fields = true, solver = buffer_reusing_solver) + @test sweep.fields[1] !== sweep.fields[2] + for (k, ω) in pairs(ωs) + A = maxwell_operator(model, ω) + Ferrite.apply!(A, model.ch) + B = FiniteElementMethod.port_excitations(model, ω) + B[model.ch.prescribed_dofs, :] .= 0 + @test norm(A * sweep.fields[k] - B) / norm(B) < 1.0e-8 + end +end From bb91c830a0fae803640189a4abbccad4e37c8502 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:17:50 +0000 Subject: [PATCH 05/11] Reject overlapping ports by facet nodes, not facet indices An interior sheet listed from each of its two cells has disjoint FacetIndex sets but is one sheet; the overlap check of boundary conditions now compares sorted facet node identities. 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/model.jl | 15 ++++++++++++--- test/Maxwell/lumped.jl | 8 ++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index 3ea8f871..bac8d38a 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -95,6 +95,13 @@ struct MaxwellModel{G, DH, CH, CV} ports::Vector{Union{WavePortData, LumpedPortData}} end +function _facet_node_sets(grid, name) + return Set( + sort!([Ferrite.getcells(grid, cell).nodes[i] for i in _TET_FACET_NODES[local_facet]]) + for (cell, local_facet) in Ferrite.getfacetset(grid, name) + ) +end + function MaxwellModel( grid::Ferrite.Grid; materials = Dict{String, MaxwellMaterial}(), pec = String[], absorbing = String[], ports = [], length_scale::Real = 1.0, eps0::Real = EPS0, mu0::Real = MU0, quadrature::Int = 2 @@ -105,10 +112,12 @@ function MaxwellModel( absorbing = String.(collect(absorbing)) foreach(name -> _check_facetset(grid, name), pec) foreach(name -> _check_facetset(grid, name), absorbing) - # Each boundary condition assembles its own term, so a facet in two of them would get both. - conditions = [[("absorbing", name) for name in absorbing]; [("wave port", port.facetset) for port in ports]] + # Each boundary condition assembles its own term, so a facet in two of them would get both. An interior facet is + # the same facet from both of its cells, so facets are compared by their nodes. + conditions = [[("absorbing", name) for name in absorbing]; [("port", port.facetset) for port in ports]] + node_sets = Dict(name => _facet_node_sets(grid, name) for (_, name) in conditions) for (i, (kind_i, name_i)) in pairs(conditions), (kind_j, name_j) in conditions[(i + 1):end] - isdisjoint(Ferrite.getfacetset(grid, name_i), Ferrite.getfacetset(grid, name_j)) || + isdisjoint(node_sets[name_i], node_sets[name_j]) || throw(ArgumentError("facet sets $(repr(name_i)) ($kind_i) and $(repr(name_j)) ($kind_j) share facets: a facet can carry only one absorbing or wave port condition")) end cell_materials = _cell_materials(grid, materials) diff --git a/test/Maxwell/lumped.jl b/test/Maxwell/lumped.jl index 32bccff0..df125673 100644 --- a/test/Maxwell/lumped.jl +++ b/test/Maxwell/lumped.jl @@ -121,6 +121,14 @@ end @test length(plane) == 2 * 8 # 2 × 2 squares of 2 triangles, each from both sides @test gap.length ≈ PLATE_H && gap.width ≈ PLATE_W && abs(gap.normal[3]) ≈ 1 @test length(FiniteElementMethod._unique_facets(grid, plane)) == 8 + # The same sheet listed from either side is one sheet: two ports on it overlap. + below = [f for f in plane if sum(getcoordinates(grid, f[1]))[3] / 4 < len] + addfacetset!(grid, "gap_below", below) + addfacetset!(grid, "gap_above", setdiff(plane, below)) + @test_throws "share facets" MaxwellModel( + grid; pec = ["front", "back"], length_scale = 1.0e-3, + ports = [LumpedPort("gap_below"; direction = (0, 1, 0)), LumpedPort("gap_above"; direction = (0, 1, 0))] + ) S = lumped_S(model, F3) Zc = ETA0 * PLATE_H / PLATE_W Ystub = im * tan(F3 / FiniteElementMethod.C0 * d * 1.0e-3) / Zc From 2356b50195b38ca4882ba47b94b50a4f13a0727d Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 01:48:53 +0000 Subject: [PATCH 06/11] Check port facet sets exist before comparing them for overlap 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/model.jl | 1 + 1 file changed, 1 insertion(+) diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index bac8d38a..1b2be6e2 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -115,6 +115,7 @@ function MaxwellModel( # Each boundary condition assembles its own term, so a facet in two of them would get both. An interior facet is # the same facet from both of its cells, so facets are compared by their nodes. conditions = [[("absorbing", name) for name in absorbing]; [("port", port.facetset) for port in ports]] + foreach(((_, name),) -> _check_facetset(grid, name), conditions) node_sets = Dict(name => _facet_node_sets(grid, name) for (_, name) in conditions) for (i, (kind_i, name_i)) in pairs(conditions), (kind_j, name_j) in conditions[(i + 1):end] isdisjoint(node_sets[name_i], node_sets[name_j]) || From a822abc30b2b36a6af1462eb26f7e652412726fe Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 10:41:15 +0000 Subject: [PATCH 07/11] Wave ports: reject zero frequency in the S-parameter normalisation The wave impedance is infinite below cutoff, so at omega = 0 the power-wave scale is 0/0 and the scattering matrix came out all NaN; s_parameters and port_excitations now throw an ArgumentError for a wave port at omega = 0. 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/ports.jl | 8 ++++++-- test/Maxwell/ports.jl | 7 +++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 096b7182..8190788b 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -237,10 +237,13 @@ end _excitation(model, data::WavePortData, ω) = (2im * _propagation_constant(data, model.mu0 * model.eps0, ω) * model.length_scale / data.mu_r) .* data.profile -# The propagation constants of the wave ports at ω. At exact cutoff β = 0, the wave impedance ωμ/β is infinite and the +# The propagation constants of the wave ports at ω. At ω = 0 and at exact cutoff β = 0, the wave impedance ωμ/β is infinite and the # power-wave scale of the S-parameters is 0/0, so it is an error rather than a NaN matrix. function _check_not_at_cutoff(model, ω) for (j, data) in pairs(model.ports) + data isa WavePortData && iszero(ω) && throw( + ArgumentError("ω = 0 is below the TE10 cutoff of wave port $j, where its wave impedance is infinite and its S-parameters are undefined; use a positive frequency") + ) data isa WavePortData && iszero(_propagation_constant(data, model.mu0 * model.eps0, float(ω))) && throw( ArgumentError("ω = $ω is exactly the TE10 cutoff of wave port $j, where its wave impedance is infinite and its S-parameters are undefined; use a nearby frequency") ) @@ -290,7 +293,8 @@ The scattering matrix `Sᵢⱼ = bᵢ / aⱼ` from the solutions `U[:, j]` with `bᵢ = (pᵢᵀuⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ / Zᵢ) exp(iβᵢdᵢ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. A lumped port has `aⱼ = sqrt(Z0ⱼ) / 2` and `bᵢ = (2Vᵢ - Z0ᵢ δᵢⱼ) / (2 sqrt(Z0ᵢ))`, so between lumped ports `Sᵢⱼ = 2Vᵢ / sqrt(Z0ᵢ Z0ⱼ) - δᵢⱼ`. At exactly a wave port's cutoff `βᵢ = 0`, `Zᵢ` is -infinite and the S-parameters are undefined, so this throws an `ArgumentError`. +infinite and the S-parameters are undefined, so this throws an `ArgumentError`; so does `ω = 0` with a wave port, whose +`Zᵢ` is infinite below cutoff. """ function s_parameters(model, ω::Real, U::AbstractMatrix) ω = float(ω) diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index ad36665e..ec3fab82 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -255,3 +255,10 @@ end model = MaxwellModel(grid; pec = walls, ports = Iterators.Stateful(ports), eps0 = 1.0, mu0 = 1.0) @test length(model.ports) == 2 end + +@testset "wave port S-parameters at zero frequency are rejected, not NaN" begin + model = wr90(5.0, 10.0) + U = zeros(ComplexF64, ndofs(model.dh), 2) + @test_throws "ω = 0" FiniteElementMethod.s_parameters(model, 0.0, U) + @test_throws "ω = 0" FiniteElementMethod.port_excitations(model, 0.0) +end From 2f1377ed954c05ac7412df6f3f6dd9e0280aa40c Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:09:44 +0000 Subject: [PATCH 08/11] Wave ports: explain the zero-frequency guard by the singular normalisation At omega = 0 the propagation constant is -i kc and the wave impedance is 0, not infinite; the power-wave amplitude factor sqrt(beta/(omega mu)) diverges. The infinite-impedance explanation is kept for exact cutoff only. The guard and its tests are unchanged apart from the message match. 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 | 3 ++- src/maxwell/ports.jl | 14 ++++++++------ test/Maxwell/ports.jl | 4 ++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 44b115b2..03756eb7 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -70,7 +70,8 @@ current `I/w` along `direction`; its voltage is the sheet average of the line in `iωμ0 L/(w² Z0) g gᵀ` (`gᵢ = ∮ l̂⋅Nᵢ dS`) to the operator, and the driven port adds a 1 A current source in parallel, so `Sᵢⱼ = 2Vᵢ/sqrt(Z0ᵢZ0ⱼ) - δᵢⱼ`. Because the load, the source and the voltage use the same `g`, these circuit identities hold exactly for the discrete system: a lossless structure gives a unitary `S`. -Wave and lumped ports can share one model and one sweep, both normalised to power waves. +Wave and lumped ports can share one model and one sweep; lumped ports and propagating wave ports are +normalised to power waves. ```julia using FiniteElementMethod, Ferrite diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 25098e15..111e4b4f 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -242,12 +242,13 @@ end _excitation(model, data::WavePortData, ω) = (2im * _propagation_constant(data, model.mu0 * model.eps0, ω) * model.length_scale / data.mu_r) .* data.profile -# The propagation constants of the wave ports at ω. At ω = 0 and at exact cutoff β = 0, the wave impedance ωμ/β is infinite and the -# power-wave scale of the S-parameters is 0/0, so it is an error rather than a NaN matrix. +# The S-parameter normalisation scales a wave port by sqrt(β/(ωμ)). At exact cutoff β = 0 the wave impedance ωμ/β is +# infinite and the scale is 0/0; at ω = 0, β = -i kc and Z = ωμ/β is 0, and the scale diverges. Both are an error +# rather than a NaN matrix. function _check_not_at_cutoff(model, ω) for (j, data) in pairs(model.ports) data isa WavePortData && iszero(ω) && throw( - ArgumentError("ω = 0 is below the TE10 cutoff of wave port $j, where its wave impedance is infinite and its S-parameters are undefined; use a positive frequency") + ArgumentError("ω = 0 is not supported for wave port $j: the amplitude factor sqrt(β/(ωμ)) of its S-parameter normalisation diverges there; use a positive frequency") ) data isa WavePortData && iszero(_propagation_constant(data, model.mu0 * model.eps0, float(ω))) && throw( ArgumentError("ω = $ω is exactly the TE10 cutoff of wave port $j, where its wave impedance is infinite and its S-parameters are undefined; use a nearby frequency") @@ -274,7 +275,8 @@ function port_excitations(model, ω::Real) return B end -# Power waves (peak phasors, |a|²/2 watts) of a port for the excitation of `port_excitations`: the incident +# Wave coefficients of a port for the excitation of `port_excitations`, power waves (peak phasors, |a|²/2 watts) for a +# lumped port and a propagating wave port, generalized traveling-wave coefficients below cutoff: the incident # wave `a` when the port is driven and the outgoing wave `b` in the solution `u`, `driven` or not. function _power_waves(model, data::WavePortData, ω, u, driven::Bool) β = _propagation_constant(data, model.mu0 * model.eps0, ω) @@ -298,8 +300,8 @@ The scattering matrix `Sᵢⱼ = bᵢ / aⱼ` from the solutions `U[:, j]` with `bᵢ = (pᵢᵀuⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ / Zᵢ) exp(iβᵢdᵢ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. A lumped port has `aⱼ = sqrt(Z0ⱼ) / 2` and `bᵢ = (2Vᵢ - Z0ᵢ δᵢⱼ) / (2 sqrt(Z0ᵢ))`, so between lumped ports `Sᵢⱼ = 2Vᵢ / sqrt(Z0ᵢ Z0ⱼ) - δᵢⱼ`. At exactly a wave port's cutoff `βᵢ = 0`, `Zᵢ` is -infinite and the S-parameters are undefined, so this throws an `ArgumentError`; so does `ω = 0` with a wave port, whose -`Zᵢ` is infinite below cutoff. +infinite and the S-parameters are undefined, so this throws an `ArgumentError`; so does `ω = 0` with a wave port, where the +normalisation factor `sqrt(βᵢ / (ωμ0μr))` diverges (`βᵢ = -iπ/(aL)` and `Zᵢ = 0` there). The wave coefficients are power waves for propagating ports only; below cutoff they are generalized traveling-wave coefficients (see [`WavePort`](@ref)). """ diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index fe588765..67a140ba 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -259,8 +259,8 @@ end @testset "wave port S-parameters at zero frequency are rejected, not NaN" begin model = wr90(5.0, 10.0) U = zeros(ComplexF64, ndofs(model.dh), 2) - @test_throws "ω = 0" FiniteElementMethod.s_parameters(model, 0.0, U) - @test_throws "ω = 0" FiniteElementMethod.port_excitations(model, 0.0) + @test_throws "ω = 0 is not supported" FiniteElementMethod.s_parameters(model, 0.0, U) + @test_throws "ω = 0 is not supported" FiniteElementMethod.port_excitations(model, 0.0) end @testset "axial power of the incident mode: propagating ports carry it, evanescent ones do not" begin From a52dd7c62da1482ac7676b52afa6df67ef42ec6f Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:09:51 +0000 Subject: [PATCH 09/11] Docstring: s_parameters coefficients are power waves for propagating ports Consistent with the below-cutoff note on WavePort. 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/ports.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 111e4b4f..c7e5c439 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -296,7 +296,7 @@ end s_parameters(model::MaxwellModel, ω, U) The scattering matrix `Sᵢⱼ = bᵢ / aⱼ` from the solutions `U[:, j]` with port `j` driven by -[`port_excitations`](@ref), in power waves. A wave port has `aⱼ = sqrt(Pⱼ / Zⱼ) exp(-iβⱼdⱼ)` and +[`port_excitations`](@ref), in wave coefficients, which are power waves for lumped ports and propagating wave ports. A wave port has `aⱼ = sqrt(Pⱼ / Zⱼ) exp(-iβⱼdⱼ)` and `bᵢ = (pᵢᵀuⱼ / Pᵢ - δᵢⱼ) sqrt(Pᵢ / Zᵢ) exp(iβᵢdᵢ)`, with `Pᵢ = ∮ e⋅e dS`, the TE10 wave impedance `Zᵢ = ωμ0μr / βᵢ` and the de-embedding distances `dᵢ`. A lumped port has `aⱼ = sqrt(Z0ⱼ) / 2` and `bᵢ = (2Vᵢ - Z0ᵢ δᵢⱼ) / (2 sqrt(Z0ᵢ))`, so between lumped ports `Sᵢⱼ = 2Vᵢ / sqrt(Z0ᵢ Z0ⱼ) - δᵢⱼ`. At exactly a wave port's cutoff `βᵢ = 0`, `Zᵢ` is From fc963b4ef01e1f3741c874e57d87d80deeec9084 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 19:18:41 +0000 Subject: [PATCH 10/11] Tests: use the verified facet node table instead of a Ferrite internal The lumped port tests read the local facet nodes from a function that is not public in Ferrite; the package's own table is now checked against the geometry in test/Maxwell/model.jl and used here. 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 --- test/Maxwell/lumped.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Maxwell/lumped.jl b/test/Maxwell/lumped.jl index df125673..fac775ab 100644 --- a/test/Maxwell/lumped.jl +++ b/test/Maxwell/lumped.jl @@ -110,7 +110,7 @@ end len, d, hz = PLATE_LEN, 6.0, 1.0 grid = generate_grid(Tetrahedron, (2, 2, round(Int, (len + d) / hz)), Vec(0.0, 0.0, 0.0), Vec(PLATE_W, PLATE_H, len + d)) plane = FacetIndex[] - for cell in 1:getncells(grid), (k, facet) in pairs(Ferrite.reference_facets(RefTetrahedron)) + for cell in 1:getncells(grid), (k, facet) in pairs(FiniteElementMethod._TET_FACET_NODES) x = getcoordinates(grid, cell) all(i -> x[i][3] ≈ len, facet) && push!(plane, FacetIndex(cell, k)) end @@ -181,8 +181,8 @@ end # Parallel normals and a matching projected area, but two halves at different heights. split = generate_grid(Tetrahedron, (2, 1, 1)) halves = [ - [f for f in getfacetset(split, "bottom") if all(x -> x[1] <= 0, getcoordinates(split, f[1])[collect(Ferrite.reference_facets(RefTetrahedron)[f[2]])])]; - [f for f in getfacetset(split, "top") if all(x -> x[1] >= 0, getcoordinates(split, f[1])[collect(Ferrite.reference_facets(RefTetrahedron)[f[2]])])] + [f for f in getfacetset(split, "bottom") if all(x -> x[1] <= 0, getcoordinates(split, f[1])[collect(FiniteElementMethod._TET_FACET_NODES[f[2]])])]; + [f for f in getfacetset(split, "top") if all(x -> x[1] >= 0, getcoordinates(split, f[1])[collect(FiniteElementMethod._TET_FACET_NODES[f[2]])])] ] addfacetset!(split, "steps", halves) @test_throws "not planar" MaxwellModel(split; ports = [LumpedPort("steps"; direction = (0, 1, 0))]) From afb1e152287b2d4bee2c8c50445e20bd6f355228 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 20:03:11 +0000 Subject: [PATCH 11/11] Port sweeps: reject zero frequency for lumped ports too At omega = 0 the Norton excitation and port loading vanish, leaving the singular curl-curl operator with a zero right-hand side, so a lumped-port sweep returned S = -I instead of failing; zero frequency is now an ArgumentError before any solve (no test or documented behaviour used it). 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/ports.jl | 3 +++ src/maxwell/sweep.jl | 6 +++++- test/Maxwell/lumped.jl | 7 +++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/maxwell/ports.jl b/src/maxwell/ports.jl index 8966cf6e..64fd729b 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -255,6 +255,9 @@ _excitation(model, data::WavePortData, ω) = # rather than a NaN matrix. function _check_not_at_cutoff(model, ω) for (j, data) in pairs(model.ports) + data isa LumpedPortData && iszero(ω) && throw( + ArgumentError("ω = 0 is not supported for lumped port $j: its excitation and loading vanish there and there is no static formulation; use a positive frequency") + ) data isa WavePortData && iszero(ω) && throw( ArgumentError("ω = 0 is not supported for wave port $j: the amplitude factor sqrt(β/(ωμ)) of its S-parameter normalisation diverges there; use a positive frequency") ) diff --git a/src/maxwell/sweep.jl b/src/maxwell/sweep.jl index a6a4f9a7..4ba063d5 100644 --- a/src/maxwell/sweep.jl +++ b/src/maxwell/sweep.jl @@ -36,11 +36,15 @@ as a [`MaxwellSweep`](@ref). Each frequency recombines the nonzero values of one [`maxwell_operator!`](@ref), applies the PEC constraints, and solves for all port excitations at once with `solver(A, B, cache)` (see [`FiniteElementMethod.umfpack_solver`](@ref)), which may keep its factorisation between frequencies in `cache`. `fields = true` keeps the solutions (`ndofs × nports` complex values per -frequency). An empty `omegas` gives an empty sweep. +frequency). An empty `omegas` gives an empty sweep. A zero frequency (no static formulation of the ports) and, with +wave ports, a negative one are an `ArgumentError`. """ function solve_sweep(model::MaxwellModel, omegas; fields::Bool = false, solver = umfpack_solver) isempty(model.ports) && throw(ArgumentError("the model has no ports")) omegas = float.(collect(omegas)) + any(iszero, omegas) && throw( + ArgumentError("a port sweep has no static (ω = 0) formulation: the ports and their excitations vanish there") + ) any(data -> data isa WavePortData, model.ports) && !all(>(0), omegas) && throw(ArgumentError("wave ports need positive frequencies, got ω = $(omegas[findfirst(<=(0), omegas)])")) np = length(model.ports) S = zeros(ComplexF64, np, np, length(omegas)) diff --git a/test/Maxwell/lumped.jl b/test/Maxwell/lumped.jl index fac775ab..22a34807 100644 --- a/test/Maxwell/lumped.jl +++ b/test/Maxwell/lumped.jl @@ -212,3 +212,10 @@ end @test norm(A * sweep.fields[k] - B) / norm(B) < 1.0e-8 end end + +@testset "zero frequency is rejected for lumped ports" begin + model = plates(4.0) + @test_throws "no static" solve_sweep(model, [F3, 0.0]) + @test_throws "ω = 0 is not supported for lumped port" FiniteElementMethod.port_excitations(model, 0.0) + @test_throws "ω = 0 is not supported for lumped port" FiniteElementMethod.s_parameters(model, 0.0, zeros(ComplexF64, ndofs(model.dh), 2)) +end