import os
from pathlib import Path

# --8<-- [start:code]
"""A copper fuse strip heated by its own current until its neck reaches the melting point: potential and heat, solved together."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
# copper, in mm, s, W, J, K
SIG0, ALPHA_R = 5.96e4, 3.9e-3  # conductivity (S/mm) at room temperature, and its drop per kelvin (1/K)
K_TH, RHO_C = 0.4, 3.45e-3  # thermal conductivity (W/(mm K)), volumetric heat capacity (J/(mm^3 K))
T0, T_MELT = 300.0, 1358.0  # room temperature and melting point (K)
L, WID, THICK = 20.0, 6.0, 0.1  # the strip (mm)
NECK, R_NOTCH, VOLT = 1.2, 2.0, 0.5  # the neck's width and the notches' radius (mm), the terminal voltage (V)
T_END, STEPS = 0.08, 160

XC, YC = L / 2, WID / 2
notches = [jno.shape.disk(XC, YC + s * (NECK / 2 + R_NOTCH), R_NOTCH) for s in (1, -1)]
h_of = lambda x, y, z: min(0.15, 0.03 + 0.05 * np.hypot(x - XC, y - YC))  # fine at the neck
d = (jno.shape.rect(0, 0, L, WID) - notches[0] - notches[1]).sized(h_of).domain(time=(0.0, T_END, STEPS + 1))
x, y, t = d.variable("interior", split=True)
left, right, ci = (d.variable(side, split=True) for side in ("left", "right", "initial"))
phi, T = d.unknown.scalar(name="phi"), d.unknown.scalar(name="T")
psi, s = phi.test(), T.test()

grad, dot = (lambda w: jno.np.jacobian(w, [x, y])), jno.np.inner
sigma = SIG0 / (1 + ALPHA_R * (T - T0))  # copper conducts less as it heats
joule = sigma * dot(grad(phi), grad(phi))  # the heat per volume

fem = jno.fem(
    [
        sigma * dot(grad(phi), grad(psi)),  # div(sigma grad phi) = 0
        RHO_C * T.bind(x=x, y=y, t=t).t * s + K_TH * dot(grad(T), grad(s)) - joule * s,  # rho c T_t = div(k grad T) + joule
        phi(*left) - VOLT,  # the terminals: the voltage across, and room temperature
        phi(*right) - 0.0,
        T(*left) - T0,
        T(*right) - T0,
        T(*ci) - T0,
    ]
)
traj = np.asarray(fem.solve(nonlinear=jno.solve.newton(direct=True), linear=jno.solve.lu(backend="host")).eval())

it = fem.block_index(T)
pts, temp, ts = np.asarray(fem.field_points[it])[:, :2], traj[:, fem.blocks[it]], np.linspace(0.0, T_END, STEPS + 1)
k_melt = int(np.argmax(temp.max(axis=1) >= T_MELT))  # the first step with a molten node
t_melt = np.interp(T_MELT, temp.max(axis=1)[k_melt - 1 : k_melt + 1], ts[k_melt - 1 : k_melt + 1])

# a weak term at step k: its rows sum to the integral over the strip, and its rows on a terminal to the reaction there
row = lambda e, k: np.asarray(fem.eval(e, traj[k]))
power = lambda k: THICK * row(joule * s, k).sum()  # W, the Joule heat
current = lambda k: THICK * row(sigma * dot(grad(phi), grad(psi)), k)[fem.region_dofs("left", field=phi)].sum()  # A
stored = lambda k: THICK * row(RHO_C * (T - T0) * s, k).sum()  # J, the heat above room temperature
neck = int(np.argmin(np.hypot(pts[:, 0] - XC, pts[:, 1] - YC)))
heating = row(joule * s, 1)[fem.blocks[it]] / row(1.0 * s, 1)[fem.blocks[it]]  # sigma |grad phi|^2 at the nodes
rate = RHO_C * (temp[1, neck] - T0) / ts[1]  # what the neck gained in the first step
generated = sum(power(k) for k in range(1, k_melt + 1)) * ts[1]
print(f"{fem.dofs} DOFs on {len(pts)} nodes, {STEPS} steps; the neck reaches {T_MELT:.0f} K at t = {t_melt * 1e3:.1f} ms")
print(
    f"power {power(k_melt):.2f} W, voltage times current {VOLT * current(k_melt):.2f} W; current {current(1):.0f} A -> {current(k_melt):.0f} A"
)
print(
    f"first step at the neck: rho c dT/dt = {rate:.1f}, sigma |grad phi|^2 = {heating[neck]:.1f} W/mm^3 (ratio {rate / heating[neck]:.3f})"
)
print(
    f"until melting {generated:.2f} J generated, {stored(k_melt):.2f} J stored, {1 - stored(k_melt) / generated:.1%} gone into the terminals"
)
assert all(abs(power(k) / (VOLT * current(k)) - 1) < 1e-3 for k in (1, k_melt))  # P = V I, at the start and at melting
assert (
    0.9 < rate / heating[neck] < 1.0
)  # adiabatic start: dT/dt = sigma |E|^2 / (rho c), less the little that conduction takes
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "joule_fuse.npz",
        points=pts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        T=temp.astype(np.float32),
        phi=traj[:, fem.blocks[fem.block_index(phi)]].astype(np.float32),
        t=ts,
        k_melt=k_melt,
        geometry=[L, WID, XC, YC],
        material=[SIG0, ALPHA_R, T0, T_MELT],
    )
