import os
from pathlib import Path

# --8<-- [start:code]
"""DFG benchmark 2D-2: vortex shedding past a cylinder at Re = 100, on stabilised equal-order P1/P1
marched with BDF2, checked against the published Strouhal number.

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

Schafer & Turek (1996): the channel and cylinder of 2D-1, driven three times harder, U_mean = 1.
St = f D / U_mean with f the frequency of the transverse velocity at a probe in the wake (reference ~ 0.30).
The momentum residual in tau is quasi-static (no u_t), the form this tutorial was measured with.
"""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
L, H, CX, CY, RR = 2.2, 0.41, 0.2, 0.2, 0.05
UMAX, NU, C_I = 1.5, 1e-3, 36.0
UMEAN, DIA = 2 / 3 * UMAX, 2 * RR
MS, T_END, NSTEPS = 0.010, 6.0, 2400  # mesh size and steps; the refinement table is on the page
ST_REF = 0.30  # Schafer & Turek (1996)
dt = T_END / NSTEPS

d = (jno.shape.rect(0, 0, L, H, size=MS) - jno.shape.disk(CX, CY, RR, size=MS / 5)).domain(time=(0.0, T_END, NSTEPS + 1))
x, y, t = 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
ci = d.variable("initial", split=True)

u = d.unknown.vector(2)  # equal order: P1 velocity,
p = d.unknown.scalar(name="p")  # P1 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)
adv = lambda w, b: dot(grad(w), b)  # (b . grad) w
ddt = lambda w: w.bind(x=x, y=y, t=t).t

# SUPG and PSPG; tau carries the step size, so it assumes the fixed grid of domain(time=...)
G = d.cell_metric
tau = jno.lag(((2 / dt) ** 2 + 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)
momentum = dot(ddt(u), v) + dot(adv(u, u), v) + NU * ddot(grad(u), grad(v)) - p * div(v) + tau * dot(adv(v, u), r_m)
continuity = -q * div(u) - tau * dot(grad(q), r_m)

fem = jno.fem(
    [
        momentum,
        continuity,
        u(xin, yin)[0] - 4 * UMAX * yin * (H - yin) / H**2,  # parabolic inflow
        u(xin, yin)[1] - 0.0,
        u(xw, yw) - 0.0,
        u(xc, yc) - 0.0,
        u(*ci) - 0.0,  # start from rest; the outlet gets no term (do-nothing)
    ]
)
assert fem.is_transient and not fem.is_linear
newton, lu = jno.solve.newton(direct=True, rtol=1e-7, atol=1e-7), jno.solve.lu(backend="host")
traj = np.asarray(fem.solve(nonlinear=newton, linear=lu, time=jno.solve.bdf2()).eval())  # BDF2: second order, L-stable

# St from the transverse velocity at a wake probe, off the centreline so the mode is visible
pts = np.asarray(fem.points)
k = np.argmin(np.sum((pts - [CX + 4 * RR, CY + RR]) ** 2, axis=1))
ts = np.linspace(0.0, T_END, NSTEPS + 1)
uy = traj[:, 2 * k + 1]  # node-major (u_x, u_y)
tail, t_tail = uy[len(uy) // 2 :], ts[len(uy) // 2 :]  # discard the start-up
crossings = np.where(np.diff(np.sign(tail - tail.mean())))[0]
period = 2 * np.mean(np.diff(t_tail[crossings]))
st = DIA / (UMEAN * period)
print(
    f"Re={UMEAN * DIA / NU:.0f}: dofs={fem.dofs}  period {period:.4f} s  St = {st:.4f}  (reference {ST_REF}, {100 * (st - ST_REF) / ST_REF:+.1f}%)"
)
assert len(crossings) >= 4 and tail.max() - tail.min() > 0.1  # a sustained oscillation
assert 0.24 < st < 0.31
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    per = int(round(period / dt))
    frames = np.arange(len(ts) - 2 * per, len(ts))  # the last two shedding cycles, every step
    np.savez_compressed(
        Path(out) / "vortex_shedding_dfg_2d2.npz",
        points=pts,
        cells=np.asarray(d._cells_p1()),
        velocity=traj[frames, : fem.offsets[1]].reshape(len(frames), len(pts), 2).astype(np.float32),
        t=ts[frames],
        geometry=np.array([L, H, CX, CY, RR]),
        probe_t=ts,
        probe_uy=uy,
        period=period,
        strouhal=st,
    )
