#import os
#os.environ['R_HOME'] = '/Library/Frameworks/R.framework/Resources'

from pylab import *
import numpy as np
import pandas as pd
import time, sys, dill
from statsmodels.stats.multicomp import pairwise_tukeyhsd

models = ['cox', 'gbm', 'sf', 'spp']
score_t = [1000,2000,3000,4000]
colors = {'spp':'red', 'cox':'cyan', 'gbm':'lime', 'sf':'gold'}

linewidth = 1.0
boxwidth = 0.2
ylimm = {'tll': [-0.6,0.5], 'auc':[0.55,0.85]} # linear
#ylimm = {'tll': [-0.6,0.2], 'auc':[0.1,1.0]}

posit = {m: arange(0,len(score_t)) + p
         for m,p in zip(models,linspace(-0.35,0.35,len(models)))}

figure(figsize=(15,6))

scores = {m:dill.load(open('result/'+m+'_pbc.dill','rb'))
          for m in models}

subplot(1,8,(1,3))
xlim(-0.6,len(score_t)-0.4)
sc = 'tll'; title(sc);#ylim(ylimm[sc])
kentei = [pd.DataFrame(columns=['model','score']) for _ in score_t]
for m in models:
    z = array(scores[m][sc]).T
    s = [round(x,1) for x in scores[m]['t']]
    z = z[isin(s,score_t),:].T
    bp = boxplot(z,positions=posit[m], widths=[boxwidth]*len(posit[m]),
                 boxprops={'facecolor':colors[m], 'linewidth':linewidth},
                 flierprops={'markersize':4, 'markerfacecolor':colors[m]},
                 medianprops={'color':'k', 'linewidth':linewidth},
                 whiskerprops={'linewidth':linewidth,'linestyle':'--'},
                 capprops={'linewidth':linewidth},
                 patch_artist=True, notch=False)
    for i in range(len(score_t)):
        df = pd.DataFrame([[m,x] for x in z[:,i]], columns=['model','score'])
        kentei[i] = pd.concat([kentei[i],df],axis=0)

print('KENTEI:')
for df in kentei:
    print(pairwise_tukeyhsd(df.score, df.model))
    
subplot(1,8,(4,6))
xlim(-0.6,len(score_t)-0.4)
sc = 'auc'; title(sc);#ylim(ylimm[sc])
kentei = [pd.DataFrame(columns=['model','score']) for _ in score_t]
for m in models:
    z = array(scores[m][sc]).T
    s = [round(x,1) for x in scores[m]['t']]
    z = z[isin(s,score_t),:].T
    bp = boxplot(z,positions=posit[m], widths=[boxwidth]*len(posit[m]),
                 boxprops={'facecolor':colors[m], 'linewidth':linewidth},
                 flierprops={'markersize':4, 'markerfacecolor':colors[m]},
                 medianprops={'color':'k', 'linewidth':linewidth},
                 whiskerprops={'linewidth':linewidth,'linestyle':'--'},
                 capprops={'linewidth':linewidth},
                 patch_artist=True, notch=False)
    for i in range(len(score_t)):
        df = pd.DataFrame([[m,x] for x in z[:,i]], columns=['model','score'])
        kentei[i] = pd.concat([kentei[i],df],axis=0)
print('KENTEI:')
for df in kentei:
    print(pairwise_tukeyhsd(df.score, df.model))

subplot(1,8,(7,8))
title('cpu')
yscale('log')

m = 'cox'
bp = boxplot([scores[m]['cpu']],positions=[1],
             boxprops={'facecolor':colors[m], 'linewidth':linewidth},
             flierprops={'markersize':4, 'markerfacecolor':colors[m]},
             medianprops={'color':'k', 'linewidth':linewidth},
             whiskerprops={'linewidth':linewidth,'linestyle':'--'},
             capprops={'linewidth':linewidth},patch_artist=True)
m = 'gbm'
bp = boxplot([array(scores[m]['cpu'])/9.],positions=[2],
             boxprops={'facecolor':colors[m], 'linewidth':linewidth},
             flierprops={'markersize':4, 'markerfacecolor':colors[m]},
             medianprops={'color':'k', 'linewidth':linewidth},
             whiskerprops={'linewidth':linewidth,'linestyle':'--'},
             capprops={'linewidth':linewidth},patch_artist=True)
m = 'sf'
bp = boxplot([array(scores[m]['cpu'])/6.],positions=[3],
             boxprops={'facecolor':colors[m], 'linewidth':linewidth},
             flierprops={'markersize':4, 'markerfacecolor':colors[m]},
             medianprops={'color':'k', 'linewidth':linewidth},
             whiskerprops={'linewidth':linewidth,'linestyle':'--'},
             capprops={'linewidth':linewidth},patch_artist=True)
m = 'spp'
bp = boxplot([array(scores[m]['cpu'])/9.],positions=[4],
             boxprops={'facecolor':colors[m], 'linewidth':linewidth},
             flierprops={'markersize':4, 'markerfacecolor':colors[m]},
             medianprops={'color':'k', 'linewidth':linewidth},
             whiskerprops={'linewidth':linewidth,'linestyle':'--'},
             capprops={'linewidth':linewidth},patch_artist=True)

tight_layout()
savefig('result/figure_pbc.eps')


print(mean(scores['cox']['cpu']))
print(mean(scores['spp']['cpu'])/9.)
print(mean(scores['gbm']['cpu'])/9.)
print(mean(scores['sf']['cpu'])/6.)
show()
sys.exit()

cpu = {m:[] for m in models}
for nint in cpu_nint:
    scores = {m:dill.load(open('result/'+type+'/'+m+'_data_nsub'+str(nsub)+'nint'+str(nint)+'.dill','rb'))
              for m in models}
    for m in models:
        if m in ['spp','gbm']:
            cpu[m].append(array(scores[m]['cpu'])/9.)
        else:
            cpu[m].append(array(scores[m]['cpu']))
for m in models:
    errorbar(cpu_nint, mean(cpu[m],1), yerr=std(cpu[m],1), capsize=5,
             fmt='o', markersize=5, ecolor=colors[m], markerfacecolor=colors[m],
             markeredgecolor=colors[m])
    plot(cpu_nint, mean(cpu[m],1),colors[m])


tight_layout()
savefig('result/'+type+'/figure_nonlinear.eps')
show()

