def ConcatenateRoot(inDir,tree,nFiles=-1):
    if not inDir[-1]=='/': inDir+='/'
    fileNames = []
    if nFiles==-1:
        fileNames = [inDir+fileName for fileName in os.listdir(inDir) if '.root' in fileName[-5:]]
    else:
        fileNames = [inDir+fileName for fileName in os.listdir(inDir)[:nFiles] if '.root' in fileName[-5:]]
    df_v = [Pandafy(fileName,tree) for fileName in fileNames]
    df = pd.concat(df_v,ignore_index=True)
    af.End()
    return df
def Plot2dHitsHisto(inDir,jobType,histoName='PHVsWidth',zMax='None'):
    # Settings
    col = ['r','g','b']
    titles = ['U plane','V plane','Y plane']
    subs = ['FitTrackHits','AllHits']
    subNames = ['Track Hits','All (other) Hits']
    xlab = 'PH [ADC]'
    ylab = 'Width [TDC]'

    if not inDir[-1]=='/': inDir+='/'
    fileNames = [inDir+fileName for fileName in os.listdir(inDir) if '.root' in fileName[-5:]]

    rootFile = ROOT.TFile(fileNames[0],'READ')
    rootDir = rootFile.Get('TrackHitAna')
    rootSub = rootDir.Get(subs[0])
    rootHisto = rootSub.Get(histoName+'0')
    refMap2D = Hist2d2Array(rootHisto)
    nx = len(refMap2D[0])
    ny = len(refMap2D[1])

    for k,sub in enumerate(subs):
        fig = [[],[],[]]
        canv = plt.figure(figsize=(15,5))
        for plane in range(3):
            mapSum = [np.zeros([nx]),np.zeros([ny]),np.zeros([nx,ny])]
            for i in range(nx):
                mapSum[0][i] = refMap2D[0][i]
            for j in range(ny):
                mapSum[1][j] = refMap2D[1][j]
            for fileName in fileNames:
                rootFile = ROOT.TFile(fileName,'READ')
                rootDir = rootFile.Get('TrackHitAna')
                rootSub = rootDir.Get(sub)
                rootHisto = rootSub.Get(histoName+'%i' %plane)
                map2D = Hist2d2Array(rootHisto)
                for i in range(nx):
                    for j in range(ny):
                        mapSum[2][i][j] += map2D[2][i][j]
            fig[plane] = canv.add_subplot(131+plane)
            plt.pcolormesh(mapSum[0],mapSum[1],mapSum[2].T,cmap='RdYlBu_r')
            plt.title(jobType+' | '+subNames[k]+'\n'+titles[plane]+'\n')
            if plane==2:
                plt.axvline(3.25,color='black',lw=3,ls='--')
            else:
                plt.axvline(2.6,color='black',lw=3,ls='--')
            plt.xlabel(xlab)
            plt.xlim(1,20.)
            if zMax!='None': plt.clim(0,zmax)
            plt.colorbar()
        fig[0].set_ylabel(ylab)
        plt.show()
    af.End()
def Plot1dHitsHisto(inDir,jobType,histoName='PulseHeightS',xlab='PH [ADC]',xlim=100.):
    # Settings
    col = ['r','g','b']
    titles = ['U plane','V plane','Y plane']
    subs = ['FitTrackHits','PFPartHits','AllHits']
    subNames = ['Track Hits','PFPart Hits','All (other) Hits']

    if not inDir[-1]=='/': inDir+='/'
    fileNames = [inDir+fileName for fileName in os.listdir(inDir) if '.root' in fileName[-5:]]

    rootFile = ROOT.TFile(fileNames[0],'READ')
    rootDir = rootFile.Get('TrackHitAna')
    rootSub = rootDir.Get(subs[0])
    rootHisto = rootSub.Get(histoName+'0')
    refMap2D = Hist1d2Array(rootHisto)
    nx = len(refMap2D[0])

    for k,sub in enumerate(subs):
        fig = [[],[],[]]
        canv = plt.figure(figsize=(15,5))
        for plane in range(3):
            mapSum = [np.zeros([nx]),np.zeros([nx])]
            for i in range(nx):
                mapSum[0][i] = refMap2D[0][i]
            for fileName in fileNames:
                rootFile = ROOT.TFile(fileName,'READ')
                rootDir = rootFile.Get('TrackHitAna')
                rootSub = rootDir.Get(sub)
                rootHisto = rootSub.Get(histoName+'%i' %plane)
                map2D = Hist1d2Array(rootHisto)
                for i in range(nx):
                    mapSum[1][i] += map2D[1][i]
            dof = len(mapSum[0])-4
            fig[plane] = canv.add_subplot(131+plane)
            plt.plot(mapSum[0],mapSum[1],color=col[plane],lw=1,drawstyle='steps')
            plt.title(jobType+' | '+subNames[k]+'\n'+titles[plane]+'\n')
            plt.xlabel(xlab)
            plt.xlim(0,xlim)
            plt.grid(True)
            if 'PulseHeight' in histoName:
                if plane==2:
                    plt.axvline(3.25,color='black',lw=3,ls='--')
                else:
                    plt.axvline(2.6,color='black',lw=3,ls='--')
        plt.show()
    af.End()
def PlotEach(rootDf_track,rootDf_others,jobType):
    plt.rcParams['font.size']=15
    for i,plane in enumerate(planes[:-1]):
        canv = plt.figure(figsize=figsize)
        plt.title(jobType+' | %s plane' %plane)
        plt.xlabel('Threshold')
        plt.ylabel('Completeness')
        plt.xlim(1.,endT)
        if i==2:
            plt.axvline(3.25,color='black',lw=3,ls='--')
        else:
            plt.axvline(2.6,color='black',lw=3,ls='--')
        completeness_others = [CompletenessMean(rootDf_others,plane,0,t) for t in thresholds]
        plt.plot(thresholds,completeness_others,color='black',lw=3,marker='o',label='Other hits')
        for j,length in enumerate(LP(lengths)):
            completeness_track = [CompletenessMean(rootDf_track,plane,length,t) for t in thresholds]
            plt.plot(thresholds,completeness_track,color=colors[j],marker='o',lw=2,label='>%i cm' %length)
            plt.grid()
            plt.legend(loc='best')
    af.End()
def PlotAll(rootDf_track,rootDf_others,jobType):
    plt.rcParams['font.size']=10
    canv = plt.figure(figsize=figsize)
    ax = [0,0,0,0]
    for i,plane in enumerate(planes[:-1]):
        ax[i] = canv.add_subplot(131+i)
        ax[i].set_title(jobType+' | %s plane' %plane)
        ax[i].set_xlabel('Threshold')
        if i==2:
            plt.axvline(3.25,color='black',lw=3,ls='--')
        else:
            plt.axvline(2.6,color='black',lw=3,ls='--')
        completeness_others = [CompletenessMean(rootDf_others,plane,0,t) for t in thresholds]
        plt.plot(thresholds,completeness_others,color='black',lw=3,label='Other hits')
        for j,length in enumerate(LP(lengths)):
            completeness_track = [CompletenessMean(rootDf_track,plane,length,t) for t in thresholds]
            plt.plot(thresholds,completeness_track,color=colors[j],lw=2,label='>%i cm' %length)
            plt.ylim(0.,1.)
            plt.xlim(1.,endT)
            plt.grid()
    ax[0].set_ylabel('Completeness')
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, ncol=5)
    af.End()