From 721df521f55d531ed068aecc4e54c52b8501c223 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 19:01:26 +0000 Subject: [PATCH 1/7] Add add_boundary_pieces! for boundary pieces given as submeshes Maps each cell of a lower-dimensional Ferrite grid to a facet of the parent by node coordinates and adds the facets as a named facet set. A facet set containing interior facets is now an error rather than a warning, since a piece lies on the boundary. 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 | 4 +- src/mesh.jl | 136 +++++++++++++++++++++++++++++++++++-- test/Space/space.jl | 3 +- test/qa/qa.jl | 4 +- 4 files changed, 136 insertions(+), 11 deletions(-) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 262977f7..04e9863f 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -13,7 +13,7 @@ using DiffEqBase: BrownFullBasicInit using DomainSets: DomainSets using Ferrite: Ferrite, Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron using ForwardDiff: ForwardDiff -using LinearAlgebra: dot, mul! +using LinearAlgebra: dot, mul!, norm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -46,7 +46,7 @@ using PDEBase: StrongForm, MeshDomain, Region, boundarypiece, boundarypieces, No include("discretization.jl") include("frontend.jl") _is_normal_derivative(op) = op isa NormalDerivative -export FEMDiscretization, Galerkin, SUPG +export FEMDiscretization, Galerkin, SUPG, add_boundary_pieces! export MeshDomain, Region, boundarypiece, boundarypieces, NormalDerivative include("precompile.jl") diff --git a/src/mesh.jl b/src/mesh.jl index 43db01a9..6bff351d 100644 --- a/src/mesh.jl +++ b/src/mesh.jl @@ -55,13 +55,14 @@ end _facet_key(fi::Ferrite.FacetIndex) = (fi[1], fi[2]) """ - check_facetsets(grid, names) + check_facetsets(grid, names; disjoint = true) Validate the facet sets that boundary conditions refer to (spec §4.6, §6.1): every name must be a facet set -of `grid`, no facet may lie in two of the named sets, and a set containing interior facets (shared by two -cells) draws a warning. Returns `nothing`. +of `grid`, no facet may lie in two of the named sets (unless `disjoint = false`), and a set containing +interior facets (shared by two cells) is an error, since a boundary piece lies on the boundary. Returns +`nothing`. """ -function check_facetsets(grid::Ferrite.Grid, names) +function check_facetsets(grid::Ferrite.Grid, names; disjoint::Bool = true) available = _facetset_names(grid) used = unique(Symbol.(names)) for name in used @@ -72,7 +73,7 @@ function check_facetsets(grid::Ferrite.Grid, names) ) end owner = Dict{Ferrite.FacetIndex, Symbol}() - for name in used, fi in Ferrite.getfacetset(grid, String(name)) + for name in used, fi in (disjoint ? Ferrite.getfacetset(grid, String(name)) : ()) first_owner = get!(owner, fi, name) first_owner === name && continue shared = sort!( @@ -93,8 +94,129 @@ function check_facetsets(grid::Ferrite.Grid, names) [fi for fi in Ferrite.getfacetset(grid, String(name)) if !isempty(Ferrite.getneighborhood(topology, grid, fi))]; by = _facet_key ) - isempty(interior) || @warn "facet set $(repr(name)) contains $(length(interior)) interior facets " * - "(shared by two cells; first: cell $(interior[1][1]), local facet $(interior[1][2]))" + isempty(interior) || throw( + ArgumentError( + "facet set $(repr(name)) is not on the boundary: it contains $(length(interior)) interior facets " * + "(shared by two cells; first: cell $(interior[1][1]), local facet $(interior[1][2]))" + ) + ) end return nothing end + +# Sorted corner-node ids of local facet `lf` of `cell`: the identity of a facet of a conforming mesh, whatever the +# cell order and orientation. +_facet_corners(cell, lf) = sort!([Ferrite.vertices(cell)[i] for i in Ferrite.reference_facets(cell)[lf]]) + +# Every facet of `grid`, keyed by its corner nodes: a boundary facet has one owner, an interior facet two. +function _facet_owners(grid::Ferrite.Grid) + owners = Dict{Vector{Int}, Vector{Ferrite.FacetIndex}}() + for (c, cell) in enumerate(Ferrite.getcells(grid)), lf in 1:Ferrite.nfacets(cell) + push!(get!(owners, _facet_corners(cell, lf), Ferrite.FacetIndex[]), Ferrite.FacetIndex(c, lf)) + end + return owners +end + +_boundary_facets(grid::Ferrite.Grid) = Set(only(fs) for fs in values(_facet_owners(grid)) if length(fs) == 1) + +# Map each node of `sub` to the parent node within `atol` of it (the nearest one), through a hash of `atol`-wide +# buckets, so that a point's candidates lie in the 3^dim buckets around its own. +function _match_nodes(grid::Ferrite.Grid{dim}, sub::Ferrite.Grid, atol) where {dim} + bucket(x) = ntuple(d -> floor(Int, x[d] / atol), dim) + buckets = Dict{NTuple{dim, Int}, Vector{Int}}() + for (i, node) in enumerate(Ferrite.getnodes(grid)) + push!(get!(buckets, bucket(node.x), Int[]), i) + end + offsets = Iterators.product(ntuple(Returns(-1:1), dim)...) + return map(Ferrite.getnodes(sub)) do node + b = bucket(node.x) + best, bestdist = 0, Inf + for off in offsets, i in get(buckets, b .+ off, ()) + dist = norm(Ferrite.get_node_coordinate(grid, i) - node.x) + dist <= atol && dist < bestdist && ((best, bestdist) = (i, dist)) + end + best + end +end + +function _submesh_facets(grid::Ferrite.Grid{dim}, name, sub::Ferrite.Grid, atol, owners) where {dim} + _meshdim(sub) == dim || throw( + ArgumentError( + "boundary piece $(repr(name)): the submesh has $(_meshdim(sub))-dimensional coordinates but the parent mesh " * + "has $(dim)-dimensional ones; give the submesh its nodes in the coordinates of the parent" + ) + ) + cells = Ferrite.getcells(sub) + isempty(cells) && throw(ArgumentError("boundary piece $(repr(name)): the submesh has no cells")) + all(c -> Ferrite.getrefdim(c) == dim - 1, cells) || throw( + ArgumentError( + "boundary piece $(repr(name)): the cells of the submesh must have dimension $(dim - 1), the facets of the " * + "$(dim)-dimensional parent mesh" + ) + ) + atol = something(atol, 1.0e-8 * max(1.0, maximum(d -> maximum(n -> n.x[d], Ferrite.getnodes(grid)) - minimum(n -> n.x[d], Ferrite.getnodes(grid)), 1:dim))) + parent = _match_nodes(grid, sub, atol) + unmatched = findall(iszero, parent) + isempty(unmatched) || throw( + ArgumentError( + "boundary piece $(repr(name)): $(length(unmatched)) of $(length(parent)) submesh nodes are not within " * + "atol = $atol of a node of the parent mesh (first: submesh node $(unmatched[1]) at " * + "$(Tuple(Ferrite.get_node_coordinate(sub, unmatched[1]))))" + ) + ) + facets = valtype(grid.facetsets)() + missing_cells, interior_cells = Int[], Int[] + for (k, cell) in enumerate(cells) + found = get(owners, sort!([parent[i] for i in Ferrite.vertices(cell)]), nothing) + found === nothing && (push!(missing_cells, k); continue) + length(found) == 1 || (push!(interior_cells, k); continue) + push!(facets, only(found)) + end + centre(k) = Tuple(sum(Ferrite.get_node_coordinate(sub, i) for i in Ferrite.vertices(cells[k])) / length(Ferrite.vertices(cells[k]))) + isempty(missing_cells) || throw( + ArgumentError( + "boundary piece $(repr(name)): $(length(missing_cells)) of $(length(cells)) submesh cells match no facet of " * + "the parent mesh, whose corner nodes they share (first: submesh cell $(missing_cells[1]) centred at " * + "$(centre(missing_cells[1])))" + ) + ) + isempty(interior_cells) || throw( + ArgumentError( + "boundary piece $(repr(name)): $(length(interior_cells)) of $(length(cells)) submesh cells match an interior " * + "facet of the parent mesh (shared by two cells), not a boundary facet (first: submesh cell " * + "$(interior_cells[1]) centred at $(centre(interior_cells[1])))" + ) + ) + return facets +end + +""" + add_boundary_pieces!(grid, name => submesh, ...; atol = nothing) + add_boundary_pieces!(grid, pieces::AbstractDict; atol = nothing) + +Add a boundary piece to the `Ferrite.Grid` `grid` for each pair `name => submesh`: a facet set called `name` +holding the facets of `grid` that the cells of `submesh` coincide with. `submesh` is a `Ferrite.Grid` of one +dimension less than `grid`, in the coordinates of `grid`: the boundary mesh that Gmsh gives for a physical +group, or any grid whose cells are facets of `grid`. Afterwards `boundarypiece(MeshDomain(grid), name)` is the +piece, exactly as for any other facet set; `grid` is modified, as by `Ferrite.addfacetset!`, and returns. + +A submesh cell is matched to a facet of `grid` through the nodes: each node of the submesh is the node of `grid` +within `atol` of it (by coordinates, since the two grids number their nodes independently; the default `atol` +is `1e-8` times the larger of `1` and the largest extent of `grid`), and the cell is the facet whose corner +nodes are those of the cell. Nothing is added, for any of the pieces, if a node has no node of `grid` within +`atol`, a cell matches no facet of `grid`, a cell matches an interior facet (shared by two cells) or `name` is +already a facet set of `grid`; each is an `ArgumentError` that says which. +""" +function add_boundary_pieces!(grid::Ferrite.Grid, pieces::Pair...; atol = nothing) + names = [String(first(p)) for p in pieces] + allunique(names) || throw(ArgumentError("boundary piece names must be unique; got $(Symbol.(names))")) + for name in names + haskey(grid.facetsets, name) && + throw(ArgumentError("the mesh already has a facet set $(repr(Symbol(name))); pick another name for the boundary piece")) + end + owners = _facet_owners(grid) + sets = [_submesh_facets(grid, Symbol(n), last(p), atol, owners) for (n, p) in zip(names, pieces)] + foreach((n, s) -> Ferrite.addfacetset!(grid, n, s), names, sets) + return grid +end +add_boundary_pieces!(grid::Ferrite.Grid, pieces::AbstractDict; kwargs...) = add_boundary_pieces!(grid, pieces...; kwargs...) diff --git a/test/Space/space.jl b/test/Space/space.jl index ee670139..f65c5487 100644 --- a/test/Space/space.jl +++ b/test/Space/space.jl @@ -221,7 +221,8 @@ end @test check_facetsets(grid, [:left, :left, :bottom]) === nothing addfacetset!(grid, "middle", x -> x[1] ≈ 0.5) - @test_logs (:warn, r"middle.*interior") check_facetsets(grid, [:middle]) + @test_throws ArgumentError check_facetsets(grid, [:middle]) + @test occursin("not on the boundary", errmsg(() -> check_facetsets(grid, [:middle]))) @test_logs check_facetsets(grid, [:left, :top]) end diff --git a/test/qa/qa.jl b/test/qa/qa.jl index 22185597..93cb6d7b 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -4,6 +4,8 @@ using JET # `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`; # `Ferrite.dirichlet_facetdof_indices` (a facet's local nodes) has no public spelling in Ferrite 1. +# `Ferrite.vertices`, `reference_facets` and `getrefdim` (the corner nodes of a cell, of its facets, and the +# dimension of its reference shape) identify the facets of a submesh and have no public spelling in Ferrite 1. # ModelingToolkit re-exports these ModelingToolkitBase names; on Julia 1.10 `Base.which` reports # ModelingToolkitBase as their owner, on 1.11+ ModelingToolkit, the module we depend on. const LTS_MTK_OWNER = VERSION < v"1.11" ? (:ProblemTypeCtx, :t_nounits) : () @@ -14,7 +16,7 @@ run_qa( aqua_kwargs = (; piracies = (; treat_as_own = [FiniteElementMethod.Ferrite.Grid])), ei_kwargs = (; all_qualified_accesses_are_public = (; - ignore = (:FieldWise, :derivative, :dirichlet_facetdof_indices), + ignore = (:FieldWise, :derivative, :dirichlet_facetdof_indices, :vertices, :reference_facets, :getrefdim), ), all_explicit_imports_via_owners = (; ignore = LTS_MTK_OWNER), all_qualified_accesses_via_owners = (; ignore = LTS_MTK_OWNER), From 1aa0e4a2894f91a4c766bdcc37df730de28e8933 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 19:01:26 +0000 Subject: [PATCH 2/7] Check boundary completeness per field, with natural and boundary_check Boundary facets with no condition for a field whose equation has a flux now give one aggregated warning per discretize call. FEMDiscretization(natural = [pieces]) declares them zero-flux, boundary_check = :error makes the warning an error and :off skips it. 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 | 24 +++++++++++++--- src/frontend.jl | 41 +++++++++++++++++++++++----- test/shared/frontend_tests/errors.jl | 2 +- 3 files changed, 55 insertions(+), 12 deletions(-) diff --git a/src/discretization.jl b/src/discretization.jl index df1bee3a..eaaa252a 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, natural = (), boundary_check = :warn, kwargs...) Finite-element discretization of a `PDESystem` whose spatial domain is the mesh domain `Ω` (of a `Ferrite.Grid`), with time variable `t`. `discretize(pdesys, disc)` assembles the @@ -28,6 +28,16 @@ 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`. + - `natural`: boundary pieces (as `boundarypiece(Ω, name)` or a facet set name) that deliberately carry + the natural zero-flux condition of every field, such as an outflow or a symmetry plane. A piece + with an explicit zero Neumann condition `Dn(u(t, Γ)) ~ 0` needs no entry here. See `boundary_check`. + - `boundary_check`: what to do when part of the boundary has no condition for a field whose + equation has a flux, neither a Dirichlet, Neumann or Robin condition nor a `natural` piece. + `:warn` (default) logs one warning per `discretize` call, listing the pieces and the number of + facets for each such field, and treats them as zero-flux; `:error` throws the same message as an + `ArgumentError`, for strict completeness; `:off` skips the check. A facet claimed by two pieces that both carry + conditions, and a piece that is not on the boundary, are errors whatever `boundary_check` is. + A boundary given as a lower-dimensional mesh is made a piece with [`add_boundary_pieces!`](@ref). - `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 `discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` @@ -58,6 +68,8 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization pairing::Dict{Equation, Any} codegen::Symbol dirichlet::Symbol + natural::Vector{Symbol} + boundary_check::Symbol 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, natural = (), boundary_check::Symbol = :warn, 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,16 @@ 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 + boundary_check in (:warn, :error, :off) || + throw(ArgumentError("boundary_check must be :warn, :error or :off, got $(repr(boundary_check))")) + natural = Symbol[p isa PDEBase.BoundaryPiece ? p.name : Symbol(p) for p in natural] + check_facetsets(domain.mesh, natural; disjoint = false) _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, unique(natural), boundary_check, NamedTuple(kwargs) ) end @@ -131,7 +147,7 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time must be the first argument of every dependent variable. - 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. + - Boundary pieces must be disjoint and lie on the boundary. Boundary facets with no condition for a field get the natural zero-flux condition, with a warning when that field's equation has a flux; `natural` declares them and `boundary_check` makes the warning an error or turns it off. - 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. diff --git a/src/frontend.jl b/src/frontend.jl index 8956bc8c..8b94c111 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -316,6 +316,38 @@ function _initial_values(ics, ctx, space, coords, an, names, pvals) return u0 end +# Boundary facets that carry no condition for a field whose equation has a flux get the natural zero-flux condition +# silently, which hides a forgotten piece. A piece is covered for a field by a Dirichlet condition on that field, a +# Neumann or Robin condition in its equation, or an entry in `disc.natural`. +function _check_boundary_conditions(disc::FEMDiscretization, an, ctx) + disc.boundary_check === :off && return nothing + grid = disc.domain.mesh + boundary = _boundary_facets(grid) + facetsets = Dict(name => Set(Ferrite.getfacetset(grid, String(name))) for name in _facetset_names(grid)) + lines = String[] + for (f, op) in enumerate(ctx.ops) + all(c -> isequal(c, 0), an.conormal[f]) && continue + covered = Set{Ferrite.FacetIndex}() + for name in [disc.natural; [bc.piece.name for bc in an.essential if bc.field == f]; [bc.piece.name for bc in an.natural if bc.eq == f]] + union!(covered, facetsets[name]) + end + cells = haskey(disc.regions, op) ? Set(Ferrite.getcellset(grid, String(disc.regions[op].name))) : nothing + open = Set(fi for fi in boundary if fi ∉ covered && (cells === nothing || fi[1] in cells)) + isempty(open) && continue + pieces = [(name, length(intersect(open, set))) for (name, set) in sort!(collect(facetsets); by = first)] + listed = ["Γ_$name ($n facets)" for (name, n) in pieces if n > 0] + unnamed = length(setdiff(open, union(values(facetsets)...))) + unnamed > 0 && push!(listed, "$unnamed facets in no piece") + push!(lines, " $(nameof(op)): $(length(open)) of $(length(boundary)) boundary facets have no condition: $(join(listed, ", "))") + end + isempty(lines) && return nothing + msg = "boundary facets with no condition get the natural zero-flux condition:\n" * join(lines, "\n") * + "\nDeclare them with `FEMDiscretization(…; natural = [pieces])` or a zero Neumann condition, or set `boundary_check = :off`" + disc.boundary_check === :error && throw(ArgumentError(msg)) + @warn msg + return nothing +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) @@ -323,16 +355,10 @@ function _lower(pdesys, disc::FEMDiscretization) v = PDEBase.VariableMap(sys, disc; replaced_vars = replaced) PDEBase.interface_errors(sys, v, disc) boundarymap = _boundary_map(sys.bcs, v, disc) - ics, bcmap = PDEBase.split_ics_bcs(boundarymap, v, disc) + ics, _ = 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)) - 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) - Γ in covered || @warn "boundary piece $Γ has no condition, so it gets the natural zero-flux condition" - end - end disc.test_space isa SUPG && _check_supg(disc.test_space, an, ctx) wf = weak_form(an; test_space = disc.test_space) _check_linear(wf) @@ -340,6 +366,7 @@ 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) + _check_boundary_conditions(disc, an, ctx) 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) diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index 726c3305..b68a8343 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -182,6 +182,6 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @testset "a piece with no condition warns when its flux is not zero" begin Ω = box() Γl, Γr, Γb, Γt = sides(Ω) - @test_logs (:warn, r"boundary piece Γ_top has no condition") match_mode = :any lower([heat], [u(t, Γl) ~ 0, u(t, Γr) ~ 0, u(t, Γb) ~ 0, ic], Ω) + @test_logs (:warn, r"u: 2 of 8 boundary facets have no condition: Γ_top \(2 facets\)") match_mode = :any lower([heat], [u(t, Γl) ~ 0, u(t, Γr) ~ 0, u(t, Γb) ~ 0, ic], Ω) end end From ae30979a89212e8272d887a540065e9c66a0a8cf Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 19:01:26 +0000 Subject: [PATCH 3/7] Test and document submesh pieces and boundary completeness 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 --- README.md | 6 + docs/src/boundary_conditions.md | 56 +++++- docs/src/discretization.md | 8 +- test/Frontend/boundaries.jl | 2 + test/shared/frontend_tests/boundaries.jl | 214 +++++++++++++++++++++++ 5 files changed, 280 insertions(+), 6 deletions(-) create mode 100644 test/Frontend/boundaries.jl create mode 100644 test/shared/frontend_tests/boundaries.jl diff --git a/README.md b/README.md index ff5ce4eb..246ddf57 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,12 @@ traces `u(t, Γ)` and normal derivatives `NormalDerivative(Γ)`, and the solutio called in the same symbols. The [documentation](https://docs.sciml.ai/FiniteElementMethod/stable/) covers how this differs from [MethodOfLines.jl](https://docs.sciml.ai/MethodOfLines/stable/). +A boundary with no condition gets the natural zero-flux condition, with a warning that lists it; +declare it with `FEMDiscretization(Ω, t; natural = [Γ_out])`, or make the warning an error with +`boundary_check = :error`. A boundary given as a lower-dimensional mesh becomes a piece with +`add_boundary_pieces!(grid, :inlet => inlet_mesh)`. See +[boundary conditions](https://docs.sciml.ai/FiniteElementMethod/stable/boundary_conditions/). + ## Benchmarks Accuracy per degree of freedom against MethodOfLines, assembly cost against hand-written Ferrite, diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 8168ea60..65f3fe8e 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -29,7 +29,7 @@ Restrictions of this release: - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time must be the first argument of every dependent variable. - 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. + - Boundary pieces must be disjoint and lie on the boundary. Boundary facets with no condition for a field get the natural zero-flux condition, with a warning when that field's equation has a flux; `natural` declares them and `boundary_check` makes the warning an error or turns it off. - 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. @@ -41,11 +41,30 @@ Restrictions of this release: The spatial domain is a `MeshDomain(grid)` of a `Ferrite.Grid`, for example one read from Gmsh with `FerriteGmsh.togrid` or made with `Ferrite.generate_grid`. Boundary pieces are the grid's facet sets: `boundarypiece(Ω, :inlet)` is the facet set `"inlet"`. Pieces must be disjoint; a -facet in two pieces that both carry conditions is an error naming the first shared facet. +facet in two pieces that both carry conditions is an error naming the first shared facet, and a +piece containing an interior facet (one shared by two cells) is an error, since a piece lies on +the boundary. Line, triangle and quadrilateral meshes are tested; tetrahedral and hexahedral meshes construct but are not evidenced (see [Supported equation classes](@ref)). Every cell of the mesh must have the same shape. +**Pieces from submeshes.** A boundary may also be given as a lower-dimensional mesh: the boundary +mesh that Gmsh gives for a physical group, or any `Ferrite.Grid` whose cells are facets of the +parent (line cells on a 2D mesh, surface cells on a 3D mesh). [`add_boundary_pieces!`](@ref) +matches each submesh cell to a facet of the parent by the coordinates of its nodes, within a +tolerance `atol` (the two meshes number their nodes independently), and adds the facets as the +facet set `name`: + +```julia +grid = rectangle_grid(Triangle, (4, 4)) +add_boundary_pieces!(grid, :inlet => inlet_mesh, :wall => wall_mesh) +Ω = MeshDomain(grid) +Γ_in = boundarypiece(Ω, :inlet) +``` + +A submesh cell that matches no facet of the parent, or only an interior facet, is an error that +names the cell and where it is. The grid's own facet sets work as before. + Coordinates are Cartesian. Their names and order come from the `(x, y) ∈ Ω` pairing (see [Coordinate binding](@ref)). A curvilinear operator, such as a radial Laplacian, is written out in Cartesian-coordinate form in the equation. @@ -95,8 +114,8 @@ rescaled when it is proportional to the conormal derivative; a condition that is `Dx(u(t, Γ)) ~ h` on a piece that is not perpendicular to the `x` axis, is an error asking for the normal derivative. -A boundary piece with no condition gets the natural zero-flux condition. When the equations -have a flux, the discretization warns about each such piece. +Boundary facets with no condition get the natural zero-flux condition; see +[Boundary completeness](@ref). ## Robin conditions @@ -119,6 +138,31 @@ Not supported. There is no syntax for a condition on an interior interface betwe regions, and every field is defined on the whole mesh. Discontinuous coefficients across an interface are not evidenced (see [Supported equation classes](@ref)). +## Boundary completeness + +A boundary facet is covered for a field when it lies in a piece with a Dirichlet condition on +that field, or a Neumann or Robin condition in that field's equation. Where part of the boundary +is not covered for a field whose equation has a flux, the discretization treats it as the natural +zero-flux condition. That is often intended (an insulated wall, a symmetry plane, the outflow +`ν ∂ₙu = 0` of a channel flow), so it is not an error by default, but it is also what a forgotten +piece looks like. The check is therefore configurable on [`FEMDiscretization`](@ref): + + - By default (`boundary_check = :warn`) `discretize` logs one warning per call, listing for + each such field the uncovered pieces and their number of facets (and the facets that belong + to no named piece). + - `natural = [Γ_out, :symmetry]` declares pieces as deliberately natural for every field; the + warning is then silent for them. An explicit zero Neumann condition `Dn(u(t, Γ)) ~ 0` also + covers its piece. + - `boundary_check = :error` throws the same message as an `ArgumentError`, for strict + completeness; `boundary_check = :off` skips the check. + - A field whose equation has no flux, such as a pressure, is not checked. + +These are errors whatever `boundary_check` is: a facet in two pieces that both carry conditions +(which includes two Dirichlet values on one facet through overlapping pieces, and the same piece +and field listed twice), and a piece that is not on the boundary. + +Detecting a singular pure-Neumann problem is not part of this check. + ## Validation Every condition is checked when the system is discretized, by `discretize(pdesys, disc)`, before a solver runs. An unsupported condition, operator or option @@ -140,4 +184,6 @@ is an error that names the problem; nothing falls back to `mtkcompile`. | 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 | | 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 | +| Boundary facets with no condition for a field | natural zero-flux condition, with one warning per `discretize` call when that field's equation has a flux; `natural` declares them, `boundary_check = :error` or `:off` | +| A piece that is not on the boundary | error | +| A submesh cell that matches no facet, or an interior facet, of the parent | error from `add_boundary_pieces!` | diff --git a/docs/src/discretization.md b/docs/src/discretization.md index 82c09ea5..0c1bf0df 100644 --- a/docs/src/discretization.md +++ b/docs/src/discretization.md @@ -1,6 +1,6 @@ # Discretization -`FEMDiscretization`, `Galerkin` and `SUPG` are exported, as are the PDEBase names a model needs +`FEMDiscretization`, `Galerkin`, `SUPG` and `add_boundary_pieces!` are exported, as are the PDEBase names a model needs (`MeshDomain`, `Region`, `boundarypiece`, `boundarypieces`, `NormalDerivative`) and Ferrite's `Lagrange` and reference shapes. [Getting started](@ref) shows them in use. @@ -12,6 +12,12 @@ FiniteElementMethod.Galerkin FiniteElementMethod.assemble_sources! ``` +## Boundary pieces from submeshes + +```@docs +add_boundary_pieces! +``` + `discretize(pdesys, disc)` returns the `DAEProblem` of the discretization. `symbolic_discretize(pdesys, disc)` returns `(sys, tspan)`, where `sys` is the array-residual `System` attached to that problem (see [`FiniteElementMethod.fem_system`](@ref)): one block equation per field over the diff --git a/test/Frontend/boundaries.jl b/test/Frontend/boundaries.jl new file mode 100644 index 00000000..3216a9d2 --- /dev/null +++ b/test/Frontend/boundaries.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "boundaries.jl")) diff --git a/test/shared/frontend_tests/boundaries.jl b/test/shared/frontend_tests/boundaries.jl new file mode 100644 index 00000000..f8a4d137 --- /dev/null +++ b/test/shared/frontend_tests/boundaries.jl @@ -0,0 +1,214 @@ +# Boundary pieces given as submeshes (add_boundary_pieces!) and the completeness rules of the boundary +# conditions (natural, boundary_check), each end to end: PDESystem -> DAEProblem -> solve -> exact solution. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, add_boundary_pieces! +using Ferrite: Ferrite, Triangle, Quadrilateral, Hexahedron, Line, Grid, Node, Vec, addfacetset!, getfacetset + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y z u(..) v(..) +const Dt, Dx, Dy, Dz = Differential(t), Differential(x), Differential(y), Differential(z) +const tol = 1.0e-8 +Dn(Γ) = NormalDerivative(Γ) + +# A box grid without its facet sets, so that every boundary piece comes from a submesh. +function bare_box(celltype, cells) + grid = rectangle_grid(celltype, cells) + empty!(grid.facetsets) + return grid +end + +# The segment from `a` to `b` in `n` Line cells; every other cell is reversed and the nodes are numbered backwards, +# so that neither node ids nor cell orientation agree with the parent's. +function segment(a, b, n) + nodes = [Node(Vec(Tuple(a .+ (b .- a) .* (k / n)))) for k in n:-1:0] + cells = [Line(isodd(i) ? (n + 2 - i, n + 1 - i) : (n + 1 - i, n + 2 - i)) for i in 1:n] + return Grid(cells, nodes) +end + +# The unit square [0, 1]² in `m × m` quadrilaterals, placed on the plane `x_axis = value` of the unit cube. +function face(axis, value, m) + sq = Ferrite.generate_grid(Quadrilateral, (m, m), Vec(0.0, 0.0), Vec(1.0, 1.0)) + place(p) = Vec(Tuple(insert_at(axis, value, p))) + return Grid(Ferrite.getcells(sq), [Node(place(n.x)) for n in Ferrite.getnodes(sq)]) +end +insert_at(axis, value, p) = axis == 1 ? (value, p[1], p[2]) : axis == 2 ? (p[1], value, p[2]) : (p[1], p[2], value) + +heat2d = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) +ic2d = u(0, x, y) ~ 1 + x +uexact2d(t_, x_, y_) = (1 + x_) * (1 + t_) + +function box2d(n = 4) + grid = bare_box(Triangle, (n, n)) + add_boundary_pieces!( + grid, :bottom => segment((0.0, 0.0), (1.0, 0.0), n), :right => segment((1.0, 0.0), (1.0, 1.0), n), + :top => segment((0.0, 1.0), (1.0, 1.0), n), :left => segment((0.0, 0.0), (0.0, 1.0), n) + ) + return MeshDomain(grid) +end + +@testset verbose = true "boundary pieces from submeshes" begin + @testset "2D box with its four sides as 1D submeshes" begin + Ω = box2d() + Γb, Γr, Γt, Γl = boundarypiece.(Ω, (:bottom, :right, :top, :left)) + @test length(getfacetset(Ω.mesh, "bottom")) == 4 && all(fi -> fi[1] ≤ 32, getfacetset(Ω.mesh, "left")) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + (1 + x) + # Dirichlet on three sides, Neumann (du/dn = 1 + t) on the right side. + bcs = [ + u(t, Γl) ~ 1 + t, u(t, Γb) ~ (1 + x) * (1 + t), u(t, Γt) ~ (1 + x) * (1 + t), + Dn(Γr)(u(t, Γr)) ~ 1 + t, ic2d, + ] + sol, _ = fem_solve([eq], bcs, Ω, (x, y), t, [u(t, x, y)]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, u(t, x, y), uexact2d) <= tol + end + + @testset "3D box with its six faces as 2D submeshes" begin + grid = bare_box(Hexahedron, (2, 2, 2)) + faces = [ + :x1_lo => face(1, 0.0, 2), :x1_hi => face(1, 1.0, 2), :x2_lo => face(2, 0.0, 2), + :x2_hi => face(2, 1.0, 2), :x3_lo => face(3, 0.0, 2), :x3_hi => face(3, 1.0, 2), + ] + add_boundary_pieces!(grid, Dict(faces)) + Ω = MeshDomain(grid) + @test all(p -> length(getfacetset(grid, String(first(p)))) == 4, faces) + eq = Dt(u(t, x, y, z)) ~ Dx(Dx(u(t, x, y, z))) + Dy(Dy(u(t, x, y, z))) + Dz(Dz(u(t, x, y, z))) + (1 + x + 2y + 3z) + bcs = [ + [u(t, boundarypiece(Ω, first(p))) ~ (1 + x + 2y + 3z) * (1 + t) for p in faces]; + u(0, x, y, z) ~ 1 + x + 2y + 3z + ] + sol, _ = fem_solve([eq], bcs, Ω, (x, y, z), t, [u(t, x, y, z)]; spaces = Dict(u => Lagrange{RefHexahedron, 1}())) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, u(t, x, y, z), (t_, x_, y_, z_) -> (1 + x_ + 2y_ + 3z_) * (1 + t_)) <= tol + end + + @testset "submesh errors" begin + grid() = bare_box(Triangle, (4, 4)) + # A segment shifted off the boundary: its nodes are not nodes of the parent. + msg = errmsg(() -> add_boundary_pieces!(grid(), :bottom => segment((0.0, 0.1), (1.0, 0.1), 4))) + @test occursin("boundary piece :bottom", msg) && occursin("submesh nodes are not within atol", msg) + @test occursin("first: submesh node", msg) + # Nodes of the parent, but one cell spans two parent facets. + msg = errmsg(() -> add_boundary_pieces!(grid(), :bottom => segment((0.0, 0.0), (1.0, 0.0), 2))) + @test occursin("2 of 2 submesh cells match no facet of the parent mesh", msg) + @test occursin("first: submesh cell 1 centred at (", msg) + # The mid-line y = 0.5 lies on mesh edges of the parent, but they are interior facets. + g = grid() + msg = errmsg(() -> add_boundary_pieces!(g, :middle => segment((0.0, 0.5), (1.0, 0.5), 4))) + @test occursin("4 of 4 submesh cells match an interior facet of the parent mesh", msg) + @test !haskey(g.facetsets, "middle") + # One bad piece adds none of the pieces, and a piece cannot take the name of a facet set. + g = grid() + @test_throws ArgumentError add_boundary_pieces!( + g, :bottom => segment((0.0, 0.0), (1.0, 0.0), 4), :middle => segment((0.0, 0.5), (1.0, 0.5), 4) + ) + @test isempty(g.facetsets) + add_boundary_pieces!(g, :bottom => segment((0.0, 0.0), (1.0, 0.0), 4)) + @test occursin("already has a facet set :bottom", errmsg(() -> add_boundary_pieces!(g, :bottom => segment((0.0, 0.0), (1.0, 0.0), 4)))) + @test_throws ArgumentError("boundary piece names must be unique; got [:a, :a]") add_boundary_pieces!( + g, :a => segment((0.0, 0.0), (1.0, 0.0), 4), :a => segment((0.0, 1.0), (1.0, 1.0), 4) + ) + # A 2D cell is not a facet of a 2D mesh; a 3D submesh does not live in the parent's space. + msg = errmsg(() -> add_boundary_pieces!(grid(), :all => rectangle_grid(Triangle, (1, 1)))) + @test occursin("must have dimension 1", msg) + msg = errmsg(() -> add_boundary_pieces!(grid(), :face => face(1, 0.0, 2))) + @test occursin("has 3-dimensional coordinates", msg) + # A looser tolerance admits a segment that is off by less than it. + g = grid() + add_boundary_pieces!(g, :bottom => segment((0.0, 1.0e-4), (1.0, 1.0e-4), 4); atol = 1.0e-3) + @test length(getfacetset(g, "bottom")) == 4 + end + + @testset "a piece that is not on the boundary is an error" begin + grid = rectangle_grid(Triangle, (4, 4)) + addfacetset!(grid, "middle", p -> p[2] ≈ 0.5) + Ω = MeshDomain(grid) + Γ, Γl, Γr, Γb = boundarypiece.(Ω, (:middle, :left, :right, :bottom)) + bcs = [u(t, Γ) ~ 0, u(t, Γl) ~ 0, u(t, Γr) ~ 0, u(t, Γb) ~ 0, ic2d] + msg = errmsg(() -> fem_solve([heat2d], bcs, Ω, (x, y), t, [u(t, x, y)])) + @test occursin("facet set :middle is not on the boundary", msg) + end + + @testset "two conditions on one facet are an error" begin + # The bottom side twice, once as a submesh and once as the grid's own facet set. + grid = rectangle_grid(Triangle, (4, 4)) + add_boundary_pieces!(grid, :floor => segment((0.0, 0.0), (1.0, 0.0), 4)) + Ω = MeshDomain(grid) + Γb, Γf = boundarypiece.(Ω, (:bottom, :floor)) + bcs = [u(t, Γb) ~ 0, u(t, Γf) ~ 1, ic2d] + @test occursin("share 4 facets", errmsg(() -> fem_solve([heat2d], bcs, Ω, (x, y), t, [u(t, x, y)]))) + end +end + +@testset verbose = true "boundary completeness" begin + # u* = (1 + x)(1 + t) has no normal derivative on the top side, so leaving it out is the zero-flux condition. + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + (1 + x) + function open_top(; disc_kwargs...) + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + bcs = [u(t, Γl) ~ 1 + t, u(t, Γr) ~ 2 * (1 + t), u(t, Γb) ~ (1 + x) * (1 + t), ic2d] + return fem_solve([eq], bcs, Ω, (x, y), t, [u(t, x, y)]; disc_kwargs...), Γt + end + + @testset "a boundary with no condition warns once, naming the field and the piece" begin + (sol, _), _ = @test_logs (:warn, r"u: 4 of 16 boundary facets have no condition: Γ_top \(4 facets\)") open_top() + @test nodal_error(sol, u(t, x, y), uexact2d) <= tol + end + + @testset "natural = [pieces] declares the zero-flux condition and silences the warning" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + (sol, _), _ = @test_logs min_level = Base.CoreLogging.Warn open_top(; natural = [:top]) + @test nodal_error(sol, u(t, x, y), uexact2d) <= tol + # A BoundaryPiece is accepted as well as a name. + @test_logs min_level = Base.CoreLogging.Warn open_top(; natural = [boundarypiece(Ω, :top)]) + @test_throws ArgumentError("unknown facet set :nosuch; the mesh has facet sets :bottom, :left, :right, :top") FEMDiscretization(Ω, t; natural = [:nosuch]) + @test_throws ArgumentError FEMDiscretization(Ω, t; boundary_check = :loud) + end + + @testset "an explicit zero Neumann condition is silent too" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + bcs = [u(t, Γl) ~ 1 + t, u(t, Γr) ~ 2 * (1 + t), u(t, Γb) ~ (1 + x) * (1 + t), Dn(Γt)(u(t, Γt)) ~ 0, ic2d] + sol, _ = @test_logs min_level = Base.CoreLogging.Warn fem_solve([eq], bcs, Ω, (x, y), t, [u(t, x, y)]) + @test nodal_error(sol, u(t, x, y), uexact2d) <= tol + end + + @testset "boundary_check = :error is strict" begin + msg = errmsg(() -> open_top(; boundary_check = :error)) + @test occursin("u: 4 of 16 boundary facets have no condition: Γ_top (4 facets)", msg) + @test occursin("natural = [pieces]", msg) + (sol, _), _ = open_top(; boundary_check = :error, natural = [:top]) + @test nodal_error(sol, u(t, x, y), uexact2d) <= tol + end + + @testset "boundary_check = :off skips the check" begin + (sol, _), _ = @test_logs min_level = Base.CoreLogging.Warn open_top(; boundary_check = :off) + @test nodal_error(sol, u(t, x, y), uexact2d) <= tol + end + + @testset "one warning per call covers every field" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + eqs = [ + Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))), + Dt(v(t, x, y)) ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))), + ] + bcs = [u(t, Γl) ~ 0, v(t, Γl) ~ 0, v(t, Γt) ~ 0, u(0, x, y) ~ 0, v(0, x, y) ~ 0] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y), v(t, x, y)], []) + logs, _ = Test.collect_test_logs(() -> discretize(pdesys, FEMDiscretization(Ω, t))) + warns = filter(l -> l.level == Base.CoreLogging.Warn, logs) + @test length(warns) == 1 + @test occursin(r"u: 12 of 16 boundary facets.*Γ_bottom \(4 facets\), Γ_right \(4 facets\), Γ_top \(4 facets\)", warns[1].message) + @test occursin(r"v: 8 of 16 boundary facets.*Γ_bottom \(4 facets\), Γ_right \(4 facets\)", warns[1].message) + end + + @testset "a boundary outside every named piece is counted" begin + grid = bare_box(Triangle, (4, 4)) + add_boundary_pieces!(grid, :left => segment((0.0, 0.0), (0.0, 1.0), 4)) + Ω = MeshDomain(grid) + @named pdesys = PDESystem([heat2d], [u(t, boundarypiece(Ω, :left)) ~ 0, u(0, x, y) ~ 0], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_logs (:warn, r"12 of 16 boundary facets have no condition: 12 facets in no piece") discretize(pdesys, FEMDiscretization(Ω, t)) + end +end From 61842ad418f7932d1137a70bb15e491bec77a6ee Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 19:16:15 +0000 Subject: [PATCH 4/7] Handle meshes with no named facet sets in the boundary 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/frontend.jl | 2 +- test/shared/frontend_tests/boundaries.jl | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/frontend.jl b/src/frontend.jl index 8b94c111..f14ef605 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -336,7 +336,7 @@ function _check_boundary_conditions(disc::FEMDiscretization, an, ctx) isempty(open) && continue pieces = [(name, length(intersect(open, set))) for (name, set) in sort!(collect(facetsets); by = first)] listed = ["Γ_$name ($n facets)" for (name, n) in pieces if n > 0] - unnamed = length(setdiff(open, union(values(facetsets)...))) + unnamed = length(setdiff(open, union(Set{Ferrite.FacetIndex}(), values(facetsets)...))) unnamed > 0 && push!(listed, "$unnamed facets in no piece") push!(lines, " $(nameof(op)): $(length(open)) of $(length(boundary)) boundary facets have no condition: $(join(listed, ", "))") end diff --git a/test/shared/frontend_tests/boundaries.jl b/test/shared/frontend_tests/boundaries.jl index f8a4d137..319b355d 100644 --- a/test/shared/frontend_tests/boundaries.jl +++ b/test/shared/frontend_tests/boundaries.jl @@ -211,4 +211,10 @@ end @named pdesys = PDESystem([heat2d], [u(t, boundarypiece(Ω, :left)) ~ 0, u(0, x, y) ~ 0], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) @test_logs (:warn, r"12 of 16 boundary facets have no condition: 12 facets in no piece") discretize(pdesys, FEMDiscretization(Ω, t)) end + + @testset "a mesh with no named pieces warns instead of failing" begin + Ω = MeshDomain(bare_box(Triangle, (4, 4))) + @named pdesys = PDESystem([heat2d], [u(0, x, y) ~ 0], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_logs (:warn, r"16 of 16 boundary facets have no condition: 16 facets in no piece") discretize(pdesys, FEMDiscretization(Ω, t)) + end end From 66b5be4598d90d0d182a54208441afc1a635b4c3 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 19:18:47 +0000 Subject: [PATCH 5/7] Reject a non-positive atol in add_boundary_pieces! 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/mesh.jl | 3 ++- test/shared/frontend_tests/boundaries.jl | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/mesh.jl b/src/mesh.jl index 6bff351d..35db9d2b 100644 --- a/src/mesh.jl +++ b/src/mesh.jl @@ -201,13 +201,14 @@ group, or any grid whose cells are facets of `grid`. Afterwards `boundarypiece(M piece, exactly as for any other facet set; `grid` is modified, as by `Ferrite.addfacetset!`, and returns. A submesh cell is matched to a facet of `grid` through the nodes: each node of the submesh is the node of `grid` -within `atol` of it (by coordinates, since the two grids number their nodes independently; the default `atol` +within `atol > 0` of it (by coordinates, since the two grids number their nodes independently; the default `atol` is `1e-8` times the larger of `1` and the largest extent of `grid`), and the cell is the facet whose corner nodes are those of the cell. Nothing is added, for any of the pieces, if a node has no node of `grid` within `atol`, a cell matches no facet of `grid`, a cell matches an interior facet (shared by two cells) or `name` is already a facet set of `grid`; each is an `ArgumentError` that says which. """ function add_boundary_pieces!(grid::Ferrite.Grid, pieces::Pair...; atol = nothing) + atol === nothing || atol > 0 || throw(ArgumentError("atol must be positive, got $atol")) names = [String(first(p)) for p in pieces] allunique(names) || throw(ArgumentError("boundary piece names must be unique; got $(Symbol.(names))")) for name in names diff --git a/test/shared/frontend_tests/boundaries.jl b/test/shared/frontend_tests/boundaries.jl index 319b355d..06bf504a 100644 --- a/test/shared/frontend_tests/boundaries.jl +++ b/test/shared/frontend_tests/boundaries.jl @@ -115,6 +115,7 @@ end @test occursin("must have dimension 1", msg) msg = errmsg(() -> add_boundary_pieces!(grid(), :face => face(1, 0.0, 2))) @test occursin("has 3-dimensional coordinates", msg) + @test_throws ArgumentError("atol must be positive, got 0.0") add_boundary_pieces!(grid(), :bottom => segment((0.0, 0.0), (1.0, 0.0), 4); atol = 0.0) # A looser tolerance admits a segment that is off by less than it. g = grid() add_boundary_pieces!(g, :bottom => segment((0.0, 1.0e-4), (1.0, 1.0e-4), 4); atol = 1.0e-3) From 1a6e75b5983554b6194336427810f266de3974ff Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 19:21:39 +0000 Subject: [PATCH 6/7] Bucket submesh nodes relative to the parent's corner 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/mesh.jl | 4 +++- test/shared/frontend_tests/boundaries.jl | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/mesh.jl b/src/mesh.jl index 35db9d2b..26fae53e 100644 --- a/src/mesh.jl +++ b/src/mesh.jl @@ -122,7 +122,9 @@ _boundary_facets(grid::Ferrite.Grid) = Set(only(fs) for fs in values(_facet_owne # Map each node of `sub` to the parent node within `atol` of it (the nearest one), through a hash of `atol`-wide # buckets, so that a point's candidates lie in the 3^dim buckets around its own. function _match_nodes(grid::Ferrite.Grid{dim}, sub::Ferrite.Grid, atol) where {dim} - bucket(x) = ntuple(d -> floor(Int, x[d] / atol), dim) + # Relative to the parent's lowest corner, and clamped, so a translated mesh or a tiny `atol` cannot overflow `Int`. + origin = ntuple(d -> minimum(n -> n.x[d], Ferrite.getnodes(grid)), dim) + bucket(x) = ntuple(d -> floor(Int, clamp((x[d] - origin[d]) / atol, -1.0e15, 1.0e15)), dim) buckets = Dict{NTuple{dim, Int}, Vector{Int}}() for (i, node) in enumerate(Ferrite.getnodes(grid)) push!(get!(buckets, bucket(node.x), Int[]), i) diff --git a/test/shared/frontend_tests/boundaries.jl b/test/shared/frontend_tests/boundaries.jl index 06bf504a..4fdde4d2 100644 --- a/test/shared/frontend_tests/boundaries.jl +++ b/test/shared/frontend_tests/boundaries.jl @@ -116,6 +116,11 @@ end msg = errmsg(() -> add_boundary_pieces!(grid(), :face => face(1, 0.0, 2))) @test occursin("has 3-dimensional coordinates", msg) @test_throws ArgumentError("atol must be positive, got 0.0") add_boundary_pieces!(grid(), :bottom => segment((0.0, 0.0), (1.0, 0.0), 4); atol = 0.0) + # A mesh far from the origin, or a tiny tolerance, does not overflow the node lookup. + far = rectangle_grid(Triangle, (4, 4); lo = (1.0e8, 1.0e8), hi = (1.0e8 + 1, 1.0e8 + 1)) + empty!(far.facetsets) + add_boundary_pieces!(far, :bottom => segment((1.0e8, 1.0e8), (1.0e8 + 1, 1.0e8), 4); atol = 1.0e-12) + @test length(getfacetset(far, "bottom")) == 4 # A looser tolerance admits a segment that is off by less than it. g = grid() add_boundary_pieces!(g, :bottom => segment((0.0, 1.0e-4), (1.0, 1.0e-4), 4); atol = 1.0e-3) From e7e5d23a2560cc9ea62706c982e756424e2c1727 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 23:46:41 +0000 Subject: [PATCH 7/7] Declare the intended open boundaries in the facet_dofs and operators tests These tests have no boundary conditions on purpose, so they print the completeness warning on every run (12 lines in the Frontend log). They now declare natural sides; the two @test_logs that assert the warning are unchanged. 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/facet_dofs.jl | 12 +++++++----- test/shared/frontend_tests/operators.jl | 10 +++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/test/shared/frontend_tests/facet_dofs.jl b/test/shared/frontend_tests/facet_dofs.jl index 6b0626fa..243c2a39 100644 --- a/test/shared/frontend_tests/facet_dofs.jl +++ b/test/shared/frontend_tests/facet_dofs.jl @@ -1,7 +1,7 @@ # 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! +using Ferrite: Triangle, Quadrilateral, addcellset!, getcellset, getfacetset, getfacetsets, addfacetset! include(joinpath(@__DIR__, "..", "frontend.jl")) @@ -11,12 +11,14 @@ using ModelingToolkit: t_nounits as t 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). +sides(Ω) = Symbol.(keys(getfacetsets(Ω.mesh))) + +# The metadata of the heat problem on `Ω` with no boundary conditions (natural zero flux on every side). 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 + return discretize(pdesys, FEMDiscretization(Ω, t; natural = sides(Ω), kwargs...)).problem_type end @testset verbose = true "facet_dofs, dof_coordinates, cell_dofs" begin @@ -67,7 +69,7 @@ end @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 + md = discretize(pdesys, FEMDiscretization(Ω, t; natural = sides(Ω), 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 @@ -83,7 +85,7 @@ end @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 + md = discretize(pdesys, FEMDiscretization(Ω, t; natural = sides(Ω), regions = Dict(u => Region(Ω, :left_half)))).problem_type @test isempty(facet_dofs(md, :right, u)) @test length(facet_dofs(md, :left, u)) == 5 end diff --git a/test/shared/frontend_tests/operators.jl b/test/shared/frontend_tests/operators.jl index 41332bcc..2989c50f 100644 --- a/test/shared/frontend_tests/operators.jl +++ b/test/shared/frontend_tests/operators.jl @@ -38,7 +38,7 @@ end Ω = 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) + disc = FEMDiscretization(Ω, t; natural = [:top, :bottom]) ops = FiniteElementMethod.operators(pdesys, disc) md = ops.metadata @test sort(ops.prescribed) == sort([facet_dofs(md, left, u); facet_dofs(md, right, u)]) @@ -80,11 +80,11 @@ end 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)))) + @test occursin("nonlinear", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]; eq = nonlinear), FEMDiscretization(Ω, t; natural = [:right, :top, :bottom])))) + @test occursin("constant in time", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ sin(t)]), FEMDiscretization(Ω, t; natural = [:right, :top, :bottom])))) 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("time-independent", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]; eq = sourced), FEMDiscretization(Ω, t; natural = [:right, :top, :bottom])))) + ops = FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]), FEMDiscretization(Ω, t; natural = [:right, :top, :bottom])) @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