import os
from pathlib import Path

# --8<-- [start:code]
"""A ship in oblique seas: a free-floating hull in a 3-D tank of linear potential flow, and the waves it adds to the sea."""

import time
from types import SimpleNamespace

import jax
import numpy as np

import jno

jax.config.update("jax_enable_x64", True)  # the tank is one complex system
run = jno.setup(__file__)
SCALE = 1.0  # multiplies the mesh sizes
G, RHO = 9.81, 1.025  # kN, m, s, t: pressure in kPa
H, LAM, A_W = 30.0, 36.0, 0.6  # water depth, wave length, wave amplitude
BETA = np.radians(40.0)  # the wave travels towards +x and +y: it meets the bow 40 degrees off the centre line
omega = lambda k: np.sqrt(G * k * np.tanh(k * H))  # the dispersion relation w^2 = g k tanh(k h)
K = 2 * np.pi / LAM
W = omega(K)
L, B, T, RB, ZG = 60.0, 11.0, 4.0, 2.0, -1.4  # hull: length, beam, draft, bilge radius; centre of mass below the waterline
KXX = 0.3 * B  # roll radius of gyration
XC, SPW = 250.0, 72.0  # the sea is clear to |x|, |y| = 250 m, then a damping zone two wave lengths wide

SOLVES, t0 = 9 + 4 * 9, time.time()  # the tank solves this script does; a line with the progress after each


def tick(done=[0]):
    done[0] += 1
    gone = time.time() - t0
    print(
        f"solve {done[0]}/{SOLVES} done, {gone / 60:.0f} min elapsed, ~{gone / done[0] * (SOLVES - done[0]) / 60:.0f} min left",
        flush=True,
    )


# ---- the hull: the waterplane (bow at -x, blunt stern) extruded down and cut by a section with rounded bilges
xs = np.linspace(-L / 2, L / 2, 41)
s = (xs + L / 2) / L
half_beam = B / 2 * np.minimum(np.clip(s / 0.35, 0, 1) ** 0.6, 0.45 + 0.55 * np.clip((1 - s) / 0.1, 0, 1) ** 0.7)
hbp = lambda x: np.interp(x, xs, half_beam)  # half beam at the waterline
side = [(x, h) for x, h in zip(xs, half_beam) if h > 0]
plan = [(xs[0], 0.0)] + [(x, -h) for x, h in side] + [(x, h) for x, h in side[::-1]]
arc = np.linspace(-np.pi / 2, 0, 7)[1:]
right = [(B / 2 - RB, -T)] + [(B / 2 - RB + RB * np.cos(t), -T + RB + RB * np.sin(t)) for t in arc] + [(B / 2, 0.0)]
section = [(-y, z) for y, z in right[::-1]] + right
hull = jno.shape.polygon(plan).extrude(T + 1).translate((0, 0, -T))
hull &= jno.shape.polygon(section).extrude(L + 4).rotate((0, 0, 0), (1, 1, 1), 2 * np.pi / 3).translate((-L / 2 - 2, 0, 0))

# ---- weight = buoyancy, section by section: the section area, its centroid, the volume and the centre of gravity
yy = np.linspace(0, B / 2, 2001)
keel = np.where(
    yy <= B / 2 - RB, -T, -T + RB - np.sqrt(np.maximum(RB**2 - (yy - (B / 2 - RB)) ** 2, 0))
)  # keel height at y
integral = lambda f: np.concatenate([[0], np.cumsum(0.5 * (f[1:] + f[:-1]) * np.diff(yy))])
area = lambda x: 2 * np.interp(hbp(x), yy, integral(-keel))  # submerged section area at x
z_sec = lambda x: 2 * np.interp(hbp(x), yy, integral(-(keel**2) / 2)) / np.maximum(area(x), 1e-9)  # height of its centroid
xq = np.linspace(-L / 2, L / 2, 2001)
VOL = np.trapezoid(area(xq), xq)
XG = np.trapezoid(area(xq) * xq, xq) / VOL
IT_PLAN = np.trapezoid(2 / 3 * hbp(xq) ** 3, xq)  # waterplane's second moment about the centre line, from the plan


# ---- the sea: a box of water minus the hull, meshed finer at the hull, the clear sea and the damping zone around it
def regions(
    dom, wall, xc, spw
):  # the coordinates (and normals) of the tank's regions, made once: every read-back must use the same ones
    ax = lambda name: dom.variable(name, split=True)[:3]
    return SimpleNamespace(
        dom=dom, xc=xc, spw=spw, inside=ax("interior"), surf=ax("surf"), wall=ax(wall), n=dom.variable(wall, normals=True)
    )


def ocean(xc, spw):
    """Water to |x|, |y| = xc plus a damping zone spw wide, the hull cut out."""
    near = lambda x, y, z: np.hypot(np.hypot(max(abs(x) - L / 2, 0), max(abs(y) - B / 2, 0)), max(-T - z, 0))
    size = lambda x, y, z: min(
        (min(1.5 + 0.25 * near(x, y, z), LAM / 15) + 0.025 * max(abs(x) - xc, abs(y) - xc, 0)) * SCALE + 0.3 * abs(z), 15.0
    )  # 1.5 m at the hull, 15 elements per wave length on the surface
    dom = (jno.shape.box(-xc - spw, -xc - spw, -H, xc + spw, xc + spw, 0) - hull).sized(size).domain()
    dom.tag("hull", lambda x, y, z: (np.abs(x) <= L / 2 + 1e-6) & (z >= -T - 1e-6) & (np.abs(y) <= hbp(x) + 1e-6))
    dom.tag("surf", lambda x, y, z: z > -1e-9)  # the free surface, the hull's waterline included
    return regions(dom, "hull", xc, spw)


# ---- the water: psi = phi_t as a complex amplitude (e^{i w t}); eta = -psi / g, pressure p = -rho psi
def wavenumber(w):  # the dispersion relation solved for k by fixed-point iteration
    k = w**2 / G
    for _ in range(80):
        k = w**2 / (G * np.tanh(k * H))
    return k


cosh_ratio = lambda z, k: jno.np.cosh(k * (z + H)) / np.cosh(k * H)
sinh_ratio = lambda z, k: jno.np.sinh(k * (z + H)) / np.cosh(k * H)
psi_inc = lambda x, y, z, k=K, beta=BETA: (
    -G * A_W * cosh_ratio(z, k) * jno.np.exp(-1j * k * (x * np.cos(beta) + y * np.sin(beta)))
)
dpsi_inc = lambda x, y, z, n, k=K, beta=BETA: (
    -G
    * A_W
    * k
    * jno.np.exp(-1j * k * (x * np.cos(beta) + y * np.sin(beta)))
    * (-1j * cosh_ratio(z, k) * (np.cos(beta) * n[..., 0:1] + np.sin(beta) * n[..., 1:2]) + sinh_ratio(z, k) * n[..., 2:3])
)
MODES = ("surge", "sway", "heave", "roll", "pitch", "yaw")
motion = lambda j, x, y, z, n: [
    n[..., 0:1],
    n[..., 1:2],
    n[..., 2:3],
    y * n[..., 2:3] - (z - ZG) * n[..., 1:2],
    (x - XG) * n[..., 2:3] - (z - ZG) * n[..., 0:1],
    (x - XG) * n[..., 1:2] - y * n[..., 0:1],
][j]  # the normal velocity of the unit motion j of the hull about its centre of gravity
lu = jno.solve.lu(backend="pardiso")


def tank(r, flux, w=W, strength=1.0):
    """Laplace for psi in the tank, the free surface with a damping zone, and psi_n = flux on the wall (hull or wavemaker)."""
    psi = r.dom.unknown.scalar(order=2)  # quadratic elements: the phase error of a wave goes with (k h)^4
    v = psi.test()
    at = lambda f, c: f.bind(x=c[0], y=c[1], z=c[2])
    nu = (
        strength
        * w
        * jno.np.maximum(jno.np.maximum(jno.np.abs(r.surf[0]), jno.np.abs(r.surf[1])) - r.xc, 0) ** 2
        / r.spw**2
    )
    grad = lambda f: jno.np.jacobian(at(f, r.inside), list(r.inside))
    fem = jno.fem(
        [
            jno.np.inner(grad(psi), grad(v)),  # Laplace
            -(w**2 - nu**2 - 2j * w * nu) / G * at(psi, r.surf) * at(v, r.surf),  # psi_z = (w^2 - nu^2 - 2i w nu) psi / g
            -flux(*r.wall, r.n) * at(v, r.wall),
        ]
    )
    state = np.asarray(fem.solve(linear=lu))
    tick()
    return SimpleNamespace(fem=fem, psi=psi, v=v, state=state, r=r)


sea = ocean(XC, SPW)
xh, yh, zh = sea.wall
xf, yf, zf = sea.surf
nh = sea.n  # pointing out of the water, into the hull
at = lambda f, x, y, z: f.bind(x=x, y=y, z=z)
rows = lambda sol, f: np.asarray(
    sol.fem.eval(f * at(sol.v, xh, yh, zh), sol.state)
)  # int f v dS on the hull, for every test function v
force = lambda sol, j, extra=lambda x, y, z: 0.0: (
    np.sum(  # the force in mode j on the ship from p = -rho psi, psi = extra + the solved field
        sol.fem.eval(
            -RHO
            * (extra(*sol.r.wall) + at(sol.psi, *sol.r.wall))
            * motion(j, *sol.r.wall, sol.r.n)
            * at(sol.v, *sol.r.wall),
            sol.state,
        )
    )
)


def hydrodynamics(w, r=sea, modes=range(6), strength=1.0):
    """The wave on the hull held still (diffraction), then unit motion in each of the `modes` (radiation), at frequency w."""
    k = wavenumber(w)
    solves = {"diffraction": tank(r, lambda x, y, z, n: -dpsi_inc(x, y, z, n, k), w, strength)}
    for j in modes:
        solves[j] = tank(r, lambda x, y, z, n, j=j: -(w**2) * motion(j, x, y, z, n), w, strength)
    F = np.array(
        [force(solves["diffraction"], j, lambda x, y, z: psi_inc(x, y, z, k)) for j in range(6)]
    )  # the wave's force on the held hull
    Q = np.array(
        [[force(solves[i], j) if i in modes else 0.0 for i in range(6)] for j in range(6)]
    )  # force in mode j of unit motion i: w^2 A - i w B
    return SimpleNamespace(w=w, solves=solves, F=F, Q=Q)


# ---- check 1: a wave maker at one end of an empty strip of the tank sends an Airy wave through it
strip = jno.shape.box(-100.0, 0, -H, 100.0 + SPW, 20, 0).sized(lambda x, y, z: min(LAM / 15 + 0.3 * abs(z), 15.0)).domain()
strip.tag("surf", lambda x, y, z: z > -1e-9)
strip.tag("maker", lambda x, y, z: x < -100.0 + 1e-6)
free = tank(regions(strip, "maker", 100.0, SPW), lambda x, y, z, n: dpsi_inc(x, y, z, n, beta=0.0))
at_s = np.asarray(free.fem.field_points[0])
line = np.where((at_s[:, 2] > -1e-9) & (at_s[:, 1] < 1e-9) & (at_s[:, 0] < 100.0))[0]
line = line[np.argsort(at_s[line, 0])]
k_fe = -np.polyfit(at_s[line, 0], np.unwrap(np.angle(free.state[line])), 1)[0]
amp = np.abs(free.state[line]) / G
print(
    f"free wave: k = {k_fe:.6f} against {K:.6f} (speed {W / k_fe:.3f} against {W / K:.3f} m/s), amplitude {amp.min():.4f} to {amp.max():.4f} m"
)
assert abs(k_fe / K - 1) < 3e-3 and np.ptp(amp) < 0.05 * A_W  # the amplitude ripple is the damping zone's reflection

# ---- the six radiation solves and the diffraction solve, and the forces they give
hd = hydrodynamics(W)
dif = hd.solves["diffraction"]
pts = np.asarray(dif.fem.field_points[0])
print(
    f"tank: {len(pts)} complex unknowns (quadratic elements on {len(sea.dom.mesh_connectivity['tetrahedra'])} tetrahedra)"
)

# ---- hydrostatics from the wetted surface: the rows of n_z integrate functions of x, y, z over the waterplane and the volume
rows_z = rows(dif, nh[..., 2:3]).real  # n_z weights at the hull nodes
A_WP, S_WP, I_L, I_T = (np.sum(f * rows_z) for f in (1.0, pts[:, 0] - XG, (pts[:, 0] - XG) ** 2, pts[:, 1] ** 2))
V_S, VZ = (-np.sum(pts[:, 2] ** a * rows_z / a) for a in (1, 2))  # volume and its first moment about the waterline
print(
    f"hull: volume {V_S:.0f} m^3 against {VOL:.0f} from the sections, waterplane {A_WP:.0f} m^2, "
    f"centre of buoyancy {VZ / V_S:.2f} m, waterplane inertia about the centre line {I_T:.0f} m^4 against {IT_PLAN:.0f} from the plan"
)
assert abs(V_S / VOL - 1) < 0.01 and abs(I_T / IT_PLAN - 1) < 0.01

# ---- the rigid ship: (C - w^2 M - Q) X = F, six modes about the centre of mass, no mooring
mass = RHO * V_S
pitch_inertia = RHO * np.trapezoid(area(xq) * (xq - XG) ** 2, xq)  # the weight is spread like the buoyancy
M = np.diag([mass, mass, mass, mass * KXX**2, pitch_inertia, pitch_inertia])
C = np.zeros((6, 6))  # hydrostatic stiffness: only heave, roll and pitch are restored (surge, sway, yaw are free)
C[2, 2] = RHO * G * A_WP
C[2, 4] = C[4, 2] = RHO * G * S_WP
C[3, 3] = RHO * G * (I_T + VZ - V_S * ZG)  # waterplane + (centre of buoyancy - centre of gravity) V
C[4, 4] = RHO * G * (I_L + VZ - V_S * ZG)
X = np.linalg.solve(C - W**2 * M - hd.Q, hd.F)
GM = C[3, 3] / (RHO * G * V_S)
print(
    f"metacentric height {GM:.2f} m; added mass and damping in roll {hd.Q[3, 3].real / W**2:.0f} t m^2, {-hd.Q[3, 3].imag / W:.0f} kN m s"
)
print(
    "motion per wave amplitude: "
    + ", ".join(f"{n} {abs(X[j]) * (np.degrees(1) if j in (3, 4, 5) else 1):.2f}" for j, n in enumerate(MODES))
    + f" (m, degrees) for a wave of amplitude {A_W} m"
)

# ---- check 2, Haskind: the exciting force from the radiation potentials and the incident wave alone, no diffraction solve
dpsi_rows = rows(dif, dpsi_inc(xh, yh, zh, nh))  # int dpsi_inc/dn v dS
F_haskind = np.array(
    [
        np.sum(rows(dif, -RHO * psi_inc(xh, yh, zh) * motion(j, xh, yh, zh, nh)))
        - RHO / W**2 * np.sum(hd.solves[j].state * dpsi_rows)
        for j in range(6)
    ]
)
haskind = np.abs(F_haskind - hd.F).max() / np.abs(hd.F).max()
reciprocity = np.abs(hd.Q - hd.Q.T).max() / np.abs(hd.Q).max()
print(
    f"Haskind: exciting force from the radiation fields differs by {haskind:.1e}; added mass and damping matrices symmetric to {reciprocity:.1e}"
)
assert haskind < 1e-6 and reciprocity < 1e-6

# ---- check 3, energy: the power the ship adds to the sea leaves through the damping zone (hull integral against surface integral)
nu_zone = lambda x, y: W * jno.np.maximum(jno.np.maximum(jno.np.abs(x), jno.np.abs(y)) - XC, 0) ** 2 / SPW**2
c_g = 0.5 * W / K * (1 + 2 * K * H / np.sinh(2 * K * H))
P_wave = 0.5 * RHO * G * A_W**2 * c_g  # the incident wave's power per metre of crest
zone_rows = lambda state: np.asarray(dif.fem.eval(nu_zone(xf, yf) * at(dif.psi, xf, yf, zf) * at(dif.v, xf, yf, zf), state))
for name, coef in (("held hull", np.zeros(6)), ("free ship", X)):
    state = dif.state + sum(c * hd.solves[j].state for j, c in enumerate(coef))  # scattered + radiated psi
    g_rows = rows(dif, -dpsi_inc(xh, yh, zh, nh)) + sum(
        c * rows(dif, -(W**2) * motion(j, xh, yh, zh, nh)) for j, c in enumerate(coef)
    )
    p_hull, p_zone = (
        np.vdot(state, g_rows),
        np.vdot(state, 2 * W / G * zone_rows(state)),
    )  # int psi_n^* psi dS and int 2 w nu |psi|^2 / g dS
    P_hull, P_abs = RHO / (2 * W) * p_hull.imag, RHO / (2 * W) * p_zone.real  # kW
    print(
        f"energy, {name}: the hull gives the sea {P_hull:.1f} kW, the damping zone absorbs {P_abs:.1f} kW: as much as {P_hull / P_wave:.1f} m of the incident crest carries"
    )
    assert abs(P_hull / P_abs - 1) < 1e-6 and P_abs > 0

# ---- check 4, the damping zone is a radiation condition: 1.5 times as strong, the exciting force changes by
dif_b = tank(sea, lambda x, y, z, n: -dpsi_inc(x, y, z, n), strength=1.5)
F_b = np.array([force(dif_b, j, psi_inc) for j in range(6)])
reflection = np.abs(F_b - hd.F).max() / np.abs(hd.F).max()
print(f"damping zone 1.5 times stronger: exciting force changes by {reflection:.1e}")
assert reflection < 0.02

# ---- check 5, the roll resonance: the frequency scanned on a smaller sea, the peak of the roll against the natural frequency
sea_s = ocean(80.0, SPW)
anti = [1, 3, 5]  # sway, roll, yaw: the modes the hull's mirror symmetry decouples from surge, heave and pitch
coupling = np.abs(hd.Q[np.ix_([0, 2, 4], anti)]).max() / np.abs(hd.Q).max()
print(f"surge, heave and pitch against sway, roll and yaw: coupling {coupling:.1e} of the largest entry")
ws = np.linspace(0.97, 1.27, 9)
roll, a_roll = [], []
for w in ws:
    hs = hydrodynamics(w, sea_s, anti)
    roll.append(abs(np.linalg.solve((C - w**2 * M - hs.Q)[np.ix_(anti, anti)], hs.F[anti])[1]))
    a_roll.append(hs.Q[3, 3].real / w**2)
roll, a_roll = np.array(roll), np.array(a_roll)
net = C[3, 3] - ws**2 * (M[3, 3] + a_roll)  # restoring minus inertia, added inertia included: zero at the natural frequency
w_nat = np.interp(0.0, net[::-1], ws[::-1])  # the zero of `net`, linearly between the scan points
i = int(roll.argmax())  # the largest roll of the scan
w_peak = ws[i] - 0.5 * (ws[1] - ws[0]) * (roll[i + 1] - roll[i - 1]) / (
    roll[i + 1] - 2 * roll[i] + roll[i - 1]
)  # vertex of the parabola through the peak
print(
    f"roll: natural frequency {w_nat:.3f} rad/s ({2 * np.pi / w_nat:.2f} s) from the hydrostatics and the added inertia, resonance of the scan at {w_peak:.3f} rad/s"
)
assert 0 < i < len(ws) - 1 and abs(w_peak / w_nat - 1) < 0.05

# ---- the hull girder: shear force and bending moment along the ship from the pressure on the hull, the hydrostatics and the inertia
FB, T_DECK, T_SIDE = 3.0, 0.020, 0.012  # freeboard, deck and bottom plating, side plating (m): an assumed box section
ZREF = (FB - T) / 2  # its neutral axis
parts = [(dif, 1.0, psi_inc(xh, yh, zh))] + [(hd.solves[j], X[j], 0.0) for j in range(6)]
nodal = (
    lambda k: sum(  # the pressure's force component k at every hull node, for the whole motion
        c
        * np.asarray(
            sol.fem.eval(-RHO * (e + at(sol.psi, xh, yh, zh)) * nh[..., k : k + 1] * at(sol.v, xh, yh, zh), sol.state)
        )
        for sol, c, e in parts
    )
)
f_x, f_z = nodal(0), nodal(2)
xst = np.linspace(-L / 2, L / 2, 121)  # stations from the bow
order = np.argsort(pts[:, 0])
left = lambda w: np.concatenate([[0], np.cumsum(w[order])])[
    np.searchsorted(pts[order, 0], xst, side="right")
]  # nodal values left of a station
xi = np.linspace(-L / 2, L / 2, 4001)
along = lambda f: np.interp(
    xst, xi, np.concatenate([[0], np.cumsum(0.5 * (f[1:] + f[:-1]) * np.diff(xi))])
)  # integral from the bow
m_line = mass * area(xi) / VOL  # mass per metre
q_line = (W**2 * m_line - RHO * G * 2 * hbp(xi)) * (
    X[2] + (xi - XG) * X[4]
)  # inertia and the hydrostatic change of a heaving, pitching hull
tilt = m_line * G * X[4]  # the weight and the buoyancy, tilted against each other
shear = left(f_z) + along(q_line)
moment = (  # sagging +, about the neutral axis: vertical loads (x_s - x), horizontal loads their height above it
    xst * left(f_z)
    - left(pts[:, 0] * f_z)
    + left((pts[:, 2] - ZREF) * f_x)
    + xst * along(q_line)
    - along(xi * q_line)
    + along((ZG - ZREF) * (W**2 * m_line * X[0] - tilt) + (z_sec(xi) - ZREF) * tilt)
)
closure = max(abs(shear[-1]) / abs(shear).max(), abs(moment[-1]) / abs(moment).max())
I_sec = (
    2 * T_DECK * np.maximum(2 * hbp(xst), 2.0) * ((FB + T) / 2) ** 2 + 2 * T_SIDE * (FB + T) ** 3 / 12
)  # second moment of the box section
sigma_deck = (
    -moment * (FB - ZREF) / I_sec / 1e3
)  # MPa, tension positive, a complex amplitude: sagging puts the deck in compression
print(
    f"hull girder: bending moment {abs(moment).max():.0f} kN m at x = {xst[np.abs(moment).argmax()]:.1f} m, deck stress {abs(sigma_deck).max():.1f} MPa; the loads close at the stern to {closure:.1%}"
)
assert closure < 0.1
# --8<-- [end:code]

if out := os.environ.get("JNO_FIGURE_DATA"):
    from scipy.spatial import cKDTree

    mesh = sea.dom.mesh_connectivity
    pt, tet = np.asarray(mesh["points"]), np.asarray(mesh["tetrahedra"])
    assert np.allclose(pt, pts[: len(pt)])  # the first nodes of a P2 field are the mesh vertices
    faces = np.sort(tet[:, [[1, 2, 3], [0, 3, 2], [0, 1, 3], [0, 2, 1]]].reshape(-1, 3), axis=1)
    faces, count = np.unique(faces, axis=0, return_counts=True)
    faces = faces[count == 1]  # the boundary triangles
    top = faces[(pt[faces, 2] > -1e-9).all(1)]  # those on the free surface
    top = top[(np.abs(pt[top, :2]).max(axis=(1, 2)) <= XC)]  # the clear sea only
    mid = lambda i, j: cKDTree(pts).query((pts[i] + pts[j]) / 2)[1]  # the P2 node in the middle of an edge
    ab, bc, ca = mid(top[:, 0], top[:, 1]), mid(top[:, 1], top[:, 2]), mid(top[:, 2], top[:, 0])
    a, b, c = top.T
    sub = np.concatenate(
        [np.stack(t, 1) for t in ((a, ab, ca), (ab, b, bc), (ca, bc, c), (ab, bc, ca))]
    )  # four per triangle
    on_surface = np.unique(sub)
    np.savez_compressed(
        Path(out) / "ship_in_waves.npz",
        surface_nodes=pts[on_surface],
        surface_triangles=np.searchsorted(on_surface, sub),
        psi_incident=-G
        * A_W
        * np.exp(-1j * K * (pts[on_surface, 0] * np.cos(BETA) + pts[on_surface, 1] * np.sin(BETA))),  # at z = 0
        psi_scattered=dif.state[on_surface],
        psi_radiated=sum(X[j] * hd.solves[j].state for j in range(6))[on_surface],
        motion=X,
        centre=[XG, ZG],
        wave=[A_W, LAM, W, G, H, K, BETA],
        ship=[L, B, T, FB],
        stations=xst,
        moment=moment,
        shear=shear,
        sigma_deck=sigma_deck,
        half_beam=hbp(xst),
        clear=[XC, SPW],
    )
