import os
from pathlib import Path

# --8<-- [start:code]
"""A scanning laser on a steel plate: melting, thermal stress (von Mises) and the distortion left behind, marched once."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
# 316L-ish stainless steel, SI
RHO, CP, K_TH = 7000.0, 750.0, 30.0
T_SOL, T_LIQ, L_FUS, T0 = 1690.0, 1730.0, 2.7e5, 300.0
E_MOD, NU, ALPHA, E_MIN = 200e9, 0.3, 1.7e-5, 1e-6  # E_MIN: the melt's residual stiffness keeps the block invertible
G_EL, LAM = E_MOD / (2 * (1 + NU)), E_MOD * NU / ((1 + NU) * (1 - 2 * NU))  # plane strain
# laser, geometry, mesh grading and time
POWER, R0, ETA, VSCAN = 105.0, 150e-6, 0.35, 0.15  # W, m, -, m/s
X_START, LX, LY = 0.3e-3, 1.2e-3, 0.4e-3
EMIS, SIGMA_SB, H_CONV = 0.4, 5.67e-8, 20.0
H_FINE, H_COARSE, BAND = 4e-6, 30e-6, 100e-6
T_END, NSTEPS = 20e-3, 2000  # long enough for the pool to freeze

h_of = lambda x, y, z: (
    H_FINE + (H_COARSE - H_FINE) * min(1.0, max(0.0, (LY - y) / BAND))
)  # three arguments, as gmsh calls it
d = jno.shape.rect(0, 0, LX, LY, size=h_of).domain(time=(0.0, T_END, NSTEPS + 1))
x, y, t = d.variable("interior", split=True)
top, left, right, base = (d.variable(side, split=True) for side in ("top", "left", "right", "bottom"))
ci = d.variable("initial", split=True)
T = d.unknown.scalar(name="T")
w = d.unknown.vector(2, name="w")
S, phi = T.test(), w.test()
Ti = T.bind(x=x, y=y, t=t)
Tt = T.bind(x=top[0], y=top[1], t=top[2])  # the temperature on the top face

grad, eps = (lambda f: jno.np.jacobian(f, [x, y])), (lambda f: jno.np.symgrad(f, [x, y]))
ddot, tr, I2 = (lambda a, b: jno.np.inner(a, b, n_contract=2)), jno.np.trace, jno.np.identity(2)
tanh = jno.np.tanh

# latent heat as an apparent heat capacity, the liquid fraction a smooth ramp through the mushy range
T_MID, T_HALF = 0.5 * (T_SOL + T_LIQ), 0.5 * (T_LIQ - T_SOL)
fl = 0.5 * (1.0 + tanh((Ti - T_MID) / T_HALF))
c_eff = CP + L_FUS * 0.5 * (1.0 - tanh((Ti - T_MID) / T_HALF) ** 2) / T_HALF

# a liquid carries no shear: the moduli scale with the solid fraction squared (lagged: its tangent is what makes the solve stiff)
solid = (1.0 - fl) ** 2 + E_MIN
thermal = lambda f: (3 * LAM + 2 * G_EL) * ALPHA * (Ti - T0) * f  # the stress that blocked thermal expansion would carry
sigma = jno.lag(solid) * (2 * G_EL * eps(w) + LAM * tr(eps(w)) * I2 - thermal(I2))

# radiation as a lagged heat-transfer coefficient, an exact rewrite of the quartic that stays stable
h_rad = jno.lag(EMIS * SIGMA_SB * (Tt**2 + T0**2) * (Tt + T0))
q_laser = (2 * ETA * POWER / (np.pi * R0**2)) * jno.np.exp(-2 * ((top[0] - (X_START + VSCAN * top[2])) / R0) ** 2)

fem = jno.fem(
    [
        RHO * c_eff * Ti.t * S + K_TH * jno.np.inner(grad(T), grad(S)),  # rho c_eff T_t = div(k grad T)
        -(q_laser - (h_rad + H_CONV) * (Tt - T0))
        * S.bind(x=top[0], y=top[1], t=top[2]),  # laser in; radiation, convection out
        ddot(sigma, eps(phi)),  # div sigma = 0, quasi-static; top and sides traction-free
        T(*left) - T0,  # far field at ambient
        T(*right) - T0,
        T(*base) - T0,
        w(*base) - (0.0, 0.0),  # the plate is clamped to its base
        T(*ci) - T0,
    ]
)
traj = np.asarray(
    fem.solve(
        nonlinear=jno.solve.newton(direct=True, rtol=1e-6, atol=1e-6),  # a sparse-direct tangent: the phase change is stiff
        linear=jno.solve.lu(backend="host"),
    ).eval()
)
print(f"dofs={fem.dofs}  nodes={len(np.asarray(fem.points))}  steps={NSTEPS}  dt={T_END / NSTEPS * 1e6:.1f}us")

pts = np.asarray(fem.points)
block = lambda f, c: traj[:, fem.blocks[fem.block_index(f)].start : fem.blocks[fem.block_index(f)].stop].reshape(
    len(traj), -1, c
)
Tf, W = block(T, 1)[..., 0], block(w, 2)
mag, ts, on_top = np.linalg.norm(W, axis=-1), np.linspace(0.0, T_END, NSTEPS + 1), pts[:, 1] > LY - 1e-9
k_hot, k_def = int(np.argmax(Tf.max(axis=1))), int(np.argmax(mag.max(axis=1)))
molten = Tf > T_SOL
hot = pts[molten[k_hot]]
print(
    f"peak T {Tf.max():.0f} K at t={ts[k_hot] * 1e3:.2f} ms (solidus {T_SOL:.0f}, boiling ~3100); molten nodes, max {molten.sum(axis=1).max()}"
)
print(
    f"pool at that step: {np.ptp(hot[:, 0]) * 1e6:.0f} um long, {(LY - hot[:, 1].min()) * 1e6:.0f} um deep ({(LY - hot[:, 1].min()) / H_FINE:.0f} cells)"
)
print(
    f"beam leaves the domain at {(LX - X_START) / VSCAN * 1e3:.1f} ms; final T max {Tf[-1].max():.0f} K, molten nodes {molten[-1].sum()}"
)
print(
    f"peak |displacement| {mag.max() * 1e6:.3f} um at t={ts[k_def] * 1e3:.2f} ms (surface {W[k_def][on_top, 1].max() * 1e6:+.3f} um)"
)
print(
    f"RESIDUAL |displacement| once cooled: {mag[-1].max() * 1e6:.3f} um, surface {W[-1][on_top, 1].min() * 1e6:+.3f} to {W[-1][on_top, 1].max() * 1e6:+.3f} um"
)
# free thermal expansion over the thermal diffusion length bounds the surface rise
L_therm = np.sqrt(K_TH / (RHO * CP) * ts[k_def])
bound = ALPHA * (Tf[k_def].max() - T0) * L_therm
print(
    f"check: free expansion alpha dT sqrt(alpha t) = {L_therm * 1e6:.0f} um: <= {bound * 1e6:.2f} um against a computed rise of {W[k_def][on_top, 1].max() * 1e6:.2f} um"
)
assert molten.any() and molten[-1].sum() == 0  # the pool forms and then freezes
assert 0 < W[k_def][on_top, 1].max() <= bound  # the bulge stays below free expansion

# von Mises stress (GPa) of the solid, plane strain: the out-of-plane stress s_zz is the one the plate cannot relax
s = solid * (2 * G_EL * eps(w) + LAM * tr(eps(w)) * I2 - thermal(I2))  # sigma, not lagged: the output of each step
s_xx, s_yy, s_xy = s[..., 0, 0], s[..., 1, 1], s[..., 0, 1]
s_zz = solid * (LAM * tr(eps(w)) - thermal(1.0))
mises = jno.np.sqrt(0.5 * ((s_xx - s_yy) ** 2 + (s_yy - s_zz) ** 2 + (s_zz - s_xx) ** 2) + 3 * s_xy**2) / 1e9
lump = np.asarray(fem.eval(1.0 * S, traj[0]))[fem.blocks[fem.block_index(T)]]  # nodal weights: rows of a term are integrals
vm = lambda state: np.asarray(fem.eval(mises * S, state))[fem.blocks[fem.block_index(T)]] / lump  # nodal average per step
frames = np.arange(0, NSTEPS + 1, 20)  # the steps the animation shows
VM = np.array([vm(traj[k]) for k in frames])
k_vm = frames[int(np.argmax(VM.max(axis=1)))]

# check: a plate heated uniformly and free to expand has no in-plane stress, only s_zz = -E alpha dT, so the von Mises value is E alpha dT
heated, dT = traj[0].copy(), 300.0
heated[fem.blocks[fem.block_index(T)]] = T0 + dT
heated[fem.blocks[fem.block_index(w)]] = ((1 + NU) * ALPHA * dT * pts).ravel()  # free in-plane expansion, dT < T_SOL
free = vm(heated)
print(
    f"von Mises: peak {VM.max():.2f} GPa at t = {ts[k_vm] * 1e3:.2f} ms; uniform {dT:.0f} K heating gives {free.mean():.4f} GPa against E alpha dT = {E_MOD * ALPHA * dT / 1e9:.4f}"
)
i_hot = int(np.argmax(Tf[frames].max(axis=1)))
core = int(np.argmax(Tf[frames[i_hot]]))  # the pool's hottest node, inside the liquid
print(
    f"stress at the end of the run: {VM[-1].max():.3f} GPa; at the pool's hottest node ({Tf[frames[i_hot], core]:.0f} K) only {VM[i_hot, core]:.4f} GPa"
)
assert np.allclose(free, E_MOD * ALPHA * dT / 1e9, rtol=1e-6)  # stress-free in plane, E alpha dT out of plane
assert VM[i_hot, core] < 0.01 * VM.max()  # the liquid at the heart of the pool carries (almost) none
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "melt_pool_laser.npz",
        points=pts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        T=Tf[frames].astype(np.float32),
        mises=VM.astype(np.float32),
        t=ts[frames],
        box=[LX, LY],
        laser=[X_START, VSCAN, R0],
        melting=[T_SOL, T_LIQ],
    )
