diff --git a/Project.toml b/Project.toml index de6763ab..3f43466e 100644 --- a/Project.toml +++ b/Project.toml @@ -36,6 +36,7 @@ FerriteGmsh = "1.5" ForwardDiff = "1.4" Gmsh = "0.3" LinearAlgebra = "1.10" +LinearSolve = "5" ModelingToolkit = "11" NonlinearSolveFirstOrder = "2.10" OrdinaryDiffEqBDF = "2.4" @@ -56,6 +57,7 @@ julia = "1.10" AllocCheck = "9b6a8646-10ed-4001-bbdc-1d2f46dfbb1a" FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" Gmsh = "705231aa-382f-11e9-3f0c-b7cb4346fdeb" +LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae" OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" @@ -63,4 +65,4 @@ SciMLTesting = "09d9d899-5365-40a9-917a-5f67fddea283" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] -test = ["AllocCheck", "FerriteGmsh", "Gmsh", "OrdinaryDiffEqBDF", "Random", "SafeTestsets", "SciMLTesting", "Test"] +test = ["AllocCheck", "FerriteGmsh", "Gmsh", "LinearSolve", "OrdinaryDiffEqBDF", "Random", "SafeTestsets", "SciMLTesting", "Test"] diff --git a/benchmarks/navier_stokes/Project.toml b/benchmarks/navier_stokes/Project.toml new file mode 100644 index 00000000..3beab4ab --- /dev/null +++ b/benchmarks/navier_stokes/Project.toml @@ -0,0 +1,28 @@ +[deps] +ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" +BlockArrays = "8e7c35d0-a365-5155-bbbb-fb81a777f24e" +Dates = "ade2ca70-3891-5945-98fb-dc099432e06a" +DiffEqBase = "2b5f629d-d688-5b77-993f-72d75c75574e" +DomainSets = "5b8099bc-c8ec-5219-889f-1d9e522a28bf" +Ferrite = "c061ca5d-56c9-439f-9c0e-210fe06d3992" +FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" +FiniteElementMethod = "e08948db-0ae8-498a-9b98-73fc7f237ce3" +Gmsh = "705231aa-382f-11e9-3f0c-b7cb4346fdeb" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae" +ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" +OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" +OrdinaryDiffEqRosenbrock = "43230ef6-c299-4910-a778-202eb28ce4ce" +PDEBase = "a7812802-0625-4b9e-961c-d332478797e5" +Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" +Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +SciMLBase = "0bca4576-84f4-4d90-8ffe-ffa030f20462" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +TOML = "fa267f1f-6049-4f14-aa54-33bafae1ed76" + +[sources] +FiniteElementMethod = {path = "../.."} +PDEBase = {rev = "forge/mesh-axis-order", url = "https://github.com/xtalax-droid/PDEBase.jl"} + +[compat] +julia = "1.11" diff --git a/benchmarks/navier_stokes/README.md b/benchmarks/navier_stokes/README.md new file mode 100644 index 00000000..c7b5f040 --- /dev/null +++ b/benchmarks/navier_stokes/README.md @@ -0,0 +1,28 @@ +# Benchmark (d): Navier–Stokes flow past a cylinder + +`ns_cylinder.jl` measures, in one process and after a warm-up solve on each side: + +1. Wall-clock against Ferrite's `ns_vs_diffeq.jl` tutorial (`ferrite_ns_vs_diffeq.jl`, the tutorial's code with + the changes listed at its top) on the same mesh, `dfg_channel_grid(h = 0.05, length = 1.1)`, with the + tutorial's settings: ν = 1e-3, inflow ramp `min(1.5t, 1.5)` (Re = 100), T = 6, abstol 1e-4, reltol 1e-5, + output every 0.1. Both sides solve one discrete problem: the outlet treatment of the PDESystem example (∇p + tested strongly, p = 0 on the outlet), which Ferrite's side gets from `outlet = :pressure`. Ferrite runs Rodas5P + on its mass-matrix ODE; FiniteElementMethod discretizes the PDESystem of `examples/dfg_cylinder` to a + DAEProblem and runs DFBDF. The horizontal velocities are compared at t = 1 and t = T at 20 points behind the + cylinder, and the time ratio is recorded only if they agree to 1% of the largest velocity there. The tutorial as + published (do-nothing outlet) is timed too, for reference. The time steppers and their error norms differ, so + the times are comparable in magnitude, not a measure of which package is faster. +2. DFG 2D-1 (Re = 20) drag, lift and pressure difference on the full channel at the meshes of + `BENCHMARK_NS_MESHES` (`h:hc` pairs, default `0.04:0.0025,0.02:0.00333,0.01:0.00167`, up to 149 094 unknowns), + with their errors against the DFG reference values. + +```sh +julia --project=benchmarks/navier_stokes -e 'using Pkg; Pkg.instantiate()' +julia --project=benchmarks/navier_stokes benchmarks/navier_stokes/ns_cylinder.jl +``` + +The results go to `benchmarks/results/ns_cylinder.toml` (or `BENCHMARK_RESULTS_DIR`) with the environment record of +`benchmarks/common.jl`: origin, date, commit, CPU, thread counts, Julia and package versions. Peak memory of the +default run is about 6.5 GB, from the 149 094-unknown 2D-1 solve; the run takes about 10 minutes on one thread. +The environment uses this repository's package and, until a PDEBase release has the mesh layer, PDEBase from the +`forge/mesh-axis-order` branch (`[sources]`). diff --git a/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl b/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl new file mode 100644 index 00000000..80e32ddc --- /dev/null +++ b/benchmarks/navier_stokes/ferrite_ns_vs_diffeq.jl @@ -0,0 +1,256 @@ +# Baseline of benchmark (d), spec §11.5: Ferrite's own tutorial `docs/src/literate-tutorials/ns_vs_diffeq.jl` +# (Ferrite 1.7, MIT licence), run as published apart from three changes that do not touch the numerics: the mesh +# comes from `dfg_channel_grid` of the example (the same geometry for both sides of the comparison; the tutorial's +# own Gmsh rectangle-minus-circle with `Mesh.MeshSizeMax = 0.05` is kept as `tutorial_grid`), the VTK output loop +# is replaced by `solve` with `saveat`, the progress bar and logging are off, and the linear solver is named as +# UMFPACK: the tutorial predates LinearSolve's current sparse default, whose supernodal LU rejects the change of +# sparsity pattern between Rodas5P's W matrices that UMFPACK, the default when the tutorial was written, accepts. Everything else +# (Q2Q1 Taylor–Hood with a vector velocity, ν = 1e-3, the inflow ramp `min(1.5t, 1.5)`, Rodas5P with the Ferrite +# Dirichlet limiter, `abstol = 1e-4`, `reltol = 1e-5`, `dt = 1e-3`, the free-dof error norm) is the tutorial's. +# +# `outlet = :pressure` switches to the outlet treatment of the PDESystem example, so that the timed comparison in +# `ns_cylinder.jl` solves one discrete problem on both sides. Prints and returns `(; seconds, ndofs, steps, ...)`; `ns_cylinder.jl` calls it and writes the results file. +using Ferrite, SparseArrays, BlockArrays, LinearAlgebra +using DiffEqBase +using OrdinaryDiffEqRosenbrock: Rodas5P +using ADTypes: AutoFiniteDiff +using LinearSolve: UMFPACKFactorization + +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "mesh.jl")) + +function tutorial_grid() + Gmsh.initialize() + try + gmsh.option.set_number("General.Verbosity", 2) + dim = 2 + rect_tag = gmsh.model.occ.add_rectangle(0, 0, 0, 1.1, 0.41) + circle_tag = gmsh.model.occ.add_circle(0.2, 0.2, 0, 0.05) + circle_curve_tag = gmsh.model.occ.add_curve_loop([circle_tag]) + circle_surf_tag = gmsh.model.occ.add_plane_surface([circle_curve_tag]) + gmsh.model.occ.cut([(dim, rect_tag)], [(dim, circle_surf_tag)]) + gmsh.model.occ.synchronize() + gmsh.model.model.add_physical_group(dim - 1, [6], -1, "bottom") + gmsh.model.model.add_physical_group(dim - 1, [7], -1, "inlet") + gmsh.model.model.add_physical_group(dim - 1, [8], -1, "outlet") + gmsh.model.model.add_physical_group(dim - 1, [9], -1, "top") + gmsh.model.model.add_physical_group(dim - 1, [5], -1, "cylinder") + gmsh.option.setNumber("Mesh.Algorithm", 11) + gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 20) + gmsh.option.setNumber("Mesh.MeshSizeMax", 0.05) + gmsh.model.mesh.generate(dim) + grid = FerriteGmsh.togrid() + addfacetset!(grid, "walls", union(getfacetset(grid, "bottom"), getfacetset(grid, "top"))) + return grid + finally + Gmsh.finalize() + end +end + +function assemble_mass_matrix(cv::MultiFieldCellValues, M::SparseMatrixCSC, dh::DofHandler) + n_basefuncs_v = getnbasefunctions(cv.v) + n_basefuncs_p = getnbasefunctions(cv.p) + n_basefuncs = n_basefuncs_v + n_basefuncs_p + v▄, p▄ = 1, 2 + Mₑ = BlockedArray(zeros(n_basefuncs, n_basefuncs), [n_basefuncs_v, n_basefuncs_p], [n_basefuncs_v, n_basefuncs_p]) + mass_assembler = start_assemble(M) + for cell in CellIterator(dh) + fill!(Mₑ, 0) + Ferrite.reinit!(cv, cell) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + for i in 1:n_basefuncs_v + φᵢ = shape_value(cv.v, q_point, i) + for j in 1:n_basefuncs_v + φⱼ = shape_value(cv.v, q_point, j) + Mₑ[BlockIndex((v▄, v▄), (i, j))] += φᵢ ⋅ φⱼ * dΩ + end + end + end + assemble!(mass_assembler, celldofs(cell), Mₑ) + end + return M +end + +function assemble_stokes_matrix(cv::MultiFieldCellValues, ν, K::SparseMatrixCSC, dh::DofHandler; outlet = :do_nothing) + n_basefuncs_v = getnbasefunctions(cv.v) + n_basefuncs_p = getnbasefunctions(cv.p) + n_basefuncs = n_basefuncs_v + n_basefuncs_p + v▄, p▄ = 1, 2 + Kₑ = BlockedArray(zeros(n_basefuncs, n_basefuncs), [n_basefuncs_v, n_basefuncs_p], [n_basefuncs_v, n_basefuncs_p]) + stiffness_assembler = start_assemble(K) + for cell in CellIterator(dh) + fill!(Kₑ, 0) + Ferrite.reinit!(cv, cell) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + for i in 1:n_basefuncs_v + ∇φᵢ = shape_gradient(cv.v, q_point, i) + for j in 1:n_basefuncs_v + ∇φⱼ = shape_gradient(cv.v, q_point, j) + Kₑ[BlockIndex((v▄, v▄), (i, j))] -= ν * ∇φᵢ ⊡ ∇φⱼ * dΩ + end + end + for j in 1:n_basefuncs_p + ψ = shape_value(cv.p, q_point, j) + for i in 1:n_basefuncs_v + divφ = shape_divergence(cv.v, q_point, i) + # `outlet = :pressure` keeps ∇p strong, as the PDESystem example does (see ferrite_ns_vs_diffeq). + Kₑ[BlockIndex((v▄, p▄), (i, j))] += outlet === :pressure ? + -(shape_gradient(cv.p, q_point, j) ⋅ shape_value(cv.v, q_point, i)) * dΩ : (divφ * ψ) * dΩ + Kₑ[BlockIndex((p▄, v▄), (j, i))] += (ψ * divφ) * dΩ + end + end + end + assemble!(stiffness_assembler, celldofs(cell), Kₑ) + end + return K +end + +struct RHSparams{KT, CH, DH, CV, UT} + K::KT + ch::CH + dh::DH + cv::CV + u::UT +end + +function ferrite_limiter!(u, _, p, t) + update!(p.ch, t) + return apply!(u, p.ch) +end + +function navierstokes_rhs_element!(dvₑ, vₑ, cv) + n_basefuncs = getnbasefunctions(cv.v) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + ∇v = function_gradient(cv.v, q_point, vₑ) + v = function_value(cv.v, q_point, vₑ) + for j in 1:n_basefuncs + φⱼ = shape_value(cv.v, q_point, j) + dvₑ[j] -= v ⋅ ∇v' ⋅ φⱼ * dΩ + end + end + return +end + +function navierstokes!(du, u_uc, p::RHSparams, t) + (; K, ch, dh, cv, u) = p + u .= u_uc + update!(ch, t) + apply!(u, ch) + mul!(du, K, u) + v_range = dof_range(dh, :v) + n_basefuncs = getnbasefunctions(cv.v) + vₑ = zeros(n_basefuncs) + duₑ = zeros(n_basefuncs) + for cell in CellIterator(dh) + Ferrite.reinit!(cv, cell) + v_celldofs = @view celldofs(cell)[v_range] + vₑ .= @views u[v_celldofs] + fill!(duₑ, 0.0) + navierstokes_rhs_element!(duₑ, vₑ, cv) + assemble!(du, v_celldofs, duₑ) + end + return +end + +function navierstokes_jac_element!(Jₑ, vₑ, cv) + n_basefuncs = getnbasefunctions(cv.v) + for q_point in 1:getnquadpoints(cv) + dΩ = getdetJdV(cv, q_point) + ∇v = function_gradient(cv.v, q_point, vₑ) + v = function_value(cv.v, q_point, vₑ) + for j in 1:n_basefuncs + φⱼ = shape_value(cv.v, q_point, j) + for i in 1:n_basefuncs + φᵢ = shape_value(cv.v, q_point, i) + ∇φᵢ = shape_gradient(cv.v, q_point, i) + Jₑ[j, i] -= (φᵢ ⋅ ∇v' + v ⋅ ∇φᵢ') ⋅ φⱼ * dΩ + end + end + end + return +end + +function navierstokes_jac!(J, u_uc, p, t) + (; K, ch, dh, cv, u) = p + u .= u_uc + update!(ch, t) + apply!(u, ch) + nonzeros(J) .= nonzeros(K) + assembler = start_assemble(J; fillzero = false) + n_basefuncs = getnbasefunctions(cv.v) + Jₑ = zeros(n_basefuncs, n_basefuncs) + vₑ = zeros(n_basefuncs) + v_range = dof_range(dh, :v) + for cell in CellIterator(dh) + Ferrite.reinit!(cv, cell) + v_celldofs = @view celldofs(cell)[v_range] + vₑ .= @views u[v_celldofs] + fill!(Jₑ, 0.0) + navierstokes_jac_element!(Jₑ, vₑ, cv) + assemble!(assembler, v_celldofs, Jₑ) + end + return apply!(J, ch) +end + +struct FreeDofErrorNorm + ch::ConstraintHandler +end +(fe_norm::FreeDofErrorNorm)(u::Union{AbstractFloat, Complex}, t) = DiffEqBase.ODE_DEFAULT_NORM(u, t) +(fe_norm::FreeDofErrorNorm)(u::AbstractArray, t) = DiffEqBase.ODE_DEFAULT_NORM(u[fe_norm.ch.free_dofs], t) + +""" + ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1e-3, vmax = 1.5, Δt_save = 0.1, outlet = :do_nothing) + +Ferrite's tutorial problem on `grid` (facet sets `"inlet"`, `"outlet"`, `"walls"`, `"cylinder"`): build the +operators and integrate to `T`. Returns the solution, the `DofHandler` and the setup and solve times. + +`outlet = :do_nothing` is the tutorial as published: the pressure gradient integrated by parts, so the outlet +carries the traction-free condition `ν∂ₙu − p n = 0`. `outlet = :pressure` is the discrete problem of the +PDESystem example instead: `∇p` tested strongly (`ν∂ₙu = 0` at the outlet) and `p = 0` imposed on the outlet +through the constraint handler, which drops the continuity equations of the outlet pressure nodes as the +example's Dirichlet rows do. +""" +function ferrite_ns_vs_diffeq(grid; T = 6.0, ν = 1.0e-3, vmax = 1.5, Δt_save = 0.1, outlet = :do_nothing) + outlet in (:do_nothing, :pressure) || throw(ArgumentError("outlet must be :do_nothing or :pressure, got $(repr(outlet))")) + setup = @elapsed begin + dim = 2 + ip_v = Lagrange{RefQuadrilateral, 2}()^dim + qr = QuadratureRule{RefQuadrilateral}(4) + ip_p = Lagrange{RefQuadrilateral, 1}() + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(grid)) + cellvalues = MultiFieldCellValues(qr, (v = ip_v, p = ip_p), ip_geo) + dh = DofHandler(grid) + add!(dh, :v, ip_v) + add!(dh, :p, ip_p) + close!(dh) + ch = ConstraintHandler(dh) + ∂Ω_noslip = union(getfacetset(grid, "walls"), getfacetset(grid, "cylinder")) + add!(ch, Dirichlet(:v, ∂Ω_noslip, (x, t) -> Vec((0.0, 0.0)), [1, 2])) + vᵢₙ(t) = min(t * vmax, vmax) + parabolic_inflow_profile(x, t) = Vec((4 * vᵢₙ(t) * x[2] * (0.41 - x[2]) / 0.41^2, 0.0)) + add!(ch, Dirichlet(:v, getfacetset(grid, "inlet"), parabolic_inflow_profile, [1, 2])) + outlet === :pressure && add!(ch, Dirichlet(:p, getfacetset(grid, "outlet"), (x, t) -> 0.0)) + close!(ch) + update!(ch, 0.0) + M = assemble_mass_matrix(cellvalues, allocate_matrix(dh), dh) + K = assemble_stokes_matrix(cellvalues, ν, allocate_matrix(dh), dh; outlet) + u₀ = zeros(ndofs(dh)) + apply!(u₀, ch) + jac_sparsity = sparse(K) + apply!(M, ch) + p = RHSparams(K, ch, dh, cellvalues, copy(u₀)) + rhs = ODEFunction(navierstokes!, mass_matrix = M; jac = navierstokes_jac!, jac_prototype = jac_sparsity) + problem = ODEProblem(rhs, u₀, (0.0, T), p) + timestepper = Rodas5P( + autodiff = AutoFiniteDiff(), step_limiter! = ferrite_limiter!, linsolve = UMFPACKFactorization() + ) + end + solve_s = @elapsed sol = solve( + problem, timestepper; initializealg = NoInit(), dt = 1.0e-3, + adaptive = true, abstol = 1.0e-4, reltol = 1.0e-5, saveat = Δt_save, + internalnorm = FreeDofErrorNorm(ch), d_discontinuities = [1.0] + ) + return (; sol, dh, ch, setup_s = setup, solve_s, ndofs = ndofs(dh), steps = sol.stats.naccept + sol.stats.nreject) +end diff --git a/benchmarks/navier_stokes/ns_cylinder.jl b/benchmarks/navier_stokes/ns_cylinder.jl new file mode 100644 index 00000000..71de1287 --- /dev/null +++ b/benchmarks/navier_stokes/ns_cylinder.jl @@ -0,0 +1,104 @@ +# Benchmark (d), spec §11.5: wall-clock of the Navier–Stokes cylinder flow through the PDESystem front end against +# Ferrite's `ns_vs_diffeq.jl` tutorial on the same mesh and settings, and the DFG 2D-1 drag and lift. +# +# julia --project=benchmarks/navier_stokes -e 'using Pkg; Pkg.instantiate()' +# julia --project=benchmarks/navier_stokes benchmarks/navier_stokes/ns_cylinder.jl +# +# Part 1, wall-clock: one discrete problem on both sides, the tutorial's (ν = 1e-3, peak inflow min(1.5t, 1.5), so Re = 100 once ramped, to +# T = 6, abstol = 1e-4, reltol = 1e-5, output every 0.1) on `dfg_channel_grid(h = 0.05, length = 1.1)`, the +# tutorial's shortened channel, with the outlet treatment of the PDESystem example on both sides (∇p strong, +# p = 0 on the outlet; Ferrite's side is `ferrite_ns_vs_diffeq(...; outlet = :pressure)`). The tutorial as +# published (do-nothing outlet) is timed as well, for reference only. Ferrite: the tutorial's Rodas5P on the +# mass-matrix ODE. FiniteElementMethod: the +# PDESystem of `examples/dfg_cylinder` with the same ramp, discretized to a DAEProblem and solved with DFBDF, the +# pressure and Dirichlet rows out of error control (the tutorial's norm leaves out the Dirichlet dofs). Both +# are timed after a warm-up solve to t = 0.05 in the same process, so neither includes compilation; the +# discretization time of the PDESystem is reported separately. +# The two solutions are compared at t = 1 (end of the ramp) and t = T at 20 points behind the cylinder, and the +# timing ratio is recorded only if they agree to AGREEMENT_TOL relative to the largest velocity there. +# Part 2, accuracy: 2D-1 (Re = 20) on the full channel at the meshes `BENCHMARK_NS_MESHES`, `h:hc` pairs of +# `dfg_channel_grid` sizes (default 0.04:0.0025,0.02:0.00333,0.01:0.00167). +include(joinpath(@__DIR__, "..", "common.jl")) +include(joinpath(@__DIR__, "ferrite_ns_vs_diffeq.jl")) +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "dfg_cylinder.jl")) +using Printf + +const MESHES = [Tuple(parse.(Float64, split(m, ":"))) for m in split(get(ENV, "BENCHMARK_NS_MESHES", "0.04:0.0025,0.02:0.00333,0.01:0.00167"), ",")] +const T_END = parse(Float64, get(ENV, "BENCHMARK_NS_T", "6.0")) + +function fem_tutorial(grid; T) + build_s = @elapsed prob = dfg_problem(grid; tend = T, ν_ = 1.0e-3, Umax_ = 1.5, ramp = min(t, 1)) + abstol = differential_abstol(prob, 1.0e-4) + solve_s = @elapsed sol = check_solved(solve(prob, DFG_ALG; abstol, reltol = 1.0e-5, saveat = 0.1, tstops = [1.0])) + return (; sol, build_s, solve_s, ndofs = length(prob.u0), steps = sol.original_sol.stats.naccept + sol.original_sol.stats.nreject) +end + +# Largest difference of the horizontal velocity at 20 points behind the cylinder, relative to its largest value. +function velocity_difference(grid, ferrite, fem, τ) + points = [Ferrite.Vec(x_, y_) for x_ in range(0.4, 1.0; length = 5) for y_ in range(0.05, 0.36; length = 4)] + ph = Ferrite.PointEvalHandler(grid, points) + u_ferrite = first.(Ferrite.evaluate_at_points(ph, ferrite.dh, ferrite.sol(τ), :v)) + u_fem = Ferrite.evaluate_at_points(ph, fem.sol.disc_data.space.dh, fem.sol.original_sol(τ), :u) + return maximum(abs, u_ferrite - u_fem) / maximum(abs, u_ferrite) +end + +# The timing ratio is published only when both sides solved the same problem to comparable accuracy. +const AGREEMENT_TOL = 1.0e-2 + +function run() + grid = dfg_channel_grid(; h = 0.05, length = 1.1) + ferrite_ns_vs_diffeq(grid; T = 0.05, outlet = :pressure) + ferrite = ferrite_ns_vs_diffeq(grid; T = T_END, outlet = :pressure) + published = ferrite_ns_vs_diffeq(grid; T = T_END) + fem_tutorial(grid; T = 0.05) + fem = fem_tutorial(grid; T = T_END) + agreement = Dict{String, Any}("t$τ" => velocity_difference(grid, ferrite, fem, τ) for τ in (1.0, T_END)) + comparable = all(<=(AGREEMENT_TOL), values(agreement)) + println("relative velocity difference: ", agreement, comparable ? "" : " (above $AGREEMENT_TOL: no ratio published)") + @printf( + "tutorial problem to T = %g, same outlet treatment: Ferrite %.1f s (%d dofs, %d steps, %s); FiniteElementMethod %.1f s (%d dofs, %d steps, %s), discretization %.1f s; tutorial as published %.1f s\n", + T_END, ferrite.solve_s, ferrite.ndofs, ferrite.steps, ferrite.sol.retcode, fem.solve_s, fem.ndofs, fem.steps, fem.sol.retcode, fem.build_s, published.solve_s + ) + + rows = Dict{String, Any}[] + for (h, hc) in MESHES + r = dfg_solve(; h, hc) + c = r.coefficients + push!( + rows, Dict{String, Any}( + "h" => h, "hc" => hc, "ndofs" => r.ndofs, "build_s" => r.build_s, "solve_s" => r.solve_s, + "cD" => c.cD, "cL" => c.cL, "dp" => c.Δp, + "cD_relerr" => c.cD / DFG_2D1.cD - 1, "cL_relerr" => c.cL / DFG_2D1.cL - 1, "dp_relerr" => c.Δp / DFG_2D1.Δp - 1, + ) + ) + @printf( + "2D-1, h = %g: %d dofs, cD = %.6f (%.2e), cL = %.6f (%.2e), Δp = %.6f (%.2e), solve %.1f s\n", + h, r.ndofs, c.cD, c.cD / DFG_2D1.cD - 1, c.cL, c.cL / DFG_2D1.cL - 1, c.Δp, c.Δp / DFG_2D1.Δp - 1, r.solve_s + ) + end + return write_results( + "ns_cylinder", Dict( + "benchmark" => "(d) Navier–Stokes flow past a cylinder: wall-clock against Ferrite's ns_vs_diffeq tutorial, and DFG 2D-1 drag and lift", + "wallclock" => Dict( + "description" => "ns_vs_diffeq settings (ν = 1e-3, inflow min(1.5t, 1.5), abstol 1e-4, reltol 1e-5, saveat 0.1) to T = $T_END on dfg_channel_grid(h = 0.05, length = 1.1), Q2/Q1 Taylor–Hood, after a warm-up solve", + "cells" => Ferrite.getncells(grid), + "ferrite_solver" => "Rodas5P (AutoFiniteDiff, Ferrite step limiter, UMFPACK) on the mass-matrix ODE", + "ferrite_s" => ferrite.solve_s, "ferrite_ndofs" => ferrite.ndofs, "ferrite_steps" => ferrite.steps, + "fem_solver" => "DFBDF on the DAEProblem of the PDESystem", + "fem_s" => fem.solve_s, "fem_ndofs" => fem.ndofs, "fem_steps" => fem.steps, "fem_discretize_s" => fem.build_s, + "ferrite_published_s" => published.solve_s, + "outlet" => "both sides: ∇p tested strongly, p = 0 on the outlet (ferrite_ns_vs_diffeq outlet = :pressure); ferrite_published_s is the tutorial's do-nothing outlet", + "relative_velocity_difference" => agreement, + "agreement_tol" => AGREEMENT_TOL, + "ratio" => comparable ? fem.solve_s / ferrite.solve_s : "not published: velocity difference above agreement_tol", + ), + "dfg_2d1" => Dict( + "reference" => Dict("cD" => DFG_2D1.cD, "cL" => DFG_2D1.cL, "dp" => DFG_2D1.Δp), + "bands" => Dict("cD" => collect(DFG_2D1_BANDS.cD), "cL" => collect(DFG_2D1_BANDS.cL), "dp" => collect(DFG_2D1_BANDS.Δp)), + "rows" => rows, + ), + ) + ) +end + +run() diff --git a/docs/pages.jl b/docs/pages.jl index 022a1759..9a946c1e 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -5,5 +5,7 @@ pages = [ "Supported equation classes" => "equation_classes.md", "Boundary conditions and limitations" => "boundary_conditions.md", "Discretization" => "discretization.md", + "Navier–Stokes example" => "navier_stokes.md", + "Extension contract" => "extension_contract.md", "API" => "api.md", ] diff --git a/docs/src/api.md b/docs/src/api.md index 425be864..aa8ce004 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -25,11 +25,13 @@ FiniteElementMethod.dirichlet_values! FiniteElementMethod.FEMOperators FiniteElementMethod.FEMOp FiniteElementMethod.FEMLoad +FiniteElementMethod.FEMNonlinear FiniteElementMethod.load! FiniteElementMethod.dirichlet_rates FiniteElementMethod.fem_system FiniteElementMethod.numeric_dae_problem FiniteElementMethod.consistent_du0 +FiniteElementMethod.eliminate_dirichlet FiniteElementMethod.check_finite_initial_condition ``` @@ -42,6 +44,9 @@ FiniteElementMethod.FEMInterpolant piece_nodes normal_flux write_vtk +facet_dofs +dof_coordinates +cell_dofs ``` ## Weak form, kernels and assembly diff --git a/docs/src/boundary_conditions.md b/docs/src/boundary_conditions.md index 8168ea60..ec8aa0b7 100644 --- a/docs/src/boundary_conditions.md +++ b/docs/src/boundary_conditions.md @@ -26,13 +26,13 @@ rendering. Restrictions of this release: - Geometries are `Ferrite.Grid` meshes (1D, 2D and 3D cell shapes) wrapped as `MeshDomain(grid)`, with boundary pieces named by the grid's facet sets. Only 1D and 2D are evidenced; meshes with mixed cell types are rejected until M4. - - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time must be the first argument of every dependent variable. + - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time is the first or last argument of every dependent variable, never between spatial arguments. - Dirichlet data may depend on space, time and parameters but not on another field. Neumann and Robin conditions are written with `NormalDerivative(Γ)`, with any conormal coefficient written explicitly. Neumann and Robin data may depend on time; the Robin coefficient multiplying `u(t, Γ)` may depend only on space and parameters until M3. - Periodic conditions `u(t, Γa) ~ u(t, Γb)` are rejected until M4. Interface conditions between regions have no syntax; every field lives on the whole mesh. - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. - Where two Dirichlet pieces of one field meet, the condition listed last in the `PDESystem` wins. - Every field with a time derivative needs an initial condition, linear in that one field and finite at every node. - - Steady problems, `dirichlet = :eliminate`, fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Nonlinear operators, time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. + - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. "Time-dependent" means boundary data that varies with time, for every condition kind. @@ -104,7 +104,7 @@ have a flux, the discretization warns about each such piece. Neumann conditions. The data `β` may depend on the coordinates, time and parameters. The coefficient `α` may depend on the coordinates and parameters but not on time in this release: a time-dependent `α` makes the boundary part of the stiffness operator time-dependent, which is -rejected with `time-dependent coefficients in the mass or stiffness operator land in M3`. +rejected with `time-dependent coefficients in the mass or stiffness operator are not supported`. Like a Neumann condition, it enters the weak form as a facet integral. ## Periodic conditions @@ -128,16 +128,11 @@ is an error that names the problem; nothing falls back to `mtkcompile`. | Input | Result in this release | |:--- |:--- | -| A steady problem (no time variable) | error; lands in M4 | -| A nonlinear operator, such as `Dx((1 + u^2) * Dx(u))` | error; lands in M3 | | A time-dependent coefficient in the mass or stiffness operator, such as `Dx((1 + t) * Dx(u))` | error; lands in M3 | | A time-dependent Robin coefficient, such as `Dn(u(t, Γ)) + (1 + t) * u(t, Γ) ~ 0` | error; lands in M3 | | `FEMDiscretization(…; codegen = :mtk)` | error; lands in M3 | -| `FEMDiscretization(…; dirichlet = :eliminate)` | error; lands in M4 | -| A test space other than `Galerkin()` | error; lands in M4 | | A mesh with mixed cell types | error; lands in M4 | -| Fields with different interpolations, such as P2 velocity and P1 pressure | error; lands in M4 | | A periodic condition `u(t, Γa) ~ u(t, Γb)` | error; lands in M4 | -| A dependent variable whose first argument is not time, such as `u(x, y, t)` | error | +| A time argument between spatial arguments, such as `u(x, t, y)` | error | | Two Dirichlet pieces of one field sharing nodes | the condition listed last wins | | A boundary piece with no condition | natural zero-flux condition, with a warning when the equations have a flux | diff --git a/docs/src/differences.md b/docs/src/differences.md index 5614feaf..ccdf85b4 100644 --- a/docs/src/differences.md +++ b/docs/src/differences.md @@ -34,9 +34,8 @@ piece `Γ`, a facet set of the mesh obtained from `boundarypiece(Ω, :name)`. `u(t, 0, y)`. Every other argument is unchanged. - **`u(Γ)` is an error on a time-dependent problem.** The message shows the form to write: `u(Γ_left): trace is missing the time argument; write u(t, Γ_left)`. `u(Γ)` is the trace - only on a steady problem whose dependent variables have no time argument, such as `u(x, y)`. - Steady problems are not discretized yet (see [Restrictions](@ref)), so in practice every - trace is `u(t, Γ)`. + only on a steady problem whose dependent variables have no time argument, such as `u(x, y)` + (see [Steady problems](@ref)). - **`Dn_Γ(u(t, Γ))` is the trace of the normal derivative**, where `Dn_Γ = NormalDerivative(Γ)`: differentiate along the outward unit normal of `Γ`, then evaluate on `Γ`. This is the reading of MethodOfLines' `Dx(u(t, 0, y))`. Write a conormal coefficient explicitly, as in @@ -63,9 +62,17 @@ with these differences. linear cells the nodes are the vertices. Tensor-grid plotting calls such as `heatmap(sol[x], sol[y], …)` fail with a shape error; resample with `sol(t, xs, ys; dv = u(t, x, y))` instead, which gives the tensor product of `xs` and `ys`. - - **`sol[u(t, x, y)]` is `nt × nnodes`**, and column `i` pairs with `(sol[x][i], sol[y][i])`. - It is the field evaluated at the mesh nodes, so for a P2 field the edge dofs are not - included. `sol[u(t, x, y), k, :]` is the row at `t_k`. + - **`sol[u(t, x, y)]` is `nt × nnodes`** (`nnodes × nt` for `u(x, y, t)`), and node `i` + pairs with `(sol[x][i], sol[y][i])`. It is the field evaluated at the mesh nodes, so for a + P2 field the edge dofs are not included. `sol[u(t, x, y), k, :]` is the row at `t_k`. + - **The time axis goes first or last according to the declared argument order of each + dependent variable**, as in MethodOfLines. For a time-last `u(x, y, t)` every array keyed + by that field is transposed, `nnodes × nt` (the trace `sol[u(Γ, t)]`, the gradient + `sol[Differential(x)(u(x, y, t))]` and `normal_flux` too), and calls take the time last: + `sol(x, y, t; dv)`, `sol(Γ, t; dv)`, `sol(pts, t; dv)`. With vector arguments + `sol(xs, ys, ts; dv)` is `length(xs) × length(ys) × length(ts)`. Fields of one system may + differ; `sol(args...)` without `dv` then throws, because the position of the time argument + is ambiguous. Time between two spatial arguments, `u(x, t, y)`, is rejected by `discretize`. - **The raw dof coefficients are in `sol.original_sol`**, the solution of the `DAEProblem`; `sol.original_sol.u[k]` is the dof vector at `t_k`. - **Points outside the mesh return `NaN`** by default, which a non-convex mesh needs, since @@ -90,4 +97,35 @@ with these differences. - [`write_vtk`](@ref)`(sol, base)` writes one `.vtu` file per saved time and a ParaView collection `base.pvd`. +## Observed expressions + +`sol[expr]` evaluates an expression in the dependent variables, their first spatial +derivatives, the independent variables and the parameters of the `PDESystem`, for example +`sol[u(t, x, y)^2 + k * v(t, x, y)]`, `sol[2u(t, x, y)]` or `sol[x^2 + y]`. It has the shape of +`sol[u(t, x, y)]`, `nt × nnodes` (a vector for a steady solution), even when the expression +names only coordinates. `sol(t, xs, ys; dv = expr)` and `sol(t, Γ; dv = expr)` evaluate it at +points or on a boundary piece, with the shapes of a field, and `NaN` outside the mesh. + +The time axis follows the expression's dependent variables, as for a field: an expression in +time-last variables, `sol[u(x, y, t)^2]`, is `nnodes × nt` and is called as +`sol(xs, ys, t; dv = expr)`. An expression with no dependent variable follows the system's +variables. An expression that mixes time-first and time-last variables, or names none in a +system that mixes them, throws an `ArgumentError`: evaluate the parts separately. + + - The expression is compiled once with `build_function` and broadcast over the vertex values + of its leaves; nothing is substituted per vertex. A first derivative such as + `Differential(x)(u(t, x, y))` uses the same values as `sol[Differential(x)(u(t, x, y))]`. + - A parameter takes the value given in the `PDESystem`, as `k => 2.0`; the front end has + assembled the operators with that value, so `remake` with a new one does not change it. + - An expression that cannot be evaluated throws an `ArgumentError` beginning + "cannot evaluate the expression … on this solution:", which names a variable that is not + of the system, a trace `u(t, Γ)` (index the trace on its own, or pass `Γ` to the call + instead), a derivative that is not a first spatial derivative, or a dependent variable at + fixed arguments such as `u(t, 0, y)`. + - A dependent variable at fixed arguments, such as `u(t, 0, y)` or `u(0, x, y)`, is rejected + wherever a dependent variable is accepted (`sol[…]`, `dv`, derivatives, [`normal_flux`](@ref)) + with the `ArgumentError` "u(t, 0, y) fixes arguments of u(t, x, y); write the dependent + variable as u(t, x, y)"; a mesh has no coordinate lines to restrict to. A trace keeps time + and replaces the coordinates by one piece, `u(t, Γ)` or `u(Γ, t)`. + The docstrings are on the [API](@ref "API") page. diff --git a/docs/src/discretization.md b/docs/src/discretization.md index 82c09ea5..98525737 100644 --- a/docs/src/discretization.md +++ b/docs/src/discretization.md @@ -7,12 +7,15 @@ ```@docs FEMDiscretization FiniteElementMethod.SciMLBase.discretize(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) +FiniteElementMethod.SciMLBase.NonlinearProblem(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.AbstractTestSpace FiniteElementMethod.Galerkin +FiniteElementMethod.SciMLBase.symbolic_discretize(::FiniteElementMethod.ModelingToolkit.PDESystem, ::FEMDiscretization) FiniteElementMethod.assemble_sources! +FiniteElementMethod.operators ``` -`discretize(pdesys, disc)` returns the `DAEProblem` of the discretization. `symbolic_discretize(pdesys, disc)` +`discretize(pdesys, disc)` returns the `DAEProblem` of the discretization (the `NonlinearProblem` of a steady one, see [Steady problems](@ref)). `symbolic_discretize(pdesys, disc)` returns `(sys, tspan)`, where `sys` is the array-residual `System` attached to that problem (see [`FiniteElementMethod.fem_system`](@ref)): one block equation per field over the assembled operators, not scalar equations per node as MethodOfLines returns. @@ -58,20 +61,37 @@ small piece (a single facet set), or leave an outflow piece with the natural con The pressure is absent from its own rows, so the DAE has index 2. Two things make `DFBDF` step it: start from a velocity that is discretely divergence free (zero, with zero Dirichlet data at the initial time) and a pressure initial condition, and leave the algebraic rows out of the -error control with a large `abstol` on them, since the pressure's local error does not shrink -with the step: +error control with a large absolute tolerance on them, since the pressure's local error does +not shrink with the step. `FEMDiscretization` does the second by default: with +`algebraic_abstol = :auto` it detects an algebraic field absent from its own equation and gives +the problem the `abstol` vector `1e8` on every algebraic row (the algebraic fields and the +Dirichlet rows of all fields) and `1e-6` elsewhere: ```julia -prob = discretize(pdesys, disc) -abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars] -sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0)); abstol, reltol = 1.0e-8) +prob = discretize(pdesys, disc) # prob.kwargs[:abstol] is the vector +sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0)); reltol = 1.0e-8) ``` -Without the `abstol`, the step size collapses near the initial time (`dt` below `eps` at -`t ≈ 1e-10` on a 16 × 16 Taylor–Hood mesh). When the linear solver then reports the Newton +A number `abstol` given to `FEMDiscretization` or `discretize` sets the differential rows' +entries, as in `discretize(pdesys, disc; abstol = 1.0e-8)`; an array is used as it is. +`algebraic_abstol = 1.0e4` sets another value on the algebraic rows, of any system, and +`algebraic_abstol = nothing` sets none. An `abstol` passed to `solve` replaces the whole vector +(SciMLBase merges the problem's keywords first and the `solve` keywords over them), so +`solve(prob, alg; abstol = 1.0e-8)` puts the algebraic rows back under error control; write the +vector by hand in that case, `abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars]`. +Systems without an index-2 field, such as `0 ~ Δv + u` paired with `v`, get no `abstol`. +The keyword applies to the time-dependent (DAE) path only: a steady `FEMDiscretization(Ω)` +accepts `:auto` and `nothing` and does nothing with them, and raises for a number. + +Without the large tolerance, the step size collapses near the initial time (`dt` below `eps` +at `t ≈ 1e-10` on a 16 × 16 Taylor–Hood mesh). When the linear solver then reports the Newton matrix as singular, LinearSolve falls back to a sparse QR factorization, which can take minutes and tens of gigabytes on a saddle-point system. +`algebraic_abstol` is not in the spec (§7.1, §7.6 list the `FEMDiscretization` keywords +without it): it was added after the Taylor–Hood Stokes and DFG cylinder benchmarks needed the +tolerance in user code every time. + A field can live on part of the mesh: `regions = Dict(w => Region(Ω, :name))` restricts `w` to the cell set `name`, through a Ferrite `SubDofHandler`. Outside its region the field has no dofs, its equation is not assembled, it enters the other equations as zero, and the solution @@ -97,3 +117,88 @@ tested with `τ b·∇v`, which needs the shape-function Hessians, so the `CellV with them. Limits: linear terms only, `τ` and `b` must be numbers or expressions in the coordinates, time and `hK` (not parameters of the `PDESystem`), and boundary terms stay Galerkin. + +## Curved meshes + +The geometry of every cell comes from the mesh: the space, the assembly (facet normals +included) and the solution interface map each cell with the geometric interpolation of its +Ferrite cell type. A second-order mesh therefore gives curved cells with no option to set. +To keep P2 at its full rate on a curved domain, mesh it at order 2 so the mid-side nodes lie +on the true boundary: + +```julia +using FerriteGmsh, Gmsh + +Gmsh.initialize() +gmsh.option.setNumber("Mesh.MeshSizeMax", 0.05) +outer, inner = gmsh.model.occ.addCircle(0, 0, 0, 1.0), gmsh.model.occ.addCircle(0, 0, 0, 0.5) +surface = gmsh.model.occ.addPlaneSurface([gmsh.model.occ.addCurveLoop([outer]), gmsh.model.occ.addCurveLoop([inner])]) +gmsh.model.occ.synchronize() +gmsh.model.addPhysicalGroup(1, [inner], -1, "inner") +gmsh.model.addPhysicalGroup(1, [outer], -1, "outer") +gmsh.model.addPhysicalGroup(2, [surface], -1, "domain") +gmsh.model.mesh.generate(2) +gmsh.model.mesh.setOrder(2) # QuadraticTriangle cells, mid-side nodes on the circles +grid = FerriteGmsh.togrid() +Gmsh.finalize() + +Ω = MeshDomain(grid) +Γi, Γo = boundarypiece.(Ω, (:inner, :outer)) +disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}())) +``` + +Conditions on the curved pieces are written as on any other piece, with `NormalDerivative(Γ)` +the derivative along the outward normal of the curved facets. With straight-sided cells +(`setOrder(1)`) the boundary is a polygon and P2 drops from L2 rate 3 to 2 once boundary data +or normals of the true curve enter; `test/shared/frontend_tests/curved.jl` measures both on +this annulus. Use a mesh generator that does not leave nodes outside every cell, such as the +centre point of Gmsh's built-in-kernel circle arcs: `sol[u]` is `NaN` at such nodes. + +## Steady problems + +A `PDESystem` with no time variable, discretized by a `FEMDiscretization` built without one, +lowers to a `NonlinearProblem` `K u + N(u) - F = 0`, where `N` holds the terms whose +coefficients depend on the state; without them Newton solves it in one step. Dirichlet rows +are the algebraic equations `u_d - g_d = 0`, the Jacobian `K + ∂N/∂u` is sparse, and `solve` returns a +`PDENoTimeSolution` with the same interface as a transient solution, without the time argument: +`sol[u(x, y)]`, `sol(x, y; dv)`, traces `sol[u(Γ)]`, derivatives such as `sol[Dx(u(x, y))]`, +`normal_flux` and `write_vtk` (one `.vtu` file). Traces are written `u(Γ)`, since the dependent +variables have no time argument. + +```julia +using FiniteElementMethod, ModelingToolkit, NonlinearSolve +using Ferrite: Triangle +@variables x y u(..) +Dx, Dy = Differential(x), Differential(y) +Ω = MeshDomain(FiniteElementMethod.rectangle_grid(Triangle, (16, 16))) +eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ -1 +@named pdesys = PDESystem([eq], [u(Γ) ~ 0 for Γ in boundarypieces(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) +prob = discretize(pdesys, FEMDiscretization(Ω)) +sol = solve(prob, NewtonRaphson()) +sol(0.5, 0.5; dv = u(x, y)) +``` + +Newton starts from zero, with the Dirichlet data on any Dirichlet dofs the unknown vector +holds; another initial guess is a vector laid out like `prob.u0`, passed as `remake(prob; u0)`. With the +default `dirichlet = :algebraic` that vector holds every dof and field `name` occupies +`FiniteElementMethod.field_range(prob.problem_type.space, name)`. Equations with no entry in +`pairing` are tested with the remaining dependent variables in declared order. +`algebraic_abstol` belongs to the time-dependent (DAE) path: a steady discretization accepts +`:auto` and `nothing` and does nothing with them, and raises for a number. + +## Dirichlet conditions + +`dirichlet = :algebraic` (the default) keeps every dof as an unknown and makes each prescribed +row the algebraic equation `u_d = g_d(t)`, so it accepts Dirichlet data of any time dependence. +`dirichlet = :eliminate` removes the prescribed dofs instead: the `DAEProblem` has only the free +dofs as unknowns, with `M[fr, fr]`, `K[fr, fr]` and the load `F[fr] - K[fr, cd] g`; nonlinear +terms are evaluated at the full state with `u_cd = g` and keep their rows `fr`. It needs +Dirichlet data that are constant in time, though they may vary in space; time-dependent data +raise an `ArgumentError` naming the boundary piece. The solution is the same either way: +`sol[u]`, `sol(t, x, y)`, traces `sol[u(t, Γ)]`, `normal_flux` and `write_vtk` all return the +full field with `g` at the prescribed nodes. Only `sol.original_sol` and the array unknowns +hold the free dofs alone. + +```julia +disc = FEMDiscretization(Ω, t; dirichlet = :eliminate) +``` diff --git a/docs/src/extension_contract.md b/docs/src/extension_contract.md new file mode 100644 index 00000000..ff0b7ee5 --- /dev/null +++ b/docs/src/extension_contract.md @@ -0,0 +1,106 @@ +# Extension contract + +```@meta +CurrentModule = FiniteElementMethod +``` + +SciMLBase's +[Core Extension Contract](https://docs.sciml.ai/SciMLBase/stable/interfaces/PDE/#Core-Extension-Contract) +asks a discretizer for a `discretize` that returns a solver-ready problem, forwards the +problem-construction keywords, rejects what it cannot discretize with a clean error and keeps +the metadata to rebuild the PDE solution; `symbolic_discretize` is optional. This page states +how `FEMDiscretization` meets each clause. + +## `discretize` returns a solver-ready problem + +[`discretize(pdesys, disc; kwargs...)`](@ref SciMLBase.discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization)) +accepts a `ModelingToolkit.PDESystem` on a `MeshDomain` and returns + + - a `DAEProblem` + when `disc` has a time variable, `FEMDiscretization(Ω, t)`, for a DAE solver such as `DFBDF`; + - a [`NonlinearProblem`](@ref SciMLBase.NonlinearProblem(::ModelingToolkit.PDESystem, ::FEMDiscretization)) + when it has none, `FEMDiscretization(Ω)`, for a nonlinear solver such as `NewtonRaphson`. + +Both carry the sparse analytic Jacobian and its prototype, so `solve(prob, alg)` needs nothing +else. `DAEProblem(pdesys, disc)` and `NonlinearProblem(pdesys, disc)` build the same problems +directly. + +## Keywords + +Keywords given to `FEMDiscretization` are stored in `disc.kwargs` and passed to the problem +first, then the keywords of the `discretize` call, so a call keyword wins over the same +keyword in `disc`. Every keyword not listed below is forwarded to the problem, as other SciML +problem constructors do: `saveat`, `tstops`, `abstol`, `reltol`, `callback` and any other solve +option are stored in `prob.kwargs` and reach `solve`. + +```julia +disc = FEMDiscretization(Ω, t; abstol = 1.0e-8) +prob = discretize(pdesys, disc; saveat = 0.1, abstol = 1.0e-10) # abstol 1e-10 wins +``` + +Ten keywords are reserved and raise an `ArgumentError`, from `FEMDiscretization` and from the +problem constructors alike. Six are set by the discretization itself and cannot be set at all: +`iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters`. Four are defined by the +`PDESystem` or computed by the discretization, and are set there instead: + +| Keyword | Comes from | To change it | +|:------------------- |:-------------------------------- |:------------------------------------------------------------------- | +| `tspan` | the time domain of the PDESystem | change that domain, `t ∈ Interval(t0, t1)` | +| `u0` | its initial conditions (steady: zero with the Dirichlet data) | change them, or `remake(prob; u0 = ...)` on the returned problem | +| `p` | its parameter defaults | change them and discretize again; the operators are assembled at those values, so `solve` rejects `remake(prob; p = ...)` | +| `differential_vars` | the weak form: the fields with a time derivative | change the equations | + +The error message says the same, for example +``keyword `tspan` cannot be passed: the time span is the time domain of the PDESystem; change that domain to change it``. + +## Validation + +What the discretization cannot handle raises an `ArgumentError` that says what is unsupported. +The checks include: + + - the call itself: further positional arguments + (`discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 1`) and a + first argument that is not a `PDESystem` + (`FEMDiscretization discretizes a ModelingToolkit.PDESystem; got ...`); + - domains: no `(x, y) ∈ MeshDomain(mesh)` pairing, a `MeshDomain` other than the + discretization's, a time variable not paired with an interval, a time interval with a steady + `disc` or the reverse, mixed cell types, interpolations on another reference shape; + - equations: an equation count that differs from the number of dependent variables, unknown + `pairing`, `spaces` or `regions` keys, time-dependent mass or stiffness coefficients, + parameters without a numeric value, SUPG with parameters in `τ` or `b`; + - boundary conditions: periodic conditions, conditions on facet sets the mesh lacks, a + region's field with conditions outside the region, time-dependent Dirichlet data with + `dirichlet = :eliminate`. + +These are checked before the operators are assembled. Initial conditions are checked against +the node coordinates during assembly: one that does not name a single dependent variable, is not +linear in it or is not finite at a node raises, as does a field with a time derivative and no +initial condition. The [Discretization](@ref) page describes what is supported. + +## Metadata and the solution + +The problem's `problem_type` is a [`FEMMetadata`](@ref), a subtype of +`SciMLBase.AbstractDiscretizationMetadata{hasTime}` that holds the dof handler, the fields, +the boundary pieces and the `PDESystem`. After the solve, `SciMLBase.wrap_sol` passes the +solver's solution and that metadata to the constructors FiniteElementMethod defines, +`PDETimeSeriesSolution(sol, md::FEMMetadata)` (with time) and +`PDENoTimeSolution(sol, md::FEMMetadata)` (steady), so `solve` returns a solution indexed and +called in the `PDESystem`'s variables, `sol[u(t, x, y)]` and `sol(t, x, y; dv)`; see +[Solution shapes that differ from MethodOfLines](@ref). The solver's own solution stays in `sol.original_sol`. + +## `symbolic_discretize` + +[`symbolic_discretize(pdesys, disc; kwargs...)`](@ref SciMLBase.symbolic_discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization)) +returns the tuple `(sys, tspan)`, the shape PDEBase and MethodOfLines return; this return type +is part of the public interface. It runs the code path of `discretize`, takes the same keywords +with the same errors, and returns `prob.f.sys`, the completed `ModelingToolkit.System` with the +`FEMMetadata` attached, and `prob.tspan`. A steady `disc` raises an `ArgumentError`, because its +`NonlinearProblem` has no symbolic system; use `discretize` for it. + +## Subtyping + +Nothing in the contract requires a discretizer to subtype `SciMLBase.AbstractDiscretization`, +and nothing in FiniteElementMethod dispatches on it. `FEMDiscretization{T}` subtypes +`PDEBase.AbstractMeshDiscretization` (under `PDEBase.AbstractEquationSystemDiscretization` and +`SciMLBase.AbstractDiscretization`) so that PDEBase's mesh-domain machinery, such as +`PDEBase.interface_errors` and the boundary parsing, applies to it. diff --git a/docs/src/index.md b/docs/src/index.md index e4082360..868c41cb 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -6,10 +6,11 @@ on a mesh, derives the Galerkin weak form, assembles it with [Ferrite.jl](https://github.com/Ferrite-FEM/Ferrite.jl) and lowers it to a `DAEProblem`. !!! warning - This package is under construction. Linear time-dependent problems with Galerkin testing - are supported, with one or more fields; steady problems, nonlinear terms, periodic - conditions and other test spaces raise an error. [Boundary conditions and limitations](@ref) - lists every restriction. + This package is under construction. Problems with Galerkin testing are supported, + including nonlinear terms whose state dependence is in the coefficients, sources and + natural conditions (`∇·((1 + u²)∇u)`, `u ∂ₓu`, `u²`, `∂ₙu = −u⁴`); periodic + conditions, time-dependent mass or stiffness coefficients and other test spaces raise + an error. [Boundary conditions and limitations](@ref) lists every restriction. [Getting started](@ref) solves a heat equation on a Gmsh mesh. A MethodOfLines user should then read [Differences from MethodOfLines](@ref): coordinates are bound differently, boundary diff --git a/docs/src/navier_stokes.md b/docs/src/navier_stokes.md new file mode 100644 index 00000000..fc665024 --- /dev/null +++ b/docs/src/navier_stokes.md @@ -0,0 +1,85 @@ +# Navier–Stokes: flow past a cylinder + +The DFG benchmark of Schäfer and Turek (1996), case 2D-1: steady incompressible flow at +Reynolds number 20 past a cylinder of diameter 0.1 centred at (0.2, 0.2) in the channel +[0, 2.2] × [0, 0.41], with a parabolic inflow of peak 0.3, no slip on the walls and the +cylinder, and kinematic viscosity 10⁻³. It is a mixed saddle-point problem: the pressure has no +equation of its own and needs an inf-sup-stable pair, here Q2/Q1 Taylor–Hood. + +The script is `examples/dfg_cylinder/dfg_cylinder.jl`; the mesh generator (`mesh.jl`), the +drag and lift functional (`forces.jl`) and a hand-written Ferrite solver used as an oracle +(`reference.jl`) sit next to it. The core is ordinary strong-form ModelingToolkit: + +```julia +@parameters ν Umax +@variables x y u(..) v(..) p(..) +Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +Ω = MeshDomain(dfg_channel_grid(; h = 0.04, hc = 0.0025)) # Gmsh, all quadrilaterals, curved cylinder +Γin, Γout, Γwall, Γcyl = boundarypiece.(Ω, (:inlet, :outlet, :walls, :cylinder)) +U, V, P = u(t, x, y), v(t, x, y), p(t, x, y) +eqs = [ + Dt(U) ~ Dx(ν * Dx(U)) + Dy(ν * Dy(U)) - U * Dx(U) - V * Dy(U) - Dx(P), + Dt(V) ~ Dx(ν * Dx(V)) + Dy(ν * Dy(V)) - U * Dx(V) - V * Dy(V) - Dy(P), + 0 ~ Dx(U) + Dy(V), +] +inflow = (1 - exp(-t^2)) * 4Umax * y * (0.41 - y) / 0.41^2 +bcs = [ + u(t, Γin) ~ inflow, v(t, Γin) ~ 0, u(t, Γwall) ~ 0, v(t, Γwall) ~ 0, + u(t, Γcyl) ~ 0, v(t, Γcyl) ~ 0, p(t, Γout) ~ 0, u(0, x, y) ~ 0, v(0, x, y) ~ 0, +] +@named dfg = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 60.0)], [t, x, y], [U, V, P], + [ν => 1e-3, Umax => 0.3]) +Q2, Q1 = Lagrange{RefQuadrilateral, 2}(), Lagrange{RefQuadrilateral, 1}() +disc = FEMDiscretization(Ω, t; spaces = Dict(u => Q2, v => Q2, p => Q1), + pairing = Dict(eqs[3] => p), initializealg = CheckInit()) +prob = DAEProblem(dfg, disc) +abstol = [d ? 1e-7 : 1e8 for d in prob.differential_vars] # pressure and Dirichlet rows out of error control +sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()); + abstol, reltol = 1e-7) +``` + +## Formulation choices + +- **Outflow condition.** PDEBase's strong-form analysis integrates only second-order terms by + parts, so the pressure gradient is tested strongly and the natural outflow condition is + `ν ∂ₙu = 0` instead of the do-nothing condition `ν ∂ₙu − p n = 0` of the benchmark. The + pressure level is fixed by `p = 0` on the outlet. The hand-written Ferrite solver gives the + same drag, lift and pressure difference to seven digits with either formulation on five + meshes from 5 000 to 149 000 unknowns. +- **Index-2 DAE.** The continuity equation is paired with the pressure explicitly. The flow + starts at rest and the inflow is ramped by `1 − exp(−t²)`, whose value and rate vanish at + `t = 0`, so the zero initial state is consistent and `CheckInit()` only verifies it. The + default initialiser would solve the algebraic rows for the algebraic variables, and the + continuity rows do not contain the pressure, so its Newton matrix would be singular in the + pressure columns. The zero + velocity is discretely divergence free; the pressure, an algebraic variable, starts at zero + and needs no initial condition, since every residual row vanishes at `t = 0`. The + pressure and the Dirichlet rows are left out of the error control: the local error of an + index-2 variable does not shrink with the step. +- **Steady state.** 2D-1 is steady; the DAE is integrated to `t = 60`, where the flow has + settled to the solver tolerance, and the coefficients include the `∂ₜu` term of the + functional. +- **Linear solver.** UMFPACK is named because LinearSolve 5.18's default sparse LU throws + "snlu! requires the same sparsity pattern as the analyzed matrix" on these Newton matrices + (and on Ferrite's own `ns_vs_diffeq.jl` tutorial). Naming it also removes the default's + silent fall-back to sparse QR on a singular Newton matrix, which costs tens of gigabytes + here; the example's `check_solved` raises if the solve stops before its final time. + +## Drag and lift + +The coefficients are the weighted residuals of the momentum equations (John 2004; Braack and +Richter 2006): with `w` the finite-element function equal to `e_k` at the cylinder nodes and +zero elsewhere, `F_k = −∫ (∂ₜu·w + ν∇u:∇w + (u·∇)u·w − p ∇·w) dx` and `c = 2F/(Ū² D)` with +`Ū = 0.2`, `D = 0.1`. This volume form converges at twice the rate of the line integral of +the discrete stresses. + +**Tolerance.** The acceptance intervals of the benchmark paper, `c_D ∈ [5.57, 5.59]`, +`c_L ∈ [0.0104, 0.0110]` and `Δp ∈ [0.1172, 0.1176]` (reference values 5.57953523384, +0.010618948146 and 0.11752016697). The `NavierStokes` test group solves on a 16 430-unknown +mesh and asserts the three intervals, and agreement with the hand-written Ferrite Newton +solver on the same mesh to a relative 10⁻⁵. Benchmark (d) in `benchmarks/navier_stokes` +repeats the solve on finer meshes and records the errors against the reference values. + +This is the evidence that moves mixed saddle-point problems into Tier 1 of the supported +equation classes. diff --git a/examples/dfg_cylinder/dfg_cylinder.jl b/examples/dfg_cylinder/dfg_cylinder.jl new file mode 100644 index 00000000..cc624e62 --- /dev/null +++ b/examples/dfg_cylinder/dfg_cylinder.jl @@ -0,0 +1,128 @@ +# The DFG/Schäfer–Turek 2D flow around a cylinder (Schäfer & Turek 1996, case 2D-1, Re = 20), written as a +# strong-form ModelingToolkit PDESystem and discretized with Q2/Q1 Taylor–Hood elements by FEMDiscretization. +# +# julia --project=benchmarks/navier_stokes examples/dfg_cylinder/dfg_cylinder.jl [h] +# +# The incompressible Navier–Stokes equations are written with scalar velocity components u, v and pressure p. +# Formulation choices, each forced by the front end and checked against the hand-written Ferrite solver of +# `reference.jl` (do-nothing outflow, weak pressure gradient), which it matches on every mesh tried: +# +# - The pressure gradient is a first-order term, so PDEBase's strong-form analysis keeps it strong (tested with +# V, not integrated by parts) and the natural outflow condition is ν∂ₙu = 0 rather than the do-nothing +# ν∂ₙu − p n = 0. The pressure level is then fixed by p = 0 on the outlet. On five meshes from 5k to +# 149k dofs, `dfg_reference_steady` gives the same cD, cL and Δp to seven digits with either formulation +# (`pressure = :weak` or `:strong`). +# - The pressure has no equation of its own: the continuity equation is paired with it explicitly, and the +# system is a DAE of index 2. Its initial state is consistent without index reduction because the flow starts +# at rest and the inflow is ramped up by 1 − exp(−t²), whose value and rate vanish at t = 0. The zero +# velocity is discretely divergence free, and p needs no initial condition: it is algebraic, starts at zero, +# and every residual row vanishes at t = 0. `CheckInit()` therefore only verifies that start. The default +# initialiser would instead solve the algebraic rows for the algebraic variables, and the continuity rows do +# not contain p, so its Newton matrix is singular in the pressure columns: there is nothing for it to fix +# and nothing it could determine. +# - The pressure, an index-2 algebraic variable, and the Dirichlet rows are left out of DFBDF's error control (an +# absolute tolerance of 1e8 on them): the local error of an index-2 variable does not shrink with the step, so +# with it DFBDF cuts the step to nothing. The Dirichlet rows are exact anyway with a W refreshed every step. +# - 2D-1 is steady: the DAE is integrated until the flow has settled, and the coefficients are evaluated at the +# final time with the time-derivative term of the force functional included. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF +using OrdinaryDiffEqBDF: NLNewton +using LinearSolve: UMFPACKFactorization +using ModelingToolkit: t_nounits as t +using SciMLBase: SciMLBase, CheckInit, init, solve! +using Ferrite: Ferrite + +include(joinpath(@__DIR__, "mesh.jl")) +include(joinpath(@__DIR__, "forces.jl")) + +"DFG 2D-1 reference values (Nabh 1998, John & Matthies 2001), quoted by the FEATFLOW benchmark pages." +const DFG_2D1 = (cD = 5.57953523384, cL = 0.010618948146, Δp = 0.11752016697) +"Acceptance intervals of the benchmark paper (Schäfer & Turek 1996, table 4): the tolerance this example meets." +const DFG_2D1_BANDS = (cD = (5.57, 5.59), cL = (0.0104, 0.011), Δp = (0.1172, 0.1176)) + +@parameters ν Umax +@variables x y u(..) v(..) p(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +""" + dfg_problem(grid; tend = 30.0, ν_ = 1e-3, Umax_ = 0.3, ramp = 1 - exp(-t^2), kwargs...) + +The `DAEProblem` of the DFG channel `grid` (from `dfg_channel_grid`) with peak inflow `Umax_` times `ramp`, an +expression in `t`; `kwargs` are passed to `FEMDiscretization`. +""" +function dfg_problem(grid; tend = 30.0, ν_ = 1.0e-3, Umax_ = 0.3, ramp = 1 - exp(-t^2), kwargs...) + Ω = MeshDomain(grid) + Γin, Γout, Γwall, Γcyl = boundarypiece.(Ω, (:inlet, :outlet, :walls, :cylinder)) + U, V, P = u(t, x, y), v(t, x, y), p(t, x, y) + eqs = [ + Dt(U) ~ Dx(ν * Dx(U)) + Dy(ν * Dy(U)) - U * Dx(U) - V * Dy(U) - Dx(P), + Dt(V) ~ Dx(ν * Dx(V)) + Dy(ν * Dy(V)) - U * Dx(V) - V * Dy(V) - Dy(P), + 0 ~ Dx(U) + Dy(V), + ] + inflow = ramp * 4Umax * y * (0.41 - y) / 0.41^2 + bcs = [ + u(t, Γin) ~ inflow, v(t, Γin) ~ 0, + u(t, Γwall) ~ 0, v(t, Γwall) ~ 0, + u(t, Γcyl) ~ 0, v(t, Γcyl) ~ 0, + p(t, Γout) ~ 0, + u(0, x, y) ~ 0, v(0, x, y) ~ 0, + ] + domains = [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)] + @named dfg = PDESystem(eqs, bcs, domains, [t, x, y], [U, V, P], [ν => ν_, Umax => Umax_]) + Q2, Q1 = Lagrange{RefQuadrilateral, 2}(), Lagrange{RefQuadrilateral, 1}() + disc = FEMDiscretization( + Ω, t; spaces = Dict(u => Q2, v => Q2, p => Q1), pairing = Dict(eqs[3] => p), + initializealg = CheckInit(), kwargs... + ) + return DAEProblem(dfg, disc) +end + +"Absolute tolerances: `abstol` on the differential variables, none (1e8) on the algebraic ones." +differential_abstol(prob, abstol) = [d ? abstol : 1.0e8 for d in prob.differential_vars] + +# UMFPACK by name: LinearSolve 5.18's default sparse LU (supernodal) throws "snlu! requires the same sparsity +# pattern as the analyzed matrix" on these Newton matrices, as it does on Ferrite's own ns_vs_diffeq tutorial. +# Naming it also removes the default's silent fall-back to sparse QR when a Newton matrix is singular, which +# for this index-2 system took tens of GB: a singular matrix now fails the step, and `check_solved` raises. +const DFG_ALG = DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()) + +"Raise unless `sol` succeeded and reached its final time (a callback can stop it early with `Terminated`, a success code); a DAE solve that stopped early must not report coefficients." +function check_solved(sol) + tend = last(sol.original_sol.prob.tspan) + SciMLBase.successful_retcode(sol) && sol.t[end] == tend && return sol + return error( + "the DFG solve stopped at t = $(sol.t[end]) of $tend with retcode $(sol.retcode); with the pressure in the error control or a singular Newton matrix DFBDF cuts its step to nothing" + ) +end + +""" + dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1e-7, reltol = 1e-7) + +Mesh, discretize and solve 2D-1; returns `(; sol, prob, coefficients, dxdt, ndofs, build_s, solve_s)` with the +coefficients `(cD, cL, Δp)` at `tend`. `dxdt` is the integrator's derivative at `tend`, used in the `∂ₜu` term of +the force functional: with `save_everystep = false` the saved solution has only its two end points, and its +derivative is the slope between them, not the derivative at `tend`. +""" +function dfg_solve(; h = 0.04, hc = 0.0025, tend = 60.0, alg = DFG_ALG, abstol = 1.0e-7, reltol = 1.0e-7) + grid = dfg_channel_grid(; h, hc) + build_s = @elapsed prob = dfg_problem(grid; tend) + integrator = init(prob, alg; abstol = differential_abstol(prob, abstol), reltol, save_everystep = false) + solve_s = @elapsed solve!(integrator) + sol = check_solved(SciMLBase.wrap_sol(integrator.sol)) + dh = sol.disc_data.space.dh + xend = sol.original_sol.u[end] + dxdt = copy(integrator.du) + coefficients = dfg_coefficients(dh, xend; ν = 1.0e-3, Umean = 0.2, dxdt) + return (; sol, prob, coefficients, dxdt, ndofs = length(prob.u0), build_s, solve_s) +end + +if abspath(PROGRAM_FILE) == @__FILE__ + h = isempty(ARGS) ? 0.06 : parse(Float64, ARGS[1]) + r = dfg_solve(; h, hc = h / 6) + c = r.coefficients + println("2D-1, h = $h: $(r.ndofs) dofs, build $(round(r.build_s; digits = 1)) s, solve $(round(r.solve_s; digits = 1)) s") + for k in (:cD, :cL, :Δp) + lo, hi = DFG_2D1_BANDS[k] + println(" $k = $(c[k]) (reference $(DFG_2D1[k]), relative error $(c[k] / DFG_2D1[k] - 1), band [$lo, $hi]: ", lo <= c[k] <= hi ? "pass" : "FAIL", ")") + end +end diff --git a/examples/dfg_cylinder/forces.jl b/examples/dfg_cylinder/forces.jl new file mode 100644 index 00000000..e51f4a28 --- /dev/null +++ b/examples/dfg_cylinder/forces.jl @@ -0,0 +1,70 @@ +using Ferrite: Ferrite +using LinearAlgebra: dot + +""" + dfg_coefficients(dh, x; ν, Umean, D = 0.1, dxdt = nothing, fields = (:u, :v, :p)) + +Drag and lift coefficients `(cD, cL)` of the cylinder (facet set `"cylinder"`) and the pressure difference +`Δp = p(0.15, 0.2) − p(0.25, 0.2)` between its front and back, from the dof vector `x` of the `DofHandler` `dh` +with velocity components `fields[1:2]` and pressure `fields[3]`. + +The forces are the weighted residuals of the momentum equations (John 2004, Braack & Richter 2006): +with `w` the finite-element function equal to `e_k` on the cylinder and zero at every other node, + + F_k = −∫_Ω (∂ₜu·w + ν ∇u : ∇w + (u·∇)u·w − p ∇·w) dx, + +which equals the surface integral `∮ (ν ∂ₙu − p n)·e_k` over the cylinder for the exact solution but converges +at the order of the energy error squared, where the surface integral of the discrete gradient converges at the +order of the energy error. `dxdt` is the time derivative of `x` (omit it for a steady state). The coefficients are +`2F/(Umean² D)` with unit density. +""" +function dfg_coefficients(dh, x; ν, Umean, D = 0.1, dxdt = nothing, fields = (:u, :v, :p)) + fu, fv, fp = fields + grid = dh.grid + sdh = only(dh.subdofhandlers) + ip_u = Ferrite.getfieldinterpolation(sdh, fu) + ip_p = Ferrite.getfieldinterpolation(sdh, fp) + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(grid)) + shape = Ferrite.getrefshape(ip_u) + qr = Ferrite.QuadratureRule{shape}(2 * Ferrite.getorder(ip_u) + 1) + cv_u, cv_p = Ferrite.CellValues(qr, ip_u, ip_geo), Ferrite.CellValues(qr, ip_p, ip_geo) + + # The weight is the nodal interpolant of 1 on the cylinder: the sum of its velocity basis functions. + w = zeros(Ferrite.ndofs(dh)) + ch = Ferrite.ConstraintHandler(dh) + Ferrite.add!(ch, Ferrite.Dirichlet(fu, Ferrite.getfacetset(grid, "cylinder"), Returns(1.0))) + Ferrite.close!(ch) + w[ch.prescribed_dofs] .= 1 + + ru, rv = Ferrite.dof_range(dh, fu), Ferrite.dof_range(dh, fv) + rp = Ferrite.dof_range(dh, fp) + F = zeros(2) + coords = Ferrite.getcoordinates(grid, 1) + for cell in 1:Ferrite.getncells(grid) + dofs = Ferrite.celldofs(dh, cell) + w_cell = w[dofs[ru]] + any(!iszero, w_cell) || continue + Ferrite.getcoordinates!(coords, grid, cell) + Ferrite.reinit!(cv_u, coords) + Ferrite.reinit!(cv_p, coords) + u_cell, v_cell, p_cell = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] + for q in 1:Ferrite.getnquadpoints(cv_u) + dΩ = Ferrite.getdetJdV(cv_u, q) + U = (Ferrite.function_value(cv_u, q, u_cell), Ferrite.function_value(cv_u, q, v_cell)) + ∇U = (Ferrite.function_gradient(cv_u, q, u_cell), Ferrite.function_gradient(cv_u, q, v_cell)) + ∂U = dxdt === nothing ? (0.0, 0.0) : + (Ferrite.function_value(cv_u, q, dxdt[dofs[ru]]), Ferrite.function_value(cv_u, q, dxdt[dofs[rv]])) + p = Ferrite.function_value(cv_p, q, p_cell) + W = Ferrite.function_value(cv_u, q, w_cell) + ∇W = Ferrite.function_gradient(cv_u, q, w_cell) + for k in 1:2 + convection = U[1] * ∇U[k][1] + U[2] * ∇U[k][2] + F[k] -= ((∂U[k] + convection) * W + ν * dot(∇U[k], ∇W) - p * ∇W[k]) * dΩ + end + end + end + scale = 2 / (Umean^2 * D) + ph = Ferrite.PointEvalHandler(grid, [Ferrite.Vec(0.15, 0.2), Ferrite.Vec(0.25, 0.2)]) + pfront, pback = Ferrite.evaluate_at_points(ph, dh, x, fp) + return (cD = scale * F[1], cL = scale * F[2], Δp = pfront - pback) +end diff --git a/examples/dfg_cylinder/mesh.jl b/examples/dfg_cylinder/mesh.jl new file mode 100644 index 00000000..86f8b82f --- /dev/null +++ b/examples/dfg_cylinder/mesh.jl @@ -0,0 +1,73 @@ +using Ferrite: Ferrite +using FerriteGmsh: FerriteGmsh +using Gmsh: Gmsh, gmsh + +""" + dfg_channel_grid(; h = 0.04, hc = h / 6, length = 2.2, order = 2) + +Quadrilateral mesh of the DFG/Schäfer–Turek 2D channel `[0, length] × [0, 0.41]` minus the cylinder of +radius 0.05 centred at `(0.2, 0.2)`, built with the Gmsh API and converted with `FerriteGmsh.togrid`. +The element size is `hc` on the cylinder, grows linearly to `h` at distance 0.25 from it and is `h` +elsewhere; halving both is one uniform refinement. `order = 2` gives `QuadraticQuadrilateral` cells whose +edge midpoints lie on the cylinder, so the cylinder is curved for an isoparametric Q2 field; `order = 1` +gives straight-edged `Quadrilateral`s. `length = 1.1` is the shortened channel of Ferrite's +`ns_vs_diffeq.jl` tutorial. + +Facet sets: `"inlet"` (`x = 0`), `"outlet"` (`x = length`), `"walls"` (`y = 0` and `y = 0.41`) and +`"cylinder"`. +""" +function dfg_channel_grid(; h = 0.04, hc = h / 6, length = 2.2, order = 2) + Gmsh.initialize() + try + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("dfg") + rect = gmsh.model.occ.addRectangle(0, 0, 0, length, 0.41) + disk = gmsh.model.occ.addDisk(0.2, 0.2, 0, 0.05, 0.05) + gmsh.model.occ.cut([(2, rect)], [(2, disk)]) + gmsh.model.occ.synchronize() + surfaces = gmsh.model.getEntities(2) + curves = [tag for (_, tag) in gmsh.model.getEntities(1)] + # Classify the boundary curves by their bounding boxes rather than by OCC's tag numbering. + on(tag, test) = test(gmsh.model.getBoundingBox(1, tag)...) + tol = 1.0e-6 + inlet = filter(c -> on(c, (x0, y0, z0, x1, y1, z1) -> x1 < tol), curves) + outlet = filter(c -> on(c, (x0, y0, z0, x1, y1, z1) -> x0 > length - tol), curves) + walls = filter(c -> on(c, (x0, y0, z0, x1, y1, z1) -> y1 < tol || y0 > 0.41 - tol), curves) + cylinder = setdiff(curves, inlet, outlet, walls) + gmsh.model.addPhysicalGroup(1, inlet, -1, "inlet") + gmsh.model.addPhysicalGroup(1, outlet, -1, "outlet") + gmsh.model.addPhysicalGroup(1, walls, -1, "walls") + gmsh.model.addPhysicalGroup(1, cylinder, -1, "cylinder") + gmsh.model.addPhysicalGroup(2, [tag for (_, tag) in surfaces], -1, "fluid") + + distance = gmsh.model.mesh.field.add("Distance") + gmsh.model.mesh.field.setNumbers(distance, "CurvesList", cylinder) + gmsh.model.mesh.field.setNumber(distance, "Sampling", 200) + threshold = gmsh.model.mesh.field.add("Threshold") + gmsh.model.mesh.field.setNumber(threshold, "InField", distance) + # Subdivision halves every edge, so the triangulation is made at twice the final size. + gmsh.model.mesh.field.setNumber(threshold, "SizeMin", 2hc) + gmsh.model.mesh.field.setNumber(threshold, "SizeMax", 2h) + gmsh.model.mesh.field.setNumber(threshold, "DistMin", 0.0) + gmsh.model.mesh.field.setNumber(threshold, "DistMax", 0.25) + gmsh.model.mesh.field.setAsBackgroundMesh(threshold) + gmsh.option.setNumber("Mesh.MeshSizeExtendFromBoundary", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromPoints", 0) + gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 0) + # Frontal-Delaunay for quads and Blossom recombination; the subdivision step splits any triangle + # Blossom leaves into three quadrilaterals, so the mesh is all quadrilaterals at every size. + gmsh.option.setNumber("Mesh.Algorithm", 8) + gmsh.option.setNumber("Mesh.RecombinationAlgorithm", 1) + gmsh.option.setNumber("Mesh.RecombineAll", 1) + gmsh.option.setNumber("Mesh.SubdivisionAlgorithm", 1) + gmsh.model.mesh.generate(2) + gmsh.model.mesh.setOrder(order) + grid = FerriteGmsh.togrid() + celltype = Ferrite.getcelltype(grid) + expected = order == 2 ? Ferrite.QuadraticQuadrilateral : Ferrite.Quadrilateral + celltype === expected || error("Gmsh left non-quadrilateral cells; the cell type is $celltype") + return grid + finally + Gmsh.finalize() + end +end diff --git a/examples/dfg_cylinder/reference.jl b/examples/dfg_cylinder/reference.jl new file mode 100644 index 00000000..8bb5e53a --- /dev/null +++ b/examples/dfg_cylinder/reference.jl @@ -0,0 +1,105 @@ +using Ferrite: Ferrite +using LinearAlgebra: dot, norm +using SparseArrays: SparseMatrixCSC + +""" + dfg_reference_steady(grid; ν = 1.0e-3, Umax = 0.3, tol = 1.0e-10, maxiter = 20) + +Hand-written Ferrite solution of the steady DFG 2D-1 problem on `grid` (from [`dfg_channel_grid`](@ref)): scalar +velocity components `u`, `v` on `Lagrange{RefQuadrilateral, 2}` and pressure `p` on `Lagrange{RefQuadrilateral, 1}`, +parabolic inflow of peak `Umax`, no slip on the walls and the cylinder, and the do-nothing condition +`ν ∂ₙu − p n = 0` at the outlet, solved by Newton's method from zero. Returns `(dh, x, iterations)`, and +raises if the residual norm is not below `tol` after `maxiter` iterations. + +This is the oracle the PDESystem path is compared with on the same mesh; it uses no FiniteElementMethod code. +""" +function dfg_reference_steady(grid; ν = 1.0e-3, Umax = 0.3, tol = 1.0e-10, maxiter = 20, pressure = :weak) + shape = Ferrite.RefQuadrilateral + ip_u, ip_p = Ferrite.Lagrange{shape, 2}(), Ferrite.Lagrange{shape, 1}() + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(grid)) + qr = Ferrite.QuadratureRule{shape}(4) + cv_u, cv_p = Ferrite.CellValues(qr, ip_u, ip_geo), Ferrite.CellValues(qr, ip_p, ip_geo) + dh = Ferrite.DofHandler(grid) + Ferrite.add!(dh, :u, ip_u) + Ferrite.add!(dh, :v, ip_u) + Ferrite.add!(dh, :p, ip_p) + Ferrite.close!(dh) + ch = Ferrite.ConstraintHandler(dh) + noslip = union(Ferrite.getfacetset(grid, "walls"), Ferrite.getfacetset(grid, "cylinder")) + inflow = Ferrite.getfacetset(grid, "inlet") + Ferrite.add!(ch, Ferrite.Dirichlet(:u, noslip, Returns(0.0))) + Ferrite.add!(ch, Ferrite.Dirichlet(:v, noslip, Returns(0.0))) + Ferrite.add!(ch, Ferrite.Dirichlet(:u, inflow, x -> 4Umax * x[2] * (0.41 - x[2]) / 0.41^2)) + Ferrite.add!(ch, Ferrite.Dirichlet(:v, inflow, Returns(0.0))) + pressure === :strong && Ferrite.add!(ch, Ferrite.Dirichlet(:p, Ferrite.getfacetset(grid, "outlet"), Returns(0.0))) + Ferrite.close!(ch) + + ru, rv, rp = Ferrite.dof_range(dh, :u), Ferrite.dof_range(dh, :v), Ferrite.dof_range(dh, :p) + nu, np = Ferrite.getnbasefunctions(cv_u), Ferrite.getnbasefunctions(cv_p) + ne = 2nu + np + J = Ferrite.allocate_matrix(dh) + r = zeros(Ferrite.ndofs(dh)) + x = zeros(Ferrite.ndofs(dh)) + Ferrite.apply!(x, ch) + Je, re = zeros(ne, ne), zeros(ne) + iterations = 0 + for it in 1:maxiter + assembler = Ferrite.start_assemble(J, r) + for cell in Ferrite.CellIterator(dh) + Ferrite.reinit!(cv_u, cell) + Ferrite.reinit!(cv_p, cell) + dofs = Ferrite.celldofs(cell) + u_cell, v_cell, p_cell = x[dofs[ru]], x[dofs[rv]], x[dofs[rp]] + fill!(Je, 0) + fill!(re, 0) + for q in 1:Ferrite.getnquadpoints(cv_u) + dΩ = Ferrite.getdetJdV(cv_u, q) + U = (Ferrite.function_value(cv_u, q, u_cell), Ferrite.function_value(cv_u, q, v_cell)) + ∇U = (Ferrite.function_gradient(cv_u, q, u_cell), Ferrite.function_gradient(cv_u, q, v_cell)) + p = Ferrite.function_value(cv_p, q, p_cell) + ∇p = Ferrite.function_gradient(cv_p, q, p_cell) + div = ∇U[1][1] + ∇U[2][2] + blocks = (ru, rv) + for i in 1:nu + φ, ∇φ = Ferrite.shape_value(cv_u, q, i), Ferrite.shape_gradient(cv_u, q, i) + for k in 1:2 + a = blocks[k][i] + conv = U[1] * ∇U[k][1] + U[2] * ∇U[k][2] + re[a] += (conv * φ + ν * dot(∇U[k], ∇φ) + (pressure === :strong ? ∇p[k] * φ : -p * ∇φ[k])) * dΩ + for j in 1:nu + ψ, ∇ψ = Ferrite.shape_value(cv_u, q, j), Ferrite.shape_gradient(cv_u, q, j) + # d(conv_k)/d(u_l) along ψ: U·∇ψ (l = k) + ψ ∂_l U_k + for l in 1:2 + b = blocks[l][j] + dconv = (l == k ? U[1] * ∇ψ[1] + U[2] * ∇ψ[2] : 0.0) + ψ * ∇U[k][l] + Je[a, b] += (dconv * φ + (l == k ? ν * dot(∇ψ, ∇φ) : 0.0)) * dΩ + end + end + for j in 1:np + Je[a, rp[j]] += ( + pressure === :strong ? Ferrite.shape_gradient(cv_p, q, j)[k] * φ : + -Ferrite.shape_value(cv_p, q, j) * ∇φ[k] + ) * dΩ + end + end + end + for i in 1:np + ψ = Ferrite.shape_value(cv_p, q, i) + re[rp[i]] += ψ * div * dΩ + for j in 1:nu + ∇φ = Ferrite.shape_gradient(cv_u, q, j) + Je[rp[i], ru[j]] += ψ * ∇φ[1] * dΩ + Je[rp[i], rv[j]] += ψ * ∇φ[2] * dΩ + end + end + end + Ferrite.assemble!(assembler, dofs, Je, re) + end + Ferrite.apply_zero!(J, r, ch) + resnorm = norm(r) + iterations = it + resnorm < tol && return dh, x, iterations + x .-= J \ r + end + return error("Newton's method did not converge in $maxiter iterations: residual norm $(norm(r)) at the last assembly, tolerance $tol") +end diff --git a/src/FiniteElementMethod.jl b/src/FiniteElementMethod.jl index 262977f7..27a4159c 100644 --- a/src/FiniteElementMethod.jl +++ b/src/FiniteElementMethod.jl @@ -38,7 +38,7 @@ include("weakform.jl") include("kernels.jl") include("assembly.jl") include("operators.jl") -export FieldInfo, FEMMetadata, piece_nodes, normal_flux, write_vtk +export FieldInfo, FEMMetadata, piece_nodes, normal_flux, write_vtk, facet_dofs, dof_coordinates, cell_dofs # Re-exported so that the user API of a FEM model needs no `using PDEBase, Ferrite`. export Lagrange, RefLine, RefTriangle, RefQuadrilateral, RefTetrahedron, RefHexahedron diff --git a/src/discretization.jl b/src/discretization.jl index df1bee3a..850d42e9 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -7,16 +7,22 @@ PDEBase.contains_point(grid::Ferrite.Grid, x) = _contains_point(grid, x) """ FEMDiscretization(Ω::MeshDomain, t = nothing; spaces = Dict(), regions = Dict(), quadrature = nothing, test_space = Galerkin(), ibp = Dict(), pairing = Dict(), - codegen = :numeric, dirichlet = :algebraic, kwargs...) + codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, kwargs...) Finite-element discretization of a `PDESystem` whose spatial domain is the mesh domain `Ω` (of a `Ferrite.Grid`), with time variable `t`. `discretize(pdesys, disc)` assembles the Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknown per field. +Without `t` the discretization is steady: the `PDESystem` must have no time variable, and +`discretize` (or `NonlinearProblem(pdesys, disc)`) returns a `NonlinearProblem` whose `solve` +gives a `PDENoTimeSolution`. - `spaces`: dependent variable (`u` or `u(t, x, y)`) `=>` `Ferrite.Interpolation`; the default is `Lagrange{RefShape, 1}()` on the mesh's reference shape. Fields may have different orders, such as the Taylor–Hood pair `Lagrange{RefTriangle, 2}()` for the - velocity and `Lagrange{RefTriangle, 1}()` for the pressure. + velocity and `Lagrange{RefTriangle, 1}()` for the pressure. The geometry is not a choice here: + cells are mapped with the geometric interpolation of the mesh's cell type, so a mesh of + quadratic cells (`QuadraticTriangle`, say, from a second-order Gmsh mesh) is mapped + isoparametrically. - `regions`: dependent variable `=>` `Region(Ω, name)`, a cell set of the mesh on which the field lives (a `Ferrite.SubDofHandler`); elsewhere it has no dofs, its equation is not assembled, it enters other equations as zero and the solution reads `NaN`. Its @@ -27,11 +33,42 @@ Galerkin operators with Ferrite and returns a `DAEProblem` with one array unknow stabilisation of every equation; linear terms only, and `τ` cannot reference parameters. - `ibp`: equation (or its index) `=>` `PDEBase.StrongForm` integration-by-parts policy. - `pairing`: equation `=>` dependent variable it is tested with, needed for an equation - with no time derivative of its own, such as `0 ~ Dxx(v) + f`. - - `codegen = :mtk` and `dirichlet = :eliminate` are reserved for later milestones and - raise; remaining keywords are passed to the `DAEProblem`, where a keyword given at the - `discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate` and `name` - are set by the discretization and rejected. + with no time derivative of its own, such as `0 ~ Dxx(v) + f`. In a steady system the + equations not named here take the remaining dependent variables in declared order. + - `algebraic_abstol`: the absolute tolerance the `DAEProblem` carries for its algebraic rows + (those with `differential_vars` false: algebraic fields and Dirichlet rows), so that they + are left out of the solver's error control. `:auto` sets `1e8` when the system has index + 2, that is when an algebraic field's own unknowns are absent from its equation (the + pressure in `0 ~ Dx(u1) + Dy(u2)`; a nonlinear term in the field, as in `0 ~ v^2 - u`, + counts as present), and nothing otherwise; a positive number sets that + value on the algebraic rows of any system; `nothing` sets nothing. The differential rows + get the `abstol` passed to `FEMDiscretization` or `DAEProblem` if it is a number, else + OrdinaryDiffEq's default `1e-6`; an array `abstol` passed there is used as it is. An + `abstol` passed to `solve` replaces the problem's whole vector. The keyword belongs to the + time-dependent (DAE) path: a steady discretization ignores `:auto` and `nothing` and + rejects a number. This keyword is not in the spec (§7.1, §7.6): without it, `DFBDF` + drives the step size of an index-2 system below `eps` near the initial time, since the + local error of the index-2 unknowns does not shrink with the step. + - `dirichlet`: how Dirichlet conditions enter the DAE (spec §7.3). The default `:algebraic` + keeps every dof as an unknown and makes each prescribed row the algebraic equation + `u_d = g_d(t)`. `:eliminate` removes the prescribed dofs: the unknowns are the free dofs + `fr`, the operators are `M[fr, fr]` and `K[fr, fr]` and the load is `F[fr] - K[fr, cd] g`; + nonlinear terms are evaluated at the full state with `u_cd = g` and keep their rows `fr`. + It needs Dirichlet data that are constant in time (they may vary in space); data that + depend on time raise `ArgumentError("dirichlet = :eliminate needs Dirichlet data that are + constant in time, but the condition on boundary piece depends on time; use the default + dirichlet = :algebraic")` from `discretize`. A field whose dofs are all prescribed has no + array unknown (its `FieldInfo.unknown` is `nothing`); if every dof of the problem is + prescribed, `discretize` raises `ArgumentError("dirichlet = :eliminate leaves no unknowns + because every dof is prescribed; use the default dirichlet = :algebraic")`. The solution + still returns full fields, with `g` at the prescribed nodes, through `sol[u]`, + `sol(t, x, y)`, traces and `write_vtk`; only `sol.original_sol` and the array unknowns + hold the free dofs alone. `:algebraic` is recommended. + - `codegen = :mtk` is reserved and raises; remaining keywords are + passed to the `DAEProblem` (or `NonlinearProblem`), where a keyword given at the + `discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters` are set + by the discretization and rejected, as are `tspan`, `u0`, `p` and `differential_vars`, which + come from the `PDESystem` and the weak form. Pieces come from `boundarypiece.(Ω, names)`; on an analytic DomainSets box write `boundarypiece.(Ref(rect), names)`, since DomainSets types do not broadcast as scalars. @@ -45,7 +82,9 @@ Fields are numbered in one order throughout (`DofHandler` blocks, array unknowns through `PDEBase.StrongForm.pair_equations`. Parameters are substituted by the values given in the `PDESystem` when the operators are -assembled, so `remake` with new parameter values does not reassemble them. +assembled, and are parameters of the problem at those values. The operators are not +reassembled for new values: after `remake(prob; p = [k => 3.0])` the solve throws an +`ArgumentError` naming `k`; build a new problem with `discretize(pdesys, disc)` instead. """ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization domain::PDEBase.MeshDomain @@ -58,14 +97,26 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization pairing::Dict{Equation, Any} codegen::Symbol dirichlet::Symbol + algebraic_abstol::Union{Symbol, Nothing, Float64} kwargs::NamedTuple end # Keywords of `numeric_dae_problem` that the front end sets itself. -const _RESERVED_KWARGS = (:iv, :unknowns, :du0, :coordinate, :name) +const _RESERVED_KWARGS = (:iv, :unknowns, :du0, :coordinate, :name, :parameters) + +# Problem keywords the front end computes, with where each value comes from instead. +const _DERIVED_KWARGS = ( + tspan = "the time span is the time domain of the PDESystem; change that domain to change it", + u0 = "the initial state comes from the PDESystem's initial conditions (a steady problem starts from zero " * + "with its Dirichlet data); change those, or call remake(prob; u0 = ...) on the returned problem", + p = "the parameter values are the PDESystem's parameter defaults; change those and discretize again " * + "(the operators are assembled at those values, so solve rejects remake(prob; p = ...))", + differential_vars = "which unknowns are differential is computed from the weak form (the fields with a time derivative)", +) function _check_reserved(kwargs) for k in keys(kwargs) + haskey(_DERIVED_KWARGS, k) && throw(ArgumentError("keyword `$k` cannot be passed: " * _DERIVED_KWARGS[k])) k in _RESERVED_KWARGS && throw( ArgumentError( "keyword `$k` is set by the FEM discretization and cannot be passed; the reserved keywords are " * @@ -79,27 +130,33 @@ end function FEMDiscretization( domain::PDEBase.MeshDomain, time = nothing; spaces = Dict(), regions = Dict(), quadrature = nothing, test_space = Galerkin(), ibp = Dict(), pairing = Dict(), codegen::Symbol = :numeric, - dirichlet::Symbol = :algebraic, kwargs... + dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, kwargs... ) domain.mesh isa Ferrite.Grid || throw(ArgumentError("FEMDiscretization needs a MeshDomain of a Ferrite.Grid, got a mesh of type $(typeof(domain.mesh))")) - codegen === :mtk && throw(ArgumentError("codegen = :mtk lands in M3; use the default codegen = :numeric")) + codegen === :mtk && throw(ArgumentError("codegen = :mtk is not supported; use the default codegen = :numeric")) codegen === :numeric || throw(ArgumentError("codegen must be :numeric, got $(repr(codegen))")) - dirichlet === :eliminate && - throw(ArgumentError("dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic")) - dirichlet === :algebraic || throw(ArgumentError("dirichlet must be :algebraic, got $(repr(dirichlet))")) + dirichlet in (:algebraic, :eliminate) || + throw(ArgumentError("dirichlet must be :algebraic or :eliminate, got $(repr(dirichlet))")) test_space isa Union{Galerkin, SUPG} || throw(ArgumentError("test_space must be Galerkin() or SUPG(τ; b = nothing), got $(repr(test_space))")) for (dv, region) in regions region isa PDEBase.Region && region.parent === domain || throw(ArgumentError("the region of $(_field_op(dv)) must be a Region of the FEMDiscretization's MeshDomain, as Region(Ω, name); got $(repr(region))")) end + algebraic_abstol === :auto || algebraic_abstol === nothing || algebraic_abstol isa Real && algebraic_abstol > 0 || + throw(ArgumentError("algebraic_abstol must be :auto, nothing or a positive number, got $(repr(algebraic_abstol))")) + time === nothing && algebraic_abstol isa Real && throw( + ArgumentError( + "algebraic_abstol applies to time-dependent problems (the DAE path); a steady FEMDiscretization has no time stepper" + ) + ) _check_reserved(kwargs) return FEMDiscretization{typeof(time)}( domain, time, Dict{Any, Ferrite.Interpolation}(_field_op(k) => ip for (k, ip) in spaces), Dict{Any, Any}(_field_op(k) => r for (k, r) in regions), quadrature, test_space, Dict{Any, StrongForm.IBPPolicy}(ibp), Dict{Equation, Any}(pairing), - codegen, dirichlet, NamedTuple(kwargs) + codegen, dirichlet, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, NamedTuple(kwargs) ) end @@ -128,12 +185,12 @@ PDEBase.supported_conditions(::FEMDiscretization) = PDEBase.SupportedConditions( Restrictions of this release: - Geometries are `Ferrite.Grid` meshes (1D, 2D and 3D cell shapes) wrapped as `MeshDomain(grid)`, with boundary pieces named by the grid's facet sets. Only 1D and 2D are evidenced; meshes with mixed cell types are rejected until M4. - - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time must be the first argument of every dependent variable. + - Coordinates are Cartesian and named by the `(x, y) ∈ Ω` pairing. Time is the first or last argument of every dependent variable, never between spatial arguments. - Dirichlet data may depend on space, time and parameters but not on another field. Neumann and Robin conditions are written with `NormalDerivative(Γ)`, with any conormal coefficient written explicitly. Neumann and Robin data may depend on time; the Robin coefficient multiplying `u(t, Γ)` may depend only on space and parameters until M3. - Periodic conditions `u(t, Γa) ~ u(t, Γb)` are rejected until M4. Interface conditions between regions have no syntax; every field lives on the whole mesh. - Boundary pieces must be disjoint. A piece with no condition gets the natural zero-flux condition, with a warning when the operator has a flux. - Where two Dirichlet pieces of one field meet, the condition listed last in the `PDESystem` wins. - Every field with a time derivative needs an initial condition, linear in that one field and finite at every node. - - Steady problems, `dirichlet = :eliminate`, fields with different interpolations and test spaces other than `Galerkin()` are rejected until M4. Nonlinear operators, time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. + - Time-dependent mass or stiffness coefficients and `codegen = :mtk` are rejected until M3. """ ) diff --git a/src/frontend.jl b/src/frontend.jl index 8956bc8c..1196f0c2 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -8,7 +8,7 @@ # Tracking: move to PDEBase's `symbolic_discretize` with hook methods once the numeric path builds # its system through `generate_system` (PDEBase M0 release as the compat floor). -const _PERIODIC_M4 = "periodic conditions need milestone M4 (Ferrite PeriodicDirichlet)" +const _PERIODIC_UNSUPPORTED = "periodic boundary conditions are not supported" _unwrap_arg(a) = SymbolicUtils.unwrap_const(unwrap(a)) @@ -56,7 +56,16 @@ function _check_domains(pdesys, disc::FEMDiscretization) pairings[i].domain === disc.domain || throw(ArgumentError("the PDESystem's MeshDomain is not the domain of the FEMDiscretization")) t = disc.time - t === nothing && return nothing + if t === nothing + j = findfirst(d -> d.domain isa DomainSets.AbstractInterval, pairings) + j === nothing || throw( + ArgumentError( + "the PDESystem pairs $(pairings[j].variables) with an interval, but the FEMDiscretization has no time " * + "variable; for a time-dependent problem write FEMDiscretization(Ω, $(pairings[j].variables))" + ) + ) + return nothing + end j = findfirst(d -> isequal(unwrap(d.variables), unwrap(t)), pairings) (j === nothing || !(pairings[j].domain isa DomainSets.AbstractInterval)) && throw(ArgumentError("time $t must be paired with an interval, as in $t ∈ Interval(0.0, 1.0)")) @@ -79,8 +88,8 @@ function PDEBase.interface_errors(pdesys::ModelingToolkit.PDESystem, v::PDEBase. t = v.time for u in dvs args = SymbolicUtils.arguments(unwrap(u)) - t !== nothing && any(a -> isequal(a, t), args) && !isequal(first(args), t) && - throw(ArgumentError("time must be the first argument of $u; time-last ordering lands later")) + t !== nothing && any(a -> isequal(a, t), args[2:(end - 1)]) && + throw(ArgumentError("time must be the first or the last argument of $u, as in u(t, x, y) or u(x, y, t)")) end grid = disc.domain.mesh if !isconcretetype(Ferrite.getcelltype(grid)) @@ -91,7 +100,7 @@ function PDEBase.interface_errors(pdesys::ModelingToolkit.PDESystem, v::PDEBase. "`spaces`; $(join(unset, ", ")) has none" ) ) - throw(ArgumentError("meshes with mixed cell types land in M4")) + throw(ArgumentError("meshes with mixed cell types are not supported; use a mesh with a single cell type")) end check_facetsets(grid, [Γ.name for Γ in _condition_pieces(pdesys.bcs)]) return nothing @@ -99,7 +108,7 @@ end function _boundary_map(bcs, v, disc) for eq in bcs - length(_trace_pieces(eq.lhs - eq.rhs)) > 1 && throw(ArgumentError("$(_PERIODIC_M4): $eq")) + length(_trace_pieces(eq.lhs - eq.rhs)) > 1 && throw(ArgumentError("$(_PERIODIC_UNSUPPORTED): $eq")) end orders = Dict(x => PDEBase.d_orders(x, bcs) for x in PDEBase.all_ivs(v)) return PDEBase.parse_bcs(bcs, v, orders, disc) @@ -123,6 +132,14 @@ function _paired(an, eqs, ctx, disc) f === nothing && throw(ArgumentError("pairing value $dv is not a dependent variable of the system")) explicit[e] = f end + # A steady system has no time derivatives to pair by, so the unnamed equations take the + # unnamed fields in declared order. + if disc.time === nothing + free = [f for f in eachindex(ctx.ops) if !(f in values(explicit))] + for e in eachindex(eqs) + haskey(explicit, e) || (explicit[e] = popfirst!(free)) + end + end fields = StrongForm.pair_equations(an.mass, an.slots; pairing = explicit) order = invperm(fields) natural = [typeof(bc)(bc.piece, fields[bc.eq], bc.Φ) for bc in an.natural] @@ -150,19 +167,18 @@ function _check_supg(test_space, an, ctx) return nothing end -function _check_linear(wf) +function _check_terms(wf) for term in vcat(wf.volume, wf.facet) - term.kind === :nonlinear && - throw(ArgumentError("nonlinear terms land in M3: equation $(term.eq) has the nonlinear term $(term.integrand)")) term.kind in (:mass, :bilinear) && term.timedep && throw( - ArgumentError("time-dependent coefficients in the mass or stiffness operator land in M3: equation $(term.eq) has $(term.integrand)") + ArgumentError("time-dependent coefficients in the mass or stiffness operator are not supported: equation $(term.eq) has $(term.integrand)") ) end return nothing end function _parameter_values(pdesys, ctx) - given = Dict{Any, Any}(unwrap(p.first) => p.second for p in pdesys.ps if p isa Pair) + ps = pdesys.ps isa SciMLBase.NullParameters ? () : pdesys.ps + given = Dict{Any, Any}(unwrap(p.first) => p.second for p in ps if p isa Pair) return map(ctx.params) do p haskey(given, p) && given[p] isa Number || throw(ArgumentError("parameter $p needs a numeric value in the PDESystem, as $p => value")) @@ -253,14 +269,6 @@ function assemble_sources!(F, ctx::AssemblyContext, kernels, p, t) return F end -# `reinit!` mutates CellValues and FacetValues, so each load evaluation gets its own copies and -# concurrent solves of one problem's remakes share no mutable state. -function _fresh_values(ctx::AssemblyContext{NF, DH, CV, FV}) where {NF, DH, CV, FV} - return AssemblyContext{NF, DH, CV, FV}( - ctx.dh, ctx.fields, map(copy, ctx.cellvalues), map(copy, ctx.facetvalues), ctx.facetsets, ctx.facetcells - ) -end - function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) kernels = emit_kernels(wf) # `emit_kernels` sums the terms sharing an equation, kind and piece, so a kernel is dynamic when any of its terms is. @@ -275,13 +283,16 @@ function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) M, K, F = copy(space.pattern), copy(space.pattern), zeros(n) assemble_linear!(M, K, F, ctx, static, pvals; t = t0) load = isempty(dynamic) ? F : (out, t) -> (assemble_sources!(out, _fresh_values(ctx), dynamic, pvals, t); out .+= F) + nonlinear = any(k -> k.kind === :nonlinear, kernels) ? + FEMNonlinear(NonlinearOperator(_fresh_values(ctx), kernels; ch = space.ch), pvals) : nothing coords = _dof_coordinates(space) values!, values0 = _dirichlet_values(space, dirichlet, coords, pvals, t0) ops = FEMOperators( M, K, load, [name => field_range(space, name) for name in names]; - prescribed = prescribed_dofs(space), dirichlet_values = timedep_dirichlet ? values! : values0 + prescribed = prescribed_dofs(space), dirichlet_values = timedep_dirichlet ? values! : values0, nonlinear ) - return ops, coords + raw = (; M, K, load, nonlinear = nonlinear !== nothing, prescribed = prescribed_dofs(space), dirichlet_values = values0, timedep_dirichlet) + return ops, coords, raw end function _initial_values(ics, ctx, space, coords, an, names, pvals) @@ -317,7 +328,6 @@ function _initial_values(ics, ctx, space, coords, an, names, pvals) end function _lower(pdesys, disc::FEMDiscretization) - disc.time === nothing && throw(ArgumentError("steady problems land in M4; give FEMDiscretization a time variable")) _check_domains(pdesys, disc) sys, replaced = PDEBase.make_pdesys_compatible(pdesys) v = PDEBase.VariableMap(sys, disc; replaced_vars = replaced) @@ -326,7 +336,7 @@ function _lower(pdesys, disc::FEMDiscretization) ics, bcmap = PDEBase.split_ics_bcs(boundarymap, v, disc) ctx = StrongForm.SlotContext(sys, v) an = _paired(StrongForm.analyse(sys, v, boundarymap; ibp = disc.ibp), pdesys.eqs, ctx, disc) - isempty(an.periodic) || throw(ArgumentError(_PERIODIC_M4)) + isempty(an.periodic) || throw(ArgumentError(_PERIODIC_UNSUPPORTED)) covered = Set(Γ for bykey in values(bcmap) for (Γ, bs) in bykey if !isempty(bs)) if any(c -> !all(x -> isequal(x, 0), c), an.conormal) for Γ in PDEBase.boundarypieces(disc.domain) @@ -335,33 +345,90 @@ function _lower(pdesys, disc::FEMDiscretization) end disc.test_space isa SUPG && _check_supg(disc.test_space, an, ctx) wf = weak_form(an; test_space = disc.test_space) - _check_linear(wf) + steady = disc.time === nothing + _check_terms(wf) + disc.test_space isa SUPG && any(term -> term.kind === :nonlinear, wf.volume) && throw( + ArgumentError("SUPG stabilises linear terms only, but the system has a nonlinear term; use test_space = Galerkin()") + ) pvals = _parameter_values(sys, ctx) dirichlet = emit_dirichlet(an) - t0, t1 = v.intervals[v.time] + t0, t1 = steady ? (0.0, 0.0) : v.intervals[v.time] space, names, ips = _space(disc, ctx, an, dirichlet, pvals, t0) - timedep_dirichlet = any(bc -> _depends(bc.g, [an.slots.T]), an.essential) - ops, coords = _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) + timedep = findfirst(bc -> _depends(bc.g, [an.slots.T]), an.essential) + disc.dirichlet === :eliminate && timedep !== nothing && throw( + ArgumentError( + "dirichlet = :eliminate needs Dirichlet data that are constant in time, but the condition on boundary piece " * + "$(an.essential[timedep].piece.name) depends on time; use the default dirichlet = :algebraic" + ) + ) + ops, coords, raw = _operators(space, wf, names, dirichlet, pvals, t0, timedep !== nothing) u0 = _initial_values(Equation[b.eq for b in ics], ctx, space, coords, an, names, pvals) dirichlet_values!(view(u0, ops.prescribed), ops.load, t0) + elimination = nothing + unknown_u0 = u0 + if disc.dirichlet === :eliminate + ops, elimination = eliminate_dirichlet(ops) + unknown_u0 = u0[elimination.free] + end iv = disc.time - unknowns = [only(@variables $name(iv)[1:length(field_range(space, name))]) for name in names] - fields = [FieldInfo(dv, name, u, ip) for (dv, name, u, ip) in zip(StrongForm.declared_fields(sys, v), names, unknowns, ips)] + unknowns = map(ops.fields) do (name, r) + steady ? only(@variables $name[1:length(r)]) : only(@variables $name(iv)[1:length(r)]) + end + unknown_of = Dict(zip(first.(ops.fields), unknowns)) + fields = [ + FieldInfo(dv, name, get(unknown_of, name, nothing), ip) + for (dv, name, ip) in zip(StrongForm.declared_fields(sys, v), names, ips) + ] pieces = Dict{Any, String}(Γ => String(Γ.name) for Γ in PDEBase.boundarypieces(disc.domain)) - md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0) - return (; ops, u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys)) + md = FEMMetadata(space, iv, v.x̄, fields, pieces, pdesys; u0, elimination) + parameters = [q => v for (q, v) in zip(ctx.params, pvals)] + selfnonlinear = Set(names[f] for f in 1:an.nfields if _nonlinear_in_own_field(wf, an, f)) + return (; ops, u0 = unknown_u0, tspan = (t0, t1), md, iv, unknowns, name = nameof(pdesys), parameters, selfnonlinear, raw, full_u0 = u0) +end + +# `K u + N(u, t0) - F` with the Dirichlet rows `u_d - g_d`: `K` holds `e_d`, `F` holds `g_d` and `N` is zero there. +function _steady_problem(parts; kwargs...) + (; ops) = parts + t0 = first(parts.tspan) + F = load!(zeros(length(parts.u0)), ops.load, t0) + N = ops.nonlinear + function f!(res, u, p) + mul!(res, ops.K, u) + res .-= F + N === nothing || add_nonlinear!(res, N, u, t0) + return nothing + end + function jac!(J, u, p) + check_pattern(J, ops.K, "the Jacobian") + copyto!(nonzeros(J), nonzeros(ops.K)) + N === nothing || add_nonlinear_jacobian!(J, N, u, t0) + return nothing + end + f = SciMLBase.NonlinearFunction{true}(f!; jac = jac!, jac_prototype = copy(ops.K)) + return SciMLBase.NonlinearProblem{true}(f, parts.u0, SciMLBase.NullParameters(), parts.md; kwargs...) end """ discretize(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) -Discretize `pdesys` with `disc` and return the `DAEProblem` `M du + K u = F(t)` of the -Galerkin operators, with Dirichlet rows `u_d = g_d(t)` as algebraic equations, a sparse -analytic Jacobian and the `FEMMetadata` as its `problem_type`, so `solve` returns a -`PDETimeSeriesSolution`. Nothing calls `mtkcompile`; anything this milestone cannot -discretize raises. Keywords are passed to the `DAEProblem` after `disc.kwargs`, so a keyword -given here wins; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, -`name`) are rejected. +Discretize `pdesys` with `disc` and return the `DAEProblem` `M du + K u + N(u, t) = F(t)` of +the Galerkin operators, with Dirichlet rows `u_d = g_d(t)` as algebraic equations (or, with +`dirichlet = :eliminate`, restricted to the free dofs), a sparse +analytic Jacobian (the nonlinear part `N` from the terms whose coefficients depend on the +state, with its symbolic tangent) and the `FEMMetadata` as its `problem_type`, so `solve` returns a +`PDETimeSeriesSolution` (`SciMLBase.wrap_sol` of the solver's solution). Nothing calls +`mtkcompile`; anything it cannot discretize raises. A `disc` without a time variable lowers instead to the steady +`NonlinearProblem` documented under `NonlinearProblem(pdesys, disc)`. Keywords are passed to +the `DAEProblem` after `disc.kwargs`, so a keyword given here wins; the keywords the discretization sets (`iv`, `unknowns`, `du0`, `coordinate`, +`name`, `parameters`) are rejected, and so are `tspan` (the `PDESystem`'s time domain), `u0` (its +initial conditions; use `remake(prob; u0)`), `p` (its parameter defaults) and `differential_vars` +(computed from the weak form). The problem carries an `abstol` vector when `disc.algebraic_abstol` +applies (see [`FEMDiscretization`](@ref)). Any other SciML problem or solver keyword (`saveat`, +`tstops`, `callback`, ...) is forwarded. Further positional arguments, a first argument that is not +a `PDESystem`, and an equation, domain or boundary condition the discretization does not support +raise an `ArgumentError` before the operators are assembled. +[`symbolic_discretize`](@ref SciMLBase.symbolic_discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization)) +returns the symbolic system of the same discretization. The Dirichlet rows are linear with identity Jacobian rows, so a Newton step with a current Jacobian satisfies them exactly. OrdinaryDiffEq's BDF methods reuse the Jacobian across @@ -372,17 +439,155 @@ size change and holds `u(t, Γ) ~ g(t)` to round-off. function SciMLBase.discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) _check_reserved(kwargs) parts = _lower(pdesys, disc) + disc.time === nothing && return _steady_problem(parts; disc.kwargs..., kwargs...) + kwargs = merge(disc.kwargs, values(kwargs)) return numeric_dae_problem( parts.ops, parts.u0, parts.tspan, parts.md; - iv = parts.iv, unknowns = parts.unknowns, name = parts.name, disc.kwargs..., kwargs... + iv = parts.iv, unknowns = parts.unknowns, name = parts.name, parameters = parts.parameters, kwargs..., + _abstol(disc.algebraic_abstol, parts.ops, parts.selfnonlinear, get(kwargs, :abstol, nothing))... ) end +# An algebraic field whose own unknowns are absent from its equation (the pressure in the continuity equation) is +# fixed only through the other fields, which makes the DAE index 2. The nonlinear Jacobian shares K's pattern and +# says nothing about which blocks are zero, so a field in `selfnonlinear`, whose equation has a nonlinear term in +# the field itself (0 = v² − u), counts as present. +function _index2(ops::FEMOperators, selfnonlinear) + free = trues(size(ops.K, 1)) + free[ops.prescribed] .= false + return any(ops.fields) do (name, r) + rows = filter(i -> free[i], r) + !isempty(rows) && !(name in selfnonlinear) && !any(ops.differential_vars[rows]) && iszero(ops.K[rows, r]) + end +end + +# Whether a nonlinear term of equation `f` (paired with field `f`) reads field `f`'s value, gradient or Hessian. +function _nonlinear_in_own_field(wf, an, f) + d = an.dim + own = [an.slots.U[f]; an.slots.G[((f - 1) * d + 1):(f * d)]; an.slots.H[((f - 1) * d * d + 1):(f * d * d)]] + return any(term -> term.kind === :nonlinear && term.eq == f && _depends(unwrap(term.integrand), own), [wf.volume; wf.facet]) +end + +# The `abstol` keyword of the `DAEProblem` (see `FEMDiscretization`'s `algebraic_abstol`); empty when none is set. +function _abstol(algebraic, ops, selfnonlinear, abstol) + algebraic === :auto && (algebraic = _index2(ops, selfnonlinear) ? 1.0e8 : nothing) + (algebraic === nothing || !(abstol isa Union{Nothing, Real})) && return (;) + differential = something(abstol, 1.0e-6) + return (; abstol = [d ? differential : algebraic for d in ops.differential_vars]) +end + SciMLBase.DAEProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) = - SciMLBase.discretize(pdesys, disc; kwargs...) + disc.time === nothing ? + throw( + ArgumentError( + "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem, not a DAEProblem; " * + "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" + ) + ) : SciMLBase.discretize(pdesys, disc; kwargs...) + +""" + NonlinearProblem(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) + +Discretize the steady `pdesys` with a `disc` that has no time variable and return the +`NonlinearProblem` `K u + N(u) - F = 0` of the Galerkin operators, with Dirichlet rows +`u_d - g_d` as algebraic equations, the sparse analytic Jacobian `K + ∂N/∂u` and the +`FEMMetadata` as its `problem_type`, so `solve` returns a `PDENoTimeSolution`. `N` holds the +terms whose coefficients depend on the state, as on the time-dependent path; without them +Newton solves the problem in one step. + +The initial guess `u0` is zero, with the Dirichlet data `g_d` wherever the problem's unknown +vector holds Dirichlet dofs; a steady `PDESystem` has no initial conditions. To start Newton +elsewhere, `remake(prob; u0)` with a vector laid out like `prob.u0`, the problem's unknown +vector (with the default `dirichlet = :algebraic` it holds every dof, and field `name` +occupies `FiniteElementMethod.field_range(prob.problem_type.space, name)`). +Keywords are passed to the `NonlinearProblem` after `disc.kwargs`; the keywords +`iv`, `unknowns`, `du0`, `coordinate`, `name`, `parameters`, `tspan`, `u0`, `p` and +`differential_vars` are rejected, as for the `DAEProblem`. +""" +function SciMLBase.NonlinearProblem(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization; kwargs...) + disc.time === nothing || throw( + ArgumentError( + "the FEMDiscretization has the time variable $(disc.time), so it lowers to a DAEProblem; " * + "for a steady problem write FEMDiscretization(Ω) without a time variable" + ) + ) + return SciMLBase.discretize(pdesys, disc; kwargs...) +end -# `(sys, tspan)`, the shape PDEBase and MethodOfLines return. -function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) - prob = SciMLBase.discretize(pdesys, disc) +SciMLBase.discretize(::ModelingToolkit.PDESystem, ::FEMDiscretization, arg, args...; kwargs...) = + throw(ArgumentError("discretize(pdesys, disc; kwargs...) takes no further positional arguments; got $(length(args) + 1)")) + +SciMLBase.discretize(x, ::FEMDiscretization, args...; kwargs...) = + throw(ArgumentError("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got $(typeof(x))")) + +""" + symbolic_discretize(pdesys::PDESystem, disc::FEMDiscretization; kwargs...) + +Return `(sys, tspan)`, the shape PDEBase and MethodOfLines return, for the discretization that +`discretize(pdesys, disc; kwargs...)` builds: it runs the same code path, so it assembles the +Galerkin operators, and returns the `DAEProblem`'s `prob.f.sys` and `prob.tspan`. `sys` is the +completed `ModelingToolkit.System` of [`FiniteElementMethod.fem_system`](@ref), whose unknowns are +the arrays of field values, with the operators as parameters and the `FEMMetadata` (the +problem's `problem_type`) attached for rebuilding the solution; `tspan` is the time interval of +`pdesys`. Keywords are passed to that problem construction as for `discretize`, +so the reserved keywords raise the same `ArgumentError`. Further positional arguments raise an +`ArgumentError`. + +A steady `disc` (no time variable) raises an `ArgumentError`: its `NonlinearProblem` is built +from a numeric `NonlinearFunction` with no `System`, so there is no symbolic system describing +it; call `discretize(pdesys, disc)` for the `NonlinearProblem`. +""" +function SciMLBase.symbolic_discretize(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization, args...; kwargs...) + isempty(args) || throw( + ArgumentError( + "symbolic_discretize(pdesys, disc; kwargs...) takes no further positional arguments; got $(length(args))" + ) + ) + disc.time === nothing && throw( + ArgumentError( + "a steady FEMDiscretization builds no symbolic System, so it has no symbolic_discretize; " * + "call discretize(pdesys, disc) for its NonlinearProblem" + ) + ) + prob = SciMLBase.discretize(pdesys, disc; kwargs...) return prob.f.sys, prob.tspan end + +""" + operators(pdesys::PDESystem, disc::FEMDiscretization) -> NamedTuple + +The assembled Galerkin operators of `discretize(pdesys, disc)` as plain data, for a caller that +builds its own system around them (such as a component with boundary ports). Returns + + - `M`, `K`: the mass and stiffness matrices with one sparsity pattern, before any Dirichlet row + is replaced, so a caller can impose its own conditions or read reactions from them; + - `F`: the load vector, the volume sources and natural boundary data, without Dirichlet values; + - `fields`: `name => dof range` per field, in declared order; + - `differential_vars`: rows of `M` with a nonzero entry; + - `prescribed`, `dirichlet_values`: the dofs of the `PDESystem`'s Dirichlet conditions and + their values (the rows `M` and `K` would have replaced); + - `u0`: the initial dof vector, with the Dirichlet values on the prescribed dofs; + - `metadata`: the [`FEMMetadata`](@ref), for [`facet_dofs`](@ref), + [`dof_coordinates`](@ref) and [`cell_dofs`](@ref). + +It is the linear, time-independent case only: a nonlinear term, a time-dependent source or +time-dependent Dirichlet data has no data form and raises an `ArgumentError`. Parameters are +substituted by their values, as for the `DAEProblem`. +""" +function operators(pdesys::ModelingToolkit.PDESystem, disc::FEMDiscretization) + parts = _lower(pdesys, disc) + (; M, K, load, nonlinear, prescribed, dirichlet_values, timedep_dirichlet) = parts.raw + nonlinear && throw(ArgumentError("operators returns linear operators only, but the PDESystem has nonlinear terms")) + load isa AbstractVector || throw(ArgumentError("operators needs time-independent sources, but a source depends on time")) + timedep_dirichlet && throw(ArgumentError("operators needs Dirichlet data that are constant in time")) + differential_vars = falses(size(M, 1)) + for (k, i) in enumerate(rowvals(M)) + iszero(nonzeros(M)[k]) || (differential_vars[i] = true) + end + md = parts.md + fields = [f.name => field_range(md.space, f.name) for f in md.fields] + return (; + M = copy(M), K = copy(K), F = copy(load), fields, differential_vars, prescribed = copy(prescribed), + dirichlet_values = copy(dirichlet_values), u0 = parts.full_u0, metadata = md, + ) +end diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index ece30738..ff1cbea7 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -50,6 +50,10 @@ function load!(out, F::FEMLoad, t) return out end +# ForwardDiff residuals, as from the default initializer's NewtonRaphson: the load does not depend on the state +# and is assembled in `Float64`. +load!(out::AbstractVector{<:ForwardDiff.Dual}, F::FEMLoad, t) = (out .= load!(zeros(length(out)), F, t)) + function dirichlet_values!(out, F::FEMLoad, t) g = F.values if g isa Union{Number, AbstractVector} @@ -91,9 +95,135 @@ fem_load(op::FEMLoad, rows::UnitRange{Int}, t) = load!(zeros(op.n), op, t)[rows] end """ - FEMOperators(M, K, load, fields; prescribed = Int[], dirichlet_values = 0.0) + FEMNonlinear(op, p) + +Opaque wrapper for the nonlinear part `N(u, t)` of `M du + K u + N(u, t) = F(t)`, used as a +non-tunable `System` parameter like [`FEMOp`](@ref): `op` is a [`NonlinearOperator`](@ref) +and `p` the parameter values its kernels are evaluated with. [`FEMOperators`](@ref) marks the +prescribed dofs, whose rows of `N` and of its Jacobian are then zero. `op` is untyped so that +the parameter has one concrete type; each call dispatches on it once. `op` itself is never +evaluated: each evaluation borrows a copy with its own buffers and values objects from a pool, +so problems sharing this wrapper (remakes, ensembles) can be solved concurrently. +After [`eliminate_dirichlet`](@ref) the wrapper evaluates `N` at the full state rebuilt from +the free dofs with `u_d = g_d`, and keeps its free rows and its `[free, free]` Jacobian block. + +The element pipeline is `Float64`: `N` is evaluated at `Float64` states and at first-order +`ForwardDiff.Dual`s of `Float64` (as the default initializer passes), whose partials go through +the analytic tangent. Any other state, such as `Float32`, `BigFloat`, `Dual`s of those or nested +`Dual`s, throws `ArgumentError("the nonlinear operator evaluates Float64 states and first-order +ForwardDiff Duals of Float64; got T")` with `T` the state's element type; its Jacobian is +evaluated at `Float64` states only and otherwise throws `ArgumentError("the nonlinear +operator's Jacobian evaluates Float64 states; got T")`. +""" +struct FEMNonlinear + op::Any + p::Vector{Float64} + prescribed::BitVector + pool::Vector{Any} + lock::ReentrantLock + elimination::Any # `nothing`, or `(e::DirichletElimination, nzmap)` with `nzmap` the positions of `J_N[free, free]` in `J_N` +end +FEMNonlinear(op, p, prescribed = falses(0)) = FEMNonlinear(op, collect(Float64, p), prescribed, Any[], ReentrantLock(), nothing) +Base.show(io::IO, ::FEMNonlinear) = print(io, "FEMNonlinear") + +# `f(op)` with an operator no other running call holds; the pool grows to the number of concurrent calls. +function with_operator(f, N::FEMNonlinear) + op = @lock N.lock isempty(N.pool) ? nothing : pop!(N.pool) + op === nothing && (op = independent_copy(N.op)) + try + return f(op) + finally + @lock N.lock push!(N.pool, op) + end +end + +check_state(::AbstractVector{Float64}) = nothing +check_state(::AbstractVector{<:ForwardDiff.Dual{<:Any, Float64}}) = nothing +check_state(u) = throw(ArgumentError("the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got $(eltype(u))")) + +# `r .+= N(u, t)` outside the prescribed rows. After elimination `u` and `r` hold the free dofs only. +function add_nonlinear!(r, N::FEMNonlinear, u, t) + check_state(u) + N.elimination === nothing && return add_full_nonlinear!(r, N, u, t) + e = first(N.elimination) + r .+= view(add_full_nonlinear!(zeros(eltype(r), e.n), N, full_state(e, u), t), e.free) + return r +end + +function add_full_nonlinear!(r, N::FEMNonlinear, u, t) + return with_operator(N) do op + residual!(op.r, op, u, N.p, t) + for i in eachindex(r) + N.prescribed[i] || (r[i] += op.r[i]) + end + r + end +end + +# ForwardDiff states, as from the default initializer's NewtonRaphson: the partials are pushed through the +# analytic tangent, `∂N(u) = J_N(value(u)) ∂u`, since the element buffers hold `Float64`. +function add_full_nonlinear!(r, N::FEMNonlinear, u::AbstractVector{ForwardDiff.Dual{T, Float64, P}}, t) where {T, P} + du = [ForwardDiff.partials(x, k) for x in u, k in 1:P] + return with_operator(N) do op + J = jacobian!(op.J, op, ForwardDiff.value.(u), N.p, t) + dr = J * du + for i in eachindex(r) + N.prescribed[i] || (r[i] += ForwardDiff.Dual{T}(op.r[i], ForwardDiff.Partials(ntuple(k -> dr[i, k], Val(P))))) + end + r + end +end + +nonlinear_residual!(r, N::FEMNonlinear, u, t) = add_nonlinear!(fill!(r, 0), N, u, t) + +# `nonzeros(J) .+= nonzeros(∂N/∂u)` outside the prescribed rows; `J` must have the pattern of `N`'s Jacobian. +function add_nonlinear_jacobian!(J, N::FEMNonlinear, u, t) + u isa AbstractVector{Float64} || + throw(ArgumentError("the nonlinear operator's Jacobian evaluates Float64 states; got $(eltype(u))")) + elimination = N.elimination + return with_operator(N) do op + if elimination === nothing + JN = jacobian!(op.J, op, u, N.p, t) + check_pattern(J, JN, "Nop") + rows, vals, out = rowvals(JN), nonzeros(JN), nonzeros(J) + for k in eachindex(rows) + N.prescribed[rows[k]] || (out[k] += vals[k]) + end + else + e, nzmap = elimination + vals, out = nonzeros(jacobian!(op.J, op, full_state(e, u), N.p, t)), nonzeros(J) + for k in eachindex(nzmap) + out[k] += vals[nzmap[k]] + end + end + J + end +end + +# `fem_nonlinear(op, rows, t, x)` is rows `rows` of `N(x, t)`, with `x` the whole state built from the +# field arrays by `fem_cat`. A registered function gets a method for every symbolic/numeric combination +# of its arguments, so it takes the state as one array rather than one argument per field (which made +# about 150·5ⁿ⁻¹ methods for n fields); `fem_cat` keeps the fields whole arrays instead of the scalars +# that `vcat` of symbolic arrays gives. +fem_cat(a::AbstractVector, b::AbstractVector) = vcat(a, b) +@register_array_symbolic fem_cat(a::AbstractVector, b::AbstractVector) begin + size = (length(a) + length(b),) + eltype = promote_type(eltype(a), eltype(b)) + ndims = 1 +end -Assembled operators of the semi-discrete system `M du + K u = F(p, t)`, with Dirichlet +fem_nonlinear(op::FEMNonlinear, rows::UnitRange{Int}, t, x::AbstractVector) = + nonlinear_residual!(zeros(promote_type(Float64, eltype(x)), length(x)), op, x, t)[rows] +@register_array_symbolic fem_nonlinear(op::FEMNonlinear, rows::UnitRange{Int}, t, x::AbstractVector) begin + size = (length(rows),) + eltype = Float64 + ndims = 1 +end + +""" + FEMOperators(M, K, load, fields; prescribed = Int[], dirichlet_values = 0.0, nonlinear = nothing) + +Assembled operators of the semi-discrete system `M du + K u + N(u, t) = F(p, t)`, with Dirichlet conditions applied by algebraic row replacement: for each prescribed dof `d`, row `d` of `M` is zeroed, row `d` of `K` becomes `e_d` and `F[d] = g_d(t)`. `M` and `K` are copied, not mutated, and must share one sparsity pattern (for example from `Ferrite.allocate_matrix(dh, ch)`) @@ -103,6 +233,9 @@ that contains the diagonal entry of every prescribed dof. not see the parameters; parameter-dependent operators are reassembled instead (spec §8.3). - `fields`: `name => range` pairs in state order; the ranges must tile `1:size(M, 1)`. - `dirichlet_values`: a number, a vector over `prescribed`, or `(out, t) -> out`. + - `nonlinear`: `nothing`, or a [`FEMNonlinear`](@ref) whose Jacobian has the sparsity + pattern of `M` and `K`. Its rows at prescribed dofs are dropped, so the Dirichlet rows + stay `u_d = g_d(t)`. The fields `M`, `K`, `load`, `fields`, `prescribed`, `differential_vars` and `jac_prototype` are read by [`numeric_dae_problem`](@ref). `differential_vars` is `false` on prescribed dofs @@ -116,11 +249,12 @@ struct FEMOperators prescribed::Vector{Int} differential_vars::BitVector jac_prototype::SparseMatrixCSC{Float64, Int} + nonlinear::Union{Nothing, FEMNonlinear} end function FEMOperators( M::SparseMatrixCSC, K::SparseMatrixCSC, load, fields; - prescribed = Int[], dirichlet_values = 0.0 + prescribed = Int[], dirichlet_values = 0.0, nonlinear = nothing ) n = size(K, 1) size(M) == size(K) == (n, n) || throw(DimensionMismatch("M and K must be square of the same size; got $(size(M)) and $(size(K))")) @@ -141,13 +275,24 @@ function FEMOperators( iszero(nonzeros(M)[k]) || (differential_vars[i] = true) end F = FEMLoad(load, prescribed, dirichlet_values, n) - return FEMOperators(M, K, F, fields, prescribed, differential_vars, copy(K)) + if nonlinear !== nothing + J = nonlinear.op.J + J.colptr == K.colptr && J.rowval == K.rowval || + throw(ArgumentError("the nonlinear operator's Jacobian must have the sparsity pattern of M and K, e.g. NonlinearOperator(ctx, kernels; ch) with the ConstraintHandler of allocate_matrix(dh, ch)")) + nonlinear = FEMNonlinear(nonlinear.op, nonlinear.p, isprescribed_mask(n, prescribed)) + end + return FEMOperators(M, K, F, fields, prescribed, differential_vars, copy(K), nonlinear) +end + +function isprescribed_mask(n, prescribed) + mask = falses(n) + mask[prescribed] .= true + return mask end # One pass over the stored entries; the Jacobian then needs no row zeroing. function replace_dirichlet_rows!(M, K, prescribed) - isprescribed = falses(size(K, 1)) - isprescribed[prescribed] .= true + isprescribed = isprescribed_mask(size(K, 1), prescribed) rows = rowvals(K) for j in axes(K, 2), k in nzrange(K, j) i = rows[k] @@ -161,6 +306,67 @@ function replace_dirichlet_rows!(M, K, prescribed) return M, K end +# What the post-step needs to rebuild the full dof vector from the free dofs. +struct DirichletElimination + n::Int + free::Vector{Int} + prescribed::Vector{Int} + values::Vector{Float64} +end + +function full_state(e::DirichletElimination, u_free) + u = zeros(eltype(u_free), e.n) + u[e.free] = u_free + u[e.prescribed] = e.values + return u +end + +""" + eliminate_dirichlet(ops::FEMOperators) -> (reduced::FEMOperators, elimination) + +Restrict `ops` to its free dofs `fr` (spec §7.3): `M[fr, fr]`, `K[fr, fr]` and the load +`F[fr] - K[fr, cd] g` for the prescribed dofs `cd`. The Dirichlet data `g` must be constant in +time, so `g' = 0` and the term `M[fr, cd] g'` vanishes; time-dependent data, and operators +with every dof prescribed, throw an `ArgumentError`. +The field ranges of `reduced` count free dofs only, and a field whose dofs are all prescribed +is left out of them; `full_state(elimination, u_free)` rebuilds +the full dof vector with `u[cd] = g`. A nonlinear part `N` is kept: it is evaluated at that +full vector, with its rows `fr` and its Jacobian block `[fr, fr]`. +""" +function eliminate_dirichlet(ops::FEMOperators) + F = ops.load + F.values isa Union{Number, AbstractVector} || + throw(ArgumentError("eliminate_dirichlet needs Dirichlet data that are constant in time")) + n = size(ops.K, 1) + isfree = trues(n) + isfree[ops.prescribed] .= false + free = findall(isfree) + isempty(free) && throw( + ArgumentError("dirichlet = :eliminate leaves no unknowns because every dof is prescribed; use the default dirichlet = :algebraic") + ) + g = dirichlet_values!(zeros(length(ops.prescribed)), F, 0.0) + Kg = ops.K[free, ops.prescribed] * g + load = F.load isa AbstractVector ? F.load[free] - Kg : + (out, t) -> (out .= view(F.load(zeros(n), t), free) .- Kg; out) + stop = 0 + fields = Pair{Symbol, UnitRange{Int}}[] + for (name, r) in ops.fields + nfree = count(view(isfree, r)) + # A field with every dof prescribed has no unknowns; MTK rejects an empty array unknown. + nfree == 0 || push!(fields, name => (stop + 1):(stop + nfree)) + stop += nfree + end + reduced = FEMOperators(ops.M[free, free], ops.K[free, free], load, fields) + elimination = DirichletElimination(n, free, ops.prescribed, g) + N = ops.nonlinear + N === nothing && return reduced, elimination + # The positions of the stored entries of K[free, free], which has the pattern of N's Jacobian block. + positions = SparseMatrixCSC(n, n, ops.K.colptr, ops.K.rowval, collect(eachindex(nonzeros(ops.K)))) + Nfree = FEMNonlinear(N.op, N.p, N.prescribed, Any[], ReentrantLock(), (elimination, nonzeros(positions[free, free]))) + (; M, K, load, fields, prescribed, differential_vars, jac_prototype) = reduced + return FEMOperators(M, K, load, fields, prescribed, differential_vars, jac_prototype, Nfree), elimination +end + """ check_finite_initial_condition(u0, fields; coordinate = nothing) @@ -182,29 +388,36 @@ end fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothing, name = :fem) The completed array-residual `System`: one array unknown per field, the operators as opaque -non-tunable parameters `Mop`, `Kop`, `Fop`, and one block equation per field, -`F_i(p, t) ~ Σ_j M_ij D(u_j) + K_ij u_j`. `unknowns` defaults to `name(iv)[1:n]` per field. +non-tunable parameters `Mop`, `Kop`, `Fop` (and `Nop` for `ops.nonlinear`), and one block +equation per field, `F_i(p, t) ~ Σ_j M_ij D(u_j) + K_ij u_j (+ N_i(u, t))`. `parameters` are `symbol => value` pairs +added as parameters with those values, which the operators were assembled with. `unknowns` defaults to `name(iv)[1:n]` per field. Returns `(sys, unknowns, parameter_map)`. """ -function fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothing, name = :fem) +function fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothing, name = :fem, parameters = ()) D = Differential(iv) us = unknowns === nothing ? [only(@variables $field(iv)[1:length(r)]) for (field, r) in ops.fields] : collect(unknowns) @parameters Mop::FEMOp [tunable = false] Kop::FEMOp [tunable = false] Fop::FEMLoad [tunable = false] ranges = last.(ops.fields) - eqs = [ - fem_load(Fop, ri, iv) ~ sum( - fem_apply(Mop, ri, rj, D(uj)) + fem_apply(Kop, ri, rj, uj) - for (rj, uj) in zip(ranges, us) - ) - for ri in ranges - ] + linear(ri) = sum(fem_apply(Mop, ri, rj, D(uj)) + fem_apply(Kop, ri, rj, uj) for (rj, uj) in zip(ranges, us)) + ps = Any[Mop, Kop, Fop] + append!(ps, first.(parameters)) + if ops.nonlinear === nothing + eqs = [fem_load(Fop, ri, iv) ~ linear(ri) for ri in ranges] + else + @parameters Nop::FEMNonlinear [tunable = false] + push!(ps, Nop) + state = foldl(fem_cat, us) + eqs = [fem_load(Fop, ri, iv) ~ linear(ri) + fem_nonlinear(Nop, ri, iv, state) for ri in ranges] + end md = metadata === nothing ? [] : [ProblemTypeCtx => metadata] - sys = complete(System(eqs, iv, us, [Mop, Kop, Fop]; name, metadata = md)) + sys = complete(System(eqs, iv, us, ps; name, metadata = md)) for (u, r) in zip(us, ranges) variable_index(sys, u) == r || error("System reordered the unknowns: $u is at $(variable_index(sys, u)), expected $r") end pmap = Dict{Any, Any}(Mop => FEMOp(ops.M), Kop => FEMOp(ops.K), Fop => ops.load) + ops.nonlinear === nothing || (pmap[last(ps)] = ops.nonlinear) + foreach(((q, v),) -> pmap[q] = v, parameters) return sys, us, pmap end @@ -212,7 +425,7 @@ end consistent_du0(ops::FEMOperators, u0, t0) `du0` with `du_d = g'(t0)` on prescribed dofs, zero on the other algebraic rows, and -`M_ff du_f = (F(t0) - K u0 - M_fd g'(t0))_f` on the differential rows. Throws an +`M_ff du_f = (F(t0) - K u0 - N(u0, t0) - M_fd g'(t0))_f` on the differential rows. Throws an `ArgumentError` when a non-prescribed algebraic variable has a nonzero column in `M`: its `du` is then not zero, cannot be found without index reduction, and must be passed as `du0`. The zero on a non-prescribed algebraic row is by contract: the residual does not define the derivative of an @@ -230,6 +443,7 @@ function consistent_du0(ops::FEMOperators, u0, t0) du0[ops.prescribed] = dirichlet_rates(ops.load, t0) any(dd) || return du0 rhs = load!(zeros(length(u0)), ops.load, t0) - ops.K * u0 - ops.M * du0 + ops.nonlinear === nothing || (rhs .-= nonlinear_residual!(zeros(length(u0)), ops.nonlinear, u0, t0)) du0[dd] = ops.M[dd, dd] \ rhs[dd] return du0 end @@ -240,6 +454,26 @@ function check_pattern(J, A, name) return nothing end +# The operators hold the parameter values they were assembled with; a `remake` with other values would +# otherwise be solved silently with the old ones. +function assembled_parameter_check(sys, parameters) + isempty(parameters) && return Returns(nothing) + syms = [q for (q, _) in parameters] + assembled = [v for (_, v) in parameters] + get = getp(sys, syms) + return function (p) + current = get(p) + for (q, a, c) in zip(syms, assembled, current) + isequal(a, c) || throw( + ArgumentError( + "parameter $q was $a when the operators were assembled but is $c in this problem; operators are not reassembled for new parameter values, so build a new problem with discretize(pdesys, disc)" + ) + ) + end + return nothing + end +end + default_initializealg() = BrownFullBasicInit(nlsolve = NewtonRaphson(autodiff = AutoForwardDiff())) """ @@ -248,11 +482,13 @@ default_initializealg() = BrownFullBasicInit(nlsolve = NewtonRaphson(autodiff = initializealg = BrownFullBasicInit(nlsolve = NewtonRaphson(autodiff = AutoForwardDiff())), coordinate = nothing, name = :fem, kwargs...) -Build the `DAEProblem` for `M du + K u - F(p, t) = 0` with a numeric residual, an analytic -sparse Jacobian `K + γ M` and the completed `System` of [`fem_system`](@ref) attached for +Build the `DAEProblem` for `M du + K u + N(u, t) - F(p, t) = 0` with a numeric residual, an +analytic sparse Jacobian `K + γ M + ∂N/∂u` and the completed `System` of [`fem_system`](@ref) attached for symbolic indexing. No initialization problem is built and nothing calls `mtkcompile`. -`metadata` becomes the problem's `problem_type`; a `SciMLBase.AbstractDiscretizationMetadata` +`parameters` (`symbol => value` pairs) become parameters of the `System` at the values the +operators were assembled with; the residual and Jacobian throw an `ArgumentError` naming the +parameter if a `remake` has changed one. `metadata` becomes the problem's `problem_type`; a `SciMLBase.AbstractDiscretizationMetadata` first gets the `System` through `PDEBase.add_metadata!`. `du0` defaults to the consistent one of [`consistent_du0`](@ref). `coordinate(dof)` is used in the error for a non-finite `u0`. Remaining keywords are passed to `DAEProblem`. @@ -260,26 +496,36 @@ Remaining keywords are passed to `DAEProblem`. function numeric_dae_problem( ops::FEMOperators, u0, tspan, metadata = nothing; iv = ModelingToolkit.t_nounits, unknowns = nothing, du0 = nothing, - initializealg = default_initializealg(), coordinate = nothing, name = :fem, kwargs... + initializealg = default_initializealg(), coordinate = nothing, name = :fem, parameters = (), kwargs... ) length(u0) == size(ops.K, 1) || throw(DimensionMismatch("u0 has length $(length(u0)), the operators have $(size(ops.K, 1)) rows")) check_finite_initial_condition(u0, ops.fields; coordinate) - sys, _, pmap = fem_system(ops, iv; unknowns, metadata, name) + sys, _, pmap = fem_system(ops, iv; unknowns, metadata, name, parameters) p = MTKParameters(sys, pmap) + check_assembled = assembled_parameter_check(sys, parameters) getM, getK, getF = getp(sys, sys.Mop), getp(sys, sys.Kop), getp(sys, sys.Fop) + getN = ops.nonlinear === nothing ? Returns(nothing) : getp(sys, sys.Nop) function residual!(res, du, u, p, t) + check_assembled(p) + ops.nonlinear === nothing || check_state(u) load!(res, getF(p), t) res .= .-res mul!(res, getM(p).A, du, true, true) mul!(res, getK(p).A, u, true, true) + N = getN(p) + N === nothing || add_nonlinear!(res, N, u, t) return nothing end - # The Dirichlet rows of K + γM are already e_d, so the stored values are copied as they are. + # The Dirichlet rows of K + γM are already e_d and N's Jacobian skips them, so the + # stored values are added as they are. function jac!(J, du, u, p, γ, t) + check_assembled(p) Kp, Mp = getK(p).A, getM(p).A check_pattern(J, Kp, "Kop") check_pattern(J, Mp, "Mop") nonzeros(J) .= nonzeros(Kp) .+ γ .* nonzeros(Mp) + N = getN(p) + N === nothing || add_nonlinear_jacobian!(J, N, u, t) return nothing end u0 = collect(u0) diff --git a/src/operators.jl b/src/operators.jl index 3e534581..f1f5dddc 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -60,6 +60,19 @@ end (op::NonlinearOperator)(r, u, p, t) = residual!(r, op, u, p, t) +# `reinit!` mutates CellValues and FacetValues, so each load evaluation gets its own copies and +# concurrent solves of one problem's remakes share no mutable state. +function _fresh_values(ctx::AssemblyContext{NF, DH, CV, FV}) where {NF, DH, CV, FV} + return AssemblyContext{NF, DH, CV, FV}( + ctx.dh, ctx.fields, map(copy, ctx.cellvalues), map(copy, ctx.facetvalues), ctx.facetsets, ctx.facetcells + ) +end + +# A copy of `op` that shares no mutable state with it: new buffers, Jacobian and values objects. +function independent_copy(op::NonlinearOperator) + return NonlinearOperator(_fresh_values(op.ctx), op.volume, op.groups, zero(op.r), copy(op.J), zero(op.Je), zero(op.re), zero(op.u_elem)) +end + const LINEAR_TARGET = (mass = :M, bilinear = :K, source = :F) """ diff --git a/src/solution.jl b/src/solution.jl index f77261a0..2873c704 100644 --- a/src/solution.jl +++ b/src/solution.jl @@ -3,7 +3,8 @@ One dependent variable of a FEM discretization: the `PDESystem` dependent variable `dv` (for example `u(t, x, y)`), the name of its field in the `DofHandler`, the array unknown -of the discretized system (for example `u(t)[1:n]`) and the field's interpolation. +of the discretized system (for example `u(t)[1:n]`, or `nothing` for a field that +`dirichlet = :eliminate` prescribes entirely) and the field's interpolation. """ struct FieldInfo dv::Any @@ -13,7 +14,7 @@ struct FieldInfo end """ - FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[]) + FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[], elimination = nothing) Discretization metadata passed as the `problem_type` of the `DAEProblem` (or, for a steady problem with `time === nothing`, the `NonlinearProblem`), so that `solve` returns a @@ -27,6 +28,8 @@ called in the variables of the `PDESystem`. - `fields`: one [`FieldInfo`](@ref) per dependent variable. - `pieces`: maps each boundary piece to the name of its Ferrite facet set. - `pdesys`: the `PDESystem` that was discretized. + - `elimination`: `nothing`, or for `dirichlet = :eliminate` the data that rebuild the full + dof vector from the solver's free dofs, so every accessor returns full fields. """ struct FEMMetadata{hasTime, DH, PDE, Sp} <: SciMLBase.AbstractDiscretizationMetadata{hasTime} space::Sp @@ -37,13 +40,14 @@ struct FEMMetadata{hasTime, DH, PDE, Sp} <: SciMLBase.AbstractDiscretizationMeta pdesys::PDE metadata::Ref{Any} u0::Vector + elimination::Union{Nothing, DirichletElimination} end -function FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[]) +function FEMMetadata(space, time, x̄, fields, pieces, pdesys; u0 = Float64[], elimination = nothing) hasTime = time === nothing ? Val(false) : Val(true) return FEMMetadata{hasTime, typeof(space.dh), typeof(pdesys), typeof(space)}( space, time, collect(Any, x̄), collect(FieldInfo, fields), - Dict{Any, String}(pieces), pdesys, Ref{Any}(nothing), u0 + Dict{Any, String}(pieces), pdesys, Ref{Any}(nothing), u0, elimination ) end @@ -104,6 +108,8 @@ function _locate(grid, pts) end _dh(md::FEMMetadata) = md.space.dh +# The full dof vector of a solver state. +_full(md::FEMMetadata, U) = md.elimination === nothing ? U : full_state(md.elimination, U) _grid(md::FEMMetadata) = _dh(md).grid # Ferrite's FE values default to linear geometry, which breaks on quadratic cells. _geometry(md::FEMMetadata) = Ferrite.geometric_interpolation(Ferrite.getcelltype(_grid(md))) @@ -118,6 +124,11 @@ end _field_cells(dh, name) = sort!([c for sdh in dh.subdofhandlers if name in sdh.field_names for c in sdh.cellset]) _vertex_coordinates(md, d) = [Ferrite.get_node_coordinate(n)[d] for n in Ferrite.getnodes(_grid(md))] +# The time axis of a field's arrays and call arguments goes first or last as in its declared +# arguments, `u(t, x, y)` or `u(x, y, t)`, as in MethodOfLines (MOL timedep.jl:74-86). +_time_last(md::FEMMetadata, f::FieldInfo) = + md.time !== nothing && isequal(last(SymbolicUtils.arguments(Symbolics.unwrap(f.dv))), Symbolics.unwrap(md.time)) + function _wrap_parts(sol, md::FEMMetadata, states) nt = length(states) T = eltype(first(states)) @@ -125,9 +136,9 @@ function _wrap_parts(sol, md::FEMMetadata, states) for f in md.fields out = Matrix{T}(undef, nt, Ferrite.getnnodes(_grid(md))) for (k, U) in enumerate(states) - out[k, :] .= Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name) + out[k, :] .= Ferrite.evaluate_at_grid_nodes(_dh(md), _full(md, U), f.name) end - umap[Num(f.dv)] = out + umap[Num(f.dv)] = _time_last(md, f) ? permutedims(out) : out end xs = ntuple(d -> _vertex_coordinates(md, d), length(md.x̄)) dvs = [Num(f.dv) for f in md.fields] @@ -173,12 +184,13 @@ function Base.lastindex(::FEMSolution, ::Integer) throw(ArgumentError("`end` cannot be resolved in `sol[dv, inds...]`; index the field instead: `sol[dv][end, :]`.")) end -_states(A::FEMTimeSolution) = A.original_sol.u -_states(A::FEMSteadySolution) = [A.original_sol.u] -_stack(::FEMTimeSolution, rows) = permutedims(reduce(hcat, rows)) -_stack(::FEMSteadySolution, rows) = only(rows) -_columns(values::AbstractMatrix, idxs) = values[:, idxs] -_columns(values::AbstractVector, idxs) = values[idxs] +_states(A::FEMTimeSolution) = [_full(A.disc_data, U) for U in A.original_sol.u] +_states(A::FEMSteadySolution) = [_full(A.disc_data, A.original_sol.u)] +# `rows` holds one row per saved time. +_stack(A::FEMTimeSolution, f, rows) = _time_last(A.disc_data, f) ? reduce(hcat, rows) : permutedims(reduce(hcat, rows)) +_stack(::FEMSteadySolution, f, rows) = only(rows) +_columns(A, f, values::AbstractMatrix, idxs) = _time_last(A.disc_data, f) ? values[idxs, :] : values[:, idxs] +_columns(A, f, values::AbstractVector, idxs) = values[idxs] function _fieldinfo(md, s) SymbolicUtils.iscall(s) || return nothing @@ -193,6 +205,33 @@ function _piece_arg(s) return i === nothing ? nothing : args[i] end +# `_fieldinfo` matches the function name only; these check the arguments. A trace keeps the +# dependent variable's other arguments in place and replaces its coordinates by one piece, +# `u(t, Γ)` or `u(Γ, t)`. +_is_canonical(f::FieldInfo, s) = isequal(s, Symbolics.unwrap(f.dv)) +function _is_trace(md, f::FieldInfo, s) + spatial(a) = any(x -> isequal(a, Symbolics.unwrap(x)), md.x̄) + dvargs = SymbolicUtils.arguments(Symbolics.unwrap(f.dv)) + i = findfirst(spatial, dvargs) + i === nothing && return false + expected = Any[dvargs[1:(i - 1)]..., :piece, filter(!spatial, dvargs[i:end])...] + args = map(SymbolicUtils.unwrap_const, SymbolicUtils.arguments(s)) + length(args) == length(expected) || return false + return all(((a, e),) -> e === :piece ? a isa DomainSets.Domain : isequal(a, e), zip(args, expected)) +end + +_fixed_args_message(ex, f::FieldInfo) = "$ex fixes arguments of $(f.dv); write the dependent variable as $(f.dv)" + +# A dependent variable, or the field differentiated in `s`, at fixed arguments such as +# `u(t, 0, y)` is rejected rather than evaluated as the whole field. +function _reject_fixed(md, s) + SymbolicUtils.iscall(s) && SymbolicUtils.operation(s) isa Symbolics.Differential && + (s = Symbolics.unwrap(only(SymbolicUtils.arguments(s)))) + f = _fieldinfo(md, s) + (f === nothing || _piece_arg(s) !== nothing || _is_canonical(f, s)) && return nothing + throw(ArgumentError(_fixed_args_message(s, f))) +end + function _facetset(md, Γ) haskey(md.pieces, Γ) || throw(ArgumentError("$Γ is not a boundary piece of this mesh; the pieces are $(collect(keys(md.pieces)))")) @@ -206,8 +245,8 @@ _sorted_facets(md, Γ) = sort!(collect(_facetset(md, Γ)); by = fi -> (fi[1], fi piece_nodes(sol, Γ) Sorted vertex ids of the boundary piece `Γ`. They are the columns of `sol[u(t, Γ)]` and -`sol(t, Γ; dv)`, and they index `sol[x]`, so `sol[x][piece_nodes(sol, Γ)]` are the -coordinates of the trace values. +`sol(t, Γ; dv)` (the rows of `sol[u(Γ, t)]` for a time-last `u(x, y, t)`), and they index +`sol[x]`, so `sol[x][piece_nodes(sol, Γ)]` are the coordinates of the trace values. """ piece_nodes(A::FEMSolution, Γ) = piece_nodes(A.disc_data, Γ) function piece_nodes(md::FEMMetadata, Γ) @@ -222,10 +261,91 @@ function piece_nodes(md::FEMMetadata, Γ) return sort!(unique!(ids)) end +# A field as its `Symbol`/`String` name or as the dependent variable (`u`, `u(..)` or `u(t, x, y)`). +function _field_name(md::FEMMetadata, field) + name = field isa Union{Symbol, AbstractString} ? Symbol(field) : begin + s = Symbolics.unwrap(field) + nameof(SymbolicUtils.iscall(s) ? SymbolicUtils.operation(s) : s) + end + any(f -> f.name === name, md.fields) || + throw(ArgumentError("$field is not a field of this discretization; the fields are $(map(f -> f.name, md.fields))")) + return name +end + +# A boundary piece of the discretization, or a facet set named by `String` or `Symbol`. +function _facetset_name(md::FEMMetadata, Γ) + Γ isa Union{Symbol, AbstractString} || (_facetset(md, Γ); return md.pieces[Γ]) + name = String(Γ) + haskey(_grid(md).facetsets, name) || + throw(ArgumentError("$(repr(name)) is not a facet set of the mesh; they are $(sort!(collect(keys(_grid(md).facetsets))))")) + return name +end + +""" + facet_dofs(md::FEMMetadata, Γ, field) -> Vector{Int} + +Sorted global dof indices of `field` on the boundary piece `Γ` (a piece of the discretization, or a +facet-set name as `String` or `Symbol`): every dof whose basis function is nonzero on a facet of +`Γ`, so for order 2 the mid-edge dofs as well as the vertices. `field` is the field name or its +dependent variable. These are the rows a boundary term on `Γ` enters, and the trace of the field +on `Γ` is determined by the values there. A field that lives in no cell next to `Γ` (a field on a +region) has no dofs there, and the result is empty. +""" +function facet_dofs(md::FEMMetadata, Γ, field) + dh = _dh(md) + name = _field_name(md, field) + facets = Ferrite.getfacetset(_grid(md), _facetset_name(md, Γ)) + # Ferrite throws when no facet of the set lies in a cell that holds the field. + any(fi -> _cell_range(dh, fi[1], name) !== nothing, facets) || return Int[] + ch = Ferrite.ConstraintHandler(dh) + Ferrite.add!(ch, Ferrite.Dirichlet(name, facets, Returns(0.0))) + Ferrite.close!(ch) + return sort!(copy(ch.prescribed_dofs)) +end + +""" + dof_coordinates(md::FEMMetadata) -> Matrix{Float64} + +`dim × ndofs` matrix whose column `d` is the coordinate of global dof `d` (Lagrange dofs are nodal, +so the field's value at that point is the dof value). Dofs of a field restricted to a region have +coordinates only where the field lives; this covers every dof of every field. +""" +function dof_coordinates(md::FEMMetadata) + dh = _dh(md) + dim = length(Ferrite.get_node_coordinate(first(Ferrite.getnodes(_grid(md))))) + X = zeros(dim, Ferrite.ndofs(dh)) + for name in map(f -> f.name, md.fields), d in 1:dim + a = fill(NaN, Ferrite.ndofs(dh)) + Ferrite.apply_analytical!(a, dh, name, x -> x[d]) + r = field_range(md.space, name) + X[d, r] .= view(a, r) + end + return X +end + +""" + cell_dofs(md::FEMMetadata, field) -> Matrix{Int} + +`nbasis × ncells` matrix of the global dofs of `field` in each cell, in the local order of the +field's interpolation (vertices first, as Ferrite numbers them). A discretization with regions +throws, since its fields do not live on every cell. +""" +function cell_dofs(md::FEMMetadata, field) + name = _field_name(md, field) + dh = _dh(md) + (length(dh.subdofhandlers) == 1 && length(only(dh.subdofhandlers).cellset) == Ferrite.getncells(_grid(md))) || + throw(ArgumentError("cell_dofs needs a discretization without regions; this one has regions covering $(length(dh.subdofhandlers)) subdomains, not the whole mesh")) + r = Ferrite.dof_range(dh, name) + return stack(c -> Ferrite.celldofs(dh, c)[r], 1:Ferrite.getncells(_grid(md))) +end + function _facet_normal_flux(md, f::FieldInfo, Γ, U) dh = _dh(md) grid = _grid(md) - fv = Ferrite.FacetValues(Ferrite.FacetQuadratureRule{Ferrite.getrefshape(f.ip)}(2), f.ip, _geometry(md)) + geometry = _geometry(md) + # The order grows with both interpolations: on a curved facet the integrand is rational in the facet coordinate. + order = 2 * (_order(f.ip) + _order(geometry)) + fv = Ferrite.FacetValues(Ferrite.FacetQuadratureRule{Ferrite.getrefshape(f.ip)}(order), f.ip, geometry) return map(_sorted_facets(md, Γ)) do fi r = _cell_range(dh, fi[1], f.name) r === nothing && return convert(eltype(U), NaN) @@ -246,14 +366,17 @@ end normal_flux(sol, dv, Γ) Facet-mean outward normal derivative `∇u·n` of the field `dv` on every facet of the boundary -piece `Γ`, `nt × nfacets` (a vector for a steady solution). Facets are ordered by +piece `Γ`, `nt × nfacets` (`nfacets × nt` for a time-last `u(x, y, t)`, a vector for a steady +solution). Facets are ordered by `(cell, local facet)`. This is a post-processed flux, not the imposed boundary datum. """ function normal_flux(A::FEMSolution, dv, Γ) md = A.disc_data - f = _fieldinfo(md, Symbolics.unwrap(dv)) - f === nothing && throw(ArgumentError("$dv is not a dependent variable of this solution; they are $(A.dvs)")) - return _stack(A, [_facet_normal_flux(md, f, Γ, U) for U in _states(A)]) + s = Symbolics.unwrap(dv) + _reject_fixed(md, s) + f = _fieldinfo(md, s) + (f === nothing || !_is_canonical(f, s)) && throw(ArgumentError("$dv is not a dependent variable of this solution; they are $(A.dvs)")) + return _stack(A, f, [_facet_normal_flux(md, f, Γ, U) for U in _states(A)]) end # L2 projection of the cellwise gradient onto the field's own space, assembled and factorised once @@ -296,7 +419,7 @@ function _gradkey(md, s) D.order == 1 || return nothing inner = only(SymbolicUtils.arguments(s)) f = _fieldinfo(md, inner) - (f === nothing || _piece_arg(inner) !== nothing) && return nothing + (f === nothing || !_is_canonical(f, inner)) && return nothing d = findfirst(x -> isequal(Symbolics.unwrap(x), Symbolics.unwrap(D.x)), md.x̄) return d === nothing ? nothing : (f, d) end @@ -319,23 +442,39 @@ function Base.getindex(A::FEMSolution, sym::Num) i = findfirst(iv -> isequal(Symbolics.unwrap(iv), s), A.ivs) i === nothing || return A.ivdomain[i] haskey(A.u, sym) && return A.u[sym] + _reject_fixed(md, s) g = _gradkey(md, s) if g !== nothing projector = _gradient_projector(md, g[1]) - return _stack(A, [_nodal_gradient(md, g..., U, projector) for U in _states(A)]) + return _stack(A, g[1], [_nodal_gradient(md, g..., U, projector) for U in _states(A)]) end if SymbolicUtils.iscall(s) && _is_normal_derivative(SymbolicUtils.operation(s)) trace = Symbolics.unwrap(only(SymbolicUtils.arguments(s))) f = _fieldinfo(md, trace) Γ = _piece_arg(trace) - (f === nothing || !isequal(Γ, SymbolicUtils.operation(s).piece)) && _key_error(A, sym) + (f === nothing || !_is_trace(md, f, trace) || !isequal(Γ, SymbolicUtils.operation(s).piece)) && _key_error(A, sym) return normal_flux(A, f.dv, Γ) end f = _fieldinfo(md, s) - f === nothing && _key_error(A, sym) + if f === nothing + _is_expression(s) || _key_error(A, sym) + compiled = _compile_observed(A, sym) + fn, terms, kinds = compiled + timed = A isa FEMTimeSolution + # Evaluated time-first (`nt × nvertices`), then turned as the expression's fields declare. + function value(term, kind) + kind === :time && return A.t + v = A[Num(term)] + kind === :coord && return timed ? permutedims(v) : v + return timed && _time_last(md, _leaf_field(md, term)) ? permutedims(v) : v + end + nv = Ferrite.getnnodes(_grid(md)) + out = _broadcast_observed(fn, timed ? (length(A.t), nv) : (nv,), map(value, terms, kinds)) + return _observed_time_last(A, sym, compiled) ? permutedims(out) : out + end + _is_trace(md, f, s) || throw(ArgumentError(_fixed_args_message(s, f))) Γ = _piece_arg(s) - Γ === nothing && _key_error(A, sym) - return _columns(A.u[Num(f.dv)], piece_nodes(md, Γ)) + return _columns(A, f, A.u[Num(f.dv)], piece_nodes(md, Γ)) end Base.getindex(A::FEMSolution, sym::Num, args...) = A[sym][args...] @@ -343,7 +482,7 @@ Base.getindex(A::FEMSolution, sym::Num, args...) = A[sym][args...] function _dofs_at(A::FEMTimeSolution, t::Real) lo, hi = minmax(A.t[1], A.t[end]) lo <= t <= hi || throw(DomainError(t, "outside the saved time span $(A.t[1]) .. $(A.t[end])")) - return A.original_sol(t) + return _full(A.disc_data, A.original_sol(t)) end _axis(a) = a isa AbstractVector ? collect(a) : [a] @@ -362,30 +501,21 @@ function _point_gradient(ph, md, f, d, U) return out end -# `states` holds one dof vector per requested time; `tshape` is `(nt,)` or `()`. -function _evaluate(A::FEMSolution, states, tshape, xs, dv, outside) - md = A.disc_data - dv === nothing && return map(d -> _evaluate(A, states, tshape, xs, d, outside), A.dvs) - s = Symbolics.unwrap(dv) - g = _gradkey(md, s) - f = g === nothing ? _fieldinfo(md, s) : g[1] - f === nothing && throw(ArgumentError("dv = $dv is not a dependent variable or a first spatial derivative of one; the dependent variables are $(A.dvs)")) - if length(xs) == 1 && only(xs) isa DomainSets.Domain - g === nothing || throw(ArgumentError("dv = $dv: traces of derivatives are not supported; use normal_flux(sol, dv, Γ)")) - nodes = piece_nodes(md, only(xs)) - rows = [Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name)[nodes] for U in states] - return isempty(tshape) ? only(rows) : permutedims(reduce(hcat, rows)) - end +# Scattered points `pts` and the shape their values take: vector arguments give a tensor product +# and scalar arguments drop their axis. +function _points(md, xs) if length(xs) == 1 && only(xs) isa AbstractVector{<:Ferrite.Vec} pts = collect(only(xs)) - pshape = (length(pts),) - else - length(xs) == length(md.x̄) || - throw(ArgumentError("expected $(length(md.x̄)) spatial arguments $(md.x̄), got $(length(xs))")) - axes_ = map(_axis, xs) - pts = vec([Ferrite.Vec{length(xs)}(Float64.(Tuple(c))) for c in Iterators.product(axes_...)]) - pshape = Tuple(length(a) for (a, x) in zip(axes_, xs) if x isa AbstractVector) + return pts, (length(pts),) end + length(xs) == length(md.x̄) || + throw(ArgumentError("expected $(length(md.x̄)) spatial arguments $(md.x̄), got $(length(xs))")) + axes_ = map(_axis, xs) + pts = vec([Ferrite.Vec{length(xs)}(Float64.(Tuple(c))) for c in Iterators.product(axes_...)]) + return pts, Tuple(length(a) for (a, x) in zip(axes_, xs) if x isa AbstractVector) +end + +function _located(A::FEMSolution, pts, outside) ph = _handler(A.interp, pts) if outside === :error i = findfirst(isnothing, ph.cells) @@ -393,26 +523,196 @@ function _evaluate(A::FEMSolution, states, tshape, xs, dv, outside) elseif outside !== :nan throw(ArgumentError("outside must be :nan or :error, got $(repr(outside))")) end + return ph +end + +_trace_call(md, f::FieldInfo) = md.time === nothing ? "sol(Γ; dv = $(f.dv))" : + _time_last(md, f) ? "sol(Γ, t; dv = $(f.dv))" : "sol(t, Γ; dv = $(f.dv))" + +# The field `f` a `dv` names and, for a first derivative, `g = (f, d)`; `(nothing, nothing)` for an +# observed expression. +function _dvfield(A::FEMSolution, dv) + md = A.disc_data + s = Symbolics.unwrap(dv) + _reject_fixed(md, s) + g = _gradkey(md, s) + f = g === nothing ? _fieldinfo(md, s) : g[1] + if f === nothing + _is_expression(s) && return nothing, nothing + throw(ArgumentError("dv = $dv is not a dependent variable or a first spatial derivative of one; the dependent variables are $(A.dvs)")) + end + g === nothing && !_is_canonical(f, s) && + throw(ArgumentError("dv = $dv is a trace; evaluate a trace as $(_trace_call(md, f))")) + return f, g +end + +# `states` holds one dof vector per requested time; `tshape` is `(nt,)` or `()`. The time axis of +# the result goes where field `f` declares its time argument. +function _evaluate(A::FEMSolution, states, tshape, xs, f, g, outside) + md = A.disc_data + if length(xs) == 1 && only(xs) isa DomainSets.Domain + g === nothing || throw(ArgumentError("traces of derivatives of $(f.dv) are not supported; use normal_flux(sol, dv, Γ)")) + nodes = piece_nodes(md, only(xs)) + rows = [Ferrite.evaluate_at_grid_nodes(_dh(md), U, f.name)[nodes] for U in states] + return isempty(tshape) ? only(rows) : _stack(A, f, rows) + end + pts, pshape = _points(md, xs) + ph = _located(A, pts, outside) out = Matrix{eltype(first(states))}(undef, length(states), length(pts)) for (k, U) in enumerate(states) out[k, :] .= g === nothing ? Ferrite.evaluate_at_points(ph, _dh(md), U, f.name) : _point_gradient(ph, md, f, g[2], U) end - shp = (tshape..., pshape...) - return isempty(shp) ? out[1] : reshape(out, shp) + return _shaped(out, tshape, pshape, _time_last(md, f)) +end + +# `out` is `nt × npoints`; the time axis goes last for a time-last result. +function _shaped(out, tshape, pshape, time_last) + isempty((tshape..., pshape...)) && return out[1] + !isempty(tshape) && time_last && return reshape(permutedims(out), (pshape..., tshape...)) + return reshape(out, (tshape..., pshape...)) end const _CallArg = Union{Number, AbstractArray, DomainSets.Domain} # Documented in docs/src/solution.md: a docstring on a call of SciMLBase's type has no # binding of this package for Documenter to check against. -function (A::FEMTimeSolution)(t::Union{Real, AbstractVector{<:Real}}, xs::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) - states = [_dofs_at(A, tk) for tk in _axis(t)] - return _evaluate(A, states, t isa AbstractVector ? (length(t),) : (), xs, dv, outside) +function (A::FEMTimeSolution)(args::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) + md = A.disc_data + if dv === nothing + allequal(_time_last(md, f) for f in md.fields) || throw( + ArgumentError("the dependent variables $(A.dvs) put time in different argument positions; pass dv to choose one") + ) + return map(d -> A(args...; dv = d, outside), A.dvs) + end + f, g = _dvfield(A, dv) + compiled = f === nothing ? _compile_observed(A, dv) : nothing + last_ = f === nothing ? _observed_time_last(A, dv, compiled) : _time_last(md, f) + t = isempty(args) ? nothing : last_ ? last(args) : first(args) + t isa Union{Real, AbstractVector{<:Real}} || throw( + ArgumentError("the $(last_ ? "last" : "first") argument must be a time or a vector of times, as $(f === nothing ? "the dependent variables of $dv declare" : "$(f.dv) declares"); got $(repr(t))") + ) + xs = last_ ? Base.front(args) : Base.tail(args) + ts = _axis(t) + states = [_dofs_at(A, tk) for tk in ts] + tshape = t isa AbstractVector ? (length(t),) : () + f === nothing && return _evaluate_observed(A, ts, states, tshape, xs, compiled, last_, outside) + return _evaluate(A, states, tshape, xs, f, g, outside) end function (A::FEMSteadySolution)(xs::Vararg{_CallArg}; dv = nothing, outside::Symbol = :nan) - return _evaluate(A, _states(A), (), xs, dv, outside) + dv === nothing && return map(d -> A(xs...; dv = d, outside), A.dvs) + f, g = _dvfield(A, dv) + f === nothing && return _evaluate_observed(A, nothing, _states(A), (), xs, _compile_observed(A, dv), false, outside) + return _evaluate(A, _states(A), (), xs, f, g, outside) +end + +# Observed expressions (spec O9). Without `mtkcompile` there are no observed equations, so an +# expression is compiled once with `build_function` into a scalar function of its leaves (the +# fields, their first spatial derivatives, time and the coordinates) and broadcast over the +# leaves' values at every vertex or point; parameters are replaced by their PDESystem values. +_is_expression(s) = SymbolicUtils.iscall(s) && !(SymbolicUtils.operation(s) isa Symbolics.Differential) + +function _observed_error(dv, why) + throw(ArgumentError("cannot evaluate the expression $dv on this solution: $why")) +end + +_check_field_call(dv, ex, f::FieldInfo) = _is_canonical(f, ex) || _observed_error(dv, _fixed_args_message(ex, f)) + +# Adds the leaves of `ex` to `terms` as `term => kind`, with kind `:field`, `:time` or `:coord`, +# and the value of each parameter to `params`. +function _observed_leaves!(terms, params, A, dv, ex) + md = A.disc_data + ex = SymbolicUtils.unwrap_const(Symbolics.unwrap(ex)) + ex isa Number && return nothing + if md.time !== nothing && isequal(ex, Symbolics.unwrap(md.time)) + terms[ex] = :time + elseif any(x -> isequal(ex, Symbolics.unwrap(x)), md.x̄) + terms[ex] = :coord + elseif _gradkey(md, ex) !== nothing + terms[ex] = :field + elseif SymbolicUtils.iscall(ex) && SymbolicUtils.operation(ex) isa Symbolics.Differential + inner = Symbolics.unwrap(only(SymbolicUtils.arguments(ex))) + f = _fieldinfo(md, inner) + f === nothing || _piece_arg(inner) !== nothing || _check_field_call(dv, inner, f) + _observed_error(dv, "$ex is not a first spatial derivative of a dependent variable, the only derivatives an expression accepts") + elseif (f = _fieldinfo(md, ex)) !== nothing + _piece_arg(ex) === nothing || + _observed_error(dv, "it contains the trace $ex; an expression is evaluated at every vertex, so write $(f.dv) instead") + _check_field_call(dv, ex, f) + terms[ex] = :field + elseif SymbolicUtils.issym(ex) || SymbolicUtils.issym(SymbolicUtils.operation(ex)) + # The front end requires a numeric value for every parameter of the PDESystem. + ps = md.pdesys === nothing || md.pdesys.ps isa SciMLBase.NullParameters ? [] : md.pdesys.ps + i = findfirst(p -> p isa Pair && isequal(Symbolics.unwrap(p.first), ex), ps) + i === nothing && _observed_error( + dv, "$ex is not a dependent variable, an independent variable or a parameter; the dependent variables are $(join(A.dvs, ", ")) and the independent variables $(join(A.ivs, ", "))" + ) + params[ex] = ps[i].second + else + foreach(a -> _observed_leaves!(terms, params, A, dv, a), SymbolicUtils.arguments(ex)) + end + return nothing +end + +# `(fn, terms, kinds)`: `fn(values...)` evaluates `dv` given the value of each of `terms`. +function _compile_observed(A::FEMSolution, dv) + terms, params = Dict{Any, Symbol}(), Dict{Any, Any}() + _observed_leaves!(terms, params, A, dv, dv) + leaves = collect(keys(terms)) + # Fixed names give an equal expression the same body, so the compiled function is reused. + vars = [Symbolics.unwrap(Symbolics.variable(:leaf, i)) for i in eachindex(leaves)] + body = substitute(Symbolics.unwrap(dv), merge(Dict{Any, Any}(zip(leaves, vars)), params)) + fn = Symbolics.build_function(body, vars...; expression = Val(false)) + return fn, leaves, [terms[l] for l in leaves] +end + +# One call of `fn` per entry of an array of size `shape`; `values` broadcast against it. +_broadcast_observed(fn, shape, values) = broadcast((_, v...) -> fn(v...), falses(shape), values...) + +_leaf_field(md, term) = (g = _gradkey(md, term); g === nothing ? _fieldinfo(md, term) : g[1]) + +# Whether time goes last in the arrays of an expression: as its dependent variables declare or, +# when it names none, as all those of the system do. +function _observed_time_last(A::FEMSolution, dv, (_, terms, kinds)) + md = A.disc_data + md.time === nothing && return false + fields = [_leaf_field(md, term) for (term, kind) in zip(terms, kinds) if kind === :field] + positions = unique(_time_last(md, f) for f in (isempty(fields) ? md.fields : fields)) + length(positions) == 1 || _observed_error( + dv, "its dependent variables (all those of the system when it names none) put time in different argument positions; evaluate the time-first and the time-last parts separately" + ) + return only(positions) +end + +# Values on the points `xs` at the times `ts` of `states`, through the per-field point evaluation; +# coordinate-only expressions are `NaN` outside the mesh like field values. +function _evaluate_observed(A::FEMSolution, ts, states, tshape, xs, (fn, terms, kinds), time_last, outside) + md = A.disc_data + nt = length(states) + if length(xs) == 1 && only(xs) isa DomainSets.Domain + nodes = piece_nodes(md, only(xs)) + coords = [A[Num(x)][nodes] for x in md.x̄] + pshape, lost = (length(nodes),), falses(length(nodes)) + else + pts, pshape = _points(md, xs) + lost = isnothing.(_located(A, pts, outside).cells) + coords = [getindex.(pts, d) for d in eachindex(md.x̄)] + end + # The expression is evaluated only inside the mesh, where its domain (sqrt, log) may not + # extend, and the output is floating point so that the outside points can hold NaN. + inside = findall(!, lost) + function value(term, kind) + kind === :time && return ts + kind === :coord && return permutedims(coords[findfirst(x -> isequal(term, Symbolics.unwrap(x)), md.x̄)][inside]) + f = _leaf_field(md, term) + v = _evaluate(A, states, (nt,), xs, f, _gradkey(md, term), outside) + return (_time_last(md, f) ? permutedims(reshape(v, :, nt)) : reshape(v, nt, :))[:, inside] + end + vals = _broadcast_observed(fn, (nt, length(inside)), map(value, terms, kinds)) + out = fill(eltype(vals) <: Number ? float(eltype(vals))(NaN) : NaN, nt, length(lost)) + out[:, inside] .= vals + return _shaped(out, tshape, pshape, time_last) end _xml_escape(str) = replace(str, '&' => "&", '<' => "<", '>' => ">", '"' => """, '\'' => "'") @@ -423,7 +723,8 @@ _xml_escape(str) = replace(str, '&' => "&", '<' => "<", '>' => ">", '" Write one `.vtu` file per saved time, `"\$(base)_0001.vtu"` and so on, with every field as point data, plus a ParaView collection `"\$(base).pvd"` that maps them to `sol.t`. Returns the -path of the `.pvd` file. +path of the `.pvd` file. A steady solution is written to the single file `"\$(base).vtu"`, +whose path is returned. """ function write_vtk(A::FEMTimeSolution, base::AbstractString) dh = _dh(A.disc_data) @@ -448,3 +749,11 @@ function write_vtk(A::FEMTimeSolution, base::AbstractString) ) return pvd end + +function write_vtk(A::FEMSteadySolution, base::AbstractString) + dh = _dh(A.disc_data) + Ferrite.VTKGridFile(base, dh) do vtk + Ferrite.write_solution(vtk, dh, only(_states(A))) + end + return base * ".vtu" +end diff --git a/src/weakform.jl b/src/weakform.jl index 7842ee06..a0b9c352 100644 --- a/src/weakform.jl +++ b/src/weakform.jl @@ -83,7 +83,18 @@ struct KernelSpec{F, T, C} end KernelSpec(eq, kind, piece, f, tangent) = KernelSpec(eq, kind, piece, f, tangent, nothing) -addterms(ex) = SU.iscall(ex) && SU.operation(ex) === (+) ? reduce(vcat, addterms.(SU.arguments(ex))) : [ex] +# `expand` leaves a quotient whole, so `(U·V + g·V) / r` (a Robin condition whose data has the +# denominator `r`, as normals on a circle do) is split over its numerator's terms. +function addterms(ex) + SU.iscall(ex) || return [ex] + op = SU.operation(ex) + op === (+) && return reduce(vcat, addterms.(SU.arguments(ex))) + if op === (/) + num, den = SU.arguments(ex) + return [term / den for term in addterms(num)] + end + return [ex] +end function depends(ex, syms) vars = Set(Symbolics.get_variables(ex)) diff --git a/test/DAE/numeric_dae.jl b/test/DAE/numeric_dae.jl index 185f7359..b6acd3d6 100644 --- a/test/DAE/numeric_dae.jl +++ b/test/DAE/numeric_dae.jl @@ -163,6 +163,11 @@ heat_operators(fe; kw...) = FEMOperators(fe.M, fe.K, fe.F, [:u => 1:length(fe.F) Kp = SparseMatrixCSC(2, 2, [1, 3, 5], [1, 2, 1, 2], [0.0, 0.0, 0.0, 1.0]) opsp = FEMOperators(pat, Kp, (out, t) -> (out .= (0.0, t); out), [:u => 1:2]) @test_throws "pass du0 explicitly" numeric_dae_problem(opsp, zeros(2), (0.0, 1.0)) + # The nonlinear part must share the pattern of M and K; checking it needs no working operator. + FN = FiniteElementMethod.FEMNonlinear + @test_throws ArgumentError( + "the nonlinear operator's Jacobian must have the sparsity pattern of M and K, e.g. NonlinearOperator(ctx, kernels; ch) with the ConstraintHandler of allocate_matrix(dh, ch)" + ) FEMOperators(Md, copy(Md), zeros(3), [:u => 1:3]; nonlinear = FN((; J = Kt), Float64[])) probp = numeric_dae_problem(opsp, zeros(2), (0.0, 1.0); du0 = [-1.0, 1.0]) solp = solve(probp, DFBDF(); tol...) @test solp.u[end] ≈ [-1.0, 1.0] atol = 1.0e-8 @@ -230,6 +235,16 @@ heat_operators(fe; kw...) = FEMOperators(fe.M, fe.K, fe.F, [:u => 1:length(fe.F) @test SciMLBase.successful_retcode(sol) @test sol(0.05) ≈ [-0.05, 0.05] atol = 1.0e-12 @test sol.u[end] ≈ [-1.0, 1.0] atol = 1.0e-12 + @test_throws ArgumentError("eliminate_dirichlet needs Dirichlet data that are constant in time") FiniteElementMethod.eliminate_dirichlet(ops2) + # Eliminating every dof of the first field leaves only the second as an unknown. + A4 = spdiagm(-1 => fill(-1.0, 3), 0 => fill(2.0, 4), 1 => fill(-1.0, 3)) + ops4 = FEMOperators(A4, copy(A4), zeros(4), [:u => 1:2, :v => 3:4]; prescribed = [1, 2], dirichlet_values = 1.0) + reduced, elimination = FiniteElementMethod.eliminate_dirichlet(ops4) + @test reduced.fields == [:v => 1:2] + @test reduced.load.load == [1.0, 0.0] + prob4 = numeric_dae_problem(reduced, zeros(2), (0.0, 1.0)) + @test length(prob4.u0) == 2 + @test FiniteElementMethod.full_state(elimination, [3.0, 4.0]) == [1.0, 1.0, 3.0, 4.0] # Constant Dirichlet data gives du_d = 0. @test FiniteElementMethod.dirichlet_rates(ops.load, 0.0) == zeros(length(fe.prescribed)) end diff --git a/test/Frontend/arguments.jl b/test/Frontend/arguments.jl new file mode 100644 index 00000000..fd9c53e9 --- /dev/null +++ b/test/Frontend/arguments.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "arguments.jl")) diff --git a/test/Frontend/curved.jl b/test/Frontend/curved.jl new file mode 100644 index 00000000..92d5f17b --- /dev/null +++ b/test/Frontend/curved.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "curved.jl")) diff --git a/test/Frontend/eliminate.jl b/test/Frontend/eliminate.jl new file mode 100644 index 00000000..0587d82d --- /dev/null +++ b/test/Frontend/eliminate.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "eliminate.jl")) diff --git a/test/Frontend/extension_contract.jl b/test/Frontend/extension_contract.jl new file mode 100644 index 00000000..2ce54d2b --- /dev/null +++ b/test/Frontend/extension_contract.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "extension_contract.jl")) diff --git a/test/Frontend/facet_dofs.jl b/test/Frontend/facet_dofs.jl new file mode 100644 index 00000000..30874809 --- /dev/null +++ b/test/Frontend/facet_dofs.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "facet_dofs.jl")) diff --git a/test/Frontend/messages.jl b/test/Frontend/messages.jl new file mode 100644 index 00000000..e1fb20a6 --- /dev/null +++ b/test/Frontend/messages.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "messages.jl")) diff --git a/test/Frontend/nonlinear.jl b/test/Frontend/nonlinear.jl new file mode 100644 index 00000000..d15dfbed --- /dev/null +++ b/test/Frontend/nonlinear.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "nonlinear.jl")) diff --git a/test/Frontend/observed.jl b/test/Frontend/observed.jl new file mode 100644 index 00000000..ed9ca4be --- /dev/null +++ b/test/Frontend/observed.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "observed.jl")) diff --git a/test/Frontend/operators.jl b/test/Frontend/operators.jl new file mode 100644 index 00000000..cd8b8c86 --- /dev/null +++ b/test/Frontend/operators.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "operators.jl")) diff --git a/test/Frontend/steady.jl b/test/Frontend/steady.jl new file mode 100644 index 00000000..80253e6d --- /dev/null +++ b/test/Frontend/steady.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "steady.jl")) diff --git a/test/Frontend/symbolic.jl b/test/Frontend/symbolic.jl new file mode 100644 index 00000000..8aa3f065 --- /dev/null +++ b/test/Frontend/symbolic.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "symbolic.jl")) diff --git a/test/Frontend/time_last.jl b/test/Frontend/time_last.jl new file mode 100644 index 00000000..5cf4f629 --- /dev/null +++ b/test/Frontend/time_last.jl @@ -0,0 +1,2 @@ +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "shared", "frontend_tests", "time_last.jl")) diff --git a/test/Integration/geometry.jl b/test/Integration/geometry.jl index e9a81c8b..da2e0479 100644 --- a/test/Integration/geometry.jl +++ b/test/Integration/geometry.jl @@ -33,7 +33,7 @@ end BC("inner", U ~ on_arc(1)), BC("outer", U ~ on_arc(2)), BC("left", U ~ ustar), BC("bottom", -Dy(U) ~ -expand_derivatives(Dy(ustar)), [0.0, -1.0]), ] - c = chain([0 ~ Dx(Dx(U)) + Dy(Dy(U)) + f], bcs; depvars = [U], t, sivs = [x, y]) + c = chain([0 ~ Dx(Dx(U)) + Dy(Dy(U)) + f], bcs; depvars = [U], t, sivs = [x, y], domain = [(0.0, 2.0), (0.0, 2.0)]) @test any(term -> term.piece == "bottom", c.wf.facet) exact = numeric(ustar, [x, y]) sizes = (2, 4, 8, 16) diff --git a/test/NavierStokes/dfg_cylinder.jl b/test/NavierStokes/dfg_cylinder.jl new file mode 100644 index 00000000..e97625e5 --- /dev/null +++ b/test/NavierStokes/dfg_cylinder.jl @@ -0,0 +1,45 @@ +# The DFG 2D-1 cylinder example (spec §11.5): the PDESystem path against the benchmark's acceptance intervals +# and against the hand-written Ferrite solver on the same mesh. +using FiniteElementMethod, Test +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "dfg_cylinder.jl")) +include(joinpath(@__DIR__, "..", "..", "examples", "dfg_cylinder", "reference.jl")) + +@testset "DFG 2D-1 flow around a cylinder" begin + h, hc = 0.04, 0.0025 + r = dfg_solve(; h, hc) + @info "DFG 2D-1" r.ndofs r.build_s r.solve_s r.coefficients + @test SciMLBase.successful_retcode(r.sol) + stopped = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, maxiters = 3) + @test_throws "the DFG solve stopped at t = " check_solved(stopped) + # Terminated is a success code, so the final time is checked too. + halt = SciMLBase.DiscreteCallback((u, t, integrator) -> t > 1.0, SciMLBase.terminate!) + terminated = solve(r.prob, DFG_ALG; abstol = differential_abstol(r.prob, 1.0e-7), reltol = 1.0e-7, callback = halt) + @test terminated.retcode == SciMLBase.ReturnCode.Terminated + @test_throws "the DFG solve stopped at t = " check_solved(terminated) + c = r.coefficients + # The force functional gets the integrator's final derivative, which vanishes at the steady state and + # satisfies the DAE there, not the slope between the two saved end points (about |u|/t_end). + dv = r.prob.differential_vars + x_end = r.sol.original_sol.u[end] + @test maximum(abs, r.dxdt[dv]) <= 1.0e-6 + residual = zeros(length(x_end)) + r.prob.f(residual, r.dxdt, x_end, r.prob.p, last(r.prob.tspan)) + @test maximum(abs, residual[dv]) <= 1.0e-9 + steady = dfg_coefficients(r.sol.disc_data.space.dh, x_end; ν = 1.0e-3, Umean = 0.2) + for k in (:cD, :cL) + @test c[k] ≈ steady[k] rtol = 1.0e-8 + end + for k in (:cD, :cL, :Δp) + lo, hi = DFG_2D1_BANDS[k] + @test lo <= c[k] <= hi + end + + # The hand-written steady solution on the same mesh: same dof numbering after FieldWise renumbering. + grid = dfg_channel_grid(; h, hc) + @test_throws "Newton's method did not converge in 1 iterations" dfg_reference_steady(grid; maxiter = 1) + dh_ref, x_ref, _ = dfg_reference_steady(grid; pressure = :strong) + ref = dfg_coefficients(dh_ref, x_ref; ν = 1.0e-3, Umean = 0.2) + for k in (:cD, :cL, :Δp) + @test c[k] ≈ ref[k] rtol = 1.0e-7 + end +end diff --git a/test/Solution/solution.jl b/test/Solution/solution.jl index 514bd4c5..a59bee49 100644 --- a/test/Solution/solution.jl +++ b/test/Solution/solution.jl @@ -3,6 +3,7 @@ using OrdinaryDiffEqBDF: DFBDF using FiniteElementMethod: FEMMetadata, piece_nodes, normal_flux, write_vtk include(joinpath(@__DIR__, "..", "shared", "heat.jl")) +include(joinpath(@__DIR__, "..", "shared", "references.jl")) const P1 = Lagrange{RefTriangle, 1}() const P2 = Lagrange{RefTriangle, 2}() @@ -185,6 +186,20 @@ end @test sol[Differential(x)(U)] ≈ -ones(getnnodes(grid)) atol = 1.0e-10 @test sol(0.3, 0.6; dv = Differential(x)(U)) ≈ -1 atol = 1.0e-12 @test isnan(sol(1.5, 0.5; dv = U)) + @test sol[U^2 + x] ≈ sol[U] .^ 2 .+ sol[x] atol = 1.0e-12 + @test sol[2U + Differential(x)(U)] ≈ 1 .- 2 .* sol[x] atol = 1.0e-10 + @test sol(0.3, 0.6; dv = U * y) ≈ 0.7 * 0.6 atol = 1.0e-12 + @test sol(Γ; dv = U + y) ≈ 1 .+ sol[y][piece_nodes(sol, Γ)] atol = 1.0e-12 + fixed = Differential(y)(u(0, y)) + 1 + msg = ArgumentError("cannot evaluate the expression $fixed on this solution: $(u(0, y)) fixes arguments of u(x, y); write the dependent variable as u(x, y)") + @test_throws msg sol[fixed] + @test_throws msg sol(0.3, 0.6; dv = fixed) + bare = ArgumentError("$(u(0, y)) fixes arguments of u(x, y); write the dependent variable as u(x, y)") + for ex in (u(0, y), Differential(y)(u(0, y))) + @test_throws bare sol[ex] + @test_throws bare sol(0.3, 0.6; dv = ex) + end + @test_throws bare normal_flux(sol, u(0, y), Γ) end @testset "Points missed by Ferrite's nearest-node search" begin @@ -353,3 +368,40 @@ end @test normal_flux(sol, u(x, y), Γ) ≈ [-dgx(Vec(0.0, ym)) for ym in (1 / 6, 1 / 2, 5 / 6)] atol = 1.0e-12 end end + +# A fixed low facet quadrature order was exact only for straight facets up to P4. +@testset "Facet-mean flux at high order and on curved facets" begin + # u = x y⁴ is in P5; the inlet normal is -x, so the mean of -∂u/∂x = -y⁴ over [a, b] is -(b⁵ - a⁵) / (5 (b - a)). + grid = with_inlet(square_grid(3)) + dh = DofHandler(grid) + add!(dh, :u, Lagrange{RefTriangle, 5}()) + close!(dh) + U = zeros(ndofs(dh)) + apply_analytical!(U, dh, :u, p -> p[1] * p[2]^4) + sol, syms = steady_from_dofs(dh, (; u = Lagrange{RefTriangle, 5}()), U) + exact = [-((k / 3)^5 - ((k - 1) / 3)^5) / (5 / 3) for k in 1:3] + @test normal_flux(sol, syms.u(syms.x, syms.y), syms.Γ) ≈ exact rtol = 1.0e-12 + + # Quadratic cells with P2 and P4 fields: the facet-mean flux on the outer arc against a high-order reference. + grid = quarter_annulus(3; quadratic = true) + for p in (2, 4) + ip = Lagrange{RefTriangle, p}() + dh = DofHandler(grid) + add!(dh, :u, ip) + close!(dh) + U = zeros(ndofs(dh)) + apply_analytical!(U, dh, :u, X -> X[1]^2 + X[2]^2) + sol, syms = steady_from_dofs(dh, (; u = ip), U) + sol.disc_data.pieces[syms.Γ] = "outer" + fv = FacetValues(FacetQuadratureRule{RefTriangle}(14), ip, geometric_interpolation(QuadraticTriangle)) + reference = map(sort!(collect(getfacetset(grid, "outer")); by = fi -> (fi[1], fi[2]))) do (c, f) + Ferrite.reinit!(fv, getcoordinates(grid, c), f) + u_cell = U[celldofs(dh, c)] + q = 1:getnquadpoints(fv) + sum(q) do i + (function_gradient(fv, i, u_cell) ⋅ getnormal(fv, i)) * getdetJdV(fv, i) + end / sum(i -> getdetJdV(fv, i), q) + end + @test normal_flux(sol, syms.u(syms.x, syms.y), syms.Γ) ≈ reference rtol = 1.0e-10 + end +end diff --git a/test/WeakForm/weakform.jl b/test/WeakForm/weakform.jl index 892cb007..9765c738 100644 --- a/test/WeakForm/weakform.jl +++ b/test/WeakForm/weakform.jl @@ -184,3 +184,16 @@ end ) ) end + +@testset "a quotient is split over its numerator's terms (Robin data with a 1/r normal)" begin + s = StateSlots(1, 2, 0) + (; V) = TestSlots(2) + X, T = s.X, s.T + r = sqrt(X[1]^2 + X[2]^2) + # A Robin condition on a circle, u + ∂ₙu = g with ∂ₙ = −X·∇/r, gathered over one denominator. + robin = Num(Symbolics.unwrap((s.U[1] * r * V + (1 + T) * X[1] * V) / r)) + classes = classify(robin, s, TestSlots(2)) + @test [c.kind for c in classes] == [:bilinear, :source] + @test matches(classes, Dict(:bilinear => s.U[1] * V, :source => (1 + T) * X[1] * V / r)) + @test only(c.timedep for c in classes if c.kind === :bilinear) == false +end diff --git a/test/qa/qa.jl b/test/qa/qa.jl index 22185597..7058a84e 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -2,7 +2,8 @@ using SciMLTesting, FiniteElementMethod, Test using JET # `Ferrite.DofOrder.FieldWise` is Ferrite's documented renumbering API but is not declared `public`; -# ForwardDiff documents `derivative` as its API but does not declare it `public`; +# ForwardDiff documents `derivative`, and `Dual`, `Partials`, `value` and `partials` for custom rules, as its API +# but declares none of them `public`; # `Ferrite.dirichlet_facetdof_indices` (a facet's local nodes) has no public spelling in Ferrite 1. # ModelingToolkit re-exports these ModelingToolkitBase names; on Julia 1.10 `Base.which` reports # ModelingToolkitBase as their owner, on 1.11+ ModelingToolkit, the module we depend on. @@ -14,7 +15,9 @@ run_qa( aqua_kwargs = (; piracies = (; treat_as_own = [FiniteElementMethod.Ferrite.Grid])), ei_kwargs = (; all_qualified_accesses_are_public = (; - ignore = (:FieldWise, :derivative, :dirichlet_facetdof_indices), + ignore = ( + :FieldWise, :derivative, :Dual, :Partials, :value, :partials, :dirichlet_facetdof_indices, + ), ), all_explicit_imports_via_owners = (; ignore = LTS_MTK_OWNER), all_qualified_accesses_via_owners = (; ignore = LTS_MTK_OWNER), diff --git a/test/shared/annulus.jl b/test/shared/annulus.jl new file mode 100644 index 00000000..9d156077 --- /dev/null +++ b/test/shared/annulus.jl @@ -0,0 +1,35 @@ +using Ferrite: Ferrite +using FerriteGmsh: FerriteGmsh +using Gmsh: Gmsh, gmsh + +""" + annulus_grid(h; order = 2, r = 0.5, R = 1.0) + +Triangle mesh of the annulus `r ≤ |x| ≤ R` with mesh size `h`, built with the Gmsh API from +OpenCASCADE circles and converted with `FerriteGmsh.togrid`. With `order = 2` Gmsh places the mid-side +nodes on the circles and the grid has `QuadraticTriangle` cells; with `order = 1` the same +vertices make straight-sided `Triangle`s. Physical groups of dimension 1: `"inner"` (`|x| = r`) +and `"outer"` (`|x| = R`); dimension 2: `"domain"`. +""" +function annulus_grid(h; order = 2, r = 0.5, R = 1.0) + Gmsh.initialize() + try + gmsh.option.setNumber("General.Terminal", 0) + gmsh.model.add("annulus") + # OpenCASCADE full circles: Gmsh's built-in kernel needs a centre point for its arcs, which + # FerriteGmsh would keep as a node outside every cell. + gmsh.option.setNumber("Mesh.MeshSizeMax", h) + outer = gmsh.model.occ.addCircle(0, 0, 0, R) + inner = gmsh.model.occ.addCircle(0, 0, 0, r) + surface = gmsh.model.occ.addPlaneSurface([gmsh.model.occ.addCurveLoop([outer]), gmsh.model.occ.addCurveLoop([inner])]) + gmsh.model.occ.synchronize() + gmsh.model.addPhysicalGroup(1, [inner], -1, "inner") + gmsh.model.addPhysicalGroup(1, [outer], -1, "outer") + gmsh.model.addPhysicalGroup(2, [surface], -1, "domain") + gmsh.model.mesh.generate(2) + gmsh.model.mesh.setOrder(order) + return FerriteGmsh.togrid() + finally + Gmsh.finalize() + end +end diff --git a/test/shared/frontend_tests/arguments.jl b/test/shared/frontend_tests/arguments.jl new file mode 100644 index 00000000..0f479920 --- /dev/null +++ b/test/shared/frontend_tests/arguments.jl @@ -0,0 +1,95 @@ +# What `discretize` accepts besides the PDESystem and the FEMDiscretization: problem and solve +# keywords are forwarded to the problem; keywords the discretization computes, further positional +# arguments and a first argument that is not a PDESystem raise. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid +using Ferrite: Ferrite, Triangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +box() = MeshDomain(rectangle_grid(Triangle, (2, 2))) +sides(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + +function heat_system(Ω) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + bcs = [[u(t, Γ) ~ 0 for Γ in sides(Ω)]; u(0, x, y) ~ 0] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + return pdesys +end + +function poisson_system(Ω) + eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ -1 + @named pdesys = PDESystem([eq], [u(Γ) ~ 0 for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + return pdesys +end + +const DERIVED_MESSAGES = ( + tspan = "keyword `tspan` cannot be passed: the time span is the time domain of the PDESystem; change that domain to change it", + u0 = "keyword `u0` cannot be passed: the initial state comes from the PDESystem's initial conditions " * + "(a steady problem starts from zero with its Dirichlet data); change those, or call remake(prob; u0 = ...) on the returned problem", + p = "keyword `p` cannot be passed: the parameter values are the PDESystem's parameter defaults; change those and " * + "discretize again (the operators are assembled at those values, so solve rejects remake(prob; p = ...))", + differential_vars = "keyword `differential_vars` cannot be passed: which unknowns are differential is computed " * + "from the weak form (the fields with a time derivative)", +) + +const DERIVED_VALUES = (tspan = (0.0, 2.0), u0 = zeros(9), p = [1.0], differential_vars = trues(9)) + +@testset verbose = true "discretize arguments" begin + Ω = box() + pdesys = heat_system(Ω) + disc = FEMDiscretization(Ω, t) + + @testset "solve keywords reach the problem and the solve" begin + calls = Ref(0) + callback = SciMLBase.DiscreteCallback((u, t, integrator) -> true, integrator -> (calls[] += 1); save_positions = (false, false)) + prob = discretize(pdesys, disc; saveat = 0.25, tstops = [0.3], abstol = 1.0e-8, callback) + @test prob.kwargs[:saveat] == 0.25 + @test prob.kwargs[:tstops] == [0.3] + @test prob.kwargs[:abstol] == 1.0e-8 + @test prob.kwargs[:callback] === callback + sol = solve(prob, EXACT_ROWS) + @test SciMLBase.successful_retcode(sol) + @test sol.t ≈ [0.0, 0.25, 0.5, 0.75, 1.0] + @test calls[] > 0 + end + + @testset "an unknown keyword is forwarded too" begin + @test discretize(pdesys, disc; foo = 1).kwargs[:foo] == 1 + end + + @testset "keyword `$k` is derived" for k in keys(DERIVED_MESSAGES) + kw = NamedTuple{(k,)}((DERIVED_VALUES[k],)) + @test_throws ArgumentError(DERIVED_MESSAGES[k]) discretize(pdesys, disc; kw...) + @test_throws ArgumentError(DERIVED_MESSAGES[k]) SciMLBase.DAEProblem(pdesys, disc; kw...) + end + + @testset "derived keywords in FEMDiscretization and NonlinearProblem" begin + @test_throws ArgumentError(DERIVED_MESSAGES.tspan) FEMDiscretization(Ω, t; tspan = (0.0, 2.0)) + @test_throws ArgumentError(DERIVED_MESSAGES.p) FEMDiscretization(Ω; p = [1.0]) + steady = poisson_system(Ω) + @test_throws ArgumentError(DERIVED_MESSAGES.u0) SciMLBase.NonlinearProblem(steady, FEMDiscretization(Ω); u0 = zeros(9)) + @test_throws ArgumentError(DERIVED_MESSAGES.u0) discretize(steady, FEMDiscretization(Ω); u0 = zeros(9)) + end + + @testset "further positional arguments" begin + @test_throws ArgumentError("discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 1") discretize( + pdesys, disc, (0.0, 1.0) + ) + @test_throws ArgumentError("discretize(pdesys, disc; kwargs...) takes no further positional arguments; got 2") discretize( + pdesys, disc, 1, 2; saveat = 0.1 + ) + end + + @testset "first argument not a PDESystem" begin + @test_throws ArgumentError("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got Float64") discretize(1.0, disc) + @test_throws ArgumentError("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got Vector{Int64}") discretize( + [1, 2], disc, 1 + ) + end +end diff --git a/test/shared/frontend_tests/curved.jl b/test/shared/frontend_tests/curved.jl new file mode 100644 index 00000000..105bd8b1 --- /dev/null +++ b/test/shared/frontend_tests/curved.jl @@ -0,0 +1,168 @@ +# End to end on a curved domain (spec §6.2, §10.3 for P2, M4): a second-order Gmsh mesh of an +# annulus through the PDESystem front end. The space, the assembly (facet normals included) and +# the solution interface map cells with the mesh's own geometric interpolation, so P2 on +# quadratic cells keeps the L2 rate 3, while the same vertices with straight-sided cells cap it +# at 2: the Dirichlet data live on the true circle and the Robin data use its true normal. +using Test +using LinearAlgebra: norm, dot +using FiniteElementMethod: FiniteElementMethod, piece_nodes, normal_flux +using Ferrite: Ferrite, RefTriangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) +include(joinpath(@__DIR__, "..", "annulus.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +const r_in, r_out = 0.5, 1.0 + +# u* = (1 + t)φ is linear in t, which BDF integrates exactly, so the error is the spatial one. +φ = sin(2x) * cos(y) + x^2 * y +u_star = (1 + t) * φ +heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + + expand_derivatives(Dt(u_star) - Dx(Dx(u_star)) - Dy(Dy(u_star))) +ρ = sqrt(x^2 + y^2) +# The outer Dirichlet data are u* at the radial projection onto |x| = r_out: equal to u* only on +# the true circle. The inner Robin condition uses the true outward normal −(x, y)/ρ. +outer_data = substitute(u_star, Dict(x => r_out * x / ρ, y => r_out * y / ρ)) +inner_data = expand_derivatives(-(x * Dx(u_star) + y * Dy(u_star)) / ρ) + u_star +const φ_f = Symbolics.build_function(φ, x, y; expression = Val(false)) +u_exact(t_, x_, y_) = (1 + t_) * φ_f(x_, y_) +const ∇φ_f = [Symbolics.build_function(g, x, y; expression = Val(false)) for g in Symbolics.gradient(φ, [x, y])] +# Coordinates of the vertices of facet `fi`. +facet_ends(grid, fi) = [Ferrite.get_node_coordinate(grid, n) for n in Ferrite.facets(Ferrite.getcells(grid, fi[1]))[fi[2]]] + +const P2 = Lagrange{RefTriangle, 2}() + +function annulus_solve(h; order) + Ω = MeshDomain(annulus_grid(h; order, r = r_in, R = r_out)) + Γi, Γo = boundarypiece.(Ω, (:inner, :outer)) + bcs = [ + u(t, Γo) ~ outer_data, + NormalDerivative(Γi)(u(t, Γi)) + u(t, Γi) ~ inner_data, + u(0, x, y) ~ φ, + ] + sol, _ = fem_solve([heat], bcs, Ω, (x, y), t, [u(t, x, y)]; spaces = Dict(u => P2)) + return (; sol, Ω, Γi, Γo, grid = Ω.mesh) +end + +# L2 error at the final time over the discrete domain, with the geometry of the space. +function l2_error(sol) + space = sol.disc_data.space + ip_geo = Ferrite.geometric_interpolation(Ferrite.getcelltype(space.grid)) + cv = Ferrite.CellValues(Ferrite.QuadratureRule{RefTriangle}(8), P2, ip_geo) + U, tk = sol.original_sol.u[end], sol.t[end] + err = 0.0 + for cell in Ferrite.CellIterator(space.dh) + Ferrite.reinit!(cv, cell) + xs, u_cell = Ferrite.getcoordinates(cell), U[Ferrite.celldofs(cell)] + for q in 1:Ferrite.getnquadpoints(cv) + X = Ferrite.spatial_coordinate(cv, q, xs) + err += (Ferrite.function_value(cv, q, u_cell) - u_exact(tk, X...))^2 * Ferrite.getdetJdV(cv, q) + end + end + return sqrt(err) +end + +# Least-squares slope of log(error) against log(h). +function slope(hs, errs) + X, Y = log.(hs), log.(errs) + X̄, Ȳ = sum(X) / length(X), sum(Y) / length(Y) + return sum((X .- X̄) .* (Y .- Ȳ)) / sum(abs2, X .- X̄) +end + +const SIZES = (0.2, 0.1, 0.05, 0.025) + +@testset verbose = true "curved Gmsh domain" begin + runs = Dict(order => [annulus_solve(h; order) for h in SIZES] for order in (2, 1)) + + @testset "P2 converges at rate 3 on quadratic geometry and 2 on straight-sided cells" begin + @test all(run -> SciMLBase.successful_retcode(run.sol), vcat(values(runs)...)) + @test all(run -> Ferrite.getcelltype(run.grid) === Ferrite.QuadraticTriangle, runs[2]) + @test all(run -> Ferrite.getcelltype(run.grid) === Ferrite.Triangle, runs[1]) + # Gmsh meshes are not nested; h is the mean cell size. + hs = [sqrt(π * (r_out^2 - r_in^2) / Ferrite.getncells(run.grid)) for run in runs[2]] + curved, straight = (map(run -> l2_error(run.sol), runs[order]) for order in (2, 1)) + rate(errs) = [log(errs[k] / errs[k + 1]) / log(hs[k] / hs[k + 1]) for k in 1:(length(errs) - 1)] + show3(v) = Tuple(round.(v; sigdigits = 3)) + @info "annulus, P2 through the front end" h = show3(hs) curved = show3(curved) rates_curved = show3(rate(curved)) slope(hs, curved) straight = show3(straight) rates_straight = show3(rate(straight)) slope(hs, straight) + @test slope(hs, curved) >= 2.8 + @test all(>=(2.6), rate(curved)) + @test slope(hs, straight) <= 2.3 + @test all(<=(2.4), rate(straight)) + @test curved[end] < straight[end] / 20 + end + + curved, straight = runs[2][2], runs[1][2] + + @testset "space and facet values use the mesh's geometry" begin + # Perimeter of the inner circle and the deviation of the facet normals from −X/|X|. + function geometry(run) + space = run.sol.disc_data.space + fv = only(space.facetvalues) + perimeter, normal = 0.0, 0.0 + for fi in Ferrite.getfacetset(space.grid, "inner") + xs = Ferrite.getcoordinates(space.grid, fi[1]) + Ferrite.reinit!(fv, xs, fi[2]) + for q in 1:Ferrite.getnquadpoints(fv) + X = Ferrite.spatial_coordinate(fv, q, xs) + perimeter += Ferrite.getdetJdV(fv, q) + normal = max(normal, norm(Ferrite.getnormal(fv, q) + X / norm(X))) + end + end + return (; perimeter = abs(perimeter - 2π * r_in), normal) + end + c, s = geometry(curved), geometry(straight) + @info "geometry errors at h = $(SIZES[2])" curved = c straight = s + @test c.perimeter < s.perimeter / 100 + @test c.normal < s.normal / 100 + end + + @testset "solution interface on the curved mesh" begin + (; sol, Γi, Γo, grid) = curved + U = u(t, x, y) + # Traces: every node of the outer piece, mid-side nodes included, is on the circle. + nodes = piece_nodes(sol, Γo) + X, Y = sol[x][nodes], sol[y][nodes] + @test length(nodes) == 2 * length(Ferrite.getfacetset(grid, "outer")) + @test maximum(abs, hypot.(X, Y) .- r_out) <= 1.0e-12 + trace = sol[u(t, Γo)] + @test trace ≈ sol(sol.t, Γo; dv = U) rtol = 1.0e-12 + @test maximum(abs, trace .- [u_exact(tk, X[i], Y[i]) for tk in sol.t, i in eachindex(nodes)]) <= 1.0e-8 + @test nodal_error(sol, U, u_exact) <= 1.0e-3 + + # Point evaluation inside, and between the vertices of an outer arc, where the chord of a + # straight-sided cell leaves the domain. + pts = [(0.7, 0.1), (-0.3, 0.6), (0.0, -0.9)] + @test all(p -> abs(sol(1.0, p...; dv = U) - u_exact(1.0, p...)) <= 1.0e-3, pts) + fi = first(sort!(collect(Ferrite.getfacetset(grid, "outer")); by = fi -> (fi[1], fi[2]))) + a, b = (atan(v[2], v[1]) for v in facet_ends(grid, fi)) + θ = a + 0.25 * rem2pi(b - a, RoundNearest) + p = (r_out - 1.0e-9) .* (cos(θ), sin(θ)) + @test abs(sol(1.0, p...; dv = U) - u_exact(1.0, p...)) <= 1.0e-3 + @test isnan(straight.sol(1.0, p...; dv = U)) + + # The facet-mean normal flux on the curved Robin piece converges to that of u*. + @test sol[NormalDerivative(Γi)(u(t, Γi))] == normal_flux(sol, U, Γi) + function flux_error(run) + (; sol, Γi, grid) = run + fv = only(sol.disc_data.space.facetvalues) + facets = sort!(collect(Ferrite.getfacetset(grid, "inner")); by = fi -> (fi[1], fi[2])) + exact = map(facets) do fi + xs = Ferrite.getcoordinates(grid, fi[1]) + Ferrite.reinit!(fv, xs, fi[2]) + qs = 1:Ferrite.getnquadpoints(fv) + sum(qs) do q + X = Ferrite.spatial_coordinate(fv, q, xs) + (1 + sol.t[end]) * dot([g(X...) for g in ∇φ_f], Ferrite.getnormal(fv, q)) * Ferrite.getdetJdV(fv, q) + end / sum(q -> Ferrite.getdetJdV(fv, q), qs) + end + return maximum(abs, sol[NormalDerivative(Γi)(u(t, Γi))][end, :] - exact) + end + errs = [flux_error(runs[2][k]) for k in 2:3] + @info "inner normal flux error at h = $(SIZES[2:3])" errs + @test errs[2] < errs[1] / 3 + @test errs[2] <= 5.0e-3 + end +end diff --git a/test/shared/frontend_tests/documentation.jl b/test/shared/frontend_tests/documentation.jl index 0512d9fe..c5706a4b 100644 --- a/test/shared/frontend_tests/documentation.jl +++ b/test/shared/frontend_tests/documentation.jl @@ -62,7 +62,7 @@ using ModelingToolkit: t_nounits as t ] @named sys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) @test_throws ArgumentError( - "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has U₁*V + T*U₁*V" + "time-dependent coefficients in the mass or stiffness operator are not supported: equation 1 has U₁*V + T*U₁*V" ) discretize(sys, FEMDiscretization(Ω, t)) end end diff --git a/test/shared/frontend_tests/eliminate.jl b/test/shared/frontend_tests/eliminate.jl new file mode 100644 index 00000000..d71e80f9 --- /dev/null +++ b/test/shared/frontend_tests/eliminate.jl @@ -0,0 +1,173 @@ +# End-to-end tests of `dirichlet = :eliminate` (spec §7.3): PDESystem -> DAEProblem on the free +# dofs -> solve, checked against exact solutions in the finite-element space and against +# `:algebraic`, with the full field rebuilt for every solution accessor. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, field_range, prescribed_dofs +using Ferrite: Triangle, Line + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t +using LinearAlgebra: norm + +@variables x y u(..) v(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +const tol = 1.0e-8 +const P2_LINE = Dict(u => Lagrange{RefLine, 2}()) + +pieces(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +eliminated(args...; kw...) = fem_solve(args...; dirichlet = :eliminate, kw...) + +# u* = a + b x + x(1 - x)(1 + t) solves u_t = u_xx + x(1 - x) + 2(1 + t) and is in the P2 space. +bubble_eq = Dt(u(t, x)) ~ Dx(Dx(u(t, x))) + x * (1 - x) + 2 * (1 + t) +bubble(a, b) = (t_, x_) -> a + b * x_ + x_ * (1 - x_) * (1 + t_) + +@testset verbose = true "dirichlet = :eliminate" begin + @testset "homogeneous Dirichlet, 1D P2" begin + Ω = MeshDomain(rectangle_grid(Line, (4,))) + lo, hi = boundarypiece.(Ω, (:x1_lo, :x1_hi)) + bcs = [u(t, lo) ~ 0, u(t, hi) ~ 0, u(0, x) ~ x * (1 - x)] + sol, prob = eliminated([bubble_eq], bcs, Ω, (x,), t, [u(t, x)]; spaces = P2_LINE) + @test SciMLBase.successful_retcode(sol) + @test length(prob.u0) == 9 - 2 + @test nodal_error(sol, u(t, x), bubble(0, 0)) <= tol + end + + @testset "nonzero constant Dirichlet, 1D P2" begin + Ω = MeshDomain(rectangle_grid(Line, (4,))) + lo, hi = boundarypiece.(Ω, (:x1_lo, :x1_hi)) + bcs = [u(t, lo) ~ 2, u(t, hi) ~ 3, u(0, x) ~ 2 + x + x * (1 - x)] + sol, _ = eliminated([bubble_eq], bcs, Ω, (x,), t, [u(t, x)]; spaces = P2_LINE) + @test nodal_error(sol, u(t, x), bubble(2, 1)) <= tol + @test sol[u(t, lo)] ≈ fill(2.0, length(sol.t), 1) atol = 1.0e-14 + @test sol[u(t, hi)] ≈ fill(3.0, length(sol.t), 1) atol = 1.0e-14 + end + + @testset "spatially varying constant Dirichlet with Neumann pieces, 2D P2" begin + # u* = 1 + x + 2y + x(1 - x)(1 + t): Dirichlet in x, Neumann in y. + Ω = MeshDomain(rectangle_grid(Triangle, (3, 3))) + Γl, Γr, Γb, Γt = pieces(Ω) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + x * (1 - x) + 2 * (1 + t) + bcs = [ + u(t, Γl) ~ 1 + 2y, u(t, Γr) ~ 2 + 2y, + NormalDerivative(Γb)(u(t, Γb)) ~ -2, NormalDerivative(Γt)(u(t, Γt)) ~ 2, + u(0, x, y) ~ 1 + x + 2y + x * (1 - x), + ] + sol, _ = eliminated( + [eq], bcs, Ω, (x, y), t, [u(t, x, y)]; spaces = Dict(u => Lagrange{RefTriangle, 2}()) + ) + @test nodal_error(sol, u(t, x, y), (t_, x_, y_) -> 1 + x_ + 2y_ + x_ * (1 - x_) * (1 + t_)) <= tol + end + + # Constant Dirichlet data, a time-dependent source (the load is a function of t) and an + # initial field that is not an exact solution. + Ω = MeshDomain(rectangle_grid(Triangle, (6, 6))) + Γl, Γr, Γb, Γt = pieces(Ω) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + sin(3x + t) * (1 + y) + top(x_) = 1 + x_ + x_ * (1 - x_) + bcs = [[u(t, Γ) ~ 1 + x for Γ in (Γl, Γr, Γb)]; u(t, Γt) ~ top(x); u(0, x, y) ~ 1 + x + x * (1 - x) * y^2] + solve_kwargs = (; abstol = 1.0e-10, reltol = 1.0e-10, saveat = 0.1) + alg_sol, alg_prob = fem_solve([eq], bcs, Ω, (x, y), t, [u(t, x, y)]; solve_kwargs) + sol, prob = eliminated([eq], bcs, Ω, (x, y), t, [u(t, x, y)]; solve_kwargs) + + @testset "agrees with :algebraic" begin + @test SciMLBase.successful_retcode(sol) + @test sol.t ≈ alg_sol.t + @test maximum(abs, sol[u(t, x, y)] - alg_sol[u(t, x, y)]) <= 1.0e-7 + end + + @testset "reduced problem" begin + space = sol.disc_data.space + free = setdiff(1:length(alg_prob.u0), prescribed_dofs(space)) + @test length(prob.u0) == length(free) == size(prob.f.jac_prototype, 1) + @test prob.u0 == alg_prob.u0[free] + @test all(prob.differential_vars) + res = similar(prob.u0) + prob.f(res, prob.du0, prob.u0, prob.p, 0.0) + @test norm(res, Inf) <= 1.0e-10 + @test length(sol.original_sol[only(sol.disc_data.fields).unknown][end]) == length(free) + end + + @testset "solution interface returns full fields" begin + U = sol[u(t, x, y)] + @test size(U) == size(alg_sol[u(t, x, y)]) + for (Γ, g) in ((Γl, x_ -> 1 + x_), (Γt, top)) + nodes = piece_nodes(sol, Γ) + expected = [g(sol[x][i]) for _ in sol.t, i in nodes] + @test sol[u(t, Γ)] ≈ expected atol = 1.0e-14 + @test U[:, nodes] ≈ expected atol = 1.0e-14 + @test sol(0.35, Γ; dv = u(t, x, y)) ≈ expected[1, :] atol = 1.0e-14 + end + @test sol(0.35, 0.0, 0.5; dv = u(t, x, y)) ≈ 1.0 atol = 1.0e-14 + @test sol(0.35, 0.3, 0.6; dv = u(t, x, y)) ≈ alg_sol(0.35, 0.3, 0.6; dv = u(t, x, y)) atol = 1.0e-6 + @test normal_flux(sol, u(t, x, y), Γr) ≈ normal_flux(alg_sol, u(t, x, y), Γr) atol = 1.0e-6 + @test sol[Dx(u(t, x, y))] ≈ alg_sol[Dx(u(t, x, y))] atol = 1.0e-6 + mktempdir() do dir + pvd = write_vtk(sol, joinpath(dir, "heat")) + @test isfile(pvd) + @test count(endswith(".vtu"), readdir(dir)) == length(sol.t) + end + end + + @testset "algebraic field: structurally zero mass rows stay algebraic" begin + # u_t = Δu + v with 0 = Δv: v* = 1 + x is exact in P1, and u is compared with :algebraic. + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(t, x, y) + algebraic = 0 ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))) + Ω2 = MeshDomain(rectangle_grid(Triangle, (4, 4))) + bcs2 = [ + [u(t, Γ) ~ 1 + x + 2y for Γ in pieces(Ω2)]; [v(t, Γ) ~ 1 + x for Γ in pieces(Ω2)]; + u(0, x, y) ~ (1 + x + 2y) + x * (1 - x) * y * (1 - y) + ] + sol2, prob2 = eliminated( + [parabolic, algebraic], bcs2, Ω2, (x, y), t, [u(t, x, y), v(t, x, y)]; + pairing = Dict(algebraic => v), tspan = (0.0, 5.0), solve_kwargs + ) + alg2, _ = fem_solve( + [parabolic, algebraic], bcs2, Ω2, (x, y), t, [u(t, x, y), v(t, x, y)]; + pairing = Dict(algebraic => v), tspan = (0.0, 5.0), solve_kwargs + ) + @test SciMLBase.successful_retcode(sol2) + space = sol2.disc_data.space + nfree(name) = count(!in(prescribed_dofs(space)), field_range(space, name)) + @test prob2.differential_vars == [trues(nfree(:u)); falses(nfree(:v))] + @test nodal_error(sol2, v(t, x, y), (t_, x_, y_) -> 1 + x_) <= tol + @test maximum(abs, sol2[u(t, x, y)] - alg2[u(t, x, y)]) <= 1.0e-7 + end + + @testset "a field with every dof prescribed has no unknowns" begin + # Two triangles have no interior node, so v = 1 + x on the whole boundary prescribes all of v. + # u* = (1 + x) t solves u_t = Δu + v with the Neumann data ∂ₙu = ∓t on the left and right. + Ω1 = MeshDomain(rectangle_grid(Triangle, (1, 1))) + Γl1, Γr1, Γb1, Γt1 = pieces(Ω1) + Dn(Γ) = NormalDerivative(Γ) + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(t, x, y) + algebraic = 0 ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))) + bcs1 = [ + Dn(Γl1)(u(t, Γl1)) ~ -t; Dn(Γr1)(u(t, Γr1)) ~ t; Dn(Γb1)(u(t, Γb1)) ~ 0; Dn(Γt1)(u(t, Γt1)) ~ 0; + [v(t, Γ) ~ 1 + x for Γ in pieces(Ω1)]; u(0, x, y) ~ 0 + ] + sol1, prob1 = eliminated( + [parabolic, algebraic], bcs1, Ω1, (x, y), t, [u(t, x, y), v(t, x, y)]; pairing = Dict(algebraic => v) + ) + @test SciMLBase.successful_retcode(sol1) + @test length(prob1.u0) == 4 + @test [f.unknown === nothing for f in sol1.disc_data.fields] == [false, true] + @test nodal_error(sol1, u(t, x, y), (t_, x_, y_) -> (1 + x_) * t_) <= tol + @test nodal_error(sol1, v(t, x, y), (t_, x_, y_) -> 1 + x_) <= 1.0e-14 + @test size(sol1[v(t, x, y)]) == size(sol1[u(t, x, y)]) + # With every dof prescribed there is nothing left to integrate. + @test_throws ArgumentError( + "dirichlet = :eliminate leaves no unknowns because every dof is prescribed; use the default dirichlet = :algebraic" + ) eliminated([eq], [[u(t, Γ) ~ 1 + x for Γ in pieces(Ω1)]; u(0, x, y) ~ 1 + x], Ω1, (x, y), t, [u(t, x, y)]) + end + + @testset "time-dependent Dirichlet data are rejected" begin + td = [u(t, Γl) ~ 1 + x; u(t, Γr) ~ (2 + x) * (1 + t); [u(t, Γ) ~ 1 + x for Γ in (Γb, Γt)]; u(0, x, y) ~ 1 + x] + @named pdesys = PDESystem([eq], td, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_throws ArgumentError( + "dirichlet = :eliminate needs Dirichlet data that are constant in time, but the condition on " * + "boundary piece right depends on time; use the default dirichlet = :algebraic" + ) discretize(pdesys, FEMDiscretization(Ω, t; dirichlet = :eliminate)) + @test discretize(pdesys, FEMDiscretization(Ω, t)) isa SciMLBase.DAEProblem + end +end diff --git a/test/shared/frontend_tests/end_to_end.jl b/test/shared/frontend_tests/end_to_end.jl index 41c6ea32..9d599aad 100644 --- a/test/shared/frontend_tests/end_to_end.jl +++ b/test/shared/frontend_tests/end_to_end.jl @@ -44,6 +44,16 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test nodal_error(sol, u(t, x, y), uexact) <= tol space = sol.disc_data.space @test !any(prob.differential_vars[space.ch.prescribed_dofs]) + # Not index 2: the default algebraic_abstol = :auto sets no abstol. + @test !haskey(prob.kwargs, :abstol) + # An explicit algebraic_abstol applies to any system: here to the Dirichlet rows, which stay exact. + sol, prob = fem_solve( + [heat_eq], [dirichlet_all(Ω); ic], Ω, (x, y), t, [u(t, x, y)]; algebraic_abstol = 1.0e3, + solve_kwargs = (; reltol = 1.0e-10), abstol = 1.0e-10 + ) + @test prob.kwargs[:abstol] == [d ? 1.0e-10 : 1.0e3 for d in prob.differential_vars] + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, u(t, x, y), uexact) <= tol # The symbolic Dirichlet data agree with the ConstraintHandler, including at corners # shared by two pieces, where the condition added last wins. load = SciMLBase.SymbolicIndexingInterface.getp(prob.f.sys, prob.f.sys.Fop)(prob.p) @@ -62,7 +72,7 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test sol.t == 0:0.25:1 @test sol.disc_data isa FEMMetadata @test discretize(pdesys, FEMDiscretization(Ω, t; saveat = 0.25); saveat = 0.5).kwargs[:saveat] == 0.5 - reserved = "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name" + reserved = "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name, parameters" @test_throws ArgumentError(reserved) FEMDiscretization(Ω, t; name = :other) @test_throws ArgumentError(replace(reserved, "`name`" => "`du0`")) discretize(pdesys, FEMDiscretization(Ω, t); du0 = zeros(3)) @test sprint(show, sol.disc_data) == sprint(show, prob.problem_type) == "FEMMetadata(fields = [u], ndofs = 9, hasTime = true)" @@ -72,6 +82,17 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test sys isa ModelingToolkit.System end + @testset "PDESystem without parameters" begin + # Leaving out `ps` gives the system `NullParameters()`, which means no parameters. + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + domains = [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)] + @named pdesys = PDESystem([heat_eq], [dirichlet_all(Ω); ic], domains, [t, x, y], [u(t, x, y)]) + @test pdesys.ps isa SciMLBase.NullParameters + sol = solve(discretize(pdesys, FEMDiscretization(Ω, t)), EXACT_ROWS; abstol = 1.0e-10, reltol = 1.0e-10) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, u(t, x, y), uexact) <= tol + end + @testset "P1 quadrilaterals" begin Ω = MeshDomain(rectangle_grid(Quadrilateral, (3, 4))) sol, _ = fem_solve([heat_eq], [dirichlet_all(Ω); ic], Ω, (x, y), t, [u(t, x, y)]) @@ -213,6 +234,8 @@ dirichlet_all(Ω) = [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)] @test SciMLBase.successful_retcode(sol) space = sol.disc_data.space @test !any(prob.differential_vars[FiniteElementMethod.field_range(space, :v)]) + # v is algebraic but appears in its own equation (index 1): no abstol is set. + @test !haskey(prob.kwargs, :abstol) @test nodal_error(sol, u(t, x, y), uexact) <= tol @test nodal_error(sol, v(t, x, y), (t_, x_, y_) -> 1 + x_ + 2y_) <= tol end diff --git a/test/shared/frontend_tests/errors.jl b/test/shared/frontend_tests/errors.jl index 726c3305..3144e6b0 100644 --- a/test/shared/frontend_tests/errors.jl +++ b/test/shared/frontend_tests/errors.jl @@ -77,35 +77,60 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] Ω = box() Γl, Γr = sides(Ω) @test_throws ArgumentError( - "periodic conditions need milestone M4 (Ferrite PeriodicDirichlet): u(t, Γ_left) ~ u(t, Γ_right)" + "periodic boundary conditions are not supported: u(t, Γ_left) ~ u(t, Γ_right)" ) lower([heat], [u(t, Γl) ~ u(t, Γr), ic], Ω) end @testset "reserved options" begin Ω = box() - @test_throws ArgumentError("codegen = :mtk lands in M3; use the default codegen = :numeric") FEMDiscretization( + @test_throws ArgumentError("codegen = :mtk is not supported; use the default codegen = :numeric") FEMDiscretization( Ω, t; codegen = :mtk ) - @test_throws ArgumentError("dirichlet = :eliminate lands in M4; use the default dirichlet = :algebraic") FEMDiscretization( - Ω, t; dirichlet = :eliminate + @test_throws ArgumentError("dirichlet must be :algebraic or :eliminate, got :condense") FEMDiscretization( + Ω, t; dirichlet = :condense ) + for (value, shown) in ((0, "0"), (-1.0e8, "-1.0e8"), (NaN, "NaN"), ("1e8", "\"1e8\""), (:on, ":on"), ([1.0e8], "[1.0e8]")) + @test_throws ArgumentError("algebraic_abstol must be :auto, nothing or a positive number, got $shown") FEMDiscretization( + Ω, t; algebraic_abstol = value + ) + end + end + + @testset "steady and time-dependent entry points" begin + Ω = box() @named steady = PDESystem( [Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], [u(Γ) ~ 0 for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], [] ) - @test_throws ArgumentError("steady problems land in M4; give FEMDiscretization a time variable") discretize( - steady, FEMDiscretization(Ω) - ) + @test_throws ArgumentError( + "the FEMDiscretization has no time variable, so it lowers to a NonlinearProblem, not a DAEProblem; " * + "call discretize(pdesys, disc) or NonlinearProblem(pdesys, disc)" + ) DAEProblem(steady, FEMDiscretization(Ω)) + @named transient = PDESystem([heat], [dirichlet(Ω); ic], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + @test_throws ArgumentError( + "the FEMDiscretization has the time variable t, so it lowers to a DAEProblem; " * + "for a steady problem write FEMDiscretization(Ω) without a time variable" + ) SciMLBase.NonlinearProblem(transient, FEMDiscretization(Ω, t)) + @test_throws ArgumentError( + "the PDESystem pairs t with an interval, but the FEMDiscretization has no time variable; " * + "for a time-dependent problem write FEMDiscretization(Ω, t)" + ) discretize(transient, FEMDiscretization(Ω)) + @test_throws ArgumentError( + "keyword `name` is set by the FEM discretization and cannot be passed; the reserved keywords are iv, unknowns, du0, coordinate, name, parameters" + ) discretize(steady, FEMDiscretization(Ω); name = :other) + @test_throws ArgumentError( + "algebraic_abstol applies to time-dependent problems (the DAE path); a steady FEMDiscretization has no time stepper" + ) FEMDiscretization(Ω; algebraic_abstol = 1.0e8) + # :auto (the default) and nothing are accepted and set no abstol on the NonlinearProblem. + for value in (:auto, nothing) + @test !haskey(discretize(steady, FEMDiscretization(Ω; algebraic_abstol = value)).kwargs, :abstol) + end end - @testset "nonlinear and time-dependent operators" begin + @testset "time-dependent operators" begin Ω = box() - nl = Dt(u(t, x, y)) ~ Dx((1 + u(t, x, y)^2) * Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) - @test_throws ArgumentError("nonlinear terms land in M3: equation 1 has the nonlinear term G₁*(U₁^2)*W₁") lower( - [nl], [dirichlet(Ω); ic], Ω - ) td = Dt(u(t, x, y)) ~ Dx((1 + t) * Dx(u(t, x, y))) + Dy((1 + t) * Dy(u(t, x, y))) @test_throws ArgumentError( - "time-dependent coefficients in the mass or stiffness operator land in M3: equation 1 has " * + "time-dependent coefficients in the mass or stiffness operator are not supported: equation 1 has " * "G₁*W₁ + G₂*W₂ + G₁*T*W₁ + G₂*T*W₂" ) lower([td], [dirichlet(Ω); ic], Ω) end @@ -142,12 +167,12 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] ) end - @testset "time must be the first argument" begin + @testset "time must be the first or the last argument" begin Ω = box() - eq = Dt(u(x, y, t)) ~ Dx(Dx(u(x, y, t))) + Dy(Dy(u(x, y, t))) - bcs = [u(x, y, 0) ~ 0] - @test_throws ArgumentError("time must be the first argument of u(x, y, t); time-last ordering lands later") lower( - [eq], bcs, Ω; dvs = [u(x, y, t)] + eq = Dt(u(x, t, y)) ~ Dx(Dx(u(x, t, y))) + Dy(Dy(u(x, t, y))) + bcs = [u(x, 0, y) ~ 0] + @test_throws ArgumentError("time must be the first or the last argument of u(x, t, y), as in u(t, x, y) or u(x, y, t)") lower( + [eq], bcs, Ω; dvs = [u(x, t, y)] ) end @@ -179,6 +204,20 @@ dirichlet(Ω) = [u(t, Γ) ~ 0 for Γ in sides(Ω)] @test SciMLBase.successful_retcode(sol) end + @testset "parameters" begin + Ω = box() + @parameters k + eq = Dt(u(t, x, y)) ~ k * (Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y)))) + system(ps...) = PDESystem([eq], [dirichlet(Ω); ic], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], ps...; name = :pdesys) + # An undeclared parameter is reported the same way whether `ps` is empty or left out. + for pdesys in (system([]), system()) + @test occursin("unresolved symbols", errmsg(() -> discretize(pdesys, FEMDiscretization(Ω, t)))) + end + @test_throws ArgumentError("parameter k needs a numeric value in the PDESystem, as k => value") discretize( + system([k]), FEMDiscretization(Ω, t) + ) + end + @testset "a piece with no condition warns when its flux is not zero" begin Ω = box() Γl, Γr, Γb, Γt = sides(Ω) diff --git a/test/shared/frontend_tests/extension_contract.jl b/test/shared/frontend_tests/extension_contract.jl new file mode 100644 index 00000000..810e1f39 --- /dev/null +++ b/test/shared/frontend_tests/extension_contract.jl @@ -0,0 +1,44 @@ +# The Extension contract page (docs/src/extension_contract.md) states the keyword sets, messages and types of the +# front end; these tests keep the page and the code in step. +using Test +using FiniteElementMethod: FiniteElementMethod, FEMMetadata, rectangle_grid +using Ferrite: Triangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t +using PDEBase: PDEBase + +const PAGE = read(joinpath(@__DIR__, "..", "..", "..", "docs", "src", "extension_contract.md"), String) + +message(f) = try + f() + "" +catch e + e isa ArgumentError ? e.msg : rethrow() +end + +@testset verbose = true "extension contract page" begin + reserved = FiniteElementMethod._RESERVED_KWARGS + derived = keys(FiniteElementMethod._DERIVED_KWARGS) + @test occursin(join(("`$k`" for k in reserved), ", ", " and "), PAGE) + @test all(k -> occursin("| `$k`", PAGE), derived) + @test length(reserved) + length(derived) == 10 + @test occursin("Ten keywords are reserved", PAGE) + + @variables x y u(..) + Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + Ω = MeshDomain(rectangle_grid(Triangle, (2, 2))) + eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + bcs = [[u(t, Γ) ~ 0 for Γ in boundarypieces(Ω)]; u(0, x, y) ~ 0] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t) + @test occursin(message(() -> FEMDiscretization(Ω, t; tspan = (0.0, 2.0))), PAGE) + @test occursin(message(() -> discretize(pdesys, disc, 1)), PAGE) + @test startswith(message(() -> discretize(1, disc)), "FEMDiscretization discretizes a ModelingToolkit.PDESystem; got ") + @test occursin("FEMDiscretization discretizes a ModelingToolkit.PDESystem; got ...", PAGE) + + @test FEMMetadata <: SciMLBase.AbstractDiscretizationMetadata + @test discretize(pdesys, disc).problem_type isa FEMMetadata + @test FEMDiscretization <: PDEBase.AbstractMeshDiscretization <: SciMLBase.AbstractDiscretization +end diff --git a/test/shared/frontend_tests/facet_dofs.jl b/test/shared/frontend_tests/facet_dofs.jl new file mode 100644 index 00000000..6b0626fa --- /dev/null +++ b/test/shared/frontend_tests/facet_dofs.jl @@ -0,0 +1,104 @@ +# Index data on the FEMMetadata of a discretized problem: `facet_dofs`, `dof_coordinates` and `cell_dofs`. +using Test +using FiniteElementMethod: rectangle_grid, facet_dofs, dof_coordinates, cell_dofs +using Ferrite: Triangle, Quadrilateral, addcellset!, getcellset, getfacetset, addfacetset! + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) w(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +Δ(f) = Dx(Dx(f)) + Dy(Dy(f)) + +# The metadata of the heat problem on `Ω` with no boundary conditions (natural zero flux). +function heat_metadata(Ω; kwargs...) + @named pdesys = PDESystem( + [Dt(u(t, x, y)) ~ Δ(u(t, x, y))], [u(0, x, y) ~ x], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], [] + ) + return discretize(pdesys, FEMDiscretization(Ω, t; kwargs...)).problem_type +end + +@testset verbose = true "facet_dofs, dof_coordinates, cell_dofs" begin + @testset "P1 and P2 triangles" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 3))) + left, top = boundarypiece.(Ω, (:left, :top)) + for (order, nleft, ntop) in ((1, 4, 5), (2, 7, 9)) + md = heat_metadata(Ω; spaces = Dict(u => Lagrange{RefTriangle, order}())) + ndofs = size(dof_coordinates(md), 2) + X = dof_coordinates(md) + @test size(X) == (2, (order == 1 ? 5 * 4 : 9 * 7)) + dl = facet_dofs(md, left, u) + @test length(dl) == nleft && issorted(dl) + @test all(iszero, X[1, dl]) + @test facet_dofs(md, "top", :u) == facet_dofs(md, top, u) + @test length(facet_dofs(md, top, u(t, x, y))) == ntop + @test all(≈(1.0), X[2, facet_dofs(md, :top, u)]) + C = cell_dofs(md, u) + @test size(C) == (order == 1 ? 3 : 6, 4 * 3 * 2) + @test sort!(unique(vec(C))) == 1:ndofs + end + end + + @testset "a mesh of one cell still gives a matrix" begin + md = heat_metadata(MeshDomain(rectangle_grid(Quadrilateral, (1, 1)))) + @test cell_dofs(md, :u) isa Matrix{Int} + @test size(cell_dofs(md, :u)) == (4, 1) + end + + @testset "a field that does not reach the facet set has no dofs there" begin + grid = rectangle_grid(Triangle, (4, 4)) + addcellset!(grid, "left_half", X -> X[1] <= 0.5 + 1.0e-12) + region = getcellset(grid, "left_half") + for side in ("bottom", "top") + set = getfacetset(grid, side) + delete!(grid.facetsets, side) + addfacetset!(grid, side * "_left", Set(fi for fi in set if fi[1] in region)) + addfacetset!(grid, side * "_right", Set(fi for fi in set if !(fi[1] in region))) + end + Ω = MeshDomain(grid) + Γ = Dict(n => boundarypiece(Ω, n) for n in (:left, :right, :bottom_left, :bottom_right, :top_left, :top_right)) + U, W = u(t, x, y), w(t, x, y) + bcs = [ + [u(t, Γ[n]) ~ 0 for n in keys(Γ)]; + [w(t, Γ[n]) ~ 0 for n in (:left, :bottom_left, :top_left)]; + u(0, x, y) ~ x; w(0, x, y) ~ y + ] + @named pdesys = PDESystem( + [Dt(U) ~ Δ(U), Dt(W) ~ Δ(W) + U], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U, W], [] + ) + md = discretize(pdesys, FEMDiscretization(Ω, t; regions = Dict(w => Region(Ω, :left_half)))).problem_type + @test isempty(facet_dofs(md, :right, w)) + @test !isempty(facet_dofs(md, :right, u)) + @test length(facet_dofs(md, :left, w)) == 5 + @test occursin("regions", errmsg(() -> cell_dofs(md, w))) + end + + @testset "cells that hold no field at all" begin + grid = rectangle_grid(Triangle, (4, 4)) + addcellset!(grid, "left_half", X -> X[1] <= 0.5 + 1.0e-12) + Ω = MeshDomain(grid) + Γ = Dict(n => boundarypiece(Ω, n) for n in (:left, :right)) + U = u(t, x, y) + @named pdesys = PDESystem( + [Dt(U) ~ Δ(U)], [u(t, Γ[:left]) ~ 0; u(0, x, y) ~ x], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], [] + ) + md = discretize(pdesys, FEMDiscretization(Ω, t; regions = Dict(u => Region(Ω, :left_half)))).problem_type + @test isempty(facet_dofs(md, :right, u)) + @test length(facet_dofs(md, :left, u)) == 5 + end + + @testset "cell_dofs rejects a single region that covers only part of the mesh" begin + grid = rectangle_grid(Triangle, (4, 4)) + addcellset!(grid, "left_half", X -> X[1] <= 0.5 + 1.0e-12) + md = heat_metadata(MeshDomain(grid); regions = Dict(u => Region(MeshDomain(grid), :left_half))) + @test occursin("regions", errmsg(() -> cell_dofs(md, u))) + end + + @testset "rejections" begin + md = heat_metadata(MeshDomain(rectangle_grid(Quadrilateral, (2, 2)))) + @test occursin("not a facet set", errmsg(() -> facet_dofs(md, "nope", u))) + @test occursin("not a field", errmsg(() -> facet_dofs(md, "left", :v))) + @test occursin("not a field", errmsg(() -> cell_dofs(md, :v))) + end +end diff --git a/test/shared/frontend_tests/messages.jl b/test/shared/frontend_tests/messages.jl new file mode 100644 index 00000000..25ee79e3 --- /dev/null +++ b/test/shared/frontend_tests/messages.jl @@ -0,0 +1,24 @@ +# Exact messages of front-end errors not covered in errors.jl. +using Test +using Ferrite: Ferrite, Triangle, Quadrilateral, Grid, Node, Vec, Lagrange, RefTriangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +@testset "front-end messages" begin + @testset "mixed cell types" begin + nodes = [Node(Vec(0.0, 0.0)), Node(Vec(1.0, 0.0)), Node(Vec(0.0, 1.0)), Node(Vec(2.0, 0.0)), Node(Vec(1.0, 1.0))] + grid = Grid(Ferrite.AbstractCell[Triangle((1, 2, 3)), Quadrilateral((2, 4, 5, 3))], nodes) + Ω = MeshDomain(grid) + heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + @named pdesys = PDESystem([heat], [u(0, x, y) ~ 0], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 1}())) + @test_throws ArgumentError("meshes with mixed cell types are not supported; use a mesh with a single cell type") discretize( + pdesys, disc + ) + end +end diff --git a/test/shared/frontend_tests/multifield.jl b/test/shared/frontend_tests/multifield.jl index 6d5329a8..59ec050b 100644 --- a/test/shared/frontend_tests/multifield.jl +++ b/test/shared/frontend_tests/multifield.jl @@ -52,6 +52,30 @@ end rates(errs) = [log2(errs[i] / errs[i + 1]) for i in 1:(length(errs) - 1)] +# Taylor–Hood Stokes on the unit square: stream function ψ = x²(1 − x)²y²(1 − y)², u = (ψ_y, −ψ_x), which +# vanishes on the boundary, and p = x³ − y³; the source makes (u, p) steady. +const U1, U2, P = u1(t, x, y), u2(t, x, y), p(t, x, y) +const STOKES_ψ = x^2 * (1 - x)^2 * y^2 * (1 - y)^2 +const STOKES_SOLUTION = (expand_derivatives(Dy(STOKES_ψ)), expand_derivatives(-Dx(STOKES_ψ)), x^3 - y^3) +const STOKES_EXACT = map(e -> Symbolics.build_function(e, x, y; expression = Val(false)), STOKES_SOLUTION) +function stokes_problem(ct, n; kw...) + u1s, u2s, ps = STOKES_SOLUTION + f1, f2 = expand_derivatives(-Δ(u1s) + Dx(ps)), expand_derivatives(-Δ(u2s) + Dy(ps)) + continuity = 0 ~ Dx(U1) + Dy(U2) + eqs = [Dt(U1) ~ Δ(U1) - Dx(P) + f1, Dt(U2) ~ Δ(U2) - Dy(P) + f2, continuity] + Ω = MeshDomain(corner_grid(ct, n)) + Γs = boundarypiece.(Ω, (:left, :right, :bottom, :top, :corner)) + bcs = [ + [u1(t, Γ) ~ 0 for Γ in Γs]; [u2(t, Γ) ~ 0 for Γ in Γs]; p(t, Γs[end]) ~ x^3 - y^3; + u1(0, x, y) ~ 0; u2(0, x, y) ~ 0; p(0, x, y) ~ x^3 - y^3 + ] + @named stokes = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x, y], [U1, U2, P], []) + shape = SHAPE[ct] + P2, P1 = Lagrange{shape, 2}(), Lagrange{shape, 1}() + disc = FEMDiscretization(Ω, t; spaces = Dict(u1 => P2, u2 => P2, p => P1), pairing = Dict(continuity => p), kw...) + return discretize(stokes, disc) +end + @testset verbose = true "multi-field front end" begin @testset "unequal orders, $(ct)s: rates p + 1 for both fields" for ct in (Triangle, Quadrilateral) # u in P2/Q2, w in P1/Q1. w's equation reads u but not the reverse, so u keeps its own rate. @@ -87,39 +111,51 @@ rates(errs) = [log2(errs[i] / errs[i + 1]) for i in 1:(length(errs) - 1)] end @testset "Taylor–Hood Stokes, $(ct)s: velocity rate 3, pressure rate 2" for ct in (Triangle, Quadrilateral) - # Stream function ψ = x²(1 − x)²y²(1 − y)², u = (ψ_y, −ψ_x), which vanishes on the boundary, and p = x³ − y³; - # the source makes (u, p) steady. Marched from u = 0 to the steady state (the slowest Stokes mode decays like + # Marched from u = 0 to the steady state (the slowest Stokes mode decays like # e^{−52t}). The continuity rows are algebraic and the pressure is absent from them (index 2): the pressure - # starts from its exact values, is pinned on the one-facet piece "corner", and is left out of the error - # control through a large abstol, without which DFBDF fails at t ≈ 1e-10 on the 16 × 16 meshes. - U1, U2, P = u1(t, x, y), u2(t, x, y), p(t, x, y) - ψ = x^2 * (1 - x)^2 * y^2 * (1 - y)^2 - u1s, u2s, ps = expand_derivatives(Dy(ψ)), expand_derivatives(-Dx(ψ)), x^3 - y^3 - f1, f2 = expand_derivatives(-Δ(u1s) + Dx(ps)), expand_derivatives(-Δ(u2s) + Dy(ps)) - continuity = 0 ~ Dx(U1) + Dy(U2) - eqs = [Dt(U1) ~ Δ(U1) - Dx(P) + f1, Dt(U2) ~ Δ(U2) - Dy(P) + f2, continuity] - exact = map(e -> Symbolics.build_function(e, x, y; expression = Val(false)), (u1s, u2s, ps)) - shape = SHAPE[ct] + # starts from its exact values and is pinned on the one-facet piece "corner". FEMDiscretization's default + # algebraic_abstol = :auto leaves the algebraic rows out of the error control (abstol 1e8), without which + # DFBDF fails at t ≈ 1e-10 on the 16 × 16 meshes; no abstol is written here. errs = map((4, 8, 16)) do n - Ω = MeshDomain(corner_grid(ct, n)) - Γs = boundarypiece.(Ω, (:left, :right, :bottom, :top, :corner)) - bcs = [ - [u1(t, Γ) ~ 0 for Γ in Γs]; [u2(t, Γ) ~ 0 for Γ in Γs]; p(t, Γs[end]) ~ x^3 - y^3; - u1(0, x, y) ~ 0; u2(0, x, y) ~ 0; p(0, x, y) ~ x^3 - y^3 - ] - @named stokes = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, x, y], [U1, U2, P], []) - P2, P1 = Lagrange{shape, 2}(), Lagrange{shape, 1}() - prob = discretize(stokes, FEMDiscretization(Ω, t; spaces = Dict(u1 => P2, u2 => P2, p => P1), pairing = Dict(continuity => p))) - @test count(.!prob.differential_vars) > length(FiniteElementMethod.field_range(prob.problem_type.space, :p)) - abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars] - sol = solve(prob, EXACT_ROWS; abstol, reltol = 1.0e-8) + prob = stokes_problem(ct, n) + abstol = prob.kwargs[:abstol] + @test abstol == [d ? 1.0e-6 : 1.0e8 for d in prob.differential_vars] + space = prob.problem_type.space + pressure = setdiff(FiniteElementMethod.field_range(space, :p), FiniteElementMethod.prescribed_dofs(space)) + @test !isempty(pressure) && all(==(1.0e8), abstol[pressure]) + @test count(==(1.0e8), abstol) > length(pressure) + sol = solve(prob, EXACT_ROWS; reltol = 1.0e-8) @test SciMLBase.successful_retcode(sol) - [rms_error(sol, dv, (_, x_, y_) -> e(x_, y_)) for (dv, e) in zip((U1, U2, P), exact)] + [rms_error(sol, dv, (_, x_, y_) -> e(x_, y_)) for (dv, e) in zip((U1, U2, P), STOKES_EXACT)] end @test all(>(2.7), rates(getindex.(errs, 1))) && all(>(2.7), rates(getindex.(errs, 2))) @test all(>(1.7), rates(getindex.(errs, 3))) end + @testset "algebraic_abstol off with a hand-written vector, a scalar abstol, an override at solve" begin + n = 8 + # Hand-written vector (the recipe before the keyword) with the keyword off: the same solution. + prob = stokes_problem(Quadrilateral, n; algebraic_abstol = nothing) + @test !haskey(prob.kwargs, :abstol) + abstol = [d ? 1.0e-8 : 1.0e8 for d in prob.differential_vars] + manual = solve(prob, EXACT_ROWS; abstol, reltol = 1.0e-8) + @test SciMLBase.successful_retcode(manual) + # A scalar abstol given to discretize goes to the differential rows; the solve gives the same solution. + auto = solve(stokes_problem(Quadrilateral, n; abstol = 1.0e-8), EXACT_ROWS; reltol = 1.0e-8) + @test auto.t == manual.t && auto.original_sol.u[end] == manual.original_sol.u[end] + # Measured on this 8 × 8 Q2/Q1 mesh: 1.6e-5 for each velocity component, 2.7e-3 for the pressure. + errs = [rms_error(manual, dv, (_, x_, y_) -> e(x_, y_)) for (dv, e) in zip((U1, U2, P), STOKES_EXACT)] + @test all(errs .< [3.0e-5, 3.0e-5, 6.0e-3]) + # An abstol given to solve replaces the problem's vector. + prob = stokes_problem(Quadrilateral, n; algebraic_abstol = 1.0e4) + @test prob.kwargs[:abstol] == [d ? 1.0e-6 : 1.0e4 for d in prob.differential_vars] + @test SciMLBase.init(prob, EXACT_ROWS).opts.abstol == prob.kwargs[:abstol] + @test SciMLBase.init(prob, EXACT_ROWS; abstol = 1.0e-9).opts.abstol == 1.0e-9 + # An array abstol given to discretize is used as it is. + given = fill(1.0e-7, length(prob.u0)) + @test stokes_problem(Quadrilateral, n; abstol = given).kwargs[:abstol] === given + end + @testset "a field on a region reads NaN outside it" begin # u everywhere, w on the cells left of x = 1/2 only. w* = (1 + 2y)(1 + t) has zero flux through the # interface x = 1/2, where w gets the natural condition; both exact solutions are in P1. diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl new file mode 100644 index 00000000..950c1e24 --- /dev/null +++ b/test/shared/frontend_tests/nonlinear.jl @@ -0,0 +1,275 @@ +# Nonlinear terms through the front end (spec §8.1): PDESystem -> DAEProblem -> solve against manufactured +# solutions, the analytic Jacobian against finite differences, the Dirichlet rows, the remake policy and the +# nonlinear classes that stay rejected. +# +# Every manufactured solution is u* = (1 + x + 2y)(1 + t), which lies in the P1 space. Each source is written so +# that it cancels the nonlinear term pointwise at u*, so u* solves the discrete equations exactly whatever the +# quadrature, and the nodal error is at the level of the time-integration tolerance. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid +using Ferrite: Triangle +using LinearAlgebra: I, norm +using SciMLBase: remake +using NonlinearSolveFirstOrder: NewtonRaphson + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@parameters k +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +const U = u(t, x, y) +const tol = 1.0e-8 + +uexact(t_, x_, y_) = (1 + x_ + 2y_) * (1 + t_) +const ustar = (1 + x + 2y) * (1 + t) +const ic = u(0, x, y) ~ 1 + x + 2y +square() = MeshDomain(rectangle_grid(Triangle, (4, 4))) +sides(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +dirichlet(Ω, Γs = sides(Ω)) = [u(t, Γ) ~ ustar for Γ in Γs] + +function pdesystem(eqs, bcs, Ω; ps = []) + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], ps) + return pdesys +end + +# Central differences of the DAE residual in u, plus γ times those in du. +function fd_jacobian(prob, du, u0, γ, t0; ε = 1.0e-6) + n = length(u0) + J = zeros(n, n) + r₊, r₋ = zeros(n), zeros(n) + for j in 1:n + e = zeros(n) + e[j] = ε + prob.f(r₊, du, u0 + e, prob.p, t0) + prob.f(r₋, du, u0 - e, prob.p, t0) + J[:, j] .= (r₊ - r₋) / 2ε + prob.f(r₊, du + γ * e, u0, prob.p, t0) + prob.f(r₋, du - γ * e, u0, prob.p, t0) + J[:, j] .+= (r₊ - r₋) / 2ε + end + return J +end + +@testset verbose = true "nonlinear terms" begin + @testset "nonlinear diffusion −∇·((1 + u²)∇u)" begin + # ∇·((1 + u*²)∇u*) = 2u*|∇u*|² = 10u*(1 + t)²; the source is time dependent. + Ω = square() + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + (1 + x + 2y) - 10 * ustar * (1 + t)^2 + sol, prob = fem_solve([eq], [dirichlet(Ω); ic], Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + @test any(p -> nameof(p) === :Nop, ModelingToolkit.parameters(prob.f.sys)) + end + + @testset "nonlinear reaction −u²" begin + Ω = square() + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) - U^2 + (1 + x + 2y) + ustar^2 + sol, _ = fem_solve([eq], [dirichlet(Ω); ic], Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "algebraic field fixed by a nonlinear term in itself (index 1) keeps its abstol" begin + # 0 = v² − u − s with v* = 1 + x + 2y: v's linear block is zero, but v² determines v, so the system has + # index 1 and algebraic_abstol = :auto must not put v out of error control. + @variables v(..) + V = v(t, x, y) + Ω = square() + parabolic = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) + constraint = 0 ~ V^2 - U - ((1 + x + 2y)^2 - ustar) + bcs = [dirichlet(Ω); ic; v(0, x, y) ~ 1 + x + 2y] + sol, prob = fem_solve( + [parabolic, constraint], bcs, Ω, (x, y), t, [U, V]; pairing = Dict(constraint => v), + abstol = 1.0e-10, solve_kwargs = (; reltol = 1.0e-10) + ) + @test !any(prob.differential_vars[FiniteElementMethod.field_range(sol.disc_data.space, :v)]) + @test prob.kwargs[:abstol] === 1.0e-10 + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + @test nodal_error(sol, V, (_, x_, y_) -> 1 + x_ + 2y_) <= tol + @named pdesys = PDESystem([parabolic, constraint], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U, V], []) + @test !haskey(discretize(pdesys, FEMDiscretization(Ω, t; pairing = Dict(constraint => v))).kwargs, :abstol) + end + + @testset "Burgers-type convection u(∂ₓu + ∂ᵧu)" begin + # u*(∂ₓu* + ∂ᵧu*) = 3u*(1 + t). + Ω = square() + eq = Dt(U) + U * Dx(U) + U * Dy(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) + 3 * ustar * (1 + t) + sol, _ = fem_solve([eq], [dirichlet(Ω); ic], Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "nonlinear natural condition ∂ₙu = −u² + h" begin + # On the right side x = 1, ∂ₙu* = ∂ₓu* = 1 + t, so h = (1 + t) + u*². + Ω = square() + Γl, Γr, Γb, Γt = sides(Ω) + Dn = NormalDerivative(Γr) + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) + bcs = [dirichlet(Ω, (Γl, Γb, Γt)); Dn(u(t, Γr)) ~ -u(t, Γr)^2 + (1 + t) + ustar^2; ic] + sol, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "Jacobian against finite differences, Dirichlet rows" begin + Ω = square() + eq = Dt(U) + U * Dx(U) ~ Dx((1 + U^2) * Dx(U)) + Dy(Dy(U)) - U^2 + (1 + x + 2y) + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + n = length(prob.u0) + rng_u = [0.3 + 0.1 * sin(3i) for i in 1:n] + rng_du = [0.2 * cos(5i) for i in 1:n] + γ, t0 = 0.7, 0.4 + J = copy(prob.f.jac_prototype) + prob.f.jac(J, rng_du, rng_u, prob.p, γ, t0) + Jfd = fd_jacobian(prob, rng_du, rng_u, γ, t0) + @test norm(Matrix(J) - Jfd, Inf) <= 1.0e-7 * norm(Jfd, Inf) + # Prescribed rows are u_d − g_d(t): identity rows of the Jacobian, unaffected by N(u). + space = prob.problem_type.space + dofs = space.ch.prescribed_dofs + @test Matrix(J)[dofs, :] == Matrix(1.0 * I(n))[dofs, :] + r = zeros(n) + prob.f(r, rng_du, rng_u, prob.p, t0) + g = FiniteElementMethod.dirichlet_values!(zeros(length(dofs)), space, t0) + @test r[dofs] ≈ rng_u[dofs] - g atol = 1.0e-14 + end + + @testset "inconsistent Dirichlet u0 through the default initializer" begin + # BrownFullBasicInit's NewtonRaphson differentiates the residual with ForwardDiff, so the load and N(u) + # see Dual states; the time-dependent source exercises the load path too. + Ω = square() + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + (1 + x + 2y) - 10 * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + dofs = prob.problem_type.space.ch.prescribed_dofs + u0 = copy(prob.u0) + u0[dofs] .+= 0.5 + sol = solve(remake(prob; u0), EXACT_ROWS; abstol = 1.0e-10, reltol = 1.0e-10) + @test SciMLBase.successful_retcode(sol) + @test nodal_error(sol, U, uexact) <= tol + end + + @testset "remakes solved concurrently match serial solves" begin + # Every evaluation borrows its own copy of the nonlinear operator's buffers and values objects. + Ω = MeshDomain(rectangle_grid(Triangle, (16, 16))) + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + (1 + x + 2y) - 10 * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + probs = [remake(prob; u0 = s * prob.u0) for s in (1.0, 1.3, 0.7)] + final(q) = solve(q, EXACT_ROWS; abstol = 1.0e-8, reltol = 1.0e-8).original_sol.u[end] + serial = final.(probs) + @test serial[1] != serial[2] + concurrent = fetch.([Threads.@spawn final(q) for q in probs]) + @test concurrent == serial + Threads.nthreads() > 1 || @info "the remakes were solved on one thread, so this test cannot see a race; run with JULIA_NUM_THREADS > 1" + end + + @testset "states other than Float64 and Dual{Float64} are rejected" begin + Ω = square() + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) - 2 * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) + n = length(prob.u0) + Dual = FiniteElementMethod.ForwardDiff.Dual + states = ( + Float32.(prob.u0), big.(prob.u0), Dual{Nothing}.(Float32.(prob.u0), 1.0f0), + Dual{:outer}.(Dual{:inner}.(prob.u0, 1.0), Dual{:inner}(1.0, 0.0)), + ) + for u in states + T = eltype(u) + msg = "the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got $T" + @test_throws ArgumentError(msg) prob.f(zeros(T, n), zeros(T, n), u, prob.p, 0.0) + end + @test_throws ArgumentError("the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got Float32") prob.f( + zeros(Float32, n), zeros(Float32, n), Float32.(prob.u0), prob.p, 0.0 + ) + @test_throws ArgumentError("the nonlinear operator's Jacobian evaluates Float64 states; got Float32") prob.f.jac( + copy(prob.f.jac_prototype), zeros(n), Float32.(prob.u0), prob.p, 1.0, 0.0 + ) + # The supported states still evaluate: Float64 and a first-order Dual of Float64. + r = zeros(n) + prob.f(r, zeros(n), prob.u0, prob.p, 0.0) + rd = zeros(Dual{Nothing, Float64, 1}, n) + prob.f(rd, zeros(n), Dual{Nothing}.(prob.u0, 1.0), prob.p, 0.0) + @test FiniteElementMethod.ForwardDiff.value.(rd) ≈ r + end + + @testset "steady nonlinear diffusion, dirichlet = $dirichlet" for dirichlet in (:algebraic, :eliminate) + # ∇·((1 + u*²)∇u*) = 2u*|∇u*|² = 10u* for u* = 1 + x + 2y, which lies in the P1 space. + Ω = square() + us = 1 + x + 2y + eq = Dx((1 + u(x, y)^2) * Dx(u(x, y))) + Dy((1 + u(x, y)^2) * Dy(u(x, y))) ~ 10 * us + @named steady = PDESystem([eq], [u(Γ) ~ us for Γ in sides(Ω)], [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + prob = discretize(steady, FEMDiscretization(Ω; dirichlet)) + sol = solve(prob, NewtonRaphson(); abstol = 1.0e-12) + @test SciMLBase.successful_retcode(sol) + @test sol.stats.nsteps > 1 + pts = range(0.05, 0.95; length = 7) + @test maximum(abs(sol(px, py; dv = u(x, y)) - (1 + px + 2py)) for px in pts, py in pts) <= tol + end + + @testset "dirichlet = :eliminate keeps the nonlinear terms" begin + # u* = 1 + x + 2y is steady, so its Dirichlet data are constant in time; the sources cancel the diffusion + # (10u*) and reaction (u*²) terms at u*, so u stays u* only if N is evaluated. + Ω = square() + us = 1 + x + 2y + eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) - U^2 + us^2 - 10 * us + bcs = [[u(t, Γ) ~ us for Γ in sides(Ω)]; u(0, x, y) ~ us] + exact(t_, x_, y_) = 1 + x_ + 2y_ + sole, probe = fem_solve([eq], bcs, Ω, (x, y), t, [U]; dirichlet = :eliminate) + sola, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sole) + @test nodal_error(sole, U, exact) <= tol + @test maximum(abs, sole[U][end, :] - sola[U][end, :]) <= tol + @test any(p -> nameof(p) === :Nop, ModelingToolkit.parameters(probe.f.sys)) + # The analytic Jacobian on the free dofs against central differences of the reduced residual. + n = length(probe.u0) + rng_u = [1.0 + 0.1 * sin(3i) for i in 1:n] + rng_du = [0.2 * cos(5i) for i in 1:n] + J = copy(probe.f.jac_prototype) + probe.f.jac(J, rng_du, rng_u, probe.p, 0.7, 0.4) + Jfd = fd_jacobian(probe, rng_du, rng_u, 0.7, 0.4) + @test norm(Matrix(J) - Jfd, Inf) <= 1.0e-7 * norm(Jfd, Inf) + end + + @testset "a parameter changed by remake is rejected, not ignored" begin + # The operators, the nonlinear one included, hold the values they were assembled with (spec §8.3). + Ω = square() + eq = Dt(U) ~ Dx((1 + k * U^2) * Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) - 2k * ustar * (1 + t)^2 + prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω; ps = [k => 1.0]), FEMDiscretization(Ω, t)) + sol = solve(prob, EXACT_ROWS; abstol = 1.0e-10, reltol = 1.0e-10) + @test nodal_error(sol, U, uexact) <= tol + @test SciMLBase.successful_retcode(solve(remake(prob; p = [k => 1.0]), EXACT_ROWS)) + msg = "parameter k was 1.0 when the operators were assembled but is 3.0 in this problem; operators are not reassembled for new parameter values, so build a new problem with discretize(pdesys, disc)" + @test_throws ArgumentError(msg) solve(remake(prob; p = [k => 3.0]), EXACT_ROWS) + end +end + +@testset verbose = true "still-rejected nonlinear classes" begin + Ω = square() + lower(eqs, bcs = [dirichlet(Ω); ic]) = DAEProblem(pdesystem(eqs, bcs, Ω), FEMDiscretization(Ω, t)) + # Raised by PDEBase's strong-form analysis with the messages of spec Appendix A. + @test_throws ErrorException("state-dependent mass in Differential(t, 1)(u(t, x, y))*(u(t, x, y)^2) needs residual-form DAE") lower( + [(1 + U^2) * Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U))] + ) + @test_throws ErrorException("time derivative in Differential(t, 1)(u(t, x, y))^2 is not ∂ₜu × coefficient") lower( + [Dt(U)^2 ~ Dx(Dx(U)) + Dy(Dy(U))] + ) + @test_throws ErrorException( + "time derivative in -Differential(x, 1)(Differential(t, 1)(Differential(x, 1)(u(t, x, y)))) is not ∂ₜu × coefficient" + ) lower([Dt(U) ~ Dx(Dt(Dx(U))) + Dy(Dy(U))]) + @test_throws ErrorException("second derivative not in a divergence-compatible position: -sin(Differential(x, 2)(u(t, x, y)))") lower( + [Dt(U) ~ sin(Dx(Dx(U))) + Dy(Dy(U))] + ) + # The printed order of a product's factors differs between Julia versions, so these two match the + # message up to the term. + @test_throws "second derivative not in a divergence-compatible position: -" lower([Dt(U) ~ Dx(Dx(U)) * Dy(Dy(U))]) + @test_throws "second derivative not in a divergence-compatible position: -" lower([Dt(U) ~ Dx(U) * Dx(Dx(U)) + Dy(Dy(U))]) + Γl = first(sides(Ω)) + @test_throws ErrorException("Dirichlet data must be linear in one field: u(t, Γ_left)^2 ~ 1 on Γ_left") lower( + [Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U))], [[u(t, Γl)^2 ~ 1]; dirichlet(Ω, sides(Ω)[2:end]); ic] + ) + # The front end's own: a time-dependent coefficient in a linear operator would need reassembly. + @test_throws ArgumentError( + "time-dependent coefficients in the mass or stiffness operator are not supported: equation 1 has G₁*W₁ + G₁*T*W₁" + ) lower([Dt(U) ~ Dx((1 + t) * Dx(U))]) +end diff --git a/test/shared/frontend_tests/observed.jl b/test/shared/frontend_tests/observed.jl new file mode 100644 index 00000000..980bcd18 --- /dev/null +++ b/test/shared/frontend_tests/observed.jl @@ -0,0 +1,233 @@ +# End-to-end tests of observed expressions, `sol[expr]` and `sol(t, xs...; dv = expr)` (spec §7.8, +# O9): PDESystem -> DAEProblem -> solve, then each expression is checked against the same +# expression computed from the field arrays and against the exact solution. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, piece_nodes, normal_flux +using Ferrite: Triangle, Vec + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t + +@variables x y u(..) v(..) z(..) w +@parameters k +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) + +# u* = (1 + x + 2y)(1 + t) solves u_t = Δu + (1 + x + 2y) and is in the P1 space. +uexact(t_, x_, y_) = (1 + x_ + 2y_) * (1 + t_) +heat_eq = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + (1 + x + 2y) +pieces(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) +heat_bcs(Ω) = [[u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)]; u(0, x, y) ~ 1 + x + 2y] + +observed_error(ex, why) = ArgumentError("cannot evaluate the expression $ex on this solution: $why") + +@testset verbose = true "observed expressions" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + sol, _ = fem_solve([heat_eq], heat_bcs(Ω), Ω, (x, y), t, [u(t, x, y)]; ps = [k => 2.0]) + U = u(t, x, y) + T, X, Y = sol.t, permutedims(sol[x]), permutedims(sol[y]) + nt, nv = length(T), length(X) + + @testset "heat: sol[expr] against the field arrays and the exact solution" begin + @test size(sol[U^2 + k * x]) == (nt, nv) + @test sol[U^2 + k * x] ≈ sol[U] .^ 2 .+ 2 .* X atol = 1.0e-12 + @test maximum(abs, sol[U^2 + k * x] .- (uexact.(T, X, Y) .^ 2 .+ 2 .* X)) <= 1.0e-6 + @test sol[2U] == 2 .* sol[U] + @test sol[sin(t) * U] ≈ sin.(T) .* sol[U] atol = 1.0e-12 + # P1 reproduces the linear u*, so its projected gradient is (1 + t, 2(1 + t)). + @test sol[Dx(U) * U] ≈ sol[Dx(U)] .* sol[U] atol = 1.0e-12 + @test maximum(abs, sol[Dx(U) + Dy(U)] .- 3 .* (1 .+ T)) <= 1.0e-6 + end + + @testset "coordinate, time and parameter expressions" begin + @test sol[x^2 + y] == repeat(X .^ 2 .+ Y, nt) + @test sol[t * x + k] ≈ T .* X .+ 2 atol = 1.0e-14 + @test sol[2k] == fill(4.0, nt, nv) + end + + @testset "point evaluation sol(t, xs...; dv = expr)" begin + @test sol(0.5, 0.3, 0.2; dv = U^2 + k * x) ≈ sol(0.5, 0.3, 0.2; dv = U)^2 + 0.6 atol = 1.0e-12 + @test sol(0.5, 0.3, 0.2; dv = U^2 + k * x) ≈ uexact(0.5, 0.3, 0.2)^2 + 0.6 atol = 1.0e-6 + xs, ys = range(0, 1, length = 5), range(0, 1, length = 4) + vals = sol(T, xs, ys; dv = t * U + Dy(U)) + @test size(vals) == (nt, 5, 4) + @test vals ≈ [ + T[n] * sol(T[n], xs[i], ys[j]; dv = U) + sol(T[n], xs[i], ys[j]; dv = Dy(U)) + for n in 1:nt, i in 1:5, j in 1:4 + ] atol = 1.0e-12 + @test size(sol(0.5, xs, 0.2; dv = 2U)) == (5,) + # A coordinate-only expression is NaN outside the mesh, like a field value. + @test isequal(sol(0.5, [Vec(0.3, 0.2), Vec(2.0, 0.0)]; dv = x + y), [0.5, NaN]) + @test_throws DomainError sol(0.5, 2.0, 0.0; dv = 2x, outside = :error) + # Outside points are not evaluated, so an expression undefined there is NaN, not an error. + @test isnan(sol(0.5, -1.0, 0.5; dv = sqrt(x))) + @test isequal(sol(0.5, [0.25, -1.0], 0.5; dv = log(x) + U), [log(0.25) + sol(0.5, 0.25, 0.5; dv = U), NaN]) + # An integer-valued expression is returned as floating point so outside points hold NaN. + @test sol(0.5, 0.3, 0.5; dv = 2k) === 4.0 + @test isequal(sol(0.5, [0.3, 2.0], 0.5; dv = 2k), [4.0, NaN]) + @test isnan(sol(0.5, 2.0, 0.5; dv = 2k)) + Γ = first(pieces(Ω)) + nodes = piece_nodes(sol, Γ) + @test sol(0.5, Γ; dv = U + y) ≈ sol(0.5, Γ; dv = U) .+ sol[y][nodes] atol = 1.0e-14 + @test sol(T, Γ; dv = t * U) ≈ T .* sol[u(t, Γ)] atol = 1.0e-12 + err = errmsg(() -> sol(0.5, Γ; dv = Dx(U) + 1)) + @test occursin("traces of derivatives of u(t, x, y) are not supported", err) + end + + @testset "error paths" begin + dvs, ivs = "u(t, x, y)", "t, x, y" + unknown(s) = "$s is not a dependent variable, an independent variable or a parameter; the dependent variables are $dvs and the independent variables $ivs" + derivative(d) = "$d is not a first spatial derivative of a dependent variable, the only derivatives an expression accepts" + Γ = first(pieces(Ω)) + cases = [ + U * z(t, x, y) => unknown(z(t, x, y)), + 2w => unknown(w), + u(t, Γ)^2 => "it contains the trace $(u(t, Γ)); an expression is evaluated at every vertex, so write u(t, x, y) instead", + Dx(Dx(U)) + 1 => derivative(Dx(Dx(U))), + 2Dt(U) => derivative(Dt(U)), + u(t, 0, y) + 1 => "$(u(t, 0, y)) fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)", + Dy(u(t, 0, y)) + 1 => "$(u(t, 0, y)) fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)", + ] + for (ex, why) in cases + @test_throws observed_error(ex, why) sol[ex] + @test_throws observed_error(ex, why) sol(0.5, 0.3, 0.2; dv = ex) + end + # A derivative key that is not an expression keeps the key error. + @test occursin("first", errmsg(() -> sol[Dx(Dx(U))])) + end + + @testset "a dependent variable at fixed arguments is rejected on every path" begin + Γ = first(pieces(Ω)) + fixed(ex) = ArgumentError("$ex fixes arguments of u(t, x, y); write the dependent variable as u(t, x, y)") + for ex in (u(t, 0, y), u(t, x, 0.5), u(0, x, y)) + @test_throws fixed(ex) sol[ex] + @test_throws fixed(ex) sol(0.5, 0.3, 0.2; dv = ex) + @test_throws fixed(ex) sol(0.5, Γ; dv = ex) + @test_throws fixed(ex) sol[Dx(ex)] + @test_throws fixed(ex) sol(0.5, 0.3, 0.2; dv = Dx(ex)) + @test_throws fixed(ex) normal_flux(sol, ex, Γ) + end + # A trace must keep time and replace the coordinates by one piece. + @test_throws fixed(u(0, Γ)) sol[u(0, Γ)] + @test sol[u(t, Γ)] == sol[U][:, piece_nodes(sol, Γ)] + @test occursin("is not a key of this solution", errmsg(() -> sol[NormalDerivative(Γ)(u(0, Γ))])) + trace = ArgumentError("dv = $(u(t, Γ)) is a trace; evaluate a trace as sol(t, Γ; dv = u(t, x, y))") + @test_throws trace sol(0.5, 0.3, 0.2; dv = u(t, Γ)) + @test_throws trace sol(0.5, Γ; dv = u(t, Γ)) + @test occursin("is not a dependent variable of this solution", errmsg(() -> normal_flux(sol, u(t, Γ), Γ))) + end + + @testset "two fields" begin + # u_t = Δu + v with the algebraic row 0 = Δv; u* = (1 + x + 2y)(1 + t), v* = 1 + x + 2y. + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(t, x, y) + algebraic = 0 ~ Dx(Dx(v(t, x, y))) + Dy(Dy(v(t, x, y))) + bcs = [heat_bcs(Ω); [v(t, Γ) ~ 1 + x + 2y for Γ in pieces(Ω)]] + sol2, _ = fem_solve( + [parabolic, algebraic], bcs, Ω, (x, y), t, [u(t, x, y), v(t, x, y)]; pairing = Dict(algebraic => v) + ) + V = v(t, x, y) + @test sol2[U * V + V] ≈ sol2[U] .* sol2[V] .+ sol2[V] atol = 1.0e-12 + @test maximum(abs, sol2[U - V] .- sol2.t .* (1 .+ X .+ 2 .* Y)) <= 1.0e-6 + @test sol2(0.5, 0.3, 0.2; dv = U - V) ≈ 0.5 * 1.7 atol = 1.0e-6 + @test sol2(0.5, 0.3, 0.2; dv = U / V) ≈ sol2(0.5, 0.3, 0.2; dv = U) / sol2(0.5, 0.3, 0.2; dv = V) atol = 1.0e-12 + dvs2 = "u(t, x, y), v(t, x, y)" + @test_throws observed_error(U * z(t, x, y), "z(t, x, y) is not a dependent variable, an independent variable or a parameter; the dependent variables are $dvs2 and the independent variables t, x, y") sol2[U * z(t, x, y)] + end + + @testset "a PDESystem without parameters" begin + # Through the front end with ps = []; a PDESystem built without ps carries NullParameters, + # checked on the same solution rewrapped with such a system. + sol0, _ = fem_solve([heat_eq], heat_bcs(Ω), Ω, (x, y), t, [u(t, x, y)]) + @test sol0[U^2 + x] ≈ sol0[U] .^ 2 .+ X atol = 1.0e-12 + unknown_k = observed_error(U + k, "k is not a dependent variable, an independent variable or a parameter; the dependent variables are u(t, x, y) and the independent variables t, x, y") + @test_throws unknown_k sol0[U + k] + @named bare = PDESystem([heat_eq], heat_bcs(Ω), [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U]) + @test bare.ps isa SciMLBase.NullParameters + md = sol0.disc_data + md0 = FiniteElementMethod.FEMMetadata(md.space, md.time, md.x̄, md.fields, md.pieces, bare; u0 = md.u0) + rewrapped = SciMLBase.PDETimeSeriesSolution(sol0.original_sol, md0) + @test rewrapped[U^2 + x] == sol0[U^2 + x] + @test_throws unknown_k rewrapped[U + k] + @test_throws unknown_k rewrapped(0.5, 0.3, 0.2; dv = U + k) + end + + @testset "time-last fields" begin + UL = u(x, y, t) + eq = Dt(UL) ~ Dx(Dx(UL)) + Dy(Dy(UL)) + (1 + x + 2y) + bcs = [[u(Γ, t) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)]; u(x, y, 0) ~ 1 + x + 2y] + soll, _ = fem_solve([eq], bcs, Ω, (x, y), t, [UL]; ps = [k => 2.0]) + Tl, Xc, Yc = permutedims(soll.t), soll[x], soll[y] + exact = uexact.(Tl, Xc, Yc) + # Arrays keep the orientation of sol[u(x, y, t)], nvertices × nt. + @test size(soll[UL^2 + k * x]) == (nv, length(soll.t)) + @test soll[UL^2 + k * x] ≈ soll[UL] .^ 2 .+ 2 .* Xc atol = 1.0e-12 + @test maximum(abs, soll[UL^2 + k * x] .- (exact .^ 2 .+ 2 .* Xc)) <= 1.0e-6 + @test soll[t * UL] ≈ Tl .* soll[UL] atol = 1.0e-12 + @test soll[x + y] == repeat(Xc .+ Yc, 1, length(soll.t)) + @test soll[Dx(UL) + UL] ≈ soll[Dx(UL)] .+ soll[UL] atol = 1.0e-12 + # Calls take the time last. + @test soll(0.3, 0.2, 0.5; dv = UL^2) ≈ uexact(0.5, 0.3, 0.2)^2 atol = 1.0e-6 + xs, ys, ts = range(0, 1, length = 5), range(0, 1, length = 4), [0.2, 0.5, 0.9] + vals = soll(xs, ys, ts; dv = t * UL) + @test size(vals) == (5, 4, 3) + @test vals ≈ [ts[n] * soll(xs[i], ys[j], ts[n]; dv = UL) for i in 1:5, j in 1:4, n in 1:3] atol = 1.0e-12 + @test maximum(abs, vals .- [ts[n] * uexact(ts[n], xs[i], ys[j]) for i in 1:5, j in 1:4, n in 1:3]) <= 1.0e-6 + Γ = first(pieces(Ω)) + nodes = piece_nodes(soll, Γ) + @test size(soll(Γ, ts; dv = UL + y)) == (length(nodes), 3) + @test soll(Γ, ts; dv = UL + y) ≈ soll(Γ, ts; dv = UL) .+ Yc[nodes] atol = 1.0e-12 + @test soll[u(Γ, t)] == soll[UL][nodes, :] + # Fixed arguments and malformed traces in time-last form. + fixed(ex) = ArgumentError("$ex fixes arguments of u(x, y, t); write the dependent variable as u(x, y, t)") + for ex in (u(0, y, t), u(x, y, 0)) + @test_throws fixed(ex) soll[ex] + @test_throws fixed(ex) soll(0.3, 0.2, 0.5; dv = ex) + @test_throws fixed(ex) soll[Dx(ex)] + @test_throws fixed(ex) normal_flux(soll, ex, Γ) + @test_throws observed_error(ex + 1, "$ex fixes arguments of u(x, y, t); write the dependent variable as u(x, y, t)") soll[ex + 1] + end + @test_throws fixed(u(Γ, 0)) soll[u(Γ, 0)] + @test_throws fixed(u(t, Γ)) soll[u(t, Γ)] + @test_throws ArgumentError("dv = $(u(Γ, t)) is a trace; evaluate a trace as sol(Γ, t; dv = u(x, y, t))") soll(0.3, 0.2, 0.5; dv = u(Γ, t)) + end + + @testset "fields with different time positions" begin + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(x, y, t) + algebraic = 0 ~ Dx(Dx(v(x, y, t))) + Dy(Dy(v(x, y, t))) + bcs = [heat_bcs(Ω); [v(Γ, t) ~ 1 + x + 2y for Γ in pieces(Ω)]] + solm, _ = fem_solve( + [parabolic, algebraic], bcs, Ω, (x, y), t, [u(t, x, y), v(x, y, t)]; pairing = Dict(algebraic => v) + ) + VL = v(x, y, t) + # One field per expression: its own orientation. + @test solm[2U] == 2 .* solm[U] + @test solm[VL * x] ≈ solm[VL] .* solm[x] atol = 1.0e-12 + @test solm(0.3, 0.2, 0.5; dv = 2VL) ≈ 2 * (1 + 0.3 + 0.4) atol = 1.0e-6 + # Mixed time positions have no orientation, documented as an error. + mixed = "its dependent variables (all those of the system when it names none) put time in different argument positions; evaluate the time-first and the time-last parts separately" + @test_throws observed_error(U + VL, mixed) solm[U + VL] + @test_throws observed_error(U + VL, mixed) solm(0.5, 0.3, 0.2; dv = U + VL) + @test_throws observed_error(2x, mixed) solm[2x] + end + + @testset "evaluation is batched at 10^4 vertices" begin + big = MeshDomain(rectangle_grid(Triangle, (99, 99))) + bsol, _ = fem_solve([heat_eq], heat_bcs(big), big, (x, y), t, [u(t, x, y)]; ps = [k => 2.0], saveat = 0.5) + @test size(bsol[U]) == (3, 10_000) + E = U^2 + k * x * U + Dx(U) + @test maximum(abs, bsol[E] .- (bsol[U] .^ 2 .+ 2 .* permutedims(bsol[x]) .* bsol[U] .+ bsol[Dx(U)])) <= 1.0e-10 + # Past the symbolic compile, which does not depend on the mesh, the cost is the projection + # of Dx(U) and a few output-sized arrays; a substitution per vertex would allocate far more. + bsol[E] + bsol[Dx(U)] + compile = @allocated FiniteElementMethod._compile_observed(bsol, E) + @test @allocated(bsol[E]) < compile + @allocated(bsol[Dx(U)]) + 4 * sizeof(bsol[U]) + xs = range(0, 1, length = 100) + F = U^2 + k * x * U + bsol(bsol.t, xs, xs; dv = F) + bsol(bsol.t, xs, xs; dv = U) + compile = @allocated FiniteElementMethod._compile_observed(bsol, F) + @test @allocated(bsol(bsol.t, xs, xs; dv = F)) < compile + 4 * @allocated(bsol(bsol.t, xs, xs; dv = U)) + @info "observed evaluation at 10^4 vertices" compile_bytes = compile vertex_bytes = @allocated(bsol[F]) seconds = @elapsed(bsol[F]) + end +end diff --git a/test/shared/frontend_tests/operators.jl b/test/shared/frontend_tests/operators.jl new file mode 100644 index 00000000..41332bcc --- /dev/null +++ b/test/shared/frontend_tests/operators.jl @@ -0,0 +1,91 @@ +# The data API for callers that build their own system around the operators: `operators`, +# `facet_dofs`, `dof_coordinates` and `cell_dofs`. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, facet_dofs, dof_coordinates, cell_dofs, prescribed_dofs +using Ferrite: Quadrilateral, Triangle + +include(joinpath(@__DIR__, "..", "frontend.jl")) + +using ModelingToolkit: t_nounits as t +using SparseArrays: nnz + +@variables x y u(..) +const Dt, Dx, Dy = Differential(t), Differential(x), Differential(y) +heat = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + +function heat_system(Ω, bcs; eq = heat) + @named pdesys = PDESystem([eq], [bcs; u(0, x, y) ~ x], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [u(t, x, y)], []) + return pdesys +end + +@testset verbose = true "operators" begin + @testset "Neumann heat on a rectangle, P1 quadrilaterals" begin + Ω = MeshDomain(rectangle_grid(Quadrilateral, (4, 3); hi = (2.0, 1.0))) + ops = @test_logs (:warn,) match_mode = :any FiniteElementMethod.operators(heat_system(Ω, Equation[]), FEMDiscretization(Ω, t)) + n = 5 * 4 + @test size(ops.M) == size(ops.K) == (n, n) + @test ops.fields == [:u => 1:n] + @test sum(ops.M) ≈ 2.0 # ∫ 1 dΩ + @test maximum(abs, ops.K * ones(n)) < 1.0e-12 # constants are in the kernel + @test ops.M ≈ ops.M' && ops.K ≈ ops.K' + @test all(ops.differential_vars) + @test iszero(ops.F) && isempty(ops.prescribed) + X = dof_coordinates(ops.metadata) + @test ops.u0 ≈ X[1, :] + end + + @testset "Dirichlet rows are left unconstrained" begin + Ω = MeshDomain(rectangle_grid(Quadrilateral, (4, 3))) + left, right = boundarypiece.(Ω, (:left, :right)) + pdesys = heat_system(Ω, [u(t, left) ~ 2.0, u(t, right) ~ 0.0]) + disc = FEMDiscretization(Ω, t) + ops = FiniteElementMethod.operators(pdesys, disc) + md = ops.metadata + @test sort(ops.prescribed) == sort([facet_dofs(md, left, u); facet_dofs(md, right, u)]) + @test maximum(abs, ops.K * ones(size(ops.K, 1))) < 1.0e-12 + @test ops.u0[facet_dofs(md, left, u)] ≈ fill(2.0, 4) + # Off the Dirichlet rows the operators are those of the DAEProblem. + prob = DAEProblem(pdesys, disc) + free = setdiff(1:size(ops.K, 1), ops.prescribed) + res = zeros(length(prob.u0)) + du = randn(length(prob.u0)) + prob.f(res, du, prob.u0, prob.p, 0.0) + @test res[free] ≈ (ops.M * du + ops.K * prob.u0 - ops.F)[free] + end + + @testset "facet_dofs, dof_coordinates and cell_dofs" begin + Ω = MeshDomain(rectangle_grid(Triangle, (4, 3))) + left, top = boundarypiece.(Ω, (:left, :top)) + for (order, nleft, ntop) in ((1, 4, 5), (2, 7, 9)) + ops = @test_logs (:warn,) match_mode = :any FiniteElementMethod.operators( + heat_system(Ω, Equation[]), FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, order}())) + ) + md = ops.metadata + X = dof_coordinates(md) + @test size(X) == (2, size(ops.K, 1)) + dl = facet_dofs(md, left, u) + @test length(dl) == nleft && issorted(dl) + @test all(iszero, X[1, dl]) + @test facet_dofs(md, "top", :u) == facet_dofs(md, top, u) + @test length(facet_dofs(md, top, u(t, x, y))) == ntop + @test all(≈(1.0), X[2, facet_dofs(md, :top, u)]) + C = cell_dofs(md, u) + @test size(C) == (order == 1 ? 3 : 6, 4 * 3 * 2) + @test sort!(unique(vec(C))) == 1:size(ops.K, 1) + end + end + + @testset "rejections" begin + Ω = MeshDomain(rectangle_grid(Quadrilateral, (2, 2))) + left = boundarypiece(Ω, :left) + msg(f) = errmsg(f) + nonlinear = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) - u(t, x, y)^3 + @test occursin("nonlinear", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]; eq = nonlinear), FEMDiscretization(Ω, t)))) + @test occursin("constant in time", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ sin(t)]), FEMDiscretization(Ω, t)))) + sourced = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + t + @test occursin("time-independent", msg(() -> FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]; eq = sourced), FEMDiscretization(Ω, t)))) + ops = FiniteElementMethod.operators(heat_system(Ω, [u(t, left) ~ 0]), FEMDiscretization(Ω, t)) + @test occursin("not a facet set", msg(() -> facet_dofs(ops.metadata, "nope", u))) + @test occursin("not a field", msg(() -> facet_dofs(ops.metadata, left, :v))) + end +end diff --git a/test/shared/frontend_tests/steady.jl b/test/shared/frontend_tests/steady.jl new file mode 100644 index 00000000..bb25e52d --- /dev/null +++ b/test/shared/frontend_tests/steady.jl @@ -0,0 +1,155 @@ +# End-to-end tests of steady problems: a PDESystem with no time variable -> NonlinearProblem -> +# solve -> PDENoTimeSolution, checked against manufactured solutions. +using Test +using FiniteElementMethod: FiniteElementMethod, rectangle_grid, field_range +using Ferrite: Ferrite, Triangle +using NonlinearSolveFirstOrder: NewtonRaphson + +include(joinpath(@__DIR__, "..", "frontend.jl")) +include(joinpath(@__DIR__, "..", "lshape.jl")) + +@variables x y u(..) v(..) +const Dx, Dy = Differential(x), Differential(y) + +sides(Ω) = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + +function steady_solve(eqs, bcs, Ω, dvs; disc_kwargs...) + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω], [x, y], dvs, []) + prob = discretize(pdesys, FEMDiscretization(Ω; disc_kwargs...)) + return solve(prob, NewtonRaphson(); abstol = 1.0e-12), prob +end + +"Largest error of `dv` against `exact(x, y)` at a lattice of points off the mesh nodes." +function point_error(sol, dv, exact) + pts = range(0.0123, 0.9877; length = 41) + return maximum(abs(sol(px, py; dv) - exact(px, py)) for px in pts, py in pts) +end + +ustar(x_, y_) = sin(pi * x_) * exp(y_) + +# Δu = Δu* on the unit square, u = u* on every side. +function poisson_error(n, order) + Ω = MeshDomain(rectangle_grid(Triangle, (n, n))) + eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ (1 - pi^2) * ustar(x, y) + sol, _ = steady_solve( + [eq], [u(Γ) ~ ustar(x, y) for Γ in sides(Ω)], Ω, [u(x, y)]; + spaces = Dict(u => Lagrange{RefTriangle, order}()) + ) + @test SciMLBase.successful_retcode(sol) + @test sol.stats.nsteps == 1 + return point_error(sol, u(x, y), ustar) +end + +@testset verbose = true "steady" begin + @testset "Poisson on a rectangle grid converges at rate $(order + 1) for P$order" for order in (1, 2) + e1, e2 = poisson_error.((8, 16), order) + @test log2(e1 / e2) > order + 0.8 + end + + @testset "PDESystem without parameters" begin + # Leaving out `ps` gives the system `NullParameters()`, which means no parameters. + # u* = 1 + x² + 2y² + xy has Δu* = 6 and is exact in P2. + u_exact(x_, y_) = 1 + x_^2 + 2y_^2 + x_ * y_ + Ω = MeshDomain(rectangle_grid(Triangle, (3, 3))) + bcs = [u(Γ) ~ u_exact(x, y) for Γ in sides(Ω)] + @named pdesys = PDESystem([Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 6], bcs, [(x, y) ∈ Ω], [x, y], [u(x, y)]) + @test pdesys.ps isa SciMLBase.NullParameters + disc = FEMDiscretization(Ω; spaces = Dict(u => Lagrange{RefTriangle, 2}())) + sol = solve(discretize(pdesys, disc), NewtonRaphson(); abstol = 1.0e-12) + @test SciMLBase.successful_retcode(sol) + @test maximum(abs, sol[u(x, y)] - u_exact.(sol[x], sol[y])) <= 1.0e-10 + end + + @testset "L-shape with Dirichlet, Neumann and Robin pieces" begin + # u* = 1 + x + 2y + xy + x², Δu* = 2, is exact in P2 on straight triangles. ∇u* = (1 + y + 2x, 2 + x). + u_exact(x_, y_) = 1 + x_ + 2y_ + x_ * y_ + x_^2 + Ω = MeshDomain(lshape_grid(; h = 0.5)) + Γi, Γw, Γo = boundarypiece.(Ω, (:inlet, :wall, :outlet)) + # The wall is y = 0 (outward normal -y), the edges y = 1 for x > 1 and y = 2 (normal +y), and + # x = 1 for 1 < y < 2 (normal +x); facet quadrature points lie strictly inside the edges. + wall_flux = ifelse(y < 0.5, -(2 + x), ifelse(x > 1 + 1.0e-8, 2 + x, ifelse(y > 2 - 1.0e-8, 2 + x, 1 + 2x + y))) + bcs = [ + u(Γi) ~ 1 + 2y, + NormalDerivative(Γw)(u(Γw)) ~ wall_flux, + NormalDerivative(Γo)(u(Γo)) + u(Γo) ~ (5 + y) + (7 + 4y), + ] + sol, _ = steady_solve( + [Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 2], bcs, Ω, [u(x, y)]; + spaces = Dict(u => Lagrange{RefTriangle, 2}()) + ) + @test SciMLBase.successful_retcode(sol) + @test maximum(abs, sol[u(x, y)] - u_exact.(sol[x], sol[y])) <= 1.0e-10 + @test abs(sol(0.5, 1.5; dv = u(x, y)) - u_exact(0.5, 1.5)) <= 1.0e-10 + end + + @testset "two fields, paired $(how)" for how in ("by declared order", "explicitly") + # Δu + v = 5 + x and Δv = 0 with u* = x² + y², v* = 1 + x, both exact in P2. + Ω = MeshDomain(rectangle_grid(Triangle, (3, 3))) + u_eq = Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) + v(x, y) ~ 5 + x + v_eq = Dx(Dx(v(x, y))) + Dy(Dy(v(x, y))) ~ 0 + bcs = [[u(Γ) ~ x^2 + y^2 for Γ in sides(Ω)]; [v(Γ) ~ 1 + x for Γ in sides(Ω)]] + P2 = Lagrange{RefTriangle, 2}() + kw = how == "explicitly" ? (; pairing = Dict(v_eq => v)) : (;) + eqs = how == "explicitly" ? [v_eq, u_eq] : [u_eq, v_eq] + sol, prob = steady_solve(eqs, bcs, Ω, [u(x, y), v(x, y)]; spaces = Dict(u => P2, v => P2), kw...) + @test SciMLBase.successful_retcode(sol) + @test maximum(abs, sol[u(x, y)] - (sol[x] .^ 2 + sol[y] .^ 2)) <= 1.0e-10 + @test maximum(abs, sol[v(x, y)] - (1 .+ sol[x])) <= 1.0e-10 + @test length(sol(0.4, 0.7)) == 2 + @test [f.name for f in prob.problem_type.fields] == [:u, :v] + end + + @testset "steady solution interface" begin + # u* = 1 + x + 2y is exact in P1: harmonic, with u = u* on the left and right and + # ∂u/∂n = ±2 on the bottom and top. + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = sides(Ω) + bcs = [u(Γl) ~ 1 + 2y, u(Γr) ~ 2 + 2y, NormalDerivative(Γb)(u(Γb)) ~ -2, NormalDerivative(Γt)(u(Γt)) ~ 2] + @named pdesys = PDESystem([Dx(Dx(u(x, y))) + Dy(Dy(u(x, y))) ~ 0], bcs, [(x, y) ∈ Ω], [x, y], [u(x, y)], []) + prob = discretize(pdesys, FEMDiscretization(Ω; abstol = 1.0e-12)) + @test prob isa SciMLBase.NonlinearProblem + @test prob.kwargs[:abstol] == 1.0e-12 + @test SciMLBase.NonlinearProblem(pdesys, FEMDiscretization(Ω)).u0 == prob.u0 + # The initial guess is zero except on the Dirichlet dofs, which hold the data. + space = prob.problem_type.space + pd = space.ch.prescribed_dofs + @test all(iszero, prob.u0[setdiff(1:length(prob.u0), pd)]) + coords = FiniteElementMethod._dof_coordinates(space) + @test prob.u0[pd] ≈ [1 + c[1] + 2c[2] for c in coords[pd]] + @test sprint(show, prob.problem_type) == "FEMMetadata(fields = [u], ndofs = 25, hasTime = false)" + + sol = solve(prob, NewtonRaphson()) + U = u(x, y) + @test sol isa SciMLBase.PDENoTimeSolution + @test sol.disc_data isa FEMMetadata{Val(false)} + nv = Ferrite.getnnodes(Ω.mesh) + @test sol[U] isa Vector{Float64} && length(sol[U]) == nv + @test sol[U] ≈ 1 .+ sol[x] .+ 2 .* sol[y] atol = 1.0e-12 + @test sol(0.3, 0.6; dv = U) ≈ 2.5 atol = 1.0e-12 + @test sol([0.3, 2.0], 0.6; dv = U)[1] ≈ 2.5 atol = 1.0e-12 + @test isnan(sol([0.3, 2.0], 0.6; dv = U)[2]) + @test sol[u(Γr)] ≈ 2 .+ 2 .* sol[y][piece_nodes(sol, Γr)] atol = 1.0e-12 + @test sol(Γl; dv = U) ≈ 1 .+ 2 .* sol[y][piece_nodes(sol, Γl)] atol = 1.0e-12 + @test sol[Dx(U)] ≈ ones(nv) atol = 1.0e-10 + @test sol(0.3, 0.6; dv = Dy(U)) ≈ 2 atol = 1.0e-10 + @test normal_flux(sol, U, Γt) ≈ fill(2.0, 4) atol = 1.0e-10 + @test normal_flux(sol, U, Γl) ≈ fill(-1.0, 4) atol = 1.0e-10 + mktempdir() do dir + path = write_vtk(sol, joinpath(dir, "poisson")) + @test path == joinpath(dir, "poisson.vtu") + @test isfile(path) && occursin(" (1 + x_ + 2y_) * (1 + t_)) <= tol + @test nodal_error_last(sol_l, ul, (t_, x_, y_) -> (1 + x_ + 2y_) * (1 + t_)) <= tol + + # Arrays: the time axis is last. + @test size(sol_l[ul]) == (nv, nt) + @test sol_l[ul] ≈ permutedims(sol_f[uf]) atol = 1.0e-12 + @test sol_l[ul, 3, :] == sol_l[ul][3, :] + nΓ = length(piece_nodes(sol_l, Γl)) + @test size(sol_l[u(Γl, t)]) == (nΓ, nt) + @test sol_l[u(Γl, t)] ≈ permutedims(sol_f[u(t, Γl)]) atol = 1.0e-12 + @test sol_l[Dx(ul)] ≈ permutedims(sol_f[Dx(uf)]) atol = 1.0e-10 + @test size(sol_l[Dx(ul)]) == (nv, nt) + Dn = NormalDerivative(Γr) + @test sol_l[Dn(u(Γr, t))] ≈ permutedims(sol_f[Dn(u(t, Γr))]) atol = 1.0e-10 + @test normal_flux(sol_l, ul, Γr) == sol_l[Dn(u(Γr, t))] + @test size(normal_flux(sol_l, ul, Γr), 2) == nt + + # Calls: the time argument is last. + @test sol_l(0.3, 0.4, 0.55; dv = ul) ≈ sol_f(0.55, 0.3, 0.4; dv = uf) atol = 1.0e-12 + @test sol_l(0.3, 0.4, 0.55; dv = ul) ≈ (1 + 0.3 + 0.8) * 1.55 atol = 1.0e-6 + @test sol_l(0.3, 0.4, 0.55) ≈ [sol_l(0.3, 0.4, 0.55; dv = ul)] + xs, ys, ts = range(0, 1, length = 5), range(0, 1, length = 4), [0.2, 0.5, 0.9] + @test size(sol_l(xs, ys, ts; dv = ul)) == (5, 4, 3) + @test sol_l(xs, ys, ts; dv = ul) ≈ permutedims(sol_f(ts, xs, ys; dv = uf), (2, 3, 1)) atol = 1.0e-12 + @test sol_l(xs, 0.3, ts; dv = ul) ≈ permutedims(sol_f(ts, xs, 0.3; dv = uf)) atol = 1.0e-12 + @test size(sol_l(xs, ys, 0.5; dv = ul)) == (5, 4) + @test sol_l(Γl, 0.5; dv = ul) ≈ sol_f(0.5, Γl; dv = uf) atol = 1.0e-12 + @test size(sol_l(Γl, ts; dv = ul)) == (nΓ, 3) + @test sol_l(Γl, ts; dv = ul) ≈ permutedims(sol_f(ts, Γl; dv = uf)) atol = 1.0e-12 + pts = [Vec(0.2, 0.3), Vec(0.7, 0.1)] + @test sol_l(pts, ts; dv = ul) ≈ permutedims(sol_f(ts, pts; dv = uf)) atol = 1.0e-12 + @test sol_l(0.3, 0.4, 0.55; dv = Dx(ul)) ≈ sol_f(0.55, 0.3, 0.4; dv = Dx(uf)) atol = 1.0e-12 + @test_throws ArgumentError("the last argument must be a time or a vector of times, as u(x, y, t) declares; got $(repr(Γl))") sol_l( + 0.5, Γl; dv = ul + ) + @test_throws ArgumentError("the first argument must be a time or a vector of times, as u(t, x, y) declares; got $(repr(Γl))") sol_f( + Γl, 0.5; dv = uf + ) + @test_throws ArgumentError("the last argument must be a time or a vector of times, as u(x, y, t) declares; got nothing") sol_l(; dv = ul) + end + + @testset "manufactured solution with time-dependent source, Dirichlet and Neumann data" begin + # u* = (1 + x + 2y)(1 + t²) needs the source 2t(1 + x + 2y), reassembled at every t. + u_exact(t_, x_, y_) = (1 + x_ + 2y_) * (1 + t_^2) + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + Γl, Γr, Γb, Γt = pieces(Ω) + U = u(x, y, t) + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + 2t * (1 + x + 2y) + bcs = [ + u(Γl, t) ~ (1 + 2y) * (1 + t^2), + u(Γb, t) ~ (1 + x) * (1 + t^2), + NormalDerivative(Γr)(u(Γr, t)) ~ 1 + t^2, + NormalDerivative(Γt)(u(Γt, t)) ~ 2 * (1 + t^2), + u(x, y, 0) ~ 1 + x + 2y, + ] + sol, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test SciMLBase.successful_retcode(sol) + @test nodal_error_last(sol, U, u_exact) <= 1.0e-6 + @test sol[u(Γl, t)] ≈ [u_exact(τ, 0.0, sol[y][i]) for i in piece_nodes(sol, Γl), τ in sol.t] atol = 1.0e-10 + end + + @testset "Gmsh L-shape" begin + u_exact(t_, x_, y_) = (1 + x_) * (1 + t_) + Ω = MeshDomain(lshape_grid(; h = 0.5)) + Γi, Γw, Γo = boundarypiece.(Ω, (:inlet, :wall, :outlet)) + U = u(x, y, t) + eq = Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x) + bcs = [u(Γi, t) ~ 1 + t, u(Γw, t) ~ (1 + x) * (1 + t), NormalDerivative(Γo)(u(Γo, t)) ~ 1 + t, u(x, y, 0) ~ 1 + x] + sol, _ = fem_solve([eq], bcs, Ω, (x, y), t, [U]) + @test nodal_error_last(sol, U, u_exact) <= tol + @test size(sol[U]) == (length(sol[x]), length(sol.t)) + @test sol[u(Γi, t)] ≈ repeat(permutedims(1 .+ sol.t), length(piece_nodes(sol, Γi))) atol = tol + @test isnan(sol(1.5, 1.5, 0.5; dv = U)) + @test sol(0.5, 1.5, [0.0, 1.0]; dv = U) ≈ u_exact.([0.0, 1.0], 0.5, 1.5) atol = tol + end + + @testset "fields with different time positions" begin + # u_t = Δu + v with the algebraic row 0 = Δv; u(t, x, y) is time-first, v(x, y, t) time-last. + Ω = MeshDomain(rectangle_grid(Triangle, (4, 4))) + parabolic = Dt(u(t, x, y)) ~ Dx(Dx(u(t, x, y))) + Dy(Dy(u(t, x, y))) + v(x, y, t) + algebraic = 0 ~ Dx(Dx(v(x, y, t))) + Dy(Dy(v(x, y, t))) + bcs = [ + [u(t, Γ) ~ (1 + x + 2y) * (1 + t) for Γ in pieces(Ω)]; + [v(Γ, t) ~ 1 + x + 2y for Γ in pieces(Ω)]; + u(0, x, y) ~ 1 + x + 2y + ] + sol, _ = fem_solve( + [parabolic, algebraic], bcs, Ω, (x, y), t, [u(t, x, y), v(x, y, t)]; pairing = Dict(algebraic => v) + ) + @test nodal_error(sol, u(t, x, y), (t_, x_, y_) -> (1 + x_ + 2y_) * (1 + t_)) <= tol + @test nodal_error_last(sol, v(x, y, t), (t_, x_, y_) -> 1 + x_ + 2y_) <= tol + nt, nv = length(sol.t), length(sol[x]) + @test size(sol[u(t, x, y)]) == (nt, nv) && size(sol[v(x, y, t)]) == (nv, nt) + @test sol(0.3, 0.4, 0.5; dv = v(x, y, t)) ≈ 1 + 0.3 + 0.8 atol = tol + @test sol(0.5, 0.3, 0.4; dv = u(t, x, y)) ≈ (1 + 0.3 + 0.8) * 1.5 atol = tol + @test_throws ArgumentError( + "the dependent variables $(sol.dvs) put time in different argument positions; pass dv to choose one" + ) sol(0.5, 0.3, 0.4) + end +end diff --git a/test/test_groups.toml b/test/test_groups.toml index 9de6ee32..e464a755 100644 --- a/test/test_groups.toml +++ b/test/test_groups.toml @@ -42,3 +42,6 @@ versions = ["lts", "1"] [Library] in_all = false versions = ["lts", "1"] + +[NavierStokes] +versions = ["lts", "1", "pre"]