diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 3ac89999..5d77825e 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -19,7 +19,7 @@ rendering. | Dirichlet | yes | | Neumann | yes | | Robin | yes | -| Periodic | no | +| Periodic | yes | | Interface | no | | Time-dependent | yes | @@ -28,7 +28,7 @@ Restrictions of this release: - Geometries are `Ferrite.Grid` meshes (1D, 2D and 3D cell shapes) wrapped as `MeshDomain(grid)`, with boundary pieces named by the grid's facet sets. 1D, 2D and 3D meshes are tested; meshes with mixed cell types are rejected. - 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. - - Periodic conditions `u(t, Γa) ~ u(t, Γb)` are rejected. Interface conditions between regions have no syntax; every field lives on the whole mesh. + - Periodic conditions `u(t, Γa) ~ u(t, Γb)` pair two pieces that are translates of each other; they need `dirichlet = :algebraic` and are not returned by `operators`. Interface conditions between regions have no syntax; every field lives on the whole mesh. - 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. @@ -140,9 +140,71 @@ Like a Neumann condition, it enters the weak form as a facet integral. ## Periodic conditions -Not supported in this release. An equation between traces on two pieces, -`u(t, Γ_left) ~ u(t, Γ_right)`, is rejected with -`periodic boundary conditions are not supported`. +An equation between the traces of one field on two pieces, `u(t, Γ_left) ~ u(t, Γ_right)` (or +`u(Γ_left) ~ u(Γ_right)` for a steady problem), makes the field take equal values on the two +pieces. The pieces must be translates of each other: the translation is the difference of their +centroids, and every node of one piece (every dof of the field, for a higher-order space) must +have a node of the other at the translated place. Otherwise `discretize` throws an `ArgumentError` +that names both pieces and the mismatch. The pairs are per field, so one field may be periodic +where another carries Dirichlet pieces, and they work with any element space, including the +Taylor–Hood pair of a Navier–Stokes system, in the time-dependent and steady paths and with +`SUPG` test spaces. + +For a fully periodic box write one pair per direction. A corner node belongs to several pairs; +the nodes of all pairs of a field are collected into classes of equal nodes, and each class keeps +one master. Where a periodic piece meets a Dirichlet piece, the class contains a prescribed node +and that node is the master, so the Dirichlet value holds at the shared corner. If a class holds more than one +prescribed node (a Dirichlet piece touching both ends of a periodic pair), their data must agree. `discretize` compares them at 17 evenly spaced times of the time interval, and +time-dependent data are compared again at every evaluation by the solver; a difference beyond a relative `1e-8` is an +`ArgumentError` naming the periodic pieces, the nodes, the two values and the time. + +```julia +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF +using Ferrite: generate_grid, Triangle, Vec +using ModelingToolkit: t_nounits as t +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +Ω = MeshDomain(generate_grid(Triangle, (16, 16), Vec(0.0, 0.0), Vec(1.0, 1.0))) +left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +@named pdesys = PDESystem( + [Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))], + [u(t, left) ~ u(t, right), u(t, bottom) ~ u(t, top), u(0, x, y) ~ sin(2π * (x + y))], + [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.05)], [t, x, y], [u(t, x, y)], []) +prob = discretize(pdesys, FEMDiscretization(Ω, t)) +``` + +The solution is `exp(-8π² t) sin(2π (x + y))` and converges at the optimal rate; +`test/Interface/periodic.jl` runs this case, the steady and Navier–Stokes ones. + +Periodic pairs work in every problem class of this package, including nonlinear terms (the +nonlinear residual and Jacobian get the same row sums and ties inside Newton's method), SUPG test +spaces, steady and transient problems and coupled fields with different spaces: + +| Problem class with a periodic pair | Status | Covered by | +|:--- |:--- |:--- | +| Scalar linear, transient, 2D, P1 and P2, triangles and quadrilaterals, fully periodic | supported | `test/Interface/periodic.jl`, heat on a periodic box | +| Periodic in one direction with Dirichlet pieces in the other | supported | `test/Interface/periodic.jl`, periodic in x | +| Scalar linear on a line, transient, Galerkin and SUPG | supported | `test/Interface/periodic.jl`, periodic line | +| Scalar linear on a hexahedral mesh, steady, fully periodic | supported | `test/Interface/periodic.jl`, periodic cube | +| Steady (`NonlinearProblem`), linear terms, Galerkin and SUPG | supported | `test/Interface/periodic.jl`, steady advection–diffusion | +| Steady, nonlinear terms | supported | `test/Interface/periodic.jl`, steady nonlinear diffusion | +| Transient (`DAEProblem`), nonlinear terms and a time-dependent source | supported | `test/Interface/periodic.jl`, viscous Burgers | +| Coupled fields, different spaces per field, per-field pairs | supported | `test/Interface/periodic.jl`, coupled P2/P1 | +| Taylor–Hood Navier–Stokes, steady and transient (index-2 DAE) | supported | `test/Interface/periodic_navier_stokes.jl` | +| Boundary integrals (Neumann, Robin) on the other, non-periodic pieces | supported | assembled as before; the periodic pieces take no boundary integral | +| Pieces that are not translates of each other | error `periodic pieces Γa and Γb of u do not match under a translation: …` | `test/Interface/periodic.jl`, rejected pairs | +| A periodic piece that also carries another condition for that field | error `… has a periodic condition on Γ and a Dirichlet condition on the same piece` | same | +| `dirichlet = :eliminate`, or `operators` | error `… does not support periodic conditions …` | same | +| A space that is not a scalar Lagrange space (edge elements need orientation signs across the map) | error `… is not a nodal Lagrange space; periodic conditions are supported for scalar Lagrange spaces only …` | same, edge-element case | + +The operators keep every dof as an unknown. Each node of a class other than its master is tied +to it by an algebraic row `u_node − u_master = 0`, and the Galerkin equation of the tied node is +added to its master's, which is the condensed system `PᵀKP` of the identification. No boundary +integral is assembled on a periodic piece, since the two contributions cancel for a periodic +solution. The initial value of a tied node is its master's. A piece of a periodic pair cannot +also carry a Dirichlet, Neumann or Robin condition for that field. `dirichlet = :eliminate` and +[`operators`](@ref FiniteElementMethod.operators) do not support periodic conditions. ## Interface conditions @@ -188,7 +250,9 @@ is an error that names the problem; nothing falls back to `mtkcompile`. | A time-dependent Robin coefficient, such as `Dn(u(t, Γ)) + (1 + t) * u(t, Γ) ~ 0` | error | | `FEMDiscretization(…; codegen = :mtk)` | error | | A mesh with mixed cell types | error | -| A periodic condition `u(t, Γa) ~ u(t, Γb)` | error | +| A periodic condition `u(t, Γa) ~ u(t, Γb)` between pieces that are not translates of each other | error naming both pieces | +| A periodic piece that also carries a Dirichlet, Neumann or Robin condition for that field | error | +| A periodic condition with `dirichlet = :eliminate`, or in `operators` | error | | A time argument between spatial arguments, such as `u(x, t, y)` | error | | Two Dirichlet pieces of one field sharing nodes | the condition listed last wins | | 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` | diff --git a/docs/src/equation_classes.md b/docs/src/equation_classes.md index 40c280aa..a17e6b3f 100644 --- a/docs/src/equation_classes.md +++ b/docs/src/equation_classes.md @@ -21,14 +21,17 @@ mesh domain, no second time derivative, no integral term, nothing in 3D and noth | 1 | Nonlinear through state-dependent coefficients and sources: `k(u)`, `f(u)`, viscous Burgers | `k = 1+u²` rates 1.71–1.94 (report 5, red cell); `burgers_2d` two-field, rates 2.26, 2.43 (report 6) | VERIFIED | | 1 | Convection–diffusion at moderate cell Péclet number | `convdiff2` rates 2.01, 2.00 against MethodOfLines' 4.75e-2, 2.54e-2, 1.32e-2 (rate about 1) (report 6) | VERIFIED | | 1 | Curvilinear radial Laplacians through the product rule | `sph`, `4/r² ∂ᵣ(r² ∂ᵣu)`, rate 2.00 on four refinements (report 6) | VERIFIED | +| 1 | Periodic conditions `u(t, Γa) ~ u(t, Γb)` between translated boundary pieces, in one or both directions, scalar or coupled fields with different spaces | `test/Interface/periodic.jl`: the heat equation on a fully periodic box follows its Fourier mode at rate 2 (P1) and 3 (P2); periodic in x with Dirichlet in y; steady periodic advection–diffusion at rate 2, with Galerkin and `SUPG`; two coupled fields; `test/Interface/periodic_navier_stokes.jl`: Kovasznay flow with periodic bottom and top at rates 3 and 2, and a Q2/Q1 channel flow past a block, periodic in the cross-stream direction, that conserves mass to 1e-3 | VERIFIED; the library corpus has no periodic system solved by this package | | 1 | Dirichlet (constant and time-dependent), Neumann, Robin | time-dependent Dirichlet in `burgers_2d` and all `funcconv`; Neumann in `pdesys`, `sph` (report 6); Robin in cases (i), (ii) and the 2D DAE prototype (reports 5, 4) | VERIFIED; Robin from reports 4–5 only | | 1 | 1D and 2D on boxes | `Line` and `Quadrilateral` grids end to end (report 6); 2D DAE with three condition kinds (report 4); two-field P1/P2 solution interface (report 7) | VERIFIED | | 1 | Unstructured and Gmsh meshes | pieces resolved to facet sets on an L-shaped Ferrite grid and a Gmsh import probed (reports 2, 4); the API example of [Getting started](@ref) then solves on a Gmsh L-shape | VERIFIED | | 1 | Mixed saddle-point problems with an inf-sup-stable unequal-order pair chosen by the user: Stokes and incompressible Navier–Stokes with Taylor–Hood Q2/Q1 or P2/P1 | DFG 2D-1 cylinder through the PDESystem front end (#31; test group NavierStokes, test/NavierStokes/dfg_cylinder.jl): tolerance stated before the runs = Schäfer–Turek intervals cD ∈ [5.57, 5.59], cL ∈ [0.0104, 0.0110], Δp ∈ [0.1172, 0.1176]; 16 430 unknowns give cD 5.579436, cL 0.010583, Δp 0.117584 and agree with an independent hand-written Ferrite solver on the same mesh to 1e-7; 148 986 unknowns: relative errors −4.5e-7, −5.1e-6, −5.3e-5 (benchmark (d)); Taylor–Hood Stokes rates 3 and 2 (#28) | VERIFIED for the example's formulation: continuity paired with p explicitly, pressure pinned on a boundary piece, outflow ν∂ₙu = 0, index-2 DAE started from rest; no inf-sup check is made, the user chooses a stable pair | | 2, accepted; unreliable with Galerkin testing, use `SUPG(τ)` | Pure advection, advection-dominated problems, inviscid hyperbolic problems | `inviscid_burgers_monotonic` exact to 1e-10 only because its solution lies in the P1 space, so it says nothing about shocks or steep fronts; `convdiff4` at cell Péclet > 1 dropped to rate 1.44 on the coarse mesh (report 6) | VERIFIED limitation | -| 3, rejected with a clean error | Periodic conditions; mixed cell types; third- and fourth-order spatial operators; `∂ₜ²` (write a first-order system); integral terms; state-dependent mass; non-conormal natural conditions | Appendix A messages; 16 library rejections all periodic, 7 of them also higher order (report 6) | VERIFIED | +| 3, rejected with a clean error | Mixed cell types; third- and fourth-order spatial operators; `∂ₜ²` (write a first-order system); integral terms; state-dependent mass; non-conormal natural conditions | Appendix A messages; the 16 library rejections of report 6 were all periodic, 7 of them also higher order, and the periodic ones are now supported (see the periodic row above) | VERIFIED | | not evidenced | discontinuous coefficients across interfaces | nothing in any corpus or prototype | neither claimed nor rejected | +The periodic row was added when periodic conditions were implemented; the specification table lists them in the rejected class. + The "Unstructured and Gmsh meshes" row's solve on a Gmsh mesh is the API example of [Getting started](@ref), which the test suite runs (`test/Frontend/api_example.jl`). diff --git a/docs/src/extension_contract.md b/docs/src/extension_contract.md index 0c0213fc..0c3fed0d 100644 --- a/docs/src/extension_contract.md +++ b/docs/src/extension_contract.md @@ -68,7 +68,7 @@ The checks include: - equations: an equation count that differs from the number of dependent variables, unknown `pairing`, `spaces` or `regions` keys, time-dependent mass or stiffness coefficients, parameters without a numeric value, SUPG with parameters in `τ` or `b`; - - boundary conditions: periodic conditions, conditions on facet sets the mesh lacks, a + - boundary conditions: periodic pieces that are not translates of each other or that carry another condition, conditions on facet sets the mesh lacks, a region's field with conditions outside the region, time-dependent Dirichlet data with `dirichlet = :eliminate`. diff --git a/docs/src/index.md b/docs/src/index.md index a158b637..5fa4ff1a 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -8,8 +8,7 @@ on a mesh, derives the Galerkin weak form, assembles it with !!! warning This package is under construction. Problems with Galerkin or SUPG testing are supported, including nonlinear terms whose state dependence is in the coefficients, sources and - natural conditions (`∇·((1 + u²)∇u)`, `u ∂ₓu`, `u²`, `∂ₙu = −u⁴`); periodic - conditions and time-dependent mass or stiffness coefficients raise an error. [Boundary conditions and limitations](@ref) lists every restriction. + natural conditions (`∇·((1 + u²)∇u)`, `u ∂ₓu`, `u²`, `∂ₙu = −u⁴`); time-dependent mass or stiffness coefficients raise an error. [Boundary conditions and limitations](@ref) lists every restriction. [Getting started](@ref) solves a heat equation on a Gmsh mesh. A MethodOfLines user should then read [Differences from MethodOfLines](@ref): coordinates are bound differently, boundary diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 09eb1685..faed3491 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!, norm +using LinearAlgebra: I, dot, mul!, norm using ModelingToolkit: ModelingToolkit, @parameters, @variables, Differential, MTKParameters, ProblemTypeCtx, System, complete, getmetadata using NonlinearSolveFirstOrder: NewtonRaphson @@ -22,7 +22,7 @@ using PrecompileTools: PrecompileTools using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions using SciMLBase: SciMLBase, DAEFunction, DAEProblem using SciMLBase.SymbolicIndexingInterface: SymbolicIndexingInterface, getp, parameter_index, variable_index -using SparseArrays: SparseMatrixCSC, nonzeros, nzrange, rowvals +using SparseArrays: SparseMatrixCSC, findnz, nonzeros, nzrange, rowvals, sparse using SymbolicUtils: SymbolicUtils using Symbolics: Symbolics, Equation, Num, @register_array_symbolic, substitute, unwrap @@ -32,6 +32,7 @@ RuntimeGeneratedFunctions.init(@__MODULE__) include("numeric_dae.jl") include("mesh.jl") +include("periodic.jl") include("space.jl") include("solution.jl") include("weakform.jl") diff --git a/src/discretization.jl b/src/discretization.jl index b8cdcdf8..ac0806e2 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -80,6 +80,11 @@ gives a `PDENoTimeSolution`. by the discretization and rejected, as are `tspan`, `u0`, `p` and `differential_vars`, which come from the `PDESystem` and the weak form. +A periodic condition `u(t, Γa) ~ u(t, Γb)` (`u(Γa) ~ u(Γb)` without time) makes the field `u` take equal values at +the nodes of two boundary pieces that are translates of each other; pieces that are not are an error naming +them. Fully periodic domains list one pair per direction, and a node shared by several pairs is tied to one master. +See the documentation page on boundary conditions for the algebraic form. + Pieces come from `boundarypiece.(Ω, names)`; on an analytic DomainSets box write `boundarypiece.(Ref(rect), names)`, since DomainSets types do not broadcast as scalars. @@ -195,7 +200,7 @@ end # it on the Discretization page and docs/src/boundary_conditions.md keeps a static copy; # test/Frontend/documentation.jl keeps the two equal. PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions(; - geometries = (:mesh,), dirichlet = true, neumann = true, robin = true, periodic = false, + geometries = (:mesh,), dirichlet = true, neumann = true, robin = true, periodic = true, interface = false, time_dependent = true, notes = """ Restrictions of this release: @@ -203,7 +208,7 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( - Geometries are `Ferrite.Grid` meshes (1D, 2D and 3D cell shapes) wrapped as `MeshDomain(grid)`, with boundary pieces named by the grid's facet sets. 1D, 2D and 3D meshes are tested; meshes with mixed cell types are rejected. - 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. - - Periodic conditions `u(t, Γa) ~ u(t, Γb)` are rejected. Interface conditions between regions have no syntax; every field lives on the whole mesh. + - Periodic conditions `u(t, Γa) ~ u(t, Γb)` pair two pieces that are translates of each other; they need `dirichlet = :algebraic` and are not returned by `operators`. Interface conditions between regions have no syntax; every field lives on the whole mesh. - 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. diff --git a/src/frontend.jl b/src/frontend.jl index 67410165..5f5d5dfb 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -8,7 +8,7 @@ # Tracking: move to PDEBase's `symbolic_discretize` with hook methods once the numeric path builds # its system through `generate_system` (PDEBase M0 release as the compat floor). -const _PERIODIC_UNSUPPORTED = "periodic boundary conditions are not supported" +const _PERIODIC_FORM = "a condition relating traces on two boundary pieces must be a periodic pair of the form u(t, Γa) ~ u(t, Γb)" _unwrap_arg(a) = SymbolicUtils.unwrap_const(unwrap(a)) @@ -106,10 +106,54 @@ function PDEBase.interface_errors(pdesys::ModelingToolkit.PDESystem, v::PDEBase. return nothing end -function _boundary_map(bcs, v, disc) +# A condition on two pieces is a periodic pair `u(t, Γa) ~ u(t, Γb)` of one field (`u(Γa) ~ u(Γb)` without time); the +# pairs leave the conditions that PDEBase parses, as `(field, Γa, Γb)`. Both traces must take exactly the time variable +# (or nothing, for a steady system) besides the piece: any other time argument would be a different problem. +function _split_periodic(bcs, ctx, time) + pairs, rest = Tuple{Int, Any, Any}[], [] for eq in bcs - length(_trace_pieces(eq.lhs - eq.rhs)) > 1 && throw(ArgumentError("$(_PERIODIC_UNSUPPORTED): $eq")) + length(_trace_pieces(eq.lhs - eq.rhs)) > 1 || (push!(rest, eq); continue) + lhs, rhs = _unwrap_arg(eq.lhs), _unwrap_arg(eq.rhs) + f = _field_index(ctx, lhs) + (f !== nothing && _field_index(ctx, rhs) !== nothing && length(_trace_pieces(lhs)) == 1 && length(_trace_pieces(rhs)) == 1) || + throw(ArgumentError("$_PERIODIC_FORM: $eq")) + f == _field_index(ctx, rhs) || + throw(ArgumentError("a periodic condition relates the traces of one field on two pieces, but $eq names two fields")) + for trace in (lhs, rhs) + others = [a for a in SymbolicUtils.arguments(trace) if !(_unwrap_arg(a) isa PDEBase.BoundaryPiece)] + ok = time === nothing ? isempty(others) : length(others) == 1 && isequal(_unwrap_arg(only(others)), _unwrap_arg(time)) + ok || throw( + ArgumentError( + "the trace $trace of the periodic condition $eq must take " * + (time === nothing ? "no time argument, as in u(Γa) ~ u(Γb), since the system is steady" : "the time variable $time as its only argument besides the piece, as in u($time, Γa) ~ u($time, Γb)") * + "; a fixed, shifted or scaled time is not supported" + ) + ) + end + push!(pairs, (f, only(_trace_pieces(lhs)), only(_trace_pieces(rhs)))) + end + return pairs, rest +end + +# A piece of a periodic pair carries no other condition on that field: the pair takes its place. +function _check_periodic_conflicts(periodic, an, ctx) + for (f, Γa, Γb) in periodic, Γ in (Γa, Γb) + for (kind, pieces) in ( + "Dirichlet" => [bc.piece for bc in an.essential if bc.field == f], + "Neumann or Robin" => [bc.piece for bc in an.natural if bc.eq == f], + ) + any(isequal(Γ), pieces) && throw( + ArgumentError( + "$(nameof(ctx.ops[f])) has a periodic condition on $Γ and a $kind condition on the same piece; " * + "a periodic piece cannot carry another condition for that field" + ) + ) + end end + return nothing +end + +function _boundary_map(bcs, v, disc) orders = Dict(x => PDEBase.d_orders(x, bcs) for x in PDEBase.all_ivs(v)) return PDEBase.parse_bcs(bcs, v, orders, disc) end @@ -186,7 +230,7 @@ function _parameter_values(pdesys, ctx) end end -function _space(disc, ctx, analysis, dirichlet, pvals, t0) +function _space(disc, ctx, analysis, dirichlet, periodic, pvals, t0, tend) grid = disc.domain.mesh shape = Ferrite.getrefshape(Ferrite.getcelltype(grid)) names = Symbol[nameof(op) for op in ctx.ops] @@ -200,9 +244,19 @@ function _space(disc, ctx, analysis, dirichlet, pvals, t0) for (bc, (_, _, g)) in zip(analysis.essential, dirichlet) ] regions = Dict(names[f] => String(disc.regions[op].name) for (f, op) in enumerate(ctx.ops) if haskey(disc.regions, op)) - _check_region_pieces(grid, regions, names, analysis) + _check_region_pieces(grid, regions, names, analysis, periodic) + for (f, Γa, Γb) in periodic + ips[f] isa Ferrite.Lagrange || throw( + ArgumentError( + "$(names[f]) has a periodic condition on $Γa and $Γb but the space $(ips[f]) is not a nodal Lagrange space; " * + "periodic conditions are supported for scalar Lagrange spaces only, since other spaces (such as edge elements) " * + "need orientation signs across the periodic map" + ) + ) + end + pairs = [(names[f], String(Γa.name), String(Γb.name)) for (f, Γa, Γb) in periodic] space = FEMSpace( - grid, names .=> ips; dirichlet = bcs, quadrature = disc.quadrature, t0, regions, + grid, names .=> ips; dirichlet = bcs, periodic = pairs, quadrature = disc.quadrature, t0, tend, regions, hessians = disc.test_space isa SUPG ) return space, names, ips @@ -210,8 +264,11 @@ end # A condition on a field restricted to a region must lie on the region: Ferrite would otherwise drop the facets # outside it without a word. -function _check_region_pieces(grid, regions, names, analysis) - conditions = [[(bc.field, bc.piece) for bc in analysis.essential]; [(bc.eq, bc.piece) for bc in analysis.natural]] +function _check_region_pieces(grid, regions, names, analysis, periodic) + conditions = [ + [(bc.field, bc.piece) for bc in analysis.essential]; [(bc.eq, bc.piece) for bc in analysis.natural]; + [(f, Γ) for (f, Γa, Γb) in periodic for Γ in (Γa, Γb)] + ] for (f, Γ) in conditions haskey(regions, names[f]) || continue cells = Ferrite.getcellset(grid, regions[names[f]]) @@ -226,16 +283,17 @@ function _check_region_pieces(grid, regions, names, analysis) end # Nodal coordinates of every dof; Lagrange interpolation of `x_d` gives them exactly. -function _dof_coordinates(space) - dim = _meshdim(space.grid) +_dof_coordinates(space) = _dof_coordinates(space.grid, space.dh, space.fields) +function _dof_coordinates(grid, dh, names) + dim = _meshdim(grid) comps = map(1:dim) do d - a = zeros(Ferrite.ndofs(space.dh)) - for name in space.fields - Ferrite.apply_analytical!(a, space.dh, name, x -> x[d]) + a = zeros(Ferrite.ndofs(dh)) + for name in names + Ferrite.apply_analytical!(a, dh, name, x -> x[d]) end a end - return [Ferrite.Vec{dim}(ntuple(d -> comps[d][i], dim)) for i in 1:Ferrite.ndofs(space.dh)] + return [Ferrite.Vec{dim}(ntuple(d -> comps[d][i], dim)) for i in 1:Ferrite.ndofs(dh)] end # The Dirichlet values at `t` are evaluated from the symbolic data rather than through the @@ -251,7 +309,12 @@ function _dirichlet_values(space, dirichlet, coords, pvals, t0) end gs = [g for (_, _, g) in dirichlet] dofs = prescribed_dofs(space) - values!(out, t) = (foreach(((k, d),) -> out[k] = gs[owner[d]](coords[d], t, pvals), enumerate(dofs)); out) + position = Dict(d => k for (k, d) in enumerate(dofs)) + function values!(out, t) + foreach(((k, d),) -> out[k] = gs[owner[d]](coords[d], t, pvals), enumerate(dofs)) + check_agreement(space.classes, d -> out[position[d]], t) + return out + end return values!, values!(zeros(length(dofs)), t0) end @@ -284,12 +347,12 @@ function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) assemble_linear!(M, K, F, ctx, static, pvals; t = t0) load = isempty(dynamic) ? F : (out, t) -> (assemble_sources!(out, _fresh_values(ctx), dynamic, pvals, t); out .+= F) nonlinear = any(k -> k.kind === :nonlinear, kernels) ? - FEMNonlinear(NonlinearOperator(_fresh_values(ctx), kernels; ch = space.ch), pvals) : nothing + FEMNonlinear(NonlinearOperator(_fresh_values(ctx), kernels; pattern = space.pattern), pvals) : nothing coords = _dof_coordinates(space) values!, values0 = _dirichlet_values(space, dirichlet, coords, pvals, t0) ops = FEMOperators( M, K, load, [name => field_range(space, name) for name in names]; - prescribed = prescribed_dofs(space), dirichlet_values = timedep_dirichlet ? values! : values0, nonlinear + prescribed = prescribed_dofs(space), dirichlet_values = timedep_dirichlet ? values! : values0, nonlinear, ties = space.ties ) raw = (; M, K, load, nonlinear = nonlinear !== nothing, prescribed = prescribed_dofs(space), dirichlet_values = values0, timedep_dirichlet) return ops, coords, raw @@ -329,8 +392,8 @@ 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) +# Neumann or Robin condition in its equation, a periodic pair, or an entry in `disc.natural`. +function _check_boundary_conditions(disc::FEMDiscretization, an, ctx, periodic) disc.boundary_check === :off && return nothing grid = disc.domain.mesh boundary = _boundary_facets(grid) @@ -339,7 +402,7 @@ function _check_boundary_conditions(disc::FEMDiscretization, an, ctx) 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]] + 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]; [Γ.name for (g, Γa, Γb) in periodic if g == f for Γ in (Γa, Γb)]] union!(covered, facetsets[name]) end cells = haskey(disc.regions, op) ? Set(Ferrite.getcellset(grid, String(disc.regions[op].name))) : nothing @@ -364,11 +427,13 @@ function _lower(pdesys, disc::FEMDiscretization) 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, _ = PDEBase.split_ics_bcs(boundarymap, v, disc) ctx = StrongForm.SlotContext(sys, v) + periodic, bcs = _split_periodic(sys.bcs, ctx, disc.time) + boundarymap = _boundary_map(bcs, v, disc) + ics, _ = PDEBase.split_ics_bcs(boundarymap, v, disc) an = _paired(StrongForm.analyse(sys, v, boundarymap; ibp = disc.ibp), pdesys.eqs, ctx, disc) - isempty(an.periodic) || throw(ArgumentError(_PERIODIC_UNSUPPORTED)) + isempty(an.periodic) || throw(ArgumentError(_PERIODIC_FORM)) + _check_periodic_conflicts(periodic, an, ctx) 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 @@ -379,8 +444,8 @@ function _lower(pdesys, disc::FEMDiscretization) pvals = _parameter_values(sys, ctx) 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) + space, names, ips = _space(disc, ctx, an, dirichlet, periodic, pvals, t0, t1) + _check_boundary_conditions(disc, an, ctx, periodic) timedep = findfirst(bc -> _depends(bc.g, [an.slots.T]), an.essential) disc.dirichlet === :eliminate && timedep !== nothing && throw( ArgumentError( @@ -388,9 +453,15 @@ function _lower(pdesys, disc::FEMDiscretization) "$(an.essential[timedep].piece.name) depends on time; use the default dirichlet = :algebraic" ) ) + disc.dirichlet === :eliminate && !isempty(periodic) && throw( + ArgumentError("dirichlet = :eliminate does not support periodic conditions; use the default dirichlet = :algebraic") + ) ops, coords, raw = _operators(space, wf, names, dirichlet, pvals, t0, timedep !== nothing) u0 = _initial_values(Equation[b.eq for b in ics], ctx, space, coords, an, names, pvals) dirichlet_values!(view(u0, ops.prescribed), ops.load, t0) + for (m, s) in ops.ties + u0[m] = u0[s] + end elimination = nothing unknown_u0 = u0 if disc.dirichlet === :eliminate @@ -505,6 +576,7 @@ end function _index2(ops::FEMOperators, selfnonlinear) free = trues(size(ops.K, 1)) free[ops.prescribed] .= false + free[first.(ops.ties)] .= false # the identification rows of a periodic pair are not part of the saddle structure return any(ops.fields) do (name, r) rows = filter(i -> free[i], r) !isempty(rows) && !(name in selfnonlinear) && !any(ops.differential_vars[rows]) && iszero(ops.K[rows, r]) @@ -638,7 +710,7 @@ It is the linear, time-independent case only, and anything else raises an `Argum nonlinear term ("operators returns linear operators only, but the PDESystem has nonlinear terms"), a time-dependent source ("operators needs time-independent sources, but a source depends on time") and time-dependent Dirichlet data ("operators needs Dirichlet data that are -constant in time"). Parameters are substituted by their values, as for the `DAEProblem`. +constant in time"), and a periodic condition. Parameters are substituted by their values, as for the `DAEProblem`. """ function operators(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) parts = _lower(pdesys, disc) @@ -646,6 +718,7 @@ function operators(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) nonlinear && throw(ArgumentError("operators returns linear operators only, but the PDESystem has nonlinear terms")) load isa AbstractVector || throw(ArgumentError("operators needs time-independent sources, but a source depends on time")) timedep_dirichlet && throw(ArgumentError("operators needs Dirichlet data that are constant in time")) + isempty(parts.md.space.ties) || throw(ArgumentError("operators does not support periodic conditions; use discretize")) differential_vars = falses(size(M, 1)) for (k, i) in enumerate(rowvals(M)) iszero(nonzeros(M)[k]) || (differential_vars[i] = true) diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index 863aea17..dca631de 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -127,10 +127,11 @@ struct FEMNonlinear{T <: AbstractFloat} pool::Vector{Any} lock::ReentrantLock elimination::Any # `nothing`, or `(e::DirichletElimination, nzmap)` with `nzmap` the positions of `J_N[free, free]` in `J_N` + ties::Any # `nothing`, or `(summed, from, to)`: the summed `mirror => master` ties and the positions in `J_N` of the entries of mirror rows and of the entries of the master rows they are added to end -function FEMNonlinear(op, p, prescribed = falses(0)) +function FEMNonlinear(op, p, prescribed = falses(0), ties = nothing) T = eltype(p) <: AbstractFloat ? eltype(p) : Float64 - return FEMNonlinear(op, collect(T, p), prescribed, Any[], ReentrantLock(), nothing) + return FEMNonlinear(op, collect(T, p), prescribed, Any[], ReentrantLock(), nothing, ties) end Base.show(io::IO, ::FEMNonlinear) = print(io, "FEMNonlinear") @@ -164,6 +165,7 @@ function add_full_nonlinear!(r, N::FEMNonlinear, u, t) for i in eachindex(r) N.prescribed[i] || (r[i] += op.r[i]) end + N.ties === nothing || foreach(((m, s),) -> r[s] += op.r[m], first(N.ties)) r end end @@ -178,6 +180,7 @@ function add_full_nonlinear!(r, N::FEMNonlinear, u::AbstractVector{ForwardDiff.D for i in eachindex(r) N.prescribed[i] || (r[i] += ForwardDiff.Dual{T}(op.r[i], ForwardDiff.Partials(ntuple(k -> dr[i, k], Val(P))))) end + N.ties === nothing || foreach(((m, s),) -> r[s] += ForwardDiff.Dual{T}(op.r[m], ForwardDiff.Partials(ntuple(k -> dr[m, k], Val(P)))), first(N.ties)) r end end @@ -197,6 +200,12 @@ function add_nonlinear_jacobian!(J, N::FEMNonlinear, u, t) for k in eachindex(rows) N.prescribed[rows[k]] || (out[k] += vals[k]) end + if N.ties !== nothing + _, from, to = N.ties + for (a, b) in zip(from, to) + out[b] += vals[a] + end + end else e, nzmap = elimination vals, out = nonzeros(jacobian!(op.J, op, full_state(e, u), N.p, t)), nonzeros(J) @@ -258,11 +267,14 @@ struct FEMOperators differential_vars::BitVector jac_prototype::SparseMatrixCSC{Float64, Int} nonlinear::Union{Nothing, FEMNonlinear} + ties::Vector{Pair{Int, Int}} end +FEMOperators(M, K, load, fields, prescribed, differential_vars, jac_prototype, nonlinear) = + FEMOperators(M, K, load, fields, prescribed, differential_vars, jac_prototype, nonlinear, Pair{Int, Int}[]) function FEMOperators( M::SparseMatrixCSC, K::SparseMatrixCSC, load, fields; - prescribed = Int[], dirichlet_values = 0.0, nonlinear = nothing + prescribed = Int[], dirichlet_values = 0.0, nonlinear = nothing, ties = Pair{Int, Int}[] ) n = size(K, 1) size(M) == size(K) == (n, n) || throw(DimensionMismatch("M and K must be square of the same size; got $(size(M)) and $(size(K))")) @@ -277,19 +289,32 @@ function FEMOperators( stop == n || throw(ArgumentError("field ranges cover 1:$stop but the operators have $n rows")) prescribed = collect(Int, prescribed) M, K = copy(SparseMatrixCSC{Float64, Int}(M)), copy(SparseMatrixCSC{Float64, Int}(K)) + ties = collect(Pair{Int, Int}, ties) + apply_ties!(M, K, ties, prescribed) replace_dirichlet_rows!(M, K, prescribed) differential_vars = falses(n) for (k, i) in enumerate(rowvals(M)) iszero(nonzeros(M)[k]) || (differential_vars[i] = true) end - F = FEMLoad(load, prescribed, dirichlet_values, n) + tied_load = if isempty(ties) + load + elseif load isa AbstractVector + apply_ties!(copy(load), ties, prescribed) + else + isprescribed = isprescribed_mask(n, prescribed) + function (out, t) + load(out, t) + return apply_ties!(out, ties, isprescribed) + end + end + F = FEMLoad(tied_load, prescribed, dirichlet_values, n) if nonlinear !== nothing J = nonlinear.op.J J.colptr == K.colptr && J.rowval == K.rowval || throw(ArgumentError("the nonlinear operator's Jacobian must have the sparsity pattern of M and K, e.g. NonlinearOperator(ctx, kernels; ch) with the ConstraintHandler of allocate_matrix(dh, ch)")) - nonlinear = FEMNonlinear(nonlinear.op, nonlinear.p, isprescribed_mask(n, prescribed)) + nonlinear = FEMNonlinear(nonlinear.op, nonlinear.p, isprescribed_mask(n, [prescribed; first.(ties)]), _tie_positions(J, ties, prescribed)) end - return FEMOperators(M, K, F, fields, prescribed, differential_vars, copy(K), nonlinear) + return FEMOperators(M, K, F, fields, prescribed, differential_vars, copy(K), nonlinear, ties) end function isprescribed_mask(n, prescribed) @@ -370,7 +395,7 @@ function eliminate_dirichlet(ops::FEMOperators) N === nothing && return reduced, elimination # The positions of the stored entries of K[free, free], which has the pattern of N's Jacobian block. positions = SparseMatrixCSC(n, n, ops.K.colptr, ops.K.rowval, collect(eachindex(nonzeros(ops.K)))) - Nfree = FEMNonlinear(N.op, N.p, N.prescribed, Any[], ReentrantLock(), (elimination, nonzeros(positions[free, free]))) + Nfree = FEMNonlinear(N.op, N.p, N.prescribed, Any[], ReentrantLock(), (elimination, nonzeros(positions[free, free])), nothing) (; M, K, load, fields, prescribed, differential_vars, jac_prototype) = reduced return FEMOperators(M, K, load, fields, prescribed, differential_vars, jac_prototype, Nfree), elimination end @@ -444,19 +469,25 @@ algebraic variable, and the solution and its dense output do not depend on it. """ function consistent_du0(ops::FEMOperators, u0, t0) dd = ops.differential_vars - isprescribed = falses(length(u0)) + n = length(u0) + # `du` of a tied dof is its master's, so the columns of tied dofs fold into their masters'. + mirrors, masters = first.(ops.ties), last.(ops.ties) + kept = setdiff(1:n, mirrors) + fold = isempty(ops.ties) ? I : sparse([kept; mirrors], [kept; masters], 1.0, n, n) + M = ops.M * fold + isprescribed = falses(n) isprescribed[ops.prescribed] .= true - for j in axes(ops.M, 2) - dd[j] || isprescribed[j] || all(iszero, view(nonzeros(ops.M), nzrange(ops.M, j))) || + for j in axes(M, 2) + dd[j] || isprescribed[j] || all(iszero, view(nonzeros(M), nzrange(M, j))) || throw(ArgumentError("variable $j is algebraic (its row of M is zero) but its column of M is not, so a consistent du0 cannot be computed; pass du0 explicitly")) end - du0 = zeros(promote_type(eltype(u0), eltype(ops.M)), length(u0)) + du0 = zeros(promote_type(eltype(u0), eltype(ops.M)), n) du0[ops.prescribed] = dirichlet_rates(ops.load, t0) - any(dd) || return du0 - rhs = load!(zeros(length(u0)), ops.load, t0) - ops.K * u0 - ops.M * du0 - ops.nonlinear === nothing || (rhs .-= nonlinear_residual!(zeros(length(u0)), ops.nonlinear, u0, t0)) - du0[dd] = ops.M[dd, dd] \ rhs[dd] - return du0 + any(dd) || return fold * du0 + rhs = load!(zeros(n), ops.load, t0) - ops.K * u0 - M * du0 + ops.nonlinear === nothing || (rhs .-= nonlinear_residual!(zeros(n), ops.nonlinear, u0, t0)) + du0[dd] = M[dd, dd] \ rhs[dd] + return fold * du0 end function check_pattern(J, A, name) diff --git a/src/operators.jl b/src/operators.jl index 7229ae87..38d0d0c9 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -1,10 +1,10 @@ # Nonlinear operator and linear-operator cache with the reassembly policy (spec §8.1–8.3, red-cell m5). """ - NonlinearOperator(ctx, kernels; ch = nothing) + NonlinearOperator(ctx, kernels; ch = nothing, pattern = allocate_matrix(dh, ch)) The `:nonlinear` kernels of `kernels` on `ctx`, with preallocated residual `r`, Jacobian `J` (sparsity from -`allocate_matrix(dh, ch)`) and element scratch. Use [`residual!`](@ref), [`jacobian!`](@ref) and +`allocate_matrix(dh, ch)`, or `pattern`) and element scratch. Use [`residual!`](@ref), [`jacobian!`](@ref) and [`residual_jacobian!`](@ref); `op(r, u, p, t)` is `residual!(r, op, u, p, t)`. """ struct NonlinearOperator{C <: AssemblyContext, V <: Tuple, G <: Tuple, JT, T <: AbstractFloat} @@ -18,11 +18,11 @@ struct NonlinearOperator{C <: AssemblyContext, V <: Tuple, G <: Tuple, JT, T <: u_elem::Vector{T} end -function NonlinearOperator(ctx::AssemblyContext, kernels; ch = nothing) +function NonlinearOperator(ctx::AssemblyContext, kernels; ch = nothing, pattern = allocate_pattern(ctx, ch)) ne = _max_ndofs(ctx.dh) volume, groups = _split(ctx, kernels, (:nonlinear,)) r = zeros(Ferrite.ndofs(ctx.dh)) - return NonlinearOperator(ctx, volume, groups, r, allocate_pattern(ctx, ch), zeros(ne, ne), zeros(ne), zeros(ne)) + return NonlinearOperator(ctx, volume, groups, r, copy(pattern), zeros(ne, ne), zeros(ne), zeros(ne)) end function _nonlinear!(r, aJ, op::NonlinearOperator, u, p, t) diff --git a/src/periodic.jl b/src/periodic.jl new file mode 100644 index 00000000..d56884f6 --- /dev/null +++ b/src/periodic.jl @@ -0,0 +1,238 @@ +# Periodic identification of boundary pieces. The dofs of one field on two pieces that are translates of each other +# are matched by coordinate; every connected class of matched dofs (a corner of a fully periodic box joins four +# of them) keeps one master and ties the others to it, `u_mirror = u_master`. The assembled operators keep all dofs +# as unknowns: `apply_ties!` adds each tied row to its master's row and replaces the tied row by `u_mirror - u_master`. + +# Coordinates of the dofs of `field` on the facet set `set`. +function _piece_dofs(dh, field, grid, set) + ch = Ferrite.ConstraintHandler(dh) + Ferrite.add!(ch, Ferrite.Dirichlet(field, Ferrite.getfacetset(grid, String(set)), (x, t) -> 0.0)) + Ferrite.close!(ch) + return sort(ch.prescribed_dofs) +end + +# Coordinates are matched on a grid of cell `tol`, looking in the neighbouring cells too. +function _match_translate(coords, from, to, shift, tol) + index = Dict{Any, Vector{Int}}() + for d in to + push!(get!(index, Tuple(round.(Int, coords[d] / tol)), Int[]), d) + end + dim = length(first(coords)) + matched = Pair{Int, Int}[] + unmatched = Int[] + for d in from + target = coords[d] + shift + key = round.(Int, target / tol) + best, bestdist = 0, Inf + for offset in Iterators.product(ntuple(_ -> -1:1, dim)...), e in get(index, Tuple(key .+ offset), Int[]) + dist = norm(coords[e] - target) + dist < bestdist && ((best, bestdist) = (e, dist)) + end + bestdist <= tol ? push!(matched, d => best) : push!(unmatched, d) + end + return matched, unmatched +end + +# Why the matching of `da` onto `db` is not a one-to-one correspondence, or `nothing`: every node of Γ_a needs a node of +# Γ_b within `tol`, no node of Γ_b may be the target of two, and the nearest node of Γ_a to each node of Γ_b must be its +# own preimage. +function _matching_problem(coords, da, db, matched, unmatched, shift, tol, a, b) + isempty(unmatched) || return "the node at $(_tuple_str(coords[first(unmatched)])) on Γ_$a has no node of Γ_$b at " * + "$(_tuple_str(coords[first(unmatched)] + shift)) ($(length(unmatched)) such nodes of Γ_$a, $(length(da)) on Γ_$a and $(length(db)) on Γ_$b)" + owner = Dict{Int, Int}() + for (x, y) in matched + haskey(owner, y) && return "the nodes at $(_tuple_str(coords[owner[y]])) and $(_tuple_str(coords[x])) on Γ_$a both match the node at " * + "$(_tuple_str(coords[y])) on Γ_$b, at distances $(round(norm(coords[owner[y]] + shift - coords[y]); sigdigits = 3)) and " * + "$(round(norm(coords[x] + shift - coords[y]); sigdigits = 3))" + owner[y] = x + end + missed = [y for y in db if !haskey(owner, y)] + isempty(missed) || return "the node at $(_tuple_str(coords[first(missed)])) on Γ_$b has no node of Γ_$a ($(length(da)) on Γ_$a and $(length(db)) on Γ_$b)" + back, _ = _match_translate(coords, db, da, -shift, tol) + for (y, x) in back + owner[y] == x && continue + return "the node at $(_tuple_str(coords[y])) on Γ_$b is nearest to the node at $(_tuple_str(coords[x])) on Γ_$a, not to its match at " * + "$(_tuple_str(coords[owner[y]]))" + end + return nothing +end + +function _tuple_str(x) + return "(" * join(round.(x; sigdigits = 6), ", ") * ")" +end + +# periodic_ties(grid, dh, coords, periodic, prescribed) -> Vector{Pair{Int, Int}} +# +# `(ties, classes)`: `mirror => master` dof pairs (and the prescribed dofs of each class, for `check_agreement`) that make the dofs matched by `periodic`, a collection of +# `(field, set_a, set_b)`, equal. The pieces of a pair must be translates of each other: the translation is the +# difference of their centroids and each node of one must have a node of the other at the translated place, or +# an `ArgumentError` names both pieces. A master is a `prescribed` (Dirichlet) dof of its class if it has one, else +# its lowest dof; prescribed dofs are never mirrors. +function periodic_ties(grid, dh, nodes, periodic, prescribed; dirichlet = Dict{Int, Any}(), times = (0.0,)) + coords = [collect(Float64, Tuple(x)) for x in nodes] + lo = reduce((a, b) -> min.(a, b), coords) + hi = reduce((a, b) -> max.(a, b), coords) + tol = 1.0e-6 * max(norm(hi - lo), eps()) + parent = collect(1:Ferrite.ndofs(dh)) + root(d) = parent[d] == d ? d : (parent[d] = root(parent[d])) + for (field, a, b) in periodic + da, db = _piece_dofs(dh, field, grid, a), _piece_dofs(dh, field, grid, b) + mean_coord(ds) = sum(coords[d] for d in ds) / length(ds) + shift = mean_coord(db) - mean_coord(da) + names = "Γ_$a and Γ_$b of $field" + norm(shift) <= tol && throw(ArgumentError("periodic pieces $names coincide: their centroids are the same point, so there is no translation between them")) + matched, unmatched = _match_translate(coords, da, db, shift, tol) + problem = _matching_problem(coords, da, db, matched, unmatched, shift, tol, a, b) + problem === nothing || throw( + ArgumentError( + "periodic pieces $names do not match under a translation: $problem; the translation between their centroids is " * + "$(_tuple_str(shift)) and the tolerance is $(round(tol; sigdigits = 3)). Periodic pieces must be translates of each other, " * + "with a one-to-one correspondence of their nodes" + ) + ) + for (x, y) in matched + parent[root(x)] = root(y) + end + end + classes = Dict{Int, Vector{Int}}() + for d in eachindex(parent) + push!(get!(classes, root(d), Int[]), d) + end + isprescribed = falses(length(parent)) + isprescribed[prescribed] .= true + ties = Pair{Int, Int}[] + groups = Vector{Int}[] + for members in values(classes) + length(members) > 1 || continue + master = members[something(findfirst(d -> isprescribed[d], members), 1)] + fixed = filter(d -> isprescribed[d], members) + length(fixed) > 1 && push!(groups, fixed) + for d in members + d == master || isprescribed[d] || push!(ties, d => master) + end + end + classes = DirichletClasses( + groups, Dict(d => collect(Float64, Tuple(nodes[d])) for g in groups for d in g), + Dict(d => String(first(dirichlet[d])) for g in groups for d in g), collect(Any, periodic) + ) + for t in times + check_agreement(classes, d -> (g = last(dirichlet[d]); hasmethod(g, Tuple{typeof(nodes[d]), Float64}) ? g(nodes[d], t) : g(nodes[d])), t) + end + return sort!(ties), classes +end + +# The prescribed dofs of each periodic class that holds more than one, with what an error needs to name them. +struct DirichletClasses + groups::Vector{Vector{Int}} + nodes::Dict{Int, Vector{Float64}} + pieces::Dict{Int, String} + periodic::Vector{Any} +end + +# check_agreement(classes::DirichletClasses, value, t) +# +# Throw an `ArgumentError` when `value(d)`, the prescribed value of dof `d` at time `t`, differs between two prescribed dofs +# of one periodic class by more than `1e-8` relative to the data. Called at every evaluation of the Dirichlet data. +function check_agreement(classes::DirichletClasses, value, t) + for group in classes.groups + a = ForwardDiff.value(value(first(group))) + for d in view(group, 2:length(group)) + b = ForwardDiff.value(value(d)) + abs(a - b) <= 1.0e-8 * max(1.0, abs(a), abs(b)) && continue + pairs = join(("Γ_$pa ~ Γ_$pb" for (_, pa, pb) in classes.periodic), ", ") + throw( + ArgumentError( + "the Dirichlet data of periodic pieces ($pairs) disagree: the nodes at $(_tuple_str(classes.nodes[first(group)])) " * + "and $(_tuple_str(classes.nodes[d])) are the same node of the periodic map, but Γ_$(classes.pieces[first(group)]) " * + "prescribes $a and Γ_$(classes.pieces[d]) prescribes $b at t = $(ForwardDiff.value(t))" + ) + ) + end + end + return nothing +end + +# The tied rows whose residual is summed into the master's row: those whose master is not prescribed. +_summed(ties, isprescribed) = [m => s for (m, s) in ties if !isprescribed[s]] + +# extend_pattern(pattern, ties, prescribed) -> SparseMatrixCSC +# +# `pattern` with the entries `apply_ties!` writes: the master row of every summed tie gains the columns of the tied +# row, and each tied row gains its diagonal and its master's column. +function extend_pattern(pattern::SparseMatrixCSC, ties, prescribed) + isempty(ties) && return pattern + isprescribed = isprescribed_mask(size(pattern, 1), prescribed) + rows = rowvals(pattern) + I, J = findnz(pattern) + by_row = Dict{Int, Vector{Int}}() + for j in axes(pattern, 2), k in nzrange(pattern, j) + push!(get!(by_row, rows[k], Int[]), j) + end + for (m, s) in ties + append!(I, (m, m)); append!(J, (m, s)) + for (mm, ss) in _summed((m => s,), isprescribed), j in by_row[mm] + push!(I, ss); push!(J, j) + end + end + return sparse(I, J, zeros(length(I)), size(pattern)...) +end + +# Position in `A`'s stored values of entry `(i, j)`, which the pattern must hold. +function _position(A, i, j) + r = nzrange(A, j) + k = searchsortedfirst(view(rowvals(A), r), i) + k <= length(r) && rowvals(A)[r[k]] == i || throw(ArgumentError("the sparsity pattern has no entry ($i, $j) for a periodic tie")) + return r[k] +end + +# apply_ties!(M, K, ties, prescribed) +# +# For each `mirror => master` of `ties`, add the mirror's row of `M` and `K` to the master's row (unless the master +# is prescribed) and replace the mirror's rows: `M` row zero, `K` row `e_mirror - e_master`. `M` and `K` must have the +# pattern of `extend_pattern`. +function apply_ties!(M, K, ties, prescribed) + isempty(ties) && return M, K + n = size(K, 1) + isprescribed = isprescribed_mask(n, prescribed) + master = zeros(Int, n) + foreach(((m, s),) -> master[m] = s, ties) + rows = rowvals(K) + for A in (M, K), j in axes(A, 2), k in nzrange(A, j) + s = master[rows[k]] + s == 0 || isprescribed[s] || (nonzeros(A)[_position(A, s, j)] += nonzeros(A)[k]) + end + for j in axes(K, 2), k in nzrange(K, j) + i = rows[k] + master[i] == 0 && continue + nonzeros(M)[k] = 0 + nonzeros(K)[k] = i == j ? 1 : j == master[i] ? -1 : 0 + end + return M, K +end + +# Rows of the load vector summed and cleared like the rows of `apply_ties!`. +apply_ties!(F::AbstractVector, ties, prescribed::AbstractVector{<:Integer}) = apply_ties!(F, ties, isprescribed_mask(length(F), prescribed)) +function apply_ties!(F::AbstractVector, ties, isprescribed::BitVector) + for (m, s) in ties + isprescribed[s] || (F[s] += F[m]) + F[m] = 0 + end + return F +end + +# What `FEMNonlinear` needs to add a mirror row of the nonlinear residual and Jacobian to its master's row. +function _tie_positions(J, ties, prescribed) + isempty(ties) && return nothing + summed = _summed(ties, isprescribed_mask(size(J, 1), prescribed)) + master = zeros(Int, size(J, 1)) + foreach(((m, s),) -> master[m] = s, summed) + from, to = Int[], Int[] + rows = rowvals(J) + for j in axes(J, 2), k in nzrange(J, j) + s = master[rows[k]] + s == 0 && continue + push!(from, k) + push!(to, _position(J, s, j)) + end + return (summed, from, to) +end diff --git a/src/space.jl b/src/space.jl index 1583f6fb..cef75186 100644 --- a/src/space.jl +++ b/src/space.jl @@ -1,10 +1,12 @@ """ - FEMSpace(grid, fields; dirichlet = (), quadrature = nothing, t0 = 0.0, regions = Dict(), hessians = false) + FEMSpace(grid, fields; dirichlet = (), periodic = (), quadrature = nothing, t0 = 0.0, regions = Dict(), hessians = false) The Ferrite discrete space of a mesh discretization (spec §6.2-6.4). `fields` is an ordered collection of `name => interpolation` pairs; after `renumber!(dh, DofOrder.FieldWise())` field `k` occupies a contiguous block of the global dof vector, in declaration order. `dirichlet` is a collection of -`(field, facetset_name, g)` with `g(x, t)`. `quadrature` is the quadrature order shared by every field, +`(field, facetset_name, g)` with `g(x, t)`. `periodic` is a collection of `(field, facetset_a, facetset_b)` +that identify the dofs of `field` on two facet sets that are translates of each other (see `periodic_ties`). +`tend` is the end time, with `t0` the range over which the Dirichlet data of a periodic class are checked for agreement. `quadrature` is the quadrature order shared by every field, `2p` for the highest Lagrange order `p` by default (spec §5.6). The constraint handler is first updated at `t0`, the initial time, since Dirichlet data need not be defined before it. @@ -15,8 +17,9 @@ kernels need. Fields: `grid`, `dh` (the `DofHandler`), `ch` (the closed `ConstraintHandler`), `fields` (names in declaration order), `cellvalues` and `facetvalues` (`NamedTuple`s keyed by field), `ranges` (global dof -range per field), `pieces` (piece name `=>` facet set name, for every facet set of the grid) and `pattern` -(`allocate_matrix(dh, ch)`, to be copied for every operator). +range per field), `pieces` (piece name `=>` facet set name, for every facet set of the grid), `pattern` +(`allocate_matrix(dh, ch)` plus the entries of the periodic ties, to be copied for every operator) and `ties` +(`mirror => master` dofs of the periodic conditions) and `classes` (the prescribed dofs of each periodic class). """ struct FEMSpace{G, DH, CH, CV <: NamedTuple, FV <: NamedTuple, R <: NamedTuple, A} <: PDEBase.AbstractDiscreteSpace @@ -30,13 +33,15 @@ struct FEMSpace{G, DH, CH, CV <: NamedTuple, FV <: NamedTuple, R <: NamedTuple, pieces::Dict{Symbol, String} pattern::A gbuf::Vector{Float64} + ties::Vector{Pair{Int, Int}} + classes::DirichletClasses end _order(::Ferrite.Interpolation{shape, order}) where {shape, order} = order function FEMSpace( - grid::Ferrite.Grid, fields; dirichlet = (), quadrature::Union{Nothing, Int} = nothing, t0::Real = 0.0, - regions = Dict(), hessians::Bool = false + grid::Ferrite.Grid, fields; dirichlet = (), periodic = (), quadrature::Union{Nothing, Int} = nothing, + t0::Real = 0.0, tend::Real = t0, regions = Dict(), hessians::Bool = false ) names = Symbol[first(f) for f in fields] ips = Tuple(last(f) for f in fields) @@ -46,6 +51,11 @@ function FEMSpace( throw(ArgumentError("Dirichlet condition on unknown field $(repr(Symbol(field))); fields are $(names)")) end check_facetsets(grid, [Symbol(set) for (_, set, _) in dirichlet]) + for (field, a, b) in periodic + Symbol(field) in names || + throw(ArgumentError("periodic condition on unknown field $(repr(Symbol(field))); fields are $(names)")) + check_facetsets(grid, [Symbol(a), Symbol(b)]) + end dh = _dofhandler(grid, names, ips, regions) # With regions, Ferrite lists the fields in sub-handler order, not declaration order; block k is field k. @@ -75,10 +85,18 @@ function FEMSpace( facetvalues = NamedTuple{key}(map(ip -> Ferrite.FacetValues(fqr, ip, ip_geo), ips)) ranges = NamedTuple{key}(_global_ranges(dh, names)) pieces = Dict(Symbol(name) => name for name in keys(grid.facetsets)) - return FEMSpace( - grid, dh, ch, names, cellvalues, facetvalues, ranges, pieces, - Ferrite.allocate_matrix(dh, ch), zeros(Ferrite.ndofs(dh)) - ) + owner = Dict{Int, Any}() + for (field, set, g) in dirichlet, d in _piece_dofs(dh, Symbol(field), grid, set) + owner[d] = (set, g) + end + times = range(t0, tend; length = 17) + ties, classes = isempty(periodic) ? (Pair{Int, Int}[], DirichletClasses(Vector{Int}[], Dict{Int, Vector{Float64}}(), Dict{Int, String}(), Any[])) : + periodic_ties( + grid, dh, _dof_coordinates(grid, dh, names), [(Symbol(f), a, b) for (f, a, b) in periodic], ch.prescribed_dofs; + dirichlet = owner, times + ) + pattern = extend_pattern(Ferrite.allocate_matrix(dh, ch), ties, ch.prescribed_dofs) + return FEMSpace(grid, dh, ch, names, cellvalues, facetvalues, ranges, pieces, pattern, zeros(Ferrite.ndofs(dh)), ties, classes) end # One DofHandler for all fields, or, with regions, one SubDofHandler per distinct set of fields present on a cell; diff --git a/test/DAE/numeric_dae.jl b/test/DAE/numeric_dae.jl index b6acd3d6..2992072d 100644 --- a/test/DAE/numeric_dae.jl +++ b/test/DAE/numeric_dae.jl @@ -296,3 +296,19 @@ heat_operators(fe; kw...) = FEMOperators(fe.M, fe.K, fe.F, [:u => 1:length(fe.F) @test occursin("not finite", e.msg) end end + +@testset "periodic ties act on the load buffer, not on the callback's return value" begin + # A dense 3 x 3 pattern holds the entries of the tie 2 => 1; the in-place load returns nothing, as `load!` allows. + dense(A) = (S = sparse(ones(3, 3)); S.nzval .= vec(A); S) + M = dense(Matrix(1.0I, 3, 3)) + K = dense([2.0 -1 0; -1 2 -1; 0 -1 2]) + load = (out, t) -> (fill!(out, 1.0); nothing) + ops = FEMOperators(M, K, load, [:u => 1:3]; ties = [2 => 1]) + @test FiniteElementMethod.load!(zeros(3), ops.load, 0.0) == [2.0, 0.0, 1.0] + prob = numeric_dae_problem(ops, [0.5, 0.5, 0.0], (0.0, 0.5)) + sol = solve(prob, DImplicitEuler(); dt = 0.1, adaptive = false) + @test SciMLBase.successful_retcode(sol) + @test sol.u[end][1] == sol.u[end][2] + # The steady residual evaluates the same load. + @test FiniteElementMethod.load!(zeros(3), ops.load, 1.0) == [2.0, 0.0, 1.0] +end diff --git a/test/Integration/linear.jl b/test/Integration/linear.jl index 81fc2d0a..8db34a83 100644 --- a/test/Integration/linear.jl +++ b/test/Integration/linear.jl @@ -235,9 +235,9 @@ end end @testset "periodic conditions are carried through weak_form untouched" begin - # Checks only that weak_form passes periodic data through with its terms unchanged. Periodic conditions are not - # supported by the discretizer ("periodic boundary conditions are not supported"), which rejects them - # after weak_form, so this is not coverage of the periodic BC kind. + # Checks only that weak_form passes periodic data through with its terms unchanged. FEMDiscretization takes its + # periodic pairs from the piece equations `u(t, Γa) ~ u(t, Γb)` and never reads `analysis.periodic`, so this is not + # coverage of the periodic BC kind; test/Interface/periodic.jl is. eq = Dt(U) ~ Dx(k * Dx(U)) + Dy(k * Dy(U)) + x * y + 1 bcs = [BC("top", k * Dy(U) + α * U ~ β, TOP)] periodic = [PeriodicBC("left", "right", 1, [2.0, 0.0])] diff --git a/test/Interface/README.md b/test/Interface/README.md index 8e2a1bc4..c1d35285 100644 --- a/test/Interface/README.md +++ b/test/Interface/README.md @@ -105,10 +105,12 @@ boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D a | `navier_stokes.jl` | Kovasznay flow, Taylor-Hood, rates 3 and 2 | steady incompressible Navier-Stokes | 2 | P2/P1 | Dirichlet velocity, Dirichlet pressure on one side | | `metadata_and_operators.jl` | `facet_dofs`, `dof_coordinates`, `cell_dofs` | heat | 2 | P1, P2 | zero Dirichlet | | `metadata_and_operators.jl` | `operators` gives the matrices for a hand-made steady solve | heat at its steady state | 2 | P2 | Dirichlet | +| `periodic.jl` | periodic pairs: heat on a fully periodic box (rates 2, 3), periodic in x only, steady advection-diffusion with Galerkin and SUPG, coupled fields, rejected pairs | heat, advection-diffusion | 2 | P1, P2 | periodic, Dirichlet | +| `periodic_navier_stokes.jl` | Kovasznay flow with periodic bottom and top (rates 3, 2); flow past a block in a channel periodic in y, mass conserved | steady and transient incompressible Navier-Stokes | 2 | P2/P1, Q2/Q1 | periodic, Dirichlet velocity, outlet pressure | | `rejections.jl` | rejected boundary conditions, equations, options, domains, shared facets, SUPG with a nonlinear term, observed expressions, `operators`, `ferrite_grid` | heat and others | 1 to 3 | | | ## Not covered -The DFG cylinder (Navier-Stokes, about 149 000 unknowns) is the `NavierStokes` group. Periodic conditions, `codegen = :mtk`, +The DFG cylinder (Navier-Stokes, about 149 000 unknowns) is the `NavierStokes` group. `codegen = :mtk`, time-dependent coefficients in the mass or stiffness operator, third-order and second-order-in-time equations are rejected, and `rejections.jl` asserts the messages. diff --git a/test/Interface/periodic.jl b/test/Interface/periodic.jl new file mode 100644 index 00000000..b1eead7a --- /dev/null +++ b/test/Interface/periodic.jl @@ -0,0 +1,371 @@ +# Periodic boundary conditions through the full interface: an equation between the traces of one field on two +# boundary pieces, `u(t, Γa) ~ u(t, Γb)` (or `u(Γa) ~ u(Γb)` without time), identifies the field on the two pieces when +# they are translates of each other. Each case builds the PDESystem as a user would, solves it and compares with an +# exact solution; the last cases are the inputs that are refused. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, NonlinearSolveFirstOrder, Test +using Ferrite: Ferrite, Grid, Node, generate_grid, Line, Triangle, Quadrilateral, Hexahedron, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) v(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + +unit_square(celltype, n) = MeshDomain(generate_grid(celltype, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) +sides(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + +# Solves `eq` on Ω with the conditions `bcs` to `tend`; the keywords go to `FEMDiscretization`. +function solve_heat(eq, Ω, bcs, tend; kw...) + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x, y], [u(t, x, y)], []) + return solve(discretize(pdesys, FEMDiscretization(Ω, t; kw...)), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 0.05), meshes of 8, 16 and 32 cells per side +# BCs: u(t, left) ~ u(t, right) and u(t, bottom) ~ u(t, top): periodic in both directions; IC sin(2 pi (x + y)) +# Exact: u = exp(-8 pi^2 t) sin(2 pi (x + y)), which does not vanish on the boundary +# Shows: a fully periodic box, whose corners belong to several pairs, converges at rate 2 (P1) and 3 (P2), on both cell +# shapes, and the two sides of the seam carry the same values. +@testset "heat equation on a fully periodic box follows its Fourier mode at the optimal rate for $name" for (name, celltype, ref, order) in ( + ("P1 triangles", Triangle, RefTriangle, 1), ("P2 quadrilaterals", Quadrilateral, RefQuadrilateral, 2), + ) + exact(x_, y_) = exp(-8pi^2 * 0.05) * sin(2pi * (x_ + y_)) + ns = (8, 16, 32) + errors = map(ns) do n + Ω = unit_square(celltype, n) + left, right, bottom, top = sides(Ω) + bcs = [u(t, left) ~ u(t, right), u(t, bottom) ~ u(t, top), u(0, x, y) ~ sin(2pi * (x + y))] + sol = solve_heat(heat, Ω, bcs, 0.05; spaces = Dict(u => Lagrange{ref, order}())) + edge = collect(range(0.0, 1.0; length = 7)) + @test sol(0.05, [0.0], edge; dv = u(t, x, y)) ≈ sol(0.05, [1.0], edge; dv = u(t, x, y)) atol = 1.0e-12 + @test sol(0.05, edge, [0.0]; dv = u(t, x, y)) ≈ sol(0.05, edge, [1.0]; dv = u(t, x, y)) atol = 1.0e-12 + l2_error(sol, u(t, x, y), exact, 0.05, sample_points(40), sample_points(40)) + end + @test all(observed_rate(errors, 1 ./ ns) .> order + 0.8) +end + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 0.05), meshes of 8, 16 and 32 triangle pairs per side +# BCs: periodic left and right; u = 0 on bottom and top (Dirichlet); IC sin(2 pi x) sin(pi y) +# Exact: u = exp(-5 pi^2 t) sin(2 pi x) sin(pi y) +# Shows: a pair of periodic pieces whose corners meet Dirichlet pieces: the Dirichlet value holds at the shared +# corners and P1 elements converge at rate 2. +@testset "heat equation periodic in x and Dirichlet in y follows its Fourier mode at rate 2" begin + exact(x_, y_) = exp(-5pi^2 * 0.05) * sin(2pi * x_) * sin(pi * y_) + ns = (8, 16, 32) + errors = map(ns) do n + Ω = unit_square(Triangle, n) + left, right, bottom, top = sides(Ω) + bcs = [u(t, left) ~ u(t, right), u(t, bottom) ~ 0, u(t, top) ~ 0, u(0, x, y) ~ sin(2pi * x) * sin(pi * y)] + sol = solve_heat(heat, Ω, bcs, 0.05) + @test sol(0.05, [0.0, 1.0], [0.0, 1.0]; dv = u(t, x, y)) ≈ zeros(2, 2) atol = 1.0e-12 + l2_error(sol, u(t, x, y), exact, 0.05, sample_points(40), sample_points(40)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 1.8) +end + +# PDE: -ν (u_xx + u_yy) + b.grad u + c u = f with ν = 0.1, b = (1, 0.5), c = 1 (steady advection-diffusion-reaction) +# Domain: the unit square, meshes of 8, 16 and 32 cells per side, P1 triangles +# BCs: u(left) ~ u(right) and u(bottom) ~ u(top), with no time variable +# Exact: u = sin(2 pi x) cos(2 pi y) + 0.5, so f follows by differentiation +# Shows: the steady path imposes periodic conditions too and converges at rate 2; SUPG with a small τ stays within +# a factor 1.5 of the Galerkin error and converges at a rate above 1.5. +@testset "steady advection-diffusion on a periodic box converges at rate 2, with Galerkin and with SUPG" begin + ν, bx, by, c = 0.1, 1.0, 0.5, 1.0 + ex = sin(2pi * x) * cos(2pi * y) + 0.5 + exact(x_, y_) = sin(2pi * x_) * cos(2pi * y_) + 0.5 + D(f, v) = ModelingToolkit.expand_derivatives(Differential(v)(f)) + source = -ν * (D(D(ex, x), x) + D(D(ex, y), y)) + bx * D(ex, x) + by * D(ex, y) + c * ex + U = u(x, y) + eq = -ν * (Dx(Dx(U)) + Dy(Dy(U))) + bx * Dx(U) + by * Dy(U) + c * U ~ source + function solve_periodic(n, test_space) + Ω = unit_square(Triangle, n) + left, right, bottom, top = sides(Ω) + @named pdesys = PDESystem([eq], [u(left) ~ u(right), u(bottom) ~ u(top)], [(x, y) ∈ Ω], [x, y], [U], []) + return solve(discretize(pdesys, FEMDiscretization(Ω; test_space)), NewtonRaphson(); abstol = 1.0e-12) + end + ns = (8, 16, 32) + errors = map(n -> l2_error(solve_periodic(n, Galerkin()), U, exact, sample_points(40), sample_points(40)), ns) + @test all(observed_rate(errors, 1 ./ ns) .> 1.8) + supg = SUPG((hK, b) -> hK / (20 * hypot(b...))) + errors_supg = map(n -> l2_error(solve_periodic(n, supg), U, exact, sample_points(40), sample_points(40)), ns) + @test all(observed_rate(errors_supg, 1 ./ ns) .> 1.5) + @test all(errors_supg .< 1.5 .* errors) +end + +# PDE: u_t = u_xx + u_yy and v_t = v_xx + v_yy + 3 u, two coupled fields with P2 and P1 spaces +# Domain: the unit square, t in (0, 0.05), 16 x 16 triangle pairs +# BCs: u periodic in x and y; v periodic in x only and zero on bottom and top +# Exact: u = exp(-4 pi^2 t) sin(2 pi x), v = exp(-5 pi^2 t) sin(2 pi x) sin(pi y) + the particular solution of the coupling +# Shows: the periodic pairs are per field: one field may be periodic where another has Dirichlet pieces. +@testset "periodic conditions apply per field in a coupled system with different spaces" begin + Ω = unit_square(Triangle, 16) + left, right, bottom, top = sides(Ω) + eqs = [heat, Dt(v(t, x, y)) ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))) + 3u(t, x, y)] + bcs = [ + u(t, left) ~ u(t, right), u(t, bottom) ~ u(t, top), v(t, left) ~ v(t, right), v(t, bottom) ~ 0, v(t, top) ~ 0, + u(0, x, y) ~ sin(2pi * x), v(0, x, y) ~ 0, + ] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.05)], [t, x, y], [u(t, x, y), v(t, x, y)], []) + spaces = Dict(u => Lagrange{RefTriangle, 2}(), v => Lagrange{RefTriangle, 1}()) + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; spaces)), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + @test l2_error(sol, u(t, x, y), (x_, y_) -> exp(-4pi^2 * 0.05) * sin(2pi * x_), 0.05, sample_points(40), sample_points(40)) < 1.0e-4 + edge = collect(range(0.0, 1.0; length = 7)) + @test sol(0.05, [0.0], edge; dv = v(t, x, y)) ≈ sol(0.05, [1.0], edge; dv = v(t, x, y)) atol = 1.0e-12 + @test sol(0.05, edge, [0.0, 1.0]; dv = v(t, x, y)) ≈ zeros(7, 2) atol = 1.0e-12 +end + +# PDE: the 2D heat equation on the unit square +# BCs: malformed periodic pairs, pieces that are not translates of each other, and a periodic piece with another +# condition on the same field +# Shows: each mistake is refused when the problem is built, and the message names the pieces involved. +@testset "periodic conditions that cannot be imposed are rejected with the pieces named" begin + ic = u(0, x, y) ~ 0 + Ω = unit_square(Triangle, 4) + left, right, bottom, top = sides(Ω) + lower(bcs; mesh = Ω, kw...) = begin + @named pdesys = PDESystem([heat], bcs, [(x, y) ∈ mesh, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + discretize(pdesys, FEMDiscretization(mesh, t; kw...)) + end + dirichlet = [u(t, bottom) ~ 0, u(t, top) ~ 0] + @test lower([u(t, left) ~ u(t, right); dirichlet; ic]) isa SciMLBase.DAEProblem + @test_throws "periodic pieces Γ_left and Γ_bottom of u do not match under a translation" lower([u(t, left) ~ u(t, bottom), u(t, right) ~ 0, u(t, top) ~ 0, ic]) + # A mesh stretched by 1 + x / 2 in y: the sides have the same number of nodes, but the right one is longer. + grid = generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0)) + stretched = Grid(grid.cells, [Node(Vec(n.x[1], n.x[2] * (1 + n.x[1] / 2))) for n in grid.nodes]; facetsets = grid.facetsets) + Ωs = MeshDomain(stretched) + left_s, right_s, bottom_s, top_s = sides(Ωs) + @test_throws "periodic pieces Γ_left and Γ_right of u do not match under a translation" lower( + [u(t, left_s) ~ u(t, right_s), u(t, bottom_s) ~ 0, u(t, top_s) ~ 0, ic]; mesh = Ωs + ) + @test_throws "has a periodic condition on Γ_left and a Dirichlet condition on the same piece" lower([u(t, left) ~ u(t, right), u(t, left) ~ 0, dirichlet..., ic]) + @test_throws "has a periodic condition on Γ_right and a Neumann or Robin condition on the same piece" lower( + [u(t, left) ~ u(t, right), NormalDerivative(right)(u(t, right)) ~ 0, dirichlet..., ic] + ) + @test_throws "must be a periodic pair of the form u(t, Γa) ~ u(t, Γb)" lower([u(t, left) ~ u(t, right) + 1, dirichlet..., ic]) + @test_throws "dirichlet = :eliminate does not support periodic conditions" lower([u(t, left) ~ u(t, right); dirichlet; ic]; dirichlet = :eliminate) +end + +# BCs: a periodic pair for a field whose space is not a scalar Lagrange space (an edge element) +# Shows: the unsupported combination is refused with an error naming the space, rather than giving a wrong answer. +@testset "periodic conditions on a non-Lagrange space are rejected" begin + Ω = unit_square(Triangle, 4) + left, right, bottom, top = sides(Ω) + bcs = [u(t, left) ~ u(t, right), u(t, bottom) ~ 0, u(t, top) ~ 0, u(0, x, y) ~ 0] + @named pdesys = PDESystem([heat], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Ferrite.Nedelec{RefTriangle, 1}())) + @test_throws "is not a nodal Lagrange space" discretize(pdesys, disc) +end + +# PDE: ((1 + u^2) u_x)_x + ((1 + u^2) u_y)_y - u = f, a steady nonlinear diffusion solved by Newton's method +# Domain: the unit square, meshes of 8, 16 and 32 cells per side, P1 triangles +# BCs: periodic left and right, periodic bottom and top, no time variable +# Exact: u = 0.5 sin(2 pi x) cos(2 pi y) + 1, so f follows by differentiation +# Shows: the Newton residual and Jacobian carry the periodic ties: the nonlinear steady problem converges at rate 2. +@testset "steady nonlinear diffusion on a periodic box converges at rate 2" begin + ex = 0.5 * sin(2pi * x) * cos(2pi * y) + 1 + exact(x_, y_) = 0.5 * sin(2pi * x_) * cos(2pi * y_) + 1 + D(f, v) = ModelingToolkit.expand_derivatives(Differential(v)(f)) + source = D((1 + ex^2) * D(ex, x), x) + D((1 + ex^2) * D(ex, y), y) - ex + U = u(x, y) + eq = Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) - U ~ source + ns = (8, 16, 32) + errors = map(ns) do n + Ω = unit_square(Triangle, n) + left, right, bottom, top = sides(Ω) + @named pdesys = PDESystem([eq], [u(left) ~ u(right), u(bottom) ~ u(top)], [(x, y) ∈ Ω], [x, y], [U], []) + sol = solve(discretize(pdesys, FEMDiscretization(Ω)), NewtonRaphson(); abstol = 1.0e-11) + @test SciMLBase.successful_retcode(sol) + l2_error(sol, U, exact, sample_points(40), sample_points(40)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 1.8) +end + +# PDE: u_t + u u_x + u u_y = ν (u_xx + u_yy) + f with ν = 0.1 (viscous Burgers), a transient nonlinear problem +# Domain: the unit square, t in (0, 0.1), meshes of 8, 16 and 32 cells per side, P1 triangles +# BCs: periodic in both directions; IC sin(2 pi (x + y)) +# Exact: u = exp(-t) sin(2 pi (x + y)), so f follows by differentiation +# Shows: the nonlinear DAE path carries the periodic ties and converges at rate 2. +@testset "viscous Burgers on a periodic box converges at rate 2 in the transient path" begin + ν = 0.1 + ex = exp(-t) * sin(2pi * (x + y)) + exact(x_, y_) = exp(-0.1) * sin(2pi * (x_ + y_)) + D(f, v) = ModelingToolkit.expand_derivatives(Differential(v)(f)) + source = D(ex, t) + ex * D(ex, x) + ex * D(ex, y) - ν * (D(D(ex, x), x) + D(D(ex, y), y)) + U = u(t, x, y) + eq = Dt(U) + U * Dx(U) + U * Dy(U) ~ ν * (Dx(Dx(U)) + Dy(Dy(U))) + source + ns = (8, 16, 32) + errors = map(ns) do n + Ω = unit_square(Triangle, n) + left, right, bottom, top = sides(Ω) + bcs = [u(t, left) ~ u(t, right), u(t, bottom) ~ u(t, top), u(0, x, y) ~ sin(2pi * (x + y))] + sol = solve_heat(eq, Ω, bcs, 0.1) + @test SciMLBase.successful_retcode(sol) + l2_error(sol, U, exact, 0.1, sample_points(40), sample_points(40)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 1.8) +end + +# PDE: u_t + c u_x = ε u_xx with c = 1, ε = 0.05, a travelling decaying wave on a ring +# Domain: x in (0, 1), t in (0, 0.2), meshes of 16, 32 and 64 line cells, P1; Galerkin and SUPG +# BCs: u(t, left) ~ u(t, right); IC sin(2 pi x) +# Exact: u = exp(-4 pi^2 ε t) sin(2 pi (x - c t)) +# Shows: periodic conditions on a line mesh, in the transient path, converge at rate 2 with Galerkin testing and at rate 1 +# with the first-order SUPG stabilisation. +@testset "advection-diffusion on a periodic line converges at rate $rate with $name testing" for (name, test_space, rate) in ( + ("Galerkin", Galerkin(), 2), ("SUPG", SUPG((hK, b) -> hK / (20 * abs(b[1]))), 1), + ) + c, ε = 1.0, 0.05 + eq = Dt(u(t, x)) + c * Dx(u(t, x)) ~ ε * Dx(Dx(u(t, x))) + exact(x_) = exp(-4pi^2 * ε * 0.2) * sin(2pi * (x_ - c * 0.2)) + ns = (16, 32, 64) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + bcs = [u(t, left) ~ u(t, right), u(0, x) ~ sin(2pi * x)] + @named pdesys = PDESystem([eq], bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, 0.2)], [t, x], [u(t, x)], []) + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; test_space)), DFBDF(); abstol = 1.0e-11, reltol = 1.0e-11) + @test sol(0.2, [0.0]; dv = u(t, x)) ≈ sol(0.2, [1.0]; dv = u(t, x)) atol = 1.0e-12 + l2_error(sol, u(t, x), exact, 0.2, sample_points(200)) + end + @test all(observed_rate(errors, 1 ./ ns) .> rate - 0.2) +end + +# PDE: -(u_xx + u_yy + u_zz) + u = f +# Domain: the unit cube, meshes of 4 and 8 hexahedra per side, P1 +# BCs: periodic in x, y and z (three pairs; the 8 corners form one class) +# Exact: u = sin(2 pi x) sin(2 pi y) cos(2 pi z) + 1 +# Shows: periodic conditions in 3D, with edges and corners shared by several pairs, converge at rate 2. +@testset "steady reaction-diffusion on a fully periodic cube converges at rate 2" begin + @variables z + Dz = Differential(z) + ex = sin(2pi * x) * sin(2pi * y) * cos(2pi * z) + 1 + exact(x_, y_, z_) = sin(2pi * x_) * sin(2pi * y_) * cos(2pi * z_) + 1 + D(f, v) = ModelingToolkit.expand_derivatives(Differential(v)(f)) + source = -(D(D(ex, x), x) + D(D(ex, y), y) + D(D(ex, z), z)) + ex + U = u(x, y, z) + eq = -(Dx(Dx(U)) + Dy(Dy(U)) + Dz(Dz(U))) + U ~ source + ns = (4, 8) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Hexahedron, (n, n, n), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0))) + left, right, front, back, bottom, top = boundarypiece.(Ω, (:left, :right, :front, :back, :bottom, :top)) + @named pdesys = PDESystem([eq], [u(left) ~ u(right), u(front) ~ u(back), u(bottom) ~ u(top)], [(x, y, z) ∈ Ω], [x, y, z], [U], []) + sol = solve(discretize(pdesys, FEMDiscretization(Ω)), NewtonRaphson(); abstol = 1.0e-11) + l2_error(sol, U, exact, sample_points(12), sample_points(12), sample_points(12)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 1.7) +end + +# PDE: the 2D heat equation on the unit square, t in (0, 0.2), 4 x 4 triangle pairs +# BCs: periodic left and right; Dirichlet data on bottom and top whose corners are shared through the periodic map +# Shows: Dirichlet data that agree at the two ends of a periodic class are imposed and the solution is periodic; data that +# differ (at any time of the interval) are an error naming the pieces, the nodes and the two values. +@testset "Dirichlet data on the corners of a periodic class must agree" begin + Ω = unit_square(Triangle, 4) + left, right, bottom, top = sides(Ω) + ic = u(0, x, y) ~ 1 + build(bcs; tend = 0.2) = begin + @named pdesys = PDESystem([heat], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x, y], [u(t, x, y)], []) + discretize(pdesys, FEMDiscretization(Ω, t)) + end + sol = solve(build([u(t, left) ~ u(t, right), u(t, bottom) ~ 1, u(t, top) ~ 1, ic]), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + edge = collect(range(0.0, 1.0; length = 5)) + @test sol(0.2, [0.0], edge; dv = u(t, x, y)) ≈ sol(0.2, [1.0], edge; dv = u(t, x, y)) atol = 1.0e-12 + @test sol(0.2, [0.0, 1.0], [0.0, 1.0]; dv = u(t, x, y)) ≈ ones(2, 2) atol = 1.0e-12 + # Time-dependent data that agree: the same function of t on both corners. + @test build([u(t, left) ~ u(t, right), u(t, bottom) ~ 1 + t, u(t, top) ~ 1 + t, ic]) isa SciMLBase.DAEProblem + @test_throws "the Dirichlet data of periodic pieces (Γ_left ~ Γ_right) disagree" build([u(t, left) ~ u(t, right), u(t, bottom) ~ x, u(t, top) ~ 0, ic]) + @test_throws "Γ_bottom prescribes 0.0 and Γ_bottom prescribes 1.0" build([u(t, left) ~ u(t, right), u(t, bottom) ~ x, u(t, top) ~ 0, ic]) + # Data that agree at all of the 17 sample times of the interval but differ in between are caught when the solver + # evaluates them: x sin(16 pi t) agrees on the two bottom corners at t = 0, 1/16, ... 1 and differs by 1 at t = 1/32. + sneaky = build([u(t, left) ~ u(t, right), u(t, bottom) ~ x * sin(16pi * t), u(t, top) ~ 0, ic]; tend = 1.0) + @test sneaky isa SciMLBase.DAEProblem + @test_throws "the Dirichlet data of periodic pieces (Γ_left ~ Γ_right) disagree" sneaky.f(zeros(length(sneaky.u0)), zeros(length(sneaky.u0)), sneaky.u0, sneaky.p, 1 / 32) + # Data that agree at t = 0 and differ later. + @test_throws "disagree" build([u(t, left) ~ u(t, right), u(t, bottom) ~ t * x, u(t, top) ~ 0, ic]) +end + +# PDE: the 2D heat equation, t in (0, 0.1) +# BCs: periodic left and right on meshes whose sides match one to one (a normal and a graded mesh) and on meshes whose sides +# have the same number of nodes without a one-to-one correspondence +# Shows: the nodes of the two pieces are matched one to one; two nodes closer than the tolerance to the same partner, or a +# node moved by more than the tolerance, are an error naming the pieces and the nodes. +@testset "periodic pieces need a one-to-one correspondence of their nodes" begin + function problem(grid) + Ω = MeshDomain(grid) + left, right, bottom, top = sides(Ω) + bcs = [u(t, left) ~ u(t, right), u(t, bottom) ~ 0, u(t, top) ~ 0, u(0, x, y) ~ 0] + @named pdesys = PDESystem([heat], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [u(t, x, y)], []) + return discretize(pdesys, FEMDiscretization(Ω, t)) + end + base = generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0)) + remesh(f) = Grid(base.cells, [Node(f(n.x)) for n in base.nodes]; facetsets = base.facetsets) + @test problem(base) isa SciMLBase.DAEProblem + @test problem(remesh(X -> Vec(X[1], X[2]^2))) isa SciMLBase.DAEProblem + moved = remesh(X -> X[1] > 0.99 && 0.4 < X[2] < 0.6 ? Vec(X[1], X[2] + 1.0e-3) : X) + @test_throws "periodic pieces Γ_left and Γ_right of u do not match under a translation" problem(moved) + # Two nodes on each side lie within the tolerance of one node of the other side. + nodes = [Node(Vec(0.0, 0.0)), Node(Vec(1.0, 0.0)), Node(Vec(1.0, 1.0e-7)), Node(Vec(0.0, 1.0e-9)), Node(Vec(1.0, 1.0)), Node(Vec(0.0, 1.0))] + close_grid = Grid( + [Quadrilateral((1, 2, 3, 4)), Quadrilateral((4, 3, 5, 6))], nodes; + facetsets = Dict( + "left" => Set([Ferrite.FacetIndex(1, 4), Ferrite.FacetIndex(2, 4)]), "right" => Set([Ferrite.FacetIndex(1, 2), Ferrite.FacetIndex(2, 2)]), + "bottom" => Set([Ferrite.FacetIndex(1, 1)]), "top" => Set([Ferrite.FacetIndex(2, 3)]), + ) + ) + @test_throws "both match the node" problem(close_grid) +end + +# BCs: periodic pairs whose traces do not both take exactly the time variable (transient) or no time (steady) +# Shows: a fixed, shifted or scaled time, mismatched times, a time on a steady system and two different fields are errors +# naming the condition; they are neither a periodic pair nor read as an initial or Dirichlet condition. +@testset "periodic pairs need the system's time variable on both traces" begin + Ω = unit_square(Triangle, 4) + left, right, bottom, top = sides(Ω) + walls = [u(t, bottom) ~ 0, u(t, top) ~ 0, u(0, x, y) ~ 0] + function build(bc) + @named pdesys = PDESystem([heat], [bc; walls], [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [u(t, x, y)], []) + return discretize(pdesys, FEMDiscretization(Ω, t)) + end + @test build(u(t, left) ~ u(t, right)) isa SciMLBase.DAEProblem + @test build(u(left, t) ~ u(right, t)) isa SciMLBase.DAEProblem + @test_throws "must be a periodic pair" build(u(t, left) - u(t, right) ~ 0) + for bc in (u(0, left) ~ u(t, right), u(t, left) ~ u(0, right), u(0, left) ~ u(0, right), u(t + 1, left) ~ u(t, right), u(2t, left) ~ u(2t, right)) + @test_throws "of the periodic condition" build(bc) + @test_throws "a fixed, shifted or scaled time is not supported" build(bc) + end + two = [heat, Dt(v(t, x, y)) ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y)))] + @named twofields = PDESystem( + two, [u(t, left) ~ v(t, right), u(t, bottom) ~ 0, u(t, top) ~ 0, v(t, bottom) ~ 0, v(t, top) ~ 0, u(0, x, y) ~ 0, v(0, x, y) ~ 0], + [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [u(t, x, y), v(t, x, y)], [] + ) + @test_throws "names two fields" discretize(twofields, FEMDiscretization(Ω, t)) + # Steady: no time argument; a time on a steady system is rejected with the same message. + Δ(f) = Dx(Dx(f)) + Dy(Dy(f)) + function steady(bc) + @named pdesys = PDESystem([Δ(u(x, y)) - u(x, y) ~ 0], [bc, u(bottom) ~ 0, u(top) ~ 0], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + return discretize(pdesys, FEMDiscretization(Ω)) + end + @test steady(u(left) ~ u(right)) isa SciMLBase.NonlinearProblem + @test_throws "must take no time argument" steady(u(t, left) ~ u(t, right)) +end + +# PDE: the 2D heat equation for u restricted to the upper half y >= 1/2 of the unit square (`regions`) +# BCs: a periodic pair on the full left and right sides, which reach outside the region, or on the upper halves of the sides, +# which lie inside it; Dirichlet zero on the top +# Shows: a periodic piece must lie in the field's region, like any other condition on the field. +@testset "periodic pieces must lie in the region of their field" begin + grid = generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0)) + Ferrite.addcellset!(grid, "upper_half", p -> p[2] >= 0.5 - 1.0e-12) + Ferrite.addfacetset!(grid, "upper_left", p -> p[1] < 1.0e-12 && p[2] >= 0.5 - 1.0e-12) + Ferrite.addfacetset!(grid, "upper_right", p -> p[1] > 1 - 1.0e-12 && p[2] >= 0.5 - 1.0e-12) + Ω = MeshDomain(grid) + left, right, top, upper_left, upper_right = boundarypiece.(Ω, (:left, :right, :top, :upper_left, :upper_right)) + function build(pair) + bcs = [pair, u(t, top) ~ 0, u(0, x, y) ~ 0] + @named pdesys = PDESystem([heat], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [u(t, x, y)], []) + return discretize(pdesys, FEMDiscretization(Ω, t; regions = Dict(u => Region(Ω, :upper_half)), boundary_check = :off)) + end + @test_throws "has facets outside the region :upper_half of u" build(u(t, left) ~ u(t, right)) + @test build(u(t, upper_left) ~ u(t, upper_right)) isa SciMLBase.DAEProblem +end diff --git a/test/Interface/periodic_navier_stokes.jl b/test/Interface/periodic_navier_stokes.jl new file mode 100644 index 00000000..51dc1a0b --- /dev/null +++ b/test/Interface/periodic_navier_stokes.jl @@ -0,0 +1,108 @@ +# Incompressible Navier-Stokes with Taylor-Hood elements (P2 or Q2 velocity, P1 or Q1 pressure) and periodic conditions +# in the cross-stream direction, so that three fields with two different spaces share the periodic pairs. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, NonlinearSolveFirstOrder, LinearSolve, Test +using Ferrite: Grid, addfacetset!, generate_grid, Quadrilateral, Triangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) v(..) p(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +Δ(f) = Dx(Dx(f)) + Dy(Dy(f)) + +const ν_kovasznay = 1 / 20 +const λ = 1 / (2ν_kovasznay) - sqrt(1 / (4ν_kovasznay^2) + 4pi^2) +kovasznay_u(x_, y_) = 1 - exp(λ * x_) * cos(2pi * y_) +kovasznay_v(x_, y_) = λ / 2pi * exp(λ * x_) * sin(2pi * y_) +kovasznay_p(x_, y_) = (1 - exp(2λ * x_)) / 2 + +# PDE: ν Δu - (u.grad)u - grad p = 0 and div u = 0 with ν = 1/20 (Reynolds number 20), no source +# Domain: x in (-1/2, 1), y in (-1/2, 3/2) (two periods of the flow in y), meshes of 6 x 8, 12 x 16 and 24 x 32 triangle pairs +# BCs: velocity = the exact velocity on left and right and the pressure fixed on the right, as in navier_stokes.jl; bottom and +# top are periodic for u, v and p instead of carrying exact data +# Exact: Kovasznay's flow, which has period 1 in y +# Shows: a steady nonlinear saddle-point problem with periodic pairs for velocity (P2) and pressure (P1): the velocity +# converges at rate 3 and the pressure at rate 2, as with exact data on the sides. +@testset "steady Kovasznay flow with periodic bottom and top converges at rates 3 and 2" begin + continuity = 0 ~ Dx(u(x, y)) + Dy(v(x, y)) + eqs = [ + ν_kovasznay * Δ(u(x, y)) - u(x, y) * Dx(u(x, y)) - v(x, y) * Dy(u(x, y)) - Dx(p(x, y)) ~ 0, + ν_kovasznay * Δ(v(x, y)) - u(x, y) * Dx(v(x, y)) - v(x, y) * Dy(v(x, y)) - Dy(p(x, y)) ~ 0, + continuity, + ] + exact_u, exact_v = kovasznay_u(x, y), kovasznay_v(x, y) + ns = (2, 4, 8) + errors = map(ns) do k + Ω = MeshDomain(generate_grid(Triangle, (3k, 4k), Vec(-0.5, -0.5), Vec(1.0, 1.5))) + left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + bcs = [ + u(left) ~ exact_u, u(right) ~ exact_u, v(left) ~ exact_v, v(right) ~ exact_v, p(right) ~ (1 - exp(2λ * x)) / 2, + u(bottom) ~ u(top), v(bottom) ~ v(top), p(bottom) ~ p(top), + ] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω], [x, y], [u(x, y), v(x, y), p(x, y)], []) + P2, P1 = Lagrange{RefTriangle, 2}(), Lagrange{RefTriangle, 1}() + disc = FEMDiscretization(Ω; spaces = Dict(u => P2, v => P2, p => P1), pairing = Dict(continuity => p)) + sol = solve(discretize(pdesys, disc), NewtonRaphson(); abstol = 1.0e-10) + @test SciMLBase.successful_retcode(sol) + xs, ys = sample_points(40; lo = -0.5, hi = 1.0), sample_points(40; lo = -0.5, hi = 1.5) + (l2_error(sol, u(x, y), kovasznay_u, xs, ys), l2_error(sol, v(x, y), kovasznay_v, xs, ys), l2_error(sol, p(x, y), kovasznay_p, xs, ys)) + end + h = 1 ./ ns + @test all(observed_rate(getindex.(errors, 1), h) .> 2.5) && all(observed_rate(getindex.(errors, 2), h) .> 2.5) + @test all(observed_rate(getindex.(errors, 3), h) .> 1.7) +end + +# The channel [0, 2] x [0, 1] of `nx` x `ny` quadrilaterals with the 2 x 2 cells at 0.4 < x, y < 0.6 removed, with the +# facet sets inlet, outlet, bottom, top and block (the sides of the removed cells). +function channel_with_block(nx, ny) + full = generate_grid(Quadrilateral, (nx, ny), Vec(0.0, 0.0), Vec(2.0, 1.0)) + center(cell) = sum(n -> full.nodes[n].x, cell.nodes) / 4 + cells = [c for c in full.cells if !(0.4 < center(c)[1] < 0.6 && 0.4 < center(c)[2] < 0.6)] + grid = Grid(cells, full.nodes) + tol = 1.0e-8 + addfacetset!(grid, "inlet", X -> X[1] < tol) + addfacetset!(grid, "outlet", X -> X[1] > 2 - tol) + addfacetset!(grid, "bottom", X -> X[2] < tol) + addfacetset!(grid, "top", X -> X[2] > 1 - tol) + addfacetset!(grid, "block", X -> 0.4 - tol < X[1] < 0.6 + tol && 0.4 - tol < X[2] < 0.6 + tol) + return grid +end + +# PDE: u_t + (u.grad)u = ν Δu - grad p and div u = 0 with ν = 1/100, from rest, t in (0, 2) +# Domain: the channel [0, 2] x [0, 1] with a square block of side 0.2 at its centre, 196 quadrilaterals, Q2/Q1 (1 934 unknowns) +# BCs: inflow u = 1 - exp(-t²), v = 0; no slip on the block; p = 0 at the outlet; u, v and p periodic between bottom and top +# Shows: the flow past a block in a channel periodic in the cross-stream direction runs to the end time, the two sides of the +# seam carry the same values, the flow speeds up around the block, and the flux through the outlet equals the flux +# through the inlet (mass is conserved) to 1e-3. +@testset "flow past a block in a channel periodic in the cross-stream direction conserves mass" begin + Ω = MeshDomain(channel_with_block(20, 10)) + inlet, outlet, bottom, top, block = boundarypiece.(Ω, (:inlet, :outlet, :bottom, :top, :block)) + ν = 0.01 + U, V, P = u(t, x, y), v(t, x, y), p(t, x, y) + eqs = [ + Dt(U) ~ ν * Δ(U) - U * Dx(U) - V * Dy(U) - Dx(P), + Dt(V) ~ ν * Δ(V) - U * Dx(V) - V * Dy(V) - Dy(P), + 0 ~ Dx(U) + Dy(V), + ] + bcs = [ + u(t, inlet) ~ 1 - exp(-t^2), v(t, inlet) ~ 0, u(t, block) ~ 0, v(t, block) ~ 0, p(t, outlet) ~ 0, + u(t, bottom) ~ u(t, top), v(t, bottom) ~ v(t, top), p(t, bottom) ~ p(t, top), u(0, x, y) ~ 0, v(0, x, y) ~ 0, + ] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 2.0)], [t, x, y], [U, V, P], []) + Q2, Q1 = Lagrange{RefQuadrilateral, 2}(), Lagrange{RefQuadrilateral, 1}() + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Q2, v => Q2, p => Q1), pairing = Dict(eqs[3] => p), natural = [outlet], initializealg = CheckInit()) + prob = discretize(pdesys, disc) + # The default `algebraic_abstol = :auto` detects the index-2 pressure despite its periodic identification rows, so the + # problem carries the same tolerances as the non-periodic twin (1e8 on the algebraic rows) and no `abstol` is passed. + @test prob.kwargs[:abstol] == [d ? 1.0e-6 : 1.0e8 for d in prob.differential_vars] + sol = solve(prob, DFBDF(linsolve = UMFPACKFactorization()); reltol = 1.0e-6) + @test SciMLBase.successful_retcode(sol) + ys = collect(range(0.005, 0.995; length = 100)) + flux(x_) = sum(sol(2.0, [x_], ys; dv = U)) / length(ys) + @test flux(0.0) ≈ 1 - exp(-4) rtol = 1.0e-3 + @test flux(2.0) ≈ flux(0.0) rtol = 1.0e-3 + seam = [0.5, 1.0, 1.5] + for dv in (U, V, P) + @test sol(2.0, seam, [0.0]; dv) ≈ sol(2.0, seam, [1.0]; dv) atol = 1.0e-10 + end + @test maximum(filter(!isnan, sol(2.0, collect(range(0.0, 2.0; length = 41)), ys; dv = U))) > 1.3 +end diff --git a/test/Interface/rejections.jl b/test/Interface/rejections.jl index bca94322..df67fa87 100644 --- a/test/Interface/rejections.jl +++ b/test/Interface/rejections.jl @@ -32,7 +32,6 @@ end @test_throws "which is not on Γ_left; write the trace on the operator's piece" lower( [heat], [NormalDerivative(left)(u(t, right)) ~ 0, ic] ) - @test_throws "periodic boundary conditions are not supported" lower([heat], [u(t, left) ~ u(t, right), ic]) @test_throws "Dirichlet data depends on another field" lower( [heat, Dt(v(t, x, y)) ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y)))], [u(t, left) + v(t, left) ~ 1, ic, v(0, x, y) ~ 0]; dvs = [u(t, x, y), v(t, x, y)] diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index 43d35b84..1e0a88be 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -75,10 +75,17 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @testset "periodic conditions" begin Ω = box() - Γl, Γr = sides(Ω) + Γl, Γr, Γb, Γt = sides(Ω) + Γ = [u(t, Γb) ~ 0, u(t, Γt) ~ 0] + @test lower([heat], [u(t, Γl) ~ u(t, Γr); Γ; ic], Ω) isa SciMLBase.DAEProblem @test_throws ArgumentError( - "periodic boundary conditions are not supported: u(t, Γ_left) ~ u(t, Γ_right)" - ) lower([heat], [u(t, Γl) ~ u(t, Γr), ic], Ω) + "a condition relating traces on two boundary pieces must be a periodic pair of the form u(t, Γa) ~ u(t, Γb): " * + "u(t, Γ_left) ~ 1 + u(t, Γ_right)" + ) lower([heat], [u(t, Γl) ~ 1 + u(t, Γr); Γ; ic], Ω) + @test occursin( + "periodic pieces Γ_left and Γ_bottom of u do not match under a translation", + errmsg(() -> lower([heat], [u(t, Γl) ~ u(t, Γb), u(t, Γr) ~ 0, u(t, Γt) ~ 0, ic], Ω)) + ) end @testset "reserved options" begin