From edb4d14f92e3da702829010cba7da513bfd0a2d4 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 18:02:01 +0000 Subject: [PATCH 01/12] Add the Interface test group: narrated end-to-end cases through the public API Heat in 1D and 2D (P1/P2, triangles and quadrilaterals, constant and time-dependent Dirichlet), Neumann, Robin and mixed sides, solution access and parameters, and the documented rejections, each compared with a manufactured solution. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/README.md | 57 ++++++++++++++++++++ test/Interface/heat_1d.jl | 48 +++++++++++++++++ test/Interface/heat_2d.jl | 69 ++++++++++++++++++++++++ test/Interface/neumann_robin.jl | 88 +++++++++++++++++++++++++++++++ test/Interface/rejections.jl | 86 ++++++++++++++++++++++++++++++ test/Interface/solution_access.jl | 74 ++++++++++++++++++++++++++ test/README.md | 2 + test/shared/interface_helpers.jl | 33 ++++++++++++ test/test_groups.toml | 3 ++ 9 files changed, 460 insertions(+) create mode 100644 test/Interface/README.md create mode 100644 test/Interface/heat_1d.jl create mode 100644 test/Interface/heat_2d.jl create mode 100644 test/Interface/neumann_robin.jl create mode 100644 test/Interface/rejections.jl create mode 100644 test/Interface/solution_access.jl create mode 100644 test/shared/interface_helpers.jl diff --git a/test/Interface/README.md b/test/Interface/README.md new file mode 100644 index 00000000..3588056c --- /dev/null +++ b/test/Interface/README.md @@ -0,0 +1,57 @@ +# Interface tests + +End-to-end tests written the way a user writes a script, in the style of MethodOfLines.jl's interface +tests: build a `PDESystem`, choose a `FEMDiscretization`, `discretize`, `solve`, and compare with the exact +(manufactured) solution. They use the exported and documented API only: no internals such as +`sol.disc_data` or `FiniteElementMethod.rectangle_grid`. Meshes come from `Ferrite.generate_grid`, as in +the documentation. + +Run the group with `GROUP=Interface julia --project=. -e 'using Pkg; Pkg.test()'`. Every `*.jl` file in this +directory runs in its own `@safetestset`, so each file is self-contained. + +## Conventions + +1. **One narrated testset per case.** The name reads as a sentence stating the result + (`"P1 elements on a line converge at rate 2 for ..."`). +2. **The comment block opens every testset** and states, in this order: `PDE`, `Domain`, `BCs` (boundary and + initial conditions), `Exact` (the manufactured solution) and `Shows` (what the case demonstrates). + A testset that loops over variants uses `$name` in its title and one comment block for all of them. +3. **Short.** A case is about 40 lines at most. If it needs more, move the repeated PDE setup into a small + function above the testset (see `heat_1d_error` in `heat_1d.jl`) or split the case. +4. **Cheap.** Meshes and time spans are small; a case takes seconds after compilation. +5. **Exact comparison.** Choose a solution inside the element space (error at solver tolerance, tolerance + `1e-7`) or compare against a smooth one with a stated tolerance, or check the convergence rate with + `observed_rate` over a refinement sequence. Compare through `sol(t, x, y; dv)` using `l2_error`. +6. **Unsupported inputs** go in `rejections.jl` with `@test_throws "message text" expr`. Do not add `@test_broken`. +7. Shared code is in `test/shared/interface_helpers.jl` (`sample_points`, `l2_error`, `observed_rate`); add to it + only what two files need. + +## Adding a case + +Copy the nearest testset, change the PDE, boundary conditions and exact solution, update the comment block, +and add a row to the table below. A new theme is a new file in this directory; nothing needs registering. +The mesh of a box is `MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0)))`; its +boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D and `(:left, :right)` in 1D. + +## Cases + +| File | Case | PDE | Dim | Order | Boundary conditions | +|------|------|-----|-----|-------|---------------------| +| `heat_1d.jl` | P1 convergence rate 2 | heat | 1 | P1 | constant Dirichlet | +| `heat_1d.jl` | P2 convergence rate 3 | heat | 1 | P2 | constant Dirichlet | +| `heat_2d.jl` | eigenmode decay on triangles and quadrilaterals | heat | 2 | P1, P2 | zero Dirichlet | +| `heat_2d.jl` | exact reproduction by P2 | heat | 2 | P2 | time-dependent Dirichlet | +| `heat_2d.jl` | P1 convergence rate 2 | heat | 2 | P1 | time-dependent Dirichlet | +| `neumann_robin.jl` | Neumann on three sides | heat | 2 | P2 | Dirichlet and Neumann | +| `neumann_robin.jl` | Robin with parameters `k`, `α` | heat | 2 | P2 | Dirichlet and Robin | +| `neumann_robin.jl` | Dirichlet, Neumann and Robin together | heat | 2 | P2 | all three | +| `neumann_robin.jl` | insulated box | heat | 2 | P1 | zero Neumann | +| `solution_access.jl` | `sol[u]`, `sol[x]`, `sol[y]` shapes | heat with parameter `D` | 2 | P2 | Dirichlet | +| `solution_access.jl` | `sol(t, x, y; dv)` points, grids, outside the mesh | heat | 2 | P2 | Dirichlet | +| `solution_access.jl` | derivative and trace keys | heat | 2 | P2 | Dirichlet | +| `solution_access.jl` | parameter values set the diffusivity | heat | 2 | P2 | Dirichlet | +| `rejections.jl` | rejected boundary conditions, equations, options, domains, shared facets | heat | 1 to 2 | | | + +## Not covered on this branch + +Steady problems, time-last variables, observed expressions, SUPG and Navier-Stokes are not on `master`. diff --git a/test/Interface/heat_1d.jl b/test/Interface/heat_1d.jl new file mode 100644 index 00000000..6986100b --- /dev/null +++ b/test/Interface/heat_1d.jl @@ -0,0 +1,48 @@ +# The 1D heat equation through the full interface: PDESystem -> FEMDiscretization -> discretize -> +# solve -> comparison with the exact solution, in piecewise-linear (P1) and piecewise-quadratic (P2) +# elements, with the convergence rate read off a refinement sequence. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x u(..) +Dt, Dx = Differential(t), Differential(x) + +# Solves u_t = u_xx on a mesh of `n` cells with the given element order, returns the L2 error at t = 0.1. +function heat_1d_error(n, order) + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + eqs = [Dt(u(t, x)) ~ Dx(Dx(u(t, x)))] + bcs = [u(t, left) ~ 1, u(t, right) ~ 1, u(0, x) ~ 1 + sin(pi * x)] + domains = [(x,) ∈ Ω, t ∈ Interval(0.0, 0.1)] + @named pdesys = PDESystem(eqs, bcs, domains, [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, order}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-11, reltol = 1.0e-11) + exact(x_) = 1 + exp(-pi^2 * 0.1) * sin(pi * x_) + return l2_error(sol, u(t, x), exact, 0.1, sample_points(400)) +end + +# PDE: u_t = u_xx +# Domain: x in (0, 1), t in (0, 0.1), meshes of 4, 8, 16 and 32 line cells +# BCs: u(t, 0) = u(t, 1) = 1 (constant Dirichlet); IC u(0, x) = 1 + sin(pi x) +# Exact: u = 1 + exp(-pi^2 t) sin(pi x) +# Shows: P1 elements converge at the optimal L2 rate 2. +@testset "P1 elements on a line converge at rate 2 for the heat equation with constant Dirichlet data" begin + ns = (4, 8, 16, 32) + errors = heat_1d_error.(ns, 1) + @test issorted(errors; rev = true) + @test all(observed_rate(errors, 1 ./ ns) .> 1.9) +end + +# PDE: u_t = u_xx +# Domain: x in (0, 1), t in (0, 0.1), meshes of 2, 4, 8 and 16 line cells +# BCs: u(t, 0) = u(t, 1) = 1 (constant Dirichlet); IC u(0, x) = 1 + sin(pi x) +# Exact: u = 1 + exp(-pi^2 t) sin(pi x) +# Shows: P2 elements, chosen with `spaces`, converge at the optimal L2 rate 3. +@testset "P2 elements on a line converge at rate 3 for the heat equation with constant Dirichlet data" begin + ns = (2, 4, 8, 16) + errors = heat_1d_error.(ns, 2) + @test issorted(errors; rev = true) + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end diff --git a/test/Interface/heat_2d.jl b/test/Interface/heat_2d.jl new file mode 100644 index 00000000..28384ac3 --- /dev/null +++ b/test/Interface/heat_2d.jl @@ -0,0 +1,69 @@ +# The 2D heat equation through the full interface on a quadrilateral mesh and on a triangle mesh, +# in P1 and P2 elements, with constant and time-dependent Dirichlet data, compared with exact +# solutions. Every case builds the PDESystem, the FEMDiscretization and the problem, solves it, and +# measures the L2 distance to the exact solution at the final time. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Triangle, Quadrilateral, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +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 `heat` on Ω with the given element space and boundary and initial conditions to `tend`. +function solve_heat(Ω, space, bcs, tend) + domains = [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)] + @named pdesys = PDESystem([heat], bcs, domains, [t, x, y], [u(t, x, y)], []) + prob = discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => space))) + return solve(prob, 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), 16 x 16 cells +# BCs: u = 0 on all four sides (constant Dirichlet); IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = exp(-2 pi^2 t) sin(pi x) sin(pi y) +# Shows: the decaying eigenmode is reproduced by P1 and P2 elements on triangles and quadrilaterals. +@testset "the heat equation with zero Dirichlet data decays as its eigenmode on $name meshes" for (name, celltype, ref, order, tol) in ( + ("P1 triangle", Triangle, RefTriangle, 1, 5.0e-3), ("P2 triangle", Triangle, RefTriangle, 2, 1.0e-4), + ("P1 quadrilateral", Quadrilateral, RefQuadrilateral, 1, 5.0e-3), ("P2 quadrilateral", Quadrilateral, RefQuadrilateral, 2, 1.0e-4), + ) + Ω = unit_square(celltype, 16) + bcs = [[u(t, Γ) ~ 0 for Γ in sides(Ω)]; u(0, x, y) ~ sin(pi * x) * sin(pi * y)] + sol = solve_heat(Ω, Lagrange{ref, order}(), bcs, 0.05) + exact(x_, y_) = exp(-2pi^2 * 0.05) * sin(pi * x_) * sin(pi * y_) + @test l2_error(sol, u(t, x, y), exact, 0.05, sample_points(50), sample_points(50)) < tol +end + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 1), 4 x 4 cells +# BCs: u = x^2 + y^2 + 4t on all four sides (time-dependent Dirichlet); IC u(0, x, y) = x^2 + y^2 +# Exact: u = x^2 + y^2 + 4t, which lies in the P2 space, so the error is the solver tolerance +# Shows: time-dependent Dirichlet data is imposed at every time, on both cell shapes. +@testset "time-dependent Dirichlet data is reproduced exactly by P2 elements on $name meshes" for (name, celltype, ref) in ( + ("triangle", Triangle, RefTriangle), ("quadrilateral", Quadrilateral, RefQuadrilateral), + ) + Ω = unit_square(celltype, 4) + bcs = [[u(t, Γ) ~ x^2 + y^2 + 4t for Γ in sides(Ω)]; u(0, x, y) ~ x^2 + y^2] + sol = solve_heat(Ω, Lagrange{ref, 2}(), bcs, 1.0) + @test l2_error(sol, u(t, x, y), (x_, y_) -> x_^2 + y_^2 + 4, 1.0, sample_points(20), sample_points(20)) < 1.0e-7 +end + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 0.5), meshes of 4, 8 and 16 triangle pairs per side +# BCs: u = exp(2t + x + y) on all four sides (time-dependent, not in the element space) +# Exact: u = exp(2t + x + y) +# Shows: P1 elements converge at the optimal L2 rate 2 under time-dependent Dirichlet data. +@testset "P1 elements converge at rate 2 under time-dependent Dirichlet data on triangles" begin + ns = (4, 8, 16) + errors = map(ns) do n + Ω = unit_square(Triangle, n) + bcs = [[u(t, Γ) ~ exp(2t + x + y) for Γ in sides(Ω)]; u(0, x, y) ~ exp(x + y)] + sol = solve_heat(Ω, Lagrange{RefTriangle, 1}(), bcs, 0.5) + l2_error(sol, u(t, x, y), (x_, y_) -> exp(1 + x_ + y_), 0.5, sample_points(60), sample_points(60)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 1.9) +end diff --git a/test/Interface/neumann_robin.jl b/test/Interface/neumann_robin.jl new file mode 100644 index 00000000..5eb0ef9b --- /dev/null +++ b/test/Interface/neumann_robin.jl @@ -0,0 +1,88 @@ +# Neumann, Robin and mixed boundary conditions on the sides of a rectangle, through the full +# interface. The manufactured solution u = x^2 + y^2 + 4t solves u_t = u_xx + u_yy without a source +# and lies in the P2 and Q2 spaces, so each case must reproduce it to the solver tolerance. Its +# outward normal derivatives on the unit square are 2 (right), 2 (top), 0 (left) and 0 (bottom). +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Triangle, Quadrilateral, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +@parameters k α +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +unit_square(celltype, n) = MeshDomain(generate_grid(celltype, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + +# Solves u_t = k (u_xx + u_yy) with k = 1 and α = 3 under `bcs(left, right, bottom, top)` and compares with the exact solution. +function exact_error(bcs, celltype, ref) + Ω = unit_square(celltype, 4) + eq = Dt(u(t, x, y)) ~ Dx(k * Dx(u(t, x, y))) + Dy(k * Dy(u(t, x, y))) + conditions = [bcs(boundarypiece.(Ω, (:left, :right, :bottom, :top))...); u(0, x, y) ~ x^2 + y^2] + @named pdesys = PDESystem([eq], conditions, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], [k => 1.0, α => 3.0]) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{ref, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + return l2_error(sol, u(t, x, y), (x_, y_) -> x_^2 + y_^2 + 4, 1.0, sample_points(20), sample_points(20)) +end + +cells = ((Triangle, RefTriangle), (Quadrilateral, RefQuadrilateral)) + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 1) +# BCs: Dirichlet u = x^2 + y^2 + 4t on the left; Neumann du/dn = 2, 2, 0 on the right, top, bottom +# Exact: u = x^2 + y^2 + 4t +# Shows: a Neumann condition is written with NormalDerivative(Γ) and reproduces the exact flux. +@testset "Neumann conditions on three sides reproduce the exact solution on $(first(c)) meshes" for c in cells + err = exact_error(c...) do left, right, bottom, top + [ + u(t, left) ~ y^2 + 4t, NormalDerivative(right)(u(t, right)) ~ 2, + NormalDerivative(bottom)(u(t, bottom)) ~ 0, NormalDerivative(top)(u(t, top)) ~ 2, + ] + end + @test err < 1.0e-7 +end + +# PDE: u_t = k (u_xx + u_yy), with the parameter k = 1 +# Domain: the unit square, t in (0, 1) +# BCs: Dirichlet on the left, bottom and top; Robin k du/dn + alpha u = alpha (1 + y^2 + 4t) + 2 k on the right +# Exact: u = x^2 + y^2 + 4t +# Shows: a Robin condition with an explicit conormal coefficient k and a parameter alpha. +@testset "a Robin condition with parameters reproduces the exact solution on $(first(c)) meshes" for c in cells + err = exact_error(c...) do left, right, bottom, top + [ + u(t, left) ~ y^2 + 4t, u(t, bottom) ~ x^2 + 4t, u(t, top) ~ x^2 + 1 + 4t, + k * NormalDerivative(right)(u(t, right)) + α * u(t, right) ~ α * (1 + y^2 + 4t) + 2k, + ] + end + @test err < 1.0e-7 +end + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 1) +# BCs: Dirichlet on the left, Neumann on the bottom, Robin du/dn + alpha u = ... on the top and right +# Exact: u = x^2 + y^2 + 4t +# Shows: Dirichlet, Neumann and Robin conditions on different sides of one rectangle. +@testset "Dirichlet, Neumann and Robin sides of one rectangle reproduce the exact solution on $(first(c)) meshes" for c in cells + err = exact_error(c...) do left, right, bottom, top + [ + u(t, left) ~ y^2 + 4t, NormalDerivative(bottom)(u(t, bottom)) ~ 0, + k * NormalDerivative(top)(u(t, top)) + α * u(t, top) ~ α * (x^2 + 1 + 4t) + 2k, + k * NormalDerivative(right)(u(t, right)) + α * u(t, right) ~ α * (1 + y^2 + 4t) + 2k, + ] + end + @test err < 1.0e-7 +end + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 0.1) +# BCs: zero flux on all four sides; IC u(0, x, y) = 1 + cos(pi x) cos(pi y) +# Exact: u = 1 + exp(-2 pi^2 t) cos(pi x) cos(pi y) +# Shows: a fully insulated box relaxes to its mean value 1 along the exact cosine mode. +@testset "a fully insulated box decays along its cosine mode on triangle meshes" begin + Ω = unit_square(Triangle, 16) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + bcs = [[NormalDerivative(Γ)(u(t, Γ)) ~ 0 for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))]; u(0, x, y) ~ 1 + cos(pi * x) * cos(pi * y)] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [u(t, x, y)], []) + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t)), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + exact(x_, y_) = 1 + exp(-2pi^2 * 0.1) * cos(pi * x_) * cos(pi * y_) + @test l2_error(sol, u(t, x, y), exact, 0.1, sample_points(50), sample_points(50)) < 5.0e-3 +end diff --git a/test/Interface/rejections.jl b/test/Interface/rejections.jl new file mode 100644 index 00000000..dd26a705 --- /dev/null +++ b/test/Interface/rejections.jl @@ -0,0 +1,86 @@ +# Inputs the discretization refuses, each through the full interface: the PDESystem is built as a user +# would build it, and `discretize` (or the `FEMDiscretization` constructor) throws before any solver runs. +# Every case asserts the part of the documented message that names the problem (`@test_throws "text" expr`). +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: Ferrite +using Ferrite: generate_grid, Triangle, Vec +using ModelingToolkit: t_nounits as t + +@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))) +ic = u(0, x, y) ~ 0 + +Ω = MeshDomain(generate_grid(Triangle, (2, 2), Vec(0.0, 0.0), Vec(1.0, 1.0))) +left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +dirichlet = [u(t, Γ) ~ 0 for Γ in (left, right, bottom, top)] + +# Builds the PDESystem for `eqs` and `bcs` and discretizes it; the keywords go to `FEMDiscretization`. +function lower(eqs, bcs; mesh = Ω, dvs = [u(t, x, y)], domains = [(x, y) ∈ mesh, t ∈ Interval(0.0, 1.0)], ivs = [t, x, y], kw...) + @named pdesys = PDESystem(eqs, bcs, domains, ivs, dvs, []) + return discretize(pdesys, FEMDiscretization(mesh, t; kw...)) +end + +# PDE: the 2D heat equation on the unit square, t in (0, 1), on a 2 x 2 triangle mesh +# BCs: a malformed or unsupported boundary condition on one of the four sides +# Shows: the message names the mistake and, where there is one, the form to write instead. +@testset "boundary conditions that cannot be imposed are rejected with the fix in the message" begin + @test_throws "trace is missing the time argument; write `u(t, Γ_left)`" lower([heat], [u(left) ~ 0, ic]) + @test_throws "write a trace on a boundary piece instead" lower([heat], [u(t, 0, y) ~ 0, ic]) + @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 conditions need milestone M4" 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)] + ) +end + +# PDE: heat equations with a nonlinear coefficient, a time-dependent coefficient, third order in space +# or second order in time, with zero Dirichlet data +# Shows: an operator the Galerkin weak form cannot assemble yet is named in the error. +@testset "equations outside the supported classes are rejected naming the term" begin + nonlinear = Dt(u(t, x, y)) ~ Dx((1 + u(t, x, y)^2) * Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + @test_throws "nonlinear terms land in M3" lower([nonlinear], [dirichlet; ic]) + varying = Dt(u(t, x, y)) ~ Dx((1 + t) * Dx(u(t, x, y))) + Dy((1 + t) * Dy(u(t, x, y))) + @test_throws "time-dependent coefficients in the mass or stiffness operator land in M3" lower([varying], [dirichlet; ic]) + @test_throws "third-order" lower([Dt(u(t, x, y)) ~ Dx(Dx(Dx(u(t, x, y))))], [dirichlet; ic]) + @test_throws "second order in time; write as a first-order system" lower( + [Differential(t, 2)(u(t, x, y)) ~ Dx(Dx(u(t, x, y)))], [dirichlet; ic] + ) +end + +# PDE: the 2D heat equation, or a steady Laplace equation +# Shows: options reserved for later releases, and unknown `spaces` keys, fail with the supported default named. +@testset "options that are not available yet are rejected when the discretization is built" begin + @test_throws "codegen = :mtk lands in M3; use the default codegen = :numeric" FEMDiscretization(Ω, t; codegen = :mtk) + @test_throws "dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic" FEMDiscretization(Ω, t; dirichlet = :eliminate) + @named steady = PDESystem([Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in (left, right, bottom, top)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + @test_throws "steady problems land in M4; give FEMDiscretization a time variable" discretize(steady, FEMDiscretization(Ω)) + @test_throws "`spaces` has keys that are not dependent variables of the system: v" lower( + [heat], [dirichlet; ic]; spaces = Dict(v => Lagrange{RefTriangle, 2}()) + ) +end + +# PDE: the 2D heat equation, with a Rectangle domain, a split time interval or time as the last argument +# Shows: the PDESystem's domains must be a mesh for space and one interval for time, with time first. +@testset "domains the discretization cannot use are rejected naming what is expected" begin + box = [(x, y) ∈ Rectangle([0.0, 0.0], [1.0, 1.0]), t ∈ Interval(0.0, 1.0)] + @test_throws "FEMDiscretization discretizes on a mesh" lower([heat], [ic]; domains = box) + split_time = [(x, y) ∈ Ω, t ∈ UnionDomain(Interval(0.0, 1.0), Interval(2.0, 3.0))] + @test_throws "time t must be paired with an interval" lower([heat], [ic]; domains = split_time) + time_last = Dt(u(x, y, t)) ~ Dx(Dx(u(x, y, t))) + Dy(Dy(u(x, y, t))) + @test_throws "time must be the first argument of u(x, y, t)" lower([time_last], [u(x, y, 0) ~ 0]; dvs = [u(x, y, t)]) +end + +# PDE: the 2D heat equation on the unit square +# BCs: Dirichlet data on the facet sets "inlet" and "left", which are the same two facets +# Shows: boundary pieces must be disjoint. +@testset "two boundary pieces that share facets are rejected naming the count" begin + grid = generate_grid(Triangle, (2, 2), Vec(0.0, 0.0), Vec(1.0, 1.0)) + Ferrite.addfacetset!(grid, "inlet", p -> p[1] ≈ 0) # the same facets as "left" + mesh = MeshDomain(grid) + inlet, left_side = boundarypiece.(mesh, (:inlet, :left)) + @test_throws "share 2 facets" lower([heat], [u(t, inlet) ~ 0, u(t, left_side) ~ 1, ic]; mesh) +end diff --git a/test/Interface/solution_access.jl b/test/Interface/solution_access.jl new file mode 100644 index 00000000..2de2e221 --- /dev/null +++ b/test/Interface/solution_access.jl @@ -0,0 +1,74 @@ +# Reading a solution: `sol.t`, `sol[u(t, x, y)]`, `sol[x]`, `sol(t, x, y; dv)`, traces, derivatives and +# the parameters of the PDESystem, on the problem u_t = D (u_xx + u_yy) on the unit square with the +# manufactured solution u = x^2 + y^2 + 4 D t, which a P2 space on triangles holds exactly. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Triangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@parameters D +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# Builds, discretizes and solves the problem with diffusivity `diffusivity`; returns the solution and the left piece. +function solve_diffusion(diffusivity) + Ω = MeshDomain(generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0))) + left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + exact = x^2 + y^2 + 4D * t + eq = Dt(u(t, x, y)) ~ D * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) + bcs = [[u(t, Γ) ~ exact for Γ in (left, right, bottom, top)]; u(0, x, y) ~ x^2 + y^2] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], [D => diffusivity]) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}()), saveat = 0.25) + return solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10), left +end + +# PDE: u_t = D (u_xx + u_yy) with D = 2 +# Domain: the unit square, t in (0, 1), 4 x 4 triangle pairs, P2; saved every 0.25 +# BCs: u = x^2 + y^2 + 4 D t on all sides; IC u(0, x, y) = x^2 + y^2 +# Exact: u = x^2 + y^2 + 4 D t +# Shows: the shapes of sol.t, sol[u], sol[x] and sol[y], and that column i of sol[u] sits at (sol[x][i], sol[y][i]). +@testset "sol[u(t, x, y)] holds one row per saved time and one column per mesh node" begin + sol, _ = solve_diffusion(2.0) + @test sol.t == [0.0, 0.25, 0.5, 0.75, 1.0] + values, xs, ys = sol[u(t, x, y)], sol[x], sol[y] + @test size(values) == (5, length(xs)) && length(xs) == length(ys) == 25 + @test values ≈ [x_^2 + y_^2 + 8t_ for t_ in sol.t, (x_, y_) in zip(xs, ys)] atol = 1.0e-7 +end + +# PDE, Domain, BCs, Exact: as in the first case, with D = 2 +# Shows: sol(t, x, y; dv) evaluates the finite-element field anywhere in the mesh, interpolating in time. +@testset "sol(t, x, y; dv) evaluates the field at points and on tensor grids at any time" begin + sol, _ = solve_diffusion(2.0) + exact(t_, x_, y_) = x_^2 + y_^2 + 8t_ + @test sol(0.6, 0.3, 0.7; dv = u(t, x, y)) ≈ exact(0.6, 0.3, 0.7) atol = 1.0e-5 + grid = sol(0.5, [0.1, 0.5, 0.9], [0.2, 0.8]; dv = u(t, x, y)) + @test size(grid) == (3, 2) + @test grid ≈ [exact(0.5, x_, y_) for x_ in (0.1, 0.5, 0.9), y_ in (0.2, 0.8)] atol = 1.0e-7 + @test isnan(sol(0.5, 1.5, 0.5; dv = u(t, x, y))) # outside the mesh + @test_throws DomainError sol(0.5, 1.5, 0.5; dv = u(t, x, y), outside = :error) + @test_throws DomainError sol(2.0, 0.5, 0.5; dv = u(t, x, y)) # outside the saved time span +end + +# PDE, Domain, BCs, Exact: as in the first case, with D = 2 +# Shows: derivatives and traces are read with the same indexing: sol[Dx(u)] is du/dx = 2x, +# and sol[u(t, Γ)] is the field on the nodes of the boundary piece Γ. +@testset "sol[Dx(u)] gives the gradient and sol[u(t, Γ)] the trace on a boundary piece" begin + sol, left = solve_diffusion(2.0) + xs = sol[x] + @test sol[Dx(u(t, x, y))][end, :] ≈ 2 .* xs atol = 1.0e-5 + trace = sol[u(t, left)] + @test size(trace) == (5, length(piece_nodes(sol, left))) + @test trace ≈ [y_^2 + 8t_ for t_ in sol.t, y_ in sol[y][piece_nodes(sol, left)]] atol = 1.0e-7 +end + +# PDE: u_t = D (u_xx + u_yy), solved for D = 1, 2 and 4 +# Domain: the unit square, t in (0, 1), P2; BCs and IC as in the first case +# Exact: u = x^2 + y^2 + 4 D t +# Shows: the numeric value given to the parameter D in the PDESystem's parameter list sets the diffusivity, +# so the value at the centre of the square, 0.5 + 4 D t, grows with D. +@testset "the parameter values of the PDESystem set the diffusivity" begin + for diffusivity in (1.0, 2.0, 4.0) + sol, _ = solve_diffusion(diffusivity) + @test sol(1.0, 0.5, 0.5; dv = u(t, x, y)) ≈ 0.5 + 4diffusivity atol = 1.0e-7 + end +end diff --git a/test/README.md b/test/README.md index 7eee9bfe..11c1b4a1 100644 --- a/test/README.md +++ b/test/README.md @@ -11,6 +11,8 @@ the group list and for the CI matrix: `.github/workflows/Tests.yml` fans out one | `QA` | `test/qa/*.jl` (Aqua and JET) | `test/qa/Project.toml` | | `X` | `test/X/*.jl`, for any other declared `X` | `test/X/Project.toml` if present, else main | +`Interface` is the exemplary end-to-end group: narrated user-facing cases through the public interface only (see `test/Interface/README.md`). + An unset `GROUP` runs `Core` plus every declared group except `QA`; `GROUP=Everything` also runs `QA`. diff --git a/test/shared/interface_helpers.jl b/test/shared/interface_helpers.jl new file mode 100644 index 00000000..c07ae6fc --- /dev/null +++ b/test/shared/interface_helpers.jl @@ -0,0 +1,33 @@ +# Helpers shared by the Interface group. They use only the public solution interface, so each case +# reads as a user's script followed by a comparison with the exact solution. +using Test + +""" + sample_points(n; lo = 0.0, hi = 1.0) + +The `n` cell midpoints of a uniform partition of `[lo, hi]`, the sample points of [`l2_error`](@ref). +""" +sample_points(n; lo = 0.0, hi = 1.0) = range(lo + (hi - lo) / 2n, hi - (hi - lo) / 2n; length = n) + +""" + l2_error(sol, dv, exact, t, points...) + +The L2 distance at time `t` between the field `dv` of the solution `sol` and the function +`exact(x...)`, on the tensor product of the sample `points` (one range per coordinate, as made by +[`sample_points`](@ref)). Each sample carries the volume `prod(step.(points))` of its cell, so the +midpoint rule approximates the integral over the domain the points cover. +""" +function l2_error(sol, dv, exact, t, points...) + computed = sol(t, collect.(points)...; dv) + expected = [exact(x...) for x in Iterators.product(points...)] + cell_volume = prod(step.(points)) + return sqrt(sum(abs2, computed .- expected) * cell_volume) +end + +""" + observed_rate(errors, hs) + +The convergence rates `log(errors[i - 1] / errors[i]) / log(hs[i - 1] / hs[i])` between successive +refinements of mesh size `hs`. +""" +observed_rate(errors, hs) = [log(errors[i - 1] / errors[i]) / log(hs[i - 1] / hs[i]) for i in 2:length(errors)] diff --git a/test/test_groups.toml b/test/test_groups.toml index 9de6ee32..6a847a4b 100644 --- a/test/test_groups.toml +++ b/test/test_groups.toml @@ -28,6 +28,9 @@ versions = ["lts", "1", "pre"] [Integration] versions = ["lts", "1", "pre"] +[Interface] +versions = ["lts", "1", "pre"] + [Convergence] versions = ["lts", "1", "pre"] From 3977f6b564b3cb698fad5eae9418c2b1a33dcab1 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 18:12:04 +0000 Subject: [PATCH 02/12] Add advection-diffusion, reaction-diffusion, variable-coefficient and source-term Interface cases Manufactured solutions with sources in 1D and 2D, P2 elements on triangles and quadrilaterals, divergence and non-divergence variable diffusivity, linear and coupled reaction terms, and the documented rejection of a nonlinear reaction. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/advection_diffusion.jl | 96 +++++++++++++++++ test/Interface/reaction_diffusion.jl | 100 ++++++++++++++++++ test/Interface/source_terms.jl | 72 +++++++++++++ .../variable_coefficient_diffusion.jl | 95 +++++++++++++++++ 4 files changed, 363 insertions(+) create mode 100644 test/Interface/advection_diffusion.jl create mode 100644 test/Interface/reaction_diffusion.jl create mode 100644 test/Interface/source_terms.jl create mode 100644 test/Interface/variable_coefficient_diffusion.jl diff --git a/test/Interface/advection_diffusion.jl b/test/Interface/advection_diffusion.jl new file mode 100644 index 00000000..7209132b --- /dev/null +++ b/test/Interface/advection_diffusion.jl @@ -0,0 +1,96 @@ +# Advection-diffusion with a constant velocity through the full interface, in 1D and 2D with P2 elements, +# against manufactured solutions: a source term f is chosen so that a known u solves the equation. +# docs/src/equation_classes.md lists convection-diffusion at moderate cell Peclet number as a Tier 1 class +# (supported, VERIFIED); only pure advection and advection-dominated problems are Tier 2 (need SUPG, M4), +# so every case here keeps the cell Peclet number below one. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Triangle, Quadrilateral, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +line(n) = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) +unit_square(celltype, n) = MeshDomain(generate_grid(celltype, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + +# Solves the 1D problem eq on the line Ω with Dirichlet data g(t, x) at both ends and the initial condition g(0, x). +function solve_1d(eq, Ω, g, tend) + left, right = boundarypiece.(Ω, (:left, :right)) + bcs = [u(t, left) ~ g(t, 0), u(t, right) ~ g(t, 1), u(0, x) ~ g(0, x)] + @named pdesys = PDESystem([eq], bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, 2}())) + return solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# Same in 2D on the unit square with Dirichlet data g(t, x, y) on all four sides. +function solve_2d(eq, Ω, ref, g, tend) + bcs = [[u(t, Γ) ~ g(t, x, y) for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))]; u(0, x, y) ~ g(0, x, y)] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{ref, 2}())) + return solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# PDE: u_t + c u_x = D u_xx + f, with c = 2, D = 0.5 +# Domain: x in (0, 1), t in (0, 1), 4 line cells +# BCs: u = g(t, x) at both ends (time-dependent Dirichlet); IC u(0, x) = g(0, x) +# Exact: u = x^2 + 3x t + t, so f = u_t + c u_x - D u_xx = 3x + 1 + 2 (2x + 3t) - 1, which lies in the P2 space +# Shows: the advection term has the right sign and size: the P2 solution is exact to the solver tolerance. +@testset "constant-velocity advection-diffusion is reproduced exactly by P2 elements on a line" begin + c, D = 2.0, 0.5 + exact(t_, x_) = x_^2 + 3x_ * t_ + t_ + source = 3x + 1 + c * (2x + 3t) - D * 2 + sol = solve_1d(Dt(u(t, x)) + c * Dx(u(t, x)) ~ D * Dx(Dx(u(t, x))) + source, line(4), exact, 1.0) + @test l2_error(sol, u(t, x), x_ -> exact(1.0, x_), 1.0, sample_points(40)) < 1.0e-7 +end + +# PDE: u_t + c u_x = D u_xx + f, with c = 5, D = 1 (cell Peclet number c h / 2D is 0.63 on the coarsest mesh and 0.16 on the finest) +# Domain: x in (0, 1), t in (0, 0.2), meshes of 4, 8 and 16 line cells +# BCs: u = 0 at both ends; IC u(0, x) = sin(pi x) +# Exact: u = exp(-t) sin(pi x), so f = (D pi^2 - 1) u + c pi exp(-t) cos(pi x) +# Shows: P2 elements converge at the optimal L2 rate 3 with a source term and a first-order term. +@testset "P2 elements on a line converge at rate 3 for advection-diffusion with a manufactured source" begin + c, D = 5.0, 1.0 + source = exp(-t) * ((D * pi^2 - 1) * sin(pi * x) + c * pi * cos(pi * x)) + ns = (4, 8, 16) + errors = map(ns) do n + sol = solve_1d(Dt(u(t, x)) + c * Dx(u(t, x)) ~ D * Dx(Dx(u(t, x))) + source, line(n), (t_, x_) -> exp(-t_) * sin(pi * x_), 0.2) + l2_error(sol, u(t, x), x_ -> exp(-0.2) * sin(pi * x_), 0.2, sample_points(200)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end + +# PDE: u_t + c . grad u = D (u_xx + u_yy) + f, with c = (1, -2), D = 0.5 +# Domain: the unit square, t in (0, 1), 4 x 4 cells +# BCs: u = g(t, x, y) on all four sides (time-dependent Dirichlet); IC u(0, x, y) = g(0, x, y) +# Exact: u = x^2 + x y + 2 y^2 + t (1 + x - y), so f = u_t + c . grad u - D Laplace u, in the P2 space +# Shows: a constant velocity vector acts in both directions, on triangles and quadrilaterals. +@testset "constant-velocity advection-diffusion is reproduced exactly by P2 elements on $name meshes" for (name, celltype, ref) in ( + ("triangle", Triangle, RefTriangle), ("quadrilateral", Quadrilateral, RefQuadrilateral), + ) + cx, cy, D = 1.0, -2.0, 0.5 + exact(t_, x_, y_) = x_^2 + x_ * y_ + 2y_^2 + t_ * (1 + x_ - y_) + u_x, u_y = 2x + y + t, x + 4y - t + source = (1 + x - y) + cx * u_x + cy * u_y - D * (2 + 4) + eq = Dt(u(t, x, y)) + cx * Dx(u(t, x, y)) + cy * Dy(u(t, x, y)) ~ D * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) + source + sol = solve_2d(eq, unit_square(celltype, 4), ref, exact, 1.0) + @test l2_error(sol, u(t, x, y), (x_, y_) -> exact(1.0, x_, y_), 1.0, sample_points(20), sample_points(20)) < 1.0e-7 +end + +# PDE: u_t + c . grad u = D (u_xx + u_yy) + f, with c = (3, 2), D = 1 +# Domain: the unit square, t in (0, 0.1), meshes of 2, 4 and 8 per side +# BCs: u = 0 on all four sides; IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = exp(-t) sin(pi x) sin(pi y), so f = (2 D pi^2 - 1) u + c_x pi exp(-t) cos(pi x) sin(pi y) + c_y pi exp(-t) sin(pi x) cos(pi y) +# Shows: P2 elements converge at the optimal L2 rate 3 in 2D with advection and a manufactured source. +@testset "P2 elements on triangles converge at rate 3 for 2D advection-diffusion with a manufactured source" begin + cx, cy, D = 3.0, 2.0, 1.0 + s = exp(-t) + source = s * ((2D * pi^2 - 1) * sin(pi * x) * sin(pi * y) + cx * pi * cos(pi * x) * sin(pi * y) + cy * pi * sin(pi * x) * cos(pi * y)) + eq = Dt(u(t, x, y)) + cx * Dx(u(t, x, y)) + cy * Dy(u(t, x, y)) ~ D * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) + source + ns = (2, 4, 8) + errors = map(ns) do n + sol = solve_2d(eq, unit_square(Triangle, n), RefTriangle, (t_, x_, y_) -> exp(-t_) * sin(pi * x_) * sin(pi * y_), 0.1) + l2_error(sol, u(t, x, y), (x_, y_) -> exp(-0.1) * sin(pi * x_) * sin(pi * y_), 0.1, sample_points(40), sample_points(40)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 2.7) +end diff --git a/test/Interface/reaction_diffusion.jl b/test/Interface/reaction_diffusion.jl new file mode 100644 index 00000000..531fc4f9 --- /dev/null +++ b/test/Interface/reaction_diffusion.jl @@ -0,0 +1,100 @@ +# Reaction-diffusion through the full interface: a linear reaction term, a linearly coupled two-field +# system, and the documented rejection of a nonlinear reaction. +# docs/src/equation_classes.md lists second-order parabolic equations "scalar or coupled multi-field" as +# Tier 1 (VERIFIED, two-field reaction-diffusion to 1.9e-16). It also lists nonlinear sources `f(u)` as +# Tier 1 in the design, but states that this release rejects state-dependent coefficients with an error +# naming milestone M3, so the nonlinear case below asserts that rejection. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Triangle, Quadrilateral, 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) + +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` for u on the unit square with zero Dirichlet data and the initial condition u0. +function solve_square(eq, Ω, ref, order, u0, tend) + bcs = [[u(t, Γ) ~ 0 for Γ in sides(Ω)]; u(0, x, y) ~ u0] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{ref, order}())) + return solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# PDE: u_t = u_xx + u_yy - k u + f, with k = 4 (a decay reaction) +# Domain: the unit square, t in (0, 0.1), 16 x 16 cells +# BCs: u = 0 on all four sides; IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = exp(-t) sin(pi x) sin(pi y), so f = (2 pi^2 + k - 1) u +# Shows: a linear reaction term and a source term together, on triangles and quadrilaterals. +@testset "linear reaction-diffusion with a manufactured source matches the exact solution on $name meshes" for (name, celltype, ref) in ( + ("triangle", Triangle, RefTriangle), ("quadrilateral", Quadrilateral, RefQuadrilateral), + ) + k = 4.0 + exact(t_, x_, y_) = exp(-t_) * sin(pi * x_) * sin(pi * y_) + source = (2pi^2 + k - 1) * exp(-t) * sin(pi * x) * sin(pi * y) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) - k * u(t, x, y) + source + sol = solve_square(eq, unit_square(celltype, 16), ref, 2, sin(pi * x) * sin(pi * y), 0.1) + @test l2_error(sol, u(t, x, y), (x_, y_) -> exact(0.1, x_, y_), 0.1, sample_points(40), sample_points(40)) < 1.0e-4 +end + +# PDE: u_t = u_xx - k u, with k = 3 (no source) +# Domain: x in (0, 1), t in (0, 0.2), meshes of 2, 4, 8 and 16 line cells +# BCs: u(t, 0) = u(t, 1) = 0; IC u(0, x) = sin(pi x) +# Exact: u = exp(-(pi^2 + k) t) sin(pi x): the reaction only speeds up the decay of the heat eigenmode +# Shows: P2 elements converge at rate 3 and the reaction coefficient enters the decay rate. +@testset "P2 elements on a line converge at rate 3 for the decay-reaction heat equation" begin + k, tend = 3.0, 0.2 + ns = (2, 4, 8, 16) + 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) ~ 0, u(t, right) ~ 0, u(0, x) ~ sin(pi * x)] + @named pdesys = PDESystem([Dt(u(t, x)) ~ Dx(Dx(u(t, x))) - k * u(t, x)], bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-11, reltol = 1.0e-11) + l2_error(sol, u(t, x), x_ -> exp(-(pi^2 + k) * tend) * sin(pi * x_), tend, sample_points(200)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end + +# PDE: u_t = u_xx + a (v - u) + f_u, v_t = D v_xx - a (v - u) + f_v, with a = 2, D = 0.5 +# (two fields coupled linearly through the reaction) +# Domain: x in (0, 1), t in (0, 1), 4 line cells +# BCs: u = v = g(t, x) at both ends (time-dependent Dirichlet); IC from the exact solution +# Exact: u = x^2 + t, v = 1 + x^2 - t x^2, both in the P2 space, so f_u and f_v follow from the equations +# Shows: coupled multi-field reaction-diffusion with a source in each field is solved exactly. +@testset "two linearly coupled fields are reproduced exactly by P2 elements" begin + a, D = 2.0, 0.5 + u_exact(t_, x_) = x_^2 + t_ + v_exact(t_, x_) = 1 + x_^2 - t_ * x_^2 + Ω = MeshDomain(generate_grid(Line, (4,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + ue, ve = x^2 + t, 1 + x^2 - t * x^2 + f_u = 1 - 2 - a * (ve - ue) + f_v = -x^2 - D * (2 - 2t) + a * (ve - ue) + eqs = [ + Dt(u(t, x)) ~ Dx(Dx(u(t, x))) + a * (v(t, x) - u(t, x)) + f_u, + Dt(v(t, x)) ~ D * Dx(Dx(v(t, x))) - a * (v(t, x) - u(t, x)) + f_v, + ] + bcs = [ + u(t, left) ~ u_exact(t, 0), u(t, right) ~ u_exact(t, 1), u(0, x) ~ u_exact(0, x), + v(t, left) ~ v_exact(t, 0), v(t, right) ~ v_exact(t, 1), v(0, x) ~ v_exact(0, x), + ] + @named pdesys = PDESystem(eqs, bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x], [u(t, x), v(t, x)], []) + P2 = Lagrange{RefLine, 2}() + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => P2, v => P2))), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + @test l2_error(sol, u(t, x), x_ -> u_exact(1.0, x_), 1.0, sample_points(40)) < 1.0e-7 + @test l2_error(sol, v(t, x), x_ -> v_exact(1.0, x_), 1.0, sample_points(40)) < 1.0e-7 +end + +# PDE: u_t = u_xx + u_yy + u (1 - u) (a nonlinear, logistic reaction) +# Shows: state-dependent sources are named in the error rather than silently linearised (M3). +@testset "a nonlinear reaction term is rejected naming milestone M3" begin + Ω = unit_square(Triangle, 2) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + u(t, x, y) * (1 - u(t, x, y)) + bcs = [[u(t, Γ) ~ 0 for Γ in sides(Ω)]; u(0, x, y) ~ 0] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_throws "nonlinear terms land in M3" discretize(pdesys, FEMDiscretization(Ω, t)) +end diff --git a/test/Interface/source_terms.jl b/test/Interface/source_terms.jl new file mode 100644 index 00000000..706716d7 --- /dev/null +++ b/test/Interface/source_terms.jl @@ -0,0 +1,72 @@ +# The heat equation with a manufactured source term f(t, x, ...): the source is chosen so that a +# non-trivial exact solution (oscillating in time, non-zero on the boundary) solves the equation, and the +# exact solution is recovered from the PDESystem through the full interface. +# docs/src/equation_classes.md, Tier 1: second-order parabolic equations, with time-dependent Dirichlet data +# (VERIFIED); sources that depend on (t, x) only are plain right-hand-side terms, not state-dependent ones. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Triangle, Quadrilateral, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# PDE: u_t = u_xx + f +# Domain: x in (0, 1), t in (0, 1), meshes of 4, 8 and 16 line cells +# BCs: u = g(t, x) at both ends (time-dependent Dirichlet, from the exact solution); IC u(0, x) = g(0, x) +# Exact: u = sin(3t) cos(pi x), so f = 3 cos(3t) cos(pi x) + pi^2 sin(3t) cos(pi x) +# Shows: the solution is not zero at the boundary and changes sign in time, yet P1 and P2 recover it at rates 2 and 3. +@testset "the 1D heat equation with a manufactured source recovers the exact solution at the optimal rate for $name" for (name, order, rate) in ( + ("P1", 1, 1.9), ("P2", 2, 2.8), + ) + ns = (4, 8, 16) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + source = 3cos(3t) * cos(pi * x) + pi^2 * sin(3t) * cos(pi * x) + bcs = [u(t, left) ~ sin(3t), u(t, right) ~ -sin(3t), u(0, x) ~ 0] + @named pdesys = PDESystem([Dt(u(t, x)) ~ Dx(Dx(u(t, x))) + source], bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, order}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + l2_error(sol, u(t, x), x_ -> sin(3) * cos(pi * x_), 1.0, sample_points(200)) + end + @test all(observed_rate(errors, 1 ./ ns) .> rate) +end + +# PDE: u_t = u_xx + u_yy + f +# Domain: the unit square, t in (0, 1), meshes of 2, 4 and 8 cells per side +# BCs: u = g(t, x, y) on all four sides (time-dependent Dirichlet, from the exact solution); IC u(0, x, y) = g(0, x, y) +# Exact: u = cos(t) exp(x + y), so f = -sin(t) exp(x + y) - 2 cos(t) exp(x + y) +# Shows: P2 elements recover a solution that is in no element space at the optimal rate 3, on both cell shapes. +@testset "the 2D heat equation with a manufactured source converges at rate 3 on $name meshes" for (name, celltype, ref) in ( + ("triangle", Triangle, RefTriangle), ("quadrilateral", Quadrilateral, RefQuadrilateral), + ) + ns = (2, 4, 8) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(celltype, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + source = (-sin(t) - 2cos(t)) * exp(x + y) + bcs = [[u(t, Γ) ~ cos(t) * exp(x + y) for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))]; u(0, x, y) ~ exp(x + y)] + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + source + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{ref, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + l2_error(sol, u(t, x, y), (x_, y_) -> cos(1.0) * exp(x_ + y_), 1.0, sample_points(40), sample_points(40)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 2.7) +end + +# PDE: u_t = u_xx + u_yy + f +# Domain: the unit square, t in (0, 1), 4 x 4 triangle cells +# BCs: u = t^2 (1 + x^2 + y^2) on all four sides; IC u(0, x, y) = 0 +# Exact: u = t^2 (1 + x^2 + y^2), so f = 2t (1 + x^2 + y^2) - 4 t^2, in the P2 space for every t +# Shows: a source that is quadratic in time and space is reproduced to the solver tolerance. +@testset "a polynomial manufactured solution is reproduced exactly by P2 elements" begin + Ω = MeshDomain(generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0))) + source = 2t * (1 + x^2 + y^2) - 4t^2 + bcs = [[u(t, Γ) ~ t^2 * (1 + x^2 + y^2) for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))]; u(0, x, y) ~ 0] + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + source + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + @test l2_error(sol, u(t, x, y), (x_, y_) -> 1 + x_^2 + y_^2, 1.0, sample_points(20), sample_points(20)) < 1.0e-7 +end diff --git a/test/Interface/variable_coefficient_diffusion.jl b/test/Interface/variable_coefficient_diffusion.jl new file mode 100644 index 00000000..2fdf5bfa --- /dev/null +++ b/test/Interface/variable_coefficient_diffusion.jl @@ -0,0 +1,95 @@ +# Diffusion with a space-dependent diffusivity a(x), in the two forms the front end accepts: divergence +# form Dx(a Dx(u)) and non-divergence form a Dxx(u), with manufactured solutions and sources. +# docs/src/equation_classes.md, Tier 1: "Second-order parabolic equations in divergence or non-divergence +# form" (VERIFIED, non-divergence `a(x,y) Δu` at rates 1.96 to 2.01). Coefficients that depend on time or on +# the solution are rejected (M3), and discontinuous coefficients across interfaces are "not evidenced", +# so a(x) here is smooth and depends on space only. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Triangle, Quadrilateral, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# The warning the front end gives when integration by parts of a(x) u_xx produces product-rule terms. +const warning = r"product-rule correction terms" + +# Solves `eq` for u on a line of n cells with u = 0 at both ends and IC sin(pi x); returns the error at tend. +function error_1d(eq, n, tend) + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + bcs = [u(t, left) ~ 0, u(t, right) ~ 0, u(0, x) ~ sin(pi * x)] + @named pdesys = PDESystem([eq], bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-11, reltol = 1.0e-11) + return l2_error(sol, u(t, x), x_ -> exp(-tend) * sin(pi * x_), tend, sample_points(200)) +end + +# Same on the unit square for the exact solution exp(-t) sin(pi x) sin(pi y). +function error_2d(eq, celltype, ref, n, tend) + Ω = MeshDomain(generate_grid(celltype, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + bcs = [[u(t, Γ) ~ 0 for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))]; u(0, x, y) ~ sin(pi * x) * sin(pi * y)] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{ref, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + return l2_error(sol, u(t, x, y), (x_, y_) -> exp(-tend) * sin(pi * x_) * sin(pi * y_), tend, sample_points(40), sample_points(40)) +end + +# PDE: u_t = (a u_x)_x + f, with a(x) = 1 + x (divergence form) +# Domain: x in (0, 1), t in (0, 0.2), meshes of 4, 8 and 16 line cells +# BCs: u = 0 at both ends; IC u(0, x) = sin(pi x) +# Exact: u = exp(-t) sin(pi x), so f = u_t - a_x u_x - a u_xx = exp(-t) (-sin(pi x) - pi cos(pi x) + (1 + x) pi^2 sin(pi x)) +# Shows: P2 elements converge at rate 3; the product rule on a(x) u_x is applied by the front end. +@testset "divergence-form diffusion with a(x) = 1 + x converges at rate 3 on a line" begin + source = exp(-t) * (-sin(pi * x) - pi * cos(pi * x) + (1 + x) * pi^2 * sin(pi * x)) + ns = (4, 8, 16) + errors = [error_1d(Dt(u(t, x)) ~ Dx((1 + x) * Dx(u(t, x))) + source, n, 0.2) for n in ns] + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end + +# PDE: u_t = a u_xx + f, with a(x) = 1 + x (non-divergence form) +# Domain: x in (0, 1), t in (0, 0.2), meshes of 4, 8 and 16 line cells +# BCs: u = 0 at both ends; IC u(0, x) = sin(pi x) +# Exact: u = exp(-t) sin(pi x), so f = u_t - a u_xx = exp(-t) (-1 + (1 + x) pi^2) sin(pi x) +# Shows: P2 elements converge at rate 3; the same exact solution needs a different source than in divergence form, +# and the front end warns that the product-rule terms make the stiffness matrix non-symmetric. +@testset "non-divergence-form diffusion with a(x) = 1 + x converges at rate 3 on a line" begin + source = exp(-t) * (-1 + (1 + x) * pi^2) * sin(pi * x) + ns = (4, 8, 16) + errors = @test_logs (:warn, warning) match_mode = :any [error_1d(Dt(u(t, x)) ~ (1 + x) * Dx(Dx(u(t, x))) + source, n, 0.2) for n in ns] + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end + +# PDE: u_t = (a u_x)_x + (a u_y)_y + f, with a(x, y) = 1 + x + y (divergence form) +# Domain: the unit square, t in (0, 0.1), meshes of 2, 4 and 8 cells per side +# BCs: u = 0 on all four sides; IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = exp(-t) sin(pi x) sin(pi y); with a_x = a_y = 1, f = u_t - a Laplace(u) - u_x - u_y +# Shows: P2 elements converge at rate 3 on triangles and quadrilaterals. +@testset "divergence-form diffusion with a(x, y) = 1 + x + y converges at rate 3 on $name meshes" for (name, celltype, ref) in ( + ("triangle", Triangle, RefTriangle), ("quadrilateral", Quadrilateral, RefQuadrilateral), + ) + a = 1 + x + y + s = exp(-t) + source = s * (-sin(pi * x) * sin(pi * y) + 2pi^2 * a * sin(pi * x) * sin(pi * y) - pi * cos(pi * x) * sin(pi * y) - pi * sin(pi * x) * cos(pi * y)) + eq = Dt(u(t, x, y)) ~ Dx(a * Dx(u(t, x, y))) + Dy(a * Dy(u(t, x, y))) + source + ns = (2, 4, 8) + errors = [error_2d(eq, celltype, ref, n, 0.1) for n in ns] + @test all(observed_rate(errors, 1 ./ ns) .> 2.7) +end + +# PDE: u_t = a (u_xx + u_yy) + f, with a(x, y) = 1 + x + y (non-divergence form) +# Domain: the unit square, t in (0, 0.1), meshes of 2, 4 and 8 cells per side +# BCs: u = 0 on all four sides; IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = exp(-t) sin(pi x) sin(pi y), so f = (-1 + 2 pi^2 a) u +# Shows: P2 elements converge at rate 3 on triangles and quadrilaterals, with the same product-rule warning. +@testset "non-divergence-form diffusion with a(x, y) = 1 + x + y converges at rate 3 on $name meshes" for (name, celltype, ref) in ( + ("triangle", Triangle, RefTriangle), ("quadrilateral", Quadrilateral, RefQuadrilateral), + ) + a = 1 + x + y + source = exp(-t) * (-1 + 2pi^2 * a) * sin(pi * x) * sin(pi * y) + eq = Dt(u(t, x, y)) ~ a * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) + source + ns = (2, 4, 8) + errors = @test_logs (:warn, warning) match_mode = :any [error_2d(eq, celltype, ref, n, 0.1) for n in ns] + @test all(observed_rate(errors, 1 ./ ns) .> 2.7) +end From 28e347086fa356ae5556e14a48f62b2ed2107431 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 18:12:04 +0000 Subject: [PATCH 03/12] Add theme B rows to the Interface README case table Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/Interface/README.md b/test/Interface/README.md index 3588056c..0396d52f 100644 --- a/test/Interface/README.md +++ b/test/Interface/README.md @@ -50,6 +50,21 @@ boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D a | `solution_access.jl` | `sol(t, x, y; dv)` points, grids, outside the mesh | heat | 2 | P2 | Dirichlet | | `solution_access.jl` | derivative and trace keys | heat | 2 | P2 | Dirichlet | | `solution_access.jl` | parameter values set the diffusivity | heat | 2 | P2 | Dirichlet | +| `advection_diffusion.jl` | exact reproduction with constant velocity | advection-diffusion with source | 1 | P2 | time-dependent Dirichlet | +| `advection_diffusion.jl` | P2 convergence rate 3 with manufactured source | advection-diffusion with source | 1 | P2 | zero Dirichlet | +| `advection_diffusion.jl` | exact reproduction with velocity vector on triangles and quadrilaterals | advection-diffusion with source | 2 | P2 | time-dependent Dirichlet | +| `advection_diffusion.jl` | P2 convergence rate 3 with manufactured source | advection-diffusion with source | 2 | P2 | zero Dirichlet | +| `reaction_diffusion.jl` | linear reaction with source on triangles and quadrilaterals | reaction-diffusion | 2 | P2 | zero Dirichlet | +| `reaction_diffusion.jl` | decay reaction, P2 convergence rate 3 | reaction-diffusion | 1 | P2 | zero Dirichlet | +| `reaction_diffusion.jl` | two linearly coupled fields, exact | coupled reaction-diffusion | 1 | P2 | time-dependent Dirichlet | +| `reaction_diffusion.jl` | nonlinear reaction rejected (M3) | logistic reaction-diffusion | 2 | P1 | zero Dirichlet | +| `variable_coefficient_diffusion.jl` | `Dx(a Dx(u))`, rate 3 | divergence-form diffusion | 1 | P2 | zero Dirichlet | +| `variable_coefficient_diffusion.jl` | `a Dxx(u)`, rate 3 | non-divergence-form diffusion | 1 | P2 | zero Dirichlet | +| `variable_coefficient_diffusion.jl` | `Dx(a Dx(u)) + Dy(a Dy(u))`, rate 3, triangles and quadrilaterals | divergence-form diffusion | 2 | P2 | zero Dirichlet | +| `variable_coefficient_diffusion.jl` | `a (Dxx(u) + Dyy(u))`, rate 3, triangles and quadrilaterals | non-divergence-form diffusion | 2 | P2 | zero Dirichlet | +| `source_terms.jl` | manufactured source, rates 2 and 3 | heat with source | 1 | P1, P2 | time-dependent Dirichlet | +| `source_terms.jl` | manufactured source, rate 3, triangles and quadrilaterals | heat with source | 2 | P2 | time-dependent Dirichlet | +| `source_terms.jl` | polynomial solution, exact | heat with source | 2 | P2 | time-dependent Dirichlet | | `rejections.jl` | rejected boundary conditions, equations, options, domains, shared facets | heat | 1 to 2 | | | ## Not covered on this branch From 0dcf56975e629a56b3715d9fac632b85735830e9 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 18:25:06 +0000 Subject: [PATCH 04/12] Add 3D heat, element order and solver choice interface tests Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/element_order.jl | 61 +++++++++++++++++++++++++++ test/Interface/heat_3d.jl | 72 ++++++++++++++++++++++++++++++++ test/Interface/solver_choices.jl | 71 +++++++++++++++++++++++++++++++ 3 files changed, 204 insertions(+) create mode 100644 test/Interface/element_order.jl create mode 100644 test/Interface/heat_3d.jl create mode 100644 test/Interface/solver_choices.jl diff --git a/test/Interface/element_order.jl b/test/Interface/element_order.jl new file mode 100644 index 00000000..c6bd95a3 --- /dev/null +++ b/test/Interface/element_order.jl @@ -0,0 +1,61 @@ +# The same smooth problem solved with elements of increasing polynomial order, showing the observed +# L2 convergence rate equal to order + 1 on a refinement sequence. P1 and P2 are available in 1D and +# 2D; P3 is available on triangles and quadrilaterals (Ferrite has no cubic Lagrange line). +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Triangle, Quadrilateral, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# L2 error at t = 0.1 of the 1D eigenmode on `n` line cells. +function eigenmode_error_1d(n, order) + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + bcs = [u(t, left) ~ 0, u(t, right) ~ 0, u(0, x) ~ sin(pi * x)] + @named pdesys = PDESystem([Dt(u(t, x)) ~ Dx(Dx(u(t, x)))], bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, order}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + return l2_error(sol, u(t, x), x_ -> exp(-pi^2 * 0.1) * sin(pi * x_), 0.1, sample_points(200)) +end + +# L2 error at t = 0.05 of the 2D eigenmode on an `n` x `n` mesh of `celltype`. +function eigenmode_error_2d(celltype, ref, n, order) + Ω = MeshDomain(generate_grid(celltype, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + bcs = [[u(t, Γ) ~ 0 for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))]; u(0, x, y) ~ sin(pi * x) * sin(pi * y)] + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.05)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{ref, order}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + exact(x_, y_) = exp(-2pi^2 * 0.05) * sin(pi * x_) * sin(pi * y_) + return l2_error(sol, u(t, x, y), exact, 0.05, sample_points(40), sample_points(40)) +end + +# PDE: u_t = u_xx +# Domain: x in (0, 1), t in (0, 0.1), meshes of 2, 4, 8 and 16 line cells +# BCs: u(t, 0) = u(t, 1) = 0 (constant Dirichlet); IC u(0, x) = sin(pi x) +# Exact: u = exp(-pi^2 t) sin(pi x) +# Shows: on a line the L2 rate is order + 1: about 2 for P1 and about 3 for P2. +@testset "$name elements on a line converge at rate $(order + 1)" for (name, order) in (("P1", 1), ("P2", 2)) + ns = (2, 4, 8, 16) + errors = [eigenmode_error_1d(n, order) for n in ns] + @test issorted(errors; rev = true) + @test all(observed_rate(errors, 1 ./ ns)[2:end] .> order + 0.85) +end + +shapes = (("triangle", Triangle, RefTriangle), ("quadrilateral", Quadrilateral, RefQuadrilateral)) +orders = (("P1", 1), ("P2", 2), ("P3", 3)) + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 0.05), meshes of 2, 4 and 8 cells per side +# BCs: u = 0 on all four sides (constant Dirichlet); IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = exp(-2 pi^2 t) sin(pi x) sin(pi y) +# Shows: on triangles and quadrilaterals the L2 rate is order + 1 for P1, P2 and P3; the finest +# pair of meshes is in the asymptotic range, so only its rate is checked. +@testset "$name elements converge at rate $(order + 1) on $shape meshes" for (shape, celltype, ref) in shapes, (name, order) in orders + ns = order == 1 ? (4, 8, 16) : (2, 4, 8) + errors = [eigenmode_error_2d(celltype, ref, n, order) for n in ns] + @test issorted(errors; rev = true) + @test last(observed_rate(errors, 1 ./ ns)) > order + 0.85 +end diff --git a/test/Interface/heat_3d.jl b/test/Interface/heat_3d.jl new file mode 100644 index 00000000..102e0e79 --- /dev/null +++ b/test/Interface/heat_3d.jl @@ -0,0 +1,72 @@ +# The 3D heat equation through the full interface on a hexahedron mesh and on a tetrahedron mesh, in +# P1 and P2 elements, compared with exact solutions. Meshes are kept to a few cells per side because +# 3D degrees of freedom grow fast; the cases still check every step of the workflow in three dimensions. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Tetrahedron, Hexahedron, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y z u(..) +Dt, Dx, Dy, Dz = Differential(t), Differential(x), Differential(y), Differential(z) +heat = Dt(u(t, x, y, z)) ~ Dx(Dx(u(t, x, y, z))) + Dy(Dy(u(t, x, y, z))) + Dz(Dz(u(t, x, y, z))) + +unit_cube(celltype, n) = MeshDomain(generate_grid(celltype, (n, n, n), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0))) +faces(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top, :front, :back)) + +# Solves `heat` on Ω with the given element space and boundary and initial conditions to `tend`. +function solve_heat_3d(Ω, space, bcs, tend) + domains = [(x, y, z) ∈ Ω, t ∈ Interval(0.0, tend)] + @named pdesys = PDESystem([heat], bcs, domains, [t, x, y, z], [u(t, x, y, z)], []) + prob = discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => space))) + return solve(prob, DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# L2 error at `tend` of the decaying eigenmode sin(pi x) sin(pi y) sin(pi z) with zero Dirichlet data. +function eigenmode_error(celltype, space, n, tend) + Ω = unit_cube(celltype, n) + bcs = [[u(t, Γ) ~ 0 for Γ in faces(Ω)]; u(0, x, y, z) ~ sin(pi * x) * sin(pi * y) * sin(pi * z)] + sol = solve_heat_3d(Ω, space, bcs, tend) + exact(x_, y_, z_) = exp(-3pi^2 * tend) * sin(pi * x_) * sin(pi * y_) * sin(pi * z_) + points = sample_points(11) + return l2_error(sol, u(t, x, y, z), exact, tend, points, points, points) +end + +# PDE: u_t = u_xx + u_yy + u_zz +# Domain: the unit cube, t in (0, 0.02); 4 cells per side for P1, 2 for P2 +# BCs: u = 0 on all six faces (constant Dirichlet); IC u(0, x, y, z) = sin(pi x) sin(pi y) sin(pi z) +# Exact: u = exp(-3 pi^2 t) sin(pi x) sin(pi y) sin(pi z) +# Shows: the decaying eigenmode is reproduced by P1 and P2 elements on hexahedra and on tetrahedra. +@testset "the 3D heat equation with zero Dirichlet data decays as its eigenmode on $name meshes" for (name, celltype, ref, order, n, tol) in ( + ("P1 hexahedron", Hexahedron, RefHexahedron, 1, 4, 5.0e-2), ("P2 hexahedron", Hexahedron, RefHexahedron, 2, 2, 1.2e-2), + ("P1 tetrahedron", Tetrahedron, RefTetrahedron, 1, 4, 8.0e-2), ("P2 tetrahedron", Tetrahedron, RefTetrahedron, 2, 2, 4.0e-2), + ) + @test eigenmode_error(celltype, Lagrange{ref, order}(), n, 0.02) < tol +end + +# PDE: u_t = u_xx + u_yy + u_zz +# Domain: the unit cube, t in (0, 1), 2 cells per side +# BCs: u = x^2 + y^2 + z^2 + 6t on all six faces (time-dependent Dirichlet); IC u(0, x, y, z) = x^2 + y^2 + z^2 +# Exact: u = x^2 + y^2 + z^2 + 6t, which lies in the P2 space, so the error is the solver tolerance +# Shows: time-dependent Dirichlet data is imposed at every time in 3D, on both cell shapes. +@testset "time-dependent Dirichlet data is reproduced exactly by P2 elements on $name meshes" for (name, celltype, ref) in ( + ("hexahedron", Hexahedron, RefHexahedron), ("tetrahedron", Tetrahedron, RefTetrahedron), + ) + Ω = unit_cube(celltype, 2) + bcs = [[u(t, Γ) ~ x^2 + y^2 + z^2 + 6t for Γ in faces(Ω)]; u(0, x, y, z) ~ x^2 + y^2 + z^2] + sol = solve_heat_3d(Ω, Lagrange{ref, 2}(), bcs, 1.0) + points = sample_points(7) + @test l2_error(sol, u(t, x, y, z), (x_, y_, z_) -> x_^2 + y_^2 + z_^2 + 6, 1.0, points, points, points) < 1.0e-7 +end + +# PDE: u_t = u_xx + u_yy + u_zz +# Domain: the unit cube, t in (0, 0.02), meshes of 4, 8, 16 (P1 hexahedra) or 2, 3, 4 (P2 tetrahedra) cells per side +# BCs: u = 0 on all six faces (constant Dirichlet); IC u(0, x, y, z) = sin(pi x) sin(pi y) sin(pi z) +# Exact: u = exp(-3 pi^2 t) sin(pi x) sin(pi y) sin(pi z) +# Shows: the optimal L2 rates order + 1 hold in 3D; the coarsest mesh is pre-asymptotic, so the finest pair is checked. +@testset "$name elements converge at rate $(order + 1) for the 3D heat equation" for (name, celltype, ref, order, ns) in ( + ("P1 hexahedron", Hexahedron, RefHexahedron, 1, (4, 8, 16)), ("P2 tetrahedron", Tetrahedron, RefTetrahedron, 2, (2, 3, 4)), + ) + errors = [eigenmode_error(celltype, Lagrange{ref, order}(), n, 0.02) for n in ns] + @test issorted(errors; rev = true) + @test last(observed_rate(errors, 1 ./ ns)) > order + 0.85 +end diff --git a/test/Interface/solver_choices.jl b/test/Interface/solver_choices.jl new file mode 100644 index 00000000..27b80fae --- /dev/null +++ b/test/Interface/solver_choices.jl @@ -0,0 +1,71 @@ +# One problem solved with each DAE solver that the test environment offers. `discretize` returns a +# DAEProblem, so the choices are the implicit-form BDF methods of OrdinaryDiffEqBDF (DFBDF, DABDF2, +# DImplicitEuler); ODE solvers are refused by `solve`. Rodas5P and IDA are not in the test environment. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x u(..) +Dt, Dx = Differential(t), Differential(x) + +# u_t = u_xx on 16 line cells in P2 elements, t in (0, 0.1), with Dirichlet data `g(t, x)` at both ends +# and initial condition `initial(x)`. +function heat_problem(g, initial) + Ω = MeshDomain(generate_grid(Line, (16,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + eqs = [Dt(u(t, x)) ~ Dx(Dx(u(t, x)))] + bcs = [u(t, left) ~ g(t, 0), u(t, right) ~ g(t, 1), u(0, x) ~ initial(x)] + @named pdesys = PDESystem(eqs, bcs, [(x,) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x], [u(t, x)], []) + return discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, 2}()))) +end +eigenmode_problem() = heat_problem((t_, x_) -> 1, x_ -> 1 + sin(pi * x_)) +eigenmode(x_) = 1 + exp(-pi^2 * 0.1) * sin(pi * x_) +parabola_problem() = heat_problem((t_, x_) -> x_^2 + 2t_, x_ -> x_^2) + +# PDE: u_t = u_xx +# Domain: x in (0, 1), t in (0, 0.1), 16 line cells +# BCs: u(t, 0) = u(t, 1) = 1 (constant Dirichlet); IC u(0, x) = 1 + sin(pi x) +# Exact: u = 1 + exp(-pi^2 t) sin(pi x) +# Shows: every DAE solver reaches the same spatial error (set by the mesh, not the solver) from one problem. +@testset "the DAE solver $name solves the heat equation to the spatial error of the mesh" for (name, alg) in ( + ("DFBDF", DFBDF()), ("DABDF2", DABDF2()), ("DImplicitEuler", DImplicitEuler()), + ("DFBDF of order 2", DFBDF(max_order = Val(2))), + ) + sol = solve(eigenmode_problem(), alg; abstol = 1.0e-10, reltol = 1.0e-10) + @test sol.retcode == SciMLBase.ReturnCode.Success + @test l2_error(sol, u(t, x), eigenmode, 0.1, sample_points(100)) < 2.0e-4 +end + +# PDE: u_t = u_xx +# Domain: x in (0, 1), t in (0, 0.1), 16 line cells +# BCs: u(t, 0) = u(t, 1) = 1 (constant Dirichlet); IC u(0, x) = 1 + sin(pi x) +# Exact: u = 1 + exp(-pi^2 t) sin(pi x) +# Shows: tolerances are ordinary solve keywords: tightening them lowers the error down to the spatial error. +@testset "looser solver tolerances give a larger error than tight ones" begin + error_at(tol) = l2_error(solve(eigenmode_problem(), DFBDF(); abstol = tol, reltol = tol), u(t, x), eigenmode, 0.1, sample_points(100)) + @test error_at(1.0e-3) > error_at(1.0e-10) + @test error_at(1.0e-10) < 2.0e-4 +end + +# PDE: u_t = u_xx +# Domain: x in (0, 1), t in (0, 0.1), 16 line cells +# BCs: u(t, 0) = 2t, u(t, 1) = 1 + 2t (time-dependent Dirichlet); IC u(0, x) = x^2 +# Exact: u = x^2 + 2t +# Shows: `saveat` chooses the output times and the solution holds the Dirichlet data at both ends at each of them. +@testset "saveat controls the stored times and the boundary value is held at each" begin + times = collect(0.0:0.025:0.1) + sol = solve(parabola_problem(), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10, saveat = times) + @test sol.t ≈ times + @test all(abs(sol(tk, 0.0; dv = u(t, x)) - 2tk) < 1.0e-6 for tk in times) + @test all(abs(sol(tk, 1.0; dv = u(t, x)) - (1 + 2tk)) < 1.0e-6 for tk in times) +end + +# PDE: u_t = u_xx +# Domain: x in (0, 1), t in (0, 0.1), 16 line cells +# BCs: u(t, 0) = 2t, u(t, 1) = 1 + 2t (time-dependent Dirichlet) +# Exact: none; an ODE solver is not valid for the DAEProblem +# Shows: an ODE solver such as FBDF is refused with SciMLBase's pairing message, not a wrong answer. +@testset "an ODE solver is refused for the DAE problem" begin + @test_throws "Incompatible problem+solver pairing" solve(parabola_problem(), FBDF()) +end From ada3c35d0d1ba942dcb35322cf4775a01261aeda Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 18:25:06 +0000 Subject: [PATCH 05/12] Interface README: rows for heat_3d, element_order and solver_choices Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/Interface/README.md b/test/Interface/README.md index 3588056c..16837601 100644 --- a/test/Interface/README.md +++ b/test/Interface/README.md @@ -50,6 +50,14 @@ boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D a | `solution_access.jl` | `sol(t, x, y; dv)` points, grids, outside the mesh | heat | 2 | P2 | Dirichlet | | `solution_access.jl` | derivative and trace keys | heat | 2 | P2 | Dirichlet | | `solution_access.jl` | parameter values set the diffusivity | heat | 2 | P2 | Dirichlet | +| `heat_3d.jl` | eigenmode decay on hexahedra and tetrahedra | heat | 3 | P1, P2 | zero Dirichlet | +| `heat_3d.jl` | exact reproduction by P2 | heat | 3 | P2 | time-dependent Dirichlet | +| `heat_3d.jl` | P1 hexahedra rate 2, P2 tetrahedra rate 3 | heat | 3 | P1, P2 | zero Dirichlet | +| `element_order.jl` | line P1, P2 rates 2 and 3 | heat | 1 | P1, P2 | zero Dirichlet | +| `element_order.jl` | triangle and quadrilateral P1, P2, P3 rates 2, 3, 4 | heat | 2 | P1, P2, P3 | zero Dirichlet | +| `solver_choices.jl` | DFBDF, DABDF2, DImplicitEuler, DFBDF order 2 | heat | 1 | P2 | constant Dirichlet | +| `solver_choices.jl` | tolerances and `saveat` | heat | 1 | P2 | constant and time-dependent Dirichlet | +| `solver_choices.jl` | ODE solver refused for the DAE problem | heat | 1 | P2 | time-dependent Dirichlet | | `rejections.jl` | rejected boundary conditions, equations, options, domains, shared facets | heat | 1 to 2 | | | ## Not covered on this branch From 70c094e697d61a1abf5e36dcfe40bdd6dacccd22 Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 18:29:19 +0000 Subject: [PATCH 06/12] Add Interface cases: coupled systems, first-order wave, mesh domains, curved geometry, parameters Five self-contained files in the Interface group, each case narrated with its PDE, domain, boundary conditions and exact solution. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/coupled_systems.jl | 125 +++++++++++++++++++++++++++++ test/Interface/curved_geometry.jl | 74 +++++++++++++++++ test/Interface/mesh_domains.jl | 96 ++++++++++++++++++++++ test/Interface/parameters.jl | 71 ++++++++++++++++ test/Interface/wave_first_order.jl | 75 +++++++++++++++++ 5 files changed, 441 insertions(+) create mode 100644 test/Interface/coupled_systems.jl create mode 100644 test/Interface/curved_geometry.jl create mode 100644 test/Interface/mesh_domains.jl create mode 100644 test/Interface/parameters.jl create mode 100644 test/Interface/wave_first_order.jl diff --git a/test/Interface/coupled_systems.jl b/test/Interface/coupled_systems.jl new file mode 100644 index 00000000..7bb6c22a --- /dev/null +++ b/test/Interface/coupled_systems.jl @@ -0,0 +1,125 @@ +# Coupled two-field systems through the full interface: two dependent variables u and v of equal order, each +# with its own equation, boundary conditions and initial condition, coupled through the right-hand sides. +# `spaces` names a Lagrange space for each field; the solution is read per field with `dv`. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Triangle, Quadrilateral, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@parameters a b +@variables x y u(..) v(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +U, V = u(t, x, y), v(t, x, y) +laplacian(f) = Dx(Dx(f)) + Dy(Dy(f)) + +unit_square(celltype, n) = MeshDomain(generate_grid(celltype, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + +# Solves the system `eqs` for (u, v) on Ω with conditions `bcs` to `tend`, both fields in `space`. +function solve_pair(eqs, bcs, Ω, space, tend, ps = []) + domains = [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)] + @named pdesys = PDESystem(eqs, bcs, domains, [t, x, y], [U, V], ps) + prob = discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => space, v => space))) + return solve(prob, DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# PDE: u_t = Δu + a v + f1, v_t = Δv - b u + f2, with a = 2, b = 3 in `ps` +# Domain: the unit square, t in (0, 1), 4 x 4 triangle pairs, P2 for both fields +# BCs: u and v equal to their exact values on all four sides; ICs from the exact values at t = 0 +# Exact: u = x^2 + y^2 + t, v = x y + 2t; the sources f1, f2 are chosen so these solve the system +# Shows: the two fields are coupled in both directions (u feeds v and v feeds u), each is read back with +# its own `dv`, and a solution inside the element space is reproduced to the solver tolerance. +@testset "a bidirectionally coupled pair is reproduced exactly by P2 elements" begin + Ω = unit_square(Triangle, 4) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + u_exact, v_exact = x^2 + y^2 + t, x * y + 2t + eqs = [ + Dt(U) ~ laplacian(U) + a * V + (1 - 4 - a * v_exact), + Dt(V) ~ laplacian(V) - b * U + (2 + b * u_exact), + ] + bcs = [ + [u(t, Γ) ~ u_exact for Γ in sides]; [v(t, Γ) ~ v_exact for Γ in sides]; + u(0, x, y) ~ x^2 + y^2; v(0, x, y) ~ x * y + ] + sol = solve_pair(eqs, bcs, Ω, Lagrange{RefTriangle, 2}(), 1.0, [a => 2.0, b => 3.0]) + points = (sample_points(20), sample_points(20)) + @test l2_error(sol, U, (x_, y_) -> x_^2 + y_^2 + 1, 1.0, points...) < 1.0e-7 + @test l2_error(sol, V, (x_, y_) -> x_ * y_ + 2, 1.0, points...) < 1.0e-7 +end + +# PDE: u_t = Δu + v, v_t = Δv + u +# Domain: the unit square, t in (0, 0.05), 16 x 16 cells, P2 for both fields, triangles and quadrilaterals +# BCs: u = v = 0 on all four sides; IC u = sin(pi x) sin(pi y), v = 0 +# Exact: u = e^(-2 pi^2 t) cosh(t) φ, v = e^(-2 pi^2 t) sinh(t) φ with φ = sin(pi x) sin(pi y) +# Shows: the coupling u <-> v turns the single eigenmode φ into the pair (cosh t, sinh t), so a correct +# off-diagonal block gives v a nonzero amplitude although v starts at zero. +@testset "the coupled eigenmode pair (cosh, sinh) is followed on $name meshes" for (name, celltype, space) in ( + ("triangle", Triangle, Lagrange{RefTriangle, 2}()), ("quadrilateral", Quadrilateral, Lagrange{RefQuadrilateral, 2}()), + ) + Ω = unit_square(celltype, 16) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + eqs = [Dt(U) ~ laplacian(U) + V, Dt(V) ~ laplacian(V) + U] + bcs = [ + [u(t, Γ) ~ 0 for Γ in sides]; [v(t, Γ) ~ 0 for Γ in sides]; + u(0, x, y) ~ sin(pi * x) * sin(pi * y); v(0, x, y) ~ 0 + ] + sol = solve_pair(eqs, bcs, Ω, space, 0.05) + φ(x_, y_) = sin(pi * x_) * sin(pi * y_) + points = (sample_points(40), sample_points(40)) + @test l2_error(sol, U, (x_, y_) -> exp(-2pi^2 * 0.05) * cosh(0.05) * φ(x_, y_), 0.05, points...) < 1.0e-4 + @test l2_error(sol, V, (x_, y_) -> exp(-2pi^2 * 0.05) * sinh(0.05) * φ(x_, y_), 0.05, points...) < 1.0e-4 +end + +# PDE: u_t = Δu + v + f1, v_t = Δv + u + f2 +# Domain: the unit square, t in (0, 0.5), 4, 8 and 16 triangle pairs per side, P1 for both fields +# BCs: u and v equal to their exact values on all four sides +# Exact: u = e^(x + y + t), v = cos(x) e^(y - t) (not in the element space); f1, f2 from the equations +# Shows: each field of a coupled P1 system converges at the optimal L2 rate 2. +@testset "both fields of a coupled P1 system converge at rate 2" begin + u_exact, v_exact = exp(x + y + t), cos(x) * exp(y - t) + eqs = [ + Dt(U) ~ laplacian(U) + V + expand_derivatives(Dt(u_exact) - laplacian(u_exact) - v_exact), + Dt(V) ~ laplacian(V) + U + expand_derivatives(Dt(v_exact) - laplacian(v_exact) - u_exact), + ] + ns = (4, 8, 16) + errors = map(ns) do n + Ω = unit_square(Triangle, n) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + bcs = [ + [u(t, Γ) ~ u_exact for Γ in sides]; [v(t, Γ) ~ v_exact for Γ in sides]; + u(0, x, y) ~ exp(x + y); v(0, x, y) ~ cos(x) * exp(y) + ] + sol = solve_pair(eqs, bcs, Ω, Lagrange{RefTriangle, 1}(), 0.5) + points = (sample_points(50), sample_points(50)) + [ + l2_error(sol, U, (x_, y_) -> exp(x_ + y_ + 0.5), 0.5, points...), + l2_error(sol, V, (x_, y_) -> cos(x_) * exp(y_ - 0.5), 0.5, points...), + ] + end + @test all(observed_rate(first.(errors), 1 ./ ns) .> 1.9) + @test all(observed_rate(last.(errors), 1 ./ ns) .> 1.9) +end + +# PDE: u_t = Δu + a v + f1, v_t = Δv - b u + f2 (as in the first case) +# Domain: the unit square, t in (0, 1), P2 for both fields +# BCs: u Dirichlet on all sides; v Dirichlet on left and bottom, ∂ₙv = y on right and ∂ₙv = x on top (Neumann) +# Exact: u = x^2 + y^2 + t, v = x y + 2t +# Shows: each field has its own boundary conditions: a Neumann condition on v while u is held by Dirichlet data. +@testset "the two fields carry different kinds of boundary condition" begin + Ω = unit_square(Triangle, 4) + left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + u_exact, v_exact = x^2 + y^2 + t, x * y + 2t + eqs = [ + Dt(U) ~ laplacian(U) + a * V + (1 - 4 - a * v_exact), + Dt(V) ~ laplacian(V) - b * U + (2 + b * u_exact), + ] + bcs = [ + [u(t, Γ) ~ u_exact for Γ in (left, right, bottom, top)]; + v(t, left) ~ v_exact; v(t, bottom) ~ v_exact; + NormalDerivative(right)(v(t, right)) ~ y; NormalDerivative(top)(v(t, top)) ~ x; + u(0, x, y) ~ x^2 + y^2; v(0, x, y) ~ x * y + ] + sol = solve_pair(eqs, bcs, Ω, Lagrange{RefTriangle, 2}(), 1.0, [a => 2.0, b => 3.0]) + points = (sample_points(20), sample_points(20)) + @test l2_error(sol, U, (x_, y_) -> x_^2 + y_^2 + 1, 1.0, points...) < 1.0e-7 + @test l2_error(sol, V, (x_, y_) -> x_ * y_ + 2, 1.0, points...) < 1.0e-7 +end diff --git a/test/Interface/curved_geometry.jl b/test/Interface/curved_geometry.jl new file mode 100644 index 00000000..f836d4be --- /dev/null +++ b/test/Interface/curved_geometry.jl @@ -0,0 +1,74 @@ +# Curved geometry: a quarter annulus meshed with quadratic triangles (Ferrite's `QuadraticTriangle`), whose +# edges on the circles are arcs. The grid is built with Ferrite's public constructors; the discretization maps +# each cell isoparametrically, so the element spaces keep their optimal rates on the curved boundary. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: Ferrite, Grid, Node, QuadraticTriangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# The quarter annulus 1 <= r <= 2, 0 <= θ <= π/2 made of 2 n^2 quadratic triangles: an n x n grid of (r, θ) +# rectangles, each cut into two triangles. Every node, mid-side nodes included, sits at its (r, θ) position. +# Facet sets: "inner" (r = 1), "outer" (r = 2), "bottom" (y = 0) and "left" (x = 0). +function quarter_annulus(n) + m = 2n + 1 + node_index(i, j) = i + 1 + j * m + position(i, j) = Vec((1 + i / 2n) * cos(pi / 2 * j / 2n), (1 + i / 2n) * sin(pi / 2 * j / 2n)) + nodes = [Node(position(i, j)) for j in 0:(2n) for i in 0:(2n)] + cells = QuadraticTriangle[] + for a in 0:(n - 1), b in 0:(n - 1) + i, j = 2a, 2b + ids = (di, dj) -> node_index(i + di, j + dj) + push!(cells, QuadraticTriangle((ids(0, 0), ids(2, 0), ids(2, 2), ids(1, 0), ids(2, 1), ids(1, 1)))) + push!(cells, QuadraticTriangle((ids(0, 0), ids(2, 2), ids(0, 2), ids(1, 1), ids(1, 2), ids(0, 1)))) + end + grid = Grid(cells, nodes) + radius(p) = sqrt(p[1]^2 + p[2]^2) + Ferrite.addfacetset!(grid, "inner", p -> radius(p) ≈ 1) + Ferrite.addfacetset!(grid, "outer", p -> radius(p) ≈ 2) + Ferrite.addfacetset!(grid, "bottom", p -> abs(p[2]) < 1.0e-12) + Ferrite.addfacetset!(grid, "left", p -> abs(p[1]) < 1.0e-12) + return grid +end + +# L2 error of the field `dv` at time `t_end` over the annulus: the midpoint rule in (r, θ) with weight r dr dθ. +function annulus_l2_error(sol, dv, exact, t_end, n) + radii, angles = sample_points(n; lo = 1.0, hi = 2.0), sample_points(n; lo = 0.0, hi = pi / 2) + points = [Vec(r * cos(θ), r * sin(θ)) for r in radii for θ in angles] + weights = [r * step(radii) * step(angles) for r in radii for θ in angles] + return sqrt(sum(weights .* abs2.(sol(t_end, points; dv) .- exact.(points)))) +end + +# Solves u_t = Δu + f on the quarter annulus of `n` cells per direction in order-`order` elements. +function solve_annulus(n, order) + Ω = MeshDomain(quarter_annulus(n)) + inner, outer, bottom, left = boundarypiece.(Ω, (:inner, :outer, :bottom, :left)) + exact = (1 + t) * sin(x) * cos(y) + bcs = [ + u(t, inner) ~ exact, u(t, outer) ~ exact, u(t, left) ~ exact, + NormalDerivative(bottom)(u(t, bottom)) ~ 0, u(0, x, y) ~ sin(x) * cos(y), + ] + eqs = [Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + (3 + 2t) * sin(x) * cos(y)] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, order}())) + return solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# PDE: u_t = Δu + (3 + 2t) sin(x) cos(y) +# Domain: the quarter annulus 1 <= r <= 2, 0 <= θ <= π/2, t in (0, 0.5), 2 n^2 quadratic triangles, +# n = 4, 8, 16, with P1 or P2 elements; the arcs r = 1 and r = 2 are exact in the geometry +# BCs: u = (1 + t) sin(x) cos(y) on the arcs and on x = 0; ∂ₙu = 0 on y = 0 (which the exact solution satisfies) +# Exact: u = (1 + t) sin(x) cos(y), not in the element space +# Shows: a curved boundary, given by mid-side nodes, keeps the optimal L2 rates p + 1 (P1: 2, P2: 3), +# so the boundary is not approximated by chords. +@testset "$name elements keep the optimal rate on a quarter annulus with curved boundaries" for (name, order, rate) in (("P1", 1, 2), ("P2", 2, 3)) + ns = (4, 8, 16) + errors = map(ns) do n + sol = solve_annulus(n, order) + annulus_l2_error(sol, u(t, x, y), p -> 1.5 * sin(p[1]) * cos(p[2]), 0.5, 60) + end + @test issorted(errors; rev = true) + @test all(observed_rate(errors, 1 ./ ns) .> rate - 0.2) +end diff --git a/test/Interface/mesh_domains.jl b/test/Interface/mesh_domains.jl new file mode 100644 index 00000000..bd4fa11d --- /dev/null +++ b/test/Interface/mesh_domains.jl @@ -0,0 +1,96 @@ +# Mesh domains with named boundary pieces. A `MeshDomain` takes its pieces from the facet sets of the Ferrite +# grid: `boundarypiece(Ω, :name)` is the facet set "name". The sets come from `generate_grid`, from +# `Ferrite.addfacetset!` on a grid you build, or from the physical groups of a Gmsh mesh read with FerriteGmsh. +# Each piece then carries its own boundary condition. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: Ferrite, generate_grid, Triangle, Vec +using FerriteGmsh: FerriteGmsh +using Gmsh: Gmsh, gmsh +using ModelingToolkit: t_nounits as t + +@parameters k α +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +laplacian(f) = Dx(Dx(f)) + Dy(Dy(f)) + +# Writes a triangle mesh of the L-shape [0, 2]^2 minus (1, 2]^2 to `path` as a Gmsh .msh file, with the physical +# groups "inlet" (x = 0), "outlet" (x = 2), "wall" (the other four edges) and "domain". +function write_lshape(path; h = 0.5) + Gmsh.initialize() + try + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("lshape") + corners = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)] + points = [gmsh.model.geo.addPoint(px, py, 0, h) for (px, py) in corners] + lines = [gmsh.model.geo.addLine(points[i], points[mod1(i + 1, 6)]) for i in 1:6] + surface = gmsh.model.geo.addPlaneSurface([gmsh.model.geo.addCurveLoop(lines)]) + gmsh.model.geo.synchronize() + gmsh.model.addPhysicalGroup(1, [lines[6]], -1, "inlet") + gmsh.model.addPhysicalGroup(1, [lines[2]], -1, "outlet") + gmsh.model.addPhysicalGroup(1, lines[[1, 3, 4, 5]], -1, "wall") + gmsh.model.addPhysicalGroup(2, [surface], -1, "domain") + gmsh.model.mesh.generate(2) + gmsh.write(path) + finally + Gmsh.finalize() + end + return path +end + +# PDE: u_t = Δu +# Domain: the unit square, t in (0, 1), 4 x 4 triangle pairs, P2; the bottom side is split in two pieces +# at x = 1/2 with `addfacetset!`, giving five pieces: left, right, top, bottom_left, bottom_right +# BCs: left and bottom_right: Dirichlet u = x^2 + y^2 + 4t; bottom_left: ∂ₙu = 0; right: Robin ∂ₙu + 3u = 5 + 3y^2 + 12t; +# top: ∂ₙu = 2 +# Exact: u = x^2 + y^2 + 4t, in the P2 space +# Shows: pieces made by the user are first-class: one side of the square carries two different conditions. +@testset "a side split into two named pieces carries two different boundary conditions" begin + grid = generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0)) + delete!(grid.facetsets, "bottom") + Ferrite.addfacetset!(grid, "bottom_left", p -> p[2] < 1.0e-12 && p[1] < 0.5 + 1.0e-12) + Ferrite.addfacetset!(grid, "bottom_right", p -> p[2] < 1.0e-12 && p[1] > 0.5 - 1.0e-12) + Ω = MeshDomain(grid) + left, right, top, bottom_left, bottom_right = boundarypiece.(Ω, (:left, :right, :top, :bottom_left, :bottom_right)) + @test length(boundarypieces(Ω)) == 5 + bcs = [ + u(t, left) ~ x^2 + y^2 + 4t, u(t, bottom_right) ~ x^2 + y^2 + 4t, + NormalDerivative(bottom_left)(u(t, bottom_left)) ~ 0, + NormalDerivative(right)(u(t, right)) + 3u(t, right) ~ 5 + 3y^2 + 12t, + NormalDerivative(top)(u(t, top)) ~ 2, + u(0, x, y) ~ x^2 + y^2, + ] + @named pdesys = PDESystem([Dt(u(t, x, y)) ~ laplacian(u(t, x, y))], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}()))), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + @test sol[u(t, x, y)][end, :] ≈ sol[x] .^ 2 .+ sol[y] .^ 2 .+ 4 atol = 1.0e-7 + @test sol[u(t, bottom_left)][end, :] ≈ sol[x][piece_nodes(sol, bottom_left)] .^ 2 .+ 4 atol = 1.0e-7 +end + +# PDE: u_t = k Δu with k = 2, and a Robin condition with α = 5 in `ps` +# Domain: the L-shape [0, 2]^2 minus (1, 2]^2, t in (0, 1), a Gmsh triangle mesh (h = 0.5) written to a .msh +# file and read back with `FerriteGmsh.togrid(path)`; P2; pieces inlet, wall, outlet from physical groups +# BCs: inlet and wall: Dirichlet u = x^2 + y^2 + 4 k t; outlet (x = 2): k ∂ₙu + α u = 4k + α (4 + y^2 + 4 k t); +# IC u(0, x, y) = x^2 + y^2 +# Exact: u = x^2 + y^2 + 4 k t, in the P2 space of the straight-sided triangles +# Shows: a mesh stored in a file becomes a domain whose pieces are the Gmsh physical groups; the missing +# quadrant reads NaN; and a name that is not a facet set of the mesh is rejected with the valid names. +@testset "an L-shaped Gmsh mesh read from a file is solved with inlet, wall and outlet pieces" begin + grid = mktempdir() do dir + FerriteGmsh.togrid(write_lshape(joinpath(dir, "lshape.msh"))) + end + Ω = MeshDomain(grid) + inlet, wall, outlet = boundarypiece.(Ω, (:inlet, :wall, :outlet)) + exact = x^2 + y^2 + 4k * t + bcs = [ + u(t, inlet) ~ exact, u(t, wall) ~ exact, + k * NormalDerivative(outlet)(u(t, outlet)) + α * u(t, outlet) ~ 4k + α * (4 + y^2 + 4k * t), + u(0, x, y) ~ x^2 + y^2, + ] + @named pdesys = PDESystem( + [Dt(u(t, x, y)) ~ k * laplacian(u(t, x, y))], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], [k => 2.0, α => 5.0] + ) + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}()))), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + @test sol[u(t, x, y)][end, :] ≈ sol[x] .^ 2 .+ sol[y] .^ 2 .+ 8 atol = 1.0e-7 + @test sol(1.0, 0.5, 1.5; dv = u(t, x, y)) ≈ 0.25 + 2.25 + 8 atol = 1.0e-7 + @test isnan(sol(1.0, 1.5, 1.5; dv = u(t, x, y))) + @test_throws "has no facet set :outflow; valid names are :inlet, :outlet, :wall" boundarypiece(Ω, :outflow) +end diff --git a/test/Interface/parameters.jl b/test/Interface/parameters.jl new file mode 100644 index 00000000..acba434f --- /dev/null +++ b/test/Interface/parameters.jl @@ -0,0 +1,71 @@ +# Parameters of the PDESystem: values given in the `ps` list (`[D => 2.0, ...]`) enter the diffusivity, the +# source, the reaction rate and the boundary data. The numeric value is fixed when `discretize` assembles the +# operators, so each value is a new PDESystem (and a new discretization) and the exact solution tracks it. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Triangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@parameters D A g q λ +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# Solves `eq` on the unit square (n x n triangle pairs) with conditions `bcs(left, right, bottom, top)`, parameter values `ps`, to `tend`. +function solve_square(eq, bcs, ps, tend; n = 4) + Ω = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + @named pdesys = PDESystem(eq, bcs(left, right, bottom, top), [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x, y], [u(t, x, y)], ps) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}())) + return solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# PDE: u_t = D (u_xx + u_yy) + A, with D, A and the boundary offset g given in `ps` +# Domain: the unit square, t in (0, 1), 4 x 4 triangle pairs, P2 +# BCs: u = x^2 + y^2 + (4D + A) t + g on all four sides; IC u(0, x, y) = x^2 + y^2 + g +# Exact: u = x^2 + y^2 + (4D + A) t + g, which lies in the P2 space, so the error is the solver tolerance +# Shows: the diffusivity, the source amplitude and the Dirichlet value are all read from `ps`, and the +# computed solution follows the exact one for each of three parameter sets. +@testset "diffusivity, source amplitude and boundary value come from ps, for $ps" for ps in ( + (D = 1.0, A = 0.0, g = 0.0), (D = 0.5, A = 3.0, g = 1.0), (D = 4.0, A = -2.0, g = -0.5), + ) + exact = x^2 + y^2 + (4D + A) * t + g + eq = [Dt(u(t, x, y)) ~ D * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) + A] + bcs(sides...) = [[u(t, Γ) ~ exact for Γ in sides]; u(0, x, y) ~ x^2 + y^2 + g] + sol = solve_square(eq, bcs, [D => ps.D, A => ps.A, g => ps.g], 1.0) + final(x_, y_) = x_^2 + y_^2 + 4ps.D + ps.A + ps.g + @test l2_error(sol, u(t, x, y), final, 1.0, sample_points(20), sample_points(20)) < 1.0e-7 +end + +# PDE: u_t = D (u_xx + u_yy) +# Domain: the unit square, t in (0, 1), P2 +# BCs: u = D q t on the left; u_x = q on the right (flux value from `ps`); u_y = 0 on top and bottom +# (Neumann data enters through `NormalDerivative`); IC u(0, x, y) = q x^2 / 2 +# Exact: u = q x^2 / 2 + D q t, in the P2 space +# Shows: a parameter can be the value of a Neumann condition, and the solution scales with it. +@testset "a Neumann flux read from ps scales the solution, for q = $flux" for flux in (0.5, 2.0, -1.0) + diffusivity = 1.5 + eq = [Dt(u(t, x, y)) ~ D * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))))] + bcs(left, right, bottom, top) = [ + u(t, left) ~ D * q * t, NormalDerivative(right)(u(t, right)) ~ q, + NormalDerivative(bottom)(u(t, bottom)) ~ 0, NormalDerivative(top)(u(t, top)) ~ 0, u(0, x, y) ~ q * x^2 / 2, + ] + sol = solve_square(eq, bcs, [D => diffusivity, q => flux], 1.0) + final(x_, y_) = flux * x_^2 / 2 + diffusivity * flux + @test l2_error(sol, u(t, x, y), final, 1.0, sample_points(20), sample_points(20)) < 1.0e-7 +end + +# PDE: u_t = D (u_xx + u_yy) - λ u +# Domain: the unit square, t in (0, 0.05), 16 x 16 triangle pairs, P2 +# BCs: u = 0 on all four sides; IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = exp(-(2 pi^2 D + λ) t) sin(pi x) sin(pi y) +# Shows: a parameter in the reaction term changes the decay rate, and the final amplitude at the centre +# tracks exp(-(2 pi^2 D + λ) t) for each pair (D, λ). +@testset "the decay rate of an eigenmode follows D and the reaction rate λ in ps, for $ps" for ps in ( + (D = 1.0, λ = 0.0), (D = 0.5, λ = 10.0), (D = 2.0, λ = 3.0), + ) + eq = [Dt(u(t, x, y)) ~ D * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) - λ * u(t, x, y)] + bcs(sides...) = [[u(t, Γ) ~ 0 for Γ in sides]; u(0, x, y) ~ sin(pi * x) * sin(pi * y)] + sol = solve_square(eq, bcs, [D => ps.D, λ => ps.λ], 0.05; n = 16) + final(x_, y_) = exp(-(2pi^2 * ps.D + ps.λ) * 0.05) * sin(pi * x_) * sin(pi * y_) + @test l2_error(sol, u(t, x, y), final, 0.05, sample_points(30), sample_points(30)) < 1.0e-4 +end diff --git a/test/Interface/wave_first_order.jl b/test/Interface/wave_first_order.jl new file mode 100644 index 00000000..7caf63da --- /dev/null +++ b/test/Interface/wave_first_order.jl @@ -0,0 +1,75 @@ +# The wave equation u_tt = c^2 Δu has a second time derivative, which the discretization rejects (see +# rejections.jl). Written as the first-order system u_t = v, v_t = c^2 Δu it is accepted: u has no spatial +# operator in its own equation, v carries the Laplacian. These cases solve the system for standing waves +# and compare both fields with the exact solution. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Triangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@parameters c +@variables x y u(..) v(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# Solves u_t = v, v_t = c^2 u_xx on a mesh of `n` line cells in order-`order` elements with wave speed `speed`; +# returns the L2 errors of u and v at t = 0.5 against u = cos(c pi t) sin(pi x), v = -c pi sin(c pi t) sin(pi x). +function wave_1d_errors(n, order, speed) + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + eqs = [Dt(u(t, x)) ~ v(t, x), Dt(v(t, x)) ~ c^2 * Dx(Dx(u(t, x)))] + bcs = [u(t, left) ~ 0, u(t, right) ~ 0, v(t, left) ~ 0, v(t, right) ~ 0, u(0, x) ~ sin(pi * x), v(0, x) ~ 0] + @named pdesys = PDESystem(eqs, bcs, [x ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x], [u(t, x), v(t, x)], [c => speed]) + space = Lagrange{RefLine, order}() + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => space, v => space))), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + points = sample_points(200) + return ( + l2_error(sol, u(t, x), x_ -> cos(speed * pi * 0.5) * sin(pi * x_), 0.5, points), + l2_error(sol, v(t, x), x_ -> -speed * pi * sin(speed * pi * 0.5) * sin(pi * x_), 0.5, points), + ) +end + +# PDE: u_t = v, v_t = c^2 u_xx with c = 1 +# Domain: x in (0, 1), t in (0, 0.5), meshes of 4, 8, 16 and 32 line cells, P1 or P2 for both fields +# BCs: u = v = 0 at both ends; ICs u(0, x) = sin(pi x), v(0, x) = 0 +# Exact: u = cos(pi t) sin(pi x), v = -pi sin(pi t) sin(pi x), a standing wave of period 2 +# Shows: the first-order form of the wave equation converges in both fields: with elements of order p, both +# u and v converge at the optimal L2 rate p + 1 (u is superconvergent for P2, rate 4). +@testset "the first-order wave system converges in u and v with $name elements on a line" for (name, order) in (("P1", 1), ("P2", 2)) + ns = (4, 8, 16, 32) + errors = [wave_1d_errors(n, order, 1.0) for n in ns] + @test all(observed_rate(first.(errors), 1 ./ ns) .> order + 0.8) + @test all(observed_rate(last.(errors), 1 ./ ns) .> order + 0.8) +end + +# PDE: u_t = v, v_t = c^2 u_xx with the wave speed c = 2 given in `ps` +# Domain: x in (0, 1), t in (0, 0.5), 16 P2 line cells +# BCs, ICs: as in the previous case +# Exact: u = cos(2 pi t) sin(pi x), v = -2 pi sin(2 pi t) sin(pi x): the wave oscillates twice as fast +# Shows: the wave speed is a parameter; the period is 1, so at t = 0.5 the wave has flipped sign: +# u(0.5, x) = -sin(pi x), v(0.5, x) = 0, to the discretization error. +@testset "the wave speed c in ps sets the oscillation frequency" begin + error_u, error_v = wave_1d_errors(16, 2, 2.0) + @test error_u < 1.0e-4 && error_v < 1.0e-4 +end + +# PDE: u_t = v, v_t = u_xx + u_yy +# Domain: the unit square, t in (0, 0.25), 8 x 8 triangle pairs, P2 for both fields +# BCs: u = v = 0 on all four sides; ICs u(0, x, y) = sin(pi x) sin(pi y), v(0, x, y) = 0 +# Exact: u = cos(sqrt(2) pi t) sin(pi x) sin(pi y), v = -sqrt(2) pi sin(sqrt(2) pi t) sin(pi x) sin(pi y) +# Shows: the same first-order system in 2D, with angular frequency sqrt(2) pi from the eigenvalue 2 pi^2. +@testset "a 2D standing wave on triangles is followed by both fields" begin + Ω = MeshDomain(generate_grid(Triangle, (8, 8), Vec(0.0, 0.0), Vec(1.0, 1.0))) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + U, V = u(t, x, y), v(t, x, y) + bcs = [ + [u(t, Γ) ~ 0 for Γ in sides]; [v(t, Γ) ~ 0 for Γ in sides]; + u(0, x, y) ~ sin(pi * x) * sin(pi * y); v(0, x, y) ~ 0 + ] + @named pdesys = PDESystem([Dt(U) ~ V, Dt(V) ~ Dx(Dx(U)) + Dy(Dy(U))], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.25)], [t, x, y], [U, V], []) + space = Lagrange{RefTriangle, 2}() + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => space, v => space))), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + ω = sqrt(2) * pi + points = (sample_points(30), sample_points(30)) + @test l2_error(sol, U, (x_, y_) -> cos(ω * 0.25) * sin(pi * x_) * sin(pi * y_), 0.25, points...) < 2.0e-3 + @test l2_error(sol, V, (x_, y_) -> -ω * sin(ω * 0.25) * sin(pi * x_) * sin(pi * y_), 0.25, points...) < 1.0e-2 +end From a218e6b507761d3eed604a83237f51c276819a9e Mon Sep 17 00:00:00 2001 From: Alex Jones Date: Tue, 3 Nov 2026 18:29:19 +0000 Subject: [PATCH 07/12] Add the coupled, wave, mesh, curved and parameter cases to the Interface README table Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/Interface/README.md b/test/Interface/README.md index 3588056c..797beef2 100644 --- a/test/Interface/README.md +++ b/test/Interface/README.md @@ -50,6 +50,19 @@ boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D a | `solution_access.jl` | `sol(t, x, y; dv)` points, grids, outside the mesh | heat | 2 | P2 | Dirichlet | | `solution_access.jl` | derivative and trace keys | heat | 2 | P2 | Dirichlet | | `solution_access.jl` | parameter values set the diffusivity | heat | 2 | P2 | Dirichlet | +| `coupled_systems.jl` | bidirectionally coupled pair, exact in P2 | two coupled reaction-diffusion fields | 2 | P2 | Dirichlet | +| `coupled_systems.jl` | coupled eigenmode pair (cosh, sinh) on triangles and quadrilaterals | two coupled heat fields | 2 | P2 | zero Dirichlet | +| `coupled_systems.jl` | both fields converge at rate 2 | two coupled heat fields | 2 | P1 | time-dependent Dirichlet | +| `coupled_systems.jl` | different boundary condition kinds per field | two coupled reaction-diffusion fields | 2 | P2 | Dirichlet on u; Dirichlet and Neumann on v | +| `wave_first_order.jl` | convergence of u and v on a line | wave as a first-order system | 1 | P1, P2 | zero Dirichlet | +| `wave_first_order.jl` | wave speed `c` in `ps` | wave as a first-order system | 1 | P2 | zero Dirichlet | +| `wave_first_order.jl` | 2D standing wave | wave as a first-order system | 2 | P2 | zero Dirichlet | +| `mesh_domains.jl` | side split into two named pieces | heat | 2 | P2 | Dirichlet, Neumann and Robin on five pieces | +| `mesh_domains.jl` | L-shaped Gmsh mesh read from a file | heat with parameters `k`, `α` | 2 | P2 | Dirichlet on inlet and wall, Robin on outlet | +| `curved_geometry.jl` | optimal rates on a quarter annulus with `QuadraticTriangle` cells | heat with source | 2 | P1, P2 | Dirichlet on the arcs, Neumann | +| `parameters.jl` | `D`, `A`, `g` from `ps` for three parameter sets | heat with source | 2 | P2 | Dirichlet with parameter | +| `parameters.jl` | Neumann flux `q` from `ps` | heat | 2 | P2 | Dirichlet and Neumann with parameter | +| `parameters.jl` | `D` and reaction rate `λ` from `ps` | heat with decay | 2 | P2 | zero Dirichlet | | `rejections.jl` | rejected boundary conditions, equations, options, domains, shared facets | heat | 1 to 2 | | | ## Not covered on this branch From 91f01f8624d23073b6011aad794ef45def5f45a4 Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 18:55:02 +0000 Subject: [PATCH 08/12] Distinguish the 1D and 2D advection-diffusion rows in the Interface README The two P2 convergence-rate rows had identical descriptions. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Interface/README.md b/test/Interface/README.md index 2cf55262..7448a990 100644 --- a/test/Interface/README.md +++ b/test/Interface/README.md @@ -59,9 +59,9 @@ boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D a | `solver_choices.jl` | tolerances and `saveat` | heat | 1 | P2 | constant and time-dependent Dirichlet | | `solver_choices.jl` | ODE solver refused for the DAE problem | heat | 1 | P2 | time-dependent Dirichlet | | `advection_diffusion.jl` | exact reproduction with constant velocity | advection-diffusion with source | 1 | P2 | time-dependent Dirichlet | -| `advection_diffusion.jl` | P2 convergence rate 3 with manufactured source | advection-diffusion with source | 1 | P2 | zero Dirichlet | +| `advection_diffusion.jl` | P2 convergence rate 3 with manufactured source on a line | advection-diffusion with source | 1 | P2 | zero Dirichlet | | `advection_diffusion.jl` | exact reproduction with velocity vector on triangles and quadrilaterals | advection-diffusion with source | 2 | P2 | time-dependent Dirichlet | -| `advection_diffusion.jl` | P2 convergence rate 3 with manufactured source | advection-diffusion with source | 2 | P2 | zero Dirichlet | +| `advection_diffusion.jl` | P2 convergence rate 3 with manufactured source on triangles | advection-diffusion with source | 2 | P2 | zero Dirichlet | | `reaction_diffusion.jl` | linear reaction with source on triangles and quadrilaterals | reaction-diffusion | 2 | P2 | zero Dirichlet | | `reaction_diffusion.jl` | decay reaction, P2 convergence rate 3 | reaction-diffusion | 1 | P2 | zero Dirichlet | | `reaction_diffusion.jl` | two linearly coupled fields, exact | coupled reaction-diffusion | 1 | P2 | time-dependent Dirichlet | From e17e6cdce5d07aac3be87107de2fb5204cdcf23d Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 23:13:34 +0000 Subject: [PATCH 09/12] Update the Interface rejections and reaction-diffusion cases for M4 Steady problems, nonlinear terms, time-last variables, periodic-free options and dirichlet = :eliminate are supported on master now, so rejections.jl asserts the rejections that remain (the current messages) and reaction_diffusion.jl solves the logistic reaction against a manufactured solution at rate 3. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/advection_diffusion.jl | 2 +- test/Interface/reaction_diffusion.jl | 35 ++++++---- test/Interface/rejections.jl | 70 ++++++++++++++----- .../variable_coefficient_diffusion.jl | 6 +- 4 files changed, 78 insertions(+), 35 deletions(-) diff --git a/test/Interface/advection_diffusion.jl b/test/Interface/advection_diffusion.jl index 7209132b..2215a7ec 100644 --- a/test/Interface/advection_diffusion.jl +++ b/test/Interface/advection_diffusion.jl @@ -1,7 +1,7 @@ # Advection-diffusion with a constant velocity through the full interface, in 1D and 2D with P2 elements, # against manufactured solutions: a source term f is chosen so that a known u solves the equation. # docs/src/equation_classes.md lists convection-diffusion at moderate cell Peclet number as a Tier 1 class -# (supported, VERIFIED); only pure advection and advection-dominated problems are Tier 2 (need SUPG, M4), +# (supported, VERIFIED); only pure advection and advection-dominated problems are Tier 2 (they need SUPG, see `supg.jl`), # so every case here keeps the cell Peclet number below one. using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test using Ferrite: generate_grid, Line, Triangle, Quadrilateral, Vec diff --git a/test/Interface/reaction_diffusion.jl b/test/Interface/reaction_diffusion.jl index 531fc4f9..de8c1253 100644 --- a/test/Interface/reaction_diffusion.jl +++ b/test/Interface/reaction_diffusion.jl @@ -1,10 +1,6 @@ # Reaction-diffusion through the full interface: a linear reaction term, a linearly coupled two-field -# system, and the documented rejection of a nonlinear reaction. -# docs/src/equation_classes.md lists second-order parabolic equations "scalar or coupled multi-field" as -# Tier 1 (VERIFIED, two-field reaction-diffusion to 1.9e-16). It also lists nonlinear sources `f(u)` as -# Tier 1 in the design, but states that this release rejects state-dependent coefficients with an error -# naming milestone M3, so the nonlinear case below asserts that rejection. -using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +# system and a nonlinear (logistic) reaction term, which is a state-dependent source solved with Newton steps. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Symbolics, Test using Ferrite: generate_grid, Line, Triangle, Quadrilateral, Vec using ModelingToolkit: t_nounits as t include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) @@ -89,12 +85,23 @@ end @test l2_error(sol, v(t, x), x_ -> v_exact(1.0, x_), 1.0, sample_points(40)) < 1.0e-7 end -# PDE: u_t = u_xx + u_yy + u (1 - u) (a nonlinear, logistic reaction) -# Shows: state-dependent sources are named in the error rather than silently linearised (M3). -@testset "a nonlinear reaction term is rejected naming milestone M3" begin - Ω = unit_square(Triangle, 2) - eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + u(t, x, y) * (1 - u(t, x, y)) - bcs = [[u(t, Γ) ~ 0 for Γ in sides(Ω)]; u(0, x, y) ~ 0] - @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) - @test_throws "nonlinear terms land in M3" discretize(pdesys, FEMDiscretization(Ω, t)) +# PDE: u_t = u_xx + u (1 - u) + f (a nonlinear, logistic reaction: the Fisher-KPP equation with a source) +# Domain: x in (0, 1), t in (0, 0.2), meshes of 2, 4, 8 and 16 line cells, P2 +# BCs: u(t, 0) = u(t, 1) = 0; IC u(0, x) = sin(pi x) +# Exact: u = exp(-t) sin(pi x); the source f = u_t - u_xx - u (1 - u) is built symbolically from it +# Shows: a state-dependent reaction is solved with Newton steps inside the time integration, at the optimal rate 3. +@testset "P2 elements on a line converge at rate 3 for the logistic reaction-diffusion equation" begin + exact = exp(-t) * sin(pi * x) + source = expand_derivatives(Dt(exact) - Dx(Dx(exact)) - exact * (1 - exact)) + ns = (2, 4, 8, 16) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + eq = Dt(u(t, x)) ~ Dx(Dx(u(t, x))) + u(t, x) * (1 - u(t, x)) + source + @named pdesys = PDESystem([eq], [u(t, left) ~ 0, u(t, right) ~ 0, u(0, x) ~ sin(pi * x)], [(x,) ∈ Ω, t ∈ Interval(0.0, 0.2)], [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-11, reltol = 1.0e-11) + l2_error(sol, u(t, x), x_ -> exp(-0.2) * sin(pi * x_), 0.2, sample_points(200)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) end diff --git a/test/Interface/rejections.jl b/test/Interface/rejections.jl index dd26a705..a2170c14 100644 --- a/test/Interface/rejections.jl +++ b/test/Interface/rejections.jl @@ -1,9 +1,10 @@ # Inputs the discretization refuses, each through the full interface: the PDESystem is built as a user # would build it, and `discretize` (or the `FEMDiscretization` constructor) throws before any solver runs. # Every case asserts the part of the documented message that names the problem (`@test_throws "text" expr`). +# The last cases, on solution queries, solve a four-cell problem first. using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test using Ferrite: Ferrite -using Ferrite: generate_grid, Triangle, Vec +using Ferrite: generate_grid, Line, Triangle, Vec using ModelingToolkit: t_nounits as t @variables x y u(..) v(..) @@ -30,48 +31,53 @@ 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 conditions need milestone M4" lower([heat], [u(t, left) ~ u(t, right), 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)] ) end -# PDE: heat equations with a nonlinear coefficient, a time-dependent coefficient, third order in space -# or second order in time, with zero Dirichlet data -# Shows: an operator the Galerkin weak form cannot assemble yet is named in the error. +# PDE: heat equations with a time-dependent coefficient, a state-dependent mass, third order in space, second +# order in time, or a nonlinear Dirichlet condition, with zero Dirichlet data +# Shows: an operator the Galerkin weak form cannot assemble is named in the error. @testset "equations outside the supported classes are rejected naming the term" begin - nonlinear = Dt(u(t, x, y)) ~ Dx((1 + u(t, x, y)^2) * Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) - @test_throws "nonlinear terms land in M3" lower([nonlinear], [dirichlet; ic]) varying = Dt(u(t, x, y)) ~ Dx((1 + t) * Dx(u(t, x, y))) + Dy((1 + t) * Dy(u(t, x, y))) - @test_throws "time-dependent coefficients in the mass or stiffness operator land in M3" lower([varying], [dirichlet; ic]) + @test_throws "time-dependent coefficients in the mass or stiffness operator are not supported" lower([varying], [dirichlet; ic]) + @test_throws "state-dependent mass" lower([(1 + u(t, x, y)^2) * Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))], [dirichlet; ic]) @test_throws "third-order" lower([Dt(u(t, x, y)) ~ Dx(Dx(Dx(u(t, x, y))))], [dirichlet; ic]) @test_throws "second order in time; write as a first-order system" lower( [Differential(t, 2)(u(t, x, y)) ~ Dx(Dx(u(t, x, y)))], [dirichlet; ic] ) + @test_throws "Dirichlet data must be linear in one field" lower([heat], [u(t, left)^2 ~ 1, u(t, right) ~ 0, u(t, bottom) ~ 0, u(t, top) ~ 0, ic]) end # PDE: the 2D heat equation, or a steady Laplace equation -# Shows: options reserved for later releases, and unknown `spaces` keys, fail with the supported default named. -@testset "options that are not available yet are rejected when the discretization is built" begin - @test_throws "codegen = :mtk lands in M3; use the default codegen = :numeric" FEMDiscretization(Ω, t; codegen = :mtk) - @test_throws "dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic" FEMDiscretization(Ω, t; dirichlet = :eliminate) +# Shows: options that do not exist, a time-dependent condition with `dirichlet = :eliminate`, and a steady problem +# paired with a time-dependent discretization (or the reverse) fail naming the fix. +@testset "options and discretizations that do not fit the problem are rejected when the problem is built" begin + @test_throws "codegen = :mtk is not supported; use the default codegen = :numeric" FEMDiscretization(Ω, t; codegen = :mtk) + @test_throws "dirichlet must be :algebraic or :eliminate, got :condense" FEMDiscretization(Ω, t; dirichlet = :condense) + timed = [u(t, Γ) ~ sin(t) for Γ in (left, right, bottom, top)] + @test_throws "dirichlet = :eliminate needs Dirichlet data that are constant in time" lower([heat], [timed; ic]; dirichlet = :eliminate) @named steady = PDESystem([Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in (left, right, bottom, top)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) - @test_throws "steady problems land in M4; give FEMDiscretization a time variable" discretize(steady, FEMDiscretization(Ω)) + @test_throws "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem" DAEProblem(steady, FEMDiscretization(Ω)) + @named transient = PDESystem([heat], [dirichlet; ic], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_throws "for a time-dependent problem write FEMDiscretization(Ω, t)" discretize(transient, FEMDiscretization(Ω)) @test_throws "`spaces` has keys that are not dependent variables of the system: v" lower( [heat], [dirichlet; ic]; spaces = Dict(v => Lagrange{RefTriangle, 2}()) ) end -# PDE: the 2D heat equation, with a Rectangle domain, a split time interval or time as the last argument -# Shows: the PDESystem's domains must be a mesh for space and one interval for time, with time first. +# PDE: the 2D heat equation, with a Rectangle domain, a split time interval or time between the spatial arguments +# Shows: the PDESystem's domains must be a mesh for space and one interval for time; time is the first or last argument. @testset "domains the discretization cannot use are rejected naming what is expected" begin box = [(x, y) ∈ Rectangle([0.0, 0.0], [1.0, 1.0]), t ∈ Interval(0.0, 1.0)] @test_throws "FEMDiscretization discretizes on a mesh" lower([heat], [ic]; domains = box) split_time = [(x, y) ∈ Ω, t ∈ UnionDomain(Interval(0.0, 1.0), Interval(2.0, 3.0))] @test_throws "time t must be paired with an interval" lower([heat], [ic]; domains = split_time) - time_last = Dt(u(x, y, t)) ~ Dx(Dx(u(x, y, t))) + Dy(Dy(u(x, y, t))) - @test_throws "time must be the first argument of u(x, y, t)" lower([time_last], [u(x, y, 0) ~ 0]; dvs = [u(x, y, t)]) + between = Dt(u(x, t, y)) ~ Dx(Dx(u(x, t, y))) + Dy(Dy(u(x, t, y))) + @test_throws "time must be the first or the last argument of u(x, t, y)" lower([between], [u(x, 0, y) ~ 0]; dvs = [u(x, t, y)]) end # PDE: the 2D heat equation on the unit square @@ -84,3 +90,33 @@ end inlet, left_side = boundarypiece.(mesh, (:inlet, :left)) @test_throws "share 2 facets" lower([heat], [u(t, inlet) ~ 0, u(t, left_side) ~ 1, ic]; mesh) end + +Ω1 = MeshDomain(generate_grid(Line, (4,), Vec(0.0), Vec(1.0))) +ends = boundarypiece.(Ω1, (:left, :right)) +line_system(eq) = PDESystem([eq], [u(t, ends[1]) ~ 0, u(t, ends[2]) ~ 1, u(0, x) ~ x], [(x,) ∈ Ω1, t ∈ Interval(0.0, 1.0)], [t, x], [u(t, x)], []; name = :line) + +# PDE: u_t = 0.01 u_xx - u_x - u^2, discretized with SUPG; and the options of `test_space` +# Shows: SUPG stabilises linear terms only, and `test_space` must be `Galerkin()` or `SUPG(τ)`. +@testset "SUPG with a nonlinear term, or a test space that is not Galerkin or SUPG, is rejected" begin + nonlinear = Dt(u(t, x)) ~ 0.01 * Dx(Dx(u(t, x))) - Dx(u(t, x)) - u(t, x)^2 + @test_throws "SUPG stabilises linear terms only" discretize(line_system(nonlinear), FEMDiscretization(Ω1, t; test_space = SUPG(0.05))) + @test_throws "test_space must be Galerkin() or SUPG(τ; b = nothing), got :supg" FEMDiscretization(Ω1, t; test_space = :supg) +end + +# PDE: u_t = u_xx on a line, solved, then queried with expressions the solution cannot evaluate +# Shows: an observed expression may contain only the dependent variables, their first spatial derivatives, the +# coordinates, time and parameters; anything else is named in the error. +@testset "observed expressions with unknown symbols, second derivatives or fixed arguments are rejected" begin + sol = solve(discretize(line_system(Dt(u(t, x)) ~ Dx(Dx(u(t, x)))), FEMDiscretization(Ω1, t)), DFBDF()) + @test_throws "is not a dependent variable, an independent variable or a parameter" sol[u(t, x) * v(t, x)] + @test_throws "is not a first spatial derivative of a dependent variable" sol[Dx(Dx(u(t, x))) + 1] + @test_throws "fixes arguments of u(t, x); write the dependent variable as u(t, x)" sol[u(0, x) + 1] + @test_throws "is not a dependent variable or a first spatial derivative of one" sol(0.5, 0.5; dv = Dt(u(t, x))) +end + +# PDE: u_t = u_xx - u^3 +# Shows: `operators` returns the linear time-independent operators only; a nonlinear term is named. +@testset "operators rejects a nonlinear term" begin + nonlinear = Dt(u(t, x)) ~ Dx(Dx(u(t, x))) - u(t, x)^3 + @test_throws "operators returns linear operators only" FiniteElementMethod.operators(line_system(nonlinear), FEMDiscretization(Ω1, t)) +end diff --git a/test/Interface/variable_coefficient_diffusion.jl b/test/Interface/variable_coefficient_diffusion.jl index 2fdf5bfa..8669f105 100644 --- a/test/Interface/variable_coefficient_diffusion.jl +++ b/test/Interface/variable_coefficient_diffusion.jl @@ -1,9 +1,9 @@ # Diffusion with a space-dependent diffusivity a(x), in the two forms the front end accepts: divergence # form Dx(a Dx(u)) and non-divergence form a Dxx(u), with manufactured solutions and sources. # docs/src/equation_classes.md, Tier 1: "Second-order parabolic equations in divergence or non-divergence -# form" (VERIFIED, non-divergence `a(x,y) Δu` at rates 1.96 to 2.01). Coefficients that depend on time or on -# the solution are rejected (M3), and discontinuous coefficients across interfaces are "not evidenced", -# so a(x) here is smooth and depends on space only. +# form" (VERIFIED, non-divergence `a(x,y) Δu` at rates 1.96 to 2.01). Coefficients that depend on the solution +# are covered in `nonlinear.jl`, those that depend on time are rejected (`rejections.jl`), and discontinuous +# coefficients across interfaces are "not evidenced", so a(x) here is smooth and depends on space only. using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test using Ferrite: generate_grid, Line, Triangle, Quadrilateral, Vec using ModelingToolkit: t_nounits as t From b1f9afc029b8e11cde459e35cf5257356938a84a Mon Sep 17 00:00:00 2001 From: t Date: Tue, 3 Nov 2026 23:13:34 +0000 Subject: [PATCH 10/12] Add the M4 cases to the Interface test group Steady problems, time-last variables, observed expressions, dirichlet = :eliminate, nonlinear terms, unequal-order and region fields, SUPG, a Kovasznay Navier-Stokes case, and the facet_dofs / operators data API, each in the one-narrated-testset style of the group. Adds a steady l2_error method to the shared helpers and updates the README case table. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/README.md | 27 ++++++++-- test/Interface/eliminate.jl | 51 ++++++++++++++++++ test/Interface/metadata_and_operators.jl | 63 ++++++++++++++++++++++ test/Interface/multifield_spaces.jl | 61 +++++++++++++++++++++ test/Interface/navier_stokes.jl | 48 +++++++++++++++++ test/Interface/nonlinear.jl | 56 +++++++++++++++++++ test/Interface/observed_expressions.jl | 38 +++++++++++++ test/Interface/steady.jl | 68 +++++++++++++++++++++++ test/Interface/supg.jl | 49 +++++++++++++++++ test/Interface/time_last_variables.jl | 69 ++++++++++++++++++++++++ test/shared/interface_helpers.jl | 14 ++++- 11 files changed, 538 insertions(+), 6 deletions(-) create mode 100644 test/Interface/eliminate.jl create mode 100644 test/Interface/metadata_and_operators.jl create mode 100644 test/Interface/multifield_spaces.jl create mode 100644 test/Interface/navier_stokes.jl create mode 100644 test/Interface/nonlinear.jl create mode 100644 test/Interface/observed_expressions.jl create mode 100644 test/Interface/steady.jl create mode 100644 test/Interface/supg.jl create mode 100644 test/Interface/time_last_variables.jl diff --git a/test/Interface/README.md b/test/Interface/README.md index 7448a990..13507adf 100644 --- a/test/Interface/README.md +++ b/test/Interface/README.md @@ -65,7 +65,7 @@ boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D a | `reaction_diffusion.jl` | linear reaction with source on triangles and quadrilaterals | reaction-diffusion | 2 | P2 | zero Dirichlet | | `reaction_diffusion.jl` | decay reaction, P2 convergence rate 3 | reaction-diffusion | 1 | P2 | zero Dirichlet | | `reaction_diffusion.jl` | two linearly coupled fields, exact | coupled reaction-diffusion | 1 | P2 | time-dependent Dirichlet | -| `reaction_diffusion.jl` | nonlinear reaction rejected (M3) | logistic reaction-diffusion | 2 | P1 | zero Dirichlet | +| `reaction_diffusion.jl` | logistic reaction, manufactured source, rate 3 | nonlinear reaction-diffusion | 1 | P2 | zero Dirichlet | | `variable_coefficient_diffusion.jl` | `Dx(a Dx(u))`, rate 3 | divergence-form diffusion | 1 | P2 | zero Dirichlet | | `variable_coefficient_diffusion.jl` | `a Dxx(u)`, rate 3 | non-divergence-form diffusion | 1 | P2 | zero Dirichlet | | `variable_coefficient_diffusion.jl` | `Dx(a Dx(u)) + Dy(a Dy(u))`, rate 3, triangles and quadrilaterals | divergence-form diffusion | 2 | P2 | zero Dirichlet | @@ -86,8 +86,27 @@ boundary pieces are `boundarypiece.(Ω, (:left, :right, :bottom, :top))` in 2D a | `parameters.jl` | `D`, `A`, `g` from `ps` for three parameter sets | heat with source | 2 | P2 | Dirichlet with parameter | | `parameters.jl` | Neumann flux `q` from `ps` | heat | 2 | P2 | Dirichlet and Neumann with parameter | | `parameters.jl` | `D` and reaction rate `λ` from `ps` | heat with decay | 2 | P2 | zero Dirichlet | -| `rejections.jl` | rejected boundary conditions, equations, options, domains, shared facets | heat | 1 to 2 | | | +| `steady.jl` | steady Poisson on a line, rates 2 and 3 | Poisson, no time variable | 1 | P1, P2 | constant Dirichlet | +| `steady.jl` | steady Poisson with Dirichlet and Neumann sides, rates 2 and 3 | Poisson | 2 | P1, P2 | Dirichlet and Neumann | +| `steady.jl` | steady nonlinear diffusion `k(u) = 1 + u^2`, rate 3 | nonlinear diffusion, Newton | 2 | P2 | zero Dirichlet | +| `time_last_variables.jl` | `u(x, y, t)` and `u(t, x, y)` give the same solution, time axis last | heat | 2 | P2 | zero Dirichlet | +| `time_last_variables.jl` | time-last traces, Dirichlet and Neumann data, exact | heat with time-dependent source | 2 | P2 | Dirichlet and Neumann | +| `observed_expressions.jl` | `sol[expr]` and `sol(t, x, y; dv = expr)` | heat with parameter `D` | 2 | P2 | Dirichlet | +| `eliminate.jl` | `dirichlet = :eliminate` against `:algebraic` | heat | 2 | P2 | space-dependent Dirichlet, constant in time | +| `eliminate.jl` | `dirichlet = :eliminate` on a steady problem | Laplace | 2 | P1 | Dirichlet | +| `nonlinear.jl` | viscous Burgers `u u_x`, rate 3 | Burgers with source | 1 | P2 | zero Dirichlet | +| `nonlinear.jl` | nonlinear diffusion `k(u) = 1 + u^2`, rate 3 | nonlinear diffusion with source | 2 | P2 | zero Dirichlet | +| `multifield_spaces.jl` | P2 and P1 fields in one system, rates 3 and 2 | two coupled heat fields | 2 | P2, P1 | Dirichlet | +| `multifield_spaces.jl` | a field restricted to a region reads NaN outside it | two heat fields, one on a half | 2 | P2 | Dirichlet; natural on the region's other sides | +| `supg.jl` | Galerkin oscillates, SUPG with the optimal `τ` is nodally exact | convection-diffusion boundary layer | 1 | P1 | Dirichlet | +| `supg.jl` | constant `τ` with explicit velocity, and `τ(hK, b)` | convection-diffusion boundary layer | 1 | P1 | Dirichlet | +| `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 | +| `rejections.jl` | rejected boundary conditions, equations, options, domains, shared facets, SUPG with a nonlinear term, observed expressions, `operators` | heat and others | 1 to 2 | | | -## Not covered on this branch +## Not covered -Steady problems, time-last variables, observed expressions, SUPG and Navier-Stokes are not on `master`. +The DFG cylinder (Navier-Stokes, about 149 000 unknowns) is the `NavierStokes` group. Periodic conditions, `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/eliminate.jl b/test/Interface/eliminate.jl new file mode 100644 index 00000000..0775c10f --- /dev/null +++ b/test/Interface/eliminate.jl @@ -0,0 +1,51 @@ +# `dirichlet = :eliminate`: the prescribed dofs are removed from the unknowns instead of kept as algebraic rows, so the +# DAE is smaller and has no Dirichlet rows. It needs Dirichlet data that are constant in time (they may vary in space). +# The solution interface is unchanged: `sol[u]` and `sol(t, x, y; dv)` hold the full field. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, NonlinearSolveFirstOrder, Test +using Ferrite: generate_grid, Triangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +unit_square(n) = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + +# PDE: u_t = u_xx + u_yy +# Domain: the unit square, t in (0, 0.1), 8 x 8 triangle pairs, P2 +# BCs: u = 1 + x + 2y on all sides (constant in time, linear in space); IC u = 1 + x + 2y + sin(pi x) sin(pi y) +# Exact: u = 1 + x + 2y + exp(-2 pi^2 t) sin(pi x) sin(pi y) +# Shows: the eliminated problem has fewer unknowns, the same solution as the algebraic one, and the boundary values. +@testset "dirichlet = :eliminate solves the heat equation with fewer unknowns and the same solution" begin + Ω = unit_square(8) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + U = u(t, x, y) + bcs = [[u(t, Γ) ~ 1 + x + 2y for Γ in sides]; u(0, x, y) ~ 1 + x + 2y + sin(pi * x) * sin(pi * y)] + @named pdesys = PDESystem([Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U))], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [U], []) + solve_with(dirichlet) = begin + prob = discretize(pdesys, FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}()), dirichlet, saveat = 0.025)) + prob, solve(prob, DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + end + (algebraic_problem, algebraic), (eliminated_problem, eliminated) = solve_with(:algebraic), solve_with(:eliminate) + @test length(eliminated_problem.u0) == length(algebraic_problem.u0) - 64 # 32 vertices and 32 mid-edge nodes on the boundary + @test eliminated[U] ≈ algebraic[U] atol = 1.0e-8 + exact(x_, y_) = 1 + x_ + 2y_ + exp(-2pi^2 * 0.1) * sin(pi * x_) * sin(pi * y_) + @test l2_error(eliminated, U, exact, 0.1, sample_points(40), sample_points(40)) < 1.0e-3 + left = first(sides) + @test eliminated[u(t, left)] ≈ repeat(permutedims(1 .+ 2 .* eliminated[y][piece_nodes(eliminated, left)]), length(eliminated.t)) atol = 1.0e-12 +end + +# PDE: u_xx + u_yy = 0 (steady) +# Domain: the unit square, 4 x 4 triangle pairs, P1 +# BCs: u = 1 + x + 2y on all sides +# Exact: u = 1 + x + 2y +# Shows: a steady problem takes `dirichlet = :eliminate` too: fewer unknowns, the full field in the solution. +@testset "dirichlet = :eliminate on a steady problem leaves only the interior nodes unknown" begin + Ω = unit_square(4) + bcs = [u(Γ) ~ 1 + x + 2y for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))] + @named pdesys = PDESystem([Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], bcs, [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + prob = discretize(pdesys, FEMDiscretization(Ω; dirichlet = :eliminate)) + sol = solve(prob, NewtonRaphson(); abstol = 1.0e-12) + @test length(prob.u0) == 9 # the 3 x 3 interior nodes of the 5 x 5 vertex lattice + @test sol[u(x, y)] ≈ 1 .+ sol[x] .+ 2 .* sol[y] atol = 1.0e-10 +end diff --git a/test/Interface/metadata_and_operators.jl b/test/Interface/metadata_and_operators.jl new file mode 100644 index 00000000..11630b76 --- /dev/null +++ b/test/Interface/metadata_and_operators.jl @@ -0,0 +1,63 @@ +# The data API for callers that build their own system around the discretization: `facet_dofs`, `dof_coordinates` and +# `cell_dofs` read the index data of a problem's `FEMMetadata` (its `problem_type`), and `FiniteElementMethod.operators` +# returns the assembled mass and stiffness matrices and the load vector as plain data. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Triangle, Vec +using LinearAlgebra: norm +using ModelingToolkit: t_nounits as t + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# The PDESystem u_t = u_xx + u_yy + 4 on a 4 x 3 mesh of the unit square with Dirichlet data `g` on all four sides. +function heat_system(g) + Ω = MeshDomain(generate_grid(Triangle, (4, 3), Vec(0.0, 0.0), Vec(1.0, 1.0))) + sides = 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))) + 4], [[u(t, Γ) ~ g for Γ in sides]; u(0, x, y) ~ 0], + [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], [] + ) + return pdesys, Ω, sides +end + +# PDE: u_t = u_xx + u_yy + 4 +# Domain: the unit square, 4 x 3 triangle pairs, P1 and P2 +# BCs: u = 0 on all sides +# Shows: `dof_coordinates` places each dof, `facet_dofs` lists the dofs of a boundary piece (by piece, name or field +# expression) and `cell_dofs` gives the dofs of every cell, one column per cell. +@testset "facet_dofs, dof_coordinates and cell_dofs describe where the dofs of a field sit" for (order, nleft, ntop, nnodes) in ((1, 4, 5, 20), (2, 7, 9, 63)) + pdesys, Ω, (left, _, _, top) = heat_system(0) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, order}())) + md = discretize(pdesys, disc).problem_type + X = dof_coordinates(md) + @test size(X) == (2, nnodes) + dofs = facet_dofs(md, left, u) + @test length(dofs) == nleft && issorted(dofs) && all(iszero, X[1, dofs]) + @test facet_dofs(md, "top", :u) == facet_dofs(md, top, u) == facet_dofs(md, top, u(t, x, y)) + @test length(facet_dofs(md, top, u)) == ntop && all(≈(1.0), X[2, facet_dofs(md, top, u)]) + cells = cell_dofs(md, u) + @test size(cells) == (order == 1 ? 3 : 6, 4 * 3 * 2) + @test sort!(unique(vec(cells))) == 1:nnodes +end + +# PDE: u_t = u_xx + u_yy + 4, solved at its steady state -(u_xx + u_yy) = 4 by hand from `operators` +# Domain: the unit square, 4 x 3 triangle pairs, P2 +# BCs: u = x (1 - x) + y (1 - y) on all sides +# Exact: u = x (1 - x) + y (1 - y), in the P2 space +# Shows: `operators` returns M, K and F with the Dirichlet rows left unconstrained; eliminating the prescribed dofs +# and solving K u = F reproduces the exact solution at every dof. +@testset "operators gives the matrices and load to assemble a steady solve by hand" begin + exact(x_, y_) = x_ * (1 - x_) + y_ * (1 - y_) + pdesys, Ω, _ = heat_system(x * (1 - x) + y * (1 - y)) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}())) + ops = FiniteElementMethod.operators(pdesys, disc) + n = size(ops.K, 1) + @test size(ops.M) == (n, n) && ops.fields == [:u => 1:n] + @test norm(ops.K * ones(n)) < 1.0e-12 # constants are in the kernel of the stiffness matrix + fixed, free = ops.prescribed, setdiff(1:n, ops.prescribed) + U = zeros(n) + U[fixed] = ops.dirichlet_values + U[free] = ops.K[free, free] \ (ops.F[free] - ops.K[free, fixed] * ops.dirichlet_values) + X = dof_coordinates(ops.metadata) + @test U ≈ [exact(X[1, i], X[2, i]) for i in 1:n] atol = 1.0e-12 +end diff --git a/test/Interface/multifield_spaces.jl b/test/Interface/multifield_spaces.jl new file mode 100644 index 00000000..a5d4638a --- /dev/null +++ b/test/Interface/multifield_spaces.jl @@ -0,0 +1,61 @@ +# Fields with their own element spaces and their own regions: `spaces` gives each dependent variable an interpolation +# (here P2 for one field and P1 for the other), and `regions` restricts a field to the cells of a cell set. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Symbolics, Test +using Ferrite: generate_grid, addcellset!, Triangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) w(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +Δ(f) = Dx(Dx(f)) + Dy(Dy(f)) + +# PDE: u_t = Δu + f_u and w_t = Δw + u + f_w (w reads u, u does not read w) +# Domain: the unit square, t in (0, 0.25), meshes of 4 x 4, 8 x 8 and 16 x 16 triangle pairs +# BCs: Dirichlet data from the exact solution on all sides for both fields; IC from the exact solution +# Exact: u = (1 + t) sin(pi x) sin(pi y) + x in P2, w = (1 + t) cos(x + y) in P1; f_u and f_w follow from the equations +# Shows: `spaces = Dict(u => P2, w => P1)` gives the two fields different orders; each converges at its own rate (3 and 2). +@testset "a P2 field and a P1 field coupled in one system converge at rates 3 and 2" begin + us, ws = (1 + t) * sin(pi * x) * sin(pi * y) + x, (1 + t) * cos(x + y) + eqs = [Dt(u(t, x, y)) ~ Δ(u(t, x, y)) + expand_derivatives(Dt(us) - Δ(us)), Dt(w(t, x, y)) ~ Δ(w(t, x, y)) + u(t, x, y) + expand_derivatives(Dt(ws) - Δ(ws) - us)] + u_exact(t_, x_, y_) = (1 + t_) * sin(pi * x_) * sin(pi * y_) + x_ + w_exact(t_, x_, y_) = (1 + t_) * cos(x_ + y_) + ns = (4, 8, 16) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + bcs = [[u(t, Γ) ~ us for Γ in sides]; [w(t, Γ) ~ ws for Γ in sides]; u(0, x, y) ~ substitute(us, t => 0); w(0, x, y) ~ substitute(ws, t => 0)] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.25)], [t, x, y], [u(t, x, y), w(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}(), w => Lagrange{RefTriangle, 1}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + pts = (sample_points(40), sample_points(40)) + (l2_error(sol, u(t, x, y), (a, b) -> u_exact(0.25, a, b), 0.25, pts...), l2_error(sol, w(t, x, y), (a, b) -> w_exact(0.25, a, b), 0.25, pts...)) + end + @test all(observed_rate(first.(errors), 1 ./ ns) .> 2.7) + @test all(observed_rate(last.(errors), 1 ./ ns) .> 1.8) +end + +# PDE: u_t = Δu on the whole square, and w_t = Δw + u + f_w only on the left half x <= 1/2 +# Domain: the unit square, t in (0, 0.5), 4 x 4 triangle pairs with the cell set "left_half", P2 for both fields +# BCs: u = x^2 + y^2 + 4 t on all sides; w = 1 + 1/4 + t on the left side only (w is natural zero-flux elsewhere) +# Exact: u = x^2 + y^2 + 4 t; w = 1 + (x - 1/2)^2 + t on the left half, whose normal derivative vanishes on the +# bottom, top and the cut x = 1/2, so the natural condition holds; f_w = 1 - Δw - u +# Shows: `regions = Dict(w => Region(Ω, :left_half))` puts w on the left half only; it reads NaN elsewhere. +@testset "a field restricted to a region is solved there and reads NaN outside" begin + grid = generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0)) + addcellset!(grid, "left_half", p -> p[1] <= 0.5 + 1.0e-12) + Ω = MeshDomain(grid) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + us, ws = x^2 + y^2 + 4t, 1 + (x - 1 / 2)^2 + t + eqs = [Dt(u(t, x, y)) ~ Δ(u(t, x, y)), Dt(w(t, x, y)) ~ Δ(w(t, x, y)) + u(t, x, y) + expand_derivatives(Dt(ws) - Δ(ws) - us)] + bcs = [[u(t, Γ) ~ us for Γ in sides]; w(t, first(sides)) ~ 5 / 4 + t; u(0, x, y) ~ x^2 + y^2; w(0, x, y) ~ 1 + (x - 1 / 2)^2] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x, y], [u(t, x, y), w(t, x, y)], []) + P2 = Lagrange{RefTriangle, 2}() + disc = FEMDiscretization(Ω, t; spaces = Dict(u => P2, w => P2), regions = Dict(w => Region(Ω, :left_half))) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + inside = sol[x] .<= 0.5 + 1.0e-12 + @test all(isfinite, sol[w(t, x, y)][:, inside]) && all(isnan, sol[w(t, x, y)][:, .!inside]) + @test sol[w(t, x, y)][end, inside] ≈ [1 + (a - 0.5)^2 + 0.5 for a in sol[x][inside]] atol = 1.0e-7 + @test sol(0.5, 0.3, 0.6; dv = w(t, x, y)) ≈ 1 + 0.2^2 + 0.5 atol = 1.0e-7 + @test isnan(@test_logs((:warn, r"assigned to cells where field :w is not defined"), sol(0.5, 0.8, 0.6; dv = w(t, x, y)))) + @test sol(0.5, 0.8, 0.6; dv = u(t, x, y)) ≈ 0.8^2 + 0.6^2 + 2 atol = 1.0e-7 +end diff --git a/test/Interface/navier_stokes.jl b/test/Interface/navier_stokes.jl new file mode 100644 index 00000000..c4ca7dd2 --- /dev/null +++ b/test/Interface/navier_stokes.jl @@ -0,0 +1,48 @@ +# Incompressible Navier-Stokes through the full interface, at a size that solves in seconds: a steady mixed problem +# for velocity and pressure with Taylor-Hood elements (P2 velocity, P1 pressure), checked against Kovasznay's exact flow. +# (The DFG cylinder benchmark, ~149k unknowns, is the NavierStokes test group, not this one.) +using FiniteElementMethod, ModelingToolkit, DomainSets, NonlinearSolveFirstOrder, Test +using Ferrite: generate_grid, Triangle, Vec +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) v(..) p(..) +Dx, Dy = Differential(x), Differential(y) +Δ(f) = Dx(Dx(f)) + Dy(Dy(f)) + +const ν = 1 / 20 +const λ = 1 / (2ν) - sqrt(1 / (4ν^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), meshes of 6 x 8, 12 x 16 and 24 x 32 triangle pairs (up to 7 195 unknowns) +# BCs: velocity = the exact velocity on all four sides; the pressure is fixed to the exact pressure on the right side +# Exact: u = 1 - exp(λx) cos(2πy), v = λ/(2π) exp(λx) sin(2πy), p = (1 - exp(2λx))/2, λ = Re/2 - sqrt(Re^2/4 + 4π^2) +# Shows: a steady nonlinear saddle-point problem: `pairing` tests the continuity equation with p, Newton finds the flow, and +# the velocity converges at rate 3 and the pressure at rate 2. +@testset "steady Navier-Stokes with Taylor-Hood elements reproduces Kovasznay's flow at rates 3 and 2" begin + continuity = 0 ~ Dx(u(x, y)) + Dy(v(x, y)) + eqs = [ + ν * Δ(u(x, y)) - u(x, y) * Dx(u(x, y)) - v(x, y) * Dy(u(x, y)) - Dx(p(x, y)) ~ 0, + ν * Δ(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 = 1 - exp(λ * x) * cos(2pi * y), λ / 2pi * exp(λ * x) * sin(2pi * 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))) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + bcs = [[u(Γ) ~ exact_u for Γ in sides]; [v(Γ) ~ exact_v for Γ in sides]; p(sides[2]) ~ (1 - exp(2λ * x)) / 2] + @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 diff --git a/test/Interface/nonlinear.jl b/test/Interface/nonlinear.jl new file mode 100644 index 00000000..2e0423d3 --- /dev/null +++ b/test/Interface/nonlinear.jl @@ -0,0 +1,56 @@ +# Nonlinear terms through the full interface: state-dependent diffusion coefficients and convection `u u_x`, solved +# in a transient problem against manufactured solutions. The nonlinear part of the operator is assembled +# with its analytic Jacobian, and the source is built symbolically so that the exact solution solves the equation. +# (The logistic reaction is in `reaction_diffusion.jl`, the steady nonlinear problem in `steady.jl`.) +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Symbolics, Test +using Ferrite: generate_grid, Line, Triangle, Vec +using ModelingToolkit: t_nounits as t +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# PDE: u_t + u u_x = nu u_xx + f with nu = 0.1 (viscous Burgers equation with a source) +# Domain: x in (0, 1), t in (0, 0.2), meshes of 2, 4, 8 and 16 line cells, P2 +# BCs: u(t, 0) = u(t, 1) = 0; IC u(0, x) = sin(pi x) +# Exact: u = (1 + t) sin(pi x); f = u_t + u u_x - nu u_xx +# Shows: a nonlinear convection term is solved at the optimal rate 3. +@testset "P2 elements on a line converge at rate 3 for the viscous Burgers equation" begin + nu, tend = 0.1, 0.2 + exact = (1 + t) * sin(pi * x) + source = expand_derivatives(Dt(exact) + exact * Dx(exact) - nu * Dx(Dx(exact))) + ns = (2, 4, 8, 16) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + eq = Dt(u(t, x)) + u(t, x) * Dx(u(t, x)) ~ nu * Dx(Dx(u(t, x))) + source + @named pdesys = PDESystem([eq], [u(t, left) ~ 0, u(t, right) ~ 0, u(0, x) ~ sin(pi * x)], [(x,) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x], [u(t, x)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefLine, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-11, reltol = 1.0e-11) + l2_error(sol, u(t, x), x_ -> (1 + tend) * sin(pi * x_), tend, sample_points(200)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end + +# PDE: u_t = (k(u) u_x)_x + (k(u) u_y)_y + f with k(u) = 1 + u^2 (nonlinear diffusion) +# Domain: the unit square, t in (0, 0.1), meshes of 4 x 4, 8 x 8 and 16 x 16 triangle pairs, P2 +# BCs: u = 0 on all four sides; IC u(0, x, y) = sin(pi x) sin(pi y) +# Exact: u = (1 + t) sin(pi x) sin(pi y); f = u_t - div(k(u) grad u) +# Shows: a state-dependent diffusion coefficient in divergence form is solved at the optimal rate 3. +@testset "P2 elements converge at rate 3 for nonlinear diffusion with k(u) = 1 + u^2" begin + tend = 0.1 + exact = (1 + t) * sin(pi * x) * sin(pi * y) + source = expand_derivatives(Dt(exact) - Dx((1 + exact^2) * Dx(exact)) - Dy((1 + exact^2) * Dy(exact))) + ns = (4, 8, 16) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + U = u(t, x, y) + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + source + bcs = [[u(t, Γ) ~ 0 for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))]; u(0, x, y) ~ sin(pi * x) * sin(pi * y)] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)], [t, x, y], [U], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + l2_error(sol, U, (x_, y_) -> (1 + tend) * sin(pi * x_) * sin(pi * y_), tend, sample_points(40), sample_points(40)) + end + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end diff --git a/test/Interface/observed_expressions.jl b/test/Interface/observed_expressions.jl new file mode 100644 index 00000000..4e32f675 --- /dev/null +++ b/test/Interface/observed_expressions.jl @@ -0,0 +1,38 @@ +# Observed expressions: any expression of the dependent variables, their first spatial derivatives, the coordinates, +# time and the parameters can be a key of the solution, `sol[expr]`, or the `dv` of a point evaluation, +# `sol(t, xs...; dv = expr)`. The expression is evaluated at every mesh vertex (or point) from the finite-element fields. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Triangle, Vec +using ModelingToolkit: t_nounits as t + +@parameters D +@variables x y u(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# PDE: u_t = D (u_xx + u_yy) with D = 2 +# Domain: the unit square, t in (0, 1), 4 x 4 triangle pairs, P2; saved every 0.25 +# BCs: u = x^2 + y^2 + 4 D t on all sides; IC u(0, x, y) = x^2 + y^2 +# Exact: u = x^2 + y^2 + 4 D t, so grad u = (2x, 2y) and the expressions below have closed forms +# Shows: `sol[expr]` and `sol(t, x, y; dv = expr)` for expressions of u, grad u, coordinates, time and a parameter. +@testset "expressions of the solution, its gradient, the coordinates, time and a parameter are observed" begin + Ω = MeshDomain(generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0))) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + U = u(t, x, y) + @named pdesys = PDESystem( + [Dt(U) ~ D * (Dx(Dx(U)) + Dy(Dy(U)))], [[u(t, Γ) ~ x^2 + y^2 + 4D * t for Γ in sides]; u(0, x, y) ~ x^2 + y^2], + [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], [D => 2.0] + ) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}()), saveat = 0.25) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + T, X, Y = sol.t, permutedims(sol[x]), permutedims(sol[y]) + + @test size(sol[U^2 + D * x]) == (length(T), length(X)) + @test sol[U^2 + D * x] ≈ sol[U] .^ 2 .+ 2 .* X atol = 1.0e-12 + @test sol[U^2 + D * x] ≈ (X .^ 2 .+ Y .^ 2 .+ 8 .* T) .^ 2 .+ 2 .* X atol = 1.0e-5 + @test sol[Dx(U)^2 + Dy(U)^2] ≈ repeat(4 .* (X .^ 2 .+ Y .^ 2), length(T)) atol = 1.0e-6 + + @test sol(0.5, 0.3, 0.2; dv = U - x^2 - y^2) ≈ 8 * 0.5 atol = 1.0e-6 + xs, ys = range(0, 1, length = 5), range(0, 1, length = 4) + @test sol(T, xs, ys; dv = t * U) ≈ [T[n] * (a^2 + b^2 + 8T[n]) for n in eachindex(T), a in xs, b in ys] atol = 1.0e-6 + @test isnan(sol(0.5, 2.0, 0.0; dv = 2x)) +end diff --git a/test/Interface/steady.jl b/test/Interface/steady.jl new file mode 100644 index 00000000..986d6283 --- /dev/null +++ b/test/Interface/steady.jl @@ -0,0 +1,68 @@ +# Steady problems through the full interface: a PDESystem with no time variable and a FEMDiscretization built +# without one lower to a NonlinearProblem, and `solve` returns a solution called without a time, `sol(x, y; dv)`. +using FiniteElementMethod, ModelingToolkit, DomainSets, NonlinearSolveFirstOrder, Symbolics, Test +using Ferrite: generate_grid, Line, Triangle, Vec +include(joinpath(@__DIR__, "..", "shared", "interface_helpers.jl")) + +@variables x y u(..) +Dx, Dy = Differential(x), Differential(y) + +# Solves the steady `eq` for u on the unit square meshed by `n` x `n` triangle pairs with the given order. +function solve_steady_square(eq, bcs, n, order) + Ω = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + @named pdesys = PDESystem([eq], bcs(Ω), [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + disc = FEMDiscretization(Ω; spaces = Dict(u => Lagrange{RefTriangle, order}())) + return solve(discretize(pdesys, disc), NewtonRaphson(); abstol = 1.0e-12) +end + +# PDE: u_xx = -pi^2 sin(pi x) +# Domain: x in (0, 1), meshes of 4, 8, 16 and 32 line cells (P1) or 2, 4, 8 and 16 (P2) +# BCs: u(0) = 0, u(1) = 1 (Dirichlet); no time variable, so no initial condition +# Exact: u = sin(pi x) + x +# Shows: a steady Poisson problem converges at the optimal L2 rates 2 (P1) and 3 (P2); the linear problem takes one Newton step. +@testset "steady Poisson on a line converges at rate $(order + 1) for P$order elements" for (order, ns) in ((1, (4, 8, 16, 32)), (2, (2, 4, 8, 16))) + errors = map(ns) do n + Ω = MeshDomain(generate_grid(Line, (n,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + @named pdesys = PDESystem([Dx(Dx(u(x))) ~ -pi^2 * sin(pi * x)], [u(left) ~ 0, u(right) ~ 1], [(x,) ∈ Ω], [x], [u(x)], []) + disc = FEMDiscretization(Ω; spaces = Dict(u => Lagrange{RefLine, order}())) + sol = solve(discretize(pdesys, disc), NewtonRaphson(); abstol = 1.0e-12) + @test sol.stats.nsteps == 1 + l2_error(sol, u(x), x_ -> sin(pi * x_) + x_, sample_points(400)) + end + @test all(observed_rate(errors, 1 ./ ns) .> order + 0.8) +end + +# PDE: u_xx + u_yy = (1 - pi^2) sin(pi x) exp(y) +# Domain: the unit square, meshes of 4 x 4, 8 x 8 and 16 x 16 triangle pairs +# BCs: Dirichlet u = sin(pi x) exp(y) on left, right and bottom; Neumann du/dn = e sin(pi x) on top +# Exact: u = sin(pi x) exp(y) +# Shows: a steady problem with Dirichlet and Neumann pieces converges at rate 2 (P1) and 3 (P2). +@testset "steady Poisson with Dirichlet and Neumann sides converges at rate $(order + 1) for P$order elements" for order in (1, 2) + exact(x_, y_) = sin(pi * x_) * exp(y_) + bcs(Ω) = begin + left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + [u(left) ~ exact(x, y), u(right) ~ exact(x, y), u(bottom) ~ exact(x, y), NormalDerivative(top)(u(top)) ~ ℯ * sin(pi * x)] + end + eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ (1 - pi^2) * exact(x, y) + ns = (4, 8, 16) + errors = [l2_error(solve_steady_square(eq, bcs, n, order), u(x, y), exact, sample_points(50), sample_points(50)) for n in ns] + @test all(observed_rate(errors, 1 ./ ns) .> order + 0.8) +end + +# PDE: (k(u) u_x)_x + (k(u) u_y)_y = f with k(u) = 1 + u^2 (nonlinear diffusion) +# Domain: the unit square, meshes of 4 x 4, 8 x 8 and 16 x 16 triangle pairs, P2 +# BCs: u = 0 on all four sides +# Exact: u = sin(pi x) sin(pi y); the source f is the left-hand side evaluated at the exact solution +# Shows: a nonlinear steady problem is solved by Newton's method (more than one step) at rate 3. +@testset "steady nonlinear diffusion converges at rate 3 with P2 elements" begin + exact = sin(pi * x) * sin(pi * y) + f = expand_derivatives(Dx((1 + exact^2) * Dx(exact)) + Dy((1 + exact^2) * Dy(exact))) + eq = Dx((1 + u(x, y)^2) * Dx(u(x, y))) + Dy((1 + u(x, y)^2) * Dy(u(x, y))) ~ f + bcs(Ω) = [u(Γ) ~ 0 for Γ in boundarypiece.(Ω, (:left, :right, :bottom, :top))] + ns = (4, 8, 16) + sols = [solve_steady_square(eq, bcs, n, 2) for n in ns] + @test all(sol -> sol.stats.nsteps > 1, sols) + errors = [l2_error(sol, u(x, y), (x_, y_) -> sin(pi * x_) * sin(pi * y_), sample_points(50), sample_points(50)) for sol in sols] + @test all(observed_rate(errors, 1 ./ ns) .> 2.8) +end diff --git a/test/Interface/supg.jl b/test/Interface/supg.jl new file mode 100644 index 00000000..cc1d5f77 --- /dev/null +++ b/test/Interface/supg.jl @@ -0,0 +1,49 @@ +# Streamline-upwind Petrov-Galerkin stabilisation for convection-dominated problems: `test_space = SUPG(τ)` tests each +# equation with v + τ b.grad(v), where b is the advection velocity read from the equation. Plain Galerkin behaves like a +# centred scheme and oscillates once the cell Peclet number exceeds one. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +using Ferrite: generate_grid, Line, Vec +using ModelingToolkit: t_nounits as t + +@variables x u(..) +Dt, Dx = Differential(t), Differential(x) + +const ε = 0.01 +layer(x_) = expm1(x_ / ε) / expm1(1 / ε) + +# Marches u_t = ε u_xx - u_x to its steady state at t = 5 on 20 line cells (cell Peclet number 2.5) and returns the +# nodal values of u and their largest distance from the exact boundary layer. +function boundary_layer(test_space) + Ω = MeshDomain(generate_grid(Line, (20,), Vec(0.0), Vec(1.0))) + left, right = boundarypiece.(Ω, (:left, :right)) + eq = Dt(u(t, x)) ~ ε * Dx(Dx(u(t, x))) - Dx(u(t, x)) + @named pdesys = PDESystem([eq], [u(t, left) ~ 0, u(t, right) ~ 1, u(0, x) ~ x], [(x,) ∈ Ω, t ∈ Interval(0.0, 5.0)], [t, x], [u(t, x)], []) + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t; test_space)), DFBDF(); abstol = 1.0e-11, reltol = 1.0e-11) + nodal = sol[u(t, x)][end, :] + return nodal, maximum(abs.(nodal .- layer.(sol[x]))) +end + +# PDE: u_t = ε u_xx - u_x with ε = 0.01 (convection-diffusion, advection velocity 1) +# Domain: x in (0, 1), t in (0, 5), 20 line cells, P1 +# BCs: u(t, 0) = 0, u(t, 1) = 1; IC u(0, x) = x +# Exact: the steady boundary layer u = (exp(x / ε) - 1) / (exp(1 / ε) - 1) +# Shows: Galerkin undershoots below -0.4 at this Peclet number; SUPG with the optimal τ(hK, b) is nodally exact. +@testset "SUPG removes the oscillations of Galerkin in a boundary layer and is nodally exact with the optimal τ" begin + nodal, error_galerkin = boundary_layer(Galerkin()) + @test minimum(nodal) < -0.4 && error_galerkin > 0.4 + optimal_τ(hK, b) = (Pe = abs(b[1]) * hK / (2ε); hK / (2abs(b[1])) * (coth(Pe) - 1 / Pe)) + nodal, error_supg = boundary_layer(SUPG(optimal_τ)) + @test minimum(nodal) >= -1.0e-10 && maximum(nodal) <= 1 + 1.0e-10 + @test error_supg < 1.0e-9 +end + +# PDE, Domain, BCs, Exact: as in the first case +# Shows: τ may be a plain number with the velocity `b` given, or a function of the cell size and velocity, here hK / (2|b|); +# both are monotone and smear the layer over about a cell, and the two agree on this uniform mesh (hK = 1/20). +@testset "SUPG accepts a constant τ with an explicit velocity or a function of the cell size" begin + nodal_function, error_function = boundary_layer(SUPG((hK, b) -> hK / (2abs(b[1])))) + nodal_constant, _ = boundary_layer(SUPG(1 / 40; b = [1.0])) + @test minimum(nodal_function) >= -1.0e-10 && maximum(nodal_function) <= 1 + 1.0e-10 + @test error_function < 0.2 + @test nodal_constant ≈ nodal_function atol = 1.0e-8 +end diff --git a/test/Interface/time_last_variables.jl b/test/Interface/time_last_variables.jl new file mode 100644 index 00000000..ee60a385 --- /dev/null +++ b/test/Interface/time_last_variables.jl @@ -0,0 +1,69 @@ +# Time as the last argument of the dependent variable, `u(x, y, t)`, as MethodOfLines accepts it: the front end and +# the solution follow the declared argument order, so arrays put the time axis last and calls take the time last. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF, Test +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) + +unit_square(n) = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) +exact(t_, x_, y_) = exp(-2pi^2 * t_) * sin(pi * x_) * sin(pi * y_) + +# Solves the heat equation on a P2 mesh of 8 x 8 triangle pairs. `U(args...)` is u(t, args...) or u(args..., t), and `ic` the +# matching initial condition. +function solve_heat(U, ic) + Ω = unit_square(8) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + eq = Dt(U(x, y)) ~ Dx(Dx(U(x, y))) + Dy(Dy(U(x, y))) + bcs = [[U(Γ) ~ 0 for Γ in sides]; ic] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [U(x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}()), saveat = 0.025) + return solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) +end + +# PDE: u_t = u_xx + u_yy, written once as u(t, x, y) and once as u(x, y, t) +# Domain: the unit square, t in (0, 0.1), 8 x 8 triangle pairs, P2; saved every 0.025 +# BCs: u = 0 on all sides; IC u = sin(pi x) sin(pi y) at t = 0 +# Exact: u = exp(-2 pi^2 t) sin(pi x) sin(pi y) +# Shows: both forms give the same solution; `sol[u]` is nt x nvertices time-first and nvertices x nt time-last, +# and `sol(t, x, y; dv)` becomes `sol(x, y, t; dv)`. +@testset "the heat equation written with u(x, y, t) gives the u(t, x, y) solution with the time axis last" begin + start = sin(pi * x) * sin(pi * y) + time_first = solve_heat((args...) -> u(t, args...), u(0, x, y) ~ start) + time_last = solve_heat((args...) -> u(args..., t), u(x, y, 0) ~ start) + Uf, Ul = u(t, x, y), u(x, y, t) + nt, nv = length(time_first.t), length(time_first[x]) + @test time_last.t == time_first.t + @test size(time_first[Uf]) == (nt, nv) && size(time_last[Ul]) == (nv, nt) + @test time_last[Ul] ≈ permutedims(time_first[Uf]) atol = 1.0e-10 + @test time_last(0.3, 0.4, 0.05; dv = Ul) ≈ time_first(0.05, 0.3, 0.4; dv = Uf) atol = 1.0e-10 + @test time_last(0.3, 0.4, 0.05; dv = Ul) ≈ exact(0.05, 0.3, 0.4) atol = 1.0e-3 + xs, ys, ts = range(0, 1, length = 5), range(0, 1, length = 4), [0.0, 0.05, 0.1] + @test size(time_last(xs, ys, ts; dv = Ul)) == (5, 4, 3) + @test time_last(xs, ys, ts; dv = Ul) ≈ permutedims(time_first(ts, xs, ys; dv = Uf), (2, 3, 1)) atol = 1.0e-10 +end + +# PDE: u_t = u_xx + u_yy + 2 t (1 + x + 2y) +# Domain: the unit square, t in (0, 1), 4 x 4 triangle pairs, P2 +# BCs: Dirichlet u = (1 + x + 2y)(1 + t^2) on left and bottom; Neumann du/dn = 1 + t^2 on right and 2(1 + t^2) on top, +# all written with the trace `u(Γ, t)`; IC u(x, y, 0) = 1 + x + 2y +# Exact: u = (1 + x + 2y)(1 + t^2), in the P2 space +# Shows: traces and normal derivatives take the time last too, and a time-dependent source works. +@testset "time-last traces carry Dirichlet and Neumann data and the solution is exact" begin + Ω = unit_square(4) + left, right, bottom, top = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + U = u(x, y, t) + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + 2t * (1 + x + 2y) + bcs = [ + u(left, t) ~ (1 + 2y) * (1 + t^2), u(bottom, t) ~ (1 + x) * (1 + t^2), + NormalDerivative(right)(u(right, t)) ~ 1 + t^2, NormalDerivative(top)(u(top, t)) ~ 2 * (1 + t^2), + u(x, y, 0) ~ 1 + x + 2y, + ] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}())) + sol = solve(discretize(pdesys, disc), DFBDF(); abstol = 1.0e-10, reltol = 1.0e-10) + xs = range(0.1, 0.9, length = 5) + @test sol(xs, 0.3, 0.7; dv = U) ≈ [(1 + a + 0.6) * (1 + 0.7^2) for a in xs] atol = 1.0e-6 + @test sol[U][:, end] ≈ [(1 + a + 2b) * 2 for (a, b) in zip(sol[x], sol[y])] atol = 1.0e-6 +end diff --git a/test/shared/interface_helpers.jl b/test/shared/interface_helpers.jl index c07ae6fc..a56855a4 100644 --- a/test/shared/interface_helpers.jl +++ b/test/shared/interface_helpers.jl @@ -17,8 +17,18 @@ The L2 distance at time `t` between the field `dv` of the solution `sol` and the [`sample_points`](@ref)). Each sample carries the volume `prod(step.(points))` of its cell, so the midpoint rule approximates the integral over the domain the points cover. """ -function l2_error(sol, dv, exact, t, points...) - computed = sol(t, collect.(points)...; dv) +function l2_error(sol, dv, exact, t::Real, points...) + return l2_distance(sol(t, collect.(points)...; dv), exact, points) +end + +""" + l2_error(sol, dv, exact, points...) + +The same for a steady solution, which is called without a time: `sol(xs...; dv)`. +""" +l2_error(sol, dv, exact, points::AbstractRange...) = l2_distance(sol(collect.(points)...; dv), exact, points) + +function l2_distance(computed, exact, points) expected = [exact(x...) for x in Iterators.product(points...)] cell_volume = prod(step.(points)) return sqrt(sum(abs2, computed .- expected) * cell_volume) From 7054ae6d7837695ae94912fc6763af8d2fbef1c5 Mon Sep 17 00:00:00 2001 From: t Date: Wed, 4 Nov 2026 22:52:29 +0000 Subject: [PATCH 11/12] Rename the manufactured-solution variables flagged by the spell check typos reads `ue` as a misspelling of "use" or "due" (reaction_diffusion.jl, lines 70 to 72). The names are now u_sym and v_sym. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- test/Interface/reaction_diffusion.jl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/Interface/reaction_diffusion.jl b/test/Interface/reaction_diffusion.jl index de8c1253..e0629d47 100644 --- a/test/Interface/reaction_diffusion.jl +++ b/test/Interface/reaction_diffusion.jl @@ -67,9 +67,9 @@ end v_exact(t_, x_) = 1 + x_^2 - t_ * x_^2 Ω = MeshDomain(generate_grid(Line, (4,), Vec(0.0), Vec(1.0))) left, right = boundarypiece.(Ω, (:left, :right)) - ue, ve = x^2 + t, 1 + x^2 - t * x^2 - f_u = 1 - 2 - a * (ve - ue) - f_v = -x^2 - D * (2 - 2t) + a * (ve - ue) + u_sym, v_sym = x^2 + t, 1 + x^2 - t * x^2 + f_u = 1 - 2 - a * (v_sym - u_sym) + f_v = -x^2 - D * (2 - 2t) + a * (v_sym - u_sym) eqs = [ Dt(u(t, x)) ~ Dx(Dx(u(t, x))) + a * (v(t, x) - u(t, x)) + f_u, Dt(v(t, x)) ~ D * Dx(Dx(v(t, x))) - a * (v(t, x) - u(t, x)) + f_v, From 69495f5112c9a7d7bb67d6844c97b80871cfd43b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 03:23:03 +0000 Subject: [PATCH 12/12] Raise the OrdinaryDiffEqBDF test floor to 2.4.1 DABDF2 at OrdinaryDiffEqBDF 2.4.0 returns Unstable on the heat problem of test/Interface/solver_choices.jl (t = 1e-7, error estimate about -548) in the Downgrade job. Upstream fixed it in SciML/OrdinaryDiffEq.jl PR #3995 ("Fix DABDF2 adaptive error estimate on DAEs", Unstable regression #3960): the second-order startup step is a DImplicitEuler step that never wrote fsallast, so the first BDF2 step used a stale fsalfirst. Bisect with only OrdinaryDiffEqBDF changed: 2.4.0 Unstable (Julia 1.10.12 and 1.12.1), 2.4.1 and every later version Success (l2 1.15e-5, 898 steps). OrdinaryDiffEqBDF is a test-only dependency, so this raises the floor of the test environment. Agent-Harness: Claude Code 2.1.312 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- Project.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index 3ba326c5..fc7c0189 100644 --- a/Project.toml +++ b/Project.toml @@ -39,7 +39,7 @@ LinearAlgebra = "1.10" ModelingToolkit = "11.34" LinearSolve = "5" NonlinearSolveFirstOrder = "2.10" -OrdinaryDiffEqBDF = "2.4" +OrdinaryDiffEqBDF = "2.4.1" OrdinaryDiffEqNonlinearSolve = "2.9.4" PDEBase = "0.1.40" PrecompileTools = "1.2.1"