import os
from pathlib import Path

# --8<-- [start:code]
"""A finned heat sink in a channel of air: laminar flow in the air, conduction in the metal, one temperature."""

import functools

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
RE, PR = 50.0, 0.71  # Re = U_mean h_fin / nu, in units of the fin height h_fin
NU, ALPHA = 1 / RE, 1 / (RE * PR)  # kinematic viscosity, thermal diffusivity of the air
K_RATIO, RC_RATIO = 300.0, 50.0  # metal / air: conductivity, volumetric heat capacity
L, HC, UM = 8.0, 1.9, 1.0  # channel length and height, mean inflow speed
X0, W, T_BASE, T_FIN, H_FIN, N_FIN = 2.0, 3.0, 0.4, 0.15, 1.0, 4  # sink: base, fins
Q = 0.5  # heat flux into the base from below
T_END, STEPS, SIZE = 800.0, 100, 0.04

base = jno.shape.rect(X0, 0, X0 + W, T_BASE)
fins = [
    jno.shape.rect(X0 + i * (W - T_FIN) / (N_FIN - 1), 0, X0 + i * (W - T_FIN) / (N_FIN - 1) + T_FIN, T_BASE + H_FIN)
    for i in range(N_FIN)
]
sink = functools.reduce(lambda a, b: a | b, fins, base)
channel = jno.shape.rect(0, 0, L, HC) - sink
d = (
    (sink.name("sink").attach(k=K_RATIO * ALPHA, rc=RC_RATIO) + channel.name("air").attach(k=ALPHA, rc=1.0))
    .sized(SIZE)
    .domain(time=(0.0, T_END, STEPS + 1))
)
x, y, t = d.variable("interior", split=True)
xa, ya, _ = d.variable("air", split=True)
inlet, top, wet, ci = (d.variable(s, split=True) for s in ("left", "top", "air|sink", "initial"))
floor = d.variable("floor", where=lambda x, y: (y < 1e-9) & ((x < X0 - 1e-9) | (x > X0 + W + 1e-9)), split=True)
heated = d.variable("heated", where=lambda x, y: (y < 1e-9) & (x > X0 + 1e-9) & (x < X0 + W - 1e-9), split=True)

u = d.unknown.vector(2, order=2, region="air")  # velocity and pressure live in the air only
p = d.unknown.scalar(name="p", region="air")
T = d.unknown.scalar(name="T")  # the temperature in both
v, q, s = u.test(), p.test(), T.test()

gradf = lambda w: jno.np.jacobian(w, [xa, ya])
grad = lambda w: jno.np.jacobian(w, [x, y])
dot, ddot = jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)

fem = jno.fem(
    [
        dot(dot(gradf(u), u), v) + NU * ddot(gradf(u), gradf(v)) - p * jno.np.trace(gradf(v)),  # Navier-Stokes, steady
        -q * jno.np.trace(gradf(u)),
        d.rc * T.bind(x=x, y=y, t=t).t * s + dot(u, grad(T)) * s + d.k * dot(grad(T), grad(s)),  # heat, one equation
        -Q * s.bind(x=heated[0], y=heated[1]),  # heat flux in at the base
        u(*inlet)[0] - 6 * UM * inlet[1] * (HC - inlet[1]) / HC**2,  # parabolic inflow
        u(*inlet)[1] - 0.0,
        u(*top) - 0.0,
        u(*floor) - 0.0,
        u(*wet) - 0.0,  # no slip on the fins
        T(*inlet) - 0.0,  # cold air in
        T(*ci) - 0.0,
    ]
)
traj = np.asarray(fem.solve(nonlinear=jno.solve.newton(direct=True), linear=jno.solve.lu(backend="host")).eval())

ib, it = fem.block_index(u), fem.block_index(T)
pts, tri = np.asarray(fem.field_points[it])[:, :2], np.asarray(d.mesh.cells_dict["triangle"])
temp, ts = traj[:, fem.blocks[it]], np.linspace(0.0, T_END, STEPS + 1)

# a weak term at step k: its rows sum to the integral over the region it is written on
row = lambda e, k: np.asarray(fem.eval(e, traj[k]))
xo, yo, _ = d.variable("right", split=True)  # the outlet
To, so, uo = T.bind(x=xo, y=yo), s.bind(x=xo, y=yo), u.bind(x=xo, y=yo)
stored = lambda k: row(d.rc * T.bind(x=x, y=y) * s, k).sum()  # the heat content, in units of rho c_air
outflow = lambda k: row((uo[0] * To - ALPHA * To.x) * so, k).sum()  # advected and conducted through the outlet
heat_in = Q * W * ts
heat_out = np.concatenate(
    [[0.0], np.cumsum([ts[1] * outflow(k) for k in range(1, STEPS + 1)])]
)  # backward Euler: end-of-step fluxes
heat_kept = np.array([stored(k) for k in range(STEPS + 1)])
gap = np.abs(heat_in - heat_out - heat_kept)[1:] / heat_in[1:]
print(
    f"{fem.dofs} DOFs, {STEPS} steps; hottest metal {temp[-1].max():.3f}, outlet air {outflow(STEPS) / (Q * W):.1%} of the heat input"
)
print(
    f"heat in {heat_in[-1]:.1f} = out {heat_out[-1]:.1f} + stored {heat_kept[-1]:.1f}; worst imbalance {gap.max():.2%} of the heat in"
)
assert gap.max() < 0.03  # energy balance at every step: input = outflow + storage
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    from scipy.spatial import cKDTree

    from jno.domain.domain_class import mesh_cell_region_membership

    vpts = np.asarray(fem.field_points[ib])[:, :2]
    vel = traj[-1, fem.blocks[ib]].reshape(-1, 2)[cKDTree(vpts).query(pts)[1]]  # the velocity at the vertices
    solid = np.zeros(len(tri), bool)
    solid[mesh_cell_region_membership(d.mesh, 2)["sink"]] = True
    np.savez_compressed(
        Path(out) / "conjugate_heat_sink.npz",
        points=pts,
        cells=tri,
        T=temp.astype(np.float32),
        velocity=vel.astype(np.float32),
        solid=solid,
        t=ts,
        geometry=[L, HC, X0, W, T_BASE, T_FIN, H_FIN, N_FIN],
    )
