import os
from pathlib import Path

# --8<-- [start:code]
"""A plate with a circular hole pulled past yield: J2 plasticity with linear hardening, loaded, then unloaded."""

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
E, nu, sy, H = 200.0, 0.3, 0.2, 10.0  # modulus, Poisson, yield stress, hardening modulus (stress/E = 1e-3 at yield)
lam, mu = E * nu / ((1 + nu) * (1 - 2 * nu)), E / (2 * (1 + nu))
K, rt = lam + 2 * mu / 3, 1.5**0.5
a, L, h_min, h_max, NSTEP, PEAK = (
    1.0,
    10.0,
    0.04,
    0.5,
    100,
    0.19,
)  # hole radius, quarter size, mesh sizes, steps, peak stress

hole = jno.shape.disk(0, 0, a)
size = lambda x, y, z: np.minimum(h_max, h_min + 0.05 * np.maximum(np.hypot(x, y) - a, 0))  # fine at the hole edge
d = (jno.shape.rect(0, 0, L, L) - hole).sized(size).domain(tau=(0.0, 1.0, NSTEP + 1))  # quarter plate; tau: the load path
x, y, tau = d.variable("interior", split=True)
cl, cb, cr = d.variable("left", split=True), d.variable("bottom", split=True), d.variable("right", split=True)

u = d.unknown.vector(2, order=2, name="u")  # displacement
ep = d.unknown.matrix(2, 2, symmetric=True, name="ep")  # plastic strain: a state, advanced, never solved for
al = d.unknown.scalar(name="al")  # equivalent plastic strain: the hardening state
post = d.unknown.vector(3, order=1, name="post")  # readout, projected onto the nodes: (von Mises, sigma_xx, plastic strain)
v, q = u.test(), post.test()

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

# plane strain: eps_zz = 0, and plastic flow is incompressible, so ep_zz = -tr(ep) and the elastic strain has e_zz = tr(ep)
e = eps(u)
D, Dz = e - ep.i(-1) - tr(e) / 3 * I2, tr(ep.i(-1)) - tr(e) / 3  # deviatoric elastic predictor, in plane and out of plane
dd = jno.np.sqrt(ddot(D, D) + Dz**2 + 1e-30)  # its norm (the 1e-30 keeps it differentiable at zero)
dg = jno.np.maximum(rt * 2 * mu * dd - (sy + H * al.i(-1)), 0.0) / (3 * mu + H)  # plastic multiplier of the return map
n = D / dd  # flow direction
s2, szz = 2 * mu * (D - rt * dg * n), 2 * mu * (Dz - rt * dg * Dz / dd)  # deviatoric stress, in plane and out of plane
sigma = K * tr(e) * I2 + s2  # returned Cauchy stress
mises = jno.np.sqrt(1.5 * (ddot(s2, s2) + szz**2) + 1e-30)

load = PEAK * jno.np.minimum(cr[-1] / 0.7, (1 - cr[-1]) / 0.3)  # stress on the right edge: up to PEAK at tau=0.7, then off
fem = jno.fem(
    [
        ddot(sigma, eps(v)),  # equilibrium
        -load * v.bind(x=cr[0], y=cr[1], tau=cr[-1])[0],  # the pull on the right edge
        ep.evolves(ep.i(-1) + rt * dg * n),  # plastic strain advances
        al.evolves(al.i(-1) + dg),  # hardening advances
        jno.np.inner(post - jno.np.vector(mises, sigma[..., 0, 0], al.i(-1) + dg), q, n_contract=1),  # nodal readout
        u(*cl)[0] - 0.0,  # symmetry: no x displacement on x = 0
        u(*cb)[1] - 0.0,  # symmetry: no y displacement on y = 0
    ]
)
traj = np.asarray(fem.solve())  # (steps, dofs): the whole load path
out = traj[:, fem.blocks[fem.block_index(post)]].reshape(NSTEP + 1, -1, 3)
vm, sxx, pe = out[..., 0], out[..., 1], out[..., 2]  # nodal von Mises stress, sigma_xx, equivalent plastic strain per step
pts = np.asarray(fem.field_points[fem.block_index(post)])
pull = PEAK * np.minimum(
    np.linspace(0, 1, NSTEP + 1) / 0.7, (1 - np.linspace(0, 1, NSTEP + 1)) / 0.3
)  # applied stress per step
tip = np.argmin(np.hypot(pts[:, 0], pts[:, 1] - a))  # the hole edge at 90 degrees to the load
print(f"{fem.dofs} dofs, {len(pts)} nodes, {NSTEP} steps")

# (1) elastic first step: Kirsch, sigma_xx(0, y) = p/2 (2 + a^2/y^2 + 3 a^4/y^4), factor 3 at the hole edge, infinite plate
ligament = (np.abs(pts[:, 0]) < 1e-9) & (pts[:, 1] > a + 1e-9) & (pts[:, 1] < 3 * a)
kirsch = lambda r: 0.5 * (2 + a**2 / r**2 + 3 * a**4 / r**4)
Kt, dev = sxx[1, tip] / pull[1], np.abs(sxx[1, ligament] / pull[1] / kirsch(pts[ligament, 1]) - 1).max()
# (2) first yield: the elastic response scales with the load, so the hole edge yields at sy / (its von Mises stress per unit load)
first = int(np.argmax(pe.max(axis=1) > 1e-9))  # first step with plastic strain
unit = vm[1:first].max(axis=1) / pull[1:first]
p_yield = sy / unit[0]
# (3) consistency: the stress stays on or inside the hardened yield surface, and the plastic strain only grows while loading
excess = (vm - sy - H * pe).max()
K70 = NSTEP * 7 // 10  # the peak of the load
rise, drop = np.diff(pe[: K70 + 1], axis=0).min(), np.diff(pe[K70:], axis=0).min()
print(f"elastic scaling spread {np.ptp(unit) / unit[0]:.1e}")
print(f"Kirsch: Kt = {Kt:.3f} (3 for an infinite plate), ligament profile within {dev:.1%}")
print(
    f"first yield at p = {p_yield:.4f} (elastic scaling; {p_yield / sy:.3f} sigma_y), first plastic step p = {pull[first]:.4f}; the hole edge's von Mises stress is {unit[0]:.3f} per unit load"
)
print(
    f"peak load {PEAK}: plastic strain {pe[K70].max():.2e} ({pe[K70].max() * E / sy:.1f} yield strains), plastic nodes {(pe[K70] > 1e-9).sum()}"
)
print(
    f"yield-surface excess {excess:.1e}, smallest plastic-strain increment {rise:.1e}, residual sigma_xx at the hole edge {sxx[-1, tip]:.4f}"
)
print(
    f"after unloading: plastic strain {pe[-1].max():.2e} (peak load {pe[K70].max():.2e}), plastic nodes {(pe[-1] > 1e-9).sum()}, smallest increment while unloading {drop:.1e}"
)
assert abs(Kt - 3) < 0.15 and dev < 0.08  # Kirsch, plus the finite-width and projection error of this plate
assert np.ptp(unit) < 1e-4 * unit[0]  # linear elastic scaling before first yield
assert 0.97 * p_yield < pull[first] < 1.08 * p_yield and np.hypot(*pts[pe[first].argmax()] - [0, a]) < 0.3 * a  # at the tip
assert excess < 0.05 * sy and rise > -0.01 * pe.max()  # consistency, to the nodal projection's overshoot
assert (
    sxx[-1, tip] < 0 and pe[-1].max() >= (1 - 0.01) * pe[K70].max() and drop > -0.02 * pe.max()
)  # unloading: plastic strain stays, residual stress
# --8<-- [end:code]
if out_dir := os.environ.get("JNO_FIGURE_DATA"):
    iu = fem.block_index(u)
    np.savez_compressed(
        Path(out_dir) / "plate_hole_plasticity.npz",
        points=pts,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        u_points=np.asarray(fem.field_points[iu]),
        displacement=traj[:, fem.blocks[iu]].reshape(NSTEP + 1, -1, 2),
        mises=vm,
        sigma_xx=sxx,
        plastic_strain=pe,
        pull=pull,
        a=a,
        L=L,
        sy=sy,
    )
