import nixio as nix
import os
from IPython import embed
#from utility import *
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.mlab as ml
import scipy.integrate as si
from scipy.ndimage import gaussian_filter
from IPython import embed
from myfunctions import *
from myfunctions import auto_rows
from myfunctions import remove_tick_ymarks
from myfunctions import remove_tick_marks
import string
from matplotlib import gridspec

def plot_amp(grid, nrow, ncol,ax, mean1, dev,nrs = [3,4,5],nr_size = 12,name = 'amp',nr = 1, wide = 'gainsboro', middle = 'darkgrey', narrow = 'black'):
    np.unique(mean1['type'])
    all_means = mean1[mean1['type'] == name +' mean']
    original = all_means[all_means['dev'] == 'original']
    #m005 = all_means[all_means['dev'] == '005']
    m05 = all_means[all_means['dev'] == '05']
    m2 = all_means[all_means['dev'] == '2']
    # fig, ax = plt.subplots(nrows=4, ncols = 3, sharex=True)
    versions = [original, m05, m2] #m005,
    lim = [[]]*len(versions)
    for i in range(len(versions)):
        keys = [k for k in versions[i]][2::]
        try:
            data = np.array(versions[i][keys])[0]
        except:
            break
        axis = np.arange(0, len(data), 1)
        axis_new = axis * 1
        similarity = [keys, data]
        sim = np.argsort(similarity[0])
        # similarity[sim]
        all_means = mean1[mean1['type'] == name+' std']
        std = all_means[all_means['dev'] == dev[i]]
        std = np.array(std[keys])[0]
        #ax[1, 1].set_ylabel('Modulation depth')
        #ax[nr,i].set_title(dev[i] + ' ms')
        all_means = mean1[mean1['type'] == name+' 95']
        std95 = all_means[all_means['dev'] == dev[i]]
        std95 = np.array(std95[keys])[0]
        all_means = mean1[mean1['type'] == name+' 05']
        std05 = all_means[all_means['dev'] == dev[i]]
        std05 = np.array(std05[keys])[0]
        #ax['mod'+str(i)] = plt.subplot(nrow, ncol, i * 2 + 2)
        ax['mod' + str(i)] = plt.subplot(grid[i * 2 + 1])
        if nrs:
            ax['mod'+str(i)].text(-0.1, 1.1, string.ascii_uppercase[nrs[i]], transform=ax['mod'+str(i)].transAxes,
                   size=nr_size, weight='bold')

        ax['mod'+str(i)].fill_between(np.array(keys)[sim], list(std95[sim]), list(std05[sim]),
                              color=wide)
        ax['mod'+str(i)].fill_between(np.array(keys)[sim], list(data[sim] + std[sim]), list(data[sim] - std[sim]),
                              color=middle)
        #if i != 0:
        #    ax['mod'+str(i)] = remove_tick_ymarks(ax['mod'+str(i)])
        if i != 2:
            ax['mod' + str(i)] = remove_tick_marks(ax['mod' + str(i)])
        # ax[i].plot(data_tob.ff, data_tob.fe, color='grey', linestyle='--', label='AMf')
        ax['mod'+str(i)].plot(np.array(keys)[sim], data[sim], color=narrow)
        lim[i] = np.nanmax(std95[sim])
        # ax[0].plot(data1.x, data1.freq20, color=colors[1], label='20 %')
    for i in range(len(versions)):
        ax['mod'+str(i)].set_ylim(0,np.nanmax(lim))
    #embed()
    return ax

def create_beat_corr(hz_range, eod_fr):
    beat_corr = hz_range%eod_fr
    beat_corr[beat_corr>eod_fr/2] = eod_fr[beat_corr>eod_fr/2] - beat_corr[beat_corr>eod_fr/2]
    return beat_corr


def plot_mean_cells():
    mean1 = pd.read_pickle('mean.pkl')

    colors = ['#BA2D22', '#F47F17', '#AAB71B', '#3673A4', '#53379B']
    inch_factor = 2.54
    whole_page_width = 4
    intermediate_length = 7.5

    plt.rcParams['figure.figsize'] = (whole_page_width, intermediate_length)
    plt.rcParams['font.size'] = 11
    plt.rcParams['axes.titlesize'] = 12
    plt.rcParams['axes.labelsize'] = 12
    plt.rcParams['lines.linewidth'] = 1.5
    plt.rcParams['lines.markersize'] = 8
    plt.rcParams['legend.loc'] = 'upper right'
    plt.rcParams["legend.frameon"] = False

    x = np.arange(0, 2550, 50)
    corr = create_beat_corr(x, np.array([500] * len(x)))

    np.unique(mean1['type'])
    all_means = mean1[mean1['type'] == 'max mean']

    #versions = [[]]*len(dev)
    #for i in range(len(dev)):
    original = all_means[all_means['dev'] == 'original']
    m005 = all_means[all_means['dev'] == '005']
    m05 = all_means[all_means['dev'] == '05']
    m2 = all_means[all_means['dev'] == '2']
    dev = ['original',  '05', '2']#'005',
    titels = ['binary','0.5 ms','2 ms']
    #fig, ax = plt.subplots(nrows=3, ncols=2, sharex=True)
    fig = plt.figure()
    versions = [original,  m05, m2]#m005,
    nrs = [0,1,2]
    nrs = [0,2,4]
    nrs = []
    nr_size = 12
    ax = {}
    nrow = 6
    ncol = 1
    grid = gridspec.GridSpec(6,1,hspace = 0.4,left = 0.2)
    for i in range(len(versions)):
        keys = [k for k in versions[i]][2::]
        try:
            data = np.array(versions[i][keys])[0]
        except:
            #embed()
            break
        axis = np.arange(0, len(data), 1)
        axis_new = axis * 1
        similarity = [keys, data]
        sim = np.argsort(similarity[0])
        # similarity[sim]
        all_means = mean1[mean1['type'] == 'max std']
        std = all_means[all_means['dev'] == dev[i]]
        std = np.array(std[keys])[0]
        #ax[0,i].set_title(dev[i] +' ms')
        ax[i+1] = plt.subplot(grid[i*2])
        ax[i+1].set_title(titels[i])
        #ax[i+1].set_ylabel('MPF [EODf]')
        all_means = mean1[mean1['type'] == 'max 95']
        std95 = all_means[all_means['dev'] == dev[i]]
        std95 = np.array(std95[keys])[0]
        all_means = mean1[mean1['type'] == 'max 05']
        std05 = all_means[all_means['dev'] == dev[i]]
        std05 = np.array(std05[keys])[0]
        #std[np.where(list(data[sim] + std[sim])>std95[sim])] = std95[sim][np.where(list(data[sim] + std[sim])>std95[sim])]
        #embed()
        middle  = 'pink'#'LightSalmon'
        wide='lightpink'#mistyrose'
        narrow = 'crimson'
        ax[i+1].fill_between(np.array(keys)[sim], list(std95[sim]), list(std05[sim]),
                              color=wide, alpha = 0.45)#
        #embed()

        ax[i+1].fill_between(np.array(keys)[sim], list(data[sim] + std[sim]), list(data[sim] - std[sim]), color=middle)

        ax[i+1].plot(x / 500, corr / 500 + 1, color='grey', linestyle='--', label='AMf')
        ax[i+1].plot(np.array(keys)[sim], data[sim], color=narrow)
        # plt.fill_between(np.array([0,1]),np.array([0,0]),np.array([1,1]))
        if nrs:
            ax[i+1].text(-0.1, 1.1, string.ascii_uppercase[nrs[i]], transform=ax[i+1].transAxes,
                   size=nr_size, weight='bold')
        ax[i+1] = remove_tick_marks(ax[i+1])
        #if i != 0:
        #    ax[i+1] = remove_tick_ymarks(ax[i+1])
        # ax[0].plot(data1.x, data1.freq20, color=colors[1], label='20 %')
    #ax[1].legend(bbox_to_anchor=(0.7, 1, 0.7, .1), loc='lower left',
    #                ncol=3, mode="expand", borderaxespad=0.)

    #ax = plot_amp(ax, mean1, dev,name = 'amp',nr = 2)
    #ax[1].legend(bbox_to_anchor=(0.3, 1, 0.7, .1), loc='lower left',
    #                ncol=3, mode="expand", borderaxespad=0.)
    nrs = [1,3,5]
    nrs = []
    ax = plot_amp(grid, nrow, ncol, ax,mean1, dev,nrs = nrs,nr_size = nr_size,name='amp max', nr=1,wide = 'gainsboro', middle = 'lightblue', narrow = 'steelblue')
    # ax[1].plot(data_tob.ff, data_tob.fe, color='grey', linestyle='--')
    # ax[1].plot(data2.x, transfer_array, color=colors[0])
    # ax[1].plot(data2.x, data2.freq20, color=colors[1])

    # ax[2].plot(data_tob.ff, data_tob.fe, color='grey', linestyle='--')
    # ax[2].plot(data3.x, transfer_array, color=colors[0])
    # ax[2].plot(data3.x,  color=colors[1])

    # ax[2].plot(data_tob.ff, transfer_array, color='grey', linestyle='--')
    # ax[2].plot(data4.x, transfer_array, color=colors[0])
    # ax[2].plot(data3.x,  color=colors[1])

    ax[2+1].set_ylabel('MPF [EODf]')
    #ax[1, 0].set_ylabel('Modulation depth')
    ax['mod'+str(2)].set_ylabel('Modulation')
    #ax[2, 0].set_ylabel('Whole modulation ')
    plt.subplots_adjust(hspace = 0.35)
    for i in range(3):

        ax['mod'+str(i)].spines['right'].set_visible(False)
        ax['mod'+str(i)].spines['top'].set_visible(False)
        ax[i+1].spines['right'].set_visible(False)
        ax[i+1].spines['top'].set_visible(False)
        #ax[i].spines['right'].set_visible(False)
        #ax[i].spines['top'].set_visible(False)
        #ax[i,3].spines['right'].set_visible(False)
        #ax[i,3].spines['top'].set_visible(False)
    #for i in range(3):
    ax['mod'+str(2)].set_xlabel('stimulus frequency [EODf]')
        #ax[2, i].set_ylim([0, 370])
        #ax[2,i].set_ylim([0, 4700])
    #ax[2, 1].set_xlabel('stimulus frequency [EODf]')
    plt.subplots_adjust(bottom = 0.13)
    #fig.tight_layout()f
    # fig.label_axes()
    return fig

if __name__ == "__main__":
    fig = plot_mean_cells()
    #fig.savefig()
    plt.savefig('MPFmodulation_trans.pdf')
    plt.savefig('../highbeats_pdf/MPFmodulation_trans.pdf')
    plt.show()
    # plt.close()

