import os
from pathlib import Path

# --8<-- [start:code]
"""Second-order (AT2) phase-field fracture of a single-edge-notched specimen: one term list, two solver slots."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
E, nu = 210.0, 0.3  # stiff, brittle
lam, mu = E * nu / ((1 + nu) * (1 - 2 * nu)), E / (2 * (1 + nu))
K = lam + mu  # plane-strain bulk modulus
Gc, ell, eta = 2.7e-3, 0.06, 1e-6  # toughness, regularization length, degradation floor
h_min, h_max, w_slit = 0.01, 0.03, 0.010  # mesh size on the crack plane y = 0.5 and far from it; slit half-width
DELTA, NOUT = 1.4e-2, 61  # peak grip displacement, load levels reported

plate = jno.shape.rect(0, 0, 1, 1)
slit = jno.shape.rect(-0.01, 0.5 - w_slit, 0.5, 0.5 + w_slit)  # the notch is cut, not painted on
size = lambda x, y, z: np.minimum(h_max, h_min + 0.1 * np.abs(y - 0.5))  # fine along the crack plane
d = (plate - slit).sized(size).domain(tau=(0.0, 1.0, NOUT))  # tau: the load path
x, y, _ = d.variable("interior", split=True)
cb, ct = d.variable("bottom", split=True), d.variable("top", split=True)

u = d.unknown.vector(2, name="u")  # displacement
dm = d.unknown.scalar(name="d")  # damage
Hs = d.unknown.scalar(name="H")  # history of the tensile energy: evolved, never solved for
v, q = u.test(), dm.test()

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

e = eps(u)  # bound once: the stress differentiates with respect to this object
dev = e - tr(e) / 2 * jno.np.identity(2)
psi_p = 0.5 * K * pos(tr(e)) ** 2 + mu * ddot(dev, dev)  # tensile: drives damage
psi_m = 0.5 * K * neg(tr(e)) ** 2  # compressive: never degraded
g = (1 - dm) ** 2 + eta  # AT2 degradation
sigma = jno.np.diff(g * psi_p + psi_m, e)  # the stress is the energy derivative

momentum = ddot(sigma, eps(v))
damage = (Gc / ell) * dm * q + Gc * ell * jno.np.inner(grad(dm), grad(q), n_contract=1) - 2 * (1 - dm) * Hs.i(-1) * q

fem = jno.fem(
    [
        momentum,
        damage,
        Hs.evolves(jno.np.maximum(Hs.i(-1), psi_p)),  # irreversibility: a crack cannot heal
        dm.bounds(0.0, 1.0),  # damage is a fraction: an inequality, not a clip
        u(*cb) - (0.0, 0.0),  # bottom grip clamped
        u(*ct) - jno.np.vector(0.0, DELTA * ct[-1]),  # top grip pulled, ramped in tau: displacement control
    ]
)
alt = jno.solve.staggered([u, dm], max_sweeps=60, rtol=1e-7, atol=1e-9)
traj = np.asarray(fem.solve(nonlinear=alt, tau=jno.solve.adaptive(limit=[(dm, 0.5)], max_steps=120)))
schedule = fem.tau_schedule

dmg = traj[:, fem.blocks[fem.block_index(dm)]]  # block order is first appearance, so ask
pts = np.asarray(fem.field_points[fem.block_index(dm)])
grip = fem.region_dofs("top", field=u, component=1)
reaction = np.array([float(np.asarray(fem.eval(momentum, s))[grip].sum()) for s in traj])  # momentum residual on the grip
peak = int(np.argmax(np.abs(reaction)))
front = np.array([pts[s > 0.5, 0].max() if (s > 0.5).any() else 0.5 for s in dmg])  # crack tip abscissa

print(f"SENT: {len(pts)} nodes, {fem.dofs} dofs, h_min/ell = {h_min / ell:.2f}, {len(schedule)} adaptive load steps")
print(
    f"  damage in [{dmg.min():.1e}, {dmg.max():.3f}], crack tip x = {front[-1]:.2f}, peak reaction {abs(reaction[peak]):.4f}, final {abs(reaction[-1]):.4f}"
)
assert dmg.min() > -1e-12 and dmg.max() < 1 + 1e-12 and dmg.max() > 0.5  # the bound holds exactly
assert np.all(np.diff(dmg.max(axis=1)) > -1e-9)  # irreversible
apex = pts[dmg[-1].argmax()]
assert abs(apex[1] - 0.5) < ell and apex[0] > 0.5 - 1e-9  # damage peaks at the notch tip, not at a grip
band = np.abs(pts[dmg[-1] > 0.5, 1] - 0.5) < 4 * ell
assert band.mean() > 0.8 and front[-1] > 0.5 + ell  # a band on the crack plane, advancing
assert abs(reaction[-1]) < 0.9 * abs(reaction[peak])  # the specimen softens after the peak

# past the peak there is no nearby equilibrium: a tighter step limit is refused instead of returning a path
try:
    fem.solve(nonlinear=alt, tau=jno.solve.adaptive(limit=[(dm, 0.25)], max_steps=120))
    verdict = "converged: the propagation was stable after all"
except RuntimeError as exc:
    assert "UNSTABLE" in str(exc) and "arc-length" in str(exc)
    verdict = "refused, and named the unstable branch rather than returning a path"
print(f"  tighter limit (0.25): {verdict}")
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    iu = fem.block_index(u)
    # every frame of the animation is a load step the solver really took: replay an explicit, uniform load path
    tau = np.linspace(0.0, 1.0, NOUT)
    frames = np.asarray(fem.solve(nonlinear=alt, tau=tau))
    np.savez_compressed(
        Path(out) / "phase_field_fracture_sent.npz",
        points=pts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        damage=frames[:, fem.blocks[fem.block_index(dm)]],
        displacement=frames[:, fem.blocks[iu]].reshape(len(frames), -1, 2),
        reaction=reaction,
        schedule=schedule,
        tau=tau,
        delta=DELTA,
        ell=ell,
    )
