import os
from pathlib import Path

# --8<-- [start:code]
"""Stabilised equal-order Navier-Stokes: P1 velocity and P1 pressure, which is not an inf-sup-stable
pair, made to work by SUPG and PSPG written as ordinary weak-form terms. The exact solution is
Kovasznay (1948), so every number is checked against a closed form.

    (u.grad)u - nu lap u + grad p = 0,   div u = 0

tau after Tezduyar & Osawa, CMAME 190 (2000), Sec. 3; PSPG after Hughes, Franca & Balestra, CMAME 59 (1986).
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
NU, C_I = 0.05, 36.0  # C_I: inverse-estimate constant for linear elements
RE = 1 / NU
LAM = RE / 2 - np.sqrt(RE**2 / 4 + 4 * np.pi**2)

d = jno.shape.rect(-0.5, -0.5, 1.0, 1.5, size=0.03).domain()
x, y, _ = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)

u = d.unknown.vector(2)  # P1 velocity and P1 pressure: equal 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)

# tau is lagged: a coefficient, not part of the equation. G is the element metric J^-T J^-1.
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)  # the momentum strong residual

# SUPG and PSPG are the same residual against two test functions, so two terms; each takes the sign of its equation
momentum = momentum + tau * dot(adv(v, u), r_m)
continuity = continuity - tau * dot(grad(q), r_m)

fem = jno.fem(
    [
        momentum,
        continuity,
        u(xb, yb)[0] - (1 - jno.np.exp(LAM * xb) * jno.np.cos(2 * np.pi * yb)),  # the exact velocity on the boundary
        u(xb, yb)[1] - LAM / (2 * np.pi) * jno.np.exp(LAM * xb) * jno.np.sin(2 * np.pi * yb),
        p.pin(),  # the pressure is gauge-free
    ]
)
sol = np.asarray(fem.solve(nonlinear=jno.solve.newton(direct=True)))  # the matrix-free Newton diverges from rest

pts = np.asarray(fem.points)
px, py = pts[:, 0], pts[:, 1]
uv, ph = sol[: fem.offsets[1]].reshape(-1, 2), sol[fem.offsets[1] :]
u_ex = np.stack(
    [1 - np.exp(LAM * px) * np.cos(2 * np.pi * py), LAM / (2 * np.pi) * np.exp(LAM * px) * np.sin(2 * np.pi * py)], -1
)
p_ex = 0.5 * (1 - np.exp(2 * LAM * px))
e_u = np.sqrt(np.mean(np.sum((uv - u_ex) ** 2, axis=1)))
e_p = np.sqrt(np.mean(((ph - ph.mean()) - (p_ex - p_ex.mean())) ** 2))  # compared up to the gauge
print(
    f"Kovasznay Re={RE:.0f}, P1/P1 + SUPG + PSPG: dofs={fem.dofs}  velocity RMS error {e_u:.3e}  pressure RMS error {e_p:.3e}"
)
assert e_u < 5e-2 and e_p < 1.5e-1
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "navier_stokes_stabilised_2d.npz",
        points=pts[:, :2],
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        velocity=uv.astype(np.float32),
        pressure=ph.astype(np.float32),
        box=np.array([-0.5, -0.5, 1.0, 1.5, RE]),
        errors=np.array([e_u, e_p]),
    )
