Exemplo n.º 1
0
def plot_stack(channel, name,var, bin, low, high, ylabel, xlabel, setLog = False):

    folder = 'test'
    yield_Zll = {}
    yield_dic = {}
    yield_Wln = {}
    yield_signal = {}
    stack = THStack('a', 'a')
    added = TH1D('a', 'a',bin,low,high)
    added.Sumw2()
    f  = {}
    h1 = {}

    Variables = {}    
    cut_standard= build_selection(channel,200)
    print "INFO Channel is: ", channel, " variable is: ", var, " Selection is: ", cut_standard,"\n"
    print 'INFO time is:', datetime.datetime.fromtimestamp( time.time())

    reordered_physics_processes = []
    if channel == 'Zll': reordered_physics_processes = reversed(ordered_physics_processes)
    else: reordered_physics_processes = ordered_physics_processes
 
    for Type in reordered_physics_processes:
        # Create the Histograms
        histName = Type+'_'+name+'_'+channel
        Variables[Type] = TH1F(histName, histName, bin, low, high)
        Variables[Type].Sumw2()

        print "\n"
        # this right now breaks the tchain logic! 
        # if we have more than 1 file, this will break!!!!  
        print physics_processes[Type]['files'][0]
        f[Type] = ROOT.TFile(physics_processes[Type]['files'][0],"read")
        h1[Type] = f[Type].Get("htotal")
        total =  h1[Type].GetBinContent(1)
        f[Type].Close()
        
        input_tree   = makeTrees(Type,"events",channel)
        n_entries = input_tree.GetEntries()

        #Incase you want to apply event by event re-weighting
        w = 1.0;
        # this is the scale using the total number of effective events
        scale = 1.0;
        scale = float(lumi)*physics_processes[Type]['xsec']/total
        #print "type: ", Type, "weight", w, "scale", scale, "lumi", lumi, physics_processes[Type]['xsec'], total

        if Type.startswith('QCD') or Type.startswith('Zll') or \
        Type.startswith('others') or Type.startswith('Wlv') or \
        Type.startswith('Zvv'):
            Variables[Type].SetFillColor(physics_processes[Type]['color'])
            Variables[Type].SetLineColor(physics_processes[Type]['color'])
            makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*" +str(w),"goff")
            Variables[Type].Scale(scale)
            #print "Type: ", Type, "Total Events:", scale* Variables[Type].GetEntries() , "scale", scale, "raw events", Variables[Type].GetEntries()
            stack.Add(Variables[Type],"hist")
            added.Add(Variables[Type])

        if Type.startswith('signal_higgs'):
            Variables[Type].SetLineColor(1)
            Variables[Type].SetLineWidth(3)
            Variables[Type].SetLineStyle(8)
            makeTrees(Type,"events",channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*"+str(w),"goff")
            Variables[Type].Scale(scale)
                        
        if Type.startswith("data"):
            Variables[Type].SetMarkerStyle(20)
            makeTrees(Type,"events",channel).Draw(var + " >> " + histName,  "(" + cut_standard + " && triggerFired[0]==1)*mcWeight*"+str(w), "goff")
        
        yield_dic[Type] = round(Variables[Type].Integral(),3)

    dump_datacard(channel,yield_dic)

    #added.Write()
            
    print 'INFO - Drawing the Legend', datetime.datetime.fromtimestamp( time.time())



    legend = TLegend(.60,.60,.92,.92)
    for process in  ordered_physics_processes:
        Variables[process].SetTitle(process)
        #Variables[process].Write()
        if process is not 'data' and process is not 'Zvv_ht200' and process is not 'Zvv_ht400' and process is not 'Zvv_ht600': 
            legend . AddEntry(Variables[process],physics_processes[process]['label'] , "f")
        if process is 'data':
            legend . AddEntry(Variables[process],physics_processes[process]['label'] , "p")

    c4 = TCanvas("c4","c4", 900, 1000)
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)

    stack.SetMinimum(0.1)

    if setLog:
        c4.SetLogy()
        stack.SetMaximum( stack.GetMaximum()  +  1000*stack.GetMaximum() )
    
    stack.Draw()
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetYaxis().CenterTitle()
    stack.GetXaxis().SetTitle(xlabel)
    stack.GetXaxis().SetLabelSize(0)
    stack.GetXaxis().SetTitle('')

    Variables['data'].Draw("Esame")
    Variables['signal_higgs'].Draw("same")
    
    legend.SetShadowColor(0);
    legend.SetFillColor(0);
    legend.SetLineColor(0);

    legend.Draw("same")
    plot_cms(True,lumi)

    Pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    Pad.SetTopMargin(0.7)
    Pad.SetFillColor(0)
    Pad.SetGridy(1)
    Pad.SetFillStyle(0)
    Pad.Draw()
    Pad.cd(0)
    Pad.SetRightMargin(0.06)
    
    data = Variables['data'].Clone()
    plot_ratio(False,data,added,bin,xlabel)

    f1 = TF1("f1","1",-5000,5000);
    f1.SetLineColor(4);
    f1.SetLineStyle(2);
    f1.SetLineWidth(2);
    f1.Draw("same")

    c4.SaveAs(folder+'/Histo_' + name + '_'+channel+'.pdf')

    del Variables
    del var
    del f
    del h1
    c4.IsA().Destructor( c4 )
    stack.IsA().Destructor( stack )
Exemplo n.º 2
0
def plot_stack(channel,
               name,
               var,
               bin,
               low,
               high,
               ylabel,
               xlabel,
               setLog=False):

    yield_dic = {}

    stack = THStack('a', 'a')
    if var is 'met':
        binLowE = [200, 250, 300, 350, 400, 500, 600, 1000]
        #        binLowE = [250,300,350,400,500,600,1000]
        added = TH1D('added', 'added', len(binLowE) - 1, array('d', binLowE))
    else:
        added = TH1D('added', 'added', bin, low, high)
    added.Sumw2()
    f = {}
    h1 = {}

    Variables = {}
    cut_standard = build_selection(channel, metcut)

    if var is 'met':
        if channel is not 'signal':
            xlabel = 'U [GeV]'

    print "INFO Channel is: ", channel, " variable is: ", var, " Selection is: ", cut_standard, "\n"
    print 'INFO time is:', datetime.datetime.fromtimestamp(time.time())

    reordered_physics_processes = []
    if channel == 'Zmm' or channel == 'Zee':
        reordered_physics_processes = reversed(ordered_physics_processes)
    else:
        reordered_physics_processes = ordered_physics_processes
    #reordered_physics_processes = ordered_physics_processes

    for Type in ordered_physics_processes:
        yield_dic[physics_processes[Type]['datacard']] = 0

    for Type in reordered_physics_processes:
        # Create the Histograms
        histName = Type + '_' + name + '_' + channel

        if var is 'met':
            #binLowE = [200,250,300,350,400,500,600,900,1500]
            binLowE = [200, 250, 300, 350, 400, 500, 600, 1000]
            #            binLowE = [250,300,350,400,500,600,1000]
            Variables[Type] = TH1F(histName, histName,
                                   len(binLowE) - 1, array('d', binLowE))
        else:
            Variables[Type] = TH1F(histName, histName, bin, low, high)

        Variables[Type].Sumw2()
        #print "\n"

        # this right now breaks the tchain logic!
        # if we have more than 1 file, this will break!!!!

        if Type is not 'data':
            f[Type] = ROOT.TFile(physics_processes[Type]['files'][0], "read")
            h1[Type] = f[Type].Get("htotal")
            total = h1[Type].GetBinContent(1)
            #total = h1[Type].GetEntries()
            f[Type].Close()
        else:
            total = 1.0

        input_tree = makeTrees(Type, "events", channel)
        n_entries = input_tree.GetEntries()

        #Incase you want to apply event by event re-weighting

        w = "((0.0*(npv>-0.5&&npv<=0.5)+3.30418257204*(npv>0.5&&npv<=1.5)+2.59691269521*(npv>1.5&&npv<=2.5)+2.44251087681*(npv>2.5&&npv<=3.5)+2.42846225153*(npv>3.5&&npv<=4.5)+2.40062512591*(npv>4.5&&npv<=5.5)+2.30279811595*(npv>5.5&&npv<=6.5)+2.12054720297*(npv>6.5&&npv<=7.5)+1.9104708827*(npv>7.5&&npv<=8.5)+1.67904936047*(npv>8.5&&npv<=9.5)+1.43348925382*(npv>9.5&&npv<=10.5)+1.17893952713*(npv>10.5&&npv<=11.5)+0.940505177881*(npv>11.5&&npv<=12.5)+0.740901867872*(npv>12.5&&npv<=13.5)+0.56877478036*(npv>13.5&&npv<=14.5)+0.433148655714*(npv>14.5&&npv<=15.5)+0.325343558476*(npv>15.5&&npv<=16.5)+0.241688459349*(npv>16.5&&npv<=17.5)+0.180491032782*(npv>17.5&&npv<=18.5)+0.136993937378*(npv>18.5&&npv<=19.5)+0.104859480066*(npv>19.5&&npv<=20.5)+0.0768271030309*(npv>20.5&&npv<=21.5)+0.0563426184938*(npv>21.5&&npv<=22.5)+0.0454037058117*(npv>22.5&&npv<=23.5)+0.0359945616383*(npv>23.5&&npv<=24.5)+0.0286879205085*(npv>24.5&&npv<=25.5)+0.0208185595478*(npv>25.5&&npv<=26.5)+0.0170977379612*(npv>26.5&&npv<=27.5)+0.0122446391898*(npv>27.5&&npv<=28.5)+0.0148028308301*(npv>28.5&&npv<=29.5)+0.0120527550003*(npv>29.5&&npv<=30.5)+0.00402643194054*(npv>30.5&&npv<=31.5)+0.00981143754301*(npv>31.5&&npv<=32.5)+0.0*(npv>32.5&&npv<=33.5)+0.0155664899019*(npv>33.5&&npv<=34.5)+0.0*(npv>34.5&&npv<=35.5)+0.0*(npv>35.5&&npv<=36.5)+0.0*(npv>36.5&&npv<=37.5)+0.0*(npv>37.5&&npv<=38.5)+0.0*(npv>38.5&&npv<=39.5)))"

        if channel is 'signal' or channel is 'Zmm' or channel is 'Wmn':
            w_trig = '((met < 250)*0.97 + (met >=250 && met<350)* 0.987 + (met>=350)* 1.0 )'
        else:
            w_trig = '(1.0)'

        anlo1_over_alo = "(1.24087232993*(genBos_pt>100.0&&genBos_pt<=150.0)+1.55807026252*(genBos_pt>150.0&&genBos_pt<=200.0)+1.51043242876*(genBos_pt>200.0&&genBos_pt<=250.0)+1.47333461572*(genBos_pt>250.0&&genBos_pt<=300.0)+1.43497331471*(genBos_pt>300.0&&genBos_pt<=350.0)+1.37846354687*(genBos_pt>350.0&&genBos_pt<=400.0)+1.2920177717*(genBos_pt>400.0&&genBos_pt<=500.0)+1.31414429236*(genBos_pt>500.0&&genBos_pt<=600.0)+1.20453974747*(genBos_pt>600.0))"
        a_ewkcorr = "(0.998568444581*(genBos_pt>100.0&&genBos_pt<=150.0)+0.992098286517*(genBos_pt>150.0&&genBos_pt<=200.0)+0.986010290609*(genBos_pt>200.0&&genBos_pt<=250.0)+0.980265498435*(genBos_pt>250.0&&genBos_pt<=300.0)+0.974830448283*(genBos_pt>300.0&&genBos_pt<=350.0)+0.969676202351*(genBos_pt>350.0&&genBos_pt<=400.0)+0.962417128177*(genBos_pt>400.0&&genBos_pt<=500.0)+0.953511139209*(genBos_pt>500.0&&genBos_pt<=600.0)+0.934331895615*(genBos_pt>600.0))"

        w_ewkcorr = "(0.980859240872*(genBos_pt>100.0&&genBos_pt<=150.0)+0.962118764182*(genBos_pt>150.0&&genBos_pt<=200.0)+0.944428528597*(genBos_pt>200.0&&genBos_pt<=250.0)+0.927685912907*(genBos_pt>250.0&&genBos_pt<=300.0)+0.911802238928*(genBos_pt>300.0&&genBos_pt<=350.0)+0.896700388113*(genBos_pt>350.0&&genBos_pt<=400.0)+0.875368225896*(genBos_pt>400.0&&genBos_pt<=500.0)+0.849096933047*(genBos_pt>500.0&&genBos_pt<=600.0)+0.792158791839*(genBos_pt>600.0))"
        wnlo012_over_wlo = "(1.89123123702*(genBos_pt>100.0&&genBos_pt<=150.0)+1.70414182145*(genBos_pt>150.0&&genBos_pt<=200.0)+1.60726459197*(genBos_pt>200.0&&genBos_pt<=250.0)+1.57205818769*(genBos_pt>250.0&&genBos_pt<=300.0)+1.51688539716*(genBos_pt>300.0&&genBos_pt<=350.0)+1.41090079307*(genBos_pt>350.0&&genBos_pt<=400.0)+1.30757555038*(genBos_pt>400.0&&genBos_pt<=500.0)+1.32046236765*(genBos_pt>500.0&&genBos_pt<=600.0)+1.26852513234*(genBos_pt>600.0))"

        z_ewkcorr = "(0.984525344338*(genBos_pt>100.0&&genBos_pt<=150.0)+0.969078612189*(genBos_pt>150.0&&genBos_pt<=200.0)+0.954626582726*(genBos_pt>200.0&&genBos_pt<=250.0)+0.941059330021*(genBos_pt>250.0&&genBos_pt<=300.0)+0.92828367065*(genBos_pt>300.0&&genBos_pt<=350.0)+0.916219976557*(genBos_pt>350.0&&genBos_pt<=400.0)+0.89931198024*(genBos_pt>400.0&&genBos_pt<=500.0)+0.878692669663*(genBos_pt>500.0&&genBos_pt<=600.0)+0.834717745177*(genBos_pt>600.0))"
        znlo012_over_zlo = "(1.68500099066*(genBos_pt>100.0&&genBos_pt<=150.0)+1.55256109189*(genBos_pt>150.0&&genBos_pt<=200.0)+1.52259467479*(genBos_pt>200.0&&genBos_pt<=250.0)+1.52062313572*(genBos_pt>250.0&&genBos_pt<=300.0)+1.4322825541*(genBos_pt>300.0&&genBos_pt<=350.0)+1.45741443405*(genBos_pt>350.0&&genBos_pt<=400.0)+1.36849777989*(genBos_pt>400.0&&genBos_pt<=500.0)+1.3580214432*(genBos_pt>500.0&&genBos_pt<=600.0)+1.16484769869*(genBos_pt>600.0))"

        wm_postfit = "(1.0)"
        zm_postfit = "(1.0)"
        g_postfit = "(1.0)"

        # this is the scale using the total number of effective events
        scale = 1.0
        scale = float(lumi) * physics_processes[Type]['xsec'] / total

        #print '\n'
        #        print "type: ", Type,  "scale", scale, "lumi", lumi, physics_processes[Type]['xsec'], total

        if Type is not 'data' and Type is not 'signal_dm' and Type is not 'signal_dm_s' and Type is not 'signal_dm_ps' and Type is not 'signal_dm_v' and Type is not 'signal_dm_av_1_2':
            Variables[Type].SetFillColor(physics_processes[Type]['color'])
            Variables[Type].SetLineColor(physics_processes[Type]['color'])

            if Type.startswith('GJets'):
                makeTrees(Type, 'events', channel).Draw(
                    var + " >> " + histName,
                    "(" + cut_standard + ")*mcWeight*0.98*" + str(g_postfit) +
                    "*" + str(anlo1_over_alo) + "*" + str(a_ewkcorr) + "*" +
                    str(w) + "*" + str(w_trig), "goff")

            elif (Type.startswith('Zvv') or Type.startswith('Zll')):
                if channel is 'signal':
                    makeTrees(Type, 'events', channel).Draw(
                        var + " >> " + histName,
                        "(" + cut_standard + ")*mcWeight*" + str(zm_postfit) +
                        "*" + str(z_ewkcorr) + "*" + str(znlo012_over_zlo) +
                        "*" + str(w) + "*" + str(w_trig), "goff")
                else:
                    #SF explicitly written for the leading tight lepton from the root files
                    makeTrees(Type, 'events', channel).Draw(
                        var + " >> " + histName, "(" + cut_standard +
                        ")*mcWeight*(0.98 *(lep1Eta<2.1)+0.91*(lep1Eta>=2.1))*"
                        + str(zm_postfit) + "*" + str(z_ewkcorr) + "*" +
                        str(znlo012_over_zlo) + "*" + str(w) + "*" +
                        str(w_trig), "goff")

            elif Type.startswith('Wlv'):
                if channel is 'signal':
                    makeTrees(Type, 'events', channel).Draw(
                        var + " >> " + histName,
                        "(" + cut_standard + ")*mcWeight*" + str(wm_postfit) +
                        "*" + str(wnlo012_over_wlo) + "*" + str(w_ewkcorr) +
                        "*" + str(w) + "*" + str(w_trig), "goff")
                else:
                    makeTrees(Type, 'events', channel).Draw(
                        var + " >> " + histName,
                        "(" + cut_standard + ")*mcWeight*" + str(wm_postfit) +
                        "*" + str(wnlo012_over_wlo) + "*" + str(w_ewkcorr) +
                        "*" + str(w) + "*" + str(w_trig), "goff")

            else:
                makeTrees(Type, 'events', channel).Draw(
                    var + " >> " + histName, "(" + cut_standard +
                    ") *mcWeight*" + str(w) + "*" + str(w_trig), "goff")

            Variables[Type].Scale(scale, "width")
            stack.Add(Variables[Type], "hist")
            added.Add(Variables[Type])

        if Type.startswith('signal_h_ggf'):
            Variables[Type].SetLineColor(1)
            Variables[Type].SetLineWidth(3)
            Variables[Type].SetLineStyle(1)
            makeTrees(Type, "events", channel).Draw(
                var + " >> " + histName,
                "(" + cut_standard + ")*mcWeight*" + str(w), "goff")
            Variables[Type].Scale(scale, "width")

        if Type.startswith('signal_dm_av_1_2'):
            Variables[Type].SetLineColor(1)
            Variables[Type].SetLineWidth(3)
            Variables[Type].SetLineStyle(8)
            makeTrees(Type, "events", channel).Draw(
                var + " >> " + histName,
                "(" + cut_standard + ")*mcWeight*" + str(w), "goff")
            Variables[Type].Scale(scale, "width")

        if Type.startswith('data'):
            Variables[Type].SetMarkerStyle(20)
            if channel is 'signal' or channel is 'Zmm' or channel is 'Wmn':
                makeTrees(Type, "events", channel).Draw(
                    var + " >> " + histName, "(" + cut_standard +
                    " && (triggerFired[0]==1 || triggerFired[1]==1 || triggerFired[2]==1) )",
                    "goff")
            else:
                makeTrees(Type, "events",
                          channel).Draw(var + " >> " + histName,
                                        "(" + cut_standard + " )", "goff")
            Variables[Type].Scale(1, "width")

        yield_dic[physics_processes[Type]['datacard']] += round(
            Variables[Type].Integral("width"), 3)

    dump_datacard(channel, yield_dic)

    #added.Write()

    print 'INFO - Drawing the Legend', datetime.datetime.fromtimestamp(
        time.time())

    #    if channel is 'Zmm' or channel is 'Zee':
    #        legend = TLegend(.60,.65,.92,.92)
    #    elif channel is 'gjets':
    #        legend = TLegend(.60,.65,.82,.92)
    #    else:
    #        legend = TLegend(.60,.60,.92,.92)

    legend = TLegend(.60, .70, .92, .92)

    lastAdded = ''
    for process in ordered_physics_processes:
        #print process
        Variables[process].SetTitle(process)
        if physics_processes[process]['label'] != lastAdded:
            lastAdded = physics_processes[process]['label']
            if process is not 'data' and process is not 'signal_dm' and process is not 'signal_dm_av_1_2' and process is not 'signal_h_ggf' and process is not 'signal_h_vbf':
                legend.AddEntry(Variables[process],
                                physics_processes[process]['label'], "f")
            if process is 'data':
                legend.AddEntry(Variables[process],
                                physics_processes[process]['label'], "p")

    c4 = TCanvas("c4", "c4", 900, 1000)
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)

    stack.SetMinimum(0.01)
    #stack.SetMinimum(10)

    if setLog:
        c4.SetLogy()
        if var is 'fatjet1tau21' or var is 'fatjet1PrunedM':
            stack.SetMaximum(stack.GetMaximum() + 1e5 * stack.GetMaximum())
        else:
            stack.SetMaximum(stack.GetMaximum() + 1e2 * stack.GetMaximum())
    else:
        stack.SetMaximum(stack.GetMaximum() + 0.5 * stack.GetMaximum())

    stack.Draw()
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetYaxis().CenterTitle()
    stack.GetYaxis().SetTitleOffset(1.2)
    stack.GetXaxis().SetTitle(xlabel)
    stack.GetXaxis().SetLabelSize(0)
    stack.GetXaxis().SetTitle('')

    Variables['data'].Draw("Esame")

    legend.SetShadowColor(0)
    legend.SetFillColor(0)
    legend.SetLineColor(0)

    legend.Draw("same")
    plot_cms(True, lumi_str)

    Pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    Pad.SetTopMargin(0.7)
    Pad.SetFillColor(0)
    Pad.SetGridy(1)
    Pad.SetFillStyle(0)
    Pad.Draw()
    Pad.cd(0)
    Pad.SetRightMargin(0.06)

    data = Variables['data'].Clone()

    plot_ratio(False, data, added, bin, xlabel, 0, 2.0, 5)

    f1 = TF1("f1", "1", -5000, 5000)
    f1.SetLineColor(4)
    f1.SetLineStyle(2)
    f1.SetLineWidth(2)
    f1.Draw("same")

    outputName = folder + '/mj_Histo_' + name + '_' + channel
    c4.SaveAs(outputName + '.pdf')
    c4.SaveAs(outputName + '.png')
    c4.SaveAs(outputName + '.C')

    del Variables
    del var
    del f
    del h1
    c4.IsA().Destructor(c4)
    stack.IsA().Destructor(stack)
Exemplo n.º 3
0
def plot_stack(channel, name,var, bin, low, high, ylabel, xlabel, setLog = False):

    folder = '/afs/cern.ch/user/z/zdemirag/www/Monojet/frozen/'
    if not os.path.exists(folder):
        os.mkdir(folder)

    yield_dic = {}

    stack = THStack('a', 'a')
    added = TH1D('a', 'a',bin,low,high)
    added.Sumw2()
    f  = {}
    h1 = {}

    Variables = {}    
    #cut_standard= build_selection(channel,0) ### Fix this back to 200 ###
    cut_standard= build_selection(channel,200) ### Fix this back to 200 ###

    if var is 'met':
        if channel is not 'signal': 
            xlabel = 'U [GeV]'

    print "INFO Channel is: ", channel, " variable is: ", var, " Selection is: ", cut_standard,"\n"
    print 'INFO time is:', datetime.datetime.fromtimestamp( time.time())

    reordered_physics_processes = []
    if channel == 'Zmm' or channel == 'Zee': 
        reordered_physics_processes = reversed(ordered_physics_processes)
    else: 
        reordered_physics_processes = ordered_physics_processes
    #reordered_physics_processes = ordered_physics_processes

    for Type in ordered_physics_processes:
        yield_dic[physics_processes[Type]['datacard']] = 0
 
    for Type in reordered_physics_processes:
        # Create the Histograms
        histName = Type+'_'+name+'_'+channel

        if var is 'met':
            binLowE = [200,250,300,350,400,500,600,1000]
            Variables[Type] = TH1F(histName,histName,7,array('d',binLowE))
            Variables[Type].Scale(1,"width");
        else:
            Variables[Type] = TH1F(histName, histName, bin, low, high)

        Variables[Type].Sumw2()
        #print "\n"

        # this right now breaks the tchain logic! 
        # if we have more than 1 file, this will break!!!!  
        #print physics_processes[Type]['files'][0]
        f[Type] = ROOT.TFile(physics_processes[Type]['files'][0],"read")
        h1[Type] = f[Type].Get("htotal")
        total = h1[Type].GetBinContent(1)
        f[Type].Close()
        
        input_tree   = makeTrees(Type,"events",channel)
        n_entries = input_tree.GetEntries()

        #Incase you want to apply event by event re-weighting
        #w = 1.0;
        w = '(3.57041 + -1.49846*npv + 0.515829*npv*npv + -0.0839209*npv*npv*npv + 0.00719964*npv*npv*npv*npv + -0.000354548*npv*npv*npv*npv*npv + 1.01544e-05*npv*npv*npv*npv*npv*npv + -1.58019e-07*npv*npv*npv*npv*npv*npv*npv + 1.03663e-09*npv*npv*npv*npv*npv*npv*npv*npv)'

        # this is the scale using the total number of effective events
        scale = 1.0;
        scale = float(lumi)*physics_processes[Type]['xsec']/total
        
        #print '\n'
        print "type: ", Type,  "scale", scale, "lumi", lumi, physics_processes[Type]['xsec'], total

        if(shapelimits is True):
            # WRITING OUT A TREE
            file_out = ROOT.TFile("monojet_"+channel+".root", "update")
            if Type is 'data':
                selectedTree = input_tree.CopyTree( cut_standard );
            else:
                selectedTree = input_tree.CopyTree( cut_standard );

            scale_w = n.zeros(1,dtype=float)
            selectedTree.Branch('scale_w',scale_w,'scale_w/D')
            
            for i in range(selectedTree.GetEntries()):
                selectedTree.GetEntry(i)
                if Type is 'data':
                    scale_w[0] = 1.0
                else:
                    scale_w[0] = scale
                    
            selectedTree.Fill()
            selectedTree.Write(Type+"_"+channel)        
            file_out.Close()

            os.system('root -l -q -b "addMCWeight.C(\\"monojet_'+channel+'.root\\",\\"'+Type+'_'+channel+'\\")"')

        if Type is not 'data' and Type is not 'signal_dm':
            Variables[Type].SetFillColor(physics_processes[Type]['color'])
            Variables[Type].SetLineColor(physics_processes[Type]['color'])
            if Type.startswith('GJets'):
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*kfactor*" +str(w),"goff")            
            else:
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*" +str(w),"goff")
            Variables[Type].Scale(scale)
            stack.Add(Variables[Type],"hist")
            added.Add(Variables[Type])

        if Type.startswith('signal_dm'):
            Variables[Type].SetLineColor(1)
            Variables[Type].SetLineWidth(3)
            Variables[Type].SetLineStyle(8)
            makeTrees(Type,"events",channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*"+str(w),"goff")
            Variables[Type].Scale(scale)
            
        if Type.startswith('data'):
            Variables[Type].SetMarkerStyle(20)
            if channel is 'signal':
                makeTrees(Type,"events",channel).Draw(var + " >> " + histName, "(" + cut_standard + "&& (triggerFired[1]==1 || triggerFired[0]==1 || triggerFired[2]==1 ))", "goff")
            else:
                makeTrees(Type,"events",channel).Draw(var + " >> " + histName, "(" + cut_standard + ")", "goff")

        yield_dic[physics_processes[Type]['datacard']] += round(Variables[Type].Integral(),3)
        #print Type, round(Variables[Type].Integral(),3), "total in: ", physics_processes[Type]['datacard'],  yield_dic[physics_processes[Type]['datacard']]

    dump_datacard(channel,yield_dic)

    #added.Write()
            
    print 'INFO - Drawing the Legend', datetime.datetime.fromtimestamp( time.time())

    legend = TLegend(.60,.60,.92,.92)
    lastAdded = ''
    for process in  ordered_physics_processes:
        #print process
        Variables[process].SetTitle(process)
        if physics_processes[process]['label'] != lastAdded:
            lastAdded = physics_processes[process]['label']
            if process is not 'data' and process is not 'signal_dm': 
                legend . AddEntry(Variables[process],physics_processes[process]['label'] , "f")
            if process is 'data':
                legend . AddEntry(Variables[process],physics_processes[process]['label'] , "p")
            if process is 'signal_dm':
                legend . AddEntry(Variables[process],physics_processes[process]['label'] , "l")


    c4 = TCanvas("c4","c4", 900, 1000)
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)

    stack.SetMinimum(0.1)

    if setLog:
        c4.SetLogy()
        stack.SetMaximum( stack.GetMaximum()  +  1000*stack.GetMaximum() )
    else:
        stack.SetMaximum( stack.GetMaximum()  +  stack.GetMaximum() )
    
    stack.Draw()
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetYaxis().CenterTitle()
    stack.GetXaxis().SetTitle(xlabel)
    stack.GetXaxis().SetLabelSize(0)
    stack.GetXaxis().SetTitle('')

    Variables['data'].Draw("Esame")
    Variables['signal_dm'].Draw("same")
    
    legend.SetShadowColor(0);
    legend.SetFillColor(0);
    legend.SetLineColor(0);

    legend.Draw("same")
    plot_cms(True,lumi)

    Pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    Pad.SetTopMargin(0.7)
    Pad.SetFillColor(0)
    Pad.SetGridy(1)
    Pad.SetFillStyle(0)
    Pad.Draw()
    Pad.cd(0)
    Pad.SetRightMargin(0.06)
    
    data = Variables['data'].Clone()
    plot_ratio(False,data,added,bin,xlabel)

    f1 = TF1("f1","1",-5000,5000);
    f1.SetLineColor(4);
    f1.SetLineStyle(2);
    f1.SetLineWidth(2);
    f1.Draw("same")

    c4.SaveAs(folder+'/'+channel+'/Histo_' + name + '_'+channel+'.pdf')
    c4.SaveAs(folder+'/'+channel+'/Histo_' + name + '_'+channel+'.png')
    c4.SaveAs(folder+'/'+channel+'/Histo_' + name + '_'+channel+'.C')

    del Variables
    del var
    del f
    del h1
    c4.IsA().Destructor( c4 )
    stack.IsA().Destructor( stack )
Exemplo n.º 4
0
def plot_stack(channel,
               name,
               var,
               bin,
               low,
               high,
               ylabel,
               xlabel,
               setLog=False):

    folder = '/afs/cern.ch/user/z/zdemirag/www/monojet/panda/v1'

    if not os.path.exists(folder):
        os.mkdir(folder)

    yield_dic = {}

    stack = THStack('a', 'a')
    if var.startswith('pfmet') or var.startswith('pfU'):
        binLowE = [
            250.0, 280.0, 310.0, 340.0, 370.0, 400.0, 430.0, 470.0, 510.0,
            550.0, 590.0, 640.0, 690.0, 740.0, 790.0, 840.0, 900.0, 960.0,
            1020.0, 1090.0, 1160.0, 1250.0, 1400.0
        ]
        nb = len(binLowE) - 1
        added = TH1D('added', 'added', nb, array('d', binLowE))
    else:
        added = TH1D('added', 'added', bin, low, high)

    added.Sumw2()

    f = {}
    h1 = {}

    Variables = {}
    cut_standard = build_selection(channel)

    if var.startswith('pfU'):
        if channel is not 'signal':
            xlabel = 'Hadronic Recoil p_{T} [GeV]'

    print "INFO Channel is: ", channel, " variable is: ", var, " Selection is: ", cut_standard, "\n"
    print 'INFO time is:', datetime.datetime.fromtimestamp(time.time())

    reordered_physics_processes = []
    if channel == 'Zmm' or channel == 'Zee':
        reordered_physics_processes = reversed(ordered_physics_processes)
    else:
        reordered_physics_processes = ordered_physics_processes

    for Type in ordered_physics_processes:
        yield_dic[physics_processes[Type]['datacard']] = 0

    for Type in reordered_physics_processes:
        histName = Type + '_' + name + '_' + channel

        if var.startswith('pfmet') or var.startswith('pfU'):
            binLowE = [
                250.0, 280.0, 310.0, 340.0, 370.0, 400.0, 430.0, 470.0, 510.0,
                550.0, 590.0, 640.0, 690.0, 740.0, 790.0, 840.0, 900.0, 960.0,
                1020.0, 1090.0, 1160.0, 1250.0, 1400.0
            ]
            n2 = len(binLowE) - 1
            Variables[Type] = TH1F(histName, histName, n2, array('d', binLowE))
        else:
            Variables[Type] = TH1F(histName, histName, bin, low, high)

        Variables[Type].Sumw2()
        Variables[Type].StatOverflows(kTRUE)

        input_tree = makeTrees(Type, "events", channel)
        n_entries = input_tree.GetEntries()

        scale = float(lumi)  # *physics_processes[Type]['xsec']/total

        common_weight = build_weights(channel, Type)

        print Type, common_weight, scale

        #if Type is not 'data' and Type is not 'signal_ggf' and Type is not 'signal_vbf':
        if Type is not 'data' and Type is not 'signal_ggf':

            Variables[Type].SetFillColor(
                TColor.GetColor(physics_processes[Type]['color']))
            Variables[Type].SetLineColor(1)

            makeTrees(Type, 'events',
                      channel).Draw(var + " >> " + histName,
                                    "(" + cut_standard + " )" + common_weight,
                                    "goff")

            if var == "pfmet" or var.startswith('pfU'):
                nbins = Variables[Type].GetNbinsX()
                Variables[Type].SetBinContent(
                    Variables[Type].GetNbinsX(),
                    Variables[Type].GetBinContent(nbins) +
                    Variables[Type].GetBinContent(nbins + 1))

            Variables[Type].Scale(scale, "width")
            stack.Add(Variables[Type], "hist")
            added.Add(Variables[Type])

        if Type.startswith('signal'):
            makeTrees(Type, 'events',
                      channel).Draw(var + " >> " + histName,
                                    "(" + cut_standard + ")" + common_weight,
                                    "goff")
            if var == "pfmet" or var.startswith('pfU'):
                nbins = Variables[Type].GetNbinsX()
                Variables[Type].SetBinContent(
                    Variables[Type].GetNbinsX(),
                    Variables[Type].GetBinContent(nbins) +
                    Variables[Type].GetBinContent(nbins + 1))
            Variables[Type].Scale(scale, "width")

        if Type.startswith('data'):
            Variables[Type].SetMarkerStyle(20)
            if channel in 'signal' or channel in 'Zmm' or channel in 'Wmn':
                #met trigger
                #makeTrees(Type,"events",channel).Draw(var + " >> " + histName, "(" + cut_standard + "&& (trigger&1)!=0)", "goff")
                makeTrees(Type, "events",
                          channel).Draw(var + " >> " + histName, cut_standard,
                                        "goff")
            elif channel in 'GJets':
                #photon trigger - no need, the flag is not working properly
                makeTrees(Type, "events",
                          channel).Draw(var + " >> " + histName, cut_standard,
                                        "goff")
            else:
                #ele trigger
                makeTrees(Type, "events", channel).Draw(
                    var + " >> " + histName,
                    "(" + cut_standard + "&& (trigger&2)!=0)", "goff")

            if var == "pfmet" or var.startswith('pfU'):
                nbins = Variables[Type].GetNbinsX()
                Variables[Type].SetBinContent(
                    Variables[Type].GetNbinsX(),
                    Variables[Type].GetBinContent(nbins) +
                    Variables[Type].GetBinContent(nbins + 1))
            Variables[Type].Scale(1, "width")

        yield_dic[physics_processes[Type]['datacard']] += round(
            Variables[Type].Integral("width"), 3)

    dump_datacard(channel, yield_dic)

    print 'INFO - Drawing the Legend', datetime.datetime.fromtimestamp(
        time.time())

    if channel is 'GJets':
        legend = TLegend(.60, .65, .82, .92)
    else:
        legend = TLegend(.60, .55, .92, .92)

    lastAdded = ''
    for process in ordered_physics_processes:
        Variables[process].SetTitle(process)
        if physics_processes[process]['label'] != lastAdded:
            lastAdded = physics_processes[process]['label']
            #if process is not 'data' and process is not 'signal_vbf' and process is not 'signal_ggf':
            if process is not 'data' and process is not 'signal_ggf':
                legend.AddEntry(Variables[process],
                                physics_processes[process]['label'], "f")
            if process is 'data':
                legend.AddEntry(Variables[process],
                                physics_processes[process]['label'], "p")

    c4 = TCanvas("c4", "c4", 600, 700)
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)
    stack.SetMinimum(0.01)

    if setLog:
        c4.SetLogy()
        if "eta" in var:
            stack.SetMaximum(Variables['data'].GetMaximum() +
                             1e8 * Variables['data'].GetMaximum())
        else:
            stack.SetMaximum(Variables['data'].GetMaximum() +
                             1e2 * Variables['data'].GetMaximum())

    else:
        stack.SetMaximum(Variables['data'].GetMaximum() +
                         0.5 * Variables['data'].GetMaximum())

    stack.Draw()
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetYaxis().CenterTitle()
    stack.GetYaxis().SetTitleOffset(1.2)
    stack.GetXaxis().SetTitleOffset(1.2)
    stack.GetXaxis().SetTitle(xlabel)
    stack.GetXaxis().SetLabelSize(0)
    stack.GetXaxis().SetTitle('')

    if channel is 'signal' and blind:
        for b in range(Variables['data'].GetNbinsX()):
            Variables['data'].SetBinContent(b + 1, 0.0)

    Variables['data'].Draw("Esame")
    #Variables['signal_vbf'].SetLineWidth(2)
    Variables['signal_ggf'].SetLineWidth(2)
    #Variables['signal_vbf'].SetLineColor(1)
    Variables['signal_ggf'].SetLineColor(4)
    #Variables['signal_vbf'].Draw("samehist")
    #Variables['signal_ggf'].Draw("samehist")

    #legend . AddEntry(Variables['signal_vbf'],physics_processes['signal_vbf']['label'] , "l")
    #legend . AddEntry(Variables['signal_ggf'],physics_processes['signal_ggf']['label'] , "l")

    legend.SetShadowColor(0)
    legend.SetFillColor(0)
    legend.SetLineColor(0)

    legend.Draw("same")
    plot_cms(True, lumi_str, c4)

    Pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 0.9)
    Pad.SetTopMargin(0.7)
    Pad.SetRightMargin(0.06)
    Pad.SetFillColor(0)
    Pad.SetGridy(1)
    Pad.SetFillStyle(0)
    Pad.Draw()
    Pad.cd(0)

    data = Variables['data'].Clone()

    plot_ratio(False, data, added, bin, xlabel, 0.5, 1.5, 5)

    f1 = TF1("f1", "1", -5000, 5000)
    f1.SetLineColor(4)
    f1.SetLineStyle(2)
    f1.SetLineWidth(2)
    f1.Draw("same")

    Pad.Update()
    Pad.RedrawAxis()

    c4.SaveAs(folder + '/Histo_' + category + '_' + name + '_' + channel +
              '.pdf')
    c4.SaveAs(folder + '/Histo_' + category + '_' + name + '_' + channel +
              '.png')
    c4.SaveAs(folder + '/Histo_' + category + '_' + name + '_' + channel +
              '.C')

    del Variables
    del var
    del f
    del h1
    c4.IsA().Destructor(c4)
    stack.IsA().Destructor(stack)
Exemplo n.º 5
0
def plot_stack(channel, name,var, bin, low, high, ylabel, xlabel, setLog = False):

    folder = '/afs/cern.ch/user/d/dabercro/www/plots/' + os.environ.get('CROMBIEDATE') + '_monojet/'
    if not os.path.exists(folder):
        os.mkdir(folder)

    yield_dic = {}    

    stack = THStack('a', 'a')
    if var.startswith('met'):
        if vtag or vbf:
            binLowE = [250,300,350,400,500,600,750,1000]
        else:
            binLowE = [200., 230., 260.0, 290.0, 320.0, 350.0, 390.0, 430.0, 470.0, 510.0, 550.0, 590.0, 640.0, 690.0, 740.0, 790.0, 840.0, 900.0, 960.0, 1020.0, 1090.0, 1160.0, 1250.0]

            
        nb = len(binLowE)-1
        added = TH1D('added','added',nb,array('d',binLowE))
    else:
        added = TH1D('added', 'added',bin,low,high)

    added.Sumw2()

    f  = {}
    h1 = {}

    Variables = {}
    cut_standard= build_selection(channel,metcut)

    if var.startswith('met'):
        if channel is not 'signal': 
            xlabel = 'U [GeV]'

    print "INFO Channel is: ", channel, " variable is: ", var, " Selection is: ", cut_standard,"\n"
    print 'INFO time is:', datetime.datetime.fromtimestamp( time.time())

    reordered_physics_processes = []
    if channel == 'Zmm' or channel == 'Zee': 
        reordered_physics_processes = reversed(ordered_physics_processes)
    else: 
        reordered_physics_processes = ordered_physics_processes

    for Type in ordered_physics_processes:
        yield_dic[physics_processes[Type]['datacard']] = 0

    for Type in reordered_physics_processes:
        if not vbf:
            if Type.startswith('EWK') :
                continue
            #Create the Histograms
        histName = Type+'_'+name+'_'+channel

        if var.startswith('met'):
            if vtag or vbf :
                binLowE = [250,300,350,400,500,600,750,1000]
            else:
                binLowE = [200., 230., 260.0, 290.0, 320.0, 350.0, 390.0, 430.0, 470.0, 510.0, 550.0, 590.0, 640.0, 690.0, 740.0, 790.0, 840.0, 900.0, 960.0, 1020.0, 1090.0, 1160.0, 1250.0]            

            n2 = len(binLowE)-1
            Variables[Type] = TH1F(histName,histName,n2,array('d',binLowE))
        else:
            Variables[Type] = TH1F(histName, histName, bin, low, high)

        Variables[Type].Sumw2()
        Variables[Type].StatOverflows(kTRUE)

        if Type is not 'data':
            f[Type] = ROOT.TFile(physics_processes[Type]['files'][0],"read")
            h1[Type] = f[Type].Get("htotal")
            total = h1[Type].GetBinContent(1)
            f[Type].Close()
        else:
            total = 1.0

        input_tree   = makeTrees(Type,"events",channel)
        n_entries = input_tree.GetEntries()

        w_trig = '(1.0)'

        # this is the scale using the total number of effective events
        scale = 1.0;
        scale = float(lumi)*physics_processes[Type]['xsec']/total

        #print Type, scale, total

        ##Common weights used for the analysis        
        triggercut = "(1.0)"

        if channel is 'signal':
            if Type is 'data':
                common_weight = "*(1.0)"
                triggercut = "(triggerFired[10]==1 || triggerFired[11] == 1 || triggerFired[12] || triggerFired[13] == 1)"
            else:
                common_weight = "*mcWeight*lepton_SF1*lepton_SF2*METTrigger*puWeight*topPtReweighting"                

        elif channel is 'Zmm':
            if Type is 'data':
                common_weight = "*(1.0)"
                triggercut = "(triggerFired[10]==1 || triggerFired[11] == 1 || triggerFired[12] || triggerFired[13] == 1)"
            else:
                common_weight = "*mcWeight*lepton_SF1*lepton_SF2*METTrigger*puWeight*topPtReweighting*tracking_SF1*tracking_SF2"

        elif channel is 'Wmn':
            if Type is 'data':
                common_weight = "*(1.0)"
                triggercut = "(triggerFired[10]==1 || triggerFired[11] == 1 || triggerFired[12] || triggerFired[13] == 1)"
            else:
                common_weight = "*mcWeight*lepton_SF1*lepton_SF2*METTrigger*puWeight*topPtReweighting*tracking_SF1"
                
        elif channel is 'Wen':
            if Type is 'data':
                common_weight = "*(1.0)"
                triggercut = "(triggerFired[0] || triggerFired[1] || triggerFired[2] || triggerFired[3] || triggerFired[4] || triggerFired[5] || triggerFired[26])"
            else:
                common_weight = "*mcWeight*puWeight*EleTrigger_w1*EleTrigger_w2*lepton_SF1*topPtReweighting*gsfTracking_SF1"         

        elif channel is 'Zee':
            if Type is 'data':
                common_weight = "*(1.0)"
                triggercut = "(triggerFired[0] || triggerFired[1] || triggerFired[2] || triggerFired[3] || triggerFired[4] || triggerFired[5] || triggerFired[26])"
            else:
                common_weight = "*mcWeight*puWeight*lepton_SF1*lepton_SF2*topPtReweighting*gsfTracking_SF1*gsfTracking_SF2" 
        else:
            if Type is 'data':
                common_weight = "*(1.0)"
                triggercut = "(triggerFired[18] || triggerFired[19] || triggerFired[17] || triggerFired[5] || triggerFired[15] || triggerFired[16])"
            else:
                common_weight = "*mcWeight*PhoTrigger*topPtReweighting*photon_SF*puWeight"
                
        #common_weight = "*mcWeight*lepton_SF1*lepton_SF2*puWeight_true" 

        if Type is not 'data' and Type is not 'signal_ggf' and Type is not 'signal_vbf':

            Variables[Type].SetFillColor(TColor.GetColor(physics_processes[Type]['color']))
            Variables[Type].SetLineColor(TColor.GetColor(physics_processes[Type]['color']))        
            
            if Type.startswith('GJets') :
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight+"*ewk_a*akfactor","goff")
                #makeTrees(Type,'events',channel).Draw("photonPt*0.98 >> " + histName,"(" + cut_standard + ")"+common_weight+"*ewk_a*akfactor","goff")
            elif (Type.startswith('Zvv')):                
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight+"*ewk_z*zkfactor","goff")   
            elif (Type.startswith('Zll')) :                                  
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight+"*ewk_z*zkfactor","goff")
                #makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight+"*ewk_z","goff")
            elif Type.startswith('Wlv'):
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight+"*ewk_w","goff")
            elif Type.startswith('QCD') and channel is 'signal':
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight,"goff")
            else:
                if Type.startswith('QCD') and channel is 'gjets':
                    # qcd is from the purity study
                    purity = "((0.04802 * (photonPt >= 175 && photonPt < 200 )) + \
                               (0.04241 * (photonPt >= 200 && photonPt < 250 )) + \
                               (0.0364  * (photonPt >= 250 && photonPt < 300 )) + \
                               (0.0333  * (photonPt >= 300 && photonPt < 350 )) + \
                               (0.02544 * (photonPt >= 350)))"
                    #purity = "((0.0320  * (photonPt >= 175 && photonPt < 200 )) + \
                    #           (0.0253  * (photonPt >= 200 && photonPt < 250 )) + \
                    #           (0.0211  * (photonPt >= 250 && photonPt < 300 )) + \
                    #           (0.0223  * (photonPt >= 300 && photonPt < 350 )) + \
                    #           (0.0187  * (photonPt >= 350)))"
                    makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight+"*ewk_a*akfactor*"+str(purity),"goff")
                    #makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*"+str(purity),"goff")
                else:
                    makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight,"goff")

            if var == "met":
                nbins = Variables[Type].GetNbinsX()
                Variables[Type].SetBinContent(Variables[Type].GetNbinsX(),Variables[Type].GetBinContent(nbins)+Variables[Type].GetBinContent(nbins+1))

            Variables[Type].Scale(scale,"width")
            stack.Add(Variables[Type],"hist")
            added.Add(Variables[Type])

        if Type.startswith('signal'):
            makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")"+common_weight,"goff")
            if var == "met":
                nbins = Variables[Type].GetNbinsX()
                Variables[Type].SetBinContent(Variables[Type].GetNbinsX(),Variables[Type].GetBinContent(nbins)+Variables[Type].GetBinContent(nbins+1))
            Variables[Type].Scale(scale,"width")

        if Type.startswith('data'):
            Variables[Type].SetMarkerStyle(20)
            #makeTrees(Type,'events',channel).Draw("photonPt*1.02 >> " + histName,"(" + cut_standard +" && metfilter==1 && filterbadChCandidate && filterbadPFMuon && "+triggercut+")","goff")
            #makeTrees(Type,'events',channel).Draw("transverseMass(lep1Pt*1.02,lep1Phi,trueMet,trueMetPhi) >> " + histName,"(" + cut_standard +" && metfilter==1 && filterbadChCandidate && filterbadPFMuon && "+triggercut+")","goff")
            makeTrees(Type,"events",channel).Draw(var + " >> " + histName, "(" + cut_standard +" && metfilter==1 && filterbadChCandidate && filterbadPFMuon && "+triggercut+")", "goff")             
            if var == "met":
                nbins = Variables[Type].GetNbinsX()
                Variables[Type].SetBinContent(Variables[Type].GetNbinsX(),Variables[Type].GetBinContent(nbins)+Variables[Type].GetBinContent(nbins+1))
            Variables[Type].Scale(1,"width")

        yield_dic[physics_processes[Type]['datacard']] += round(Variables[Type].Integral("width"),3)
        #yield_dic[physics_processes[Type]['datacard']] += round(Variables[Type].Integral(),3)
        #print Type, round(Variables[Type].Integral(),3), "total in: ", physics_processes[Type]['datacard'],  yield_dic[physics_processes[Type]['datacard']], round(Variables[Type].Integral("width"),3)        

    dump_datacard(channel,yield_dic)
            
    print 'INFO - Drawing the Legend', datetime.datetime.fromtimestamp( time.time())

    if channel is 'gjets':
        legend = TLegend(.60,.65,.82,.92)
    else:
        legend = TLegend(.60,.55,.92,.92)

    lastAdded  = ''
    for process in  ordered_physics_processes:
        #print process
        if not vbf:
            if process.startswith('EWK'):
                continue
        Variables[process].SetTitle(process)
        if physics_processes[process]['label'] != lastAdded:
            lastAdded = physics_processes[process]['label']
            if process is not 'data' and process is not 'signal_vbf' and process is not 'signal_ggf':
                legend . AddEntry(Variables[process],physics_processes[process]['label'] , "f")
            if process is 'data':
                legend . AddEntry(Variables[process],physics_processes[process]['label'] , "p")


    #c4 = TCanvas("c4","c4", 900, 1000)
    c4 = TCanvas("c4","c4", 600, 700)
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)

    #stack.Add(h_temp)

    stack.SetMinimum(0.01)
    #stack.SetMinimum(1)

    if setLog:
        c4.SetLogy()
        if var == "ht_cleanedjets":
        #stack.SetMaximum( stack.GetMaximum()  +  1e1*stack.GetMaximum() )
            stack.SetMaximum( Variables['data'].GetMaximum()  +  1e3*Variables['data'].GetMaximum() )
        else:
            stack.SetMaximum( Variables['data'].GetMaximum()  +  1e1*Variables['data'].GetMaximum() )
            #stack.SetMaximum( Variables['data'].GetMaximum()  +  1e4*Variables['data'].GetMaximum() )

    else:
        #stack.SetMaximum( stack.GetMaximum()  +  0.5*stack.GetMaximum() )
        #stack.SetMaximum( stack.GetMaximum()  +  1*stack.GetMaximum() )
        stack.SetMaximum( Variables['data'].GetMaximum()  +  0.5*Variables['data'].GetMaximum() )
    
    stack.Draw()
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetYaxis().CenterTitle()
    stack.GetYaxis().SetTitleOffset(1.2)
    stack.GetXaxis().SetTitle(xlabel)
    stack.GetXaxis().SetLabelSize(0)
    stack.GetXaxis().SetTitle('')
    
    if channel is 'signal' and blind:
         for b in range(Variables['data'].GetNbinsX()):
             Variables['data'].SetBinContent(b+1,0.0)

    Variables['data'].Draw("Esame")  
    Variables['signal_vbf'].SetLineWidth(2)
    #Variables['signal_ggf'].SetLineWidth(2)
    Variables['signal_vbf'].SetLineColor(1)
    #Variables['signal_ggf'].SetLineColor(4)
    Variables['signal_vbf'].Draw("samehist")
    #Variables['signal_ggf'].Draw("samehist")


    legend . AddEntry(Variables['signal_vbf'],physics_processes['signal_vbf']['label'] , "l")
    #legend . AddEntry(Variables['signal_ggf'],physics_processes['signal_ggf']['label'] , "l")


    legend.SetShadowColor(0);
    legend.SetFillColor(0);
    legend.SetLineColor(0);

    legend.Draw("same")
    plot_cms(True,lumi_str,c4)


    Pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 0.9)
    Pad.SetTopMargin(0.7)
    Pad.SetRightMargin(0.06)
    Pad.SetFillColor(0)
    Pad.SetGridy(1)
    Pad.SetFillStyle(0)
    Pad.Draw()
    Pad.cd(0)

    data = Variables['data'].Clone()

    if vtag is True:
        plot_ratio(False,data,added,bin,xlabel,0.25,1.75,5)     
    else:

        if channel is 'Zmm' and var.startswith('met'):
            plot_ratio(False,data,added,bin,xlabel,0.5,1.5,5)
        else:
            plot_ratio(False,data,added,bin,xlabel,0.5,1.5,5)

    f1 = TF1("f1","1",-5000,5000);
    f1.SetLineColor(4);
    f1.SetLineStyle(2);
    f1.SetLineWidth(2);
    f1.Draw("same")

    Pad.Update()
    Pad.RedrawAxis()

    if vtag is True:
        c4.SaveAs(folder+'/Histo_vtag_' + name + '_'+channel+'.pdf')
        c4.SaveAs(folder+'/Histo_vtag_' + name + '_'+channel+'.png')
        c4.SaveAs(folder+'/Histo_vtag_' + name + '_'+channel+'.C')
    elif vbf is True:
        c4.SaveAs(folder+'/Histo_vbf_' + name + '_'+channel+'.pdf')
        c4.SaveAs(folder+'/Histo_vbf_' + name + '_'+channel+'.png')
        c4.SaveAs(folder+'/Histo_vbf_' + name + '_'+channel+'.C')
    else:   
        #c4.SaveAs(folder+'/Histo_notrig_monojet_'+ name + '_'+channel+'.pdf')
        #c4.SaveAs(folder+'/Histo_notrig_monojet_'+ name + '_'+channel+'.png')
        #c4.SaveAs(folder+'/Histo_notrig_monojet_'+ name + '_'+channel+'.C')
        c4.SaveAs(folder+'/Histo_monojet_'+ name + '_'+channel+'.pdf')
        c4.SaveAs(folder+'/Histo_monojet_'+ name + '_'+channel+'.png')
        c4.SaveAs(folder+'/Histo_monojet_'+ name + '_'+channel+'.C')
        #c4.SaveAs(folder+'/Histo_monojet_'+str(lumi_str)+'_' + name + '_'+channel+'.pdf')
        #c4.SaveAs(folder+'/Histo_monojet_'+str(lumi_str)+'_' + name + '_'+channel+'.png')
        #c4.SaveAs(folder+'/Histo_monojet_'+str(lumi_str)+'_' + name + '_'+channel+'.C')
 

    ###### Create a root file and save the histograms individually
    #if var == 'photonPt' or var=='dilepPt':
    if var=='met':
        fhist = ROOT.TFile(channel+"_fullhist.root","recreate")
        fhist.cd();
        for Type in reordered_physics_processes:
            Variables[Type].Write()
        fhist.Write()
        fhist.Close()

    del Variables
    del var
    del f
    del h1
    c4.IsA().Destructor( c4 )
    stack.IsA().Destructor( stack )
Exemplo n.º 6
0
def plot_stack(channel, name,var, bin, low, high, ylabel, xlabel, setLog = False):

    yield_dic = {}

    stack = THStack('a', 'a')
    if var is 'met':
        binLowE = [200,250,300,350,400,500,600,1000]
#        binLowE = [250,300,350,400,500,600,1000]
        added = TH1D('added','added',len(binLowE)-1,array('d',binLowE))
    else:
        added = TH1D('added', 'added',bin,low,high)
    added.Sumw2()
    f  = {}
    h1 = {}

    Variables = {}
    cut_standard= build_selection(channel,metcut)

    if var is 'met':
        if channel is not 'signal': 
            xlabel = 'U [GeV]'

    print "INFO Channel is: ", channel, " variable is: ", var, " Selection is: ", cut_standard,"\n"
    print 'INFO time is:', datetime.datetime.fromtimestamp( time.time())

    reordered_physics_processes = []
    if channel == 'Zmm' or channel == 'Zee': 
        reordered_physics_processes = reversed(ordered_physics_processes)
    else: 
        reordered_physics_processes = ordered_physics_processes
    #reordered_physics_processes = ordered_physics_processes

    for Type in ordered_physics_processes:
        yield_dic[physics_processes[Type]['datacard']] = 0
 
    for Type in reordered_physics_processes:
        # Create the Histograms
        histName = Type+'_'+name+'_'+channel

        if var is 'met':
            #binLowE = [200,250,300,350,400,500,600,900,1500]
            binLowE = [200,250,300,350,400,500,600,1000]
#            binLowE = [250,300,350,400,500,600,1000]
            Variables[Type] = TH1F(histName,histName,len(binLowE)-1,array('d',binLowE))
        else:
            Variables[Type] = TH1F(histName, histName, bin, low, high)

        Variables[Type].Sumw2()
        #print "\n"

        # this right now breaks the tchain logic! 
        # if we have more than 1 file, this will break!!!!  

        if Type is not 'data':
            f[Type] = ROOT.TFile(physics_processes[Type]['files'][0],"read")
            h1[Type] = f[Type].Get("htotal")
            total = h1[Type].GetBinContent(1)
            #total = h1[Type].GetEntries()
            f[Type].Close()
        else:
            total = 1.0

        input_tree   = makeTrees(Type,"events",channel)
        n_entries = input_tree.GetEntries()

        #Incase you want to apply event by event re-weighting

        w = "((0.0*(npv>-0.5&&npv<=0.5)+3.30418257204*(npv>0.5&&npv<=1.5)+2.59691269521*(npv>1.5&&npv<=2.5)+2.44251087681*(npv>2.5&&npv<=3.5)+2.42846225153*(npv>3.5&&npv<=4.5)+2.40062512591*(npv>4.5&&npv<=5.5)+2.30279811595*(npv>5.5&&npv<=6.5)+2.12054720297*(npv>6.5&&npv<=7.5)+1.9104708827*(npv>7.5&&npv<=8.5)+1.67904936047*(npv>8.5&&npv<=9.5)+1.43348925382*(npv>9.5&&npv<=10.5)+1.17893952713*(npv>10.5&&npv<=11.5)+0.940505177881*(npv>11.5&&npv<=12.5)+0.740901867872*(npv>12.5&&npv<=13.5)+0.56877478036*(npv>13.5&&npv<=14.5)+0.433148655714*(npv>14.5&&npv<=15.5)+0.325343558476*(npv>15.5&&npv<=16.5)+0.241688459349*(npv>16.5&&npv<=17.5)+0.180491032782*(npv>17.5&&npv<=18.5)+0.136993937378*(npv>18.5&&npv<=19.5)+0.104859480066*(npv>19.5&&npv<=20.5)+0.0768271030309*(npv>20.5&&npv<=21.5)+0.0563426184938*(npv>21.5&&npv<=22.5)+0.0454037058117*(npv>22.5&&npv<=23.5)+0.0359945616383*(npv>23.5&&npv<=24.5)+0.0286879205085*(npv>24.5&&npv<=25.5)+0.0208185595478*(npv>25.5&&npv<=26.5)+0.0170977379612*(npv>26.5&&npv<=27.5)+0.0122446391898*(npv>27.5&&npv<=28.5)+0.0148028308301*(npv>28.5&&npv<=29.5)+0.0120527550003*(npv>29.5&&npv<=30.5)+0.00402643194054*(npv>30.5&&npv<=31.5)+0.00981143754301*(npv>31.5&&npv<=32.5)+0.0*(npv>32.5&&npv<=33.5)+0.0155664899019*(npv>33.5&&npv<=34.5)+0.0*(npv>34.5&&npv<=35.5)+0.0*(npv>35.5&&npv<=36.5)+0.0*(npv>36.5&&npv<=37.5)+0.0*(npv>37.5&&npv<=38.5)+0.0*(npv>38.5&&npv<=39.5)))"

        if channel is 'signal' or channel is 'Zmm' or channel is 'Wmn':
            w_trig = '((met < 250)*0.97 + (met >=250 && met<350)* 0.987 + (met>=350)* 1.0 )'
        else:
            w_trig = '(1.0)'
            
        anlo1_over_alo = "(1.24087232993*(genBos_pt>100.0&&genBos_pt<=150.0)+1.55807026252*(genBos_pt>150.0&&genBos_pt<=200.0)+1.51043242876*(genBos_pt>200.0&&genBos_pt<=250.0)+1.47333461572*(genBos_pt>250.0&&genBos_pt<=300.0)+1.43497331471*(genBos_pt>300.0&&genBos_pt<=350.0)+1.37846354687*(genBos_pt>350.0&&genBos_pt<=400.0)+1.2920177717*(genBos_pt>400.0&&genBos_pt<=500.0)+1.31414429236*(genBos_pt>500.0&&genBos_pt<=600.0)+1.20453974747*(genBos_pt>600.0))"
        a_ewkcorr = "(0.998568444581*(genBos_pt>100.0&&genBos_pt<=150.0)+0.992098286517*(genBos_pt>150.0&&genBos_pt<=200.0)+0.986010290609*(genBos_pt>200.0&&genBos_pt<=250.0)+0.980265498435*(genBos_pt>250.0&&genBos_pt<=300.0)+0.974830448283*(genBos_pt>300.0&&genBos_pt<=350.0)+0.969676202351*(genBos_pt>350.0&&genBos_pt<=400.0)+0.962417128177*(genBos_pt>400.0&&genBos_pt<=500.0)+0.953511139209*(genBos_pt>500.0&&genBos_pt<=600.0)+0.934331895615*(genBos_pt>600.0))"

        w_ewkcorr = "(0.980859240872*(genBos_pt>100.0&&genBos_pt<=150.0)+0.962118764182*(genBos_pt>150.0&&genBos_pt<=200.0)+0.944428528597*(genBos_pt>200.0&&genBos_pt<=250.0)+0.927685912907*(genBos_pt>250.0&&genBos_pt<=300.0)+0.911802238928*(genBos_pt>300.0&&genBos_pt<=350.0)+0.896700388113*(genBos_pt>350.0&&genBos_pt<=400.0)+0.875368225896*(genBos_pt>400.0&&genBos_pt<=500.0)+0.849096933047*(genBos_pt>500.0&&genBos_pt<=600.0)+0.792158791839*(genBos_pt>600.0))"
        wnlo012_over_wlo = "(1.89123123702*(genBos_pt>100.0&&genBos_pt<=150.0)+1.70414182145*(genBos_pt>150.0&&genBos_pt<=200.0)+1.60726459197*(genBos_pt>200.0&&genBos_pt<=250.0)+1.57205818769*(genBos_pt>250.0&&genBos_pt<=300.0)+1.51688539716*(genBos_pt>300.0&&genBos_pt<=350.0)+1.41090079307*(genBos_pt>350.0&&genBos_pt<=400.0)+1.30757555038*(genBos_pt>400.0&&genBos_pt<=500.0)+1.32046236765*(genBos_pt>500.0&&genBos_pt<=600.0)+1.26852513234*(genBos_pt>600.0))"

        z_ewkcorr = "(0.984525344338*(genBos_pt>100.0&&genBos_pt<=150.0)+0.969078612189*(genBos_pt>150.0&&genBos_pt<=200.0)+0.954626582726*(genBos_pt>200.0&&genBos_pt<=250.0)+0.941059330021*(genBos_pt>250.0&&genBos_pt<=300.0)+0.92828367065*(genBos_pt>300.0&&genBos_pt<=350.0)+0.916219976557*(genBos_pt>350.0&&genBos_pt<=400.0)+0.89931198024*(genBos_pt>400.0&&genBos_pt<=500.0)+0.878692669663*(genBos_pt>500.0&&genBos_pt<=600.0)+0.834717745177*(genBos_pt>600.0))"
        znlo012_over_zlo = "(1.68500099066*(genBos_pt>100.0&&genBos_pt<=150.0)+1.55256109189*(genBos_pt>150.0&&genBos_pt<=200.0)+1.52259467479*(genBos_pt>200.0&&genBos_pt<=250.0)+1.52062313572*(genBos_pt>250.0&&genBos_pt<=300.0)+1.4322825541*(genBos_pt>300.0&&genBos_pt<=350.0)+1.45741443405*(genBos_pt>350.0&&genBos_pt<=400.0)+1.36849777989*(genBos_pt>400.0&&genBos_pt<=500.0)+1.3580214432*(genBos_pt>500.0&&genBos_pt<=600.0)+1.16484769869*(genBos_pt>600.0))"
        
        wm_postfit = "(1.0)"
        zm_postfit = "(1.0)"
        g_postfit  = "(1.0)"
            
        # this is the scale using the total number of effective events
        scale = 1.0;
        scale = float(lumi)*physics_processes[Type]['xsec']/total
        
        #print '\n'
#        print "type: ", Type,  "scale", scale, "lumi", lumi, physics_processes[Type]['xsec'], total

        if Type is not 'data' and Type is not 'signal_dm' and Type is not 'signal_dm_s' and Type is not 'signal_dm_ps' and Type is not 'signal_dm_v' and Type is not 'signal_dm_av_1_2':
            Variables[Type].SetFillColor(physics_processes[Type]['color'])
            Variables[Type].SetLineColor(physics_processes[Type]['color'])

            if Type.startswith('GJets') :
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*0.98*"+str(g_postfit)+"*"+str(anlo1_over_alo)+"*"+str(a_ewkcorr)+"*" +str(w)+"*"+str(w_trig),"goff")

            elif (Type.startswith('Zvv') or Type.startswith('Zll')) :
                if channel is 'signal' :
                    makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*"+str(zm_postfit)+"*"+str(z_ewkcorr)+"*"+str(znlo012_over_zlo)+"*"+str(w)+"*"+str(w_trig),"goff")
                else:
                    #SF explicitly written for the leading tight lepton from the root files
                    makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*(0.98 *(lep1Eta<2.1)+0.91*(lep1Eta>=2.1))*"+str(zm_postfit)+"*"+str(z_ewkcorr)+"*"+str(znlo012_over_zlo)+"*"+str(w)+"*"+str(w_trig),"goff")


            elif Type.startswith('Wlv'):
                if channel is 'signal' :
                    makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*"+str(wm_postfit)+"*"+str(wnlo012_over_wlo)+"*"+str(w_ewkcorr)+"*" +str(w)+"*"+str(w_trig),"goff")
                else:                
                    makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*"+str(wm_postfit)+"*"+str(wnlo012_over_wlo)+"*"+str(w_ewkcorr)+"*" +str(w)+"*"+str(w_trig),"goff")
            
            else:
                makeTrees(Type,'events',channel).Draw(var + " >> " + histName,"(" + cut_standard + ") *mcWeight*" +str(w)+"*"+str(w_trig),"goff")
                

            Variables[Type].Scale(scale,"width")
            stack.Add(Variables[Type],"hist")
            added.Add(Variables[Type])

        if Type.startswith('signal_h_ggf'):
            Variables[Type].SetLineColor(1)
            Variables[Type].SetLineWidth(3)
            Variables[Type].SetLineStyle(1)
            makeTrees(Type,"events",channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*"+str(w),"goff")
            Variables[Type].Scale(scale,"width")

        if Type.startswith('signal_dm_av_1_2'):
            Variables[Type].SetLineColor(1)
            Variables[Type].SetLineWidth(3)
            Variables[Type].SetLineStyle(8)
            makeTrees(Type,"events",channel).Draw(var + " >> " + histName,"(" + cut_standard + ")*mcWeight*"+str(w),"goff")
            Variables[Type].Scale(scale,"width")
            
        if Type.startswith('data'):
            Variables[Type].SetMarkerStyle(20)
            if channel is 'signal' or channel is 'Zmm' or channel is 'Wmn':
                makeTrees(Type,"events",channel).Draw(var + " >> " + histName, "(" + cut_standard + " && (triggerFired[0]==1 || triggerFired[1]==1 || triggerFired[2]==1) )", "goff")
            else:
                makeTrees(Type,"events",channel).Draw(var + " >> " + histName, "(" + cut_standard +" )", "goff") 
            Variables[Type].Scale(1,"width")

        yield_dic[physics_processes[Type]['datacard']] += round(Variables[Type].Integral("width"),3)


    dump_datacard(channel,yield_dic)

    #added.Write()
            
    print 'INFO - Drawing the Legend', datetime.datetime.fromtimestamp( time.time())

#    if channel is 'Zmm' or channel is 'Zee':
#        legend = TLegend(.60,.65,.92,.92)
#    elif channel is 'gjets':
#        legend = TLegend(.60,.65,.82,.92)
#    else:
#        legend = TLegend(.60,.60,.92,.92)

    legend = TLegend(.60,.70,.92,.92)

    lastAdded = ''
    for process in  ordered_physics_processes:
        #print process
        Variables[process].SetTitle(process)
        if physics_processes[process]['label'] != lastAdded:
            lastAdded = physics_processes[process]['label']
            if process is not 'data' and process is not 'signal_dm' and process is not 'signal_dm_av_1_2' and process is not 'signal_h_ggf' and process is not 'signal_h_vbf':
                legend . AddEntry(Variables[process],physics_processes[process]['label'] , "f")
            if process is 'data':
                legend . AddEntry(Variables[process],physics_processes[process]['label'] , "p")

    c4 = TCanvas("c4","c4", 900, 1000)
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)

    stack.SetMinimum(0.01)
    #stack.SetMinimum(10)

    if setLog:
        c4.SetLogy()
        if var is 'fatjet1tau21' or var is 'fatjet1PrunedM':
            stack.SetMaximum( stack.GetMaximum()  +  1e5*stack.GetMaximum() )
        else:
            stack.SetMaximum( stack.GetMaximum()  +  1e2*stack.GetMaximum() )
    else:
        stack.SetMaximum( stack.GetMaximum()  +  0.5*stack.GetMaximum() )
    
    stack.Draw()
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetYaxis().CenterTitle()
    stack.GetYaxis().SetTitleOffset(1.2)
    stack.GetXaxis().SetTitle(xlabel)
    stack.GetXaxis().SetLabelSize(0)
    stack.GetXaxis().SetTitle('')

    Variables['data'].Draw("Esame")

    legend.SetShadowColor(0);
    legend.SetFillColor(0);
    legend.SetLineColor(0);

    legend.Draw("same")
    plot_cms(True,lumi_str)

    Pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    Pad.SetTopMargin(0.7)
    Pad.SetFillColor(0)
    Pad.SetGridy(1)
    Pad.SetFillStyle(0)
    Pad.Draw()
    Pad.cd(0)
    Pad.SetRightMargin(0.06)
    
    data = Variables['data'].Clone()

    plot_ratio(False,data,added,bin,xlabel,0,2.0,5)

    f1 = TF1("f1","1",-5000,5000);
    f1.SetLineColor(4);
    f1.SetLineStyle(2);
    f1.SetLineWidth(2);
    f1.Draw("same")

    outputName = folder+'/mj_Histo_' + name + '_'+channel
    c4.SaveAs(outputName+'.pdf')
    c4.SaveAs(outputName+'.png')
    c4.SaveAs(outputName+'.C')

    del Variables
    del var
    del f
    del h1
    c4.IsA().Destructor( c4 )
    stack.IsA().Destructor( stack )
Exemplo n.º 7
0
def plot_stack(channel,
               name,
               var,
               bin,
               low,
               high,
               ylabel,
               xlabel,
               setLog=False):

    folder = 'test'
    yield_Zll = {}
    yield_dic = {}
    yield_Wln = {}
    yield_signal = {}
    stack = THStack('a', 'a')
    added = TH1D('a', 'a', bin, low, high)
    added.Sumw2()
    f = {}
    h1 = {}

    Variables = {}
    cut_standard = build_selection(channel, 200)
    print "INFO Channel is: ", channel, " variable is: ", var, " Selection is: ", cut_standard, "\n"
    print 'INFO time is:', datetime.datetime.fromtimestamp(time.time())

    reordered_physics_processes = []
    if channel == 'Zll':
        reordered_physics_processes = reversed(ordered_physics_processes)
    else:
        reordered_physics_processes = ordered_physics_processes

    for Type in reordered_physics_processes:
        # Create the Histograms
        histName = Type + '_' + name + '_' + channel
        Variables[Type] = TH1F(histName, histName, bin, low, high)
        Variables[Type].Sumw2()

        print "\n"
        # this right now breaks the tchain logic!
        # if we have more than 1 file, this will break!!!!
        print physics_processes[Type]['files'][0]
        f[Type] = ROOT.TFile(physics_processes[Type]['files'][0], "read")
        h1[Type] = f[Type].Get("htotal")
        total = h1[Type].GetBinContent(1)
        f[Type].Close()

        input_tree = makeTrees(Type, "events", channel)
        n_entries = input_tree.GetEntries()

        #Incase you want to apply event by event re-weighting
        w = 1.0
        # this is the scale using the total number of effective events
        scale = 1.0
        scale = float(lumi) * physics_processes[Type]['xsec'] / total
        #print "type: ", Type, "weight", w, "scale", scale, "lumi", lumi, physics_processes[Type]['xsec'], total

        if Type.startswith('QCD') or Type.startswith('Zll') or \
        Type.startswith('others') or Type.startswith('Wlv') or \
        Type.startswith('Zvv'):
            Variables[Type].SetFillColor(physics_processes[Type]['color'])
            Variables[Type].SetLineColor(physics_processes[Type]['color'])
            makeTrees(Type, 'events', channel).Draw(
                var + " >> " + histName,
                "(" + cut_standard + ")*mcWeight*" + str(w), "goff")
            Variables[Type].Scale(scale)
            #print "Type: ", Type, "Total Events:", scale* Variables[Type].GetEntries() , "scale", scale, "raw events", Variables[Type].GetEntries()
            stack.Add(Variables[Type], "hist")
            added.Add(Variables[Type])

        if Type.startswith('signal_higgs'):
            Variables[Type].SetLineColor(1)
            Variables[Type].SetLineWidth(3)
            Variables[Type].SetLineStyle(8)
            makeTrees(Type, "events", channel).Draw(
                var + " >> " + histName,
                "(" + cut_standard + ")*mcWeight*" + str(w), "goff")
            Variables[Type].Scale(scale)

        if Type.startswith("data"):
            Variables[Type].SetMarkerStyle(20)
            makeTrees(Type, "events", channel).Draw(
                var + " >> " + histName, "(" + cut_standard +
                " && triggerFired[0]==1)*mcWeight*" + str(w), "goff")

        yield_dic[Type] = round(Variables[Type].Integral(), 3)

    dump_datacard(channel, yield_dic)

    #added.Write()

    print 'INFO - Drawing the Legend', datetime.datetime.fromtimestamp(
        time.time())

    legend = TLegend(.60, .60, .92, .92)
    for process in ordered_physics_processes:
        Variables[process].SetTitle(process)
        #Variables[process].Write()
        if process is not 'data' and process is not 'Zvv_ht200' and process is not 'Zvv_ht400' and process is not 'Zvv_ht600':
            legend.AddEntry(Variables[process],
                            physics_processes[process]['label'], "f")
        if process is 'data':
            legend.AddEntry(Variables[process],
                            physics_processes[process]['label'], "p")

    c4 = TCanvas("c4", "c4", 900, 1000)
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)

    stack.SetMinimum(0.1)

    if setLog:
        c4.SetLogy()
        stack.SetMaximum(stack.GetMaximum() + 1000 * stack.GetMaximum())

    stack.Draw()
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetYaxis().CenterTitle()
    stack.GetXaxis().SetTitle(xlabel)
    stack.GetXaxis().SetLabelSize(0)
    stack.GetXaxis().SetTitle('')

    Variables['data'].Draw("Esame")
    Variables['signal_higgs'].Draw("same")

    legend.SetShadowColor(0)
    legend.SetFillColor(0)
    legend.SetLineColor(0)

    legend.Draw("same")
    plot_cms(True, lumi)

    Pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    Pad.SetTopMargin(0.7)
    Pad.SetFillColor(0)
    Pad.SetGridy(1)
    Pad.SetFillStyle(0)
    Pad.Draw()
    Pad.cd(0)
    Pad.SetRightMargin(0.06)

    data = Variables['data'].Clone()
    plot_ratio(False, data, added, bin, xlabel)

    f1 = TF1("f1", "1", -5000, 5000)
    f1.SetLineColor(4)
    f1.SetLineStyle(2)
    f1.SetLineWidth(2)
    f1.Draw("same")

    c4.SaveAs(folder + '/Histo_' + name + '_' + channel + '.pdf')

    del Variables
    del var
    del f
    del h1
    c4.IsA().Destructor(c4)
    stack.IsA().Destructor(stack)