Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
628b8b4
Add a PDESystem front end for the frequency-domain Maxwell model
Nov 6, 2026
709d22d
Check the Maxwell coefficients at every cell centroid and reject othe…
Nov 6, 2026
840e8f3
Reject Maxwell equation parts the front end would drop
Nov 6, 2026
f6ea005
Check perfect-conductor conditions at the actual facet normals
Nov 6, 2026
1285509
Merge maxwell/1-core into maxwell/9-frontend-f1 (PR workflow triggers)
Nov 6, 2026
009b9ab
Merge forge/mwsync-1-core into maxwell/9-frontend-f1
Nov 10, 2026
42a7fb0
Judge a zeroth-order coupling against the zeroth-order coefficients
Nov 10, 2026
7dbaddc
Check first-order terms of the Maxwell equation against roundoff, not…
Nov 10, 2026
21a4fe9
Judge the second-order part of the Maxwell equation against itself
Nov 10, 2026
fc1a35a
Merge forge/mwsync-1-core into 9-frontend-f1
Nov 11, 2026
06eaf1d
Merge forge/mwsync-1-core into 9-frontend-f1
Nov 11, 2026
e9e45b7
Maxwell front end: judge lower-order coefficients one by one, local f…
Nov 12, 2026
d0fe18f
Maxwell front end: reject a frequency whose reaction coefficient is n…
Nov 12, 2026
7228d18
Maxwell front end: lower-order roundoff tolerance relative to the equ…
Nov 12, 2026
da23b52
Maxwell front end: do not shadow the compiled diagonal in the zero test
Nov 12, 2026
c537d65
Maxwell front end: exact zero tests for lower-order coefficients
Nov 12, 2026
df877de
FEMDiscretization: omega squared must be representable
Nov 12, 2026
a48254f
Maxwell front end: reject a nu whose reciprocal is not representable
Nov 12, 2026
8bcc28d
Maxwell front end: reject a reaction coefficient lost to underflow in…
Nov 12, 2026
339563c
Merge forge/mwsync-1-core into 9-frontend-f1
Nov 12, 2026
e25564c
Front end: compare component coefficients exactly
Nov 12, 2026
7984b0e
Front end: exact net reaction, symbolic structure checks, trace argum…
Nov 13, 2026
70e4b3e
Front end: reject a net reaction lost to underflow after cancellation
Nov 13, 2026
20ca571
Front end: form the net reaction in exact rational arithmetic
Nov 13, 2026
732f87c
Front end: check the reaction by round trip through assembly
Nov 13, 2026
6d8bd32
Front end: reject a reaction or source lost to underflow in assembly
Nov 13, 2026
8c553cc
Front end: one explicit working window for coefficients, source ampli…
Nov 13, 2026
297190b
Front end: a zero assembled load is legitimate, not an underflow
Nov 13, 2026
cd513f8
Front end: validate the source at every quadrature point, finiteness …
Nov 13, 2026
1c096da
Front end: reject nonzero values that underflow in the Float64 conver…
Nov 13, 2026
ddd2dc3
Front end: validate parameter values before the Float64 conversion
Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/src/boundary_conditions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
41 changes: 41 additions & 0 deletions docs/src/maxwell.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions src/FiniteElementMethod.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")

Expand Down
38 changes: 35 additions & 3 deletions src/discretization.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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))"))
Expand All @@ -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)
Expand Down Expand Up @@ -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.
"""
)
28 changes: 22 additions & 6 deletions src/frontend.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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))
Expand Down Expand Up @@ -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...)
Expand Down Expand Up @@ -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; " *
Expand Down Expand Up @@ -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; " *
Expand Down Expand Up @@ -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"))
Expand Down
17 changes: 17 additions & 0 deletions src/maxwell/driven.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Loading
Loading