import os
from pathlib import Path

# --8<-- [start:code]
"""Fourth-order phase-field fracture on the Morley element: a notched plate with holes, pulled until it breaks."""

import jax
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
E, nu = 1.0, 0.3
lam, mu = E * nu / ((1 + nu) * (1 - 2 * nu)), E / (2 * (1 + nu))
Gc, ell, eta = 2.0e-3, 0.06, 1e-3  # toughness, regularization length, degradation floor
h_min, h_max = 0.008, 0.05  # mesh size where a crack may run and far from it
holes = [(0.50, 0.63, 0.09), (0.72, 0.36, 0.09), (0.88, 0.66, 0.07)]  # centre and radius

plate = jno.shape.rect(0, 0, 1, 1) - jno.shape.rect(-0.01, 0.49, 0.25, 0.51)  # notch cut into the left side
for cx, cy, r in holes:
    plate = plate - jno.shape.disk(cx, cy, r)
band = lambda x, y, z: np.hypot(np.maximum(np.abs(y - 0.5) - 0.25, 0.0), np.maximum(0.15 - x, 0.0))
d = plate.sized(lambda x, y, z: np.minimum(h_max, h_min + 0.15 * band(x, y, z))).domain()
x, y, _ = d.variable("interior", split=True)
cb, ct = (d.variable(side, split=True) for side in ("bottom", "top"))
nodes, cells = np.asarray(d.built_mesh.points)[:, :2], np.asarray(d.mesh.cells_dict["triangle"])

u, dd, g = d.unknown.vector(2), d.unknown.scalar(space="Morley"), d.unknown.scalar(name="g")
v, q = u.test(), dd.test()
H = jno.np.parameter(g.test(), name="H")  # tensile-energy history, drives damage
gd = jno.np.parameter(g.test(), name="gd")  # stiffness degradation g(d)

eps = lambda w: jno.np.symgrad(w, [x, y])
ddot, tr = lambda a, b: jno.np.inner(a, b, n_contract=2), jno.np.trace
hess = lambda w: jno.np.hessian(w, [x, y])
di, qi = dd.bind(x=x, y=y), q.bind(x=x, y=y)
# Morley is non-conforming: the biharmonic term is the full Hessian product, not the Laplacian one
regularization = 2 * Gc * ell * (di.x * qi.x + di.y * qi.y) + Gc * ell**3 * ddot(hess(di), hess(qi))

damage = jno.fem([(2 * H + Gc / ell) * di * qi + regularization - 2 * H * qi])
elasticity = jno.fem(  # unit top displacement; by linearity u = delta * u_hat
    [gd * (lam * tr(eps(u)) * tr(eps(v)) + 2 * mu * ddot(eps(u), eps(v))), u(*cb) - (0.0, 0.0), u(*ct) - (0.0, 1.0)]
)
solve = lambda fem, **values: jax.jit(lambda **kw: fem.solve(linear=jno.solve.lu(), **kw))(**values)

# Part 1: the 1-D profile (1 + r/ell) exp(-r/ell) of the fourth-order model, d = 1 pinned on the edge of a strip
dp = jno.shape.rect(0, 0, 1, 0.05).sized(lambda x, y, z: np.minimum(0.04, h_min + 0.1 * x)).domain()
xp, yp, _ = dp.variable("interior", split=True)
cp = dp.variable("left", split=True)
dq = dp.unknown.scalar(space="Morley")
dpi, dqi = dq.bind(x=xp, y=yp), dq.test().bind(x=xp, y=yp)
hp = lambda w: jno.np.hessian(w, [xp, yp])
profile = jno.fem(
    [(Gc / ell) * dpi * dqi + 2 * Gc * ell * (dpi.x * dqi.x + dpi.y * dqi.y) + Gc * ell**3 * ddot(hp(dpi), hp(dqi))]
    + [dq(*cp) - 1.0, dq.dn(*cp) - 0.0]
)
rp = np.asarray(dp.built_mesh.points)[:, 0]
d_profile = np.asarray(solve(profile))[: len(rp)]  # the first nv Morley DOFs are the vertex values
rms = lambda ref: float(np.sqrt(np.mean((d_profile - ref) ** 2)))
e4, e2 = rms((1 + rp / ell) * np.exp(-rp / ell)), rms(np.exp(-rp / ell))

# Part 2: P1 shape gradients give the strain; psi+ is the tensile energy (Miehe's spectral split)
nv, nc = len(nodes), len(cells)
P = nodes[cells]
a2 = (P[:, 1, 0] - P[:, 0, 0]) * (P[:, 2, 1] - P[:, 0, 1]) - (P[:, 2, 0] - P[:, 0, 0]) * (P[:, 1, 1] - P[:, 0, 1])
area = np.abs(a2) / 2
gradN = (
    np.stack(
        [np.roll(P[..., 1], -1, 1) - np.roll(P[..., 1], 1, 1), np.roll(P[..., 0], 1, 1) - np.roll(P[..., 0], -1, 1)], -1
    )
    / a2[:, None, None]
)


def tensile_energy(w):  # per cell: 1/2 lam <tr e>^2 + mu (<e1>^2 + <e2>^2), e1, e2 the principal strains
    e = 0.5 * (np.einsum("cid,cie->cde", w[cells], gradN) + np.einsum("cid,cie->ced", w[cells], gradN))
    t, s = e[:, 0, 0] + e[:, 1, 1], np.sqrt(((e[:, 0, 0] - e[:, 1, 1]) / 2) ** 2 + e[:, 0, 1] ** 2)
    pos = lambda a: np.maximum(a, 0.0)
    return 0.5 * lam * pos(t) ** 2 + mu * (pos(t / 2 + s) ** 2 + pos(t / 2 - s) ** 2)


def sweep(delta, Hist, dvals):  # alternate: displacement given damage, damage given the history
    for _ in range(3):
        u_hat = np.asarray(solve(elasticity, gd=(1 - dvals) ** 2 + eta)).reshape(-1, 2)
        psi = tensile_energy(u_hat)
        cell_max = np.zeros(nv)
        np.maximum.at(cell_max, cells.ravel(), np.repeat(psi, 3))
        Hist = np.maximum(Hist, delta**2 * cell_max)  # irreversible: no healing
        dvals = np.clip(np.asarray(solve(damage, H=Hist))[:nv], 0.0, 1.0)
    g_cell = (1 - dvals[cells].mean(1)) ** 2 + eta
    return Hist, dvals, 2 * delta * float(np.sum(g_cell * psi * area))  # reaction ~ dPi/d delta


edges = np.concatenate([cells[:, [0, 1]], cells[:, [1, 2]], cells[:, [2, 0]]])


def separated(dvals):  # a connected set of vertices with d > 0.5 runs from the notch tip to the right edge
    dead = (dvals > 0.5)[edges].all(1)
    label = connected_components(coo_matrix((np.ones(dead.sum()), tuple(edges[dead].T)), shape=(nv, nv)), directed=False)[1]
    tip = (np.abs(nodes[:, 1] - 0.5) < 0.05) & (np.abs(nodes[:, 0] - 0.25) < 0.05) & (dvals > 0.5)
    return bool(set(label[tip]) & set(label[(nodes[:, 0] > 1 - 1e-9) & (dvals > 0.5)]))


# Load path by adaptive steps: halve the step when the damage jumps, grow it when it barely moves
Hist, dvals = np.zeros(nv), np.zeros(nv)
delta, step, loads, force, snaps = 0.0, 0.004, [], [], []
while not (snaps and separated(dvals) and force[-1] < 0.1 * max(force)):
    Hn, dn, f = sweep(delta + step, Hist, dvals)
    jump = float((dn - dvals).max())
    if jump > 0.03 and step > 1e-4:
        step /= 2
        continue
    delta, Hist, dvals = delta + step, Hn, dn
    loads.append(delta), force.append(f), snaps.append(dvals)
    step = min(2 * step if jump < 0.01 else step, 0.005)
loads, force, snaps = np.array(loads), np.array(force), np.array(snaps)

print(
    f"fracture of a plate with holes, Morley: nv={nv} nc={nc} damage dofs={damage.dofs}  ell={ell}  h_min/ell={h_min / ell:.2f}"
)
print(f"  profile RMS vs 4th-order {e4:.3f}, vs 2nd-order {e2:.3f}  ({e2 / e4:.1f}x better)")
print(
    f"  {len(loads)} load steps to delta={loads[-1]:.3f}; peak reaction {force.max():.3e} at delta={loads[force.argmax()]:.3f}; final {force[-1]:.3e}"
)
print(f"  plate separated by the crack: {separated(dvals)}  ({(dvals > 0.5).sum()}/{nv} damaged)")
assert e4 < 0.05 and e4 < 0.4 * e2  # the profile is the fourth-order one
assert separated(dvals)  # the crack has crossed the plate, wandering between the holes
assert force[-1] < 0.1 * force.max()  # complete separation: only the degradation floor still carries load
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "phase_field_fracture_2d.npz",
        points=nodes,
        cells=cells,
        damage=snaps,
        loads=loads,
        force=force,
        holes=np.array(holes),
    )
