import os
from pathlib import Path

# --8<-- [start:code]
"""DFG benchmark 2D-1: steady Navier-Stokes past a cylinder at Re = 20, against the published reference.

    (u.grad)u - nu lap u + grad p = 0,   div u = 0,   Re = U_mean D / nu = 20

Schafer & Turek (1996): [0, 2.2] x [0, 0.41] minus a disk of radius 0.05 at (0.2, 0.2), parabolic inflow
with U_mean = 2/3 * 0.3 = 0.2. The outlet gets no term: do-nothing is the natural condition.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
L, H, CX, CY, RR, UMAX, NU = 2.2, 0.41, 0.2, 0.2, 0.05, 0.3, 1e-3
UMEAN, DIA = 2 / 3 * UMAX, 2 * RR
CD_REF, CL_REF, DP_REF = 5.57953523384, 0.010618948146, 0.11752016697  # Schafer & Turek (1996)

d = (jno.shape.rect(0, 0, L, H, size=0.012) - jno.shape.disk(CX, CY, RR, size=0.0025)).domain()  # fine on the disk
x, y, _ = d.variable("interior", split=True)
xin, yin, _ = d.variable("left", split=True)
xw, yw, _ = d.variable("walls", where=lambda x, y: (y < 1e-9) | (y > H - 1e-9), split=True)
xc, yc, _ = d.variable("arc", split=True)  # the cylinder

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)
momentum = dot(dot(grad(u), u), v) + NU * ddot(grad(u), grad(v)) - p * div(v)

fem = jno.fem(
    [
        momentum,
        -q * div(u),
        u(xin, yin)[0] - 4 * UMAX * yin * (H - yin) / H**2,  # parabolic inflow
        u(xin, yin)[1] - 0.0,
        u(xw, yw) - 0.0,  # no slip on the channel walls
        u(xc, yc) - 0.0,  # and on the cylinder
    ]
)
assert not fem.is_linear  # Re = 20 keeps the convective term
sol = np.asarray(fem.solve(linear=jno.solve.lu(backend="host")))  # a saddle system: solve it directly

# drag and lift are reactions: the momentum residual summed over the cylinder's constrained DOFs
free = np.asarray(fem.eval(momentum, sol))
scale = 2 / (UMEAN**2 * DIA)
cD = -scale * free[fem.region_dofs("arc", field=u, component=0)].sum()
cL = -scale * free[fem.region_dofs("arc", field=u, component=1)].sum()

pre, ppts = sol[fem.offsets[1] :], np.asarray(fem.field_points[1])
probe = lambda pt: pre[np.argmin(np.sum((ppts - pt) ** 2, axis=1))]  # the nearest pressure node
dP = probe((CX - RR, CY)) - probe((CX + RR, CY))

print(f"DFG 2D-1 (Re={UMEAN * DIA / NU:.0f}): dofs={fem.dofs}")
for name, val, ref in (("cD", cD, CD_REF), ("cL", cL, CL_REF), ("dP", dP, DP_REF)):
    print(f"  {name} = {val:9.5f}   reference {ref:9.5f}   ({100 * abs(val - ref) / ref:.2f}%)")
assert abs(cD - CD_REF) / CD_REF < 5e-3 and abs(dP - DP_REF) / DP_REF < 1.5e-2
assert 0.0 < cL < 5 * CL_REF  # the lift is a small residue of nearly cancelling forces: sign and size only
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "navier_stokes_cylinder_dfg.npz",
        points=ppts[:, :2],
        velocity=sol[fem.offsets[0] : fem.offsets[1]].reshape(-1, 2),
        pressure=pre,
        vertices=np.asarray(d.built_mesh.points)[:, :2],
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        vel_points=np.asarray(fem.field_points[0])[:, :2],
        geometry=np.array([L, H, CX, CY, RR]),
        coefficients=np.array([cD, cL, dP]),
    )
