
# coding: utf-8

# In[1]:

# hostogram with bins for paper
get_ipython().magic(u'matplotlib inline')
import matplotlib
#matplotlib.use('macosx')  # TkAgg Force mpl to use Tk backend
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap, shiftgrid
import numpy as np
import seaborn as sns
import datetime
import netCDF4
import sys
import math 
import matplotlib.patches as mpatches
# needs gridspec
from matplotlib import gridspec
from matplotlib.colors import ListedColormap
import palettable 
from pandas import DataFrame 
from collections import Counter
import pandas as pd



from Boreal_Variables import bare_ea_east as bare
from Boreal_Variables import savanna_ea_east as savanna
from Boreal_Variables import forest_ea_east as forest 


savabmap = ListedColormap(palettable.colorbrewer.diverging.PuOr_5_r.mpl_colors)
baremap = ListedColormap(palettable.colorbrewer.diverging.PuOr_5.mpl_colors)

sns.set_style(style="white")
dataforr_ea_east = np.loadtxt("/Users/Beniamino/Documents/OneDrive/MPI-M/iPython_Notebooks/Boreal_Area/boreal_ea_east_database.txt") # columns=["VCFF", "MAR", "MASM", "Tmin", "PZI", "FF", "GDD0", "State", "Elev", "Lon", "Lat"]

# conditional histograms section

cmapbare = sns.light_palette("#7570b3", n_colors=5, reverse=False, as_cmap=True)
cmapsava = sns.light_palette("#d95f02", n_colors=5, reverse=False, as_cmap=True)
cmapfore = sns.light_palette("#1b9e77", n_colors=5, reverse=False, as_cmap=True)
colbare = '#7570b3'
colsava = '#d95f02'
colfore = '#1b9e77'



del_ind = []
for i in range(len(forest[:,5])):
    if forest[i,5]==0: del_ind.append(i)
for_with_fire = np.delete(forest[:], del_ind, 0)

del_ind = []
for i in range(len(bare[:,5])):
    if bare[i,5]==0: del_ind.append(i)
bar_with_fire = np.delete(bare[:], del_ind, 0)

del_ind = []
for i in range(len(savanna[:,5])):
    if savanna[i,5]==0: del_ind.append(i)
sav_with_fire = np.delete(savanna[:], del_ind, 0)

del_ind = []
for i in range(len(dataforr_ea_east[:,5])):
    if dataforr_ea_east[i,5]==0: del_ind.append(i)
data_with_fire = np.delete(dataforr_ea_east[:], del_ind, 0)

columns_2=["VCFF [%]", "MAR - ["+r'mm yr$^{-1}$'+"]", "Mean_Spring_SM - ["+r'mm'+"]", "Mean_Tmin - ["+r'$^\circ$C'+"]",           "PZI", "FF - ["+r'fires yr$^{-1}$'+"]", "GDD0 - ["+r'$^\circ$C yr$^{-1}$'+"]", "PTD", "ST", "State","Elev", "Lon", "Lat" ]
columns=["VCFF", "MAR", "Mean_Spring_SM", "Mean_Tmin", "PZI", "FF", "GDD0", "PTD", "ST", "State","Elev", "Lon", "Lat" ]


# In[11]:


# In[7]:
index = 3
fsize=14
sava_90 = np.percentile(savanna[:,index],90)
sava_10 = np.percentile(savanna[:,index],10)



binBoundaries = np.linspace(np.min(dataforr_ea_east[:,index]),np.max(dataforr_ea_east[:,index]),101) #
binw = (binBoundaries[2]-binBoundaries[1])
s_annot_location = round((sava_90)/binw)*binw+binw#+ binBoundaries[0]-binw
s_annot_location_10 = round((sava_10)/binw)*binw+binw#+ binBoundaries[0]-2*binw
delimiters = [-10.55258484,  -8.54070816,  -6.52883148,  -4.5169548,   -2.50507812]


fig = plt.figure(figsize=(12,8))
gs = gridspec.GridSpec(6, 1)


ax = fig.add_subplot(gs[0:2,:], xticks=delimiters)
ax.set_title('Eastern North Eurasia '+str(columns_2[index]), fontsize=fsize, y=1.06)

sns.despine(left=True)
hist_X = ax.hist([bare[:,index], savanna[:,index], forest[:,index]], label=["Treeless", "Open woodland", "Forest"],             stacked=True,bins=binBoundaries, alpha=0.7,normed=False, color = ['#7570b3', '#d95f02', '#1b9e77'])#hist(bare[:,1], color = '#5673E0', normed = True)
lin_s = np.linspace(0,0.20*np.max(hist_X[0]))

# [colbare, colsava, colfore]
mi, qua, mid, triqua, ma = 0, (np.min(hist_X[0])+np.max(hist_X[0]))/4,(np.min(hist_X[0])+np.max(hist_X[0]))/2,(np.min(hist_X[0])+np.max(hist_X[0]))/4+(np.min(hist_X[0])+np.max(hist_X[0]))/2, np.max(hist_X[0])
ax.set_yticks([int(mi), int(qua), int(mid), int(triqua), int(ma)])

plt.plot([delimiters[0] for i in lin_s ], lin_s*4.2, color = 'k')
ax.annotate('open woodland\n10th percentile', ha="center", fontsize = fsize-2, xy=(delimiters[0], 0.92*np.max(hist_X[0])))
plt.plot([delimiters[-1] for i in lin_s ], lin_s*3.2, color = 'k')
ax.annotate('open woodland\n90th percentile', ha="center", fontsize = fsize-2, xy=(delimiters[-1], 0.72*np.max(hist_X[0])))

plt.xticks(fontsize = fsize)
plt.yticks(fontsize = fsize)
plt.xlim(np.min(binBoundaries),np.max(binBoundaries))

plt.legend(fontsize=14, loc="upper left")
plt.ylabel("No. of gridcells", fontsize=fsize)

gs.update(hspace=0.50)

#dividers plot
axt=fig.add_subplot(gs[2,:], xticks=[], ylim=(-0.4,0.2), yticks=[])
axt.xaxis.set_label_position('top') 
axt.xaxis.tick_top()


sns.despine(ax=axt,left=True, top=True, bottom=True)
plt.xticks(fontsize = fsize)


annotations = [(np.min(binBoundaries)-10.55258484)/2.,  (-10.55258484-8.54070816)/2.,  (-8.54070816-6.52883148)/2.,  (-6.52883148-4.5169548)/2.,   (-4.5169548-2.50507812)/2., (-2.50507812+np.max(binBoundaries))/2.]
for elem in delimiters:
    plt.plot([elem for i in lin_s ], lin_s, color = 'k', linewidth=2.)
for elem in [np.min(binBoundaries),np.max(binBoundaries)]:
    plt.plot([elem for i in lin_s ], lin_s, color = 'k', linewidth=4.0)
   
    
for i in range(len(annotations)):
    axt.annotate("bin "+str(i+1), xy=(annotations[i], 0.1), ha="center", va="center", size=16)

    

plt.xlim(np.min(binBoundaries),np.max(binBoundaries))
#plt.ylim(0,520)
#plt.savefig( '/Users/Beniamino/Documents/OneDrive/MPI-M/My_Papers/First_Paper_First_Draft/bor_ea_east_MTmin_bins_with_title.pdf',dpi=300, transparent=False)
plt.show()



# In[ ]:




# In[ ]:



