From 2830673f4e5ff013c392568dcb0d7b5447cd7a31 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 09:32:49 +0000 Subject: [PATCH 01/62] Support time-last dependent variables in the front end and solution wrapper The spec (section 7.8) and the MOL-pattern table place the time axis by each dependent variable's declared argument order, as MethodOfLines does; the front end rejected u(x, y, t). PDEBase already lowers time-last initial, Dirichlet and Neumann conditions, so the check now rejects only time between spatial arguments, and the solution wrapper puts the time axis of arrays, traces, gradients, normal fluxes and call arguments last for a time-last field. sol(args...) without dv throws when fields put time in different positions. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/solution.md | 16 ++- src/frontend.jl | 4 +- src/solution.jl | 73 ++++++++---- test/Frontend/time_last.jl | 9 ++ test/shared/frontend_tests/errors.jl | 10 +- test/shared/frontend_tests/time_last.jl | 152 ++++++++++++++++++++++++ 6 files changed, 233 insertions(+), 31 deletions(-) create mode 100644 test/Frontend/time_last.jl create mode 100644 test/shared/frontend_tests/time_last.jl diff --git a/docs/src/solution.md b/docs/src/solution.md index 9a64decc..a154201b 100644 --- a/docs/src/solution.md +++ b/docs/src/solution.md @@ -11,12 +11,26 @@ A mesh domain carries no coordinate names. The names and their order come only f `(x, y) ∈ Ω` pairing of the `PDESystem`: tuple position `i` is coordinate component `i` of the mesh. The same pairing orders `sol[x]`, `sol[y]` and the arguments of `sol(t, x, y)`. +## Time axis + +The time axis goes first or last according to the declared argument order of each dependent +variable, as in MethodOfLines. For a time-first `u(t, x, y)` the arrays below are +`nt × nvertices` and calls take the time first, `sol(t, x, y; dv)`. For a time-last +`u(x, y, t)` every array keyed by that field is transposed, `nvertices × nt` (the trace +`sol[u(Γ, t)]`, the gradient `sol[Differential(x)(u(x, y, t))]` and `normal_flux` too), and +calls take the time last: `sol(x, y, t; dv)`, `sol(Γ, t; dv)`, `sol(pts, t; dv)`. With +vector arguments `sol(xs, ys, ts; dv)` is `length(xs) × length(ys) × length(ts)`. Fields of +one system may differ; `sol(args...)` without `dv` then throws, because the position of the +time argument is ambiguous. Time between two spatial arguments, `u(x, t, y)`, is rejected by +`discretize`. + ## Shapes that differ from MethodOfLines - `sol[x]` is the vector of mesh vertex coordinates, not an axis grid, so tensor-grid plotting calls such as `heatmap(sol[x], sol[y], …)` fail with a shape error. Resample with `sol(t, xs, ys; dv = u(t, x, y))` instead. - - `sol[u(t, x, y)]` is `nt × nvertices`, and column `i` pairs with `(sol[x][i], sol[y][i])`. + - `sol[u(t, x, y)]` is `nt × nvertices` (`nvertices × nt` for `u(x, y, t)`), and vertex + `i` pairs with `(sol[x][i], sol[y][i])`. For a P2 field the edge dofs are not included; `sol[u(t, x, y), k, :]` is the row at `t_k`. - The raw dof coefficients are in `sol.original_sol`, for example `sol.original_sol[u_arr]` for the array unknown of a field. diff --git a/src/frontend.jl b/src/frontend.jl index 6c493082..2ff77070 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -77,8 +77,8 @@ function PDEBase.interface_errors(pdesys::ModelingToolkit.PDESystem, v::PDEBase. t = v.time for u in dvs args = SymbolicUtils.arguments(unwrap(u)) - t !== nothing && any(a -> isequal(a, t), args) && !isequal(first(args), t) && - throw(ArgumentError("time must be the first argument of $u; time-last ordering lands later")) + t !== nothing && any(a -> isequal(a, t), args[2:(end - 1)]) && + throw(ArgumentError("time must be the first or the last argument of $u, as in u(t, x, y) or u(x, y, t)")) end grid = disc.domain.mesh if !isconcretetype(Ferrite.getcelltype(grid)) diff --git a/src/solution.jl b/src/solution.jl index 98c0911b..ae292bcf 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -109,6 +109,11 @@ _grid(md::FEMMetadata) = _dh(md).grid _geometry(md::FEMMetadata) = Ferrite.geometric_interpolation(Ferrite.getcelltype(_grid(md))) _vertex_coordinates(md, d) = [Ferrite.get_node_coordinate(n)[d] for n in Ferrite.getnodes(_grid(md))] +# The time axis of a field's arrays and call arguments goes first or last as in its declared +# arguments, `u(t, x, y)` or `u(x, y, t)`, as in MethodOfLines (MOL timedep.jl:74-86). +_time_last(md::FEMMetadata, f::FieldInfo) = + md.time !== nothing && isequal(last(SymbolicUtils.arguments(Symbolics.unwrap(f.dv))), Symbolics.unwrap(md.time)) + function _wrap_parts(sol, md::FEMMetadata, states) nt = length(states) T = eltype(first(states)) @@ -118,7 +123,7 @@ function _wrap_parts(sol, md::FEMMetadata, states) for (k, U) in enumerate(states) out[k, :] .= Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name) end - umap[Num(f.dv)] = out + umap[Num(f.dv)] = _time_last(md, f) ? permutedims(out) : out end xs = ntuple(d -> _vertex_coordinates(md, d), length(md.x̄)) dvs = [Num(f.dv) for f in md.fields] @@ -166,10 +171,11 @@ end _states(A::FEMTimeSolution) = A.original_sol.u _states(A::FEMSteadySolution) = [A.original_sol.u] -_stack(::FEMTimeSolution, rows) = permutedims(reduce(hcat, rows)) -_stack(::FEMSteadySolution, rows) = only(rows) -_columns(values::AbstractMatrix, idxs) = values[:, idxs] -_columns(values::AbstractVector, idxs) = values[idxs] +# `rows` holds one row per saved time. +_stack(A::FEMTimeSolution, f, rows) = _time_last(A.disc_data, f) ? reduce(hcat, rows) : permutedims(reduce(hcat, rows)) +_stack(::FEMSteadySolution, f, rows) = only(rows) +_columns(A, f, values::AbstractMatrix, idxs) = _time_last(A.disc_data, f) ? values[idxs, :] : values[:, idxs] +_columns(A, f, values::AbstractVector, idxs) = values[idxs] function _fieldinfo(md, s) SymbolicUtils.iscall(s) || return nothing @@ -197,8 +203,8 @@ _sorted_facets(md, Γ) = sort!(collect(_facetset(md, Γ)); by = fi -> (fi[1], fi piece_nodes(sol, Γ) Sorted vertex ids of the boundary piece `Γ`. They are the columns of `sol[u(t, Γ)]` and -`sol(t, Γ; dv)`, and they index `sol[x]`, so `sol[x][piece_nodes(sol, Γ)]` are the -coordinates of the trace values. +`sol(t, Γ; dv)` (the rows of `sol[u(Γ, t)]` for a time-last `u(x, y, t)`), and they index +`sol[x]`, so `sol[x][piece_nodes(sol, Γ)]` are the coordinates of the trace values. """ piece_nodes(A::FEMSolution, Γ) = piece_nodes(A.disc_data, Γ) function piece_nodes(md::FEMMetadata, Γ) @@ -236,14 +242,15 @@ end normal_flux(sol, dv, Γ) Facet-mean outward normal derivative `∇u·n` of the field `dv` on every facet of the boundary -piece `Γ`, `nt × nfacets` (a vector for a steady solution). Facets are ordered by +piece `Γ`, `nt × nfacets` (`nfacets × nt` for a time-last `u(x, y, t)`, a vector for a steady +solution). Facets are ordered by `(cell, local facet)`. This is a post-processed flux, not the imposed boundary datum. """ function normal_flux(A::FEMSolution, dv, Γ) md = A.disc_data f = _fieldinfo(md, Symbolics.unwrap(dv)) f === nothing && throw(ArgumentError("$dv is not a dependent variable of this solution; they are $(A.dvs)")) - return _stack(A, [_facet_normal_flux(md, f, Γ, U) for U in _states(A)]) + return _stack(A, f, [_facet_normal_flux(md, f, Γ, U) for U in _states(A)]) end # L2 projection of the cellwise gradient onto the field's own space, assembled and factorised once @@ -313,7 +320,7 @@ function Base.getindex(A::FEMSolution, sym::Num) g = _gradkey(md, s) if g !== nothing projector = _gradient_projector(md, g[1]) - return _stack(A, [_nodal_gradient(md, g..., U, projector) for U in _states(A)]) + return _stack(A, g[1], [_nodal_gradient(md, g..., U, projector) for U in _states(A)]) end if SymbolicUtils.iscall(s) && _is_normal_derivative(SymbolicUtils.operation(s)) trace = Symbolics.unwrap(only(SymbolicUtils.arguments(s))) @@ -326,7 +333,7 @@ function Base.getindex(A::FEMSolution, sym::Num) f === nothing && _key_error(A, sym) Γ = _piece_arg(s) Γ === nothing && _key_error(A, sym) - return _columns(A.u[Num(f.dv)], piece_nodes(md, Γ)) + return _columns(A, f, A.u[Num(f.dv)], piece_nodes(md, Γ)) end Base.getindex(A::FEMSolution, sym::Num, args...) = A[sym][args...] @@ -352,19 +359,23 @@ function _point_gradient(ph, md, f, d, U) return out end -# `states` holds one dof vector per requested time; `tshape` is `(nt,)` or `()`. -function _evaluate(A::FEMSolution, states, tshape, xs, dv, outside) - md = A.disc_data - dv === nothing && return map(d -> _evaluate(A, states, tshape, xs, d, outside), A.dvs) +function _dvfield(A::FEMSolution, dv) s = Symbolics.unwrap(dv) - g = _gradkey(md, s) - f = g === nothing ? _fieldinfo(md, s) : g[1] + g = _gradkey(A.disc_data, s) + f = g === nothing ? _fieldinfo(A.disc_data, s) : g[1] f === nothing && throw(ArgumentError("dv = $dv is not a dependent variable or a first spatial derivative of one; the dependent variables are $(A.dvs)")) + return f, g +end + +# `states` holds one dof vector per requested time; `tshape` is `(nt,)` or `()`. The time axis of +# the result goes where field `f` declares its time argument. +function _evaluate(A::FEMSolution, states, tshape, xs, f, g, outside) + md = A.disc_data if length(xs) == 1 && only(xs) isa DomainSets.Domain - g === nothing || throw(ArgumentError("dv = $dv: traces of derivatives are not supported; use normal_flux(sol, dv, Γ)")) + g === nothing || throw(ArgumentError("traces of derivatives of $(f.dv) are not supported; use normal_flux(sol, dv, Γ)")) nodes = piece_nodes(md, only(xs)) rows = [Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name)[nodes] for U in states] - return isempty(tshape) ? only(rows) : permutedims(reduce(hcat, rows)) + return isempty(tshape) ? only(rows) : _stack(A, f, rows) end if length(xs) == 1 && only(xs) isa AbstractVector{<:Ferrite.Vec} pts = collect(only(xs)) @@ -389,20 +400,36 @@ function _evaluate(A::FEMSolution, states, tshape, xs, dv, outside) _point_gradient(ph, md, f, g[2], U) end shp = (tshape..., pshape...) - return isempty(shp) ? out[1] : reshape(out, shp) + isempty(shp) && return out[1] + !isempty(tshape) && _time_last(md, f) && return reshape(permutedims(out), (pshape..., tshape...)) + return reshape(out, shp) end const _CallArg = Union{Number, AbstractArray, DomainSets.Domain} # Documented in docs/src/solution.md: a docstring on a call of SciMLBase's type has no # binding of this package for Documenter to check against. -function (A::FEMTimeSolution)(t::Union{Real, AbstractVector{<:Real}}, xs::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) +function (A::FEMTimeSolution)(args::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) + if dv === nothing + allequal(_time_last(A.disc_data, f) for f in A.disc_data.fields) || throw( + ArgumentError("the dependent variables $(A.dvs) put time in different argument positions; pass dv to choose one") + ) + return map(d -> A(args...; dv = d, outside), A.dvs) + end + f, g = _dvfield(A, dv) + last_ = _time_last(A.disc_data, f) + t = isempty(args) ? nothing : last_ ? last(args) : first(args) + t isa Union{Real, AbstractVector{<:Real}} || throw( + ArgumentError("the $(last_ ? "last" : "first") argument must be a time or a vector of times, as $(f.dv) declares; got $(repr(t))") + ) + xs = last_ ? Base.front(args) : Base.tail(args) states = [_dofs_at(A, tk) for tk in _axis(t)] - return _evaluate(A, states, t isa AbstractVector ? (length(t),) : (), xs, dv, outside) + return _evaluate(A, states, t isa AbstractVector ? (length(t),) : (), xs, f, g, outside) end function (A::FEMSteadySolution)(xs::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) - return _evaluate(A, _states(A), (), xs, dv, outside) + dv === nothing && return map(d -> A(xs...; dv = d, outside), A.dvs) + return _evaluate(A, _states(A), (), xs, _dvfield(A, dv)..., outside) end _xml_escape(str) = replace(str, '&' => "&", '<' => "<", '>' => ">", '"' => """, '\'' => "'") diff --git a/test/Frontend/time_last.jl b/test/Frontend/time_last.jl new file mode 100644 index 00000000..5037ec81 --- /dev/null +++ b/test/Frontend/time_last.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "time_last.jl")) +else + @testset "time_last (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index f50b6b39..5506c3ad 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -142,12 +142,12 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] ) end - @testset "time must be the first argument" begin + @testset "time must be the first or the last argument" begin Ω = box() - eq = Dt(u(x, y, t)) ~ Dx(Dx(u(x, y, t))) + Dy(Dy(u(x, y, t))) - bcs = [u(x, y, 0) ~ 0] - @test_throws ArgumentError("time must be the first argument of u(x, y, t); time-last ordering lands later") lower( - [eq], bcs, Ω; dvs = [u(x, y, t)] + eq = Dt(u(x, t, y)) ~ Dx(Dx(u(x, t, y))) + Dy(Dy(u(x, t, y))) + bcs = [u(x, 0, y) ~ 0] + @test_throws ArgumentError("time must be the first or the last argument of u(x, t, y), as in u(t, x, y) or u(x, y, t)") lower( + [eq], bcs, Ω; dvs = [u(x, t, y)] ) end diff --git a/test/shared/frontend_tests/time_last.jl b/test/shared/frontend_tests/time_last.jl new file mode 100644 index 00000000..de8f30c1 --- /dev/null +++ b/test/shared/frontend_tests/time_last.jl @@ -0,0 +1,152 @@ +# Time-last dependent variables u(x, y, t): the front end and the solution wrapper follow the +# declared argument order, as MethodOfLines does, so arrays put the time axis last and calls take +# the time last. Each problem is checked against a manufactured solution and, where it has one, +# against the same problem written time-first. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, piece_nodes, normal_flux +using Ferrite: Triangle, Vec + +include(joinpath(@__DIR__, "..", "frontend.jl")) +include(joinpath(@__DIR__, "..", "lshape.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) v(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +const tol = 1.0e-8 + +pieces(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + +"Largest nodal error of the time-last `dv` against `exact(t, x...)`; `sol[dv]` is `nvertices × nt`." +function nodal_error_last(sol, dv, exact) + vals = sol[dv] + xs = [sol[Num(x)] for x in sol.disc_data.x̄] + return maximum(abs(vals[i, k] - exact(sol.t[k], getindex.(xs, i)...)) for i in axes(vals, 1), k in eachindex(sol.t)) +end + +# u* = (1 + x + 2y)(1 + t) with time-dependent Dirichlet and Neumann data; `U(a, b)` is +# u(t, a, b) or u(a, b, t), and `U(Γ)` the trace. +function heat_system(U, Ω, ic) + Γl, Γr, Γb, Γt = pieces(Ω) + eq = Dt(U(x, y)) ~ Dx(Dx(U(x, y))) + Dy(Dy(U(x, y))) + (1 + x + 2y) + bcs = [ + U(Γl) ~ (1 + 2y) * (1 + t), + NormalDerivative(Γr)(U(Γr)) ~ 1 + t, + U(Γb) ~ (1 + x) * (1 + t), + NormalDerivative(Γt)(U(Γt)) ~ 2 * (1 + t), + ic, + ] + return [eq], bcs +end + +@testset verbose = true "time last" begin + @testset "the same heat problem written time-first and time-last" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = pieces(Ω) + first_(a...) = u(t, a...) + last_(a...) = u(a..., t) + sol_f, _ = fem_solve(heat_system(first_, Ω, u(0, x, y) ~ 1 + x + 2y)..., Ω, (x, y), t, [u(t, x, y)]; saveat = 0.1) + sol_l, _ = fem_solve(heat_system(last_, Ω, u(x, y, 0) ~ 1 + x + 2y)..., Ω, (x, y), t, [u(x, y, t)]; saveat = 0.1) + uf, ul = u(t, x, y), u(x, y, t) + nt, nv = length(sol_f.t), length(sol_f[x]) + @test sol_l.t == sol_f.t + @test nodal_error(sol_f, uf, (t_, x_, y_) -> (1 + x_ + 2y_) * (1 + t_)) <= tol + @test nodal_error_last(sol_l, ul, (t_, x_, y_) -> (1 + x_ + 2y_) * (1 + t_)) <= tol + + # Arrays: the time axis is last. + @test size(sol_l[ul]) == (nv, nt) + @test sol_l[ul] ≈ permutedims(sol_f[uf]) atol = 1.0e-12 + @test sol_l[ul, 3, :] == sol_l[ul][3, :] + nΓ = length(piece_nodes(sol_l, Γl)) + @test size(sol_l[u(Γl, t)]) == (nΓ, nt) + @test sol_l[u(Γl, t)] ≈ permutedims(sol_f[u(t, Γl)]) atol = 1.0e-12 + @test sol_l[Dx(ul)] ≈ permutedims(sol_f[Dx(uf)]) atol = 1.0e-10 + @test size(sol_l[Dx(ul)]) == (nv, nt) + Dn = NormalDerivative(Γr) + @test sol_l[Dn(u(Γr, t))] ≈ permutedims(sol_f[Dn(u(t, Γr))]) atol = 1.0e-10 + @test normal_flux(sol_l, ul, Γr) == sol_l[Dn(u(Γr, t))] + @test size(normal_flux(sol_l, ul, Γr), 2) == nt + + # Calls: the time argument is last. + @test sol_l(0.3, 0.4, 0.55; dv = ul) ≈ sol_f(0.55, 0.3, 0.4; dv = uf) atol = 1.0e-12 + @test sol_l(0.3, 0.4, 0.55; dv = ul) ≈ (1 + 0.3 + 0.8) * 1.55 atol = 1.0e-6 + @test sol_l(0.3, 0.4, 0.55) ≈ [sol_l(0.3, 0.4, 0.55; dv = ul)] + xs, ys, ts = range(0, 1, length = 5), range(0, 1, length = 4), [0.2, 0.5, 0.9] + @test size(sol_l(xs, ys, ts; dv = ul)) == (5, 4, 3) + @test sol_l(xs, ys, ts; dv = ul) ≈ permutedims(sol_f(ts, xs, ys; dv = uf), (2, 3, 1)) atol = 1.0e-12 + @test sol_l(xs, 0.3, ts; dv = ul) ≈ permutedims(sol_f(ts, xs, 0.3; dv = uf)) atol = 1.0e-12 + @test size(sol_l(xs, ys, 0.5; dv = ul)) == (5, 4) + @test sol_l(Γl, 0.5; dv = ul) ≈ sol_f(0.5, Γl; dv = uf) atol = 1.0e-12 + @test size(sol_l(Γl, ts; dv = ul)) == (nΓ, 3) + @test sol_l(Γl, ts; dv = ul) ≈ permutedims(sol_f(ts, Γl; dv = uf)) atol = 1.0e-12 + pts = [Vec(0.2, 0.3), Vec(0.7, 0.1)] + @test sol_l(pts, ts; dv = ul) ≈ permutedims(sol_f(ts, pts; dv = uf)) atol = 1.0e-12 + @test sol_l(0.3, 0.4, 0.55; dv = Dx(ul)) ≈ sol_f(0.55, 0.3, 0.4; dv = Dx(uf)) atol = 1.0e-12 + @test_throws ArgumentError("the last argument must be a time or a vector of times, as u(x, y, t) declares; got $(repr(Γl))") sol_l( + 0.5, Γl; dv = ul + ) + @test_throws ArgumentError("the first argument must be a time or a vector of times, as u(t, x, y) declares; got $(repr(Γl))") sol_f( + Γl, 0.5; dv = uf + ) + @test_throws ArgumentError("the last argument must be a time or a vector of times, as u(x, y, t) declares; got nothing") sol_l(; dv = ul) + end + + @testset "manufactured solution with time-dependent source, Dirichlet and Neumann data" begin + # u* = (1 + x + 2y)(1 + t²) needs the source 2t(1 + x + 2y), reassembled at every t. + u_exact(t_, x_, y_) = (1 + x_ + 2y_) * (1 + t_^2) + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = pieces(Ω) + U = u(x, y, t) + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + 2t * (1 + x + 2y) + bcs = [ + u(Γl, t) ~ (1 + 2y) * (1 + t^2), + u(Γb, t) ~ (1 + x) * (1 + t^2), + NormalDerivative(Γr)(u(Γr, t)) ~ 1 + t^2, + NormalDerivative(Γt)(u(Γt, t)) ~ 2 * (1 + t^2), + u(x, y, 0) ~ 1 + x + 2y, + ] + sol, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error_last(sol, U, u_exact) <= 1.0e-6 + @test sol[u(Γl, t)] ≈ [u_exact(τ, 0.0, sol[y][i]) for i in piece_nodes(sol, Γl), τ in sol.t] atol = 1.0e-10 + end + + @testset "Gmsh L-shape" begin + u_exact(t_, x_, y_) = (1 + x_) * (1 + t_) + Ω = MeshDomain(lshape_grid(; h = 0.5)) + Γi, Γw, Γo = boundarypiece.(Ω, (:inlet, :wall, :outlet)) + U = u(x, y, t) + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x) + bcs = [u(Γi, t) ~ 1 + t, u(Γw, t) ~ (1 + x) * (1 + t), NormalDerivative(Γo)(u(Γo, t)) ~ 1 + t, u(x, y, 0) ~ 1 + x] + sol, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test nodal_error_last(sol, U, u_exact) <= tol + @test size(sol[U]) == (length(sol[x]), length(sol.t)) + @test sol[u(Γi, t)] ≈ repeat(permutedims(1 .+ sol.t), length(piece_nodes(sol, Γi))) atol = tol + @test isnan(sol(1.5, 1.5, 0.5; dv = U)) + @test sol(0.5, 1.5, [0.0, 1.0]; dv = U) ≈ u_exact.([0.0, 1.0], 0.5, 1.5) atol = tol + end + + @testset "fields with different time positions" begin + # u_t = Δu + v with the algebraic row 0 = Δv; u(t, x, y) is time-first, v(x, y, t) time-last. + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(x, y, t) + algebraic = 0 ~ Dx(Dx(v(x, y, t))) + Dy(Dy(v(x, y, t))) + bcs = [ + [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)]; + [v(Γ, t) ~ 1 + x + 2y for Γ in pieces(Ω)]; + u(0, x, y) ~ 1 + x + 2y + ] + sol, _ = fem_solve( + [parabolic, algebraic], bcs, Ω, (x, y), t, [u(t, x, y), v(x, y, t)]; pairing = Dict(algebraic => v) + ) + @test nodal_error(sol, u(t, x, y), (t_, x_, y_) -> (1 + x_ + 2y_) * (1 + t_)) <= tol + @test nodal_error_last(sol, v(x, y, t), (t_, x_, y_) -> 1 + x_ + 2y_) <= tol + nt, nv = length(sol.t), length(sol[x]) + @test size(sol[u(t, x, y)]) == (nt, nv) && size(sol[v(x, y, t)]) == (nv, nt) + @test sol(0.3, 0.4, 0.5; dv = v(x, y, t)) ≈ 1 + 0.3 + 0.8 atol = tol + @test sol(0.5, 0.3, 0.4; dv = u(t, x, y)) ≈ (1 + 0.3 + 0.8) * 1.5 atol = tol + @test_throws ArgumentError( + "the dependent variables $(sol.dvs) put time in different argument positions; pass dv to choose one" + ) sol(0.5, 0.3, 0.4) + end +end From 53d316a4bc7864f43e9e044bf799871ea41c8179 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 09:37:27 +0000 Subject: [PATCH 02/62] Evaluate observed expressions with sol[expr] and sol(t, xs...; dv = expr) Spec O9: without mtkcompile there are no observed equations, so an expression in the fields, their first spatial derivatives, time, the coordinates and the PDESystem's parameters is compiled once with build_function and broadcast over the vertex or point values of its leaves. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/solution.md | 20 ++++ src/solution.jl | 159 +++++++++++++++++++++---- test/Frontend/observed.jl | 9 ++ test/Solution/solution.jl | 4 + test/shared/frontend_tests/observed.jl | 128 ++++++++++++++++++++ 5 files changed, 295 insertions(+), 25 deletions(-) create mode 100644 test/Frontend/observed.jl create mode 100644 test/shared/frontend_tests/observed.jl diff --git a/docs/src/solution.md b/docs/src/solution.md index 9a64decc..ce159814 100644 --- a/docs/src/solution.md +++ b/docs/src/solution.md @@ -34,4 +34,24 @@ mesh. The same pairing orders `sol[x]`, `sol[y]` and the arguments of `sol(t, x, `sol(t, x, y; dv = Differential(x)(u(t, x, y)))` is the pointwise gradient. - [`normal_flux`](@ref) is a post-processed facet-mean flux `∇u·n`, not the imposed datum. +## Observed expressions + +`sol[expr]` evaluates an expression in the dependent variables, their first spatial +derivatives, the independent variables and the parameters of the `PDESystem`, for example +`sol[u(t, x, y)^2 + k * v(t, x, y)]`, `sol[2u(t, x, y)]` or `sol[x^2 + y]`. It has the shape of +`sol[u(t, x, y)]`, `nt × nvertices` (a vector for a steady solution), even when the expression +names only coordinates. `sol(t, xs, ys; dv = expr)` and `sol(t, Γ; dv = expr)` evaluate it at +points or on a boundary piece, with the shapes of a field, and `NaN` outside the mesh. + + - The expression is compiled once with `build_function` and broadcast over the vertex values + of its leaves; nothing is substituted per vertex. A first derivative such as + `Differential(x)(u(t, x, y))` uses the same values as `sol[Differential(x)(u(t, x, y))]`. + - A parameter takes the value given in the `PDESystem`, as `k => 2.0`; the front end has + assembled the operators with that value, so `remake` with a new one does not change it. + - An expression that cannot be evaluated throws an `ArgumentError` beginning + "cannot evaluate the expression … on this solution:", which names a variable that is not + of the system, a trace `u(t, Γ)` (index the trace on its own, or pass `Γ` to the call + instead), a derivative that is not a first spatial derivative, or a dependent variable at + fixed arguments such as `u(t, 0, y)`. + The docstrings are on the [API](@ref "API") page. diff --git a/src/solution.jl b/src/solution.jl index 98c0911b..7d1748a5 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -323,7 +323,16 @@ function Base.getindex(A::FEMSolution, sym::Num) return normal_flux(A, f.dv, Γ) end f = _fieldinfo(md, s) - f === nothing && _key_error(A, sym) + if f === nothing + _is_expression(s) || _key_error(A, sym) + fn, terms, kinds = _compile_observed(A, sym) + timed = A isa FEMTimeSolution + value(term, kind) = kind === :time ? A.t : + kind === :coord && timed ? permutedims(A[Num(term)]) : A[Num(term)] + nv = Ferrite.getnnodes(_grid(md)) + shape = timed ? (length(A.t), nv) : (nv,) + return _broadcast_observed(fn, shape, map(value, terms, kinds)) + end Γ = _piece_arg(s) Γ === nothing && _key_error(A, sym) return _columns(A.u[Num(f.dv)], piece_nodes(md, Γ)) @@ -352,30 +361,21 @@ function _point_gradient(ph, md, f, d, U) return out end -# `states` holds one dof vector per requested time; `tshape` is `(nt,)` or `()`. -function _evaluate(A::FEMSolution, states, tshape, xs, dv, outside) - md = A.disc_data - dv === nothing && return map(d -> _evaluate(A, states, tshape, xs, d, outside), A.dvs) - s = Symbolics.unwrap(dv) - g = _gradkey(md, s) - f = g === nothing ? _fieldinfo(md, s) : g[1] - f === nothing && throw(ArgumentError("dv = $dv is not a dependent variable or a first spatial derivative of one; the dependent variables are $(A.dvs)")) - if length(xs) == 1 && only(xs) isa DomainSets.Domain - g === nothing || throw(ArgumentError("dv = $dv: traces of derivatives are not supported; use normal_flux(sol, dv, Γ)")) - nodes = piece_nodes(md, only(xs)) - rows = [Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name)[nodes] for U in states] - return isempty(tshape) ? only(rows) : permutedims(reduce(hcat, rows)) - end +# Scattered points `pts` and the shape their values take: vector arguments give a tensor product +# and scalar arguments drop their axis. +function _points(md, xs) if length(xs) == 1 && only(xs) isa AbstractVector{<:Ferrite.Vec} pts = collect(only(xs)) - pshape = (length(pts),) - else - length(xs) == length(md.x̄) || - throw(ArgumentError("expected $(length(md.x̄)) spatial arguments $(md.x̄), got $(length(xs))")) - axes_ = map(_axis, xs) - pts = vec([Ferrite.Vec{length(xs)}(Float64.(Tuple(c))) for c in Iterators.product(axes_...)]) - pshape = Tuple(length(a) for (a, x) in zip(axes_, xs) if x isa AbstractVector) + return pts, (length(pts),) end + length(xs) == length(md.x̄) || + throw(ArgumentError("expected $(length(md.x̄)) spatial arguments $(md.x̄), got $(length(xs))")) + axes_ = map(_axis, xs) + pts = vec([Ferrite.Vec{length(xs)}(Float64.(Tuple(c))) for c in Iterators.product(axes_...)]) + return pts, Tuple(length(a) for (a, x) in zip(axes_, xs) if x isa AbstractVector) +end + +function _located(A::FEMSolution, pts, outside) ph = _handler(A.interp, pts) if outside === :error i = findfirst(isnothing, ph.cells) @@ -383,6 +383,29 @@ function _evaluate(A::FEMSolution, states, tshape, xs, dv, outside) elseif outside !== :nan throw(ArgumentError("outside must be :nan or :error, got $(repr(outside))")) end + return ph +end + +# `states` holds one dof vector per requested time `ts` (`nothing` when steady); `tshape` is +# `(nt,)` or `()`. +function _evaluate(A::FEMSolution, ts, states, tshape, xs, dv, outside) + md = A.disc_data + dv === nothing && return map(d -> _evaluate(A, ts, states, tshape, xs, d, outside), A.dvs) + s = Symbolics.unwrap(dv) + g = _gradkey(md, s) + f = g === nothing ? _fieldinfo(md, s) : g[1] + if f === nothing + _is_expression(s) && return _evaluate_observed(A, ts, states, tshape, xs, dv, outside) + throw(ArgumentError("dv = $dv is not a dependent variable or a first spatial derivative of one; the dependent variables are $(A.dvs)")) + end + if length(xs) == 1 && only(xs) isa DomainSets.Domain + g === nothing || throw(ArgumentError("dv = $dv: traces of derivatives are not supported; use normal_flux(sol, dv, Γ)")) + nodes = piece_nodes(md, only(xs)) + rows = [Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name)[nodes] for U in states] + return isempty(tshape) ? only(rows) : permutedims(reduce(hcat, rows)) + end + pts, pshape = _points(md, xs) + ph = _located(A, pts, outside) out = Matrix{eltype(first(states))}(undef, length(states), length(pts)) for (k, U) in enumerate(states) out[k, :] .= g === nothing ? Ferrite.evaluate_at_points(ph, _dh(md), U, f.name) : @@ -397,12 +420,98 @@ const _CallArg = Union{Number, AbstractArray, DomainSets.Domain} # Documented in docs/src/solution.md: a docstring on a call of SciMLBase's type has no # binding of this package for Documenter to check against. function (A::FEMTimeSolution)(t::Union{Real, AbstractVector{<:Real}}, xs::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) - states = [_dofs_at(A, tk) for tk in _axis(t)] - return _evaluate(A, states, t isa AbstractVector ? (length(t),) : (), xs, dv, outside) + ts = _axis(t) + states = [_dofs_at(A, tk) for tk in ts] + return _evaluate(A, ts, states, t isa AbstractVector ? (length(t),) : (), xs, dv, outside) end function (A::FEMSteadySolution)(xs::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) - return _evaluate(A, _states(A), (), xs, dv, outside) + return _evaluate(A, nothing, _states(A), (), xs, dv, outside) +end + +# Observed expressions (spec O9). Without `mtkcompile` there are no observed equations, so an +# expression is compiled once with `build_function` into a scalar function of its leaves (the +# fields, their first spatial derivatives, time and the coordinates) and broadcast over the +# leaves' values at every vertex or point; parameters are replaced by their PDESystem values. +_is_expression(s) = SymbolicUtils.iscall(s) && !(SymbolicUtils.operation(s) isa Symbolics.Differential) + +function _observed_error(dv, why) + throw(ArgumentError("cannot evaluate the expression $dv on this solution: $why")) +end + +# Adds the leaves of `ex` to `terms` as `term => kind`, with kind `:field`, `:time` or `:coord`, +# and the value of each parameter to `params`. +function _observed_leaves!(terms, params, A, dv, ex) + md = A.disc_data + ex = SymbolicUtils.unwrap_const(Symbolics.unwrap(ex)) + ex isa Number && return nothing + if md.time !== nothing && isequal(ex, Symbolics.unwrap(md.time)) + terms[ex] = :time + elseif any(x -> isequal(ex, Symbolics.unwrap(x)), md.x̄) + terms[ex] = :coord + elseif _gradkey(md, ex) !== nothing + terms[ex] = :field + elseif SymbolicUtils.iscall(ex) && SymbolicUtils.operation(ex) isa Symbolics.Differential + _observed_error(dv, "$ex is not a first spatial derivative of a dependent variable, the only derivatives an expression accepts") + elseif (f = _fieldinfo(md, ex)) !== nothing + _piece_arg(ex) === nothing || + _observed_error(dv, "it contains the trace $ex; an expression is evaluated at every vertex, so write $(f.dv) instead") + isequal(ex, Symbolics.unwrap(f.dv)) || + _observed_error(dv, "$ex fixes arguments of $(f.dv); write the dependent variable as $(f.dv)") + terms[ex] = :field + elseif SymbolicUtils.issym(ex) || SymbolicUtils.issym(SymbolicUtils.operation(ex)) + # The front end requires a numeric value for every parameter of the PDESystem. + ps = md.pdesys === nothing ? [] : md.pdesys.ps + i = findfirst(p -> p isa Pair && isequal(Symbolics.unwrap(p.first), ex), ps) + i === nothing && _observed_error( + dv, "$ex is not a dependent variable, an independent variable or a parameter; the dependent variables are $(join(A.dvs, ", ")) and the independent variables $(join(A.ivs, ", "))" + ) + params[ex] = ps[i].second + else + foreach(a -> _observed_leaves!(terms, params, A, dv, a), SymbolicUtils.arguments(ex)) + end + return nothing +end + +# `(fn, terms, kinds)`: `fn(values...)` evaluates `dv` given the value of each of `terms`. +function _compile_observed(A::FEMSolution, dv) + terms, params = Dict{Any, Symbol}(), Dict{Any, Any}() + _observed_leaves!(terms, params, A, dv, dv) + leaves = collect(keys(terms)) + # Fixed names give an equal expression the same body, so the compiled function is reused. + vars = [Symbolics.unwrap(Symbolics.variable(:leaf, i)) for i in eachindex(leaves)] + body = substitute(Symbolics.unwrap(dv), merge(Dict{Any, Any}(zip(leaves, vars)), params)) + fn = Symbolics.build_function(body, vars...; expression = Val(false)) + return fn, leaves, [terms[l] for l in leaves] +end + +# One call of `fn` per entry of an array of size `shape`; `values` broadcast against it. +_broadcast_observed(fn, shape, values) = broadcast((_, v...) -> fn(v...), falses(shape), values...) + +# Values on the points `xs` at the times of `states`, through the per-field point evaluation; +# coordinate-only expressions are `NaN` outside the mesh like field values. +function _evaluate_observed(A::FEMSolution, ts, states, tshape, xs, dv, outside) + md = A.disc_data + fn, terms, kinds = _compile_observed(A, dv) + nt = length(states) + if length(xs) == 1 && only(xs) isa DomainSets.Domain + nodes = piece_nodes(md, only(xs)) + coords = [A[Num(x)][nodes] for x in md.x̄] + pshape, lost = (length(nodes),), falses(length(nodes)) + else + pts, pshape = _points(md, xs) + lost = isnothing.(_located(A, pts, outside).cells) + coords = [getindex.(pts, d) for d in eachindex(md.x̄)] + end + function value(term, kind) + kind === :time && return ts + kind === :coord && return permutedims(coords[findfirst(x -> isequal(term, Symbolics.unwrap(x)), md.x̄)]) + return reshape(_evaluate(A, ts, states, (nt,), xs, term, outside), nt, :) + end + out = _broadcast_observed(fn, (nt, length(lost)), map(value, terms, kinds)) + out[:, lost] .= NaN + shp = (tshape..., pshape...) + return isempty(shp) ? out[1] : reshape(out, shp) end _xml_escape(str) = replace(str, '&' => "&", '<' => "<", '>' => ">", '"' => """, '\'' => "'") diff --git a/test/Frontend/observed.jl b/test/Frontend/observed.jl new file mode 100644 index 00000000..e829a6f9 --- /dev/null +++ b/test/Frontend/observed.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "observed.jl")) +else + @testset "observed (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/Solution/solution.jl b/test/Solution/solution.jl index 514bd4c5..6af710db 100644 --- a/test/Solution/solution.jl +++ b/test/Solution/solution.jl @@ -185,6 +185,10 @@ end @test sol[Differential(x)(U)] ≈ -ones(getnnodes(grid)) atol = 1.0e-10 @test sol(0.3, 0.6; dv = Differential(x)(U)) ≈ -1 atol = 1.0e-12 @test isnan(sol(1.5, 0.5; dv = U)) + @test sol[U^2 + x] ≈ sol[U] .^ 2 .+ sol[x] atol = 1.0e-12 + @test sol[2U + Differential(x)(U)] ≈ 1 .- 2 .* sol[x] atol = 1.0e-10 + @test sol(0.3, 0.6; dv = U * y) ≈ 0.7 * 0.6 atol = 1.0e-12 + @test sol(Γ; dv = U + y) ≈ 1 .+ sol[y][piece_nodes(sol, Γ)] atol = 1.0e-12 end @testset "Points missed by Ferrite's nearest-node search" begin diff --git a/test/shared/frontend_tests/observed.jl b/test/shared/frontend_tests/observed.jl new file mode 100644 index 00000000..fecbd859 --- /dev/null +++ b/test/shared/frontend_tests/observed.jl @@ -0,0 +1,128 @@ +# End-to-end tests of observed expressions, `sol[expr]` and `sol(t, xs...; dv = expr)` (spec §7.8, +# O9): PDESystem -> DAEProblem -> solve, then each expression is checked against the same +# expression computed from the field arrays and against the exact solution. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, piece_nodes +using Ferrite: Triangle, Vec + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) v(..) z(..) w +@parameters k +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# u* = (1 + x + 2y)(1 + t) solves u_t = Δu + (1 + x + 2y) and is in the P1 space. +uexact(t_, x_, y_) = (1 + x_ + 2y_) * (1 + t_) +heat_eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + (1 + x + 2y) +pieces(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +heat_bcs(Ω) = [[u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)]; u(0, x, y) ~ 1 + x + 2y] + +observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on this solution: $why") + +@testset verbose = true "observed expressions" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + sol, _ = fem_solve([heat_eq], heat_bcs(Ω), Ω, (x, y), t, [u(t, x, y)]; ps = [k => 2.0]) + U = u(t, x, y) + T, X, Y = sol.t, permutedims(sol[x]), permutedims(sol[y]) + nt, nv = length(T), length(X) + + @testset "heat: sol[expr] against the field arrays and the exact solution" begin + @test size(sol[U^2 + k * x]) == (nt, nv) + @test sol[U^2 + k * x] ≈ sol[U] .^ 2 .+ 2 .* X atol = 1.0e-12 + @test maximum(abs, sol[U^2 + k * x] .- (uexact.(T, X, Y) .^ 2 .+ 2 .* X)) <= 1.0e-6 + @test sol[2U] == 2 .* sol[U] + @test sol[sin(t) * U] ≈ sin.(T) .* sol[U] atol = 1.0e-12 + # P1 reproduces the linear u*, so its projected gradient is (1 + t, 2(1 + t)). + @test sol[Dx(U) * U] ≈ sol[Dx(U)] .* sol[U] atol = 1.0e-12 + @test maximum(abs, sol[Dx(U) + Dy(U)] .- 3 .* (1 .+ T)) <= 1.0e-6 + end + + @testset "coordinate, time and parameter expressions" begin + @test sol[x^2 + y] == repeat(X .^ 2 .+ Y, nt) + @test sol[t * x + k] ≈ T .* X .+ 2 atol = 1.0e-14 + @test sol[2k] == fill(4.0, nt, nv) + end + + @testset "point evaluation sol(t, xs...; dv = expr)" begin + @test sol(0.5, 0.3, 0.2; dv = U^2 + k * x) ≈ sol(0.5, 0.3, 0.2; dv = U)^2 + 0.6 atol = 1.0e-12 + @test sol(0.5, 0.3, 0.2; dv = U^2 + k * x) ≈ uexact(0.5, 0.3, 0.2)^2 + 0.6 atol = 1.0e-6 + xs, ys = range(0, 1, length = 5), range(0, 1, length = 4) + vals = sol(T, xs, ys; dv = t * U + Dy(U)) + @test size(vals) == (nt, 5, 4) + @test vals ≈ [ + T[n] * sol(T[n], xs[i], ys[j]; dv = U) + sol(T[n], xs[i], ys[j]; dv = Dy(U)) + for n in 1:nt, i in 1:5, j in 1:4 + ] atol = 1.0e-12 + @test size(sol(0.5, xs, 0.2; dv = 2U)) == (5,) + # A coordinate-only expression is NaN outside the mesh, like a field value. + @test isequal(sol(0.5, [Vec(0.3, 0.2), Vec(2.0, 0.0)]; dv = x + y), [0.5, NaN]) + @test_throws DomainError sol(0.5, 2.0, 0.0; dv = 2x, outside = :error) + Γ = first(pieces(Ω)) + nodes = piece_nodes(sol, Γ) + @test sol(0.5, Γ; dv = U + y) ≈ sol(0.5, Γ; dv = U) .+ sol[y][nodes] atol = 1.0e-14 + @test sol(T, Γ; dv = t * U) ≈ T .* sol[u(t, Γ)] atol = 1.0e-12 + err = errmsg(() -> sol(0.5, Γ; dv = Dx(U) + 1)) + @test occursin("traces of derivatives are not supported", err) + end + + @testset "error paths" begin + dvs, ivs = "u(t, x, y)", "t, x, y" + unknown(s) = "$s is not a dependent variable, an independent variable or a parameter; the dependent variables are $dvs and the independent variables $ivs" + derivative(d) = "$d is not a first spatial derivative of a dependent variable, the only derivatives an expression accepts" + Γ = first(pieces(Ω)) + cases = [ + U * z(t, x, y) => unknown(z(t, x, y)), + 2w => unknown(w), + u(t, Γ)^2 => "it contains the trace $(u(t, Γ)); an expression is evaluated at every vertex, so write u(t, x, y) instead", + Dx(Dx(U)) + 1 => derivative(Dx(Dx(U))), + 2Dt(U) => derivative(Dt(U)), + u(t, 0, y) + 1 => "$(u(t, 0, y)) fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)", + ] + for (ex, why) in cases + @test_throws observed_error(ex, why) sol[ex] + @test_throws observed_error(ex, why) sol(0.5, 0.3, 0.2; dv = ex) + end + # A derivative key that is not an expression keeps the key error. + @test occursin("first", errmsg(() -> sol[Dx(Dx(U))])) + end + + @testset "two fields" begin + # u_t = Δu + v with the algebraic row 0 = Δv; u* = (1 + x + 2y)(1 + t), v* = 1 + x + 2y. + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(t, x, y) + algebraic = 0 ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))) + bcs = [heat_bcs(Ω); [v(t, Γ) ~ 1 + x + 2y for Γ in pieces(Ω)]] + sol2, _ = fem_solve( + [parabolic, algebraic], bcs, Ω, (x, y), t, [u(t, x, y), v(t, x, y)]; pairing = Dict(algebraic => v) + ) + V = v(t, x, y) + @test sol2[U * V + V] ≈ sol2[U] .* sol2[V] .+ sol2[V] atol = 1.0e-12 + @test maximum(abs, sol2[U - V] .- sol2.t .* (1 .+ X .+ 2 .* Y)) <= 1.0e-6 + @test sol2(0.5, 0.3, 0.2; dv = U - V) ≈ 0.5 * 1.7 atol = 1.0e-6 + @test sol2(0.5, 0.3, 0.2; dv = U / V) ≈ sol2(0.5, 0.3, 0.2; dv = U) / sol2(0.5, 0.3, 0.2; dv = V) atol = 1.0e-12 + dvs2 = "u(t, x, y), v(t, x, y)" + @test_throws observed_error(U * z(t, x, y), "z(t, x, y) is not a dependent variable, an independent variable or a parameter; the dependent variables are $dvs2 and the independent variables t, x, y") sol2[U * z(t, x, y)] + end + + @testset "evaluation is batched at 10^4 vertices" begin + big = MeshDomain(rectangle_grid(Triangle, (99, 99))) + bsol, _ = fem_solve([heat_eq], heat_bcs(big), big, (x, y), t, [u(t, x, y)]; ps = [k => 2.0], saveat = 0.5) + @test size(bsol[U]) == (3, 10_000) + E = U^2 + k * x * U + Dx(U) + @test maximum(abs, bsol[E] .- (bsol[U] .^ 2 .+ 2 .* permutedims(bsol[x]) .* bsol[U] .+ bsol[Dx(U)])) <= 1.0e-10 + # Past the symbolic compile, which does not depend on the mesh, the cost is the projection + # of Dx(U) and a few output-sized arrays; a substitution per vertex would allocate far more. + bsol[E] + bsol[Dx(U)] + compile = @allocated FiniteElementMethod._compile_observed(bsol, E) + @test @allocated(bsol[E]) < compile + @allocated(bsol[Dx(U)]) + 4 * sizeof(bsol[U]) + xs = range(0, 1, length = 100) + F = U^2 + k * x * U + bsol(bsol.t, xs, xs; dv = F) + bsol(bsol.t, xs, xs; dv = U) + compile = @allocated FiniteElementMethod._compile_observed(bsol, F) + @test @allocated(bsol(bsol.t, xs, xs; dv = F)) < compile + 4 * @allocated(bsol(bsol.t, xs, xs; dv = U)) + @info "observed evaluation at 10^4 vertices" compile_bytes = compile vertex_bytes = @allocated(bsol[F]) seconds = @elapsed(bsol[F]) + end +end From 49b0436753dd20acd3a523b87cc5626106935460 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 10:42:36 +0000 Subject: [PATCH 03/62] Skip observed expressions at points outside the mesh and return floats there Codex round 1: sqrt(x) at an outside point threw DomainError before the NaN mask, and an integer-valued expression such as 2k could not hold the NaN. The expression is now evaluated only at points inside the mesh, into a floating-point output prefilled with NaN. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 12 ++++++++---- test/shared/frontend_tests/observed.jl | 7 +++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/solution.jl b/src/solution.jl index 7d1748a5..0c0e4ea2 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -503,13 +503,17 @@ function _evaluate_observed(A::FEMSolution, ts, states, tshape, xs, dv, outside) lost = isnothing.(_located(A, pts, outside).cells) coords = [getindex.(pts, d) for d in eachindex(md.x̄)] end + # The expression is evaluated only inside the mesh, where its domain (sqrt, log) may not + # extend, and the output is floating point so that the outside points can hold NaN. + inside = findall(!, lost) function value(term, kind) kind === :time && return ts - kind === :coord && return permutedims(coords[findfirst(x -> isequal(term, Symbolics.unwrap(x)), md.x̄)]) - return reshape(_evaluate(A, ts, states, (nt,), xs, term, outside), nt, :) + kind === :coord && return permutedims(coords[findfirst(x -> isequal(term, Symbolics.unwrap(x)), md.x̄)][inside]) + return reshape(_evaluate(A, ts, states, (nt,), xs, term, outside), nt, :)[:, inside] end - out = _broadcast_observed(fn, (nt, length(lost)), map(value, terms, kinds)) - out[:, lost] .= NaN + vals = _broadcast_observed(fn, (nt, length(inside)), map(value, terms, kinds)) + out = fill(eltype(vals) <: Number ? float(eltype(vals))(NaN) : NaN, nt, length(lost)) + out[:, inside] .= vals shp = (tshape..., pshape...) return isempty(shp) ? out[1] : reshape(out, shp) end diff --git a/test/shared/frontend_tests/observed.jl b/test/shared/frontend_tests/observed.jl index fecbd859..20781479 100644 --- a/test/shared/frontend_tests/observed.jl +++ b/test/shared/frontend_tests/observed.jl @@ -59,6 +59,13 @@ observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on t # A coordinate-only expression is NaN outside the mesh, like a field value. @test isequal(sol(0.5, [Vec(0.3, 0.2), Vec(2.0, 0.0)]; dv = x + y), [0.5, NaN]) @test_throws DomainError sol(0.5, 2.0, 0.0; dv = 2x, outside = :error) + # Outside points are not evaluated, so an expression undefined there is NaN, not an error. + @test isnan(sol(0.5, -1.0, 0.5; dv = sqrt(x))) + @test isequal(sol(0.5, [0.25, -1.0], 0.5; dv = log(x) + U), [log(0.25) + sol(0.5, 0.25, 0.5; dv = U), NaN]) + # An integer-valued expression is returned as floating point so outside points hold NaN. + @test sol(0.5, 0.3, 0.5; dv = 2k) === 4.0 + @test isequal(sol(0.5, [0.3, 2.0], 0.5; dv = 2k), [4.0, NaN]) + @test isnan(sol(0.5, 2.0, 0.5; dv = 2k)) Γ = first(pieces(Ω)) nodes = piece_nodes(sol, Γ) @test sol(0.5, Γ; dv = U + y) ≈ sol(0.5, Γ; dv = U) .+ sol[y][nodes] atol = 1.0e-14 From 196682aa742e6400354dd312ac5b8e1ff08076d2 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 09:35:02 +0000 Subject: [PATCH 04/62] Discretize steady PDESystems to a NonlinearProblem A FEMDiscretization without a time variable now lowers a PDESystem with no time variable to the NonlinearProblem K u - F = 0 (Dirichlet rows u_d - g_d, sparse Jacobian K) with the FEMMetadata as problem_type, so solve returns the PDENoTimeSolution wrapper. Nonlinear terms stay rejected, as on the transient path; the residual has one place for N(u). The initial guess is zero with the Dirichlet data on prescribed dofs; steady equations not named in pairing take the remaining fields in declared order. write_vtk gains a steady method. End-to-end tests: Poisson P1/P2 rates, Gmsh L-shape with Dirichlet, Neumann and Robin, two fields, the solution interface, and the entry-point and nonlinear error paths. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 30 +++++++ src/FiniteElementMethod.jl | 2 +- src/discretization.jl | 10 ++- src/frontend.jl | 87 ++++++++++++++++-- src/solution.jl | 11 ++- test/Frontend/steady.jl | 9 ++ test/shared/frontend_tests/errors.jl | 34 ++++++- test/shared/frontend_tests/steady.jl | 129 +++++++++++++++++++++++++++ 8 files changed, 299 insertions(+), 13 deletions(-) create mode 100644 test/Frontend/steady.jl create mode 100644 test/shared/frontend_tests/steady.jl diff --git a/docs/discretization.md b/docs/discretization.md index b38631ad..0ea8b860 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -7,7 +7,37 @@ shapes. ```@docs FEMDiscretization FiniteElementMethod.SciMLBase.DAEProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) +FiniteElementMethod.SciMLBase.NonlinearProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.AbstractTestSpace FiniteElementMethod.Galerkin FiniteElementMethod.assemble_sources! ``` + +## Steady problems + +A `PDESystem` with no time variable, discretized by a `FEMDiscretization` built without one, +lowers to a `NonlinearProblem` `K u - F = 0`, which Newton solves in one step. Dirichlet rows +are the algebraic equations `u_d - g_d = 0`, the Jacobian `K` is sparse, and `solve` returns a +`PDENoTimeSolution` with the same interface as a transient solution, without the time argument: +`sol[u(x, y)]`, `sol(x, y; dv)`, traces `sol[u(Γ)]`, derivatives such as `sol[Dx(u(x, y))]`, +`normal_flux` and `write_vtk` (one `.vtu` file). Traces are written `u(Γ)`, since the dependent +variables have no time argument. + +```julia +using FiniteElementMethod, ModelingToolkit, NonlinearSolve +using Ferrite: Triangle +@variables x y u(..) +Dx, Dy = Differential(x), Differential(y) +Ω = MeshDomain(FiniteElementMethod.rectangle_grid(Triangle, (16, 16))) +eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ -1 +@named pdesys = PDESystem([eq], [u(Γ) ~ 0 for Γ in boundarypieces(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) +prob = discretize(pdesys, FEMDiscretization(Ω)) +sol = solve(prob, NewtonRaphson()) +sol(0.5, 0.5; dv = u(x, y)) +``` + +Nonlinear terms are rejected on the steady path, as on the time-dependent one. Newton starts +from zero on the free dofs and the Dirichlet data on the prescribed dofs; another initial guess +is a dof vector passed as `remake(prob; u0)`, where field `name` occupies +`FiniteElementMethod.field_range(prob.problem_type.space, name)`. Equations with no entry in +`pairing` are tested with the remaining dependent variables in declared order. diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 4c08217c..7f33b2e1 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -20,7 +20,7 @@ using NonlinearSolveFirstOrder: NewtonRaphson using PDEBase: PDEBase using PrecompileTools: PrecompileTools using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions -using SciMLBase: SciMLBase, DAEFunction, DAEProblem +using SciMLBase: SciMLBase, DAEFunction, DAEProblem, NonlinearProblem using SciMLBase.SymbolicIndexingInterface: getp, variable_index using SparseArrays: SparseMatrixCSC, nonzeros, nzrange, rowvals using SymbolicUtils: SymbolicUtils diff --git a/src/discretization.jl b/src/discretization.jl index 1a34c9b4..d4185974 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -12,6 +12,9 @@ PDEBase.contains_point(grid::Ferrite.Grid, x) = _contains_point(grid, x) Finite-element discretization of a `PDESystem` whose spatial domain is the mesh domain `Ω` (of a `Ferrite.Grid`), with time variable `t`. `DAEProblem(pdesys, disc)` assembles the Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknown per field. +Without `t` the discretization is steady: the `PDESystem` must have no time variable, and +`discretize` (or `NonlinearProblem(pdesys, disc)`) returns a `NonlinearProblem` whose `solve` +gives a `PDENoTimeSolution`. - `spaces`: dependent variable (`u` or `u(t, x, y)`) `=>` `Ferrite.Interpolation`; the default is `Lagrange{RefShape, 1}()` on the mesh's reference shape. All fields must @@ -19,10 +22,11 @@ Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknow - `quadrature`: quadrature order; `nothing` means `2p` for Lagrange order `p`. - `ibp`: equation (or its index) `=>` `PDEBase.StrongForm` integration-by-parts policy. - `pairing`: equation `=>` dependent variable it is tested with, needed for an equation - with no time derivative of its own, such as `0 ~ Dxx(v) + f`. + with no time derivative of its own, such as `0 ~ Dxx(v) + f`. In a steady system the + equations not named here take the remaining dependent variables in declared order. - `codegen = :mtk` and `dirichlet = :eliminate` are reserved for later milestones and - raise; remaining keywords are passed to the `DAEProblem`, where a keyword given at the - `DAEProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` + raise; remaining keywords are passed to the `DAEProblem` (or `NonlinearProblem`), where a + keyword given at the `DAEProblem`/`NonlinearProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` are set by the discretization and rejected. Pieces come from `boundarypiece.(Ω, names)`; on an analytic DomainSets box write diff --git a/src/frontend.jl b/src/frontend.jl index 6c493082..864cad77 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -56,7 +56,16 @@ function _check_domains(pdesys, disc::FEMDiscretization) pairings[i].domain === disc.domain || throw(ArgumentError("the PDESystem's MeshDomain is not the domain of the FEMDiscretization")) t = disc.time - t === nothing && return nothing + if t === nothing + j = findfirst(d -> d.domain isa DomainSets.AbstractInterval, pairings) + j === nothing || throw( + ArgumentError( + "the PDESystem pairs $(pairings[j].variables) with an interval, but the FEMDiscretization has no time " * + "variable; for a time-dependent problem write FEMDiscretization(Ω, $(pairings[j].variables))" + ) + ) + return nothing + end j = findfirst(d -> isequal(unwrap(d.variables), unwrap(t)), pairings) (j === nothing || !(pairings[j].domain isa DomainSets.AbstractInterval)) && throw(ArgumentError("time $t must be paired with an interval, as in $t ∈ Interval(0.0, 1.0)")) @@ -121,6 +130,14 @@ function _paired(an, eqs, ctx, disc) f === nothing && throw(ArgumentError("pairing value $dv is not a dependent variable of the system")) explicit[e] = f end + # A steady system has no time derivatives to pair by, so the unnamed equations take the + # unnamed fields in declared order. + if disc.time === nothing + free = [f for f in eachindex(ctx.ops) if !(f in values(explicit))] + for e in eachindex(eqs) + haskey(explicit, e) || (explicit[e] = popfirst!(free)) + end + end fields = StrongForm.pair_equations(an.mass, an.slots; pairing = explicit) order = invperm(fields) natural = [typeof(bc)(bc.piece, fields[bc.eq], bc.Φ) for bc in an.natural] @@ -270,7 +287,6 @@ function _initial_values(ics, ctx, space, coords, an, names, pvals) end function _lower(pdesys, disc::FEMDiscretization) - disc.time === nothing && throw(ArgumentError("steady problems land in M4; give FEMDiscretization a time variable")) _check_domains(pdesys, disc) sys, replaced = PDEBase.make_pdesys_compatible(pdesys) v = PDEBase.VariableMap(sys, disc; replaced_vars = replaced) @@ -287,23 +303,46 @@ function _lower(pdesys, disc::FEMDiscretization) end end wf = weak_form(an) + steady = disc.time === nothing _check_linear(wf) pvals = _parameter_values(sys, ctx) dirichlet = emit_dirichlet(an) - t0, t1 = v.intervals[v.time] + t0, t1 = steady ? (0.0, 0.0) : v.intervals[v.time] space, names, ips = _space(disc, ctx, an, dirichlet, pvals, t0) timedep_dirichlet = any(bc -> _depends(bc.g, [an.slots.T]), an.essential) ops, coords = _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) u0 = _initial_values(Equation[b.eq for b in ics], ctx, space, coords, an, names, pvals) dirichlet_values!(view(u0, ops.prescribed), ops.load, t0) iv = disc.time - unknowns = [only(@variables $name(iv)[1:length(field_range(space, name))]) for name in names] + unknowns = map(names) do name + n = length(field_range(space, name)) + steady ? only(@variables $name[1:n]) : only(@variables $name(iv)[1:n]) + end fields = [FieldInfo(dv, name, u, ip) for (dv, name, u, ip) in zip(StrongForm.declared_fields(sys, v), names, unknowns, ips)] pieces = Dict{Any, String}(Γ => String(Γ.name) for Γ in PDEBase.boundarypieces(disc.domain)) md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0) return (; ops, u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys)) end +# `K u - F` with the Dirichlet rows `u_d - g_d`: `K` holds `e_d` and `F` holds `g_d` there. +# Nonlinear terms `N(u)` would be added to the residual in `f!` and `∂N/∂u` to `jac!`. +function _steady_problem(parts; kwargs...) + (; ops) = parts + F = load!(zeros(length(parts.u0)), ops.load, 0.0) + function f!(res, u, p) + mul!(res, ops.K, u) + res .-= F + return nothing + end + function jac!(J, u, p) + check_pattern(J, ops.K, "the Jacobian") + copyto!(nonzeros(J), nonzeros(ops.K)) + return nothing + end + f = SciMLBase.NonlinearFunction{true}(f!; jac = jac!, jac_prototype = copy(ops.K)) + return SciMLBase.NonlinearProblem{true}(f, parts.u0, SciMLBase.NullParameters(), parts.md; kwargs...) +end + """ DAEProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) @@ -323,6 +362,12 @@ size change and holds `u(t, Γ) ~ g(t)` to round-off. """ function SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) _check_reserved(kwargs) + disc.time === nothing && throw( + ArgumentError( + "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem, not a DAEProblem; " * + "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" + ) + ) parts = _lower(pdesys, disc) return numeric_dae_problem( parts.ops, parts.u0, parts.tspan, parts.md; @@ -330,11 +375,43 @@ function SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscre ) end +""" + NonlinearProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) + +Discretize the steady `pdesys` with a `disc` that has no time variable and return the +`NonlinearProblem` `K u - F = 0` of the Galerkin operators, with Dirichlet rows `u_d - g_d` +as algebraic equations, the sparse Jacobian `K` and the `FEMMetadata` as its `problem_type`, +so `solve` returns a `PDENoTimeSolution`; Newton solves it in one step. Nonlinear terms are +rejected, as on the time-dependent path. + +The initial guess `u0` is zero on the free dofs and `g_d` on the Dirichlet dofs; a steady +`PDESystem` has no initial conditions. To start Newton elsewhere, `remake(prob; u0)` with a +dof vector (field `name` occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`). +Keywords are passed to the `NonlinearProblem` after `disc.kwargs`; the keywords +`iv`, `unknowns`, `du0`, `coordinate` and `name` are rejected, as for the `DAEProblem`. +""" +function SciMLBase.NonlinearProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) + _check_reserved(kwargs) + disc.time === nothing || throw( + ArgumentError( + "the FEMDiscretization has the time variable $(disc.time), so it lowers to a DAEProblem; " * + "for a steady problem write FEMDiscretization(Ω) without a time variable" + ) + ) + return _steady_problem(_lower(pdesys, disc); disc.kwargs..., kwargs...) +end + SciMLBase.discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) = - DAEProblem(pdesys, disc; kwargs...) + disc.time === nothing ? NonlinearProblem(pdesys, disc; kwargs...) : DAEProblem(pdesys, disc; kwargs...) # `(sys, tspan)`, the shape PDEBase and MethodOfLines return. function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) + disc.time === nothing && throw( + ArgumentError( + "a steady FEMDiscretization builds no symbolic System, so it has no symbolic_discretize; " * + "call discretize(pdesys, disc) for its NonlinearProblem" + ) + ) prob = DAEProblem(pdesys, disc) return prob.f.sys, prob.tspan end diff --git a/src/solution.jl b/src/solution.jl index 98c0911b..afe9bf35 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -413,7 +413,8 @@ _xml_escape(str) = replace(str, '&' => "&", '<' => "<", '>' => ">", '" Write one `.vtu` file per saved time, `"\$(base)_0001.vtu"` and so on, with every field as point data, plus a ParaView collection `"\$(base).pvd"` that maps them to `sol.t`. Returns the -path of the `.pvd` file. +path of the `.pvd` file. A steady solution is written to the single file `"\$(base).vtu"`, +whose path is returned. """ function write_vtk(A::FEMTimeSolution, base::AbstractString) dh = _dh(A.disc_data) @@ -438,3 +439,11 @@ function write_vtk(A::FEMTimeSolution, base::AbstractString) ) return pvd end + +function write_vtk(A::FEMSteadySolution, base::AbstractString) + dh = _dh(A.disc_data) + Ferrite.VTKGridFile(base, dh) do vtk + Ferrite.write_solution(vtk, dh, A.original_sol.u) + end + return base * ".vtu" +end diff --git a/test/Frontend/steady.jl b/test/Frontend/steady.jl new file mode 100644 index 00000000..c60d1408 --- /dev/null +++ b/test/Frontend/steady.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "steady.jl")) +else + @testset "steady (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index f50b6b39..954a2506 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -89,12 +89,33 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @test_throws ArgumentError("dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic") FEMDiscretization( Ω, t; dirichlet = :eliminate ) + end + + @testset "steady and time-dependent entry points" begin + Ω = box() @named steady = PDESystem( [Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], [] ) - @test_throws ArgumentError("steady problems land in M4; give FEMDiscretization a time variable") discretize( - steady, FEMDiscretization(Ω) - ) + @test_throws ArgumentError( + "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem, not a DAEProblem; " * + "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" + ) DAEProblem(steady, FEMDiscretization(Ω)) + @test_throws ArgumentError( + "a steady FEMDiscretization builds no symbolic System, so it has no symbolic_discretize; " * + "call discretize(pdesys, disc) for its NonlinearProblem" + ) SciMLBase.symbolic_discretize(steady, FEMDiscretization(Ω)) + @named transient = PDESystem([heat], [dirichlet(Ω); ic], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_throws ArgumentError( + "the FEMDiscretization has the time variable t, so it lowers to a DAEProblem; " * + "for a steady problem write FEMDiscretization(Ω) without a time variable" + ) SciMLBase.NonlinearProblem(transient, FEMDiscretization(Ω, t)) + @test_throws ArgumentError( + "the PDESystem pairs t with an interval, but the FEMDiscretization has no time variable; " * + "for a time-dependent problem write FEMDiscretization(Ω, t)" + ) discretize(transient, FEMDiscretization(Ω)) + @test_throws ArgumentError( + "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name" + ) discretize(steady, FEMDiscretization(Ω); name = :other) end @testset "nonlinear and time-dependent operators" begin @@ -108,6 +129,13 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has " * "G₁*W₁ + G₂*W₂ + G₁*T*W₁ + G₂*T*W₂" ) lower([td], [dirichlet(Ω); ic], Ω) + @named steady_nl = PDESystem( + [Dx((1 + u(x, y)^2) * Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in sides(Ω)], + [(x, y) ∈ Ω], [x, y], [u(x, y)], [] + ) + @test_throws ArgumentError("nonlinear terms land in M3: equation 1 has the nonlinear term -G₁*(U₁^2)*W₁") discretize( + steady_nl, FEMDiscretization(Ω) + ) end @testset "non-finite initial condition names the node" begin diff --git a/test/shared/frontend_tests/steady.jl b/test/shared/frontend_tests/steady.jl new file mode 100644 index 00000000..eda36866 --- /dev/null +++ b/test/shared/frontend_tests/steady.jl @@ -0,0 +1,129 @@ +# End-to-end tests of steady problems: a PDESystem with no time variable -> NonlinearProblem -> +# solve -> PDENoTimeSolution, checked against manufactured solutions. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, field_range +using Ferrite: Ferrite, Triangle +using NonlinearSolveFirstOrder: NewtonRaphson + +include(joinpath(@__DIR__, "..", "frontend.jl")) +include(joinpath(@__DIR__, "..", "lshape.jl")) + +@variables x y u(..) v(..) +const Dx, Dy = Differential(x), Differential(y) + +sides(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + +function steady_solve(eqs, bcs, Ω, dvs; disc_kwargs...) + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω], [x, y], dvs, []) + prob = discretize(pdesys, FEMDiscretization(Ω; disc_kwargs...)) + return solve(prob, NewtonRaphson(); abstol = 1.0e-12), prob +end + +"Largest error of `dv` against `exact(x, y)` at a lattice of points off the mesh nodes." +function point_error(sol, dv, exact) + pts = range(0.0123, 0.9877; length = 41) + return maximum(abs(sol(px, py; dv) - exact(px, py)) for px in pts, py in pts) +end + +ustar(x_, y_) = sin(pi * x_) * exp(y_) + +# Δu = Δu* on the unit square, u = u* on every side. +function poisson_error(n, order) + Ω = MeshDomain(rectangle_grid(Triangle, (n, n))) + eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ (1 - pi^2) * ustar(x, y) + sol, _ = steady_solve( + [eq], [u(Γ) ~ ustar(x, y) for Γ in sides(Ω)], Ω, [u(x, y)]; + spaces = Dict(u => Lagrange{RefTriangle, order}()) + ) + @test SciMLBase.successful_retcode(sol) + @test sol.stats.nsteps == 1 + return point_error(sol, u(x, y), ustar) +end + +@testset verbose = true "steady" begin + @testset "Poisson on a rectangle grid converges at rate $(order + 1) for P$order" for order in (1, 2) + e1, e2 = poisson_error.((8, 16), order) + @test log2(e1 / e2) > order + 0.8 + end + + @testset "L-shape with Dirichlet, Neumann and Robin pieces" begin + # u* = 1 + x + 2y + xy + x², Δu* = 2, is exact in P2 on straight triangles. ∇u* = (1 + y + 2x, 2 + x). + u_exact(x_, y_) = 1 + x_ + 2y_ + x_ * y_ + x_^2 + Ω = MeshDomain(lshape_grid(; h = 0.5)) + Γi, Γw, Γo = boundarypiece.(Ω, (:inlet, :wall, :outlet)) + # The wall is y = 0 (outward normal -y), the edges y = 1 for x > 1 and y = 2 (normal +y), and + # x = 1 for 1 < y < 2 (normal +x); facet quadrature points lie strictly inside the edges. + wall_flux = ifelse(y < 0.5, -(2 + x), ifelse(x > 1 + 1.0e-8, 2 + x, ifelse(y > 2 - 1.0e-8, 2 + x, 1 + 2x + y))) + bcs = [ + u(Γi) ~ 1 + 2y, + NormalDerivative(Γw)(u(Γw)) ~ wall_flux, + NormalDerivative(Γo)(u(Γo)) + u(Γo) ~ (5 + y) + (7 + 4y), + ] + sol, _ = steady_solve( + [Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 2], bcs, Ω, [u(x, y)]; + spaces = Dict(u => Lagrange{RefTriangle, 2}()) + ) + @test SciMLBase.successful_retcode(sol) + @test maximum(abs, sol[u(x, y)] - u_exact.(sol[x], sol[y])) <= 1.0e-10 + @test abs(sol(0.5, 1.5; dv = u(x, y)) - u_exact(0.5, 1.5)) <= 1.0e-10 + end + + @testset "two fields, paired $(how)" for how in ("by declared order", "explicitly") + # Δu + v = 5 + x and Δv = 0 with u* = x² + y², v* = 1 + x, both exact in P2. + Ω = MeshDomain(rectangle_grid(Triangle, (3, 3))) + u_eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) + v(x, y) ~ 5 + x + v_eq = Dx(Dx(v(x, y))) + Dy(Dy(v(x, y))) ~ 0 + bcs = [[u(Γ) ~ x^2 + y^2 for Γ in sides(Ω)]; [v(Γ) ~ 1 + x for Γ in sides(Ω)]] + P2 = Lagrange{RefTriangle, 2}() + kw = how == "explicitly" ? (; pairing = Dict(v_eq => v)) : (;) + eqs = how == "explicitly" ? [v_eq, u_eq] : [u_eq, v_eq] + sol, prob = steady_solve(eqs, bcs, Ω, [u(x, y), v(x, y)]; spaces = Dict(u => P2, v => P2), kw...) + @test SciMLBase.successful_retcode(sol) + @test maximum(abs, sol[u(x, y)] - (sol[x] .^ 2 + sol[y] .^ 2)) <= 1.0e-10 + @test maximum(abs, sol[v(x, y)] - (1 .+ sol[x])) <= 1.0e-10 + @test length(sol(0.4, 0.7)) == 2 + @test [f.name for f in prob.problem_type.fields] == [:u, :v] + end + + @testset "steady solution interface" begin + # u* = 1 + x + 2y is exact in P1: harmonic, with u = u* on the left and right and + # ∂u/∂n = ±2 on the bottom and top. + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = sides(Ω) + bcs = [u(Γl) ~ 1 + 2y, u(Γr) ~ 2 + 2y, NormalDerivative(Γb)(u(Γb)) ~ -2, NormalDerivative(Γt)(u(Γt)) ~ 2] + @named pdesys = PDESystem([Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], bcs, [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + prob = discretize(pdesys, FEMDiscretization(Ω; abstol = 1.0e-12)) + @test prob isa SciMLBase.NonlinearProblem + @test prob.kwargs[:abstol] == 1.0e-12 + @test SciMLBase.NonlinearProblem(pdesys, FEMDiscretization(Ω)).u0 == prob.u0 + # The initial guess is zero except on the Dirichlet dofs, which hold the data. + space = prob.problem_type.space + pd = space.ch.prescribed_dofs + @test all(iszero, prob.u0[setdiff(1:length(prob.u0), pd)]) + coords = FiniteElementMethod._dof_coordinates(space) + @test prob.u0[pd] ≈ [1 + c[1] + 2c[2] for c in coords[pd]] + @test sprint(show, prob.problem_type) == "FEMMetadata(fields = [u], ndofs = 25, hasTime = false)" + + sol = solve(prob, NewtonRaphson()) + U = u(x, y) + @test sol isa SciMLBase.PDENoTimeSolution + @test sol.disc_data isa FEMMetadata{Val(false)} + nv = Ferrite.getnnodes(Ω.mesh) + @test sol[U] isa Vector{Float64} && length(sol[U]) == nv + @test sol[U] ≈ 1 .+ sol[x] .+ 2 .* sol[y] atol = 1.0e-12 + @test sol(0.3, 0.6; dv = U) ≈ 2.5 atol = 1.0e-12 + @test sol([0.3, 2.0], 0.6; dv = U)[1] ≈ 2.5 atol = 1.0e-12 + @test isnan(sol([0.3, 2.0], 0.6; dv = U)[2]) + @test sol[u(Γr)] ≈ 2 .+ 2 .* sol[y][piece_nodes(sol, Γr)] atol = 1.0e-12 + @test sol(Γl; dv = U) ≈ 1 .+ 2 .* sol[y][piece_nodes(sol, Γl)] atol = 1.0e-12 + @test sol[Dx(U)] ≈ ones(nv) atol = 1.0e-10 + @test sol(0.3, 0.6; dv = Dy(U)) ≈ 2 atol = 1.0e-10 + @test normal_flux(sol, U, Γt) ≈ fill(2.0, 4) atol = 1.0e-10 + @test normal_flux(sol, U, Γl) ≈ fill(-1.0, 4) atol = 1.0e-10 + mktempdir() do dir + path = write_vtk(sol, joinpath(dir, "poisson")) + @test path == joinpath(dir, "poisson.vtu") + @test isfile(path) && occursin(" Date: Tue, 27 Oct 2026 09:51:27 +0000 Subject: [PATCH 05/62] Split a quotient over its numerator when classifying weak-form terms Symbolics.expand leaves (a + b) / c whole, so a Robin condition whose data carry a denominator (the normal -(x, y)/r of a circle) was classified as one bilinear term containing the time-dependent data and rejected by the front end as a time-dependent stiffness coefficient. addterms now splits the numerator's terms over the denominator. Unit test in WeakForm; the curved-domain end-to-end test exercises it through the front end. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/weakform.jl | 13 ++++++++++++- test/WeakForm/weakform.jl | 13 +++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/weakform.jl b/src/weakform.jl index dd0cb14e..9c40f3df 100644 --- a/src/weakform.jl +++ b/src/weakform.jl @@ -83,7 +83,18 @@ struct KernelSpec{F, T, C} end KernelSpec(eq, kind, piece, f, tangent) = KernelSpec(eq, kind, piece, f, tangent, nothing) -addterms(ex) = SU.iscall(ex) && SU.operation(ex) === (+) ? reduce(vcat, addterms.(SU.arguments(ex))) : [ex] +# `expand` leaves a quotient whole, so `(U·V + g·V) / r` (a Robin condition whose data has the +# denominator `r`, as normals on a circle do) is split over its numerator's terms. +function addterms(ex) + SU.iscall(ex) || return [ex] + op = SU.operation(ex) + op === (+) && return reduce(vcat, addterms.(SU.arguments(ex))) + if op === (/) + num, den = SU.arguments(ex) + return [term / den for term in addterms(num)] + end + return [ex] +end function depends(ex, syms) vars = Set(Symbolics.get_variables(ex)) diff --git a/test/WeakForm/weakform.jl b/test/WeakForm/weakform.jl index 892cb007..9765c738 100644 --- a/test/WeakForm/weakform.jl +++ b/test/WeakForm/weakform.jl @@ -184,3 +184,16 @@ end ) ) end + +@testset "a quotient is split over its numerator's terms (Robin data with a 1/r normal)" begin + s = StateSlots(1, 2, 0) + (; V) = TestSlots(2) + X, T = s.X, s.T + r = sqrt(X[1]^2 + X[2]^2) + # A Robin condition on a circle, u + ∂ₙu = g with ∂ₙ = −X·∇/r, gathered over one denominator. + robin = Num(Symbolics.unwrap((s.U[1] * r * V + (1 + T) * X[1] * V) / r)) + classes = classify(robin, s, TestSlots(2)) + @test [c.kind for c in classes] == [:bilinear, :source] + @test matches(classes, Dict(:bilinear => s.U[1] * V, :source => (1 + T) * X[1] * V / r)) + @test only(c.timedep for c in classes if c.kind === :bilinear) == false +end From 602ce476c4f8961c6a14f8ed4ef701aa52e0771b Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 09:51:27 +0000 Subject: [PATCH 06/62] Test P2 on a curved second-order Gmsh mesh through the front end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spec §6.2, §10.3 (M4). The front end already maps cells with the mesh's geometric interpolation in the space, the assembly and the solution, so an order-2 Gmsh mesh needs no option. New end-to-end test on an annulus: heat equation with u* = (1 + t)phi, Dirichlet data on the outer circle given at the radial projection, Robin with NormalDerivative and the true normal on the inner circle, P2 Lagrange, four mesh sizes. Quadratic geometry gives L2 slope ~3.1, straight-sided cells of the same vertices ~2.0. Also checks perimeter and facet normals of the curved pieces, traces on mid-side nodes on the circle, point evaluation between arc nodes (NaN on the straight mesh), and normal_flux convergence. Docs: a Curved meshes section; FEMDiscretization docstring states that the geometry follows the cell type. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 36 ++++++ src/discretization.jl | 4 +- test/Frontend/curved.jl | 9 ++ test/shared/annulus.jl | 35 ++++++ test/shared/frontend_tests/curved.jl | 168 +++++++++++++++++++++++++++ 5 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 test/Frontend/curved.jl create mode 100644 test/shared/annulus.jl create mode 100644 test/shared/frontend_tests/curved.jl diff --git a/docs/discretization.md b/docs/discretization.md index b38631ad..94b574ba 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -4,6 +4,42 @@ `boundarypiece`, `boundarypieces`, `NormalDerivative`) and Ferrite's `Lagrange` and reference shapes. +## Curved meshes + +The geometry of every cell comes from the mesh: the space, the assembly (facet normals +included) and the solution interface map each cell with the geometric interpolation of its +Ferrite cell type. A second-order mesh therefore gives curved cells with no option to set. +To keep P2 at its full rate on a curved domain, mesh it at order 2 so the mid-side nodes lie +on the true boundary: + +```julia +using FerriteGmsh, Gmsh + +Gmsh.initialize() +gmsh.option.setNumber("Mesh.MeshSizeMax", 0.05) +outer, inner = gmsh.model.occ.addCircle(0, 0, 0, 1.0), gmsh.model.occ.addCircle(0, 0, 0, 0.5) +surface = gmsh.model.occ.addPlaneSurface([gmsh.model.occ.addCurveLoop([outer]), gmsh.model.occ.addCurveLoop([inner])]) +gmsh.model.occ.synchronize() +gmsh.model.addPhysicalGroup(1, [inner], -1, "inner") +gmsh.model.addPhysicalGroup(1, [outer], -1, "outer") +gmsh.model.addPhysicalGroup(2, [surface], -1, "domain") +gmsh.model.mesh.generate(2) +gmsh.model.mesh.setOrder(2) # QuadraticTriangle cells, mid-side nodes on the circles +grid = FerriteGmsh.togrid() +Gmsh.finalize() + +Ω = MeshDomain(grid) +Γi, Γo = boundarypiece.(Ω, (:inner, :outer)) +disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}())) +``` + +Conditions on the curved pieces are written as on any other piece, with `NormalDerivative(Γ)` +the derivative along the outward normal of the curved facets. With straight-sided cells +(`setOrder(1)`) the boundary is a polygon and P2 drops from L2 rate 3 to 2 once boundary data +or normals of the true curve enter; `test/shared/frontend_tests/curved.jl` measures both on +this annulus. Use a mesh generator that does not leave nodes outside every cell, such as the +centre point of Gmsh's built-in-kernel circle arcs: `sol[u]` is `NaN` at such nodes. + ```@docs FEMDiscretization FiniteElementMethod.SciMLBase.DAEProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) diff --git a/src/discretization.jl b/src/discretization.jl index 1a34c9b4..bbbbc645 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -15,7 +15,9 @@ Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknow - `spaces`: dependent variable (`u` or `u(t, x, y)`) `=>` `Ferrite.Interpolation`; the default is `Lagrange{RefShape, 1}()` on the mesh's reference shape. All fields must - currently share one interpolation. + currently share one interpolation. The geometry is not a choice here: cells are mapped + with the geometric interpolation of the mesh's cell type, so a mesh of quadratic cells + (`QuadraticTriangle`, say, from a second-order Gmsh mesh) is mapped isoparametrically. - `quadrature`: quadrature order; `nothing` means `2p` for Lagrange order `p`. - `ibp`: equation (or its index) `=>` `PDEBase.StrongForm` integration-by-parts policy. - `pairing`: equation `=>` dependent variable it is tested with, needed for an equation diff --git a/test/Frontend/curved.jl b/test/Frontend/curved.jl new file mode 100644 index 00000000..e6b62156 --- /dev/null +++ b/test/Frontend/curved.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "curved.jl")) +else + @testset "curved (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/annulus.jl b/test/shared/annulus.jl new file mode 100644 index 00000000..9d156077 --- /dev/null +++ b/test/shared/annulus.jl @@ -0,0 +1,35 @@ +using Ferrite: Ferrite +using FerriteGmsh: FerriteGmsh +using Gmsh: Gmsh, gmsh + +""" + annulus_grid(h; order = 2, r = 0.5, R = 1.0) + +Triangle mesh of the annulus `r ≤ |x| ≤ R` with mesh size `h`, built with the Gmsh API from +OpenCASCADE circles and converted with `FerriteGmsh.togrid`. With `order = 2` Gmsh places the mid-side +nodes on the circles and the grid has `QuadraticTriangle` cells; with `order = 1` the same +vertices make straight-sided `Triangle`s. Physical groups of dimension 1: `"inner"` (`|x| = r`) +and `"outer"` (`|x| = R`); dimension 2: `"domain"`. +""" +function annulus_grid(h; order = 2, r = 0.5, R = 1.0) + Gmsh.initialize() + try + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("annulus") + # OpenCASCADE full circles: Gmsh's built-in kernel needs a centre point for its arcs, which + # FerriteGmsh would keep as a node outside every cell. + gmsh.option.setNumber("Mesh.MeshSizeMax", h) + outer = gmsh.model.occ.addCircle(0, 0, 0, R) + inner = gmsh.model.occ.addCircle(0, 0, 0, r) + surface = gmsh.model.occ.addPlaneSurface([gmsh.model.occ.addCurveLoop([outer]), gmsh.model.occ.addCurveLoop([inner])]) + gmsh.model.occ.synchronize() + gmsh.model.addPhysicalGroup(1, [inner], -1, "inner") + gmsh.model.addPhysicalGroup(1, [outer], -1, "outer") + gmsh.model.addPhysicalGroup(2, [surface], -1, "domain") + gmsh.model.mesh.generate(2) + gmsh.model.mesh.setOrder(order) + return FerriteGmsh.togrid() + finally + Gmsh.finalize() + end +end diff --git a/test/shared/frontend_tests/curved.jl b/test/shared/frontend_tests/curved.jl new file mode 100644 index 00000000..105bd8b1 --- /dev/null +++ b/test/shared/frontend_tests/curved.jl @@ -0,0 +1,168 @@ +# End to end on a curved domain (spec §6.2, §10.3 for P2, M4): a second-order Gmsh mesh of an +# annulus through the PDESystem front end. The space, the assembly (facet normals included) and +# the solution interface map cells with the mesh's own geometric interpolation, so P2 on +# quadratic cells keeps the L2 rate 3, while the same vertices with straight-sided cells cap it +# at 2: the Dirichlet data live on the true circle and the Robin data use its true normal. +using Test +using LinearAlgebra: norm, dot +using FiniteElementMethod: FiniteElementMethod, piece_nodes, normal_flux +using Ferrite: Ferrite, RefTriangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) +include(joinpath(@__DIR__, "..", "annulus.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +const r_in, r_out = 0.5, 1.0 + +# u* = (1 + t)φ is linear in t, which BDF integrates exactly, so the error is the spatial one. +φ = sin(2x) * cos(y) + x^2 * y +u_star = (1 + t) * φ +heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + + expand_derivatives(Dt(u_star) - Dx(Dx(u_star)) - Dy(Dy(u_star))) +ρ = sqrt(x^2 + y^2) +# The outer Dirichlet data are u* at the radial projection onto |x| = r_out: equal to u* only on +# the true circle. The inner Robin condition uses the true outward normal −(x, y)/ρ. +outer_data = substitute(u_star, Dict(x => r_out * x / ρ, y => r_out * y / ρ)) +inner_data = expand_derivatives(-(x * Dx(u_star) + y * Dy(u_star)) / ρ) + u_star +const φ_f = Symbolics.build_function(φ, x, y; expression = Val(false)) +u_exact(t_, x_, y_) = (1 + t_) * φ_f(x_, y_) +const ∇φ_f = [Symbolics.build_function(g, x, y; expression = Val(false)) for g in Symbolics.gradient(φ, [x, y])] +# Coordinates of the vertices of facet `fi`. +facet_ends(grid, fi) = [Ferrite.get_node_coordinate(grid, n) for n in Ferrite.facets(Ferrite.getcells(grid, fi[1]))[fi[2]]] + +const P2 = Lagrange{RefTriangle, 2}() + +function annulus_solve(h; order) + Ω = MeshDomain(annulus_grid(h; order, r = r_in, R = r_out)) + Γi, Γo = boundarypiece.(Ω, (:inner, :outer)) + bcs = [ + u(t, Γo) ~ outer_data, + NormalDerivative(Γi)(u(t, Γi)) + u(t, Γi) ~ inner_data, + u(0, x, y) ~ φ, + ] + sol, _ = fem_solve([heat], bcs, Ω, (x, y), t, [u(t, x, y)]; spaces = Dict(u => P2)) + return (; sol, Ω, Γi, Γo, grid = Ω.mesh) +end + +# L2 error at the final time over the discrete domain, with the geometry of the space. +function l2_error(sol) + space = sol.disc_data.space + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(space.grid)) + cv = Ferrite.CellValues(Ferrite.QuadratureRule{RefTriangle}(8), P2, ip_geo) + U, tk = sol.original_sol.u[end], sol.t[end] + err = 0.0 + for cell in Ferrite.CellIterator(space.dh) + Ferrite.reinit!(cv, cell) + xs, u_cell = Ferrite.getcoordinates(cell), U[Ferrite.celldofs(cell)] + for q in 1:Ferrite.getnquadpoints(cv) + X = Ferrite.spatial_coordinate(cv, q, xs) + err += (Ferrite.function_value(cv, q, u_cell) - u_exact(tk, X...))^2 * Ferrite.getdetJdV(cv, q) + end + end + return sqrt(err) +end + +# Least-squares slope of log(error) against log(h). +function slope(hs, errs) + X, Y = log.(hs), log.(errs) + X̄, Ȳ = sum(X) / length(X), sum(Y) / length(Y) + return sum((X .- X̄) .* (Y .- Ȳ)) / sum(abs2, X .- X̄) +end + +const SIZES = (0.2, 0.1, 0.05, 0.025) + +@testset verbose = true "curved Gmsh domain" begin + runs = Dict(order => [annulus_solve(h; order) for h in SIZES] for order in (2, 1)) + + @testset "P2 converges at rate 3 on quadratic geometry and 2 on straight-sided cells" begin + @test all(run -> SciMLBase.successful_retcode(run.sol), vcat(values(runs)...)) + @test all(run -> Ferrite.getcelltype(run.grid) === Ferrite.QuadraticTriangle, runs[2]) + @test all(run -> Ferrite.getcelltype(run.grid) === Ferrite.Triangle, runs[1]) + # Gmsh meshes are not nested; h is the mean cell size. + hs = [sqrt(π * (r_out^2 - r_in^2) / Ferrite.getncells(run.grid)) for run in runs[2]] + curved, straight = (map(run -> l2_error(run.sol), runs[order]) for order in (2, 1)) + rate(errs) = [log(errs[k] / errs[k + 1]) / log(hs[k] / hs[k + 1]) for k in 1:(length(errs) - 1)] + show3(v) = Tuple(round.(v; sigdigits = 3)) + @info "annulus, P2 through the front end" h = show3(hs) curved = show3(curved) rates_curved = show3(rate(curved)) slope(hs, curved) straight = show3(straight) rates_straight = show3(rate(straight)) slope(hs, straight) + @test slope(hs, curved) >= 2.8 + @test all(>=(2.6), rate(curved)) + @test slope(hs, straight) <= 2.3 + @test all(<=(2.4), rate(straight)) + @test curved[end] < straight[end] / 20 + end + + curved, straight = runs[2][2], runs[1][2] + + @testset "space and facet values use the mesh's geometry" begin + # Perimeter of the inner circle and the deviation of the facet normals from −X/|X|. + function geometry(run) + space = run.sol.disc_data.space + fv = only(space.facetvalues) + perimeter, normal = 0.0, 0.0 + for fi in Ferrite.getfacetset(space.grid, "inner") + xs = Ferrite.getcoordinates(space.grid, fi[1]) + Ferrite.reinit!(fv, xs, fi[2]) + for q in 1:Ferrite.getnquadpoints(fv) + X = Ferrite.spatial_coordinate(fv, q, xs) + perimeter += Ferrite.getdetJdV(fv, q) + normal = max(normal, norm(Ferrite.getnormal(fv, q) + X / norm(X))) + end + end + return (; perimeter = abs(perimeter - 2π * r_in), normal) + end + c, s = geometry(curved), geometry(straight) + @info "geometry errors at h = $(SIZES[2])" curved = c straight = s + @test c.perimeter < s.perimeter / 100 + @test c.normal < s.normal / 100 + end + + @testset "solution interface on the curved mesh" begin + (; sol, Γi, Γo, grid) = curved + U = u(t, x, y) + # Traces: every node of the outer piece, mid-side nodes included, is on the circle. + nodes = piece_nodes(sol, Γo) + X, Y = sol[x][nodes], sol[y][nodes] + @test length(nodes) == 2 * length(Ferrite.getfacetset(grid, "outer")) + @test maximum(abs, hypot.(X, Y) .- r_out) <= 1.0e-12 + trace = sol[u(t, Γo)] + @test trace ≈ sol(sol.t, Γo; dv = U) rtol = 1.0e-12 + @test maximum(abs, trace .- [u_exact(tk, X[i], Y[i]) for tk in sol.t, i in eachindex(nodes)]) <= 1.0e-8 + @test nodal_error(sol, U, u_exact) <= 1.0e-3 + + # Point evaluation inside, and between the vertices of an outer arc, where the chord of a + # straight-sided cell leaves the domain. + pts = [(0.7, 0.1), (-0.3, 0.6), (0.0, -0.9)] + @test all(p -> abs(sol(1.0, p...; dv = U) - u_exact(1.0, p...)) <= 1.0e-3, pts) + fi = first(sort!(collect(Ferrite.getfacetset(grid, "outer")); by = fi -> (fi[1], fi[2]))) + a, b = (atan(v[2], v[1]) for v in facet_ends(grid, fi)) + θ = a + 0.25 * rem2pi(b - a, RoundNearest) + p = (r_out - 1.0e-9) .* (cos(θ), sin(θ)) + @test abs(sol(1.0, p...; dv = U) - u_exact(1.0, p...)) <= 1.0e-3 + @test isnan(straight.sol(1.0, p...; dv = U)) + + # The facet-mean normal flux on the curved Robin piece converges to that of u*. + @test sol[NormalDerivative(Γi)(u(t, Γi))] == normal_flux(sol, U, Γi) + function flux_error(run) + (; sol, Γi, grid) = run + fv = only(sol.disc_data.space.facetvalues) + facets = sort!(collect(Ferrite.getfacetset(grid, "inner")); by = fi -> (fi[1], fi[2])) + exact = map(facets) do fi + xs = Ferrite.getcoordinates(grid, fi[1]) + Ferrite.reinit!(fv, xs, fi[2]) + qs = 1:Ferrite.getnquadpoints(fv) + sum(qs) do q + X = Ferrite.spatial_coordinate(fv, q, xs) + (1 + sol.t[end]) * dot([g(X...) for g in ∇φ_f], Ferrite.getnormal(fv, q)) * Ferrite.getdetJdV(fv, q) + end / sum(q -> Ferrite.getdetJdV(fv, q), qs) + end + return maximum(abs, sol[NormalDerivative(Γi)(u(t, Γi))][end, :] - exact) + end + errs = [flux_error(runs[2][k]) for k in 2:3] + @info "inner normal flux error at h = $(SIZES[2:3])" errs + @test errs[2] < errs[1] / 3 + @test errs[2] <= 5.0e-3 + end +end From 2e4a793c4b2dae7787817e720a3f355291d52cce Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 09:28:30 +0000 Subject: [PATCH 07/62] Implement dirichlet = :eliminate on the numeric path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spec §7.3 offers eliminating the prescribed dofs for constant Dirichlet data: the DAE is restricted to the free dofs (M[fr,fr], K[fr,cd] g moved to the load) and the solution wrapper rebuilds the full field, so every accessor returns the same shapes as :algebraic. Time-dependent data are rejected with a documented ArgumentError. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 16 +++ docs/src/api.md | 1 + src/discretization.jl | 24 ++-- src/frontend.jl | 25 +++- src/numeric_dae.jl | 45 ++++++++ src/solution.jl | 19 +-- test/DAE/numeric_dae.jl | 1 + test/Frontend/eliminate.jl | 9 ++ test/shared/frontend_tests/eliminate.jl | 146 ++++++++++++++++++++++++ test/shared/frontend_tests/errors.jl | 4 +- 10 files changed, 268 insertions(+), 22 deletions(-) create mode 100644 test/Frontend/eliminate.jl create mode 100644 test/shared/frontend_tests/eliminate.jl diff --git a/docs/discretization.md b/docs/discretization.md index b38631ad..3463b840 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -11,3 +11,19 @@ FiniteElementMethod.AbstractTestSpace FiniteElementMethod.Galerkin FiniteElementMethod.assemble_sources! ``` + +## Dirichlet conditions + +`dirichlet = :algebraic` (the default) keeps every dof as an unknown and makes each prescribed +row the algebraic equation `u_d = g_d(t)`, so it accepts Dirichlet data of any time dependence. +`dirichlet = :eliminate` removes the prescribed dofs instead: the `DAEProblem` has only the free +dofs as unknowns, with `M[fr, fr]`, `K[fr, fr]` and the load `F[fr] - K[fr, cd] g`. It needs +Dirichlet data that are constant in time, though they may vary in space; time-dependent data +raise an `ArgumentError` naming the boundary piece. The solution is the same either way: +`sol[u]`, `sol(t, x, y)`, traces `sol[u(t, Γ)]`, `normal_flux` and `write_vtk` all return the +full field with `g` at the prescribed nodes. Only `sol.original_sol` and the array unknowns +hold the free dofs alone. + +```julia +disc = FEMDiscretization(Ω, t; dirichlet = :eliminate) +``` diff --git a/docs/src/api.md b/docs/src/api.md index 8bdde336..92724e96 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -31,6 +31,7 @@ FiniteElementMethod.dirichlet_rates FiniteElementMethod.fem_system FiniteElementMethod.numeric_dae_problem FiniteElementMethod.consistent_du0 +FiniteElementMethod.eliminate_dirichlet FiniteElementMethod.check_finite_initial_condition ``` diff --git a/src/discretization.jl b/src/discretization.jl index 1a34c9b4..755a6464 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -20,10 +20,21 @@ Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknow - `ibp`: equation (or its index) `=>` `PDEBase.StrongForm` integration-by-parts policy. - `pairing`: equation `=>` dependent variable it is tested with, needed for an equation with no time derivative of its own, such as `0 ~ Dxx(v) + f`. - - `codegen = :mtk` and `dirichlet = :eliminate` are reserved for later milestones and - raise; remaining keywords are passed to the `DAEProblem`, where a keyword given at the - `DAEProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` - are set by the discretization and rejected. + - `dirichlet`: how Dirichlet conditions enter the DAE (spec §7.3). The default `:algebraic` + keeps every dof as an unknown and makes each prescribed row the algebraic equation + `u_d = g_d(t)`. `:eliminate` removes the prescribed dofs: the unknowns are the free dofs + `fr`, the operators are `M[fr, fr]` and `K[fr, fr]` and the load is `F[fr] - K[fr, cd] g`. + It needs Dirichlet data that are constant in time (they may vary in space); data that + depend on time raise `ArgumentError("dirichlet = :eliminate needs Dirichlet data that are + constant in time, but the condition on boundary piece depends on time; use the default + dirichlet = :algebraic")` from `DAEProblem`. The solution 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. + - `codegen = :mtk` is reserved for a later milestone and raises; remaining keywords are + passed to the `DAEProblem`, where a keyword given at the `DAEProblem`/`discretize` call + wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` are set by the discretization and + rejected. Pieces come from `boundarypiece.(Ω, names)`; on an analytic DomainSets box write `boundarypiece.(Ref(rect), names)`, since DomainSets types do not broadcast as scalars. @@ -76,9 +87,8 @@ function FEMDiscretization( throw(ArgumentError("FEMDiscretization needs a MeshDomain of a Ferrite.Grid, got a mesh of type $(typeof(domain.mesh))")) codegen === :mtk && throw(ArgumentError("codegen = :mtk lands in M3; use the default codegen = :numeric")) codegen === :numeric || throw(ArgumentError("codegen must be :numeric, got $(repr(codegen))")) - dirichlet === :eliminate && - throw(ArgumentError("dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic")) - dirichlet === :algebraic || throw(ArgumentError("dirichlet must be :algebraic, got $(repr(dirichlet))")) + dirichlet in (:algebraic, :eliminate) || + throw(ArgumentError("dirichlet must be :algebraic or :eliminate, got $(repr(dirichlet))")) test_space isa Galerkin || throw(ArgumentError("test space $(test_space) lands in M4; only Galerkin() is supported")) _check_reserved(kwargs) diff --git a/src/frontend.jl b/src/frontend.jl index 6c493082..a376c4d4 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -292,23 +292,36 @@ function _lower(pdesys, disc::FEMDiscretization) dirichlet = emit_dirichlet(an) t0, t1 = v.intervals[v.time] space, names, ips = _space(disc, ctx, an, dirichlet, pvals, t0) - timedep_dirichlet = any(bc -> _depends(bc.g, [an.slots.T]), an.essential) - ops, coords = _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) + timedep = findfirst(bc -> _depends(bc.g, [an.slots.T]), an.essential) + disc.dirichlet === :eliminate && timedep !== nothing && throw( + ArgumentError( + "dirichlet = :eliminate needs Dirichlet data that are constant in time, but the condition on boundary piece " * + "$(an.essential[timedep].piece.name) depends on time; use the default dirichlet = :algebraic" + ) + ) + ops, coords = _operators(space, wf, names, dirichlet, pvals, t0, timedep !== nothing) u0 = _initial_values(Equation[b.eq for b in ics], ctx, space, coords, an, names, pvals) dirichlet_values!(view(u0, ops.prescribed), ops.load, t0) + elimination = nothing + unknown_u0 = u0 + if disc.dirichlet === :eliminate + ops, elimination = eliminate_dirichlet(ops) + unknown_u0 = u0[elimination.free] + end iv = disc.time - unknowns = [only(@variables $name(iv)[1:length(field_range(space, name))]) for name in names] + unknowns = [only(@variables $name(iv)[1:length(r)]) for (name, r) in ops.fields] fields = [FieldInfo(dv, name, u, ip) for (dv, name, u, ip) in zip(StrongForm.declared_fields(sys, v), names, unknowns, ips)] pieces = Dict{Any, String}(Γ => String(Γ.name) for Γ in PDEBase.boundarypieces(disc.domain)) - md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0) - return (; ops, u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys)) + md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0, elimination) + return (; ops, u0 = unknown_u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys)) end """ DAEProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) Discretize `pdesys` with `disc` and return the `DAEProblem` `M du + K u = F(t)` of the -Galerkin operators, with Dirichlet rows `u_d = g_d(t)` as algebraic equations, a sparse +Galerkin operators, with Dirichlet rows `u_d = g_d(t)` as algebraic equations (or, with +`dirichlet = :eliminate`, restricted to the free dofs), a sparse analytic Jacobian and the `FEMMetadata` as its `problem_type`, so `solve` returns a `PDETimeSeriesSolution`. Nothing calls `mtkcompile`; anything this milestone cannot discretize raises. Keywords are passed to the `DAEProblem` after `disc.kwargs`, so a keyword diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index ef8bf2d2..6da03038 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -155,6 +155,51 @@ function replace_dirichlet_rows!(M, K, prescribed) return M, K end +# What the post-step needs to rebuild the full dof vector from the free dofs. +struct DirichletElimination + n::Int + free::Vector{Int} + prescribed::Vector{Int} + values::Vector{Float64} +end + +function full_state(e::DirichletElimination, u_free) + u = zeros(eltype(u_free), e.n) + u[e.free] = u_free + u[e.prescribed] = e.values + return u +end + +""" + eliminate_dirichlet(ops::FEMOperators) -> (reduced::FEMOperators, elimination) + +Restrict `ops` to its free dofs `fr` (spec §7.3): `M[fr, fr]`, `K[fr, fr]` and the load +`F[fr] - K[fr, cd] g` for the prescribed dofs `cd`. The Dirichlet data `g` must be constant in +time, so `g' = 0` and the term `M[fr, cd] g'` vanishes; time-dependent data throw an `ArgumentError`. +The field ranges of `reduced` count free dofs only; `full_state(elimination, u_free)` rebuilds +the full dof vector with `u[cd] = g`. +""" +function eliminate_dirichlet(ops::FEMOperators) + F = ops.load + F.values isa Union{Number, AbstractVector} || + throw(ArgumentError("eliminate_dirichlet needs Dirichlet data that are constant in time")) + n = size(ops.K, 1) + isfree = trues(n) + isfree[ops.prescribed] .= false + free = findall(isfree) + g = dirichlet_values!(zeros(length(ops.prescribed)), F, 0.0) + Kg = ops.K[free, ops.prescribed] * g + load = F.load isa AbstractVector ? F.load[free] - Kg : + (out, t) -> (out .= view(F.load(zeros(n), t), free) .- Kg; out) + stop = 0 + fields = map(ops.fields) do (name, r) + start, stop = stop + 1, stop + count(view(isfree, r)) + name => start:stop + end + reduced = FEMOperators(ops.M[free, free], ops.K[free, free], load, fields) + return reduced, DirichletElimination(n, free, ops.prescribed, g) +end + """ check_finite_initial_condition(u0, fields; coordinate = nothing) diff --git a/src/solution.jl b/src/solution.jl index 98c0911b..b165e4c0 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -13,7 +13,7 @@ struct FieldInfo end """ - FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[]) + FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[], elimination = nothing) Discretization metadata passed as the `problem_type` of the `DAEProblem` (or, for a steady problem with `time === nothing`, the `NonlinearProblem`), so that `solve` returns a @@ -27,6 +27,8 @@ called in the variables of the `PDESystem`. - `fields`: one [`FieldInfo`](@ref) per dependent variable. - `pieces`: maps each boundary piece to the name of its Ferrite facet set. - `pdesys`: the `PDESystem` that was discretized. + - `elimination`: `nothing`, or for `dirichlet = :eliminate` the data that rebuild the full + dof vector from the solver's free dofs, so every accessor returns full fields. """ struct FEMMetadata{hasTime, DH, PDE, Sp} <: SciMLBase.AbstractDiscretizationMetadata{hasTime} space::Sp @@ -37,13 +39,14 @@ struct FEMMetadata{hasTime, DH, PDE, Sp} <: SciMLBase.AbstractDiscretizationMeta pdesys::PDE metadata::Ref{Any} u0::Vector + elimination::Union{Nothing, DirichletElimination} end -function FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[]) +function FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[], elimination = nothing) hasTime = time === nothing ? Val(false) : Val(true) return FEMMetadata{hasTime, typeof(space.dh), typeof(pdesys), typeof(space)}( space, time, collect(Any, x̄), collect(FieldInfo, fields), - Dict{Any, String}(pieces), pdesys, Ref{Any}(nothing), u0 + Dict{Any, String}(pieces), pdesys, Ref{Any}(nothing), u0, elimination ) end @@ -104,6 +107,8 @@ function _locate(grid, pts) end _dh(md::FEMMetadata) = md.space.dh +# The full dof vector of a solver state. +_full(md::FEMMetadata, U) = md.elimination === nothing ? U : full_state(md.elimination, U) _grid(md::FEMMetadata) = _dh(md).grid # Ferrite's FE values default to linear geometry, which breaks on quadratic cells. _geometry(md::FEMMetadata) = Ferrite.geometric_interpolation(Ferrite.getcelltype(_grid(md))) @@ -116,7 +121,7 @@ function _wrap_parts(sol, md::FEMMetadata, states) for f in md.fields out = Matrix{T}(undef, nt, Ferrite.getnnodes(_grid(md))) for (k, U) in enumerate(states) - out[k, :] .= Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name) + out[k, :] .= Ferrite.evaluate_at_grid_nodes(_dh(md), _full(md, U), f.name) end umap[Num(f.dv)] = out end @@ -164,8 +169,8 @@ function Base.lastindex(::FEMSolution, ::Integer) throw(ArgumentError("`end` cannot be resolved in `sol[dv, inds...]`; index the field instead: `sol[dv][end, :]`.")) end -_states(A::FEMTimeSolution) = A.original_sol.u -_states(A::FEMSteadySolution) = [A.original_sol.u] +_states(A::FEMTimeSolution) = [_full(A.disc_data, U) for U in A.original_sol.u] +_states(A::FEMSteadySolution) = [_full(A.disc_data, A.original_sol.u)] _stack(::FEMTimeSolution, rows) = permutedims(reduce(hcat, rows)) _stack(::FEMSteadySolution, rows) = only(rows) _columns(values::AbstractMatrix, idxs) = values[:, idxs] @@ -334,7 +339,7 @@ Base.getindex(A::FEMSolution, sym::Num, args...) = A[sym][args...] function _dofs_at(A::FEMTimeSolution, t::Real) lo, hi = minmax(A.t[1], A.t[end]) lo <= t <= hi || throw(DomainError(t, "outside the saved time span $(A.t[1]) .. $(A.t[end])")) - return A.original_sol(t) + return _full(A.disc_data, A.original_sol(t)) end _axis(a) = a isa AbstractVector ? collect(a) : [a] diff --git a/test/DAE/numeric_dae.jl b/test/DAE/numeric_dae.jl index 98b20403..470f77e0 100644 --- a/test/DAE/numeric_dae.jl +++ b/test/DAE/numeric_dae.jl @@ -230,6 +230,7 @@ heat_operators(fe; kw...) = FEMOperators(fe.M, fe.K, fe.F, [:u => 1:length(fe.F) @test SciMLBase.successful_retcode(sol) @test sol(0.05) ≈ [-0.05, 0.05] atol = 1.0e-12 @test sol.u[end] ≈ [-1.0, 1.0] atol = 1.0e-12 + @test_throws ArgumentError("eliminate_dirichlet needs Dirichlet data that are constant in time") FiniteElementMethod.eliminate_dirichlet(ops2) # Constant Dirichlet data gives du_d = 0. @test FiniteElementMethod.dirichlet_rates(ops.load, 0.0) == zeros(length(fe.prescribed)) end diff --git a/test/Frontend/eliminate.jl b/test/Frontend/eliminate.jl new file mode 100644 index 00000000..cc93a575 --- /dev/null +++ b/test/Frontend/eliminate.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "eliminate.jl")) +else + @testset "eliminate (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/eliminate.jl b/test/shared/frontend_tests/eliminate.jl new file mode 100644 index 00000000..a7611904 --- /dev/null +++ b/test/shared/frontend_tests/eliminate.jl @@ -0,0 +1,146 @@ +# End-to-end tests of `dirichlet = :eliminate` (spec §7.3): PDESystem -> DAEProblem on the free +# dofs -> solve, checked against exact solutions in the finite-element space and against +# `:algebraic`, with the full field rebuilt for every solution accessor. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, field_range, prescribed_dofs +using Ferrite: Triangle, Line + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t +using LinearAlgebra: norm + +@variables x y u(..) v(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +const tol = 1.0e-8 +const P2_LINE = Dict(u => Lagrange{RefLine, 2}()) + +pieces(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +eliminated(args...; kw...) = fem_solve(args...; dirichlet = :eliminate, kw...) + +# u* = a + b x + x(1 - x)(1 + t) solves u_t = u_xx + x(1 - x) + 2(1 + t) and is in the P2 space. +bubble_eq = Dt(u(t, x)) ~ Dx(Dx(u(t, x))) + x * (1 - x) + 2 * (1 + t) +bubble(a, b) = (t_, x_) -> a + b * x_ + x_ * (1 - x_) * (1 + t_) + +@testset verbose = true "dirichlet = :eliminate" begin + @testset "homogeneous Dirichlet, 1D P2" begin + Ω = MeshDomain(rectangle_grid(Line, (4,))) + lo, hi = boundarypiece.(Ω, (:x1_lo, :x1_hi)) + bcs = [u(t, lo) ~ 0, u(t, hi) ~ 0, u(0, x) ~ x * (1 - x)] + sol, prob = eliminated([bubble_eq], bcs, Ω, (x,), t, [u(t, x)]; spaces = P2_LINE) + @test SciMLBase.successful_retcode(sol) + @test length(prob.u0) == 9 - 2 + @test nodal_error(sol, u(t, x), bubble(0, 0)) <= tol + end + + @testset "nonzero constant Dirichlet, 1D P2" begin + Ω = MeshDomain(rectangle_grid(Line, (4,))) + lo, hi = boundarypiece.(Ω, (:x1_lo, :x1_hi)) + bcs = [u(t, lo) ~ 2, u(t, hi) ~ 3, u(0, x) ~ 2 + x + x * (1 - x)] + sol, _ = eliminated([bubble_eq], bcs, Ω, (x,), t, [u(t, x)]; spaces = P2_LINE) + @test nodal_error(sol, u(t, x), bubble(2, 1)) <= tol + @test sol[u(t, lo)] ≈ fill(2.0, length(sol.t), 1) atol = 1.0e-14 + @test sol[u(t, hi)] ≈ fill(3.0, length(sol.t), 1) atol = 1.0e-14 + end + + @testset "spatially varying constant Dirichlet with Neumann pieces, 2D P2" begin + # u* = 1 + x + 2y + x(1 - x)(1 + t): Dirichlet in x, Neumann in y. + Ω = MeshDomain(rectangle_grid(Triangle, (3, 3))) + Γl, Γr, Γb, Γt = pieces(Ω) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + x * (1 - x) + 2 * (1 + t) + bcs = [ + u(t, Γl) ~ 1 + 2y, u(t, Γr) ~ 2 + 2y, + NormalDerivative(Γb)(u(t, Γb)) ~ -2, NormalDerivative(Γt)(u(t, Γt)) ~ 2, + u(0, x, y) ~ 1 + x + 2y + x * (1 - x), + ] + sol, _ = eliminated( + [eq], bcs, Ω, (x, y), t, [u(t, x, y)]; spaces = Dict(u => Lagrange{RefTriangle, 2}()) + ) + @test nodal_error(sol, u(t, x, y), (t_, x_, y_) -> 1 + x_ + 2y_ + x_ * (1 - x_) * (1 + t_)) <= tol + end + + # Constant Dirichlet data, a time-dependent source (the load is a function of t) and an + # initial field that is not an exact solution. + Ω = MeshDomain(rectangle_grid(Triangle, (6, 6))) + Γl, Γr, Γb, Γt = pieces(Ω) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + sin(3x + t) * (1 + y) + top(x_) = 1 + x_ + x_ * (1 - x_) + bcs = [[u(t, Γ) ~ 1 + x for Γ in (Γl, Γr, Γb)]; u(t, Γt) ~ top(x); u(0, x, y) ~ 1 + x + x * (1 - x) * y^2] + solve_kwargs = (; abstol = 1.0e-10, reltol = 1.0e-10, saveat = 0.1) + alg_sol, alg_prob = fem_solve([eq], bcs, Ω, (x, y), t, [u(t, x, y)]; solve_kwargs) + sol, prob = eliminated([eq], bcs, Ω, (x, y), t, [u(t, x, y)]; solve_kwargs) + + @testset "agrees with :algebraic" begin + @test SciMLBase.successful_retcode(sol) + @test sol.t ≈ alg_sol.t + @test maximum(abs, sol[u(t, x, y)] - alg_sol[u(t, x, y)]) <= 1.0e-7 + end + + @testset "reduced problem" begin + space = sol.disc_data.space + free = setdiff(1:length(alg_prob.u0), prescribed_dofs(space)) + @test length(prob.u0) == length(free) == size(prob.f.jac_prototype, 1) + @test prob.u0 == alg_prob.u0[free] + @test all(prob.differential_vars) + res = similar(prob.u0) + prob.f(res, prob.du0, prob.u0, prob.p, 0.0) + @test norm(res, Inf) <= 1.0e-10 + @test length(sol.original_sol[only(sol.disc_data.fields).unknown][end]) == length(free) + end + + @testset "solution interface returns full fields" begin + U = sol[u(t, x, y)] + @test size(U) == size(alg_sol[u(t, x, y)]) + for (Γ, g) in ((Γl, x_ -> 1 + x_), (Γt, top)) + nodes = piece_nodes(sol, Γ) + expected = [g(sol[x][i]) for _ in sol.t, i in nodes] + @test sol[u(t, Γ)] ≈ expected atol = 1.0e-14 + @test U[:, nodes] ≈ expected atol = 1.0e-14 + @test sol(0.35, Γ; dv = u(t, x, y)) ≈ expected[1, :] atol = 1.0e-14 + end + @test sol(0.35, 0.0, 0.5; dv = u(t, x, y)) ≈ 1.0 atol = 1.0e-14 + @test sol(0.35, 0.3, 0.6; dv = u(t, x, y)) ≈ alg_sol(0.35, 0.3, 0.6; dv = u(t, x, y)) atol = 1.0e-6 + @test normal_flux(sol, u(t, x, y), Γr) ≈ normal_flux(alg_sol, u(t, x, y), Γr) atol = 1.0e-6 + @test sol[Dx(u(t, x, y))] ≈ alg_sol[Dx(u(t, x, y))] atol = 1.0e-6 + mktempdir() do dir + pvd = write_vtk(sol, joinpath(dir, "heat")) + @test isfile(pvd) + @test count(endswith(".vtu"), readdir(dir)) == length(sol.t) + end + end + + @testset "algebraic field: structurally zero mass rows stay algebraic" begin + # u_t = Δu + v with 0 = Δv: v* = 1 + x is exact in P1, and u is compared with :algebraic. + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(t, x, y) + algebraic = 0 ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))) + Ω2 = MeshDomain(rectangle_grid(Triangle, (4, 4))) + bcs2 = [ + [u(t, Γ) ~ 1 + x + 2y for Γ in pieces(Ω2)]; [v(t, Γ) ~ 1 + x for Γ in pieces(Ω2)]; + u(0, x, y) ~ (1 + x + 2y) + x * (1 - x) * y * (1 - y) + ] + sol2, prob2 = eliminated( + [parabolic, algebraic], bcs2, Ω2, (x, y), t, [u(t, x, y), v(t, x, y)]; + pairing = Dict(algebraic => v), tspan = (0.0, 5.0), solve_kwargs + ) + alg2, _ = fem_solve( + [parabolic, algebraic], bcs2, Ω2, (x, y), t, [u(t, x, y), v(t, x, y)]; + pairing = Dict(algebraic => v), tspan = (0.0, 5.0), solve_kwargs + ) + @test SciMLBase.successful_retcode(sol2) + space = sol2.disc_data.space + nfree(name) = count(!in(prescribed_dofs(space)), field_range(space, name)) + @test prob2.differential_vars == [trues(nfree(:u)); falses(nfree(:v))] + @test nodal_error(sol2, v(t, x, y), (t_, x_, y_) -> 1 + x_) <= tol + @test maximum(abs, sol2[u(t, x, y)] - alg2[u(t, x, y)]) <= 1.0e-7 + end + + @testset "time-dependent Dirichlet data are rejected" begin + td = [u(t, Γl) ~ 1 + x; u(t, Γr) ~ (2 + x) * (1 + t); [u(t, Γ) ~ 1 + x for Γ in (Γb, Γt)]; u(0, x, y) ~ 1 + x] + @named pdesys = PDESystem([eq], td, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_throws ArgumentError( + "dirichlet = :eliminate needs Dirichlet data that are constant in time, but the condition on " * + "boundary piece right depends on time; use the default dirichlet = :algebraic" + ) discretize(pdesys, FEMDiscretization(Ω, t; dirichlet = :eliminate)) + @test discretize(pdesys, FEMDiscretization(Ω, t)) isa SciMLBase.DAEProblem + end +end diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index f50b6b39..c256e8c0 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -86,8 +86,8 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @test_throws ArgumentError("codegen = :mtk lands in M3; use the default codegen = :numeric") FEMDiscretization( Ω, t; codegen = :mtk ) - @test_throws ArgumentError("dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic") FEMDiscretization( - Ω, t; dirichlet = :eliminate + @test_throws ArgumentError("dirichlet must be :algebraic or :eliminate, got :condense") FEMDiscretization( + Ω, t; dirichlet = :condense ) @named steady = PDESystem( [Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], [] From 35c99dce88c2ade79ddab966605d9d4e4935fbe7 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 12:01:44 +0000 Subject: [PATCH 08/62] Leave fully prescribed fields out of the eliminated system With dirichlet = :eliminate a field whose dofs are all prescribed kept an empty range, and ModelingToolkit rejects an empty array unknown (Codex round 1). Such a field now has no array unknown (FieldInfo.unknown is nothing) and is rebuilt from its Dirichlet data; a problem with every dof prescribed is rejected with a documented ArgumentError. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 11 ++++++---- src/frontend.jl | 6 +++++- src/numeric_dae.jl | 18 ++++++++++++----- src/solution.jl | 3 ++- test/DAE/numeric_dae.jl | 9 +++++++++ test/shared/frontend_tests/eliminate.jl | 27 +++++++++++++++++++++++++ 6 files changed, 63 insertions(+), 11 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index 755a6464..bd732141 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -27,10 +27,13 @@ Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknow It needs Dirichlet data that are constant in time (they may vary in space); data that depend on time raise `ArgumentError("dirichlet = :eliminate needs Dirichlet data that are constant in time, but the condition on boundary piece depends on time; use the default - dirichlet = :algebraic")` from `DAEProblem`. The solution 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. + dirichlet = :algebraic")` from `DAEProblem`. A field whose dofs are all prescribed has no + array unknown (its `FieldInfo.unknown` is `nothing`); if every dof of the problem is + prescribed, `DAEProblem` raises `ArgumentError("dirichlet = :eliminate leaves no unknowns + because every dof is prescribed; use the default dirichlet = :algebraic")`. The solution + 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. - `codegen = :mtk` is reserved for a later milestone and raises; remaining keywords are passed to the `DAEProblem`, where a keyword given at the `DAEProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` are set by the discretization and diff --git a/src/frontend.jl b/src/frontend.jl index a376c4d4..a394fda4 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -310,7 +310,11 @@ function _lower(pdesys, disc::FEMDiscretization) end iv = disc.time unknowns = [only(@variables $name(iv)[1:length(r)]) for (name, r) in ops.fields] - fields = [FieldInfo(dv, name, u, ip) for (dv, name, u, ip) in zip(StrongForm.declared_fields(sys, v), names, unknowns, ips)] + unknown_of = Dict(zip(first.(ops.fields), unknowns)) + fields = [ + FieldInfo(dv, name, get(unknown_of, name, nothing), ip) + for (dv, name, ip) in zip(StrongForm.declared_fields(sys, v), names, ips) + ] pieces = Dict{Any, String}(Γ => String(Γ.name) for Γ in PDEBase.boundarypieces(disc.domain)) md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0, elimination) return (; ops, u0 = unknown_u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys)) diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index 6da03038..f469a5d5 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -175,8 +175,10 @@ end Restrict `ops` to its free dofs `fr` (spec §7.3): `M[fr, fr]`, `K[fr, fr]` and the load `F[fr] - K[fr, cd] g` for the prescribed dofs `cd`. The Dirichlet data `g` must be constant in -time, so `g' = 0` and the term `M[fr, cd] g'` vanishes; time-dependent data throw an `ArgumentError`. -The field ranges of `reduced` count free dofs only; `full_state(elimination, u_free)` rebuilds +time, so `g' = 0` and the term `M[fr, cd] g'` vanishes; time-dependent data, and operators +with every dof prescribed, throw an `ArgumentError`. +The field ranges of `reduced` count free dofs only, and a field whose dofs are all prescribed +is left out of them; `full_state(elimination, u_free)` rebuilds the full dof vector with `u[cd] = g`. """ function eliminate_dirichlet(ops::FEMOperators) @@ -187,14 +189,20 @@ function eliminate_dirichlet(ops::FEMOperators) isfree = trues(n) isfree[ops.prescribed] .= false free = findall(isfree) + isempty(free) && throw( + ArgumentError("dirichlet = :eliminate leaves no unknowns because every dof is prescribed; use the default dirichlet = :algebraic") + ) g = dirichlet_values!(zeros(length(ops.prescribed)), F, 0.0) Kg = ops.K[free, ops.prescribed] * g load = F.load isa AbstractVector ? F.load[free] - Kg : (out, t) -> (out .= view(F.load(zeros(n), t), free) .- Kg; out) stop = 0 - fields = map(ops.fields) do (name, r) - start, stop = stop + 1, stop + count(view(isfree, r)) - name => start:stop + fields = Pair{Symbol, UnitRange{Int}}[] + for (name, r) in ops.fields + nfree = count(view(isfree, r)) + # A field with every dof prescribed has no unknowns; MTK rejects an empty array unknown. + nfree == 0 || push!(fields, name => (stop + 1):(stop + nfree)) + stop += nfree end reduced = FEMOperators(ops.M[free, free], ops.K[free, free], load, fields) return reduced, DirichletElimination(n, free, ops.prescribed, g) diff --git a/src/solution.jl b/src/solution.jl index b165e4c0..ae1eba30 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -3,7 +3,8 @@ One dependent variable of a FEM discretization: the `PDESystem` dependent variable `dv` (for example `u(t, x, y)`), the name of its field in the `DofHandler`, the array unknown -of the discretized system (for example `u(t)[1:n]`) and the field's interpolation. +of the discretized system (for example `u(t)[1:n]`, or `nothing` for a field that +`dirichlet = :eliminate` prescribes entirely) and the field's interpolation. """ struct FieldInfo dv::Any diff --git a/test/DAE/numeric_dae.jl b/test/DAE/numeric_dae.jl index 470f77e0..7cc76d6d 100644 --- a/test/DAE/numeric_dae.jl +++ b/test/DAE/numeric_dae.jl @@ -231,6 +231,15 @@ heat_operators(fe; kw...) = FEMOperators(fe.M, fe.K, fe.F, [:u => 1:length(fe.F) @test sol(0.05) ≈ [-0.05, 0.05] atol = 1.0e-12 @test sol.u[end] ≈ [-1.0, 1.0] atol = 1.0e-12 @test_throws ArgumentError("eliminate_dirichlet needs Dirichlet data that are constant in time") FiniteElementMethod.eliminate_dirichlet(ops2) + # Eliminating every dof of the first field leaves only the second as an unknown. + A4 = spdiagm(-1 => fill(-1.0, 3), 0 => fill(2.0, 4), 1 => fill(-1.0, 3)) + ops4 = FEMOperators(A4, copy(A4), zeros(4), [:u => 1:2, :v => 3:4]; prescribed = [1, 2], dirichlet_values = 1.0) + reduced, elimination = FiniteElementMethod.eliminate_dirichlet(ops4) + @test reduced.fields == [:v => 1:2] + @test reduced.load.load == [1.0, 0.0] + prob4 = numeric_dae_problem(reduced, zeros(2), (0.0, 1.0)) + @test length(prob4.u0) == 2 + @test FiniteElementMethod.full_state(elimination, [3.0, 4.0]) == [1.0, 1.0, 3.0, 4.0] # Constant Dirichlet data gives du_d = 0. @test FiniteElementMethod.dirichlet_rates(ops.load, 0.0) == zeros(length(fe.prescribed)) end diff --git a/test/shared/frontend_tests/eliminate.jl b/test/shared/frontend_tests/eliminate.jl index a7611904..d71e80f9 100644 --- a/test/shared/frontend_tests/eliminate.jl +++ b/test/shared/frontend_tests/eliminate.jl @@ -134,6 +134,33 @@ bubble(a, b) = (t_, x_) -> a + b * x_ + x_ * (1 - x_) * (1 + t_) @test maximum(abs, sol2[u(t, x, y)] - alg2[u(t, x, y)]) <= 1.0e-7 end + @testset "a field with every dof prescribed has no unknowns" begin + # Two triangles have no interior node, so v = 1 + x on the whole boundary prescribes all of v. + # u* = (1 + x) t solves u_t = Δu + v with the Neumann data ∂ₙu = ∓t on the left and right. + Ω1 = MeshDomain(rectangle_grid(Triangle, (1, 1))) + Γl1, Γr1, Γb1, Γt1 = pieces(Ω1) + Dn(Γ) = NormalDerivative(Γ) + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(t, x, y) + algebraic = 0 ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))) + bcs1 = [ + Dn(Γl1)(u(t, Γl1)) ~ -t; Dn(Γr1)(u(t, Γr1)) ~ t; Dn(Γb1)(u(t, Γb1)) ~ 0; Dn(Γt1)(u(t, Γt1)) ~ 0; + [v(t, Γ) ~ 1 + x for Γ in pieces(Ω1)]; u(0, x, y) ~ 0 + ] + sol1, prob1 = eliminated( + [parabolic, algebraic], bcs1, Ω1, (x, y), t, [u(t, x, y), v(t, x, y)]; pairing = Dict(algebraic => v) + ) + @test SciMLBase.successful_retcode(sol1) + @test length(prob1.u0) == 4 + @test [f.unknown === nothing for f in sol1.disc_data.fields] == [false, true] + @test nodal_error(sol1, u(t, x, y), (t_, x_, y_) -> (1 + x_) * t_) <= tol + @test nodal_error(sol1, v(t, x, y), (t_, x_, y_) -> 1 + x_) <= 1.0e-14 + @test size(sol1[v(t, x, y)]) == size(sol1[u(t, x, y)]) + # With every dof prescribed there is nothing left to integrate. + @test_throws ArgumentError( + "dirichlet = :eliminate leaves no unknowns because every dof is prescribed; use the default dirichlet = :algebraic" + ) eliminated([eq], [[u(t, Γ) ~ 1 + x for Γ in pieces(Ω1)]; u(0, x, y) ~ 1 + x], Ω1, (x, y), t, [u(t, x, y)]) + end + @testset "time-dependent Dirichlet data are rejected" begin td = [u(t, Γl) ~ 1 + x; u(t, Γr) ~ (2 + x) * (1 + t); [u(t, Γ) ~ 1 + x for Γ in (Γb, Γt)]; u(0, x, y) ~ 1 + x] @named pdesys = PDESystem([eq], td, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) From 40e3ff5447a6a5180fe7274c5da663df9aaa6540 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 12:35:03 +0000 Subject: [PATCH 09/62] Treat a PDESystem without parameters as having none A PDESystem built without the ps argument stores NullParameters(), and iterating it in _parameter_values threw on both the time-dependent and the steady path. Regression tests solve a heat and a Poisson problem built without ps, and check that an undeclared parameter keeps its error with ps = [] and without ps. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/frontend.jl | 3 ++- test/shared/frontend_tests/end_to_end.jl | 11 +++++++++++ test/shared/frontend_tests/errors.jl | 14 ++++++++++++++ test/shared/frontend_tests/steady.jl | 14 ++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/frontend.jl b/src/frontend.jl index 864cad77..486dd42e 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -159,7 +159,8 @@ function _check_linear(wf) end function _parameter_values(pdesys, ctx) - given = Dict{Any, Any}(unwrap(p.first) => p.second for p in pdesys.ps if p isa Pair) + ps = pdesys.ps isa SciMLBase.NullParameters ? () : pdesys.ps + given = Dict{Any, Any}(unwrap(p.first) => p.second for p in ps if p isa Pair) return map(ctx.params) do p haskey(given, p) && given[p] isa Number || throw(ArgumentError("parameter $p needs a numeric value in the PDESystem, as $p => value")) diff --git a/test/shared/frontend_tests/end_to_end.jl b/test/shared/frontend_tests/end_to_end.jl index 7cfaea55..97fa0765 100644 --- a/test/shared/frontend_tests/end_to_end.jl +++ b/test/shared/frontend_tests/end_to_end.jl @@ -72,6 +72,17 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test sys isa ModelingToolkit.System end + @testset "PDESystem without parameters" begin + # Leaving out `ps` gives the system `NullParameters()`, which means no parameters. + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + domains = [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)] + @named pdesys = PDESystem([heat_eq], [dirichlet_all(Ω); ic], domains, [t, x, y], [u(t, x, y)]) + @test pdesys.ps isa SciMLBase.NullParameters + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t)), EXACT_ROWS; abstol = 1.0e-10, reltol = 1.0e-10) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, u(t, x, y), uexact) <= tol + end + @testset "P1 quadrilaterals" begin Ω = MeshDomain(rectangle_grid(Quadrilateral, (3, 4))) sol, _ = fem_solve([heat_eq], [dirichlet_all(Ω); ic], Ω, (x, y), t, [u(t, x, y)]) diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index 954a2506..8cc5a210 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -207,6 +207,20 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @test SciMLBase.successful_retcode(sol) end + @testset "parameters" begin + Ω = box() + @parameters k + eq = Dt(u(t, x, y)) ~ k * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) + system(ps...) = PDESystem([eq], [dirichlet(Ω); ic], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], ps...; name = :pdesys) + # An undeclared parameter is reported the same way whether `ps` is empty or left out. + for pdesys in (system([]), system()) + @test occursin("unresolved symbols", errmsg(() -> discretize(pdesys, FEMDiscretization(Ω, t)))) + end + @test_throws ArgumentError("parameter k needs a numeric value in the PDESystem, as k => value") discretize( + system([k]), FEMDiscretization(Ω, t) + ) + end + @testset "a piece with no condition warns when its flux is not zero" begin Ω = box() Γl, Γr, Γb, Γt = sides(Ω) diff --git a/test/shared/frontend_tests/steady.jl b/test/shared/frontend_tests/steady.jl index eda36866..4923c83c 100644 --- a/test/shared/frontend_tests/steady.jl +++ b/test/shared/frontend_tests/steady.jl @@ -46,6 +46,20 @@ end @test log2(e1 / e2) > order + 0.8 end + @testset "PDESystem without parameters" begin + # Leaving out `ps` gives the system `NullParameters()`, which means no parameters. + # u* = 1 + x² + 2y² + xy has Δu* = 6 and is exact in P2. + u_exact(x_, y_) = 1 + x_^2 + 2y_^2 + x_ * y_ + Ω = MeshDomain(rectangle_grid(Triangle, (3, 3))) + bcs = [u(Γ) ~ u_exact(x, y) for Γ in sides(Ω)] + @named pdesys = PDESystem([Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 6], bcs, [(x, y) ∈ Ω], [x, y], [u(x, y)]) + @test pdesys.ps isa SciMLBase.NullParameters + disc = FEMDiscretization(Ω; spaces = Dict(u => Lagrange{RefTriangle, 2}())) + sol = solve(discretize(pdesys, disc), NewtonRaphson(); abstol = 1.0e-12) + @test SciMLBase.successful_retcode(sol) + @test maximum(abs, sol[u(x, y)] - u_exact.(sol[x], sol[y])) <= 1.0e-10 + end + @testset "L-shape with Dirichlet, Neumann and Robin pieces" begin # u* = 1 + x + 2y + xy + x², Δu* = 2, is exact in P2 on straight triangles. ∇u* = (1 + y + 2x, 2 + x). u_exact(x_, y_) = 1 + x_ + 2y_ + x_ * y_ + x_^2 From 72a6ef99a94d5dd7883bbf257d17f8e14dbc0513 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 12:30:35 +0000 Subject: [PATCH 10/62] Accept nonlinear terms on the numeric DAE path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Terms whose coefficients depend on the state (k(u) diffusion, u·∇u convection, reactions, nonlinear natural conditions) were rejected by the front end as an M3 item, which blocks Navier–Stokes. FEMOperators takes an optional FEMNonlinear wrapping m1's NonlinearOperator: the residual is M du + K u + N(u, t) − F with N's Dirichlet rows zeroed, the Jacobian adds N's symbolic tangent, and the attached System carries N as one registered term on the whole state (fem_cat keeps the fields as arrays; a per-field-count registration generated 150·5ⁿ⁻¹ methods and an 17 GB precompile). PDE parameters become parameters of the System at the values the operators were assembled with, and a remake that changes one is rejected at solve time instead of being ignored (spec §8.3). Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/api.md | 1 + docs/src/index.md | 7 +- src/discretization.jl | 10 +- src/frontend.jl | 25 ++-- src/numeric_dae.jl | 161 +++++++++++++++++++---- test/DAE/numeric_dae.jl | 5 + test/Frontend/nonlinear.jl | 9 ++ test/shared/frontend_tests/end_to_end.jl | 2 +- test/shared/frontend_tests/errors.jl | 6 +- test/shared/frontend_tests/nonlinear.jl | 157 ++++++++++++++++++++++ 10 files changed, 336 insertions(+), 47 deletions(-) create mode 100644 test/Frontend/nonlinear.jl create mode 100644 test/shared/frontend_tests/nonlinear.jl diff --git a/docs/src/api.md b/docs/src/api.md index 8bdde336..b3279cf1 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -26,6 +26,7 @@ FiniteElementMethod.dirichlet_values! FiniteElementMethod.FEMOperators FiniteElementMethod.FEMOp FiniteElementMethod.FEMLoad +FiniteElementMethod.FEMNonlinear FiniteElementMethod.load! FiniteElementMethod.dirichlet_rates FiniteElementMethod.fem_system diff --git a/docs/src/index.md b/docs/src/index.md index 40806562..f0495799 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -6,8 +6,11 @@ on a mesh, derives the Galerkin weak form, assembles it with [Ferrite.jl](https://github.com/Ferrite-FEM/Ferrite.jl) and lowers it to a `DAEProblem`. !!! warning - This package is under construction. Linear scalar problems with Galerkin testing are - supported; nonlinear terms, periodic conditions and other test spaces raise an error. + This package is under construction. Problems with Galerkin testing are supported, + including nonlinear terms whose state dependence is in the coefficients, sources and + natural conditions (`∇·((1 + u²)∇u)`, `u ∂ₓu`, `u²`, `∂ₙu = −u⁴`); periodic + conditions, time-dependent mass or stiffness coefficients and other test spaces raise + an error. ```@docs FiniteElementMethod diff --git a/src/discretization.jl b/src/discretization.jl index 1a34c9b4..d444ff96 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -22,8 +22,8 @@ Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknow with no time derivative of its own, such as `0 ~ Dxx(v) + f`. - `codegen = :mtk` and `dirichlet = :eliminate` are reserved for later milestones and raise; remaining keywords are passed to the `DAEProblem`, where a keyword given at the - `DAEProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` - are set by the discretization and rejected. + `DAEProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate`, `name` and + `parameters` are set by the discretization and rejected. Pieces come from `boundarypiece.(Ω, names)`; on an analytic DomainSets box write `boundarypiece.(Ref(rect), names)`, since DomainSets types do not broadcast as scalars. @@ -37,7 +37,9 @@ Fields are numbered in one order throughout (`DofHandler` blocks, array unknowns through `PDEBase.StrongForm.pair_equations`. Parameters are substituted by the values given in the `PDESystem` when the operators are -assembled, so `remake` with new parameter values does not reassemble them. +assembled, and are parameters of the problem at those values. The operators are not +reassembled for new values: after `remake(prob; p = [k => 3.0])` the solve throws an +`ArgumentError` naming `k`; build a new problem with `DAEProblem(pdesys, disc)` instead. """ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization domain::PDEBase.MeshDomain @@ -53,7 +55,7 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization end # Keywords of `numeric_dae_problem` that the front end sets itself. -const _RESERVED_KWARGS = (:iv, :unknowns, :du0, :coordinate, :name) +const _RESERVED_KWARGS = (:iv, :unknowns, :du0, :coordinate, :name, :parameters) function _check_reserved(kwargs) for k in keys(kwargs) diff --git a/src/frontend.jl b/src/frontend.jl index 6c493082..4cb3ecf1 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -130,10 +130,8 @@ function _paired(an, eqs, ctx, disc) ) end -function _check_linear(wf) +function _check_terms(wf) for term in vcat(wf.volume, wf.facet) - term.kind === :nonlinear && - throw(ArgumentError("nonlinear terms land in M3: equation $(term.eq) has the nonlinear term $(term.integrand)")) term.kind in (:mass, :bilinear) && term.timedep && throw( ArgumentError("time-dependent coefficients in the mass or stiffness operator land in M3: equation $(term.eq) has $(term.integrand)") ) @@ -228,11 +226,13 @@ function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) M, K, F = copy(space.pattern), copy(space.pattern), zeros(n) assemble_linear!(M, K, F, ctx, static, pvals; t = t0) load = isempty(dynamic) ? F : (out, t) -> (assemble_sources!(out, _fresh_values(ctx), dynamic, pvals, t); out .+= F) + nonlinear = any(k -> k.kind === :nonlinear, kernels) ? + FEMNonlinear(NonlinearOperator(_fresh_values(ctx), kernels; ch = space.ch), pvals) : nothing coords = _dof_coordinates(space) values!, values0 = _dirichlet_values(space, dirichlet, coords, pvals, t0) ops = FEMOperators( M, K, load, [name => field_range(space, name) for name in names]; - prescribed = prescribed_dofs(space), dirichlet_values = timedep_dirichlet ? values! : values0 + prescribed = prescribed_dofs(space), dirichlet_values = timedep_dirichlet ? values! : values0, nonlinear ) return ops, coords end @@ -287,7 +287,7 @@ function _lower(pdesys, disc::FEMDiscretization) end end wf = weak_form(an) - _check_linear(wf) + _check_terms(wf) pvals = _parameter_values(sys, ctx) dirichlet = emit_dirichlet(an) t0, t1 = v.intervals[v.time] @@ -301,19 +301,21 @@ function _lower(pdesys, disc::FEMDiscretization) fields = [FieldInfo(dv, name, u, ip) for (dv, name, u, ip) in zip(StrongForm.declared_fields(sys, v), names, unknowns, ips)] pieces = Dict{Any, String}(Γ => String(Γ.name) for Γ in PDEBase.boundarypieces(disc.domain)) md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0) - return (; ops, u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys)) + parameters = [q => v for (q, v) in zip(ctx.params, pvals)] + return (; ops, u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys), parameters) end """ DAEProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) -Discretize `pdesys` with `disc` and return the `DAEProblem` `M du + K u = F(t)` of the -Galerkin operators, with Dirichlet rows `u_d = g_d(t)` as algebraic equations, a sparse -analytic Jacobian and the `FEMMetadata` as its `problem_type`, so `solve` returns a +Discretize `pdesys` with `disc` and return the `DAEProblem` `M du + K u + N(u, t) = F(t)` of +the Galerkin operators, with Dirichlet rows `u_d = g_d(t)` as algebraic equations, a sparse +analytic Jacobian (the nonlinear part `N` from the terms whose coefficients depend on the +state, with its symbolic tangent) and the `FEMMetadata` as its `problem_type`, so `solve` returns a `PDETimeSeriesSolution`. Nothing calls `mtkcompile`; anything this milestone cannot discretize raises. Keywords are passed to the `DAEProblem` after `disc.kwargs`, so a keyword given here wins; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, -`name`) are rejected. +`name`, `parameters`) are rejected. The Dirichlet rows are linear with identity Jacobian rows, so a Newton step with a current Jacobian satisfies them exactly. OrdinaryDiffEq's BDF methods reuse the Jacobian across @@ -326,7 +328,8 @@ function SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscre parts = _lower(pdesys, disc) return numeric_dae_problem( parts.ops, parts.u0, parts.tspan, parts.md; - iv = parts.iv, unknowns = parts.unknowns, name = parts.name, disc.kwargs..., kwargs... + iv = parts.iv, unknowns = parts.unknowns, name = parts.name, parameters = parts.parameters, + disc.kwargs..., kwargs... ) end diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index ef8bf2d2..38d0ba4b 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -85,9 +85,63 @@ fem_load(op::FEMLoad, rows::UnitRange{Int}, t) = load!(zeros(op.n), op, t)[rows] end """ - FEMOperators(M, K, load, fields; prescribed = Int[], dirichlet_values = 0.0) + FEMNonlinear(op, p) -Assembled operators of the semi-discrete system `M du + K u = F(p, t)`, with Dirichlet +Opaque wrapper for the nonlinear part `N(u, t)` of `M du + K u + N(u, t) = F(t)`, used as a +non-tunable `System` parameter like [`FEMOp`](@ref): `op` is a [`NonlinearOperator`](@ref) +and `p` the parameter values its kernels are evaluated with. [`FEMOperators`](@ref) marks the +prescribed dofs, whose rows of `N` and of its Jacobian are then zero. `op` is untyped so that +the parameter has one concrete type; each call dispatches on it once. The operator's buffers +are shared by every problem holding this wrapper (remakes, ensembles), so those problems must +not be solved concurrently. +""" +struct FEMNonlinear + op::Any + p::Vector{Float64} + prescribed::BitVector +end +FEMNonlinear(op, p) = FEMNonlinear(op, collect(Float64, p), falses(0)) +Base.show(io::IO, ::FEMNonlinear) = print(io, "FEMNonlinear") + +function nonlinear_residual!(r, N::FEMNonlinear, u, t) + residual!(r, N.op, u, N.p, t) + r[N.prescribed] .= 0 + return r +end + +function nonlinear_jacobian!(N::FEMNonlinear, u, t) + J = jacobian!(N.op.J, N.op, u, N.p, t) + rows = rowvals(J) + for k in eachindex(rows) + N.prescribed[rows[k]] && (nonzeros(J)[k] = 0) + end + return J +end + +# `fem_nonlinear(op, rows, t, x)` is rows `rows` of `N(x, t)`, with `x` the whole state built from the +# field arrays by `fem_cat`. A registered function gets a method for every symbolic/numeric combination +# of its arguments, so it takes the state as one array rather than one argument per field (which made +# about 150·5ⁿ⁻¹ methods for n fields); `fem_cat` keeps the fields whole arrays instead of the scalars +# that `vcat` of symbolic arrays gives. +fem_cat(a::AbstractVector, b::AbstractVector) = vcat(a, b) +@register_array_symbolic fem_cat(a::AbstractVector, b::AbstractVector) begin + size = (length(a) + length(b),) + eltype = promote_type(eltype(a), eltype(b)) + ndims = 1 +end + +fem_nonlinear(op::FEMNonlinear, rows::UnitRange{Int}, t, x::AbstractVector) = + nonlinear_residual!(zeros(promote_type(Float64, eltype(x)), length(x)), op, x, t)[rows] +@register_array_symbolic fem_nonlinear(op::FEMNonlinear, rows::UnitRange{Int}, t, x::AbstractVector) begin + size = (length(rows),) + eltype = Float64 + ndims = 1 +end + +""" + FEMOperators(M, K, load, fields; prescribed = Int[], dirichlet_values = 0.0, nonlinear = nothing) + +Assembled operators of the semi-discrete system `M du + K u + N(u, t) = F(p, t)`, with Dirichlet conditions applied by algebraic row replacement: for each prescribed dof `d`, row `d` of `M` is zeroed, row `d` of `K` becomes `e_d` and `F[d] = g_d(t)`. `M` and `K` are copied, not mutated, and must share one sparsity pattern (for example from `Ferrite.allocate_matrix(dh, ch)`) @@ -97,6 +151,9 @@ that contains the diagonal entry of every prescribed dof. not see the parameters; parameter-dependent operators are reassembled instead (spec §8.3). - `fields`: `name => range` pairs in state order; the ranges must tile `1:size(M, 1)`. - `dirichlet_values`: a number, a vector over `prescribed`, or `(out, t) -> out`. + - `nonlinear`: `nothing`, or a [`FEMNonlinear`](@ref) whose Jacobian has the sparsity + pattern of `M` and `K`. Its rows at prescribed dofs are dropped, so the Dirichlet rows + stay `u_d = g_d(t)`. The fields `M`, `K`, `load`, `fields`, `prescribed`, `differential_vars` and `jac_prototype` are read by [`numeric_dae_problem`](@ref). `differential_vars` is `false` on prescribed dofs @@ -110,11 +167,12 @@ struct FEMOperators prescribed::Vector{Int} differential_vars::BitVector jac_prototype::SparseMatrixCSC{Float64, Int} + nonlinear::Union{Nothing, FEMNonlinear} end function FEMOperators( M::SparseMatrixCSC, K::SparseMatrixCSC, load, fields; - prescribed = Int[], dirichlet_values = 0.0 + prescribed = Int[], dirichlet_values = 0.0, nonlinear = nothing ) n = size(K, 1) size(M) == size(K) == (n, n) || throw(DimensionMismatch("M and K must be square of the same size; got $(size(M)) and $(size(K))")) @@ -135,13 +193,24 @@ function FEMOperators( iszero(nonzeros(M)[k]) || (differential_vars[i] = true) end F = FEMLoad(load, prescribed, dirichlet_values, n) - return FEMOperators(M, K, F, fields, prescribed, differential_vars, copy(K)) + if nonlinear !== nothing + J = nonlinear.op.J + J.colptr == K.colptr && J.rowval == K.rowval || + throw(ArgumentError("the nonlinear operator's Jacobian must have the sparsity pattern of M and K, e.g. NonlinearOperator(ctx, kernels; ch) with the ConstraintHandler of allocate_matrix(dh, ch)")) + nonlinear = FEMNonlinear(nonlinear.op, nonlinear.p, isprescribed_mask(n, prescribed)) + end + return FEMOperators(M, K, F, fields, prescribed, differential_vars, copy(K), nonlinear) +end + +function isprescribed_mask(n, prescribed) + mask = falses(n) + mask[prescribed] .= true + return mask end # One pass over the stored entries; the Jacobian then needs no row zeroing. function replace_dirichlet_rows!(M, K, prescribed) - isprescribed = falses(size(K, 1)) - isprescribed[prescribed] .= true + isprescribed = isprescribed_mask(size(K, 1), prescribed) rows = rowvals(K) for j in axes(K, 2), k in nzrange(K, j) i = rows[k] @@ -176,29 +245,36 @@ end fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothing, name = :fem) The completed array-residual `System`: one array unknown per field, the operators as opaque -non-tunable parameters `Mop`, `Kop`, `Fop`, and one block equation per field, -`F_i(p, t) ~ Σ_j M_ij D(u_j) + K_ij u_j`. `unknowns` defaults to `name(iv)[1:n]` per field. +non-tunable parameters `Mop`, `Kop`, `Fop` (and `Nop` for `ops.nonlinear`), and one block +equation per field, `F_i(p, t) ~ Σ_j M_ij D(u_j) + K_ij u_j (+ N_i(u, t))`. `parameters` are `symbol => value` pairs +added as parameters with those values, which the operators were assembled with. `unknowns` defaults to `name(iv)[1:n]` per field. Returns `(sys, unknowns, parameter_map)`. """ -function fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothing, name = :fem) +function fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothing, name = :fem, parameters = ()) D = Differential(iv) us = unknowns === nothing ? [only(@variables $field(iv)[1:length(r)]) for (field, r) in ops.fields] : collect(unknowns) @parameters Mop::FEMOp [tunable = false] Kop::FEMOp [tunable = false] Fop::FEMLoad [tunable = false] ranges = last.(ops.fields) - eqs = [ - fem_load(Fop, ri, iv) ~ sum( - fem_apply(Mop, ri, rj, D(uj)) + fem_apply(Kop, ri, rj, uj) - for (rj, uj) in zip(ranges, us) - ) - for ri in ranges - ] + linear(ri) = sum(fem_apply(Mop, ri, rj, D(uj)) + fem_apply(Kop, ri, rj, uj) for (rj, uj) in zip(ranges, us)) + ps = Any[Mop, Kop, Fop] + append!(ps, first.(parameters)) + if ops.nonlinear === nothing + eqs = [fem_load(Fop, ri, iv) ~ linear(ri) for ri in ranges] + else + @parameters Nop::FEMNonlinear [tunable = false] + push!(ps, Nop) + state = foldl(fem_cat, us) + eqs = [fem_load(Fop, ri, iv) ~ linear(ri) + fem_nonlinear(Nop, ri, iv, state) for ri in ranges] + end md = metadata === nothing ? [] : [ProblemTypeCtx => metadata] - sys = complete(System(eqs, iv, us, [Mop, Kop, Fop]; name, metadata = md)) + sys = complete(System(eqs, iv, us, ps; name, metadata = md)) for (u, r) in zip(us, ranges) variable_index(sys, u) == r || error("System reordered the unknowns: $u is at $(variable_index(sys, u)), expected $r") end pmap = Dict{Any, Any}(Mop => FEMOp(ops.M), Kop => FEMOp(ops.K), Fop => ops.load) + ops.nonlinear === nothing || (pmap[last(ps)] = ops.nonlinear) + foreach(((q, v),) -> pmap[q] = v, parameters) return sys, us, pmap end @@ -206,7 +282,7 @@ end consistent_du0(ops::FEMOperators, u0, t0) `du0` with `du_d = g'(t0)` on prescribed dofs, zero on the other algebraic rows, and -`M_ff du_f = (F(t0) - K u0 - M_fd g'(t0))_f` on the differential rows. Throws an +`M_ff du_f = (F(t0) - K u0 - N(u0, t0) - M_fd g'(t0))_f` on the differential rows. Throws an `ArgumentError` when a non-prescribed algebraic variable has a nonzero column in `M`: its `du` is then not zero, cannot be found without index reduction, and must be passed as `du0`. """ @@ -222,6 +298,7 @@ function consistent_du0(ops::FEMOperators, u0, t0) du0[ops.prescribed] = dirichlet_rates(ops.load, t0) any(dd) || return du0 rhs = load!(zeros(length(u0)), ops.load, t0) - ops.K * u0 - ops.M * du0 + ops.nonlinear === nothing || (rhs .-= nonlinear_residual!(zeros(length(u0)), ops.nonlinear, u0, t0)) du0[dd] = ops.M[dd, dd] \ rhs[dd] return du0 end @@ -232,6 +309,26 @@ function check_pattern(J, A, name) return nothing end +# The operators hold the parameter values they were assembled with; a `remake` with other values would +# otherwise be solved silently with the old ones. +function assembled_parameter_check(sys, parameters) + isempty(parameters) && return Returns(nothing) + syms = [q for (q, _) in parameters] + assembled = [v for (_, v) in parameters] + get = getp(sys, syms) + return function (p) + current = get(p) + for (q, a, c) in zip(syms, assembled, current) + isequal(a, c) || throw( + ArgumentError( + "parameter $q was $a when the operators were assembled but is $c in this problem; operators are not reassembled for new parameter values, so build a new problem with DAEProblem(pdesys, disc)" + ) + ) + end + return nothing + end +end + default_initializealg() = BrownFullBasicInit(nlsolve = NewtonRaphson(autodiff = AutoForwardDiff())) """ @@ -240,11 +337,13 @@ default_initializealg() = BrownFullBasicInit(nlsolve = NewtonRaphson(autodiff = initializealg = BrownFullBasicInit(nlsolve = NewtonRaphson(autodiff = AutoForwardDiff())), coordinate = nothing, name = :fem, kwargs...) -Build the `DAEProblem` for `M du + K u - F(p, t) = 0` with a numeric residual, an analytic -sparse Jacobian `K + γ M` and the completed `System` of [`fem_system`](@ref) attached for +Build the `DAEProblem` for `M du + K u + N(u, t) - F(p, t) = 0` with a numeric residual, an +analytic sparse Jacobian `K + γ M + ∂N/∂u` and the completed `System` of [`fem_system`](@ref) attached for symbolic indexing. No initialization problem is built and nothing calls `mtkcompile`. -`metadata` becomes the problem's `problem_type`; a `SciMLBase.AbstractDiscretizationMetadata` +`parameters` (`symbol => value` pairs) become parameters of the `System` at the values the +operators were assembled with; the residual and Jacobian throw an `ArgumentError` naming the +parameter if a `remake` has changed one. `metadata` becomes the problem's `problem_type`; a `SciMLBase.AbstractDiscretizationMetadata` first gets the `System` through `PDEBase.add_metadata!`. `du0` defaults to the consistent one of [`consistent_du0`](@ref). `coordinate(dof)` is used in the error for a non-finite `u0`. Remaining keywords are passed to `DAEProblem`. @@ -252,26 +351,40 @@ Remaining keywords are passed to `DAEProblem`. function numeric_dae_problem( ops::FEMOperators, u0, tspan, metadata = nothing; iv = ModelingToolkit.t_nounits, unknowns = nothing, du0 = nothing, - initializealg = default_initializealg(), coordinate = nothing, name = :fem, kwargs... + initializealg = default_initializealg(), coordinate = nothing, name = :fem, parameters = (), kwargs... ) length(u0) == size(ops.K, 1) || throw(DimensionMismatch("u0 has length $(length(u0)), the operators have $(size(ops.K, 1)) rows")) check_finite_initial_condition(u0, ops.fields; coordinate) - sys, _, pmap = fem_system(ops, iv; unknowns, metadata, name) + sys, _, pmap = fem_system(ops, iv; unknowns, metadata, name, parameters) p = MTKParameters(sys, pmap) + check_assembled = assembled_parameter_check(sys, parameters) getM, getK, getF = getp(sys, sys.Mop), getp(sys, sys.Kop), getp(sys, sys.Fop) + getN = ops.nonlinear === nothing ? Returns(nothing) : getp(sys, sys.Nop) + nbuf = zeros(length(u0)) function residual!(res, du, u, p, t) + check_assembled(p) load!(res, getF(p), t) res .= .-res mul!(res, getM(p).A, du, true, true) mul!(res, getK(p).A, u, true, true) + N = getN(p) + N === nothing || (res .+= nonlinear_residual!(nbuf, N, u, t)) return nothing end - # The Dirichlet rows of K + γM are already e_d, so the stored values are copied as they are. + # The Dirichlet rows of K + γM are already e_d and those of N's Jacobian zero, so the + # stored values are added as they are. function jac!(J, du, u, p, γ, t) + check_assembled(p) Kp, Mp = getK(p).A, getM(p).A check_pattern(J, Kp, "Kop") check_pattern(J, Mp, "Mop") nonzeros(J) .= nonzeros(Kp) .+ γ .* nonzeros(Mp) + N = getN(p) + if N !== nothing + JN = nonlinear_jacobian!(N, u, t) + check_pattern(J, JN, "Nop") + nonzeros(J) .+= nonzeros(JN) + end return nothing end u0 = collect(u0) diff --git a/test/DAE/numeric_dae.jl b/test/DAE/numeric_dae.jl index 98b20403..d35f8f7e 100644 --- a/test/DAE/numeric_dae.jl +++ b/test/DAE/numeric_dae.jl @@ -163,6 +163,11 @@ heat_operators(fe; kw...) = FEMOperators(fe.M, fe.K, fe.F, [:u => 1:length(fe.F) Kp = SparseMatrixCSC(2, 2, [1, 3, 5], [1, 2, 1, 2], [0.0, 0.0, 0.0, 1.0]) opsp = FEMOperators(pat, Kp, (out, t) -> (out .= (0.0, t); out), [:u => 1:2]) @test_throws "pass du0 explicitly" numeric_dae_problem(opsp, zeros(2), (0.0, 1.0)) + # The nonlinear part must share the pattern of M and K; checking it needs no working operator. + FN = FiniteElementMethod.FEMNonlinear + @test_throws ArgumentError( + "the nonlinear operator's Jacobian must have the sparsity pattern of M and K, e.g. NonlinearOperator(ctx, kernels; ch) with the ConstraintHandler of allocate_matrix(dh, ch)" + ) FEMOperators(Md, copy(Md), zeros(3), [:u => 1:3]; nonlinear = FN((; J = Kt), Float64[])) probp = numeric_dae_problem(opsp, zeros(2), (0.0, 1.0); du0 = [-1.0, 1.0]) solp = solve(probp, DFBDF(); tol...) @test solp.u[end] ≈ [-1.0, 1.0] atol = 1.0e-8 diff --git a/test/Frontend/nonlinear.jl b/test/Frontend/nonlinear.jl new file mode 100644 index 00000000..430f603e --- /dev/null +++ b/test/Frontend/nonlinear.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "nonlinear.jl")) +else + @testset "nonlinear (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/end_to_end.jl b/test/shared/frontend_tests/end_to_end.jl index 7cfaea55..c36213da 100644 --- a/test/shared/frontend_tests/end_to_end.jl +++ b/test/shared/frontend_tests/end_to_end.jl @@ -62,7 +62,7 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test sol.t == 0:0.25:1 @test sol.disc_data isa FEMMetadata @test discretize(pdesys, FEMDiscretization(Ω, t; saveat = 0.25); saveat = 0.5).kwargs[:saveat] == 0.5 - reserved = "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name" + reserved = "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name, parameters" @test_throws ArgumentError(reserved) FEMDiscretization(Ω, t; name = :other) @test_throws ArgumentError(replace(reserved, "`name`" => "`du0`")) discretize(pdesys, FEMDiscretization(Ω, t); du0 = zeros(3)) @test sprint(show, sol.disc_data) == sprint(show, prob.problem_type) == "FEMMetadata(fields = [u], ndofs = 9, hasTime = true)" diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index f50b6b39..5229895c 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -97,12 +97,8 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] ) end - @testset "nonlinear and time-dependent operators" begin + @testset "time-dependent operators" begin Ω = box() - nl = Dt(u(t, x, y)) ~ Dx((1 + u(t, x, y)^2) * Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) - @test_throws ArgumentError("nonlinear terms land in M3: equation 1 has the nonlinear term G₁*(U₁^2)*W₁") lower( - [nl], [dirichlet(Ω); ic], Ω - ) td = Dt(u(t, x, y)) ~ Dx((1 + t) * Dx(u(t, x, y))) + Dy((1 + t) * Dy(u(t, x, y))) @test_throws ArgumentError( "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has " * diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl new file mode 100644 index 00000000..4a94d8ed --- /dev/null +++ b/test/shared/frontend_tests/nonlinear.jl @@ -0,0 +1,157 @@ +# Nonlinear terms through the front end (spec §8.1): PDESystem -> DAEProblem -> solve against manufactured +# solutions, the analytic Jacobian against finite differences, the Dirichlet rows, the remake policy and the +# nonlinear classes that stay rejected. +# +# Every manufactured solution is u* = (1 + x + 2y)(1 + t), which lies in the P1 space. Each source is written so +# that it cancels the nonlinear term pointwise at u*, so u* solves the discrete equations exactly whatever the +# quadrature, and the nodal error is at the level of the time-integration tolerance. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid +using Ferrite: Triangle +using LinearAlgebra: I, norm +using SciMLBase: remake + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@parameters k +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +const U = u(t, x, y) +const tol = 1.0e-8 + +uexact(t_, x_, y_) = (1 + x_ + 2y_) * (1 + t_) +const ustar = (1 + x + 2y) * (1 + t) +const ic = u(0, x, y) ~ 1 + x + 2y +square() = MeshDomain(rectangle_grid(Triangle, (4, 4))) +sides(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +dirichlet(Ω, Γs = sides(Ω)) = [u(t, Γ) ~ ustar for Γ in Γs] + +function pdesystem(eqs, bcs, Ω; ps = []) + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], ps) + return pdesys +end + +# Central differences of the DAE residual in u, plus γ times those in du. +function fd_jacobian(prob, du, u0, γ, t0; ε = 1.0e-6) + n = length(u0) + J = zeros(n, n) + r₊, r₋ = zeros(n), zeros(n) + for j in 1:n + e = zeros(n) + e[j] = ε + prob.f(r₊, du, u0 + e, prob.p, t0) + prob.f(r₋, du, u0 - e, prob.p, t0) + J[:, j] .= (r₊ - r₋) / 2ε + prob.f(r₊, du + γ * e, u0, prob.p, t0) + prob.f(r₋, du - γ * e, u0, prob.p, t0) + J[:, j] .+= (r₊ - r₋) / 2ε + end + return J +end + +@testset verbose = true "nonlinear terms" begin + @testset "nonlinear diffusion −∇·((1 + u²)∇u)" begin + # ∇·((1 + u*²)∇u*) = 2u*|∇u*|² = 10u*(1 + t)²; the source is time dependent. + Ω = square() + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + (1 + x + 2y) - 10 * ustar * (1 + t)^2 + sol, prob = fem_solve([eq], [dirichlet(Ω); ic], Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + @test any(p -> nameof(p) === :Nop, ModelingToolkit.parameters(prob.f.sys)) + end + + @testset "nonlinear reaction −u²" begin + Ω = square() + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) - U^2 + (1 + x + 2y) + ustar^2 + sol, _ = fem_solve([eq], [dirichlet(Ω); ic], Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "Burgers-type convection u(∂ₓu + ∂ᵧu)" begin + # u*(∂ₓu* + ∂ᵧu*) = 3u*(1 + t). + Ω = square() + eq = Dt(U) + U * Dx(U) + U * Dy(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) + 3 * ustar * (1 + t) + sol, _ = fem_solve([eq], [dirichlet(Ω); ic], Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "nonlinear natural condition ∂ₙu = −u² + h" begin + # On the right side x = 1, ∂ₙu* = ∂ₓu* = 1 + t, so h = (1 + t) + u*². + Ω = square() + Γl, Γr, Γb, Γt = sides(Ω) + Dn = NormalDerivative(Γr) + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) + bcs = [dirichlet(Ω, (Γl, Γb, Γt)); Dn(u(t, Γr)) ~ -u(t, Γr)^2 + (1 + t) + ustar^2; ic] + sol, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "Jacobian against finite differences, Dirichlet rows" begin + Ω = square() + eq = Dt(U) + U * Dx(U) ~ Dx((1 + U^2) * Dx(U)) + Dy(Dy(U)) - U^2 + (1 + x + 2y) + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + n = length(prob.u0) + rng_u = [0.3 + 0.1 * sin(3i) for i in 1:n] + rng_du = [0.2 * cos(5i) for i in 1:n] + γ, t0 = 0.7, 0.4 + J = copy(prob.f.jac_prototype) + prob.f.jac(J, rng_du, rng_u, prob.p, γ, t0) + Jfd = fd_jacobian(prob, rng_du, rng_u, γ, t0) + @test norm(Matrix(J) - Jfd, Inf) <= 1.0e-7 * norm(Jfd, Inf) + # Prescribed rows are u_d − g_d(t): identity rows of the Jacobian, unaffected by N(u). + space = prob.problem_type.space + dofs = space.ch.prescribed_dofs + @test Matrix(J)[dofs, :] == Matrix(1.0 * I(n))[dofs, :] + r = zeros(n) + prob.f(r, rng_du, rng_u, prob.p, t0) + g = FiniteElementMethod.dirichlet_values!(zeros(length(dofs)), space, t0) + @test r[dofs] ≈ rng_u[dofs] - g atol = 1.0e-14 + end + + @testset "a parameter changed by remake is rejected, not ignored" begin + # The operators, the nonlinear one included, hold the values they were assembled with (spec §8.3). + Ω = square() + eq = Dt(U) ~ Dx((1 + k * U^2) * Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) - 2k * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω; ps = [k => 1.0]), FEMDiscretization(Ω, t)) + sol = solve(prob, EXACT_ROWS; abstol = 1.0e-10, reltol = 1.0e-10) + @test nodal_error(sol, U, uexact) <= tol + @test SciMLBase.successful_retcode(solve(remake(prob; p = [k => 1.0]), EXACT_ROWS)) + msg = "parameter k was 1.0 when the operators were assembled but is 3.0 in this problem; operators are not reassembled for new parameter values, so build a new problem with DAEProblem(pdesys, disc)" + @test_throws ArgumentError(msg) solve(remake(prob; p = [k => 3.0]), EXACT_ROWS) + end +end + +@testset verbose = true "still-rejected nonlinear classes" begin + Ω = square() + lower(eqs, bcs = [dirichlet(Ω); ic]) = DAEProblem(pdesystem(eqs, bcs, Ω), FEMDiscretization(Ω, t)) + # Raised by PDEBase's strong-form analysis with the messages of spec Appendix A. + @test_throws ErrorException("state-dependent mass in Differential(t, 1)(u(t, x, y))*(u(t, x, y)^2) needs residual-form DAE") lower( + [(1 + U^2) * Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U))] + ) + @test_throws ErrorException("time derivative in Differential(t, 1)(u(t, x, y))^2 is not ∂ₜu × coefficient") lower( + [Dt(U)^2 ~ Dx(Dx(U)) + Dy(Dy(U))] + ) + @test_throws ErrorException( + "time derivative in -Differential(x, 1)(Differential(t, 1)(Differential(x, 1)(u(t, x, y)))) is not ∂ₜu × coefficient" + ) lower([Dt(U) ~ Dx(Dt(Dx(U))) + Dy(Dy(U))]) + @test_throws ErrorException("second derivative not in a divergence-compatible position: -sin(Differential(x, 2)(u(t, x, y)))") lower( + [Dt(U) ~ sin(Dx(Dx(U))) + Dy(Dy(U))] + ) + # The printed order of a product's factors differs between Julia versions, so these two match the + # message up to the term. + @test_throws "second derivative not in a divergence-compatible position: -" lower([Dt(U) ~ Dx(Dx(U)) * Dy(Dy(U))]) + @test_throws "second derivative not in a divergence-compatible position: -" lower([Dt(U) ~ Dx(U) * Dx(Dx(U)) + Dy(Dy(U))]) + Γl = first(sides(Ω)) + @test_throws ErrorException("Dirichlet data must be linear in one field: u(t, Γ_left)^2 ~ 1 on Γ_left") lower( + [Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U))], [[u(t, Γl)^2 ~ 1]; dirichlet(Ω, sides(Ω)[2:end]); ic] + ) + # The front end's own: a time-dependent coefficient in a linear operator would need reassembly. + @test_throws ArgumentError( + "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has G₁*W₁ + G₁*T*W₁" + ) lower([Dt(U) ~ Dx((1 + t) * Dx(U))]) +end From 76a07fe4e4a604478bf7e57e56efe8d9472b8cb4 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 09:55:11 +0000 Subject: [PATCH 11/62] Add the DFG cylinder mesh, force functional and Ferrite reference solver MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The DFG/Schäfer–Turek channel generator (all-quadrilateral Gmsh mesh with a refinement parameter, optional quadratic geometry), the weighted-residual drag and lift functional and a hand-written Ferrite Newton solver of the steady 2D-1 case, which is the oracle the PDESystem example is compared with on the same mesh. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- examples/dfg_cylinder/forces.jl | 70 +++++++++++++++++++ examples/dfg_cylinder/mesh.jl | 73 ++++++++++++++++++++ examples/dfg_cylinder/reference.jl | 104 +++++++++++++++++++++++++++++ 3 files changed, 247 insertions(+) create mode 100644 examples/dfg_cylinder/forces.jl create mode 100644 examples/dfg_cylinder/mesh.jl create mode 100644 examples/dfg_cylinder/reference.jl diff --git a/examples/dfg_cylinder/forces.jl b/examples/dfg_cylinder/forces.jl new file mode 100644 index 00000000..3290a90b --- /dev/null +++ b/examples/dfg_cylinder/forces.jl @@ -0,0 +1,70 @@ +using Ferrite: Ferrite +using LinearAlgebra: dot + +""" + dfg_coefficients(dh, x; ν, Umean, D = 0.1, dxdt = nothing, fields = (:u, :v, :p)) + +Drag and lift coefficients `(cD, cL)` of the cylinder (facet set `"cylinder"`) and the pressure difference +`Δp = p(0.15, 0.2) − p(0.25, 0.2)` between its front and back, from the dof vector `x` of the `DofHandler` `dh` +with velocity components `fields[1:2]` and pressure `fields[3]`. + +The forces are the weighted residuals of the momentum equations (John 2004, Braack & Richter 2006): +with `w` the finite-element function equal to `e_k` on the cylinder and zero at every other node, + + F_k = −∫_Ω (∂ₜu·w + ν ∇u : ∇w + (u·∇)u·w − p ∇·w) dx, + +which equals the surface integral `∮ (ν ∂ₙu − p n)·e_k` over the cylinder for the exact solution but converges +at the order of the energy error squared, where the surface integral of the discrete gradient converges at the +order of the energy error. `dxdt` is the time derivative of `x` (omit it for a steady state). The coefficients are +`2F/(Umean² D)` with unit density. +""" +function dfg_coefficients(dh, x; ν, Umean, D = 0.1, dxdt = nothing, fields = (:u, :v, :p)) + fu, fv, fp = fields + grid = dh.grid + sdh = only(dh.subdofhandlers) + ip_u = Ferrite.getfieldinterpolation(sdh, fu) + ip_p = Ferrite.getfieldinterpolation(sdh, fp) + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(grid)) + shape = Ferrite.getrefshape(ip_u) + qr = Ferrite.QuadratureRule{shape}(2 * Ferrite.getorder(ip_u) + 1) + cv_u, cv_p = Ferrite.CellValues(qr, ip_u, ip_geo), Ferrite.CellValues(qr, ip_p, ip_geo) + + # The weight is the nodal interpolant of 1 on the cylinder: the sum of its velocity basis functions. + w = zeros(Ferrite.ndofs(dh)) + ch = Ferrite.ConstraintHandler(dh) + Ferrite.add!(ch, Ferrite.Dirichlet(fu, Ferrite.getfacetset(grid, "cylinder"), Returns(1.0))) + Ferrite.close!(ch) + w[ch.prescribed_dofs] .= 1 + + ru, rv = Ferrite.dof_range(dh, fu), Ferrite.dof_range(dh, fv) + rp = Ferrite.dof_range(dh, fp) + F = zeros(2) + coords = Ferrite.getcoordinates(grid, 1) + for cell in 1:Ferrite.getncells(grid) + dofs = Ferrite.celldofs(dh, cell) + we = w[dofs[ru]] + any(!iszero, we) || continue + Ferrite.getcoordinates!(coords, grid, cell) + Ferrite.reinit!(cv_u, coords) + Ferrite.reinit!(cv_p, coords) + ue, ve, pe = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] + for q in 1:Ferrite.getnquadpoints(cv_u) + dΩ = Ferrite.getdetJdV(cv_u, q) + U = (Ferrite.function_value(cv_u, q, ue), Ferrite.function_value(cv_u, q, ve)) + ∇U = (Ferrite.function_gradient(cv_u, q, ue), Ferrite.function_gradient(cv_u, q, ve)) + ∂U = dxdt === nothing ? (0.0, 0.0) : + (Ferrite.function_value(cv_u, q, dxdt[dofs[ru]]), Ferrite.function_value(cv_u, q, dxdt[dofs[rv]])) + p = Ferrite.function_value(cv_p, q, pe) + W = Ferrite.function_value(cv_u, q, we) + ∇W = Ferrite.function_gradient(cv_u, q, we) + for k in 1:2 + convection = U[1] * ∇U[k][1] + U[2] * ∇U[k][2] + F[k] -= ((∂U[k] + convection) * W + ν * dot(∇U[k], ∇W) - p * ∇W[k]) * dΩ + end + end + end + scale = 2 / (Umean^2 * D) + ph = Ferrite.PointEvalHandler(grid, [Ferrite.Vec(0.15, 0.2), Ferrite.Vec(0.25, 0.2)]) + pfront, pback = Ferrite.evaluate_at_points(ph, dh, x, fp) + return (cD = scale * F[1], cL = scale * F[2], Δp = pfront - pback) +end diff --git a/examples/dfg_cylinder/mesh.jl b/examples/dfg_cylinder/mesh.jl new file mode 100644 index 00000000..86f8b82f --- /dev/null +++ b/examples/dfg_cylinder/mesh.jl @@ -0,0 +1,73 @@ +using Ferrite: Ferrite +using FerriteGmsh: FerriteGmsh +using Gmsh: Gmsh, gmsh + +""" + dfg_channel_grid(; h = 0.04, hc = h / 6, length = 2.2, order = 2) + +Quadrilateral mesh of the DFG/Schäfer–Turek 2D channel `[0, length] × [0, 0.41]` minus the cylinder of +radius 0.05 centred at `(0.2, 0.2)`, built with the Gmsh API and converted with `FerriteGmsh.togrid`. +The element size is `hc` on the cylinder, grows linearly to `h` at distance 0.25 from it and is `h` +elsewhere; halving both is one uniform refinement. `order = 2` gives `QuadraticQuadrilateral` cells whose +edge midpoints lie on the cylinder, so the cylinder is curved for an isoparametric Q2 field; `order = 1` +gives straight-edged `Quadrilateral`s. `length = 1.1` is the shortened channel of Ferrite's +`ns_vs_diffeq.jl` tutorial. + +Facet sets: `"inlet"` (`x = 0`), `"outlet"` (`x = length`), `"walls"` (`y = 0` and `y = 0.41`) and +`"cylinder"`. +""" +function dfg_channel_grid(; h = 0.04, hc = h / 6, length = 2.2, order = 2) + Gmsh.initialize() + try + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("dfg") + rect = gmsh.model.occ.addRectangle(0, 0, 0, length, 0.41) + disk = gmsh.model.occ.addDisk(0.2, 0.2, 0, 0.05, 0.05) + gmsh.model.occ.cut([(2, rect)], [(2, disk)]) + gmsh.model.occ.synchronize() + surfaces = gmsh.model.getEntities(2) + curves = [tag for (_, tag) in gmsh.model.getEntities(1)] + # Classify the boundary curves by their bounding boxes rather than by OCC's tag numbering. + on(tag, test) = test(gmsh.model.getBoundingBox(1, tag)...) + tol = 1.0e-6 + inlet = filter(c -> on(c, (x0, y0, z0, x1, y1, z1) -> x1 < tol), curves) + outlet = filter(c -> on(c, (x0, y0, z0, x1, y1, z1) -> x0 > length - tol), curves) + walls = filter(c -> on(c, (x0, y0, z0, x1, y1, z1) -> y1 < tol || y0 > 0.41 - tol), curves) + cylinder = setdiff(curves, inlet, outlet, walls) + gmsh.model.addPhysicalGroup(1, inlet, -1, "inlet") + gmsh.model.addPhysicalGroup(1, outlet, -1, "outlet") + gmsh.model.addPhysicalGroup(1, walls, -1, "walls") + gmsh.model.addPhysicalGroup(1, cylinder, -1, "cylinder") + gmsh.model.addPhysicalGroup(2, [tag for (_, tag) in surfaces], -1, "fluid") + + distance = gmsh.model.mesh.field.add("Distance") + gmsh.model.mesh.field.setNumbers(distance, "CurvesList", cylinder) + gmsh.model.mesh.field.setNumber(distance, "Sampling", 200) + threshold = gmsh.model.mesh.field.add("Threshold") + gmsh.model.mesh.field.setNumber(threshold, "InField", distance) + # Subdivision halves every edge, so the triangulation is made at twice the final size. + gmsh.model.mesh.field.setNumber(threshold, "SizeMin", 2hc) + gmsh.model.mesh.field.setNumber(threshold, "SizeMax", 2h) + gmsh.model.mesh.field.setNumber(threshold, "DistMin", 0.0) + gmsh.model.mesh.field.setNumber(threshold, "DistMax", 0.25) + gmsh.model.mesh.field.setAsBackgroundMesh(threshold) + gmsh.option.setNumber("Mesh.MeshSizeExtendFromBoundary", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromPoints", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 0) + # Frontal-Delaunay for quads and Blossom recombination; the subdivision step splits any triangle + # Blossom leaves into three quadrilaterals, so the mesh is all quadrilaterals at every size. + gmsh.option.setNumber("Mesh.Algorithm", 8) + gmsh.option.setNumber("Mesh.RecombinationAlgorithm", 1) + gmsh.option.setNumber("Mesh.RecombineAll", 1) + gmsh.option.setNumber("Mesh.SubdivisionAlgorithm", 1) + gmsh.model.mesh.generate(2) + gmsh.model.mesh.setOrder(order) + grid = FerriteGmsh.togrid() + celltype = Ferrite.getcelltype(grid) + expected = order == 2 ? Ferrite.QuadraticQuadrilateral : Ferrite.Quadrilateral + celltype === expected || error("Gmsh left non-quadrilateral cells; the cell type is $celltype") + return grid + finally + Gmsh.finalize() + end +end diff --git a/examples/dfg_cylinder/reference.jl b/examples/dfg_cylinder/reference.jl new file mode 100644 index 00000000..8e7fd2eb --- /dev/null +++ b/examples/dfg_cylinder/reference.jl @@ -0,0 +1,104 @@ +using Ferrite: Ferrite +using LinearAlgebra: dot, norm +using SparseArrays: SparseMatrixCSC + +""" + dfg_reference_steady(grid; ν = 1.0e-3, Umax = 0.3, tol = 1.0e-10, maxiter = 20) + +Hand-written Ferrite solution of the steady DFG 2D-1 problem on `grid` (from [`dfg_channel_grid`](@ref)): scalar +velocity components `u`, `v` on `Lagrange{RefQuadrilateral, 2}` and pressure `p` on `Lagrange{RefQuadrilateral, 1}`, +parabolic inflow of peak `Umax`, no slip on the walls and the cylinder, and the do-nothing condition +`ν ∂ₙu − p n = 0` at the outlet, solved by Newton's method from zero. Returns `(dh, x, iterations)`. + +This is the oracle the PDESystem path is compared with on the same mesh; it uses no FiniteElementMethod code. +""" +function dfg_reference_steady(grid; ν = 1.0e-3, Umax = 0.3, tol = 1.0e-10, maxiter = 20, pressure = :weak) + shape = Ferrite.RefQuadrilateral + ip_u, ip_p = Ferrite.Lagrange{shape, 2}(), Ferrite.Lagrange{shape, 1}() + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(grid)) + qr = Ferrite.QuadratureRule{shape}(4) + cv_u, cv_p = Ferrite.CellValues(qr, ip_u, ip_geo), Ferrite.CellValues(qr, ip_p, ip_geo) + dh = Ferrite.DofHandler(grid) + Ferrite.add!(dh, :u, ip_u) + Ferrite.add!(dh, :v, ip_u) + Ferrite.add!(dh, :p, ip_p) + Ferrite.close!(dh) + ch = Ferrite.ConstraintHandler(dh) + noslip = union(Ferrite.getfacetset(grid, "walls"), Ferrite.getfacetset(grid, "cylinder")) + inflow = Ferrite.getfacetset(grid, "inlet") + Ferrite.add!(ch, Ferrite.Dirichlet(:u, noslip, Returns(0.0))) + Ferrite.add!(ch, Ferrite.Dirichlet(:v, noslip, Returns(0.0))) + Ferrite.add!(ch, Ferrite.Dirichlet(:u, inflow, x -> 4Umax * x[2] * (0.41 - x[2]) / 0.41^2)) + Ferrite.add!(ch, Ferrite.Dirichlet(:v, inflow, Returns(0.0))) + pressure === :strong && Ferrite.add!(ch, Ferrite.Dirichlet(:p, Ferrite.getfacetset(grid, "outlet"), Returns(0.0))) + Ferrite.close!(ch) + + ru, rv, rp = Ferrite.dof_range(dh, :u), Ferrite.dof_range(dh, :v), Ferrite.dof_range(dh, :p) + nu, np = Ferrite.getnbasefunctions(cv_u), Ferrite.getnbasefunctions(cv_p) + ne = 2nu + np + J = Ferrite.allocate_matrix(dh) + r = zeros(Ferrite.ndofs(dh)) + x = zeros(Ferrite.ndofs(dh)) + Ferrite.apply!(x, ch) + Je, re = zeros(ne, ne), zeros(ne) + iterations = 0 + for it in 1:maxiter + assembler = Ferrite.start_assemble(J, r) + for cell in Ferrite.CellIterator(dh) + Ferrite.reinit!(cv_u, cell) + Ferrite.reinit!(cv_p, cell) + dofs = Ferrite.celldofs(cell) + ue, ve, pe = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] + fill!(Je, 0) + fill!(re, 0) + for q in 1:Ferrite.getnquadpoints(cv_u) + dΩ = Ferrite.getdetJdV(cv_u, q) + U = (Ferrite.function_value(cv_u, q, ue), Ferrite.function_value(cv_u, q, ve)) + ∇U = (Ferrite.function_gradient(cv_u, q, ue), Ferrite.function_gradient(cv_u, q, ve)) + p = Ferrite.function_value(cv_p, q, pe) + ∇p = Ferrite.function_gradient(cv_p, q, pe) + div = ∇U[1][1] + ∇U[2][2] + blocks = (ru, rv) + for i in 1:nu + φ, ∇φ = Ferrite.shape_value(cv_u, q, i), Ferrite.shape_gradient(cv_u, q, i) + for k in 1:2 + a = blocks[k][i] + conv = U[1] * ∇U[k][1] + U[2] * ∇U[k][2] + re[a] += (conv * φ + ν * dot(∇U[k], ∇φ) + (pressure === :strong ? ∇p[k] * φ : -p * ∇φ[k])) * dΩ + for j in 1:nu + ψ, ∇ψ = Ferrite.shape_value(cv_u, q, j), Ferrite.shape_gradient(cv_u, q, j) + # d(conv_k)/d(u_l) along ψ: U·∇ψ (l = k) + ψ ∂_l U_k + for l in 1:2 + b = blocks[l][j] + dconv = (l == k ? U[1] * ∇ψ[1] + U[2] * ∇ψ[2] : 0.0) + ψ * ∇U[k][l] + Je[a, b] += (dconv * φ + (l == k ? ν * dot(∇ψ, ∇φ) : 0.0)) * dΩ + end + end + for j in 1:np + Je[a, rp[j]] += ( + pressure === :strong ? Ferrite.shape_gradient(cv_p, q, j)[k] * φ : + -Ferrite.shape_value(cv_p, q, j) * ∇φ[k] + ) * dΩ + end + end + end + for i in 1:np + ψ = Ferrite.shape_value(cv_p, q, i) + re[rp[i]] += ψ * div * dΩ + for j in 1:nu + ∇φ = Ferrite.shape_gradient(cv_u, q, j) + Je[rp[i], ru[j]] += ψ * ∇φ[1] * dΩ + Je[rp[i], rv[j]] += ψ * ∇φ[2] * dΩ + end + end + end + Ferrite.assemble!(assembler, dofs, Je, re) + end + Ferrite.apply_zero!(J, r, ch) + resnorm = norm(r) + iterations = it + resnorm < tol && break + x .-= J \ r + end + return dh, x, iterations +end From 9f2e557c173bdf8d22b53f27201cfd615f15f06a Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 12:55:55 +0000 Subject: [PATCH 12/62] =?UTF-8?q?Add=20the=20DFG=202D-1=20Navier=E2=80=93S?= =?UTF-8?q?tokes=20cylinder=20example=20and=20its=20test=20group?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Incompressible flow past a cylinder on the full 2.2 × 0.41 channel, written as a strong-form PDESystem with Q2/Q1 Taylor–Hood spaces, time-marched to the steady 2D-1 state; drag, lift and pressure difference from the weighted-residual functional. The NavierStokes group checks them against the Schäfer–Turek acceptance intervals and against the hand-written Ferrite solver on the same mesh (rtol 1e-5). LinearSolve becomes a test-only dependency: its default sparse LU throws on these Newton matrices, so the example names UMFPACK. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- Project.toml | 4 +- examples/dfg_cylinder/dfg_cylinder.jl | 109 ++++++++++++++++++++++++++ examples/dfg_cylinder/forces.jl | 16 ++-- examples/dfg_cylinder/reference.jl | 10 +-- test/NavierStokes/dfg_cylinder.jl | 30 +++++++ test/test_groups.toml | 3 + 6 files changed, 158 insertions(+), 14 deletions(-) create mode 100644 examples/dfg_cylinder/dfg_cylinder.jl create mode 100644 test/NavierStokes/dfg_cylinder.jl diff --git a/Project.toml b/Project.toml index 7db52daa..10090ad0 100644 --- a/Project.toml +++ b/Project.toml @@ -36,6 +36,7 @@ FerriteGmsh = "1.5" ForwardDiff = "1.4" Gmsh = "0.3" LinearAlgebra = "1.10" +LinearSolve = "5" ModelingToolkit = "11" NonlinearSolveFirstOrder = "2.10" OrdinaryDiffEqBDF = "2.4" @@ -56,6 +57,7 @@ julia = "1.10" AllocCheck = "9b6a8646-10ed-4001-bbdc-1d2f46dfbb1a" FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" Gmsh = "705231aa-382f-11e9-3f0c-b7cb4346fdeb" +LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae" OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" @@ -63,4 +65,4 @@ SciMLTesting = "09d9d899-5365-40a9-917a-5f67fddea283" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["AllocCheck", "FerriteGmsh", "Gmsh", "OrdinaryDiffEqBDF", "Random", "SafeTestsets", "SciMLTesting", "Test"] +test = ["AllocCheck", "FerriteGmsh", "Gmsh", "LinearSolve", "OrdinaryDiffEqBDF", "Random", "SafeTestsets", "SciMLTesting", "Test"] diff --git a/examples/dfg_cylinder/dfg_cylinder.jl b/examples/dfg_cylinder/dfg_cylinder.jl new file mode 100644 index 00000000..b7a236ae --- /dev/null +++ b/examples/dfg_cylinder/dfg_cylinder.jl @@ -0,0 +1,109 @@ +# The DFG/Schäfer–Turek 2D flow around a cylinder (Schäfer & Turek 1996, case 2D-1, Re = 20), written as a +# strong-form ModelingToolkit PDESystem and discretized with Q2/Q1 Taylor–Hood elements by FEMDiscretization. +# +# julia --project=benchmarks/navier_stokes examples/dfg_cylinder/dfg_cylinder.jl [h] +# +# The incompressible Navier–Stokes equations are written with scalar velocity components u, v and pressure p. +# Formulation choices, each forced by the front end and checked against the hand-written Ferrite solver of +# `reference.jl` (do-nothing outflow, weak pressure gradient), which it matches on every mesh tried: +# +# - The pressure gradient is a first-order term, so PDEBase's strong-form analysis keeps it strong (tested with +# V, not integrated by parts) and the natural outflow condition is ν∂ₙu = 0 rather than the do-nothing +# ν∂ₙu − p n = 0. The pressure level is then fixed by p = 0 on the outlet. On five meshes from 5k to +# 149k dofs, `dfg_reference_steady` gives the same cD, cL and Δp to seven digits with either formulation +# (`pressure = :weak` or `:strong`). +# - The pressure has no equation of its own: the continuity equation is paired with it explicitly, and the +# system is a DAE of index 2. Its initial state is consistent without index reduction because the flow starts +# at rest and the inflow is ramped up by 1 − exp(−t²), whose value and rate vanish at t = 0; the default +# initialisation, which would solve the continuity rows for p, is replaced by a check. +# - The pressure, an index-2 algebraic variable, and the Dirichlet rows are left out of DFBDF's error control (an +# absolute tolerance of 1e8 on them): the local error of an index-2 variable does not shrink with the step, so +# with it DFBDF cuts the step to nothing. The Dirichlet rows are exact anyway with a W refreshed every step. +# - 2D-1 is steady: the DAE is integrated until the flow has settled, and the coefficients are evaluated at the +# final time with the time-derivative term of the force functional included. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF +using OrdinaryDiffEqBDF: NLNewton +using LinearSolve: UMFPACKFactorization +using ModelingToolkit: t_nounits as t +using SciMLBase: SciMLBase, CheckInit +using Ferrite: Ferrite + +include(joinpath(@__DIR__, "mesh.jl")) +include(joinpath(@__DIR__, "forces.jl")) + +"DFG 2D-1 reference values (Nabh 1998, John & Matthies 2001), quoted by the FEATFLOW benchmark pages." +const DFG_2D1 = (cD = 5.57953523384, cL = 0.010618948146, Δp = 0.11752016697) +"Acceptance intervals of the benchmark paper (Schäfer & Turek 1996, table 4): the tolerance this example meets." +const DFG_2D1_BANDS = (cD = (5.57, 5.59), cL = (0.0104, 0.011), Δp = (0.1172, 0.1176)) + +@parameters ν Umax +@variables x y u(..) v(..) p(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +""" + dfg_problem(grid; tend = 30.0, ν_ = 1e-3, Umax_ = 0.3, ramp = 1 - exp(-t^2), kwargs...) + +The `DAEProblem` of the DFG channel `grid` (from `dfg_channel_grid`) with peak inflow `Umax_` times `ramp`, an +expression in `t`; `kwargs` are passed to `FEMDiscretization`. +""" +function dfg_problem(grid; tend = 30.0, ν_ = 1.0e-3, Umax_ = 0.3, ramp = 1 - exp(-t^2), kwargs...) + Ω = MeshDomain(grid) + Γin, Γout, Γwall, Γcyl = boundarypiece.(Ω, (:inlet, :outlet, :walls, :cylinder)) + U, V, P = u(t, x, y), v(t, x, y), p(t, x, y) + eqs = [ + Dt(U) ~ Dx(ν * Dx(U)) + Dy(ν * Dy(U)) - U * Dx(U) - V * Dy(U) - Dx(P), + Dt(V) ~ Dx(ν * Dx(V)) + Dy(ν * Dy(V)) - U * Dx(V) - V * Dy(V) - Dy(P), + 0 ~ Dx(U) + Dy(V), + ] + inflow = ramp * 4Umax * y * (0.41 - y) / 0.41^2 + bcs = [ + u(t, Γin) ~ inflow, v(t, Γin) ~ 0, + u(t, Γwall) ~ 0, v(t, Γwall) ~ 0, + u(t, Γcyl) ~ 0, v(t, Γcyl) ~ 0, + p(t, Γout) ~ 0, + u(0, x, y) ~ 0, v(0, x, y) ~ 0, + ] + domains = [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)] + @named dfg = PDESystem(eqs, bcs, domains, [t, x, y], [U, V, P], [ν => ν_, Umax => Umax_]) + Q2, Q1 = Lagrange{RefQuadrilateral, 2}(), Lagrange{RefQuadrilateral, 1}() + disc = FEMDiscretization( + Ω, t; spaces = Dict(u => Q2, v => Q2, p => Q1), pairing = Dict(eqs[3] => p), + initializealg = CheckInit(), kwargs... + ) + return DAEProblem(dfg, disc) +end + +"Absolute tolerances: `abstol` on the differential variables, none (1e8) on the algebraic ones." +differential_abstol(prob, abstol) = [d ? abstol : 1.0e8 for d in prob.differential_vars] + +# UMFPACK by name: LinearSolve 5.18's default sparse LU (supernodal) throws "snlu! requires the same sparsity +# pattern as the analyzed matrix" on these Newton matrices, as it does on Ferrite's own ns_vs_diffeq tutorial. +const DFG_ALG = DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()) + +""" + dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1e-7, reltol = 1e-7) + +Mesh, discretize and solve 2D-1; returns `(; sol, prob, coefficients, ndofs, build_s, solve_s)` with the +coefficients `(cD, cL, Δp)` at `tend`. +""" +function dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1.0e-7, reltol = 1.0e-7) + grid = dfg_channel_grid(; h, hc) + build_s = @elapsed prob = dfg_problem(grid; tend) + solve_s = @elapsed sol = solve(prob, alg; abstol = differential_abstol(prob, abstol), reltol, save_everystep = false) + dh = sol.disc_data.space.dh + xend = sol.original_sol.u[end] + dxdt = sol.original_sol(tend, Val{1}) + coefficients = dfg_coefficients(dh, xend; ν = 1.0e-3, Umean = 0.2, dxdt) + return (; sol, prob, coefficients, ndofs = length(prob.u0), build_s, solve_s) +end + +if abspath(PROGRAM_FILE) == @__FILE__ + h = isempty(ARGS) ? 0.06 : parse(Float64, ARGS[1]) + r = dfg_solve(; h, hc = h / 6) + c = r.coefficients + println("2D-1, h = $h: $(r.ndofs) dofs, build $(round(r.build_s; digits = 1)) s, solve $(round(r.solve_s; digits = 1)) s") + for k in (:cD, :cL, :Δp) + lo, hi = DFG_2D1_BANDS[k] + println(" $k = $(c[k]) (reference $(DFG_2D1[k]), relative error $(c[k] / DFG_2D1[k] - 1), band [$lo, $hi]: ", lo <= c[k] <= hi ? "pass" : "FAIL", ")") + end +end diff --git a/examples/dfg_cylinder/forces.jl b/examples/dfg_cylinder/forces.jl index 3290a90b..e51f4a28 100644 --- a/examples/dfg_cylinder/forces.jl +++ b/examples/dfg_cylinder/forces.jl @@ -42,21 +42,21 @@ function dfg_coefficients(dh, x; ν, Umean, D = 0.1, dxdt = nothing, fields = (: coords = Ferrite.getcoordinates(grid, 1) for cell in 1:Ferrite.getncells(grid) dofs = Ferrite.celldofs(dh, cell) - we = w[dofs[ru]] - any(!iszero, we) || continue + w_cell = w[dofs[ru]] + any(!iszero, w_cell) || continue Ferrite.getcoordinates!(coords, grid, cell) Ferrite.reinit!(cv_u, coords) Ferrite.reinit!(cv_p, coords) - ue, ve, pe = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] + u_cell, v_cell, p_cell = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] for q in 1:Ferrite.getnquadpoints(cv_u) dΩ = Ferrite.getdetJdV(cv_u, q) - U = (Ferrite.function_value(cv_u, q, ue), Ferrite.function_value(cv_u, q, ve)) - ∇U = (Ferrite.function_gradient(cv_u, q, ue), Ferrite.function_gradient(cv_u, q, ve)) + U = (Ferrite.function_value(cv_u, q, u_cell), Ferrite.function_value(cv_u, q, v_cell)) + ∇U = (Ferrite.function_gradient(cv_u, q, u_cell), Ferrite.function_gradient(cv_u, q, v_cell)) ∂U = dxdt === nothing ? (0.0, 0.0) : (Ferrite.function_value(cv_u, q, dxdt[dofs[ru]]), Ferrite.function_value(cv_u, q, dxdt[dofs[rv]])) - p = Ferrite.function_value(cv_p, q, pe) - W = Ferrite.function_value(cv_u, q, we) - ∇W = Ferrite.function_gradient(cv_u, q, we) + p = Ferrite.function_value(cv_p, q, p_cell) + W = Ferrite.function_value(cv_u, q, w_cell) + ∇W = Ferrite.function_gradient(cv_u, q, w_cell) for k in 1:2 convection = U[1] * ∇U[k][1] + U[2] * ∇U[k][2] F[k] -= ((∂U[k] + convection) * W + ν * dot(∇U[k], ∇W) - p * ∇W[k]) * dΩ diff --git a/examples/dfg_cylinder/reference.jl b/examples/dfg_cylinder/reference.jl index 8e7fd2eb..15810bb3 100644 --- a/examples/dfg_cylinder/reference.jl +++ b/examples/dfg_cylinder/reference.jl @@ -48,15 +48,15 @@ function dfg_reference_steady(grid; ν = 1.0e-3, Umax = 0.3, tol = 1.0e-10, maxi Ferrite.reinit!(cv_u, cell) Ferrite.reinit!(cv_p, cell) dofs = Ferrite.celldofs(cell) - ue, ve, pe = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] + u_cell, v_cell, p_cell = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] fill!(Je, 0) fill!(re, 0) for q in 1:Ferrite.getnquadpoints(cv_u) dΩ = Ferrite.getdetJdV(cv_u, q) - U = (Ferrite.function_value(cv_u, q, ue), Ferrite.function_value(cv_u, q, ve)) - ∇U = (Ferrite.function_gradient(cv_u, q, ue), Ferrite.function_gradient(cv_u, q, ve)) - p = Ferrite.function_value(cv_p, q, pe) - ∇p = Ferrite.function_gradient(cv_p, q, pe) + U = (Ferrite.function_value(cv_u, q, u_cell), Ferrite.function_value(cv_u, q, v_cell)) + ∇U = (Ferrite.function_gradient(cv_u, q, u_cell), Ferrite.function_gradient(cv_u, q, v_cell)) + p = Ferrite.function_value(cv_p, q, p_cell) + ∇p = Ferrite.function_gradient(cv_p, q, p_cell) div = ∇U[1][1] + ∇U[2][2] blocks = (ru, rv) for i in 1:nu diff --git a/test/NavierStokes/dfg_cylinder.jl b/test/NavierStokes/dfg_cylinder.jl new file mode 100644 index 00000000..2ec54d07 --- /dev/null +++ b/test/NavierStokes/dfg_cylinder.jl @@ -0,0 +1,30 @@ +# The DFG 2D-1 cylinder example (spec §11.5): the PDESystem path against the benchmark's acceptance intervals +# and against the hand-written Ferrite solver on the same mesh. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "dfg_cylinder.jl")) + include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "reference.jl")) + + @testset "DFG 2D-1 flow around a cylinder" begin + h, hc = 0.04, 0.0025 + r = dfg_solve(; h, hc) + @info "DFG 2D-1" r.ndofs r.build_s r.solve_s r.coefficients + @test SciMLBase.successful_retcode(r.sol) + c = r.coefficients + for k in (:cD, :cL, :Δp) + lo, hi = DFG_2D1_BANDS[k] + @test lo <= c[k] <= hi + end + + # The hand-written steady solution on the same mesh: same dof numbering after FieldWise renumbering. + dh_ref, x_ref, _ = dfg_reference_steady(dfg_channel_grid(; h, hc); pressure = :strong) + ref = dfg_coefficients(dh_ref, x_ref; ν = 1.0e-3, Umean = 0.2) + for k in (:cD, :cL, :Δp) + @test c[k] ≈ ref[k] rtol = 1.0e-5 + end + end +else + @testset "dfg_cylinder (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/test_groups.toml b/test/test_groups.toml index aeb13747..70f38b44 100644 --- a/test/test_groups.toml +++ b/test/test_groups.toml @@ -30,3 +30,6 @@ versions = ["lts", "1", "pre"] [Perf] versions = ["1"] + +[NavierStokes] +versions = ["lts", "1", "pre"] From e981ce49f54397a429a8c62bbeb24540112c8a4e Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 13:23:07 +0000 Subject: [PATCH 13/62] =?UTF-8?q?Add=20benchmark=20(d):=20Navier=E2=80=93S?= =?UTF-8?q?tokes=20cylinder=20against=20Ferrite's=20ns=5Fvs=5Fdiffeq?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit benchmarks/navier_stokes runs Ferrite's ns_vs_diffeq tutorial and the PDESystem example on the same mesh and settings, compares the two velocity fields, and records DFG 2D-1 drag, lift and pressure difference on three meshes up to 149k unknowns, with the environment record of benchmarks/common.jl (identical to the m1 benchmarks branch's file). The documentation gains a page on the example, its formulation choices and the tolerance. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- benchmarks/common.jl | 58 +++++ benchmarks/navier_stokes/Project.toml | 28 ++ benchmarks/navier_stokes/README.md | 24 ++ .../navier_stokes/ferrite_ns_vs_diffeq.jl | 245 ++++++++++++++++++ benchmarks/navier_stokes/ns_cylinder.jl | 92 +++++++ docs/pages.jl | 1 + docs/src/navier_stokes.md | 79 ++++++ 7 files changed, 527 insertions(+) create mode 100644 benchmarks/common.jl create mode 100644 benchmarks/navier_stokes/Project.toml create mode 100644 benchmarks/navier_stokes/README.md create mode 100644 benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl create mode 100644 benchmarks/navier_stokes/ns_cylinder.jl create mode 100644 docs/src/navier_stokes.md diff --git a/benchmarks/common.jl b/benchmarks/common.jl new file mode 100644 index 00000000..cb0390ba --- /dev/null +++ b/benchmarks/common.jl @@ -0,0 +1,58 @@ +# Shared by the benchmark scripts: timing, the environment record and the results file. +using Dates, Pkg, TOML + +const RESULTS_DIR = get(ENV, "BENCHMARK_RESULTS_DIR", joinpath(@__DIR__, "results")) + +"Minimum wall time of `f()` over `n` runs after one warm-up call." +best_time(f; n = 10) = (f(); minimum(@elapsed(f()) for _ in 1:n)) + +function git_sha() + sha = try + readchomp(`git -C $(@__DIR__) rev-parse HEAD`) + catch + "unknown" + end + # The package source and the benchmark scripts and environment; not the results this run writes. + dirty = try + !isempty(readchomp(`git -C $(@__DIR__) status --porcelain -- ../src . ':(exclude)results'`)) + catch + false + end + return dirty ? sha * "-dirty" : sha +end + +# A version string that pins what ran: a branch-tracked package also records its resolved git tree hash, and a +# path package (FiniteElementMethod itself) points at `git_sha`, which carries the dirty flag. +function package_version(info) + version = string(something(info.version, "unversioned")) + info.is_tracking_repo && return "$version ($(info.git_revision) at tree $(info.tree_hash))" + info.is_tracking_path && return "$version (path, see git_sha)" + return version +end + +"Where and with what a result was produced. `BENCHMARK_ORIGIN` is set by the Benchmarks workflow." +function environment() + packages = Dict(info.name => package_version(info) for info in values(Pkg.dependencies()) if info.is_direct_dep) + return Dict( + "origin" => get(ENV, "BENCHMARK_ORIGIN", "local run, not CI"), + "date" => string(now(UTC)) * "Z", + "git_sha" => git_sha(), + "julia" => string(VERSION), + "cpu" => strip(Sys.cpu_info()[1].model), + "cpu_threads" => Sys.CPU_THREADS, + "julia_threads" => Threads.nthreads(), + "os" => string(Sys.KERNEL, " ", Sys.MACHINE), + "packages" => packages, + ) +end + +"Write `results` (a Dict) with the environment record to `RESULTS_DIR/name.toml`; return the path." +function write_results(name, results) + mkpath(RESULTS_DIR) + path = joinpath(RESULTS_DIR, name * ".toml") + open(path, "w") do io + TOML.print(io, merge(Dict("environment" => environment()), results); sorted = true) + end + println("wrote ", path) + return path +end diff --git a/benchmarks/navier_stokes/Project.toml b/benchmarks/navier_stokes/Project.toml new file mode 100644 index 00000000..3beab4ab --- /dev/null +++ b/benchmarks/navier_stokes/Project.toml @@ -0,0 +1,28 @@ +[deps] +ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" +BlockArrays = "8e7c35d0-a365-5155-bbbb-fb81a777f24e" +Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" +DiffEqBase = "2b5f629d-d688-5b77-993f-72d75c75574e" +DomainSets = "5b8099bc-c8ec-5219-889f-1d9e522a28bf" +Ferrite = "c061ca5d-56c9-439f-9c0e-210fe06d3992" +FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" +FiniteElementMethod = "e08948db-0ae8-498a-9b98-73fc7f237ce3" +Gmsh = "705231aa-382f-11e9-3f0c-b7cb4346fdeb" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae" +ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" +OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" +OrdinaryDiffEqRosenbrock = "43230ef6-c299-4910-a778-202eb28ce4ce" +PDEBase = "a7812802-0625-4b9e-961c-d332478797e5" +Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" +Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +SciMLBase = "0bca4576-84f4-4d90-8ffe-ffa030f20462" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +TOML = "fa267f1f-6049-4f14-aa54-33bafae1ed76" + +[sources] +FiniteElementMethod = {path = "../.."} +PDEBase = {rev = "forge/mesh-axis-order", url = "https://github.com/xtalax-droid/PDEBase.jl"} + +[compat] +julia = "1.11" diff --git a/benchmarks/navier_stokes/README.md b/benchmarks/navier_stokes/README.md new file mode 100644 index 00000000..1cf664c4 --- /dev/null +++ b/benchmarks/navier_stokes/README.md @@ -0,0 +1,24 @@ +# Benchmark (d): Navier–Stokes flow past a cylinder + +`ns_cylinder.jl` measures, in one process and after a warm-up solve on each side: + +1. Wall-clock against Ferrite's `ns_vs_diffeq.jl` tutorial (`ferrite_ns_vs_diffeq.jl`, the tutorial's code with + the changes listed at its top) on the same mesh, `dfg_channel_grid(h = 0.05, length = 1.1)`, with the + tutorial's settings: ν = 1e-3, inflow ramp `min(1.5t, 1.5)` (Re = 100), T = 6, abstol 1e-4, reltol 1e-5, + output every 0.1. Ferrite runs Rodas5P on its mass-matrix ODE; FiniteElementMethod discretizes the PDESystem + of `examples/dfg_cylinder` to a DAEProblem and runs DFBDF. The two velocity fields are compared at t = 1 and + t = T at 20 points behind the cylinder. +2. DFG 2D-1 (Re = 20) drag, lift and pressure difference on the full channel at the meshes of + `BENCHMARK_NS_MESHES` (`h:hc` pairs, default `0.04:0.0025,0.02:0.00333,0.01:0.00167`, up to 149 094 unknowns), + with their errors against the DFG reference values. + +```sh +julia --project=benchmarks/navier_stokes -e 'using Pkg; Pkg.instantiate()' +julia --project=benchmarks/navier_stokes benchmarks/navier_stokes/ns_cylinder.jl +``` + +The results go to `benchmarks/results/ns_cylinder.toml` (or `BENCHMARK_RESULTS_DIR`) with the environment record of +`benchmarks/common.jl`: origin, date, commit, CPU, thread counts, Julia and package versions. Peak memory of the +default run is about 6.5 GB, from the 149 094-unknown 2D-1 solve; the run takes about 10 minutes on one thread. +The environment uses this repository's package and, until a PDEBase release has the mesh layer, PDEBase from the +`forge/mesh-axis-order` branch (`[sources]`). diff --git a/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl b/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl new file mode 100644 index 00000000..f9233ddf --- /dev/null +++ b/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl @@ -0,0 +1,245 @@ +# Baseline of benchmark (d), spec §11.5: Ferrite's own tutorial `docs/src/literate-tutorials/ns_vs_diffeq.jl` +# (Ferrite 1.7, MIT licence), run as published apart from three changes that do not touch the numerics: the mesh +# comes from `dfg_channel_grid` of the example (the same geometry for both sides of the comparison; the tutorial's +# own Gmsh rectangle-minus-circle with `Mesh.MeshSizeMax = 0.05` is kept as `tutorial_grid`), the VTK output loop +# is replaced by `solve` with `saveat`, the progress bar and logging are off, and the linear solver is named as +# UMFPACK: the tutorial predates LinearSolve's current sparse default, whose supernodal LU rejects the change of +# sparsity pattern between Rodas5P's W matrices that UMFPACK, the default when the tutorial was written, accepts. Everything else +# (Q2Q1 Taylor–Hood with a vector velocity, ν = 1e-3, the inflow ramp `min(1.5t, 1.5)`, Rodas5P with the Ferrite +# Dirichlet limiter, `abstol = 1e-4`, `reltol = 1e-5`, `dt = 1e-3`, the free-dof error norm) is the tutorial's. +# +# Prints and returns `(; seconds, ndofs, steps, ...)`; `ns_cylinder.jl` calls it and writes the results file. +using Ferrite, SparseArrays, BlockArrays, LinearAlgebra +using DiffEqBase +using OrdinaryDiffEqRosenbrock: Rodas5P +using ADTypes: AutoFiniteDiff +using LinearSolve: UMFPACKFactorization + +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "mesh.jl")) + +function tutorial_grid() + Gmsh.initialize() + try + gmsh.option.set_number("General.Verbosity", 2) + dim = 2 + rect_tag = gmsh.model.occ.add_rectangle(0, 0, 0, 1.1, 0.41) + circle_tag = gmsh.model.occ.add_circle(0.2, 0.2, 0, 0.05) + circle_curve_tag = gmsh.model.occ.add_curve_loop([circle_tag]) + circle_surf_tag = gmsh.model.occ.add_plane_surface([circle_curve_tag]) + gmsh.model.occ.cut([(dim, rect_tag)], [(dim, circle_surf_tag)]) + gmsh.model.occ.synchronize() + gmsh.model.model.add_physical_group(dim - 1, [6], -1, "bottom") + gmsh.model.model.add_physical_group(dim - 1, [7], -1, "inlet") + gmsh.model.model.add_physical_group(dim - 1, [8], -1, "outlet") + gmsh.model.model.add_physical_group(dim - 1, [9], -1, "top") + gmsh.model.model.add_physical_group(dim - 1, [5], -1, "cylinder") + gmsh.option.setNumber("Mesh.Algorithm", 11) + gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 20) + gmsh.option.setNumber("Mesh.MeshSizeMax", 0.05) + gmsh.model.mesh.generate(dim) + grid = FerriteGmsh.togrid() + addfacetset!(grid, "walls", union(getfacetset(grid, "bottom"), getfacetset(grid, "top"))) + return grid + finally + Gmsh.finalize() + end +end + +function assemble_mass_matrix(cv::MultiFieldCellValues, M::SparseMatrixCSC, dh::DofHandler) + n_basefuncs_v = getnbasefunctions(cv.v) + n_basefuncs_p = getnbasefunctions(cv.p) + n_basefuncs = n_basefuncs_v + n_basefuncs_p + v▄, p▄ = 1, 2 + Mₑ = BlockedArray(zeros(n_basefuncs, n_basefuncs), [n_basefuncs_v, n_basefuncs_p], [n_basefuncs_v, n_basefuncs_p]) + mass_assembler = start_assemble(M) + for cell in CellIterator(dh) + fill!(Mₑ, 0) + Ferrite.reinit!(cv, cell) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + for i in 1:n_basefuncs_v + φᵢ = shape_value(cv.v, q_point, i) + for j in 1:n_basefuncs_v + φⱼ = shape_value(cv.v, q_point, j) + Mₑ[BlockIndex((v▄, v▄), (i, j))] += φᵢ ⋅ φⱼ * dΩ + end + end + end + assemble!(mass_assembler, celldofs(cell), Mₑ) + end + return M +end + +function assemble_stokes_matrix(cv::MultiFieldCellValues, ν, K::SparseMatrixCSC, dh::DofHandler) + n_basefuncs_v = getnbasefunctions(cv.v) + n_basefuncs_p = getnbasefunctions(cv.p) + n_basefuncs = n_basefuncs_v + n_basefuncs_p + v▄, p▄ = 1, 2 + Kₑ = BlockedArray(zeros(n_basefuncs, n_basefuncs), [n_basefuncs_v, n_basefuncs_p], [n_basefuncs_v, n_basefuncs_p]) + stiffness_assembler = start_assemble(K) + for cell in CellIterator(dh) + fill!(Kₑ, 0) + Ferrite.reinit!(cv, cell) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + for i in 1:n_basefuncs_v + ∇φᵢ = shape_gradient(cv.v, q_point, i) + for j in 1:n_basefuncs_v + ∇φⱼ = shape_gradient(cv.v, q_point, j) + Kₑ[BlockIndex((v▄, v▄), (i, j))] -= ν * ∇φᵢ ⊡ ∇φⱼ * dΩ + end + end + for j in 1:n_basefuncs_p + ψ = shape_value(cv.p, q_point, j) + for i in 1:n_basefuncs_v + divφ = shape_divergence(cv.v, q_point, i) + Kₑ[BlockIndex((v▄, p▄), (i, j))] += (divφ * ψ) * dΩ + Kₑ[BlockIndex((p▄, v▄), (j, i))] += (ψ * divφ) * dΩ + end + end + end + assemble!(stiffness_assembler, celldofs(cell), Kₑ) + end + return K +end + +struct RHSparams{KT, CH, DH, CV, UT} + K::KT + ch::CH + dh::DH + cv::CV + u::UT +end + +function ferrite_limiter!(u, _, p, t) + update!(p.ch, t) + return apply!(u, p.ch) +end + +function navierstokes_rhs_element!(dvₑ, vₑ, cv) + n_basefuncs = getnbasefunctions(cv.v) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + ∇v = function_gradient(cv.v, q_point, vₑ) + v = function_value(cv.v, q_point, vₑ) + for j in 1:n_basefuncs + φⱼ = shape_value(cv.v, q_point, j) + dvₑ[j] -= v ⋅ ∇v' ⋅ φⱼ * dΩ + end + end + return +end + +function navierstokes!(du, u_uc, p::RHSparams, t) + (; K, ch, dh, cv, u) = p + u .= u_uc + update!(ch, t) + apply!(u, ch) + mul!(du, K, u) + v_range = dof_range(dh, :v) + n_basefuncs = getnbasefunctions(cv.v) + vₑ = zeros(n_basefuncs) + duₑ = zeros(n_basefuncs) + for cell in CellIterator(dh) + Ferrite.reinit!(cv, cell) + v_celldofs = @view celldofs(cell)[v_range] + vₑ .= @views u[v_celldofs] + fill!(duₑ, 0.0) + navierstokes_rhs_element!(duₑ, vₑ, cv) + assemble!(du, v_celldofs, duₑ) + end + return +end + +function navierstokes_jac_element!(Jₑ, vₑ, cv) + n_basefuncs = getnbasefunctions(cv.v) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + ∇v = function_gradient(cv.v, q_point, vₑ) + v = function_value(cv.v, q_point, vₑ) + for j in 1:n_basefuncs + φⱼ = shape_value(cv.v, q_point, j) + for i in 1:n_basefuncs + φᵢ = shape_value(cv.v, q_point, i) + ∇φᵢ = shape_gradient(cv.v, q_point, i) + Jₑ[j, i] -= (φᵢ ⋅ ∇v' + v ⋅ ∇φᵢ') ⋅ φⱼ * dΩ + end + end + end + return +end + +function navierstokes_jac!(J, u_uc, p, t) + (; K, ch, dh, cv, u) = p + u .= u_uc + update!(ch, t) + apply!(u, ch) + nonzeros(J) .= nonzeros(K) + assembler = start_assemble(J; fillzero = false) + n_basefuncs = getnbasefunctions(cv.v) + Jₑ = zeros(n_basefuncs, n_basefuncs) + vₑ = zeros(n_basefuncs) + v_range = dof_range(dh, :v) + for cell in CellIterator(dh) + Ferrite.reinit!(cv, cell) + v_celldofs = @view celldofs(cell)[v_range] + vₑ .= @views u[v_celldofs] + fill!(Jₑ, 0.0) + navierstokes_jac_element!(Jₑ, vₑ, cv) + assemble!(assembler, v_celldofs, Jₑ) + end + return apply!(J, ch) +end + +struct FreeDofErrorNorm + ch::ConstraintHandler +end +(fe_norm::FreeDofErrorNorm)(u::Union{AbstractFloat, Complex}, t) = DiffEqBase.ODE_DEFAULT_NORM(u, t) +(fe_norm::FreeDofErrorNorm)(u::AbstractArray, t) = DiffEqBase.ODE_DEFAULT_NORM(u[fe_norm.ch.free_dofs], t) + +""" + ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1e-3, vmax = 1.5, Δt_save = 0.1) + +Ferrite's tutorial problem on `grid` (facet sets `"inlet"`, `"outlet"`, `"walls"`, `"cylinder"`): build the +operators and integrate to `T`. Returns the solution, the `DofHandler` and the setup and solve times. +""" +function ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1.0e-3, vmax = 1.5, Δt_save = 0.1) + setup = @elapsed begin + dim = 2 + ip_v = Lagrange{RefQuadrilateral, 2}()^dim + qr = QuadratureRule{RefQuadrilateral}(4) + ip_p = Lagrange{RefQuadrilateral, 1}() + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(grid)) + cellvalues = MultiFieldCellValues(qr, (v = ip_v, p = ip_p), ip_geo) + dh = DofHandler(grid) + add!(dh, :v, ip_v) + add!(dh, :p, ip_p) + close!(dh) + ch = ConstraintHandler(dh) + ∂Ω_noslip = union(getfacetset(grid, "walls"), getfacetset(grid, "cylinder")) + add!(ch, Dirichlet(:v, ∂Ω_noslip, (x, t) -> Vec((0.0, 0.0)), [1, 2])) + vᵢₙ(t) = min(t * vmax, vmax) + parabolic_inflow_profile(x, t) = Vec((4 * vᵢₙ(t) * x[2] * (0.41 - x[2]) / 0.41^2, 0.0)) + add!(ch, Dirichlet(:v, getfacetset(grid, "inlet"), parabolic_inflow_profile, [1, 2])) + close!(ch) + update!(ch, 0.0) + M = assemble_mass_matrix(cellvalues, allocate_matrix(dh), dh) + K = assemble_stokes_matrix(cellvalues, ν, allocate_matrix(dh), dh) + u₀ = zeros(ndofs(dh)) + apply!(u₀, ch) + jac_sparsity = sparse(K) + apply!(M, ch) + p = RHSparams(K, ch, dh, cellvalues, copy(u₀)) + rhs = ODEFunction(navierstokes!, mass_matrix = M; jac = navierstokes_jac!, jac_prototype = jac_sparsity) + problem = ODEProblem(rhs, u₀, (0.0, T), p) + timestepper = Rodas5P( + autodiff = AutoFiniteDiff(), step_limiter! = ferrite_limiter!, linsolve = UMFPACKFactorization() + ) + end + solve_s = @elapsed sol = solve( + problem, timestepper; initializealg = NoInit(), dt = 1.0e-3, + adaptive = true, abstol = 1.0e-4, reltol = 1.0e-5, saveat = Δt_save, + internalnorm = FreeDofErrorNorm(ch), d_discontinuities = [1.0] + ) + return (; sol, dh, ch, setup_s = setup, solve_s, ndofs = ndofs(dh), steps = sol.stats.naccept + sol.stats.nreject) +end diff --git a/benchmarks/navier_stokes/ns_cylinder.jl b/benchmarks/navier_stokes/ns_cylinder.jl new file mode 100644 index 00000000..14534770 --- /dev/null +++ b/benchmarks/navier_stokes/ns_cylinder.jl @@ -0,0 +1,92 @@ +# Benchmark (d), spec §11.5: wall-clock of the Navier–Stokes cylinder flow through the PDESystem front end against +# Ferrite's `ns_vs_diffeq.jl` tutorial on the same mesh and settings, and the DFG 2D-1 drag and lift. +# +# julia --project=benchmarks/navier_stokes -e 'using Pkg; Pkg.instantiate()' +# julia --project=benchmarks/navier_stokes benchmarks/navier_stokes/ns_cylinder.jl +# +# Part 1, wall-clock: the tutorial's problem (ν = 1e-3, peak inflow min(1.5t, 1.5), so Re = 100 once ramped, to +# T = 6, abstol = 1e-4, reltol = 1e-5, output every 0.1) on `dfg_channel_grid(h = 0.05, length = 1.1)`, the +# tutorial's shortened channel. Ferrite: the tutorial's Rodas5P on the mass-matrix ODE. FiniteElementMethod: the +# PDESystem of `examples/dfg_cylinder` with the same ramp, discretized to a DAEProblem and solved with DFBDF, the +# pressure and Dirichlet rows out of error control (the tutorial's norm leaves out the Dirichlet dofs). Both +# are timed after a warm-up solve to t = 0.05 in the same process, so neither includes compilation; the +# discretization time of the PDESystem is reported separately. +# The two solutions are compared at t = 1 (end of the ramp) and t = T at 20 points behind the cylinder. +# Part 2, accuracy: 2D-1 (Re = 20) on the full channel at the meshes `BENCHMARK_NS_MESHES`, `h:hc` pairs of +# `dfg_channel_grid` sizes (default 0.04:0.0025,0.02:0.00333,0.01:0.00167). +include(joinpath(@__DIR__, "..", "common.jl")) +include(joinpath(@__DIR__, "ferrite_ns_vs_diffeq.jl")) +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "dfg_cylinder.jl")) +using Printf + +const MESHES = [Tuple(parse.(Float64, split(m, ":"))) for m in split(get(ENV, "BENCHMARK_NS_MESHES", "0.04:0.0025,0.02:0.00333,0.01:0.00167"), ",")] +const T_END = parse(Float64, get(ENV, "BENCHMARK_NS_T", "6.0")) + +function fem_tutorial(grid; T) + build_s = @elapsed prob = dfg_problem(grid; tend = T, ν_ = 1.0e-3, Umax_ = 1.5, ramp = min(t, 1)) + abstol = differential_abstol(prob, 1.0e-4) + solve_s = @elapsed sol = solve(prob, DFG_ALG; abstol, reltol = 1.0e-5, saveat = 0.1, tstops = [1.0]) + return (; sol, build_s, solve_s, ndofs = length(prob.u0), steps = sol.original_sol.stats.naccept + sol.original_sol.stats.nreject) +end + +function run() + grid = dfg_channel_grid(; h = 0.05, length = 1.1) + ferrite_ns_vs_diffeq(grid; T = 0.05) + ferrite = ferrite_ns_vs_diffeq(grid; T = T_END) + fem_tutorial(grid; T = 0.05) + fem = fem_tutorial(grid; T = T_END) + # Horizontal velocity of both solutions at points behind the cylinder. + points = [Ferrite.Vec(x_, y_) for x_ in range(0.4, 1.0; length = 5) for y_ in range(0.05, 0.36; length = 4)] + ph = Ferrite.PointEvalHandler(grid, points) + agreement = Dict{String, Any}() + for τ in (1.0, T_END) + u_ferrite = first.(Ferrite.evaluate_at_points(ph, ferrite.dh, ferrite.sol(τ), :v)) + u_fem = Ferrite.evaluate_at_points(ph, fem.sol.disc_data.space.dh, fem.sol.original_sol(τ), :u) + agreement["max_abs_u_difference_t$(τ)"] = maximum(abs, u_ferrite - u_fem) + agreement["max_abs_u_t$(τ)"] = maximum(abs, u_ferrite) + end + println("velocity agreement: ", agreement) + @printf( + "tutorial problem to T = %g: Ferrite %.1f s (%d dofs, %d steps, %s); FiniteElementMethod %.1f s (%d dofs, %d steps, %s), discretization %.1f s\n", + T_END, ferrite.solve_s, ferrite.ndofs, ferrite.steps, ferrite.sol.retcode, fem.solve_s, fem.ndofs, fem.steps, fem.sol.retcode, fem.build_s + ) + + rows = Dict{String, Any}[] + for (h, hc) in MESHES + r = dfg_solve(; h, hc) + c = r.coefficients + push!( + rows, Dict{String, Any}( + "h" => h, "hc" => hc, "ndofs" => r.ndofs, "build_s" => r.build_s, "solve_s" => r.solve_s, + "cD" => c.cD, "cL" => c.cL, "dp" => c.Δp, + "cD_relerr" => c.cD / DFG_2D1.cD - 1, "cL_relerr" => c.cL / DFG_2D1.cL - 1, "dp_relerr" => c.Δp / DFG_2D1.Δp - 1, + ) + ) + @printf( + "2D-1, h = %g: %d dofs, cD = %.6f (%.2e), cL = %.6f (%.2e), Δp = %.6f (%.2e), solve %.1f s\n", + h, r.ndofs, c.cD, c.cD / DFG_2D1.cD - 1, c.cL, c.cL / DFG_2D1.cL - 1, c.Δp, c.Δp / DFG_2D1.Δp - 1, r.solve_s + ) + end + return write_results( + "ns_cylinder", Dict( + "benchmark" => "(d) Navier–Stokes flow past a cylinder: wall-clock against Ferrite's ns_vs_diffeq tutorial, and DFG 2D-1 drag and lift", + "wallclock" => Dict( + "description" => "ns_vs_diffeq settings (ν = 1e-3, inflow min(1.5t, 1.5), abstol 1e-4, reltol 1e-5, saveat 0.1) to T = $T_END on dfg_channel_grid(h = 0.05, length = 1.1), Q2/Q1 Taylor–Hood, after a warm-up solve", + "cells" => Ferrite.getncells(grid), + "ferrite_solver" => "Rodas5P (AutoFiniteDiff, Ferrite step limiter, UMFPACK) on the mass-matrix ODE", + "ferrite_s" => ferrite.solve_s, "ferrite_ndofs" => ferrite.ndofs, "ferrite_steps" => ferrite.steps, + "fem_solver" => "DFBDF on the DAEProblem of the PDESystem", + "fem_s" => fem.solve_s, "fem_ndofs" => fem.ndofs, "fem_steps" => fem.steps, "fem_discretize_s" => fem.build_s, + "ratio" => fem.solve_s / ferrite.solve_s, + "agreement" => agreement, + ), + "dfg_2d1" => Dict( + "reference" => Dict("cD" => DFG_2D1.cD, "cL" => DFG_2D1.cL, "dp" => DFG_2D1.Δp), + "bands" => Dict("cD" => collect(DFG_2D1_BANDS.cD), "cL" => collect(DFG_2D1_BANDS.cL), "dp" => collect(DFG_2D1_BANDS.Δp)), + "rows" => rows, + ), + ) + ) +end + +run() diff --git a/docs/pages.jl b/docs/pages.jl index 14f7e5fa..2c958db5 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -1,5 +1,6 @@ pages = [ "Home" => "index.md", "Solutions" => "solution.md", + "Navier–Stokes example" => "navier_stokes.md", "API" => "api.md", ] diff --git a/docs/src/navier_stokes.md b/docs/src/navier_stokes.md new file mode 100644 index 00000000..f45e8dcc --- /dev/null +++ b/docs/src/navier_stokes.md @@ -0,0 +1,79 @@ +# Navier–Stokes: flow past a cylinder + +The DFG benchmark of Schäfer and Turek (1996), case 2D-1: steady incompressible flow at +Reynolds number 20 past a cylinder of diameter 0.1 centred at (0.2, 0.2) in the channel +[0, 2.2] × [0, 0.41], with a parabolic inflow of peak 0.3, no slip on the walls and the +cylinder, and kinematic viscosity 10⁻³. It is a mixed saddle-point problem: the pressure has no +equation of its own and needs an inf-sup-stable pair, here Q2/Q1 Taylor–Hood. + +The script is `examples/dfg_cylinder/dfg_cylinder.jl`; the mesh generator (`mesh.jl`), the +drag and lift functional (`forces.jl`) and a hand-written Ferrite solver used as an oracle +(`reference.jl`) sit next to it. The core is ordinary strong-form ModelingToolkit: + +```julia +@parameters ν Umax +@variables x y u(..) v(..) p(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +Ω = MeshDomain(dfg_channel_grid(; h = 0.04, hc = 0.0025)) # Gmsh, all quadrilaterals, curved cylinder +Γin, Γout, Γwall, Γcyl = boundarypiece.(Ω, (:inlet, :outlet, :walls, :cylinder)) +U, V, P = u(t, x, y), v(t, x, y), p(t, x, y) +eqs = [ + Dt(U) ~ Dx(ν * Dx(U)) + Dy(ν * Dy(U)) - U * Dx(U) - V * Dy(U) - Dx(P), + Dt(V) ~ Dx(ν * Dx(V)) + Dy(ν * Dy(V)) - U * Dx(V) - V * Dy(V) - Dy(P), + 0 ~ Dx(U) + Dy(V), +] +inflow = (1 - exp(-t^2)) * 4Umax * y * (0.41 - y) / 0.41^2 +bcs = [ + u(t, Γin) ~ inflow, v(t, Γin) ~ 0, u(t, Γwall) ~ 0, v(t, Γwall) ~ 0, + u(t, Γcyl) ~ 0, v(t, Γcyl) ~ 0, p(t, Γout) ~ 0, u(0, x, y) ~ 0, v(0, x, y) ~ 0, +] +@named dfg = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 60.0)], [t, x, y], [U, V, P], + [ν => 1e-3, Umax => 0.3]) +Q2, Q1 = Lagrange{RefQuadrilateral, 2}(), Lagrange{RefQuadrilateral, 1}() +disc = FEMDiscretization(Ω, t; spaces = Dict(u => Q2, v => Q2, p => Q1), + pairing = Dict(eqs[3] => p), initializealg = CheckInit()) +prob = DAEProblem(dfg, disc) +abstol = [d ? 1e-7 : 1e8 for d in prob.differential_vars] # pressure and Dirichlet rows out of error control +sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()); + abstol, reltol = 1e-7) +``` + +## Formulation choices + +- **Outflow condition.** PDEBase's strong-form analysis integrates only second-order terms by + parts, so the pressure gradient is tested strongly and the natural outflow condition is + `ν ∂ₙu = 0` instead of the do-nothing condition `ν ∂ₙu − p n = 0` of the benchmark. The + pressure level is fixed by `p = 0` on the outlet. The hand-written Ferrite solver gives the + same drag, lift and pressure difference to seven digits with either formulation on five + meshes from 5 000 to 149 000 unknowns. +- **Index-2 DAE.** The continuity equation is paired with the pressure explicitly. The flow + starts at rest and the inflow is ramped by `1 − exp(−t²)`, whose value and rate vanish at + `t = 0`, so the zero initial state is consistent and the default initialisation (which + would solve the continuity rows for the pressure) is replaced by `CheckInit()`. The + pressure and the Dirichlet rows are left out of the error control: the local error of an + index-2 variable does not shrink with the step. +- **Steady state.** 2D-1 is steady; the DAE is integrated to `t = 60`, where the flow has + settled to the solver tolerance, and the coefficients include the `∂ₜu` term of the + functional. +- **Linear solver.** UMFPACK is named because LinearSolve 5.18's default sparse LU throws + "snlu! requires the same sparsity pattern as the analyzed matrix" on these Newton matrices + (and on Ferrite's own `ns_vs_diffeq.jl` tutorial). + +## Drag and lift + +The coefficients are the weighted residuals of the momentum equations (John 2004; Braack and +Richter 2006): with `w` the finite-element function equal to `e_k` at the cylinder nodes and +zero elsewhere, `F_k = −∫ (∂ₜu·w + ν∇u:∇w + (u·∇)u·w − p ∇·w) dx` and `c = 2F/(Ū² D)` with +`Ū = 0.2`, `D = 0.1`. This volume form converges at twice the rate of the line integral of +the discrete stresses. + +**Tolerance.** The acceptance intervals of the benchmark paper, `c_D ∈ [5.57, 5.59]`, +`c_L ∈ [0.0104, 0.0110]` and `Δp ∈ [0.1172, 0.1176]` (reference values 5.57953523384, +0.010618948146 and 0.11752016697). The `NavierStokes` test group solves on a 16 430-unknown +mesh and asserts the three intervals, and agreement with the hand-written Ferrite Newton +solver on the same mesh to a relative 10⁻⁵. Benchmark (d) in `benchmarks/navier_stokes` +repeats the solve on finer meshes and records the errors against the reference values. + +This is the evidence that moves mixed saddle-point problems into Tier 1 of the supported +equation classes. From 3b33d71bc7c774bddaed59f59a895b5142ecfde1 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 13:41:07 +0000 Subject: [PATCH 14/62] Make a DFG solve that stops early fail loudly check_solved raises when DFBDF does not reach the final time, so no coefficients are reported from a truncated solve; with UMFPACK named there is no silent fall-back to sparse QR on a singular Newton matrix. Documents the index-2 recipe (algebraic rows out of error control, divergence-free start, no pressure initial condition needed). Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- benchmarks/navier_stokes/ns_cylinder.jl | 2 +- docs/src/navier_stokes.md | 8 ++++++-- examples/dfg_cylinder/dfg_cylinder.jl | 15 +++++++++++++-- test/NavierStokes/dfg_cylinder.jl | 2 ++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/benchmarks/navier_stokes/ns_cylinder.jl b/benchmarks/navier_stokes/ns_cylinder.jl index 14534770..fb7d490a 100644 --- a/benchmarks/navier_stokes/ns_cylinder.jl +++ b/benchmarks/navier_stokes/ns_cylinder.jl @@ -25,7 +25,7 @@ const T_END = parse(Float64, get(ENV, "BENCHMARK_NS_T", "6.0")) function fem_tutorial(grid; T) build_s = @elapsed prob = dfg_problem(grid; tend = T, ν_ = 1.0e-3, Umax_ = 1.5, ramp = min(t, 1)) abstol = differential_abstol(prob, 1.0e-4) - solve_s = @elapsed sol = solve(prob, DFG_ALG; abstol, reltol = 1.0e-5, saveat = 0.1, tstops = [1.0]) + solve_s = @elapsed sol = check_solved(solve(prob, DFG_ALG; abstol, reltol = 1.0e-5, saveat = 0.1, tstops = [1.0])) return (; sol, build_s, solve_s, ndofs = length(prob.u0), steps = sol.original_sol.stats.naccept + sol.original_sol.stats.nreject) end diff --git a/docs/src/navier_stokes.md b/docs/src/navier_stokes.md index f45e8dcc..08906157 100644 --- a/docs/src/navier_stokes.md +++ b/docs/src/navier_stokes.md @@ -50,7 +50,9 @@ sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFP - **Index-2 DAE.** The continuity equation is paired with the pressure explicitly. The flow starts at rest and the inflow is ramped by `1 − exp(−t²)`, whose value and rate vanish at `t = 0`, so the zero initial state is consistent and the default initialisation (which - would solve the continuity rows for the pressure) is replaced by `CheckInit()`. The + would solve the continuity rows for the pressure) is replaced by `CheckInit()`. The zero + velocity is discretely divergence free; the pressure, an algebraic variable, starts at zero + and needs no initial condition, since every residual row vanishes at `t = 0`. The pressure and the Dirichlet rows are left out of the error control: the local error of an index-2 variable does not shrink with the step. - **Steady state.** 2D-1 is steady; the DAE is integrated to `t = 60`, where the flow has @@ -58,7 +60,9 @@ sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFP functional. - **Linear solver.** UMFPACK is named because LinearSolve 5.18's default sparse LU throws "snlu! requires the same sparsity pattern as the analyzed matrix" on these Newton matrices - (and on Ferrite's own `ns_vs_diffeq.jl` tutorial). + (and on Ferrite's own `ns_vs_diffeq.jl` tutorial). Naming it also removes the default's + silent fall-back to sparse QR on a singular Newton matrix, which costs tens of gigabytes + here; the example's `check_solved` raises if the solve stops before its final time. ## Drag and lift diff --git a/examples/dfg_cylinder/dfg_cylinder.jl b/examples/dfg_cylinder/dfg_cylinder.jl index b7a236ae..1a0a0330 100644 --- a/examples/dfg_cylinder/dfg_cylinder.jl +++ b/examples/dfg_cylinder/dfg_cylinder.jl @@ -15,7 +15,9 @@ # - The pressure has no equation of its own: the continuity equation is paired with it explicitly, and the # system is a DAE of index 2. Its initial state is consistent without index reduction because the flow starts # at rest and the inflow is ramped up by 1 − exp(−t²), whose value and rate vanish at t = 0; the default -# initialisation, which would solve the continuity rows for p, is replaced by a check. +# initialisation, which would solve the continuity rows for p, is replaced by a check. The zero +# velocity is discretely divergence free, and p needs no initial condition: it is algebraic, starts at zero, +# and every residual row vanishes at t = 0. # - The pressure, an index-2 algebraic variable, and the Dirichlet rows are left out of DFBDF's error control (an # absolute tolerance of 1e8 on them): the local error of an index-2 variable does not shrink with the step, so # with it DFBDF cuts the step to nothing. The Dirichlet rows are exact anyway with a W refreshed every step. @@ -78,8 +80,17 @@ differential_abstol(prob, abstol) = [d ? abstol : 1.0e8 for d in prob.differenti # UMFPACK by name: LinearSolve 5.18's default sparse LU (supernodal) throws "snlu! requires the same sparsity # pattern as the analyzed matrix" on these Newton matrices, as it does on Ferrite's own ns_vs_diffeq tutorial. +# Naming it also removes the default's silent fall-back to sparse QR when a Newton matrix is singular, which +# for this index-2 system took tens of GB: a singular matrix now fails the step, and `check_solved` raises. const DFG_ALG = DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()) +"Raise unless `sol` reached its final time; a DAE solve that stopped early must not report coefficients." +function check_solved(sol) + SciMLBase.successful_retcode(sol) || + error("the DFG solve stopped at t = $(sol.t[end]) with retcode $(sol.retcode); with the pressure in the error control or a singular Newton matrix DFBDF cuts its step to nothing") + return sol +end + """ dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1e-7, reltol = 1e-7) @@ -89,7 +100,7 @@ coefficients `(cD, cL, Δp)` at `tend`. function dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1.0e-7, reltol = 1.0e-7) grid = dfg_channel_grid(; h, hc) build_s = @elapsed prob = dfg_problem(grid; tend) - solve_s = @elapsed sol = solve(prob, alg; abstol = differential_abstol(prob, abstol), reltol, save_everystep = false) + solve_s = @elapsed sol = check_solved(solve(prob, alg; abstol = differential_abstol(prob, abstol), reltol, save_everystep = false)) dh = sol.disc_data.space.dh xend = sol.original_sol.u[end] dxdt = sol.original_sol(tend, Val{1}) diff --git a/test/NavierStokes/dfg_cylinder.jl b/test/NavierStokes/dfg_cylinder.jl index 2ec54d07..8cfb6d76 100644 --- a/test/NavierStokes/dfg_cylinder.jl +++ b/test/NavierStokes/dfg_cylinder.jl @@ -10,6 +10,8 @@ if FiniteElementMethod.MESH_PDEBASE r = dfg_solve(; h, hc) @info "DFG 2D-1" r.ndofs r.build_s r.solve_s r.coefficients @test SciMLBase.successful_retcode(r.sol) + stopped = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, maxiters = 3) + @test_throws "the DFG solve stopped at t = " check_solved(stopped) c = r.coefficients for k in (:cD, :cL, :Δp) lo, hi = DFG_2D1_BANDS[k] From d0f62db2f11191cc8e8b678089e3e065f990417d Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:06:20 +0000 Subject: [PATCH 15/62] Reject derivatives of a dependent variable at fixed arguments Codex round 2: _gradkey matched a field by function name only, so Differential(y)(u(0, y)) was taken as the gradient of u(x, y) and evaluated at the current x, both as a key and inside an expression. A gradient key now requires the canonical dependent variable, and an expression reports the fixed arguments with its documented message. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 14 +++++++++++--- test/Solution/solution.jl | 6 ++++++ test/shared/frontend_tests/observed.jl | 4 ++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/solution.jl b/src/solution.jl index 0c0e4ea2..7ec9c770 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -287,7 +287,7 @@ function _gradkey(md, s) D.order == 1 || return nothing inner = only(SymbolicUtils.arguments(s)) f = _fieldinfo(md, inner) - (f === nothing || _piece_arg(inner) !== nothing) && return nothing + (f === nothing || !isequal(inner, Symbolics.unwrap(f.dv))) && return nothing d = findfirst(x -> isequal(Symbolics.unwrap(x), Symbolics.unwrap(D.x)), md.x̄) return d === nothing ? nothing : (f, d) end @@ -439,6 +439,12 @@ function _observed_error(dv, why) throw(ArgumentError("cannot evaluate the expression $dv on this solution: $why")) end +function _check_field_call(dv, ex, f::FieldInfo) + isequal(ex, Symbolics.unwrap(f.dv)) || + _observed_error(dv, "$ex fixes arguments of $(f.dv); write the dependent variable as $(f.dv)") + return nothing +end + # Adds the leaves of `ex` to `terms` as `term => kind`, with kind `:field`, `:time` or `:coord`, # and the value of each parameter to `params`. function _observed_leaves!(terms, params, A, dv, ex) @@ -452,12 +458,14 @@ function _observed_leaves!(terms, params, A, dv, ex) elseif _gradkey(md, ex) !== nothing terms[ex] = :field elseif SymbolicUtils.iscall(ex) && SymbolicUtils.operation(ex) isa Symbolics.Differential + inner = Symbolics.unwrap(only(SymbolicUtils.arguments(ex))) + f = _fieldinfo(md, inner) + f === nothing || _piece_arg(inner) !== nothing || _check_field_call(dv, inner, f) _observed_error(dv, "$ex is not a first spatial derivative of a dependent variable, the only derivatives an expression accepts") elseif (f = _fieldinfo(md, ex)) !== nothing _piece_arg(ex) === nothing || _observed_error(dv, "it contains the trace $ex; an expression is evaluated at every vertex, so write $(f.dv) instead") - isequal(ex, Symbolics.unwrap(f.dv)) || - _observed_error(dv, "$ex fixes arguments of $(f.dv); write the dependent variable as $(f.dv)") + _check_field_call(dv, ex, f) terms[ex] = :field elseif SymbolicUtils.issym(ex) || SymbolicUtils.issym(SymbolicUtils.operation(ex)) # The front end requires a numeric value for every parameter of the PDESystem. diff --git a/test/Solution/solution.jl b/test/Solution/solution.jl index 6af710db..85aaa746 100644 --- a/test/Solution/solution.jl +++ b/test/Solution/solution.jl @@ -189,6 +189,12 @@ end @test sol[2U + Differential(x)(U)] ≈ 1 .- 2 .* sol[x] atol = 1.0e-10 @test sol(0.3, 0.6; dv = U * y) ≈ 0.7 * 0.6 atol = 1.0e-12 @test sol(Γ; dv = U + y) ≈ 1 .+ sol[y][piece_nodes(sol, Γ)] atol = 1.0e-12 + fixed = Differential(y)(u(0, y)) + 1 + msg = ArgumentError("cannot evaluate the expression $fixed on this solution: $(u(0, y)) fixes arguments of u(x, y); write the dependent variable as u(x, y)") + @test_throws msg sol[fixed] + @test_throws msg sol(0.3, 0.6; dv = fixed) + @test_throws ArgumentError sol[Differential(y)(u(0, y))] + @test_throws ArgumentError sol(0.3, 0.6; dv = Differential(y)(u(0, y))) end @testset "Points missed by Ferrite's nearest-node search" begin diff --git a/test/shared/frontend_tests/observed.jl b/test/shared/frontend_tests/observed.jl index 20781479..8274d5ca 100644 --- a/test/shared/frontend_tests/observed.jl +++ b/test/shared/frontend_tests/observed.jl @@ -86,6 +86,7 @@ observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on t Dx(Dx(U)) + 1 => derivative(Dx(Dx(U))), 2Dt(U) => derivative(Dt(U)), u(t, 0, y) + 1 => "$(u(t, 0, y)) fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)", + Dy(u(t, 0, y)) + 1 => "$(u(t, 0, y)) fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)", ] for (ex, why) in cases @test_throws observed_error(ex, why) sol[ex] @@ -93,6 +94,9 @@ observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on t end # A derivative key that is not an expression keeps the key error. @test occursin("first", errmsg(() -> sol[Dx(Dx(U))])) + # A derivative of a dependent variable at fixed arguments is not a gradient key either. + @test occursin("is not a key of this solution", errmsg(() -> sol[Dy(u(t, 0, y))])) + @test occursin("is not a dependent variable or a first spatial derivative", errmsg(() -> sol(0.5, 0.3, 0.2; dv = Dy(u(t, 0, y))))) end @testset "two fields" begin From 2513c032a3d880e5880a8ba4e4ef921103b0f7ca Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:10:50 +0000 Subject: [PATCH 16/62] Evaluate the nonlinear operator on Dual states and per concurrent call The default initializer (BrownFullBasicInit with a ForwardDiff NewtonRaphson) differentiates the DAE residual, so an inconsistent u0 (for example a remade Dirichlet value) passed Dual vectors into the Float64 load assembly and the NonlinearOperator element scratch and failed with a MethodError. The load is now assembled in Float64 for a Dual residual, and N's partials are pushed through the analytic tangent, J_N(value(u)) * partials(u). Remakes of one problem share the FEMNonlinear parameter, whose operator buffers, Ferrite values objects and Jacobian were mutated by every evaluation, so concurrent solves corrupted each other (final states off by up to 4.0 on a 16x16 grid with two threads). Each evaluation now borrows an independent copy of the operator from a lock-guarded pool on the FEMNonlinear; the template operator is never evaluated. Residual time is unchanged (79 us before, 76-77 us after, n = 289) and the Jacobian is faster (149 us to 77 us) since prescribed rows are skipped in the same pass that adds the entries. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/frontend.jl | 8 --- src/numeric_dae.jl | 81 ++++++++++++++++++------- src/operators.jl | 13 ++++ test/shared/frontend_tests/nonlinear.jl | 28 +++++++++ 4 files changed, 100 insertions(+), 30 deletions(-) diff --git a/src/frontend.jl b/src/frontend.jl index 4cb3ecf1..9f1353db 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -207,14 +207,6 @@ function assemble_sources!(F, ctx::AssemblyContext, kernels, p, t) return F end -# `reinit!` mutates CellValues and FacetValues, so each load evaluation gets its own copies and -# concurrent solves of one problem's remakes share no mutable state. -function _fresh_values(ctx::AssemblyContext{NF, DH, CV, FV}) where {NF, DH, CV, FV} - return AssemblyContext{NF, DH, CV, FV}( - ctx.dh, ctx.fields, map(copy, ctx.cellvalues), map(copy, ctx.facetvalues), ctx.facetsets, ctx.facetcells - ) -end - function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) kernels = emit_kernels(wf) timedep = [term.kind === :source && term.timedep for term in vcat(wf.volume, wf.facet)] diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index 38d0ba4b..a013e27e 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -50,6 +50,10 @@ function load!(out, F::FEMLoad, t) return out end +# ForwardDiff residuals, as from the default initializer's NewtonRaphson: the load does not depend on the state +# and is assembled in `Float64`. +load!(out::AbstractVector{<:ForwardDiff.Dual}, F::FEMLoad, t) = (out .= load!(zeros(length(out)), F, t)) + function dirichlet_values!(out, F::FEMLoad, t) g = F.values if g isa Union{Number, AbstractVector} @@ -91,31 +95,69 @@ Opaque wrapper for the nonlinear part `N(u, t)` of `M du + K u + N(u, t) = F(t)` non-tunable `System` parameter like [`FEMOp`](@ref): `op` is a [`NonlinearOperator`](@ref) and `p` the parameter values its kernels are evaluated with. [`FEMOperators`](@ref) marks the prescribed dofs, whose rows of `N` and of its Jacobian are then zero. `op` is untyped so that -the parameter has one concrete type; each call dispatches on it once. The operator's buffers -are shared by every problem holding this wrapper (remakes, ensembles), so those problems must -not be solved concurrently. +the parameter has one concrete type; each call dispatches on it once. `op` itself is never +evaluated: each evaluation borrows a copy with its own buffers and values objects from a pool, +so problems sharing this wrapper (remakes, ensembles) can be solved concurrently. """ struct FEMNonlinear op::Any p::Vector{Float64} prescribed::BitVector + pool::Vector{Any} + lock::ReentrantLock end -FEMNonlinear(op, p) = FEMNonlinear(op, collect(Float64, p), falses(0)) +FEMNonlinear(op, p, prescribed = falses(0)) = FEMNonlinear(op, collect(Float64, p), prescribed, Any[], ReentrantLock()) Base.show(io::IO, ::FEMNonlinear) = print(io, "FEMNonlinear") -function nonlinear_residual!(r, N::FEMNonlinear, u, t) - residual!(r, N.op, u, N.p, t) - r[N.prescribed] .= 0 - return r +# `f(op)` with an operator no other running call holds; the pool grows to the number of concurrent calls. +function with_operator(f, N::FEMNonlinear) + op = @lock N.lock isempty(N.pool) ? nothing : pop!(N.pool) + op === nothing && (op = independent_copy(N.op)) + try + return f(op) + finally + @lock N.lock push!(N.pool, op) + end end -function nonlinear_jacobian!(N::FEMNonlinear, u, t) - J = jacobian!(N.op.J, N.op, u, N.p, t) - rows = rowvals(J) - for k in eachindex(rows) - N.prescribed[rows[k]] && (nonzeros(J)[k] = 0) +# `r .+= N(u, t)` outside the prescribed rows. +function add_nonlinear!(r, N::FEMNonlinear, u, t) + return with_operator(N) do op + residual!(op.r, op, u, N.p, t) + for i in eachindex(r) + N.prescribed[i] || (r[i] += op.r[i]) + end + r + end +end + +# ForwardDiff states, as from the default initializer's NewtonRaphson: the partials are pushed through the +# analytic tangent, `∂N(u) = J_N(value(u)) ∂u`, since the element buffers hold `Float64`. +function add_nonlinear!(r, N::FEMNonlinear, u::AbstractVector{ForwardDiff.Dual{T, Float64, P}}, t) where {T, P} + du = [ForwardDiff.partials(x, k) for x in u, k in 1:P] + return with_operator(N) do op + J = jacobian!(op.J, op, ForwardDiff.value.(u), N.p, t) + dr = J * du + for i in eachindex(r) + N.prescribed[i] || (r[i] += ForwardDiff.Dual{T}(op.r[i], ForwardDiff.Partials(ntuple(k -> dr[i, k], Val(P))))) + end + r + end +end + +nonlinear_residual!(r, N::FEMNonlinear, u, t) = add_nonlinear!(fill!(r, 0), N, u, t) + +# `nonzeros(J) .+= nonzeros(∂N/∂u)` outside the prescribed rows; `J` must have the pattern of `N`'s Jacobian. +function add_nonlinear_jacobian!(J, N::FEMNonlinear, u, t) + return with_operator(N) do op + JN = jacobian!(op.J, op, u, N.p, t) + check_pattern(J, JN, "Nop") + rows, vals, out = rowvals(JN), nonzeros(JN), nonzeros(J) + for k in eachindex(rows) + N.prescribed[rows[k]] || (out[k] += vals[k]) + end + J end - return J end # `fem_nonlinear(op, rows, t, x)` is rows `rows` of `N(x, t)`, with `x` the whole state built from the @@ -360,7 +402,6 @@ function numeric_dae_problem( check_assembled = assembled_parameter_check(sys, parameters) getM, getK, getF = getp(sys, sys.Mop), getp(sys, sys.Kop), getp(sys, sys.Fop) getN = ops.nonlinear === nothing ? Returns(nothing) : getp(sys, sys.Nop) - nbuf = zeros(length(u0)) function residual!(res, du, u, p, t) check_assembled(p) load!(res, getF(p), t) @@ -368,10 +409,10 @@ function numeric_dae_problem( mul!(res, getM(p).A, du, true, true) mul!(res, getK(p).A, u, true, true) N = getN(p) - N === nothing || (res .+= nonlinear_residual!(nbuf, N, u, t)) + N === nothing || add_nonlinear!(res, N, u, t) return nothing end - # The Dirichlet rows of K + γM are already e_d and those of N's Jacobian zero, so the + # The Dirichlet rows of K + γM are already e_d and N's Jacobian skips them, so the # stored values are added as they are. function jac!(J, du, u, p, γ, t) check_assembled(p) @@ -380,11 +421,7 @@ function numeric_dae_problem( check_pattern(J, Mp, "Mop") nonzeros(J) .= nonzeros(Kp) .+ γ .* nonzeros(Mp) N = getN(p) - if N !== nothing - JN = nonlinear_jacobian!(N, u, t) - check_pattern(J, JN, "Nop") - nonzeros(J) .+= nonzeros(JN) - end + N === nothing || add_nonlinear_jacobian!(J, N, u, t) return nothing end u0 = collect(u0) diff --git a/src/operators.jl b/src/operators.jl index 3e534581..f1f5dddc 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -60,6 +60,19 @@ end (op::NonlinearOperator)(r, u, p, t) = residual!(r, op, u, p, t) +# `reinit!` mutates CellValues and FacetValues, so each load evaluation gets its own copies and +# concurrent solves of one problem's remakes share no mutable state. +function _fresh_values(ctx::AssemblyContext{NF, DH, CV, FV}) where {NF, DH, CV, FV} + return AssemblyContext{NF, DH, CV, FV}( + ctx.dh, ctx.fields, map(copy, ctx.cellvalues), map(copy, ctx.facetvalues), ctx.facetsets, ctx.facetcells + ) +end + +# A copy of `op` that shares no mutable state with it: new buffers, Jacobian and values objects. +function independent_copy(op::NonlinearOperator) + return NonlinearOperator(_fresh_values(op.ctx), op.volume, op.groups, zero(op.r), copy(op.J), zero(op.Je), zero(op.re), zero(op.u_elem)) +end + const LINEAR_TARGET = (mass = :M, bilinear = :K, source = :F) """ diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index 4a94d8ed..a712bf85 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -113,6 +113,34 @@ end @test r[dofs] ≈ rng_u[dofs] - g atol = 1.0e-14 end + @testset "inconsistent Dirichlet u0 through the default initializer" begin + # BrownFullBasicInit's NewtonRaphson differentiates the residual with ForwardDiff, so the load and N(u) + # see Dual states; the time-dependent source exercises the load path too. + Ω = square() + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + (1 + x + 2y) - 10 * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + dofs = prob.problem_type.space.ch.prescribed_dofs + u0 = copy(prob.u0) + u0[dofs] .+= 0.5 + sol = solve(remake(prob; u0), EXACT_ROWS; abstol = 1.0e-10, reltol = 1.0e-10) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "remakes solved concurrently match serial solves" begin + # Every evaluation borrows its own copy of the nonlinear operator's buffers and values objects. + Ω = MeshDomain(rectangle_grid(Triangle, (16, 16))) + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + (1 + x + 2y) - 10 * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + probs = [remake(prob; u0 = s * prob.u0) for s in (1.0, 1.3, 0.7)] + final(q) = solve(q, EXACT_ROWS; abstol = 1.0e-8, reltol = 1.0e-8).original_sol.u[end] + serial = final.(probs) + @test serial[1] != serial[2] + concurrent = fetch.([Threads.@spawn final(q) for q in probs]) + @test concurrent == serial + Threads.nthreads() > 1 || @info "the remakes were solved on one thread, so this test cannot see a race; run with JULIA_NUM_THREADS > 1" + end + @testset "a parameter changed by remake is rejected, not ignored" begin # The operators, the nonlinear one included, hold the values they were assembled with (spec §8.3). Ω = square() From ddb4ac157e20054808ebe3eefd6bf9dd756ebdc7 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:15:39 +0000 Subject: [PATCH 17/62] Time one discrete problem on both sides of benchmark (d); fail on early stops and Newton non-convergence Codex round 1. The Ferrite baseline gains outlet = :pressure (strong pressure gradient, p = 0 on the outlet), so the timed comparison solves the PDESystem example's discrete problem on both sides; the tutorial as published is timed for reference only, and the ratio is recorded only when the velocities agree to 1%. check_solved also rejects a solve that ends before its final time with a success code (Terminated); the hand-written reference solver raises when Newton does not converge. Both error paths are tested. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- benchmarks/navier_stokes/README.md | 10 ++-- .../navier_stokes/ferrite_ns_vs_diffeq.jl | 23 +++++--- benchmarks/navier_stokes/ns_cylinder.jl | 52 ++++++++++++------- examples/dfg_cylinder/dfg_cylinder.jl | 10 ++-- examples/dfg_cylinder/reference.jl | 7 +-- test/NavierStokes/dfg_cylinder.jl | 9 +++- 6 files changed, 74 insertions(+), 37 deletions(-) diff --git a/benchmarks/navier_stokes/README.md b/benchmarks/navier_stokes/README.md index 1cf664c4..c7b5f040 100644 --- a/benchmarks/navier_stokes/README.md +++ b/benchmarks/navier_stokes/README.md @@ -5,9 +5,13 @@ 1. Wall-clock against Ferrite's `ns_vs_diffeq.jl` tutorial (`ferrite_ns_vs_diffeq.jl`, the tutorial's code with the changes listed at its top) on the same mesh, `dfg_channel_grid(h = 0.05, length = 1.1)`, with the tutorial's settings: ν = 1e-3, inflow ramp `min(1.5t, 1.5)` (Re = 100), T = 6, abstol 1e-4, reltol 1e-5, - output every 0.1. Ferrite runs Rodas5P on its mass-matrix ODE; FiniteElementMethod discretizes the PDESystem - of `examples/dfg_cylinder` to a DAEProblem and runs DFBDF. The two velocity fields are compared at t = 1 and - t = T at 20 points behind the cylinder. + output every 0.1. Both sides solve one discrete problem: the outlet treatment of the PDESystem example (∇p + tested strongly, p = 0 on the outlet), which Ferrite's side gets from `outlet = :pressure`. Ferrite runs Rodas5P + on its mass-matrix ODE; FiniteElementMethod discretizes the PDESystem of `examples/dfg_cylinder` to a + DAEProblem and runs DFBDF. The horizontal velocities are compared at t = 1 and t = T at 20 points behind the + cylinder, and the time ratio is recorded only if they agree to 1% of the largest velocity there. The tutorial as + published (do-nothing outlet) is timed too, for reference. The time steppers and their error norms differ, so + the times are comparable in magnitude, not a measure of which package is faster. 2. DFG 2D-1 (Re = 20) drag, lift and pressure difference on the full channel at the meshes of `BENCHMARK_NS_MESHES` (`h:hc` pairs, default `0.04:0.0025,0.02:0.00333,0.01:0.00167`, up to 149 094 unknowns), with their errors against the DFG reference values. diff --git a/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl b/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl index f9233ddf..80e32ddc 100644 --- a/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl +++ b/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl @@ -8,7 +8,8 @@ # (Q2Q1 Taylor–Hood with a vector velocity, ν = 1e-3, the inflow ramp `min(1.5t, 1.5)`, Rodas5P with the Ferrite # Dirichlet limiter, `abstol = 1e-4`, `reltol = 1e-5`, `dt = 1e-3`, the free-dof error norm) is the tutorial's. # -# Prints and returns `(; seconds, ndofs, steps, ...)`; `ns_cylinder.jl` calls it and writes the results file. +# `outlet = :pressure` switches to the outlet treatment of the PDESystem example, so that the timed comparison in +# `ns_cylinder.jl` solves one discrete problem on both sides. Prints and returns `(; seconds, ndofs, steps, ...)`; `ns_cylinder.jl` calls it and writes the results file. using Ferrite, SparseArrays, BlockArrays, LinearAlgebra using DiffEqBase using OrdinaryDiffEqRosenbrock: Rodas5P @@ -70,7 +71,7 @@ function assemble_mass_matrix(cv::MultiFieldCellValues, M::SparseMatrixCSC, dh:: return M end -function assemble_stokes_matrix(cv::MultiFieldCellValues, ν, K::SparseMatrixCSC, dh::DofHandler) +function assemble_stokes_matrix(cv::MultiFieldCellValues, ν, K::SparseMatrixCSC, dh::DofHandler; outlet = :do_nothing) n_basefuncs_v = getnbasefunctions(cv.v) n_basefuncs_p = getnbasefunctions(cv.p) n_basefuncs = n_basefuncs_v + n_basefuncs_p @@ -93,7 +94,9 @@ function assemble_stokes_matrix(cv::MultiFieldCellValues, ν, K::SparseMatrixCSC ψ = shape_value(cv.p, q_point, j) for i in 1:n_basefuncs_v divφ = shape_divergence(cv.v, q_point, i) - Kₑ[BlockIndex((v▄, p▄), (i, j))] += (divφ * ψ) * dΩ + # `outlet = :pressure` keeps ∇p strong, as the PDESystem example does (see ferrite_ns_vs_diffeq). + Kₑ[BlockIndex((v▄, p▄), (i, j))] += outlet === :pressure ? + -(shape_gradient(cv.p, q_point, j) ⋅ shape_value(cv.v, q_point, i)) * dΩ : (divφ * ψ) * dΩ Kₑ[BlockIndex((p▄, v▄), (j, i))] += (ψ * divφ) * dΩ end end @@ -198,12 +201,19 @@ end (fe_norm::FreeDofErrorNorm)(u::AbstractArray, t) = DiffEqBase.ODE_DEFAULT_NORM(u[fe_norm.ch.free_dofs], t) """ - ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1e-3, vmax = 1.5, Δt_save = 0.1) + ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1e-3, vmax = 1.5, Δt_save = 0.1, outlet = :do_nothing) Ferrite's tutorial problem on `grid` (facet sets `"inlet"`, `"outlet"`, `"walls"`, `"cylinder"`): build the operators and integrate to `T`. Returns the solution, the `DofHandler` and the setup and solve times. + +`outlet = :do_nothing` is the tutorial as published: the pressure gradient integrated by parts, so the outlet +carries the traction-free condition `ν∂ₙu − p n = 0`. `outlet = :pressure` is the discrete problem of the +PDESystem example instead: `∇p` tested strongly (`ν∂ₙu = 0` at the outlet) and `p = 0` imposed on the outlet +through the constraint handler, which drops the continuity equations of the outlet pressure nodes as the +example's Dirichlet rows do. """ -function ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1.0e-3, vmax = 1.5, Δt_save = 0.1) +function ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1.0e-3, vmax = 1.5, Δt_save = 0.1, outlet = :do_nothing) + outlet in (:do_nothing, :pressure) || throw(ArgumentError("outlet must be :do_nothing or :pressure, got $(repr(outlet))")) setup = @elapsed begin dim = 2 ip_v = Lagrange{RefQuadrilateral, 2}()^dim @@ -221,10 +231,11 @@ function ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1.0e-3, vmax = 1.5, Δt_save = vᵢₙ(t) = min(t * vmax, vmax) parabolic_inflow_profile(x, t) = Vec((4 * vᵢₙ(t) * x[2] * (0.41 - x[2]) / 0.41^2, 0.0)) add!(ch, Dirichlet(:v, getfacetset(grid, "inlet"), parabolic_inflow_profile, [1, 2])) + outlet === :pressure && add!(ch, Dirichlet(:p, getfacetset(grid, "outlet"), (x, t) -> 0.0)) close!(ch) update!(ch, 0.0) M = assemble_mass_matrix(cellvalues, allocate_matrix(dh), dh) - K = assemble_stokes_matrix(cellvalues, ν, allocate_matrix(dh), dh) + K = assemble_stokes_matrix(cellvalues, ν, allocate_matrix(dh), dh; outlet) u₀ = zeros(ndofs(dh)) apply!(u₀, ch) jac_sparsity = sparse(K) diff --git a/benchmarks/navier_stokes/ns_cylinder.jl b/benchmarks/navier_stokes/ns_cylinder.jl index fb7d490a..71de1287 100644 --- a/benchmarks/navier_stokes/ns_cylinder.jl +++ b/benchmarks/navier_stokes/ns_cylinder.jl @@ -4,14 +4,18 @@ # julia --project=benchmarks/navier_stokes -e 'using Pkg; Pkg.instantiate()' # julia --project=benchmarks/navier_stokes benchmarks/navier_stokes/ns_cylinder.jl # -# Part 1, wall-clock: the tutorial's problem (ν = 1e-3, peak inflow min(1.5t, 1.5), so Re = 100 once ramped, to +# Part 1, wall-clock: one discrete problem on both sides, the tutorial's (ν = 1e-3, peak inflow min(1.5t, 1.5), so Re = 100 once ramped, to # T = 6, abstol = 1e-4, reltol = 1e-5, output every 0.1) on `dfg_channel_grid(h = 0.05, length = 1.1)`, the -# tutorial's shortened channel. Ferrite: the tutorial's Rodas5P on the mass-matrix ODE. FiniteElementMethod: the +# tutorial's shortened channel, with the outlet treatment of the PDESystem example on both sides (∇p strong, +# p = 0 on the outlet; Ferrite's side is `ferrite_ns_vs_diffeq(...; outlet = :pressure)`). The tutorial as +# published (do-nothing outlet) is timed as well, for reference only. Ferrite: the tutorial's Rodas5P on the +# mass-matrix ODE. FiniteElementMethod: the # PDESystem of `examples/dfg_cylinder` with the same ramp, discretized to a DAEProblem and solved with DFBDF, the # pressure and Dirichlet rows out of error control (the tutorial's norm leaves out the Dirichlet dofs). Both # are timed after a warm-up solve to t = 0.05 in the same process, so neither includes compilation; the # discretization time of the PDESystem is reported separately. -# The two solutions are compared at t = 1 (end of the ramp) and t = T at 20 points behind the cylinder. +# The two solutions are compared at t = 1 (end of the ramp) and t = T at 20 points behind the cylinder, and the +# timing ratio is recorded only if they agree to AGREEMENT_TOL relative to the largest velocity there. # Part 2, accuracy: 2D-1 (Re = 20) on the full channel at the meshes `BENCHMARK_NS_MESHES`, `h:hc` pairs of # `dfg_channel_grid` sizes (default 0.04:0.0025,0.02:0.00333,0.01:0.00167). include(joinpath(@__DIR__, "..", "common.jl")) @@ -29,26 +33,31 @@ function fem_tutorial(grid; T) return (; sol, build_s, solve_s, ndofs = length(prob.u0), steps = sol.original_sol.stats.naccept + sol.original_sol.stats.nreject) end +# Largest difference of the horizontal velocity at 20 points behind the cylinder, relative to its largest value. +function velocity_difference(grid, ferrite, fem, τ) + points = [Ferrite.Vec(x_, y_) for x_ in range(0.4, 1.0; length = 5) for y_ in range(0.05, 0.36; length = 4)] + ph = Ferrite.PointEvalHandler(grid, points) + u_ferrite = first.(Ferrite.evaluate_at_points(ph, ferrite.dh, ferrite.sol(τ), :v)) + u_fem = Ferrite.evaluate_at_points(ph, fem.sol.disc_data.space.dh, fem.sol.original_sol(τ), :u) + return maximum(abs, u_ferrite - u_fem) / maximum(abs, u_ferrite) +end + +# The timing ratio is published only when both sides solved the same problem to comparable accuracy. +const AGREEMENT_TOL = 1.0e-2 + function run() grid = dfg_channel_grid(; h = 0.05, length = 1.1) - ferrite_ns_vs_diffeq(grid; T = 0.05) - ferrite = ferrite_ns_vs_diffeq(grid; T = T_END) + ferrite_ns_vs_diffeq(grid; T = 0.05, outlet = :pressure) + ferrite = ferrite_ns_vs_diffeq(grid; T = T_END, outlet = :pressure) + published = ferrite_ns_vs_diffeq(grid; T = T_END) fem_tutorial(grid; T = 0.05) fem = fem_tutorial(grid; T = T_END) - # Horizontal velocity of both solutions at points behind the cylinder. - points = [Ferrite.Vec(x_, y_) for x_ in range(0.4, 1.0; length = 5) for y_ in range(0.05, 0.36; length = 4)] - ph = Ferrite.PointEvalHandler(grid, points) - agreement = Dict{String, Any}() - for τ in (1.0, T_END) - u_ferrite = first.(Ferrite.evaluate_at_points(ph, ferrite.dh, ferrite.sol(τ), :v)) - u_fem = Ferrite.evaluate_at_points(ph, fem.sol.disc_data.space.dh, fem.sol.original_sol(τ), :u) - agreement["max_abs_u_difference_t$(τ)"] = maximum(abs, u_ferrite - u_fem) - agreement["max_abs_u_t$(τ)"] = maximum(abs, u_ferrite) - end - println("velocity agreement: ", agreement) + agreement = Dict{String, Any}("t$τ" => velocity_difference(grid, ferrite, fem, τ) for τ in (1.0, T_END)) + comparable = all(<=(AGREEMENT_TOL), values(agreement)) + println("relative velocity difference: ", agreement, comparable ? "" : " (above $AGREEMENT_TOL: no ratio published)") @printf( - "tutorial problem to T = %g: Ferrite %.1f s (%d dofs, %d steps, %s); FiniteElementMethod %.1f s (%d dofs, %d steps, %s), discretization %.1f s\n", - T_END, ferrite.solve_s, ferrite.ndofs, ferrite.steps, ferrite.sol.retcode, fem.solve_s, fem.ndofs, fem.steps, fem.sol.retcode, fem.build_s + "tutorial problem to T = %g, same outlet treatment: Ferrite %.1f s (%d dofs, %d steps, %s); FiniteElementMethod %.1f s (%d dofs, %d steps, %s), discretization %.1f s; tutorial as published %.1f s\n", + T_END, ferrite.solve_s, ferrite.ndofs, ferrite.steps, ferrite.sol.retcode, fem.solve_s, fem.ndofs, fem.steps, fem.sol.retcode, fem.build_s, published.solve_s ) rows = Dict{String, Any}[] @@ -77,8 +86,11 @@ function run() "ferrite_s" => ferrite.solve_s, "ferrite_ndofs" => ferrite.ndofs, "ferrite_steps" => ferrite.steps, "fem_solver" => "DFBDF on the DAEProblem of the PDESystem", "fem_s" => fem.solve_s, "fem_ndofs" => fem.ndofs, "fem_steps" => fem.steps, "fem_discretize_s" => fem.build_s, - "ratio" => fem.solve_s / ferrite.solve_s, - "agreement" => agreement, + "ferrite_published_s" => published.solve_s, + "outlet" => "both sides: ∇p tested strongly, p = 0 on the outlet (ferrite_ns_vs_diffeq outlet = :pressure); ferrite_published_s is the tutorial's do-nothing outlet", + "relative_velocity_difference" => agreement, + "agreement_tol" => AGREEMENT_TOL, + "ratio" => comparable ? fem.solve_s / ferrite.solve_s : "not published: velocity difference above agreement_tol", ), "dfg_2d1" => Dict( "reference" => Dict("cD" => DFG_2D1.cD, "cL" => DFG_2D1.cL, "dp" => DFG_2D1.Δp), diff --git a/examples/dfg_cylinder/dfg_cylinder.jl b/examples/dfg_cylinder/dfg_cylinder.jl index 1a0a0330..6f3b7f0b 100644 --- a/examples/dfg_cylinder/dfg_cylinder.jl +++ b/examples/dfg_cylinder/dfg_cylinder.jl @@ -84,11 +84,13 @@ differential_abstol(prob, abstol) = [d ? abstol : 1.0e8 for d in prob.differenti # for this index-2 system took tens of GB: a singular matrix now fails the step, and `check_solved` raises. const DFG_ALG = DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()) -"Raise unless `sol` reached its final time; a DAE solve that stopped early must not report coefficients." +"Raise unless `sol` succeeded and reached its final time (a callback can stop it early with `Terminated`, a success code); a DAE solve that stopped early must not report coefficients." function check_solved(sol) - SciMLBase.successful_retcode(sol) || - error("the DFG solve stopped at t = $(sol.t[end]) with retcode $(sol.retcode); with the pressure in the error control or a singular Newton matrix DFBDF cuts its step to nothing") - return sol + tend = last(sol.original_sol.prob.tspan) + SciMLBase.successful_retcode(sol) && sol.t[end] == tend && return sol + return error( + "the DFG solve stopped at t = $(sol.t[end]) of $tend with retcode $(sol.retcode); with the pressure in the error control or a singular Newton matrix DFBDF cuts its step to nothing" + ) end """ diff --git a/examples/dfg_cylinder/reference.jl b/examples/dfg_cylinder/reference.jl index 15810bb3..8bb5e53a 100644 --- a/examples/dfg_cylinder/reference.jl +++ b/examples/dfg_cylinder/reference.jl @@ -8,7 +8,8 @@ using SparseArrays: SparseMatrixCSC Hand-written Ferrite solution of the steady DFG 2D-1 problem on `grid` (from [`dfg_channel_grid`](@ref)): scalar velocity components `u`, `v` on `Lagrange{RefQuadrilateral, 2}` and pressure `p` on `Lagrange{RefQuadrilateral, 1}`, parabolic inflow of peak `Umax`, no slip on the walls and the cylinder, and the do-nothing condition -`ν ∂ₙu − p n = 0` at the outlet, solved by Newton's method from zero. Returns `(dh, x, iterations)`. +`ν ∂ₙu − p n = 0` at the outlet, solved by Newton's method from zero. Returns `(dh, x, iterations)`, and +raises if the residual norm is not below `tol` after `maxiter` iterations. This is the oracle the PDESystem path is compared with on the same mesh; it uses no FiniteElementMethod code. """ @@ -97,8 +98,8 @@ function dfg_reference_steady(grid; ν = 1.0e-3, Umax = 0.3, tol = 1.0e-10, maxi Ferrite.apply_zero!(J, r, ch) resnorm = norm(r) iterations = it - resnorm < tol && break + resnorm < tol && return dh, x, iterations x .-= J \ r end - return dh, x, iterations + return error("Newton's method did not converge in $maxiter iterations: residual norm $(norm(r)) at the last assembly, tolerance $tol") end diff --git a/test/NavierStokes/dfg_cylinder.jl b/test/NavierStokes/dfg_cylinder.jl index 8cfb6d76..321ce84f 100644 --- a/test/NavierStokes/dfg_cylinder.jl +++ b/test/NavierStokes/dfg_cylinder.jl @@ -12,6 +12,11 @@ if FiniteElementMethod.MESH_PDEBASE @test SciMLBase.successful_retcode(r.sol) stopped = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, maxiters = 3) @test_throws "the DFG solve stopped at t = " check_solved(stopped) + # Terminated is a success code, so the final time is checked too. + halt = SciMLBase.DiscreteCallback((u, t, integrator) -> t > 1.0, SciMLBase.terminate!) + terminated = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, callback = halt) + @test terminated.retcode == SciMLBase.ReturnCode.Terminated + @test_throws "the DFG solve stopped at t = " check_solved(terminated) c = r.coefficients for k in (:cD, :cL, :Δp) lo, hi = DFG_2D1_BANDS[k] @@ -19,7 +24,9 @@ if FiniteElementMethod.MESH_PDEBASE end # The hand-written steady solution on the same mesh: same dof numbering after FieldWise renumbering. - dh_ref, x_ref, _ = dfg_reference_steady(dfg_channel_grid(; h, hc); pressure = :strong) + grid = dfg_channel_grid(; h, hc) + @test_throws "Newton's method did not converge in 1 iterations" dfg_reference_steady(grid; maxiter = 1) + dh_ref, x_ref, _ = dfg_reference_steady(grid; pressure = :strong) ref = dfg_coefficients(dh_ref, x_ref; ν = 1.0e-3, Umean = 0.2) for k in (:cD, :cL, :Δp) @test c[k] ≈ ref[k] rtol = 1.0e-5 From da356a481b4a7035799cfdd9cf179abf7169f057 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:17:18 +0000 Subject: [PATCH 18/62] Set the abstol of algebraic rows of index-2 systems in FEMDiscretization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Taylor–Hood Stokes and Navier–Stokes need a large abstol on the algebraic rows or DFBDF drives dt below eps near t0 (and LinearSolve may fall back to sparse QR on the singular Newton matrix). The new algebraic_abstol keyword (:auto by default) gives such systems an abstol vector, 1e8 on the algebraic rows, so user code no longer writes it; other systems are unchanged, and an abstol passed to solve still wins. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 29 ++++++-- src/discretization.jl | 20 +++++- src/frontend.jl | 26 ++++++- test/shared/frontend_tests/end_to_end.jl | 12 ++++ test/shared/frontend_tests/errors.jl | 5 ++ test/shared/frontend_tests/multifield.jl | 86 +++++++++++++++++------- 6 files changed, 141 insertions(+), 37 deletions(-) diff --git a/docs/discretization.md b/docs/discretization.md index 581a4edd..0ac7c074 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -40,20 +40,35 @@ small piece (a single facet set), or leave an outflow piece with the natural con The pressure is absent from its own rows, so the DAE has index 2. Two things make `DFBDF` step it: start from a velocity that is discretely divergence free (zero, with zero Dirichlet data at the initial time) and a pressure initial condition, and leave the algebraic rows out of the -error control with a large `abstol` on them, since the pressure's local error does not shrink -with the step: +error control with a large absolute tolerance on them, since the pressure's local error does +not shrink with the step. `FEMDiscretization` does the second by default: with +`algebraic_abstol = :auto` it detects an algebraic field absent from its own equation and gives +the problem the `abstol` vector `1e8` on every algebraic row (the algebraic fields and the +Dirichlet rows of all fields) and `1e-6` elsewhere: ```julia -prob = discretize(pdesys, disc) -abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars] -sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0)); abstol, reltol = 1.0e-8) +prob = discretize(pdesys, disc) # prob.kwargs[:abstol] is the vector +sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0)); reltol = 1.0e-8) ``` -Without the `abstol`, the step size collapses near the initial time (`dt` below `eps` at -`t ≈ 1e-10` on a 16 × 16 Taylor–Hood mesh). When the linear solver then reports the Newton +A number `abstol` given to `FEMDiscretization` or `discretize` sets the differential rows' +entries, as in `discretize(pdesys, disc; abstol = 1.0e-8)`; an array is used as it is. +`algebraic_abstol = 1.0e4` sets another value on the algebraic rows, of any system, and +`algebraic_abstol = nothing` sets none. An `abstol` passed to `solve` replaces the whole vector +(SciMLBase merges the problem's keywords first and the `solve` keywords over them), so +`solve(prob, alg; abstol = 1.0e-8)` puts the algebraic rows back under error control; write the +vector by hand in that case, `abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars]`. +Systems without an index-2 field, such as `0 ~ Δv + u` paired with `v`, get no `abstol`. + +Without the large tolerance, the step size collapses near the initial time (`dt` below `eps` +at `t ≈ 1e-10` on a 16 × 16 Taylor–Hood mesh). When the linear solver then reports the Newton matrix as singular, LinearSolve falls back to a sparse QR factorization, which can take minutes and tens of gigabytes on a saddle-point system. +`algebraic_abstol` is not in the spec (§7.1, §7.6 list the `FEMDiscretization` keywords +without it): it was added after the Taylor–Hood Stokes and DFG cylinder benchmarks needed the +tolerance in user code every time. + A field can live on part of the mesh: `regions = Dict(w => Region(Ω, :name))` restricts `w` to the cell set `name`, through a Ferrite `SubDofHandler`. Outside its region the field has no dofs, its equation is not assembled, it enters the other equations as zero, and the solution diff --git a/src/discretization.jl b/src/discretization.jl index 61584899..33dcd59f 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -7,7 +7,7 @@ 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, kwargs...) + codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, kwargs...) Finite-element discretization of a `PDESystem` whose spatial domain is the mesh domain `Ω` (of a `Ferrite.Grid`), with time variable `t`. `DAEProblem(pdesys, disc)` assembles the @@ -28,6 +28,17 @@ Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknow - `ibp`: equation (or its index) `=>` `PDEBase.StrongForm` integration-by-parts policy. - `pairing`: equation `=>` dependent variable it is tested with, needed for an equation with no time derivative of its own, such as `0 ~ Dxx(v) + f`. + - `algebraic_abstol`: the absolute tolerance the `DAEProblem` carries for its algebraic rows + (those with `differential_vars` false: algebraic fields and Dirichlet rows), so that they + are left out of the solver's error control. `:auto` sets `1e8` when the system has index + 2, that is when an algebraic field's own unknowns are absent from its equation (the + pressure in `0 ~ Dx(u1) + Dy(u2)`), and nothing otherwise; a positive number sets that + value on the algebraic rows of any system; `nothing` sets nothing. The differential rows get the `abstol` passed to + `FEMDiscretization` or `DAEProblem` if it is a number, else OrdinaryDiffEq's default + `1e-6`; an array `abstol` passed there is used as it is. An `abstol` passed to `solve` + replaces the problem's whole vector. This keyword is not in the spec (§7.1, §7.6): without + it, `DFBDF` drives the step size of an index-2 system below `eps` near the initial time, + since the local error of the index-2 unknowns does not shrink with the step. - `codegen = :mtk` and `dirichlet = :eliminate` are reserved for later milestones and raise; remaining keywords are passed to the `DAEProblem`, where a keyword given at the `DAEProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` @@ -58,6 +69,7 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization pairing::Dict{Equation, Any} codegen::Symbol dirichlet::Symbol + algebraic_abstol::Union{Symbol, Nothing, Float64} kwargs::NamedTuple end @@ -79,7 +91,7 @@ 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, kwargs... + dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, kwargs... ) domain.mesh isa Ferrite.Grid || throw(ArgumentError("FEMDiscretization needs a MeshDomain of a Ferrite.Grid, got a mesh of type $(typeof(domain.mesh))")) @@ -94,12 +106,14 @@ function FEMDiscretization( region isa PDEBase.Region && region.parent === domain || throw(ArgumentError("the region of $(_field_op(dv)) must be a Region of the FEMDiscretization's MeshDomain, as Region(Ω, name); got $(repr(region))")) end + algebraic_abstol === :auto || algebraic_abstol === nothing || algebraic_abstol isa Real && algebraic_abstol > 0 || + throw(ArgumentError("algebraic_abstol must be :auto, nothing or a positive number, got $(repr(algebraic_abstol))")) _check_reserved(kwargs) 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, NamedTuple(kwargs) + codegen, dirichlet, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, NamedTuple(kwargs) ) end diff --git a/src/frontend.jl b/src/frontend.jl index cea97d7d..5f55c1bd 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -358,7 +358,8 @@ analytic Jacobian and the `FEMMetadata` as its `problem_type`, so `solve` return `PDETimeSeriesSolution`. Nothing calls `mtkcompile`; anything this milestone cannot discretize raises. Keywords are passed to the `DAEProblem` after `disc.kwargs`, so a keyword given here wins; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, -`name`) are rejected. +`name`) are rejected. The problem carries an `abstol` vector when `disc.algebraic_abstol` +applies (see [`FEMDiscretization`](@ref)). The Dirichlet rows are linear with identity Jacobian rows, so a Newton step with a current Jacobian satisfies them exactly. OrdinaryDiffEq's BDF methods reuse the Jacobian across @@ -369,12 +370,33 @@ size change and holds `u(t, Γ) ~ g(t)` to round-off. function SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) _check_reserved(kwargs) parts = _lower(pdesys, disc) + kwargs = merge(disc.kwargs, values(kwargs)) return numeric_dae_problem( parts.ops, parts.u0, parts.tspan, parts.md; - iv = parts.iv, unknowns = parts.unknowns, name = parts.name, disc.kwargs..., kwargs... + iv = parts.iv, unknowns = parts.unknowns, name = parts.name, kwargs..., + _abstol(disc.algebraic_abstol, parts.ops, get(kwargs, :abstol, nothing))... ) end +# An algebraic field whose own unknowns are absent from its equation (the pressure in the continuity equation) is +# fixed only through the other fields, which makes the DAE index 2. +function _index2(ops::FEMOperators) + free = trues(size(ops.K, 1)) + free[ops.prescribed] .= false + return any(ops.fields) do (_, r) + rows = filter(i -> free[i], r) + !isempty(rows) && !any(ops.differential_vars[rows]) && iszero(ops.K[rows, r]) + end +end + +# The `abstol` keyword of the `DAEProblem` (see `FEMDiscretization`'s `algebraic_abstol`); empty when none is set. +function _abstol(algebraic, ops, abstol) + algebraic === :auto && (algebraic = _index2(ops) ? 1.0e8 : nothing) + (algebraic === nothing || !(abstol isa Union{Nothing, Real})) && return (;) + differential = something(abstol, 1.0e-6) + return (; abstol = [d ? differential : algebraic for d in ops.differential_vars]) +end + SciMLBase.discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) = DAEProblem(pdesys, disc; kwargs...) diff --git a/test/shared/frontend_tests/end_to_end.jl b/test/shared/frontend_tests/end_to_end.jl index 7cfaea55..c6ffa950 100644 --- a/test/shared/frontend_tests/end_to_end.jl +++ b/test/shared/frontend_tests/end_to_end.jl @@ -44,6 +44,16 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test nodal_error(sol, u(t, x, y), uexact) <= tol space = sol.disc_data.space @test !any(prob.differential_vars[space.ch.prescribed_dofs]) + # Not index 2: the default algebraic_abstol = :auto sets no abstol. + @test !haskey(prob.kwargs, :abstol) + # An explicit algebraic_abstol applies to any system: here to the Dirichlet rows, which stay exact. + sol, prob = fem_solve( + [heat_eq], [dirichlet_all(Ω); ic], Ω, (x, y), t, [u(t, x, y)]; algebraic_abstol = 1.0e3, + solve_kwargs = (; reltol = 1.0e-10), abstol = 1.0e-10 + ) + @test prob.kwargs[:abstol] == [d ? 1.0e-10 : 1.0e3 for d in prob.differential_vars] + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, u(t, x, y), uexact) <= tol # The symbolic Dirichlet data agree with the ConstraintHandler, including at corners # shared by two pieces, where the condition added last wins. load = SciMLBase.SymbolicIndexingInterface.getp(prob.f.sys, prob.f.sys.Fop)(prob.p) @@ -204,6 +214,8 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test SciMLBase.successful_retcode(sol) space = sol.disc_data.space @test !any(prob.differential_vars[FiniteElementMethod.field_range(space, :v)]) + # v is algebraic but appears in its own equation (index 1): no abstol is set. + @test !haskey(prob.kwargs, :abstol) @test nodal_error(sol, u(t, x, y), uexact) <= tol @test nodal_error(sol, v(t, x, y), (t_, x_, y_) -> 1 + x_ + 2y_) <= tol end diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index f50b6b39..4acf7feb 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -89,6 +89,11 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @test_throws ArgumentError("dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic") FEMDiscretization( Ω, t; dirichlet = :eliminate ) + for (value, shown) in ((0, "0"), (-1.0e8, "-1.0e8"), (NaN, "NaN"), ("1e8", "\"1e8\""), (:on, ":on"), ([1.0e8], "[1.0e8]")) + @test_throws ArgumentError("algebraic_abstol must be :auto, nothing or a positive number, got $shown") FEMDiscretization( + Ω, t; algebraic_abstol = value + ) + end @named steady = PDESystem( [Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], [] ) diff --git a/test/shared/frontend_tests/multifield.jl b/test/shared/frontend_tests/multifield.jl index 6d5329a8..59ec050b 100644 --- a/test/shared/frontend_tests/multifield.jl +++ b/test/shared/frontend_tests/multifield.jl @@ -52,6 +52,30 @@ end rates(errs) = [log2(errs[i] / errs[i + 1]) for i in 1:(length(errs) - 1)] +# Taylor–Hood Stokes on the unit square: stream function ψ = x²(1 − x)²y²(1 − y)², u = (ψ_y, −ψ_x), which +# vanishes on the boundary, and p = x³ − y³; the source makes (u, p) steady. +const U1, U2, P = u1(t, x, y), u2(t, x, y), p(t, x, y) +const STOKES_ψ = x^2 * (1 - x)^2 * y^2 * (1 - y)^2 +const STOKES_SOLUTION = (expand_derivatives(Dy(STOKES_ψ)), expand_derivatives(-Dx(STOKES_ψ)), x^3 - y^3) +const STOKES_EXACT = map(e -> Symbolics.build_function(e, x, y; expression = Val(false)), STOKES_SOLUTION) +function stokes_problem(ct, n; kw...) + u1s, u2s, ps = STOKES_SOLUTION + f1, f2 = expand_derivatives(-Δ(u1s) + Dx(ps)), expand_derivatives(-Δ(u2s) + Dy(ps)) + continuity = 0 ~ Dx(U1) + Dy(U2) + eqs = [Dt(U1) ~ Δ(U1) - Dx(P) + f1, Dt(U2) ~ Δ(U2) - Dy(P) + f2, continuity] + Ω = MeshDomain(corner_grid(ct, n)) + Γs = boundarypiece.(Ω, (:left, :right, :bottom, :top, :corner)) + bcs = [ + [u1(t, Γ) ~ 0 for Γ in Γs]; [u2(t, Γ) ~ 0 for Γ in Γs]; p(t, Γs[end]) ~ x^3 - y^3; + u1(0, x, y) ~ 0; u2(0, x, y) ~ 0; p(0, x, y) ~ x^3 - y^3 + ] + @named stokes = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x, y], [U1, U2, P], []) + shape = SHAPE[ct] + P2, P1 = Lagrange{shape, 2}(), Lagrange{shape, 1}() + disc = FEMDiscretization(Ω, t; spaces = Dict(u1 => P2, u2 => P2, p => P1), pairing = Dict(continuity => p), kw...) + return discretize(stokes, disc) +end + @testset verbose = true "multi-field front end" begin @testset "unequal orders, $(ct)s: rates p + 1 for both fields" for ct in (Triangle, Quadrilateral) # u in P2/Q2, w in P1/Q1. w's equation reads u but not the reverse, so u keeps its own rate. @@ -87,39 +111,51 @@ rates(errs) = [log2(errs[i] / errs[i + 1]) for i in 1:(length(errs) - 1)] end @testset "Taylor–Hood Stokes, $(ct)s: velocity rate 3, pressure rate 2" for ct in (Triangle, Quadrilateral) - # Stream function ψ = x²(1 − x)²y²(1 − y)², u = (ψ_y, −ψ_x), which vanishes on the boundary, and p = x³ − y³; - # the source makes (u, p) steady. Marched from u = 0 to the steady state (the slowest Stokes mode decays like + # Marched from u = 0 to the steady state (the slowest Stokes mode decays like # e^{−52t}). The continuity rows are algebraic and the pressure is absent from them (index 2): the pressure - # starts from its exact values, is pinned on the one-facet piece "corner", and is left out of the error - # control through a large abstol, without which DFBDF fails at t ≈ 1e-10 on the 16 × 16 meshes. - U1, U2, P = u1(t, x, y), u2(t, x, y), p(t, x, y) - ψ = x^2 * (1 - x)^2 * y^2 * (1 - y)^2 - u1s, u2s, ps = expand_derivatives(Dy(ψ)), expand_derivatives(-Dx(ψ)), x^3 - y^3 - f1, f2 = expand_derivatives(-Δ(u1s) + Dx(ps)), expand_derivatives(-Δ(u2s) + Dy(ps)) - continuity = 0 ~ Dx(U1) + Dy(U2) - eqs = [Dt(U1) ~ Δ(U1) - Dx(P) + f1, Dt(U2) ~ Δ(U2) - Dy(P) + f2, continuity] - exact = map(e -> Symbolics.build_function(e, x, y; expression = Val(false)), (u1s, u2s, ps)) - shape = SHAPE[ct] + # starts from its exact values and is pinned on the one-facet piece "corner". FEMDiscretization's default + # algebraic_abstol = :auto leaves the algebraic rows out of the error control (abstol 1e8), without which + # DFBDF fails at t ≈ 1e-10 on the 16 × 16 meshes; no abstol is written here. errs = map((4, 8, 16)) do n - Ω = MeshDomain(corner_grid(ct, n)) - Γs = boundarypiece.(Ω, (:left, :right, :bottom, :top, :corner)) - bcs = [ - [u1(t, Γ) ~ 0 for Γ in Γs]; [u2(t, Γ) ~ 0 for Γ in Γs]; p(t, Γs[end]) ~ x^3 - y^3; - u1(0, x, y) ~ 0; u2(0, x, y) ~ 0; p(0, x, y) ~ x^3 - y^3 - ] - @named stokes = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x, y], [U1, U2, P], []) - P2, P1 = Lagrange{shape, 2}(), Lagrange{shape, 1}() - prob = discretize(stokes, FEMDiscretization(Ω, t; spaces = Dict(u1 => P2, u2 => P2, p => P1), pairing = Dict(continuity => p))) - @test count(.!prob.differential_vars) > length(FiniteElementMethod.field_range(prob.problem_type.space, :p)) - abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars] - sol = solve(prob, EXACT_ROWS; abstol, reltol = 1.0e-8) + prob = stokes_problem(ct, n) + abstol = prob.kwargs[:abstol] + @test abstol == [d ? 1.0e-6 : 1.0e8 for d in prob.differential_vars] + space = prob.problem_type.space + pressure = setdiff(FiniteElementMethod.field_range(space, :p), FiniteElementMethod.prescribed_dofs(space)) + @test !isempty(pressure) && all(==(1.0e8), abstol[pressure]) + @test count(==(1.0e8), abstol) > length(pressure) + sol = solve(prob, EXACT_ROWS; reltol = 1.0e-8) @test SciMLBase.successful_retcode(sol) - [rms_error(sol, dv, (_, x_, y_) -> e(x_, y_)) for (dv, e) in zip((U1, U2, P), exact)] + [rms_error(sol, dv, (_, x_, y_) -> e(x_, y_)) for (dv, e) in zip((U1, U2, P), STOKES_EXACT)] end @test all(>(2.7), rates(getindex.(errs, 1))) && all(>(2.7), rates(getindex.(errs, 2))) @test all(>(1.7), rates(getindex.(errs, 3))) end + @testset "algebraic_abstol off with a hand-written vector, a scalar abstol, an override at solve" begin + n = 8 + # Hand-written vector (the recipe before the keyword) with the keyword off: the same solution. + prob = stokes_problem(Quadrilateral, n; algebraic_abstol = nothing) + @test !haskey(prob.kwargs, :abstol) + abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars] + manual = solve(prob, EXACT_ROWS; abstol, reltol = 1.0e-8) + @test SciMLBase.successful_retcode(manual) + # A scalar abstol given to discretize goes to the differential rows; the solve gives the same solution. + auto = solve(stokes_problem(Quadrilateral, n; abstol = 1.0e-8), EXACT_ROWS; reltol = 1.0e-8) + @test auto.t == manual.t && auto.original_sol.u[end] == manual.original_sol.u[end] + # Measured on this 8 × 8 Q2/Q1 mesh: 1.6e-5 for each velocity component, 2.7e-3 for the pressure. + errs = [rms_error(manual, dv, (_, x_, y_) -> e(x_, y_)) for (dv, e) in zip((U1, U2, P), STOKES_EXACT)] + @test all(errs .< [3.0e-5, 3.0e-5, 6.0e-3]) + # An abstol given to solve replaces the problem's vector. + prob = stokes_problem(Quadrilateral, n; algebraic_abstol = 1.0e4) + @test prob.kwargs[:abstol] == [d ? 1.0e-6 : 1.0e4 for d in prob.differential_vars] + @test SciMLBase.init(prob, EXACT_ROWS).opts.abstol == prob.kwargs[:abstol] + @test SciMLBase.init(prob, EXACT_ROWS; abstol = 1.0e-9).opts.abstol == 1.0e-9 + # An array abstol given to discretize is used as it is. + given = fill(1.0e-7, length(prob.u0)) + @test stokes_problem(Quadrilateral, n; abstol = given).kwargs[:abstol] === given + end + @testset "a field on a region reads NaN outside it" begin # u everywhere, w on the cells left of x = 1/2 only. w* = (1 + 2y)(1 + t) has zero flux through the # interface x = 1/2, where w gets the natural condition; both exact solutions are in P1. From 5766069022d4e16e9932fc050c01ee42a12b865f Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:19:56 +0000 Subject: [PATCH 19/62] Check the arguments of every dependent variable the solution looks up by name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex round 3: _fieldinfo matches the function name only, so dv = u(t, 0, y) evaluated the whole field. Keys, dv (plain, derivative and trace calls), normal_flux and Dn keys now require the canonical dependent variable or a well-formed trace u(t, Γ), and reject fixed arguments with the documented message. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/solution.md | 5 +++ src/solution.jl | 43 ++++++++++++++++++++------ test/Solution/solution.jl | 8 +++-- test/shared/frontend_tests/observed.jl | 26 +++++++++++++--- 4 files changed, 66 insertions(+), 16 deletions(-) diff --git a/docs/src/solution.md b/docs/src/solution.md index ce159814..74fa8b71 100644 --- a/docs/src/solution.md +++ b/docs/src/solution.md @@ -53,5 +53,10 @@ points or on a boundary piece, with the shapes of a field, and `NaN` outside the of the system, a trace `u(t, Γ)` (index the trace on its own, or pass `Γ` to the call instead), a derivative that is not a first spatial derivative, or a dependent variable at fixed arguments such as `u(t, 0, y)`. + - A dependent variable at fixed arguments, such as `u(t, 0, y)` or `u(0, x, y)`, is rejected + wherever a dependent variable is accepted (`sol[…]`, `dv`, derivatives, [`normal_flux`](@ref)) + with the `ArgumentError` "u(t, 0, y) fixes arguments of u(t, x, y); write the dependent + variable as u(t, x, y)"; a mesh has no coordinate lines to restrict to. A trace keeps time + and replaces the coordinates by one piece, `u(t, Γ)`. The docstrings are on the [API](@ref "API") page. diff --git a/src/solution.jl b/src/solution.jl index 7ec9c770..2acaddb8 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -184,6 +184,27 @@ function _piece_arg(s) return i === nothing ? nothing : args[i] end +# `_fieldinfo` matches the function name only; these check the arguments. A trace keeps the +# dependent variable's non-spatial arguments and replaces its coordinates by one piece. +_is_canonical(f::FieldInfo, s) = isequal(s, Symbolics.unwrap(f.dv)) +function _is_trace(md, f::FieldInfo, s) + keep = [a for a in SymbolicUtils.arguments(Symbolics.unwrap(f.dv)) if !any(x -> isequal(a, Symbolics.unwrap(x)), md.x̄)] + args = map(SymbolicUtils.unwrap_const, SymbolicUtils.arguments(s)) + return length(args) == length(keep) + 1 && last(args) isa DomainSets.Domain && isequal(collect(args[1:(end - 1)]), keep) +end + +_fixed_args_message(ex, f::FieldInfo) = "$ex fixes arguments of $(f.dv); write the dependent variable as $(f.dv)" + +# A dependent variable, or the field differentiated in `s`, at fixed arguments such as +# `u(t, 0, y)` is rejected rather than evaluated as the whole field. +function _reject_fixed(md, s) + SymbolicUtils.iscall(s) && SymbolicUtils.operation(s) isa Symbolics.Differential && + (s = Symbolics.unwrap(only(SymbolicUtils.arguments(s)))) + f = _fieldinfo(md, s) + (f === nothing || _piece_arg(s) !== nothing || _is_canonical(f, s)) && return nothing + throw(ArgumentError(_fixed_args_message(s, f))) +end + function _facetset(md, Γ) haskey(md.pieces, Γ) || throw(ArgumentError("$Γ is not a boundary piece of this mesh; the pieces are $(collect(keys(md.pieces)))")) @@ -241,8 +262,10 @@ piece `Γ`, `nt × nfacets` (a vector for a steady solution). Facets are ordered """ function normal_flux(A::FEMSolution, dv, Γ) md = A.disc_data - f = _fieldinfo(md, Symbolics.unwrap(dv)) - f === nothing && throw(ArgumentError("$dv is not a dependent variable of this solution; they are $(A.dvs)")) + s = Symbolics.unwrap(dv) + _reject_fixed(md, s) + f = _fieldinfo(md, s) + (f === nothing || !_is_canonical(f, s)) && throw(ArgumentError("$dv is not a dependent variable of this solution; they are $(A.dvs)")) return _stack(A, [_facet_normal_flux(md, f, Γ, U) for U in _states(A)]) end @@ -287,7 +310,7 @@ function _gradkey(md, s) D.order == 1 || return nothing inner = only(SymbolicUtils.arguments(s)) f = _fieldinfo(md, inner) - (f === nothing || !isequal(inner, Symbolics.unwrap(f.dv))) && return nothing + (f === nothing || !_is_canonical(f, inner)) && return nothing d = findfirst(x -> isequal(Symbolics.unwrap(x), Symbolics.unwrap(D.x)), md.x̄) return d === nothing ? nothing : (f, d) end @@ -310,6 +333,7 @@ function Base.getindex(A::FEMSolution, sym::Num) i = findfirst(iv -> isequal(Symbolics.unwrap(iv), s), A.ivs) i === nothing || return A.ivdomain[i] haskey(A.u, sym) && return A.u[sym] + _reject_fixed(md, s) g = _gradkey(md, s) if g !== nothing projector = _gradient_projector(md, g[1]) @@ -319,7 +343,7 @@ function Base.getindex(A::FEMSolution, sym::Num) trace = Symbolics.unwrap(only(SymbolicUtils.arguments(s))) f = _fieldinfo(md, trace) Γ = _piece_arg(trace) - (f === nothing || !isequal(Γ, SymbolicUtils.operation(s).piece)) && _key_error(A, sym) + (f === nothing || !_is_trace(md, f, trace) || !isequal(Γ, SymbolicUtils.operation(s).piece)) && _key_error(A, sym) return normal_flux(A, f.dv, Γ) end f = _fieldinfo(md, s) @@ -333,8 +357,8 @@ function Base.getindex(A::FEMSolution, sym::Num) shape = timed ? (length(A.t), nv) : (nv,) return _broadcast_observed(fn, shape, map(value, terms, kinds)) end + _is_trace(md, f, s) || throw(ArgumentError(_fixed_args_message(s, f))) Γ = _piece_arg(s) - Γ === nothing && _key_error(A, sym) return _columns(A.u[Num(f.dv)], piece_nodes(md, Γ)) end @@ -392,12 +416,15 @@ function _evaluate(A::FEMSolution, ts, states, tshape, xs, dv, outside) md = A.disc_data dv === nothing && return map(d -> _evaluate(A, ts, states, tshape, xs, d, outside), A.dvs) s = Symbolics.unwrap(dv) + _reject_fixed(md, s) g = _gradkey(md, s) f = g === nothing ? _fieldinfo(md, s) : g[1] if f === nothing _is_expression(s) && return _evaluate_observed(A, ts, states, tshape, xs, dv, outside) throw(ArgumentError("dv = $dv is not a dependent variable or a first spatial derivative of one; the dependent variables are $(A.dvs)")) end + g === nothing && !_is_canonical(f, s) && + throw(ArgumentError("dv = $dv is a trace; evaluate a trace as sol(t, Γ; dv = $(f.dv))")) if length(xs) == 1 && only(xs) isa DomainSets.Domain g === nothing || throw(ArgumentError("dv = $dv: traces of derivatives are not supported; use normal_flux(sol, dv, Γ)")) nodes = piece_nodes(md, only(xs)) @@ -439,11 +466,7 @@ function _observed_error(dv, why) throw(ArgumentError("cannot evaluate the expression $dv on this solution: $why")) end -function _check_field_call(dv, ex, f::FieldInfo) - isequal(ex, Symbolics.unwrap(f.dv)) || - _observed_error(dv, "$ex fixes arguments of $(f.dv); write the dependent variable as $(f.dv)") - return nothing -end +_check_field_call(dv, ex, f::FieldInfo) = _is_canonical(f, ex) || _observed_error(dv, _fixed_args_message(ex, f)) # Adds the leaves of `ex` to `terms` as `term => kind`, with kind `:field`, `:time` or `:coord`, # and the value of each parameter to `params`. diff --git a/test/Solution/solution.jl b/test/Solution/solution.jl index 85aaa746..746924b9 100644 --- a/test/Solution/solution.jl +++ b/test/Solution/solution.jl @@ -193,8 +193,12 @@ end msg = ArgumentError("cannot evaluate the expression $fixed on this solution: $(u(0, y)) fixes arguments of u(x, y); write the dependent variable as u(x, y)") @test_throws msg sol[fixed] @test_throws msg sol(0.3, 0.6; dv = fixed) - @test_throws ArgumentError sol[Differential(y)(u(0, y))] - @test_throws ArgumentError sol(0.3, 0.6; dv = Differential(y)(u(0, y))) + bare = ArgumentError("$(u(0, y)) fixes arguments of u(x, y); write the dependent variable as u(x, y)") + for ex in (u(0, y), Differential(y)(u(0, y))) + @test_throws bare sol[ex] + @test_throws bare sol(0.3, 0.6; dv = ex) + end + @test_throws bare normal_flux(sol, u(0, y), Γ) end @testset "Points missed by Ferrite's nearest-node search" begin diff --git a/test/shared/frontend_tests/observed.jl b/test/shared/frontend_tests/observed.jl index 8274d5ca..37e010b7 100644 --- a/test/shared/frontend_tests/observed.jl +++ b/test/shared/frontend_tests/observed.jl @@ -2,7 +2,7 @@ # O9): PDESystem -> DAEProblem -> solve, then each expression is checked against the same # expression computed from the field arrays and against the exact solution. using Test -using FiniteElementMethod: FiniteElementMethod, rectangle_grid, piece_nodes +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, piece_nodes, normal_flux using Ferrite: Triangle, Vec include(joinpath(@__DIR__, "..", "frontend.jl")) @@ -94,9 +94,27 @@ observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on t end # A derivative key that is not an expression keeps the key error. @test occursin("first", errmsg(() -> sol[Dx(Dx(U))])) - # A derivative of a dependent variable at fixed arguments is not a gradient key either. - @test occursin("is not a key of this solution", errmsg(() -> sol[Dy(u(t, 0, y))])) - @test occursin("is not a dependent variable or a first spatial derivative", errmsg(() -> sol(0.5, 0.3, 0.2; dv = Dy(u(t, 0, y))))) + end + + @testset "a dependent variable at fixed arguments is rejected on every path" begin + Γ = first(pieces(Ω)) + fixed(ex) = ArgumentError("$ex fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)") + for ex in (u(t, 0, y), u(t, x, 0.5), u(0, x, y)) + @test_throws fixed(ex) sol[ex] + @test_throws fixed(ex) sol(0.5, 0.3, 0.2; dv = ex) + @test_throws fixed(ex) sol(0.5, Γ; dv = ex) + @test_throws fixed(ex) sol[Dx(ex)] + @test_throws fixed(ex) sol(0.5, 0.3, 0.2; dv = Dx(ex)) + @test_throws fixed(ex) normal_flux(sol, ex, Γ) + end + # A trace must keep time and replace the coordinates by one piece. + @test_throws fixed(u(0, Γ)) sol[u(0, Γ)] + @test sol[u(t, Γ)] == sol[U][:, piece_nodes(sol, Γ)] + @test occursin("is not a key of this solution", errmsg(() -> sol[NormalDerivative(Γ)(u(0, Γ))])) + trace = ArgumentError("dv = $(u(t, Γ)) is a trace; evaluate a trace as sol(t, Γ; dv = u(t, x, y))") + @test_throws trace sol(0.5, 0.3, 0.2; dv = u(t, Γ)) + @test_throws trace sol(0.5, Γ; dv = u(t, Γ)) + @test occursin("is not a dependent variable of this solution", errmsg(() -> normal_flux(sol, u(t, Γ), Γ))) end @testset "two fields" begin From 9b00be303af9d0df4a2587e0f1d016b67fc9ca6b Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:21:11 +0000 Subject: [PATCH 20/62] Allow ForwardDiff's Dual API in the QA public-access check The Dual-state path of the nonlinear operator uses ForwardDiff.Dual, Partials, value and partials, which ForwardDiff documents for custom rules but does not declare public, so ExplicitImports flagged them. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- test/qa/qa.jl | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/qa/qa.jl b/test/qa/qa.jl index e57da3b1..a8655b1a 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -1,7 +1,8 @@ using SciMLTesting, FiniteElementMethod # `Ferrite.DofOrder.FieldWise` is Ferrite's documented renumbering API but is not declared `public`; -# ForwardDiff documents `derivative` as its API but does not declare it `public`; +# ForwardDiff documents `derivative`, and `Dual`, `Partials`, `value` and `partials` for custom rules, as its API +# but declares none of them `public`; # `Ferrite.dirichlet_facetdof_indices` (a facet's local nodes) has no public spelling in Ferrite 1. # The front end uses these PDEBase names, public on the M0 stack but not on PDEBase 0.1.39 (and # `Base.ispublic` does not exist on Julia 1.10), so each is ignored only where it is not public. @@ -24,7 +25,10 @@ run_qa( aqua_kwargs = (; piracies = (; treat_as_own = [FiniteElementMethod.Ferrite.Grid])), ei_kwargs = (; all_qualified_accesses_are_public = (; - ignore = (:FieldWise, :derivative, :dirichlet_facetdof_indices, NONPUBLIC_PDEBASE...), + ignore = ( + :FieldWise, :derivative, :Dual, :Partials, :value, :partials, :dirichlet_facetdof_indices, + NONPUBLIC_PDEBASE..., + ), ), all_explicit_imports_via_owners = (; ignore = LTS_MTK_OWNER), all_qualified_accesses_via_owners = (; ignore = LTS_MTK_OWNER), From b36fc785a07afaa1af5008c2e70ece4ca9a4d6d8 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:27:12 +0000 Subject: [PATCH 21/62] Test and document observed expressions on time-last fields sol[expr], point and trace calls on a time-last heat problem against the exact solution, fixed-argument and malformed-trace rejections in time-last form, and the documented error for expressions mixing time positions. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/solution.md | 8 +++- test/shared/frontend_tests/observed.jl | 61 +++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/docs/src/solution.md b/docs/src/solution.md index 8d0579dc..09c12d4f 100644 --- a/docs/src/solution.md +++ b/docs/src/solution.md @@ -57,6 +57,12 @@ derivatives, the independent variables and the parameters of the `PDESystem`, fo names only coordinates. `sol(t, xs, ys; dv = expr)` and `sol(t, Γ; dv = expr)` evaluate it at points or on a boundary piece, with the shapes of a field, and `NaN` outside the mesh. +The time axis follows the expression's dependent variables, as for a field: an expression in +time-last variables, `sol[u(x, y, t)^2]`, is `nvertices × nt` and is called as +`sol(xs, ys, t; dv = expr)`. An expression with no dependent variable follows the system's +variables. An expression that mixes time-first and time-last variables, or names none in a +system that mixes them, throws an `ArgumentError`: evaluate the parts separately. + - The expression is compiled once with `build_function` and broadcast over the vertex values of its leaves; nothing is substituted per vertex. A first derivative such as `Differential(x)(u(t, x, y))` uses the same values as `sol[Differential(x)(u(t, x, y))]`. @@ -71,6 +77,6 @@ points or on a boundary piece, with the shapes of a field, and `NaN` outside the wherever a dependent variable is accepted (`sol[…]`, `dv`, derivatives, [`normal_flux`](@ref)) with the `ArgumentError` "u(t, 0, y) fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)"; a mesh has no coordinate lines to restrict to. A trace keeps time - and replaces the coordinates by one piece, `u(t, Γ)`. + and replaces the coordinates by one piece, `u(t, Γ)` or `u(Γ, t)`. The docstrings are on the [API](@ref "API") page. diff --git a/test/shared/frontend_tests/observed.jl b/test/shared/frontend_tests/observed.jl index 37e010b7..917012ff 100644 --- a/test/shared/frontend_tests/observed.jl +++ b/test/shared/frontend_tests/observed.jl @@ -71,7 +71,7 @@ observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on t @test sol(0.5, Γ; dv = U + y) ≈ sol(0.5, Γ; dv = U) .+ sol[y][nodes] atol = 1.0e-14 @test sol(T, Γ; dv = t * U) ≈ T .* sol[u(t, Γ)] atol = 1.0e-12 err = errmsg(() -> sol(0.5, Γ; dv = Dx(U) + 1)) - @test occursin("traces of derivatives are not supported", err) + @test occursin("traces of derivatives of u(t, x, y) are not supported", err) end @testset "error paths" begin @@ -134,6 +134,65 @@ observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on t @test_throws observed_error(U * z(t, x, y), "z(t, x, y) is not a dependent variable, an independent variable or a parameter; the dependent variables are $dvs2 and the independent variables t, x, y") sol2[U * z(t, x, y)] end + @testset "time-last fields" begin + UL = u(x, y, t) + eq = Dt(UL) ~ Dx(Dx(UL)) + Dy(Dy(UL)) + (1 + x + 2y) + bcs = [[u(Γ, t) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)]; u(x, y, 0) ~ 1 + x + 2y] + soll, _ = fem_solve([eq], bcs, Ω, (x, y), t, [UL]; ps = [k => 2.0]) + Tl, Xc, Yc = permutedims(soll.t), soll[x], soll[y] + exact = uexact.(Tl, Xc, Yc) + # Arrays keep the orientation of sol[u(x, y, t)], nvertices × nt. + @test size(soll[UL^2 + k * x]) == (nv, length(soll.t)) + @test soll[UL^2 + k * x] ≈ soll[UL] .^ 2 .+ 2 .* Xc atol = 1.0e-12 + @test maximum(abs, soll[UL^2 + k * x] .- (exact .^ 2 .+ 2 .* Xc)) <= 1.0e-6 + @test soll[t * UL] ≈ Tl .* soll[UL] atol = 1.0e-12 + @test soll[x + y] == repeat(Xc .+ Yc, 1, length(soll.t)) + @test soll[Dx(UL) + UL] ≈ soll[Dx(UL)] .+ soll[UL] atol = 1.0e-12 + # Calls take the time last. + @test soll(0.3, 0.2, 0.5; dv = UL^2) ≈ uexact(0.5, 0.3, 0.2)^2 atol = 1.0e-6 + xs, ys, ts = range(0, 1, length = 5), range(0, 1, length = 4), [0.2, 0.5, 0.9] + vals = soll(xs, ys, ts; dv = t * UL) + @test size(vals) == (5, 4, 3) + @test vals ≈ [ts[n] * soll(xs[i], ys[j], ts[n]; dv = UL) for i in 1:5, j in 1:4, n in 1:3] atol = 1.0e-12 + @test maximum(abs, vals .- [ts[n] * uexact(ts[n], xs[i], ys[j]) for i in 1:5, j in 1:4, n in 1:3]) <= 1.0e-6 + Γ = first(pieces(Ω)) + nodes = piece_nodes(soll, Γ) + @test size(soll(Γ, ts; dv = UL + y)) == (length(nodes), 3) + @test soll(Γ, ts; dv = UL + y) ≈ soll(Γ, ts; dv = UL) .+ Yc[nodes] atol = 1.0e-12 + @test soll[u(Γ, t)] == soll[UL][nodes, :] + # Fixed arguments and malformed traces in time-last form. + fixed(ex) = ArgumentError("$ex fixes arguments of u(x, y, t); write the dependent variable as u(x, y, t)") + for ex in (u(0, y, t), u(x, y, 0)) + @test_throws fixed(ex) soll[ex] + @test_throws fixed(ex) soll(0.3, 0.2, 0.5; dv = ex) + @test_throws fixed(ex) soll[Dx(ex)] + @test_throws fixed(ex) normal_flux(soll, ex, Γ) + @test_throws observed_error(ex + 1, "$ex fixes arguments of u(x, y, t); write the dependent variable as u(x, y, t)") soll[ex + 1] + end + @test_throws fixed(u(Γ, 0)) soll[u(Γ, 0)] + @test_throws fixed(u(t, Γ)) soll[u(t, Γ)] + @test_throws ArgumentError("dv = $(u(Γ, t)) is a trace; evaluate a trace as sol(Γ, t; dv = u(x, y, t))") soll(0.3, 0.2, 0.5; dv = u(Γ, t)) + end + + @testset "fields with different time positions" begin + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(x, y, t) + algebraic = 0 ~ Dx(Dx(v(x, y, t))) + Dy(Dy(v(x, y, t))) + bcs = [heat_bcs(Ω); [v(Γ, t) ~ 1 + x + 2y for Γ in pieces(Ω)]] + solm, _ = fem_solve( + [parabolic, algebraic], bcs, Ω, (x, y), t, [u(t, x, y), v(x, y, t)]; pairing = Dict(algebraic => v) + ) + VL = v(x, y, t) + # One field per expression: its own orientation. + @test solm[2U] == 2 .* solm[U] + @test solm[VL * x] ≈ solm[VL] .* solm[x] atol = 1.0e-12 + @test solm(0.3, 0.2, 0.5; dv = 2VL) ≈ 2 * (1 + 0.3 + 0.4) atol = 1.0e-6 + # Mixed time positions have no orientation, documented as an error. + mixed = "its dependent variables (all those of the system when it names none) put time in different argument positions; evaluate the time-first and the time-last parts separately" + @test_throws observed_error(U + VL, mixed) solm[U + VL] + @test_throws observed_error(U + VL, mixed) solm(0.5, 0.3, 0.2; dv = U + VL) + @test_throws observed_error(2x, mixed) solm[2x] + end + @testset "evaluation is batched at 10^4 vertices" begin big = MeshDomain(rectangle_grid(Triangle, (99, 99))) bsol, _ = fem_solve([heat_eq], heat_bcs(big), big, (x, y), t, [u(t, x, y)]; ps = [k => 2.0], saveat = 0.5) From 86c3b53e511ffcd801623d473d1da6f42b03558d Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:31:17 +0000 Subject: [PATCH 22/62] Reject nonlinear states other than Float64 and Dual{Float64} up front The element pipeline is Float64. Float32 or BigFloat states, Duals of those and nested Duals reached it and failed with a MethodError deep in assembly (or, for plain Float32 and BigFloat, would be silently rounded to Float64). The residual and the nonlinear Jacobian now check the state type on entry and throw one documented ArgumentError naming it. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/numeric_dae.jl | 16 ++++++++++++++ test/shared/frontend_tests/nonlinear.jl | 29 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index a013e27e..18c6854d 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -98,6 +98,14 @@ prescribed dofs, whose rows of `N` and of its Jacobian are then zero. `op` is un the parameter has one concrete type; each call dispatches on it once. `op` itself is never evaluated: each evaluation borrows a copy with its own buffers and values objects from a pool, so problems sharing this wrapper (remakes, ensembles) can be solved concurrently. + +The element pipeline is `Float64`: `N` is evaluated at `Float64` states and at first-order +`ForwardDiff.Dual`s of `Float64` (as the default initializer passes), whose partials go through +the analytic tangent. Any other state, such as `Float32`, `BigFloat`, `Dual`s of those or nested +`Dual`s, throws `ArgumentError("the nonlinear operator evaluates Float64 states and first-order +ForwardDiff Duals of Float64; got T")` with `T` the state's element type; its Jacobian is +evaluated at `Float64` states only and otherwise throws `ArgumentError("the nonlinear +operator's Jacobian evaluates Float64 states; got T")`. """ struct FEMNonlinear op::Any @@ -120,8 +128,13 @@ function with_operator(f, N::FEMNonlinear) end end +check_state(::AbstractVector{Float64}) = nothing +check_state(::AbstractVector{<:ForwardDiff.Dual{<:Any, Float64}}) = nothing +check_state(u) = throw(ArgumentError("the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got $(eltype(u))")) + # `r .+= N(u, t)` outside the prescribed rows. function add_nonlinear!(r, N::FEMNonlinear, u, t) + check_state(u) return with_operator(N) do op residual!(op.r, op, u, N.p, t) for i in eachindex(r) @@ -149,6 +162,8 @@ nonlinear_residual!(r, N::FEMNonlinear, u, t) = add_nonlinear!(fill!(r, 0), N, u # `nonzeros(J) .+= nonzeros(∂N/∂u)` outside the prescribed rows; `J` must have the pattern of `N`'s Jacobian. function add_nonlinear_jacobian!(J, N::FEMNonlinear, u, t) + u isa AbstractVector{Float64} || + throw(ArgumentError("the nonlinear operator's Jacobian evaluates Float64 states; got $(eltype(u))")) return with_operator(N) do op JN = jacobian!(op.J, op, u, N.p, t) check_pattern(J, JN, "Nop") @@ -404,6 +419,7 @@ function numeric_dae_problem( getN = ops.nonlinear === nothing ? Returns(nothing) : getp(sys, sys.Nop) function residual!(res, du, u, p, t) check_assembled(p) + ops.nonlinear === nothing || check_state(u) load!(res, getF(p), t) res .= .-res mul!(res, getM(p).A, du, true, true) diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index a712bf85..7dc2741c 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -141,6 +141,35 @@ end Threads.nthreads() > 1 || @info "the remakes were solved on one thread, so this test cannot see a race; run with JULIA_NUM_THREADS > 1" end + @testset "states other than Float64 and Dual{Float64} are rejected" begin + Ω = square() + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) - 2 * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + n = length(prob.u0) + Dual = FiniteElementMethod.ForwardDiff.Dual + states = ( + Float32.(prob.u0), big.(prob.u0), Dual{Nothing}.(Float32.(prob.u0), 1.0f0), + Dual{:outer}.(Dual{:inner}.(prob.u0, 1.0), Dual{:inner}(1.0, 0.0)), + ) + for u in states + T = eltype(u) + msg = "the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got $T" + @test_throws ArgumentError(msg) prob.f(zeros(T, n), zeros(T, n), u, prob.p, 0.0) + end + @test_throws ArgumentError("the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got Float32") prob.f( + zeros(Float32, n), zeros(Float32, n), Float32.(prob.u0), prob.p, 0.0 + ) + @test_throws ArgumentError("the nonlinear operator's Jacobian evaluates Float64 states; got Float32") prob.f.jac( + copy(prob.f.jac_prototype), zeros(n), Float32.(prob.u0), prob.p, 1.0, 0.0 + ) + # The supported states still evaluate: Float64 and a first-order Dual of Float64. + r = zeros(n) + prob.f(r, zeros(n), prob.u0, prob.p, 0.0) + rd = zeros(Dual{Nothing, Float64, 1}, n) + prob.f(rd, zeros(n), Dual{Nothing}.(prob.u0, 1.0), prob.p, 0.0) + @test FiniteElementMethod.ForwardDiff.value.(rd) ≈ r + end + @testset "a parameter changed by remake is rejected, not ignored" begin # The operators, the nonlinear one included, hold the values they were assembled with (spec §8.3). Ω = square() From 20f8e47b648646144761f1d71a55be67ee4bbed8 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:48:57 +0000 Subject: [PATCH 23/62] Write the full steady state in write_vtk; describe u0 by the problem's unknown vector write_vtk on a steady solution now writes only(_states(A)), the full dof vector, rather than original_sol.u, which holds only the free dofs once dirichlet = :eliminate (#25) lands; the result is unchanged on this base. The NonlinearProblem docstring and the steady docs describe the initial guess by the layout of prob.u0 and point to field_range only for the default dirichlet = :algebraic. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 5 +++-- src/frontend.jl | 8 +++++--- src/solution.jl | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/discretization.md b/docs/discretization.md index 0ea8b860..b333035d 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -37,7 +37,8 @@ sol(0.5, 0.5; dv = u(x, y)) ``` Nonlinear terms are rejected on the steady path, as on the time-dependent one. Newton starts -from zero on the free dofs and the Dirichlet data on the prescribed dofs; another initial guess -is a dof vector passed as `remake(prob; u0)`, where field `name` occupies +from zero, with the Dirichlet data on any Dirichlet dofs the unknown vector holds; another +initial guess is a vector laid out like `prob.u0`, passed as `remake(prob; u0)`. With the +default `dirichlet = :algebraic` that vector holds every dof and field `name` occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`. Equations with no entry in `pairing` are tested with the remaining dependent variables in declared order. diff --git a/src/frontend.jl b/src/frontend.jl index 864cad77..a6c8ba4a 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -384,9 +384,11 @@ as algebraic equations, the sparse Jacobian `K` and the `FEMMetadata` as its `pr so `solve` returns a `PDENoTimeSolution`; Newton solves it in one step. Nonlinear terms are rejected, as on the time-dependent path. -The initial guess `u0` is zero on the free dofs and `g_d` on the Dirichlet dofs; a steady -`PDESystem` has no initial conditions. To start Newton elsewhere, `remake(prob; u0)` with a -dof vector (field `name` occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`). +The initial guess `u0` is zero, with the Dirichlet data `g_d` wherever the problem's unknown +vector holds Dirichlet dofs; a steady `PDESystem` has no initial conditions. To start Newton +elsewhere, `remake(prob; u0)` with a vector laid out like `prob.u0`, the problem's unknown +vector (with the default `dirichlet = :algebraic` it holds every dof, and field `name` +occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`). Keywords are passed to the `NonlinearProblem` after `disc.kwargs`; the keywords `iv`, `unknowns`, `du0`, `coordinate` and `name` are rejected, as for the `DAEProblem`. """ diff --git a/src/solution.jl b/src/solution.jl index afe9bf35..b22f53d9 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -443,7 +443,7 @@ end function write_vtk(A::FEMSteadySolution, base::AbstractString) dh = _dh(A.disc_data) Ferrite.VTKGridFile(base, dh) do vtk - Ferrite.write_solution(vtk, dh, A.original_sol.u) + Ferrite.write_solution(vtk, dh, only(_states(A))) end return base * ".vtu" end From 527bfc29ca44aa15400ae97e8a4ff3fbfa02c231 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:56:04 +0000 Subject: [PATCH 24/62] Say why the DFG example keeps CheckInit after #30 #30's default initialiser repairs inconsistent states, but the DFG start is already consistent and the continuity rows do not contain the pressure, so the initialiser's Newton matrix would be singular in the pressure columns; CheckInit only verifies the start. Comment and docs only. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/navier_stokes.md | 6 ++++-- examples/dfg_cylinder/dfg_cylinder.jl | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/src/navier_stokes.md b/docs/src/navier_stokes.md index 08906157..fc665024 100644 --- a/docs/src/navier_stokes.md +++ b/docs/src/navier_stokes.md @@ -49,8 +49,10 @@ sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFP meshes from 5 000 to 149 000 unknowns. - **Index-2 DAE.** The continuity equation is paired with the pressure explicitly. The flow starts at rest and the inflow is ramped by `1 − exp(−t²)`, whose value and rate vanish at - `t = 0`, so the zero initial state is consistent and the default initialisation (which - would solve the continuity rows for the pressure) is replaced by `CheckInit()`. The zero + `t = 0`, so the zero initial state is consistent and `CheckInit()` only verifies it. The + default initialiser would solve the algebraic rows for the algebraic variables, and the + continuity rows do not contain the pressure, so its Newton matrix would be singular in the + pressure columns. The zero velocity is discretely divergence free; the pressure, an algebraic variable, starts at zero and needs no initial condition, since every residual row vanishes at `t = 0`. The pressure and the Dirichlet rows are left out of the error control: the local error of an diff --git a/examples/dfg_cylinder/dfg_cylinder.jl b/examples/dfg_cylinder/dfg_cylinder.jl index 6f3b7f0b..796c1a1b 100644 --- a/examples/dfg_cylinder/dfg_cylinder.jl +++ b/examples/dfg_cylinder/dfg_cylinder.jl @@ -14,10 +14,12 @@ # (`pressure = :weak` or `:strong`). # - The pressure has no equation of its own: the continuity equation is paired with it explicitly, and the # system is a DAE of index 2. Its initial state is consistent without index reduction because the flow starts -# at rest and the inflow is ramped up by 1 − exp(−t²), whose value and rate vanish at t = 0; the default -# initialisation, which would solve the continuity rows for p, is replaced by a check. The zero +# at rest and the inflow is ramped up by 1 − exp(−t²), whose value and rate vanish at t = 0. The zero # velocity is discretely divergence free, and p needs no initial condition: it is algebraic, starts at zero, -# and every residual row vanishes at t = 0. +# and every residual row vanishes at t = 0. `CheckInit()` therefore only verifies that start. The default +# initialiser would instead solve the algebraic rows for the algebraic variables, and the continuity rows do +# not contain p, so its Newton matrix is singular in the pressure columns: there is nothing for it to fix +# and nothing it could determine. # - The pressure, an index-2 algebraic variable, and the Dirichlet rows are left out of DFBDF's error control (an # absolute tolerance of 1e8 on them): the local error of an index-2 variable does not shrink with the step, so # with it DFBDF cuts the step to nothing. The Dirichlet rows are exact anyway with a W refreshed every step. From a6456d3fa5d322fc30a2cd00515d801c555f6329 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 14:59:05 +0000 Subject: [PATCH 25/62] Treat a PDESystem without parameters as having none in observed expressions A PDESystem built without ps carries NullParameters, so the parameter lookup threw MethodError instead of the documented unknown-variable ArgumentError. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 2 +- test/shared/frontend_tests/observed.jl | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/solution.jl b/src/solution.jl index dfc95fb9..98a13d0d 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -546,7 +546,7 @@ function _observed_leaves!(terms, params, A, dv, ex) terms[ex] = :field elseif SymbolicUtils.issym(ex) || SymbolicUtils.issym(SymbolicUtils.operation(ex)) # The front end requires a numeric value for every parameter of the PDESystem. - ps = md.pdesys === nothing ? [] : md.pdesys.ps + ps = md.pdesys === nothing || md.pdesys.ps isa SciMLBase.NullParameters ? [] : md.pdesys.ps i = findfirst(p -> p isa Pair && isequal(Symbolics.unwrap(p.first), ex), ps) i === nothing && _observed_error( dv, "$ex is not a dependent variable, an independent variable or a parameter; the dependent variables are $(join(A.dvs, ", ")) and the independent variables $(join(A.ivs, ", "))" diff --git a/test/shared/frontend_tests/observed.jl b/test/shared/frontend_tests/observed.jl index 917012ff..980bcd18 100644 --- a/test/shared/frontend_tests/observed.jl +++ b/test/shared/frontend_tests/observed.jl @@ -134,6 +134,23 @@ observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on t @test_throws observed_error(U * z(t, x, y), "z(t, x, y) is not a dependent variable, an independent variable or a parameter; the dependent variables are $dvs2 and the independent variables t, x, y") sol2[U * z(t, x, y)] end + @testset "a PDESystem without parameters" begin + # Through the front end with ps = []; a PDESystem built without ps carries NullParameters, + # checked on the same solution rewrapped with such a system. + sol0, _ = fem_solve([heat_eq], heat_bcs(Ω), Ω, (x, y), t, [u(t, x, y)]) + @test sol0[U^2 + x] ≈ sol0[U] .^ 2 .+ X atol = 1.0e-12 + unknown_k = observed_error(U + k, "k is not a dependent variable, an independent variable or a parameter; the dependent variables are u(t, x, y) and the independent variables t, x, y") + @test_throws unknown_k sol0[U + k] + @named bare = PDESystem([heat_eq], heat_bcs(Ω), [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U]) + @test bare.ps isa SciMLBase.NullParameters + md = sol0.disc_data + md0 = FiniteElementMethod.FEMMetadata(md.space, md.time, md.x̄, md.fields, md.pieces, bare; u0 = md.u0) + rewrapped = SciMLBase.PDETimeSeriesSolution(sol0.original_sol, md0) + @test rewrapped[U^2 + x] == sol0[U^2 + x] + @test_throws unknown_k rewrapped[U + k] + @test_throws unknown_k rewrapped(0.5, 0.3, 0.2; dv = U + k) + end + @testset "time-last fields" begin UL = u(x, y, t) eq = Dt(UL) ~ Dx(Dx(UL)) + Dy(Dy(UL)) + (1 + x + 2y) From 6ea30b1bb28958af77609fe3060227452747d84a Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 15:04:51 +0000 Subject: [PATCH 26/62] Give the force functional the integrator's final derivative MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex: with save_everystep = false the saved solution has only its end points, so sol(tend, Val{1}) was the slope (x_end − x_0)/t_end (max 6.6e-3 here), not the derivative at t_end (max 8.5e-10). On the CI mesh this biased cD by +7.3e-8 and cL by +1.9e-6 relative. dfg_solve now steps an integrator and passes its du; the test checks that du vanishes, satisfies the DAE, and gives the du = 0 coefficients, and the agreement with the hand-written steady solver tightens from rtol 1e-5 to 1e-7. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- examples/dfg_cylinder/dfg_cylinder.jl | 16 ++++++++++------ test/NavierStokes/dfg_cylinder.jl | 14 +++++++++++++- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/examples/dfg_cylinder/dfg_cylinder.jl b/examples/dfg_cylinder/dfg_cylinder.jl index 796c1a1b..cc624e62 100644 --- a/examples/dfg_cylinder/dfg_cylinder.jl +++ b/examples/dfg_cylinder/dfg_cylinder.jl @@ -29,7 +29,7 @@ using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF using OrdinaryDiffEqBDF: NLNewton using LinearSolve: UMFPACKFactorization using ModelingToolkit: t_nounits as t -using SciMLBase: SciMLBase, CheckInit +using SciMLBase: SciMLBase, CheckInit, init, solve! using Ferrite: Ferrite include(joinpath(@__DIR__, "mesh.jl")) @@ -98,18 +98,22 @@ end """ dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1e-7, reltol = 1e-7) -Mesh, discretize and solve 2D-1; returns `(; sol, prob, coefficients, ndofs, build_s, solve_s)` with the -coefficients `(cD, cL, Δp)` at `tend`. +Mesh, discretize and solve 2D-1; returns `(; sol, prob, coefficients, dxdt, ndofs, build_s, solve_s)` with the +coefficients `(cD, cL, Δp)` at `tend`. `dxdt` is the integrator's derivative at `tend`, used in the `∂ₜu` term of +the force functional: with `save_everystep = false` the saved solution has only its two end points, and its +derivative is the slope between them, not the derivative at `tend`. """ function dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1.0e-7, reltol = 1.0e-7) grid = dfg_channel_grid(; h, hc) build_s = @elapsed prob = dfg_problem(grid; tend) - solve_s = @elapsed sol = check_solved(solve(prob, alg; abstol = differential_abstol(prob, abstol), reltol, save_everystep = false)) + integrator = init(prob, alg; abstol = differential_abstol(prob, abstol), reltol, save_everystep = false) + solve_s = @elapsed solve!(integrator) + sol = check_solved(SciMLBase.wrap_sol(integrator.sol)) dh = sol.disc_data.space.dh xend = sol.original_sol.u[end] - dxdt = sol.original_sol(tend, Val{1}) + dxdt = copy(integrator.du) coefficients = dfg_coefficients(dh, xend; ν = 1.0e-3, Umean = 0.2, dxdt) - return (; sol, prob, coefficients, ndofs = length(prob.u0), build_s, solve_s) + return (; sol, prob, coefficients, dxdt, ndofs = length(prob.u0), build_s, solve_s) end if abspath(PROGRAM_FILE) == @__FILE__ diff --git a/test/NavierStokes/dfg_cylinder.jl b/test/NavierStokes/dfg_cylinder.jl index 321ce84f..0798b678 100644 --- a/test/NavierStokes/dfg_cylinder.jl +++ b/test/NavierStokes/dfg_cylinder.jl @@ -18,6 +18,18 @@ if FiniteElementMethod.MESH_PDEBASE @test terminated.retcode == SciMLBase.ReturnCode.Terminated @test_throws "the DFG solve stopped at t = " check_solved(terminated) c = r.coefficients + # The force functional gets the integrator's final derivative, which vanishes at the steady state and + # satisfies the DAE there, not the slope between the two saved end points (about |u|/t_end). + dv = r.prob.differential_vars + x_end = r.sol.original_sol.u[end] + @test maximum(abs, r.dxdt[dv]) <= 1.0e-6 + residual = zeros(length(x_end)) + r.prob.f(residual, r.dxdt, x_end, r.prob.p, last(r.prob.tspan)) + @test maximum(abs, residual[dv]) <= 1.0e-9 + steady = dfg_coefficients(r.sol.disc_data.space.dh, x_end; ν = 1.0e-3, Umean = 0.2) + for k in (:cD, :cL) + @test c[k] ≈ steady[k] rtol = 1.0e-8 + end for k in (:cD, :cL, :Δp) lo, hi = DFG_2D1_BANDS[k] @test lo <= c[k] <= hi @@ -29,7 +41,7 @@ if FiniteElementMethod.MESH_PDEBASE dh_ref, x_ref, _ = dfg_reference_steady(grid; pressure = :strong) ref = dfg_coefficients(dh_ref, x_ref; ν = 1.0e-3, Umean = 0.2) for k in (:cD, :cL, :Δp) - @test c[k] ≈ ref[k] rtol = 1.0e-5 + @test c[k] ≈ ref[k] rtol = 1.0e-7 end end else From 4992114586596d787d82b2e94009f227d0c561e3 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 15:49:16 +0000 Subject: [PATCH 27/62] Reject an explicit algebraic_abstol on a steady FEMDiscretization After merging #24 a steady discretization accepted algebraic_abstol and ignored it. The keyword only acts on the DAE path, so a number now raises a documented ArgumentError; :auto and nothing stay accepted and set no abstol on the NonlinearProblem. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 2 ++ src/discretization.jl | 9 ++++++++- test/shared/frontend_tests/errors.jl | 7 +++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/discretization.md b/docs/discretization.md index 008f6e23..46e94903 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -60,6 +60,8 @@ entries, as in `discretize(pdesys, disc; abstol = 1.0e-8)`; an array is used as `solve(prob, alg; abstol = 1.0e-8)` puts the algebraic rows back under error control; write the vector by hand in that case, `abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars]`. Systems without an index-2 field, such as `0 ~ Δv + u` paired with `v`, get no `abstol`. +The keyword applies to the time-dependent (DAE) path only: a steady `FEMDiscretization(Ω)` +accepts `:auto` and `nothing` and does nothing with them, and raises for a number. Without the large tolerance, the step size collapses near the initial time (`dt` below `eps` at `t ≈ 1e-10` on a 16 × 16 Taylor–Hood mesh). When the linear solver then reports the Newton diff --git a/src/discretization.jl b/src/discretization.jl index 6f0a4f36..297a860a 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -40,7 +40,9 @@ gives a `PDENoTimeSolution`. value on the algebraic rows of any system; `nothing` sets nothing. The differential rows get the `abstol` passed to `FEMDiscretization` or `DAEProblem` if it is a number, else OrdinaryDiffEq's default `1e-6`; an array `abstol` passed there is used as it is. An - `abstol` passed to `solve` replaces the problem's whole vector. This keyword is not in the spec (§7.1, §7.6): without it, `DFBDF` + `abstol` passed to `solve` replaces the problem's whole vector. The keyword belongs to the + time-dependent (DAE) path: a steady discretization ignores `:auto` and `nothing` and + rejects a number. This keyword is not in the spec (§7.1, §7.6): without it, `DFBDF` drives the step size of an index-2 system below `eps` near the initial time, since the local error of the index-2 unknowns does not shrink with the step. - `codegen = :mtk` and `dirichlet = :eliminate` are reserved for later milestones and @@ -112,6 +114,11 @@ function FEMDiscretization( end algebraic_abstol === :auto || algebraic_abstol === nothing || algebraic_abstol isa Real && algebraic_abstol > 0 || throw(ArgumentError("algebraic_abstol must be :auto, nothing or a positive number, got $(repr(algebraic_abstol))")) + time === nothing && algebraic_abstol isa Real && throw( + ArgumentError( + "algebraic_abstol applies to time-dependent problems (the DAE path); a steady FEMDiscretization has no time stepper" + ) + ) _check_reserved(kwargs) return FEMDiscretization{typeof(time)}( domain, time, Dict{Any, Ferrite.Interpolation}(_field_op(k) => ip for (k, ip) in spaces), diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index e687dbab..a64b0b00 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -121,6 +121,13 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @test_throws ArgumentError( "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name" ) discretize(steady, FEMDiscretization(Ω); name = :other) + @test_throws ArgumentError( + "algebraic_abstol applies to time-dependent problems (the DAE path); a steady FEMDiscretization has no time stepper" + ) FEMDiscretization(Ω; algebraic_abstol = 1.0e8) + # :auto (the default) and nothing are accepted and set no abstol on the NonlinearProblem. + for value in (:auto, nothing) + @test !haskey(discretize(steady, FEMDiscretization(Ω; algebraic_abstol = value)).kwargs, :abstol) + end end @testset "nonlinear and time-dependent operators" begin From 962ee721af0391585436518fd5a1df42bd462d7d Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 15:54:11 +0000 Subject: [PATCH 28/62] Solve steady problems with their nonlinear terms With #24 merged, the steady NonlinearProblem used only K and F, so a steady system with nonlinear terms (no longer rejected since this PR) solved its linear part and reported Success: 0 = div((1 + u^2) grad u) - 10u* gave a point error of 1.76 against the exact u* = 1 + x + 2y. The residual is now K u + N(u, t0) - F and the Jacobian K + dN/du, with the Dirichlet rows unchanged. #24's error tests are updated: the reserved keywords include parameters, and steady nonlinear terms are no longer rejected. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 10 +++++----- src/frontend.jl | 20 ++++++++++++-------- test/shared/frontend_tests/errors.jl | 9 +-------- test/shared/frontend_tests/nonlinear.jl | 15 +++++++++++++++ 4 files changed, 33 insertions(+), 21 deletions(-) diff --git a/docs/discretization.md b/docs/discretization.md index c250f500..b46473bd 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -16,8 +16,9 @@ FiniteElementMethod.assemble_sources! ## Steady problems A `PDESystem` with no time variable, discretized by a `FEMDiscretization` built without one, -lowers to a `NonlinearProblem` `K u - F = 0`, which Newton solves in one step. Dirichlet rows -are the algebraic equations `u_d - g_d = 0`, the Jacobian `K` is sparse, and `solve` returns a +lowers to a `NonlinearProblem` `K u + N(u) - F = 0`, where `N` holds the terms whose +coefficients depend on the state; without them Newton solves it in one step. Dirichlet rows +are the algebraic equations `u_d - g_d = 0`, the Jacobian `K + ∂N/∂u` is sparse, and `solve` returns a `PDENoTimeSolution` with the same interface as a transient solution, without the time argument: `sol[u(x, y)]`, `sol(x, y; dv)`, traces `sol[u(Γ)]`, derivatives such as `sol[Dx(u(x, y))]`, `normal_flux` and `write_vtk` (one `.vtu` file). Traces are written `u(Γ)`, since the dependent @@ -36,9 +37,8 @@ sol = solve(prob, NewtonRaphson()) sol(0.5, 0.5; dv = u(x, y)) ``` -Nonlinear terms are rejected on the steady path, as on the time-dependent one. Newton starts -from zero, with the Dirichlet data on any Dirichlet dofs the unknown vector holds; another -initial guess is a vector laid out like `prob.u0`, passed as `remake(prob; u0)`. With the +Newton starts from zero, with the Dirichlet data on any Dirichlet dofs the unknown vector +holds; another initial guess is a vector laid out like `prob.u0`, passed as `remake(prob; u0)`. With the default `dirichlet = :algebraic` that vector holds every dof and field `name` occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`. Equations with no entry in `pairing` are tested with the remaining dependent variables in declared order. diff --git a/src/frontend.jl b/src/frontend.jl index bdea8e16..9737e9e1 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -332,19 +332,22 @@ function _lower(pdesys, disc::FEMDiscretization) return (; ops, u0 = unknown_u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys), parameters) end -# `K u - F` with the Dirichlet rows `u_d - g_d`: `K` holds `e_d` and `F` holds `g_d` there. -# Nonlinear terms `N(u)` would be added to the residual in `f!` and `∂N/∂u` to `jac!`. +# `K u + N(u, t0) - F` with the Dirichlet rows `u_d - g_d`: `K` holds `e_d`, `F` holds `g_d` and `N` is zero there. function _steady_problem(parts; kwargs...) (; ops) = parts - F = load!(zeros(length(parts.u0)), ops.load, 0.0) + t0 = first(parts.tspan) + F = load!(zeros(length(parts.u0)), ops.load, t0) + N = ops.nonlinear function f!(res, u, p) mul!(res, ops.K, u) res .-= F + N === nothing || add_nonlinear!(res, N, u, t0) return nothing end function jac!(J, u, p) check_pattern(J, ops.K, "the Jacobian") copyto!(nonzeros(J), nonzeros(ops.K)) + N === nothing || add_nonlinear_jacobian!(J, N, u, t0) return nothing end f = SciMLBase.NonlinearFunction{true}(f!; jac = jac!, jac_prototype = copy(ops.K)) @@ -390,10 +393,11 @@ end NonlinearProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) Discretize the steady `pdesys` with a `disc` that has no time variable and return the -`NonlinearProblem` `K u - F = 0` of the Galerkin operators, with Dirichlet rows `u_d - g_d` -as algebraic equations, the sparse Jacobian `K` and the `FEMMetadata` as its `problem_type`, -so `solve` returns a `PDENoTimeSolution`; Newton solves it in one step. Nonlinear terms are -rejected, as on the time-dependent path. +`NonlinearProblem` `K u + N(u) - F = 0` of the Galerkin operators, with Dirichlet rows +`u_d - g_d` as algebraic equations, the sparse analytic Jacobian `K + ∂N/∂u` and the +`FEMMetadata` as its `problem_type`, so `solve` returns a `PDENoTimeSolution`. `N` holds the +terms whose coefficients depend on the state, as on the time-dependent path; without them +Newton solves the problem in one step. The initial guess `u0` is zero, with the Dirichlet data `g_d` wherever the problem's unknown vector holds Dirichlet dofs; a steady `PDESystem` has no initial conditions. To start Newton @@ -401,7 +405,7 @@ elsewhere, `remake(prob; u0)` with a vector laid out like `prob.u0`, the problem vector (with the default `dirichlet = :algebraic` it holds every dof, and field `name` occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`). Keywords are passed to the `NonlinearProblem` after `disc.kwargs`; the keywords -`iv`, `unknowns`, `du0`, `coordinate` and `name` are rejected, as for the `DAEProblem`. +`iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters` are rejected, as for the `DAEProblem`. """ function SciMLBase.NonlinearProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) _check_reserved(kwargs) diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index cf41ab3f..c4c61b13 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -114,7 +114,7 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] "for a time-dependent problem write FEMDiscretization(Ω, t)" ) discretize(transient, FEMDiscretization(Ω)) @test_throws ArgumentError( - "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name" + "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name, parameters" ) discretize(steady, FEMDiscretization(Ω); name = :other) end @@ -125,13 +125,6 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has " * "G₁*W₁ + G₂*W₂ + G₁*T*W₁ + G₂*T*W₂" ) lower([td], [dirichlet(Ω); ic], Ω) - @named steady_nl = PDESystem( - [Dx((1 + u(x, y)^2) * Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in sides(Ω)], - [(x, y) ∈ Ω], [x, y], [u(x, y)], [] - ) - @test_throws ArgumentError("nonlinear terms land in M3: equation 1 has the nonlinear term -G₁*(U₁^2)*W₁") discretize( - steady_nl, FEMDiscretization(Ω) - ) end @testset "non-finite initial condition names the node" begin diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index 7dc2741c..3e62fe0c 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -10,6 +10,7 @@ using FiniteElementMethod: FiniteElementMethod, rectangle_grid using Ferrite: Triangle using LinearAlgebra: I, norm using SciMLBase: remake +using NonlinearSolveFirstOrder: NewtonRaphson include(joinpath(@__DIR__, "..", "frontend.jl")) @@ -170,6 +171,20 @@ end @test FiniteElementMethod.ForwardDiff.value.(rd) ≈ r end + @testset "steady nonlinear diffusion, dirichlet = $dirichlet" for dirichlet in (:algebraic,) + # ∇·((1 + u*²)∇u*) = 2u*|∇u*|² = 10u* for u* = 1 + x + 2y, which lies in the P1 space. + Ω = square() + us = 1 + x + 2y + eq = Dx((1 + u(x, y)^2) * Dx(u(x, y))) + Dy((1 + u(x, y)^2) * Dy(u(x, y))) ~ 10 * us + @named steady = PDESystem([eq], [u(Γ) ~ us for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + prob = discretize(steady, FEMDiscretization(Ω; dirichlet)) + sol = solve(prob, NewtonRaphson(); abstol = 1.0e-12) + @test SciMLBase.successful_retcode(sol) + @test sol.stats.nsteps > 1 + pts = range(0.05, 0.95; length = 7) + @test maximum(abs(sol(px, py; dv = u(x, y)) - (1 + px + 2py)) for px in pts, py in pts) <= tol + end + @testset "a parameter changed by remake is rejected, not ignored" begin # The operators, the nonlinear one included, hold the values they were assembled with (spec §8.3). Ω = square() From a9ffb81d946aaf67837631aa23f682623ba62732 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 15:54:16 +0000 Subject: [PATCH 29/62] Keep nonlinear terms under dirichlet = :eliminate With #25 merged, eliminate_dirichlet rebuilt FEMOperators without the nonlinear part, so dirichlet = :eliminate silently dropped N: a stationary nonlinear diffusion-reaction problem drifted 1.31 from its exact solution, and the steady one was off by 1.76. The reduced FEMNonlinear now evaluates N at the full state rebuilt from the free dofs with u_cd = g, keeps its free rows, and adds its [free, free] Jacobian block through a precomputed map of stored-entry positions. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 3 +- src/discretization.jl | 3 +- src/numeric_dae.jl | 47 +++++++++++++++++++------ test/shared/frontend_tests/nonlinear.jl | 26 +++++++++++++- 4 files changed, 66 insertions(+), 13 deletions(-) diff --git a/docs/discretization.md b/docs/discretization.md index b46473bd..4b9dabd6 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -48,7 +48,8 @@ default `dirichlet = :algebraic` that vector holds every dof and field `name` oc `dirichlet = :algebraic` (the default) keeps every dof as an unknown and makes each prescribed row the algebraic equation `u_d = g_d(t)`, so it accepts Dirichlet data of any time dependence. `dirichlet = :eliminate` removes the prescribed dofs instead: the `DAEProblem` has only the free -dofs as unknowns, with `M[fr, fr]`, `K[fr, fr]` and the load `F[fr] - K[fr, cd] g`. It needs +dofs as unknowns, with `M[fr, fr]`, `K[fr, fr]` and the load `F[fr] - K[fr, cd] g`; nonlinear +terms are evaluated at the full state with `u_cd = g` and keep their rows `fr`. It needs Dirichlet data that are constant in time, though they may vary in space; time-dependent data raise an `ArgumentError` naming the boundary piece. The solution is the same either way: `sol[u]`, `sol(t, x, y)`, traces `sol[u(t, Γ)]`, `normal_flux` and `write_vtk` all return the diff --git a/src/discretization.jl b/src/discretization.jl index 45410eaa..07d7bc53 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -27,7 +27,8 @@ gives a `PDENoTimeSolution`. - `dirichlet`: how Dirichlet conditions enter the DAE (spec §7.3). The default `:algebraic` keeps every dof as an unknown and makes each prescribed row the algebraic equation `u_d = g_d(t)`. `:eliminate` removes the prescribed dofs: the unknowns are the free dofs - `fr`, the operators are `M[fr, fr]` and `K[fr, fr]` and the load is `F[fr] - K[fr, cd] g`. + `fr`, the operators are `M[fr, fr]` and `K[fr, fr]` and the load is `F[fr] - K[fr, cd] g`; + nonlinear terms are evaluated at the full state with `u_cd = g` and keep their rows `fr`. It needs Dirichlet data that are constant in time (they may vary in space); data that depend on time raise `ArgumentError("dirichlet = :eliminate needs Dirichlet data that are constant in time, but the condition on boundary piece depends on time; use the default diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index 2f68d086..b1173ad4 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -98,6 +98,8 @@ prescribed dofs, whose rows of `N` and of its Jacobian are then zero. `op` is un the parameter has one concrete type; each call dispatches on it once. `op` itself is never evaluated: each evaluation borrows a copy with its own buffers and values objects from a pool, so problems sharing this wrapper (remakes, ensembles) can be solved concurrently. +After [`eliminate_dirichlet`](@ref) the wrapper evaluates `N` at the full state rebuilt from +the free dofs with `u_d = g_d`, and keeps its free rows and its `[free, free]` Jacobian block. The element pipeline is `Float64`: `N` is evaluated at `Float64` states and at first-order `ForwardDiff.Dual`s of `Float64` (as the default initializer passes), whose partials go through @@ -113,8 +115,9 @@ struct FEMNonlinear prescribed::BitVector pool::Vector{Any} lock::ReentrantLock + elimination::Any # `nothing`, or `(e::DirichletElimination, nzmap)` with `nzmap` the positions of `J_N[free, free]` in `J_N` end -FEMNonlinear(op, p, prescribed = falses(0)) = FEMNonlinear(op, collect(Float64, p), prescribed, Any[], ReentrantLock()) +FEMNonlinear(op, p, prescribed = falses(0)) = FEMNonlinear(op, collect(Float64, p), prescribed, Any[], ReentrantLock(), nothing) Base.show(io::IO, ::FEMNonlinear) = print(io, "FEMNonlinear") # `f(op)` with an operator no other running call holds; the pool grows to the number of concurrent calls. @@ -132,9 +135,16 @@ check_state(::AbstractVector{Float64}) = nothing check_state(::AbstractVector{<:ForwardDiff.Dual{<:Any, Float64}}) = nothing check_state(u) = throw(ArgumentError("the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got $(eltype(u))")) -# `r .+= N(u, t)` outside the prescribed rows. +# `r .+= N(u, t)` outside the prescribed rows. After elimination `u` and `r` hold the free dofs only. function add_nonlinear!(r, N::FEMNonlinear, u, t) check_state(u) + N.elimination === nothing && return add_full_nonlinear!(r, N, u, t) + e = first(N.elimination) + r .+= view(add_full_nonlinear!(zeros(eltype(r), e.n), N, full_state(e, u), t), e.free) + return r +end + +function add_full_nonlinear!(r, N::FEMNonlinear, u, t) return with_operator(N) do op residual!(op.r, op, u, N.p, t) for i in eachindex(r) @@ -146,7 +156,7 @@ end # ForwardDiff states, as from the default initializer's NewtonRaphson: the partials are pushed through the # analytic tangent, `∂N(u) = J_N(value(u)) ∂u`, since the element buffers hold `Float64`. -function add_nonlinear!(r, N::FEMNonlinear, u::AbstractVector{ForwardDiff.Dual{T, Float64, P}}, t) where {T, P} +function add_full_nonlinear!(r, N::FEMNonlinear, u::AbstractVector{ForwardDiff.Dual{T, Float64, P}}, t) where {T, P} du = [ForwardDiff.partials(x, k) for x in u, k in 1:P] return with_operator(N) do op J = jacobian!(op.J, op, ForwardDiff.value.(u), N.p, t) @@ -164,12 +174,21 @@ nonlinear_residual!(r, N::FEMNonlinear, u, t) = add_nonlinear!(fill!(r, 0), N, u function add_nonlinear_jacobian!(J, N::FEMNonlinear, u, t) u isa AbstractVector{Float64} || throw(ArgumentError("the nonlinear operator's Jacobian evaluates Float64 states; got $(eltype(u))")) + elimination = N.elimination return with_operator(N) do op - JN = jacobian!(op.J, op, u, N.p, t) - check_pattern(J, JN, "Nop") - rows, vals, out = rowvals(JN), nonzeros(JN), nonzeros(J) - for k in eachindex(rows) - N.prescribed[rows[k]] || (out[k] += vals[k]) + if elimination === nothing + JN = jacobian!(op.J, op, u, N.p, t) + check_pattern(J, JN, "Nop") + rows, vals, out = rowvals(JN), nonzeros(JN), nonzeros(J) + for k in eachindex(rows) + N.prescribed[rows[k]] || (out[k] += vals[k]) + end + else + e, nzmap = elimination + vals, out = nonzeros(jacobian!(op.J, op, full_state(e, u), N.p, t)), nonzeros(J) + for k in eachindex(nzmap) + out[k] += vals[nzmap[k]] + end end J end @@ -305,7 +324,8 @@ time, so `g' = 0` and the term `M[fr, cd] g'` vanishes; time-dependent data, and with every dof prescribed, throw an `ArgumentError`. The field ranges of `reduced` count free dofs only, and a field whose dofs are all prescribed is left out of them; `full_state(elimination, u_free)` rebuilds -the full dof vector with `u[cd] = g`. +the full dof vector with `u[cd] = g`. A nonlinear part `N` is kept: it is evaluated at that +full vector, with its rows `fr` and its Jacobian block `[fr, fr]`. """ function eliminate_dirichlet(ops::FEMOperators) F = ops.load @@ -331,7 +351,14 @@ function eliminate_dirichlet(ops::FEMOperators) stop += nfree end reduced = FEMOperators(ops.M[free, free], ops.K[free, free], load, fields) - return reduced, DirichletElimination(n, free, ops.prescribed, g) + elimination = DirichletElimination(n, free, ops.prescribed, g) + N = ops.nonlinear + N === nothing && return reduced, elimination + # The positions of the stored entries of K[free, free], which has the pattern of N's Jacobian block. + positions = SparseMatrixCSC(n, n, ops.K.colptr, ops.K.rowval, collect(eachindex(nonzeros(ops.K)))) + Nfree = FEMNonlinear(N.op, N.p, N.prescribed, Any[], ReentrantLock(), (elimination, nonzeros(positions[free, free]))) + (; M, K, load, fields, prescribed, differential_vars, jac_prototype) = reduced + return FEMOperators(M, K, load, fields, prescribed, differential_vars, jac_prototype, Nfree), elimination end """ diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index 3e62fe0c..dd8d903c 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -171,7 +171,7 @@ end @test FiniteElementMethod.ForwardDiff.value.(rd) ≈ r end - @testset "steady nonlinear diffusion, dirichlet = $dirichlet" for dirichlet in (:algebraic,) + @testset "steady nonlinear diffusion, dirichlet = $dirichlet" for dirichlet in (:algebraic, :eliminate) # ∇·((1 + u*²)∇u*) = 2u*|∇u*|² = 10u* for u* = 1 + x + 2y, which lies in the P1 space. Ω = square() us = 1 + x + 2y @@ -185,6 +185,30 @@ end @test maximum(abs(sol(px, py; dv = u(x, y)) - (1 + px + 2py)) for px in pts, py in pts) <= tol end + @testset "dirichlet = :eliminate keeps the nonlinear terms" begin + # u* = 1 + x + 2y is steady, so its Dirichlet data are constant in time; the sources cancel the diffusion + # (10u*) and reaction (u*²) terms at u*, so u stays u* only if N is evaluated. + Ω = square() + us = 1 + x + 2y + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) - U^2 + us^2 - 10 * us + bcs = [[u(t, Γ) ~ us for Γ in sides(Ω)]; u(0, x, y) ~ us] + exact(t_, x_, y_) = 1 + x_ + 2y_ + sole, probe = fem_solve([eq], bcs, Ω, (x, y), t, [U]; dirichlet = :eliminate) + sola, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sole) + @test nodal_error(sole, U, exact) <= tol + @test maximum(abs, sole[U][end, :] - sola[U][end, :]) <= tol + @test any(p -> nameof(p) === :Nop, ModelingToolkit.parameters(probe.f.sys)) + # The analytic Jacobian on the free dofs against central differences of the reduced residual. + n = length(probe.u0) + rng_u = [1.0 + 0.1 * sin(3i) for i in 1:n] + rng_du = [0.2 * cos(5i) for i in 1:n] + J = copy(probe.f.jac_prototype) + probe.f.jac(J, rng_du, rng_u, probe.p, 0.7, 0.4) + Jfd = fd_jacobian(probe, rng_du, rng_u, 0.7, 0.4) + @test norm(Matrix(J) - Jfd, Inf) <= 1.0e-7 * norm(Jfd, Inf) + end + @testset "a parameter changed by remake is rejected, not ignored" begin # The operators, the nonlinear one included, hold the values they were assembled with (spec §8.3). Ω = square() From e0d9c3573901636c8fc755ea075a678bfd413164 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 18:05:26 +0000 Subject: [PATCH 30/62] Count a nonlinear term in a field as presence in the algebraic_abstol index-2 test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With nonlinear terms (#30) a constraint such as 0 = v² − u has a zero linear block for v yet determines v (index 1); :auto saw only K and put v's rows out of error control with abstol 1e8. The nonlinear Jacobian shares K's full pattern, so the test now reads the weak form: a field whose own equation has a nonlinear term in its value, gradient or Hessian is present in its equation. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 92cffeeb-1b19-43fa-993b-e64f8ad21ec9 Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 3 ++- src/frontend.jl | 26 +++++++++++++++++-------- test/shared/frontend_tests/nonlinear.jl | 22 +++++++++++++++++++++ 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index e111165f..9163a864 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -36,7 +36,8 @@ gives a `PDENoTimeSolution`. (those with `differential_vars` false: algebraic fields and Dirichlet rows), so that they are left out of the solver's error control. `:auto` sets `1e8` when the system has index 2, that is when an algebraic field's own unknowns are absent from its equation (the - pressure in `0 ~ Dx(u1) + Dy(u2)`), and nothing otherwise; a positive number sets that + pressure in `0 ~ Dx(u1) + Dy(u2)`; a nonlinear term in the field, as in `0 ~ v^2 - u`, + counts as present), and nothing otherwise; a positive number sets that value on the algebraic rows of any system; `nothing` sets nothing. The differential rows get the `abstol` passed to `FEMDiscretization` or `DAEProblem` if it is a number, else OrdinaryDiffEq's default `1e-6`; an array `abstol` passed there is used as it is. An diff --git a/src/frontend.jl b/src/frontend.jl index 09b77769..f59bd2b7 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -374,7 +374,8 @@ function _lower(pdesys, disc::FEMDiscretization) pieces = Dict{Any, String}(Γ => String(Γ.name) for Γ in PDEBase.boundarypieces(disc.domain)) md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0, elimination) parameters = [q => v for (q, v) in zip(ctx.params, pvals)] - return (; ops, u0 = unknown_u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys), parameters) + selfnonlinear = Set(names[f] for f in 1:an.nfields if _nonlinear_in_own_field(wf, an, f)) + return (; ops, u0 = unknown_u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys), parameters, selfnonlinear) end # `K u + N(u, t0) - F` with the Dirichlet rows `u_d - g_d`: `K` holds `e_d`, `F` holds `g_d` and `N` is zero there. @@ -432,24 +433,33 @@ function SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscre return numeric_dae_problem( parts.ops, parts.u0, parts.tspan, parts.md; iv = parts.iv, unknowns = parts.unknowns, name = parts.name, parameters = parts.parameters, kwargs..., - _abstol(disc.algebraic_abstol, parts.ops, get(kwargs, :abstol, nothing))... + _abstol(disc.algebraic_abstol, parts.ops, parts.selfnonlinear, get(kwargs, :abstol, nothing))... ) end # An algebraic field whose own unknowns are absent from its equation (the pressure in the continuity equation) is -# fixed only through the other fields, which makes the DAE index 2. -function _index2(ops::FEMOperators) +# fixed only through the other fields, which makes the DAE index 2. The nonlinear Jacobian shares K's pattern and +# says nothing about which blocks are zero, so a field in `selfnonlinear`, whose equation has a nonlinear term in +# the field itself (0 = v² − u), counts as present. +function _index2(ops::FEMOperators, selfnonlinear) free = trues(size(ops.K, 1)) free[ops.prescribed] .= false - return any(ops.fields) do (_, r) + return any(ops.fields) do (name, r) rows = filter(i -> free[i], r) - !isempty(rows) && !any(ops.differential_vars[rows]) && iszero(ops.K[rows, r]) + !isempty(rows) && !(name in selfnonlinear) && !any(ops.differential_vars[rows]) && iszero(ops.K[rows, r]) end end +# Whether a nonlinear term of equation `f` (paired with field `f`) reads field `f`'s value, gradient or Hessian. +function _nonlinear_in_own_field(wf, an, f) + d = an.dim + own = [an.slots.U[f]; an.slots.G[((f - 1) * d + 1):(f * d)]; an.slots.H[((f - 1) * d * d + 1):(f * d * d)]] + return any(term -> term.kind === :nonlinear && term.eq == f && _depends(unwrap(term.integrand), own), [wf.volume; wf.facet]) +end + # The `abstol` keyword of the `DAEProblem` (see `FEMDiscretization`'s `algebraic_abstol`); empty when none is set. -function _abstol(algebraic, ops, abstol) - algebraic === :auto && (algebraic = _index2(ops) ? 1.0e8 : nothing) +function _abstol(algebraic, ops, selfnonlinear, abstol) + algebraic === :auto && (algebraic = _index2(ops, selfnonlinear) ? 1.0e8 : nothing) (algebraic === nothing || !(abstol isa Union{Nothing, Real})) && return (;) differential = something(abstol, 1.0e-6) return (; abstol = [d ? differential : algebraic for d in ops.differential_vars]) diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index dd8d903c..df378270 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -71,6 +71,28 @@ end @test nodal_error(sol, U, uexact) <= tol end + @testset "algebraic field fixed by a nonlinear term in itself (index 1) keeps its abstol" begin + # 0 = v² − u − s with v* = 1 + x + 2y: v's linear block is zero, but v² determines v, so the system has + # index 1 and algebraic_abstol = :auto must not put v out of error control. + @variables v(..) + V = v(t, x, y) + Ω = square() + parabolic = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) + constraint = 0 ~ V^2 - U - ((1 + x + 2y)^2 - ustar) + bcs = [dirichlet(Ω); ic; v(0, x, y) ~ 1 + x + 2y] + sol, prob = fem_solve( + [parabolic, constraint], bcs, Ω, (x, y), t, [U, V]; pairing = Dict(constraint => v), + abstol = 1.0e-10, solve_kwargs = (; reltol = 1.0e-10) + ) + @test !any(prob.differential_vars[FiniteElementMethod.field_range(sol.disc_data.space, :v)]) + @test prob.kwargs[:abstol] === 1.0e-10 + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + @test nodal_error(sol, V, (_, x_, y_) -> 1 + x_ + 2y_) <= tol + @named pdesys = PDESystem([parabolic, constraint], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U, V], []) + @test !haskey(discretize(pdesys, FEMDiscretization(Ω, t; pairing = Dict(constraint => v))).kwargs, :abstol) + end + @testset "Burgers-type convection u(∂ₓu + ∂ᵧu)" begin # u*(∂ₓu* + ∂ᵧu*) = 3u*(1 + t). Ω = square() From 02dfb044bd4109ed9f761e5de7c11a5beaffb9aa Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 19:19:23 +0000 Subject: [PATCH 31/62] Say what is unsupported instead of citing milestones in error messages Errors and docstrings named internal milestones ("land in M3", "need milestone M4") that users cannot interpret. Each now states the unsupported feature and, where there is one, the alternative. _PERIODIC_M4 becomes _PERIODIC_UNSUPPORTED. The mixed-cell-type rejection gets its first exact-message test. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 6b93c7d8-ef3a-4654-a0dd-60f0e512bd1c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 4 ++-- src/frontend.jl | 14 +++++++------- test/Frontend/messages.jl | 9 +++++++++ test/shared/frontend_tests/errors.jl | 8 ++++---- test/shared/frontend_tests/messages.jl | 24 ++++++++++++++++++++++++ test/shared/frontend_tests/nonlinear.jl | 2 +- 6 files changed, 47 insertions(+), 14 deletions(-) create mode 100644 test/Frontend/messages.jl create mode 100644 test/shared/frontend_tests/messages.jl diff --git a/src/discretization.jl b/src/discretization.jl index 9163a864..de171c78 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -61,7 +61,7 @@ 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. - - `codegen = :mtk` is reserved for a later milestone and raises; remaining keywords are + - `codegen = :mtk` is reserved and raises; remaining keywords are passed to the `DAEProblem` (or `NonlinearProblem`), where a keyword given at the `DAEProblem`/`NonlinearProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters` are set by the discretization and rejected. @@ -119,7 +119,7 @@ function FEMDiscretization( ) domain.mesh isa Ferrite.Grid || throw(ArgumentError("FEMDiscretization needs a MeshDomain of a Ferrite.Grid, got a mesh of type $(typeof(domain.mesh))")) - codegen === :mtk && throw(ArgumentError("codegen = :mtk lands in M3; use the default codegen = :numeric")) + codegen === :mtk && throw(ArgumentError("codegen = :mtk is not supported; use the default codegen = :numeric")) codegen === :numeric || throw(ArgumentError("codegen must be :numeric, got $(repr(codegen))")) dirichlet in (:algebraic, :eliminate) || throw(ArgumentError("dirichlet must be :algebraic or :eliminate, got $(repr(dirichlet))")) diff --git a/src/frontend.jl b/src/frontend.jl index f59bd2b7..9d38c718 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -8,7 +8,7 @@ # Tracking: move to PDEBase's `symbolic_discretize` with hook methods once the numeric path builds # its system through `generate_system` (PDEBase M0 release as the compat floor). -const _PERIODIC_M4 = "periodic conditions need milestone M4 (Ferrite PeriodicDirichlet)" +const _PERIODIC_UNSUPPORTED = "periodic boundary conditions are not supported" _unwrap_arg(a) = SymbolicUtils.unwrap_const(unwrap(a)) @@ -89,7 +89,7 @@ function PDEBase.interface_errors(pdesys::ModelingToolkit.PDESystem, v::PDEBase. for u in dvs args = SymbolicUtils.arguments(unwrap(u)) t !== nothing && any(a -> isequal(a, t), args) && !isequal(first(args), t) && - throw(ArgumentError("time must be the first argument of $u; time-last ordering lands later")) + throw(ArgumentError("time must be the first argument of $u; time-last ordering is not supported")) end grid = disc.domain.mesh if !isconcretetype(Ferrite.getcelltype(grid)) @@ -100,7 +100,7 @@ function PDEBase.interface_errors(pdesys::ModelingToolkit.PDESystem, v::PDEBase. "`spaces`; $(join(unset, ", ")) has none" ) ) - throw(ArgumentError("meshes with mixed cell types land in M4")) + throw(ArgumentError("meshes with mixed cell types are not supported; use a mesh with a single cell type")) end check_facetsets(grid, [Γ.name for Γ in _condition_pieces(pdesys.bcs)]) return nothing @@ -108,7 +108,7 @@ end function _boundary_map(bcs, v, disc) for eq in bcs - length(_trace_pieces(eq.lhs - eq.rhs)) > 1 && throw(ArgumentError("$(_PERIODIC_M4): $eq")) + length(_trace_pieces(eq.lhs - eq.rhs)) > 1 && throw(ArgumentError("$(_PERIODIC_UNSUPPORTED): $eq")) end orders = Dict(x => PDEBase.d_orders(x, bcs) for x in PDEBase.all_ivs(v)) return PDEBase.parse_bcs(bcs, v, orders, disc) @@ -170,7 +170,7 @@ end function _check_terms(wf) for term in vcat(wf.volume, wf.facet) term.kind in (:mass, :bilinear) && term.timedep && throw( - ArgumentError("time-dependent coefficients in the mass or stiffness operator land in M3: equation $(term.eq) has $(term.integrand)") + ArgumentError("time-dependent coefficients in the mass or stiffness operator are not supported: equation $(term.eq) has $(term.integrand)") ) end return nothing @@ -331,7 +331,7 @@ function _lower(pdesys, disc::FEMDiscretization) ics, bcmap = PDEBase.split_ics_bcs(boundarymap, v, disc) ctx = StrongForm.SlotContext(sys, v) an = _paired(StrongForm.analyse(sys, v, boundarymap; ibp = disc.ibp), pdesys.eqs, ctx, disc) - isempty(an.periodic) || throw(ArgumentError(_PERIODIC_M4)) + isempty(an.periodic) || throw(ArgumentError(_PERIODIC_UNSUPPORTED)) covered = Set(Γ for bykey in values(bcmap) for (Γ, bs) in bykey if !isempty(bs)) if any(c -> !all(x -> isequal(x, 0), c), an.conormal) for Γ in PDEBase.boundarypieces(disc.domain) @@ -408,7 +408,7 @@ the Galerkin operators, with Dirichlet rows `u_d = g_d(t)` as algebraic equation `dirichlet = :eliminate`, restricted to the free dofs), a sparse analytic Jacobian (the nonlinear part `N` from the terms whose coefficients depend on the state, with its symbolic tangent) and the `FEMMetadata` as its `problem_type`, so `solve` returns a -`PDETimeSeriesSolution`. Nothing calls `mtkcompile`; anything this milestone cannot +`PDETimeSeriesSolution`. Nothing calls `mtkcompile`; anything it cannot discretize raises. Keywords are passed to the `DAEProblem` after `disc.kwargs`, so a keyword given here wins; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, `name`, `parameters`) are rejected. The problem carries an `abstol` vector when `disc.algebraic_abstol` diff --git a/test/Frontend/messages.jl b/test/Frontend/messages.jl new file mode 100644 index 00000000..3a0d7499 --- /dev/null +++ b/test/Frontend/messages.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "messages.jl")) +else + @testset "messages (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index 98b3d215..32a9771a 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -77,13 +77,13 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] Ω = box() Γl, Γr = sides(Ω) @test_throws ArgumentError( - "periodic conditions need milestone M4 (Ferrite PeriodicDirichlet): u(t, Γ_left) ~ u(t, Γ_right)" + "periodic boundary conditions are not supported: u(t, Γ_left) ~ u(t, Γ_right)" ) lower([heat], [u(t, Γl) ~ u(t, Γr), ic], Ω) end @testset "reserved options" begin Ω = box() - @test_throws ArgumentError("codegen = :mtk lands in M3; use the default codegen = :numeric") FEMDiscretization( + @test_throws ArgumentError("codegen = :mtk is not supported; use the default codegen = :numeric") FEMDiscretization( Ω, t; codegen = :mtk ) @test_throws ArgumentError("dirichlet must be :algebraic or :eliminate, got :condense") FEMDiscretization( @@ -134,7 +134,7 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] Ω = box() td = Dt(u(t, x, y)) ~ Dx((1 + t) * Dx(u(t, x, y))) + Dy((1 + t) * Dy(u(t, x, y))) @test_throws ArgumentError( - "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has " * + "time-dependent coefficients in the mass or stiffness operator are not supported: equation 1 has " * "G₁*W₁ + G₂*W₂ + G₁*T*W₁ + G₂*T*W₂" ) lower([td], [dirichlet(Ω); ic], Ω) end @@ -175,7 +175,7 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] Ω = box() eq = Dt(u(x, y, t)) ~ Dx(Dx(u(x, y, t))) + Dy(Dy(u(x, y, t))) bcs = [u(x, y, 0) ~ 0] - @test_throws ArgumentError("time must be the first argument of u(x, y, t); time-last ordering lands later") lower( + @test_throws ArgumentError("time must be the first argument of u(x, y, t); time-last ordering is not supported") lower( [eq], bcs, Ω; dvs = [u(x, y, t)] ) end diff --git a/test/shared/frontend_tests/messages.jl b/test/shared/frontend_tests/messages.jl new file mode 100644 index 00000000..25ee79e3 --- /dev/null +++ b/test/shared/frontend_tests/messages.jl @@ -0,0 +1,24 @@ +# Exact messages of front-end errors not covered in errors.jl. +using Test +using Ferrite: Ferrite, Triangle, Quadrilateral, Grid, Node, Vec, Lagrange, RefTriangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +@testset "front-end messages" begin + @testset "mixed cell types" begin + nodes = [Node(Vec(0.0, 0.0)), Node(Vec(1.0, 0.0)), Node(Vec(0.0, 1.0)), Node(Vec(2.0, 0.0)), Node(Vec(1.0, 1.0))] + grid = Grid(Ferrite.AbstractCell[Triangle((1, 2, 3)), Quadrilateral((2, 4, 5, 3))], nodes) + Ω = MeshDomain(grid) + heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + @named pdesys = PDESystem([heat], [u(0, x, y) ~ 0], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 1}())) + @test_throws ArgumentError("meshes with mixed cell types are not supported; use a mesh with a single cell type") discretize( + pdesys, disc + ) + end +end diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index df378270..f2ba582a 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -270,6 +270,6 @@ end ) # The front end's own: a time-dependent coefficient in a linear operator would need reassembly. @test_throws ArgumentError( - "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has G₁*W₁ + G₁*T*W₁" + "time-dependent coefficients in the mass or stiffness operator are not supported: equation 1 has G₁*W₁ + G₁*T*W₁" ) lower([Dt(U) ~ Dx((1 + t) * Dx(U))]) end From 7843a720c187061cd651e8e53466ed7a38f601e7 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 19:21:22 +0000 Subject: [PATCH 32/62] Make symbolic_discretize a documented contract that forwards keywords Under the SciMLBase Core Extension Contract the return of symbolic_discretize is public contract and must describe the discretization discretize builds. It now takes discretize's keywords (forwarded to the same DAEProblem construction, so reserved keywords fail identically), rejects extra positional arguments with an ArgumentError, and has a docstring in the manual. A steady discretization keeps its documented ArgumentError: its NonlinearProblem is built from a NonlinearFunction with f.sys === nothing, so there is no System to return; the test pins that evidence. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 6b93c7d8-ef3a-4654-a0dd-60f0e512bd1c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 1 + src/frontend.jl | 27 ++++++++-- test/Frontend/symbolic.jl | 9 ++++ test/shared/frontend_tests/errors.jl | 4 -- test/shared/frontend_tests/symbolic.jl | 69 ++++++++++++++++++++++++++ 5 files changed, 103 insertions(+), 7 deletions(-) create mode 100644 test/Frontend/symbolic.jl create mode 100644 test/shared/frontend_tests/symbolic.jl diff --git a/docs/discretization.md b/docs/discretization.md index 19265228..b739604a 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -8,6 +8,7 @@ FEMDiscretization FiniteElementMethod.SciMLBase.DAEProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.SciMLBase.NonlinearProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) +FiniteElementMethod.SciMLBase.symbolic_discretize(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.AbstractTestSpace FiniteElementMethod.Galerkin FiniteElementMethod.assemble_sources! diff --git a/src/frontend.jl b/src/frontend.jl index f59bd2b7..0c9a6daf 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -497,14 +497,35 @@ end SciMLBase.discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) = disc.time === nothing ? NonlinearProblem(pdesys, disc; kwargs...) : DAEProblem(pdesys, disc; kwargs...) -# `(sys, tspan)`, the shape PDEBase and MethodOfLines return. -function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) +""" + symbolic_discretize(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) + +Return `(sys, tspan)`, the shape PDEBase and MethodOfLines return, for the discretization that +`discretize(pdesys, disc; kwargs...)` builds: it runs the same code path, so it assembles the +Galerkin operators, and returns the `DAEProblem`'s `prob.f.sys` and `prob.tspan`. `sys` is the +completed `ModelingToolkit.System` of [`FiniteElementMethod.fem_system`](@ref), whose unknowns are +the arrays of field values, with the operators as parameters and the `FEMMetadata` (the +problem's `problem_type`) attached for rebuilding the solution; `tspan` is the time interval of +`pdesys`. Keywords are passed to that problem construction as for `DAEProblem(pdesys, disc)`, +so the reserved keywords raise the same `ArgumentError`. Further positional arguments raise an +`ArgumentError`. + +A steady `disc` (no time variable) raises an `ArgumentError`: its `NonlinearProblem` is built +from a numeric `NonlinearFunction` with no `System`, so there is no symbolic system describing +it; call `discretize(pdesys, disc)` for the `NonlinearProblem`. +""" +function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization, args...; kwargs...) + isempty(args) || throw( + ArgumentError( + "symbolic_discretize(pdesys, disc; kwargs...) takes no further positional arguments; got $(length(args))" + ) + ) disc.time === nothing && throw( ArgumentError( "a steady FEMDiscretization builds no symbolic System, so it has no symbolic_discretize; " * "call discretize(pdesys, disc) for its NonlinearProblem" ) ) - prob = DAEProblem(pdesys, disc) + prob = DAEProblem(pdesys, disc; kwargs...) return prob.f.sys, prob.tspan end diff --git a/test/Frontend/symbolic.jl b/test/Frontend/symbolic.jl new file mode 100644 index 00000000..b0594b17 --- /dev/null +++ b/test/Frontend/symbolic.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "symbolic.jl")) +else + @testset "symbolic_discretize (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index 98b3d215..d712ffee 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -105,10 +105,6 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem, not a DAEProblem; " * "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" ) DAEProblem(steady, FEMDiscretization(Ω)) - @test_throws ArgumentError( - "a steady FEMDiscretization builds no symbolic System, so it has no symbolic_discretize; " * - "call discretize(pdesys, disc) for its NonlinearProblem" - ) SciMLBase.symbolic_discretize(steady, FEMDiscretization(Ω)) @named transient = PDESystem([heat], [dirichlet(Ω); ic], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) @test_throws ArgumentError( "the FEMDiscretization has the time variable t, so it lowers to a DAEProblem; " * diff --git a/test/shared/frontend_tests/symbolic.jl b/test/shared/frontend_tests/symbolic.jl new file mode 100644 index 00000000..61bd025a --- /dev/null +++ b/test/shared/frontend_tests/symbolic.jl @@ -0,0 +1,69 @@ +# `symbolic_discretize(pdesys, disc)` returns the `(sys, tspan)` of the discretization `discretize(pdesys, disc)` builds. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid +using Ferrite: Triangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t, ProblemTypeCtx + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +@testset verbose = true "symbolic_discretize" begin + Ω = MeshDomain(rectangle_grid(Triangle, (2, 2))) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + bcs = [[u(t, Γ) ~ 0 for Γ in sides]; u(0, x, y) ~ x] + @named pdesys = PDESystem([heat], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t) + + @testset "the system and time span of discretize" begin + sys, tspan = SciMLBase.symbolic_discretize(pdesys, disc) + prob = discretize(pdesys, disc) + @test sys isa ModelingToolkit.System + @test tspan == prob.tspan == (0.0, 0.5) + @test isequal(unknowns(sys), unknowns(prob.f.sys)) + @test length(equations(sys)) == length(equations(prob.f.sys)) + @test isequal(ModelingToolkit.parameters(sys), ModelingToolkit.parameters(prob.f.sys)) + md = ModelingToolkit.getmetadata(sys, ProblemTypeCtx, nothing) + @test ModelingToolkit.getmetadata(prob.f.sys, ProblemTypeCtx, nothing) === prob.problem_type + @test md isa FEMMetadata + @test md.metadata[] === sys + @test sprint(show, md) == sprint(show, prob.problem_type) == "FEMMetadata(fields = [u], ndofs = 9, hasTime = true)" + @test isequal(md.x̄, prob.problem_type.x̄) + @test isequal([f.dv for f in md.fields], [f.dv for f in prob.problem_type.fields]) + @test md.u0 == prob.problem_type.u0 + @test md.pieces == prob.problem_type.pieces + end + + @testset "keywords reach the problem construction of discretize" begin + sys, tspan = SciMLBase.symbolic_discretize(pdesys, disc; saveat = 0.25) + @test tspan == (0.0, 0.5) + @test isequal(unknowns(sys), unknowns(discretize(pdesys, disc; saveat = 0.25).f.sys)) + reserved = "keyword `du0` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name, parameters" + @test_throws ArgumentError(reserved) discretize(pdesys, disc; du0 = zeros(9)) + @test_throws ArgumentError(reserved) SciMLBase.symbolic_discretize(pdesys, disc; du0 = zeros(9)) + end + + @testset "no further positional arguments" begin + @test_throws ArgumentError( + "symbolic_discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 1" + ) SciMLBase.symbolic_discretize(pdesys, disc, :extra) + @test_throws ArgumentError( + "symbolic_discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 2" + ) SciMLBase.symbolic_discretize(pdesys, disc, 1, 2) + end + + # The steady path builds its NonlinearProblem from a bare NonlinearFunction, with no System to return. + @testset "steady discretization" begin + @named steady = PDESystem( + [Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in sides], [(x, y) ∈ Ω], [x, y], [u(x, y)], [] + ) + @test NonlinearProblem(steady, FEMDiscretization(Ω)).f.sys === nothing + @test_throws ArgumentError( + "a steady FEMDiscretization builds no symbolic System, so it has no symbolic_discretize; " * + "call discretize(pdesys, disc) for its NonlinearProblem" + ) SciMLBase.symbolic_discretize(steady, FEMDiscretization(Ω)) + end +end From a1bee544a1cb450577525a6d9ebe13fa81d6e45f Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 19:40:11 +0000 Subject: [PATCH 33/62] Reject derived keywords, extra positionals and non-PDESystems in discretize discretize silently took tspan, u0, p and differential_vars, which the discretization computes or overrides, and raised a MethodError for extra positional arguments or a first argument that is not a PDESystem. The SciMLBase Core Extension Contract asks for clean errors on what a discretizer does not support, so each now raises an ArgumentError that says where the value comes from instead. Problem and solve keywords (saveat, tstops, abstol, callback, and unknown ones) are still forwarded to the problem. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 6b93c7d8-ef3a-4654-a0dd-60f0e512bd1c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 14 +++- src/frontend.jl | 13 +++- test/Frontend/arguments.jl | 9 +++ test/shared/frontend_tests/arguments.jl | 95 +++++++++++++++++++++++++ 4 files changed, 128 insertions(+), 3 deletions(-) create mode 100644 test/Frontend/arguments.jl create mode 100644 test/shared/frontend_tests/arguments.jl diff --git a/src/discretization.jl b/src/discretization.jl index 9163a864..b487e2fb 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -64,7 +64,8 @@ gives a `PDENoTimeSolution`. - `codegen = :mtk` is reserved for a later milestone and raises; remaining keywords are passed to the `DAEProblem` (or `NonlinearProblem`), where a keyword given at the `DAEProblem`/`NonlinearProblem`/`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate`, - `name` and `parameters` are set by the discretization and rejected. + `name` and `parameters` are set by the discretization and rejected, as are `tspan`, `u0`, `p` + and `differential_vars`, which come from the `PDESystem` and the weak form. Pieces come from `boundarypiece.(Ω, names)`; on an analytic DomainSets box write `boundarypiece.(Ref(rect), names)`, since DomainSets types do not broadcast as scalars. @@ -100,8 +101,19 @@ end # Keywords of `numeric_dae_problem` that the front end sets itself. const _RESERVED_KWARGS = (:iv, :unknowns, :du0, :coordinate, :name, :parameters) +# Problem keywords the front end computes, with where each value comes from instead. +const _DERIVED_KWARGS = ( + tspan = "the time span is the time domain of the PDESystem; change that domain to change it", + u0 = "the initial state comes from the PDESystem's initial conditions (a steady problem starts from zero " * + "with its Dirichlet data); change those, or call remake(prob; u0 = ...) on the returned problem", + p = "the parameter values are the PDESystem's parameter defaults; change those and discretize again " * + "(the operators are assembled at those values, so solve rejects remake(prob; p = ...))", + differential_vars = "which unknowns are differential is computed from the weak form (the fields with a time derivative)", +) + function _check_reserved(kwargs) for k in keys(kwargs) + haskey(_DERIVED_KWARGS, k) && throw(ArgumentError("keyword `$k` cannot be passed: " * _DERIVED_KWARGS[k])) k in _RESERVED_KWARGS && throw( ArgumentError( "keyword `$k` is set by the FEM discretization and cannot be passed; the reserved keywords are " * diff --git a/src/frontend.jl b/src/frontend.jl index f59bd2b7..868afabd 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -411,7 +411,9 @@ state, with its symbolic tangent) and the `FEMMetadata` as its `problem_type`, s `PDETimeSeriesSolution`. Nothing calls `mtkcompile`; anything this milestone cannot discretize raises. Keywords are passed to the `DAEProblem` after `disc.kwargs`, so a keyword given here wins; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, -`name`, `parameters`) are rejected. The problem carries an `abstol` vector when `disc.algebraic_abstol` +`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` applies (see [`FEMDiscretization`](@ref)). The Dirichlet rows are linear with identity Jacobian rows, so a Newton step with a current @@ -481,7 +483,8 @@ elsewhere, `remake(prob; u0)` with a vector laid out like `prob.u0`, the problem vector (with the default `dirichlet = :algebraic` it holds every dof, and field `name` occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`). Keywords are passed to the `NonlinearProblem` after `disc.kwargs`; the keywords -`iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters` are rejected, as for the `DAEProblem`. +`iv`, `unknowns`, `du0`, `coordinate`, `name`, `parameters`, `tspan`, `u0`, `p` and +`differential_vars` are rejected, as for the `DAEProblem`. """ function SciMLBase.NonlinearProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) _check_reserved(kwargs) @@ -497,6 +500,12 @@ end SciMLBase.discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) = disc.time === nothing ? NonlinearProblem(pdesys, disc; kwargs...) : DAEProblem(pdesys, disc; kwargs...) +SciMLBase.discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization, arg, args...; kwargs...) = + throw(ArgumentError("discretize(pdesys, disc; kwargs...) takes no further positional arguments; got $(length(args) + 1)")) + +SciMLBase.discretize(x, ::FEMDiscretization, args...; kwargs...) = + throw(ArgumentError("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got $(typeof(x))")) + # `(sys, tspan)`, the shape PDEBase and MethodOfLines return. function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) disc.time === nothing && throw( diff --git a/test/Frontend/arguments.jl b/test/Frontend/arguments.jl new file mode 100644 index 00000000..d896848f --- /dev/null +++ b/test/Frontend/arguments.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "arguments.jl")) +else + @testset "arguments (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/arguments.jl b/test/shared/frontend_tests/arguments.jl new file mode 100644 index 00000000..0f479920 --- /dev/null +++ b/test/shared/frontend_tests/arguments.jl @@ -0,0 +1,95 @@ +# What `discretize` accepts besides the PDESystem and the FEMDiscretization: problem and solve +# keywords are forwarded to the problem; keywords the discretization computes, further positional +# arguments and a first argument that is not a PDESystem raise. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid +using Ferrite: Ferrite, Triangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +box() = MeshDomain(rectangle_grid(Triangle, (2, 2))) +sides(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + +function heat_system(Ω) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + bcs = [[u(t, Γ) ~ 0 for Γ in sides(Ω)]; u(0, x, y) ~ 0] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + return pdesys +end + +function poisson_system(Ω) + eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ -1 + @named pdesys = PDESystem([eq], [u(Γ) ~ 0 for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + return pdesys +end + +const DERIVED_MESSAGES = ( + tspan = "keyword `tspan` cannot be passed: the time span is the time domain of the PDESystem; change that domain to change it", + u0 = "keyword `u0` cannot be passed: the initial state comes from the PDESystem's initial conditions " * + "(a steady problem starts from zero with its Dirichlet data); change those, or call remake(prob; u0 = ...) on the returned problem", + p = "keyword `p` cannot be passed: the parameter values are the PDESystem's parameter defaults; change those and " * + "discretize again (the operators are assembled at those values, so solve rejects remake(prob; p = ...))", + differential_vars = "keyword `differential_vars` cannot be passed: which unknowns are differential is computed " * + "from the weak form (the fields with a time derivative)", +) + +const DERIVED_VALUES = (tspan = (0.0, 2.0), u0 = zeros(9), p = [1.0], differential_vars = trues(9)) + +@testset verbose = true "discretize arguments" begin + Ω = box() + pdesys = heat_system(Ω) + disc = FEMDiscretization(Ω, t) + + @testset "solve keywords reach the problem and the solve" begin + calls = Ref(0) + callback = SciMLBase.DiscreteCallback((u, t, integrator) -> true, integrator -> (calls[] += 1); save_positions = (false, false)) + prob = discretize(pdesys, disc; saveat = 0.25, tstops = [0.3], abstol = 1.0e-8, callback) + @test prob.kwargs[:saveat] == 0.25 + @test prob.kwargs[:tstops] == [0.3] + @test prob.kwargs[:abstol] == 1.0e-8 + @test prob.kwargs[:callback] === callback + sol = solve(prob, EXACT_ROWS) + @test SciMLBase.successful_retcode(sol) + @test sol.t ≈ [0.0, 0.25, 0.5, 0.75, 1.0] + @test calls[] > 0 + end + + @testset "an unknown keyword is forwarded too" begin + @test discretize(pdesys, disc; foo = 1).kwargs[:foo] == 1 + end + + @testset "keyword `$k` is derived" for k in keys(DERIVED_MESSAGES) + kw = NamedTuple{(k,)}((DERIVED_VALUES[k],)) + @test_throws ArgumentError(DERIVED_MESSAGES[k]) discretize(pdesys, disc; kw...) + @test_throws ArgumentError(DERIVED_MESSAGES[k]) SciMLBase.DAEProblem(pdesys, disc; kw...) + end + + @testset "derived keywords in FEMDiscretization and NonlinearProblem" begin + @test_throws ArgumentError(DERIVED_MESSAGES.tspan) FEMDiscretization(Ω, t; tspan = (0.0, 2.0)) + @test_throws ArgumentError(DERIVED_MESSAGES.p) FEMDiscretization(Ω; p = [1.0]) + steady = poisson_system(Ω) + @test_throws ArgumentError(DERIVED_MESSAGES.u0) SciMLBase.NonlinearProblem(steady, FEMDiscretization(Ω); u0 = zeros(9)) + @test_throws ArgumentError(DERIVED_MESSAGES.u0) discretize(steady, FEMDiscretization(Ω); u0 = zeros(9)) + end + + @testset "further positional arguments" begin + @test_throws ArgumentError("discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 1") discretize( + pdesys, disc, (0.0, 1.0) + ) + @test_throws ArgumentError("discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 2") discretize( + pdesys, disc, 1, 2; saveat = 0.1 + ) + end + + @testset "first argument not a PDESystem" begin + @test_throws ArgumentError("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got Float64") discretize(1.0, disc) + @test_throws ArgumentError("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got Vector{Int64}") discretize( + [1, 2], disc, 1 + ) + end +end From 6f667e5f3b844795bfe1f00c7022c473b4527cb9 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 27 Oct 2026 20:26:16 +0000 Subject: [PATCH 34/62] Document discretize and how FEMDiscretization meets SciMLBase's extension contract SciMLBase's Core Extension Contract asks discretize for a solver-ready problem, forwarded keywords, clean validation errors and solution metadata. discretize had no docstring; it gets one, in the manual beside DAEProblem, NonlinearProblem and symbolic_discretize, and a new Extension contract page (built only with the front end, like the Discretization page) states each clause and how it is met. A test keeps the page's reserved keyword sets, quoted messages and types in step with the code. Agent-Harness: Claude Code 2.1.311 Agent-Model: claude-opus-5-5 Agent-Session: 6b93c7d8-ef3a-4654-a0dd-60f0e512bd1c Agent-Review: unreviewed Co-authored-by: Claude Code --- .gitignore | 3 +- docs/discretization.md | 1 + docs/extension_contract.md | 106 ++++++++++++++++++ docs/make.jl | 16 +-- src/frontend.jl | 20 ++++ test/Frontend/extension_contract.jl | 9 ++ .../frontend_tests/extension_contract.jl | 44 ++++++++ 7 files changed, 191 insertions(+), 8 deletions(-) create mode 100644 docs/extension_contract.md create mode 100644 test/Frontend/extension_contract.jl create mode 100644 test/shared/frontend_tests/extension_contract.jl diff --git a/.gitignore b/.gitignore index 9e958243..465121ea 100644 --- a/.gitignore +++ b/.gitignore @@ -24,5 +24,6 @@ docs/site/ Manifest.toml .vscode/ -# Copied from docs/discretization.md by docs/make.jl when the front end is available. +# Copied from docs/ by docs/make.jl when the front end is available. docs/src/discretization.md +docs/src/extension_contract.md diff --git a/docs/discretization.md b/docs/discretization.md index b739604a..5acc9a59 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -6,6 +6,7 @@ ```@docs FEMDiscretization +FiniteElementMethod.SciMLBase.discretize(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.SciMLBase.DAEProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.SciMLBase.NonlinearProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.SciMLBase.symbolic_discretize(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) diff --git a/docs/extension_contract.md b/docs/extension_contract.md new file mode 100644 index 00000000..bc74a2c4 --- /dev/null +++ b/docs/extension_contract.md @@ -0,0 +1,106 @@ +# Extension contract + +```@meta +CurrentModule = FiniteElementMethod +``` + +SciMLBase's +[Core Extension Contract](https://docs.sciml.ai/SciMLBase/stable/interfaces/PDE/#Core-Extension-Contract) +asks a discretizer for a `discretize` that returns a solver-ready problem, forwards the +problem-construction keywords, rejects what it cannot discretize with a clean error and keeps +the metadata to rebuild the PDE solution; `symbolic_discretize` is optional. This page states +how `FEMDiscretization` meets each clause. + +## `discretize` returns a solver-ready problem + +[`discretize(pdesys, disc; kwargs...)`](@ref SciMLBase.discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization)) +accepts a `ModelingToolkit.PDESystem` on a `MeshDomain` and returns + + - a [`DAEProblem`](@ref SciMLBase.DAEProblem(::ModelingToolkit.PDESystem, ::FEMDiscretization)) + when `disc` has a time variable, `FEMDiscretization(Ω, t)`, for a DAE solver such as `DFBDF`; + - a [`NonlinearProblem`](@ref SciMLBase.NonlinearProblem(::ModelingToolkit.PDESystem, ::FEMDiscretization)) + when it has none, `FEMDiscretization(Ω)`, for a nonlinear solver such as `NewtonRaphson`. + +Both carry the sparse analytic Jacobian and its prototype, so `solve(prob, alg)` needs nothing +else. `DAEProblem(pdesys, disc)` and `NonlinearProblem(pdesys, disc)` build the same problems +directly. + +## Keywords + +Keywords given to `FEMDiscretization` are stored in `disc.kwargs` and passed to the problem +first, then the keywords of the `discretize` call, so a call keyword wins over the same +keyword in `disc`. Every keyword not listed below is forwarded to the problem, as other SciML +problem constructors do: `saveat`, `tstops`, `abstol`, `reltol`, `callback` and any other solve +option are stored in `prob.kwargs` and reach `solve`. + +```julia +disc = FEMDiscretization(Ω, t; abstol = 1.0e-8) +prob = discretize(pdesys, disc; saveat = 0.1, abstol = 1.0e-10) # abstol 1e-10 wins +``` + +Ten keywords are reserved and raise an `ArgumentError`, from `FEMDiscretization` and from the +problem constructors alike. Six are set by the discretization itself and cannot be set at all: +`iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters`. Four are defined by the +`PDESystem` or computed by the discretization, and are set there instead: + +| Keyword | Comes from | To change it | +|:------------------- |:-------------------------------- |:------------------------------------------------------------------- | +| `tspan` | the time domain of the PDESystem | change that domain, `t ∈ Interval(t0, t1)` | +| `u0` | its initial conditions (steady: zero with the Dirichlet data) | change them, or `remake(prob; u0 = ...)` on the returned problem | +| `p` | its parameter defaults | change them and discretize again; the operators are assembled at those values, so `solve` rejects `remake(prob; p = ...)` | +| `differential_vars` | the weak form: the fields with a time derivative | change the equations | + +The error message says the same, for example +``keyword `tspan` cannot be passed: the time span is the time domain of the PDESystem; change that domain to change it``. + +## Validation + +What the discretization cannot handle raises an `ArgumentError` that says what is unsupported. +The checks include: + + - the call itself: further positional arguments + (`discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 1`) and a + first argument that is not a `PDESystem` + (`FEMDiscretization discretizes a ModelingToolkit.PDESystem; got ...`); + - domains: no `(x, y) ∈ MeshDomain(mesh)` pairing, a `MeshDomain` other than the + discretization's, a time variable not paired with an interval, a time interval with a steady + `disc` or the reverse, mixed cell types, interpolations on another reference shape; + - equations: an equation count that differs from the number of dependent variables, unknown + `pairing`, `spaces` or `regions` keys, time-dependent mass or stiffness coefficients, + parameters without a numeric value, SUPG with parameters in `τ` or `b`; + - boundary conditions: periodic conditions, conditions on facet sets the mesh lacks, a + region's field with conditions outside the region, time-dependent Dirichlet data with + `dirichlet = :eliminate`. + +These are checked before the operators are assembled. Initial conditions are checked against +the node coordinates during assembly: one that does not name a single dependent variable, is not +linear in it or is not finite at a node raises, as does a field with a time derivative and no +initial condition. The [Discretization](@ref) page describes what is supported. + +## Metadata and the solution + +The problem's `problem_type` is a [`FEMMetadata`](@ref), a subtype of +`SciMLBase.AbstractDiscretizationMetadata{hasTime}` that holds the dof handler, the fields, +the boundary pieces and the `PDESystem`. After the solve, `SciMLBase.wrap_sol` passes the +solver's solution and that metadata to the constructors FiniteElementMethod defines, +`PDETimeSeriesSolution(sol, md::FEMMetadata)` (with time) and +`PDENoTimeSolution(sol, md::FEMMetadata)` (steady), so `solve` returns a solution indexed and +called in the `PDESystem`'s variables, `sol[u(t, x, y)]` and `sol(t, x, y; dv)`; see +[Solutions](@ref). The solver's own solution stays in `sol.original_sol`. + +## `symbolic_discretize` + +[`symbolic_discretize(pdesys, disc; kwargs...)`](@ref SciMLBase.symbolic_discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization)) +returns the tuple `(sys, tspan)`, the shape PDEBase and MethodOfLines return; this return type +is part of the public interface. It runs the code path of `discretize`, takes the same keywords +with the same errors, and returns `prob.f.sys`, the completed `ModelingToolkit.System` with the +`FEMMetadata` attached, and `prob.tspan`. A steady `disc` raises an `ArgumentError`, because its +`NonlinearProblem` has no symbolic system; use `discretize` for it. + +## Subtyping + +Nothing in the contract requires a discretizer to subtype `SciMLBase.AbstractDiscretization`, +and nothing in FiniteElementMethod dispatches on it. `FEMDiscretization{T}` subtypes +`PDEBase.AbstractMeshDiscretization` (under `PDEBase.AbstractEquationSystemDiscretization` and +`SciMLBase.AbstractDiscretization`) so that PDEBase's mesh-domain machinery, such as +`PDEBase.interface_errors` and the boundary parsing, applies to it. diff --git a/docs/make.jl b/docs/make.jl index a8bd2301..571506ff 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -4,13 +4,15 @@ include("pages.jl") # The PDESystem front end exists only when the installed PDEBase has the mesh layer # (`FiniteElementMethod.MESH_PDEBASE`), and Documenter expands every page under src/, so its -# page is copied in only then. -frontend_page = joinpath(@__DIR__, "src", "discretization.md") -if FiniteElementMethod.MESH_PDEBASE - cp(joinpath(@__DIR__, "discretization.md"), frontend_page; force = true) - insert!(pages, length(pages), "Discretization" => "discretization.md") -else - rm(frontend_page; force = true) +# pages are copied in only then. +for (title, file) in ("Discretization" => "discretization.md", "Extension contract" => "extension_contract.md") + frontend_page = joinpath(@__DIR__, "src", file) + if FiniteElementMethod.MESH_PDEBASE + cp(joinpath(@__DIR__, file), frontend_page; force = true) + insert!(pages, length(pages), title => file) + else + rm(frontend_page; force = true) + end end makedocs( diff --git a/src/frontend.jl b/src/frontend.jl index cc5f627a..45b928e5 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -497,6 +497,26 @@ function SciMLBase.NonlinearProblem(pdesys::ModelingToolkit.PDESystem, disc::FEM return _steady_problem(_lower(pdesys, disc); disc.kwargs..., kwargs...) end +""" + discretize(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) + +Discretize `pdesys` with `disc` and return a problem ready for `solve`: the +[`DAEProblem`](@ref SciMLBase.DAEProblem(::ModelingToolkit.PDESystem, ::FEMDiscretization)) when +`disc` has a time variable, else the steady +[`NonlinearProblem`](@ref SciMLBase.NonlinearProblem(::ModelingToolkit.PDESystem, ::FEMDiscretization)). +Its `problem_type` is the [`FEMMetadata`](@ref), so `SciMLBase.wrap_sol` turns the solver's +solution into a `PDETimeSeriesSolution` or `PDENoTimeSolution` in the variables of `pdesys`. + +Keywords are passed to that problem after `disc.kwargs`, so a keyword given here wins; any +SciML problem or solver keyword (`saveat`, `tstops`, `abstol`, `callback`, ...) is forwarded. +The keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, `name`, +`parameters`) and those it computes from `pdesys` (`tspan`, `u0`, `p`, `differential_vars`) +raise an `ArgumentError` naming the way to set them. So do further positional arguments, a +first argument that is not a `PDESystem`, and an equation, domain or boundary condition the +discretization does not support, which is rejected before the operators are assembled. +[`symbolic_discretize`](@ref SciMLBase.symbolic_discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization)) +returns the symbolic system of the same discretization. +""" SciMLBase.discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) = disc.time === nothing ? NonlinearProblem(pdesys, disc; kwargs...) : DAEProblem(pdesys, disc; kwargs...) diff --git a/test/Frontend/extension_contract.jl b/test/Frontend/extension_contract.jl new file mode 100644 index 00000000..1aa099c6 --- /dev/null +++ b/test/Frontend/extension_contract.jl @@ -0,0 +1,9 @@ +# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. +using FiniteElementMethod, Test +if FiniteElementMethod.MESH_PDEBASE + include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "extension_contract.jl")) +else + @testset "extension contract (skipped)" begin + @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + end +end diff --git a/test/shared/frontend_tests/extension_contract.jl b/test/shared/frontend_tests/extension_contract.jl new file mode 100644 index 00000000..bf2c00cb --- /dev/null +++ b/test/shared/frontend_tests/extension_contract.jl @@ -0,0 +1,44 @@ +# The Extension contract page (docs/extension_contract.md) states the keyword sets, messages and types of the +# front end; these tests keep the page and the code in step. +using Test +using FiniteElementMethod: FiniteElementMethod, FEMMetadata, rectangle_grid +using Ferrite: Triangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t +using PDEBase: PDEBase + +const PAGE = read(joinpath(@__DIR__, "..", "..", "..", "docs", "extension_contract.md"), String) + +message(f) = try + f() + "" +catch e + e isa ArgumentError ? e.msg : rethrow() +end + +@testset verbose = true "extension contract page" begin + reserved = FiniteElementMethod._RESERVED_KWARGS + derived = keys(FiniteElementMethod._DERIVED_KWARGS) + @test occursin(join(("`$k`" for k in reserved), ", ", " and "), PAGE) + @test all(k -> occursin("| `$k`", PAGE), derived) + @test length(reserved) + length(derived) == 10 + @test occursin("Ten keywords are reserved", PAGE) + + @variables x y u(..) + Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + Ω = MeshDomain(rectangle_grid(Triangle, (2, 2))) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + bcs = [[u(t, Γ) ~ 0 for Γ in boundarypieces(Ω)]; u(0, x, y) ~ 0] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t) + @test occursin(message(() -> FEMDiscretization(Ω, t; tspan = (0.0, 2.0))), PAGE) + @test occursin(message(() -> discretize(pdesys, disc, 1)), PAGE) + @test startswith(message(() -> discretize(1, disc)), "FEMDiscretization discretizes a ModelingToolkit.PDESystem; got ") + @test occursin("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got ...", PAGE) + + @test FEMMetadata <: SciMLBase.AbstractDiscretizationMetadata + @test discretize(pdesys, disc).problem_type isa FEMMetadata + @test FEMDiscretization <: PDEBase.AbstractMeshDiscretization <: SciMLBase.AbstractDiscretization +end From d5a60706835a896584c023739fd55901b461ecb3 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Wed, 28 Oct 2026 20:41:44 +0000 Subject: [PATCH 35/62] Document AbstractTestSpace and Galerkin on the always-built API page The Discretization page is copied in only when PDEBase has the mesh layer, so with released PDEBase these exported-module docstrings were in no built page and Documenter raised :missing_docs. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/discretization.md | 2 -- docs/src/api.md | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/discretization.md b/docs/discretization.md index b38631ad..c1635f23 100644 --- a/docs/discretization.md +++ b/docs/discretization.md @@ -7,7 +7,5 @@ shapes. ```@docs FEMDiscretization FiniteElementMethod.SciMLBase.DAEProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) -FiniteElementMethod.AbstractTestSpace -FiniteElementMethod.Galerkin FiniteElementMethod.assemble_sources! ``` diff --git a/docs/src/api.md b/docs/src/api.md index 8bdde336..8ae9152c 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -65,6 +65,8 @@ FiniteElementMethod.assemble_linear FiniteElementMethod.assemble_nonlinear FiniteElementMethod._split FiniteElementMethod.assemble_linear! +FiniteElementMethod.AbstractTestSpace +FiniteElementMethod.Galerkin FiniteElementMethod.SUPG FiniteElementMethod.emit_strong FiniteElementMethod.compile_coeffs From 99020887fe6d84b2d9c706c50de8723110b869b4 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Sun, 1 Nov 2026 23:22:33 +0000 Subject: [PATCH 36/62] Give the quarter-annulus test its box so its left and bottom conditions sit at 0 pr/12 routes conditions on the facet sets left, right, bottom and top to PDEBase as box faces at the endpoints of each coordinate's interval, [-1, 1] unless the chain gets a domain. The quarter annulus (pr/16) has left at x = 0 and bottom at y = 0, so on the PDEBase path u* on the left and the Neumann data on the bottom were evaluated at x = -1 and y = -1, and both the curved and the straight-sided P2 errors stalled near 0.57. Passing domain = [(0, 2), (0, 2)] puts those faces at 0; the Integration group passes again. Agent-Harness: Claude Code 2.1.316 Agent-Model: claude-opus-5-5 Agent-Session: 451dc71c-367a-429e-8ea3-577f6a7c601f Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Integration/geometry.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Integration/geometry.jl b/test/Integration/geometry.jl index e9a81c8b..da2e0479 100644 --- a/test/Integration/geometry.jl +++ b/test/Integration/geometry.jl @@ -33,7 +33,7 @@ end BC("inner", U ~ on_arc(1)), BC("outer", U ~ on_arc(2)), BC("left", U ~ ustar), BC("bottom", -Dy(U) ~ -expand_derivatives(Dy(ustar)), [0.0, -1.0]), ] - c = chain([0 ~ Dx(Dx(U)) + Dy(Dy(U)) + f], bcs; depvars = [U], t, sivs = [x, y]) + c = chain([0 ~ Dx(Dx(U)) + Dy(Dy(U)) + f], bcs; depvars = [U], t, sivs = [x, y], domain = [(0.0, 2.0), (0.0, 2.0)]) @test any(term -> term.piece == "bottom", c.wf.facet) exact = numeric(ustar, [x, y]) sizes = (2, 4, 8, 16) From bb5dba75040f13de8e0f91aec2e026c5ccff8874 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Wed, 28 Oct 2026 22:57:15 +0000 Subject: [PATCH 37/62] Add facet_dofs, dof_coordinates and cell_dofs on FEMMetadata Index data for callers that build their own system around the assembled operators: global dofs of a field on a boundary piece or named facet set (mid-edge dofs included for order 2, unlike piece_nodes), the coordinate of every dof, and the cell-to-dof map. Agent-Harness: Claude Code 2.1.309 Agent-Model: claude-opus-5-5 Agent-Session: 451dc71c-367a-429e-8ea3-577f6a7c601f Agent-Review: unreviewed Co-authored-by: Claude Code (cherry picked from commit 42cd311d1da13aa9c3f964f3a3ac0be896434a6e) --- src/FiniteElementMethod.jl | 2 +- src/solution.jl | 72 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 262977f7..27a4159c 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -38,7 +38,7 @@ include("weakform.jl") include("kernels.jl") include("assembly.jl") include("operators.jl") -export FieldInfo, FEMMetadata, piece_nodes, normal_flux, write_vtk +export FieldInfo, FEMMetadata, piece_nodes, normal_flux, write_vtk, facet_dofs, dof_coordinates, cell_dofs # Re-exported so that the user API of a FEM model needs no `using PDEBase, Ferrite`. export Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron diff --git a/src/solution.jl b/src/solution.jl index f77261a0..81bf5369 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -222,6 +222,78 @@ function piece_nodes(md::FEMMetadata, Γ) return sort!(unique!(ids)) end +# A field as its `Symbol`/`String` name or as the dependent variable (`u`, `u(..)` or `u(t, x, y)`). +function _field_name(md::FEMMetadata, field) + name = field isa Union{Symbol, AbstractString} ? Symbol(field) : begin + s = Symbolics.unwrap(field) + nameof(SymbolicUtils.iscall(s) ? SymbolicUtils.operation(s) : s) + end + any(f -> f.name === name, md.fields) || + throw(ArgumentError("$field is not a field of this discretization; the fields are $(map(f -> f.name, md.fields))")) + return name +end + +# A boundary piece of the discretization, or a facet set named by `String` or `Symbol`. +function _facetset_name(md::FEMMetadata, Γ) + Γ isa Union{Symbol, AbstractString} || (_facetset(md, Γ); return md.pieces[Γ]) + name = String(Γ) + haskey(_grid(md).facetsets, name) || + throw(ArgumentError("$(repr(name)) is not a facet set of the mesh; they are $(sort!(collect(keys(_grid(md).facetsets))))")) + return name +end + +""" + facet_dofs(md::FEMMetadata, Γ, field) -> Vector{Int} + +Sorted global dof indices of `field` on the boundary piece `Γ` (a piece of the discretization, or a +facet-set name as `String` or `Symbol`): every dof whose basis function is nonzero on a facet of +`Γ`, so for order 2 the mid-edge dofs as well as the vertices. `field` is the field name or its +dependent variable. These are the rows a boundary term on `Γ` enters, and the trace of the field +on `Γ` is determined by the values there. +""" +function facet_dofs(md::FEMMetadata, Γ, field) + ch = Ferrite.ConstraintHandler(_dh(md)) + Ferrite.add!(ch, Ferrite.Dirichlet(_field_name(md, field), Ferrite.getfacetset(_grid(md), _facetset_name(md, Γ)), Returns(0.0))) + Ferrite.close!(ch) + return sort!(copy(ch.prescribed_dofs)) +end + +""" + dof_coordinates(md::FEMMetadata) -> Matrix{Float64} + +`dim × ndofs` matrix whose column `d` is the coordinate of global dof `d` (Lagrange dofs are nodal, +so the field's value at that point is the dof value). Dofs of a field restricted to a region have +coordinates only where the field lives; this covers every dof of every field. +""" +function dof_coordinates(md::FEMMetadata) + dh = _dh(md) + dim = Ferrite.getspatialdim(_grid(md)) + X = zeros(dim, Ferrite.ndofs(dh)) + for name in map(f -> f.name, md.fields), d in 1:dim + a = fill(NaN, Ferrite.ndofs(dh)) + Ferrite.apply_analytical!(a, dh, name, x -> x[d]) + r = field_range(md.space, name) + X[d, r] .= view(a, r) + end + return X +end + +""" + cell_dofs(md::FEMMetadata, field) -> Matrix{Int} + +`nbasis × ncells` matrix of the global dofs of `field` in each cell, in the local order of the +field's interpolation (vertices first, as Ferrite numbers them). A discretization with regions +throws, since its fields do not live on every cell. +""" +function cell_dofs(md::FEMMetadata, field) + name = _field_name(md, field) + dh = _dh(md) + length(dh.subdofhandlers) == 1 || + throw(ArgumentError("cell_dofs needs a discretization without regions; this one has $(length(dh.subdofhandlers)) subdomains")) + r = Ferrite.dof_range(dh, name) + return reduce(hcat, (Ferrite.celldofs(dh, c)[r] for c in 1:Ferrite.getncells(_grid(md)))) +end + function _facet_normal_flux(md, f::FieldInfo, Γ, U) dh = _dh(md) grid = _grid(md) From de26311020046f57e93547c34b5c0c9bc2e625fa Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 22:15:06 +0000 Subject: [PATCH 38/62] Fix facet_dofs on a field absent from the facet set and cell_dofs on one cell facet_dofs returned Ferrite's no-overlap error for a field on a region when the facet set lies outside the region; it now returns an empty vector. cell_dofs reduced with hcat, which returns a plain vector for a mesh of one cell; it now stacks. Adds test/Frontend/facet_dofs.jl, which covers the three functions at orders 1 and 2, both fixes and the argument errors. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 14 ++-- test/Frontend/facet_dofs.jl | 2 + test/shared/frontend_tests/facet_dofs.jl | 83 ++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 test/Frontend/facet_dofs.jl create mode 100644 test/shared/frontend_tests/facet_dofs.jl diff --git a/src/solution.jl b/src/solution.jl index 81bf5369..a95ea006 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -249,11 +249,17 @@ Sorted global dof indices of `field` on the boundary piece `Γ` (a piece of the facet-set name as `String` or `Symbol`): every dof whose basis function is nonzero on a facet of `Γ`, so for order 2 the mid-edge dofs as well as the vertices. `field` is the field name or its dependent variable. These are the rows a boundary term on `Γ` enters, and the trace of the field -on `Γ` is determined by the values there. +on `Γ` is determined by the values there. A field that lives in no cell next to `Γ` (a field on a +region) has no dofs there, and the result is empty. """ function facet_dofs(md::FEMMetadata, Γ, field) - ch = Ferrite.ConstraintHandler(_dh(md)) - Ferrite.add!(ch, Ferrite.Dirichlet(_field_name(md, field), Ferrite.getfacetset(_grid(md), _facetset_name(md, Γ)), Returns(0.0))) + dh = _dh(md) + name = _field_name(md, field) + facets = Ferrite.getfacetset(_grid(md), _facetset_name(md, Γ)) + # Ferrite throws when no facet of the set lies in a cell that holds the field. + any(fi -> name in dh.subdofhandlers[dh.cell_to_subdofhandler[fi[1]]].field_names, facets) || return Int[] + ch = Ferrite.ConstraintHandler(dh) + Ferrite.add!(ch, Ferrite.Dirichlet(name, facets, Returns(0.0))) Ferrite.close!(ch) return sort!(copy(ch.prescribed_dofs)) end @@ -291,7 +297,7 @@ function cell_dofs(md::FEMMetadata, field) length(dh.subdofhandlers) == 1 || throw(ArgumentError("cell_dofs needs a discretization without regions; this one has $(length(dh.subdofhandlers)) subdomains")) r = Ferrite.dof_range(dh, name) - return reduce(hcat, (Ferrite.celldofs(dh, c)[r] for c in 1:Ferrite.getncells(_grid(md)))) + return stack(c -> Ferrite.celldofs(dh, c)[r], 1:Ferrite.getncells(_grid(md))) end function _facet_normal_flux(md, f::FieldInfo, Γ, U) diff --git a/test/Frontend/facet_dofs.jl b/test/Frontend/facet_dofs.jl new file mode 100644 index 00000000..30874809 --- /dev/null +++ b/test/Frontend/facet_dofs.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "facet_dofs.jl")) diff --git a/test/shared/frontend_tests/facet_dofs.jl b/test/shared/frontend_tests/facet_dofs.jl new file mode 100644 index 00000000..f4828003 --- /dev/null +++ b/test/shared/frontend_tests/facet_dofs.jl @@ -0,0 +1,83 @@ +# Index data on the FEMMetadata of a discretized problem: `facet_dofs`, `dof_coordinates` and `cell_dofs`. +using Test +using FiniteElementMethod: rectangle_grid, facet_dofs, dof_coordinates, cell_dofs +using Ferrite: Triangle, Quadrilateral, addcellset!, getcellset, getfacetset, addfacetset! + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) w(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +Δ(f) = Dx(Dx(f)) + Dy(Dy(f)) + +# The metadata of the heat problem on `Ω` with no boundary conditions (natural zero flux). +function heat_metadata(Ω; kwargs...) + @named pdesys = PDESystem( + [Dt(u(t, x, y)) ~ Δ(u(t, x, y))], [u(0, x, y) ~ x], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], [] + ) + return discretize(pdesys, FEMDiscretization(Ω, t; kwargs...)).problem_type +end + +@testset verbose = true "facet_dofs, dof_coordinates, cell_dofs" begin + @testset "P1 and P2 triangles" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 3))) + left, top = boundarypiece.(Ω, (:left, :top)) + for (order, nleft, ntop) in ((1, 4, 5), (2, 7, 9)) + md = heat_metadata(Ω; spaces = Dict(u => Lagrange{RefTriangle, order}())) + ndofs = size(dof_coordinates(md), 2) + X = dof_coordinates(md) + @test size(X) == (2, (order == 1 ? 5 * 4 : 9 * 7)) + dl = facet_dofs(md, left, u) + @test length(dl) == nleft && issorted(dl) + @test all(iszero, X[1, dl]) + @test facet_dofs(md, "top", :u) == facet_dofs(md, top, u) + @test length(facet_dofs(md, top, u(t, x, y))) == ntop + @test all(≈(1.0), X[2, facet_dofs(md, :top, u)]) + C = cell_dofs(md, u) + @test size(C) == (order == 1 ? 3 : 6, 4 * 3 * 2) + @test sort!(unique(vec(C))) == 1:ndofs + end + end + + @testset "a mesh of one cell still gives a matrix" begin + md = heat_metadata(MeshDomain(rectangle_grid(Quadrilateral, (1, 1)))) + @test cell_dofs(md, :u) isa Matrix{Int} + @test size(cell_dofs(md, :u)) == (4, 1) + end + + @testset "a field that does not reach the facet set has no dofs there" begin + grid = rectangle_grid(Triangle, (4, 4)) + addcellset!(grid, "left_half", X -> X[1] <= 0.5 + 1.0e-12) + region = getcellset(grid, "left_half") + for side in ("bottom", "top") + set = getfacetset(grid, side) + delete!(grid.facetsets, side) + addfacetset!(grid, side * "_left", Set(fi for fi in set if fi[1] in region)) + addfacetset!(grid, side * "_right", Set(fi for fi in set if !(fi[1] in region))) + end + Ω = MeshDomain(grid) + Γ = Dict(n => boundarypiece(Ω, n) for n in (:left, :right, :bottom_left, :bottom_right, :top_left, :top_right)) + U, W = u(t, x, y), w(t, x, y) + bcs = [ + [u(t, Γ[n]) ~ 0 for n in keys(Γ)]; + [w(t, Γ[n]) ~ 0 for n in (:left, :bottom_left, :top_left)]; + u(0, x, y) ~ x; w(0, x, y) ~ y + ] + @named pdesys = PDESystem( + [Dt(U) ~ Δ(U), Dt(W) ~ Δ(W) + U], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U, W], [] + ) + md = discretize(pdesys, FEMDiscretization(Ω, t; regions = Dict(w => Region(Ω, :left_half)))).problem_type + @test isempty(facet_dofs(md, :right, w)) + @test !isempty(facet_dofs(md, :right, u)) + @test length(facet_dofs(md, :left, w)) == 5 + @test occursin("regions", errmsg(() -> cell_dofs(md, w))) + end + + @testset "rejections" begin + md = heat_metadata(MeshDomain(rectangle_grid(Quadrilateral, (2, 2)))) + @test occursin("not a facet set", errmsg(() -> facet_dofs(md, "nope", u))) + @test occursin("not a field", errmsg(() -> facet_dofs(md, "left", :v))) + @test occursin("not a field", errmsg(() -> cell_dofs(md, :v))) + end +end From 115925acd1535b77a8a44e41052478bd6224cc63 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Wed, 28 Oct 2026 22:57:15 +0000 Subject: [PATCH 39/62] Add operators(pdesys, disc): the assembled operators as plain data Returns M, K and the load before any Dirichlet row replacement, with the field ranges, differential rows, the Dirichlet dofs and values, the initial dof vector and the FEMMetadata. Linear, time-independent problems only: nonlinear terms, time-dependent sources and time-dependent Dirichlet data raise. _lower now also returns the unconstrained operators it assembled. Tests cover the Neumann and Dirichlet cases, agreement with the DAEProblem residual off the Dirichlet rows, the index functions at orders 1 and 2, and the rejections. Agent-Harness: Claude Code 2.1.309 Agent-Model: claude-opus-5-5 Agent-Session: 451dc71c-367a-429e-8ea3-577f6a7c601f Agent-Review: unreviewed Co-authored-by: Claude Code (cherry picked from commit f7615591ffec5a2a4c4c38571af01347c7b8c95c) --- src/frontend.jl | 45 +++++++++++- test/Frontend/operators.jl | 2 + test/shared/frontend_tests/operators.jl | 91 +++++++++++++++++++++++++ 3 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 test/Frontend/operators.jl create mode 100644 test/shared/frontend_tests/operators.jl diff --git a/src/frontend.jl b/src/frontend.jl index 8956bc8c..5a03a9c3 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -281,7 +281,8 @@ function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) M, K, load, [name => field_range(space, name) for name in names]; prescribed = prescribed_dofs(space), dirichlet_values = timedep_dirichlet ? values! : values0 ) - return ops, coords + raw = (; M, K, load, prescribed = prescribed_dofs(space), dirichlet_values = values0, timedep_dirichlet) + return ops, coords, raw end function _initial_values(ics, ctx, space, coords, an, names, pvals) @@ -341,7 +342,7 @@ function _lower(pdesys, disc::FEMDiscretization) t0, t1 = v.intervals[v.time] space, names, ips = _space(disc, ctx, an, dirichlet, pvals, t0) timedep_dirichlet = any(bc -> _depends(bc.g, [an.slots.T]), an.essential) - ops, coords = _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) + ops, coords, raw = _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) u0 = _initial_values(Equation[b.eq for b in ics], ctx, space, coords, an, names, pvals) dirichlet_values!(view(u0, ops.prescribed), ops.load, t0) iv = disc.time @@ -349,7 +350,7 @@ function _lower(pdesys, disc::FEMDiscretization) fields = [FieldInfo(dv, name, u, ip) for (dv, name, u, ip) in zip(StrongForm.declared_fields(sys, v), names, unknowns, ips)] pieces = Dict{Any, String}(Γ => String(Γ.name) for Γ in PDEBase.boundarypieces(disc.domain)) md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0) - return (; ops, u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys)) + return (; ops, u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys), raw) end """ @@ -386,3 +387,41 @@ function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc:: prob = SciMLBase.discretize(pdesys, disc) return prob.f.sys, prob.tspan end + +""" + operators(pdesys::PDESystem, disc::FEMDiscretization) -> NamedTuple + +The assembled Galerkin operators of `discretize(pdesys, disc)` as plain data, for a caller that +builds its own system around them (such as a component with boundary ports). Returns + + - `M`, `K`: the mass and stiffness matrices with one sparsity pattern, before any Dirichlet row + is replaced, so a caller can impose its own conditions or read reactions from them; + - `F`: the load vector, the volume sources and natural boundary data, without Dirichlet values; + - `fields`: `name => dof range` per field, in declared order; + - `differential_vars`: rows of `M` with a nonzero entry; + - `prescribed`, `dirichlet_values`: the dofs of the `PDESystem`'s Dirichlet conditions and + their values (the rows `M` and `K` would have replaced); + - `u0`: the initial dof vector, with the Dirichlet values on the prescribed dofs; + - `metadata`: the [`FEMMetadata`](@ref), for [`facet_dofs`](@ref), + [`dof_coordinates`](@ref) and [`cell_dofs`](@ref). + +It is the linear, time-independent case only: a nonlinear term, a time-dependent source or +time-dependent Dirichlet data has no data form and raises an `ArgumentError`. Parameters are +substituted by their values, as for the `DAEProblem`. +""" +function operators(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) + parts = _lower(pdesys, disc) + (; M, K, load, prescribed, dirichlet_values, timedep_dirichlet) = parts.raw + load isa AbstractVector || throw(ArgumentError("operators needs time-independent sources, but a source depends on time")) + timedep_dirichlet && throw(ArgumentError("operators needs Dirichlet data that are constant in time")) + differential_vars = falses(size(M, 1)) + for (k, i) in enumerate(rowvals(M)) + iszero(nonzeros(M)[k]) || (differential_vars[i] = true) + end + md = parts.md + fields = [f.name => field_range(md.space, f.name) for f in md.fields] + return (; + M = copy(M), K = copy(K), F = copy(load), fields, differential_vars, prescribed = copy(prescribed), + dirichlet_values = copy(dirichlet_values), u0 = parts.u0, metadata = md, + ) +end diff --git a/test/Frontend/operators.jl b/test/Frontend/operators.jl new file mode 100644 index 00000000..cd8b8c86 --- /dev/null +++ b/test/Frontend/operators.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "operators.jl")) diff --git a/test/shared/frontend_tests/operators.jl b/test/shared/frontend_tests/operators.jl new file mode 100644 index 00000000..41332bcc --- /dev/null +++ b/test/shared/frontend_tests/operators.jl @@ -0,0 +1,91 @@ +# The data API for callers that build their own system around the operators: `operators`, +# `facet_dofs`, `dof_coordinates` and `cell_dofs`. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, facet_dofs, dof_coordinates, cell_dofs, prescribed_dofs +using Ferrite: Quadrilateral, Triangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t +using SparseArrays: nnz + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + +function heat_system(Ω, bcs; eq = heat) + @named pdesys = PDESystem([eq], [bcs; u(0, x, y) ~ x], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + return pdesys +end + +@testset verbose = true "operators" begin + @testset "Neumann heat on a rectangle, P1 quadrilaterals" begin + Ω = MeshDomain(rectangle_grid(Quadrilateral, (4, 3); hi = (2.0, 1.0))) + ops = @test_logs (:warn,) match_mode = :any FiniteElementMethod.operators(heat_system(Ω, Equation[]), FEMDiscretization(Ω, t)) + n = 5 * 4 + @test size(ops.M) == size(ops.K) == (n, n) + @test ops.fields == [:u => 1:n] + @test sum(ops.M) ≈ 2.0 # ∫ 1 dΩ + @test maximum(abs, ops.K * ones(n)) < 1.0e-12 # constants are in the kernel + @test ops.M ≈ ops.M' && ops.K ≈ ops.K' + @test all(ops.differential_vars) + @test iszero(ops.F) && isempty(ops.prescribed) + X = dof_coordinates(ops.metadata) + @test ops.u0 ≈ X[1, :] + end + + @testset "Dirichlet rows are left unconstrained" begin + Ω = MeshDomain(rectangle_grid(Quadrilateral, (4, 3))) + left, right = boundarypiece.(Ω, (:left, :right)) + pdesys = heat_system(Ω, [u(t, left) ~ 2.0, u(t, right) ~ 0.0]) + disc = FEMDiscretization(Ω, t) + ops = FiniteElementMethod.operators(pdesys, disc) + md = ops.metadata + @test sort(ops.prescribed) == sort([facet_dofs(md, left, u); facet_dofs(md, right, u)]) + @test maximum(abs, ops.K * ones(size(ops.K, 1))) < 1.0e-12 + @test ops.u0[facet_dofs(md, left, u)] ≈ fill(2.0, 4) + # Off the Dirichlet rows the operators are those of the DAEProblem. + prob = DAEProblem(pdesys, disc) + free = setdiff(1:size(ops.K, 1), ops.prescribed) + res = zeros(length(prob.u0)) + du = randn(length(prob.u0)) + prob.f(res, du, prob.u0, prob.p, 0.0) + @test res[free] ≈ (ops.M * du + ops.K * prob.u0 - ops.F)[free] + end + + @testset "facet_dofs, dof_coordinates and cell_dofs" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 3))) + left, top = boundarypiece.(Ω, (:left, :top)) + for (order, nleft, ntop) in ((1, 4, 5), (2, 7, 9)) + ops = @test_logs (:warn,) match_mode = :any FiniteElementMethod.operators( + heat_system(Ω, Equation[]), FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, order}())) + ) + md = ops.metadata + X = dof_coordinates(md) + @test size(X) == (2, size(ops.K, 1)) + dl = facet_dofs(md, left, u) + @test length(dl) == nleft && issorted(dl) + @test all(iszero, X[1, dl]) + @test facet_dofs(md, "top", :u) == facet_dofs(md, top, u) + @test length(facet_dofs(md, top, u(t, x, y))) == ntop + @test all(≈(1.0), X[2, facet_dofs(md, :top, u)]) + C = cell_dofs(md, u) + @test size(C) == (order == 1 ? 3 : 6, 4 * 3 * 2) + @test sort!(unique(vec(C))) == 1:size(ops.K, 1) + end + end + + @testset "rejections" begin + Ω = MeshDomain(rectangle_grid(Quadrilateral, (2, 2))) + left = boundarypiece(Ω, :left) + msg(f) = errmsg(f) + nonlinear = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) - u(t, x, y)^3 + @test occursin("nonlinear", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]; eq = nonlinear), FEMDiscretization(Ω, t)))) + @test occursin("constant in time", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ sin(t)]), FEMDiscretization(Ω, t)))) + sourced = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + t + @test occursin("time-independent", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]; eq = sourced), FEMDiscretization(Ω, t)))) + ops = FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]), FEMDiscretization(Ω, t)) + @test occursin("not a facet set", msg(() -> facet_dofs(ops.metadata, "nope", u))) + @test occursin("not a field", msg(() -> facet_dofs(ops.metadata, left, :v))) + end +end From ddb9faf9ef66239be8839ac753e53a10e0fa397b Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:10:29 +0000 Subject: [PATCH 40/62] Remove the MESH_PDEBASE gate from the time-last wrapper and update the restriction notes The constant was deleted by #14, so the retained first-parent wrapper threw UndefVarError; supported_conditions notes and their static copy now say time may be first or last. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/boundary_conditions.md | 4 ++-- src/discretization.jl | 2 +- test/Frontend/time_last.jl | 9 +-------- 3 files changed, 4 insertions(+), 11 deletions(-) diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 8168ea60..f29a68d1 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -26,7 +26,7 @@ rendering. Restrictions of this release: - Geometries are `Ferrite.Grid` meshes (1D, 2D and 3D cell shapes) wrapped as `MeshDomain(grid)`, with boundary pieces named by the grid's facet sets. Only 1D and 2D are evidenced; meshes with mixed cell types are rejected until M4. - - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time must be the first argument of every dependent variable. + - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time is the first or last argument of every dependent variable, never between spatial arguments. - Dirichlet data may depend on space, time and parameters but not on another field. Neumann and Robin conditions are written with `NormalDerivative(Γ)`, with any conormal coefficient written explicitly. Neumann and Robin data may depend on time; the Robin coefficient multiplying `u(t, Γ)` may depend only on space and parameters until M3. - Periodic conditions `u(t, Γa) ~ u(t, Γb)` are rejected until M4. Interface conditions between regions have no syntax; every field lives on the whole mesh. - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. @@ -138,6 +138,6 @@ is an error that names the problem; nothing falls back to `mtkcompile`. | A mesh with mixed cell types | error; lands in M4 | | Fields with different interpolations, such as P2 velocity and P1 pressure | error; lands in M4 | | A periodic condition `u(t, Γa) ~ u(t, Γb)` | error; lands in M4 | -| A dependent variable whose first argument is not time, such as `u(x, y, t)` | error | +| A time argument between spatial arguments, such as `u(x, t, y)` | error | | Two Dirichlet pieces of one field sharing nodes | the condition listed last wins | | A boundary piece with no condition | natural zero-flux condition, with a warning when the equations have a flux | diff --git a/src/discretization.jl b/src/discretization.jl index df1bee3a..940ced93 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -128,7 +128,7 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( Restrictions of this release: - Geometries are `Ferrite.Grid` meshes (1D, 2D and 3D cell shapes) wrapped as `MeshDomain(grid)`, with boundary pieces named by the grid's facet sets. Only 1D and 2D are evidenced; meshes with mixed cell types are rejected until M4. - - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time must be the first argument of every dependent variable. + - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time is the first or last argument of every dependent variable, never between spatial arguments. - Dirichlet data may depend on space, time and parameters but not on another field. Neumann and Robin conditions are written with `NormalDerivative(Γ)`, with any conormal coefficient written explicitly. Neumann and Robin data may depend on time; the Robin coefficient multiplying `u(t, Γ)` may depend only on space and parameters until M3. - Periodic conditions `u(t, Γa) ~ u(t, Γb)` are rejected until M4. Interface conditions between regions have no syntax; every field lives on the whole mesh. - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. diff --git a/test/Frontend/time_last.jl b/test/Frontend/time_last.jl index 5037ec81..5cf4f629 100644 --- a/test/Frontend/time_last.jl +++ b/test/Frontend/time_last.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "time_last.jl")) -else - @testset "time_last (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "time_last.jl")) From 9f7ef14f74010eb811616114dd40b2ac418eb344 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:10:38 +0000 Subject: [PATCH 41/62] Remove the MESH_PDEBASE gate from the steady wrapper and update the restriction notes The constant was deleted by #14; the supported_conditions notes no longer list steady problems as rejected, matching the static copy. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 2 +- test/Frontend/steady.jl | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index d8103993..f735d89e 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -138,6 +138,6 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. - 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. - - Steady problems, `dirichlet = :eliminate`, fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Nonlinear operators, time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. + - `dirichlet = :eliminate`, fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Nonlinear operators, time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. """ ) diff --git a/test/Frontend/steady.jl b/test/Frontend/steady.jl index c60d1408..80253e6d 100644 --- a/test/Frontend/steady.jl +++ b/test/Frontend/steady.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "steady.jl")) -else - @testset "steady (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "steady.jl")) From 19f339beee117d140f80b7905ec1c3be87697d2f Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:10:51 +0000 Subject: [PATCH 42/62] Remove the MESH_PDEBASE gate from the eliminate wrapper and update the restriction notes The constant was deleted by #14; the supported_conditions notes no longer list dirichlet = :eliminate as rejected, matching the static copy. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 2 +- test/Frontend/eliminate.jl | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index 0ade663d..f3d49942 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -151,6 +151,6 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. - 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. - - `dirichlet = :eliminate`, fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Nonlinear operators, time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. + - Fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Nonlinear operators, time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. """ ) diff --git a/test/Frontend/eliminate.jl b/test/Frontend/eliminate.jl index cc93a575..0587d82d 100644 --- a/test/Frontend/eliminate.jl +++ b/test/Frontend/eliminate.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "eliminate.jl")) -else - @testset "eliminate (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "eliminate.jl")) From c08da8d66a596825c448a9d9f01021847490d257 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:01 +0000 Subject: [PATCH 43/62] Remove the MESH_PDEBASE gate from the nonlinear wrapper and update the restriction notes The constant was deleted by #14; the supported_conditions notes no longer list nonlinear operators as rejected, matching the static copy. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 2 +- test/Frontend/nonlinear.jl | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index b91c3366..2840e37e 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -154,6 +154,6 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. - 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. - - Fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Nonlinear operators, time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. + - Fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. """ ) diff --git a/test/Frontend/nonlinear.jl b/test/Frontend/nonlinear.jl index 430f603e..d15dfbed 100644 --- a/test/Frontend/nonlinear.jl +++ b/test/Frontend/nonlinear.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "nonlinear.jl")) -else - @testset "nonlinear (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "nonlinear.jl")) From be895f5458df6b7203e36a744d8127203cf8ea7f Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:05 +0000 Subject: [PATCH 44/62] Remove the MESH_PDEBASE gate from the curved-mesh wrapper The constant was deleted by #14. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Frontend/curved.jl | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/test/Frontend/curved.jl b/test/Frontend/curved.jl index e6b62156..92d5f17b 100644 --- a/test/Frontend/curved.jl +++ b/test/Frontend/curved.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "curved.jl")) -else - @testset "curved (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "curved.jl")) From 1f7f953e1267815bee98876bb544bd32c8854ea7 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:15 +0000 Subject: [PATCH 45/62] Remove the MESH_PDEBASE gate from the observed wrapper The constant was deleted by #14. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Frontend/observed.jl | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/test/Frontend/observed.jl b/test/Frontend/observed.jl index e829a6f9..ed9ca4be 100644 --- a/test/Frontend/observed.jl +++ b/test/Frontend/observed.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "observed.jl")) -else - @testset "observed (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "observed.jl")) From 0529b71d0246e87edfe2d8b74a24f08efd486fce Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:24 +0000 Subject: [PATCH 46/62] Update the restriction notes for multi-field systems and SUPG supported_conditions and its static copy in boundary_conditions.md no longer list different interpolations and other test spaces as rejected. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/boundary_conditions.md | 4 +--- src/discretization.jl | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 2318b311..46ee2159 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -32,7 +32,7 @@ Restrictions of this release: - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. - 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. - - Fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. + - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. "Time-dependent" means boundary data that varies with time, for every condition kind. @@ -131,9 +131,7 @@ is an error that names the problem; nothing falls back to `mtkcompile`. | A time-dependent coefficient in the mass or stiffness operator, such as `Dx((1 + t) * Dx(u))` | error; lands in M3 | | A time-dependent Robin coefficient, such as `Dn(u(t, Γ)) + (1 + t) * u(t, Γ) ~ 0` | error; lands in M3 | | `FEMDiscretization(…; codegen = :mtk)` | error; lands in M3 | -| A test space other than `Galerkin()` | error; lands in M4 | | A mesh with mixed cell types | error; lands in M4 | -| Fields with different interpolations, such as P2 velocity and P1 pressure | error; lands in M4 | | A periodic condition `u(t, Γa) ~ u(t, Γb)` | error; lands in M4 | | A time argument between spatial arguments, such as `u(x, t, y)` | error | | Two Dirichlet pieces of one field sharing nodes | the condition listed last wins | diff --git a/src/discretization.jl b/src/discretization.jl index d66af691..9b84d384 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -157,6 +157,6 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. - 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. - - Fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. + - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. """ ) From 14168ff0930fc2843da3a27a925be34757cd0a8f Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:28 +0000 Subject: [PATCH 47/62] Remove the MESH_PDEBASE gate from the DFG cylinder test The constant was deleted by #14, so the test threw UndefVarError. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/NavierStokes/dfg_cylinder.jl | 82 ++++++++++++++----------------- 1 file changed, 38 insertions(+), 44 deletions(-) diff --git a/test/NavierStokes/dfg_cylinder.jl b/test/NavierStokes/dfg_cylinder.jl index 0798b678..e97625e5 100644 --- a/test/NavierStokes/dfg_cylinder.jl +++ b/test/NavierStokes/dfg_cylinder.jl @@ -1,51 +1,45 @@ # The DFG 2D-1 cylinder example (spec §11.5): the PDESystem path against the benchmark's acceptance intervals # and against the hand-written Ferrite solver on the same mesh. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "dfg_cylinder.jl")) - include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "reference.jl")) +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "dfg_cylinder.jl")) +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "reference.jl")) - @testset "DFG 2D-1 flow around a cylinder" begin - h, hc = 0.04, 0.0025 - r = dfg_solve(; h, hc) - @info "DFG 2D-1" r.ndofs r.build_s r.solve_s r.coefficients - @test SciMLBase.successful_retcode(r.sol) - stopped = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, maxiters = 3) - @test_throws "the DFG solve stopped at t = " check_solved(stopped) - # Terminated is a success code, so the final time is checked too. - halt = SciMLBase.DiscreteCallback((u, t, integrator) -> t > 1.0, SciMLBase.terminate!) - terminated = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, callback = halt) - @test terminated.retcode == SciMLBase.ReturnCode.Terminated - @test_throws "the DFG solve stopped at t = " check_solved(terminated) - c = r.coefficients - # The force functional gets the integrator's final derivative, which vanishes at the steady state and - # satisfies the DAE there, not the slope between the two saved end points (about |u|/t_end). - dv = r.prob.differential_vars - x_end = r.sol.original_sol.u[end] - @test maximum(abs, r.dxdt[dv]) <= 1.0e-6 - residual = zeros(length(x_end)) - r.prob.f(residual, r.dxdt, x_end, r.prob.p, last(r.prob.tspan)) - @test maximum(abs, residual[dv]) <= 1.0e-9 - steady = dfg_coefficients(r.sol.disc_data.space.dh, x_end; ν = 1.0e-3, Umean = 0.2) - for k in (:cD, :cL) - @test c[k] ≈ steady[k] rtol = 1.0e-8 - end - for k in (:cD, :cL, :Δp) - lo, hi = DFG_2D1_BANDS[k] - @test lo <= c[k] <= hi - end - - # The hand-written steady solution on the same mesh: same dof numbering after FieldWise renumbering. - grid = dfg_channel_grid(; h, hc) - @test_throws "Newton's method did not converge in 1 iterations" dfg_reference_steady(grid; maxiter = 1) - dh_ref, x_ref, _ = dfg_reference_steady(grid; pressure = :strong) - ref = dfg_coefficients(dh_ref, x_ref; ν = 1.0e-3, Umean = 0.2) - for k in (:cD, :cL, :Δp) - @test c[k] ≈ ref[k] rtol = 1.0e-7 - end +@testset "DFG 2D-1 flow around a cylinder" begin + h, hc = 0.04, 0.0025 + r = dfg_solve(; h, hc) + @info "DFG 2D-1" r.ndofs r.build_s r.solve_s r.coefficients + @test SciMLBase.successful_retcode(r.sol) + stopped = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, maxiters = 3) + @test_throws "the DFG solve stopped at t = " check_solved(stopped) + # Terminated is a success code, so the final time is checked too. + halt = SciMLBase.DiscreteCallback((u, t, integrator) -> t > 1.0, SciMLBase.terminate!) + terminated = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, callback = halt) + @test terminated.retcode == SciMLBase.ReturnCode.Terminated + @test_throws "the DFG solve stopped at t = " check_solved(terminated) + c = r.coefficients + # The force functional gets the integrator's final derivative, which vanishes at the steady state and + # satisfies the DAE there, not the slope between the two saved end points (about |u|/t_end). + dv = r.prob.differential_vars + x_end = r.sol.original_sol.u[end] + @test maximum(abs, r.dxdt[dv]) <= 1.0e-6 + residual = zeros(length(x_end)) + r.prob.f(residual, r.dxdt, x_end, r.prob.p, last(r.prob.tspan)) + @test maximum(abs, residual[dv]) <= 1.0e-9 + steady = dfg_coefficients(r.sol.disc_data.space.dh, x_end; ν = 1.0e-3, Umean = 0.2) + for k in (:cD, :cL) + @test c[k] ≈ steady[k] rtol = 1.0e-8 + end + for k in (:cD, :cL, :Δp) + lo, hi = DFG_2D1_BANDS[k] + @test lo <= c[k] <= hi end -else - @testset "dfg_cylinder (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" + + # The hand-written steady solution on the same mesh: same dof numbering after FieldWise renumbering. + grid = dfg_channel_grid(; h, hc) + @test_throws "Newton's method did not converge in 1 iterations" dfg_reference_steady(grid; maxiter = 1) + dh_ref, x_ref, _ = dfg_reference_steady(grid; pressure = :strong) + ref = dfg_coefficients(dh_ref, x_ref; ν = 1.0e-3, Umean = 0.2) + for k in (:cD, :cL, :Δp) + @test c[k] ≈ ref[k] rtol = 1.0e-7 end end From 80d8ee146dc6d7ffa1c30f0ed76ab5b05b648e62 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:33 +0000 Subject: [PATCH 48/62] Remove the MESH_PDEBASE gate from the symbolic_discretize wrapper The constant was deleted by #14. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Frontend/symbolic.jl | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/test/Frontend/symbolic.jl b/test/Frontend/symbolic.jl index b0594b17..8aa3f065 100644 --- a/test/Frontend/symbolic.jl +++ b/test/Frontend/symbolic.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "symbolic.jl")) -else - @testset "symbolic_discretize (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "symbolic.jl")) From 256d66b74f11e51537c364ab16ad831ae20055b1 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:39 +0000 Subject: [PATCH 49/62] Remove the MESH_PDEBASE gate from the messages wrapper The constant was deleted by #14. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Frontend/messages.jl | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/test/Frontend/messages.jl b/test/Frontend/messages.jl index 3a0d7499..e1fb20a6 100644 --- a/test/Frontend/messages.jl +++ b/test/Frontend/messages.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "messages.jl")) -else - @testset "messages (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "messages.jl")) From 2bf026cf187cd490c723d6b9158b7225fa872ce9 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:52 +0000 Subject: [PATCH 50/62] Remove the MESH_PDEBASE gate from the arguments wrapper; point the parameter message at discretize The constant was deleted by #14, and discretize is the documented entry point, so the stale-parameter message and its docs say discretize(pdesys, disc) instead of the DAEProblem forwarder. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/discretization.jl | 2 +- src/numeric_dae.jl | 2 +- test/Frontend/arguments.jl | 9 +-------- test/shared/frontend_tests/nonlinear.jl | 2 +- 4 files changed, 4 insertions(+), 11 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index db710c38..850d42e9 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -84,7 +84,7 @@ through `PDEBase.StrongForm.pair_equations`. Parameters are substituted by the values given in the `PDESystem` when the operators are assembled, and are parameters of the problem at those values. The operators are not reassembled for new values: after `remake(prob; p = [k => 3.0])` the solve throws an -`ArgumentError` naming `k`; build a new problem with `DAEProblem(pdesys, disc)` instead. +`ArgumentError` naming `k`; build a new problem with `discretize(pdesys, disc)` instead. """ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization domain::PDEBase.MeshDomain diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index b1173ad4..7d1571a7 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -458,7 +458,7 @@ function assembled_parameter_check(sys, parameters) for (q, a, c) in zip(syms, assembled, current) isequal(a, c) || throw( ArgumentError( - "parameter $q was $a when the operators were assembled but is $c in this problem; operators are not reassembled for new parameter values, so build a new problem with DAEProblem(pdesys, disc)" + "parameter $q was $a when the operators were assembled but is $c in this problem; operators are not reassembled for new parameter values, so build a new problem with discretize(pdesys, disc)" ) ) end diff --git a/test/Frontend/arguments.jl b/test/Frontend/arguments.jl index d896848f..fd9c53e9 100644 --- a/test/Frontend/arguments.jl +++ b/test/Frontend/arguments.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "arguments.jl")) -else - @testset "arguments (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "arguments.jl")) diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index f2ba582a..950c1e24 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -239,7 +239,7 @@ end sol = solve(prob, EXACT_ROWS; abstol = 1.0e-10, reltol = 1.0e-10) @test nodal_error(sol, U, uexact) <= tol @test SciMLBase.successful_retcode(solve(remake(prob; p = [k => 1.0]), EXACT_ROWS)) - msg = "parameter k was 1.0 when the operators were assembled but is 3.0 in this problem; operators are not reassembled for new parameter values, so build a new problem with DAEProblem(pdesys, disc)" + msg = "parameter k was 1.0 when the operators were assembled but is 3.0 in this problem; operators are not reassembled for new parameter values, so build a new problem with discretize(pdesys, disc)" @test_throws ArgumentError(msg) solve(remake(prob; p = [k => 3.0]), EXACT_ROWS) end end From 4b8bf4eb8181dddd90a2c4ec4ec96b5169f4c686 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:11:56 +0000 Subject: [PATCH 51/62] Remove the MESH_PDEBASE gate from the extension contract wrapper; fix the Solutions link The constant was deleted by #14, and docs/src/solution.md was folded into differences.md, so the Solutions reference points at its heading there. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/extension_contract.md | 2 +- test/Frontend/extension_contract.jl | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/docs/src/extension_contract.md b/docs/src/extension_contract.md index 0a66a188..ff0b7ee5 100644 --- a/docs/src/extension_contract.md +++ b/docs/src/extension_contract.md @@ -86,7 +86,7 @@ solver's solution and that metadata to the constructors FiniteElementMethod defi `PDETimeSeriesSolution(sol, md::FEMMetadata)` (with time) and `PDENoTimeSolution(sol, md::FEMMetadata)` (steady), so `solve` returns a solution indexed and called in the `PDESystem`'s variables, `sol[u(t, x, y)]` and `sol(t, x, y; dv)`; see -[Solutions](@ref). The solver's own solution stays in `sol.original_sol`. +[Solution shapes that differ from MethodOfLines](@ref). The solver's own solution stays in `sol.original_sol`. ## `symbolic_discretize` diff --git a/test/Frontend/extension_contract.jl b/test/Frontend/extension_contract.jl index 1aa099c6..2ce54d2b 100644 --- a/test/Frontend/extension_contract.jl +++ b/test/Frontend/extension_contract.jl @@ -1,9 +1,2 @@ -# Needs the PDEBase mesh-discretization layer, unreleased as of PDEBase 0.1.39. using FiniteElementMethod, Test -if FiniteElementMethod.MESH_PDEBASE - include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "extension_contract.jl")) -else - @testset "extension contract (skipped)" begin - @test_skip "the installed PDEBase lacks the mesh classifier, StrongForm boundary routing or pairing-ordered mesh coordinates (PDEBase#158)" - end -end +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "extension_contract.jl")) From 1efb65053d8a2b1d5b20f1510ca5faeffa3132b1 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:13:14 +0000 Subject: [PATCH 52/62] Read the extension contract page from docs/src in its test The page moved to docs/src with the merge of #14's docs layout. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/shared/frontend_tests/extension_contract.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/shared/frontend_tests/extension_contract.jl b/test/shared/frontend_tests/extension_contract.jl index bf2c00cb..810e1f39 100644 --- a/test/shared/frontend_tests/extension_contract.jl +++ b/test/shared/frontend_tests/extension_contract.jl @@ -1,4 +1,4 @@ -# The Extension contract page (docs/extension_contract.md) states the keyword sets, messages and types of the +# The Extension contract page (docs/src/extension_contract.md) states the keyword sets, messages and types of the # front end; these tests keep the page and the code in step. using Test using FiniteElementMethod: FiniteElementMethod, FEMMetadata, rectangle_grid @@ -9,7 +9,7 @@ include(joinpath(@__DIR__, "..", "frontend.jl")) using ModelingToolkit: t_nounits as t using PDEBase: PDEBase -const PAGE = read(joinpath(@__DIR__, "..", "..", "..", "docs", "extension_contract.md"), String) +const PAGE = read(joinpath(@__DIR__, "..", "..", "..", "docs", "src", "extension_contract.md"), String) message(f) = try f() From 07ed65a44c32ffcc55f152addc1733eecfdee4dc Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:26:23 +0000 Subject: [PATCH 53/62] Choose the normal_flux facet quadrature order from the interpolations _facet_normal_flux used a fixed order-2 facet rule, which is exact only for straight facets up to P4. P5 fields and curved facets were integrated inexactly (relative error 0.44 for a random P5 field, 3e-5 to 1e-2 on a P1-P4 field on quadratic cells). The order is now 2 * (field order + geometry order). Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 5 ++++- test/Solution/solution.jl | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/solution.jl b/src/solution.jl index f77261a0..b265e483 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -225,7 +225,10 @@ end function _facet_normal_flux(md, f::FieldInfo, Γ, U) dh = _dh(md) grid = _grid(md) - fv = Ferrite.FacetValues(Ferrite.FacetQuadratureRule{Ferrite.getrefshape(f.ip)}(2), f.ip, _geometry(md)) + geometry = _geometry(md) + # The order grows with both interpolations: on a curved facet the integrand is rational in the facet coordinate. + order = 2 * (_order(f.ip) + _order(geometry)) + fv = Ferrite.FacetValues(Ferrite.FacetQuadratureRule{Ferrite.getrefshape(f.ip)}(order), f.ip, geometry) return map(_sorted_facets(md, Γ)) do fi r = _cell_range(dh, fi[1], f.name) r === nothing && return convert(eltype(U), NaN) diff --git a/test/Solution/solution.jl b/test/Solution/solution.jl index 514bd4c5..cda2d0b7 100644 --- a/test/Solution/solution.jl +++ b/test/Solution/solution.jl @@ -3,6 +3,7 @@ using OrdinaryDiffEqBDF: DFBDF using FiniteElementMethod: FEMMetadata, piece_nodes, normal_flux, write_vtk include(joinpath(@__DIR__, "..", "shared", "heat.jl")) +include(joinpath(@__DIR__, "..", "shared", "references.jl")) const P1 = Lagrange{RefTriangle, 1}() const P2 = Lagrange{RefTriangle, 2}() @@ -353,3 +354,40 @@ end @test normal_flux(sol, u(x, y), Γ) ≈ [-dgx(Vec(0.0, ym)) for ym in (1 / 6, 1 / 2, 5 / 6)] atol = 1.0e-12 end end + +# A fixed low facet quadrature order was exact only for straight facets up to P4. +@testset "Facet-mean flux at high order and on curved facets" begin + # u = x y⁴ is in P5; the inlet normal is -x, so the mean of -∂u/∂x = -y⁴ over [a, b] is -(b⁵ - a⁵) / (5 (b - a)). + grid = with_inlet(square_grid(3)) + dh = DofHandler(grid) + add!(dh, :u, Lagrange{RefTriangle, 5}()) + close!(dh) + U = zeros(ndofs(dh)) + apply_analytical!(U, dh, :u, p -> p[1] * p[2]^4) + sol, syms = steady_from_dofs(dh, (; u = Lagrange{RefTriangle, 5}()), U) + exact = [-((k / 3)^5 - ((k - 1) / 3)^5) / (5 / 3) for k in 1:3] + @test normal_flux(sol, syms.u(syms.x, syms.y), syms.Γ) ≈ exact rtol = 1.0e-12 + + # Quadratic cells with P2 and P4 fields: the facet-mean flux on the outer arc against a high-order reference. + grid = quarter_annulus(3; quadratic = true) + for p in (2, 4) + ip = Lagrange{RefTriangle, p}() + dh = DofHandler(grid) + add!(dh, :u, ip) + close!(dh) + U = zeros(ndofs(dh)) + apply_analytical!(U, dh, :u, X -> X[1]^2 + X[2]^2) + sol, syms = steady_from_dofs(dh, (; u = ip), U) + sol.disc_data.pieces[syms.Γ] = "outer" + fv = FacetValues(FacetQuadratureRule{RefTriangle}(14), ip, geometric_interpolation(QuadraticTriangle)) + reference = map(sort!(collect(getfacetset(grid, "outer")); by = fi -> (fi[1], fi[2]))) do (c, f) + Ferrite.reinit!(fv, getcoordinates(grid, c), f) + u_cell = U[celldofs(dh, c)] + q = 1:getnquadpoints(fv) + sum(q) do i + (function_gradient(fv, i, u_cell) ⋅ getnormal(fv, i)) * getdetJdV(fv, i) + end / sum(i -> getdetJdV(fv, i), q) + end + @test normal_flux(sol, syms.u(syms.x, syms.y), syms.Γ) ≈ reference rtol = 1.0e-10 + end +end From 0857a25d5fffbc05da8a79535b9123672ab0163c Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Mon, 2 Nov 2026 23:36:16 +0000 Subject: [PATCH 54/62] Match the documentation test and boundary-condition page to the reworded unsupported-coefficient message #36 reworded the message to 'are not supported'; the master-side documentation test and page still quoted 'land in M3'. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/boundary_conditions.md | 2 +- test/shared/frontend_tests/documentation.jl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 46ee2159..ec8aa0b7 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -104,7 +104,7 @@ have a flux, the discretization warns about each such piece. Neumann conditions. The data `β` may depend on the coordinates, time and parameters. The coefficient `α` may depend on the coordinates and parameters but not on time in this release: a time-dependent `α` makes the boundary part of the stiffness operator time-dependent, which is -rejected with `time-dependent coefficients in the mass or stiffness operator land in M3`. +rejected with `time-dependent coefficients in the mass or stiffness operator are not supported`. Like a Neumann condition, it enters the weak form as a facet integral. ## Periodic conditions diff --git a/test/shared/frontend_tests/documentation.jl b/test/shared/frontend_tests/documentation.jl index 0512d9fe..c5706a4b 100644 --- a/test/shared/frontend_tests/documentation.jl +++ b/test/shared/frontend_tests/documentation.jl @@ -62,7 +62,7 @@ using ModelingToolkit: t_nounits as t ] @named sys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) @test_throws ArgumentError( - "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has U₁*V + T*U₁*V" + "time-dependent coefficients in the mass or stiffness operator are not supported: equation 1 has U₁*V + T*U₁*V" ) discretize(sys, FEMDiscretization(Ω, t)) end end From 6f9a5adb6364bbab9605c9954a16a2886cf3cff9 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 01:14:32 +0000 Subject: [PATCH 55/62] Document facet_dofs, dof_coordinates and cell_dofs Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/api.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/src/api.md b/docs/src/api.md index 425be864..232cbeb7 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -42,6 +42,9 @@ FiniteElementMethod.FEMInterpolant piece_nodes normal_flux write_vtk +facet_dofs +dof_coordinates +cell_dofs ``` ## Weak form, kernels and assembly From e4c52e107ca656f2ea24edb3d0b87204929fbae3 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 01:15:21 +0000 Subject: [PATCH 56/62] Document operators(pdesys, disc) Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- docs/src/discretization.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/src/discretization.md b/docs/src/discretization.md index 82c09ea5..2d078176 100644 --- a/docs/src/discretization.md +++ b/docs/src/discretization.md @@ -10,6 +10,7 @@ FiniteElementMethod.SciMLBase.discretize(::FiniteElementMethod.ModelingToolkit.P FiniteElementMethod.AbstractTestSpace FiniteElementMethod.Galerkin FiniteElementMethod.assemble_sources! +FiniteElementMethod.operators ``` `discretize(pdesys, disc)` returns the `DAEProblem` of the discretization. `symbolic_discretize(pdesys, disc)` From ba4921fe489a3cafb4ad1999c2970d019aabe409 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 01:27:21 +0000 Subject: [PATCH 57/62] Treat facet cells with no subdofhandler as lacking the field in facet_dofs A facet set whose cells all lie outside every region indexed subdofhandlers[0]. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 2 +- test/shared/frontend_tests/facet_dofs.jl | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/solution.jl b/src/solution.jl index a95ea006..ff58a23c 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -257,7 +257,7 @@ function facet_dofs(md::FEMMetadata, Γ, field) name = _field_name(md, field) facets = Ferrite.getfacetset(_grid(md), _facetset_name(md, Γ)) # Ferrite throws when no facet of the set lies in a cell that holds the field. - any(fi -> name in dh.subdofhandlers[dh.cell_to_subdofhandler[fi[1]]].field_names, facets) || return Int[] + any(fi -> _cell_range(dh, fi[1], name) !== nothing, facets) || return Int[] ch = Ferrite.ConstraintHandler(dh) Ferrite.add!(ch, Ferrite.Dirichlet(name, facets, Returns(0.0))) Ferrite.close!(ch) diff --git a/test/shared/frontend_tests/facet_dofs.jl b/test/shared/frontend_tests/facet_dofs.jl index f4828003..541aa500 100644 --- a/test/shared/frontend_tests/facet_dofs.jl +++ b/test/shared/frontend_tests/facet_dofs.jl @@ -74,6 +74,20 @@ end @test occursin("regions", errmsg(() -> cell_dofs(md, w))) end + @testset "cells that hold no field at all" begin + grid = rectangle_grid(Triangle, (4, 4)) + addcellset!(grid, "left_half", X -> X[1] <= 0.5 + 1.0e-12) + Ω = MeshDomain(grid) + Γ = Dict(n => boundarypiece(Ω, n) for n in (:left, :right)) + U = u(t, x, y) + @named pdesys = PDESystem( + [Dt(U) ~ Δ(U)], [u(t, Γ[:left]) ~ 0; u(0, x, y) ~ x], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], [] + ) + md = discretize(pdesys, FEMDiscretization(Ω, t; regions = Dict(u => Region(Ω, :left_half)))).problem_type + @test isempty(facet_dofs(md, :right, u)) + @test length(facet_dofs(md, :left, u)) == 5 + end + @testset "rejections" begin md = heat_metadata(MeshDomain(rectangle_grid(Quadrilateral, (2, 2)))) @test occursin("not a facet set", errmsg(() -> facet_dofs(md, "nope", u))) From ba0a7e0dbca54fb3637095b9520bec0034460672 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 01:51:35 +0000 Subject: [PATCH 58/62] Read the spatial dimension of dof_coordinates from a node, not Ferrite.getspatialdim getspatialdim is not public in Ferrite, which fails the QA public-access check. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solution.jl b/src/solution.jl index ff58a23c..1aa67867 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -273,7 +273,7 @@ coordinates only where the field lives; this covers every dof of every field. """ function dof_coordinates(md::FEMMetadata) dh = _dh(md) - dim = Ferrite.getspatialdim(_grid(md)) + dim = length(Ferrite.get_node_coordinate(first(Ferrite.getnodes(_grid(md))))) X = zeros(dim, Ferrite.ndofs(dh)) for name in map(f -> f.name, md.fields), d in 1:dim a = fill(NaN, Ferrite.ndofs(dh)) From e5eae846066698dc84195244145ed9b091e9312f Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 03:11:11 +0000 Subject: [PATCH 59/62] Format with Runic Runic 1.13.0 reindents the begin block in _field_name; no behaviour change. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solution.jl b/src/solution.jl index 1aa67867..00b4488b 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -225,9 +225,9 @@ end # A field as its `Symbol`/`String` name or as the dependent variable (`u`, `u(..)` or `u(t, x, y)`). function _field_name(md::FEMMetadata, field) name = field isa Union{Symbol, AbstractString} ? Symbol(field) : begin - s = Symbolics.unwrap(field) - nameof(SymbolicUtils.iscall(s) ? SymbolicUtils.operation(s) : s) - end + s = Symbolics.unwrap(field) + nameof(SymbolicUtils.iscall(s) ? SymbolicUtils.operation(s) : s) + end any(f -> f.name === name, md.fields) || throw(ArgumentError("$field is not a field of this discretization; the fields are $(map(f -> f.name, md.fields))")) return name From dc76531f9df282ca71e2580f39e60e06e7cb3f5c Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 03:26:43 +0000 Subject: [PATCH 60/62] Reject cell_dofs on a single region that covers only part of the mesh A lone subdomain smaller than the mesh passed the one-subdomain guard and then failed inside Ferrite with a BoundsError. Also require it to cover every cell. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/solution.jl | 4 ++-- test/shared/frontend_tests/facet_dofs.jl | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/solution.jl b/src/solution.jl index 00b4488b..8085416e 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -294,8 +294,8 @@ throws, since its fields do not live on every cell. function cell_dofs(md::FEMMetadata, field) name = _field_name(md, field) dh = _dh(md) - length(dh.subdofhandlers) == 1 || - throw(ArgumentError("cell_dofs needs a discretization without regions; this one has $(length(dh.subdofhandlers)) subdomains")) + (length(dh.subdofhandlers) == 1 && length(only(dh.subdofhandlers).cellset) == Ferrite.getncells(_grid(md))) || + throw(ArgumentError("cell_dofs needs a discretization without regions; this one has regions covering $(length(dh.subdofhandlers)) subdomains, not the whole mesh")) r = Ferrite.dof_range(dh, name) return stack(c -> Ferrite.celldofs(dh, c)[r], 1:Ferrite.getncells(_grid(md))) end diff --git a/test/shared/frontend_tests/facet_dofs.jl b/test/shared/frontend_tests/facet_dofs.jl index 541aa500..6b0626fa 100644 --- a/test/shared/frontend_tests/facet_dofs.jl +++ b/test/shared/frontend_tests/facet_dofs.jl @@ -88,6 +88,13 @@ end @test length(facet_dofs(md, :left, u)) == 5 end + @testset "cell_dofs rejects a single region that covers only part of the mesh" begin + grid = rectangle_grid(Triangle, (4, 4)) + addcellset!(grid, "left_half", X -> X[1] <= 0.5 + 1.0e-12) + md = heat_metadata(MeshDomain(grid); regions = Dict(u => Region(MeshDomain(grid), :left_half))) + @test occursin("regions", errmsg(() -> cell_dofs(md, u))) + end + @testset "rejections" begin md = heat_metadata(MeshDomain(rectangle_grid(Quadrilateral, (2, 2)))) @test occursin("not a facet set", errmsg(() -> facet_dofs(md, "nope", u))) From 2ce1952f46b27c7ced4a0441f9227834ecb250c0 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 03:55:44 +0000 Subject: [PATCH 61/62] Drop unused NonlinearProblem import ExplicitImports no_stale_explicit_imports flags it; all uses are qualified SciMLBase.NonlinearProblem. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/FiniteElementMethod.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index df6a8595..262977f7 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -20,7 +20,7 @@ using NonlinearSolveFirstOrder: NewtonRaphson using PDEBase: PDEBase using PrecompileTools: PrecompileTools using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions -using SciMLBase: SciMLBase, DAEFunction, DAEProblem, NonlinearProblem +using SciMLBase: SciMLBase, DAEFunction, DAEProblem using SciMLBase.SymbolicIndexingInterface: getp, variable_index using SparseArrays: SparseMatrixCSC, nonzeros, nzrange, rowvals using SymbolicUtils: SymbolicUtils From 527863fbf8e23063696e7cafccc54accd3873849 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 03:56:06 +0000 Subject: [PATCH 62/62] Format with Runic Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/frontend.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/frontend.jl b/src/frontend.jl index 92435af7..31648abf 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -424,7 +424,7 @@ SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; throw( ArgumentError( "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem, not a DAEProblem; " * - "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" + "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" ) ) : SciMLBase.discretize(pdesys, disc; kwargs...)