import os
from pathlib import Path

# --8<-- [start:code]
"""An LES subgrid eddy viscosity, inside a real 3-D solve.

A subgrid model adds ``nu_t(grad u)`` to the molecular viscosity. It needs no library API: the filter
width is ``d.cell_size`` and the model is arithmetic on ``grad(u)``, so it goes in the term list like
any other coefficient. Three of them here:

* **Smagorinsky** (1963)                              nu_t = (Cs d)^2 |S|
* **Vreman**, Phys. Fluids 16 (2004) 3670, eq. (5)    nu_t = c sqrt(B_beta / (g:g))
* **WALE**, Nicoud & Ducros, Flow Turb. Combust. 62 (1999) 183, eq. (13)

THE POINT OF THIS SCRIPT is the property that separates them, measured on a SOLVED flow rather than on
a prescribed gradient. Two flows, because they answer different questions:

1. **Plane Couette, u = (z, 0, 0)** -- SIMPLE SHEAR: one non-zero velocity gradient, so the gradient
   tensor is nilpotent and both Vreman's B_beta and WALE's Sd:Sd vanish identically. There is no
   subgrid turbulence in a laminar shear layer, so the correct nu_t is ZERO. Smagorinsky reports a
   large one anyway, because |S| is non-zero in any shear -- the defect Van Driest damping exists to
   patch. This is the discriminating case.
2. **Lid-driven cavity at Re = 100** -- a general 3-D strain field with recirculation. Here the models
   SHOULD act: B_beta and Sd:Sd are non-zero, and a laminar cavity is not a case any of them claims to
   vanish on. Measuring it shows the models are live and how far they move a real answer, and stops
   case 1 being mistaken for "these models never do anything".

SCOPE, up front: this is a wall-bounded LAMINAR demonstration that the models behave as designed
inside a Newton solve. It is **not validated LES** -- that needs a turbulent benchmark against DNS
(channel flow, decaying isotropic turbulence), which this has not run and does not claim.
"""

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
C_I, NU = 36.0, 1.0e-2  # Re = U L / nu with U = L = 1
CS, CV, CW, EPS = 0.17, 0.07, 0.325, 1e-30

# Both invariants below are non-negative in exact arithmetic and are computed as a DIFFERENCE of two
# nearly equal numbers, so round-off can push them just below zero -- and a negative one is not a small
# error but a NaN, through sqrt() and **1.5. Measured in pure shear: B_beta lands at 1.4e-20 where it
# should be 0, from a relative cancellation of 2.7e-16. The clamp is part of the model.
clamp = lambda z: jno.np.where(z > 0.0, z, 0.0)


def eddy_viscosity(name, g, delta, dim=3):
    """The three models, written through second invariants so one spelling serves 2-D and 3-D."""
    ss = jno.np.inner(jno.np.sym(g), jno.np.sym(g), n_contract=2)
    if name == "none":
        return 0.0
    if name == "smagorinsky":
        return (CS * delta) ** 2 * jno.np.sqrt(2.0 * ss)
    if name == "vreman":
        gg = jno.np.inner(g, g, n_contract=2)
        tr_b = delta**2 * gg  # tr(beta),  beta = delta^2 g gT
        tr_b2 = delta**4 * jno.np.einsum("...ik,...jk,...jl,...il->...", g, g, g, g)  # tr(beta^2)
        return CV * jno.np.sqrt(clamp(0.5 * (tr_b**2 - tr_b2)) / (gg + EPS) + EPS)
    if name == "wale":
        tr_g2 = jno.np.einsum("...ij,...ji->...", g, g)  # tr(g @ g)
        a1 = jno.np.einsum("...ik,...kj,...il,...lj->...", g, g, g, g)  # tr(g^2 (g^2)T)
        a2 = jno.np.einsum("...ik,...kj,...jl,...li->...", g, g, g, g)  # tr(g^2 g^2)
        sd = clamp(0.5 * (a1 + a2) - tr_g2**2 / dim)  # Sd:Sd, deviator never formed
        return (CW * delta) ** 2 * (sd**1.5 / (ss**2.5 + sd**1.25 + EPS))
    raise ValueError(f"unknown model {name!r}")


def solve(case, model, n=N):
    """Stabilised P1/P1 flow in the unit cube, plus a scalar block that PROJECTS nu_t so it can be read.

    The projection block is present in every variant, `none` included, so the systems being compared
    have identical structure and the difference between them is the model and nothing else. `couette`
    imposes u = (z, 0, 0) on the whole boundary (an exact solution, so the interior is pure simple shear);
    `cavity` drives the top face in x, tapered to zero on its edges.
    """
    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")]
    boundary = d.variable("boundary", split=True)[:3]

    u = d.unknown.vector(3)
    p, nut = d.unknown.scalar(name="p"), d.unknown.scalar(name="nut")
    v, q, w = u.test(), p.test(), nut.test()

    grad = lambda f: jno.np.jacobian(f, [x, y, z])
    div = lambda f: jno.np.trace(grad(f))
    dot, ddot = jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)
    adv = lambda f, b: dot(grad(f), b)  # (b . grad) f

    # LAGGED, and this is not optional: nu_t is a square root, so its slope at u = 0 is infinite and
    # Newton diverges outright from a rest state. Freezing it within each linearisation is the same
    # Picard treatment a Carman-Kozeny drag needs.
    nu_t = jno.lag(eddy_viscosity(model, grad(u), d.cell_size))
    momentum = dot(adv(u, u), v) + (NU + nu_t) * ddot(grad(u), grad(v)) - p * div(v)
    continuity = -q * div(u)

    # SUPG and PSPG, as in the equal-order cavity. Not optional: P1/P1 without them is not inf-sup stable
    # and the factorisation is EXACTLY SINGULAR. Consistent, so a Couette profile (zero strong residual) stays exact.
    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, z]) + grad(p)
    momentum = momentum + tau * dot(adv(v, u), r_m)
    continuity = continuity - tau * dot(grad(q), r_m)

    if case == "cavity":
        lid = 16.0 * top[0] ** 2 * (1 - top[0]) ** 2 * 16.0 * top[1] ** 2 * (1 - top[1]) ** 2
        conditions = [u(*top)[0] - lid, u(*top)[1] - 0.0, u(*top)[2] - 0.0, *[u(*s) - 0.0 for s in walls]]
    else:
        conditions = [u(*boundary)[0] - boundary[2], u(*boundary)[1] - 0.0, u(*boundary)[2] - 0.0]
    fem = jno.fem([momentum, continuity, nut * w - nu_t * w, *conditions, p.pin()])  # nut * w - nu_t * w: read-out only
    sol = np.asarray(
        fem.solve(
            nonlinear=jno.solve.newton(direct=True, rtol=1e-10, atol=1e-10),
            linear=jno.solve.lu(backend="host"),
        )
    )
    bu, bn = fem.blocks[fem.block_index(u)], fem.blocks[fem.block_index(nut)]
    return fem, sol[bu.start : bu.stop], sol[bn.start : bn.stop]


print(f"(1) PLANE COUETTE, u = (z, 0, 0): simple shear, {N}x{N}x{N} tets, Re = {1 / NU:.0f}")
print("    Simple shear carries no subgrid turbulence, so the correct nu_t is ZERO.")
couette = {m: np.abs(solve("couette", m)[2]).max() for m in ("none", "vreman", "wale", "smagorinsky")}
for m, nut_max in couette.items():
    # Judged RELATIVE to Smagorinsky: Vreman's invariant is a difference of nearly equal numbers, so in
    # exact-zero cases it lands on the cancellation floor (~1e-6 of nu) rather than on 0.
    verdict = "~ ZERO (correct)" if nut_max < 1e-3 * couette["smagorinsky"] else "NON-ZERO in laminar shear"
    print(f"  {m:<12} max nu_t/nu = {nut_max / NU:11.4e}   {verdict}")
ref = couette["smagorinsky"]
print(f"    -> Smagorinsky invents nu_t/nu = {ref / NU:.3f}: {ref / max(couette['vreman'], 1e-300):.1e}x Vreman's.")

print(f"(2) LID-DRIVEN CAVITY at Re = {1 / NU:.0f}: a general 3-D strain field, where the models SHOULD act")
fem, base, nut0 = solve("cavity", "none")
print(f"  {'no model':<12} {fem.dofs} dofs   max|u| = {np.abs(base).max():.6f}")
for m in ("vreman", "wale", "smagorinsky"):
    _, uu, nut = solve("cavity", m)
    print(f"  {m:<12} d|u|/|u| = {np.abs(uu - base).max() / np.abs(base).max():.3e}   max nu_t/nu = {nut.max() / NU:8.3e}")
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/les_subgrid_3d.py), only when asked ----
# The tables above stay at N = 6; the figure shows nu_t of each model on a finer cube.
if out := os.environ.get("JNO_FIGURE_DATA"):
    NFIG = int(os.environ.get("NFIG", 16))
    fields = {}
    for m in ("smagorinsky", "vreman", "wale"):
        fem, _, nut = solve("cavity", m, n=NFIG)
        i = np.rint(np.asarray(fem.points) * NFIG).astype(int)  # the structured lattice: node (ix, iy, iz)
        fields[m] = np.zeros((NFIG + 1,) * 3)
        fields[m][i[:, 0], i[:, 1], i[:, 2]] = nut / NU
    np.savez_compressed(Path(out) / "les_subgrid_3d.npz", n=NFIG, **fields)
