import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
import matplotlib.lines as mlines


# constants of the circuit
R = 4770
C = 97.61*10**-9


# function for calculating the gain of the function
def gain_val(w):
    return 20* np.log10(1/np.sqrt(1+(w*R*C)**2))


# import data
data = np.loadtxt("bode_low_pass.dat")


# make the plot prettier
#blue_patch = mpatches.Patch(color = 'blue', label = 'Data')
red_patch = mpatches.Patch(color = 'red', label = 'Simulation')
dot_patch = mlines.Line2D([], [], color='black', marker='o',
                          label='Cutoff Frequency')

plt.xscale('log')
plt.grid(True)
plt.legend(handles = [red_patch, dot_patch])

plt.title('Gain of a signal as a function of frequency')    
plt.xlabel(r'The angular frequency of the input signal $\left[\dfrac{rad}{s}\right]$')
plt.ylabel('The gain of the input signal [dB]')


# store the data in variables
dat_in = data[:,0]*2*np.pi
dat_out = data[:,1]


# simulate the data
sim_in = dat_in
sim_out = gain_val(sim_in)


# Calculating the cutoff frequency
fc_x = 1/(R*C) # since (1*2pi)/(RC2pi) = 1/RC
fc_y = gain_val(fc_x)


# plotting the data
plt.scatter(fc_x, fc_y, c = 'black', marker = 'o', s = 60, zorder = 3)
#plt.plot(dat_in, dat_out, color = "blue", alpha = 0.3, lw = 5, zorder = 1)
plt.plot(sim_in, sim_out, color = 'red', zorder = 2)

plt.xlim(dat_in[0], dat_in[-1])
plt.ylim(dat_out[-1], dat_out[0]+5)


plt.tight_layout()
plt.savefig("LPF_sim.pdf")
