
from sys import platform
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as a
import pandas as pd
import scipy.signal as sig
import Functions as f
import shelve
from sklearn.mixture import GaussianMixture as GMM
import os
import h5py
import seaborn as sns
from tkinter import Tk
from tkinter.filedialog import askopenfilenames
root = Tk()
root.withdraw()
from scipy.stats import gaussian_kde


matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42

filenames = askopenfilenames(filetypes=[('data files', '*.db')], parent = root)
root.update()
print(filenames)

Name = ''
cm = plt.cm.get_cmap('RdYlBu')
voltageLimits = [0.1, 1.1]
dwellrange = (0, 5) #ms
dIrange = (0, 5) #nA
FracDIRange = (0, 100)

count = 0
dt = {}
dIF = {}
count = {}

dt = np.array([])
dIF = np.array([])
dI = np.array([])
tempvoltage = np.array([])
templocalbaseline = np.array([])
tempeventlength = np.array([])

localBase = np.array([])
v = np.array([])
t = np.array([])
t2 = np.array([])
count = 0

##This part needs to be adapted to Jochem-style files
for file in filenames:
    print('file is:', file)
    fileNamewithourend, end = os.path.splitext(file)
    shelfFile = shelve.open(fileNamewithourend)
    event = shelfFile['TranslocationEvents']
    dIF = np.append(dIF, np.array([x.currentDrop/x.baseline for x in event.events if x.type == 'CUSUM'])*100) #if x.type == 'CUSUM'
    dI = np.append(dI, np.array([x.currentDrop for x in event.events if x.type == 'CUSUM' ])*1e9 ) #if x.type == 'CUSUM'
    v = np.append(v, [x.voltage for x in event.events if x.type == 'CUSUM' ]) #if x.type == 'CUSUM'
    localBase = np.append(localBase, [x.baseline*1e9/x.voltage for x in event.events if x.type == 'CUSUM' ]) #if x.type == 'CUSUM'
    tempeventlength = np.append(tempeventlength, [x.eventLength for x in event.events if x.type == 'CUSUM' ]) #if x.type == 'CUSUM'
    path, filen = os.path.split(file)
    print(path[:])
    filepath = path[:] + '/' + filen[:]
    st = os.stat(filepath.replace('\\', '/'))
    dt = np.append(dt, tempeventlength*1e3)
    t = np.append(t, st.st_birthtime * np.ones(len([x.currentDrop/x.baseline for x in event.events if x.type == 'CUSUM' ] ))) #if x.type == 'CUSUM'
    t2 = np.append(t2, st.st_mtime * np.ones(len([x.currentDrop/x.baseline for x in event.events if x.type == 'CUSUM' ]))) #if x.type == 'CUSUM'
    count += len([x.currentDrop/x.baseline for x in event.events if x.type == 'CUSUM' ]) #if x.type == 'CUSUM'


# Sort the voltages.
availableVoltages = np.unique(v[np.where((v > voltageLimits[0]) & (v < voltageLimits[1]))])
print(availableVoltages)
data = []
datadII0 = []
datalBase = []
dataDwell = []
dataRate = []
labels = []
NEvents = []

for vo in availableVoltages:
    ind1 = np.argwhere(v == vo)
    ind2 = np.intersect1d(ind1, np.argwhere((dt > dwellrange[0]) & (dt < dwellrange[1])))
    ind = np.intersect1d(ind2, np.argwhere((dI > dIrange[0]) & (dI < dIrange[1])))
    data.append(dI[ind])
    datadII0.append(dIF[ind])
    dataDwell.append(dt[ind])
    datalBase.append(localBase[ind])
    NEvents.append(len(ind))
    if 1:
        print('Modified-Written is applied')
        if (np.max(t2[ind])-np.min(t[ind])) != 0:
            dataRate.append(0)
        else:
            dataRate.append(len(ind)/(np.max(t2[ind])-np.min(t[ind])))
    else:
        if (np.max(t[ind])-np.min(t[ind])) != 0:
            dataRate.append(0)
        else:
            dataRate.append(len(ind)/(np.max(t[ind])-np.min(t[ind])))
    labels.append('{:0.0f}'.format(np.round(vo*1000)))

cond = np.array([])
for i,dati in enumerate(data):
    cond = np.append(cond, dati/availableVoltages[i])

print('plotting now ')


# # 1.2.Fractional Current Drop Scatter Plot...
fig6 = plt.figure(6, figsize=(9, 6))
ax6 = fig6.add_subplot(111)
sc6 = ax6.scatter(dt[np.where(v > 0)], dI[np.where(v > 0)], c=v[np.where(v > 0)], vmin=min(v[np.where(v > 0)]), vmax=max(v[np.where(v > 0)]), s=35, cmap=cm)
# cbar6 = plt.colorbar(sc6, ticks=availableVoltages)
# cbar6.ax.set_yticklabels(labels)  # vertically oriented colorbar
ax6.set_xlabel('Time (ms)')
ax6.set_ylabel('Current Drop dI (nA)')
ax6.set_title('{}\nScatter Plot, {} events'.format(Name, count))
# fig6.savefig(file[:-24] + 'ScatterdI.pdf', transparent=True)
ax6.set_xlim(dwellrange[0], dwellrange[1])
ax6.set_ylim(dIrange[0], dIrange[1])
# plt.savefig("dI_scatterplot_end.svg")
plt.show()
# fig6.savefig(file[:-24] + 'ScatterdIZoomed.pdf', transparent=True)
#
# KDE DwellTime vs Voltages
fig32 = plt.figure(32, figsize=(16, 9))
ax32 = fig32.add_subplot(111)
for i, dati in enumerate(dataDwell):
    ax32 = sns.kdeplot(dati, label='{}mV'.format(str(int(availableVoltages[i]*1e3)), bins = 100))
ax32.legend()
ax32.set_xlabel('Dwell Time (ms)')
ax32.set_ylabel('Prob. density')
ax32.set_title('Dwell Time Histograms')
ax32.set_xlim(0, 5)
# ax32.set_xlim(left=np.min(np.concatenate(dataDwell).ravel()), right=np.max(np.concatenate(dataDwell).ravel()))
plt.show()
# fig32.savefig(file[:-24] + 'DwellTime_KDEPlot.pdf')

# 8.Histogram DwellTime vs Voltages
fig8 = plt.figure(8, figsize=(6, 12))
for i,dati in enumerate(dataDwell):
    ax8 = fig8.add_subplot(len(dataDwell), 1, i+1)
    n, bins, patches = ax8.hist(x=dati, bins = 100, alpha=0.7, rwidth=0.85)
    ax8.grid(axis='y', alpha=0.75)
    ax8.set_xlabel('Dwell Time (ms)')
    ax8.set_ylabel('Frequency')
    ax8.set_title('{}mV'.format(int(availableVoltages[i]*1e3)))
    #ax8.set_xlim(left=np.min(np.concatenate(dataDwell).ravel()), right=np.max(np.concatenate(dataDwell).ravel()))
    ax8.set_xlim(0, 5)
plt.show()
# plt.savefig("HistogramDwellTime_end.svg")
# fig8.savefig(file[:-24] + 'HistogramDwellTime.pdf', transparent=True)

# 9.Histogram CurrentDrop vs Voltages
fig9 = plt.figure(9, figsize=(6, 12))
for i,dati in enumerate(data):
    ax9 = fig9.add_subplot(len(data), 1, i+1)
    n, bins, patches = ax9.hist(x=dati, bins = 100, alpha=0.7, rwidth=0.85)
    ax9.grid(axis='y', alpha=0.75)
    ax9.set_xlabel('Current Drop (nA)')
    ax9.set_ylabel('Frequency')
    ax9.set_title('{}mV'.format(int(availableVoltages[i]*1e3)))
    #ax9.set_xlim(left=np.min(np.concatenate(data).ravel()), right=np.max(np.concatenate(data).ravel()))
    ax9.set_xlim(0, 5)
# fig9.savefig(file[:-24] + 'HistogramCurrentDrop.pdf', transparent=True)
# plt.style.use("seaborn-darkgrid")
plt.show()
# plt.savefig("Current_drop_Hist_end.svg")

# 11 KDE CurrentDrop vs Voltages
fig11 = plt.figure(11, figsize=(6, 12))
for i,dati in enumerate(data):
    ax11 = fig11.add_subplot(len(data), 1, i+1)
    ax11 = sns.distplot(dati)
    ax11.set_xlabel('Current Drop (nA)')
    ax11.set_ylabel('Frequency')
    # ax11.set_xlim(0, 2)
    ax11.set_title('{}mV'.format(int(availableVoltages[i]*1e3)))
    # ax11.set_xlim(left=np.min(np.concatenate(data).ravel()), right=np.max(np.concatenate(data).ravel()))
    ax11.set_xlim(0, 5)
# fig11.savefig(file[:-24] + 'KDECurrentDrop.pdf')#, transparent=True)
plt.show()

# 18 KDE Conductance Drop vs Voltages
fig18 = plt.figure(18, figsize=(6, 12))
for i, dati in enumerate(data):
    ax18 = fig18.add_subplot(len(data), 1, i+1)
    ax18 = sns.violinplot(dati/availableVoltages[i], orient= "v")
    ax18.set_xlabel('Conductance Drop (nS)')
    ax18.set_ylabel('Frequency')
    ax18.set_title('{}mV'.format(int(availableVoltages[i]*1e3)))
    ax18.set_xlim(0, 14)
    print("median is", statistics.median(dati/availableVoltages[i]))
    print("mean is", statistics.mean(dati/availableVoltages[i]))

# fig18.savefig(file[:-24] + 'Violin_ConductanceDrop_new.pdf')#, transparent=True)
plt.show()