import os
from pathlib import Path

# --8<-- [start:code]
"""Thermal-shock cracking: a hot ceramic slab quenched on one edge, a phase-field (AT1) crack network in plane strain."""

import jax
import numpy as np
from scipy.special import erfc

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
W, DEPTH, ELL = 48.0, 36.0, 1.0  # slab width and depth, damage length: every length is in units of ELL
E, NU, KAPPA, ETA = 1.0, 0.3, 1.0, 1e-6  # Young's modulus, Poisson ratio, diffusivity, degradation floor
STRAIN, L0_OVER_ELL = 0.01, 0.3  # thermal strain of the full shock (alpha * dT), Griffith length / ELL
GC = L0_OVER_ELL * ELL * E * STRAIN**2  # toughness, from the Griffith length l0 = Gc / (E (alpha dT)^2)
T_END, N_STEPS = 100.0, 100  # the march is uniform in sqrt(t): t = T_END (tau)^2
h_min = 0.3  # mesh size at the cooled edge, graded up to 1 deep inside
lam, mu = E * NU / ((1 + NU) * (1 - 2 * NU)), E / (2 * (1 + NU))
K = lam + mu  # plane-strain bulk modulus

size = lambda x, y, z: np.minimum(1.0, h_min + 0.03 * np.maximum(y - 8.0, 0.0))
d = jno.shape.rect(0, 0, W, DEPTH).sized(size).domain(tau=(0.0, 1.0, N_STEPS + 1))  # tau: the quench clock
x, y, tau = d.variable("interior", split=True)
cold, top, left = (d.variable(s, split=True) for s in ("bottom", "top", "left"))
sides = d.variable("sides", where=lambda x, y: (x < 1e-9) | (x > W - 1e-9), split=True)

u, T = d.unknown.vector(2, name="u"), d.unknown.scalar(name="T")  # displacement, temperature drop in units of dT
dm, Hs = d.unknown.scalar(name="d"), d.unknown.scalar(name="H")  # damage, history of the tensile energy
v, S, q = u.test(), T.test(), dm.test()

grad = lambda w: jno.np.jacobian(w, [x, y])
eps, tr, dot = lambda w: jno.np.symgrad(w, [x, y]), jno.np.trace, jno.np.inner
ddot = lambda a, b: jno.np.inner(a, b, n_contract=2)
pos, neg = lambda s: jno.np.maximum(s, 0.0), lambda s: jno.np.minimum(s, 0.0)

# thermo-elasticity: the elastic strain is the total strain minus the thermal one (plane strain: (1 + nu) alpha)
ee = eps(u) - (1 + NU) * STRAIN * T * jno.np.identity(2)
dev = ee - tr(ee) / 2 * jno.np.identity(2)
psi_p = 0.5 * K * pos(tr(ee)) ** 2 + mu * ddot(dev, dev)  # tensile energy: drives damage
psi_m = 0.5 * K * neg(tr(ee)) ** 2  # compressive energy: never degraded
sigma = jno.np.diff(((1 - dm) ** 2 + ETA) * psi_p + psi_m, ee)  # the stress is the energy derivative

dtau = 1.0 / N_STEPS
dt = T_END * (2 * jno.np.maximum(tau, dtau) - dtau) * dtau  # t = T_END tau^2, so dt = T_END (tau^2 - (tau - dtau)^2)
heat = (T - T.i(-1)) / dt * S + KAPPA * dot(grad(T), grad(S))  # backward Euler
momentum = ddot(sigma, eps(v))
damage = 3 * GC / 8 * (q / ELL + 2 * ELL * dot(grad(dm), grad(q))) - 2 * (1 - dm) * Hs.i(-1) * q  # AT1

fem = jno.fem(
    [
        heat,
        momentum,
        damage,
        Hs.evolves(jno.np.maximum(Hs.i(-1), psi_p)),  # irreversibility: a crack cannot heal
        dm.bounds(0.0, 1.0),
        T(*cold) - (-1.0 * jno.np.minimum(cold[-1] / dtau, 1.0)),  # the quench: the cold edge drops to -dT at once
        u(*sides)[0] - 0.0,  # rollers: a strip cut from an infinite slab
        u(*top)[1] - 0.0,  # the far edge holds the vertical position
    ]
)
alt = jno.solve.staggered([T, u, dm], max_sweeps=60, rtol=1e-6, atol=1e-9, direct=True)
traj = np.asarray(fem.solve(nonlinear=alt, linear=jno.solve.lu(backend="pardiso")))

it, id_ = fem.block_index(T), fem.block_index(dm)
temp, dmg = traj[:, fem.blocks[it]], traj[:, fem.blocks[id_]]
pts = np.asarray(fem.field_points[id_])
t = T_END * np.linspace(0.0, 1.0, N_STEPS + 1) ** 2

# check 1: the temperature against the half-space solution T = -erfc(y / (2 sqrt(kappa t))), before the far edge matters
k = N_STEPS // 5
err_T = np.abs(temp[k] + erfc(pts[:, 1] / (2 * np.sqrt(KAPPA * t[k])))).max()

# check 2: the undamaged stress. In the first step nothing is damaged and the state is one-dimensional, so
# sigma_xx = -E alpha dT T / (1 - nu): the force on a roller side is that stress integrated over the depth
sigma_c = np.sqrt(3 * E * GC / (8 * ELL))  # AT1 strength
sigma_0 = E * STRAIN / (1 - NU)  # the elastic stress at the cooled surface, E alpha dT / (1 - nu)
force = abs(np.asarray(fem.eval(momentum, traj[1]))[fem.region_dofs("left", field=u, component=0)].sum())
expected = sigma_0 * abs(np.asarray(fem.eval(T * S, traj[1]))[fem.blocks[it]].sum()) / W  # integral of |T| over the depth
print(f"temperature vs erfc at t = {t[k]:.1f}: max error {err_T:.4f}")
print(f"surface stress {sigma_0:.5f} = {sigma_0 / sigma_c:.2f} sigma_c; roller force {force:.6f} vs {expected:.6f}")


def cracks(a, width=1.0, gap=2.0):  # crack positions at depth a: clusters of badly damaged nodes (d > 0.5) in a thin strip
    xs = np.sort(pts[(np.abs(pts[:, 1] - a) < width) & (dmg[-1] > 0.5), 0])
    groups = np.split(xs, np.flatnonzero(np.diff(xs) > gap) + 1) if xs.size else []
    return np.array([g.mean() for g in groups if len(g) >= 3])


depths = (4.0, 6.0, 10.0, 14.0, 20.0)
found = {a: cracks(a) for a in depths}
for a, c in found.items():
    print(f"depth {a:4.1f}: {len(c)} cracks, mean spacing {W / len(c):.1f}")
counts = [len(c) for c in found.values()]
assert err_T < 0.02 and abs(force / expected - 1) < 1e-3
assert (
    counts == sorted(counts, reverse=True) and counts[0] >= 2 * counts[-1] >= 2
)  # the network coarsens: fewer, longer cracks with depth
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "thermal_shock_cracking.npz",
        points=pts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        damage=dmg.astype(np.float32),
        temperature=temp.astype(np.float32),
        t=t,
        view_depth=27.0,
        fig_w=6.6,
        fig_h=6.6 * 27.0 / W + 0.4,
    )
