import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio

# Problem 1

rx = sio.loadmat('mf_output.mat')
y = rx['mf_output'].flatten()

# number of samples per symbol (upsampling factor)
SPS = int(50)

# x-axis for one trace
traceLine = np.arange(2*SPS)

# remove excess samples to full traces
y = y[0: y.size - (y.size % traceLine.size)]

# reshape the data
y = np.reshape(y, (traceLine.size, int(y.size/traceLine.size)), 'F')

# plot the Eye Diagrams
fig, axs = plt.subplots(3, 1, constrained_layout=True)
fig.suptitle('EyeDiagram', fontsize=16)
axs[0].plot(traceLine, y.real)
axs[0].set(xlabel='Time', ylabel='Amplitude - Real')
axs[1].plot(traceLine, y.imag)
axs[1].set(xlabel='Time', ylabel='Amplitude - Imaginary')
axs[2].plot(traceLine, abs(y))
axs[2].set(xlabel='Time', ylabel='Amplitude - Absolute Value')

# find the minimum opening of the eye for each time index (that is, over rows)
min_over_rows = abs(y).min(axis=1)

# find the maximal opening of the eye and its corresponding time index
indexMax = np.argmax(min_over_rows)

print('channel_delay = ', indexMax)

# take into account the delay and downsample
y_down = y[indexMax:y.size:SPS]

plt.figure()
plt.scatter(y_down.real, y_down.imag, marker='*')
plt.title('Received symbols at the output of the MF')
plt.grid()
plt.show()
