"""Synthetic height records, directional ridge fits and weak-amplitude pulse checks.

Run with Python 3, NumPy and SciPy. No measured data are used.
"""
import numpy as np
from scipy.signal import hilbert

ORIGIN = 1.  # m
SPEED = 1.   # m/s
WIDTH = .2   # m


def recover_envelope(rate):
    """Demodulate a real-valued gauge record with a calibrated carrier."""
    g = 9.81
    f0, fm, z = 1.0, 0.05, 2.0
    omega = 2*np.pi*f0
    k0 = omega**2/g
    cg = g/(2*omega)
    time = np.arange(80*rate)/rate
    retarded = time-z/cg
    envelope = .01*(1+.3*np.cos(2*np.pi*fm*retarded))*np.exp(.37j)
    carrier = np.exp(1j*(omega*time-k0*z))
    record = np.real(envelope*carrier)
    recovered = hilbert(record)/carrier
    print("Gauge sample rate, k0, cg, maximum complex error (m):",
          rate, k0, cg, np.max(abs(recovered-envelope)))


def tank_height(length, dx, dt):
    """Synthetic signal at each camera pixel and time."""
    amplitude = .004
    x = np.linspace(0, length, round(length/dx)+1)
    times = np.arange(round(11/dt)+1)*dt
    incoming = ORIGIN+SPEED*times[:, None]
    returning = 2*length-incoming
    eta = amplitude*(np.exp(-.5*((x-incoming)/WIDTH)**2)
                     + .7*np.exp(-.5*((x-returning)/WIDTH)**2))
    return x, times, eta


def tank_ridge(length, dx, dt):
    """Extract the height maximum and fit its position before and after reflection."""
    x, times, eta = tank_height(length, dx, dt)
    centers = x[np.argmax(eta, axis=1)]
    def fit(start, end):
        selection = (times >= start-1e-9) & (times <= end+1e-9)
        return np.polyfit(times[selection], centers[selection], 1)[0]
    wall_time = (length-ORIGIN)/SPEED
    margin = 3*WIDTH/SPEED
    print("Length, dx, dt; speeds 3–8 s, 3–11 s, incident [m/s]:",
          length, dx, dt, fit(3., 8.), fit(3., 11.), fit(3., min(11., wall_time-margin)))
    if wall_time+margin < times[-1]:
        print("Return [m/s]:", fit(wall_time+margin, 11.))


if __name__ == "__main__":
    for rate in (10, 20):
        recover_envelope(rate)
    for dx, dt in ((.02, .05), (.01, .025)):
        for length in (10., 14.):
            tank_ridge(length, dx, dt)
    depth, height = .2, .004
    c0 = np.sqrt(9.81*depth)
    length_scale = np.sqrt(4*depth**3/(3*height))
    print("Shallow water: c0, c, width L, (h/L)^2:",
          c0, c0*(1+height/(2*depth)), length_scale, (depth/length_scale)**2)
    for integrated_damping in (0., .15):
        potential = .06*np.exp(-4*integrated_damping/3)
        print("Ion acoustic: a, M, width / Debye length:",
              potential, 1+potential/3, np.sqrt(6/potential))
