Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,5 @@ Manifest.toml
docs/src/discretization.md
# Generated by docs/make.jl when the front end is available.
docs/src/showcase.md
docs/src/assets/showcase.gif
# Rendered from benchmarks/results by docs/make.jl.
docs/src/benchmarks.md
98 changes: 97 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# FiniteElementMethod.jl

![Heat spreading from a pulsing heated hole through a plate and cooling through its right edge](https://docs.sciml.ai/FiniteElementMethod/dev/assets/showcase.gif)
![Heat spreading from a pulsing heated hole through a plate and cooling through its right edge](https://raw.githubusercontent.com/SciML/FiniteElementMethod.jl/master/docs/src/assets/showcase.gif)

FiniteElementMethod.jl solves PDEs written in strong form with
[ModelingToolkit.jl](https://docs.sciml.ai/ModelingToolkit/stable/) on unstructured meshes. Write
Expand Down Expand Up @@ -50,6 +50,102 @@ declare it with `FEMDiscretization(Ω, t; natural = [Γ_out])`, or make the warn
`add_boundary_pieces!(grid, :inlet => inlet_mesh)`. See
[boundary conditions](https://docs.sciml.ai/FiniteElementMethod/stable/boundary_conditions/).

## Navier–Stokes

![Speed and vorticity of the flow past a cylinder](https://raw.githubusercontent.com/SciML/FiniteElementMethod.jl/master/docs/src/assets/ns_showcase.png)

![The flow past a cylinder starting from rest: speed above, vorticity below](https://raw.githubusercontent.com/SciML/FiniteElementMethod.jl/master/docs/src/assets/ns_showcase.gif)

The incompressible Navier–Stokes equations are one more strong-form `PDESystem`: three equations
for the velocity components `u`, `v` and the pressure `p`, discretized with Q2/Q1 Taylor–Hood
elements and integrated as an index-2 DAE. The flow starts at rest in the
[DFG benchmark](https://docs.sciml.ai/FiniteElementMethod/stable/navier_stokes/) channel with a
cylinder, at Reynolds number 100 (the inflow of case 2D-2), and sheds a vortex street. The
images above are rendered by the two code blocks below, which `examples/ns_showcase.jl` runs
as written (a test fails when they change without the images being regenerated).
It is a showcase on a coarse mesh: the measured Strouhal number is about 0.3, the benchmark's
value, but the run is not validated against the benchmark's shedding data. The steady Reynolds
number 20 case (2D-1) is the one checked against its drag, lift and pressure difference.

```julia
using FiniteElementMethod, ModelingToolkit, DomainSets, OrdinaryDiffEqBDF
using OrdinaryDiffEqBDF: NLNewton
using LinearSolve: UMFPACKFactorization
using SciMLBase: CheckInit
using ModelingToolkit: t_nounits as t

include(pkgdir(FiniteElementMethod, "examples", "dfg_cylinder", "mesh.jl")) # dfg_channel_grid: Gmsh quadrilaterals, curved cylinder

@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))
Γ_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), # incompressibility: no equation for p
]
inflow = (1 - exp(-t^2)) * 4Umax * y * (0.41 - y) / 0.41^2 # parabolic, ramped up from rest
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, # no slip
p(t, Γ_out) ~ 0, # fixes the pressure level at the outlet
u(0, x, y) ~ 0, v(0, x, y) ~ 0,
]
tend = 6.0
domains = [(x, y) ∈ Ω, t ∈ Interval(0.0, tend)]
@named dfg = PDESystem(eqs, bcs, domains, [t, x, y], [U, V, P], [ν => 1.0e-3, Umax => 1.5])

Q2, Q1 = Lagrange{RefQuadrilateral, 2}(), Lagrange{RefQuadrilateral, 1}()
disc = FEMDiscretization(
Ω, t; spaces = Dict(u => Q2, v => Q2, p => Q1),
pairing = Dict(eqs[3] => p), natural = [Γ_out], initializealg = CheckInit()
)
prob = DAEProblem(dfg, disc)
abstol = [differential ? 1.0e-6 : 1.0e8 for differential in prob.differential_vars] # no error control on p
sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFPACKFactorization()); abstol, reltol = 1.0e-6)
sol(tend, 0.6, 0.2; dv = v(t, x, y)) # the cross-stream velocity in the wake
```

The solution is then resampled on a regular grid with `sol(ts, xs, ys; dv)`, which returns `NaN`
inside the cylinder, and plotted with [Makie](https://docs.makie.org). CairoMakie is not a
dependency of FiniteElementMethod: install it with `using Pkg; Pkg.add("CairoMakie")`, then run this
block in the same session as the block above, in the directory that should receive the two images.

```julia
using CairoMakie

xs, ys = range(0, 2.2; length = 440), range(0, 0.41; length = 82) # a regular grid over the channel
ts = range(0, tend; length = 90)
u_field = sol(collect(ts), collect(xs), collect(ys); dv = u(t, x, y)) # time × nx × ny
v_field = sol(collect(ts), collect(xs), collect(ys); dv = v(t, x, y))
speed = hypot.(u_field, v_field)
vorticity = fill(NaN, size(u_field)) # ∂ₓv − ∂ᵧu, central differences
i, j = 2:(length(xs) - 1), 2:(length(ys) - 1)
@views vorticity[:, i, j] .= (v_field[:, i .+ 1, j] .- v_field[:, i .- 1, j]) ./ 2step(xs) .-
(u_field[:, i, j .+ 1] .- u_field[:, i, j .- 1]) ./ 2step(ys)

frame = Observable(length(ts))
fig = Figure(size = (720, 350))
axis_options = (; aspect = DataAspect(), xlabel = "x", ylabel = "y")
top = Axis(fig[1, 1]; title = @lift("t = $(round(ts[$frame]; digits = 2))"), axis_options...)
bottom = Axis(fig[2, 1]; axis_options...)
speed_map = heatmap!(top, xs, ys, @lift(speed[$frame, :, :]); colormap = :viridis, colorrange = (0, 1.6), nan_color = :white)
vorticity_map = heatmap!(bottom, xs, ys, @lift(vorticity[$frame, :, :]); colormap = :balance, colorrange = (-40, 40), nan_color = :white)
Colorbar(fig[1, 2], speed_map; label = "speed |u|")
Colorbar(fig[2, 2], vorticity_map; label = "vorticity")

save("ns_showcase.png", fig; px_per_unit = 2) # the flow at the final time
record(fig, "ns_showcase.gif", eachindex(ts); framerate = 18, px_per_unit = 1) do index
frame[] = index
end
```

## Benchmarks

Accuracy per degree of freedom against MethodOfLines, assembly cost against hand-written Ferrite,
Expand Down
12 changes: 10 additions & 2 deletions docs/Project.toml
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
[deps]
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
DomainSets = "5b8099bc-c8ec-5219-889f-1d9e522a28bf"
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
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"
LinearSolve = "7ed4a6bd-45f5-4d41-b270-4a48e9bafcae"
ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78"
OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
SciMLBase = "0bca4576-84f4-4d90-8ffe-ffa030f20462"
TOML = "fa267f1f-6049-4f14-aa54-33bafae1ed76"

[compat]
CairoMakie = "0.15"
DomainSets = "0.7, 0.8"
Documenter = "1"
DomainSets = "0.7, 0.8"
Ferrite = "1.7"
FerriteGmsh = "1.5"
FiniteElementMethod = "0.1"
Gmsh = "0.3"
LinearSolve = "5"
ModelingToolkit = "11"
OrdinaryDiffEqBDF = "2.4"
Printf = "1"
SciMLBase = "3"
TOML = "1"
16 changes: 10 additions & 6 deletions docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ using Documenter, FiniteElementMethod

include("pages.jl")

# The README showcase animation, rendered from the README's own code block (examples/showcase.jl)
# and hosted at assets/showcase.gif, the URL the README embeds.
# The README showcase animation is rendered from the README's own code block (examples/showcase.jl). The committed
# copy in docs/src/assets is what the README and the Showcase page show; this build re-runs the block into a scratch
# directory to check that it still runs in the documentation environment.
showcase_page = joinpath(@__DIR__, "src", "showcase.md")
include(joinpath(@__DIR__, "..", "examples", "showcase.jl"))
mkpath(joinpath(@__DIR__, "src", "assets"))
# invokelatest: record_showcase is defined by the include above.
Base.invokelatest(record_showcase, joinpath(@__DIR__, "src", "assets", "showcase.gif"))
# invokelatest: render_showcase_assets is defined by the include above.
Base.invokelatest(render_showcase_assets, mktempdir())
cp(joinpath(@__DIR__, "showcase.md"), showcase_page; force = true)
insert!(pages, 2, "Showcase" => "showcase.md")
# The README's Navier–Stokes figure and animation come from its second and third code blocks (examples/ns_showcase.jl).
# The committed copies in docs/src/assets are what the README and the Navier–Stokes page show; this build re-runs the
# blocks into a scratch directory to check that they still run in the documentation environment.
include(joinpath(@__DIR__, "..", "examples", "ns_showcase.jl"))
Base.invokelatest(render_ns_showcase, mktempdir())
# The benchmark page is rendered from benchmarks/results/*.toml at build time (benchmarks/render.jl).
include(joinpath(@__DIR__, "..", "benchmarks", "render.jl"))
write(joinpath(@__DIR__, "src", "benchmarks.md"), render(joinpath(@__DIR__, "..", "benchmarks", "results")))
Expand Down
1 change: 1 addition & 0 deletions docs/src/assets/ns_showcase.fnv1a
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a3eb010d9c375841
Binary file added docs/src/assets/ns_showcase.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/src/assets/ns_showcase.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions docs/src/assets/showcase.fnv1a
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
143fc665d22ed918
Binary file added docs/src/assets/showcase.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions docs/src/navier_stokes.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ sol = solve(prob, DFBDF(nlsolve = NLNewton(new_W_dt_cutoff = 0), linsolve = UMFP
abstol, reltol = 1e-7)
```

## Vortex shedding at Reynolds number 100

![The flow past a cylinder starting from rest: speed above, vorticity below](assets/ns_showcase.gif)

![Speed and vorticity of the flow past a cylinder at the final time](assets/ns_showcase.png)

The same formulation with the inflow of DFG case 2D-2 (peak 1.5, Reynolds number 100) is the second
code block of the [README](https://github.com/SciML/FiniteElementMethod.jl#navierstokes), and the
figure and the animation above are rendered by its third block, the plotting, with
[`examples/ns_showcase.jl`](https://github.com/SciML/FiniteElementMethod.jl/blob/master/examples/ns_showcase.jl).
They are committed copies in `docs/src/assets`, the same files the README links to; a test fails
when the blocks change without them being regenerated, and the documentation build re-runs both blocks to check
that they still run. The velocity is sampled on a regular grid with `sol(ts, xs, ys; dv)`, which returns `NaN`
inside the cylinder, and the vorticity is a central difference of the sampled velocity. The flow
starts at rest, the wake behind the cylinder turns unstable and a von Kármán vortex street has
formed by `t = 6`. It is a showcase, not a validated 2D-2 run: the mesh is the coarse `h = 0.04`
mesh of the steady case above and the tolerance is `10⁻⁶`. The test suite checks only that the wake
sheds with a Strouhal number between 0.25 and 0.35 (measured 0.28 to 0.31, against about 0.3 for
the benchmark), not the benchmark's amplitudes or lift oscillation.

## Formulation choices

- **Outflow condition.** PDEBase's strong-form analysis integrates only second-order terms by
Expand Down
29 changes: 29 additions & 0 deletions examples/ns_showcase.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Renders the README's Navier–Stokes images: runs the README's second and third code blocks (the simulation and
# the plotting) in one module and writes ns_showcase.png, ns_showcase.gif and the checksum of the two blocks
# (ns_showcase.fnv1a, checked by test/Frontend/readme.jl) to a directory. By default that is docs/src/assets,
# where the committed copies the README links to live. To refresh them after changing the blocks, from the
# repository root, with the docs environment (it has CairoMakie):
#
# julia --project=docs examples/ns_showcase.jl
#
# The documentation build calls `render_ns_showcase` with a scratch directory, to check that the blocks run.
include(joinpath(@__DIR__, "readme_code.jl"))

const NS_ASSETS = joinpath(@__DIR__, "..", "docs", "src", "assets")

function render_ns_showcase(directory = NS_ASSETS)
mkpath(directory)
mod = Module(:ReadmeNavierStokes)
Core.eval(mod, :(include(path) = Base.include($mod, path)))
cd(directory) do
for block in (2, 3) # the plotting block uses the simulation block's `sol`, `u`, `v`, `t`, `x`, `y` and `tend`
Base.include_string(mod, readme_code(; block), "README.md, block $block")
end
end
write(joinpath(directory, "ns_showcase.fnv1a"), blocks_hash(2:3) * "\n")
return directory
end

if abspath(PROGRAM_FILE) == @__FILE__
render_ns_showcase(isempty(ARGS) ? NS_ASSETS : ARGS[1])
end
34 changes: 24 additions & 10 deletions examples/readme_code.jl
Original file line number Diff line number Diff line change
@@ -1,19 +1,33 @@
# The README's showcase code block, so that the test that runs it and the documentation build
# that animates it both use exactly what the README shows.

# The first ```julia block of the README.
function readme_code(readme = joinpath(@__DIR__, "..", "README.md"))
m = match(r"```julia\n(.*?)```"s, read(readme, String))
m === nothing && error("$readme has no ```julia block")
return m.captures[1]
# The `block`-th ```julia block of the README: 1 is the heat showcase, 2 the Navier–Stokes one.
function readme_code(readme = joinpath(@__DIR__, "..", "README.md"); block = 1)
blocks = collect(eachmatch(r"```julia\n(.*?)```"s, read(readme, String)))
length(blocks) < block && error("$readme has no ```julia block number $block")
return blocks[block].captures[1]
end

# Run the README block in a fresh module and return its `sol`, `u`, `x`, `y`, `t` and pieces as a
# named tuple. The bindings are read with invokelatest: they are newer than the caller's world.
function run_readme(readme = joinpath(@__DIR__, "..", "README.md"))
# Run a README block in a fresh module and return the bindings `names` (by default the heat showcase's
# `sol`, `u`, `x`, `y`, `t` and pieces) as a named tuple. The bindings are read with invokelatest: they
# are newer than the caller's world.
function run_readme(
readme = joinpath(@__DIR__, "..", "README.md"); block = 1,
names = (:sol, :u, :x, :y, :t, :Γ_in, :Γ_wall, :Γ_out)
)
mod = Module(:ReadmeShowcase)
Core.eval(mod, :(include(path) = Base.include($mod, path)))
Base.include_string(mod, readme_code(readme), readme)
names = (:sol, :u, :x, :y, :t, :Γ_in, :Γ_wall, :Γ_out)
Base.include_string(mod, readme_code(readme; block), readme)
return NamedTuple{names}(map(name -> Base.invokelatest(getglobal, mod, name), names))
end

# FNV-1a (64 bit) checksum of the README's code blocks numbered `blocks`, in plain Julia so that it needs no package.
# The images rendered from the blocks are committed with this checksum next to them, and a test fails when the blocks
# change without a re-render: the heat showcase is block 1, the Navier–Stokes simulation and plotting blocks 2 and 3.
function blocks_hash(blocks, readme = joinpath(@__DIR__, "..", "README.md"))
checksum = 0xcbf29ce484222325
for byte in codeunits(join(readme_code(readme; block) for block in blocks))
checksum = (checksum ⊻ byte) * 0x00000100000001b3
end
return string(checksum; base = 16, pad = 16)
end
23 changes: 17 additions & 6 deletions examples/showcase.jl
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# Renders the README showcase animation: runs the README's code block, resamples the solution on
# a regular grid with `sol(ts, xs, ys; dv)` (NaN in the holes) and records it with Makie.
# The documentation build calls `record_showcase` (docs/make.jl); to run it by hand, from an
# environment with FiniteElementMethod, CairoMakie, FerriteGmsh, OrdinaryDiffEqBDF,
# ModelingToolkit and DomainSets:
# a regular grid with `sol(ts, xs, ys; dv)` (NaN in the holes) and records it with Makie. The gif and the checksum
# of the README block (showcase.fnv1a, checked by test/Frontend/readme.jl) go to a directory, by default
# docs/src/assets, where the committed copies the README links to live. To refresh them after changing the block,
# from the repository root, with the docs environment (it has CairoMakie):
#
# julia --project=docs examples/showcase.jl showcase.gif
# julia --project=docs examples/showcase.jl
#
# The documentation build calls `render_showcase_assets` with a scratch directory, to check that the block runs.
using CairoMakie

include(joinpath(@__DIR__, "readme_code.jl"))
Expand All @@ -13,6 +15,15 @@ include(joinpath(@__DIR__, "readme_code.jl"))
# world, after the solve.
record_showcase(path; kwargs...) = Base.invokelatest(render_showcase, run_readme(), path; kwargs...)

const SHOWCASE_ASSETS = joinpath(@__DIR__, "..", "docs", "src", "assets")

function render_showcase_assets(directory = SHOWCASE_ASSETS)
mkpath(directory)
record_showcase(joinpath(directory, "showcase.gif"))
write(joinpath(directory, "showcase.fnv1a"), blocks_hash(1:1) * "\n")
return directory
end

function render_showcase(m, path; frames = 72, framerate = 12, resolution = (280, 140), size = (560, 300))
sol, u, t, x, y = m.sol, m.u, m.t, m.x, m.y
xs = range(0, 2; length = resolution[1])
Expand All @@ -33,5 +44,5 @@ function render_showcase(m, path; frames = 72, framerate = 12, resolution = (280
end

if abspath(PROGRAM_FILE) == @__FILE__
record_showcase(isempty(ARGS) ? "showcase.gif" : ARGS[1])
render_showcase_assets(isempty(ARGS) ? SHOWCASE_ASSETS : ARGS[1])
end
40 changes: 40 additions & 0 deletions test/Frontend/readme.jl
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,43 @@ using SciMLBase: SciMLBase
@test sol(6.0, 1.0, 0.9; dv = u(t, x, y)) > 0.1
@test isnan(sol(6.0, 0.65, 0.55; dv = u(t, x, y))) # the centre of the heated hole
end

@testset "README Navier–Stokes" begin
m = Base.invokelatest(run_readme; block = 2, names = (:sol, :u, :v, :x, :y, :t, :tend, :Γ_in, :Γ_cyl))
sol, u, v, x, y, t = m.sol, m.u, m.v, m.x, m.y, m.t
@test SciMLBase.successful_retcode(sol)
@test sol.t[end] == m.tend == 6.0
# No slip on the cylinder, and the parabolic inflow of peak 1.5 once the ramp 1 - exp(-t²) has saturated.
@test maximum(abs, sol[u(t, m.Γ_cyl)]) <= 1.0e-6 && maximum(abs, sol[v(t, m.Γ_cyl)]) <= 1.0e-6
@test maximum(sol[u(t, m.Γ_in)][end, :]) ≈ 1.5 atol = 1.0e-3
# The wake sheds: the cross-stream velocity behind the cylinder alternates sign with the DFG 2D-2
# Strouhal number f D / Ū ≈ 0.3 (measured 0.28-0.31 on this mesh; D = 0.1, mean inflow Ū = 1).
times = 4.0:0.01:6.0
probe = sol(collect(times), [0.6], [0.2]; dv = v(t, x, y))[:, 1, 1]
crossings = [times[k] for k in 1:(length(times) - 1) if probe[k] * probe[k + 1] < 0]
@test length(crossings) >= 8
half_period = (crossings[end] - crossings[1]) / (length(crossings) - 1)
@test 0.25 <= 0.1 / (2half_period) <= 0.35
end

@testset "README images are current" begin
assets = joinpath(@__DIR__, "..", "..", "docs", "src", "assets")
# The plotting block needs CairoMakie, which is not a test dependency: it must at least parse.
@test Meta.parseall(readme_code(; block = 3)) isa Expr
images = (
(name = "showcase", blocks = 1:1, files = ["showcase.gif"]),
(name = "ns_showcase", blocks = 2:3, files = ["ns_showcase.gif", "ns_showcase.png"]),
)
for (; name, blocks, files) in images
for file in [files; "$name.fnv1a"]
@test isfile(joinpath(assets, file))
end
recorded = strip(read(joinpath(assets, "$name.fnv1a"), String))
if blocks_hash(blocks) != recorded
error(
"the README code blocks $(collect(blocks)) changed; regenerate docs/src/assets/$(join(files, ", ")) " *
"and $name.fnv1a with `julia --project=docs examples/$name.jl` from the repository root"
)
end
end
end
Loading