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 ec8aa0b7..eb6774b7 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 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. + - 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. - 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 @@ -135,4 +179,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 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 | +| 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 98525737..bea6f353 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. @@ -15,6 +15,12 @@ FiniteElementMethod.assemble_sources! FiniteElementMethod.operators ``` +## Boundary pieces from submeshes + +```@docs +add_boundary_pieces! +``` + `discretize(pdesys, disc)` returns the `DAEProblem` of the discretization (the `NonlinearProblem` of a steady one, see [Steady problems](@ref)). `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/docs/src/navier_stokes.md b/docs/src/navier_stokes.md index fc665024..8f292af0 100644 --- a/docs/src/navier_stokes.md +++ b/docs/src/navier_stokes.md @@ -32,7 +32,7 @@ bcs = [ [ν => 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()) + pairing = Dict(eqs[3] => p), natural = [Γout], 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()); diff --git a/examples/dfg_cylinder/dfg_cylinder.jl b/examples/dfg_cylinder/dfg_cylinder.jl index cc624e62..0543994f 100644 --- a/examples/dfg_cylinder/dfg_cylinder.jl +++ b/examples/dfg_cylinder/dfg_cylinder.jl @@ -71,7 +71,7 @@ function dfg_problem(grid; tend = 30.0, ν_ = 1.0e-3, Umax_ = 0.3, ramp = 1 - ex @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), + Ω, t; spaces = Dict(u => Q2, v => Q2, p => Q1), pairing = Dict(eqs[3] => p), natural = [Γout], initializealg = CheckInit(), kwargs... ) return DAEProblem(dfg, disc) diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 27a4159c..c76157a6 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/discretization.jl b/src/discretization.jl index 850d42e9..c567d075 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, algebraic_abstol = :auto, kwargs...) + codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, 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 @@ -35,6 +35,16 @@ gives a `PDENoTimeSolution`. - `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`. In a steady system the equations not named here take the remaining dependent variables in declared order. + - `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). - `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 @@ -97,6 +107,8 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization pairing::Dict{Equation, Any} codegen::Symbol dirichlet::Symbol + natural::Vector{Symbol} + boundary_check::Symbol algebraic_abstol::Union{Symbol, Nothing, Float64} kwargs::NamedTuple end @@ -130,7 +142,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, algebraic_abstol = :auto, kwargs... + dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, 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))")) @@ -144,6 +156,10 @@ 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) 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( @@ -156,7 +172,7 @@ function FEMDiscretization( 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, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, NamedTuple(kwargs) + codegen, dirichlet, unique(natural), boundary_check, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, NamedTuple(kwargs) ) end @@ -188,7 +204,7 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - 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. + - 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. - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. diff --git a/src/frontend.jl b/src/frontend.jl index 1196f0c2..77101fa8 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -327,22 +327,48 @@ 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(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 + 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) _check_domains(pdesys, disc) sys, replaced = PDEBase.make_pdesys_compatible(pdesys) 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_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) - Γ 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) steady = disc.time === nothing @@ -354,6 +380,7 @@ function _lower(pdesys, disc::FEMDiscretization) dirichlet = emit_dirichlet(an) t0, t1 = steady ? (0.0, 0.0) : v.intervals[v.time] space, names, ips = _space(disc, ctx, an, dirichlet, pvals, t0) + _check_boundary_conditions(disc, an, ctx) timedep = findfirst(bc -> _depends(bc.g, [an.slots.T]), an.essential) disc.dirichlet === :eliminate && timedep !== nothing && throw( ArgumentError( diff --git a/src/mesh.jl b/src/mesh.jl index 43db01a9..26fae53e 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,132 @@ 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} + # 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) + 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 > 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 + 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/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/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 7058a84e..7f37253e 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -5,6 +5,8 @@ using JET # 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. +# `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) : () @@ -17,6 +19,7 @@ run_qa( all_qualified_accesses_are_public = (; ignore = ( :FieldWise, :derivative, :Dual, :Partials, :value, :partials, :dirichlet_facetdof_indices, + :vertices, :reference_facets, :getrefdim, ), ), all_explicit_imports_via_owners = (; ignore = LTS_MTK_OWNER), diff --git a/test/shared/frontend_tests/boundaries.jl b/test/shared/frontend_tests/boundaries.jl new file mode 100644 index 00000000..4fdde4d2 --- /dev/null +++ b/test/shared/frontend_tests/boundaries.jl @@ -0,0 +1,226 @@ +# 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) + @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) + @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 + + @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 diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index 3144e6b0..a6a87f2f 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -221,6 +221,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 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