import numpy as np
import polars as pl
import matplotlib.pyplot as plt
import os
import scipy
import nfft

DATA_PATH = os.path.dirname(__file__) + "/data.csv"

df = pl.read_csv(DATA_PATH)

plt.scatter(x="Time (s)", y="Absolute acceleration (m/s^2)", data=df)
plt.show()

start = 25
end = 125

df = df.filter((pl.col("Time (s)") >= start) & (pl.col("Time (s)") <= end))

t = df["Time (s)"].to_numpy()
a = df["Absolute acceleration (m/s^2)"].to_numpy()


plt.scatter(x=t, y=a)
plt.show()


# f = scipy.interpolate.interp1d(t, a, fill_value="extrapolate")

# N = len(df)


# plt.plot(f)
# plt.show()

# dt = []

# for i in range(len(df)-1):
#     dt.append(df["Time (s)"][i+1] - df["Time (s)"][i])

# plt.plot(dt)
# plt.show()

# define Fourier coefficients
N = len(df)
k = N // 2 + np.arange(N)

# df_ft = nfft.nfft(t, a-np.mean(df["Absolute acceleration (m/s^2)"].to_numpy()))
# spectre = np.abs(df_ft) * 2 / N
# freq = np.arange(N) / (end-start)

# amoy = np.mean(a)
# tfd = np.fft.fft(a - amoy)
# N = len(a)
# spectre = np.abs(tfd) * 2 / N
# freq = np.arange(N) / (end-start)

# # print(df_ft)
# plt.plot(freq, spectre)
# plt.show()

f = scipy.interpolate.interp1d(t, a, fill_value="extrapolate")

N = len(df)

# I made a bigger domain
x = np.linspace(start, end, N)

y = f(x)

plt.plot(x, y)
plt.show()

xf = scipy.fftpack.fftshift(scipy.fftpack.fftfreq(len(x), np.diff(x)[0]))
yf = scipy.fftpack.ifft(y)

plt.figure()
plt.plot(scipy.fftpack.fftshift(xf), np.abs(yf))
# plt.xlim(-30, 30)
plt.show()
