import os
from pathlib import Path

# --8<-- [start:code]
"""A hot gas cooling in a thick-walled vessel: a temperature match, a heat-flux balance and a pressure load."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
GAMMA = 1.4
A, B = 0.5, 1.0  # bore and outer radius
K_G, K_W, RHOC_W = 0.1, 1.0, 1.0  # gas and wall conductivity, wall heat capacity
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))
P0, T_CORE, T_WALL = 3.0, 3.0, 1.0  # the gas pressure, core and wall temperature
T_END, WINDOWS = 1.0, 60  # both problems take one backward Euler step per coupling window
H = 0.02
stack, ddot = jno.np.stack, lambda a, b: jno.np.inner(a, b, n_contract=2)

# ---- the gas: Euler with heat conduction, at rest in a quarter of the cylinder r < a
quarter = jno.shape.disk(0, 0, A) & jno.shape.rect(0, 0, 2, 2)
dg = quarter.sized(H).domain(time=(0.0, T_END, WINDOWS + 1))
x, y, t = dg.variable("interior", split=True)
ci = dg.variable("initial", split=True)
q, T = (
    dg.unknown.vector(4),
    dg.unknown.scalar(name="T"),
)  # (rho, m_x, m_y, E), and the temperature as a fifth, algebraic unknown
qi, Ti = q.bind(x=x, y=y, t=t), T.bind(x=x, y=y, t=t)
rho, mx, my, En = qi[0], qi[1], qi[2], qi[3]
u, v = mx / rho, my / rho
p = (GAMMA - 1.0) * (En - 0.5 * (mx * u + my * v))
fv, fd = jno.fv(flux="hll", limiter="minmod"), "finite_difference"
Fx = stack([mx, mx * u + p, my * u, u * (En + p)], axis=-1)
Fy = stack([my, mx * v, my * v + p, v * (En + p)], axis=-1)
zero = 0.0 * Ti.x
Qx, Qy = (
    stack([zero, zero, zero, -K_G * Ti.x], axis=-1),
    stack([zero, zero, zero, -K_G * Ti.y], axis=-1),
)  # conduction, a face flux

# at rest at one pressure: a hot core over a thermal layer that meets the wall at its temperature
layer = 0.5 * (1.0 - jno.np.tanh((jno.np.sqrt(ci[0] ** 2 + ci[1] ** 2) - (A - 0.15)) / 0.04))
T0 = T_WALL + (T_CORE - T_WALL) * layer
rest = stack([P0 / T0, 0.0 * ci[0], 0.0 * ci[0], P0 / (GAMMA - 1.0) + 0.0 * ci[0]], axis=-1)


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


gas = jno.fvm(
    [
        qi.t + Fx.d(x, scheme=fv) + Fy.d(y, scheme=fv) + Qx.d(x, scheme=fd) + Qy.d(y, scheme=fd),
        Ti - p / rho,  # T = p/rho: no time derivative, solved in every cell with the march
        slip("left"),
        slip("bottom"),
        slip("arc"),
        q(*ci) - rest,
        T(*ci) - T0,
    ]
)
xg, yg, _ = dg.variable("arc", split=True)  # the gas on the bore
ng, Tg, qg = dg.variable("arc", normals=True), T.bind(x=xg, y=yg), q.bind(x=xg, y=yg)
pg = (GAMMA - 1.0) * (qg[3] - 0.5 * (qg[1] ** 2 + qg[2] ** 2) / qg[0])

# ---- the wall: transient conduction and plane-strain thermo-elasticity, insulated outside
ring = (jno.shape.disk(0, 0, B) - jno.shape.disk(0, 0, A)) & jno.shape.rect(0, 0, 2, 2)
dw = ring.sized(H).domain(time=(0.0, T_END, WINDOWS + 1))
dw.tag("bore", lambda x, n, name: (np.asarray(name) == "arc") & (np.hypot(x[..., 0], x[..., 1]) < 0.5 * (A + B)))
xw, yw, tw = dw.variable("interior", split=True)
left, bottom, cw = (dw.variable(s, split=True) for s in ("left", "bottom", "initial"))
Tw, w = dw.unknown(name="T"), dw.unknown.vector(2, name="w")
S, phi = Tw.test(), w.test()
grad, eps, I2 = (lambda f: jno.np.jacobian(f, [xw, yw])), (lambda f: jno.np.symgrad(f, [xw, yw])), jno.np.identity(2)
tr = jno.np.trace


def sigma(wv, Tv, axes=None):  # the plane-strain thermo-elastic stress
    e = jno.np.symgrad(wv, axes or [xw, yw])
    return 2.0 * MU * e + LAM * tr(e) * I2 - (3.0 * LAM + 2.0 * MU) * ALPHA_W * (Tv - T_WALL) * I2


wall = jno.fem(
    [
        RHOC_W * Tw.bind(x=xw, y=yw, t=tw).t * S + K_W * jno.np.inner(grad(Tw), grad(S)),
        ddot(sigma(w, Tw.bind(x=xw, y=yw)), eps(phi)),
        w(*left)[0] - 0.0,  # symmetry rollers
        w(*bottom)[1] - 0.0,
        Tw(*cw) - T_WALL,
    ]
)
xs, ys, _ = dw.variable("bore", split=True)  # the wall on the bore
ns, Ts = dw.variable("bore", normals=True), Tw.bind(x=xs, y=ys)
traction = jno.np.inner(sigma(w.bind(x=xs, y=ys), Ts, [xs, ys]), ns, n_contract=1)

# ---- the coupling, three conditions written as for one problem
core = jno.core(
    [
        gas,
        wall,
        Tg - Ts,  # the temperatures agree
        K_G * Tg.d(ng) + K_W * Ts.d(ns),  # what leaves the gas enters the wall
        traction + pg * ns,  # the gas pressure loads the wall
    ]
)
traj_gas, traj_wall = core.solve(coupling=jno.solve.coupling(time={gas: None, wall: None}))

c = core.coupled
g = np.asarray(traj_gas).reshape(len(c.times), 5, -1)
V = np.asarray(gas.volumes)
pts, tri = np.asarray(dw.mesh_connectivity["points"])[:, :2], np.asarray(dw.mesh_connectivity["triangles"])
e1, e2 = pts[tri[:, 1]] - pts[tri[:, 0]], pts[tri[:, 2]] - pts[tri[:, 0]]
area = 0.5 * np.abs(e1[:, 0] * e2[:, 1] - e1[:, 1] * e2[:, 0])
wl = np.asarray(traj_wall)
TW = wl[:, wall.blocks[wall.block_index(Tw)].start : wall.blocks[wall.block_index(Tw)].stop]
disp = wl[-1, wall.blocks[wall.block_index(w)].start : wall.blocks[wall.block_index(w)].stop].reshape(-1, 2)
heat_gas, heat_wall = g[:, 3] @ V, RHOC_W * (TW[:, tri].mean(axis=2) @ area)  # the gas's energy and the wall's heat content
total, moved = heat_gas + heat_wall, heat_wall[-1] - heat_wall[0]
p_mean = (GAMMA - 1.0) * (g[:, 3] - 0.5 * (g[:, 1] ** 2 + g[:, 2] ** 2) / g[:, 0]) @ V / V.sum()
radius = np.hypot(pts[:, 0], pts[:, 1])
radial = ((disp[:, 0] * pts[:, 0] + disp[:, 1] * pts[:, 1]) / radius)[radius < A + 1e-9].mean()
print(f"{len(c.window_iterations)} windows, sweeps per window {c.window_iterations}")
print(f"heat into the wall {moved:.4f}; energy drift {np.abs(total - total[0]).max() / moved:.2%} of it")
print(
    f"gas pressure {p_mean[0]:.3f} -> {p_mean[-1]:.3f}; wall temperature up to {TW[-1].max():.3f}; bore radial displacement {radial:.2e}"
)
assert (
    np.abs(total - total[0]).max() < 0.01 * moved and p_mean[-1] < p_mean[0] < 3.1
)  # the wall takes the heat the gas gives out
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "hot_gas_vessel.npz",
        gas_points=np.asarray(dg.mesh_connectivity["points"])[:, :2],
        gas_cells=np.asarray(dg.mesh_connectivity["triangles"]),
        gas_T=g[:, 4],
        wall_points=np.asarray(wall.points),
        wall_cells=tri,
        wall_T=TW,
        t=np.asarray(c.times),
        geometry=[A, B],
    )
