import ROOT
import numpy as np
from ROOT import TFile, TLorentzVector, TVector3, TRotation, TLorentzRotation, TMath, TH1D, TCanvas, TH2D, TObject, TF1
import matplotlib.pyplot as plt
import pandas as pd
import pickle
macros = '/home/hep/matzeni/CCE/macros/CCEScan/'

filelumi = TFile('../data/db/lumi.root')
file_v_depl = TFile('../data/db/vdepl.root')
fileHam = TFile('/disk/data12/lhcb/STAgeingData/data/ST/Aging/Hamburg.root')
fileData = TFile('/disk/data12/lhcb/STAgeingData/data/ST/Aging/CCEScan.root')

# Select detector                                                                                                                                     
detector = 'TT'
nstrips = [3, 5, 7]
layer = 'TTaU'


#Taking the sector list and the corresponding initial depletion voltage
vO_sect = np.array(file_v_depl.Get('v_sector_TTaU'))

vO_vdepl = np.array(file_v_depl.Get('v_vdepl_TTaU'))
print 'vO_vdepl: ',vO_vdepl
print 'vO_sect: ',vO_sect

d = {'Sect_TTaU' : pd.Series(vO_sect), 'Vdepl_TTaU' : pd.Series(vO_vdepl)}
df_ini =pd.DataFrame(d)


#Vectors that specify fill number and time of the fills
vd_time = np.array(filelumi.Get('v_time'))

vd_fill = np.array(filelumi.Get('v_fill'))

# Load fill numbers                                                                                                                                   
with open(macros + 'Fills.dat', 'rb') as f:
    fills = f.read().splitlines()
fills.remove('2797')
fills.remove('3108')
    
#Load Sectors
with open(macros + '{DET}sectors.dat'.format(DET=detector), 'rb') as f:
    sectors = f.read().splitlines()



d = {'Fill' : pd.Series(vd_fill), 'Time' : pd.Series(vd_time)}
df =pd.DataFrame(d)

ACHT =[]


for isect in sectors:
    print'====================================================='
    print 'isect: ', isect

    #Hamburg


    V0 = df_ini['Vdepl_TTaU'][df_ini.Sect_TTaU == int(isect)].values[0]
    

    vH_deltaV = np.array(fileHam.Get('v_Hamburg_TTaU_'+str(int(isect))+'_deltaV'))
#    print 'vH_deltaV: ',vH_deltaV

#    print 'vH_V: ',vH_V
    vH_V = V0 - vH_deltaV   
    vH_time = np.array(fileHam.Get('v_Hamburg_TTaU_'+str(int(isect))+'_time'))
    #    print 'vH_time: ',vH_time


    #Data
    vD_time =[]
    vData=[]
    vData_err=[]

    for ifill in fills:


        #  vData =np.concatenate((vData, np.array(fileData.Get('TT/TTaU/'+isect+'/'+str(int(ifill))+'/v_volt_val7'))),axis=0)    
        vData = np.append( np.array(fileData.Get('TT/TTaU/'+isect+'/'+ifill+'/v_volt_val7'))[0],vData)
        vData_err = np.append( np.array(fileData.Get('TT/TTaU/'+isect+'/'+ifill+'/v_volt_val7'))[1],vData_err)
        
        print(df['Time'][df.Fill == int(ifill)].values[0])
        vD_time = np.append( df['Time'][df.Fill == int(ifill)].values[0],vD_time)




    #print 'vData: ', vData
    #print 't: ', vD_time        

    #####################################

    vH_inter = np.interp(vD_time, vH_time, vH_V)
    print 'vH_time: ',vH_time
    print 'vD_time: ',vD_time
    print 'vH_V: ',vH_V
    print 'vData: ',vData
    print 'vData_err: ',vData_err
    print 'vH_inter: ',vH_inter
    vDiff = np.absolute(vData-vH_inter)
    print 'Difference: ',vDiff

    for i in xrange(len(vD_time)):
        print(i)
        if (vDiff[i] >= 3*vData_err[i] ):
            #print 'WARNING! Check Sector: {} for Fill: {} '.format(isect,df['Fill'][df.Time==vD_time[i]].values[0])
            ACHT = np.append([isect,int(df['Fill'][df.Time==vD_time[i]].values[0])],ACHT)
#            print(ACHT)

    #plt.plot(vH_time,vH_V, 'r--',vD_time,vH_inter, 'bs',vD_time,vData, 'gs')
    #plt.show()
    #raw_input('>')

ACHT = np.reshape(ACHT,(len(ACHT)/2,2))
print 'ACHT',ACHT

data_frame = pickle.load(open('monotonics.pkl', 'rb'))


#ACHT_ele = data_frame[['Sector','Fill']][data_frame['V bias'] < 125].values
ACHT_ele = data_frame[['Sector','Fill']].values

print 'ACHT_ele', ACHT_ele

aset = set([tuple(x) for x in ACHT])
bset = set([tuple(x) for x in ACHT_ele])
inter = np.array([x for x in aset & bset])
print 'Intersection', inter

'''
        a = [ifill, vData_t[0]]





    print 'vH_V: ',vH_V

print 'vd_fill: ',vd_fill
    
print 'vd_time: ',vd_time
#Time used to do the Hamburg simulation





vH_hig = np.array(fileHam.Get('v_Hamburg_TTaU_'+isect+'_hig'))
print 'vH_hig: ',vH_hig

vH_low = np.array(fileHam.Get('v_Hamburg_TTaU_'+isect+'_low'))
print 'vH_low: ',vH_low


#vData = np.array([0.,0.,0.,0.,0.])
#print(vData)





    '''
