import os
from pathlib import Path

# --8<-- [start:code]
"""Mach 3 flow into a forward-facing step: shock formation with the finite-volume Euler equations.

    q = (rho, rho u, rho v, E),  q_t + F(q)_x + G(q)_y = 0,  p = (gamma - 1)(E - rho |u|^2 / 2).

The tunnel is 3 long and 1 high, the step 0.2 high starting 0.6 from the inlet. The flow starts impulsively at
rho = 1.4, p = 1, u = 3 (sound speed 1, Mach 3) everywhere, with walls on the floor, the step and the ceiling,
the free state at the inlet and nothing at the outlet. Every check below uses the same ``euler`` problem.
"""

import jax

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

import numpy as np
from scipy.optimize import brentq

import jno

run = jno.setup(__file__)
GAMMA, MACH, RHO, P = 1.4, 3.0, 1.4, 1.0
H, T, FRAMES = 0.0125, 4.0, 121  # cell size, final time, saved states
FREE = (RHO, RHO * MACH, 0.0, P / (GAMMA - 1) + 0.5 * RHO * MACH**2)  # the free stream (sound speed 1)
stack = jno.np.stack


def euler(d, walls, supply, start=None):
    """The 2-D Euler equations on ``d``: slip ``walls``, the free state on ``supply``, from ``start`` (default: free stream)."""
    x, y, t = d.variable("interior", split=True)
    q = d.unknown.vector(4)
    qi = q.bind(x=x, y=y, t=t)
    rho, mx, my, E = qi[0], qi[1], qi[2], qi[3]
    u, v = mx / rho, my / rho
    p = (GAMMA - 1) * (E - 0.5 * (mx * u + my * v))
    Fx = stack([mx, mx * u + p, my * u, u * (E + p)], axis=-1)  # axis=-1: the components of every point
    Fy = stack([my, mx * v, my * v + p, v * (E + p)], axis=-1)
    s = jno.fv(flux="rusanov", limiter="venkat")
    free = lambda b: stack([c + 0.0 * b[0] for c in FREE], axis=-1)
    ci = d.variable("initial", split=True)
    terms = [qi.t + Fx.d(x, scheme=s) + Fy.d(y, scheme=s), q(*ci) - (start or free)(ci)]
    for edge in supply:
        b = d.variable(edge, split=True)
        terms.append(q(*b) - free(b))
    for edge in walls:  # slip: (rho u, rho v) . n = 0
        xb, yb, _ = d.variable(edge, split=True)
        n, qb = d.variable(edge, normals=True), q.bind(x=xb, y=yb)
        terms.append(qb[1] * n[..., 0] + qb[2] * n[..., 1])
    return jno.fvm(terms)


def march(poly, size, tend, walls, supply, frames=2, start=None):
    """Solve ``euler`` on the polygon ``poly`` at CFL 0.5, the step taken from the fastest wave of each interval;
    return the problem and its states at ``frames`` equally spaced times, ``(frames, 4, cells)``."""
    flow = euler(jno.shape.polygon(poly, size=size).domain(time=(0.0, tend, frames)), walls, supply, start)
    return flow, np.asarray(flow.solve(time=jno.solve.erk("ssprk3", cfl=0.5)))


pressure = lambda q: (GAMMA - 1) * (q[..., 3, :] - 0.5 * (q[..., 1, :] ** 2 + q[..., 2, :] ** 2) / q[..., 0, :])
RH = lambda M: (  # Rankine-Hugoniot jumps of a normal shock at Mach M: density and pressure ratios
    (GAMMA + 1) * M**2 / ((GAMMA - 1) * M**2 + 2),
    1 + 2 * GAMMA / (GAMMA + 1) * (M**2 - 1),
)
A = np.sqrt(GAMMA * P / RHO)  # speed of sound of the free stream

# ---- check 1, conservation: a closed tube with a smooth jump, ends untouched, so the totals follow exactly
LY, TC = 0.5, 0.2
jump = lambda c: (1 - jno.np.tanh((c[0] - 1.0) / 0.03)) / 2  # 1 on the left, 0 on the right
tube = lambda c: stack([0.125 + 0.875 * jump(c), 0.0 * c[0], 0.0 * c[0], (0.1 + 0.9 * jump(c)) / (GAMMA - 1)], axis=-1)
tube_flow, tq = march([(0, 0), (2, 0), (2, LY), (0, LY)], 0.05, TC, ("e0", "e2"), (), 21, tube)
total = tq @ tube_flow.volumes  # (frames, 4): mass, x-momentum, y-momentum, energy
tt = np.linspace(0, TC, 21)
drift = np.abs(total - total[0] - np.outer(tt, [0, 0.9 * LY, 0, 0])).max(0)  # x-momentum grows by (p_left - p_right) LY t
print(f"conservation: drift of mass {drift[0]:.1e}, x-momentum {drift[1]:.1e}, energy {drift[3]:.1e}")
assert max(drift[[0, 1, 3]]) < 1e-12  # the y-momentum is not conserved: the walls push with the pressure

# ---- check 2, a normal shock: the flow reflected by a wall; behind the reflected shock the gas rests
TN = 0.3
W = brentq(lambda w: RH((MACH * A + w) / A)[0] - (MACH * A + w) / w, 0.1, 3.0)  # shock speed
n_rho, n_p = RH((MACH * A + W) / A)
ch, cq = march([(0, 0), (1, 0), (1, 0.2), (0, 0.2)], 0.02, TN, ("e0", "e1", "e2"), ("e3",))
rest = (ch.centroids[:, 0] > 1 - 0.7 * W * TN) & (ch.centroids[:, 0] < 0.96)  # between the shock and the wall
m_rho, m_p = np.median(cq[-1, 0, rest]) / RHO, np.median(pressure(cq[-1])[rest]) / P
print(f"normal shock (speed {W:.3f}): p {m_p:.3f} vs {n_p:.3f} (exact), rho {m_rho:.3f} vs {n_rho:.3f}")
assert abs(m_p / n_p - 1) < 0.01 and abs(m_rho / n_rho - 1) < 0.01

# ---- check 3, an oblique shock: a 15 degree ramp, the plateau and the shock angle against theta-beta-M
THETA = np.deg2rad(15.0)
turn = lambda b: np.arctan(2 / np.tan(b) * ((MACH * np.sin(b)) ** 2 - 1) / (MACH**2 * (GAMMA + np.cos(2 * b)) + 2)) - THETA
beta = brentq(turn, np.arcsin(1 / MACH) + 1e-6, np.deg2rad(40))  # the weak solution
o_rho, o_p = RH(MACH * np.sin(beta))
ramp = [(0, 0), (0.3, 0), (1.2, 0.9 * np.tan(THETA)), (1.2, 1), (0, 1)]
wf, wq = march(ramp, 0.02, 1.5, ("e0", "e1"), ("e3", "e4"))
wc, wp = wf.centroids, pressure(wq[-1])
plateau = (wc[:, 0] > 0.7) & (wc[:, 1] < (wc[:, 0] - 0.3) * np.tan(THETA) + 0.05)  # between the ramp and the shock
xs, ys = np.linspace(0.45, 1.1, 14), []
for x0 in xs:  # the height where the pressure crosses the middle of the jump, column by column
    col = np.where(np.abs(wc[:, 0] - x0) < 0.012)[0]
    col = col[np.argsort(wc[col, 1])]
    ys.append(np.interp(0.5 * (1 + o_p) * P, wp[col][::-1], wc[col, 1][::-1]))
angle = np.rad2deg(np.arctan(np.polyfit(xs, ys, 1)[0]))
m_p, m_rho = np.median(wp[plateau]) / P, np.median(wq[-1, 0, plateau]) / RHO
print(
    f"oblique shock: angle {angle:.2f} vs {np.rad2deg(beta):.2f}, p {m_p:.3f} vs {o_p:.3f}, rho {m_rho:.3f} vs {o_rho:.3f}"
)
assert abs(angle - np.rad2deg(beta)) < 0.5 and abs(m_p / o_p - 1) < 0.01 and abs(m_rho / o_rho - 1) < 0.02

# ---- the step: edges e0 floor, e1 step face, e2 step top, e3 outlet, e4 ceiling, e5 inlet
hall = [(0, 0), (0.6, 0), (0.6, 0.2), (3, 0.2), (3, 1), (0, 1)]
flow, traj = march(hall, H, T, ("e0", "e1", "e2", "e4"), ("e5",), FRAMES)  # traj: (frames, 4, cells)
cells = np.asarray(flow.centroids)
rho, pres = traj[:, 0], pressure(traj)
bad = pres <= 0  # cell states whose pressure is not positive
k, c = np.unravel_index(np.argmin(pres), pres.shape)
print(
    f"{len(cells)} cells; density in [{rho.min():.3f}, {rho.max():.3f}], pressure in [{pres.min():.3f}, {pres.max():.3f}]"
)
print(
    f"pressure not positive in {bad.sum()} of {bad.size} cell states; the lowest at ({cells[c, 0]:.3f}, {cells[c, 1]:.3f}), t = {k * T / (FRAMES - 1):.2f}"
)
assert rho.min() > 0 and bad.mean() < 1e-2
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "forward_facing_step_fvm.npz",
        cells=cells,
        t=np.linspace(0, T, FRAMES),
        rho=rho.astype(np.float32),
        q_final=traj[-1],
        h=H,
    )
