diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index e024f87..578984e 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -69,6 +69,31 @@ or a non-positive `mu_r` at a port is rejected, because the power-wave normalisa impedance and the outward power of the TE10 mode is `Re(β/μr) > 0` only for positive `μr` and `εr`. Put loss behind the port, not in its face, and a facet cannot belong to two ports or to both a port and an `absorbing` set. +## 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; lumped ports and propagating wave ports are +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 @@ -83,6 +108,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 967f4a7..93456ad 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 @@ -53,6 +53,7 @@ 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/lumped.jl") include("maxwell/ports.jl") include("maxwell/model.jl") include("maxwell/driven.jl") @@ -60,7 +61,7 @@ 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 WavePort, LumpedPort, MaxwellSweep, solve_sweep export MaxwellSensitivities, s_parameter_sensitivities, adjoint_gradient include("precompile.jl") diff --git a/src/maxwell/lumped.jl b/src/maxwell/lumped.jl new file mode 100644 index 0000000..1e3fafa --- /dev/null +++ b/src/maxwell/lumped.jl @@ -0,0 +1,164 @@ +# 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 _TET_FACET_NODES[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 = _TET_FACET_EDGE_DOFS + 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 _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̂) + (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]])) + 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 d53890a..ca70261 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(εc/μr) n × (n × E)` with `εc = εr - iσ/(ωε0)` (the outgoing root: for a negative real `εc/μr`, `-i sign(ω) sign(μr) sqrt(|εc/μr|)`), and the -[`WavePort`](@ref)s in `ports`. +[`WavePort`](@ref)s 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. @@ -70,14 +70,16 @@ sparse blocks on one sparsity pattern, each with a complex coefficient that is a mesh (so `Im(εr) = -ε''` gives the `+iω²μ0ε0L² ε''` loss term). The absorbing boundary adds `+i k0 L ∮ sqrt(εc/μr) (n × Nᵢ)⋅(n × Nⱼ) dS` (`k0 = ω sqrt(μ0 ε0)`, material of the adjacent cell) and each wave port `+i (β(ω)/μr) L p pᵀ / norm`, the rank-one term of the TE10 projection of its face (see [`WavePort`](@ref) and -[`FiniteElementMethod.WavePortData`](@ref)), whose dof pairs widen the cell-based sparsity pattern. `A` is complex -symmetric, not Hermitian. +[`FiniteElementMethod.WavePortData`](@ref)); each lumped port adds `+iω μ0 L / (w² Z0) g gᵀ` (see +[`FiniteElementMethod.LumpedPortData`](@ref)). The dof pairs of the port faces and lumped sheets 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 @@ -92,12 +94,19 @@ 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 _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 = 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))")) @@ -106,10 +115,13 @@ function MaxwellModel( ports = collect(ports) 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]] + 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(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) @@ -125,7 +137,9 @@ function MaxwellModel( Ferrite.close!(ch) cv = Ferrite.CellValues(Ferrite.QuadratureRule{RefTetrahedron}(quadrature), ip) - pattern = _sparsity_pattern(dh, [_wave_port_dofs(port, dh) for port in ports]) + lumped = Dict(i => _lumped_port_geometry(port, dh) for (i, port) in pairs(ports) if port isa LumpedPort) + wave_dofs = [_wave_port_dofs(port, dh) for port in ports if port isa WavePort] + pattern = _sparsity_pattern(dh, [[geometry.dofs for geometry in values(lumped)]; wave_dofs]) blocks = _assemble_blocks(pattern, dh, cv, cell_materials) L2 = float(length_scale)^2 k2 = mu0 * eps0 * L2 @@ -137,8 +151,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 ) @@ -183,21 +200,6 @@ function _pec_dofs(dh, grid, pec) return sort!(collect(dofs)) end -# The cell pattern of `dh` plus every pair of edge dofs within each port face: a wave port couples its whole face. -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 _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) @@ -233,8 +235,9 @@ _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`, which a wave port widens beyond that of `Ferrite.allocate_matrix(model.dh)`: make it as a copy +pattern of `model.blocks`, which a port widens beyond that of `Ferrite.allocate_matrix(model.dh)`: make it as a copy of `model.blocks.curlcurl` with its values zeroed, or with `tangential_mass` for a boundary term. + """ 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 6222bee..c90688a 100644 --- a/src/maxwell/ports.jl +++ b/src/maxwell/ports.jl @@ -254,6 +254,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, ω) @@ -261,7 +267,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) @@ -269,7 +275,7 @@ 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 @@ -277,61 +283,95 @@ end # c = pᵀu / norm the TE10 amplitude of the trace, e the mode and E0 = 1 the incident amplitude: +(iβ/μr) L p pᵀ / norm # on the operator and +2(iβ/μr) L E0 p on the load. Only the TE10 amplitude sees the port: the rest of the trace, which # is evanescent, has the natural boundary condition and absorbs no power. -function _port_term(data::WavePortData, mu0eps0, L) - return MaxwellTerm(data.coupling, ω -> im * _propagation_constant(data, mu0eps0, _nonnegative_frequency(ω)) * L / data.mu_r) +function _port_term(data::WavePortData, mu0, eps0, L) + return MaxwellTerm(data.coupling, ω -> im * _propagation_constant(data, mu0 * eps0, _nonnegative_frequency(ω)) * L / data.mu_r) end # β depends on ω², so it is the outgoing condition for ω ≥ 0 only; the operator is finite at ω = 0 (the S-parameter # normalisation is not, and the sweeps reject it). _nonnegative_frequency(ω) = ω >= 0 ? ω : throw(ArgumentError("wave ports are not defined for negative frequencies (ω = $ω): their propagation constant depends on ω² and is the outgoing condition for ω ≥ 0 only")) -# The propagation constants of all ports at ω. 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 _port_betas(model, ω) - ω > 0 || throw( - ArgumentError("ω = $ω is not supported for wave ports: the propagation constant and the S-parameter normalisation are defined for positive frequencies only, and a real system has S(-ω) = conj(S(ω))") - ) - β = [_propagation_constant(data, model.mu0 * model.eps0, float(ω)) for data in model.ports] - j = findfirst(iszero, β) - j === nothing || 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") - ) - return β +_excitation(model, data::WavePortData, ω) = + (2im * _propagation_constant(data, model.mu0 * model.eps0, ω) * model.length_scale / data.mu_r) .* data.profile +# 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 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") + ) + data isa WavePortData && ω < 0 && throw( + ArgumentError("ω = $ω is negative: wave port $j needs a positive frequency, since its propagation constant takes the positive-frequency branch and a real system has S(-ω) = conj(S(ω))") + ) + 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") + ) + end + return nothing end +# 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)) - β = _port_betas(model, ω) + _check_not_at_cutoff(model, ω) for (j, data) in pairs(model.ports) - B[:, j] .= (2im * β[j] * model.length_scale / data.mu_r) .* data.profile + B[:, j] .= _excitation(model, data, float(ω)) end return B end +# 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, ω) + # 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ᵢ`. At exactly a port's cutoff `βᵢ = 0`, `Zᵢ` is -infinite and the S-parameters are undefined, so this throws an `ArgumentError`. The wave coefficients are power -waves for propagating ports only; below cutoff they are generalized traveling-wave coefficients (see [`WavePort`](@ref)). +The scattering matrix `Sᵢⱼ = bᵢ / aⱼ` from the solutions `U[:, j]` with port `j` driven by +[`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 +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)). """ function s_parameters(model, ω::Real, U::AbstractMatrix) + ω = float(ω) + _check_not_at_cutoff(model, ω) ports = model.ports - β = _port_betas(model, ω) - # Wave scale |a|² P / Z, with Z ∝ μr / β: a power for a propagating port, a generalized coefficient below cutoff. - 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 eb526ca..dc38563 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. """ @@ -31,18 +31,28 @@ 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 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 wave ports")) + isempty(model.ports) && throw(ArgumentError("the model has no ports")) omegas = float.(collect(omegas)) - bad = findfirst(ω -> !(isfinite(ω) && ω > 0), omegas) - bad === nothing || throw(ArgumentError("wave ports need finite positive frequencies, got ω = $(omegas[bad])")) + wave = any(data -> data isa WavePortData, model.ports) + bad = findfirst(ω -> !isfinite(ω) || iszero(ω) || (wave && ω < 0), omegas) + if bad !== nothing + ω = omegas[bad] + throw( + ArgumentError( + iszero(ω) ? "a port sweep has no static (ω = 0) formulation: the ports and their excitations vanish there" : + wave ? "wave ports need finite positive frequencies, got ω = $ω" : "a port sweep needs finite frequencies, got ω = $ω" + ) + ) + end np = length(model.ports) S = zeros(ComplexF64, np, np, length(omegas)) kept = fields ? Matrix{ComplexF64}[] : nothing diff --git a/test/Maxwell/lumped.jl b/test/Maxwell/lumped.jl new file mode 100644 index 0000000..22a3480 --- /dev/null +++ b/test/Maxwell/lumped.jl @@ -0,0 +1,221 @@ +# 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(FiniteElementMethod._TET_FACET_NODES) + 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 + # 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 + 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))]) + # 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(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))]) + @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 + +@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 + +@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 diff --git a/test/Maxwell/ports.jl b/test/Maxwell/ports.jl index c48179f..d094deb 100644 --- a/test/Maxwell/ports.jl +++ b/test/Maxwell/ports.jl @@ -150,7 +150,7 @@ 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 @testset "port rim must be PEC" begin @@ -256,6 +256,13 @@ end @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 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 # Normalised guide with broad dimension a = 2, cutoff ω = π/2; the incident mode of unit amplitude is the # L² projection of the TE10 mode onto the discrete traces, with H = β/(ωμ) n × E. @@ -277,7 +284,7 @@ end model = wr90(5.0, 10.0) @test_throws "positive frequencies" solve_sweep(model, [2π * 10.0e9, -2π * 10.0e9]) @test_throws "positive frequencies" solve_sweep(model, [-2.0]) - @test_throws "not supported for wave ports" FiniteElementMethod.port_excitations(model, -2.0) + @test_throws "is negative" FiniteElementMethod.port_excitations(model, -2.0) end @testset "the absorbing boundary of a lossless negative-permittivity material is outgoing" begin