from numpy import *
from scipy import *
from scipy.signal import *
from pylab import *
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter, freqz
import os

def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y

file_path = "Dataset/Shear_Wave_Rot00_CSV_Data/Shear_x001-x101_y011_Rot00.csv"
files_path = ['Shear_x001-x101_y{:03d}_Rot00.csv'.format(i) for i in range(10, 62)]
df = pd.read_csv(file_path)

print(df.head())
"""
for file in files_path:
    file_path = "Dataset/Shear_Wave_Rot00_CSV_Data/" + file
    df = pd.read_csv(file_path)

    # Créer un DataFrame pour stocker les données transformées
    transformed_data = pd.DataFrame()

    for index, row in df.iterrows():
        # Calculate envelope, called m_hat via hilbert transform
        m_hat = abs(hilbert(row))

        fs = 600.0
        cutoff = 3.667
        filtered_m_hat = butter_lowpass_filter(m_hat, cutoff, fs)

        # Ajouter les données transformées au DataFrame
        transformed_data = pd.concat([transformed_data, pd.DataFrame(filtered_m_hat).T], ignore_index=True)

    # Créer le nom du fichier de sortie en ajoutant "_transform" à la fin du nom du fichier original
    output_file_path = "Dataset/Shear_transform/" + os.path.splitext(file)[0] + "_transform.csv"

    # Écrire le DataFrame transformé dans le fichier de sortie
    transformed_data.to_csv(output_file_path, index=False)
"""




first_row = df.iloc[0]
# Calculate envelope, called m_hat via hilbert transform
m_hat = abs(hilbert(first_row))

fs = 600.0
cutoff = 3.667
filtered_m_hat = butter_lowpass_filter(m_hat, cutoff, fs)

# Create a new figure for the first plot
plt.figure()
plt.plot(m_hat)
plt.title('Plot of the m_hat')

# Create a new figure for the second plot
plt.figure()
plt.plot(first_row)
plt.title('Plot of the pre_m_hat')

plt.show()
"""
# Plot x
plot(t, x)
plot(t, m_hat)
axis('tight')
xlabel('Time (seconds)')
ylabel('Amplitude')
title('X, with calculated envelope')
legend(['x', 'm_hat'])
ylim(-2,2)
show()
"""
