import os
from pathlib import Path

# --8<-- [start:code]
"""A ringing arch bridge: a gmsh outline imported into jNO, its modes, and the ringing after a release."""

import gmsh
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, rho = 3.0e7, 0.2, 2.4  # concrete in kN, m, s (so t/m^3)
lam, mu = E * nu / (1 - nu**2), E / (2 * (1 + nu))  # plane-stress Lame parameters
brake = 10.0  # kN/m^2: braking traction on the deck before the release
T, N = 0.7, 700  # about twelve periods of the first mode

# the outline, in a few lines of gmsh: deck, arch ring, columns and end walls, minus the opening under the arch
gmsh.initialize()
gmsh.model.add("bridge")
occ = gmsh.model.occ
box = lambda x0, y0, x1, y1: (2, occ.addRectangle(x0, y0, 0, x1 - x0, y1 - y0))
disk = lambda r: (2, occ.addDisk(10, -2.4, 0, r, r))
columns = [box(10 + s * c - 0.4, 0, 10 + s * c + 0.4, 8) for c in (0, 3.8, 7.0) for s in (-1, 1)]
parts = [box(0, 7.5, 20, 8.5), disk(8.6), box(0, 0, 0.8, 8.5), box(19.2, 0, 20, 8.5)] + columns
body, _ = occ.fuse(parts[:1], parts[1:])
inside, _ = occ.intersect(body, [box(0, 0, 20, 8.5)])
bridge, _ = occ.cut(inside, [disk(7.4)])
occ.synchronize()
bbox = lambda c: gmsh.model.getBoundingBox(1, c)  # xmin, ymin, zmin, xmax, ymax, zmax
curves = gmsh.model.getEntities(1)
gmsh.model.addPhysicalGroup(2, [b for _, b in bridge], name="bridge")
gmsh.model.addPhysicalGroup(1, [c for _, c in curves if bbox(c)[4] < 1e-6], name="feet")  # on the ground y = 0
gmsh.model.addPhysicalGroup(1, [c for _, c in curves if bbox(c)[1] > 8.5 - 1e-6], name="deck")  # the road, y = 8.5
gmsh.option.setNumber("Mesh.MeshSizeMax", 0.25)
gmsh.model.mesh.generate(2)
mesh_file = Path(__file__).with_name("ringing_bridge.msh")
gmsh.write(str(mesh_file))
gmsh.finalize()

d = jno.domain(str(mesh_file), time=(0.0, T, N))  # the file's physical groups are the tags
x, y, t = d.variable("interior", split=True)
xf, yf, _ = d.variable("feet", split=True)  # clamped abutments
xd, yd, _ = d.variable("deck", split=True)
x0, y0, t0 = d.variable("initial", split=True)
u = d.unknown.vector(2, order=2)
v = u.test()

eps = lambda w: jno.np.symgrad(w, [x, y])
dot, ddot, tr = jno.np.inner, 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 * dot(u.bind(x=x, y=y), v.bind(x=x, y=y))

# modal analysis K phi = omega^2 M phi, the four lowest modes (shift-invert about 0)
K = jno.fem([stiffness, u(xf, yf) - (0.0, 0.0)])
M = jno.fem([mass])
w2, modes = K.eigs(mass=[mass], k=4, sigma=0.0)
freq = np.sqrt(np.asarray(w2).ravel()) / (2 * np.pi)

# the bridge is pushed along the deck by a braking traction; released from that static state it rings
brake_load = dot(jno.np.vector(brake, 0.0), v.bind(x=xd, y=yd))
u_static = np.asarray(jno.fem([stiffness, u(xf, yf) - (0.0, 0.0), brake_load]).solve(linear=jno.solve.lu()))

# rho u_tt = div sigma(u): the second time derivative is reduced to [u, u_t] and marched by the trapezoidal rule
fem = jno.fem(
    [
        rho * dot(u.bind(x=x, y=y, t=t).tt, v) + stiffness,
        u(xf, yf) - (0.0, 0.0),
        u(x0, y0) - (0.0, 0.0),
        u.bind(x=x0, y=y0, t=t0).t - (0.0, 0.0),
    ]
)
n = fem.offsets[1]
traj = np.asarray(fem.solve(x0=np.concatenate([u_static, np.zeros(n)]), linear=jno.solve.lu()).eval())
disp, vel = traj[:, :n], traj[:, n:]
ts = np.linspace(fem.t0, fem.t1, len(traj))

# the dominant frequency of the mid-deck motion (zero-padded, Hann-windowed spectrum) against the first eigenfrequency
pts = np.asarray(fem.points)
mid = int(np.argmin(np.hypot(pts[:, 0] - 10, pts[:, 1] - 8.5)))
sig = disp[:, 2 * mid]
spectrum = np.abs(np.fft.rfft((sig - sig.mean()) * np.hanning(len(sig)), 32 * len(sig)))
f_ring = np.fft.rfftfreq(32 * len(sig), ts[1] - ts[0])[spectrum.argmax()]

energy = lambda A, w: 0.5 * np.einsum("ti,ti->t", w, np.asarray(A @ w.T).T)
total = energy(M.A, vel) + energy(K.A, disp)  # kinetic + strain energy
drift = float(np.abs(total / total[0] - 1).max())
clamp = float(np.abs(disp.reshape(len(ts), -1, 2)[:, pts[:, 1] < 1e-9]).max())
print(
    f"ringing bridge: dofs={fem.dofs}  first modes {np.round(freq, 2)} Hz  mid-deck |u| released from {np.abs(sig).max():.2e} m"
)
print(
    f"  ringing at {f_ring:.2f} Hz vs first eigenfrequency {freq[0]:.2f} Hz   energy drift = {drift:.1e}   clamped max |u| = {clamp:.1e}"
)
assert abs(f_ring / freq[0] - 1) < 0.03 and drift < 1e-3 and clamp < 1e-8  # it rings at its first mode, conserving energy
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    vert = np.asarray(d.built_mesh.points)[:, :2]
    at = cKDTree(pts).query(vert)[1]  # the P2 node of every mesh vertex
    np.savez_compressed(
        Path(out) / "ringing_bridge.npz",
        points=vert,
        cells=np.asarray(d.mesh.cells_dict["triangle"]),
        displacement=disp.reshape(len(ts), -1, 2)[:, at].astype(np.float32),
        modes=np.asarray(modes).reshape(-1, 2, 4)[at],
        t=ts,
        freq=freq,
        f_ring=f_ring,
    )
