From 628b8b440db90d99ebb07ed6453e2f7081f1bd70 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 6 Nov 2026 00:42:38 +0000 Subject: [PATCH 01/26] Add a PDESystem front end for the frequency-domain Maxwell model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FEMDiscretization(Ω, t; omega, spaces = Dict(E => Nedelec{RefTetrahedron, 1}())) now makes discretize read the time-domain curl-curl equation for a vector unknown off PDEBase's strong-form analysis, check its flux tensor is curl(ν curl E), sample the coefficients per cell and return the complex LinearProblem of the equivalent MaxwellModel. The perfect conductor n × E = 0 is written with facet_normal (PDEBase#164). Additive core methods: per-cell materials for MaxwellModel and a raw-load driven_problem. The operator-level model is the test oracle. 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/boundary_conditions.md | 1 + docs/src/maxwell.md | 36 +++ src/FiniteElementMethod.jl | 9 +- src/discretization.jl | 36 ++- src/frontend.jl | 28 ++- src/maxwell/driven.jl | 17 ++ src/maxwell/frontend.jl | 380 ++++++++++++++++++++++++++++++++ src/maxwell/model.jl | 8 + test/Maxwell/frontend.jl | 225 +++++++++++++++++++ test/qa/qa.jl | 10 +- 10 files changed, 734 insertions(+), 16 deletions(-) create mode 100644 src/maxwell/frontend.jl create mode 100644 test/Maxwell/frontend.jl diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index a518493e..b42b62af 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -33,6 +33,7 @@ Restrictions of this release: - Where two Dirichlet pieces of one field meet, the condition listed last in the `PDESystem` wins. - Every field with a time derivative needs an initial condition, linear in that one field and finite at every node. - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected. + - With `omega`, a time-domain curl-curl equation for a 3-component unknown in a Nédélec space becomes a frequency-domain `LinearProblem` (see `maxwell_model`); its only boundary condition is the perfect conductor `n × E = 0`, other pieces get `n × (ν curl E) = 0`, and its coefficients are real. "Time-dependent" means boundary data that varies with time, for every condition kind. diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 01d2277d..4424f38f 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -30,6 +30,42 @@ that is a function of `ω`, so a frequency sweep only recombines nonzero values [`maxwell_operator!`](@ref), and further terms (boundary conditions, ports) are added as blocks with `FiniteElementMethod.add_term!`. +## From a PDESystem + +`FEMDiscretization(Ω, t; omega, spaces = Dict(E => Nedelec{RefTetrahedron, 1}()))` discretizes the +time-domain equation `curl(ν curl E) + a₂ ∂ₜ²E + a₁ ∂ₜE + a₀ E = f` for a vector unknown `E` at the angular +frequency `omega`, and `discretize` returns the complex `LinearProblem` that [`driven_problem`](@ref) builds +for the equivalent `MaxwellModel` (in units with `ε0 = μ0 = 1`). The operator is written with [`curl`](@ref) +and the perfect conductor with [`facet_normal`](@ref), which needs a PDEBase with facet normals. + +```julia +using FiniteElementMethod, Ferrite, ModelingToolkit, LinearAlgebra, LinearSolve +grid = generate_grid(Tetrahedron, (8, 8, 8), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0)) +Ω = MeshDomain(grid) +@parameters x y z t +@variables E(..)[1:3] +X, Ev, Dt = (x, y, z), [E(t, x, y, z)[c] for c in 1:3], Differential(t) +cc = curl(curl(Ev, X) / 2, X) # μr = 2 +eqs = [cc[c] + 4 * Dt(Dt(Ev[c])) + 0.1 * Dt(Ev[c]) ~ (c == 3) * exp(-10 * ((x - 0.5)^2 + (y - 0.5)^2)) for c in 1:3] +pec = reduce(vcat, [cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0 for Γ in boundarypieces(Ω)]) +@named sys = PDESystem(eqs, pec, [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [E(t, x, y, z)]) +disc = FEMDiscretization(Ω, t; omega = 2.0, spaces = Dict(E => Nedelec{RefTetrahedron, 1}())) +sol = solve(discretize(sys, disc)) +(; model, omega) = maxwell_model(sys, disc) +field_values(MaxwellSolution(model, omega, sol.u), [Vec(0.5, 0.5, 0.5)]).E +``` + +Coefficients are real, so a complex permittivity `ε' - iε''` is only available on the operator-level +`MaxwellModel`. Absorbing boundaries and ports are not yet part of the `PDESystem` path. + +```@docs +curl(::AbstractVector, ::NTuple{3, Any}) +facet_normal +maxwell_model +``` + +## Operator level + ```@docs MaxwellModel MaxwellMaterial diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index f25a7a4e..1197cd0e 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -11,9 +11,9 @@ module FiniteElementMethod using ADTypes: AutoForwardDiff using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets -using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron +using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron, curl using ForwardDiff: ForwardDiff -using LinearAlgebra: dot, mul!, norm +using LinearAlgebra: dot, mul!, norm, rank using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -49,11 +49,14 @@ _is_normal_derivative(op) = op isa NormalDerivative 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. +# Frequency-domain Maxwell: a separate entry point assembled directly on Ferrite; `FEMDiscretization(…; omega)` reaches it +# from a PDESystem without the scalar weak form. include("maxwell/model.jl") include("maxwell/driven.jl") +include("maxwell/frontend.jl") export MaxwellMaterial, MaxwellModel, MaxwellTerm, maxwell_operator, maxwell_operator! export MaxwellSolution, driven_problem, solve_driven, field_values +export curl, facet_normal, maxwell_model include("precompile.jl") diff --git a/src/discretization.jl b/src/discretization.jl index 44a2260f..82647de5 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -7,7 +7,8 @@ PDEBase.contains_point(grid::Ferrite.Grid, x) = _contains_point(grid, x) """ FEMDiscretization(Ω::MeshDomain, t = nothing; spaces = Dict(), regions = Dict(), quadrature = nothing, test_space = Galerkin(), ibp = Dict(), pairing = Dict(), - codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check = :warn, kwargs...) + codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check = :warn, + omega = nothing, kwargs...) Finite-element discretization of a `PDESystem` whose spatial domain is the mesh domain `Ω` (of a `Ferrite.Grid`), with time variable `t`. `discretize(pdesys, disc)` assembles the @@ -74,6 +75,12 @@ gives a `PDENoTimeSolution`. still returns full fields, with `g` at the prescribed nodes, through `sol[u]`, `sol(t, x, y)`, traces and `write_vtk`; only `sol.original_sol` and the array unknowns hold the free dofs alone. `:algebraic` is recommended. + - `omega`: an angular frequency in rad/s for the frequency-domain Maxwell path. With `omega`, + `discretize` returns the complex `LinearProblem` of [`driven_problem`](@ref) for a time-domain + curl-curl `PDESystem` with a vector unknown `E` in `spaces = Dict(E => Nedelec{RefTetrahedron, 1}())`; + see [`maxwell_model`](@ref) for the equations it accepts. `omega` must be positive and finite and + needs the time variable `t`, which the `PDESystem` is written in; `test_space`, `regions`, `ibp` and + `pairing` do not apply to it and must keep their defaults. A Nédélec space needs `omega`. - `codegen = :mtk` is reserved and raises; remaining keywords are passed to the `DAEProblem` (or `NonlinearProblem`), where a keyword given at the `discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters` are set @@ -110,6 +117,7 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization natural::Vector{Symbol} boundary_check::Symbol algebraic_abstol::Union{Symbol, Nothing, Float64} + omega::Union{Nothing, Float64} kwargs::NamedTuple end @@ -142,7 +150,8 @@ end function FEMDiscretization( domain::PDEBase.MeshDomain, time = nothing; spaces = Dict(), regions = Dict(), quadrature = nothing, test_space = Galerkin(), ibp = Dict(), pairing = Dict(), codegen::Symbol = :numeric, - dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check::Symbol = :warn, kwargs... + dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check::Symbol = :warn, + omega = nothing, kwargs... ) domain.mesh isa Ferrite.Grid || throw(ArgumentError("FEMDiscretization needs a MeshDomain of a Ferrite.Grid, got a mesh of type $(typeof(domain.mesh))")) @@ -168,14 +177,34 @@ function FEMDiscretization( ) ) _check_reserved(kwargs) + _check_omega(omega, time, spaces, test_space, regions, ibp, pairing) return FEMDiscretization{typeof(time)}( domain, time, Dict{Any, Ferrite.Interpolation}(_field_op(k) => ip for (k, ip) in spaces), Dict{Any, Any}(_field_op(k) => r for (k, r) in regions), quadrature, test_space, Dict{Any, StrongForm.IBPPolicy}(ibp), Dict{Equation, Any}(pairing), - codegen, dirichlet, unique(natural), boundary_check, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, NamedTuple(kwargs) + codegen, dirichlet, unique(natural), boundary_check, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, + omega === nothing ? nothing : Float64(omega), NamedTuple(kwargs) ) end +function _check_omega(omega, time, spaces, test_space, regions, ibp, pairing) + if omega === nothing + any(ip -> ip isa Ferrite.Nedelec, values(spaces)) && throw( + ArgumentError("a Nédélec space is discretized by the frequency-domain Maxwell path; give the angular frequency, as FEMDiscretization(Ω, t; omega, spaces)") + ) + return nothing + end + omega isa Real && isfinite(omega) && omega > 0 || + throw(ArgumentError("omega must be a positive, finite angular frequency in rad/s, got $(repr(omega))")) + time === nothing && throw( + ArgumentError("omega needs the time variable of the time-domain PDESystem, as FEMDiscretization(Ω, t; omega)") + ) + for (name, unset) in (("test_space", test_space isa Galerkin), ("regions", isempty(regions)), ("ibp", isempty(ibp)), ("pairing", isempty(pairing))) + unset || throw(ArgumentError("`$name` does not apply to the frequency-domain Maxwell path (omega); leave it at its default")) + end + return nothing +end + # `u`, `u(..)` and `u(t, x, y)` all name the dependent variable `u`. function _field_op(dv) s = unwrap(dv) @@ -208,5 +237,6 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Where two Dirichlet pieces of one field meet, the condition listed last in the `PDESystem` wins. - Every field with a time derivative needs an initial condition, linear in that one field and finite at every node. - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected. + - With `omega`, a time-domain curl-curl equation for a 3-component unknown in a Nédélec space becomes a frequency-domain `LinearProblem` (see `maxwell_model`); its only boundary condition is the perfect conductor `n × E = 0`, other pieces get `n × (ν curl E) = 0`, and its coefficients are real. """ ) diff --git a/src/frontend.jl b/src/frontend.jl index 7b052c51..74d38f52 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -469,7 +469,9 @@ state, with its symbolic tangent) and the `FEMMetadata` as its `problem_type`, s `PDETimeSeriesSolution` (`SciMLBase.wrap_sol` of the solver's solution). Nothing calls `mtkcompile`; anything it cannot discretize raises. A `disc` without a time variable lowers instead to the steady `NonlinearProblem` documented under `NonlinearProblem(pdesys, disc)`. Keywords are passed to -the `DAEProblem` after `disc.kwargs`, so a keyword given here wins; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, +the `DAEProblem` after `disc.kwargs`, so a keyword given here wins. A `disc` with `omega` returns the complex +`LinearProblem` of the frequency-domain Maxwell path instead, documented under [`maxwell_model`](@ref), with the +keywords passed to the `LinearProblem`; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, `name`, `parameters`) are rejected, and so are `tspan` (the `PDESystem`'s time domain), `u0` (its initial conditions; use `remake(prob; u0)`), `p` (its parameter defaults) and `differential_vars` (computed from the weak form). The problem carries an `abstol` vector when `disc.algebraic_abstol` @@ -488,6 +490,7 @@ size change and holds `u(t, Γ) ~ g(t)` to round-off. """ function SciMLBase.discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) _check_reserved(kwargs) + disc.omega === nothing || return _maxwell_problem(pdesys, disc; kwargs...) parts = _lower(pdesys, disc) disc.time === nothing && return _steady_problem(parts; disc.kwargs..., kwargs...) kwargs = merge(disc.kwargs, values(kwargs)) @@ -526,14 +529,24 @@ function _abstol(algebraic, ops, selfnonlinear, abstol) return (; abstol = [d ? differential : algebraic for d in ops.differential_vars]) end -SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) = - disc.time === nothing ? - throw( +# The problem constructors with no frequency-domain form. +function _reject_omega(disc, what) + disc.omega === nothing || throw( + ArgumentError("$what has no frequency-domain form; a FEMDiscretization with omega lowers to a LinearProblem through discretize(pdesys, disc)") + ) + return nothing +end + +function SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) + _reject_omega(disc, "DAEProblem") + disc.time === nothing && throw( ArgumentError( "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem, not a DAEProblem; " * - "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" + "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" ) - ) : SciMLBase.discretize(pdesys, disc; kwargs...) + ) + return SciMLBase.discretize(pdesys, disc; kwargs...) +end """ NonlinearProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) @@ -555,6 +568,7 @@ Keywords are passed to the `NonlinearProblem` after `disc.kwargs`; the keywords `differential_vars` are rejected, as for the `DAEProblem`. """ function SciMLBase.NonlinearProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) + _reject_omega(disc, "NonlinearProblem") disc.time === nothing || throw( ArgumentError( "the FEMDiscretization has the time variable $(disc.time), so it lowers to a DAEProblem; " * @@ -593,6 +607,7 @@ function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc:: "symbolic_discretize(pdesys, disc; kwargs...) takes no further positional arguments; got $(length(args))" ) ) + _reject_omega(disc, "symbolic_discretize") disc.time === nothing && throw( ArgumentError( "a steady FEMDiscretization builds no symbolic System, so it has no symbolic_discretize; " * @@ -629,6 +644,7 @@ depends on time") and time-dependent Dirichlet data ("operators needs Dirichlet constant in time"). Parameters are substituted by their values, as for the `DAEProblem`. """ function operators(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) + _reject_omega(disc, "operators") parts = _lower(pdesys, disc) (; M, K, load, nonlinear, prescribed, dirichlet_values, timedep_dirichlet) = parts.raw nonlinear && throw(ArgumentError("operators returns linear operators only, but the PDESystem has nonlinear terms")) diff --git a/src/maxwell/driven.jl b/src/maxwell/driven.jl index 3dadd4ce..fc7ee25d 100644 --- a/src/maxwell/driven.jl +++ b/src/maxwell/driven.jl @@ -60,6 +60,23 @@ function driven_problem(model::MaxwellModel, ω::Real, J) return SciMLBase.LinearProblem(A, b) end +""" + driven_problem(model::MaxwellModel, ω; load) + +The `LinearProblem` `A(ω) u = load` as for `driven_problem(model, ω, J)`, with the load vector given +directly instead of from a current density: `load` is indexed by the dofs of `model.dh`, holds +`∫ f ⋅ Nᵢ` for a source `f` of the equation divided through as in [`MaxwellModel`](@ref), and is +copied before the PEC constraints are applied. +""" +function driven_problem(model::MaxwellModel, ω::Real; load::AbstractVector{<:Number}) + length(load) == Ferrite.ndofs(model.dh) || + throw(ArgumentError("load has $(length(load)) entries but the model has $(Ferrite.ndofs(model.dh)) dofs")) + A = maxwell_operator(model, float(ω)) + b = Vector{ComplexF64}(load) + Ferrite.apply!(A, b, model.ch) + return SciMLBase.LinearProblem(A, b) +end + """ MaxwellSolution(model, omega, u) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl new file mode 100644 index 00000000..d6bab7b3 --- /dev/null +++ b/src/maxwell/frontend.jl @@ -0,0 +1,380 @@ +# PDESystem front end of the Maxwell model: `discretize` with `FEMDiscretization(…; omega)` reads the +# time-domain curl-curl equation off PDEBase's strong-form analysis, samples its coefficients per cell and +# hands them to `MaxwellModel` and `driven_problem`. It bypasses the scalar weak form, assembly and DAE path. + +""" + curl(F, (x, y, z)) + +The curl `∇ × F` of the 3-vector of symbolic expressions `F` in the coordinates `(x, y, z)`, as a vector of +`Differential` expressions, for writing the Maxwell operator in a `PDESystem`: +`curl(curl(E(t, x, y, z), (x, y, z)) / μ, (x, y, z))`. This is a method of Ferrite's (Tensors') `curl`, which +`FiniteElementMethod` re-exports, so that loading both packages leaves one `curl`. +""" +function Ferrite.curl(F::AbstractVector, x::NTuple{3, Any}) + length(F) == 3 || throw(ArgumentError("curl needs a 3-vector, got $(length(F)) components")) + D = Differential.(collect(x)) + return [D[2](F[3]) - D[3](F[2]), D[3](F[1]) - D[1](F[3]), D[1](F[2]) - D[2](F[1])] +end + +""" + facet_normal(Γ::BoundaryPiece) + +The symbolic outward unit normal of the boundary piece `Γ`, `PDEBase.normal(Γ)`, for boundary conditions +such as the perfect conductor `cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0`. It needs a PDEBase +with facet normals (SciML/PDEBase.jl#164); the name avoids DomainSets' own exported `normal`. +""" +function facet_normal(Γ::PDEBase.BoundaryPiece) + hasmethod(PDEBase.normal, Tuple{typeof(Γ)}) || throw( + ArgumentError("facet_normal needs a PDEBase with PDEBase.normal(Γ) for boundary pieces (SciML/PDEBase.jl#164)") + ) + return PDEBase.normal(Γ) +end + +# PDEBase's facet normal operator, absent before SciML/PDEBase.jl#164. +const _FacetNormal = isdefined(PDEBase, :FacetNormal) ? getfield(PDEBase, :FacetNormal) : Nothing + +# A fixed, well-spread sequence in (0, 1) for the sample points of the coefficient checks. +_spread(k) = mod(0.5 + k * 0.6180339887498949, 1.0) + +const _MAXWELL_FORM = "write the operator as curl(ν*curl(E)) with curl(F, (x, y, z)), as in curl(curl(E, X) / μ, X)" + +# Sample points of the coefficient checks: cell centroids spread through the mesh, with generic values of the +# state, gradient, time and frequency slots. +function _sample_values(grid, an, pvals, t0, scale; n = 4) + (; slots) = an + cells = unique(round.(Int, range(1, Ferrite.getncells(grid); length = n))) + k = 0 + next() = (k += 1; _spread(k)) + return map(cells) do cell + x = sum(Ferrite.getcoordinates(grid, cell)) / 4 + vals = Dict{Any, Any}(unwrap(slots.X[d]) => x[d] for d in 1:3) + vals[unwrap(slots.T)] = t0 + next() + for (p, value) in zip(slots.P, pvals) + vals[unwrap(p)] = value + end + for s in [slots.U; slots.G] + vals[unwrap(s)] = 2 * next() - 1 + end + for s in scale + vals[unwrap(s)] = 1 + next() + end + vals + end +end + +function _number(ex, vals) + value = SymbolicUtils.unwrap_const(unwrap(substitute(ex, vals; fold = Val(true)))) + value isa Number || throw(ArgumentError("a coefficient of the Maxwell equation does not evaluate to a number: $ex")) + value isa Real || throw(ArgumentError("coefficients and sources of the Maxwell equation must be real, got $value in $ex")) + return Float64(value) +end + +# `Dt(E_c)` becomes `s₁ E_c` and `Dt(Dt(E_c))` `s₂ E_c` (the phasor of exp(+iωt) has s₁ = iω, s₂ = -ω²). +_phasor(ex, t, isfield, s) = substitute(ex, _phasor_rules!(Dict{Any, Any}(), unwrap(ex), t, isfield, s)) + +function _phasor_rules!(rules, ex, t, isfield, s) + SymbolicUtils.iscall(ex) || return rules + op = SymbolicUtils.operation(ex) + if op isa Differential && isequal(op.x, t) + order, inner = 0, ex + while SymbolicUtils.iscall(inner) && SymbolicUtils.operation(inner) isa Differential && + isequal(SymbolicUtils.operation(inner).x, t) + order += SymbolicUtils.operation(inner).order + inner = unwrap(only(SymbolicUtils.arguments(inner))) + end + isfield(inner) && order <= 2 || throw( + ArgumentError("the time derivative $(Num(ex)) must be a first or second time derivative of a component of the unknown") + ) + rules[ex] = unwrap(s[order] * inner) + return rules + end + foreach(a -> _phasor_rules!(rules, unwrap(a), t, isfield, s), SymbolicUtils.arguments(ex)) + return rules +end + +# The unknown with the Nédélec space and the component of each flattened field. +function _maxwell_components(fields, replaced, disc) + nedelec = [k for (k, ip) in disc.spaces if ip isa Ferrite.Nedelec] + length(nedelec) == 1 && length(disc.spaces) == 1 || throw( + ArgumentError("omega needs one vector unknown with a Nédélec space and no other spaces, as spaces = Dict(E => Nedelec{RefTetrahedron, 1}())") + ) + E = only(nedelec) + return map(fields) do u + r = get(replaced, unwrap(u), nothing) + indexed = r === nothing ? nothing : unwrap(r) + ok = indexed !== nothing && SymbolicUtils.iscall(indexed) && SymbolicUtils.operation(indexed) === getindex && + isequal(_field_op(SymbolicUtils.arguments(indexed)[1]), E) + ok || throw( + ArgumentError( + "omega discretizes one 3-component vector unknown with a Nédélec space, as @variables E(..)[1:3]; " * + "$(Num(u)) is not a component of it" + ) + ) + Int(SymbolicUtils.unwrap_const(SymbolicUtils.arguments(indexed)[2])) + end +end + +# Field `c` of the analysis is component `c` of E. Equation `e` in slot form tests component `comps[e]`; returns ν, the reaction λ and the source in slots, +# after checking that the second-order part is curl(ν curl E) and the rest is λ E - f. +function _recognise_volume(an, samples, s) + (; slots) = an + Gs(c, b) = slots.G[(c - 1) * 3 + b] + derivs = [[Symbolics.derivative(an.flux[e][a], Gs(c, b)) for a in 1:3, c in 1:3, b in 1:3] for e in 1:3] + state = [slots.U; slots.G] + nonlinear(e) = ArgumentError("the Maxwell front end discretizes linear equations only, but equation $e is nonlinear in E") + comps = zeros(Int, 3) + nus, lambdas, sources = Num[], Num[], Num[] + for e in 1:3 + any(ex -> _depends(unwrap(ex), state), derivs[e]) && throw(nonlinear(e)) + remainder = an.remainder[e] + dU = [Symbolics.derivative(remainder, slots.U[c]) for c in 1:3] + dG = [Symbolics.derivative(remainder, g) for g in slots.G] + any(ex -> _depends(unwrap(ex), state), [dU; dG]) && throw(nonlinear(e)) + flux0 = [substitute(an.flux[e][a], Dict(unwrap(g) => 0 for g in slots.G)) for a in 1:3] + trace = [sum(derivs[e][a, c, a] for a in 1:3) for c in 1:3] + for vals in samples + B = [_number(ex, vals) for ex in derivs[e]] + tr = [_number(ex, vals) for ex in trace] + λU = [_number(ex, vals) for ex in dU] + scale = max(maximum(abs, B), maximum(abs, λU), 1.0e-300) + tol = 1.0e-10 * scale + if comps[e] == 0 + comps[e] = maximum(abs, tr) > tol ? argmax(abs.(tr)) : argmax(abs.(λU)) + maximum(abs, tr) > tol || maximum(abs, λU) > tol || + throw(ArgumentError("equation $e has neither a curl-curl nor a reaction term in E")) + end + ce = comps[e] + other = mod1(ce + 1, 3) + α, β, γ = B[other, ce, other], B[other, other, ce], B[ce, other, other] + expect = [α * (c == ce) * (a == b) + β * (b == ce) * (a == c) + γ * (a == ce) * (c == b) for a in 1:3, c in 1:3, b in 1:3] + abs(γ) > tol && throw( + ArgumentError("equation $e has a grad div E term, which has no meaning on Nédélec elements; $_MAXWELL_FORM") + ) + maximum(abs, B - expect) > tol && throw( + ArgumentError("the second-order part of equation $e is anisotropic or couples the components of E differently from curl(ν*curl(E)); $_MAXWELL_FORM") + ) + abs(β) <= tol && abs(α) > tol && throw( + ArgumentError("equation $e has the vector Laplacian of E, which is component-wise H¹ and not H(curl)-conforming; $_MAXWELL_FORM") + ) + abs(α + β) > tol && throw( + ArgumentError("the second-order part of equation $e adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $_MAXWELL_FORM") + ) + any(ex -> abs(_number(ex, vals)) > tol, flux0) && throw( + ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM") + ) + any(ex -> abs(_number(ex, vals)) > tol, dG) && throw( + ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") + ) + maximum(abs, λU[[c for c in 1:3 if c != ce]]; init = 0.0) > tol && throw( + ArgumentError("the zeroth-order term of equation $e couples the components of E; the coefficients of E and its time derivatives must be scalars") + ) + end + ce = comps[e] + push!(nus, derivs[e][mod1(ce + 1, 3), mod1(ce + 1, 3), ce]) + push!(lambdas, dU[ce]) + push!(sources, -substitute(remainder, Dict(unwrap(g) => 0 for g in state))) + end + sort(comps) == 1:3 || throw(ArgumentError("the equations test the components $comps of E; write one equation per component")) + for vals in samples, (name, exs) in (("ν", nus), ("the coefficient of E", lambdas)) + v = [_number(ex, vals) for ex in exs] + maximum(abs, v .- v[1]) <= 1.0e-10 * maximum(abs, v) || throw( + ArgumentError("$name differs between the component equations, so the medium is anisotropic; the coefficients must be scalars") + ) + end + order = invperm(comps) + λ = lambdas[1] + zero_s = Dict(unwrap(x) => 0 for x in s) + a = ( + a0 = substitute(λ, zero_s), + a1 = Symbolics.derivative(λ, s[1]), a2 = Symbolics.derivative(λ, s[2]), + ) + for vals in samples + v = Dict(vals) + lin = _number(a.a0, v) + v[unwrap(s[1])] * _number(a.a1, v) + v[unwrap(s[2])] * _number(a.a2, v) + abs(_number(λ, v) - lin) <= 1.0e-10 * max(abs(lin), 1.0) || + throw(ArgumentError("the coefficient of E is nonlinear in its time derivatives")) + end + nu = nus[1] + sources = sources[order] + for (what, ex) in ["ν" => nu; ["a coefficient" => c for c in a]; ["a source" => f for f in sources]] + _depends(unwrap(ex), [slots.T]) && throw( + ArgumentError("$what of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude") + ) + end + return (; nu, a..., sources) +end + +# n × E = 0 conditions: each residual is linear in the traces and the normal, tangential (C n = 0) and of rank 2 +# together on its piece. +function _recognise_pec(bcs, fields, pvals, ctx, domain) + U = [Symbolics.variable(:U, c) for c in 1:3] + N = [Symbolics.variable(:N, d) for d in 1:3] + byp = Dict{Symbol, Vector{Num}}() + pform = "write the perfect conductor as cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0" + for eq in bcs + res = eq.lhs - eq.rhs + pieces = _trace_pieces(res) + _walk(res) do ex + SymbolicUtils.iscall(ex) && SymbolicUtils.operation(ex) isa _FacetNormal && push!(pieces, SymbolicUtils.operation(ex).piece) + end + unique!(pieces) + length(pieces) == 1 || throw( + ArgumentError("with omega every condition must be a boundary condition on one piece, and initial conditions are not used; got $eq") + ) + Γ = only(pieces) + Γ.parent === domain || throw(ArgumentError("the boundary piece $(Γ.name) of $eq is not a piece of the FEMDiscretization's MeshDomain")) + rules = Dict{Any, Any}() + _walk(res) do ex + SymbolicUtils.iscall(ex) || return + op = SymbolicUtils.operation(ex) + if op isa Union{Differential, PDEBase.NormalDerivative} + throw(ArgumentError("$eq has a derivative; with omega only the perfect conductor n × E = 0 is supported: $pform")) + elseif op isa _FacetNormal + rules[ex] = unwrap(N[Int(SymbolicUtils.unwrap_const(only(SymbolicUtils.arguments(ex))))]) + else + f = findfirst(isequal(op), ctx.ops) + f === nothing || (rules[ex] = unwrap(U[fields[f]])) + end + end + for (p, value) in zip(ctx.params, pvals) + rules[p] = value + end + B = substitute(res, rules) + extra = [x for x in Symbolics.get_variables(B) if !any(isequal(x), unwrap.([U; N]))] + isempty(extra) || throw(ArgumentError("$eq depends on $(join(Num.(extra), ", ")); $pform")) + push!(get!(byp, Γ.name, Num[]), B) + end + for (name, Bs) in byp + C = [Symbolics.derivative(B, u) for B in Bs, u in U] + any(ex -> _depends(unwrap(ex), U), C) && throw(ArgumentError("the conditions on $name are nonlinear in E; $pform")) + for k in 1:3 + n = [2 * _spread(3k + d) - 1 for d in 1:3] + n ./= norm(n) + vals = Dict{Any, Any}(unwrap(N[d]) => n[d] for d in 1:3) + merge!(vals, Dict(unwrap(u) => 0.0 for u in U)) + any(B -> abs(_number(B, vals)) > 1.0e-12, Bs) && + throw(ArgumentError("the conditions on $name prescribe a nonzero tangential field, which is not supported; $pform")) + Cn = [_number(ex, vals) for ex in C] + maximum(abs, Cn * n) > 1.0e-10 * maximum(abs, Cn) && throw( + ArgumentError("the conditions on $name are not tangential for every normal direction, as n × E = 0 is; $pform") + ) + rank(Cn) == 2 || throw( + ArgumentError("the conditions on $name constrain $(rank(Cn)) of the two tangential components of E; $pform") + ) + end + end + pec = sort!(String.(collect(keys(byp)))) + check_facetsets(domain.mesh, Symbol.(pec); disjoint = false) + return pec +end + +""" + maxwell_model(pdesys::PDESystem, disc::FEMDiscretization) -> (; model, omega, load) + +The [`MaxwellModel`](@ref), angular frequency and load vector that `discretize(pdesys, disc)` builds for a +`disc` with `omega`, so that the solution `u` of its `LinearProblem` can be wrapped as +`MaxwellSolution(model, omega, u)` and evaluated with [`field_values`](@ref). + +The `PDESystem` is the time-domain equation for a vector unknown `E` with `spaces = Dict(E => Nedelec{RefTetrahedron, 1}())`, + + curl(ν curl E) + a₂ ∂ₜ²E + a₁ ∂ₜE + a₀ E = f, + +one equation per component, written with [`curl`](@ref). ν, a₀, a₁ and a₂ are real scalar functions of +the coordinates and parameters, and the source `f(x)` is read as the phasor amplitude of `exp(+iωt)`. Each +cell gets `MaxwellMaterial(eps_r = a₂ - a₀/ω², mu_r = 1/ν, sigma = a₁)` sampled at its centroid, with +`eps0 = mu0 = length_scale = 1`, so the system is `Kc - ω² Mε + iω Mσ` of the model and the load is +`∫ f ⋅ Nᵢ`. Boundary conditions are the perfect conductor `cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0`; +pieces without a condition get the natural `n × (ν curl E) = 0`. A complex permittivity has no real +time-domain form here; build a `MaxwellModel` directly for it. +""" +function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) + disc.omega === nothing && + throw(ArgumentError("maxwell_model needs a FEMDiscretization with omega, as FEMDiscretization(Ω, t; omega = 2π, spaces)")) + _check_domains(pdesys, disc) + grid = disc.domain.mesh + celltype = Ferrite.getcelltype(grid) + celltype === Ferrite.Tetrahedron || + throw(ArgumentError("omega needs a mesh of Tetrahedron cells, got $(celltype isa DataType ? nameof(celltype) : celltype)")) + any(dv -> dv isa Complex || eltype(SymbolicUtils.symtype(unwrap(dv))) <: Complex, pdesys.dvs) && + throw(ArgumentError("the unknown must be real: with omega the PDESystem is the real time-domain equation and the phasor is complex")) + sys, replaced = PDEBase.make_pdesys_compatible(pdesys) + v = PDEBase.VariableMap(sys, disc; replaced_vars = replaced) + fields = StrongForm.declared_fields(sys, v) + comps = _maxwell_components(fields, replaced, disc) + length(fields) == 3 && comps == 1:3 || + throw(ArgumentError("omega needs all three components of the vector unknown and no other unknowns; got $(join(Num.(fields), ", "))")) + s = collect(@parameters maxwell_dt maxwell_dt2) + ops = [SymbolicUtils.operation(unwrap(u)) for u in fields] + isfield(ex) = SymbolicUtils.iscall(ex) && any(isequal(SymbolicUtils.operation(ex)), ops) + eqs = [Num(_phasor(eq.lhs, v.time, isfield, s)) ~ Num(_phasor(eq.rhs, v.time, isfield, s)) for eq in sys.eqs] + length(eqs) == 3 || throw(ArgumentError("the system has $(length(eqs)) equations for the 3 components of the vector unknown")) + ps = sys.ps isa SciMLBase.NullParameters ? [] : collect(sys.ps) + phasor_sys = ModelingToolkit.PDESystem( + eqs, Equation[], sys.domain, sys.ivs, sys.dvs, [ps; [p => 0.0 for p in s]]; name = nameof(pdesys) + ) + pv = PDEBase.VariableMap(phasor_sys, disc; replaced_vars = replaced) + an = StrongForm.analyse(phasor_sys, pv, Dict()) + ctx = StrongForm.SlotContext(phasor_sys, pv) + pvals = _parameter_values(phasor_sys, ctx) + js = [findfirst(isequal(unwrap(p)), ctx.params) for p in s] + slot_s = an.slots.P[js] + keep = setdiff(eachindex(ctx.params), js) + t0 = first(pv.intervals[pv.time]) + samples = _sample_values(grid, an, pvals, t0, slot_s) + coeffs = _recognise_volume(an, samples, slot_s) + pec = _recognise_pec(sys.bcs, comps, pvals[keep], (; ops, params = ctx.params[keep]), disc.domain) + + # Compile the coefficients and sources as functions of the mesh coordinate. + fixed = Dict{Any, Any}(unwrap(an.slots.P[j]) => pvals[j] for j in keep) + X = an.slots.X + compile(exs) = Symbolics.build_function([substitute(ex, fixed) for ex in exs], X...; expression = Val(false))[1] + coefficient_at = compile([coeffs.nu, coeffs.a0, coeffs.a1, coeffs.a2]) + source_at = compile(coeffs.sources) + ω = disc.omega + materials = map(1:Ferrite.getncells(grid)) do cell + x = sum(Ferrite.getcoordinates(grid, cell)) / length(Ferrite.getcoordinates(grid, cell)) + nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") + iszero(nu) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero")) + MaxwellMaterial(; eps_r = a2 - a0 / ω^2, mu_r = 1 / nu, sigma = a1) + end + model = MaxwellModel( + grid; materials, pec, eps0 = 1.0, mu0 = 1.0, length_scale = 1.0, quadrature = something(disc.quadrature, 2) + ) + return (; model, omega = ω, load = _source_load(model, x -> _real_values(source_at(x...), "a source"))) +end + +function _real_values(values, what) + all(v -> v isa Real && isfinite(v), values) || + throw(ArgumentError("$what of the Maxwell equation evaluates to $values; it must be real and finite")) + return Float64.(values) +end + +# ∫ f ⋅ Nᵢ for the source f(x) of the equation. +function _source_load(model, f) + cv = model.cellvalues + n = Ferrite.getnbasefunctions(cv) + b = zeros(Ferrite.ndofs(model.dh)) + be = zeros(n) + for cc in Ferrite.CellIterator(model.dh) + Ferrite.reinit!(cv, cc) + fill!(be, 0.0) + x = Ferrite.getcoordinates(cc) + for q in 1:Ferrite.getnquadpoints(cv) + fq = Ferrite.Vec{3}(Tuple(f(Ferrite.spatial_coordinate(cv, q, x)))) + dΩ = Ferrite.getdetJdV(cv, q) + for i in 1:n + be[i] += dot(Ferrite.shape_value(cv, q, i), fq) * dΩ + end + end + Ferrite.assemble!(b, Ferrite.celldofs(cc), be) + end + return b +end + +# `discretize` with omega: the LinearProblem `A(ω) u = b` of the driven model. +function _maxwell_problem(pdesys, disc; kwargs...) + (; model, omega, load) = maxwell_model(pdesys, disc) + prob = driven_problem(model, omega; load) + kwargs = merge(disc.kwargs, values(kwargs)) + return isempty(kwargs) ? prob : SciMLBase.LinearProblem(prob.A, prob.b; kwargs...) +end diff --git a/src/maxwell/model.jl b/src/maxwell/model.jl index cf45c560..aa8f120a 100644 --- a/src/maxwell/model.jl +++ b/src/maxwell/model.jl @@ -56,6 +56,7 @@ rest of the boundary. `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. +It may also be a vector of `MaxwellMaterial`s, one per cell of `grid` in cell order. Mesh coordinates are in units of `length_scale` metres. `eps0` and `mu0` default to their SI values; `eps0 = mu0 = 1` with `length_scale = 1` gives normalised units with `c = 1`. @@ -143,6 +144,13 @@ function _cell_materials(grid, materials) return cell_materials end +function _cell_materials(grid, materials::AbstractVector{MaxwellMaterial}) + length(materials) == Ferrite.getncells(grid) || throw( + ArgumentError("materials has $(length(materials)) entries but the grid has $(Ferrite.getncells(grid)) cells; give one MaxwellMaterial per cell") + ) + return collect(materials) +end + # The edge dofs on the PEC facets: the tangential traces there are exactly these dofs. function _pec_dofs(dh, grid, pec) local_dofs = Ferrite.dirichlet_facetdof_indices(_NEDELEC) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl new file mode 100644 index 00000000..de901c65 --- /dev/null +++ b/test/Maxwell/frontend.jl @@ -0,0 +1,225 @@ +# The PDESystem front end of the Maxwell model, against the operator-level MaxwellModel as oracle. Tests with a +# perfect-conductor condition need PDEBase's facet normal (SciML/PDEBase.jl#164) and are skipped without it. +using FiniteElementMethod, Ferrite, ModelingToolkit, DomainSets, LinearAlgebra, SparseArrays, Test +using LinearSolve: LinearSolve # the default solver of the LinearProblem; its exports clash with Ferrite's +using SciMLBase: DAEProblem, LinearProblem, NonlinearProblem, discretize, solve, symbolic_discretize +using FiniteElementMethod: PDEBase +using Symbolics: expand_derivatives +include(joinpath(@__DIR__, "..", "shared", "maxwell.jl")) + +const HAS_NORMAL = hasmethod(PDEBase.normal, Tuple{PDEBase.BoundaryPiece}) +HAS_NORMAL || @warn "PDEBase has no facet normal (SciML/PDEBase.jl#164); the perfect-conductor tests are skipped" + +@parameters x y z t +@variables E(..)[1:3] +const X = (x, y, z) +const Dt = Differential(t) +Ev = [E(t, x, y, z)[c] for c in 1:3] + +# curl(ν curl E) + a₂ ∂ₜ²E + a₁ ∂ₜE + a₀ E = f on Ω, one equation per component. +function maxwell_system(Ω; nu = 1, a2 = 1, a1 = 0, a0 = 0, f = zeros(3), bcs = Equation[], ps = [], extra = c -> 0) + cc = curl(curl(Ev, X) .* nu, X) + eqs = [cc[c] + a2 * Dt(Dt(Ev[c])) + a1 * Dt(Ev[c]) + a0 * Ev[c] + extra(c) ~ f[c] for c in 1:3] + return PDESystem(eqs, bcs, [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [E(t, x, y, z)], ps; name = :maxwell) +end +edge_space() = Dict(E => Nedelec{RefTetrahedron, 1}()) +maxwell_disc(Ω, ω; kw...) = FEMDiscretization(Ω, t; omega = ω, spaces = edge_space(), kw...) + +pec_conditions(Ω, names = Symbol.(CUBE_FACES)) = + reduce(vcat, [cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0 for Γ in boundarypiece.(Ref(Ω), names)]) + +relerr(a, b) = norm(a - b) / norm(b) + +@testset "curl and the omega keyword" begin + @test isequal(curl([y, z, x], X), [Differential(y)(x) - Differential(z)(z), Differential(z)(y) - Differential(x)(x), Differential(x)(z) - Differential(y)(y)]) + @test_throws ArgumentError("curl needs a 3-vector, got 2 components") curl([x, y], X) + @test curl === Ferrite.curl # one curl with both packages loaded + Ω = MeshDomain(unit_cube(1)) + @test maxwell_disc(Ω, 2).omega === 2.0 + for bad in (0, -1.0, Inf, 1 + 2im) + @test_throws ArgumentError("omega must be a positive, finite angular frequency in rad/s, got $(repr(bad))") maxwell_disc(Ω, bad) + end + @test_throws ArgumentError("omega needs the time variable of the time-domain PDESystem, as FEMDiscretization(Ω, t; omega)") FEMDiscretization(Ω; omega = 1.0, spaces = edge_space()) + @test_throws ArgumentError("a Nédélec space is discretized by the frequency-domain Maxwell path; give the angular frequency, as FEMDiscretization(Ω, t; omega, spaces)") FEMDiscretization(Ω, t; spaces = edge_space()) + @test_throws ArgumentError("`test_space` does not apply to the frequency-domain Maxwell path (omega); leave it at its default") maxwell_disc(Ω, 1; test_space = SUPG(0.1)) + @test_throws ArgumentError("`ibp` does not apply to the frequency-domain Maxwell path (omega); leave it at its default") maxwell_disc(Ω, 1; ibp = Dict(1 => PDEBase.StrongForm.Reject())) +end + +@testset "two materials: discretize equals the operator-level model" begin + grid = unit_cube(4) + addcellset!(grid, "left", x -> x[1] <= 0.5) + addcellset!(grid, "right", x -> x[1] >= 0.5) + Ω = MeshDomain(grid) + ω = 3.0 + source(p) = [sin(π * p[2]), p[1] * p[3], 1.0] + left, right = MaxwellMaterial(; eps_r = 1.0), MaxwellMaterial(; eps_r = 4.0, mu_r = 2.0, sigma = 0.3) + piecewise(a, b) = ifelse(x < 0.5, a, b) + sys = maxwell_system( + Ω; nu = piecewise(1.0, 0.5), a2 = piecewise(1.0, 4.0), a1 = piecewise(0.0, 0.3), f = source([x, y, z]), + bcs = HAS_NORMAL ? pec_conditions(Ω) : Equation[] + ) + prob = discretize(sys, maxwell_disc(Ω, ω)) + @test prob isa LinearProblem + @test eltype(prob.A) == ComplexF64 + oracle = MaxwellModel( + grid; materials = Dict("left" => left, "right" => right), pec = HAS_NORMAL ? CUBE_FACES : String[], eps0 = 1.0, mu0 = 1.0 + ) + # -iω J = f gives the oracle's load ∫ f ⋅ Nᵢ. + expected = driven_problem(oracle, ω, p -> im .* source(p) ./ ω) + @info "Maxwell front end oracle (two materials)" relerr(prob.A, expected.A) relerr(prob.b, expected.b) pec = HAS_NORMAL + @test relerr(prob.A, expected.A) <= 1.0e-12 + @test relerr(prob.b, expected.b) <= 1.0e-12 + u = prob.A \ prob.b + @test relerr(u, expected.A \ expected.b) <= 1.0e-10 + (; model, omega, load) = maxwell_model(sys, maxwell_disc(Ω, ω)) + @test omega == ω + @test model.materials == oracle.materials + @test model.pec == sort(oracle.pec) + + # Keywords reach the LinearProblem. + @test discretize(sys, maxwell_disc(Ω, ω); alias_A = true).kwargs[:alias_A] == true +end + +@testset "parameters, a reaction term and a lossy medium" begin + grid = unit_cube(3) + Ω = MeshDomain(grid) + @parameters μ σ + ω = 2.0 + sys = maxwell_system(Ω; nu = 1 / μ, a2 = 2.5, a1 = σ, a0 = 1.5, f = [1.0, y, 0.0], ps = [μ => 4.0, σ => 0.7]) + prob = discretize(sys, maxwell_disc(Ω, ω)) + # a₀ enters as -a₀/ω² in eps_r, so that -ω² eps_r = a₀ - ω² a₂. + oracle = MaxwellModel(grid; materials = fill(MaxwellMaterial(; eps_r = 2.5 - 1.5 / ω^2, mu_r = 4.0, sigma = 0.7), getncells(grid)), eps0 = 1.0, mu0 = 1.0) + expected = driven_problem(oracle, ω, p -> im .* [1.0, p[2], 0.0] ./ ω) + @test relerr(prob.A, expected.A) <= 1.0e-12 + @test relerr(prob.b, expected.b) <= 1.0e-12 + + @test_throws ArgumentError("load has 3 entries but the model has $(ndofs(oracle.dh)) dofs") driven_problem(oracle, ω; load = zeros(3)) + @test_throws ArgumentError("materials has 1 entries but the grid has $(getncells(grid)) cells; give one MaxwellMaterial per cell") MaxwellModel( + grid; materials = [MaxwellMaterial()] + ) +end + +@testset "PEC cavity, manufactured solution" begin + if !HAS_NORMAL + @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" + else + εr, μr, ω = 2.0, 2.0, 1.0 + Es = E_smooth([x, y, z]) + f = expand_derivatives.(curl(curl(Es, X) ./ μr, X)) .- ω^2 * εr .* Es + errs = map((4, 8, 16)) do n + grid = unit_cube(n) + Ω = MeshDomain(grid) + sys = maxwell_system(Ω; nu = 1 / μr, a2 = εr, f, bcs = pec_conditions(Ω)) + disc = maxwell_disc(Ω, ω) + (; model, omega) = maxwell_model(sys, disc) + sol = solve(discretize(sys, disc)) + msol = MaxwellSolution(model, omega, sol.u) + p = Vec(0.4, 0.55, 0.6) + point = norm(collect(only(field_values(msol, [p]).E)) - E_smooth(p)) + (; hcurl_errors(model, sol.u, E_smooth)..., point) + end + hs = 1 ./ (4, 8, 16) + @info "Maxwell front end MMS (PEC cavity)" errs rates(getfield.(errs, :hcurl), hs) + @test all(>=(0.9), rates(getfield.(errs, :hcurl), hs)) + @test all(>=(0.9), rates(getfield.(errs, :l2), hs)) + @test last(errs).point < first(errs).point / 2 + end +end + +@testset "rejections of the volume equation" begin + Ω = MeshDomain(unit_cube(1)) + D = Differential.(collect(X)) + form = "write the operator as curl(ν*curl(E)) with curl(F, (x, y, z)), as in curl(curl(E, X) / μ, X)" + err(msg; kw...) = @test_throws ArgumentError(msg) discretize(maxwell_system(Ω; kw...), maxwell_disc(Ω, 1.0)) + + laplacian(c) = -sum(D[d](D[d](Ev[c])) for d in 1:3) + @test_throws ArgumentError("equation 1 has the vector Laplacian of E, which is component-wise H¹ and not H(curl)-conforming; $form") discretize( + maxwell_system(Ω; nu = 0, extra = laplacian), maxwell_disc(Ω, 1.0) + ) + err("the second-order part of equation 1 adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $form"; extra = laplacian) + graddiv(c) = -D[c](sum(D[d](Ev[d]) for d in 1:3)) + err("equation 1 has a grad div E term, which has no meaning on Nédélec elements; $form"; extra = graddiv) + # The expanded curl curl, ∂ᵢ∂ⱼEⱼ - ΔEᵢ, has the grad div flux and is rejected too. + err("equation 1 has a grad div E term, which has no meaning on Nédélec elements; $form"; nu = 0, extra = c -> laplacian(c) - graddiv(c)) + err("the second-order part of equation 1 is anisotropic or couples the components of E differently from curl(ν*curl(E)); $form"; nu = [1.0, 2.0, 3.0]) + err("equation 1 has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $form"; extra = c -> D[1](Ev[c])) + # ∂ₓ∂ₓ(x Eᶜ) - ∂ₓ(x ∂ₓEᶜ) leaves the flux Eᶜ, which is first order. + err("equation 1 has a first-order term inside a derivative; $form"; extra = c -> D[1](D[1](x * Ev[c])) - D[1](x * D[1](Ev[c]))) + err("the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars"; extra = c -> Ev[mod1(c + 1, 3)]) + err("the coefficient of E differs between the component equations, so the medium is anisotropic; the coefficients must be scalars"; extra = c -> c * Ev[c]) + err("the Maxwell front end discretizes linear equations only, but equation 1 is nonlinear in E"; extra = c -> Ev[c]^3) + err("the Maxwell front end discretizes linear equations only, but equation 1 is nonlinear in E"; nu = 1 + Ev[1]^2) + err("the coefficient of E is nonlinear in its time derivatives"; a2 = 0, extra = c -> Dt(Ev[c]) * Dt(Ev[c]) / Ev[c]) + err("a source of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude"; f = [sin(t), 0, 0]) + err("a coefficient of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude"; a2 = 1 + t) + err("ν = 0.0 in cell 1; ν = 1/μ must be nonzero"; nu = 0) + @test_throws ArgumentError discretize(maxwell_system(Ω; extra = c -> Dt(Dt(Dt(Ev[c])))), maxwell_disc(Ω, 1.0)) +end + +@testset "rejections of the unknowns, spaces and mesh" begin + Ω = MeshDomain(unit_cube(1)) + sys = maxwell_system(Ω) + @test_throws ArgumentError("omega needs one vector unknown with a Nédélec space and no other spaces, as spaces = Dict(E => Nedelec{RefTetrahedron, 1}())") discretize( + sys, FEMDiscretization(Ω, t; omega = 1.0) + ) + @test_throws ArgumentError("omega needs one vector unknown with a Nédélec space and no other spaces, as spaces = Dict(E => Nedelec{RefTetrahedron, 1}())") discretize( + sys, FEMDiscretization(Ω, t; omega = 1.0, spaces = Dict(E => Lagrange{RefTetrahedron, 1}()^3)) + ) + + @variables u(..) q(..) + lap(w) = sum(Differential(s)(Differential(s)(w)) for s in X) + scalar = PDESystem([Dt(u(t, x, y, z)) ~ lap(u(t, x, y, z))], Equation[], [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [u(t, x, y, z)], []; name = :scalar) + @test_throws ArgumentError("omega discretizes one 3-component vector unknown with a Nédélec space, as @variables E(..)[1:3]; u(t, x, y, z) is not a component of it") discretize( + scalar, FEMDiscretization(Ω, t; omega = 1.0, spaces = Dict(u => Nedelec{RefTetrahedron, 1}())) + ) + @variables w(..)::Complex + complex_sys = PDESystem([Dt(w(t, x, y, z)) ~ lap(w(t, x, y, z))], Equation[], [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [w(t, x, y, z)], []; name = :complex_sys) + @test_throws ArgumentError("the unknown must be real: with omega the PDESystem is the real time-domain equation and the phasor is complex") discretize( + complex_sys, FEMDiscretization(Ω, t; omega = 1.0, spaces = Dict(w => Nedelec{RefTetrahedron, 1}())) + ) + cc = curl(curl(Ev, X), X) + mixed = PDESystem( + [[cc[c] + Dt(Dt(Ev[c])) ~ q(t, x, y, z) for c in 1:3]; Dt(q(t, x, y, z)) ~ lap(q(t, x, y, z))], Equation[], + [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [E(t, x, y, z), q(t, x, y, z)], []; name = :mixed + ) + @test_throws ArgumentError("omega discretizes one 3-component vector unknown with a Nédélec space, as @variables E(..)[1:3]; q(t, x, y, z) is not a component of it") discretize( + mixed, maxwell_disc(Ω, 1.0) + ) + two = PDESystem(cc[1:2] .+ Dt.(Dt.(Ev[1:2])) .~ 0, Equation[], [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [E(t, x, y, z)], []; name = :two) + @test_throws ArgumentError("the system has 2 equations for the 3 components of the vector unknown") discretize(two, maxwell_disc(Ω, 1.0)) + + hexes = MeshDomain(generate_grid(Hexahedron, (1, 1, 1))) + @test_throws ArgumentError("omega needs a mesh of Tetrahedron cells, got Hexahedron") discretize( + maxwell_system(hexes), FEMDiscretization(hexes, t; omega = 1.0, spaces = Dict(E => Nedelec{RefHexahedron, 1}())) + ) + + disc = maxwell_disc(Ω, 1.0) + for (f, what) in ((DAEProblem, "DAEProblem"), (NonlinearProblem, "NonlinearProblem"), (symbolic_discretize, "symbolic_discretize"), (FiniteElementMethod.operators, "operators")) + @test_throws ArgumentError("$what has no frequency-domain form; a FEMDiscretization with omega lowers to a LinearProblem through discretize(pdesys, disc)") f(sys, disc) + end + @test_throws ArgumentError("maxwell_model needs a FEMDiscretization with omega, as FEMDiscretization(Ω, t; omega = 2π, spaces)") maxwell_model(sys, FEMDiscretization(Ω, t)) + + initial = maxwell_system(Ω; bcs = [E(0, x, y, z)[c] ~ 0 for c in 1:3]) + @test_throws ArgumentError("with omega every condition must be a boundary condition on one piece, and initial conditions are not used; got $(first(PDEBase.make_pdesys_compatible(initial)[1].bcs))") discretize(initial, disc) +end + +@testset "rejections of the boundary conditions" begin + if !HAS_NORMAL + @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" + else + Ω = MeshDomain(unit_cube(1)) + Γ = boundarypiece(Ω, :left) + n = facet_normal(Γ) + Etr = [E(t, Γ)[c] for c in 1:3] + pform = "write the perfect conductor as cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0" + bad(bcs) = discretize(maxwell_system(Ω; bcs), maxwell_disc(Ω, 1.0)) + @test bad(cross(Etr, n) .~ 0) isa LinearProblem + @test_throws ArgumentError("the conditions on left are not tangential for every normal direction, as n × E = 0 is; $pform") bad([Etr[1] ~ 0]) + @test_throws ArgumentError("the conditions on left constrain 1 of the two tangential components of E; $pform") bad([cross(n, Etr)[1] ~ 0]) + @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ [1.0, 0, 0]) + @test_throws ArgumentError("the conditions on left are nonlinear in E; $pform") bad(cross(n, Etr .^ 2) .~ 0) + @test_throws ArgumentError bad([NormalDerivative(Γ)(Etr[1]) ~ 0]) + other = MeshDomain(unit_cube(1)) + @test_throws ArgumentError bad(cross(facet_normal(boundarypiece(other, :left)), [E(t, boundarypiece(other, :left))[c] for c in 1:3]) .~ 0) + end +end diff --git a/test/qa/qa.jl b/test/qa/qa.jl index 7f37253e..0dec6349 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -14,7 +14,8 @@ const LTS_MTK_OWNER = VERSION < v"1.11" ? (:ProblemTypeCtx, :t_nounits) : () run_qa( FiniteElementMethod; # The PDEBase mesh-domain interface is extended by methods on the backend's mesh type, by design. - aqua_kwargs = (; piracies = (; treat_as_own = [FiniteElementMethod.Ferrite.Grid])), + # `curl` gets a method for symbolic vectors, so that it is the one `curl` with Ferrite loaded too. + aqua_kwargs = (; piracies = (; treat_as_own = [FiniteElementMethod.Ferrite.Grid, FiniteElementMethod.Ferrite.curl])), ei_kwargs = (; all_qualified_accesses_are_public = (; ignore = ( @@ -22,12 +23,13 @@ run_qa( :vertices, :reference_facets, :getrefdim, ), ), - all_explicit_imports_via_owners = (; ignore = LTS_MTK_OWNER), - all_qualified_accesses_via_owners = (; ignore = LTS_MTK_OWNER), + # `curl` is owned by Tensors, which Ferrite re-exports and which is not a dependency. + all_explicit_imports_via_owners = (; ignore = (LTS_MTK_OWNER..., :curl)), + all_qualified_accesses_via_owners = (; ignore = (LTS_MTK_OWNER..., :curl)), ), # The user API of a FEM model: PDEBase's mesh vocabulary and Ferrite's interpolations. reexports_allow = ( :MeshDomain, :Region, :boundarypiece, :boundarypieces, :NormalDerivative, :Lagrange, - :RefLine, :RefTriangle, :RefQuadrilateral, :RefTetrahedron, :RefHexahedron, + :RefLine, :RefTriangle, :RefQuadrilateral, :RefTetrahedron, :RefHexahedron, :curl, ), ) From 709d22d4a21661672a677f093c5c7525b71871d6 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 6 Nov 2026 00:50:45 +0000 Subject: [PATCH 02/26] Check the Maxwell coefficients at every cell centroid and reject other Nedelec spaces Codex r1: the component, isotropy and first-order checks ran at four sampled centroids, so a term confined to an unsampled region (h(x) E_2 in one equation) was silently dropped. They now run at every cell centroid, the same points the materials are sampled at, for three frequency-slot values; nonlinearity, time dependence and nonlinearity in the time derivatives are checked symbolically. A Nedelec space other than Nedelec{RefTetrahedron, 1}() is rejected instead of being replaced by it. 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/frontend.jl | 161 ++++++++++++++++----------------------- test/Maxwell/frontend.jl | 33 +++++++- 2 files changed, 99 insertions(+), 95 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index d6bab7b3..263f3520 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -33,35 +33,11 @@ end # PDEBase's facet normal operator, absent before SciML/PDEBase.jl#164. const _FacetNormal = isdefined(PDEBase, :FacetNormal) ? getfield(PDEBase, :FacetNormal) : Nothing -# A fixed, well-spread sequence in (0, 1) for the sample points of the coefficient checks. +# A fixed, well-spread sequence in (0, 1) for the generic normals of the conductor check. _spread(k) = mod(0.5 + k * 0.6180339887498949, 1.0) const _MAXWELL_FORM = "write the operator as curl(ν*curl(E)) with curl(F, (x, y, z)), as in curl(curl(E, X) / μ, X)" -# Sample points of the coefficient checks: cell centroids spread through the mesh, with generic values of the -# state, gradient, time and frequency slots. -function _sample_values(grid, an, pvals, t0, scale; n = 4) - (; slots) = an - cells = unique(round.(Int, range(1, Ferrite.getncells(grid); length = n))) - k = 0 - next() = (k += 1; _spread(k)) - return map(cells) do cell - x = sum(Ferrite.getcoordinates(grid, cell)) / 4 - vals = Dict{Any, Any}(unwrap(slots.X[d]) => x[d] for d in 1:3) - vals[unwrap(slots.T)] = t0 + next() - for (p, value) in zip(slots.P, pvals) - vals[unwrap(p)] = value - end - for s in [slots.U; slots.G] - vals[unwrap(s)] = 2 * next() - 1 - end - for s in scale - vals[unwrap(s)] = 1 + next() - end - vals - end -end - function _number(ex, vals) value = SymbolicUtils.unwrap_const(unwrap(substitute(ex, vals; fold = Val(true)))) value isa Number || throw(ArgumentError("a coefficient of the Maxwell equation does not evaluate to a number: $ex")) @@ -99,6 +75,8 @@ function _maxwell_components(fields, replaced, disc) ArgumentError("omega needs one vector unknown with a Nédélec space and no other spaces, as spaces = Dict(E => Nedelec{RefTetrahedron, 1}())") ) E = only(nedelec) + disc.spaces[E] == _NEDELEC || + throw(ArgumentError("omega supports the space Nedelec{RefTetrahedron, 1}() only, got $(disc.spaces[E])")) return map(fields) do u r = get(replaced, unwrap(u), nothing) indexed = r === nothing ? nothing : unwrap(r) @@ -114,43 +92,64 @@ function _maxwell_components(fields, replaced, disc) end end -# Field `c` of the analysis is component `c` of E. Equation `e` in slot form tests component `comps[e]`; returns ν, the reaction λ and the source in slots, -# after checking that the second-order part is curl(ν curl E) and the rest is λ E - f. -function _recognise_volume(an, samples, s) +# Field `c` of the analysis is component `c` of E. Equation `e` in slot form tests component `comps[e]`; +# returns ν, a₀, a₁, a₂ and the sources in slots, after checking at every cell centroid `xs`, and for the +# frequency slots `s` at (0, 0), (1, 0) and (0, 1), that the second-order part is curl(ν curl E) and the +# rest is λ E - f with the same scalar ν and λ in every equation. `fixed` substitutes the parameter values. +function _recognise_volume(an, s, fixed, xs) (; slots) = an Gs(c, b) = slots.G[(c - 1) * 3 + b] - derivs = [[Symbolics.derivative(an.flux[e][a], Gs(c, b)) for a in 1:3, c in 1:3, b in 1:3] for e in 1:3] state = [slots.U; slots.G] nonlinear(e) = ArgumentError("the Maxwell front end discretizes linear equations only, but equation $e is nonlinear in E") - comps = zeros(Int, 3) - nus, lambdas, sources = Num[], Num[], Num[] + timedep(what) = ArgumentError("$what of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude") + B = [[Symbolics.derivative(an.flux[e][a], Gs(c, b)) for a in 1:3, c in 1:3, b in 1:3] for e in 1:3] + dU = [[Symbolics.derivative(an.remainder[e], slots.U[c]) for c in 1:3] for e in 1:3] + dG = [[Symbolics.derivative(an.remainder[e], g) for g in slots.G] for e in 1:3] + dF = [[Symbolics.derivative(an.flux[e][a], slots.U[c]) for a in 1:3, c in 1:3] for e in 1:3] + parts(e) = [vec(B[e]); dU[e]; dG[e]; vec(dF[e])] for e in 1:3 - any(ex -> _depends(unwrap(ex), state), derivs[e]) && throw(nonlinear(e)) - remainder = an.remainder[e] - dU = [Symbolics.derivative(remainder, slots.U[c]) for c in 1:3] - dG = [Symbolics.derivative(remainder, g) for g in slots.G] - any(ex -> _depends(unwrap(ex), state), [dU; dG]) && throw(nonlinear(e)) - flux0 = [substitute(an.flux[e][a], Dict(unwrap(g) => 0 for g in slots.G)) for a in 1:3] - trace = [sum(derivs[e][a, c, a] for a in 1:3) for c in 1:3] - for vals in samples - B = [_number(ex, vals) for ex in derivs[e]] - tr = [_number(ex, vals) for ex in trace] - λU = [_number(ex, vals) for ex in dU] - scale = max(maximum(abs, B), maximum(abs, λU), 1.0e-300) - tol = 1.0e-10 * scale - if comps[e] == 0 - comps[e] = maximum(abs, tr) > tol ? argmax(abs.(tr)) : argmax(abs.(λU)) - maximum(abs, tr) > tol || maximum(abs, λU) > tol || - throw(ArgumentError("equation $e has neither a curl-curl nor a reaction term in E")) - end + any(ex -> _depends(unwrap(ex), state), parts(e)) && throw(nonlinear(e)) + any(ex -> _depends(unwrap(ex), [slots.T]), parts(e)) && throw(timedep("a coefficient")) + any(_depends(unwrap(Symbolics.derivative(ex, si)), s) for ex in dU[e], si in s) && + throw(ArgumentError("the coefficient of E is nonlinear in its time derivatives")) + end + sources = [-substitute(an.remainder[e], Dict(unwrap(g) => 0 for g in state)) for e in 1:3] + any(f -> _depends(unwrap(f), [slots.T]), sources) && throw(timedep("a source")) + + values_at = Symbolics.build_function( + [substitute(ex, fixed) for e in 1:3 for ex in parts(e)], slots.X..., s...; expression = Val(false) + )[1] + points = [(x, sv) for x in xs for sv in ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))] + function unpack(x, sv) + v = _real_values(values_at(x..., sv...), "a coefficient") + return map(0:2) do k + w = v[(48k + 1):(48k + 48)] + (B = reshape(w[1:27], 3, 3, 3), λU = w[28:30], dG = w[31:39], dF = reshape(w[40:48], 3, 3)) + end + end + comps = zeros(Int, 3) + for (x, sv) in points, (e, q) in enumerate(unpack(x, sv)) + all(!iszero, comps) && break + comps[e] == 0 || continue + tr = [sum(q.B[a, c, a] for a in 1:3) for c in 1:3] + tol = 1.0e-10 * max(maximum(abs, q.B), maximum(abs, q.λU), 1.0e-300) + comps[e] = maximum(abs, tr) > tol ? argmax(abs.(tr)) : maximum(abs, q.λU) > tol ? argmax(abs.(q.λU)) : 0 + end + e0 = findfirst(iszero, comps) + e0 === nothing || throw(ArgumentError("equation $e0 has neither a curl-curl nor a reaction term in E")) + sort(comps) == 1:3 || throw(ArgumentError("the equations test the components $comps of E; write one equation per component")) + for (x, sv) in points + nus, lambdas = zeros(3), zeros(3) + for (e, q) in enumerate(unpack(x, sv)) ce = comps[e] other = mod1(ce + 1, 3) - α, β, γ = B[other, ce, other], B[other, other, ce], B[ce, other, other] + tol = 1.0e-10 * max(maximum(abs, q.B), maximum(abs, q.λU), 1.0e-300) + α, β, γ = q.B[other, ce, other], q.B[other, other, ce], q.B[ce, other, other] expect = [α * (c == ce) * (a == b) + β * (b == ce) * (a == c) + γ * (a == ce) * (c == b) for a in 1:3, c in 1:3, b in 1:3] abs(γ) > tol && throw( ArgumentError("equation $e has a grad div E term, which has no meaning on Nédélec elements; $_MAXWELL_FORM") ) - maximum(abs, B - expect) > tol && throw( + maximum(abs, q.B - expect) > tol && throw( ArgumentError("the second-order part of equation $e is anisotropic or couples the components of E differently from curl(ν*curl(E)); $_MAXWELL_FORM") ) abs(β) <= tol && abs(α) > tol && throw( @@ -159,49 +158,25 @@ function _recognise_volume(an, samples, s) abs(α + β) > tol && throw( ArgumentError("the second-order part of equation $e adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $_MAXWELL_FORM") ) - any(ex -> abs(_number(ex, vals)) > tol, flux0) && throw( - ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM") - ) - any(ex -> abs(_number(ex, vals)) > tol, dG) && throw( + maximum(abs, q.dF) > tol && throw(ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM")) + maximum(abs, q.dG) > tol && throw( ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") ) - maximum(abs, λU[[c for c in 1:3 if c != ce]]; init = 0.0) > tol && throw( + maximum(abs, q.λU[[c for c in 1:3 if c != ce]]) > tol && throw( ArgumentError("the zeroth-order term of equation $e couples the components of E; the coefficients of E and its time derivatives must be scalars") ) + nus[e], lambdas[e] = β, q.λU[ce] + end + for (name, v) in (("ν", nus), ("the coefficient of E", lambdas)) + maximum(abs, v .- v[1]) <= 1.0e-10 * maximum(abs, v) || throw( + ArgumentError("$name differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") + ) end - ce = comps[e] - push!(nus, derivs[e][mod1(ce + 1, 3), mod1(ce + 1, 3), ce]) - push!(lambdas, dU[ce]) - push!(sources, -substitute(remainder, Dict(unwrap(g) => 0 for g in state))) - end - sort(comps) == 1:3 || throw(ArgumentError("the equations test the components $comps of E; write one equation per component")) - for vals in samples, (name, exs) in (("ν", nus), ("the coefficient of E", lambdas)) - v = [_number(ex, vals) for ex in exs] - maximum(abs, v .- v[1]) <= 1.0e-10 * maximum(abs, v) || throw( - ArgumentError("$name differs between the component equations, so the medium is anisotropic; the coefficients must be scalars") - ) - end - order = invperm(comps) - λ = lambdas[1] - zero_s = Dict(unwrap(x) => 0 for x in s) - a = ( - a0 = substitute(λ, zero_s), - a1 = Symbolics.derivative(λ, s[1]), a2 = Symbolics.derivative(λ, s[2]), - ) - for vals in samples - v = Dict(vals) - lin = _number(a.a0, v) + v[unwrap(s[1])] * _number(a.a1, v) + v[unwrap(s[2])] * _number(a.a2, v) - abs(_number(λ, v) - lin) <= 1.0e-10 * max(abs(lin), 1.0) || - throw(ArgumentError("the coefficient of E is nonlinear in its time derivatives")) - end - nu = nus[1] - sources = sources[order] - for (what, ex) in ["ν" => nu; ["a coefficient" => c for c in a]; ["a source" => f for f in sources]] - _depends(unwrap(ex), [slots.T]) && throw( - ArgumentError("$what of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude") - ) end - return (; nu, a..., sources) + ce = comps[1] + nu, λ = B[1][mod1(ce + 1, 3), mod1(ce + 1, 3), ce], dU[1][ce] + a = (a0 = substitute(λ, Dict(unwrap(x) => 0 for x in s)), a1 = Symbolics.derivative(λ, s[1]), a2 = Symbolics.derivative(λ, s[2])) + return (; nu, a..., sources = sources[invperm(comps)]) end # n × E = 0 conditions: each residual is linear in the traces and the normal, tangential (C n = 0) and of rank 2 @@ -319,20 +294,18 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio js = [findfirst(isequal(unwrap(p)), ctx.params) for p in s] slot_s = an.slots.P[js] keep = setdiff(eachindex(ctx.params), js) - t0 = first(pv.intervals[pv.time]) - samples = _sample_values(grid, an, pvals, t0, slot_s) - coeffs = _recognise_volume(an, samples, slot_s) + fixed = Dict{Any, Any}(unwrap(an.slots.P[j]) => pvals[j] for j in keep) + centroids = [sum(Ferrite.getcoordinates(grid, cell)) / 4 for cell in 1:Ferrite.getncells(grid)] + coeffs = _recognise_volume(an, slot_s, fixed, centroids) pec = _recognise_pec(sys.bcs, comps, pvals[keep], (; ops, params = ctx.params[keep]), disc.domain) # Compile the coefficients and sources as functions of the mesh coordinate. - fixed = Dict{Any, Any}(unwrap(an.slots.P[j]) => pvals[j] for j in keep) X = an.slots.X compile(exs) = Symbolics.build_function([substitute(ex, fixed) for ex in exs], X...; expression = Val(false))[1] coefficient_at = compile([coeffs.nu, coeffs.a0, coeffs.a1, coeffs.a2]) source_at = compile(coeffs.sources) ω = disc.omega - materials = map(1:Ferrite.getncells(grid)) do cell - x = sum(Ferrite.getcoordinates(grid, cell)) / length(Ferrite.getcoordinates(grid, cell)) + materials = map(enumerate(centroids)) do (cell, x) nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") iszero(nu) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero")) MaxwellMaterial(; eps_r = a2 - a0 / ω^2, mu_r = 1 / nu, sigma = a1) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index de901c65..260d90e9 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -29,6 +29,16 @@ pec_conditions(Ω, names = Symbol.(CUBE_FACES)) = reduce(vcat, [cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0 for Γ in boundarypiece.(Ref(Ω), names)]) relerr(a, b) = norm(a - b) / norm(b) +# The message of the ArgumentError that `f()` throws. +function message(f) + try + f() + catch err + err isa ArgumentError && return err.msg + rethrow() + end + return "no error" +end @testset "curl and the omega keyword" begin @test isequal(curl([y, z, x], X), [Differential(y)(x) - Differential(z)(z), Differential(z)(y) - Differential(x)(x), Differential(x)(z) - Differential(y)(y)]) @@ -146,7 +156,8 @@ end # ∂ₓ∂ₓ(x Eᶜ) - ∂ₓ(x ∂ₓEᶜ) leaves the flux Eᶜ, which is first order. err("equation 1 has a first-order term inside a derivative; $form"; extra = c -> D[1](D[1](x * Ev[c])) - D[1](x * D[1](Ev[c]))) err("the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars"; extra = c -> Ev[mod1(c + 1, 3)]) - err("the coefficient of E differs between the component equations, so the medium is anisotropic; the coefficients must be scalars"; extra = c -> c * Ev[c]) + anisotropic = "differs between the component equations at x = " + @test occursin(anisotropic, message(() -> discretize(maxwell_system(Ω; extra = c -> c * Ev[c]), maxwell_disc(Ω, 1.0)))) err("the Maxwell front end discretizes linear equations only, but equation 1 is nonlinear in E"; extra = c -> Ev[c]^3) err("the Maxwell front end discretizes linear equations only, but equation 1 is nonlinear in E"; nu = 1 + Ev[1]^2) err("the coefficient of E is nonlinear in its time derivatives"; a2 = 0, extra = c -> Dt(Ev[c]) * Dt(Ev[c]) / Ev[c]) @@ -154,6 +165,20 @@ end err("a coefficient of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude"; a2 = 1 + t) err("ν = 0.0 in cell 1; ν = 1/μ must be nonzero"; nu = 0) @test_throws ArgumentError discretize(maxwell_system(Ω; extra = c -> Dt(Dt(Dt(Ev[c])))), maxwell_disc(Ω, 1.0)) + + # Terms confined to a small ball around one interior centroid are seen: every centroid is checked. + grid = unit_cube(3) + Ωf = MeshDomain(grid) + cell = getncells(grid) ÷ 2 + 1 + xc = sum(getcoordinates(grid, cell)) / 4 + h = ifelse((x - xc[1])^2 + (y - xc[2])^2 + (z - xc[3])^2 < 1.0e-4, 1.0, 0.0) + local_term(extra) = message(() -> discretize(maxwell_system(Ωf; extra), maxwell_disc(Ωf, 1.0))) + @test local_term(c -> c == 2 ? h * Ev[2] : 0) == + "the coefficient of E differs between the component equations at x = $(Tuple(xc)), so the medium is anisotropic; the coefficients must be scalars" + @test local_term(c -> h * D[1](Ev[c])) == + "equation 1 has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $form" + @test local_term(c -> c == 1 ? h * Ev[2] : 0) == + "the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars" end @testset "rejections of the unknowns, spaces and mesh" begin @@ -188,6 +213,12 @@ end two = PDESystem(cc[1:2] .+ Dt.(Dt.(Ev[1:2])) .~ 0, Equation[], [t ∈ Interval(0.0, 1.0), (x, y, z) ∈ Ω], [t, x, y, z], [E(t, x, y, z)], []; name = :two) @test_throws ArgumentError("the system has 2 equations for the 3 components of the vector unknown") discretize(two, maxwell_disc(Ω, 1.0)) + for ip in (Nedelec{RefTriangle, 2}(), Nedelec{RefTriangle, 1}()) + @test_throws ArgumentError("omega supports the space Nedelec{RefTetrahedron, 1}() only, got $ip") discretize( + sys, FEMDiscretization(Ω, t; omega = 1.0, spaces = Dict(E => ip)) + ) + end + hexes = MeshDomain(generate_grid(Hexahedron, (1, 1, 1))) @test_throws ArgumentError("omega needs a mesh of Tetrahedron cells, got Hexahedron") discretize( maxwell_system(hexes), FEMDiscretization(hexes, t; omega = 1.0, spaces = Dict(E => Nedelec{RefHexahedron, 1}())) From 840e8f38b957c55904849043d0100d5ea33e90a8 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 6 Nov 2026 00:59:28 +0000 Subject: [PATCH 03/26] Reject Maxwell equation parts the front end would drop Codex r2: a second derivative of a field-free expression lands in the StrongForm flux, which only its E-derivatives were read from, so it vanished from the load. Now the flux at E = 0 must be symbolically zero, flux, remainder and mass may not hold Hessian or time-derivative slots, time derivatives inside spatial derivatives are rejected (in the phasor walk, and as any frequency dependence of the second- and first-order coefficients), and the PEC data at E = 0 must be symbolically zero rather than at three sampled normals. Each case is rejected with its own message. 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/frontend.jl | 24 ++++++++++++++++++++---- test/Maxwell/frontend.jl | 12 ++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 263f3520..0e77b938 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -48,10 +48,13 @@ end # `Dt(E_c)` becomes `s₁ E_c` and `Dt(Dt(E_c))` `s₂ E_c` (the phasor of exp(+iωt) has s₁ = iω, s₂ = -ω²). _phasor(ex, t, isfield, s) = substitute(ex, _phasor_rules!(Dict{Any, Any}(), unwrap(ex), t, isfield, s)) -function _phasor_rules!(rules, ex, t, isfield, s) +function _phasor_rules!(rules, ex, t, isfield, s, inside = false) SymbolicUtils.iscall(ex) || return rules op = SymbolicUtils.operation(ex) if op isa Differential && isequal(op.x, t) + inside && throw( + ArgumentError("the time derivative $(Num(ex)) is inside a spatial derivative; time derivatives may only multiply E, as in ε ∂ₜ²E + σ ∂ₜE") + ) order, inner = 0, ex while SymbolicUtils.iscall(inner) && SymbolicUtils.operation(inner) isa Differential && isequal(SymbolicUtils.operation(inner).x, t) @@ -64,7 +67,7 @@ function _phasor_rules!(rules, ex, t, isfield, s) rules[ex] = unwrap(s[order] * inner) return rules end - foreach(a -> _phasor_rules!(rules, unwrap(a), t, isfield, s), SymbolicUtils.arguments(ex)) + foreach(a -> _phasor_rules!(rules, unwrap(a), t, isfield, s, inside || op isa Differential), SymbolicUtils.arguments(ex)) return rules end @@ -92,6 +95,8 @@ function _maxwell_components(fields, replaced, disc) end end +_iszero_expr(ex) = isequal(Symbolics.simplify(Symbolics.expand(Num(ex))), Num(0)) + # Field `c` of the analysis is component `c` of E. Equation `e` in slot form tests component `comps[e]`; # returns ν, a₀, a₁, a₂ and the sources in slots, after checking at every cell centroid `xs`, and for the # frequency slots `s` at (0, 0), (1, 0) and (0, 1), that the second-order part is curl(ν curl E) and the @@ -107,9 +112,20 @@ function _recognise_volume(an, s, fixed, xs) dG = [[Symbolics.derivative(an.remainder[e], g) for g in slots.G] for e in 1:3] dF = [[Symbolics.derivative(an.flux[e][a], slots.U[c]) for a in 1:3, c in 1:3] for e in 1:3] parts(e) = [vec(B[e]); dU[e]; dG[e]; vec(dF[e])] + # Flux and remainder are then of degree one in U and G, so nothing else of them is left to discard. + allslots = Dict(unwrap(g) => 0 for g in [slots.U; slots.G; slots.H; slots.Ud]) for e in 1:3 + any(ex -> _depends(unwrap(ex), [slots.H; slots.Ud]), [an.flux[e]; an.remainder[e]; an.mass[e]]) && throw( + ArgumentError("equation $e has a term the frequency-domain Maxwell path cannot place (a second derivative outside a divergence or a leftover time derivative); $_MAXWELL_FORM") + ) + any(F -> !_iszero_expr(substitute(substitute(F, allslots), fixed)), an.flux[e]) && throw( + ArgumentError("equation $e has a derivative of an expression without E, a source inside a divergence, which is not integrated by parts; write that source term out explicitly as a function of the coordinates") + ) any(ex -> _depends(unwrap(ex), state), parts(e)) && throw(nonlinear(e)) any(ex -> _depends(unwrap(ex), [slots.T]), parts(e)) && throw(timedep("a coefficient")) + any(ex -> _depends(unwrap(ex), s), [vec(B[e]); dG[e]; vec(dF[e])]) && throw( + ArgumentError("equation $e has a time derivative inside a spatial derivative; time derivatives may only multiply E, as in ε ∂ₜ²E + σ ∂ₜE") + ) any(_depends(unwrap(Symbolics.derivative(ex, si)), s) for ex in dU[e], si in s) && throw(ArgumentError("the coefficient of E is nonlinear in its time derivatives")) end @@ -222,13 +238,13 @@ function _recognise_pec(bcs, fields, pvals, ctx, domain) for (name, Bs) in byp C = [Symbolics.derivative(B, u) for B in Bs, u in U] any(ex -> _depends(unwrap(ex), U), C) && throw(ArgumentError("the conditions on $name are nonlinear in E; $pform")) + any(B -> !_iszero_expr(substitute(B, Dict(unwrap(u) => 0 for u in U))), Bs) && + throw(ArgumentError("the conditions on $name prescribe a nonzero tangential field, which is not supported; $pform")) for k in 1:3 n = [2 * _spread(3k + d) - 1 for d in 1:3] n ./= norm(n) vals = Dict{Any, Any}(unwrap(N[d]) => n[d] for d in 1:3) merge!(vals, Dict(unwrap(u) => 0.0 for u in U)) - any(B -> abs(_number(B, vals)) > 1.0e-12, Bs) && - throw(ArgumentError("the conditions on $name prescribe a nonzero tangential field, which is not supported; $pform")) Cn = [_number(ex, vals) for ex in C] maximum(abs, Cn * n) > 1.0e-10 * maximum(abs, Cn) && throw( ArgumentError("the conditions on $name are not tangential for every normal direction, as n × E = 0 is; $pform") diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 260d90e9..3f90bb1d 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -166,6 +166,16 @@ end err("ν = 0.0 in cell 1; ν = 1/μ must be nonzero"; nu = 0) @test_throws ArgumentError discretize(maxwell_system(Ω; extra = c -> Dt(Dt(Dt(Ev[c])))), maxwell_disc(Ω, 1.0)) + # A second derivative of a field-free expression lands in the flux; it must not vanish from the load. + @test_throws ArgumentError("equation 1 has a derivative of an expression without E, a source inside a divergence, which is not integrated by parts; write that source term out explicitly as a function of the coordinates") discretize( + maxwell_system(Ω; extra = c -> 3 * D[1](D[1](x^2))), maxwell_disc(Ω, 2.0) + ) + @test discretize(maxwell_system(Ω; f = [6.0, 6.0, 6.0]), maxwell_disc(Ω, 2.0)) isa LinearProblem + @test occursin( + "is inside a spatial derivative; time derivatives may only multiply E", + message(() -> discretize(maxwell_system(Ω; extra = c -> D[1](D[1](Dt(Ev[c])))), maxwell_disc(Ω, 2.0))) + ) + # Terms confined to a small ball around one interior centroid are seen: every centroid is checked. grid = unit_cube(3) Ωf = MeshDomain(grid) @@ -249,6 +259,8 @@ end @test_throws ArgumentError("the conditions on left constrain 1 of the two tangential components of E; $pform") bad([cross(n, Etr)[1] ~ 0]) @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ [1.0, 0, 0]) @test_throws ArgumentError("the conditions on left are nonlinear in E; $pform") bad(cross(n, Etr .^ 2) .~ 0) + @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ cross(n, [1.0, 0, 0])) + @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .+ [n[2] * n[3], 0, 0] .~ 0) @test_throws ArgumentError bad([NormalDerivative(Γ)(Etr[1]) ~ 0]) other = MeshDomain(unit_cube(1)) @test_throws ArgumentError bad(cross(facet_normal(boundarypiece(other, :left)), [E(t, boundarypiece(other, :left))[c] for c in 1:3]) .~ 0) From f6ea005d06549811cc4b3aab1d1c6a3bbab27c83 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 6 Nov 2026 01:07:33 +0000 Subject: [PATCH 04/26] Check perfect-conductor conditions at the actual facet normals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex r3: the rank and tangentiality checks of the PEC conditions ran at three generic normals, so n[1] .* cross(n, E) .~ 0 on the cube's top face (n[1] = 0 there, no constraint) was imposed as full PEC. The linear map from the trace to the residuals is now evaluated at the outward normal of every facet of the piece, and must have rank 2 with n in its null space, i.e. be equivalent to n × E = 0 there. 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/frontend.jl | 38 +++++++++++++++++--------------------- test/Maxwell/frontend.jl | 16 ++++++++++++++-- 2 files changed, 31 insertions(+), 23 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 0e77b938..daf3cb07 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -33,18 +33,17 @@ end # PDEBase's facet normal operator, absent before SciML/PDEBase.jl#164. const _FacetNormal = isdefined(PDEBase, :FacetNormal) ? getfield(PDEBase, :FacetNormal) : Nothing -# A fixed, well-spread sequence in (0, 1) for the generic normals of the conductor check. -_spread(k) = mod(0.5 + k * 0.6180339887498949, 1.0) +# The outward unit normal of every facet of the facet set `name`, with the facet. +function _facet_normals(grid, name) + fv = Ferrite.FacetValues(Ferrite.FacetQuadratureRule{RefTetrahedron}(1), Lagrange{RefTetrahedron, 1}()) + return map(collect(Ferrite.getfacetset(grid, name))) do facet + Ferrite.reinit!(fv, Ferrite.getcells(grid, facet[1]), Ferrite.getcoordinates(grid, facet[1]), facet[2]) + (collect(Ferrite.getnormal(fv, 1)), facet) + end +end const _MAXWELL_FORM = "write the operator as curl(ν*curl(E)) with curl(F, (x, y, z)), as in curl(curl(E, X) / μ, X)" -function _number(ex, vals) - value = SymbolicUtils.unwrap_const(unwrap(substitute(ex, vals; fold = Val(true)))) - value isa Number || throw(ArgumentError("a coefficient of the Maxwell equation does not evaluate to a number: $ex")) - value isa Real || throw(ArgumentError("coefficients and sources of the Maxwell equation must be real, got $value in $ex")) - return Float64(value) -end - # `Dt(E_c)` becomes `s₁ E_c` and `Dt(Dt(E_c))` `s₂ E_c` (the phasor of exp(+iωt) has s₁ = iω, s₂ = -ω²). _phasor(ex, t, isfield, s) = substitute(ex, _phasor_rules!(Dict{Any, Any}(), unwrap(ex), t, isfield, s)) @@ -235,28 +234,25 @@ function _recognise_pec(bcs, fields, pvals, ctx, domain) isempty(extra) || throw(ArgumentError("$eq depends on $(join(Num.(extra), ", ")); $pform")) push!(get!(byp, Γ.name, Num[]), B) end + check_facetsets(domain.mesh, collect(keys(byp)); disjoint = false) for (name, Bs) in byp C = [Symbolics.derivative(B, u) for B in Bs, u in U] any(ex -> _depends(unwrap(ex), U), C) && throw(ArgumentError("the conditions on $name are nonlinear in E; $pform")) any(B -> !_iszero_expr(substitute(B, Dict(unwrap(u) => 0 for u in U))), Bs) && throw(ArgumentError("the conditions on $name prescribe a nonzero tangential field, which is not supported; $pform")) - for k in 1:3 - n = [2 * _spread(3k + d) - 1 for d in 1:3] - n ./= norm(n) - vals = Dict{Any, Any}(unwrap(N[d]) => n[d] for d in 1:3) - merge!(vals, Dict(unwrap(u) => 0.0 for u in U)) - Cn = [_number(ex, vals) for ex in C] - maximum(abs, Cn * n) > 1.0e-10 * maximum(abs, Cn) && throw( - ArgumentError("the conditions on $name are not tangential for every normal direction, as n × E = 0 is; $pform") + C_at = Symbolics.build_function(vec(C), N...; expression = Val(false))[1] + for (n, facet) in _facet_normals(domain.mesh, String(name)) + Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 3) + where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" + maximum(abs, Cn * n; init = 0.0) > 1.0e-10 * maximum(abs, Cn; init = 0.0) && throw( + ArgumentError("the conditions $where constrain the normal component of E, unlike n × E = 0; $pform") ) rank(Cn) == 2 || throw( - ArgumentError("the conditions on $name constrain $(rank(Cn)) of the two tangential components of E; $pform") + ArgumentError("the conditions $where constrain $(rank(Cn)) of the two tangential components of E; $pform") ) end end - pec = sort!(String.(collect(keys(byp)))) - check_facetsets(domain.mesh, Symbol.(pec); disjoint = false) - return pec + return sort!(String.(collect(keys(byp)))) end """ diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 3f90bb1d..44318aec 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -255,8 +255,20 @@ end pform = "write the perfect conductor as cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0" bad(bcs) = discretize(maxwell_system(Ω; bcs), maxwell_disc(Ω, 1.0)) @test bad(cross(Etr, n) .~ 0) isa LinearProblem - @test_throws ArgumentError("the conditions on left are not tangential for every normal direction, as n × E = 0 is; $pform") bad([Etr[1] ~ 0]) - @test_throws ArgumentError("the conditions on left constrain 1 of the two tangential components of E; $pform") bad([cross(n, Etr)[1] ~ 0]) + # The facets of `left` have the normal -e₁, on which E₂ ~ 0 is tangential but E₁ ~ 0 is not. + @test occursin(r"^the conditions on left at facet \(\d+, \d+\) with normal \(-1\.0, -?0\.0, -?0\.0\) constrain the normal component of E", message(() -> bad([Etr[1] ~ 0]))) + @test occursin(r"^the conditions on left at facet .* constrain 1 of the two tangential components of E", message(() -> bad([cross(n, Etr)[2] ~ 0]))) + # (n × E)₁ = n₂E₃ - n₃E₂ vanishes identically where n = -e₁. + @test occursin(r"constrain 0 of the two tangential components", message(() -> bad([cross(n, Etr)[1] ~ 0]))) + @test occursin(r"constrain 1 of the two tangential components", message(() -> bad([Etr[2] ~ 0]))) + # Codex r3: a factor that vanishes on the actual normal of the piece is no conductor there. + Γt = boundarypiece(Ω, :top) + top(bcs) = discretize(maxwell_system(Ω; bcs), maxwell_disc(Ω, 1.0)) + @test occursin( + r"^the conditions on top at facet .* constrain 0 of the two tangential components of E", + message(() -> top(facet_normal(Γt)[1] .* cross(facet_normal(Γt), [E(t, Γt)[c] for c in 1:3]) .~ 0)) + ) + @test top(facet_normal(Γt)[3] .* cross(facet_normal(Γt), [E(t, Γt)[c] for c in 1:3]) .~ 0) isa LinearProblem @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ [1.0, 0, 0]) @test_throws ArgumentError("the conditions on left are nonlinear in E; $pform") bad(cross(n, Etr .^ 2) .~ 0) @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ cross(n, [1.0, 0, 0])) From 42a7fb0ee3b2a2d66f0977e99669eb86a228ab06 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 21:16:17 +0000 Subject: [PATCH 05/26] Judge a zeroth-order coupling against the zeroth-order coefficients The coupling tolerance was 1e-10 times the larger of the second-order and zeroth-order coefficients, so a large nu silently hid a coupling of the components of E in the zeroth-order term. It is now relative to the zeroth-order coefficients alone. 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/frontend.jl | 3 ++- test/Maxwell/frontend.jl | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index daf3cb07..f0e895d5 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -177,7 +177,8 @@ function _recognise_volume(an, s, fixed, xs) maximum(abs, q.dG) > tol && throw( ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") ) - maximum(abs, q.λU[[c for c in 1:3 if c != ce]]) > tol && throw( + # A coupling is judged against the zeroth-order coefficients, not against a larger second-order one. + maximum(abs, q.λU[[c for c in 1:3 if c != ce]]) > 1.0e-10 * maximum(abs, q.λU) && throw( ArgumentError("the zeroth-order term of equation $e couples the components of E; the coefficients of E and its time derivatives must be scalars") ) nus[e], lambdas[e] = β, q.λU[ce] diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 2eb5961d..600b86a5 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -176,6 +176,10 @@ end message(() -> discretize(maxwell_system(Ω; extra = c -> D[1](D[1](Dt(Ev[c])))), maxwell_disc(Ω, 2.0))) ) + # A coupling is judged against the zeroth-order coefficients, not against a much larger ν: ν = 1e12 sits + # beside a coupling of 1e-3 in a₀ = 1. + err("the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars"; nu = 1.0e12, a0 = 1.0, extra = c -> 1.0e-3 * Ev[mod1(c + 1, 3)]) + # Terms confined to a small ball around one interior centroid are seen: every centroid is checked. grid = unit_cube(3) Ωf = MeshDomain(grid) From 7dbaddc13009a606465902dfb31ea4265beb493c Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 21:24:01 +0000 Subject: [PATCH 06/26] Check first-order terms of the Maxwell equation against roundoff, not against nu The first-order checks used 1e-10 times the larger second-order or zeroth-order coefficient, so a first-order term of size 1 next to nu = 1e12 passed validation and was dropped from the model. No first-order term is allowed, so only roundoff (10 eps) of those coefficients is tolerated. 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/frontend.jl | 7 +++++-- test/Maxwell/frontend.jl | 4 ++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index f0e895d5..0d49723f 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -173,8 +173,11 @@ function _recognise_volume(an, s, fixed, xs) abs(α + β) > tol && throw( ArgumentError("the second-order part of equation $e adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $_MAXWELL_FORM") ) - maximum(abs, q.dF) > tol && throw(ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM")) - maximum(abs, q.dG) > tol && throw( + # No first-order term is allowed, so only roundoff of the larger coefficients may pass: a 1e-10 tolerance + # would hide a first-order term of size 1 next to ν = 1e12. + tol1 = 10eps() * max(maximum(abs, q.B), maximum(abs, q.λU), 1.0e-300) + maximum(abs, q.dF) > tol1 && throw(ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM")) + maximum(abs, q.dG) > tol1 && throw( ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") ) # A coupling is judged against the zeroth-order coefficients, not against a larger second-order one. diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 600b86a5..4eec6639 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -180,6 +180,10 @@ end # beside a coupling of 1e-3 in a₀ = 1. err("the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars"; nu = 1.0e12, a0 = 1.0, extra = c -> 1.0e-3 * Ev[mod1(c + 1, 3)]) + # The same for a first-order term next to a large ν. + err("equation 1 has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $form"; nu = 1.0e12, extra = c -> D[1](Ev[c])) + err("equation 1 has a first-order term inside a derivative; $form"; nu = 1.0e12, extra = c -> D[1](D[1](x * Ev[c])) - D[1](x * D[1](Ev[c]))) + # Terms confined to a small ball around one interior centroid are seen: every centroid is checked. grid = unit_cube(3) Ωf = MeshDomain(grid) From 21a4fe9196b5db08e45a8c59c39593c074c13247 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 10 Nov 2026 21:26:40 +0000 Subject: [PATCH 07/26] Judge the second-order part of the Maxwell equation against itself The second-order checks used a tolerance that included the zeroth-order coefficients, so a large reaction coefficient hid a component-wise Laplacian beside curl(nu*curl(E)). The tolerance is now relative to the second-order coefficients alone. 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/frontend.jl | 2 +- test/Maxwell/frontend.jl | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 0d49723f..71b9d7c5 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -158,7 +158,7 @@ function _recognise_volume(an, s, fixed, xs) for (e, q) in enumerate(unpack(x, sv)) ce = comps[e] other = mod1(ce + 1, 3) - tol = 1.0e-10 * max(maximum(abs, q.B), maximum(abs, q.λU), 1.0e-300) + tol = 1.0e-10 * max(maximum(abs, q.B), 1.0e-300) # the second-order part is judged against itself α, β, γ = q.B[other, ce, other], q.B[other, other, ce], q.B[ce, other, other] expect = [α * (c == ce) * (a == b) + β * (b == ce) * (a == c) + γ * (a == ce) * (c == b) for a in 1:3, c in 1:3, b in 1:3] abs(γ) > tol && throw( diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 4eec6639..e154c4a9 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -184,6 +184,9 @@ end err("equation 1 has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $form"; nu = 1.0e12, extra = c -> D[1](Ev[c])) err("equation 1 has a first-order term inside a derivative; $form"; nu = 1.0e12, extra = c -> D[1](D[1](x * Ev[c])) - D[1](x * D[1](Ev[c]))) + # Nor does a large reaction coefficient hide a component-wise Laplacian beside curl(ν*curl(E)). + err("the second-order part of equation 1 adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $form"; a0 = 1.0e12, a2 = 1.0e12, extra = laplacian) + # Terms confined to a small ball around one interior centroid are seen: every centroid is checked. grid = unit_cube(3) Ωf = MeshDomain(grid) From e9e45b7663a58bae9b6b3ef0965437fe8358d838 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:09:26 +0000 Subject: [PATCH 08/26] Maxwell front end: judge lower-order coefficients one by one, local facet normal, BigFloat omega range First-order terms, couplings of the components and per-component coefficients of E, dt E and dtt E are tested for exact symbolic zero (with only unit-scale roundoff beyond it), and the coefficients are compared across the equations order by order, so a large reaction coefficient no longer hides them. facet_normal builds its own symbolic normal when PDEBase has none, so the perfect-conductor tests run unconditionally. FEMDiscretization judges omega after conversion to Float64. Review-history labels are removed from a test comment. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/maxwell.md | 2 +- src/discretization.jl | 3 +- src/maxwell/frontend.jl | 98 +++++++++++++++++++++-------- test/Maxwell/frontend.jl | 132 ++++++++++++++++++++------------------- 4 files changed, 143 insertions(+), 92 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 4424f38f..4d4296d7 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -36,7 +36,7 @@ that is a function of `ω`, so a frequency sweep only recombines nonzero values time-domain equation `curl(ν curl E) + a₂ ∂ₜ²E + a₁ ∂ₜE + a₀ E = f` for a vector unknown `E` at the angular frequency `omega`, and `discretize` returns the complex `LinearProblem` that [`driven_problem`](@ref) builds for the equivalent `MaxwellModel` (in units with `ε0 = μ0 = 1`). The operator is written with [`curl`](@ref) -and the perfect conductor with [`facet_normal`](@ref), which needs a PDEBase with facet normals. +and the perfect conductor with [`facet_normal`](@ref). ```julia using FiniteElementMethod, Ferrite, ModelingToolkit, LinearAlgebra, LinearSolve diff --git a/src/discretization.jl b/src/discretization.jl index e3169eff..1319b926 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -194,7 +194,8 @@ function _check_omega(omega, time, spaces, test_space, regions, ibp, pairing) ) return nothing end - omega isa Real && isfinite(omega) && omega > 0 || + # The value is stored as a Float64, so a BigFloat beyond its range (1e-400, 1e400) is judged after the conversion. + omega isa Real && (w = Float64(omega); isfinite(w) && w > 0) || throw(ArgumentError("omega must be a positive, finite angular frequency in rad/s, got $(repr(omega))")) time === nothing && throw( ArgumentError("omega needs the time variable of the time-domain PDESystem, as FEMDiscretization(Ω, t; omega)") diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 71b9d7c5..20b5251b 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -16,22 +16,32 @@ function Ferrite.curl(F::AbstractVector, x::NTuple{3, Any}) return [D[2](F[3]) - D[3](F[2]), D[3](F[1]) - D[1](F[3]), D[1](F[2]) - D[2](F[1])] end +# The symbolic outward unit normal of a boundary piece, `n(d)` for its component `d`, until PDEBase provides one +# (SciML/PDEBase.jl#164). It only builds a term: `_recognise_pec` reads it off the condition. +struct PieceNormal{D <: DomainSets.Domain} <: SymbolicUtils.Operator + piece::D +end +Base.isequal(a::PieceNormal, b::PieceNormal) = isequal(a.piece, b.piece) +Base.:(==)(a::PieceNormal, b::PieceNormal) = isequal(a, b) +Base.hash(a::PieceNormal, h::UInt) = hash(a.piece, hash(PieceNormal, h)) +SymbolicUtils.isbinop(::PieceNormal) = false +Base.show(io::IO, n::PieceNormal) = print(io, "n_", n.piece.name) + """ facet_normal(Γ::BoundaryPiece) -The symbolic outward unit normal of the boundary piece `Γ`, `PDEBase.normal(Γ)`, for boundary conditions -such as the perfect conductor `cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0`. It needs a PDEBase -with facet normals (SciML/PDEBase.jl#164); the name avoids DomainSets' own exported `normal`. +The symbolic outward unit normal of the boundary piece `Γ`, as a vector of its three components, for boundary +conditions such as the perfect conductor `cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0`. It is +`PDEBase.normal(Γ)` where PDEBase defines it (SciML/PDEBase.jl#164) and a term of this package otherwise; the +name avoids DomainSets' own exported `normal`. The normal itself is read off the facets of the mesh. """ function facet_normal(Γ::PDEBase.BoundaryPiece) - hasmethod(PDEBase.normal, Tuple{typeof(Γ)}) || throw( - ArgumentError("facet_normal needs a PDEBase with PDEBase.normal(Γ) for boundary pieces (SciML/PDEBase.jl#164)") - ) - return PDEBase.normal(Γ) + hasmethod(PDEBase.normal, Tuple{typeof(Γ)}) && return PDEBase.normal(Γ) + return [Num(SymbolicUtils.term(PieceNormal(Γ), d; type = Real)) for d in 1:3] end -# PDEBase's facet normal operator, absent before SciML/PDEBase.jl#164. -const _FacetNormal = isdefined(PDEBase, :FacetNormal) ? getfield(PDEBase, :FacetNormal) : Nothing +# PDEBase's facet normal operator, once it exists (SciML/PDEBase.jl#164). +const _FacetNormal = isdefined(PDEBase, :FacetNormal) ? Union{PieceNormal, getfield(PDEBase, :FacetNormal)} : PieceNormal # The outward unit normal of every facet of the facet set `name`, with the facet. function _facet_normals(grid, name) @@ -154,7 +164,7 @@ function _recognise_volume(an, s, fixed, xs) e0 === nothing || throw(ArgumentError("equation $e0 has neither a curl-curl nor a reaction term in E")) sort(comps) == 1:3 || throw(ArgumentError("the equations test the components $comps of E; write one equation per component")) for (x, sv) in points - nus, lambdas = zeros(3), zeros(3) + nus = zeros(3) for (e, q) in enumerate(unpack(x, sv)) ce = comps[e] other = mod1(ce + 1, 3) @@ -173,31 +183,65 @@ function _recognise_volume(an, s, fixed, xs) abs(α + β) > tol && throw( ArgumentError("the second-order part of equation $e adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $_MAXWELL_FORM") ) - # No first-order term is allowed, so only roundoff of the larger coefficients may pass: a 1e-10 tolerance - # would hide a first-order term of size 1 next to ν = 1e12. - tol1 = 10eps() * max(maximum(abs, q.B), maximum(abs, q.λU), 1.0e-300) - maximum(abs, q.dF) > tol1 && throw(ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM")) - maximum(abs, q.dG) > tol1 && throw( - ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") - ) - # A coupling is judged against the zeroth-order coefficients, not against a larger second-order one. - maximum(abs, q.λU[[c for c in 1:3 if c != ce]]) > 1.0e-10 * maximum(abs, q.λU) && throw( - ArgumentError("the zeroth-order term of equation $e couples the components of E; the coefficients of E and its time derivatives must be scalars") - ) - nus[e], lambdas[e] = β, q.λU[ce] - end - for (name, v) in (("ν", nus), ("the coefficient of E", lambdas)) - maximum(abs, v .- v[1]) <= 1.0e-10 * maximum(abs, v) || throw( - ArgumentError("$name differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") - ) + nus[e] = β end + maximum(abs, nus .- nus[1]) <= 1.0e-10 * maximum(abs, nus) || throw( + ArgumentError("ν differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") + ) end + _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) ce = comps[1] nu, λ = B[1][mod1(ce + 1, 3), mod1(ce + 1, 3), ce], dU[1][ce] a = (a0 = substitute(λ, Dict(unwrap(x) => 0 for x in s)), a1 = Symbolics.derivative(λ, s[1]), a2 = Symbolics.derivative(λ, s[2])) return (; nu, a..., sources = sources[invperm(comps)]) end +# The terms of lower order than the curl-curl, each judged on its own, with exact symbolic zero tests rather than +# tolerances relative to the other coefficients, which a large one would hide behind: there is no first-order term, +# the coefficients of E, ∂ₜE and ∂ₜ²E of an equation do not couple the components, and each is the same scalar +# function in every equation. Only roundoff of an expression of unit scale counts as zero beyond the symbolic test. +function _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) + X = an.slots.X + # The indices of `exs` that are not zero. + function nonvanishing(exs) + exs = [substitute(ex, fixed) for ex in exs] + open = findall(ex -> !_iszero_expr(ex), exs) + isempty(open) && return open + f = Symbolics.build_function(exs[open], X...; expression = Val(false))[1] + big = falses(length(open)) + for x in xs + big .|= abs.(_real_values(f(x...), "a coefficient")) .> 100eps() + end + return open[big] + end + for e in 1:3 + isempty(nonvanishing(dF[e])) || + throw(ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM")) + isempty(nonvanishing(dG[e])) || throw( + ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") + ) + end + szero = Dict(unwrap(si) => 0 for si in s) + orders = (ex -> substitute(ex, szero), ex -> Symbolics.derivative(ex, s[1]), ex -> Symbolics.derivative(ex, s[2])) + for e in 1:3 + off = [order(dU[e][c]) for c in setdiff(1:3, comps[e]) for order in orders] + isempty(nonvanishing(off)) || throw( + ArgumentError("the zeroth-order term of equation $e couples the components of E; the coefficients of E and its time derivatives must be scalars") + ) + end + diag = [orders[k](dU[e][comps[e]]) for e in 1:3, k in 1:3] + f = Symbolics.build_function(substitute.(diag, Ref(fixed)), X...; expression = Val(false))[1] + for x in xs + v = reshape(_real_values(f(x...), "a coefficient"), 3, 3) + for k in 1:3, e in 2:3 + abs(v[e, k] - v[1, k]) <= 100eps() * max(abs(v[e, k]), abs(v[1, k])) || throw( + ArgumentError("the coefficient of E differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") + ) + end + end + return nothing +end + # n × E = 0 conditions: each residual is linear in the traces and the normal, tangential (C n = 0) and of rank 2 # together on its piece. function _recognise_pec(bcs, fields, pvals, ctx, domain) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index e154c4a9..f9c7ca57 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -1,5 +1,5 @@ # The PDESystem front end of the Maxwell model, against the operator-level MaxwellModel as oracle. Tests with a -# perfect-conductor condition need PDEBase's facet normal (SciML/PDEBase.jl#164) and are skipped without it. +# perfect-conductor condition use `facet_normal`. using FiniteElementMethod, Ferrite, ModelingToolkit, DomainSets, LinearAlgebra, SparseArrays, Test using LinearSolve: LinearSolve # the default solver of the LinearProblem; its exports clash with Ferrite's using SciMLBase: LinearProblem, discretize, solve, symbolic_discretize @@ -7,9 +7,6 @@ using FiniteElementMethod: PDEBase using Symbolics: expand_derivatives include(joinpath(@__DIR__, "..", "shared", "maxwell.jl")) -const HAS_NORMAL = hasmethod(PDEBase.normal, Tuple{PDEBase.BoundaryPiece}) -HAS_NORMAL || @warn "PDEBase has no facet normal (SciML/PDEBase.jl#164); the perfect-conductor tests are skipped" - @parameters x y z t @variables E(..)[1:3] const X = (x, y, z) @@ -46,7 +43,7 @@ end @test curl === Ferrite.curl # one curl with both packages loaded Ω = MeshDomain(unit_cube(1)) @test maxwell_disc(Ω, 2).omega === 2.0 - for bad in (0, -1.0, Inf, 1 + 2im) + for bad in (0, -1.0, Inf, 1 + 2im, big"1e-400", big"1e400") @test_throws ArgumentError("omega must be a positive, finite angular frequency in rad/s, got $(repr(bad))") maxwell_disc(Ω, bad) end @test_throws ArgumentError("omega needs the time variable of the time-domain PDESystem, as FEMDiscretization(Ω, t; omega)") FEMDiscretization(Ω; omega = 1.0, spaces = edge_space()) @@ -66,17 +63,17 @@ end piecewise(a, b) = ifelse(x < 0.5, a, b) sys = maxwell_system( Ω; nu = piecewise(1.0, 0.5), a2 = piecewise(1.0, 4.0), a1 = piecewise(0.0, 0.3), f = source([x, y, z]), - bcs = HAS_NORMAL ? pec_conditions(Ω) : Equation[] + bcs = pec_conditions(Ω) ) prob = discretize(sys, maxwell_disc(Ω, ω)) @test prob isa LinearProblem @test eltype(prob.A) == ComplexF64 oracle = MaxwellModel( - grid; materials = Dict("left" => left, "right" => right), pec = HAS_NORMAL ? CUBE_FACES : String[], eps0 = 1.0, mu0 = 1.0 + grid; materials = Dict("left" => left, "right" => right), pec = CUBE_FACES, eps0 = 1.0, mu0 = 1.0 ) # -iω J = f gives the oracle's load ∫ f ⋅ Nᵢ. expected = driven_problem(oracle, ω, p -> im .* source(p) ./ ω) - @info "Maxwell front end oracle (two materials)" relerr(prob.A, expected.A) relerr(prob.b, expected.b) pec = HAS_NORMAL + @info "Maxwell front end oracle (two materials)" relerr(prob.A, expected.A) relerr(prob.b, expected.b) @test relerr(prob.A, expected.A) <= 1.0e-12 @test relerr(prob.b, expected.b) <= 1.0e-12 u = prob.A \ prob.b @@ -110,30 +107,26 @@ end end @testset "PEC cavity, manufactured solution" begin - if !HAS_NORMAL - @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" - else - εr, μr, ω = 2.0, 2.0, 1.0 - Es = E_smooth([x, y, z]) - f = expand_derivatives.(curl(curl(Es, X) ./ μr, X)) .- ω^2 * εr .* Es - errs = map((4, 8, 16)) do n - grid = unit_cube(n) - Ω = MeshDomain(grid) - sys = maxwell_system(Ω; nu = 1 / μr, a2 = εr, f, bcs = pec_conditions(Ω)) - disc = maxwell_disc(Ω, ω) - (; model, omega) = maxwell_model(sys, disc) - sol = solve(discretize(sys, disc)) - msol = MaxwellSolution(model, omega, sol.u) - p = Vec(0.4, 0.55, 0.6) - point = norm(collect(only(field_values(msol, [p]).E)) - E_smooth(p)) - (; hcurl_errors(model, sol.u, E_smooth)..., point) - end - hs = 1 ./ (4, 8, 16) - @info "Maxwell front end MMS (PEC cavity)" errs rates(getfield.(errs, :hcurl), hs) - @test all(>=(0.9), rates(getfield.(errs, :hcurl), hs)) - @test all(>=(0.9), rates(getfield.(errs, :l2), hs)) - @test last(errs).point < first(errs).point / 2 + εr, μr, ω = 2.0, 2.0, 1.0 + Es = E_smooth([x, y, z]) + f = expand_derivatives.(curl(curl(Es, X) ./ μr, X)) .- ω^2 * εr .* Es + errs = map((4, 8, 16)) do n + grid = unit_cube(n) + Ω = MeshDomain(grid) + sys = maxwell_system(Ω; nu = 1 / μr, a2 = εr, f, bcs = pec_conditions(Ω)) + disc = maxwell_disc(Ω, ω) + (; model, omega) = maxwell_model(sys, disc) + sol = solve(discretize(sys, disc)) + msol = MaxwellSolution(model, omega, sol.u) + p = Vec(0.4, 0.55, 0.6) + point = norm(collect(only(field_values(msol, [p]).E)) - E_smooth(p)) + (; hcurl_errors(model, sol.u, E_smooth)..., point) end + hs = 1 ./ (4, 8, 16) + @info "Maxwell front end MMS (PEC cavity)" errs rates(getfield.(errs, :hcurl), hs) + @test all(>=(0.9), rates(getfield.(errs, :hcurl), hs)) + @test all(>=(0.9), rates(getfield.(errs, :l2), hs)) + @test last(errs).point < first(errs).point / 2 end @testset "rejections of the volume equation" begin @@ -202,6 +195,23 @@ end "the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars" end +@testset "a large reaction coefficient hides no other coefficient" begin + Ω = MeshDomain(unit_cube(2)) + D = Differential.(collect(X)) + rejected(ω; kw...) = message(() -> discretize(maxwell_system(Ω; kw...), maxwell_disc(Ω, ω))) != "no error" + # a0 - ω² a2 = 0: a first-order term must not vanish into the cancelling reaction and inertia. + @test rejected(2.0; a0 = 4.0e16, a2 = 1.0e16, extra = c -> D[1](Ev[c])) + # Couplings and component-dependent reactions next to a large a0 - ω² a2. + @test rejected(2.0; a0 = 4.0e12, a2 = 1.0e12, extra = c -> Ev[mod1(c + 1, 3)]) + @test rejected(2.0; a0 = 4.0e12, a2 = 1.0e12, extra = c -> Dt(Ev[mod1(c + 1, 3)])) + @test rejected(2.0; a0 = 4.0e12, a2 = 1.0e12, extra = c -> c * Ev[c]) + # Unequal inertia next to a large reaction. + @test rejected(2.0e6; a0 = 1.0e12, a2 = 1.0, extra = c -> (c - 1) * Dt(Dt(Ev[c]))) + @test rejected(2.0e6; a0 = 1.0e12, a2 = 1.0, extra = c -> (c - 1) * Dt(Ev[c])) + # The same large coefficients with scalar lower-order terms are fine. + @test !rejected(2.0e6; a0 = 1.0e12, a2 = 2.0, a1 = 3.0) +end + @testset "rejections of the unknowns, spaces and mesh" begin Ω = MeshDomain(unit_cube(1)) sys = maxwell_system(Ω) @@ -256,36 +266,32 @@ end end @testset "rejections of the boundary conditions" begin - if !HAS_NORMAL - @test_skip "needs PDEBase.normal (SciML/PDEBase.jl#164)" - else - Ω = MeshDomain(unit_cube(1)) - Γ = boundarypiece(Ω, :left) - n = facet_normal(Γ) - Etr = [E(t, Γ)[c] for c in 1:3] - pform = "write the perfect conductor as cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0" - bad(bcs) = discretize(maxwell_system(Ω; bcs), maxwell_disc(Ω, 1.0)) - @test bad(cross(Etr, n) .~ 0) isa LinearProblem - # The facets of `left` have the normal -e₁, on which E₂ ~ 0 is tangential but E₁ ~ 0 is not. - @test occursin(r"^the conditions on left at facet \(\d+, \d+\) with normal \(-1\.0, -?0\.0, -?0\.0\) constrain the normal component of E", message(() -> bad([Etr[1] ~ 0]))) - @test occursin(r"^the conditions on left at facet .* constrain 1 of the two tangential components of E", message(() -> bad([cross(n, Etr)[2] ~ 0]))) - # (n × E)₁ = n₂E₃ - n₃E₂ vanishes identically where n = -e₁. - @test occursin(r"constrain 0 of the two tangential components", message(() -> bad([cross(n, Etr)[1] ~ 0]))) - @test occursin(r"constrain 1 of the two tangential components", message(() -> bad([Etr[2] ~ 0]))) - # Codex r3: a factor that vanishes on the actual normal of the piece is no conductor there. - Γt = boundarypiece(Ω, :top) - top(bcs) = discretize(maxwell_system(Ω; bcs), maxwell_disc(Ω, 1.0)) - @test occursin( - r"^the conditions on top at facet .* constrain 0 of the two tangential components of E", - message(() -> top(facet_normal(Γt)[1] .* cross(facet_normal(Γt), [E(t, Γt)[c] for c in 1:3]) .~ 0)) - ) - @test top(facet_normal(Γt)[3] .* cross(facet_normal(Γt), [E(t, Γt)[c] for c in 1:3]) .~ 0) isa LinearProblem - @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ [1.0, 0, 0]) - @test_throws ArgumentError("the conditions on left are nonlinear in E; $pform") bad(cross(n, Etr .^ 2) .~ 0) - @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ cross(n, [1.0, 0, 0])) - @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .+ [n[2] * n[3], 0, 0] .~ 0) - @test_throws ArgumentError bad([NormalDerivative(Γ)(Etr[1]) ~ 0]) - other = MeshDomain(unit_cube(1)) - @test_throws ArgumentError bad(cross(facet_normal(boundarypiece(other, :left)), [E(t, boundarypiece(other, :left))[c] for c in 1:3]) .~ 0) - end + Ω = MeshDomain(unit_cube(1)) + Γ = boundarypiece(Ω, :left) + n = facet_normal(Γ) + Etr = [E(t, Γ)[c] for c in 1:3] + pform = "write the perfect conductor as cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0" + bad(bcs) = discretize(maxwell_system(Ω; bcs), maxwell_disc(Ω, 1.0)) + @test bad(cross(Etr, n) .~ 0) isa LinearProblem + # The facets of `left` have the normal -e₁, on which E₂ ~ 0 is tangential but E₁ ~ 0 is not. + @test occursin(r"^the conditions on left at facet \(\d+, \d+\) with normal \(-1\.0, -?0\.0, -?0\.0\) constrain the normal component of E", message(() -> bad([Etr[1] ~ 0]))) + @test occursin(r"^the conditions on left at facet .* constrain 1 of the two tangential components of E", message(() -> bad([cross(n, Etr)[2] ~ 0]))) + # (n × E)₁ = n₂E₃ - n₃E₂ vanishes identically where n = -e₁. + @test occursin(r"constrain 0 of the two tangential components", message(() -> bad([cross(n, Etr)[1] ~ 0]))) + @test occursin(r"constrain 1 of the two tangential components", message(() -> bad([Etr[2] ~ 0]))) + # A factor that vanishes on the actual normal of the piece is no conductor there. + Γt = boundarypiece(Ω, :top) + top(bcs) = discretize(maxwell_system(Ω; bcs), maxwell_disc(Ω, 1.0)) + @test occursin( + r"^the conditions on top at facet .* constrain 0 of the two tangential components of E", + message(() -> top(facet_normal(Γt)[1] .* cross(facet_normal(Γt), [E(t, Γt)[c] for c in 1:3]) .~ 0)) + ) + @test top(facet_normal(Γt)[3] .* cross(facet_normal(Γt), [E(t, Γt)[c] for c in 1:3]) .~ 0) isa LinearProblem + @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ [1.0, 0, 0]) + @test_throws ArgumentError("the conditions on left are nonlinear in E; $pform") bad(cross(n, Etr .^ 2) .~ 0) + @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .~ cross(n, [1.0, 0, 0])) + @test_throws ArgumentError("the conditions on left prescribe a nonzero tangential field, which is not supported; $pform") bad(cross(n, Etr) .+ [n[2] * n[3], 0, 0] .~ 0) + @test_throws ArgumentError bad([NormalDerivative(Γ)(Etr[1]) ~ 0]) + other = MeshDomain(unit_cube(1)) + @test_throws ArgumentError bad(cross(facet_normal(boundarypiece(other, :left)), [E(t, boundarypiece(other, :left))[c] for c in 1:3]) .~ 0) end From d0fe18fa2753e65da5d08e616be114323a7903c1 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:14:41 +0000 Subject: [PATCH 09/26] Maxwell front end: reject a frequency whose reaction coefficient is not representable a0/omega^2 overflows or is 0/0 for tiny omega and gave NaN operators; it is now an ArgumentError. 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/frontend.jl | 6 +++++- test/Maxwell/frontend.jl | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 20b5251b..86d12dd0 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -368,7 +368,11 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio materials = map(enumerate(centroids)) do (cell, x) nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") iszero(nu) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero")) - MaxwellMaterial(; eps_r = a2 - a0 / ω^2, mu_r = 1 / nu, sigma = a1) + eps_r = a2 - a0 / ω^2 + isfinite(eps_r) || throw( + ArgumentError("ε = a₂ - a₀/ω² = $a2 - $a0/$ω^2 in cell $cell is not representable at this tiny ω; use a larger frequency or a MaxwellModel directly") + ) + MaxwellMaterial(; eps_r, mu_r = 1 / nu, sigma = a1) end model = MaxwellModel( grid; materials, pec, eps0 = 1.0, mu0 = 1.0, length_scale = 1.0, quadrature = something(disc.quadrature, 2) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index f9c7ca57..614b52c0 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -195,6 +195,13 @@ end "the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars" end +@testset "a frequency too small for the reaction coefficient is rejected, not turned into NaN" begin + Ω = MeshDomain(unit_cube(1)) + for (ω, a0) in ((1.0e-200, 0.0), (1.0e-160, 1.0)) + @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0), maxwell_disc(Ω, ω)))) + end +end + @testset "a large reaction coefficient hides no other coefficient" begin Ω = MeshDomain(unit_cube(2)) D = Differential.(collect(X)) From 7228d185475254456446c971535c5fcebbdf0128 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:21:17 +0000 Subject: [PATCH 10/26] Maxwell front end: lower-order roundoff tolerance relative to the equation's own coefficients The absolute tolerance of the symbolic fallback depended on how an equation was scaled; it is now 100 eps of the largest coefficient of the same 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 --- src/maxwell/frontend.jl | 29 ++++++++++++++++------------- test/Maxwell/frontend.jl | 2 ++ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 86d12dd0..fae977b5 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -189,7 +189,7 @@ function _recognise_volume(an, s, fixed, xs) ArgumentError("ν differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") ) end - _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) + _check_lower_order(an, s, fixed, xs, B, dU, dG, dF, comps) ce = comps[1] nu, λ = B[1][mod1(ce + 1, 3), mod1(ce + 1, 3), ce], dU[1][ce] a = (a0 = substitute(λ, Dict(unwrap(x) => 0 for x in s)), a1 = Symbolics.derivative(λ, s[1]), a2 = Symbolics.derivative(λ, s[2])) @@ -200,32 +200,35 @@ end # tolerances relative to the other coefficients, which a large one would hide behind: there is no first-order term, # the coefficients of E, ∂ₜE and ∂ₜ²E of an equation do not couple the components, and each is the same scalar # function in every equation. Only roundoff of an expression of unit scale counts as zero beyond the symbolic test. -function _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) +function _check_lower_order(an, s, fixed, xs, B, dU, dG, dF, comps) X = an.slots.X - # The indices of `exs` that are not zero. - function nonvanishing(exs) + szero = Dict(unwrap(si) => 0 for si in s) + orders = (ex -> substitute(ex, szero), ex -> Symbolics.derivative(ex, s[1]), ex -> Symbolics.derivative(ex, s[2])) + # The indices of `exs` that are not zero in equation `e`: not symbolically zero and, at some point, above the + # roundoff of the largest coefficient of that equation, so that scaling an equation changes nothing. + function nonvanishing(e, exs) exs = [substitute(ex, fixed) for ex in exs] open = findall(ex -> !_iszero_expr(ex), exs) isempty(open) && return open - f = Symbolics.build_function(exs[open], X...; expression = Val(false))[1] + parts = [vec(B[e]); [order(dU[e][c]) for c in 1:3, order in orders]] + f = Symbolics.build_function( + [exs[open]; [substitute(ex, fixed) for ex in parts]], X...; expression = Val(false) + )[1] big = falses(length(open)) for x in xs - big .|= abs.(_real_values(f(x...), "a coefficient")) .> 100eps() + v = abs.(_real_values(f(x...), "a coefficient")) + big .|= v[1:length(open)] .> 100eps() * maximum(v[(length(open) + 1):end]) end return open[big] end for e in 1:3 - isempty(nonvanishing(dF[e])) || + isempty(nonvanishing(e, dF[e])) || throw(ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM")) - isempty(nonvanishing(dG[e])) || throw( + isempty(nonvanishing(e, dG[e])) || throw( ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") ) - end - szero = Dict(unwrap(si) => 0 for si in s) - orders = (ex -> substitute(ex, szero), ex -> Symbolics.derivative(ex, s[1]), ex -> Symbolics.derivative(ex, s[2])) - for e in 1:3 off = [order(dU[e][c]) for c in setdiff(1:3, comps[e]) for order in orders] - isempty(nonvanishing(off)) || throw( + isempty(nonvanishing(e, off)) || throw( ArgumentError("the zeroth-order term of equation $e couples the components of E; the coefficients of E and its time derivatives must be scalars") ) end diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 614b52c0..95054e26 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -215,6 +215,8 @@ end # Unequal inertia next to a large reaction. @test rejected(2.0e6; a0 = 1.0e12, a2 = 1.0, extra = c -> (c - 1) * Dt(Dt(Ev[c]))) @test rejected(2.0e6; a0 = 1.0e12, a2 = 1.0, extra = c -> (c - 1) * Dt(Ev[c])) + # Scaling the whole equation changes nothing: a small coupling next to small coefficients is still a coupling. + @test rejected(1.0; a2 = 1.0e-16, nu = 1.0e-16, extra = c -> 1.0e-16 * Ev[mod1(c + 1, 3)]) # The same large coefficients with scalar lower-order terms are fine. @test !rejected(2.0e6; a0 = 1.0e12, a2 = 2.0, a1 = 3.0) end From da23b5288fc883b51efaa5d1a599580f9d930034 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:51:18 +0000 Subject: [PATCH 11/26] Maxwell front end: do not shadow the compiled diagonal in the zero test 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/frontend.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index fae977b5..4a2f61fd 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -211,12 +211,12 @@ function _check_lower_order(an, s, fixed, xs, B, dU, dG, dF, comps) open = findall(ex -> !_iszero_expr(ex), exs) isempty(open) && return open parts = [vec(B[e]); [order(dU[e][c]) for c in 1:3, order in orders]] - f = Symbolics.build_function( + g = Symbolics.build_function( [exs[open]; [substitute(ex, fixed) for ex in parts]], X...; expression = Val(false) )[1] big = falses(length(open)) for x in xs - v = abs.(_real_values(f(x...), "a coefficient")) + v = abs.(_real_values(g(x...), "a coefficient")) big .|= v[1:length(open)] .> 100eps() * maximum(v[(length(open) + 1):end]) end return open[big] From c537d65bb84568464988ef9059463d7fc5964894 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:53:23 +0000 Subject: [PATCH 12/26] Maxwell front end: exact zero tests for lower-order coefficients Any tolerance relative to other coefficients, or to a unit, depends on how an equation is scaled and can hide a significant term, so a coefficient is zero only if it is symbolically zero or exactly zero at every cell centroid; also fixes the vertical concatenation of the scale list that the previous commit introduced. 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/frontend.jl | 27 ++++++++++++--------------- test/Maxwell/frontend.jl | 1 + 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 4a2f61fd..929e1da9 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -189,7 +189,7 @@ function _recognise_volume(an, s, fixed, xs) ArgumentError("ν differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") ) end - _check_lower_order(an, s, fixed, xs, B, dU, dG, dF, comps) + _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) ce = comps[1] nu, λ = B[1][mod1(ce + 1, 3), mod1(ce + 1, 3), ce], dU[1][ce] a = (a0 = substitute(λ, Dict(unwrap(x) => 0 for x in s)), a1 = Symbolics.derivative(λ, s[1]), a2 = Symbolics.derivative(λ, s[2])) @@ -199,36 +199,33 @@ end # The terms of lower order than the curl-curl, each judged on its own, with exact symbolic zero tests rather than # tolerances relative to the other coefficients, which a large one would hide behind: there is no first-order term, # the coefficients of E, ∂ₜE and ∂ₜ²E of an equation do not couple the components, and each is the same scalar -# function in every equation. Only roundoff of an expression of unit scale counts as zero beyond the symbolic test. -function _check_lower_order(an, s, fixed, xs, B, dU, dG, dF, comps) +# function in every equation. +function _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) X = an.slots.X szero = Dict(unwrap(si) => 0 for si in s) orders = (ex -> substitute(ex, szero), ex -> Symbolics.derivative(ex, s[1]), ex -> Symbolics.derivative(ex, s[2])) - # The indices of `exs` that are not zero in equation `e`: not symbolically zero and, at some point, above the - # roundoff of the largest coefficient of that equation, so that scaling an equation changes nothing. - function nonvanishing(e, exs) + # The indices of `exs` that are not zero: not symbolically zero and, at some point, not exactly zero. There is no + # tolerance, since any tolerance relative to other coefficients (or to a unit) would depend on how the equation is + # scaled and could hide a significant term; a coefficient that is zero only up to roundoff is rejected. + function nonvanishing(exs) exs = [substitute(ex, fixed) for ex in exs] open = findall(ex -> !_iszero_expr(ex), exs) isempty(open) && return open - parts = [vec(B[e]); [order(dU[e][c]) for c in 1:3, order in orders]] - g = Symbolics.build_function( - [exs[open]; [substitute(ex, fixed) for ex in parts]], X...; expression = Val(false) - )[1] + g = Symbolics.build_function(exs[open], X...; expression = Val(false))[1] big = falses(length(open)) for x in xs - v = abs.(_real_values(g(x...), "a coefficient")) - big .|= v[1:length(open)] .> 100eps() * maximum(v[(length(open) + 1):end]) + big .|= .!iszero.(_real_values(g(x...), "a coefficient")) end return open[big] end for e in 1:3 - isempty(nonvanishing(e, dF[e])) || + isempty(nonvanishing(dF[e])) || throw(ArgumentError("equation $e has a first-order term inside a derivative; $_MAXWELL_FORM")) - isempty(nonvanishing(e, dG[e])) || throw( + isempty(nonvanishing(dG[e])) || throw( ArgumentError("equation $e has a first-order term in the derivatives of E, which curl(ν*curl(E)) does not have; $_MAXWELL_FORM") ) off = [order(dU[e][c]) for c in setdiff(1:3, comps[e]) for order in orders] - isempty(nonvanishing(e, off)) || throw( + isempty(nonvanishing(off)) || throw( ArgumentError("the zeroth-order term of equation $e couples the components of E; the coefficients of E and its time derivatives must be scalars") ) end diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 95054e26..4ecedc79 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -217,6 +217,7 @@ end @test rejected(2.0e6; a0 = 1.0e12, a2 = 1.0, extra = c -> (c - 1) * Dt(Ev[c])) # Scaling the whole equation changes nothing: a small coupling next to small coefficients is still a coupling. @test rejected(1.0; a2 = 1.0e-16, nu = 1.0e-16, extra = c -> 1.0e-16 * Ev[mod1(c + 1, 3)]) + @test rejected(1.0e8; a2 = 1.0e-16, extra = c -> 1.0e-16 * Dt(Dt(Ev[mod1(c + 1, 3)]))) # The same large coefficients with scalar lower-order terms are fine. @test !rejected(2.0e6; a0 = 1.0e12, a2 = 2.0, a1 = 3.0) end From df877def74d25d8eb19796fde5cfca618cde2c16 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:55:20 +0000 Subject: [PATCH 13/26] FEMDiscretization: omega squared must be representable 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/discretization.jl | 3 ++- test/Maxwell/frontend.jl | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index 1319b926..c004a882 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -195,7 +195,8 @@ function _check_omega(omega, time, spaces, test_space, regions, ibp, pairing) return nothing end # The value is stored as a Float64, so a BigFloat beyond its range (1e-400, 1e400) is judged after the conversion. - omega isa Real && (w = Float64(omega); isfinite(w) && w > 0) || + # The solver divides by omega^2, so that must be representable too. + omega isa Real && (w = Float64(omega); isfinite(w) && w > 0 && isfinite(w^2) && w^2 > 0) || throw(ArgumentError("omega must be a positive, finite angular frequency in rad/s, got $(repr(omega))")) time === nothing && throw( ArgumentError("omega needs the time variable of the time-domain PDESystem, as FEMDiscretization(Ω, t; omega)") diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 4ecedc79..031a363f 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -43,7 +43,7 @@ end @test curl === Ferrite.curl # one curl with both packages loaded Ω = MeshDomain(unit_cube(1)) @test maxwell_disc(Ω, 2).omega === 2.0 - for bad in (0, -1.0, Inf, 1 + 2im, big"1e-400", big"1e400") + for bad in (0, -1.0, Inf, 1 + 2im, big"1e-400", big"1e400", 1.0e-200, 1.0e160) @test_throws ArgumentError("omega must be a positive, finite angular frequency in rad/s, got $(repr(bad))") maxwell_disc(Ω, bad) end @test_throws ArgumentError("omega needs the time variable of the time-domain PDESystem, as FEMDiscretization(Ω, t; omega)") FEMDiscretization(Ω; omega = 1.0, spaces = edge_space()) @@ -197,7 +197,7 @@ end @testset "a frequency too small for the reaction coefficient is rejected, not turned into NaN" begin Ω = MeshDomain(unit_cube(1)) - for (ω, a0) in ((1.0e-200, 0.0), (1.0e-160, 1.0)) + for (ω, a0) in ((1.0e-160, 1.0),) @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0), maxwell_disc(Ω, ω)))) end end From a48254fe52b1928444626cb89f483f6ac7ce691b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:57:48 +0000 Subject: [PATCH 14/26] Maxwell front end: reject a nu whose reciprocal is not representable 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/frontend.jl | 3 ++- test/Maxwell/frontend.jl | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 929e1da9..c2eb08d2 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -367,7 +367,8 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio ω = disc.omega materials = map(enumerate(centroids)) do (cell, x) nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") - iszero(nu) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero")) + (iszero(nu) || iszero(1 / nu) || !isfinite(1 / nu)) && + throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) eps_r = a2 - a0 / ω^2 isfinite(eps_r) || throw( ArgumentError("ε = a₂ - a₀/ω² = $a2 - $a0/$ω^2 in cell $cell is not representable at this tiny ω; use a larger frequency or a MaxwellModel directly") diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 031a363f..4b24f811 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -157,6 +157,7 @@ end err("a source of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude"; f = [sin(t), 0, 0]) err("a coefficient of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude"; a2 = 1 + t) err("ν = 0.0 in cell 1; ν = 1/μ must be nonzero"; nu = 0) + err("ν = 1.0e-309 in cell 1; ν = 1/μ must be nonzero and 1/ν must be representable"; nu = 1.0e-309, a2 = 1.0e-309) @test_throws ArgumentError discretize(maxwell_system(Ω; extra = c -> Dt(Dt(Dt(Ev[c])))), maxwell_disc(Ω, 1.0)) # A second derivative of a field-free expression lands in the flux; it must not vanish from the load. From 8bcc28d08628ed37368bec8ac51bf3ba73da0728 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 02:11:36 +0000 Subject: [PATCH 15/26] Maxwell front end: reject a reaction coefficient lost to underflow in eps a0/omega^2 below the smallest normal number was silently dropped next to a dominant curl-curl term; now an ArgumentError. 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/frontend.jl | 2 +- test/Maxwell/frontend.jl | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index c2eb08d2..9a937731 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -370,7 +370,7 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio (iszero(nu) || iszero(1 / nu) || !isfinite(1 / nu)) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) eps_r = a2 - a0 / ω^2 - isfinite(eps_r) || throw( + isfinite(eps_r) && (iszero(a0) || abs(a0 / ω^2) >= floatmin()) || throw( ArgumentError("ε = a₂ - a₀/ω² = $a2 - $a0/$ω^2 in cell $cell is not representable at this tiny ω; use a larger frequency or a MaxwellModel directly") ) MaxwellMaterial(; eps_r, mu_r = 1 / nu, sigma = a1) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 4b24f811..abcd0c8b 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -201,6 +201,8 @@ end for (ω, a0) in ((1.0e-160, 1.0),) @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0), maxwell_disc(Ω, ω)))) end + # a0/ω² underflows to zero next to a dominant curl-curl term, so the reaction would be silently dropped. + @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 0, a0 = 1.0e-20), maxwell_disc(Ω, 1.0e154)))) end @testset "a large reaction coefficient hides no other coefficient" begin From e25564c49634100961e15e14161cbadac3552793 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 22:12:21 +0000 Subject: [PATCH 16/26] Front end: compare component coefficients exactly The anisotropy check used a tolerance of 100 eps times the larger coefficient, so reactions 2^48 + c cancelling an inertia 2^46 at omega = 2 into diag(1, 2, 3) passed as isotropic and the equation was silently solved with one component's coefficient. Coefficients must now be equal as expressions or equal as numbers. 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/frontend.jl | 5 ++++- test/Maxwell/frontend.jl | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 9a937731..d285bbfa 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -231,10 +231,13 @@ function _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) end diag = [orders[k](dU[e][comps[e]]) for e in 1:3, k in 1:3] f = Symbolics.build_function(substitute.(diag, Ref(fixed)), X...; expression = Val(false))[1] + # Equal as expressions, or else equal as numbers: no tolerance, which would scale with coefficients (a large + # reaction against a large inertia) that cancel at the requested frequency. + same = [_iszero_expr(substitute(diag[e, k] - diag[1, k], fixed)) for e in 1:3, k in 1:3] for x in xs v = reshape(_real_values(f(x...), "a coefficient"), 3, 3) for k in 1:3, e in 2:3 - abs(v[e, k] - v[1, k]) <= 100eps() * max(abs(v[e, k]), abs(v[1, k])) || throw( + same[e, k] || v[e, k] == v[1, k] || throw( ArgumentError("the coefficient of E differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") ) end diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index abcd0c8b..9a59d624 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -221,6 +221,10 @@ end # Scaling the whole equation changes nothing: a small coupling next to small coefficients is still a coupling. @test rejected(1.0; a2 = 1.0e-16, nu = 1.0e-16, extra = c -> 1.0e-16 * Ev[mod1(c + 1, 3)]) @test rejected(1.0e8; a2 = 1.0e-16, extra = c -> 1.0e-16 * Dt(Dt(Ev[mod1(c + 1, 3)]))) + # Component reactions 2^48 + c against the inertia 2^46 cancel at ω = 2 to the anisotropic diag(1, 2, 3); the + # differences 1 and 2 are far below a tolerance scaled to 2^48, and must still be seen, exactly. + anisotropic = message(() -> discretize(maxwell_system(Ω; a2 = 2.0^46, extra = c -> (2.0^48 + c) * Ev[c]), maxwell_disc(Ω, 2.0))) + @test occursin("so the medium is anisotropic", anisotropic) # The same large coefficients with scalar lower-order terms are fine. @test !rejected(2.0e6; a0 = 1.0e12, a2 = 2.0, a1 = 3.0) end From 7984b0eb59ca29a2154c9d0c8898d67f7a644812 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 03:04:51 +0000 Subject: [PATCH 17/26] Front end: exact net reaction, symbolic structure checks, trace arguments The reaction a2 - a0/omega^2 cancelled badly for large coefficients (relative error 0.11 on an exact constant field); the net a0 - omega^2 a2 is now formed in extended precision and divided once. The structural checks (grad div E, vector Laplacian, anisotropy, component choice) compared against a tolerance scaled by the largest coefficient, so -Laplacian E with coefficient 1 next to nu = 1e12 passed; they are decided symbolically from each term's own coefficient. The trace E(t, Gamma) of a boundary condition must use the time variable and its piece, so a condition at one time is no longer taken as a perfect conductor. The perfect-conductor rows are judged by their own norm. 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/frontend.jl | 76 +++++++++++++++++++++++++--------------- test/Maxwell/frontend.jl | 40 +++++++++++++++++++++ 2 files changed, 88 insertions(+), 28 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index d285bbfa..d281d365 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -153,39 +153,43 @@ function _recognise_volume(an, s, fixed, xs) end end comps = zeros(Int, 3) + # Which component an equation tests: its Laplacian-like trace, or else its reaction, is nonzero (exactly: the choice + # is not a tolerance on the size of the other coefficients). for (x, sv) in points, (e, q) in enumerate(unpack(x, sv)) all(!iszero, comps) && break comps[e] == 0 || continue tr = [sum(q.B[a, c, a] for a in 1:3) for c in 1:3] - tol = 1.0e-10 * max(maximum(abs, q.B), maximum(abs, q.λU), 1.0e-300) - comps[e] = maximum(abs, tr) > tol ? argmax(abs.(tr)) : maximum(abs, q.λU) > tol ? argmax(abs.(q.λU)) : 0 + comps[e] = maximum(abs, tr) > 0 ? argmax(abs.(tr)) : maximum(abs, q.λU) > 0 ? argmax(abs.(q.λU)) : 0 end e0 = findfirst(iszero, comps) e0 === nothing || throw(ArgumentError("equation $e0 has neither a curl-curl nor a reaction term in E")) sort(comps) == 1:3 || throw(ArgumentError("the equations test the components $comps of E; write one equation per component")) + # The structure of the second-order part, decided symbolically from its own coefficients: a term is there or not, + # however small it is next to ν. + νs = Any[] + for e in 1:3 + ce = comps[e] + other = mod1(ce + 1, 3) + Be = [substitute(B[e][a, c, b], fixed) for a in 1:3, c in 1:3, b in 1:3] + α, β, γ = Be[other, ce, other], Be[other, other, ce], Be[ce, other, other] + _iszero_expr(γ) || + throw(ArgumentError("equation $e has a grad div E term, which has no meaning on Nédélec elements; $_MAXWELL_FORM")) + expect = [α * (c == ce) * (a == b) + β * (b == ce) * (a == c) + γ * (a == ce) * (c == b) for a in 1:3, c in 1:3, b in 1:3] + all(_iszero_expr(Be[a, c, b] - expect[a, c, b]) for a in 1:3, c in 1:3, b in 1:3) || throw( + ArgumentError("the second-order part of equation $e is anisotropic or couples the components of E differently from curl(ν*curl(E)); $_MAXWELL_FORM") + ) + _iszero_expr(β) && !_iszero_expr(α) && throw( + ArgumentError("equation $e has the vector Laplacian of E, which is component-wise H¹ and not H(curl)-conforming; $_MAXWELL_FORM") + ) + _iszero_expr(α + β) || throw( + ArgumentError("the second-order part of equation $e adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $_MAXWELL_FORM") + ) + push!(νs, β) + end + νsame = [_iszero_expr(νs[e] - νs[1]) for e in 1:3] for (x, sv) in points - nus = zeros(3) - for (e, q) in enumerate(unpack(x, sv)) - ce = comps[e] - other = mod1(ce + 1, 3) - tol = 1.0e-10 * max(maximum(abs, q.B), 1.0e-300) # the second-order part is judged against itself - α, β, γ = q.B[other, ce, other], q.B[other, other, ce], q.B[ce, other, other] - expect = [α * (c == ce) * (a == b) + β * (b == ce) * (a == c) + γ * (a == ce) * (c == b) for a in 1:3, c in 1:3, b in 1:3] - abs(γ) > tol && throw( - ArgumentError("equation $e has a grad div E term, which has no meaning on Nédélec elements; $_MAXWELL_FORM") - ) - maximum(abs, q.B - expect) > tol && throw( - ArgumentError("the second-order part of equation $e is anisotropic or couples the components of E differently from curl(ν*curl(E)); $_MAXWELL_FORM") - ) - abs(β) <= tol && abs(α) > tol && throw( - ArgumentError("equation $e has the vector Laplacian of E, which is component-wise H¹ and not H(curl)-conforming; $_MAXWELL_FORM") - ) - abs(α + β) > tol && throw( - ArgumentError("the second-order part of equation $e adds a component-wise Laplacian of E to curl(ν*curl(E)), which is not H(curl)-conforming; $_MAXWELL_FORM") - ) - nus[e] = β - end - maximum(abs, nus .- nus[1]) <= 1.0e-10 * maximum(abs, nus) || throw( + nus = [unpack(x, sv)[e].B[mod1(comps[e] + 1, 3), mod1(comps[e] + 1, 3), comps[e]] for e in 1:3] + all(e -> νsame[e] || nus[e] == nus[1], 2:3) || throw( ArgumentError("ν differs between the component equations at x = $(Tuple(x)), so the medium is anisotropic; the coefficients must be scalars") ) end @@ -245,6 +249,15 @@ function _check_lower_order(an, s, fixed, xs, dU, dG, dF, comps) return nothing end +# The trace of the field in a boundary condition is E(t, Γ): the time variable and the boundary piece of the condition, +# nothing at a fixed or shifted time (an initial condition) and no other argument. +function _check_trace_arguments(ex, t, Γ, eq) + args = [_unwrap_arg(a) for a in SymbolicUtils.arguments(ex)] + length(args) == 2 && isequal(args[1], unwrap(t)) && args[2] isa PDEBase.BoundaryPiece && args[2] == Γ || + throw(ArgumentError("$eq has the trace $(Num(ex)); a boundary condition with omega must use E(t, Γ) at the time variable t and its boundary piece Γ, not a condition at one time")) + return nothing +end + # n × E = 0 conditions: each residual is linear in the traces and the normal, tangential (C n = 0) and of rank 2 # together on its piece. function _recognise_pec(bcs, fields, pvals, ctx, domain) @@ -274,7 +287,10 @@ function _recognise_pec(bcs, fields, pvals, ctx, domain) rules[ex] = unwrap(N[Int(SymbolicUtils.unwrap_const(only(SymbolicUtils.arguments(ex))))]) else f = findfirst(isequal(op), ctx.ops) - f === nothing || (rules[ex] = unwrap(U[fields[f]])) + if f !== nothing + _check_trace_arguments(ex, ctx.t, Γ, eq) + rules[ex] = unwrap(U[fields[f]]) + end end end for (p, value) in zip(ctx.params, pvals) @@ -295,7 +311,10 @@ function _recognise_pec(bcs, fields, pvals, ctx, domain) for (n, facet) in _facet_normals(domain.mesh, String(name)) Cn = reshape(_real_values(C_at(n...), "a coefficient of the condition"), length(Bs), 3) where = "on $name at facet $((facet[1], facet[2])) with normal $(Tuple(round.(n; digits = 6)))" - maximum(abs, Cn * n; init = 0.0) > 1.0e-10 * maximum(abs, Cn; init = 0.0) && throw( + # Each equation is judged by its own size, so that one written with a large coefficient hides no other. + Cn = Cn[[norm(Cn[i, :]) > 0 for i in axes(Cn, 1)], :] + Cn = Cn ./ norm.(eachrow(Cn)) + maximum(abs, Cn * n; init = 0.0) > 1.0e-10 && throw( ArgumentError("the conditions $where constrain the normal component of E, unlike n × E = 0; $pform") ) rank(Cn) == 2 || throw( @@ -360,7 +379,7 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio fixed = Dict{Any, Any}(unwrap(an.slots.P[j]) => pvals[j] for j in keep) centroids = [sum(Ferrite.getcoordinates(grid, cell)) / 4 for cell in 1:Ferrite.getncells(grid)] coeffs = _recognise_volume(an, slot_s, fixed, centroids) - pec = _recognise_pec(sys.bcs, comps, pvals[keep], (; ops, params = ctx.params[keep]), disc.domain) + pec = _recognise_pec(sys.bcs, comps, pvals[keep], (; ops, params = ctx.params[keep], t = ctx.t), disc.domain) # Compile the coefficients and sources as functions of the mesh coordinate. X = an.slots.X @@ -372,7 +391,8 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") (iszero(nu) || iszero(1 / nu) || !isfinite(1 / nu)) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) - eps_r = a2 - a0 / ω^2 + # The net reaction a₀ - ω² a₂ is formed exactly (it cancels when the two are large), then divided once. + eps_r = Float64(-(big(a0) - big(ω)^2 * big(a2)) / big(ω)^2) isfinite(eps_r) && (iszero(a0) || abs(a0 / ω^2) >= floatmin()) || throw( ArgumentError("ε = a₂ - a₀/ω² = $a2 - $a0/$ω^2 in cell $cell is not representable at this tiny ω; use a larger frequency or a MaxwellModel directly") ) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 9a59d624..a2279155 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -312,3 +312,43 @@ end other = MeshDomain(unit_cube(1)) @test_throws ArgumentError bad(cross(facet_normal(boundarypiece(other, :left)), [E(t, boundarypiece(other, :left))[c] for c in 1:3]) .~ 0) end + +@testset "the net reaction is formed exactly" begin + # a₀ - ω² a₂ = 1 exactly with ω = 3, a₂ = 2^49 and a₀ = 9 a₂ + 1: the constant field (1, 0, 0) solves the equation. + Ω = MeshDomain(unit_cube(2)) + ω = 3.0 + sys = maxwell_system(Ω; nu = 1.0, a2 = 2.0^49, a0 = 9 * 2.0^49 + 1, f = [1.0, 0.0, 0.0]) + disc = maxwell_disc(Ω, ω) + (; model) = maxwell_model(sys, disc) + u = discretize(sys, disc).A \ discretize(sys, disc).b + E = field_values(MaxwellSolution(model, ω, u), [Vec(0.31, 0.37, 0.41)]).E[1] + @test collect(E) ≈ [1.0, 0.0, 0.0] atol = 1.0e-10 +end + +@testset "structural terms are rejected however small they are next to ν" begin + Ω = MeshDomain(unit_cube(2)) + D = Differential.(collect(X)) + laplacian(c) = -(D[1](D[1](Ev[c])) + D[2](D[2](Ev[c])) + D[3](D[3](Ev[c]))) + graddiv(c) = -D[c](D[1](Ev[1]) + D[2](Ev[2]) + D[3](Ev[3])) + rejected(; kw...) = message(() -> discretize(maxwell_system(Ω; kw...), maxwell_disc(Ω, 2.0))) != "no error" + for scale in (1.0, 1.0e12) + @test !rejected(; nu = scale, a2 = scale) + @test rejected(; nu = scale, a2 = scale, extra = c -> scale * laplacian(c)) + @test rejected(; nu = scale, a2 = scale, extra = c -> scale * graddiv(c)) + end + # A coefficient 1 next to ν = 1e12 is a term all the same. + @test rejected(; nu = 1.0e12, extra = laplacian) + @test rejected(; nu = 1.0e12, extra = graddiv) +end + +@testset "a boundary condition at one time is not a perfect conductor" begin + Ω = MeshDomain(unit_cube(2)) + left = boundarypiece(Ω, :left) + sys(trace) = maxwell_system(Ω; bcs = cross(facet_normal(left), trace) .~ 0) + documented = [E(t, left)[c] for c in 1:3] + @test discretize(sys(documented), maxwell_disc(Ω, 1.0)) isa LinearProblem + for time in (0.0, t + 1, 2t) + trace = [E(time, left)[c] for c in 1:3] + @test occursin("not a condition at one time", message(() -> discretize(sys(trace), maxwell_disc(Ω, 1.0)))) + end +end From 70e4b3ea0f7e38f3117405a615dff7b343fd5d97 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 03:16:59 +0000 Subject: [PATCH 18/26] Front end: reject a net reaction lost to underflow after cancellation With omega = 1e154, a0 = 5 and a2 = 5e-308 the net reaction a0 - omega^2 a2 is 8.4e-17 but eps_r = -net/omega^2 underflows to zero and the reaction was silently dropped. The coefficient and the reaction assembly forms from it are checked against the exact net value, and a nonzero net that becomes zero, subnormal or non-finite is an ArgumentError. 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/frontend.jl | 11 ++++++++--- test/Maxwell/frontend.jl | 2 ++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index d281d365..29645c3e 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -392,9 +392,14 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio (iszero(nu) || iszero(1 / nu) || !isfinite(1 / nu)) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) # The net reaction a₀ - ω² a₂ is formed exactly (it cancels when the two are large), then divided once. - eps_r = Float64(-(big(a0) - big(ω)^2 * big(a2)) / big(ω)^2) - isfinite(eps_r) && (iszero(a0) || abs(a0 / ω^2) >= floatmin()) || throw( - ArgumentError("ε = a₂ - a₀/ω² = $a2 - $a0/$ω^2 in cell $cell is not representable at this tiny ω; use a larger frequency or a MaxwellModel directly") + net = big(a0) - big(ω)^2 * big(a2) + eps_r = Float64(-net / big(ω)^2) + # The coefficient and the reaction -ω² eps_r that assembly forms from it must neither overflow nor lose a nonzero + # net reaction to underflow. + reaction = -ω^2 * eps_r + lost(x) = iszero(x) || issubnormal(x) + isfinite(eps_r) && isfinite(reaction) && (iszero(net) || !(lost(eps_r) || lost(reaction))) || throw( + ArgumentError("the reaction a₀ - ω² a₂ = $(Float64(net)) ($a0 - $ω^2 $a2) in cell $cell is not representable as ε = a₂ - a₀/ω² at this ω; use a frequency nearer 1 or a MaxwellModel directly") ) MaxwellMaterial(; eps_r, mu_r = 1 / nu, sigma = a1) end diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index a2279155..b6ca4bb4 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -201,6 +201,8 @@ end for (ω, a0) in ((1.0e-160, 1.0),) @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0), maxwell_disc(Ω, ω)))) end + # The net reaction a₀ - ω² a₂ = 8.4e-17 is exactly representable, but ε = -net/ω² underflows to zero. + @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0 = 5.0, a2 = 5.0e-308), maxwell_disc(Ω, 1.0e154)))) # a0/ω² underflows to zero next to a dominant curl-curl term, so the reaction would be silently dropped. @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 0, a0 = 1.0e-20), maxwell_disc(Ω, 1.0e154)))) end From 20ca57129514ba424b4f2ecd30d6dd42240c73fe Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 03:49:10 +0000 Subject: [PATCH 19/26] Front end: form the net reaction in exact rational arithmetic The cancellation used BigFloat at the caller's precision, so inside setprecision(BigFloat, 53) an exact net reaction of -1 (omega = 1 + 2^-30, a2 = 2^60, a0 = 2^60 + 2^31) rounded to zero and the reaction was dropped. The Float64 inputs are now combined as Rational{BigInt}, which is exact at any precision. 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/frontend.jl | 8 ++++++-- test/Maxwell/frontend.jl | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 29645c3e..3877315e 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -392,8 +392,12 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio (iszero(nu) || iszero(1 / nu) || !isfinite(1 / nu)) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) # The net reaction a₀ - ω² a₂ is formed exactly (it cancels when the two are large), then divided once. - net = big(a0) - big(ω)^2 * big(a2) - eps_r = Float64(-net / big(ω)^2) + all(isfinite, (a0, a2, ω)) || throw( + ArgumentError("the reaction a₀ - ω² a₂ ($a0 - $ω^2 $a2) in cell $cell is not representable as ε = a₂ - a₀/ω²; the coefficients must be finite") + ) + # Exact rational arithmetic of the Float64 inputs, so that the cancellation does not depend on any BigFloat precision. + net = Rational{BigInt}(a0) - Rational{BigInt}(ω)^2 * Rational{BigInt}(a2) + eps_r = Float64(-net / Rational{BigInt}(ω)^2) # The coefficient and the reaction -ω² eps_r that assembly forms from it must neither overflow nor lose a nonzero # net reaction to underflow. reaction = -ω^2 * eps_r diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index b6ca4bb4..866645a3 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -327,6 +327,18 @@ end @test collect(E) ≈ [1.0, 0.0, 0.0] atol = 1.0e-10 end +@testset "the net reaction does not depend on the BigFloat precision" begin + # a₀ - ω² a₂ = -1 exactly for ω = 1 + 2^-30, a₂ = 2^60 and a₀ = 2^60 + 2^31, so ε = 1/ω². + Ω = MeshDomain(unit_cube(1)) + ω = 1 + 2.0^-30 + sys = maxwell_system(Ω; nu = 1.0, a2 = 2.0^60, a0 = 2.0^60 + 2.0^31) + eps_r() = maxwell_model(sys, maxwell_disc(Ω, ω)).model.materials[1].eps_r + @test eps_r() ≈ 1 / ω^2 rtol = 1.0e-12 + setprecision(BigFloat, 53) do + @test eps_r() ≈ 1 / ω^2 rtol = 1.0e-12 + end +end + @testset "structural terms are rejected however small they are next to ν" begin Ω = MeshDomain(unit_cube(2)) D = Differential.(collect(X)) From 732f87cdf3e95d1609e010a1c1c64a0e222668e0 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 06:07:43 +0000 Subject: [PATCH 20/26] Front end: check the reaction by round trip through assembly With omega = 2e-162 the square rounds to the subnormal 5e-324, so assembly formed -4.94e-16 for an exact net reaction of -4e-16 (19% field error) while both eps_r and the reconstructed reaction were finite and nonzero. The reaction assembly forms (with omega squared rounded as it rounds it) is now compared with the exact rational net to 1e-10, and a subnormal omega squared or coefficient with a nonzero net is rejected. 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/frontend.jl | 13 ++++++++----- test/Maxwell/frontend.jl | 2 ++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 3877315e..be92bcb3 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -398,11 +398,14 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio # Exact rational arithmetic of the Float64 inputs, so that the cancellation does not depend on any BigFloat precision. net = Rational{BigInt}(a0) - Rational{BigInt}(ω)^2 * Rational{BigInt}(a2) eps_r = Float64(-net / Rational{BigInt}(ω)^2) - # The coefficient and the reaction -ω² eps_r that assembly forms from it must neither overflow nor lose a nonzero - # net reaction to underflow. - reaction = -ω^2 * eps_r - lost(x) = iszero(x) || issubnormal(x) - isfinite(eps_r) && isfinite(reaction) && (iszero(net) || !(lost(eps_r) || lost(reaction))) || throw( + # Round trip: the reaction -ω² eps_r that assembly forms (with ω² rounded as it rounds it) must be the exact net + # reaction to 1e-10, far above the few ulps that two roundings cost and far below the loss when ω² or eps_r is + # subnormal; a nonzero net may not become zero, subnormal or non-finite. + ω2 = ω^2 + reaction = -ω2 * eps_r + roundtrip = isfinite(eps_r) && isfinite(reaction) && !iszero(ω2) && !issubnormal(ω2) && !issubnormal(eps_r) && + abs(Rational{BigInt}(reaction) - net) <= 1.0e-10 * abs(net) + isfinite(eps_r) && isfinite(reaction) && (iszero(net) || roundtrip) || throw( ArgumentError("the reaction a₀ - ω² a₂ = $(Float64(net)) ($a0 - $ω^2 $a2) in cell $cell is not representable as ε = a₂ - a₀/ω² at this ω; use a frequency nearer 1 or a MaxwellModel directly") ) MaxwellMaterial(; eps_r, mu_r = 1 / nu, sigma = a1) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 866645a3..323f0c03 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -203,6 +203,8 @@ end end # The net reaction a₀ - ω² a₂ = 8.4e-17 is exactly representable, but ε = -net/ω² underflows to zero. @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0 = 5.0, a2 = 5.0e-308), maxwell_disc(Ω, 1.0e154)))) + # ω² rounds to the subnormal 5e-324, so assembly would form -4.94e-16 for the exact net reaction -4e-16. + @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 1.0e308, a0 = 0.0, f = [-4.0e-16, 0.0, 0.0]), maxwell_disc(Ω, 2.0e-162)))) # a0/ω² underflows to zero next to a dominant curl-curl term, so the reaction would be silently dropped. @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 0, a0 = 1.0e-20), maxwell_disc(Ω, 1.0e154)))) end From 6d8bd32812f3ba20a039cb4e024330c31960653c Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 07:13:10 +0000 Subject: [PATCH 21/26] Front end: reject a reaction or source lost to underflow in assembly With omega = 2^-511, nu = 1e-307 and a0 = 2^-1074 every scalar round trip is exact, yet the assembled reaction block and the load round to zero (100% field error). A subnormal reconstructed reaction is rejected again, and the assembled reaction entries and the load are checked for underflow to zero or subnormal values whenever the net reaction or a source is nonzero. 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/frontend.jl | 17 +++++++++++++++-- test/Maxwell/frontend.jl | 2 ++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index be92bcb3..85ed18eb 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -404,7 +404,7 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio ω2 = ω^2 reaction = -ω2 * eps_r roundtrip = isfinite(eps_r) && isfinite(reaction) && !iszero(ω2) && !issubnormal(ω2) && !issubnormal(eps_r) && - abs(Rational{BigInt}(reaction) - net) <= 1.0e-10 * abs(net) + !iszero(reaction) && !issubnormal(reaction) && abs(Rational{BigInt}(reaction) - net) <= 1.0e-10 * abs(net) isfinite(eps_r) && isfinite(reaction) && (iszero(net) || roundtrip) || throw( ArgumentError("the reaction a₀ - ω² a₂ = $(Float64(net)) ($a0 - $ω^2 $a2) in cell $cell is not representable as ε = a₂ - a₀/ω² at this ω; use a frequency nearer 1 or a MaxwellModel directly") ) @@ -413,7 +413,20 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio model = MaxwellModel( grid; materials, pec, eps0 = 1.0, mu0 = 1.0, length_scale = 1.0, quadrature = something(disc.quadrature, 2) ) - return (; model, omega = ω, load = _source_load(model, x -> _real_values(source_at(x...), "a source"))) + # The scalar round trips cannot see underflow during integration and scaling: the reaction contribution and the load + # that are actually assembled must keep a nonzero reaction or source, neither lost to zero nor subnormal. + reaction_term = model.terms[2] # the eps_real block with its coefficient -ω² (mu0 = eps0 = L = 1) + reaction_entries = real(reaction_term.coefficient(ω)) .* nonzeros(reaction_term.block) + lost_entries(x) = iszero(x) || issubnormal(x) + any(lost_entries, reaction_entries[findall(!iszero, nonzeros(reaction_term.block))]) && throw( + ArgumentError("the reaction of the equation is not representable after assembly at ω = $ω: its matrix entries underflow to zero or subnormal values; scale the equation or use a MaxwellModel directly") + ) + load = _source_load(model, x -> _real_values(source_at(x...), "a source")) + sourced = any(x -> any(!iszero, _real_values(source_at(x...), "a source")), centroids) + sourced && (lost_entries(maximum(abs, load; init = 0.0)) || all(lost_entries, load)) && throw( + ArgumentError("the source of the equation is not representable after assembly: its load vector underflows to zero or subnormal values; scale the equation or use a MaxwellModel directly") + ) + return (; model, omega = ω, load) end function _real_values(values, what) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 323f0c03..51ad8e14 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -205,6 +205,8 @@ end @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0 = 5.0, a2 = 5.0e-308), maxwell_disc(Ω, 1.0e154)))) # ω² rounds to the subnormal 5e-324, so assembly would form -4.94e-16 for the exact net reaction -4e-16. @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 1.0e308, a0 = 0.0, f = [-4.0e-16, 0.0, 0.0]), maxwell_disc(Ω, 2.0e-162)))) + # ω² is the smallest normal number and every scalar round trip is exact, but the assembled reaction and load underflow. + @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-307, a0 = 2.0^-1074, f = [2.0^-1074, 0.0, 0.0]), maxwell_disc(Ω, 2.0^-511)))) # a0/ω² underflows to zero next to a dominant curl-curl term, so the reaction would be silently dropped. @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 0, a0 = 1.0e-20), maxwell_disc(Ω, 1.0e154)))) end From 8c553cc3e2b2edc420776a7d29b397e40dbca231 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 07:22:57 +0000 Subject: [PATCH 22/26] Front end: one explicit working window for coefficients, source amplitude and omega MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extreme-scale underflow cases were found one at a time (conductivity block, ε from the net reaction, ω squared, the assembled reaction and load). Every nonzero nu, a0, a1, a2 and source amplitude and omega must now lie in 1e-100..1e100 and the products ω² a2 and ω a1 in 1e-250..1e250, far wider than SI-unit physics, so that products with mesh quantities cannot underflow; outside it an ArgumentError names the coefficient and the window and asks for a nondimensionalised equation. The exact, round-trip and assembly checks stay as defence in depth. The window is documented in the maxwell_model docstring and the manual, with a copper-conductivity SI example as a regression. 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 | 5 +++++ src/maxwell/frontend.jl | 39 +++++++++++++++++++++++++++++++++++++++ test/Maxwell/frontend.jl | 31 +++++++++++++++++++------------ 3 files changed, 63 insertions(+), 12 deletions(-) diff --git a/docs/src/maxwell.md b/docs/src/maxwell.md index 4d4296d7..5b86fdb4 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -64,6 +64,11 @@ facet_normal maxwell_model ``` +The front end works in a window: every nonzero `ν`, `a₀`, `a₁`, `a₂`, source amplitude and `ω` lies in +`1e-100 ≤ |c| ≤ 1e100`, and the products `ω² a₂` and `ω a₁` in `1e-250 ≤ |c| ≤ 1e250`; anything outside is an +`ArgumentError` that asks for a nondimensionalised equation. SI-unit physics (`ε₀ ≈ 8.85e-12`, `μ₀⁻¹ ≈ 8e5`, `ω` up to +`1e12`) is far inside it. + ## Operator level ```@docs diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 85ed18eb..e0bd1cd3 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -200,6 +200,30 @@ function _recognise_volume(an, s, fixed, xs) return (; nu, a..., sources = sources[invperm(comps)]) end +# The working range of the PDESystem front end: every nonzero coefficient, the source amplitude and ω lie in +# [1e-100, 1e100] in magnitude and the products ω² a₂ and ω a₁ in [1e-250, 1e250], so that products with mesh +# quantities (element volumes, mass and stiffness entries) cannot underflow to subnormal values or overflow. +const _WINDOW = (1.0e-100, 1.0e100) +const _PRODUCT_WINDOW = (1.0e-250, 1.0e250) + +function _window_error(name, value, where, lo, hi) + place = where === nothing ? "" : " in cell $where" + return ArgumentError( + "$name = $value$place is outside the supported window $lo ≤ |$name| ≤ $hi of the Maxwell front end (SI-scale physics is " * + "well inside it); nondimensionalise the equation, or build a MaxwellModel directly" + ) +end +function _check_window(name, value, where) + (iszero(value) || _WINDOW[1] <= abs(value) <= _WINDOW[2]) || throw(_window_error(name, value, where, _WINDOW...)) + return nothing +end +function _check_product_window(name, value, where) + (iszero(value) || _PRODUCT_WINDOW[1] <= abs(value) <= _PRODUCT_WINDOW[2]) || + throw(_window_error(name, value, where, _PRODUCT_WINDOW...)) + return nothing +end +_check_window_sources(values) = foreach(v -> _check_window("a source amplitude", v, nothing), values) + # The terms of lower order than the curl-curl, each judged on its own, with exact symbolic zero tests rather than # tolerances relative to the other coefficients, which a large one would hide behind: there is no first-order term, # the coefficients of E, ∂ₜE and ∂ₜ²E of an equation do not couple the components, and each is the same scalar @@ -343,6 +367,11 @@ cell gets `MaxwellMaterial(eps_r = a₂ - a₀/ω², mu_r = 1/ν, sigma = a₁)` `∫ f ⋅ Nᵢ`. Boundary conditions are the perfect conductor `cross(facet_normal(Γ), [E(t, Γ)[c] for c in 1:3]) .~ 0`; pieces without a condition get the natural `n × (ν curl E) = 0`. A complex permittivity has no real time-domain form here; build a `MaxwellModel` directly for it. + +The front end works in a window: every nonzero ν, a₀, a₁, a₂ and source amplitude and ω lie in `1e-100 ≤ |c| ≤ 1e100`, +and the products `ω² a₂` and `ω a₁` in `1e-250 ≤ |c| ≤ 1e250`. This is far wider than SI-unit physics +(ε₀ ≈ 8.85e-12, μ₀⁻¹ ≈ 8e5, ω up to 1e12) and keeps products with mesh quantities from underflowing; outside it +an `ArgumentError` names the coefficient and asks for a nondimensionalised equation. """ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) disc.omega === nothing && @@ -387,10 +416,20 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio coefficient_at = compile([coeffs.nu, coeffs.a0, coeffs.a1, coeffs.a2]) source_at = compile(coeffs.sources) ω = disc.omega + _check_window("ω", ω, nothing) + for x in centroids + _check_window_sources(_real_values(source_at(x...), "a source")) + end materials = map(enumerate(centroids)) do (cell, x) nu, a0, a1, a2 = _real_values(coefficient_at(x...), "a coefficient") (iszero(nu) || iszero(1 / nu) || !isfinite(1 / nu)) && throw(ArgumentError("ν = $nu in cell $cell; ν = 1/μ must be nonzero" * (iszero(nu) ? "" : " and 1/ν must be representable"))) + for (name, value) in (("ν", nu), ("a₀", a0), ("a₁", a1), ("a₂", a2)) + _check_window(name, value, cell) + end + for (name, value) in (("ω² a₂", ω^2 * a2), ("ω a₁", ω * a1)) + _check_product_window(name, value, cell) + end # The net reaction a₀ - ω² a₂ is formed exactly (it cancels when the two are large), then divided once. all(isfinite, (a0, a2, ω)) || throw( ArgumentError("the reaction a₀ - ω² a₂ ($a0 - $ω^2 $a2) in cell $cell is not representable as ε = a₂ - a₀/ω²; the coefficients must be finite") diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 51ad8e14..83d2a5e8 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -196,19 +196,26 @@ end "the zeroth-order term of equation 1 couples the components of E; the coefficients of E and its time derivatives must be scalars" end -@testset "a frequency too small for the reaction coefficient is rejected, not turned into NaN" begin +@testset "coefficients outside the supported window are rejected, not turned into NaN or silent underflow" begin Ω = MeshDomain(unit_cube(1)) - for (ω, a0) in ((1.0e-160, 1.0),) - @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0), maxwell_disc(Ω, ω)))) - end - # The net reaction a₀ - ω² a₂ = 8.4e-17 is exactly representable, but ε = -net/ω² underflows to zero. - @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; a0 = 5.0, a2 = 5.0e-308), maxwell_disc(Ω, 1.0e154)))) - # ω² rounds to the subnormal 5e-324, so assembly would form -4.94e-16 for the exact net reaction -4e-16. - @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 1.0e308, a0 = 0.0, f = [-4.0e-16, 0.0, 0.0]), maxwell_disc(Ω, 2.0e-162)))) - # ω² is the smallest normal number and every scalar round trip is exact, but the assembled reaction and load underflow. - @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-307, a0 = 2.0^-1074, f = [2.0^-1074, 0.0, 0.0]), maxwell_disc(Ω, 2.0^-511)))) - # a0/ω² underflows to zero next to a dominant curl-curl term, so the reaction would be silently dropped. - @test occursin("not representable", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-30, a2 = 0, a0 = 1.0e-20), maxwell_disc(Ω, 1.0e154)))) + outside(ω; kw...) = occursin("supported window", message(() -> discretize(maxwell_system(Ω; kw...), maxwell_disc(Ω, ω)))) + @test outside(1.0e-160; a0 = 1.0) + @test outside(1.0e154; a0 = 5.0, a2 = 5.0e-308) # the net reaction 8.4e-17 against ε = -net/ω² underflowing + @test outside(2.0e-162; nu = 1.0e-30, a2 = 1.0e308, a0 = 0.0, f = [-4.0e-16, 0.0, 0.0]) # ω² subnormal + @test outside(2.0^-511; nu = 1.0e-307, a0 = 2.0^-1074, f = [2.0^-1074, 0.0, 0.0]) # assembled reaction and load underflow + @test outside(1.0e154; nu = 1.0e-30, a2 = 0, a0 = 1.0e-20) + @test outside(1.0e154; nu = 1.0e-180, a0 = 0, a2 = 0, a1 = 2.0^-1074) # the conductivity block underflows in assembly + @test outside(1.0; nu = 1.0e101) + @test outside(1.0; f = [1.0e-101, 0.0, 0.0]) + # SI-scale physics is well inside the window: ε₀, 1/μ₀, ω = 2π 10 GHz and the conductivity of copper. + ε0, ν, σ, ω = 8.854187817e-12, 1 / (4π * 1.0e-7), 5.8e7, 2π * 1.0e10 + sys = maxwell_system(Ω; nu = ν, a2 = ε0, a1 = σ, f = [1.0, 0.0, 0.0]) + disc = maxwell_disc(Ω, ω) + (; model) = maxwell_model(sys, disc) + prob = discretize(sys, disc) + E = field_values(MaxwellSolution(model, ω, prob.A \ prob.b), [Vec(0.3, 0.4, 0.5)]).E[1] + reaction = -ω^2 * ε0 + im * ω * σ + @test collect(E) ≈ [1 / reaction, 0, 0] rtol = 1.0e-6 end @testset "a large reaction coefficient hides no other coefficient" begin From 297190b342334dcd2b472d48df49b5aaea4d4320 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 07:41:01 +0000 Subject: [PATCH 23/26] Front end: a zero assembled load is legitimate, not an underflow A source supported between the quadrature points integrates to an exactly zero load without any arithmetic underflow, and the window already keeps sources and mesh quantities from underflowing, so the check of the final load vector is removed. The assembled reaction check stays: it only looks at entries that are nonzero in the unscaled block. Agent-Harness: Claude Code 2.1.322 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/maxwell/frontend.jl | 14 ++++++-------- test/Maxwell/frontend.jl | 10 ++++++++++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index e0bd1cd3..8074866e 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -452,20 +452,18 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio model = MaxwellModel( grid; materials, pec, eps0 = 1.0, mu0 = 1.0, length_scale = 1.0, quadrature = something(disc.quadrature, 2) ) - # The scalar round trips cannot see underflow during integration and scaling: the reaction contribution and the load - # that are actually assembled must keep a nonzero reaction or source, neither lost to zero nor subnormal. + # The scalar round trips cannot see underflow during integration and scaling: every entry of the assembled reaction + # block that is nonzero must stay nonzero and normal after its coefficient is applied (entries that are exactly zero, + # as on cells without reaction, are not a loss). reaction_term = model.terms[2] # the eps_real block with its coefficient -ω² (mu0 = eps0 = L = 1) reaction_entries = real(reaction_term.coefficient(ω)) .* nonzeros(reaction_term.block) lost_entries(x) = iszero(x) || issubnormal(x) any(lost_entries, reaction_entries[findall(!iszero, nonzeros(reaction_term.block))]) && throw( ArgumentError("the reaction of the equation is not representable after assembly at ω = $ω: its matrix entries underflow to zero or subnormal values; scale the equation or use a MaxwellModel directly") ) - load = _source_load(model, x -> _real_values(source_at(x...), "a source")) - sourced = any(x -> any(!iszero, _real_values(source_at(x...), "a source")), centroids) - sourced && (lost_entries(maximum(abs, load; init = 0.0)) || all(lost_entries, load)) && throw( - ArgumentError("the source of the equation is not representable after assembly: its load vector underflows to zero or subnormal values; scale the equation or use a MaxwellModel directly") - ) - return (; model, omega = ω, load) + # A source cannot underflow in integration inside the window, and a load that is exactly zero is legitimate (a + # source supported between the quadrature points), so the load is not checked. + return (; model, omega = ω, load = _source_load(model, x -> _real_values(source_at(x...), "a source"))) end function _real_values(values, what) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 83d2a5e8..0ad5a770 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -350,6 +350,16 @@ end end end +@testset "a source with no quadrature point in its support gives a zero load, not an underflow error" begin + Ω = MeshDomain(unit_cube(1)) + xc = sum(Ferrite.getcoordinates(Ω.mesh, 1)) / 4 + r = 1.0e-3 + bump = ifelse(sum((X[i] - xc[i])^2 for i in 1:3) < r^2, 1.0, 0.0) + sys = maxwell_system(Ω; f = [bump, 0.0, 0.0]) + prob = discretize(sys, maxwell_disc(Ω, 1.0)) + @test prob isa LinearProblem && iszero(prob.b) +end + @testset "structural terms are rejected however small they are next to ν" begin Ω = MeshDomain(unit_cube(2)) D = Differential.(collect(X)) From cd513f81e7f8bfaee142f27670b79caff1fbb4ca Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 07:51:31 +0000 Subject: [PATCH 24/26] Front end: validate the source at every quadrature point, finiteness after conversion The window check saw only the cell centroids, so a source supported around a quadrature point with a huge or subnormal amplitude bypassed it, and a finite BigFloat 1e400 passed the finiteness test before becoming Inf as a Float64. The load assembly now evaluates a validated source (window on every value) and values are converted to Float64 before the finiteness test. 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/frontend.jl | 15 ++++++++++----- test/Maxwell/frontend.jl | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 8074866e..88d6feea 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -461,15 +461,20 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio any(lost_entries, reaction_entries[findall(!iszero, nonzeros(reaction_term.block))]) && throw( ArgumentError("the reaction of the equation is not representable after assembly at ω = $ω: its matrix entries underflow to zero or subnormal values; scale the equation or use a MaxwellModel directly") ) - # A source cannot underflow in integration inside the window, and a load that is exactly zero is legitimate (a - # source supported between the quadrature points), so the load is not checked. - return (; model, omega = ω, load = _source_load(model, x -> _real_values(source_at(x...), "a source"))) + # Every value the load assembly evaluates, at the quadrature points, is validated against the window (the centroid + # check above is only an early, cheap error); a load that is exactly zero is legitimate (a source supported between + # the quadrature points), so the load vector itself is not checked. + checked_source(x) = (v = _real_values(source_at(x...), "a source"); _check_window_sources(v); v) + return (; model, omega = ω, load = _source_load(model, checked_source)) end function _real_values(values, what) - all(v -> v isa Real && isfinite(v), values) || + all(v -> v isa Real, values) || throw(ArgumentError("$what of the Maxwell equation evaluates to $values; it must be real and finite")) - return Float64.(values) + converted = Float64.(values) # finiteness is checked after the conversion: a finite BigFloat 1e400 becomes Inf + all(isfinite, converted) || + throw(ArgumentError("$what of the Maxwell equation evaluates to $values; it must be real and finite as a Float64")) + return converted end # ∫ f ⋅ Nᵢ for the source f(x) of the equation. diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 0ad5a770..57157537 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -360,6 +360,20 @@ end @test prob isa LinearProblem && iszero(prob.b) end +@testset "source amplitudes are validated at the quadrature points" begin + Ω = MeshDomain(unit_cube(1)) + cell = Ferrite.getcoordinates(Ω.mesh, 1) + # The first point of the degree-2 rule of the reference tetrahedron, mapped to cell 1: not a centroid. + ξ = Ferrite.QuadratureRule{RefTetrahedron}(2).points[1] + xq = cell[1] + ξ[1] * (cell[2] - cell[1]) + ξ[2] * (cell[3] - cell[1]) + ξ[3] * (cell[4] - cell[1]) + ball(amplitude, r = 1.0e-3) = ifelse(sum((X[i] - xq[i])^2 for i in 1:3) < r^2, amplitude, 0.0) + solve(amplitude) = discretize(maxwell_system(Ω; f = [ball(amplitude), 0.0, 0.0]), maxwell_disc(Ω, 1.0)) + @test solve(1.0) isa LinearProblem # inside the window, evaluated at a quadrature point + @test occursin("must be real and finite as a Float64", message(() -> solve(big"1e400"))) + @test occursin("supported window", message(() -> solve(2.0^-1074))) + @test occursin("supported window", message(() -> solve(1.0e-101))) +end + @testset "structural terms are rejected however small they are next to ν" begin Ω = MeshDomain(unit_cube(2)) D = Differential.(collect(X)) From 1c096da6c8d26fd766804950d45f302d35f04b1c Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 08:02:47 +0000 Subject: [PATCH 25/26] Front end: reject nonzero values that underflow in the Float64 conversion BigFloat 1e-400 became an exact 0.0 before the window check, which exempts zero, so a nonzero source, reaction, conductivity or nu was silently erased. The shared conversion now rejects a nonzero value whose Float64 is zero or subnormal with the window error, after the finiteness test on the converted value. 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/frontend.jl | 5 +++++ test/Maxwell/frontend.jl | 17 ++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index 88d6feea..ab4f51e2 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -472,6 +472,11 @@ function _real_values(values, what) all(v -> v isa Real, values) || throw(ArgumentError("$what of the Maxwell equation evaluates to $values; it must be real and finite")) converted = Float64.(values) # finiteness is checked after the conversion: a finite BigFloat 1e400 becomes Inf + # A nonzero value that the conversion turns into zero or a subnormal number is outside the window as well. + for (v, c) in zip(values, converted) + iszero(v) || !(iszero(c) || issubnormal(c)) || + throw(_window_error(what, v, nothing, _WINDOW...)) + end all(isfinite, converted) || throw(ArgumentError("$what of the Maxwell equation evaluates to $values; it must be real and finite as a Float64")) return converted diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 57157537..98d00c1a 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -157,7 +157,7 @@ end err("a source of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude"; f = [sin(t), 0, 0]) err("a coefficient of the Maxwell equation depends on time; with omega the coefficients and sources are time-independent, and a source is the phasor amplitude"; a2 = 1 + t) err("ν = 0.0 in cell 1; ν = 1/μ must be nonzero"; nu = 0) - err("ν = 1.0e-309 in cell 1; ν = 1/μ must be nonzero and 1/ν must be representable"; nu = 1.0e-309, a2 = 1.0e-309) + @test occursin("supported window", message(() -> discretize(maxwell_system(Ω; nu = 1.0e-309, a2 = 1.0e-309), maxwell_disc(Ω, 1.0)))) # subnormal @test_throws ArgumentError discretize(maxwell_system(Ω; extra = c -> Dt(Dt(Dt(Ev[c])))), maxwell_disc(Ω, 1.0)) # A second derivative of a field-free expression lands in the flux; it must not vanish from the load. @@ -374,6 +374,21 @@ end @test occursin("supported window", message(() -> solve(1.0e-101))) end +@testset "a nonzero value that underflows in the conversion to Float64 is rejected" begin + Ω = MeshDomain(unit_cube(1)) + tiny = big"1e-400" + run(; kw...) = message(() -> discretize(maxwell_system(Ω; kw...), maxwell_disc(Ω, 1.0))) + for kw in ((; f = [tiny, 0.0, 0.0]), (; a0 = tiny), (; a2 = tiny), (; a1 = tiny), (; nu = tiny)) + @test occursin("supported window", run(; kw...)) + end + # ω = 1e-400 is not a positive Float64 either. + @test message(() -> discretize(maxwell_system(Ω), maxwell_disc(Ω, tiny))) != "no error" + # Exact zeros of any type are fine. + for zero_value in (0, 0.0, big"0") + @test discretize(maxwell_system(Ω; a1 = zero_value, f = [zero_value, 0.0, 0.0]), maxwell_disc(Ω, 1.0)) isa LinearProblem + end +end + @testset "structural terms are rejected however small they are next to ν" begin Ω = MeshDomain(unit_cube(2)) D = Differential.(collect(X)) From ddd2dc3e5df7578f3ca25c1660387b7c7e555d86 Mon Sep 17 00:00:00 2001 From: t Date: Fri, 13 Nov 2026 08:11:34 +0000 Subject: [PATCH 26/26] Front end: validate parameter values before the Float64 conversion A parameter given as BigFloat 1e-400 became an exact 0.0 in _parameter_values before the coefficient and source checks, so a parameterised source, reaction or conductivity was silently erased, and 1e400 became Inf. The values are checked at the entry of the Maxwell front end: a nonzero value that converts to zero or subnormal is a window error naming the parameter, a non-finite one a finiteness error. 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/frontend.jl | 17 +++++++++++++++++ test/Maxwell/frontend.jl | 13 +++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/maxwell/frontend.jl b/src/maxwell/frontend.jl index ab4f51e2..33d4aa21 100644 --- a/src/maxwell/frontend.jl +++ b/src/maxwell/frontend.jl @@ -401,6 +401,7 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio pv = PDEBase.VariableMap(phasor_sys, disc; replaced_vars = replaced) an = StrongForm.analyse(phasor_sys, pv, Dict()) ctx = StrongForm.SlotContext(phasor_sys, pv) + _check_parameter_values(phasor_sys) pvals = _parameter_values(phasor_sys, ctx) js = [findfirst(isequal(unwrap(p)), ctx.params) for p in s] slot_s = an.slots.P[js] @@ -468,6 +469,22 @@ function maxwell_model(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretizatio return (; model, omega = ω, load = _source_load(model, checked_source)) end +# The numeric values given for the parameters of the PDESystem, before `_parameter_values` converts them to Float64: a +# nonzero value that converts to zero or a subnormal number is outside the window, and one that converts to Inf or NaN +# is not finite, so neither can reach the coefficients and sources as a silent zero. +function _check_parameter_values(pdesys) + ps = pdesys.ps isa SciMLBase.NullParameters ? () : pdesys.ps + for p in ps + p isa Pair && p.second isa Real || continue + value, converted = p.second, Float64(p.second) + isfinite(converted) || + throw(ArgumentError("the parameter $(p.first) = $value must be real and finite as a Float64")) + iszero(value) || !(iszero(converted) || issubnormal(converted)) || + throw(_window_error("the parameter $(p.first)", value, nothing, _WINDOW...)) + end + return nothing +end + function _real_values(values, what) all(v -> v isa Real, values) || throw(ArgumentError("$what of the Maxwell equation evaluates to $values; it must be real and finite")) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl index 98d00c1a..2ddcc6e3 100644 --- a/test/Maxwell/frontend.jl +++ b/test/Maxwell/frontend.jl @@ -389,6 +389,19 @@ end end end +@testset "parameter values are validated before they become Float64" begin + Ω = MeshDomain(unit_cube(1)) + @parameters p + run(value; kw...) = message(() -> discretize(maxwell_system(Ω; ps = [p => value], kw...), maxwell_disc(Ω, 1.0))) + for kw in ((; f = [p, 0.0, 0.0]), (; a0 = p), (; a2 = p), (; a1 = p), (; nu = p)) + @test occursin("supported window", run(big"1e-400"; kw...)) + @test occursin("real and finite as a Float64", run(big"1e400"; kw...)) + end + # Exact zero and in-window parameters are accepted. + @test discretize(maxwell_system(Ω; ps = [p => big"0"], f = [p, 0.0, 0.0]), maxwell_disc(Ω, 1.0)) isa LinearProblem + @test discretize(maxwell_system(Ω; ps = [p => 2.5], a2 = p), maxwell_disc(Ω, 1.0)) isa LinearProblem +end + @testset "structural terms are rejected however small they are next to ν" begin Ω = MeshDomain(unit_cube(2)) D = Differential.(collect(X))