diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 3ac89999..227f53cc 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..5b86fdb4 100644 --- a/docs/src/maxwell.md +++ b/docs/src/maxwell.md @@ -30,6 +30,47 @@ 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). + +```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 +``` + +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 MaxwellModel MaxwellMaterial diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 390c330a..75182d98 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 @@ -52,11 +52,14 @@ export MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative # The integration-by-parts policy `ibp = Dict(eq => Weighted(w))` of `FEMDiscretization`. export Weighted -# 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 b8cdcdf8..c004a882 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 the steady `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,36 @@ 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 + # The value is stored as a Float64, so a BigFloat beyond its range (1e-400, 1e400) is judged after the conversion. + # 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)") + ) + 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 +239,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 67410165..64c84a00 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,19 +529,29 @@ function _abstol(algebraic, ops, selfnonlinear, abstol) return (; abstol = [d ? differential : algebraic for d in ops.differential_vars]) end +# 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...) Base.depwarn("`DAEProblem(pdesys, disc)` is deprecated, use `discretize(pdesys, disc)` instead", :DAEProblem) return _daeproblem(pdesys, disc; kwargs...) end -_daeproblem(pdesys, disc; kwargs...) = - disc.time === nothing ? - throw( +function _daeproblem(pdesys, disc; 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)" + "call discretize(pdesys, disc)" ) - ) : SciMLBase.discretize(pdesys, disc; kwargs...) + ) + return SciMLBase.discretize(pdesys, disc; kwargs...) +end """ NonlinearProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) @@ -567,6 +580,7 @@ function SciMLBase.NonlinearProblem(pdesys::ModelingToolkit.PDESystem, disc::FEM end function _nonlinearproblem(pdesys, disc; kwargs...) + _reject_omega(disc, "NonlinearProblem") disc.time === nothing || throw( ArgumentError( "the FEMDiscretization has the time variable $(disc.time), so it lowers to a DAEProblem; " * @@ -605,6 +619,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; " * @@ -641,6 +656,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 772ead19..7897ae6c 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..33d4aa21 --- /dev/null +++ b/src/maxwell/frontend.jl @@ -0,0 +1,530 @@ +# 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 + +# 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 `Γ`, 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(Γ)}) && return PDEBase.normal(Γ) + return [Num(SymbolicUtils.term(PieceNormal(Γ), d; type = Real)) for d in 1:3] +end + +# 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) + 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)" + +# `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, 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) + 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, inside || op isa Differential), 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) + 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) + 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 + +_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 +# 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] + state = [slots.U; slots.G] + nonlinear(e) = ArgumentError("the Maxwell front end discretizes linear equations only, but equation $e is nonlinear in E") + 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])] + # 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 + 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) + # 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] + 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 = [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 + _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 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 +# 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: 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 + g = Symbolics.build_function(exs[open], X...; expression = Val(false))[1] + big = falses(length(open)) + for x in xs + big .|= .!iszero.(_real_values(g(x...), "a coefficient")) + 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") + ) + 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] + # 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 + 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 + end + 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) + 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) + 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) + 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 + 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")) + 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)))" + # 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( + ArgumentError("the conditions $where constrain $(rank(Cn)) of the two tangential components of E; $pform") + ) + end + end + return sort!(String.(collect(keys(byp)))) +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. + +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 && + 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) + _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] + keep = setdiff(eachindex(ctx.params), js) + 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], t = ctx.t), disc.domain) + + # Compile the coefficients and sources as functions of the mesh coordinate. + 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 + _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") + ) + # 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) + # 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) && + !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") + ) + 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) + ) + # 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") + ) + # 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 + +# 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")) + 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 +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 d7fcd1fa..a3deb046 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 local edge dofs and the local nodes of each face of a tetrahedron, in Ferrite's facet order (checked against # Ferrite in the tests): Ferrite's own spellings of these are not public. const _TET_FACET_EDGE_DOFS = ((3, 2, 1), (1, 5, 4), (2, 6, 5), (4, 6, 3)) diff --git a/test/Maxwell/frontend.jl b/test/Maxwell/frontend.jl new file mode 100644 index 00000000..2ddcc6e3 --- /dev/null +++ b/test/Maxwell/frontend.jl @@ -0,0 +1,431 @@ +# The PDESystem front end of the Maxwell model, against the operator-level MaxwellModel as oracle. Tests with a +# 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 +using FiniteElementMethod: PDEBase +using Symbolics: expand_derivatives +include(joinpath(@__DIR__, "..", "shared", "maxwell.jl")) + +@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) +# 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)]) + @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, 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()) + @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 = 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 = 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) + @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 + ε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 + Ω = 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)]) + 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]) + 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 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. + @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))) + ) + + # 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)]) + + # 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]))) + + # 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) + 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 "coefficients outside the supported window are rejected, not turned into NaN or silent underflow" begin + Ω = MeshDomain(unit_cube(1)) + 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 + Ω = 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])) + # 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 + +@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)) + + 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}())) + ) + + disc = maxwell_disc(Ω, 1.0) + for (f, what) in ((FiniteElementMethod._daeproblem, "DAEProblem"), (FiniteElementMethod._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 + Ω = 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 + +@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 "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 "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 "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 "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 "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)) + 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 diff --git a/test/qa/qa.jl b/test/qa/qa.jl index 2227ee5c..be7485f6 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 weighted integration by parts, and Ferrite's interpolations. reexports_allow = ( :MeshDomain, :Region, :boundarypiece, :boundarypieces, :NormalDerivative, :Lagrange, - :RefLine, :RefTriangle, :RefQuadrilateral, :RefTetrahedron, :RefHexahedron, :Weighted, + :RefLine, :RefTriangle, :RefQuadrilateral, :RefTetrahedron, :RefHexahedron, :curl, :Weighted, ), )