#
# barrelHistHistCount.SetBinContent(1, hist_signal_integral["id_invMass_3_5_0_1.2"]/hist_signal_integral["invMass_3_5_0_1.2"])
# barrelHistHistCount.SetBinContent(2, hist_signal_integral["id_invMass_5_10_0_1.2"]/hist_signal_integral["invMass_5_10_0_1.2"])
# barrelHistHistCount.SetBinContent(3, hist_signal_integral["id_invMass_10_25_0_1.2"]/hist_signal_integral["invMass_10_25_0_1.2"])

minimum = min(
    barrelHist.GetMinimum(),
    dataBarrelHist.GetMinimum())  #, barrelHistHistCount.GetMinimum())
maximum = max(
    barrelHist.GetMaximum(),
    dataBarrelHist.GetMaximum())  #, barrelHistHistCount.GetMaximum())

barrelHist.SetMinimum(minimum - 0.1)
barrelHist.SetMaximum(maximum + 0.1)

utils.formatHist(barrelHist, utils.colorPalette[14], 0, True, True)

#setMarkers(barrelHist, 14)
#setMarkers(barrelHistSignalFit, 7)
#setMarkers(barrelHistHistCount, 1)

setMarkers(barrelHist, 1)
#setMarkers(dataBarrelHist, kFullCircle)

dataBarrelHist.SetMarkerStyle(kFullCircle)
dataBarrelHist.SetLineColor(kBlack)

legend.AddEntry(barrelHist, "MC", 'p')
legend.AddEntry(dataBarrelHist, "Data", 'p')
#legend.AddEntry(barrelHistHistCount, "Signal Count Efficiency", 'p')
Esempio n. 2
0
def main():
    
    print "Start: " + datetime.now().strftime('%d-%m-%Y %H:%M:%S')
    
    histograms = {}
    
    bg_files = glob(bg_dir + "/*")
    sumTypes = {}
    memory = []

    for f in bg_files: 
        filename = os.path.basename(f).split(".")[0]
        types = filename.split("_")
        type = None
        
        if types[0] == "TTJets":
            type = "_".join(types[0:2])
        elif types[0] == "ST":
            type = "_".join(types[0:3])
        else:
            type = types[0]
        if type not in sumTypes:
            sumTypes[type] = {}
        #sumTypes[types[0]][types[1]] = True

    print sumTypes
    #exit(0)
    for cut in cuts:
        for hist_def in histograms_defs:
            baseName = cut["name"] + "_" + hist_def["obs"]
            sigName = baseName + "_signal"
            dataName = baseName + "_data"
            histograms[sigName] = utils.UOFlowTH1F(sigName, "", hist_def["bins"], hist_def["minX"], hist_def["maxX"])
            histograms[dataName] = utils.UOFlowTH1F(dataName, "", hist_def["bins"], hist_def["minX"], hist_def["maxX"])
            utils.formatHist(histograms[sigName], utils.signalCp[0], 0.8)
            for type in sumTypes:
                if utils.existsInCoumpoundType(type):
                    continue
                bgName = baseName + "_" + type
                histograms[bgName] = utils.UOFlowTH1F(bgName, "", hist_def["bins"], hist_def["minX"], hist_def["maxX"])
            for type in utils.compoundTypes:
                bgName = baseName + "_" + type
                histograms[bgName] = utils.UOFlowTH1F(bgName, "", hist_def["bins"], hist_def["minX"], hist_def["maxX"])
    
    if plot_signal:
        createPlots([signal_dir], "signal", histograms)
    calculated_lumi = None
    if plot_data:
        dataFiles = glob(data_dir + "/*")
        calculated_lumi = createPlots(dataFiles, "data", histograms)
        print "Calculated Luminosity: ", calculated_lumi
        weight = calculated_lumi * 1000 / utils.LUMINOSITY
    
    for type in sumTypes:
        if utils.existsInCoumpoundType(type):
            continue
        #if type == "ZJetsToNuNu" or type == "WJetsToLNu":
        #    continue
        print "Summing type", type
        rootfiles = glob(bg_dir + "/*" + type + "*.root")
        createPlots(rootfiles, type, histograms)
    
    for cType in utils.compoundTypes:
        print "Creating compound type", cType
        rootFiles = []
        for type in utils.compoundTypes[cType]:
            if type not in sumTypes:
                continue
            rootFiles.extend(glob(bg_dir + "/*" + type + "*.root"))
        if len(rootFiles):
            createPlots(rootFiles, cType, histograms)
        else:
            print "**Couldn't find file for " + cType
    
    print "Plotting observable"

    c1 = TCanvas("c1", "c1", 800, 800)
    
    titlePad = TPad("titlePad", "",0.0,0.93,1.0,1.0)
    histPad = TPad("histPad", "",0.0,0.0,1.0,0.93)

    titlePad.Draw()

    t = TPaveText(0.0,0.93,1.0,1.0,"NB")
    t.SetFillStyle(0)
    t.SetLineColor(0)
    t.SetTextFont(40);
    t.AddText("No Cuts")
    t.Draw()
    histPad.Draw()
    histPad.Divide(2,2)

    c1.Print(output_file+"[");

    plot_num = 0

    pId = 1
    needToDraw = False

    memory = []
    
    for cut in cuts:
        cutName = cut["name"]
        print "Cut " + cutName
        t.Clear()
        t.AddText(cutName)
        t.Draw()
        titlePad.Update()
        pId = 1
        for hist_def in histograms_defs:
            needToDraw = True
            pad = histPad.cd(pId)
            hs = THStack(str(plot_num),"")
            plot_num += 1
            memory.append(hs)
            types = [k for k in utils.bgOrder]
            types = sorted(types, key=lambda a: utils.bgOrder[a])
            typesInx = []
            i = 0
            foundBg = False
            for type in types:
                hname = cut["name"] + "_" + hist_def["obs"] + "_" + type
                if histograms.get(hname) is not None:
                    hs.Add(histograms[hname])
                    typesInx.append(i)
                    foundBg = True
                i += 1
            sigHistName = cut["name"] + "_" + hist_def["obs"] + "_signal"
            sigHist = histograms[sigHistName]
            sigMax = sigHist.GetMaximum()
            maximum = sigMax
            if foundBg:
                bgMax = hs.GetMaximum()
                maximum = max(bgMax, sigMax)
            
            if maximum == 0:
                maximum == 10

            legend = TLegend(.20,.60,.89,.89)
            legend.SetNColumns(2)
            legend.SetBorderSize(0)
            legend.SetFillStyle(0)
            memory.append(legend)
            if foundBg:
                newBgHist = utils.styledStackFromStack(hs, memory, legend, "", typesInx, True)
                #newBgHist.SetFillColorAlpha(fillC, 0.35)
                newBgHist.SetMaximum(maximum*1000)
                newBgHist.SetMinimum(0.01)
                newBgHist.Draw("hist")
                #utils.histoStyler(newBgHist)
                newBgHist.GetXaxis().SetTitle(hist_def["obs"])
                newBgHist.GetYaxis().SetTitle("Number of events")
                #newBgHist.GetYaxis().SetTitleOffset(1.15)
                #newBgHist.GetXaxis().SetLabelSize(0.055)
                c1.Modified()
            
            if plot_signal: 
                legend.AddEntry(sigHist, "signal", 'l')
            if foundBg and plot_signal:
                sigHist.SetMaximum(maximum)
            if plot_signal:
                sigHist.SetMinimum(0.01)
                sigHist.SetLineWidth(2)
                sigHist.GetXaxis().SetTitle("GeV")
            if foundBg and plot_signal:
                sigHist.Draw("HIST SAME")
            elif plot_signal:
                sigHist.Draw("HIST")
            
            if plot_data:
                dataHistName = cut["name"] + "_" + hist_def["obs"] + "_data"
                dataHist = histograms[dataHistName]
                dataHist.SetMinimum(0.01)
                dataHist.SetMarkerStyle(kFullCircle)
                dataHist.Draw("P SAME")
                legend.AddEntry(dataHist, "data", 'p')
            
            legend.Draw("SAME")
            pad.SetLogy()
            c1.Update()

            pId += 1

            if pId > 4:
                pId = 1
                c1.Print(output_file);
                needToDraw = False;
            
            linBgHist = newBgHist.Clone()
            memory.append(linBgHist)
            linBgHist.SetMaximum(maximum*1.1)
            
            pad = histPad.cd(pId)
            pad.SetLogy(0)
            linBgHist.Draw("hist")
            if plot_signal:
                sigHist.Draw("HIST SAME")
            if plot_data:
                dataHist.Draw("P e SAME")
            legend.Draw("SAME")
            
            pId += 1

            if pId > 4:
                pId = 1
                c1.Print(output_file);
                needToDraw = False;
            
        
        if needToDraw:
            for id in range(pId, 5):
                print "Clearing pad " + str(id)
                pad = histPad.cd(id)
                pad.Clear()
        c1.Print(output_file);
        
    c1.Print(output_file+"]");
    
    print "End: " + datetime.now().strftime('%d-%m-%Y %H:%M:%S')
Esempio n. 3
0
def main():

    print "Plotting observable"

    c1 = TCanvas("c1", "c1", 800, 800)
    c1.SetBottomMargin(0.16)
    c1.SetLeftMargin(0.18)

    c1.Print(output_file+"[");

    bg_files = glob(bg_dir + "/*")
    sumTypes = {}
    memory = []

    for f in bg_files: 
        filename = os.path.basename(f).split(".")[0]
        types = filename.split("_")
        if types[0] not in sumTypes:
            sumTypes[types[0]] = {}
        sumTypes[types[0]][types[1]] = True
    histograms = {}
    print sumTypes
    for type in sumTypes:
        if utils.existsInCoumpoundType(type):
            continue
        print "Summing type", type
        rootfiles = glob(bg_dir + "/*" + type + "*.root")
        #rootfiles.append(signal_file)
        #rootfiles = [signal_file] + rootfiles
        mll = createPlots(rootfiles, type, memory)
        print type
        histograms[type] = mll
    
    for cType in utils.compoundTypes:
        print "Creating compound type", cType
        rootFiles = []
        for type in utils.compoundTypes[cType]:
            rootFiles.extend(glob(bg_dir + "/*" + type + "*.root"))
        if len(rootFiles):
            mll = createPlots(rootFiles, cType, memory)
            histograms[type] = mll
        else:
            print "**Couldn't find file for " + cType

    sigHist = createPlots([signal_dir], "signal", memory)

    utils.formatHist(sigHist, utils.signalCp[0], 0.8)

    hs = THStack("invMass","")
    memory.append(hs)
    types = [k for k in utils.bgOrder]
    types = sorted(types, key=lambda a: utils.bgOrder[a])
    typesInx = []

    i = 0
    foundBg = False
    for type in types:
        if histograms.get(type) is not None:
            hs.Add(histograms[type])
            typesInx.append(i)
            foundBg = True
        i += 1
    #hs.Add(sigHist)
    #typesInx.append(i)

    sigMax = sigHist.GetMaximum()
    maximum = sigMax
    if foundBg:
        bgMax = hs.GetMaximum()
        maximum = max(bgMax, sigMax)

    #legend = TLegend(.69,.55,.89,.89)
    legend = TLegend(.20,.60,.89,.89)
    legend.SetNColumns(2)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    memory.append(legend)
    if foundBg:
        newBgHist = utils.styledStackFromStack(hs, memory, legend, "", typesInx, True)
        #newBgHist.SetFillColorAlpha(fillC, 0.35)
        newBgHist.SetMaximum(maximum*1000)
        newBgHist.SetMinimum(0.01)
        newBgHist.Draw("hist")
        utils.histoStyler(newBgHist)
        newBgHist.GetXaxis().SetTitle("M_{ll}")
        newBgHist.GetYaxis().SetTitle("Number of events")
        newBgHist.GetYaxis().SetTitleOffset(1.15)
        #newBgHist.GetXaxis().SetLabelSize(0.055)
        c1.Modified()
        #newBgHist.SetTitle(signal_name)

    #sigHist.SetTitle(signal_name)
    legend.AddEntry(sigHist, "signal", 'l')
    if foundBg:
        sigHist.SetMaximum(maximum)
    sigHist.SetMinimum(0.01)
    sigHist.SetLineWidth(2)
    sigHist.GetXaxis().SetTitle("GeV")
    if foundBg:
        sigHist.Draw("HIST SAME")
    else:
        sigHist.Draw("HIST")
    legend.Draw("SAME")
    gPad.SetLogy();
    utils.stamp_plot()
    c1.Update()
    c1.Print(output_file);

    c1.Print(output_file+"]");
Esempio n. 4
0
def main():
    print("Start: " + datetime.now().strftime('%d-%m-%Y %H:%M:%S'))

    print("Opening histograms file " + histograms_file)
    histograms = TFile(histograms_file, 'read')

    for lepNum in [1, 2]:
        for lep in ["Muons", "Electrons"]:

            orthOpt = [True, False] if (lepNum == 2
                                        and lep == "Muons") else [False]
            for orth in orthOpt:
                histname = "bg_" + ("1t" if lepNum == 1 else "2l") + "_" + (
                    "orth_" if orth else "") + lep
                print("Getting", histname)
                bg_hist = histograms.Get(histname)

                maximum = bg_hist.GetMaximum()

                signal_histograms = []
                for signal in signals:

                    #"bg_2l_" + ("orth_" if orth else "") + lep + "_" + jetiso

                    histname = signal + "_" + ("1t" if lepNum == 1 else
                                               "2l") + "_" + ("orth_" if orth
                                                              else "") + lep
                    print("Getting", histname)
                    hist = histograms.Get(histname)
                    maximum = max(maximum, hist.GetMaximum())
                    signal_histograms.append(hist)

                bg_hist.SetMaximum(maximum)

                c1 = TCanvas("c1", "c1", 800, 800)
                c1.cd()

                legend = TLegend(0.65, 0.70, 0.87, 0.875)
                legend.SetBorderSize(0)
                legend.SetTextFont(42)
                legend.SetTextSize(0.02)

                cpRed = utils.colorPalette[7]
                utils.histoStyler(bg_hist)
                bg_hist.SetTitle("")
                bg_hist.GetXaxis().SetTitle("BDT Output")
                bg_hist.GetYaxis().SetTitle("Number of events")
                #bg_hist.GetYaxis().SetTitleOffset(1.4)
                #bg_hist.GetXaxis().SetLabelSize(0.055)
                #trainBGHist.SetMaximum(maxY + 0.02)
                utils.formatHist(bg_hist, cpRed, 0.35, True)
                # fillC = TColor.GetColor(cpRed["fillColor"])
                #             lineC = TColor.GetColor(cpRed["lineColor"])
                #             bg_hist.SetFillStyle(0)
                #             bg_hist.SetFillColorAlpha(fillC, 0.35)
                #             bg_hist.SetLineColor(lineC)
                #             bg_hist.SetLineWidth(1)
                #             bg_hist.SetOption("HIST")

                bg_hist.Draw("HIST")

                #print "BinWidth", bg_hist.GetBinWidth()
                # print("*********GetNbinsX", bg_hist.GetNbinsX())
                #                 for ibin in range(1, bg_hist.GetNbinsX()):
                #                     print("BinWidth", bg_hist.GetBinWidth(ibin))
                #                     print("GetBinLowEdge", bg_hist.GetBinLowEdge(ibin))

                legend.AddEntry(bg_hist, "Background", 'F')

                for i in range(len(signals)):
                    utils.formatHist(signal_histograms[i], utils.signalCp[i],
                                     0.8)
                    legend.AddEntry(signal_histograms[i], signals[i], 'l')
                    signal_histograms[i].Draw("hist same")

                legend.Draw("SAME")

                c1.Print(output_dir + "/signal_background_" +
                         ("1t" if lepNum == 1 else "2l") + "_" +
                         ("orth_" if orth else "") + lep + ".pdf")

                ############# DRAW SIGNIFICANCES ##############

                categories = 10
                cut_values = []
                binMax = -1

                for category in range(categories):

                    significance_histograms = []

                    for i in range(len(signals)):
                        significance_histogram = signal_histograms[i].Clone()
                        significance_histogram.Reset()

                        endPoint = signal_histograms[i].GetNbinsX(
                        ) if binMax == -1 else binMax
                        print("endPoint", endPoint)
                        for ibin in range(1, endPoint):
                            print("calculating for bin", ibin)
                            sig = utils.calcSignificanceCutCount(
                                signal_histograms[i], bg_hist, ibin,
                                binMax - 1 if binMax > 0 else -1)
                            print("sig", sig)
                            significance_histogram.SetBinContent(ibin, sig)
                        significance_histograms.append(significance_histogram)

                    c1 = TCanvas("c1", "c1", 800, 800)
                    c1.cd()

                    legend = TLegend(0.15, 0.70, 0.55, 0.875)
                    legend.SetBorderSize(0)
                    legend.SetTextFont(42)
                    legend.SetTextSize(0.02)

                    maximum = 0
                    for i in range(len(signals)):
                        maximum = max(significance_histograms[i].GetMaximum(),
                                      maximum)
                    significance_histograms[0].SetMaximum(maximum + 1)
                    utils.histoStyler(significance_histograms[0])
                    significance_histograms[0].SetTitle("")
                    significance_histograms[0].GetXaxis().SetTitle(
                        "BDT Output")
                    significance_histograms[0].GetYaxis().SetTitle(
                        "Significance")

                    for i in range(len(signals)):
                        utils.formatHist(significance_histograms[i],
                                         utils.signalCp[i], 0.8)
                        legend.AddEntry(significance_histograms[i], signals[i],
                                        'l')
                        if i == 0:
                            significance_histograms[i].Draw("hist")
                        else:
                            significance_histograms[i].Draw("hist same")

                    binMax = significance_histograms[1].GetMaximumBin()
                    maxValue = significance_histograms[1].GetXaxis(
                    ).GetBinCenter(binMax)

                    print("binMax", binMax, "maxValue",
                          "{:0.2f}".format(maxValue))

                    cut_values.append("{:0.2f}".format(maxValue))

                    sigLine = TLine(maxValue, 0, maxValue, maximum + 1)
                    sigLine.Draw("SAME")
                    sigLine.SetLineColor(kRed)
                    sigLine.SetLineWidth(2)

                    tl = TLatex()
                    tl.SetTextFont(42)
                    tl.SetTextSize(0.04)
                    tl.DrawLatex(maxValue + 0.05, maximum + 0.5,
                                 "{:0.2f}".format(maxValue))

                    legend.Draw("SAME")

                    c1.Print(output_dir + "/sr" + str(category + 1) +
                             "_significance_" +
                             ("1t" if lepNum == 1 else "2l") + "_" +
                             ("orth_" if orth else "") + lep + ".pdf")

                print("===========")
                print(("1t" if lepNum == 1 else "2l") + "_" +
                      ("orth_" if orth else "") + lep)
                print(cut_values)
    exit(0)