import os
from pathlib import Path

# --8<-- [start:code]
"""A neural hyperelastic law, learned from one stretched rubber plate and used in new finite-strain solves."""

import equinox as eqx
import jax
import jax.numpy as jnp
import numpy as np
import optax
from scipy.spatial import cKDTree

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
softplus = jax.nn.softplus
c10, c01, c20, kappa = 0.3, 0.2, 0.05, 10.0  # the true law: Mooney-Rivlin + one Yeoh term; bulk term known
L, a = 2.0, 0.5  # plate half-width and hole radius


# --8<-- [start:icnn]
class ICNN(eqx.Module):
    """W(i1, i2): convex and non-decreasing in both arguments, because every weight passes through a softplus."""

    Wx: list
    Wz: list
    b: list
    out: jax.Array

    def __init__(self, width, depth, key):
        k = jax.random.split(key, 2 * depth)
        self.Wx = [jax.random.normal(k[i], (width, 2)) - 1.0 for i in range(depth)]  # skip connection from the input
        self.Wz = [jax.random.normal(k[depth + i], (width, width)) - 2.0 for i in range(depth - 1)]
        self.b, self.out = [jnp.zeros(width) for _ in range(depth)], jnp.full(width, -1.0)

    def __call__(self, i1, i2):
        x = jnp.concatenate([i1, i2], axis=-1)
        z = softplus(x @ softplus(self.Wx[0]).T + self.b[0])
        for Wz, Wx, b in zip(self.Wz, self.Wx[1:], self.b[1:]):
            z = softplus(z @ softplus(Wz).T + x @ softplus(Wx).T + b)
        return (z @ softplus(self.out))[..., None]


net = jno.nn(ICNN(12, 2, jax.random.PRNGKey(0))).dtype(jnp.float64)
net.optimizer(optax.adam(optax.exponential_decay(3e-2, 100, 0.7)))
true = lambda i1, i2: c10 * i1 + c01 * i2 + c20 * i1**2
learned = lambda i1, i2: net(i1, i2) - net(0 * i1, 0 * i2)  # W = 0 at i1 = i2 = 0, the undeformed state
# --8<-- [end:icnn]


# --8<-- [start:solid]
def solid(d, law, order=2):
    """Plane-strain finite-strain form of a body whose energy is law(i1, i2) + kappa/2 (J-1)^2."""
    x, y, _ = d.variable("interior", split=True)
    u = d.unknown.vector(2, order=order)
    v = u.test()
    ub, vb = u.bind(x=x, y=y), v.bind(x=x, y=y)
    F = (1 + ub[0].x, ub[0].y, ub[1].x, 1 + ub[1].y)  # F_xx, F_xy, F_yx, F_yy; F_zz = 1
    J = F[0] * F[3] - F[1] * F[2]
    I1 = sum(f * f for f in F)
    i1, i2 = J ** (-2 / 3) * (I1 + 1) - 3, J ** (-4 / 3) * (I1 + J**2) - 3  # isochoric invariants minus 3
    W = law(i1, i2) + kappa / 2 * (J - 1) ** 2
    P = [jno.np.diff(W, f) for f in F]  # first Piola-Kirchhoff stress, P = dW/dF
    return u, v, F, W, P, sum(p * df for p, df in zip(P, (vb[0].x, vb[0].y, vb[1].x, vb[1].y)))


# --8<-- [end:solid]


# --8<-- [start:plate]
def plate(h, law, load):
    """A square plate with a hole (a quarter, by symmetry), pulled at its top edge by the traction `load`."""
    d = (jno.shape.rect(0, 0, L, L) - jno.shape.disk(0, 0, a)).sized(h).domain()
    u, v, F, W, P, mech = solid(d, law)
    tx, ty, _ = d.variable("top", split=True)
    left, bottom = d.variable("left", split=True), d.variable("bottom", split=True)
    return jno.fem([mech, -load * v.bind(x=tx, y=ty)[1], u(*left)[0] - 0.0, u(*bottom)[1] - 0.0]), d


newton, direct = jno.solve.newton(line_search=True), jno.solve.lu()
loads = np.linspace(0.0, 1.2, 13)
p = jno.np.parameter((1,), name="p")
fem_true, d_obs = plate(0.15, true, p)
observed = np.asarray(  # the "measured" displacement fields: true law, every load of the ramp
    fem_true.solve(continuation=jno.solve.continuation(keep="all", p=loads), nonlinear=newton, linear=direct)
)
# --8<-- [end:plate]

# --8<-- [start:train]
seen = (6, 12)  # trained on two load levels, loads[6] = 0.6 and loads[12] = 1.2
fits = [plate(0.15, learned, loads[k])[0] for k in seen]
fit = [(f.solve(x0=observed[k], nonlinear=newton, linear=direct) - observed[k]).mse for f, k in zip(fits, seen)]
jno.core(fit).solve(300, log=False)  # displacement misfit, back-propagated through two nonlinear FE solves
net.freeze()  # from here the network is a known law
# --8<-- [end:train]


# --8<-- [start:checks]
def cell(law):
    """The law on one unit cell: a homogeneous F is a linear displacement, and W, P integrate over unit area."""
    d = jno.shape.rect(0, 0, 1, 1, size=1.0).domain()
    u, v, F, W, P, mech = solid(d, law, order=1)
    fem = jno.fem([mech, u(*d.variable("left", split=True))[0] - 0.0])
    X = np.asarray(fem.points)

    def response(Fm):  # energy and the four components of P at the deformation gradient Fm (2 x 2)
        state = ((Fm - np.eye(2)) @ X.T).T.reshape(-1)
        return float(fem.eval(W, state)), np.array([float(fem.eval(q, state)) for q in P])

    return response


law_true, law_net = cell(true), cell(learned)
I2, rot = np.eye(2), lambda t: np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]])

# the learned law is zero and stress-free at the identity, and objective, whatever the weights are
W0, P0 = law_net(I2)
Fo = np.array([[1.3, 0.2], [-0.1, 0.8]])
Wf, Pf = law_net(Fo)
Wr, Pr = law_net(rot(0.7) @ Fo)
print(f"identity: W = {W0:.1e}, |P| = {np.abs(P0).max():.1e}; rotation 0.7 rad: dW = {abs(Wr - Wf):.1e}")
assert abs(W0) < 1e-12 and np.abs(P0).max() < 1e-12
assert abs(Wr - Wf) < 1e-12 and np.abs(Pr - (rot(0.7) @ Pf.reshape(2, 2)).ravel()).max() < 1e-12

# the stretches the plate went through while it was trained on (per triangle, from the observed displacements)
X, tri = np.asarray(d_obs.built_mesh.points)[:, :2], np.asarray(d_obs.mesh.cells_dict["triangle"])
to_vertex = cKDTree(np.asarray(fem_true.points)).query(X)[1]
edge = lambda A: (A[tri[:, 1:]] - A[tri[:, :1]]).transpose(0, 2, 1)  # (triangles, 2, 2): the two edges as columns
stretch = lambda U: np.linalg.svd(I2 + edge(U) @ np.linalg.inv(edge(X)), compute_uv=False)  # principal stretches
sv = np.concatenate([stretch(observed[k].reshape(-1, 2)[to_vertex]) for k in seen])
lo, hi = sv.min(), sv.max()

# held-out deformations: random rotations and principal stretches inside the trained range
rng = np.random.default_rng(1)
held = [rot(t[0]) @ np.diag(s) @ rot(t[1]) for s, t in zip(rng.uniform(lo, hi, (80, 2)), rng.uniform(0, np.pi, (80, 2)))]
pairs = [(law_net(Fm)[1], law_true(Fm)[1]) for Fm in held]
err = np.array([np.linalg.norm(pn - pt) / np.linalg.norm(pt) for pn, pt in pairs])
print(f"trained stretches {lo:.2f} .. {hi:.2f}; held-out stress error: mean {err.mean():.3f}, max {err.max():.3f}")
assert err.mean() < 0.05 and err.max() < 0.2

# stress-stretch curves of the three homogeneous tests, past the trained range
lam, gam = np.linspace(0.5, 3.2, 28), np.linspace(0.0, 3.0, 31)
tests = {
    "planar tension": ([np.diag([s, 1.0]) for s in lam], (0, 0)),
    "equibiaxial": ([np.diag([s, s]) for s in lam], (0, 0)),
    "simple shear": ([np.array([[1.0, g], [0.0, 1.0]]) for g in gam], (0, 1)),
}
curves = {
    k: [np.array([m(Fm)[1].reshape(2, 2)[c] for Fm in Fs]) for m in (law_true, law_net)] for k, (Fs, c) in tests.items()
}
for k, (pt, pn) in curves.items():
    x, top = (gam, hi - 1 / hi) if k == "simple shear" else (lam, hi)  # shear: the stretch it makes is (g + sqrt(g^2+4))/2
    inside, scale = (x >= lo if k != "simple shear" else x >= 0) & (x <= top), np.abs(pt).max()
    print(
        f"{k}: stress error {np.abs(pn - pt)[inside].max() / scale:.3f} inside, {np.abs(pn - pt)[~inside].max() / scale:.3f} outside the trained range"
    )

# --8<-- [end:checks]

# --8<-- [start:solves]
# the plate again, on a mesh four times finer than the one the law was learned on: true law and learned law
ramp = np.linspace(0.0, 1.2, 61)
q = jno.np.parameter((1,), name="q")
fine_true, d_fine = plate(0.04, true, p)
fine_net, _ = plate(0.04, learned, q)
ramp_true = np.asarray(
    fine_true.solve(continuation=jno.solve.continuation(keep="all", p=ramp), nonlinear=newton, linear=direct)
)
ramp_net = np.asarray(
    fine_net.solve(continuation=jno.solve.continuation(keep="all", q=ramp), nonlinear=newton, linear=direct)
)
diff = np.abs(ramp_net - ramp_true).max(axis=1)
print(
    f"plate, {ramp_true.shape[1]} dofs: displacement difference {100 * diff[-1] / np.abs(ramp_true[-1]).max():.2f} % of the largest displacement at full load,"
)
print(
    f"and at most {100 * diff.max() / np.abs(ramp_true[-1]).max():.2f} % of it anywhere on the ramp; {100 * (diff / np.abs(ramp_true).max(axis=1).clip(1e-12))[1]:.1f} % of the displacement at load {ramp[1]:.2f}"
)
assert diff.max() < 0.08 * np.abs(ramp_true[-1]).max()


def strip(law):
    """A block clamped on the left, its right end pulled by (0.6 g, -g): tension and shear, a test the law has not seen."""
    d = jno.shape.rect(0, 0, 2, 1, size=0.05).domain()
    u, v, F, W, P, mech = solid(d, law)
    left, right = d.variable("left", split=True), d.variable("right", split=True)
    g = jno.np.parameter((1,), name="g")
    return jno.fem([mech, u(*left) - (0.0, 0.0), u(*right)[0] - 0.6 * g, u(*right)[1] - (-g)]), mech, d


push = np.linspace(0.0, 1.0, 21)
bent = {}
for name, law in (("true", true), ("learned", learned)):
    fem, mech, d_strip = strip(law)
    path = np.asarray(fem.solve(continuation=jno.solve.continuation(keep="all", g=push), nonlinear=newton, linear=direct))
    pull = [fem.eval(mech, s)[fem.region_dofs("right", component=c)].sum() for s in path for c in (0, 1)]
    bent[name] = (path, np.array(pull).reshape(-1, 2))  # the force on the right end: both components
(s_true, r_true), (s_net, r_net) = bent["true"], bent["learned"]
du = np.abs(s_net - s_true).max() / np.abs(s_true).max()
dr = np.linalg.norm(r_net[-1] - r_true[-1]) / np.linalg.norm(r_true[-1])
print(
    f"block pulled to (0.6, -1): displacement difference {100 * du:.2f} %, end force ({r_net[-1, 0]:.3f}, {r_net[-1, 1]:.3f}) vs ({r_true[-1, 0]:.3f}, {r_true[-1, 1]:.3f}): {100 * dr:.1f} %"
)
assert du < 0.1 and dr < 0.15
# --8<-- [end:solves]
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    vertex = lambda fem, d: cKDTree(np.asarray(fem.points)).query(np.asarray(d.built_mesh.points)[:, :2])[1]
    vf, vs = vertex(fine_true, d_fine), vertex(fem, d_strip)
    np.savez_compressed(
        Path(out) / "neural_hyperelastic_law.npz",
        plate_points=np.asarray(d_fine.built_mesh.points)[:, :2],
        plate_cells=np.asarray(d_fine.mesh.cells_dict["triangle"]),
        plate_true=ramp_true.reshape(len(ramp), -1, 2)[:, vf].astype(np.float32),
        plate_net=ramp_net.reshape(len(ramp), -1, 2)[:, vf].astype(np.float32),
        loads=ramp,
        strip_points=np.asarray(d_strip.built_mesh.points)[:, :2],
        strip_cells=np.asarray(d_strip.mesh.cells_dict["triangle"]),
        strip_true=s_true.reshape(len(push), -1, 2)[:, vs].astype(np.float32),
        strip_net=s_net.reshape(len(push), -1, 2)[:, vs].astype(np.float32),
        push=push,
        reaction_true=r_true,
        reaction_net=r_net,
        lam=lam,
        gam=gam,
        trained=[lo, hi],
        **{f"{k.replace(' ', '_')}_{w}": c[i] for k, c in curves.items() for i, w in enumerate(("true", "net"))},
    )
