diff --git a/docs/Project.toml b/docs/Project.toml index 63ef2931..a9d72faa 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -9,8 +9,10 @@ Gmsh = "705231aa-382f-11e9-3f0c-b7cb4346fdeb" LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae" ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" +PDEBase = "a7812802-0625-4b9e-961c-d332478797e5" Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" SciMLBase = "0bca4576-84f4-4d90-8ffe-ffa030f20462" +Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" TOML = "fa267f1f-6049-4f14-aa54-33bafae1ed76" [compat] @@ -24,6 +26,8 @@ Gmsh = "0.3" LinearSolve = "5" ModelingToolkit = "11" OrdinaryDiffEqBDF = "2.4" +PDEBase = "0.1.40" Printf = "1" SciMLBase = "3" +Symbolics = "7" TOML = "1" diff --git a/docs/pages.jl b/docs/pages.jl index 9a946c1e..ed7f434c 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -6,6 +6,7 @@ pages = [ "Boundary conditions and limitations" => "boundary_conditions.md", "Discretization" => "discretization.md", "Navier–Stokes example" => "navier_stokes.md", + "Axisymmetric swirl: a collapsing core" => "axisymmetric_swirl.md", "Extension contract" => "extension_contract.md", "API" => "api.md", ] diff --git a/docs/src/assets/axisym_core.png b/docs/src/assets/axisym_core.png new file mode 100644 index 00000000..7240c9d5 Binary files /dev/null and b/docs/src/assets/axisym_core.png differ diff --git a/docs/src/assets/axisym_mesh.png b/docs/src/assets/axisym_mesh.png new file mode 100644 index 00000000..d5e235fd Binary files /dev/null and b/docs/src/assets/axisym_mesh.png differ diff --git a/docs/src/assets/axisym_swirl.fnv1a b/docs/src/assets/axisym_swirl.fnv1a new file mode 100644 index 00000000..bef79c90 --- /dev/null +++ b/docs/src/assets/axisym_swirl.fnv1a @@ -0,0 +1 @@ +e369978afda92609 diff --git a/docs/src/assets/axisym_swirl.gif b/docs/src/assets/axisym_swirl.gif new file mode 100644 index 00000000..a5df6a47 Binary files /dev/null and b/docs/src/assets/axisym_swirl.gif differ diff --git a/docs/src/assets/axisym_swirl_animation.fnv1a b/docs/src/assets/axisym_swirl_animation.fnv1a new file mode 100644 index 00000000..8a355a95 --- /dev/null +++ b/docs/src/assets/axisym_swirl_animation.fnv1a @@ -0,0 +1 @@ +3bb1f417d3ec6ef4 diff --git a/docs/src/axisymmetric_swirl.md b/docs/src/axisymmetric_swirl.md new file mode 100644 index 00000000..6bf6c94b --- /dev/null +++ b/docs/src/axisymmetric_swirl.md @@ -0,0 +1,286 @@ +# Axisymmetric swirl: a collapsing core + +This page shows what a finite element run of our axisymmetric-with-swirl Navier–Stokes +discretization does. The equations are the forced, incompressible, axisymmetric-with-swirl +Navier–Stokes equations in the half plane `(r, z)`, discretized with Taylor–Hood P2/P1 triangles +on a mesh graded toward the origin. The flow is a manufactured vortex core that collapses +self-similarly toward the origin, with the exponents of the leading core in the finite-time blowup +construction of 1. radial scale `τ^(1/2)`, axial scale `τ^(1/2-h)` and speeds of order `τ^(-1/2-h)`, +where `τ = 1 - t` and `h = 0.01` (the paper takes any `0 < h < 1/100`). The page reports how accurately a static graded mesh tracks that core, and at what +cost. + +This is our own discretization, and nothing more. It is not a reproduction, proof or disproof of the +result of [1]. The blowing-up flow of that paper is not axisymmetric: only its leading core is, and +the rest of the construction is three-dimensional (oscillatory pulses around the core, section 2.2 +of the paper). Nothing here represents those pulses. The driver is our own manufactured field, and the +force is defined as the residual of our equations at that field; it is singular at `t = 1`, whereas +the force of the paper is smooth through the singular time. + +**Provenance.** From the paper [1] we take the scalings and the qualitative picture of the inner core +(its section 2.1): radial scale `τ^(1/2)`, axial scale `τ^(1/2-h)` with `0 < h < 1/100`, azimuthal and +axial speeds of order `τ^(-1/2-h)` and radial speed `O(τ^(-1/2))`, a fluid that spirals inward and +flows axially outwards on both sides of a layer near `z = 0`, pressure that falls toward the axis, and +velocity `u_θ` that vanishes on the axis. Everything else is ours: the manufactured axisymmetric-with-swirl field +(its profiles, the start-up ramp and the amplitudes), the force defined as its residual, the `(r, z)` +weak form with `Weighted(r)`, the graded mesh (designed in a mesh study run by an AI agent; `mesh.geo` +and the scripts are in the repository), and every error and cost reported below. + +The code is in `examples/axisym_swirl/`: `mesh.geo` (the mesh), `manufactured.jl` (the exact +field and its force), `axisym_swirl.jl` (the problem, the solve and the error norms), +`figures.jl` (renders the two figures below), `animation.jl` (renders the animation) and `linear_residual.jl` (the linear solver check +below). The `NavierStokes` test group runs the example at two resolutions and asserts the +convergence rates. + +## The equations + +With velocity `(uᵣ, u_θ, u_z)`, pressure `p` and kinematic viscosity 1, on `r ∈ (0, R)` and +`z ∈ (-R, R)`: + +``` +∂ₜuᵣ + uᵣ∂ᵣuᵣ + u_z∂_z uᵣ - u_θ²/r + ∂ᵣp = (1/r)∂ᵣ(r∂ᵣuᵣ) + ∂_z²uᵣ - uᵣ/r² + fᵣ +∂ₜu_θ + uᵣ∂ᵣu_θ + u_z∂_z u_θ + uᵣu_θ/r = (1/r)∂ᵣ(r∂ᵣu_θ) + ∂_z²u_θ - u_θ/r² + f_θ +∂ₜu_z + uᵣ∂ᵣu_z + u_z∂_z u_z + ∂_z p = (1/r)∂ᵣ(r∂ᵣu_z) + ∂_z²u_z + f_z +(1/r)∂ᵣ(r uᵣ) + ∂_z u_z = 0 +``` + +They are written in exactly this strong form, and each of the three momentum equations is +integrated by parts with the weight `r`: `ibp = Dict(eq => Weighted(r))`. That is the standard +axisymmetric Galerkin form. The measure is `r dr dz`, the viscous flux is `r ∇u`, and the +zero-order terms `u/r`, `uᵣu_θ` and `u_θ²` that remain are bounded on the axis, where +`uᵣ = u_θ = 0`. Without the weight the Laplacian would be tested in the wrong measure. The +continuity equation is first order and stays strong. It is written already weighted, +`0 ~ Dr(r * ur) + r * Dz(uz)`, and paired with the pressure. + +`Weighted` is not exported by FiniteElementMethod; it lives in PDEBase: + +```julia +using PDEBase.StrongForm: Weighted +``` + +## The driver + +The exact field, with `ξ = r/√τ`, `ζ = z/τ^(1/2-h)`, the start-up ramp `s(t) = 1 - exp(-(t/0.1)²)` +and `G(ζ) = (ζ + 0.05) exp(-ζ²/2)`, is + +``` +uᵣ = -s τ^(-1/2) ξ exp(-ξ²/2) G′(ζ) +u_z = s τ^(-1/2-h) (2 - ξ²) exp(-ξ²/2) G(ζ) +u_θ = 5 s τ^(-1/2-h) ξ exp(-ξ²/2) exp(-ζ²/2) +p = -(25/2) s² τ^(-1-2h) exp(-ξ²) exp(-ζ²) +``` + +It is divergence free (it comes from a Stokes streamfunction), `uᵣ` and `u_θ` vanish on the axis, +and the pressure balances the swirl (`∂ᵣp = u_θ²/r`). The ramp makes every field and its time +derivative zero at `t = 0`, so the zero initial state is consistent. The flow is an inward spiral +with axial outflow above and below `z = 0`. + +The force `f` is the residual of the equations above at this field. It is ours: it is singular +at `t = 1` and grows like `τ^(-3/2-h)`. Because the field is an exact solution of the forced +system, the error the run reports is the discretization error and nothing else. + +The force expressions are thousands of characters long. The front end compiles source terms +without common subexpression elimination and evaluates them at every quadrature point and test +function, so `manufactured.jl` compiles them once with `build_function(...; cse = true)` and +registers the compiled functions with `@register_symbolic`. They depend on `(t, r, z)` only, so the +analysis accepts them as sources: + +```julia +const FORCE_FUNCTIONS = Tuple(build_function(f, t, r, z; expression = Val(false), cse = true) for f in FORCE[1:3]) +force_r(t, r, z) = FORCE_FUNCTIONS[1](t, r, z) +@register_symbolic force_r(t, r, z) # and force_t, force_z +``` + +On a small case (`c = 0.4`, `τ_end = 0.5`, 1 691 unknowns) the registered force makes the solve take +0.5 s instead of 35 s, with the same errors to ten digits. The saving grows with the problem. + +## The mesh + +`mesh.geo` is the rectangle `r ∈ [0, 8]`, `z ∈ [-8, 8]` with the axis `r = 0` as one boundary, and +a size field about the origin: the target element size is `h(ρ) = min(hmax, max(hmin, c ρ))` for +`ρ` the distance to the origin, with `hmin = c √τ_end / 2` and `hmax = 5c`. Halving `c` therefore +halves the element size everywhere. The grading is geometric, so every ball of radius `ρ` holds +about the same number of elements, which is what a self-similar core needs: at time `τ` the +field has scale `√τ` and sits at `ρ ~ √τ`. The axial and radial scales differ by `τ^(-h)`, at most +1.1 for `τ ≥ 1e-4`, so isotropic elements are the right choice. + +![The graded mesh at c = 0.1: the whole domain and a zoom to 0.3 around the origin](assets/axisym_mesh.png) + +The mesh is built from the `.geo` file through the Gmsh API; parameters reach it with +`gmsh.onelab.setNumber` before `gmsh.open`, and `FerriteGmsh.togrid()` converts it: + +```julia +gmsh.onelab.setNumber("Parameters/c", [c]) +gmsh.open("examples/axisym_swirl/mesh.geo") +gmsh.model.mesh.generate(2) +grid = FerriteGmsh.togrid() +``` + +The facet sets are `axis`, `outer`, `top` and `bottom`. + +**Why static.** The element count grows like `(1/c²) log(hmax/hmin)`, so every further decade of +`τ_end` adds a fixed number of elements. Remeshing in stages would save only that logarithmic +factor and needs the solution transferred between meshes, which the package has no API for. The +early steps pay for fine elements that the solution does not need yet; the implicit steps there +are cheap. + +**Why `R = 8`.** The initial core has scale 1 and the field decays like `exp(-ξ²/2)`, which is +1.3e-14 at `r = 8` and smaller still for every `τ < 1`, since the core only shrinks. A larger box +buys nothing, and a smaller one would make the far boundary data matter early. + +## Discretization and solve + +```julia +@variables ur(..) ut(..) uz(..) p(..) +Ω = MeshDomain(grid) +Γaxis, Γout, Γtop, Γbottom = boundarypiece.(Ω, (:axis, :outer, :top, :bottom)) +eqs = [ + Dt(UR) + UR * Dr(UR) + UZ * Dz(UR) - UT^2 / r + Dr(P) ~ laplacian(UR) - UR / r^2 + force_r(t, r, z), + Dt(UT) + UR * Dr(UT) + UZ * Dz(UT) + UR * UT / r ~ laplacian(UT) - UT / r^2 + force_t(t, r, z), + Dt(UZ) + UR * Dr(UZ) + UZ * Dz(UZ) + Dz(P) ~ laplacian(UZ) + force_z(t, r, z), + 0 ~ Dr(r * UR) + r * Dz(UZ), +] +P2, P1 = Lagrange{RefTriangle, 2}(), Lagrange{RefTriangle, 1}() +disc = FEMDiscretization( + Ω, t; spaces = Dict(ur => P2, ut => P2, uz => P2, p => P1), pairing = Dict(eqs[4] => p), + ibp = Dict(eqs[i] => Weighted(r) for i in 1:3), natural = [Γaxis], initializealg = CheckInit(), abstol +) +``` + +(`UR`, `UT`, `UZ`, `P` abbreviate `ur(t, r, z)` and so on, and `laplacian(w)` is +`(1/r) Dr(r Dr(w)) + Dz(Dz(w))`; `axisym_problem` in the example has the whole definition.) + +- **Elements.** Taylor–Hood P2/P1, which is stable for the saddle-point structure. The measured + pressure rate below is the Taylor–Hood rate of 2. +- **Axis.** `uᵣ = u_θ = 0` are Dirichlet conditions. `u_z` has no condition there and so carries the + natural condition, which is declared with `natural = [Γaxis]`; the weighted flux `r ∂ᵣu_z` + vanishes on the axis anyway. The log of the run has no boundary warning. +- **Far boundaries.** `outer`, `top` and `bottom` carry the exact velocity, which is about 1e-14 + of the core values at `R = 8`, so they are effectively no-slip; the exact values are kept so + that the convergence check is clean. +- **Pressure.** There is no equation for it, and the package tests `∇p` strongly, so there is no + do-nothing condition: the level is pinned to the exact pressure on `outer`, as in the + [Navier–Stokes: flow past a cylinder](@ref). +- **Time integration.** The system is an index-2 DAE. It is integrated with `DFBDF`, with + `CheckInit()` because the zero start is consistent (the ramp is zero at `t = 0`), and with + UMFPACK for the linear systems. `abstol` is passed to `FEMDiscretization` and applies to + the differential rows only; the pressure and Dirichlet rows stay out of the error control. +- **Newton matrix.** `NLNewton(new_W_dt_cutoff = 0)` refreshes the Newton matrix at every step. On + the DFG example the default cutoff gives identical results and is faster, but here, at + `c = 0.05`, the default leaves the pressure error at `t = 0.5` 22% larger (5.82e-4 instead + of 4.76e-4, the velocity error unchanged to six digits) for a solve that is 16% faster (85 s + instead of 101 s), so the example uses the refresh. +- **Direct solver and size.** UMFPACK holds the factors in memory: the peak of a run is 3.9 GiB at 124 + thousand unknowns and 9.5 GiB at 490 thousand (see the cost table). Its accuracy was measured on + the Newton matrix `W` itself. `examples/axisym_swirl/linear_residual.jl` steps a run to `t = 0.5`, + saves `W` and a representative right-hand side (minus the residual at the accepted state, with the time advanced by one + step; not DFBDF's own Newton right-hand side), and factorizes that one matrix with each solver in a process + of its own: + + | unknowns | solver | factor and solve | relative residual `‖W x - b‖/‖b‖` | peak memory of the process | + |---|---|---|---|---| + | 124 138 | UMFPACK | 1.1 s | 6.4e-15 | 1.4 GiB | + | 124 138 | KLU | 1015 s | 8.0e-6 | 8.4 GiB | + | 490 169 | UMFPACK | 4.9 s | 2.6e-14 | 4.0 GiB | + | 490 169 | KLU | not finished after 25 min | | at least 20 GiB, still growing | + + UMFPACK's default settings solve this system to rounding level at both sizes, about nine + orders of magnitude below the spatial errors in the table below (1e-5 to 1e-6 for the velocity), so + the linear solves do not contaminate those errors. KLU is both slower and less accurate here, which is why + every run on this page uses UMFPACK. The residual was measured at one state, `t = 0.5`, not along the whole run, and only + for this system; it says nothing about other saddle-point matrices. Every step of the runs needed about one Newton + iteration (203 iterations for 202 steps to `t = 0.5` at `c = 0.05` and 207 for 203 at `c = 0.025`, with no + Newton failure), so a linear solve error would not be iterated away; here it is at rounding level. + For problems where UMFPACK's + residual is poor, LinearSolve.jl [pull request #1414](https://github.com/SciML/LinearSolve.jl/pull/1414) + proposes opt-in `pivot_tolerance` and `strategy` keys for `UMFPACKFactorization`; it was open when this page was written, + so it is a route for large problems once a release contains it, not something this example uses. + +## What the run shows + +The error is the relative r-weighted `L²` error `√(∫ r e² dr dz) / √(∫ r u² dr dz)` against the exact +field, from the solver's dense output and an order-6 quadrature; the velocity error combines +the three components. The run goes to `τ_end = 1e-2`, that is `t = 0.99`, with `abstol = reltol = 1e-8`. +The size parameters are `c = 0.1`, `0.05` and `0.025`, i.e. 32 thousand, 124 thousand and 490 thousand +unknowns. + +| `t` | `c = 0.1` velocity / pressure | `c = 0.05` velocity / pressure | rate | `c = 0.025` velocity / pressure | rate | +|---|---|---|---|---|---| +| 0.5 | 1.83e-4 / 1.95e-3 | 2.21e-5 / 4.76e-4 | 3.05 / 2.03 | 2.72e-6 / 1.19e-4 | 3.03 / 2.00 | +| 0.9 | 1.78e-4 / 1.84e-3 | 2.14e-5 / 4.78e-4 | 3.05 / 1.95 | 2.68e-6 / 1.19e-4 | 3.00 / 2.01 | +| 0.99 | 1.68e-4 / 1.92e-3 | 2.23e-5 / 4.86e-4 | 2.91 / 1.98 | 2.71e-6 / 1.19e-4 | 3.04 / 2.02 | + +All nine cells were measured by running `axisym_solve` at the three values of `c`. A rate is +`log₂` of the error at one `c` over the error at the next, which halves the element size. + +The rates are the Taylor–Hood rates: 3 for the velocity and 2 for the pressure. Between `t = 0.5` +and `t = 0.99` the velocity grows about sevenfold and the core shrinks from radius about 0.7 to +about 0.1, while the relative error stays flat on all three meshes. That is the point of the +graded mesh: the element count per core length stays the same as the core collapses. + +![Top: the swirl speed u_θ near the core at three times, in a window that scales with the core. Bottom: the relative error against time at c = 0.1](assets/axisym_core.png) + +Absolute errors grow with the fields (the pressure scales like `τ^(-1-2h)`), so the page reports +relative errors throughout. + +### Animation + +![The swirl u_θ and the axial velocity u_z over the collapse, from τ = 0.8 to τ = 0.01: left, a fixed window with the graded mesh; middle and right, windows that scale with the core](assets/axisym_swirl.gif) + +The animation is the run at the coarsest mesh of the page, `c = 0.1` (32 thousand unknowns), sampled +from the solver's dense output at 72 frames evenly spaced in `log τ` from `τ = 0.8` to `τ = 0.01` (`t = 0.2` to `0.99`), +with the time and `τ` in the title. The left panel is a fixed window, `r ∈ [0, 2]`, `z ∈ [-2, 2]`, with +the mesh drawn over it and one colour scale for all frames: the core shrinks to a point and `u_θ` grows +by a factor of about ten, so the early frames are dim. The middle and right panels follow the core: the coordinates are `r/τ^(1/2)` and `z/τ^(1/2-h)` +and the fields are multiplied by `τ^(1/2+h)`, the scalings of the paper [1]. In these units the picture is almost +fixed, which is the self-similarity of the manufactured field, apart from the start-up ramp in the first frames. +It is rendered by `examples/axisym_swirl/animation.jl`, which reuses `axisym_solve`, and the file `docs/src/assets/axisym_swirl_animation.fnv1a` is +checked in the same way as the figures (see below). + +### Cost + +All runs went to `t = 0.99`, in 427 to 428 accepted steps with no rejected step and no Newton failure, +with one Julia process on the forge host (Julia 1.12.1, UMFPACK, 32 cores, other jobs running). The +solve time excludes compilation, about 55 s per process, and the peak resident memory includes it +(a process that only compiles and runs a 1.7 thousand-unknown case already holds 2.1 GiB). + +| `c` | cells | unknowns | Newton matrix refreshes | mesh | assembly set-up | solve | peak memory | +|---|---|---|---|---|---|---|---| +| 0.1 | 4 870 | 32 324 | 74 | 0.04 s | 1 s | 23.5 s | 2.7 GiB | +| 0.05 | 18 894 | 124 138 | 77 | 0.18 s | 5 s | 101 s | 4.0 GiB | +| 0.025 | 75 004 | 490 169 | 77 | 0.97 s | 24 s | 421 s | 9.5 GiB | + +"Assembly set-up" is the time of `axisym_problem`, which builds the discretization. The solve time grows slightly +faster than the unknown count: 4.3 times for 3.8 times the unknowns, then 4.2 times for 3.9 times. + +## Limits + +- **The run stops short of `t = 1`.** The prescribed field and its force are singular at + `t = 1`, so no finite mesh or time step reaches it. A static mesh resolves the core only down to + `τ ≈ τ_end` by construction. The runs here stop at `t = 0.99`. +- **Axisymmetric only.** The flow has no dependence on the angle; nothing here represents the + non-axisymmetric structure of the paper's blowing-up flow. +- **Static mesh.** There is no remeshing and no solution transfer between meshes. +- **Direct solver and memory.** The solve is a sparse direct factorization. Its memory grows + faster than the unknown count, 9.5 GiB peak at 490 thousand unknowns, and no iterative + saddle-point solver is provided. +- **CPU only.** There is no GPU path. +- **The driver is manufactured.** The accuracy statements are about the discretization of a + prescribed field; they say nothing about the stability of free Navier–Stokes flow. + +## Reproducing the numbers and the images + +```sh +julia --project=docs examples/axisym_swirl/axisym_swirl.jl 0.1 0.01 # c, τ_end +julia --project=docs examples/axisym_swirl/figures.jl # renders the two figures into docs/src/assets +julia --project=docs examples/axisym_swirl/animation.jl # renders the animation (one more solve, c = 0.1) +GROUP=NavierStokes julia --project=. -e 'using Pkg; Pkg.test()' +``` + +The two figures and the animation are committed in `docs/src/assets` and the documentation build does not solve +anything. `axisym_swirl.fnv1a` holds a checksum of the files the figures are rendered from, and +`axisym_swirl_animation.fnv1a` one of the files the animation is rendered from; the `NavierStokes` test group fails +when those files change without a re-render. + +## References + +1. OpenAI, *Finite time blowup for Navier–Stokes*, PDF created 8 September 2026 (no arXiv number or other date is printed in it), . Theorem 1.1: for every viscosity `ν > 0` there is a smooth, compactly supported force and a solution of the three-dimensional incompressible Navier–Stokes equations that starts from rest and has unbounded velocity as `t ↑ 1` while its kinetic energy stays uniformly bounded. The author line of the paper reads "OPENAI". We use its section 2 (the inner core) and the exponents of its section 3.1. diff --git a/examples/axisym_swirl/animation.jl b/examples/axisym_swirl/animation.jl new file mode 100644 index 00000000..6db64848 --- /dev/null +++ b/examples/axisym_swirl/animation.jl @@ -0,0 +1,72 @@ +# Renders the animation of docs/src/axisymmetric_swirl.md into docs/src/assets (committed; the documentation build +# does not solve anything). From the repository root, with the docs environment (it has CairoMakie): +# +# julia --project=docs examples/axisym_swirl/animation.jl +# +# One solve of `axisym_swirl.jl` at c = 0.1, tau_end = 1e-2 (the coarsest of the page's three meshes, 32k unknowns, +# about half a minute after compilation), sampled at frames spaced evenly in log(tau). Rendering also writes the +# checksum of the source files that test/NavierStokes/axisym_swirl.jl compares. +using CairoMakie + +include(joinpath(@__DIR__, "axisym_swirl.jl")) +include(joinpath(@__DIR__, "checksum.jl")) + +const AXISYM_ASSETS = joinpath(@__DIR__, "..", "..", "docs", "src", "assets") + +function render_axisym_animation(directory = AXISYM_ASSETS; c = 0.1, tau_end = 1.0e-2, frames = 72, tau_start = 0.8) + mkpath(directory) + grid = axisym_grid(; c, tau_end) + run = axisym_solve(; c, tau_end, report = ()) + nodes = [Ferrite.get_node_coordinate(n).data for n in Ferrite.getnodes(grid)] + edges = Point2f[] + for cell in Ferrite.getcells(grid), (a, b) in ((1, 2), (2, 3), (3, 1)) + push!(edges, Point2f(nodes[cell.nodes[a]]), Point2f(nodes[cell.nodes[b]]), Point2f(NaN, NaN)) + end + taus = exp.(range(log(tau_start), log(tau_end), frames)) + fixed = 2.0 # the fixed window is r in [0, 2], z in [-2, 2] + rs_fixed, zs_fixed = range(0, fixed, 100), range(-fixed, fixed, 200) + rs_unit, zs_unit = range(0, 3, 90), range(-3, 3, 180) # the following window, in units of the core's scales + fixed_swirl(tau) = run.sol(1 - tau, collect(rs_fixed), collect(zs_fixed); dv = ut(t, r, z)) + # In the following window r = x sqrt(tau), z = y tau^(1/2 - h) and the fields are multiplied by tau^(1/2 + h), + # which is the self-similar shape of manufactured.jl: it changes only through the ramp and the mesh. + function following(tau, field) + rs, zs = collect(rs_unit .* sqrt(tau)), collect(zs_unit .* tau^EXPONENT_D) + return run.sol(1 - tau, rs, zs; dv = field) .* tau^EXPONENT_A + end + swirl_max = maximum(maximum(fixed_swirl(tau)) for tau in taus) + + frame = Observable(1) + tau = @lift taus[$frame] + fig = Figure(size = (1260, 500)) + Label( + fig[0, 1:6], @lift("t = $(round(1 - $tau; digits = 4)), τ = 1 - t = $(round($tau; sigdigits = 3))"); + fontsize = 22, tellwidth = false + ) + ax1 = Axis( + fig[1, 1]; title = "u_θ in a fixed window", xlabel = "r", ylabel = "z", aspect = DataAspect(), + limits = (0, fixed, -fixed, fixed) + ) + hm1 = heatmap!(ax1, rs_fixed, zs_fixed, @lift(fixed_swirl(taus[$frame])); colormap = :viridis, colorrange = (0, swirl_max)) + lines!(ax1, edges; linewidth = 0.3, color = (:white, 0.35)) + Colorbar(fig[1, 2], hm1; label = "u_θ") + for (k, (field, name)) in enumerate(((ut(t, r, z), "u_θ"), (uz(t, r, z), "u_z"))) + ax = Axis( + fig[1, 2k + 1]; title = "$name · τ^(1/2+h), in a window that follows the core", xlabel = "r / τ^(1/2)", + ylabel = k == 1 ? "z / τ^(1/2-h)" : "", aspect = DataAspect(), titlesize = 13 + ) + hm = heatmap!( + ax, rs_unit, zs_unit, @lift(following(taus[$frame], field)); + colormap = k == 1 ? :viridis : :balance, colorrange = k == 1 ? (0, 3.2) : (-1.4, 1.4) + ) + Colorbar(fig[1, 2k + 2], hm) + end + record(fig, joinpath(directory, "axisym_swirl.gif"), 1:frames; framerate = 12, px_per_unit = 1) do index + frame[] = index + end + write(joinpath(directory, "axisym_swirl_animation.fnv1a"), animation_sources_hash() * "\n") + return directory +end + +if abspath(PROGRAM_FILE) == @__FILE__ + render_axisym_animation(isempty(ARGS) ? AXISYM_ASSETS : ARGS[1]) +end diff --git a/examples/axisym_swirl/axisym_swirl.jl b/examples/axisym_swirl/axisym_swirl.jl new file mode 100644 index 00000000..46a27748 --- /dev/null +++ b/examples/axisym_swirl/axisym_swirl.jl @@ -0,0 +1,160 @@ +# Axisymmetric Navier–Stokes with swirl in the half plane (r, z): a manufactured vortex core that collapses +# self-similarly toward the origin, solved with Taylor–Hood P2/P1 triangles on a mesh graded toward the origin. +# +# julia --project=docs examples/axisym_swirl/axisym_swirl.jl [c] [tau_end] +# +# This is our own discretization driven by our own manufactured field (`manufactured.jl`); it is not a +# reproduction of any blowup result. The pieces, each explained on the documentation page: +# +# - Each momentum equation is written in the textbook strong form of the (r, z) system and integrated by parts +# with `Weighted(r)`, the axisymmetric measure r dr dz. The continuity equation is written already weighted, +# `0 ~ Dr(r ur) + r Dz(uz)`, and paired with the pressure. +# - u_r = u_theta = 0 on the axis; u_z carries the natural condition there (`natural = [Γaxis]`). The far +# boundaries carry the exact velocity and the exact pressure is pinned on `outer`. +# - The mesh comes from `mesh.geo` through the Gmsh API; the size is c times the distance to the origin, +# between hmin = c sqrt(tau_end) / 2 and hmax = 5c. +using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF +using OrdinaryDiffEqBDF: NLNewton +using LinearSolve: UMFPACKFactorization +using PDEBase.StrongForm: Weighted +using SciMLBase: SciMLBase, CheckInit, solve +using Ferrite: Ferrite, Lagrange, RefTriangle +using FerriteGmsh: FerriteGmsh +using Gmsh: Gmsh, gmsh + +include(joinpath(@__DIR__, "manufactured.jl")) + +const AXISYM_MESH = joinpath(@__DIR__, "mesh.geo") + +@variables ur(..) ut(..) uz(..) p(..) + +""" + axisym_grid(; c, tau_end, R = 8.0, hmax = 5c) + +The graded triangle mesh of `mesh.geo` on `r ∈ [0, R]`, `z ∈ [-R, R]` as a `Ferrite.Grid` with facet sets `axis`, +`outer`, `top` and `bottom`. The element size is `c` times the distance to the origin, clamped to +`[c sqrt(tau_end) / 2, hmax]`, so halving `c` halves the size everywhere. Parameters reach the `.geo` file through +`gmsh.onelab.setNumber` before `gmsh.open`. +""" +function axisym_grid(; c, tau_end, R = 8.0, hmax = 5c) + Gmsh.initialize() + try + gmsh.option.setNumber("General.Terminal", 0) + for (name, value) in (("R", R), ("c", c), ("hmin", c * sqrt(tau_end) / 2), ("hmax", hmax), ("order", 1)) + gmsh.onelab.setNumber("Parameters/$name", [Float64(value)]) + end + gmsh.open(AXISYM_MESH) + gmsh.model.mesh.generate(2) + return FerriteGmsh.togrid() + finally + Gmsh.finalize() + end +end + +""" + axisym_problem(grid; tend, abstol = 1e-8) + +The `DAEProblem` of the axisymmetric swirl system on `grid` from t = 0 to `tend`. `abstol` is the absolute +tolerance of the differential rows; the pressure and Dirichlet rows are left out of the error control. +""" +function axisym_problem(grid; tend, abstol = 1.0e-8) + Ω = MeshDomain(grid) + Γaxis, Γout, Γtop, Γbottom = boundarypiece.(Ω, (:axis, :outer, :top, :bottom)) + UR, UT, UZ, P = ur(t, r, z), ut(t, r, z), uz(t, r, z), p(t, r, z) + eqs = [ + Dt(UR) + UR * Dr(UR) + UZ * Dz(UR) - UT^2 / r + Dr(P) ~ laplacian(UR) - UR / r^2 + force_r(t, r, z), + Dt(UT) + UR * Dr(UT) + UZ * Dz(UT) + UR * UT / r ~ laplacian(UT) - UT / r^2 + force_t(t, r, z), + Dt(UZ) + UR * Dr(UZ) + UZ * Dz(UZ) + Dz(P) ~ laplacian(UZ) + force_z(t, r, z), + 0 ~ Dr(r * UR) + r * Dz(UZ), + ] + far = (Γout, Γtop, Γbottom) + bcs = [ + [ur(t, Γ) ~ EXACT[:ur] for Γ in far]; [ut(t, Γ) ~ EXACT[:ut] for Γ in far]; + [uz(t, Γ) ~ EXACT[:uz] for Γ in far]; + ur(t, Γaxis) ~ 0; ut(t, Γaxis) ~ 0; + p(t, Γout) ~ EXACT[:p]; + ur(0, r, z) ~ 0; ut(0, r, z) ~ 0; uz(0, r, z) ~ 0 + ] + @named axisym = PDESystem(eqs, bcs, [(r, z) ∈ Ω, t ∈ Interval(0.0, tend)], [t, r, z], [UR, UT, UZ, P], []) + P2, P1 = Lagrange{RefTriangle, 2}(), Lagrange{RefTriangle, 1}() + disc = FEMDiscretization( + Ω, t; spaces = Dict(ur => P2, ut => P2, uz => P2, p => P1), pairing = Dict(eqs[4] => p), + ibp = Dict(eqs[i] => Weighted(r) for i in 1:3), natural = [Γaxis], initializealg = CheckInit(), abstol + ) + return DAEProblem(axisym, disc) +end + +""" + weighted_errors(sol, tt, exact) + +The r-weighted L² errors `sqrt(∫ r (u_h - u)² dr dz)` and norms `sqrt(∫ r u² dr dz)` at time `tt` of each field in +`exact`, a `Dict` from field name to a function `(t, r, z) -> value`, as two dictionaries `(err, nrm)`. Integrated +with an order-6 triangle rule on the solver's dense output. +""" +function weighted_errors(sol, tt, exact) + dh = sol.disc_data.space.dh + U = sol.original_sol(tt) + sdh = only(dh.subdofhandlers) + geometry = Ferrite.geometric_interpolation(Ferrite.getcelltype(dh.grid)) + rule = Ferrite.QuadratureRule{Ferrite.RefTriangle}(6) + values = Dict(f => Ferrite.CellValues(rule, Ferrite.getfieldinterpolation(sdh, f), geometry) for f in keys(exact)) + err2, norm2 = Dict(f => 0.0 for f in keys(exact)), Dict(f => 0.0 for f in keys(exact)) + for cell in Ferrite.CellIterator(dh) + dofs, xs = Ferrite.celldofs(cell), Ferrite.getcoordinates(cell) + for (f, exact_f) in exact + cv = values[f] + Ferrite.reinit!(cv, xs) + local_dofs = U[dofs[Ferrite.dof_range(sdh, f)]] + for q in 1:Ferrite.getnquadpoints(cv) + X = Ferrite.spatial_coordinate(cv, q, xs) + weight = Ferrite.getdetJdV(cv, q) * X[1] + value = exact_f(tt, X[1], X[2]) + err2[f] += (Ferrite.function_value(cv, q, local_dofs) - value)^2 * weight + norm2[f] += value^2 * weight + end + end + end + return Dict(f => sqrt(err2[f]) for f in keys(exact)), Dict(f => sqrt(norm2[f]) for f in keys(exact)) +end + +""" + axisym_errors(sol, tt) + +Relative r-weighted L² errors of the swirl solution at `tt` against `EXACT_FUNCTIONS`, as `(velocity, pressure)`; +the velocity error combines the three components. +""" +function axisym_errors(sol, tt) + err, nrm = weighted_errors(sol, tt, EXACT_FUNCTIONS) + velocity = (:ur, :ut, :uz) + return sqrt(sum(err[f]^2 for f in velocity) / sum(nrm[f]^2 for f in velocity)), err[:p] / nrm[:p] +end + +# A fresh Newton matrix every step (`new_W_dt_cutoff = 0`): with the default cutoff the pressure error at t = 0.5 is +# 22% larger at c = 0.05 (the velocity is unchanged) for a solve that is 16% faster. +const AXISYM_ALG = DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()) + +""" + axisym_solve(; c = 0.1, tau_end = 1e-2, tol = 1e-8, alg = AXISYM_ALG, report = (0.5, 0.9, 0.99)) + +Mesh, discretize and solve to `t = 1 - tau_end`, and return the solution with the unknown count, the cell count, +the wall times and the relative errors `(t, velocity, pressure)` at the `report` times that were reached. +""" +function axisym_solve(; c = 0.1, tau_end = 1.0e-2, tol = 1.0e-8, alg = AXISYM_ALG, report = (0.5, 0.9, 0.99)) + tend = 1 - tau_end + mesh_s = @elapsed grid = axisym_grid(; c, tau_end) + build_s = @elapsed prob = axisym_problem(grid; tend, abstol = tol) + saveat = [tt for tt in report if tt <= tend] + solve_s = @elapsed sol = solve(prob, alg; reltol = tol, saveat) + errors = [(tt, axisym_errors(sol, tt)...) for tt in saveat] + return (; sol, prob, ncells = Ferrite.getncells(grid), ndofs = length(prob.u0), mesh_s, build_s, solve_s, errors) +end + +if abspath(PROGRAM_FILE) == @__FILE__ + c = length(ARGS) >= 1 ? parse(Float64, ARGS[1]) : 0.1 + tau_end = length(ARGS) >= 2 ? parse(Float64, ARGS[2]) : 1.0e-2 + run = axisym_solve(; c, tau_end) + println("c = $c, tau_end = $tau_end: $(run.ncells) cells, $(run.ndofs) unknowns, solve $(round(run.solve_s; digits = 1)) s") + for (tt, velocity, pressure) in run.errors + println(" t = $tt: velocity error $velocity, pressure error $pressure") + end +end diff --git a/examples/axisym_swirl/checksum.jl b/examples/axisym_swirl/checksum.jl new file mode 100644 index 00000000..eba79dff --- /dev/null +++ b/examples/axisym_swirl/checksum.jl @@ -0,0 +1,17 @@ +# FNV-1a checksums of the files the committed images of the axisymmetric swirl page are rendered from. Each checksum +# is committed next to its images (docs/src/assets/axisym_swirl.fnv1a for the two figures, axisym_swirl_animation.fnv1a +# for the animation) and test/NavierStokes/axisym_swirl.jl fails when these files change without a re-render with +# `julia --project=docs examples/axisym_swirl/figures.jl` or `animation.jl`. +const FIGURE_SOURCES = ("mesh.geo", "manufactured.jl", "axisym_swirl.jl", "figures.jl") +const ANIMATION_SOURCES = ("mesh.geo", "manufactured.jl", "axisym_swirl.jl", "animation.jl") + +function sources_hash(files, directory = @__DIR__) + checksum = 0xcbf29ce484222325 + for file in files, byte in read(joinpath(directory, file)) + checksum = (checksum ⊻ byte) * 0x00000100000001b3 + end + return string(checksum; base = 16, pad = 16) +end + +figure_sources_hash(directory = @__DIR__) = sources_hash(FIGURE_SOURCES, directory) +animation_sources_hash(directory = @__DIR__) = sources_hash(ANIMATION_SOURCES, directory) diff --git a/examples/axisym_swirl/figures.jl b/examples/axisym_swirl/figures.jl new file mode 100644 index 00000000..afb96c30 --- /dev/null +++ b/examples/axisym_swirl/figures.jl @@ -0,0 +1,58 @@ +# Renders the two figures of docs/src/axisymmetric_swirl.md into docs/src/assets (committed; the documentation +# build does not solve anything). From the repository root, with the docs environment (it has CairoMakie): +# +# julia --project=docs examples/axisym_swirl/figures.jl +# +# One solve at c = 0.1, tau_end = 1e-2 (32k unknowns, about half a minute after compilation). Rendering also +# writes the checksum of the source files that test/NavierStokes/axisym_swirl.jl compares. +using CairoMakie + +include(joinpath(@__DIR__, "axisym_swirl.jl")) +include(joinpath(@__DIR__, "checksum.jl")) + +const AXISYM_ASSETS = joinpath(@__DIR__, "..", "..", "docs", "src", "assets") + +function render_axisym_figures(directory = AXISYM_ASSETS; c = 0.1, tau_end = 1.0e-2) + mkpath(directory) + grid = axisym_grid(; c, tau_end) + nodes = [Ferrite.get_node_coordinate(n).data for n in Ferrite.getnodes(grid)] + edges = Point2f[] + for cell in Ferrite.getcells(grid), (a, b) in ((1, 2), (2, 3), (3, 1)) + push!(edges, Point2f(nodes[cell.nodes[a]]), Point2f(nodes[cell.nodes[b]]), Point2f(NaN, NaN)) + end + fig = Figure(size = (900, 430)) + for (k, (extent, title)) in enumerate(((8.0, "whole domain"), (0.3, "within 0.3 of the origin"))) + ax = Axis(fig[1, k]; title, xlabel = "r", ylabel = "z", aspect = DataAspect(), limits = (0, extent, -extent, extent)) + lines!(ax, edges; linewidth = 0.4, color = :black) + end + save(joinpath(directory, "axisym_mesh.png"), fig; px_per_unit = 1) + + report = vcat(0.05:0.05:0.95, 0.96:0.01:0.99) + run = axisym_solve(; c, tau_end, report) + fig = Figure(size = (950, 780)) + for (k, tt) in enumerate((0.5, 0.9, 0.99)) + scale = sqrt(1 - tt) + rs, zs = range(0, 3scale, 120), range(-3scale, 3scale, 240) + swirl = run.sol(tt, collect(rs), collect(zs); dv = ut(t, r, z)) + ax = Axis( + fig[1, k]; title = "swirl u_θ at t = $tt", xlabel = "r", ylabel = k == 1 ? "z" : "", + aspect = DataAspect() + ) + hm = heatmap!(ax, rs, zs, swirl; colormap = :viridis) + Colorbar(fig[2, k], hm; vertical = false, flipaxis = false) + end + ax = Axis( + fig[3, 1:3]; xlabel = "t", ylabel = "relative r-weighted L² error", yscale = log10, + title = "c = $c: the error stays flat while the core collapses" + ) + scatterlines!(ax, [e[1] for e in run.errors], [e[2] for e in run.errors]; label = "velocity") + scatterlines!(ax, [e[1] for e in run.errors], [e[3] for e in run.errors]; label = "pressure") + axislegend(ax; position = :rc) + save(joinpath(directory, "axisym_core.png"), fig; px_per_unit = 1) + write(joinpath(directory, "axisym_swirl.fnv1a"), figure_sources_hash() * "\n") + return directory +end + +if abspath(PROGRAM_FILE) == @__FILE__ + render_axisym_figures(isempty(ARGS) ? AXISYM_ASSETS : ARGS[1]) +end diff --git a/examples/axisym_swirl/linear_residual.jl b/examples/axisym_swirl/linear_residual.jl new file mode 100644 index 00000000..996c194e --- /dev/null +++ b/examples/axisym_swirl/linear_residual.jl @@ -0,0 +1,45 @@ +# Accuracy of the sparse direct solvers on the Newton matrix of the axisymmetric swirl problem. +# +# julia --project=docs examples/axisym_swirl/linear_residual.jl extract c t_stop file +# julia --project=docs examples/axisym_swirl/linear_residual.jl solve file umfpack|klu +# +# `extract` steps the integrator to `t_stop`, then writes the Newton matrix W = dF/du + γ dF/d(du) at that state +# (γ is the one DFBDF built its own W with) and a representative right-hand side to `file`: minus the residual at the +# accepted state with the time advanced by one step. It is not DFBDF's own Newton right-hand side, which uses the +# predicted state, so the check is of the solver on this matrix with a right-hand side of the right size and kind. `solve` +# factorizes the saved matrix once with the named solver, in a process of its own so that the peak memory is that +# solver's, and prints the factorization time and the relative residual ‖W x - b‖ / ‖b‖. +using LinearAlgebra, SparseArrays, Serialization, Printf +using LinearSolve: LinearSolve, LinearProblem, KLUFactorization, init +using SciMLBase: SciMLBase, step!, solve! + +if ARGS[1] == "extract" + include(joinpath(@__DIR__, "axisym_swirl.jl")) + c, t_stop, file = parse(Float64, ARGS[2]), parse(Float64, ARGS[3]), ARGS[4] + prob = axisym_problem(axisym_grid(; c, tau_end = 1.0e-2); tend = 0.99) + integ = SciMLBase.init(prob, AXISYM_ALG; reltol = 1.0e-8, save_everystep = false) + while integ.t < t_stop + step!(integ) + end + stats = integ.stats + @printf("t = %.4g, dt = %.3g, steps %d, Newton iterations %d, Newton failures %d\n", integ.t, integ.dt, stats.naccept, stats.nnonliniter, stats.nnonlinconvfail) + γ = integ.cache.nlsolver.cache.W_γdt + u, du, p, tt = copy(integ.u), copy(integ.du), integ.p, integ.t + W = copy(prob.f.jac_prototype) + prob.f.jac(W, du, u, p, γ, tt) + residual = zeros(length(u)) + prob.f.f(residual, du, u, p, tt + integ.dt) + serialize(file, (; W, b = -residual, γ, t = tt, naccept = stats.naccept, newton = stats.nnonliniter)) + @printf("saved %s: %d unknowns, %d nonzeros\n", file, size(W, 1), nnz(W)) +else + W, b = let m = deserialize(ARGS[2]) + m.W, m.b + end + solver = ARGS[3] == "klu" ? KLUFactorization() : LinearSolve.UMFPACKFactorization() + cache = init(LinearProblem(W, b), solver) + factor_s = @elapsed x = solve!(cache).u + @printf( + "%s: %d unknowns, factor+solve %.1f s, relative residual %.3e, peak memory %.2f GiB\n", + ARGS[3], size(W, 1), factor_s, norm(W * x - b) / norm(b), Sys.maxrss() / 2^30 + ) +end diff --git a/examples/axisym_swirl/manufactured.jl b/examples/axisym_swirl/manufactured.jl new file mode 100644 index 00000000..b3780fbc --- /dev/null +++ b/examples/axisym_swirl/manufactured.jl @@ -0,0 +1,54 @@ +# The manufactured collapsing core of the axisymmetric swirl example, and the force that makes it an exact +# solution. Both are ours: the force is defined as the residual of the equations of `axisym_swirl.jl` at this +# field, so the finite element error against it is the discretization error and nothing else. +# +# With tau = 1 - t, h = 0.01, xi = r / sqrt(tau) and zeta = z / tau^(1/2 - h), the field has radial scale +# tau^(1/2), axial scale tau^(1/2 - h), velocities of size tau^(-1/2-h) (tau^(-1/2) radially), and a start +# from rest through the ramp s(t) = 1 - exp(-(t / 0.1)^2). It is divergence free (it comes from the Stokes +# streamfunction a s tau^(-1/2-h) r^2 exp(-xi^2/2) G(zeta)) and the pressure balances the swirl (d_r p = u_theta^2 / r). +using ModelingToolkit, Symbolics +using ModelingToolkit: t_nounits as t + +@variables r z +const Dt, Dr, Dz = Differential(t), Differential(r), Differential(z) + +const H, J0, AMP_Z, AMP_SWIRL = 0.01, 0.05, 1.0, 5.0 +const EXPONENT_A, EXPONENT_D = 1 / 2 + H, 1 / 2 - H +τ = 1 - t +ξ, ζ = r / sqrt(τ), z / τ^EXPONENT_D +ramp = 1 - exp(-(t / 0.1)^2) +profile = (ζ + J0) * exp(-ζ^2 / 2) +profile_z = (1 - ζ * (ζ + J0)) * exp(-ζ^2 / 2) +const EXACT = Dict( + :ur => -AMP_Z * ramp * τ^(-1 / 2) * ξ * exp(-ξ^2 / 2) * profile_z, + :uz => AMP_Z * ramp * τ^(-EXPONENT_A) * (2 - ξ^2) * exp(-ξ^2 / 2) * profile, + :ut => AMP_SWIRL * ramp * τ^(-EXPONENT_A) * ξ * exp(-ξ^2 / 2) * exp(-ζ^2 / 2), + :p => -(AMP_SWIRL^2 / 2) * ramp^2 * τ^(-2 * EXPONENT_A) * exp(-ξ^2) * exp(-ζ^2), +) +"The exact fields as functions `(t, r, z) -> value`, for the error norms." +const EXACT_FUNCTIONS = Dict(k => build_function(v, t, r, z; expression = Val(false)) for (k, v) in EXACT) + +laplacian(w) = (1 / r) * Dr(r * Dr(w)) + Dz(Dz(w)) + +"Strong momentum residuals (left minus right side, no force) of the axisymmetric swirl equations, and the divergence." +function residuals(UR, UT, UZ, P) + return ( + Dt(UR) + UR * Dr(UR) + UZ * Dz(UR) - UT^2 / r + Dr(P) - (laplacian(UR) - UR / r^2), + Dt(UT) + UR * Dr(UT) + UZ * Dz(UT) + UR * UT / r - (laplacian(UT) - UT / r^2), + Dt(UZ) + UR * Dr(UZ) + UZ * Dz(UZ) + Dz(P) - laplacian(UZ), + (1 / r) * Dr(r * UR) + Dz(UZ), + ) +end +const FORCE = map(expand_derivatives, residuals(EXACT[:ur], EXACT[:ut], EXACT[:uz], EXACT[:p])) + +# The force expressions are thousands of characters long. The front end compiles source terms without common +# subexpression elimination and evaluates them at every quadrature point and test function, which made the raw +# expressions 98% of the solve time. Compiled once with `cse = true` and registered as opaque functions of +# (t, r, z), they cost a few percent. They depend on the coordinates only, so the analysis accepts them as sources. +const FORCE_FUNCTIONS = Tuple(build_function(f, t, r, z; expression = Val(false), cse = true) for f in FORCE[1:3]) +force_r(t, r, z) = FORCE_FUNCTIONS[1](t, r, z) +force_t(t, r, z) = FORCE_FUNCTIONS[2](t, r, z) +force_z(t, r, z) = FORCE_FUNCTIONS[3](t, r, z) +@register_symbolic force_r(t, r, z) +@register_symbolic force_t(t, r, z) +@register_symbolic force_z(t, r, z) diff --git a/examples/axisym_swirl/mesh.geo b/examples/axisym_swirl/mesh.geo new file mode 100644 index 00000000..60013071 --- /dev/null +++ b/examples/axisym_swirl/mesh.geo @@ -0,0 +1,54 @@ +// Axisymmetric (r,z) half plane, r in [0,R], z in [-R,R], graded geometrically toward the origin. +// Target size h(rho) = min(hmax, max(hmin, c*rho)), rho = |(r,z)|. +// Override any parameter: gmsh ns_axisym.geo -2 -setnumber c 0.05 -setnumber hmin 1e-3 ... +DefineConstant[ + R = {8, Name "Parameters/R"}, + c = {0.05, Name "Parameters/c"}, + hmin = {0.05*0.5*Sqrt(1e-3), Name "Parameters/hmin"}, + hmax = {0.5, Name "Parameters/hmax"}, + order = {1, Name "Parameters/order"} +]; + +SetFactory("Built-in"); + +Point(1) = {0, -R, 0, hmax}; +Point(2) = {R, -R, 0, hmax}; +Point(3) = {R, R, 0, hmax}; +Point(4) = {0, R, 0, hmax}; +Point(5) = {0, 0, 0, hmin}; // origin: a mesh vertex sits at the singularity + +Line(1) = {1, 2}; // bottom +Line(2) = {2, 3}; // outer +Line(3) = {3, 4}; // top +Line(4) = {4, 5}; // axis, upper half +Line(5) = {5, 1}; // axis, lower half + +Curve Loop(1) = {1, 2, 3, 4, 5}; +Plane Surface(1) = {1}; + +Physical Curve("axis") = {4, 5}; +Physical Curve("outer") = {2}; +Physical Curve("top") = {3}; +Physical Curve("bottom") = {1}; +Physical Surface("fluid") = {1}; + +// Linear ramp between DistMin and DistMax reproduces c*rho exactly, clamped to [hmin, hmax]. +Field[1] = Distance; +Field[1].PointsList = {5}; +Field[2] = Threshold; +Field[2].InField = 1; +Field[2].SizeMin = hmin; +Field[2].SizeMax = hmax; +Field[2].DistMin = hmin / c; +Field[2].DistMax = hmax / c; +Field[2].Sigmoid = 0; +Field[3] = Min; +Field[3].FieldsList = {2}; +Background Field = 3; + +Mesh.MeshSizeFromPoints = 0; +Mesh.MeshSizeFromCurvature = 0; +Mesh.MeshSizeExtendFromBoundary = 0; +Mesh.Algorithm = 6; // Frontal-Delaunay +Mesh.ElementOrder = order; +Mesh.MshFileVersion = 4.1; diff --git a/test/NavierStokes/axisym_swirl.jl b/test/NavierStokes/axisym_swirl.jl new file mode 100644 index 00000000..9727034e --- /dev/null +++ b/test/NavierStokes/axisym_swirl.jl @@ -0,0 +1,74 @@ +# The axisymmetric swirl example (docs/src/axisymmetric_swirl.md): the r-weighted weak form on a scalar problem +# with a known exact solution, then the full Navier–Stokes system on graded Taylor–Hood P2/P1 triangles from Gmsh +# against the manufactured collapsing core, with the convergence rates of the Taylor–Hood pair. +using FiniteElementMethod, Test +using Ferrite: Triangle, Vec +include(joinpath(@__DIR__, "..", "..", "examples", "axisym_swirl", "axisym_swirl.jl")) +include(joinpath(@__DIR__, "..", "..", "examples", "axisym_swirl", "checksum.jl")) + +rate(coarse, fine) = log2(coarse / fine) + +@testset "Weighted(r): axisymmetric heat equation with a -u/r² term" begin + @variables u(..) + exact_heat = exp(-t) * r * exp(-r^2 - z^2) + source = expand_derivatives(Dt(exact_heat) - (laplacian(exact_heat) - exact_heat / r^2)) + exact = Dict(:u => build_function(exact_heat, t, r, z; expression = Val(false))) + errors = map((4, 8, 16)) do n + Ω = MeshDomain(Ferrite.generate_grid(Triangle, (n, n), Vec(0.0, -1.0), Vec(2.0, 1.0))) + sides = boundarypiece.(Ω, (:left, :right, :bottom, :top)) + U = u(t, r, z) + eq = Dt(U) ~ laplacian(U) - U / r^2 + source + bcs = [[u(t, Γ) ~ exact_heat for Γ in sides]; u(0, r, z) ~ substitute(exact_heat, t => 0)] + @named heat = PDESystem([eq], bcs, [(r, z) ∈ Ω, t ∈ Interval(0.0, 0.5)], [t, r, z], [U], []) + disc = FEMDiscretization(Ω, t; spaces = Dict(u => Lagrange{RefTriangle, 2}()), ibp = Dict(eq => Weighted(r))) + sol = solve(discretize(heat, disc), DFBDF(linsolve = UMFPACKFactorization()); abstol = 1.0e-11, reltol = 1.0e-11) + @test SciMLBase.successful_retcode(sol) + err, nrm = weighted_errors(sol, 0.5, exact) + err[:u] / nrm[:u] + end + @info "Weighted(r) heat" errors rate.(errors[1:(end - 1)], errors[2:end]) + @test all(>(2.7), rate.(errors[1:(end - 1)], errors[2:end])) +end + +@testset "axisymmetric swirl: collapsing core" begin + # The manufactured field is divergence free and finite on the axis. + divergence = build_function(FORCE[4], t, r, z; expression = Val(false)) + for point in ((0.3, 0.2, -0.4), (0.9, 0.05, 0.1), (0.99, 0.01, 0.02)) + @test abs(divergence(point...)) <= 1.0e-10 + end + tau_end, report = 0.1, (0.5, 0.9) + runs = [axisym_solve(; c, tau_end, report) for c in (0.2, 0.1)] + @info "axisymmetric swirl" [(r.ndofs, r.solve_s, r.errors) for r in runs] + for run in runs + @test SciMLBase.successful_retcode(run.sol) + @test run.sol.t[end] ≈ 1 - tau_end + end + for (k, tt) in enumerate(report) + coarse, fine = runs[1].errors[k], runs[2].errors[k] + @test rate(coarse[2], fine[2]) > 2.7 # velocity: Taylor–Hood order 3 + @test rate(coarse[3], fine[3]) > 1.7 # pressure: Taylor–Hood order 2 + end +end + +@testset "axisymmetric swirl images and animation are current" begin + assets = joinpath(@__DIR__, "..", "..", "docs", "src", "assets") + # figures.jl needs CairoMakie, which is not a test dependency: it must at least parse. + for script in ("figures.jl", "animation.jl") + @test Meta.parseall(read(joinpath(@__DIR__, "..", "..", "examples", "axisym_swirl", script), String)) isa Expr + end + for file in ("axisym_mesh.png", "axisym_core.png", "axisym_swirl.fnv1a", "axisym_swirl.gif", "axisym_swirl_animation.fnv1a") + @test isfile(joinpath(assets, file)) + end + if figure_sources_hash() != strip(read(joinpath(assets, "axisym_swirl.fnv1a"), String)) + error( + "the sources of the axisymmetric swirl figures changed; regenerate docs/src/assets/axisym_mesh.png, " * + "axisym_core.png and axisym_swirl.fnv1a with `julia --project=docs examples/axisym_swirl/figures.jl`" + ) + end + if animation_sources_hash() != strip(read(joinpath(assets, "axisym_swirl_animation.fnv1a"), String)) + error( + "the sources of the axisymmetric swirl animation changed; regenerate docs/src/assets/axisym_swirl.gif " * + "and axisym_swirl_animation.fnv1a with `julia --project=docs examples/axisym_swirl/animation.jl`" + ) + end +end