Ejemplo n.º 1
0
def GetFFHist(f,
              k,
              r,
              c,
              p='ttbar',
              v='GRL',
              num_or_den='Den',
              syst='',
              add_desert=False):  # file key region channel process variable
    import pennSoftLepton.PyAnalysisPlotting as anaplot
    other = '%s_%s' % (p, v)
    rtmp = r
    if r == 'all':
        rtmp = 'ltt'
    fullkey = ('FFTool_%s_%s_%s_%s%s' %
               (k, rtmp, syst, c, num_or_den)).replace('__', '_')
    hists = anaplot.GetPassEventBkgHistos(v, fullkey, p, f)
    if r == 'all' and ((c not in ['euu', 'uee']) or add_desert):
        hists += anaplot.GetPassEventBkgHistos(v,
                                               fullkey.replace('ltt',
                                                               'tlt'), p, f)
        hists += anaplot.GetPassEventBkgHistos(v,
                                               fullkey.replace('ltt',
                                                               'ttl'), p, f)
    if not hists:
        print 'Found no histograms for', fullkey
        return 0
    hist = hists[0]
    if len(hists) > 1: hist.Add(hists[1])
    if len(hists) > 2: hist.Add(hists[2])
    return hist
Ejemplo n.º 2
0
def GetFFHist(f,
              k,
              r,
              c,
              p='ttbar',
              v='MTW',
              num_or_den='Den'):  # file key region channel process variable
    other = '%s_%s' % (p, v)
    rtmp = r
    if r == 'all':
        rtmp = 'ltt'
    keyregionchannel = 'PassEvent_FFTool_%s_%s_%s%s' % (k, rtmp, c, num_or_den)
    #print 'Adding','%s/%s_%s'%(keyregionchannel,keyregionchannel,other)
    print 'Adding', ('FFTool_%s_%s_%s%s' % (k, rtmp, c, num_or_den)).replace(
        '__', '_')
    hists = anaplot.GetPassEventBkgHistos(
        v, ('FFTool_%s_%s_%s%s' % (k, rtmp, c, num_or_den)).replace('__',
                                                                    '_'), p, f)
    if not hists:
        return 0
    hist = hists[0]
    if r == 'all' and c not in ['euu', 'uee']:
        hist.Add(GetFFHist(f, k, 'tlt', c, p, v, num_or_den))
        hist.Add(GetFFHist(f, k, 'ttl', c, p, v, num_or_den))
    return hist
Ejemplo n.º 3
0
def main(options, args):

    pm = u"\u00B1"

    print 'Loading c++...'
    anaplot.LoadRootCore()
    ROOT.gROOT.SetBatch(False)

    #
    # Tables. E.g. MakeDetailedTable('')
    #
    MakeDetailedTable(options)

    print 'done.'
    return
Ejemplo n.º 4
0
def GetFFHistNew(f,k,r,c,p='ttbar',v='MTW',num_or_den='Den') : # file key region channel process variable
    other = '%s_%s'%(p,v)
    rtmp = r
    if r == 'all' :
        rtmp = 'ltt'
    keyregionchannel = ('FFTool_%s_%s_%s%s'%(k,rtmp,c,num_or_den)).replace('__','_')
    print 'Adding',keyregionchannel
    hists = anaplot.GetPassEventBkgHistos(v,keyregionchannel,p,f)
    if not hists :
        print 'NOT Adding (was missing): ',keyregionchannel
        return 0
    hist = hists[0]
    if r == 'all' :
        hist.Add(GetFFHistNew(f,k,'tlt',c,p,v,num_or_den))
        hist.Add(GetFFHistNew(f,k,'ttl',c,p,v,num_or_den))
    return hist
Ejemplo n.º 5
0
    print 'Loading c++...'
    anaplot.LoadRootCore()
    ROOT.gROOT.SetBatch(False)

    #
    # Tables. E.g. MakeDetailedTable('')
    #
    MakeDetailedTable(options)

    print 'done.'
    return


if __name__ == '__main__':
    p = anaplot.PassEventPlottingOptParser()
    p.p.remove_option('--susy')
    p.p.remove_option('-p')
    p.p.add_option('--region',
                   '-r',
                   type='string',
                   default='all',
                   dest='region',
                   help='Region (ttt,ltt,tlt,ttl,all (all means ltt+tlt+ttl)')
    p.p.add_option('--channel',
                   '-c',
                   type='string',
                   default='all',
                   dest='channel',
                   help='Channel (eee,euu,uee,uuu,all)')
    p.p.add_option('--bkgs',
Ejemplo n.º 6
0
def main(options,args) :
    
    print 'Loading c++...'
    anaplot.LoadRootCore()
    ROOT.gROOT.SetBatch(False)

    plotfunc.SetupStyle()
    ROOT.gStyle.SetPaintTextFormat("4.3f ")
    
    #
    # Draw plots
    #
    print 'Drawing the plots'
    cans = []
    for v in options.variables.split(',') :
        if not v : continue
        xlabel = options.histformat[v][3]
        n,low,high = options.histformat[v][:3]

        bkg_hists = []
        sig_hists = []
        data_hist = None

        rebin = []
        if hasattr(options.usermodule,'rebin') and v in options.usermodule.rebin.keys() :
            rebin = options.usermodule.rebin[v]

        if options.file :
            bkg_processes = options.processes.replace('data','').replace(',,',',')
            bkg_hists = anaplot.GetPassEventBkgHistos(v,options.key,bkg_processes,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high)
            anaplot.PrepareBkgHistosForStack(bkg_hists)
            if 'data' in options.processes :
                data_hist = anaplot.GetPassEventBkgHistos(v,options.key,'data',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high)[0]
                #data_hist = anaplot.GetPassEventBkgHistos(v,'FFTool_z_mccl_ltt_allNum','zjetdd',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high)[0]

                
        if options.susy :
            sig_hists = anaplot.GetPassEventSigHistos(v,options.key,options.susy,normalize=options.normalize,rebin=rebin)


        cans.append(anaplot.DrawHistos('%s_%s'%(options.key,v),v,xlabel,bkg_hists,sig_hists,data_hist=data_hist,dostack=options.stack,log=options.log,ratio=options.ratio,fb=options.fb))
        taxisfunc.SetXaxisRanges(cans[-1],low,high)

    #
    # Cutflow
    #
    f = ROOT.TFile(options.file)
    if f.IsZombie() :
        print 'exiting'
        return
    PrintCutflow(options.key
                 ,f.Get('PassEvent_%s/PassEvent_%s_PassW'%(options.key,options.key))
                 ,samp_list=options.processes.split(',')+['all']
                 ,scientific=True)
    f.Close()

    raw_input('Pausing. Press enter to exit.')
            
    if options.save :
        for can in cans :
            can.Print(can.GetName()+'.pdf')
            can.Print(can.GetName()+'.eps')

    print 'done.'
    return
Ejemplo n.º 7
0
def main(options,args) :
    
    print 'Loading c++...'
    anaplot.LoadRootCore()
    ROOT.gROOT.SetBatch(False)

    plotfunc.SetupStyle()
    style = ROOT.gROOT.GetStyle('mystyle')
    style.SetEndErrorSize(0)

    channel = 'all'
    if options.e :
        channel = 'Ele'
    if options.mu :
        channel = 'Mu'

    options.key = 'FFTool_ttt_%sNum'%(channel)
    
    #
    # Draw plots
    #
    print 'Drawing the plots'
    cans = []
    for v in options.variables.split(',') :
        if not v : continue
        xlabel = options.histformat[v][3]
        n,low,high = options.histformat[v][:3]

        bkg_hists = []
        sig_hists = []
        data_hist = None

        rebin = []
        if hasattr(options.usermodule,'rebin') and v in options.usermodule.rebin.keys() :
            rebin = options.usermodule.rebin[v]

        if options.file :
            bkg_processes = options.processes.replace('data','').replace(',,',',')
            #bkg_hists = anaplot.GetPassEventBkgHistos(v,options.key,bkg_processes,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high)

            bkg_hists.append(anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'vvv',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=Q(0.05,0.20))[0])
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'tother',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=Q(0.05,0.13))[0])
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'tz',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=Q(0.05,0.15))[0])
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'ttv',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=Q(0.05,0.13))[0])
#             bkg_hists[-1].Scale(3.15813/3.20905) # all other MC (but not ttbar) scaled down lumi-wise
            
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'ttbar',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.32)[0])
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'tw',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.32)[0])
            AddIf(bkg_hists[-1],anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'qqww',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.32))
            #bkg_hists[-1].SetTitle('t#bar{t}/Wt/WW/ttv/other')
            bkg_hists[-1].SetTitle('Others')

            bkg_hists.append(anaplot.GetPassEventBkgHistos(v,'FFTool_ttt_%sNum'%(channel),'zz',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=Q(0.05,0.08,0.04))[0])
#             bkg_hists[-1].Scale(3.15813/3.20905) # ZZ scaled down lumi-wise
            bkg_hists[-1].SetTitle('ZZ')

            bkg_hists.append(anaplot.GetPassEventBkgHistos(v,'FFTool_z_data_ltt_%sNum'%(channel),'zjetdd' ,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.00,ltt_tlt_ttl=True)[0])
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_z_data_ltt_%sNum'%(channel),'ttbar' ,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.00,ltt_tlt_ttl=True)[0],-1)
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_z_data_ltt_%sNum'%(channel),'tw'    ,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.00,ltt_tlt_ttl=True)[0],-1)
            AddIf(bkg_hists[-1],anaplot.GetPassEventBkgHistos(v,'FFTool_z_data_ltt_%sNum'%(channel),'qqww',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.00,ltt_tlt_ttl=True),-1)
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_z_data_ltt_%sNum'%(channel),'wz'    ,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.00,ltt_tlt_ttl=True)[0],-1)
            bkg_hists[-1].Add(anaplot.GetPassEventBkgHistos(v,'FFTool_z_data_ltt_%sNum'%(channel),'zz'    ,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.00,ltt_tlt_ttl=True)[0],-1)
            for i in range(bkg_hists[-1].GetNbinsX()) :
                bkg_hists[-1].SetBinError(i+1,bkg_hists[-1].GetBinContent(i+1)*0.38)
            
            bkg_hists[-1].SetTitle('Z+j / Z#gamma')
            import math
            pm = u"\u00B1"
            print '%s: %2.2f%s%2.2f'%('zjetdd',bkg_hists[-1].Integral(0,bkg_hists[-1].GetNbinsX()+1),pm,math.sqrt(sum(list(bkg_hists[-1].GetSumw2()))))

            bkg_hists += anaplot.GetPassEventBkgHistos(v,options.key,'wz',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=Q(0.07,0.05))
            bkg_hists[-1].Scale(1.17/1.15)
            bkg_hists[-1].SetTitle('W^{#pm}Z #times 1.17')

#             bkg_hists = []
#             bkg_hists.append(ROOT.TH1F('hist','hist',500,0,500))
#             for i in range(bkg_hists[-1].GetNbinsX()) :
#                 bkg_hists[-1].Fill(i+0.5)

#             for i in bkg_hists :
#                 taxisfunc.PutOverflowIntoLastBin(i,high)

#             for b in bkg_hists :
#                 if b.GetTitle() == 'zjetdd' :
#                     for i in range(b.GetNbinsX()) :
#                         b.SetBinError(i+1,b.GetBinContent(i+1)*0.38)
#                 if b.GetTitle() == 't#bar{t}/Wt/WW/ttv/other' :
#                     for i in range(b.GetNbinsX()) :
#                         b.SetBinError(i+1,b.GetBinContent(i+1)*0.32)
#                 if b.GetTitle() == '' :
#                     for i in range(b.GetNbinsX()) :
#                         b.SetBinError(i+1,b.GetBinContent(i+1)*0.32)

            anaplot.PrepareBkgHistosForStack(bkg_hists,colors_dict = colors_dict)

            for i in bkg_hists[:-1] :
                i.SetLineColor(i.GetFillColor())
            bkg_hists[-1].SetLineColor(ROOT.kRed)

            if 'data' in options.processes :
                data_hist = anaplot.GetPassEventBkgHistos(v,options.key,'data',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high)[0]
                #data_hist = anaplot.GetPassEventBkgHistos(v,'FFTool_z_mccl_ltt_%sNum'%(channel),'zjetdd',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high)[0]
                taxisfunc.PutOverflowIntoLastBin(data_hist,high)
                
        if options.susy :
            sig_hists = anaplot.GetPassEventSigHistos(v,options.key,options.susy,normalize=options.normalize,rebin=rebin)


        cans.append(DrawHistos('%s_%s'%(options.key,v),v,xlabel,bkg_hists,sig_hists,data_hist=data_hist,dostack=options.stack,log=options.log,ratio=options.ratio,fb=options.fb))
        taxisfunc.SetXaxisRanges(cans[-1],low,high)
        taxisfunc.SetYaxisRanges(cans[-1],0,57.15)

    #
    # Cutflow
    #
    f = ROOT.TFile(options.file)
    if f.IsZombie() :
        print 'exiting'
        return
    PrintCutflow(options.key
                 ,f.Get('PassEvent_%s/PassEvent_%s_PassW'%(options.key,options.key))
                 ,samp_list=options.processes.split(',')+['all']
                 ,scientific=True)
    f.Close()

    raw_input('Pausing. Press enter to exit.')
            
    if options.save :
        for can in cans :
            can.Print(can.GetName()+'.pdf')
            can.Print(can.GetName()+'.eps')

    print 'done.'
    return
Ejemplo n.º 8
0
#!/usr/bin/env python

import ROOT
import pennSoftLepton.PyAnalysisPlotting as anaplot
import math
from array import array
from pennSoftLepton.PyRandomStuff import GetFFHist,AddFFHistIf

anaplot.LoadRootCore()

version_emmanuel = True

variables = []
if version_emmanuel :
    variables = ['PtW','MTW','M3l','Mll','met_Et','NJets','NJetsLtEta2p5','PtllZ','PtllZ_Rebinned','YZminusYlW','MtWZ','DeltaPhiZWSyst','MWZ','NPV','jetPt','jetRapidity']
else :
    variables = list(ROOT.PSL.GetAllVariableStrings())
    for i in ['lepPt','lepEta','lepCharge'] :
        for j in ['lep0_index','lep1_index','lep2_index',
                  'lepW_index','lepleadZ_index','lepsubleadZ_index'] :
            variables += ['%s[%s]'%(i,j)]

skip_them = '\
nBaselineMuons nBaselineElectrons met_sumet jet0_index jet1_index \
DeltaRll PassTriggerEle PassTriggerMu PassTriggerMatch \
AntiIDSF_lep3 AntiIDSF_lep3_pt AntiIDSF_lep3_eta AntiIDSF_lep3_phi AntiIDSF_lep3_flavor \
AntiIDSF_lep3_pt_reco AntiIDSF_lep3_eta_reco AntiIDSF_lep3_phi_reco AntiIDSF_lep3_flavor_reco \
AntiIDSF_lep3_match_DR AntiIDSF_lep3_origin AntiIDSF_lep3_type NlepsfromZ AntiIDSF_lep3_truth_origin \
AntiIDSF_lep3_truth_type XCheckAntiIDSF_lep3_pt XCheckAntiIDSF_lep3_eta XCheckAntiIDSF_lep3_phi \
XCheckAntiIDSF_lep3_flavor XCheckAntiIDSF_lep3_origin XCheckAntiIDSF_lep3_type \
passLarError passTileError passSctError passCoreBit passPrimaryVtx     \
Ejemplo n.º 9
0
def main(options, args):

    plotfunc.SetupStyle()

    for i in options.histformat.keys():
        print '\'%s\':' % (i), options.histformat[i]

    anaplot.LoadRootCore()

    files_b, trees_b, keys_b, cf_b = anaplot.GetTreesFromFiles(options.bkgs)
    files_s, trees_s, keys_s, cf_s = anaplot.GetTreesFromFiles(options.susy)
    file_d, tree_d, key_d, cf_d = anaplot.GetTreesFromFiles(options.data)

    options.fb, lumi_scale_factor = helpers.GetTTreeLumiScaleFactor(
        files_b + files_s, options.fb)

    dweight = ''
    weight = 'TotalWeightNoSF*lepSFRecoIdIso[lep0_index]*lepSFRecoIdIso[lep1_index]*lepSFRecoIdIso[lep2_index]*EvtTrigSF*AntiIDSF_lep3*PassEvent_SMWZsig'
    #weight = 'TotalWeightNoPupNoSF'
    if ''.join(options.cuts):
        weight = weight + '*(%s)' % (' && '.join(options.cuts))
        dweight = '(' + ' && '.join(options.cuts) + ')'
    if hasattr(options.usermodule, 'weight'):
        weight += '*(%s)' % (options.usermodule.weight)
    if hasattr(options.usermodule, 'dataweight'):
        dweight += '*(%s)' % (options.usermodule.dataweight)

    cans = []

    # get the histograms from the files
    for vi, v1 in enumerate(options.variables.split(',')):
        n1, low1, high1 = options.histformat[v1][:3]
        xlabel1 = options.histformat[v1][3]

        rebin1 = []
        if hasattr(options.usermodule,
                   'rebin') and v1 in options.usermodule.rebin.keys():
            rebin1 = options.usermodule.rebin[v1]

        for vj, v2 in enumerate(options.variables.split(',')):
            if v2 == v1: continue
            if vj > vi: continue

            n2, low2, high2 = options.histformat[v2][:3]
            xlabel2 = options.histformat[v2][3]

            rebin2 = []
            if hasattr(options.usermodule,
                       'rebin') and v2 in options.usermodule.rebin.keys():
                rebin2 = options.usermodule.rebin[v2]

            bkg_hists = []
            sig_hists = []
            data_hist = None

            if options.bkgs:
                bkg_hists = anaplot.Get2dVariableHistsFromTrees(
                    trees_b,
                    keys_b,
                    v1,
                    v2,
                    weight,
                    n1,
                    low1,
                    high1,
                    n2,
                    low2,
                    high2,
                    normalize=options.normalize,
                    rebin1=rebin1,
                    rebin2=rebin2,
                    scale=lumi_scale_factor)
                anaplot.PrepareBkgHistosForStack(bkg_hists)
                for i, h in enumerate(bkg_hists):
                    canname = '%s_%s_%s' % (v1, v2, keys_b[i])
                    cans.append(ROOT.TCanvas(canname, canname, 500, 500))
                    h.SetMinimum(-0.00001)
                    plotfunc.AddHistogram(cans[-1], h, drawopt='colz')
                    plotfunc.FormatCanvasAxes(cans[-1])
                    plotfunc.SetAxisLabels(cans[-1], xlabel1, xlabel2)
            if options.susy:
                sig_hists = anaplot.Get2dVariableHistsFromTrees(
                    trees_s,
                    keys_s,
                    v1,
                    v2,
                    weight,
                    n1,
                    low1,
                    high1,
                    n2,
                    low2,
                    high2,
                    normalize=options.normalize,
                    rebin1=rebin1,
                    rebin2=rebin2,
                    scale=lumi_scale_factor)
                for i, h in enumerate(sig_hists):
                    canname = '%s_%s_%s' % (v1, v2, keys_s[i])
                    cans.append(ROOT.TCanvas(canname, canname, 500, 500))
                    h.SetMinimum(-0.00001)
                    plotfunc.AddHistogram(cans[-1], h, drawopt='colz')
                    plotfunc.FormatCanvasAxes(cans[-1])
                    plotfunc.SetAxisLabels(cans[-1], xlabel1, xlabel2)

            if options.data:
                data_hist = anaplot.Get2dVariableHistsFromTrees(
                    tree_d,
                    key_d,
                    v1,
                    v2,
                    dweight,
                    n1,
                    low1,
                    high1,
                    n2,
                    low2,
                    high2,
                    normalize=options.normalize,
                    rebin1=rebin1,
                    rebin2=rebin2,
                    scale=lumi_scale_factor)[0]
                data_hist.SetLineWidth(2)
                data_hist.SetLineColor(1)
                data_hist.SetMarkerColor(1)
                canname = '%s_%s_%s' % (v1, v2, 'data')
                cans.append(ROOT.TCanvas(canname, canname, 500, 500))
                h.SetMinimum(-0.00001)
                plotfunc.AddHistogram(cans[-1], h, drawopt='colz')
                plotfunc.FormatCanvasAxes(cans[-1])
                plotfunc.SetAxisLabels(cans[-1], xlabel1, xlabel2)

            cans.append(
                anaplot.DrawHistos(v,
                                   v,
                                   xlabel,
                                   bkg_hists,
                                   sig_hists,
                                   data_hist,
                                   dostack=options.stack,
                                   log=options.log,
                                   ratio=options.ratio,
                                   fb=options.fb))
    if not options.batch:
        raw_input('Press enter to exit')

    if options.save:
        for can in cans:
            can.Print(can.GetName() + '.pdf')

    print 'done.'
    return
Ejemplo n.º 10
0
                                   v,
                                   xlabel,
                                   bkg_hists,
                                   sig_hists,
                                   data_hist,
                                   dostack=options.stack,
                                   log=options.log,
                                   ratio=options.ratio,
                                   fb=options.fb))
    if not options.batch:
        raw_input('Press enter to exit')

    if options.save:
        for can in cans:
            can.Print(can.GetName() + '.pdf')

    print 'done.'
    return


if __name__ == '__main__':

    p = anaplot.TreePlottingOptParser()
    options, args = p.parse_args()

    if not options.variables:
        print 'Error! Please specify a variable!'
        sys.exit()

    main(options, args)
Ejemplo n.º 11
0
def main(options, args):

    print 'Loading c++...'
    anaplot.LoadRootCore()
    ROOT.gROOT.SetBatch(False)

    plotfunc.SetupStyle()
    style = ROOT.gROOT.GetStyle('mystyle')
    style.SetEndErrorSize(0)
    ROOT.gStyle.SetPaintTextFormat("4.3f ")

    #
    # Draw plots
    #
    print 'Drawing the plots'
    cans = []
    for v in options.variables.split(','):
        if not v: continue
        xlabel = options.histformat[v][3]
        n, low, high = options.histformat[v][:3]

        bkg_hists = []
        sig_hists = []
        data_hist = None

        rebin = []
        if hasattr(options.usermodule,
                   'rebin') and v in options.usermodule.rebin.keys():
            rebin = options.usermodule.rebin[v]

        if options.file:
            bkg_hists = []
            bkg_hists.append(
                anaplot.GetPassEventBkgHistos(v,
                                              options.key,
                                              'zz',
                                              options.file,
                                              normalize=options.normalize,
                                              rebin=rebin,
                                              n=n,
                                              low=low,
                                              high=high,
                                              globalError=Q(0.05, 0.08,
                                                            0.04))[0])
            bkg_hists[-1].Add(
                anaplot.GetPassEventBkgHistos(v,
                                              options.key,
                                              'vvv',
                                              options.file,
                                              normalize=options.normalize,
                                              rebin=rebin,
                                              n=n,
                                              low=low,
                                              high=high,
                                              globalError=Q(0.05, 0.20))[0])
            bkg_hists[-1].SetTitle('Others')
            bkg_hists.append(
                anaplot.GetPassEventBkgHistos(v,
                                              options.key,
                                              'ttv',
                                              options.file,
                                              normalize=options.normalize,
                                              rebin=rebin,
                                              n=n,
                                              low=low,
                                              high=high,
                                              globalError=Q(0.05, 0.13))[0])
            bkg_hists[-1].SetTitle('tt+V')
            bkg_hists.append(
                anaplot.GetPassEventBkgHistos(v,
                                              options.key,
                                              'wz',
                                              options.file,
                                              normalize=options.normalize,
                                              rebin=rebin,
                                              n=n,
                                              low=low,
                                              high=high,
                                              globalError=Q(0.05, 0.07))[0])
            bkg_hists[-1].Scale(1.17 / 1.15)
            bkg_hists[-1].SetTitle('W^{#pm}Z #times 1.17')
            bkg_hists.append(
                anaplot.GetPassEventBkgHistos(v,
                                              options.key,
                                              'ttbar',
                                              options.file,
                                              normalize=options.normalize,
                                              rebin=rebin,
                                              n=n,
                                              low=low,
                                              high=high,
                                              globalError=0.)[0])
            bkg_hists[-1].Add(
                anaplot.GetPassEventBkgHistos(v,
                                              options.key,
                                              'tw',
                                              options.file,
                                              normalize=options.normalize,
                                              rebin=rebin,
                                              n=n,
                                              low=low,
                                              high=high,
                                              globalError=0.)[0])
            bkg_hists[-1].Add(
                anaplot.GetPassEventBkgHistos(v,
                                              options.key,
                                              'qqww',
                                              options.file,
                                              normalize=options.normalize,
                                              rebin=rebin,
                                              n=n,
                                              low=low,
                                              high=high,
                                              globalError=0.)[0])
            bkg_hists[-1].SetTitle('t#bar{t} / Wt / WW')

            #bkg_hists.append(anaplot.GetPassEventBkgHistos(v,options.key,'zjet' ,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.)[0])
            #bkg_hists.append(anaplot.GetPassEventBkgHistos(v,options.key,'zgam' ,options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high,globalError=0.)[0])

            anaplot.PrepareBkgHistosForStack(bkg_hists,
                                             colors_dict=colors_dict)

            for i in bkg_hists:
                i.SetLineColor(i.GetFillColor())

            data_hist = anaplot.GetPassEventBkgHistos(
                v,
                options.key,
                'data',
                options.file,
                normalize=options.normalize,
                rebin=rebin,
                n=n,
                low=low,
                high=high)[0]
            #data_hist = anaplot.GetPassEventBkgHistos(v,'FFTool_z_mccl_ltt_allNum','zjetdd',options.file,normalize=options.normalize,rebin=rebin,n=n,low=low,high=high)[0]

        if options.susy:
            sig_hists = anaplot.GetPassEventSigHistos(
                v,
                options.key,
                options.susy,
                normalize=options.normalize,
                rebin=rebin)

        #bkg_hists[0].GetXaxis().SetNdivisions(5,0,0)
        cans.append(
            DrawHistos('%s_%s' % (options.key, v),
                       v,
                       xlabel,
                       bkg_hists,
                       sig_hists,
                       data_hist=data_hist,
                       dostack=options.stack,
                       log=options.log,
                       ratio=options.ratio,
                       fb=options.fb))
        taxisfunc.SetXaxisRanges(cans[-1], low, high)
        taxisfunc.SetYaxisRanges(cans[-1], 0, 12 * 0.9525)
        taxisfunc.SetNdivisions(cans[-1], 9, 0, 0)

    #
    # Cutflow
    #
    f = ROOT.TFile(options.file)
    if f.IsZombie():
        print 'exiting'
        return
    PrintCutflow(options.key,
                 f.Get('PassEvent_%s/PassEvent_%s_PassW' %
                       (options.key, options.key)),
                 samp_list=options.processes.split(',') + ['all'],
                 scientific=True)
    f.Close()

    raw_input('Pausing. Press enter to exit.')

    if options.save:
        for can in cans:
            can.Print(can.GetName() + '.pdf')
            can.Print(can.GetName() + '.eps')

    print 'done.'
    return
Ejemplo n.º 12
0
def main(options, args):

    anaplot.LoadRootCore()

    files_b, trees_b, keys_b, cf_b = anaplot.GetTreesFromFiles(options.bkgs)
    files_s, trees_s, keys_s, cf_s = anaplot.GetTreesFromFiles(options.susy)
    file_d, tree_d, key_d, cf_d = anaplot.GetTreesFromFiles(options.data)
    all_cutflows = cf_b + cf_s + cf_d

    options.fb, lumi_scale_factor = helpers.GetTTreeLumiScaleFactor(
        files_b + files_s, options.fb)

    for i in all_cutflows:
        for j in i:
            j.Scale(lumi_scale_factor)

    dweight = ''
    weight = 'TotalWeightNoSF'
    #     if ''.join(options.cuts) :
    #         weight = weight+'*(%s)'%(' && '.join(options.cuts))
    #         dweight = '('+' && '.join(options.cuts)+')'
    if hasattr(options.usermodule, 'weight'):
        weight += '*(%s)' % (options.usermodule.weight)
    if hasattr(options.usermodule, 'dataweight'):
        dweight += '*(%s)' % (options.usermodule.dataweight)

    cuts = []
    samples = []
    data_index = -1
    if options.bkgs:
        samples += list(
            a.replace('.root', '') for a in options.bkgs.split(','))
    samples += ['Total Bkg.']
    totbkg_index = len(samples) - 1
    if options.susy:
        samples += list(
            a.replace('.root', '') for a in options.susy.split(','))
    if options.data:
        samples += ['data']
        data_index = len(samples) - 1
    samples += ['s/b']
    s_over_b_index = len(samples) - 1
    samples += ['purity']
    purity_index = len(samples) - 1
    print samples

    #
    # Figure out what all the cuts were
    #
    firsthistlist = all_cutflows[0]
    for i in firsthistlist:
        for y in range(i.GetNbinsY(), 0, -1):
            cuts.append(i.GetYaxis().GetBinLabel(y))

    if hasattr(options.usermodule, 'cutflow'):
        for i in options.usermodule.cutflow:
            cuts.insert(0, i[0])

    cuts.reverse()
    print cuts

    #
    # Make a histogram to fill
    #
    cutflow_hist = ROOT.TH2F('Cutflow', 'Cutflow', len(samples), 0,
                             len(samples), len(cuts), 0, len(cuts))
    for i in range(len(samples)):
        cutflow_hist.GetXaxis().SetBinLabel(i + 1, samples[i])
    for i in range(len(cuts)):
        cutflow_hist.GetYaxis().SetBinLabel(i + 1, cuts[i])

    #
    # Grab the bin content from the "all" histograms that were saved in each file. (bkgs)
    #
    current_sample = 1
    for i, histlist in enumerate(cf_b):
        current_cut = len(cuts)
        if hasattr(options.usermodule, 'cutflow'):
            tree_cuts_list = list('(' + a[1] + ')'
                                  for a in options.usermodule.cutflow)
            for j in options.usermodule.cutflow:
                tmp_weight = weight + '*(%s)' % (' && '.join(tree_cuts_list))
                trees_b[keys_b[i]].Draw('GRL>>h1(2,0,2)', tmp_weight, 'egoff')
                tree_cuts_list.pop()
                hist = ROOT.gDirectory.Get('h1')
                hist.Scale(lumi_scale_factor)
                cutflow_hist.SetBinContent(current_sample, current_cut,
                                           hist.GetBinContent(2))
                cutflow_hist.SetBinError(current_sample, current_cut,
                                         hist.GetBinError(2))
                totbkg_content = cutflow_hist.GetBinContent(
                    totbkg_index + 1, current_cut) + hist.GetBinContent(2)
                totbkg_error = math.sqrt(
                    cutflow_hist.GetBinError(totbkg_index +
                                             1, current_cut)**2 +
                    hist.GetBinError(2)**2)
                cutflow_hist.SetBinContent(totbkg_index + 1, current_cut,
                                           totbkg_content)
                cutflow_hist.SetBinError(totbkg_index + 1, current_cut,
                                         totbkg_error)
                ROOT.gROOT.ProcessLine('delete h1')
                current_cut -= 1
        for hist in histlist:
            for x in range(hist.GetNbinsX()):
                if hist.GetXaxis().GetBinLabel(x + 1) == 'all':
                    allbin = x + 1
                    break
            for y in range(hist.GetNbinsY(), 0, -1):
                cutflow_hist.SetBinContent(current_sample, current_cut,
                                           hist.GetBinContent(allbin, y))
                cutflow_hist.SetBinError(current_sample, current_cut,
                                         hist.GetBinError(allbin, y))
                totbkg_content = cutflow_hist.GetBinContent(
                    totbkg_index + 1, current_cut) + hist.GetBinContent(
                        allbin, y)
                totbkg_error = math.sqrt(
                    cutflow_hist.GetBinError(totbkg_index +
                                             1, current_cut)**2 +
                    hist.GetBinError(allbin, y)**2)
                cutflow_hist.SetBinContent(totbkg_index + 1, current_cut,
                                           totbkg_content)
                cutflow_hist.SetBinError(totbkg_index + 1, current_cut,
                                         totbkg_error)
                current_cut -= 1
        current_sample += 1

    current_sample += 1

    #
    # susy (or wz!)
    #
    for i, histlist in enumerate(cf_s):
        current_cut = len(cuts)
        if hasattr(options.usermodule, 'cutflow'):
            tree_cuts_list = list('(' + a[1] + ')'
                                  for a in options.usermodule.cutflow)
            for j in options.usermodule.cutflow:
                #print tree_cuts_list
                tmp_weight = weight + '*(%s)' % (' && '.join(tree_cuts_list))
                trees_s[keys_s[i]].Draw('GRL>>h1(2,0,2)', tmp_weight, 'egoff')
                tree_cuts_list.pop()
                hist = ROOT.gDirectory.Get('h1')
                hist.Scale(lumi_scale_factor)
                signal_n = hist.GetBinContent(2)
                cutflow_hist.SetBinContent(current_sample, current_cut,
                                           signal_n)
                if signal_n > 0:
                    cutflow_hist.SetBinError(current_sample, current_cut,
                                             100. / float(math.sqrt(signal_n)))
                tot_bkg = cutflow_hist.GetBinContent(totbkg_index + 1,
                                                     current_cut)
                if tot_bkg:
                    cutflow_hist.SetBinContent(s_over_b_index + 1, current_cut,
                                               signal_n / float(tot_bkg))
                if tot_bkg + signal_n:
                    cutflow_hist.SetBinContent(
                        purity_index + 1, current_cut,
                        100. * signal_n / float(tot_bkg + signal_n))
                ROOT.gROOT.ProcessLine('delete h1')
                current_cut -= 1
        for hist in histlist:
            for x in range(hist.GetNbinsX()):
                if hist.GetXaxis().GetBinLabel(x + 1) == 'all':
                    allbin = x + 1
                    break
            for y in range(hist.GetNbinsY(), 0, -1):
                signal_n = hist.GetBinContent(allbin, y)
                cutflow_hist.SetBinContent(current_sample, current_cut,
                                           signal_n)
                cutflow_hist.SetBinError(current_sample, current_cut,
                                         100. / float(math.sqrt(signal_n)))
                tot_bkg = cutflow_hist.GetBinContent(totbkg_index + 1,
                                                     current_cut)
                if tot_bkg:
                    cutflow_hist.SetBinContent(s_over_b_index + 1, current_cut,
                                               signal_n / float(tot_bkg))
                if tot_bkg + signal_n:
                    cutflow_hist.SetBinContent(
                        purity_index + 1, current_cut,
                        100. * signal_n / float(tot_bkg + signal_n))
                current_cut -= 1
        current_sample += 1

    #
    # data
    #
    for i, histlist in enumerate(cf_d):
        current_cut = len(cuts)
        if hasattr(options.usermodule, 'cutflow'):
            tree_cuts_list = list('(' + a[1] + ')'
                                  for a in options.usermodule.cutflow)
            for j in options.usermodule.cutflow:
                tmp_weight = weight + '*(%s)' % (' && '.join(tree_cuts_list))
                tree_d[key_d[i]].Draw('GRL>>h1(2,0,2)', tmp_weight, 'egoff')
                tree_cuts_list.pop()
                hist = ROOT.gDirectory.Get('h1')
                hist.Scale(lumi_scale_factor)
                cutflow_hist.SetBinContent(current_sample, current_cut,
                                           hist.GetBinContent(2))
                cutflow_hist.SetBinError(current_sample, current_cut,
                                         hist.GetBinError(2))
                ROOT.gROOT.ProcessLine('delete h1')
                current_cut -= 1
        for hist in histlist:
            for x in range(hist.GetNbinsX()):
                if (hist.GetXaxis().GetBinLabel(x + 1) == 'data'):
                    allbin = x + 1
                    break
            for y in range(hist.GetNbinsY(), 0, -1):
                cutflow_hist.SetBinContent(current_sample, current_cut,
                                           hist.GetBinContent(allbin, y))
                cutflow_hist.SetBinError(current_sample, current_cut,
                                         hist.GetBinError(allbin, y))
                current_cut -= 1
        current_sample += 1

    PrintCutflow('Cutflow',
                 cutflow_hist,
                 samp_list=','.join(samples),
                 latex=options.latex)

    return
Ejemplo n.º 13
0
def main(options, args):

    plotfunc.SetupStyle()

    for i in options.histformat.keys():
        print '\'%s\':' % (i), options.histformat[i]

    anaplot.LoadRootCore()

    files_b, trees_b, keys_b, cf_b = anaplot.GetTreesFromFiles(options.bkgs)
    files_s, trees_s, keys_s, cf_s = anaplot.GetTreesFromFiles(options.susy)
    file_d, tree_d, key_d, cf_d = anaplot.GetTreesFromFiles(options.data)

    options.fb, lumi_scale_factor = helpers.GetTTreeLumiScaleFactor(
        files_b + files_s, options.fb)

    dweight = ''
    weight = 'TotalWeightNoSF'
    if ''.join(options.cuts):
        weight = weight + '*(%s)' % (' && '.join(options.cuts))
        dweight = '(' + ' && '.join(options.cuts) + ')'
    if hasattr(options.usermodule, 'weight'):
        weight += '*(%s)' % (options.usermodule.weight)
    if hasattr(options.usermodule, 'dataweight'):
        dweight += '*(%s)' % (options.usermodule.dataweight)

    cans = []

    # get the histograms from the files
    for v in options.variables.split(','):
        n, low, high = options.histformat[v][:3]
        xlabel = options.histformat[v][3]

        bkg_hists = []
        sig_hists = []
        data_hist = None

        rebin = []
        if hasattr(options.usermodule,
                   'rebin') and v in options.usermodule.rebin.keys():
            rebin = options.usermodule.rebin[v]

        if options.bkgs:
            bkg_hists = anaplot.GetVariableHistsFromTrees(
                trees_b,
                keys_b,
                v,
                weight,
                n,
                low,
                high,
                normalize=options.normalize,
                rebin=rebin,
                scale=lumi_scale_factor)
            anaplot.PrepareBkgHistosForStack(bkg_hists)
        if options.susy:
            sig_hists = anaplot.GetVariableHistsFromTrees(
                trees_s,
                keys_s,
                v,
                weight,
                n,
                low,
                high,
                normalize=options.normalize,
                rebin=rebin,
                scale=lumi_scale_factor)
        if options.data:
            data_hist = anaplot.GetVariableHistsFromTrees(
                tree_d,
                key_d,
                v,
                dweight,
                n,
                low,
                high,
                normalize=options.normalize,
                rebin=rebin,
                scale=lumi_scale_factor)[0]
            data_hist.SetLineWidth(2)
            data_hist.SetLineColor(1)
            data_hist.SetMarkerColor(1)

        nsignal = 0
        for si, s in enumerate(keys_s):
            mass_map = GetMassesMap()
            for i in mass_map.keys():
                if str(i) in sig_hists[si].GetName():
                    title = '%s,%s' % (mass_map[i]['mc1'], mass_map[i]['mn1'])
                    sig_hists[si].SetTitle(title)
            sig_hists[si].SetLineWidth(2)
            sig_hists[si].SetLineColor(signal_colors[nsignal])
            sig_hists[si].SetMarkerColor(signal_colors[nsignal])
            nsignal += 1

        cans.append(
            anaplot.DrawHistos(v,
                               v,
                               xlabel,
                               bkg_hists,
                               sig_hists,
                               data_hist,
                               dostack=options.stack,
                               log=options.log,
                               ratio=options.ratio,
                               fb=options.fb))

    if not options.batch:
        raw_input('Press enter to exit')

    if options.save:
        for can in cans:
            can.Print(can.GetName() + '.pdf')

    print 'done.'
    return
Ejemplo n.º 14
0
def main(options, args):

    print 'Loading c++...'
    anaplot.LoadRootCore()
    ROOT.gROOT.SetBatch(False)

    plotfunc.SetupStyle()

    options.keys = []
    if not options.e:
        options.keys += [
            options.key + '_ttt_MuNum', options.key + '_ltt_MuDen'
        ]
    if not options.mu:
        options.keys += [
            options.key + '_ttt_EleNum', options.key + '_ltt_EleDen'
        ]

    print options.keys

    #
    # Draw plots
    #
    print 'Drawing the plots'
    cans = []
    for v in options.variables.split(','):
        if not v: continue
        n, low, high = options.histformat[v][:3]

        lep_pt_dijet_num = None
        lep_pt_dijet_den = None

        for k in options.keys:

            bkg_hists = []
            sig_hists = []
            data_hist = None

            rebin = []
            if hasattr(options.usermodule,
                       'rebin') and v in options.usermodule.rebin.keys():
                rebin = options.usermodule.rebin[v]
                if ('lepPt' in v) and ('Mu' in k):
                    rebin = [0, 9, 15, 20, 30, 100]

            if options.file:
                bkg_processes = options.processes.replace('data', '').replace(
                    ',,', ',')
                bkg_hists = anaplot.GetPassEventBkgHistos(
                    v,
                    k,
                    bkg_processes,
                    options.file,
                    normalize=options.normalize,
                    rebin=rebin,
                    n=n,
                    low=low,
                    high=high)
                anaplot.PrepareBkgHistosForStack(bkg_hists)
                if 'data' in options.processes:
                    data_hist = anaplot.GetPassEventBkgHistos(
                        v,
                        k,
                        'data',
                        options.file,
                        normalize=options.normalize,
                        rebin=rebin,
                        n=n,
                        low=low,
                        high=high)[0]

            xlabel = ROOT.PSL.GetXaxisLabel(v.split('[')[0])
            cans.append(
                anaplot.DrawHistos('%s_%s' % (k, v),
                                   v,
                                   xlabel,
                                   bkg_hists,
                                   sig_hists,
                                   data_hist=data_hist,
                                   dostack=options.stack,
                                   log=options.log,
                                   ratio=options.ratio,
                                   fb=options.fb))
            taxisfunc.SetXaxisRanges(cans[-1], low, high)

    #
    # Specifically get the fake factor in pt:
    #
    cans_divide = []

    v = 'lepPt[lepW_index]'
    rebin_mu = [0, 9, 15, 20, 30, 100]
    rebin_e = [0, 9, 15, 20, 30, 50, 100]

    hists_MuNum = dict()
    hists_MuDen = dict()
    hists_EleNum = dict()
    hists_EleDen = dict()

    mu_options = options.file, options.normalize, rebin_mu
    e_options = options.file, options.normalize, rebin_e

    for p in options.processes.split(','):
        hists_MuNum[p] = anaplot.GetPassEventBkgHistos(
            v, options.key + '_ttt_MuNum', p, *mu_options)[0]
        hists_MuDen[p] = anaplot.GetPassEventBkgHistos(
            v, options.key + '_ltt_MuDen', p, *mu_options)[0]
        hists_EleNum[p] = anaplot.GetPassEventBkgHistos(
            v, options.key + '_ttt_EleNum', p, *e_options)[0]
        hists_EleDen[p] = anaplot.GetPassEventBkgHistos(
            v, options.key + '_ltt_EleDen', p, *e_options)[0]

    z_w = ''
    tmp = ROOT.TFile(options.file)
    syst_check = 'PassEvent_FFTool_forsyst_%s_ttt_MuNum/PassEvent_FFTool_forsyst_%s_ttt_MuNum_zjet_lepPt_antilep0_index' % (
        'wid', 'wid')
    print syst_check
    if tmp.Get(syst_check):
        z_w = 'wid'
    elif tmp.Get(syst_check.replace('wid', 'zid')):
        z_w = 'zid'

    if z_w and options.syst:
        do_z = (z_w == 'zid')
        # try to get SR FF
        hists_MuNum['zjet_sr'] = anaplot.GetPassEventBkgHistos(
            'lepPt_antilep0_index', 'FFTool_forsyst_%s_ttt_MuNum' % (z_w),
            'zjet', *mu_options)[0]
        if True:
            hists_MuDen['zjet_sr'] = anaplot.GetPassEventBkgHistos(
                'lepPt_lepW_index', 'FFTool_forsyst_ltt_MuDen', 'zjet',
                *mu_options)[0]
        if do_z:
            hists_MuDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepleadZ_index',
                                              'FFTool_forsyst_tlt_MuDen',
                                              'zjet', *mu_options)[0])
        if do_z:
            hists_MuDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepsubleadZ_index',
                                              'FFTool_forsyst_ttl_MuDen',
                                              'zjet', *mu_options)[0])

        hists_MuNum['zjet_sr'].Add(
            anaplot.GetPassEventBkgHistos(
                'lepPt_antilep0_index', 'FFTool_forsyst_%s_ttt_MuNum' % (z_w),
                'zgam', *mu_options)[0])
        if True:
            hists_MuDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepW_index',
                                              'FFTool_forsyst_ltt_MuDen',
                                              'zgam', *mu_options)[0])
        if do_z:
            hists_MuDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepleadZ_index',
                                              'FFTool_forsyst_tlt_MuDen',
                                              'zgam', *mu_options)[0])
        if do_z:
            hists_MuDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepsubleadZ_index',
                                              'FFTool_forsyst_ttl_MuDen',
                                              'zgam', *mu_options)[0])

        hists_EleNum['zjet_sr'] = anaplot.GetPassEventBkgHistos(
            'lepPt_antilep0_index', 'FFTool_forsyst_%s_ttt_EleNum' % (z_w),
            'zjet', *e_options)[0]
        if True:
            hists_EleDen['zjet_sr'] = anaplot.GetPassEventBkgHistos(
                'lepPt_lepW_index', 'FFTool_forsyst_ltt_EleDen', 'zjet',
                *e_options)[0]
        if do_z:
            hists_EleDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepleadZ_index',
                                              'FFTool_forsyst_tlt_EleDen',
                                              'zjet', *e_options)[0])
        if do_z:
            hists_EleDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepsubleadZ_index',
                                              'FFTool_forsyst_ttl_EleDen',
                                              'zjet', *e_options)[0])

        hists_EleNum['zjet_sr'].Add(
            anaplot.GetPassEventBkgHistos(
                'lepPt_antilep0_index', 'FFTool_forsyst_%s_ttt_EleNum' % (z_w),
                'zgam', *e_options)[0])
        if True:
            hists_EleDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepW_index',
                                              'FFTool_forsyst_ltt_EleDen',
                                              'zgam', *e_options)[0])
        if do_z:
            hists_EleDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepleadZ_index',
                                              'FFTool_forsyst_tlt_EleDen',
                                              'zgam', *e_options)[0])
        if do_z:
            hists_EleDen['zjet_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepsubleadZ_index',
                                              'FFTool_forsyst_ttl_EleDen',
                                              'zgam', *e_options)[0])

        # now for ttbar
        hists_MuNum['ttbar_sr'] = anaplot.GetPassEventBkgHistos(
            'lepPt_antilep0_index', 'FFTool_forsyst_%s_ttt_MuNum' % (z_w),
            'ttbar', *mu_options)[0]
        if True:
            hists_MuDen['ttbar_sr'] = anaplot.GetPassEventBkgHistos(
                'lepPt_lepW_index', 'FFTool_forsyst_ltt_MuDen', 'ttbar',
                *mu_options)[0]
        if do_z:
            hists_MuDen['ttbar_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepleadZ_index',
                                              'FFTool_forsyst_tlt_MuDen',
                                              'ttbar', *mu_options)[0])
        if do_z:
            hists_MuDen['ttbar_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepsubleadZ_index',
                                              'FFTool_forsyst_ttl_MuDen',
                                              'ttbar', *mu_options)[0])

        hists_EleNum['ttbar_sr'] = anaplot.GetPassEventBkgHistos(
            'lepPt_antilep0_index', 'FFTool_forsyst_%s_ttt_EleNum' % (z_w),
            'ttbar', *e_options)[0]
        if True:
            hists_EleDen['ttbar_sr'] = anaplot.GetPassEventBkgHistos(
                'lepPt_lepW_index', 'FFTool_forsyst_ltt_EleDen', 'ttbar',
                *e_options)[0]
        if do_z:
            hists_EleDen['ttbar_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepleadZ_index',
                                              'FFTool_forsyst_tlt_EleDen',
                                              'ttbar', *e_options)[0])
        if do_z:
            hists_EleDen['ttbar_sr'].Add(
                anaplot.GetPassEventBkgHistos('lepPt_lepsubleadZ_index',
                                              'FFTool_forsyst_ttl_EleDen',
                                              'ttbar', *e_options)[0])

        hists_MuNum['zjet_sr'].SetName('zjet_sr')
        hists_MuNum['zjet_sr'].SetTitle('zjet+z#gamma SR FF')
        hists_EleNum['zjet_sr'].SetName('zjet_sr')
        hists_EleNum['zjet_sr'].SetTitle('zjet+z#gamma SR FF')

        if False:
            hists_MuDen['zjet_sr'].Add(hists_MuDen['ttbar_sr'])
            hists_EleDen['zjet_sr'].Add(hists_EleDen['ttbar_sr'])
            hists_MuNum['zjet_sr'].Add(hists_MuNum['ttbar_sr'])
            hists_EleNum['zjet_sr'].Add(hists_EleNum['ttbar_sr'])
            hists_MuNum['zjet_sr'].SetTitle('zjet+z#gamma+ttbar SR FF')
            hists_EleNum['zjet_sr'].SetTitle('zjet+z#gamma+ttbar SR FF')

        hists_MuNum['zjet_sr'].Divide(hists_MuDen['zjet_sr'])
        hists_EleNum['zjet_sr'].Divide(hists_EleDen['zjet_sr'])

        hists_MuNum['ttbar_sr'].SetName('ttbar_sr')
        hists_MuNum['ttbar_sr'].SetTitle('ttbar SR FF')
        hists_EleNum['ttbar_sr'].SetName('ttbar_sr')
        hists_EleNum['ttbar_sr'].SetTitle('ttbar SR FF')
        hists_MuNum['ttbar_sr'].Divide(hists_MuDen['ttbar_sr'])
        hists_EleNum['ttbar_sr'].Divide(hists_EleDen['ttbar_sr'])

    print hists_MuNum.keys()

    if (options.region == 'dijet') and 'dijet' in hists_EleNum.keys():
        hists_MuNum['dijet'].SetLineColor(ROOT.kBlue + 1)
        hists_MuNum['dijet'].SetMarkerColor(ROOT.kBlue + 1)
        hists_EleNum['dijet'].SetLineColor(ROOT.kBlue + 1)
        hists_EleNum['dijet'].SetMarkerColor(ROOT.kBlue + 1)

        hists_MuNum['dijet'].Divide(hists_MuDen['dijet'])
        hists_EleNum['dijet'].Divide(hists_EleDen['dijet'])

    if (options.region == 'zjet') and 'zjet' in hists_EleNum.keys():

        hists_MuNum['zjet'].SetTitle('zjet (no z#gamma) MC')
        hists_EleNum['zjet'].SetTitle('zjet (no z#gamma) MC')

        if 'zgam' in hists_EleNum.keys():
            print '##############################################################################'
            print '## Adding zgam to your estimate'
            print '##############################################################################'
            hists_MuNum['zjet'].Add(hists_MuNum['zgam'])
            hists_EleNum['zjet'].Add(hists_EleNum['zgam'])

            hists_MuNum['zjet'].SetTitle('zjet+z#gamma MC')
            hists_EleNum['zjet'].SetTitle('zjet+z#gamma MC')

        hists_MuNum['zjet'].SetLineColor(ROOT.kBlue + 1)
        hists_MuNum['zjet'].SetMarkerColor(ROOT.kBlue + 1)
        hists_EleNum['zjet'].SetLineColor(ROOT.kBlue + 1)
        hists_EleNum['zjet'].SetMarkerColor(ROOT.kBlue + 1)

        hists_MuNum['zjet'].Divide(hists_MuDen['zjet'])
        hists_EleNum['zjet'].Divide(hists_EleDen['zjet'])


#     cans.append(ROOT.TCanvas('%s_Mu_ff_dijet'%(v),'%s_Mu_ff'%(v),500,500))
#     plotfunc.AddHistogram(cans[-1],dijet_hist_MuNum)
#     plotfunc.FormatCanvasAxes(cans[-1])
#     taxisfunc.SetYaxisRanges(cans[-1],0,0.5)

#     cans.append(ROOT.TCanvas('%s_Ele_ff_dijet'%(v),'%s_Ele_ff'%(v),500,500))
#     plotfunc.AddHistogram(cans[-1],dijet_hist_EleNum)
#     plotfunc.FormatCanvasAxes(cans[-1])
#     taxisfunc.SetYaxisRanges(cans[-1],0,0.5)

    if 'data' in hists_EleNum.keys():
        hists_EleNum['data'].SetTitle('With VV subtraction')
        hists_EleDen['data'].SetTitle('With VV subtraction')
        hists_MuNum['data'].SetTitle('With VV subtraction')
        hists_MuDen['data'].SetTitle('With VV subtraction')

        if (options.region == 'dijet'):
            hists_EleNum['data_bws'] = hists_EleNum['data'].Clone()
            hists_EleNum['data_bws'].SetName(
                hists_EleNum['data_bws'].GetName() + '_bws')
            hists_EleDen['data_bws'] = hists_EleDen['data'].Clone()
            hists_EleDen['data_bws'].SetName(
                hists_EleDen['data_bws'].GetName() + '_bws')
            hists_MuNum['data_bws'] = hists_MuNum['data'].Clone()
            hists_MuNum['data_bws'].SetName(hists_MuNum['data_bws'].GetName() +
                                            '_bws')
            hists_MuDen['data_bws'] = hists_MuDen['data'].Clone()
            hists_MuDen['data_bws'].SetName(hists_MuDen['data_bws'].GetName() +
                                            '_bws')

            hists_EleNum['data_bws'].SetTitle('No EW subtraction')
            hists_EleDen['data_bws'].SetTitle('No EW subtraction')
            hists_MuNum['data_bws'].SetTitle('No EW subtraction')
            hists_MuDen['data_bws'].SetTitle('No EW subtraction')

            hists_EleNum['data_bzs'] = hists_EleNum['data_bws'].Clone()
            hists_EleNum['data_bzs'].SetName(
                hists_EleNum['data_bzs'].GetName() + '_bzs')
            hists_EleDen['data_bzs'] = hists_EleDen['data_bws'].Clone()
            hists_EleDen['data_bzs'].SetName(
                hists_EleDen['data_bzs'].GetName() + '_bzs')
            hists_MuNum['data_bzs'] = hists_MuNum['data_bws'].Clone()
            hists_MuNum['data_bzs'].SetName(hists_MuNum['data_bzs'].GetName() +
                                            '_bzs')
            hists_MuDen['data_bzs'] = hists_MuDen['data_bws'].Clone()
            hists_MuDen['data_bzs'].SetName(hists_MuDen['data_bzs'].GetName() +
                                            '_bzs')

            hists_EleNum['data_bzs'].SetTitle('With W subtraction')
            hists_EleDen['data_bzs'].SetTitle('With W subtraction')
            hists_MuNum['data_bzs'].SetTitle('With W subtraction')
            hists_MuDen['data_bzs'].SetTitle('With W subtraction')

            for i in ['wje', 'wjm', 'wjt', 'zjee', 'zjmm', 'zjtt']:
                if i in hists_EleNum.keys():
                    print 'Subtracting', i
                    hists_EleNum['data'].Add(hists_EleNum[i], -1)
                    hists_EleDen['data'].Add(hists_EleDen[i], -1)
                    hists_MuNum['data'].Add(hists_MuNum[i], -1)
                    hists_MuDen['data'].Add(hists_MuDen[i], -1)
                    if i not in ['zjee', 'zjmm', 'zjtt']:
                        hists_EleNum['data_bzs'].Add(hists_EleNum[i], -1)
                        hists_EleDen['data_bzs'].Add(hists_EleDen[i], -1)
                        hists_MuNum['data_bzs'].Add(hists_MuNum[i], -1)
                        hists_MuDen['data_bzs'].Add(hists_MuDen[i], -1)

            hists_MuNum['data_bws'].Divide(hists_MuDen['data_bws'])
            hists_EleNum['data_bws'].Divide(hists_EleDen['data_bws'])

            hists_MuNum['data_bzs'].Divide(hists_MuDen['data_bzs'])
            hists_EleNum['data_bzs'].Divide(hists_EleDen['data_bzs'])

        if (options.region == 'zjet'):
            hists_EleNum['data_bvvs'] = hists_EleNum['data'].Clone()
            hists_EleNum['data_bvvs'].SetName(
                hists_EleNum['data_bvvs'].GetName() + '_bvvs')
            hists_EleDen['data_bvvs'] = hists_EleDen['data'].Clone()
            hists_EleDen['data_bvvs'].SetName(
                hists_EleDen['data_bvvs'].GetName() + '_bvvs')
            hists_MuNum['data_bvvs'] = hists_MuNum['data'].Clone()
            hists_MuNum['data_bvvs'].SetName(
                hists_MuNum['data_bvvs'].GetName() + '_bvvs')
            hists_MuDen['data_bvvs'] = hists_MuDen['data'].Clone()
            hists_MuDen['data_bvvs'].SetName(
                hists_MuDen['data_bvvs'].GetName() + '_bvvs')

            hists_EleNum['data_bvvs'].SetTitle('No VV subtraction')
            hists_EleDen['data_bvvs'].SetTitle('No VV subtraction')
            hists_MuNum['data_bvvs'].SetTitle('No VV subtraction')
            hists_MuDen['data_bvvs'].SetTitle('No VV subtraction')

            # 15% systematic on vv subtraction
            hists_EleNum['data_vv15sys'] = hists_EleNum['data'].Clone()
            hists_EleNum['data_vv15sys'].SetName(
                hists_EleNum['data_vv15sys'].GetName() + '_vv15sys')
            hists_EleDen['data_vv15sys'] = hists_EleDen['data'].Clone()
            hists_EleDen['data_vv15sys'].SetName(
                hists_EleDen['data_vv15sys'].GetName() + '_vv15sys')
            hists_MuNum['data_vv15sys'] = hists_MuNum['data'].Clone()
            hists_MuNum['data_vv15sys'].SetName(
                hists_MuNum['data_vv15sys'].GetName() + '_vv15sys')
            hists_MuDen['data_vv15sys'] = hists_MuDen['data'].Clone()
            hists_MuDen['data_vv15sys'].SetName(
                hists_MuDen['data_vv15sys'].GetName() + '_vv15sys')

            hists_EleNum['data_vv15sys'].SetTitle(
                '15% systematic on subtraction')
            hists_EleDen['data_vv15sys'].SetTitle(
                '15% systematic on subtraction')
            hists_MuNum['data_vv15sys'].SetTitle(
                '15% systematic on subtraction')
            hists_MuDen['data_vv15sys'].SetTitle(
                '15% systematic on subtraction')

            for i in ['wz', 'zz']:
                if i in hists_EleNum.keys():
                    print 'Subtracting', i
                    hists_EleNum['data'].Add(hists_EleNum[i], -1)
                    hists_EleDen['data'].Add(hists_EleDen[i], -1)
                    hists_MuNum['data'].Add(hists_MuNum[i], -1)
                    hists_MuDen['data'].Add(hists_MuDen[i], -1)

                    hists_EleNum['data_vv15sys'].Add(hists_EleNum[i],
                                                     -1 + 0.15)
                    hists_EleDen['data_vv15sys'].Add(hists_EleDen[i],
                                                     -1 + 0.15)
                    hists_MuNum['data_vv15sys'].Add(hists_MuNum[i], -1 + 0.15)
                    hists_MuDen['data_vv15sys'].Add(hists_MuDen[i], -1 + 0.15)

            hists_MuNum['data_bvvs'].Divide(hists_MuDen['data_bvvs'])
            hists_EleNum['data_bvvs'].Divide(hists_EleDen['data_bvvs'])

            hists_MuNum['data_vv15sys'].Divide(hists_MuDen['data_vv15sys'])
            hists_EleNum['data_vv15sys'].Divide(hists_EleDen['data_vv15sys'])

        hists_MuNum['data'].Divide(hists_MuDen['data'])
        hists_EleNum['data'].Divide(hists_EleDen['data'])

    f = ROOT.TFile('FakeFactors.root', 'recreate')
    f.cd()
    if 'data' in hists_EleNum.keys():
        if not options.e: hists_MuNum['data'].Write("Muons")
        if not options.mu: hists_EleNum['data'].Write("Electrons")
        if not options.e: hists_MuNum['data_vv15sys'].Write("Muons_wzsyst")
        if not options.mu:
            hists_EleNum['data_vv15sys'].Write("Electrons_wzsyst")
    f.Close()

    g = ROOT.TFile('FakeFactors_mcClosure.root', 'recreate')
    g.cd()
    if (options.region == 'zjet'):
        if not options.e: hists_MuNum['zjet'].Write('Muons')
        if not options.mu: hists_EleNum['zjet'].Write('Electrons')
    if (options.region == 'dijet'):
        if not options.e: hists_MuNum['dijet'].Write('Muons')
        if not options.mu: hists_EleNum['dijet'].Write('Electrons')
    g.Close()

    #
    # systematic band histogram
    #
    from array import array
    band = ROOT.TH1F('band', 'band', 5, array('d', [0, 15, 20, 30, 50, 100]))

    def SetSysts(h_band, systs):
        for i, sys in enumerate(systs):
            h_band.SetBinContent(i + 1, 1)
            h_band.SetBinError(i + 1, sys)

    band.SetFillColor(ROOT.kOrange - 0)
    band.SetMarkerSize(0)
    band.SetMarkerColor(ROOT.kOrange - 0)

    #
    # Muon fake factor plots
    #
    if not options.e:
        if 'zjet_sr' in hists_MuNum.keys():
            cans.append(
                plotfunc.RatioCanvas('lepPt_Mu_ff_systematic',
                                     '%s_Mu_ff_systematic' % (v), 500, 500))
        else:
            cans.append(ROOT.TCanvas('lepPt_Mu_ff', '%s_Mu_ff' % (v), 500,
                                     500))

        if 'data' in hists_EleNum.keys():

            if (options.region == 'dijet'):
                plotfunc.AddHistogram(cans[-1], hists_MuNum['data_bws'])
                plotfunc.AddHistogram(cans[-1], hists_MuNum['data_bzs'])
                if 'dijet' in hists_EleNum.keys():
                    plotfunc.AddHistogram(cans[-1], hists_MuNum['dijet'])

            if (options.region == 'zjet'):
                if not options.syst:
                    plotfunc.AddHistogram(cans[-1], hists_MuNum['data_bvvs'])
                #plotfunc.AddHistogram(cans[-1],hists_MuNum['data_vv15sys'])
                pass
            if not options.syst:
                plotfunc.AddHistogram(cans[-1], hists_MuNum['data'])

        if (options.region == 'zjet'):
            if 'zjet' in hists_MuNum.keys():
                plotfunc.AddHistogram(cans[-1], hists_MuNum['zjet'])
                if 'zjet_sr' in hists_MuNum.keys():
                    if z_w == 'zid':
                        SetSysts(band, [0.0, 0.25, 0.2, 0.25, 0.25])
                    else:
                        SetSysts(band, [0.0, 0.0, 0.2, 0.30, 0.30])
                    plotfunc.AddHistogram(cans[-1].GetPrimitive('pad_bot'),
                                          band, 'E2')
                    plotfunc.AddRatio(cans[-1], hists_MuNum['zjet_sr'],
                                      hists_MuNum['zjet'])
                    #plotfunc.AddRatio(cans[-1],hists_MuNum['ttbar_sr'],hists_MuNum['zjet'])

        if not plotfunc.CanvasEmpty(cans[-1]):
            plotfunc.FormatCanvasAxes(cans[-1])
            #taxisfunc.SetYaxisRanges(cans[-1],0,0.5)
            plotfunc.MakeLegend(cans[-1])
            additionaltext = ('supporting triggers'
                              if options.region == 'dijet' else None)
            plotfunc.FullFormatCanvasDefault(cans[-1],
                                             sqrts=13,
                                             lumi=options.fb,
                                             additionaltext=additionaltext)
            if 'zjet_sr' in hists_MuNum.keys():
                taxisfunc.SetYaxisRanges(cans[-1].GetPrimitive('pad_bot'), -1,
                                         3)
        plotfunc.SetAxisLabels(cans[-1], 'p_{T} [GeV]', 'fake factor')

    #
    # electron fake factor plots
    #
    if not options.mu:
        if 'zjet_sr' in hists_EleNum.keys():
            cans.append(
                plotfunc.RatioCanvas('lepPt_Ele_ff_systematic',
                                     '%s_Ele_ff_systematic' % (v), 500, 500))
        else:
            cans.append(
                ROOT.TCanvas('lepPt_Ele_ff', '%s_Ele_ff' % (v), 500, 500))

        if 'data' in hists_EleNum.keys():

            if (options.region == 'dijet'):
                plotfunc.AddHistogram(cans[-1], hists_EleNum['data_bws'])
                plotfunc.AddHistogram(cans[-1], hists_EleNum['data_bzs'])
                if 'dijet' in hists_EleNum.keys():
                    plotfunc.AddHistogram(cans[-1], hists_EleNum['dijet'])

            if (options.region == 'zjet'):
                if not options.syst:
                    plotfunc.AddHistogram(cans[-1], hists_EleNum['data_bvvs'])
                #plotfunc.AddHistogram(cans[-1],hists_EleNum['data_vv15sys'])

            if not options.syst:
                plotfunc.AddHistogram(cans[-1], hists_EleNum['data'])

        if (options.region == 'zjet'):
            if 'zjet' in hists_EleNum.keys():
                plotfunc.AddHistogram(cans[-1], hists_EleNum['zjet'])
                if 'zjet_sr' in hists_EleNum.keys():
                    if z_w == 'zid':
                        SetSysts(band, [0.0, 0.55, 0.30, 0.40, 0.60])
                    else:
                        SetSysts(band, [0.0, 0.0, 0.25, 0.25, 0.65])
                    plotfunc.AddHistogram(cans[-1].GetPrimitive('pad_bot'),
                                          band, 'E2')
                    plotfunc.AddRatio(cans[-1], hists_EleNum['zjet_sr'],
                                      hists_EleNum['zjet'])
                    #plotfunc.AddRatio(cans[-1],hists_EleNum['ttbar_sr'],hists_EleNum['zjet'])

        if not plotfunc.CanvasEmpty(cans[-1]):
            plotfunc.FormatCanvasAxes(cans[-1])
            #taxisfunc.SetYaxisRanges(cans[-1],0,0.5)
            plotfunc.MakeLegend(cans[-1])
            additionaltext = ('supporting triggers'
                              if options.region == 'dijet' else None)
            plotfunc.FullFormatCanvasDefault(cans[-1],
                                             sqrts=13,
                                             lumi=options.fb,
                                             additionaltext=additionaltext)
            if 'zjet_sr' in hists_EleNum.keys():
                taxisfunc.SetYaxisRanges(cans[-1].GetPrimitive('pad_bot'), -1,
                                         3)
        plotfunc.SetAxisLabels(cans[-1], 'p_{T} [GeV]', 'fake factor')

    raw_input('Pausing. Press enter to exit.')

    if options.save:
        for can in cans:
            can.Print(can.GetName() + '.pdf')
            can.Print(can.GetName() + '.eps')

    print 'done.'
    return
Ejemplo n.º 15
0
def main(options, args):

    plotfunc.SetupStyle()

    for i in options.histformat.keys():
        print '\'%s\':' % (i), options.histformat[i]

    anaplot.LoadRootCore()

    files_mc1, trees_mc1, keys_mc1, cf_mc1 = anaplot.GetTreesFromFiles(
        options.mc1)
    files_mc2, trees_mc2, keys_mc2, cf_mc2 = anaplot.GetTreesFromFiles(
        options.mc2)

    weight = 'TotalWeightNoSF'
    if ''.join(options.cuts):
        weight = weight + '*(%s)' % (' && '.join(options.cuts))
    if hasattr(options.usermodule, 'weight'):
        weight += '*(%s)' % (options.usermodule.weight)

    cans = []

    # get the histograms from the files
    for v in options.variables.split(','):
        n, low, high = options.histformat[v][:3]
        xlabel = options.histformat[v][3]

        mc_hists = []

        rebin = []
        if hasattr(options.usermodule,
                   'rebin') and v in options.usermodule.rebin.keys():
            rebin = options.usermodule.rebin[v]

        if options.mc1:
            mc_hists.append(
                anaplot.GetVariableHistsFromTrees(trees_mc1,
                                                  keys_mc1,
                                                  v,
                                                  weight,
                                                  n,
                                                  low,
                                                  high,
                                                  normalize=options.normalize,
                                                  rebin=rebin)[0])
            mc_hists[-1].SetTitle(options.label1)
            mc_hists[-1].SetLineWidth(2)
            mc_hists[-1].SetLineColor(1)
            mc_hists[-1].SetMarkerColor(1)
        if options.mc2:
            mc_hists.append(
                anaplot.GetVariableHistsFromTrees(trees_mc2,
                                                  keys_mc2,
                                                  v,
                                                  weight,
                                                  n,
                                                  low,
                                                  high,
                                                  normalize=options.normalize,
                                                  rebin=rebin)[0])
            mc_hists[-1].SetTitle(options.label2)
            mc_hists[-1].SetLineWidth(ROOT.kRed + 1)
            mc_hists[-1].SetLineColor(ROOT.kRed + 1)
            mc_hists[-1].SetMarkerColor(ROOT.kRed + 1)

        cans.append(
            anaplot.DrawHistos(v,
                               v,
                               xlabel,
                               mc_hists,
                               dostack=False,
                               log=options.log,
                               ratio=options.ratio,
                               fb=options.fb))

    if not options.batch:
        raw_input('Press enter to exit')

    if options.save:
        for can in cans:
            can.Print(can.GetName() + '.pdf')

    print 'done.'
    return