import os
from pathlib import Path

# --8<-- [start:code]
"""The lid-driven cavity at Re = 200, from rest: transient incompressible Navier-Stokes.

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

The lid is regularised (peak 1 at x = 0.5, zero at the corners), so the problem is all-Dirichlet.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # the assembler builds in float64
run = jno.setup(__file__)
NU = 0.005  # Re = 1 * 1 / 0.005 = 200

d = jno.shape.rect(0, 0, 1, 1, size=0.025).domain(time=(0.0, 8.0, 81))
x, y, t = d.variable("interior", split=True)
xb, yb, _ = d.variable("boundary", split=True)
ci = d.variable("initial", split=True)

u = d.unknown.vector(2, order=2)  # Taylor-Hood velocity
p = d.unknown.scalar(name="p")  # and pressure
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)
dt = lambda w: w.bind(x=x, y=y, t=t).t
lid = jno.np.where(yb > 1 - 1e-6, 16 * xb**2 * (1 - xb) ** 2, 0.0)

fem = jno.fem(
    [
        dot(dt(u), v) + dot(dot(grad(u), u), v) + NU * ddot(grad(u), grad(v)) - p * div(v),  # momentum
        -q * div(u),  # continuity
        u(xb, yb)[0] - lid,  # the moving lid on top, no slip elsewhere
        u(xb, yb)[1] - 0.0,
        p.pin(),  # fix the pressure level
        u(*ci) - 0.0,  # start from rest
    ]
)
assert fem.is_transient and not fem.is_linear  # the convective term (u.grad)u makes it nonlinear
# backward Euler + Newton per step, one row of DOFs per time level; a saddle system, so solve it directly
traj = np.asarray(fem.solve(linear=jno.solve.lu()).eval())

pts = np.asarray(fem.points)
vel = traj[:, fem.offsets[0] : fem.offsets[1]].reshape(len(traj), -1, 2)
settle = np.linalg.norm(traj[-1] - traj[-2]) / np.linalg.norm(traj[-1])  # change over the last step
centre = np.abs(pts[:, 0] - 0.5) < 0.06
top = vel[-1, centre & (pts[:, 1] > 0.7), 0].mean()  # driven by the lid: u_x > 0
bottom = vel[-1, centre & (pts[:, 1] < 0.3), 0].mean()  # the return flow: u_x < 0
print(
    f"cavity Re={1 / NU:.0f}: dofs={fem.dofs}  last-step change {settle:.2e}  centre-line u_x top {top:+.3f} bottom {bottom:+.3f}"
)
assert settle < 2e-2 and top > 0.1 and bottom < -0.02  # steady, with a recirculating vortex
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "navier_stokes_cavity_2d.npz",
        points=pts[:, :2],
        vertices=np.asarray(d.built_mesh.points)[:, :2],
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        velocity=vel.astype(np.float32),
        t=np.linspace(float(fem.t0), float(fem.t1), len(traj)),
    )
