1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def fourier(t, signal):
"""Fast Fourier Transform of time series.
Parameters
----------
t : array-like
Array of time values is seconds
signal : array-like
Array of the signal amplitudes. Must be of the same length as the
t serie.
Returns
-------
freq : numpy array
Array of frequencies in Hz.
ampl : numpy array
Array of amplitudes in [unit]^2.s.
"""
N, dt = len(t), t[1]-t[0]
signal = signal - np.mean(signal)
dft = np.fft.fft(signal)
freq = np.fft.fftfreq(t.shape[-1])[0:int(N/2)]
freq = np.fft.fftfreq(N, d=dt)[0:int(N/2)]
ampl = 2 * np.abs(dft[0:int(N/2)]**2) / (N / dt)
return freq, ampl
# Import data
df = pd.read_csv('test.txt', sep=';', header=None, usecols=(0, 2))
df.columns = ['Time', 'Elevation']
# Perform spectral analysis
freq, ampl = fourier(df.Time.values, df.Elevation.values)
# Quick checks to see if the spectral analysis seems to produce expected
# results (assumption: wave elevation following a Rayleigh distribution)
m0 = np.trapz(ampl * freq**0, freq)
m2 = np.trapz(ampl * freq**2, freq)
wave_hs = 4 * np.sqrt(m0)
wave_tz = np.sqrt(m0 / m2)
# Some plots
fig, axes = plt.subplots(2)
axes[0].plot(df.Time, df.Elevation)
axes[0].grid(True)
axes[0].set_xlabel('Time (s)')
axes[0].set_ylabel('Elevation (m)')
axes[1].plot(freq, ampl)
axes[1].grid(True)
axes[1].set_xlabel('Frequencies (Hz)')
axes[1].set_ylabel('Amplitudes ()')
plt.show() |
Partager