import os
from pathlib import Path

# --8<-- [start:code]
"""A steel tuning fork: its vibration modes from a 3-D eigenproblem, the fundamental against beam theory."""

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

import jno

jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
E, nu, rho = 2.0e5, 0.3, 7.85e-9  # steel in N, mm, tonne, s (so the density is in t/mm^3, the stiffness in MPa)
lam, mu = E * nu / ((1 + nu) * (1 - 2 * nu)), E / (2 * (1 + nu))
T, GAP, B, L = 5.0, 5.0, 7.0, 88.8  # prong thickness (in the plane of the fork), gap, depth (out of plane), length
R_STEM, L_STEM = 3.0, 45.0
W = 2 * T + GAP  # outer width of the U


def fork(h):
    """The fork: a U with two straight prongs, extruded to its depth, and a round stem under the bend."""
    outer = jno.shape.disk(0, 0, W / 2) | jno.shape.rect(-W / 2, 0, W / 2, L)
    slot = jno.shape.disk(0, 0, GAP / 2) | jno.shape.rect(-GAP / 2, 0, GAP / 2, L + 1)
    stem = jno.shape.cylinder(0, -W / 2 + 1, B / 2, 0, -(L_STEM + 1), 0, R_STEM)
    return ((outer - slot).extrude(B) | stem).sized(h).domain()


def vibration(d, k, f0, clamped=None):
    """The k eigenfrequencies (Hz) nearest f0 and mode shapes of the steel body d, free or clamped where `clamped` holds."""
    x, y, z, _ = d.variable("interior", split=True)
    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)
    mass = rho * jno.np.inner(u.bind(x=x, y=y, z=z), v.bind(x=x, y=y, z=z))
    cx, cy, cz, _ = d.variable("clamp", where=clamped or (lambda x, y, z: x > 1e9), split=True)
    K = jno.fem([stiffness] + ([u(cx, cy, cz) - (0.0, 0.0, 0.0)] if clamped else []))  # a free body has no condition
    w2, X = K.eigs(mass=[mass], k=k, sigma=(2 * np.pi * f0) ** 2)  # K phi = omega^2 M phi, shift-invert about f0
    return K, np.sqrt(np.abs(np.asarray(w2).ravel())) / (2 * np.pi), np.asarray(X)


# the fork on two meshes: six rigid-body modes at zero frequency, then the vibrations
meshes = {h: fork(h) for h in (2.0, 1.25)}
runs = {h: vibration(d, 14, 200.0) for h, d in meshes.items()}
for h, (K, f, _) in runs.items():
    print(f"mesh size {h} mm: {K.dofs} DOFs, f1 = {f[6]:.2f} Hz, f2..f5 = {np.round(f[7:11], 1)} Hz")
K, f, X = runs[1.25]
assert f[:6].max() < 1e-2 * f[6], "six rigid-body modes (three translations, three rotations) have no frequency"
assert abs(runs[2.0][1][6] / f[6] - 1) < 0.01  # the coarser mesh changes the fundamental by under 1 %

# the fundamental against beam theory: a prong as a cantilever of length L clamped at the start of the bend
c = np.sqrt(E / rho)  # speed of sound of a thin bar, mm/s
beam = 1.875104**2 / (2 * np.pi * L**2) * c * T / np.sqrt(12)  # sqrt(E I / (rho A)) = c T / sqrt(12)
prong = jno.shape.box(0, 0, 0, T, L, B, size=1.25).domain()
clamped = vibration(prong, 3, 0.9 * beam, clamped=lambda x, y, z: y < 1e-9)[1][0]  # the lowest of its modes
print(f"clamped prong: {clamped:.1f} Hz (3-D) vs {beam:.1f} Hz (beam theory); the fork rings at {f[6]:.1f} Hz")
assert abs(clamped / beam - 1) < 0.05  # the 3-D prong is a cantilever, to the accuracy of beam theory
assert 0.8 < f[6] / beam < 1.0  # the fork is lower: its bend gives and carries the stem

# the symmetry of each mode about the plane x = 0 of the fork: u(-x, y, z) = s (-u_x, u_y, u_z)(x, y, z), s = +1 or -1
P, U = np.asarray(K.points), X.reshape(-1, 3, X.shape[1])[:, :, 6:]
image = LinearNDInterpolator(P, U.reshape(len(P), -1))(P * [-1, 1, 1])  # the field at the mirror image of every node
lost = np.isnan(image).any(1)  # on the surface the image can fall just outside the mesh: the nearest node stands in
image[lost] = U.reshape(len(P), -1)[cKDTree(P).query(P[lost] * [-1, 1, 1])[1]]
mirrored = image.reshape(U.shape) * np.array([-1, 1, 1])[None, :, None]  # (-u_x, u_y, u_z) there
s = np.einsum("nck,nck->k", U, mirrored) / np.einsum("nck,nck->k", U, U)  # +1: symmetric, -1: antisymmetric
defect = np.linalg.norm(U - np.sign(s) * mirrored, axis=(0, 1)) / np.linalg.norm(U, axis=(0, 1))
print("symmetry about the fork's mid-plane (+1 symmetric): " + " ".join(f"{v:+.2f}" for v in s))
assert s[0] > 0.95 and defect[0] < 0.05  # the fundamental is symmetric: the prongs swing towards and away from each other
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    d = meshes[1.25]
    np.savez_compressed(
        Path(out) / "tuning_fork_modes.npz",
        vertices=np.asarray(d.built_mesh.points),
        triangles=np.asarray(d.mesh.cells_dict["triangle"]),
        nodes=P,
        modes=U,
        freq=f[6:],
        symmetry=s,
        geometry=[T, GAP, B, L, R_STEM, L_STEM],
    )
