"""Natural frequencies of a cantilever from an accelerometer recording: the signal, its spectrum (FFT), the peaks, and
beam theory to compare with."""
import numpy as np, pandas as pd, matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy.signal import find_peaks, butter, sosfiltfilt, hilbert

# 1. the recording
df = pd.read_csv("ruler_pluck.csv")
t, a = df["time_s"].to_numpy(), df["accel_ms2"].to_numpy()
fs = 1 / (t[1] - t[0])
print(f"{len(df)} samples at {fs:.0f} Hz, {t[-1]:.2f} s")

# 2. the spectrum: a Hann window, then the FFT
w = np.hanning(len(a))
spec = np.abs(np.fft.rfft(a * w)) * 2 / w.sum()
freq = np.fft.rfftfreq(len(a), 1 / fs)

# 3. the peaks: the natural frequencies. Higher modes die out within a fraction of a second, so look for peaks in the
#    first second, while every mode is still ringing (over the whole 4 s the third mode sinks into the noise)
n1 = int(1.0 * fs)
w1 = np.hanning(n1)
spec1 = np.abs(np.fft.rfft(a[:n1] * w1)) * 2 / w1.sum()
freq1 = np.fft.rfftfreq(n1, 1 / fs)
idx1, props = find_peaks(spec1, prominence=spec1.max() * 0.02)
top = idx1[np.argsort(props["prominences"])[::-1][:3]]        # the three clearest peaks
peaks = sorted(float(freq1[i]) for i in top)
# refine each on the full 4 s spectrum (finer: 0.25 Hz instead of 1 Hz)
peaks = [float(freq[np.argmax(np.where(abs(freq - p) < 2, spec, 0))]) for p in peaks]
idx = np.array([int(np.argmin(abs(freq - p))) for p in peaks])
print("measured peaks (Hz):", [round(p, 1) for p in peaks])

# 4. beam theory (Euler-Bernoulli cantilever): f_n = (beta_n^2 / 2 pi) * sqrt(E I / (rho A L^4))
E, rho = 193e9, 8000                     # stainless steel: Pa, kg/m^3
b, h, L = 0.025, 0.001, 0.250            # ruler width, thickness, free length: m
I, A = b * h**3 / 12, b * h
k = np.sqrt(E * I / (rho * A * L**4))
theory = [bl**2 / (2 * np.pi) * k for bl in (1.8751, 4.6941, 7.8548)]
for n, (m, th) in enumerate(zip(peaks, theory), 1):
    print(f"mode {n}: measured {m:6.1f} Hz   theory {th:6.1f} Hz   difference {100 * (m - th) / th:+.1f}%")

# 5. damping of mode 1 by the half-power bandwidth: zeta = (f2 - f1) / (2 fn)
i1 = idx[np.argmin(abs(freq[idx] - peaks[0]))]
half = spec[i1] / np.sqrt(2)
lo = i1
while spec[lo] > half: lo -= 1
hi = i1
while spec[hi] > half: hi += 1
f_lo = np.interp(half, [spec[lo], spec[lo + 1]], [freq[lo], freq[lo + 1]])
f_hi = np.interp(half, [spec[hi], spec[hi - 1]], [freq[hi], freq[hi - 1]])
print(f"mode 1 damping ratio, half-power bandwidth: {(f_hi - f_lo) / (2 * peaks[0]):.4f}  (resolution {freq[1] - freq[0]:.2f} Hz: too coarse for light damping)")

# 6. damping of mode 1 in time: keep only mode 1 (a band-pass filter), then fit how fast its envelope decays
sos = butter(4, [peaks[0] * 0.6, peaks[0] * 1.5], btype="bandpass", fs=fs, output="sos")
m1 = sosfiltfilt(sos, a)
env = np.abs(hilbert(m1))
keep = (t > 0.2) & (t < 2.5)                                  # skip the filter's start and the noise at the end
slope = np.polyfit(t[keep], np.log(env[keep]), 1)[0]          # ln(envelope) = -zeta * wn * t + c
print(f"mode 1 damping ratio, decay in time:       {-slope / (2 * np.pi * peaks[0]):.4f}")

# 7. pictures
fig, ax = plt.subplots(2, 1, figsize=(9, 6.5))
ax[0].plot(t, a, lw=0.6, color="#6d3fc4")
ax[0].set(xlabel="time (s)", ylabel="acceleration (m/s²)", title="Plucked ruler: accelerometer signal")
ax[1].semilogy(freq1, spec1, lw=0.9, color="#333")
for m, th in zip(peaks, theory):
    ax[1].axvline(th, color="#e0a000", ls="--", lw=1)
    ax[1].annotate(f"{m:.1f} Hz", (m, spec1[np.argmin(abs(freq1 - m))]), xytext=(6, 4), textcoords="offset points", color="#6d3fc4")
ax[1].set(xlim=(0, 300), xlabel="frequency (Hz)", ylabel="amplitude (m/s²)", title="Spectrum of the first second (FFT, Hann window); dashed: beam theory")
fig.tight_layout()
fig.savefig("vibration.png", dpi=150)
print("saved vibration.png")
