import os
from pathlib import Path

# --8<-- [start:code]
"""**Equal-order flow in 3-D** -- where the stabilised pair actually pays for itself.

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

In 2-D, Taylor-Hood P2/P1 costs about 2.9x the unknowns of stabilised P1/P1. In 3-D the gap is wider,
because a P2 tetrahedron carries 10 nodes to P1's 4: about 5x on the same mesh. The head-to-head below
runs both pairs on a structured N = 6 cube.

This is the same formulation as the 2-D stabilised tutorial -- SUPG on momentum, PSPG on continuity,
`dom.cell_metric` for a direction-aware `tau` -- written for three dimensions by changing the
coordinate list and `value_shape`. Nothing else about it is 3-D-specific.

The mesh is **structured**, so the vertical centreline x = y = 0.5 carries nodes of both the P1 and
the P2 velocity space and the two solutions can be compared where they both live, with no
interpolation in the comparison itself.
"""

import jax

jax.config.update("jax_enable_x64", True)

import numpy as np

import jno

run = jno.setup(__file__)

N = 6  # structured n x n x n cube; both discretisations must fit a direct solve together
C_I = 36.0
RE_LADDER = [5.0, 10.0, 25.0, 50.0, 100.0]


def cavity3d(n=N, order=1, stabilised=True):
    d = jno.shape.box(0, 0, 0, 1, 1, 1).structured(n=n).domain()
    x, y, z = d.variable("interior", split=True)[:3]
    top = d.variable("top", split=True)[:3]
    walls = [d.variable(side, split=True)[:3] for side in ("bottom", "left", "right", "front", "back")]

    nu = jno.np.parameter((1,), name="nu")
    u = d.unknown.vector(3, order=order)
    p = d.unknown.scalar(name="p")
    v, q = u.test(), p.test()

    grad = lambda w: jno.np.jacobian(w, [x, y, z])
    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 stabilised:
        G = d.cell_metric  # (3, 3) per quadrature point in 3-D: the symbol is dimension-generic
        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, z]) + grad(p)  # the VECTOR Laplacian, in 3-D
        momentum = momentum + tau * dot(adv(v, u), r_m)  # SUPG (+)
        continuity = continuity - tau * dot(grad(q), r_m)  # PSPG (-)

    # A lid driven in x, tapered to zero on all four top edges so the corners carry no singularity.
    lid = 16.0 * top[0] ** 2 * (1 - top[0]) ** 2 * 16.0 * top[1] ** 2 * (1 - top[1]) ** 2
    return d, jno.fem(
        [
            momentum,
            continuity,
            u(*top)[0] - lid,
            u(*top)[1] - 0.0,
            u(*top)[2] - 0.0,
            *[u(*w) - 0.0 for w in walls],
            p.pin(),
        ]
    )


def climb(fem):
    return np.asarray(
        fem.solve(
            nonlinear=jno.solve.newton(direct=True, rtol=1e-8, atol=1e-8),
            linear=jno.solve.lu(backend="host"),
            continuation=jno.solve.continuation(nu=[1.0 / r for r in RE_LADDER]),
        )
    )


def centreline(fem, sol, tol=1e-9):
    """`u_x` up the vertical centreline x = y = 0.5, at that field's own nodes."""
    pts = np.asarray(fem.points)
    uv = sol[fem.offsets[0] : fem.offsets[1]].reshape(len(pts), 3)
    on = (np.abs(pts[:, 0] - 0.5) < tol) & (np.abs(pts[:, 1] - 0.5) < tol)
    order = np.argsort(pts[on, 2])
    return pts[on, 2][order], uv[on, 0][order]


print(f"3-D lid-driven cavity, {N}x{N}x{N} structured tets, Re = {RE_LADDER[-1]:.0f}")

runs = {}
for label, order, stab in (("stabilised P1/P1", 1, True), ("Taylor-Hood P2/P1", 2, False)):
    d, fem = cavity3d(order=order, stabilised=stab)
    sol = climb(fem)
    runs[label] = (fem, sol)
    print(f"{label:<18}: {fem.dofs:6d} dofs")

fem_s, sol_s = runs["stabilised P1/P1"]
fem_t, sol_t = runs["Taylor-Hood P2/P1"]
print(f"\nTaylor-Hood costs {fem_t.dofs / fem_s.dofs:.1f}x the DOFs (a P2 tet carries 10 nodes to P1's 4)")

zs, ux_s = centreline(fem_s, sol_s)
zt, ux_t = centreline(fem_t, sol_t)
assert len(zs) > 3 and len(zt) > 3, "the centreline must carry nodes of both spaces"
ux_ref = np.interp(zs, zt, ux_t)  # sample the finer P2 profile at the P1 nodes
err = float(np.max(np.abs(ux_s - ux_ref)))
span = float(np.ptp(ux_ref))

print(f"\nCentreline u_x (x = y = 0.5), {len(zs)} P1 nodes vs {len(zt)} P2 nodes:")
print(f"  max deviation {err:.4f}  ({100 * err / span:.1f}% of the profile range {span:.4f})")
print(
    f"  extrema   equal-order {ux_s.min():+.4f} / {ux_s.max():+.4f}   Taylor-Hood {ux_ref.min():+.4f} / {ux_ref.max():+.4f}"
)

assert err < 0.15 * span, f"equal-order disagrees with the stable pair by {err:.3f} ({100 * err / span:.0f}%)"
print("\nEqual-order tracks the stable pair in 3-D, at a fifth of the degrees of freedom.")
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/cavity_3d_equal_order.py), only when asked ----
# The head-to-head above stays at N = 6; the figure is the stabilised pair on a finer cube.
if out := os.environ.get("JNO_FIGURE_DATA"):
    NFIG = int(os.environ.get("NFIG", 20))
    fem = cavity3d(n=NFIG)[1]
    sol = climb(fem)
    pts = np.asarray(fem.points)
    uv = sol[fem.offsets[0] : fem.offsets[1]].reshape(len(pts), 3)
    i = np.rint(pts * NFIG).astype(int)  # the structured lattice: node (ix, iy, iz)
    field = np.zeros((NFIG + 1,) * 3 + (3,))  # indexed [ix, iy, iz]
    field[i[:, 0], i[:, 1], i[:, 2]] = uv
    print(f"figure run: {NFIG}^3 cube, {fem.dofs} dofs")
    np.savez_compressed(Path(out) / "cavity_3d_equal_order.npz", u=field.astype(np.float32), n=NFIG, re=RE_LADDER[-1])
