Skip to content

A ship in ocean waves

FEM Coupling ship_in_waves.py

A 60 m ship floats free in oblique waves of 36 m length that meet its bow 40° off the centre line. The hull reflects the wave on its weather side and leaves a shadow in its lee; the ship, held by nothing but the water, surges, sways, heaves, rolls, pitches and yaws, and the waves its own motion makes join the sea. Along the hull the pressure and the inertia add up to the bending moment of the hull girder, and beam theory turns it into the stress in the deck.

The sea surface in oblique waves as a lit three-dimensional surface, drawn over one wave period, with a 60 m ship floating in it. The waves travel towards the upper right and meet the ship's bow, at the left, 40 degrees off its centre line; the surface is coloured by elevation from -0.6 m (brown) to 0.6 m (teal). The ship rolls and pitches with the waves; around it the sea carries the wave the hull reflects on the weather side, the shadow behind it and the waves it radiates. The deck is coloured by its computed stress, red in tension and blue in compression, and the strip under the sea shows the same stress along the ship.

The computed sea surface around the ship over one wave period: the incident wave, the wave the held hull scatters and the waves the moving hull radiates. Heave and the rotations are drawn four times larger than true. The deck is coloured by its computed stress.

Two plan views of the whole computed sea, 500 m by 500 m, over one wave period, on the same brown-teal colour map. Left: the sea surface, the incident wave with the ship's reflection (the checker pattern, where the reflected wave crosses the incident one) and its shadow. Right: only what the ship adds, the scattered and radiated elevation on its own colour range: a reflected wave on the weather side that leaves to the lower right and crosses the incident wave, a quiet shadow in the lee to the upper right, and rings spreading from the hull. The ship is the dark shape at the centre; the arrow gives the direction of the incident wave.

The whole sea, 500 m by 500 m. Left: the surface. Right: only what the ship adds, the scattered and radiated waves.

The problem

The water is linear potential flow at the wave frequency. With \(\psi=\phi_t=\mathrm{Re}(\hat\psi e^{i\omega t})\), the elevation is \(\eta=-\psi/g\) and the pressure \(p=-\rho\psi\):

\[\Delta\hat\psi=0,\qquad \hat\psi_z=\frac{\omega^2-\nu^2-2i\omega\nu}{g}\,\hat\psi\ \text{on the free surface},\qquad \hat\psi_n=g\ \text{on the hull},\qquad \omega^2=gk\tanh kh,\]

with \(\nu\) a damping zone that rises from 0 to \(\omega\) over two wave lengths at the rim, a numerical beach. The solves are for what the ship adds, so the beach only sees outgoing waves. With the hull held still, \(g=-\partial_n\hat\psi_\text{inc}\) (diffraction); moving it with a unit motion in mode \(j\), \(g=-\omega^2\,(\mathbf m_j\cdot\mathbf n)\) (radiation).

The ship is a rigid body of the mass of the water it displaces, with hydrostatic stiffness \(C\) and mass \(M\). The diffraction pressure gives the exciting force \(\hat F\), the six radiation pressures the force matrix \(Q\) (added mass and damping), and the motion follows from

\[\left(C - \omega^2 M - Q\right)\hat X = \hat F .\]

Two exact checks. The Haskind relation gives the exciting force from the radiation fields alone, \(F_k = -\rho\!\int\hat\psi_\text{inc}\,(\mathbf m_k\!\cdot\!\mathbf n)\,dS + (\rho/\omega^2)\!\int\hat\psi_k\,\partial_n\hat\psi_\text{inc}\,dS\), and the power the ship sends into the sea must leave through the damping zone:

\[\frac{\rho}{2\omega}\,\mathrm{Im}\oint\hat\psi_s^*\,\partial_n\hat\psi_s\,dS = \frac{\rho}{2\omega}\int\frac{2\omega\nu}{g}\,|\hat\psi_s|^2\,dS .\]

The jNO code

The hull is the waterplane extruded down and cut by a rounded section (& is the intersection), and the sea is a box of water minus the hull, graded towards it:

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))
...
dom = (jno.shape.box(-xc - spw, -xc - spw, -H, xc + spw, xc + spw, 0) - hull).sized(size).domain()

The tank is one function: Laplace, the free surface with its complex damping coefficient, and the flux through the hull. With a different flux it is the diffraction problem or one of the six radiation problems:

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))
    return SimpleNamespace(fem=fem, psi=psi, v=v, state=state, r=r)

The forces are read at the hull nodes with fem.eval, the pressure times the normal velocity of each mode:

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,
        )
    )
)

Result

799 483 complex unknowns (P2 on 473 903 tetrahedra), seven solves. A wave of amplitude 0.6 m moves the ship by 0.04 m in surge, 0.05 m in sway, 0.04 m in heave, 1.35° in roll, 1.17° in pitch and 0.24° in yaw.

check result
free wave in an empty strip: wavenumber against the dispersion relation 0.174302 / 0.174533
hull volume from the wetted surface / from the sections 2164 / 2167 m³
Haskind: exciting force from the radiation fields \(4.3\times10^{-15}\)
added mass and damping matrices symmetric \(7.9\times10^{-16}\)
power from the hull = power absorbed by the beach (held hull) 337 kW = 337 kW
beach 1.5 times stronger: change in the exciting force 0.037 %
roll resonance of a frequency scan / from hydrostatics and added inertia 1.090 / 1.095 rad/s
hull girder loads at the stern, where they vanish 1.0 % of their maxima

The held hull scatters as much power as 49.7 m of the incident crest carries. The largest bending moment, 2411 kN m, gives a deck stress of 1.4 MPa.

The hull girder from the side at the two extreme instants of the cycle, sagging (a trough amidships) and hogging (a crest amidships), at true scale with the computed motion. The hull's side view is coloured by the axial stress in the box section from beam theory, from -1.4 MPa (blue, compression) to 1.4 MPa (red, tension): the deck is in compression and the bottom in tension when the ship sags, the other way round when it hogs. The line is the computed sea surface along the centre line.

The axial stress of the hull girder at the instants of largest sagging and hogging, with the computed sea surface along the centre line.

Full script

The whole script, as it runs in the tests
"""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