import os
from pathlib import Path

# --8<-- [start:code]
"""A 3-D crane hook: a swept circular bar clamped at its shank, loaded at the saddle, checked against Winkler-Bach."""

import jax
import numpy as np
from scipy.spatial import cKDTree

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
E, nu = 2.1e5, 0.3  # steel, N and mm
lam, mu = E * nu / ((1 + nu) * (1 - 2 * nu)), E / (2 * (1 + nu))
a, R, shank, tip, h = 30.0, 100.0, 150.0, 80.0, 4.5  # bar radius, bend radius of the centre line, lengths, mesh size
pressure = 7.0  # N/mm^2 on the saddle patch

axis = (
    jno.Path(0, 0, 0)
    .line_to(0, 0, -shank)
    .arc_to(2 * R, 0, -shank, through=(R, 0, -shank - R))
    .line_to(2 * R, 0, -shank + tip)
)
d = jno.shape.disk(0, 0, a, size=h).sweep(axis).domain()
x, y, z, _ = d.variable("interior", split=True)
cx, cy, cz, _ = d.variable("clamp", where=lambda x, y, z: z > -1e-6, split=True)  # the shank's top face
inner = lambda x, y, z: (np.hypot(x - R, z + shank) < R - 0.3 * a) & (np.abs(x - R) < 0.3 * R) & (z < -shank)
px, py, pz, _ = d.variable("patch", where=inner, split=True)  # the sling rests on the inside of the bend

u = d.unknown.vector(3, order=2)
v = u.test()
eps = lambda w: jno.np.symgrad(w, [x, y, z])
ddot, tr = lambda a, b: jno.np.inner(a, b, n_contract=2), jno.np.trace
stiffness = lam * tr(eps(u)) * tr(eps(v)) + 2 * mu * ddot(eps(u), eps(v))  # sigma(u) : eps(v)

traction = jno.np.inner(jno.np.vector(0.0, 0.0, -pressure), v.bind(x=px, y=py, z=pz))  # a downward pressure on the patch
fem = jno.fem([stiffness, u(cx, cy, cz) - (0.0, 0.0, 0.0), traction])
sol = np.asarray(fem.solve(linear=jno.solve.lu()))
residual = np.asarray(fem.eval(stiffness, sol))
load = -float(residual[fem.region_dofs("clamp", component=2)].sum())  # the clamp reaction is the load F

# von Mises stress at the vertices from the P2 gradient there: grad u(x_k) = 3 u_k grad(l_k) + sum_i (4 u_ki - u_i) grad(l_i)
tree, X, tets = cKDTree(fem.points), np.asarray(d.built_mesh.points), np.asarray(d.mesh.cells_dict["tetra"])
P, U = X[tets], sol.reshape(-1, 3)
J = P[:, 1:] - P[:, :1]
gl = np.concatenate(
    [-np.linalg.inv(J).sum(2)[:, None], np.swapaxes(np.linalg.inv(J), 1, 2)], 1
)  # grad of the 4 barycentrics
node = tree.query(P)[1]
vm = np.zeros((len(tets), 4))
for k in range(4):
    G = 3 * np.einsum("tc,td->tcd", U[node[:, k]], gl[:, k])
    for i in set(range(4)) - {k}:
        edge = tree.query(0.5 * (P[:, i] + P[:, k]))[1]
        G += np.einsum("tc,td->tcd", 4 * U[edge] - U[node[:, i]], gl[:, i])
    e = 0.5 * (G + np.swapaxes(G, 1, 2))
    s = lam * np.trace(e, axis1=1, axis2=2)[:, None, None] * np.eye(3) + 2 * mu * e
    dev = s - np.trace(s, axis1=1, axis2=2)[:, None, None] / 3 * np.eye(3)
    vm[:, k] = np.sqrt(1.5 * (dev**2).sum((1, 2)))
w = np.abs(np.linalg.det(J)) / 6
vol, svm = np.zeros(len(X)), np.zeros(len(X))
np.add.at(vol, tets.ravel(), np.repeat(w, 4))
np.add.at(svm, tets.ravel(), (vm * w[:, None]).ravel())
svm /= np.maximum(vol, 1e-12)  # vertices of no tetrahedron (arc through-points) are never drawn

# Winkler-Bach for the circular bar: sigma(phi) at the inner fibre of the section phi radians into the bend
A = np.pi * a**2
rn = (R + np.sqrt(R**2 - a**2)) / 2  # radius of the neutral axis
winkler = lambda phi: load * np.cos(phi) / A * (1 + R * (rn - (R - a)) / ((R - rn) * (R - a)))
phi = np.arctan2(-(X[:, 2] + shank), -(X[:, 0] - R))
fibre = (
    (np.abs(X[:, 1]) < 0.15 * a) & (np.abs(np.hypot(X[:, 0] - R, X[:, 2] + shank) - (R - a)) < 0.1 * a) & (X[:, 2] < -shank)
)
print(f"load F={load:.0f} N; Winkler-Bach inner fibre at phi=0: {winkler(0.0):.1f} MPa")
for lo in range(0, 90, 15):
    sel = fibre & (np.degrees(phi) >= lo) & (np.degrees(phi) < lo + 15)
    print(f"  phi {lo:2d}-{lo + 15:2d} deg: FE {svm[sel].max():.1f}  theory {winkler(np.radians(lo + 7.5)):.1f}")
peak, reference = svm[fibre & (phi > 0)].max(), winkler(0.0)  # the critical section: the start of the bend, inner fibre
print(f"  FE inner-fibre peak {peak:.1f} MPa vs Winkler-Bach {reference:.1f} MPa ({100 * (peak / reference - 1):+.1f} %)")
faces = np.asarray(d.mesh.cells_dict["triangle"])
free = np.unique(faces)[X[np.unique(faces), 2] < -1.5 * a]  # surface vertices away from the clamped face
at = free[svm[free].argmax()]
print(
    f"  largest surface value away from the clamp {svm[at]:.1f} MPa at phi={np.degrees(phi[at]):.0f} deg, y={X[at, 1]:.1f} mm"
)
assert abs(peak / reference - 1) < 0.1  # curved-beam theory (Winkler-Bach): within 10 %
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(
        Path(out) / "crane_hook_3d.npz",
        points=X,
        faces=faces,
        tets=tets,
        von_mises=svm,
        displacement=U[tree.query(X)[1]],
        fibre_phi=phi[fibre],
        fibre_fe=svm[fibre],
        load=load,
        geometry=[a, R, shank, tip],
    )
