import os
from pathlib import Path

# --8<-- [start:code]
"""How far the stabilised pair goes: the lid-driven cavity from Re = 100 to Re = 5000 on equal-order
P1/P1, reached by continuation in the Reynolds number, and checked against Taylor-Hood P2/P1.

    (u.grad)u - nu lap u + grad p = 0,   div u = 0,   Re = U L / nu

The lid is regularised (16 x^2 (1-x)^2): a constant lid puts a pressure singularity in each top corner.
This is not a Ghia et al. (1982) comparison, which uses a constant lid; it checks the unstable pair
against the stable one on the same mesh.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
N, C_I = 64, 36.0  # the mesh is N x N; C_I is the inverse-estimate constant for linear elements
RE_LADDER = [*range(100, 1000, 25), *range(1000, 2000, 50), *range(2000, 5001, 100)]  # 87 rungs


def cavity(order):
    """The cavity with nu left as a runtime parameter, so a continuation can sweep it."""
    d = jno.shape.rect(0, 0, 1, 1).structured(n=N).domain()
    x, y, _ = d.variable("interior", split=True)
    xl, yl, _ = d.variable("top", split=True)  # the lid
    xw, yw, _ = d.variable("walls", where=lambda x, y: (y < 1e-9) | (x < 1e-9) | (x > 1 - 1e-9), split=True)
    nu = jno.np.parameter((1,), name="nu")

    u = d.unknown.vector(2, order=order)
    p = d.unknown.scalar(name="p")
    v, q = u.test(), p.test()
    grad = lambda w: jno.np.jacobian(w, [x, y])
    div = lambda w: jno.np.trace(grad(w))
    dot, ddot = jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)
    adv = lambda w, b: dot(grad(w), b)  # (b . grad) w

    momentum = dot(adv(u, u), v) + nu * ddot(grad(u), grad(v)) - p * div(v)
    continuity = -q * div(u)
    if order == 1:  # equal order is not inf-sup stable: SUPG and PSPG, as in the stabilised-flow tutorial
        G = d.cell_metric
        tau = jno.lag((dot(u, dot(G, u)) + C_I * nu**2 * ddot(G, G)) ** -0.5)
        r_m = adv(u, u) - nu * jno.np.laplacian(u, [x, y]) + grad(p)
        momentum = momentum + tau * dot(adv(v, u), r_m)
        continuity = continuity - tau * dot(grad(q), r_m)

    return d, jno.fem(
        [
            momentum,
            continuity,
            u(xl, yl)[0] - 16 * xl**2 * (1 - xl) ** 2,  # regularised: zero at both top corners
            u(xl, yl)[1] - 0.0,
            u(xw, yw) - 0.0,
            p.pin(),
        ]
    )


def climb(fem, ladder, keep):
    """Climb the Reynolds ladder, warm-starting each rung from the one below: one solve, one compilation."""
    newton, lu = jno.solve.newton(direct=True, rtol=1e-9, atol=1e-9), jno.solve.lu(backend="host")
    continuation = jno.solve.continuation(nu=[1 / re for re in ladder], keep=keep)  # raises on a rung that fails
    return np.asarray(fem.solve(nonlinear=newton, linear=lu, continuation=continuation))


def profiles(fem, sol):
    """u_x along x = 0.5 and u_y along y = 0.5, as (coordinate, value) sorted along the line."""
    pts = np.asarray(fem.points)
    uv = sol[: fem.offsets[1]].reshape(len(pts), 2)
    on_x, on_y = np.abs(pts[:, 0] - 0.5) < 1e-9, np.abs(pts[:, 1] - 0.5) < 1e-9
    i, j = np.argsort(pts[on_x, 1]), np.argsort(pts[on_y, 0])
    return pts[on_x, 1][i], uv[on_x, 0][i], pts[on_y, 0][j], uv[on_y, 1][j]


d, fem = cavity(order=1)
family = climb(fem, RE_LADDER, keep="all")  # (rungs, dofs)
print(f"cavity {N}x{N}, stabilised P1/P1: dofs={fem.dofs}, reached Re = {RE_LADDER[-1]}")
for re in (100, 400, 1000, 2000, 5000):
    _, ux, _, uy = profiles(fem, family[RE_LADDER.index(re)])
    print(f"  Re {re:5d}   min u_x on x=0.5 {ux.min():+.4f}   u_y on y=0.5 {uy.min():+.4f} .. {uy.max():+.4f}")

# Taylor-Hood on the same mesh at Re = 1000
fem_t = cavity(order=2)[1]
ys, ux_s, xs, uy_s = profiles(fem, family[RE_LADDER.index(1000)])
yt, ux_t, xt, uy_t = profiles(fem_t, climb(fem_t, [100, 200, 400, 700, 1000], keep="last"))
e_u, e_v = np.abs(ux_s - np.interp(ys, yt, ux_t)).max(), np.abs(uy_s - np.interp(xs, xt, uy_t)).max()
span = max(np.ptp(ux_t), np.ptp(uy_t))
print(
    f"Re 1000 against Taylor-Hood (dofs={fem_t.dofs}, {fem_t.dofs / fem.dofs:.1f}x): max |du_x| {e_u:.4f} ({100 * e_u / span:.1f}%)  max |du_y| {e_v:.4f} ({100 * e_v / span:.1f}%)"
)
assert e_u < 0.10 * span and e_v < 0.10 * span  # equal order tracks the stable pair
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "cavity_high_reynolds.npz",
        points=np.asarray(fem.points)[:, :2],
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        velocity=family[:, : fem.offsets[1]].reshape(len(RE_LADDER), -1, 2).astype(np.float32),
        reynolds=np.array(RE_LADDER),
    )
