import os
from pathlib import Path

# --8<-- [start:code]
"""A rocket nozzle's wall heated and pressed by its gas: jno.fvm and jno.fem on their own meshes, coupled on the liner."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
GAMMA, CP = 1.4, 1.4 / 0.4  # R = 1
T_BURN, N_TIME = 4.0, 9  # coupling windows of 0.5
P_CH, T_CH, U_CH = 1.0, 3.0, 0.45  # chamber pressure, temperature and inflow speed (fast enough that the throat chokes)
H0, RECOVERY = 1.0, 0.9  # the heat-transfer correlation's scale and recovery factor
K_W, RHOC_W, H_COOL, T_COOL = 1.0, 0.5, 2.0, 1.0  # wall conductivity, heat capacity, coolant
E_W, NU_W, ALPHA_W = 100.0, 0.3, 1e-2  # wall stiffness, Poisson ratio, expansion
LAM, MU = E_W * NU_W / ((1 + NU_W) * (1 - 2 * NU_W)), E_W / (2 * (1 + NU_W))
CONTOUR, THICK = (
    [(0.0, 1.0), (0.6, 1.0), (1.2, 0.5), (2.4, 0.8)],
    0.2,
)  # R(x): chamber, converging cone, throat, diverging cone
stack, sqrt, ddot = jno.np.stack, jno.np.sqrt, lambda a, b: jno.np.inner(a, b, n_contract=2)
edges = lambda *names: lambda x, n, name: np.isin(np.asarray(name), names)  # tag a union of the polygon's named edges

# ---- the gas: the axisymmetric Euler equations in the (x, r) meridian
dg = jno.shape.polygon([(0, 0), (2.4, 0), *CONTOUR[::-1][:-1], (0, 1)], size=0.04).domain(time=(0.0, T_BURN, N_TIME))
dg.tag("liner", edges("e2", "e3", "e4"))
x, r, t = dg.variable("interior", split=True)
ci, inflow = dg.variable("initial", split=True), dg.variable("e5", split=True)
q = dg.unknown.vector(4)  # (rho, m_x, m_r, E)
rho, mx, mr, En = (q.bind(x=x, y=r, t=t)[k] for k in range(4))
ux, ur = mx / rho, mr / rho
p = (GAMMA - 1.0) * (En - 0.5 * (mx * ux + mr * ur))
fv = jno.fv(flux="hll", limiter="minmod")
Fx = stack([mx, mx * ux + p, mr * ux, ux * (En + p)], axis=-1)
Fr = stack([mr, mx * ur, mr * ur + p, ur * (En + p)], axis=-1)
hoop = stack([0.0 * p, 0.0 * p, p, 0.0 * p], axis=-1)  # the pressure on the meridian's ring element
rho_ch = P_CH / T_CH
chamber = lambda like: stack(
    [c + 0.0 * like for c in (rho_ch, rho_ch * U_CH, 0.0, P_CH / (GAMMA - 1.0) + 0.5 * rho_ch * U_CH**2)], axis=-1
)


def slip(tag):  # no flow through the axis and the liner
    xe, re, _, ne = *dg.variable(tag, split=True), dg.variable(tag, normals=True)
    qe = q.bind(x=xe, y=re)
    return qe[1] * ne[..., 0] + qe[2] * ne[..., 1]


gas = jno.fvm(
    [
        r * q.bind(x=x, y=r, t=t).t + (r * Fx).d(x, scheme=fv) + (r * Fr).d(r, scheme=fv) - hoop,
        q(*inflow) - chamber(inflow[0]),
        slip("e0"),
        slip("liner"),
        q(*ci) - chamber(ci[0]),  # the exit, e1, takes no condition: supersonic outflow
    ]
)

# what the wall reads of the gas, on the liner
xl, rl, _ = dg.variable("liner", split=True)
ql = q.bind(x=xl, y=rl)
pl = (GAMMA - 1.0) * (ql[3] - 0.5 * (ql[1] ** 2 + ql[2] ** 2) / ql[0])
T_aw = pl / ql[0] + RECOVERY * (ql[1] ** 2 + ql[2] ** 2) / ql[0] ** 2 / (
    2.0 * CP
)  # the adiabatic-wall (recovery) temperature
h_gas = H0 * (sqrt(ql[1] ** 2 + ql[2] ** 2) + 1e-6) ** 0.8  # Bartz-like scaling with the mass flux

# ---- the wall: transient conduction and quasi-static thermo-elasticity, the hoop strain included
outer = [(xx, rr + THICK) for xx, rr in CONTOUR]
dw = jno.shape.polygon([*CONTOUR, *outer[::-1]], size=0.03).domain(time=(0.0, T_BURN, N_TIME))
dw.tag("bore", edges("e0", "e1", "e2"))
dw.tag("outside", edges("e4", "e5", "e6"))
xw, rw, tw = dw.variable("interior", split=True)
cw, head, outside = dw.variable("initial", split=True), dw.variable("e7", split=True), dw.variable("outside", split=True)
T, U = dw.unknown(name="T"), dw.unknown.vector(2, name="U")  # U = (u_x, u_r)
S, V = T.test(), U.test()
Tb, Sb, Ub, Vb = T.bind(x=xw, y=rw, t=tw), S.bind(x=xw, y=rw), U.bind(x=xw, y=rw), V.bind(x=xw, y=rw)


def strains(w, rr):  # (e_xx, e_rr, e_qq, e_xr): the hoop strain u_r / r has no 2-D part
    return w.x[0], w.y[1], w[1] / rr, 0.5 * (w.y[0] + w.x[1])


eu, ev = strains(Ub, rw), strains(Vb, rw)
tr_u, tr_v = eu[0] + eu[1] + eu[2], ev[0] + ev[1] + ev[2]
thermal = (3 * LAM + 2 * MU) * ALPHA_W * (Tb - T_COOL)
energy = LAM * tr_u * tr_v + 2 * MU * (eu[0] * ev[0] + eu[1] * ev[1] + eu[2] * ev[2] + 2 * eu[3] * ev[3]) - thermal * tr_v
ring = 2.0 * np.pi * rw  # the axisymmetric volume element
wall = jno.fem(
    [
        (RHOC_W * Tb.t * Sb + K_W * (Tb.x * Sb.x + Tb.y * Sb.y)) * ring,
        energy * ring,
        H_COOL
        * (T.bind(x=outside[0], y=outside[1]) - T_COOL)
        * S.bind(x=outside[0], y=outside[1])
        * 2.0
        * np.pi
        * outside[1],  # coolant
        U(*head)[0] - 0.0,  # the head end, x = 0, is held axially
        T(*cw) - T_COOL,
    ]
)

# what the gas reads of the wall, on the bore
xs, rs, _ = dw.variable("bore", split=True)
ns = dw.variable("bore", normals=True)
Ts, es = T.bind(x=xs, y=rs), strains(U.bind(x=xs, y=rs), rs)
tr_s, th = es[0] + es[1] + es[2], (3 * LAM + 2 * MU) * ALPHA_W * (Ts - T_COOL)
sig_xx, sig_rr, sig_xr = LAM * tr_s + 2 * MU * es[0] - th, LAM * tr_s + 2 * MU * es[1] - th, 2 * MU * es[3]
traction = stack([sig_xx * ns[..., 0] + sig_xr * ns[..., 1], sig_xr * ns[..., 0] + sig_rr * ns[..., 1]], axis=-1)

# ---- the coupling: both conditions are loads on the wall, so each window takes one sweep
core = jno.core(
    [
        gas,
        wall,
        K_W * Ts.d(ns) - h_gas * (T_aw - Ts),  # the heat the gas puts into the wall
        traction + pl * ns,  # the pressure it puts on it
    ]
)
spec = jno.solve.coupling(measure="axisymmetric", time={gas: jno.solve.erk("ssprk3", cfl=0.5), wall: None})
traj_gas, traj_wall = core.solve(coupling=spec)

g = np.asarray(traj_gas[-1]).reshape(4, -1)
speed2, rho_g = (g[1] ** 2 + g[2] ** 2) / g[0] ** 2, g[0]
sound2 = GAMMA * (GAMMA - 1) * (g[3] - 0.5 * rho_g * speed2) / rho_g
mach = np.sqrt(speed2 / sound2)
centroids = np.asarray(gas.centroids)
wall_T, wall_U = (
    np.asarray(traj_wall)[:, wall.blocks[wall.block_index(f)].start : wall.blocks[wall.block_index(f)].stop] for f in (T, U)
)
print(
    f"windows: {len(core.coupled.window_iterations)}, sweeps per window: {set(core.coupled.window_iterations)} (one-way loads)"
)
print(f"exit Mach {mach[centroids[:, 0] > 2.3].mean():.2f}")
print(f"wall temperature: {wall_T[0].max():.3f} -> {wall_T[-1].max():.3f}")
print(f"largest radial displacement {np.abs(wall_U[-1].reshape(-1, 2)[:, 1]).max():.2e}")
assert (
    2.0 < mach[centroids[:, 0] > 2.3].mean() < 3.0 and wall_T[-1].max() > wall_T[0].max()
)  # supersonic exit; the liner warms
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "rocket_nozzle_wall.npz",
        gas_points=np.asarray(dg.mesh_connectivity["points"])[:, :2],
        gas_cells=np.asarray(dg.mesh_connectivity["triangles"]),
        mach=mach,
        wall_points=np.asarray(wall.points),
        wall_cells=np.asarray(dw.mesh_connectivity["triangles"]),
        wall_T=wall_T[-1],
        wall_T0=wall_T[0],
    )
