from scipy.fft import fft, ifft, fftfreq
import numpy as np
import matplotlib.pyplot as plt

tid_pot = np.genfromtxt(f'/nfshk2/aygun/compressible_model_v2/TEST2/elastic3/CD_0/G_145_0/tidal_potential.dat', names=True, max_rows=999)
ind_pot = np.genfromtxt(f'/nfsy3/aygun/MM_GANYMEDE/elastic/CD_0/G_20_0/love_numbers_time.dat', skip_header=15000, max_rows=999)



n  = 1000
nn = np.arange(n-1)
per = 618153.4
w   = 2.0 * np.pi / per
Delta_t = tid_pot['Times'][1] - tid_pot['Times'][0]

inv_tid = 1.0 / (-tid_pot['Ecc_RV22'] - tid_pot['MM_RV22'])
tid_F = fft(inv_tid)
amp_F = abs(tid_F)/n
frq_F = 2.0 * np.pi * (nn) / (n*Delta_t)
frq_F= frq_F / w

ind_F = fft(ind_pot[:,2])
amp_ind = abs(ind_F)/n
frq_ind = 2.0 * np.pi * (nn) / (n*Delta_t)
frq_ind= frq_ind / w

k22_conv = np.convolve(inv_tid, ind_pot[:,2], 'same')

fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111)
ax.plot(np.abs(k22_conv), label='Convolution')
plt.xlabel('Frequency')
plt.ylabel('Convolution Amplitude')
plt.legend()
plt.yscale('log')
plt.savefig('./figs/convolution_tidal_induced.png')
plt.savefig('./figs/convolution_tidal_induced.pdf')


k22_time = ifft(k22_conv)
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111)
ax.plot(tid_pot['TimeP'], np.real(k22_time), label='Time Domain')
plt.xlabel('Time')
plt.ylabel(r'$k_{22}$')
plt.legend()
plt.savefig('./figs/k22_time_conv.png')
plt.savefig('./figs/k22_time_conv.pdf')

