#=

# 255 : Adaptive Stokes Problem with Pressure-Robust Error Estimator
([source code](@__SOURCE_URL__))

Solves the Stokes problem ``-\nu \Delta u + \nabla p = f``, ``\nabla \cdot u = 0`` on an L-shaped domain
with a singular manufactured solution. The velocity is discretized by Bernardi-Raugel elements (``H1BR\{2\}``),
the pressure by piecewise constants (``L2P0``). A reconstruction operator ``\Pi_H : H1BR\{2\} \to RT_0(H(\mathrm{div}))``
renders the load term discretely divergence-free, and a pressure-robust residual-type a posteriori error
estimator ``\eta`` drives adaptive mesh refinement. Its terms are the data term ``h^2\|\mathrm{curl}\,f\|``
(alternatively ``h\|f\|`` without reconstruction), the consistency terms ``\|\mathrm{div}\,u_h\|`` and
``\|\Delta u_h\|`` and the face jump terms ``\|[[\nabla u_h \cdot n]]\|`` and
``\|[[\Delta u_h \cdot t]]\|``, each with the appropriate mesh-size weighting
(see reference below for details). Since the load enters only through its curl, ``\eta`` (and hence the
energy error bound) is independent of the viscosity ``\nu``.

!!! reference

	"Refined a posteriori error estimation for classical and pressure-robust Stokes finite element methods",\
	P.L. Lederer, C. Merdon, J. Schöberl,\
	Numerische Mathematik 142, 713–748 (2019),\
	[>Journal-Link<](https://doi.org/10.1007/s00211-019-01049-3)

With ``\nu`` small, running `main(; reconstruct = false)` demonstrates the effect of dropping the
reconstruction: the load term is not discretely divergence-free anymore, and the velocity error is
polluted by the pressure oscillation ``\nu^{-1}\|p - \Pi_0 p\|``.

The resulting solution, adaptive mesh and convergence history for the default parameters look like:

![](example255.png)

=#
module Example255_AdaptiveStokesProblem

using ExtendableFEM
using ExtendableGrids
using GridVisualize
using LinearAlgebra
using Test #hide
import Term
import Symbolics
using Symbolics: @variables, build_function

## computes evaluatable functions for the singular exact solution on the L-shaped domain
## (given in polar coordinates r, ϕ) and the corresponding right-hand side data
function prepare_data(; ν::Real)
    @variables ϕ r

    ## corner singularity exponent α ≈ 0.544 of the Stokes problem at a reentrant corner of angle ω = 3π/2
    α = 856399 / 1572864
    ω = 3 * pi / 2
    ψ = (1 / (α + 1)) * sin((α + 1) * ϕ) * cos(α * ω) - cos((α + 1) * ϕ)
    dψ_dϕ = Symbolics.derivative(ψ, ϕ)
    d3ψ_dϕ3 = Symbolics.derivative(Symbolics.derivative(dψ_dϕ, ϕ), ϕ)
    p0 = -ν * r^(α - 1) * ((1 + α)^2 * dψ_dϕ + d3ψ_dϕ3) / (1 - α)
    u = [
        r^α * ((α + 1) * sin(ϕ) * ψ + cos(ϕ) * dψ_dϕ),
        r^α * (sin(ϕ) * dψ_dϕ - (α + 1) * cos(ϕ) * ψ),
    ]
    ∇u_rϕ = Symbolics.jacobian(u, [r, ϕ])
    ∇u = [
        ∇u_rϕ[1, 1] * cos(ϕ) - ∇u_rϕ[1, 2] * sin(ϕ) / r ∇u_rϕ[1, 1] * sin(ϕ) + ∇u_rϕ[1, 2] * cos(ϕ) / r;
        ∇u_rϕ[2, 1] * cos(ϕ) - ∇u_rϕ[2, 2] * sin(ϕ) / r ∇u_rϕ[2, 1] * sin(ϕ) + ∇u_rϕ[2, 2] * cos(ϕ) / r
    ]
    ∇u_reshaped = [∇u[1, 1], ∇u[1, 2], ∇u[2, 1], ∇u[2, 2]]

    ## extra pressure to make it more interesting for pressure-robustness
    p_plus = sin(r^2 * cos(ϕ) * sin(ϕ) * pi) # = sin(πxy), a smooth oscillating term
    ∇p_plus_rϕ = Symbolics.gradient(p_plus, [r, ϕ])
    f = [
        ∇p_plus_rϕ[1] * cos(ϕ) - ∇p_plus_rϕ[2] * sin(ϕ) / r,
        ∇p_plus_rϕ[1] * sin(ϕ) + ∇p_plus_rϕ[2] * cos(ϕ) / r,
    ]
    curl_f = 0 * r  # forcing f = ∇p_plus is irrotational
    ## exact pressure = singular part p0 ~ ν r^(α-1) + oscillating part p_plus, shifted to zero mean
    p = p0 + p_plus - 1 / 3 * 0.52466306757531903964

    function map_cartesian_to_polar(qpinfo)
        x, y = qpinfo.x
        return sqrt(x^2 + y^2), (2 * pi + atan(y, x)) % (2 * pi)
    end

    function map_expression_to_eval_func(expr)::Function
        compiled = build_function(expr, r, ϕ, expression = Val{false})
        eval_func! = isa(compiled, Tuple) ? compiled[2] : (result, values...) -> (result[1] = compiled(values...))
        return (result, qpinfo) -> eval_func!(result, map_cartesian_to_polar(qpinfo)...)
    end

    data = map(map_expression_to_eval_func, [u, ∇u_reshaped, p, f, curl_f])
    return (exact_u! = data[1], exact_∇u! = data[2], exact_p! = data[3], rhs! = data[4], exact_curl_f! = data[5])
end

## kernel function for face interpolation of normal jumps of gradient
function gradnormalflux_kernel!(result, ∇u, qpinfo)
    result .= [∇u[1] ∇u[2]; ∇u[3] ∇u[4]] * qpinfo.normal
    return nothing
end

## kernel function for face interpolation of tangential jumps of the Laplacian
function laplacetangentflux_kernel!(result, Δu, qpinfo)
    result .= Δu[1] * qpinfo.normal[2] - Δu[2] * qpinfo.normal[1]
    return nothing
end

## kernel for a posteriori error terms of the form h^p ||.||^2
η_kernel(p) = (result, v, qpinfo) -> (result .= qpinfo.volume^p * sum(v .^ 2))

function main(;
        ν::Real = 10^-3,
        reconstruct::Bool = true,
        maxdofs::Int = 5000,
        bonus_quadorder::Int = 5,
        Plotter = nothing,
        kwargs...,
    )
    @assert ν > 0
    xgrid = uniform_refine(grid_lshape(Triangle2D), 2)
    (; exact_u!, exact_∇u!, exact_p!, rhs!, exact_curl_f!) = prepare_data(; ν)

    ## kernel function for the Stokes problem
    function stokes_kernel!(result, input, _)
        result[1] = ν * input[1] - input[5]
        result[2] = ν * input[2]
        result[3] = ν * input[3]
        result[4] = ν * input[4] - input[5]
        result[5] = -(input[1] + input[4])
        return nothing
    end

    ## kernel functions for error calculations
    function velocity_error!(result, u, qpinfo)
        exact_u!(view(result, 1:2), qpinfo)
        exact_∇u!(view(result, 3:6), qpinfo)
        result .-= u
        result .= result .^ 2
        return nothing
    end

    function pressure_error!(result, p, qpinfo)
        exact_p!(view(result, 1), qpinfo)
        result .-= p
        result .= result .^ 2
        return nothing
    end

    ## kernel function for calculation of η_curl a posteriori error term
    function η_curl_kernel!(result, _, qpinfo)
        exact_curl_f!(view(result, 1), qpinfo)
        result .= qpinfo.volume^2 * result .^ 2
        return nothing
    end

    ## non-reconstructed loads are not discretely divergence-free, so the data term
    ## must resolve the full load f (h‖f‖) instead of its curl (h²‖curl f‖)
    function η_f_kernel!(result, _, qpinfo)
        fvals = zeros(2)
        rhs!(fvals, qpinfo)
        result .= qpinfo.volume * sum(fvals .^ 2)
        return nothing
    end

    ## unknowns, interpolators and item integrators for error estimation and calculation
    u = Unknown("u", name = "velocity", symbol_ansatz = "u", symbol_test = "v", dim = 2)
    p = Unknown("p", name = "pressure", symbol_ansatz = "p", symbol_test = "q", dim = 1)
    Δu = Unknown("Δu", name = "Laplacian of velocity", dim = 1)

    exact_velocity_error_integrator = ItemIntegrator(velocity_error!, [id(u), grad(u)]; quadorder = bonus_quadorder, kwargs...)
    exact_pressure_error_integrator = ItemIntegrator(pressure_error!, [id(p)]; quadorder = bonus_quadorder, kwargs...)
    η_curl_integrator = ItemIntegrator(η_curl_kernel!; resultdim = 1, quadorder = bonus_quadorder, kwargs...)
    η_f_integrator = ItemIntegrator(η_f_kernel!; resultdim = 1, quadorder = bonus_quadorder, kwargs...)
    η_data_integrator = reconstruct ? η_curl_integrator : η_f_integrator
    η_cons0_integrator = L2NormIntegrator([div(u)]; quadorder = bonus_quadorder, kwargs...)
    η_cons1_integrator = ItemIntegrator(η_kernel(1), [id(Δu)]; resultdim = 1, quadorder = bonus_quadorder)
    η_jump_integrator = ItemIntegrator(η_kernel(1), [id(1)]; resultdim = 1, quadorder = bonus_quadorder, entities = ON_FACES, kwargs...)
    normal_jump_projector = FaceInterpolator(gradnormalflux_kernel!, [jump(grad(u))]; resultdim = 2, quadorder = bonus_quadorder, only_interior = true, kwargs...)
    η_jump2_integrator = ItemIntegrator(η_kernel(3), [id(1)]; resultdim = 1, quadorder = bonus_quadorder, entities = ON_FACES, kwargs...)
    tangent_jump_projector = FaceInterpolator(laplacetangentflux_kernel!, [jump(id(Δu))]; resultdim = 1, quadorder = bonus_quadorder, entities = ON_FACES, kwargs...)

    ## pressure-robust load term: evaluate f on RT0 reconstructions of the test functions
    id_u = reconstruct ? apply(u, Reconstruct{HDIVRT0{2}, Identity}) : id(u)

    # initialize data structures for loop
    ndofs, u_l2error_results, ∇u_l2error_results, p_l2error_results, η_results = Int[], Float64[], Float64[], Float64[], Float64[]
    sol = nothing # (assigned in loop, needed after it)

    ## SOLVE -> ESTIMATE -> MARK -> REFINE loop
    ## (problem description must be recreated on each refined grid)
    for level in Iterators.countfrom(1)
        PD = ProblemDescription("Stokes problem")
        assign_unknown!(PD, u)
        assign_unknown!(PD, p)
        assign_operator!(PD, BilinearOperator(stokes_kernel!, [grad(u), id(p)]))
        assign_operator!(PD, LinearOperator(rhs!, [id_u]; bonus_quadorder))
        assign_operator!(
            PD,
            InterpolateBoundaryData(u, exact_u!; regions = 1:8, bonus_quadorder)
        )
        assign_restriction!(PD, ZeroMeanValueRestriction(p))

        ## SOLVE
        @time begin
            FES = [FESpace{H1BR{2}}(xgrid), FESpace{L2P0{1}}(xgrid)] # use BR finite element pair
            sol = solve(PD, FES)
            push!(ndofs, length(sol[1]) + length(sol[2]))
            println("\t ndof = ", ndofs[level])
            print("@time solver =")
        end

        ## calculate exact errors
        error = evaluate(exact_velocity_error_integrator, sol)
        push!(u_l2error_results, sqrt(sum(view(error, 1, :)) + sum(view(error, 2, :))))
        push!(∇u_l2error_results, sqrt(sum(sum(view(error, 3:6, :)))))
        evaluate!(error, exact_pressure_error_integrator, sol)
        push!(p_l2error_results, sqrt(sum(view(error, 1, :))))

        append!(sol, FESpace{L2P0{2}}(xgrid); tag = Δu)
        lazy_interpolate!(sol[Δu], sol, [Δ(u)]) # calculation of Δu ≡ (div ∘ ∇)u

        ## ESTIMATE : remaining terms of the a posteriori error bound
        normal_jumps_for_faces = evaluate!(normal_jump_projector, sol)
        η = evaluate(η_jump_integrator, normal_jumps_for_faces)
        η_cells = evaluate(η_cons0_integrator, sol) + evaluate(η_data_integrator, sol)
        if reconstruct
            tangent_jumps_for_faces = evaluate!(tangent_jump_projector, sol)
            η += evaluate(η_jump2_integrator, tangent_jumps_for_faces)
            η_cells += evaluate(η_cons1_integrator, sol)
        end

        ## distribute cell contributions to faces
        for (index, face) in enumerate(eachcol(xgrid[FaceCells]))
            η[index] += η_cells[face[1]]
            if face[2] > 0
                η[index] += η_cells[face[2]]
            end
        end
        push!(η_results, sqrt(sum(η)))

        println(
            "\t    η =  $(η_results[level])" *
                "\n\t    ||u - u_h|| =  $(u_l2error_results[level])" *
                "\n\t    ||∇(u - u_h)|| =  $(∇u_l2error_results[level])" *
                "\n\t    ||p - p_h|| =  $(p_l2error_results[level])"
        )

        if ndofs[level] >= maxdofs || (level >= 2 && ndofs[level - 1] == ndofs[level])
            break
        end

        ## MARK+REFINE : Dörfler marking (θ = 0.5) of faces + red-green-blue refinement
        @time begin
            facemarker = bulk_mark(xgrid, view(η, :), 0.5; indicator_AT = ON_FACES)
            xgrid = RGB_refine(xgrid, facemarker)
            print("@time refine =")
        end
    end

    ## plot solution, final mesh and convergence history
    plt = GridVisualizer(; Plotter, layout = (2, 2), clear = true, size = (1000, 800))
    vectorplot!(plt[1, 1], id(u), sol; title = "u_h")
    scalarplot!(plt[1, 2], id(p), sol; title = "p_h")
    gridplot!(plt[2, 1], xgrid; linewidth = 1, title = "adaptively refined mesh")
    plot_convergencehistory!(plt[2, 2], ndofs, [u_l2error_results ∇u_l2error_results p_l2error_results η_results]; add_h_powers = [1, 2], X_to_h = X -> X .^ (-1 / 2), ylabels = ["|| u - u_h ||", "|| ∇(u - u_h) ||", "|| p - p_h ||", "η"])
    reveal(plt)

    ## print convergence history
    print_convergencehistory(
        ndofs,
        [u_l2error_results ∇u_l2error_results p_l2error_results η_results];
        X_to_h = X -> X .^ (-1 / 2),
        ylabels = ["|| u - u_h ||", "|| ∇(u - u_h) ||", "|| p - p_h ||", "η"],
    )

    return sol, plt
end

generateplots = ExtendableFEM.default_generateplots(Example255_AdaptiveStokesProblem, "example255.png") #hide
function runtests() #hide
    sol, plt = main(; maxdofs = 800) #hide
    @test length(sol.entries) > 500 #hide
    return nothing #hide
end #hide
end # module
