# Plots PSD, fits 1/f range and has notch filter to exclude external power frequencies

import numpy as np
import scipy
from scipy import signal
import scipy.signal as sig
import scipy.signal as sig
import Functions as uf
import LoadData
import os
import matplotlib
import matplotlib.pyplot as plt
import platform

if platform.system() == 'Darwin':
    matplotlib.use('MacOSX')
from tkinter import Tk
from tkinter.filedialog import askopenfilenames
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('small')
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42

filenames = askopenfilenames()

for i,file in enumerate(filenames):
    fig = plt.figure(1, figsize=(10, 8))
    ax = fig.add_subplot(111)
    dat = LoadData.OpenFile(file)
    filename = str(os.path.split(file)[1][:-4])
    os.chdir(os.path.dirname(file))
    directory = (str(os.path.split(file)[0]) + os.sep + 'PSD' + '_SavedImages')

    if not os.path.exists(directory):
        os.makedirs(directory)
    f, Pxx = sig.welch(dat['i1'], dat['samplerate'], nperseg=2**18)
    ax.plot(f, Pxx*1e24, label = filename)
    ax.set_xlabel('Frequency (Hz)')
    ax.set_ylabel(r'PSD ($\frac{pA^2}{Hz}$)')
    ax.set_yscale('log')
    ax.set_xscale('log')
    ax.legend()

plt.show()
# plt.savefig("O2_vs_degassed_PSD_noise_100mV.svg")
